TerrainModule.cs 47 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130
  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.Collections.Generic;
  29. using System.IO;
  30. using System.Reflection;
  31. using System.Net;
  32. using log4net;
  33. using Nini.Config;
  34. using OpenMetaverse;
  35. using OpenSim.Framework;
  36. using OpenSim.Region.CoreModules.Framework.InterfaceCommander;
  37. using OpenSim.Region.CoreModules.World.Terrain.FileLoaders;
  38. using OpenSim.Region.CoreModules.World.Terrain.FloodBrushes;
  39. using OpenSim.Region.CoreModules.World.Terrain.PaintBrushes;
  40. using OpenSim.Region.Framework.Interfaces;
  41. using OpenSim.Region.Framework.Scenes;
  42. namespace OpenSim.Region.CoreModules.World.Terrain
  43. {
  44. public class TerrainModule : INonSharedRegionModule, ICommandableModule, ITerrainModule
  45. {
  46. #region StandardTerrainEffects enum
  47. /// <summary>
  48. /// A standard set of terrain brushes and effects recognised by viewers
  49. /// </summary>
  50. public enum StandardTerrainEffects : byte
  51. {
  52. Flatten = 0,
  53. Raise = 1,
  54. Lower = 2,
  55. Smooth = 3,
  56. Noise = 4,
  57. Revert = 5,
  58. // Extended brushes
  59. Erode = 255,
  60. Weather = 254,
  61. Olsen = 253
  62. }
  63. #endregion
  64. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  65. private readonly Commander m_commander = new Commander("terrain");
  66. private readonly Dictionary<StandardTerrainEffects, ITerrainFloodEffect> m_floodeffects =
  67. new Dictionary<StandardTerrainEffects, ITerrainFloodEffect>();
  68. private readonly Dictionary<string, ITerrainLoader> m_loaders = new Dictionary<string, ITerrainLoader>();
  69. private readonly Dictionary<StandardTerrainEffects, ITerrainPaintableEffect> m_painteffects =
  70. new Dictionary<StandardTerrainEffects, ITerrainPaintableEffect>();
  71. private ITerrainChannel m_channel;
  72. private Dictionary<string, ITerrainEffect> m_plugineffects;
  73. private ITerrainChannel m_revert;
  74. private Scene m_scene;
  75. private volatile bool m_tainted;
  76. #region ICommandableModule Members
  77. public ICommander CommandInterface
  78. {
  79. get { return m_commander; }
  80. }
  81. #endregion
  82. #region INonSharedRegionModule Members
  83. /// <summary>
  84. /// Creates and initialises a terrain module for a region
  85. /// </summary>
  86. /// <param name="scene">Region initialising</param>
  87. /// <param name="config">Config for the region</param>
  88. public void Initialise(IConfigSource config)
  89. {
  90. }
  91. public void AddRegion(Scene scene)
  92. {
  93. m_scene = scene;
  94. // Install terrain module in the simulator
  95. lock (m_scene)
  96. {
  97. if (m_scene.Heightmap == null)
  98. {
  99. m_channel = new TerrainChannel();
  100. m_scene.Heightmap = m_channel;
  101. m_revert = new TerrainChannel();
  102. UpdateRevertMap();
  103. }
  104. else
  105. {
  106. m_channel = m_scene.Heightmap;
  107. m_revert = new TerrainChannel();
  108. UpdateRevertMap();
  109. }
  110. m_scene.RegisterModuleInterface<ITerrainModule>(this);
  111. m_scene.EventManager.OnNewClient += EventManager_OnNewClient;
  112. m_scene.EventManager.OnPluginConsole += EventManager_OnPluginConsole;
  113. m_scene.EventManager.OnTerrainTick += EventManager_OnTerrainTick;
  114. InstallInterfaces();
  115. }
  116. InstallDefaultEffects();
  117. LoadPlugins();
  118. }
  119. public void RegionLoaded(Scene scene)
  120. {
  121. }
  122. public void RemoveRegion(Scene scene)
  123. {
  124. lock (m_scene)
  125. {
  126. // remove the commands
  127. m_scene.UnregisterModuleCommander(m_commander.Name);
  128. // remove the event-handlers
  129. m_scene.EventManager.OnTerrainTick -= EventManager_OnTerrainTick;
  130. m_scene.EventManager.OnPluginConsole -= EventManager_OnPluginConsole;
  131. m_scene.EventManager.OnNewClient -= EventManager_OnNewClient;
  132. // remove the interface
  133. m_scene.UnregisterModuleInterface<ITerrainModule>(this);
  134. }
  135. }
  136. public void Close()
  137. {
  138. }
  139. public Type ReplaceableInterface
  140. {
  141. get { return null; }
  142. }
  143. public string Name
  144. {
  145. get { return "TerrainModule"; }
  146. }
  147. #endregion
  148. #region ITerrainModule Members
  149. /// <summary>
  150. /// Loads a terrain file from disk and installs it in the scene.
  151. /// </summary>
  152. /// <param name="filename">Filename to terrain file. Type is determined by extension.</param>
  153. public void LoadFromFile(string filename)
  154. {
  155. foreach (KeyValuePair<string, ITerrainLoader> loader in m_loaders)
  156. {
  157. if (filename.EndsWith(loader.Key))
  158. {
  159. lock (m_scene)
  160. {
  161. try
  162. {
  163. ITerrainChannel channel = loader.Value.LoadFile(filename);
  164. if (channel.Width != Constants.RegionSize || channel.Height != Constants.RegionSize)
  165. {
  166. // TerrainChannel expects a RegionSize x RegionSize map, currently
  167. throw new ArgumentException(String.Format("wrong size, use a file with size {0} x {1}",
  168. Constants.RegionSize, Constants.RegionSize));
  169. }
  170. m_log.DebugFormat("[TERRAIN]: Loaded terrain, wd/ht: {0}/{1}", channel.Width, channel.Height);
  171. m_scene.Heightmap = channel;
  172. m_channel = channel;
  173. UpdateRevertMap();
  174. }
  175. catch (NotImplementedException)
  176. {
  177. m_log.Error("[TERRAIN]: Unable to load heightmap, the " + loader.Value +
  178. " parser does not support file loading. (May be save only)");
  179. throw new TerrainException(String.Format("unable to load heightmap: parser {0} does not support loading", loader.Value));
  180. }
  181. catch (FileNotFoundException)
  182. {
  183. m_log.Error(
  184. "[TERRAIN]: Unable to load heightmap, file not found. (A directory permissions error may also cause this)");
  185. throw new TerrainException(
  186. String.Format("unable to load heightmap: file {0} not found (or permissions do not allow access", filename));
  187. }
  188. catch (ArgumentException e)
  189. {
  190. m_log.ErrorFormat("[TERRAIN]: Unable to load heightmap: {0}", e.Message);
  191. throw new TerrainException(
  192. String.Format("Unable to load heightmap: {0}", e.Message));
  193. }
  194. }
  195. CheckForTerrainUpdates();
  196. m_log.Info("[TERRAIN]: File (" + filename + ") loaded successfully");
  197. return;
  198. }
  199. }
  200. m_log.Error("[TERRAIN]: Unable to load heightmap, no file loader available for that format.");
  201. throw new TerrainException(String.Format("unable to load heightmap from file {0}: no loader available for that format", filename));
  202. }
  203. /// <summary>
  204. /// Saves the current heightmap to a specified file.
  205. /// </summary>
  206. /// <param name="filename">The destination filename</param>
  207. public void SaveToFile(string filename)
  208. {
  209. try
  210. {
  211. foreach (KeyValuePair<string, ITerrainLoader> loader in m_loaders)
  212. {
  213. if (filename.EndsWith(loader.Key))
  214. {
  215. loader.Value.SaveFile(filename, m_channel);
  216. return;
  217. }
  218. }
  219. }
  220. catch (NotImplementedException)
  221. {
  222. m_log.Error("Unable to save to " + filename + ", saving of this file format has not been implemented.");
  223. throw new TerrainException(String.Format("Unable to save heightmap: saving of this file format not implemented"));
  224. }
  225. catch (IOException ioe)
  226. {
  227. m_log.Error(String.Format("[TERRAIN]: Unable to save to {0}, {1}", filename, ioe.Message));
  228. throw new TerrainException(String.Format("Unable to save heightmap: {0}", ioe.Message));
  229. }
  230. }
  231. /// <summary>
  232. /// Loads a terrain file from the specified URI
  233. /// </summary>
  234. /// <param name="filename">The name of the terrain to load</param>
  235. /// <param name="pathToTerrainHeightmap">The URI to the terrain height map</param>
  236. public void LoadFromStream(string filename, Uri pathToTerrainHeightmap)
  237. {
  238. LoadFromStream(filename, URIFetch(pathToTerrainHeightmap));
  239. }
  240. /// <summary>
  241. /// Loads a terrain file from a stream and installs it in the scene.
  242. /// </summary>
  243. /// <param name="filename">Filename to terrain file. Type is determined by extension.</param>
  244. /// <param name="stream"></param>
  245. public void LoadFromStream(string filename, Stream stream)
  246. {
  247. foreach (KeyValuePair<string, ITerrainLoader> loader in m_loaders)
  248. {
  249. if (filename.EndsWith(loader.Key))
  250. {
  251. lock (m_scene)
  252. {
  253. try
  254. {
  255. ITerrainChannel channel = loader.Value.LoadStream(stream);
  256. m_scene.Heightmap = channel;
  257. m_channel = channel;
  258. UpdateRevertMap();
  259. }
  260. catch (NotImplementedException)
  261. {
  262. m_log.Error("[TERRAIN]: Unable to load heightmap, the " + loader.Value +
  263. " parser does not support file loading. (May be save only)");
  264. throw new TerrainException(String.Format("unable to load heightmap: parser {0} does not support loading", loader.Value));
  265. }
  266. }
  267. CheckForTerrainUpdates();
  268. m_log.Info("[TERRAIN]: File (" + filename + ") loaded successfully");
  269. return;
  270. }
  271. }
  272. m_log.Error("[TERRAIN]: Unable to load heightmap, no file loader available for that format.");
  273. throw new TerrainException(String.Format("unable to load heightmap from file {0}: no loader available for that format", filename));
  274. }
  275. private static Stream URIFetch(Uri uri)
  276. {
  277. HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
  278. // request.Credentials = credentials;
  279. request.ContentLength = 0;
  280. request.KeepAlive = false;
  281. WebResponse response = request.GetResponse();
  282. Stream file = response.GetResponseStream();
  283. if (response.ContentLength == 0)
  284. throw new Exception(String.Format("{0} returned an empty file", uri.ToString()));
  285. // return new BufferedStream(file, (int) response.ContentLength);
  286. return new BufferedStream(file, 1000000);
  287. }
  288. /// <summary>
  289. /// Modify Land
  290. /// </summary>
  291. /// <param name="pos">Land-position (X,Y,0)</param>
  292. /// <param name="size">The size of the brush (0=small, 1=medium, 2=large)</param>
  293. /// <param name="action">0=LAND_LEVEL, 1=LAND_RAISE, 2=LAND_LOWER, 3=LAND_SMOOTH, 4=LAND_NOISE, 5=LAND_REVERT</param>
  294. /// <param name="agentId">UUID of script-owner</param>
  295. public void ModifyTerrain(UUID user, Vector3 pos, byte size, byte action, UUID agentId)
  296. {
  297. float duration = 0.25f;
  298. if (action == 0)
  299. duration = 4.0f;
  300. client_OnModifyTerrain(user, (float)pos.Z, duration, size, action, pos.Y, pos.X, pos.Y, pos.X, agentId);
  301. }
  302. /// <summary>
  303. /// Saves the current heightmap to a specified stream.
  304. /// </summary>
  305. /// <param name="filename">The destination filename. Used here only to identify the image type</param>
  306. /// <param name="stream"></param>
  307. public void SaveToStream(string filename, Stream stream)
  308. {
  309. try
  310. {
  311. foreach (KeyValuePair<string, ITerrainLoader> loader in m_loaders)
  312. {
  313. if (filename.EndsWith(loader.Key))
  314. {
  315. loader.Value.SaveStream(stream, m_channel);
  316. return;
  317. }
  318. }
  319. }
  320. catch (NotImplementedException)
  321. {
  322. m_log.Error("Unable to save to " + filename + ", saving of this file format has not been implemented.");
  323. throw new TerrainException(String.Format("Unable to save heightmap: saving of this file format not implemented"));
  324. }
  325. }
  326. public void TaintTerrain ()
  327. {
  328. CheckForTerrainUpdates();
  329. }
  330. #region Plugin Loading Methods
  331. private void LoadPlugins()
  332. {
  333. m_plugineffects = new Dictionary<string, ITerrainEffect>();
  334. // Load the files in the Terrain/ dir
  335. string[] files = Directory.GetFiles("Terrain");
  336. foreach (string file in files)
  337. {
  338. m_log.Info("Loading effects in " + file);
  339. try
  340. {
  341. Assembly library = Assembly.LoadFrom(file);
  342. foreach (Type pluginType in library.GetTypes())
  343. {
  344. try
  345. {
  346. if (pluginType.IsAbstract || pluginType.IsNotPublic)
  347. continue;
  348. string typeName = pluginType.Name;
  349. if (pluginType.GetInterface("ITerrainEffect", false) != null)
  350. {
  351. ITerrainEffect terEffect = (ITerrainEffect) Activator.CreateInstance(library.GetType(pluginType.ToString()));
  352. InstallPlugin(typeName, terEffect);
  353. }
  354. else if (pluginType.GetInterface("ITerrainLoader", false) != null)
  355. {
  356. ITerrainLoader terLoader = (ITerrainLoader) Activator.CreateInstance(library.GetType(pluginType.ToString()));
  357. m_loaders[terLoader.FileExtension] = terLoader;
  358. m_log.Info("L ... " + typeName);
  359. }
  360. }
  361. catch (AmbiguousMatchException)
  362. {
  363. }
  364. }
  365. }
  366. catch (BadImageFormatException)
  367. {
  368. }
  369. }
  370. }
  371. public void InstallPlugin(string pluginName, ITerrainEffect effect)
  372. {
  373. lock (m_plugineffects)
  374. {
  375. if (!m_plugineffects.ContainsKey(pluginName))
  376. {
  377. m_plugineffects.Add(pluginName, effect);
  378. m_log.Info("E ... " + pluginName);
  379. }
  380. else
  381. {
  382. m_plugineffects[pluginName] = effect;
  383. m_log.Warn("E ... " + pluginName + " (Replaced)");
  384. }
  385. }
  386. }
  387. #endregion
  388. #endregion
  389. /// <summary>
  390. /// Installs into terrain module the standard suite of brushes
  391. /// </summary>
  392. private void InstallDefaultEffects()
  393. {
  394. // Draggable Paint Brush Effects
  395. m_painteffects[StandardTerrainEffects.Raise] = new RaiseSphere();
  396. m_painteffects[StandardTerrainEffects.Lower] = new LowerSphere();
  397. m_painteffects[StandardTerrainEffects.Smooth] = new SmoothSphere();
  398. m_painteffects[StandardTerrainEffects.Noise] = new NoiseSphere();
  399. m_painteffects[StandardTerrainEffects.Flatten] = new FlattenSphere();
  400. m_painteffects[StandardTerrainEffects.Revert] = new RevertSphere(m_revert);
  401. m_painteffects[StandardTerrainEffects.Erode] = new ErodeSphere();
  402. m_painteffects[StandardTerrainEffects.Weather] = new WeatherSphere();
  403. m_painteffects[StandardTerrainEffects.Olsen] = new OlsenSphere();
  404. // Area of effect selection effects
  405. m_floodeffects[StandardTerrainEffects.Raise] = new RaiseArea();
  406. m_floodeffects[StandardTerrainEffects.Lower] = new LowerArea();
  407. m_floodeffects[StandardTerrainEffects.Smooth] = new SmoothArea();
  408. m_floodeffects[StandardTerrainEffects.Noise] = new NoiseArea();
  409. m_floodeffects[StandardTerrainEffects.Flatten] = new FlattenArea();
  410. m_floodeffects[StandardTerrainEffects.Revert] = new RevertArea(m_revert);
  411. // Filesystem load/save loaders
  412. m_loaders[".r32"] = new RAW32();
  413. m_loaders[".f32"] = m_loaders[".r32"];
  414. m_loaders[".ter"] = new Terragen();
  415. m_loaders[".raw"] = new LLRAW();
  416. m_loaders[".jpg"] = new JPEG();
  417. m_loaders[".jpeg"] = m_loaders[".jpg"];
  418. m_loaders[".bmp"] = new BMP();
  419. m_loaders[".png"] = new PNG();
  420. m_loaders[".gif"] = new GIF();
  421. m_loaders[".tif"] = new TIFF();
  422. m_loaders[".tiff"] = m_loaders[".tif"];
  423. }
  424. /// <summary>
  425. /// Saves the current state of the region into the revert map buffer.
  426. /// </summary>
  427. public void UpdateRevertMap()
  428. {
  429. int x;
  430. for (x = 0; x < m_channel.Width; x++)
  431. {
  432. int y;
  433. for (y = 0; y < m_channel.Height; y++)
  434. {
  435. m_revert[x, y] = m_channel[x, y];
  436. }
  437. }
  438. }
  439. /// <summary>
  440. /// Loads a tile from a larger terrain file and installs it into the region.
  441. /// </summary>
  442. /// <param name="filename">The terrain file to load</param>
  443. /// <param name="fileWidth">The width of the file in units</param>
  444. /// <param name="fileHeight">The height of the file in units</param>
  445. /// <param name="fileStartX">Where to begin our slice</param>
  446. /// <param name="fileStartY">Where to begin our slice</param>
  447. public void LoadFromFile(string filename, int fileWidth, int fileHeight, int fileStartX, int fileStartY)
  448. {
  449. int offsetX = (int) m_scene.RegionInfo.RegionLocX - fileStartX;
  450. int offsetY = (int) m_scene.RegionInfo.RegionLocY - fileStartY;
  451. if (offsetX >= 0 && offsetX < fileWidth && offsetY >= 0 && offsetY < fileHeight)
  452. {
  453. // this region is included in the tile request
  454. foreach (KeyValuePair<string, ITerrainLoader> loader in m_loaders)
  455. {
  456. if (filename.EndsWith(loader.Key))
  457. {
  458. lock (m_scene)
  459. {
  460. ITerrainChannel channel = loader.Value.LoadFile(filename, offsetX, offsetY,
  461. fileWidth, fileHeight,
  462. (int) Constants.RegionSize,
  463. (int) Constants.RegionSize);
  464. m_scene.Heightmap = channel;
  465. m_channel = channel;
  466. UpdateRevertMap();
  467. }
  468. return;
  469. }
  470. }
  471. }
  472. }
  473. /// <summary>
  474. /// Performs updates to the region periodically, synchronising physics and other heightmap aware sections
  475. /// </summary>
  476. private void EventManager_OnTerrainTick()
  477. {
  478. if (m_tainted)
  479. {
  480. m_tainted = false;
  481. m_scene.PhysicsScene.SetTerrain(m_channel.GetFloatsSerialised());
  482. m_scene.SaveTerrain();
  483. // Clients who look at the map will never see changes after they looked at the map, so i've commented this out.
  484. //m_scene.CreateTerrainTexture(true);
  485. }
  486. }
  487. /// <summary>
  488. /// Processes commandline input. Do not call directly.
  489. /// </summary>
  490. /// <param name="args">Commandline arguments</param>
  491. private void EventManager_OnPluginConsole(string[] args)
  492. {
  493. if (args[0] == "terrain")
  494. {
  495. if (args.Length == 1)
  496. {
  497. m_commander.ProcessConsoleCommand("help", new string[0]);
  498. return;
  499. }
  500. string[] tmpArgs = new string[args.Length - 2];
  501. int i;
  502. for (i = 2; i < args.Length; i++)
  503. tmpArgs[i - 2] = args[i];
  504. m_commander.ProcessConsoleCommand(args[1], tmpArgs);
  505. }
  506. }
  507. /// <summary>
  508. /// Installs terrain brush hook to IClientAPI
  509. /// </summary>
  510. /// <param name="client"></param>
  511. private void EventManager_OnNewClient(IClientAPI client)
  512. {
  513. client.OnModifyTerrain += client_OnModifyTerrain;
  514. client.OnBakeTerrain += client_OnBakeTerrain;
  515. }
  516. /// <summary>
  517. /// Checks to see if the terrain has been modified since last check
  518. /// but won't attempt to limit those changes to the limits specified in the estate settings
  519. /// currently invoked by the command line operations in the region server only
  520. /// </summary>
  521. private void CheckForTerrainUpdates()
  522. {
  523. CheckForTerrainUpdates(false);
  524. }
  525. /// <summary>
  526. /// Checks to see if the terrain has been modified since last check.
  527. /// If it has been modified, every all the terrain patches are sent to the client.
  528. /// If the call is asked to respect the estate settings for terrain_raise_limit and
  529. /// terrain_lower_limit, it will clamp terrain updates between these values
  530. /// currently invoked by client_OnModifyTerrain only and not the Commander interfaces
  531. /// <param name="respectEstateSettings">should height map deltas be limited to the estate settings limits</param>
  532. /// </summary>
  533. private void CheckForTerrainUpdates(bool respectEstateSettings)
  534. {
  535. bool shouldTaint = false;
  536. float[] serialised = m_channel.GetFloatsSerialised();
  537. int x;
  538. for (x = 0; x < m_channel.Width; x += Constants.TerrainPatchSize)
  539. {
  540. int y;
  541. for (y = 0; y < m_channel.Height; y += Constants.TerrainPatchSize)
  542. {
  543. if (m_channel.Tainted(x, y))
  544. {
  545. // if we should respect the estate settings then
  546. // fixup and height deltas that don't respect them
  547. if (respectEstateSettings && LimitChannelChanges(x, y))
  548. {
  549. // this has been vetoed, so update
  550. // what we are going to send to the client
  551. serialised = m_channel.GetFloatsSerialised();
  552. }
  553. SendToClients(serialised, x, y);
  554. shouldTaint = true;
  555. }
  556. }
  557. }
  558. if (shouldTaint)
  559. {
  560. m_tainted = true;
  561. }
  562. }
  563. /// <summary>
  564. /// Checks to see height deltas in the tainted terrain patch at xStart ,yStart
  565. /// are all within the current estate limits
  566. /// <returns>true if changes were limited, false otherwise</returns>
  567. /// </summary>
  568. private bool LimitChannelChanges(int xStart, int yStart)
  569. {
  570. bool changesLimited = false;
  571. double minDelta = m_scene.RegionInfo.RegionSettings.TerrainLowerLimit;
  572. double maxDelta = m_scene.RegionInfo.RegionSettings.TerrainRaiseLimit;
  573. // loop through the height map for this patch and compare it against
  574. // the revert map
  575. for (int x = xStart; x < xStart + Constants.TerrainPatchSize; x++)
  576. {
  577. for (int y = yStart; y < yStart + Constants.TerrainPatchSize; y++)
  578. {
  579. double requestedHeight = m_channel[x, y];
  580. double bakedHeight = m_revert[x, y];
  581. double requestedDelta = requestedHeight - bakedHeight;
  582. if (requestedDelta > maxDelta)
  583. {
  584. m_channel[x, y] = bakedHeight + maxDelta;
  585. changesLimited = true;
  586. }
  587. else if (requestedDelta < minDelta)
  588. {
  589. m_channel[x, y] = bakedHeight + minDelta; //as lower is a -ve delta
  590. changesLimited = true;
  591. }
  592. }
  593. }
  594. return changesLimited;
  595. }
  596. /// <summary>
  597. /// Sends a copy of the current terrain to the scenes clients
  598. /// </summary>
  599. /// <param name="serialised">A copy of the terrain as a 1D float array of size w*h</param>
  600. /// <param name="x">The patch corner to send</param>
  601. /// <param name="y">The patch corner to send</param>
  602. private void SendToClients(float[] serialised, int x, int y)
  603. {
  604. m_scene.ForEachClient(
  605. delegate(IClientAPI controller)
  606. { controller.SendLayerData(
  607. x / Constants.TerrainPatchSize, y / Constants.TerrainPatchSize, serialised);
  608. }
  609. );
  610. }
  611. private void client_OnModifyTerrain(UUID user, float height, float seconds, byte size, byte action,
  612. float north, float west, float south, float east, UUID agentId)
  613. {
  614. bool god = m_scene.Permissions.IsGod(user);
  615. bool allowed = false;
  616. if (north == south && east == west)
  617. {
  618. if (m_painteffects.ContainsKey((StandardTerrainEffects) action))
  619. {
  620. bool[,] allowMask = new bool[m_channel.Width,m_channel.Height];
  621. allowMask.Initialize();
  622. int n = size + 1;
  623. if (n > 2)
  624. n = 4;
  625. int zx = (int) (west + 0.5);
  626. int zy = (int) (north + 0.5);
  627. int dx;
  628. for (dx=-n; dx<=n; dx++)
  629. {
  630. int dy;
  631. for (dy=-n; dy<=n; dy++)
  632. {
  633. int x = zx + dx;
  634. int y = zy + dy;
  635. if (x>=0 && y>=0 && x<m_channel.Width && y<m_channel.Height)
  636. {
  637. if (m_scene.Permissions.CanTerraformLand(agentId, new Vector3(x,y,0)))
  638. {
  639. allowMask[x, y] = true;
  640. allowed = true;
  641. }
  642. }
  643. }
  644. }
  645. if (allowed)
  646. {
  647. m_painteffects[(StandardTerrainEffects) action].PaintEffect(
  648. m_channel, allowMask, west, south, height, size, seconds);
  649. CheckForTerrainUpdates(!god); //revert changes outside estate limits
  650. }
  651. }
  652. else
  653. {
  654. m_log.Debug("Unknown terrain brush type " + action);
  655. }
  656. }
  657. else
  658. {
  659. if (m_floodeffects.ContainsKey((StandardTerrainEffects) action))
  660. {
  661. bool[,] fillArea = new bool[m_channel.Width,m_channel.Height];
  662. fillArea.Initialize();
  663. int x;
  664. for (x = 0; x < m_channel.Width; x++)
  665. {
  666. int y;
  667. for (y = 0; y < m_channel.Height; y++)
  668. {
  669. if (x < east && x > west)
  670. {
  671. if (y < north && y > south)
  672. {
  673. if (m_scene.Permissions.CanTerraformLand(agentId, new Vector3(x,y,0)))
  674. {
  675. fillArea[x, y] = true;
  676. allowed = true;
  677. }
  678. }
  679. }
  680. }
  681. }
  682. if (allowed)
  683. {
  684. m_floodeffects[(StandardTerrainEffects) action].FloodEffect(
  685. m_channel, fillArea, size);
  686. CheckForTerrainUpdates(!god); //revert changes outside estate limits
  687. }
  688. }
  689. else
  690. {
  691. m_log.Debug("Unknown terrain flood type " + action);
  692. }
  693. }
  694. }
  695. private void client_OnBakeTerrain(IClientAPI remoteClient)
  696. {
  697. // Not a good permissions check (see client_OnModifyTerrain above), need to check the entire area.
  698. // for now check a point in the centre of the region
  699. if (m_scene.Permissions.CanIssueEstateCommand(remoteClient.AgentId, true))
  700. {
  701. InterfaceBakeTerrain(null); //bake terrain does not use the passed in parameter
  702. }
  703. }
  704. #region Console Commands
  705. private void InterfaceLoadFile(Object[] args)
  706. {
  707. LoadFromFile((string) args[0]);
  708. CheckForTerrainUpdates();
  709. }
  710. private void InterfaceLoadTileFile(Object[] args)
  711. {
  712. LoadFromFile((string) args[0],
  713. (int) args[1],
  714. (int) args[2],
  715. (int) args[3],
  716. (int) args[4]);
  717. CheckForTerrainUpdates();
  718. }
  719. private void InterfaceSaveFile(Object[] args)
  720. {
  721. SaveToFile((string) args[0]);
  722. }
  723. private void InterfaceBakeTerrain(Object[] args)
  724. {
  725. UpdateRevertMap();
  726. }
  727. private void InterfaceRevertTerrain(Object[] args)
  728. {
  729. int x, y;
  730. for (x = 0; x < m_channel.Width; x++)
  731. for (y = 0; y < m_channel.Height; y++)
  732. m_channel[x, y] = m_revert[x, y];
  733. CheckForTerrainUpdates();
  734. }
  735. private void InterfaceFlipTerrain(Object[] args)
  736. {
  737. String direction = (String)args[0];
  738. if (direction.ToLower().StartsWith("y"))
  739. {
  740. for (int x = 0; x < Constants.RegionSize; x++)
  741. {
  742. for (int y = 0; y < Constants.RegionSize / 2; y++)
  743. {
  744. double height = m_channel[x, y];
  745. double flippedHeight = m_channel[x, (int)Constants.RegionSize - 1 - y];
  746. m_channel[x, y] = flippedHeight;
  747. m_channel[x, (int)Constants.RegionSize - 1 - y] = height;
  748. }
  749. }
  750. }
  751. else if (direction.ToLower().StartsWith("x"))
  752. {
  753. for (int y = 0; y < Constants.RegionSize; y++)
  754. {
  755. for (int x = 0; x < Constants.RegionSize / 2; x++)
  756. {
  757. double height = m_channel[x, y];
  758. double flippedHeight = m_channel[(int)Constants.RegionSize - 1 - x, y];
  759. m_channel[x, y] = flippedHeight;
  760. m_channel[(int)Constants.RegionSize - 1 - x, y] = height;
  761. }
  762. }
  763. }
  764. else
  765. {
  766. m_log.Error("Unrecognised direction - need x or y");
  767. }
  768. CheckForTerrainUpdates();
  769. }
  770. private void InterfaceRescaleTerrain(Object[] args)
  771. {
  772. double desiredMin = (double)args[0];
  773. double desiredMax = (double)args[1];
  774. // determine desired scaling factor
  775. double desiredRange = desiredMax - desiredMin;
  776. //m_log.InfoFormat("Desired {0}, {1} = {2}", new Object[] { desiredMin, desiredMax, desiredRange });
  777. if (desiredRange == 0d)
  778. {
  779. // delta is zero so flatten at requested height
  780. InterfaceFillTerrain(new Object[] { args[1] });
  781. }
  782. else
  783. {
  784. //work out current heightmap range
  785. double currMin = double.MaxValue;
  786. double currMax = double.MinValue;
  787. int width = m_channel.Width;
  788. int height = m_channel.Height;
  789. for (int x = 0; x < width; x++)
  790. {
  791. for (int y = 0; y < height; y++)
  792. {
  793. double currHeight = m_channel[x, y];
  794. if (currHeight < currMin)
  795. {
  796. currMin = currHeight;
  797. }
  798. else if (currHeight > currMax)
  799. {
  800. currMax = currHeight;
  801. }
  802. }
  803. }
  804. double currRange = currMax - currMin;
  805. double scale = desiredRange / currRange;
  806. //m_log.InfoFormat("Current {0}, {1} = {2}", new Object[] { currMin, currMax, currRange });
  807. //m_log.InfoFormat("Scale = {0}", scale);
  808. // scale the heightmap accordingly
  809. for (int x = 0; x < width; x++)
  810. {
  811. for (int y = 0; y < height; y++)
  812. {
  813. double currHeight = m_channel[x, y] - currMin;
  814. m_channel[x, y] = desiredMin + (currHeight * scale);
  815. }
  816. }
  817. CheckForTerrainUpdates();
  818. }
  819. }
  820. private void InterfaceElevateTerrain(Object[] args)
  821. {
  822. int x, y;
  823. for (x = 0; x < m_channel.Width; x++)
  824. for (y = 0; y < m_channel.Height; y++)
  825. m_channel[x, y] += (double) args[0];
  826. CheckForTerrainUpdates();
  827. }
  828. private void InterfaceMultiplyTerrain(Object[] args)
  829. {
  830. int x, y;
  831. for (x = 0; x < m_channel.Width; x++)
  832. for (y = 0; y < m_channel.Height; y++)
  833. m_channel[x, y] *= (double) args[0];
  834. CheckForTerrainUpdates();
  835. }
  836. private void InterfaceLowerTerrain(Object[] args)
  837. {
  838. int x, y;
  839. for (x = 0; x < m_channel.Width; x++)
  840. for (y = 0; y < m_channel.Height; y++)
  841. m_channel[x, y] -= (double) args[0];
  842. CheckForTerrainUpdates();
  843. }
  844. private void InterfaceFillTerrain(Object[] args)
  845. {
  846. int x, y;
  847. for (x = 0; x < m_channel.Width; x++)
  848. for (y = 0; y < m_channel.Height; y++)
  849. m_channel[x, y] = (double) args[0];
  850. CheckForTerrainUpdates();
  851. }
  852. private void InterfaceShowDebugStats(Object[] args)
  853. {
  854. double max = Double.MinValue;
  855. double min = double.MaxValue;
  856. double sum = 0;
  857. int x;
  858. for (x = 0; x < m_channel.Width; x++)
  859. {
  860. int y;
  861. for (y = 0; y < m_channel.Height; y++)
  862. {
  863. sum += m_channel[x, y];
  864. if (max < m_channel[x, y])
  865. max = m_channel[x, y];
  866. if (min > m_channel[x, y])
  867. min = m_channel[x, y];
  868. }
  869. }
  870. double avg = sum / (m_channel.Height * m_channel.Width);
  871. m_log.Info("Channel " + m_channel.Width + "x" + m_channel.Height);
  872. m_log.Info("max/min/avg/sum: " + max + "/" + min + "/" + avg + "/" + sum);
  873. }
  874. private void InterfaceEnableExperimentalBrushes(Object[] args)
  875. {
  876. if ((bool) args[0])
  877. {
  878. m_painteffects[StandardTerrainEffects.Revert] = new WeatherSphere();
  879. m_painteffects[StandardTerrainEffects.Flatten] = new OlsenSphere();
  880. m_painteffects[StandardTerrainEffects.Smooth] = new ErodeSphere();
  881. }
  882. else
  883. {
  884. InstallDefaultEffects();
  885. }
  886. }
  887. private void InterfaceRunPluginEffect(Object[] args)
  888. {
  889. if ((string) args[0] == "list")
  890. {
  891. m_log.Info("List of loaded plugins");
  892. foreach (KeyValuePair<string, ITerrainEffect> kvp in m_plugineffects)
  893. {
  894. m_log.Info(kvp.Key);
  895. }
  896. return;
  897. }
  898. if ((string) args[0] == "reload")
  899. {
  900. LoadPlugins();
  901. return;
  902. }
  903. if (m_plugineffects.ContainsKey((string) args[0]))
  904. {
  905. m_plugineffects[(string) args[0]].RunEffect(m_channel);
  906. CheckForTerrainUpdates();
  907. }
  908. else
  909. {
  910. m_log.Warn("No such plugin effect loaded.");
  911. }
  912. }
  913. private void InstallInterfaces()
  914. {
  915. // Load / Save
  916. string supportedFileExtensions = "";
  917. foreach (KeyValuePair<string, ITerrainLoader> loader in m_loaders)
  918. supportedFileExtensions += " " + loader.Key + " (" + loader.Value + ")";
  919. Command loadFromFileCommand =
  920. new Command("load", CommandIntentions.COMMAND_HAZARDOUS, InterfaceLoadFile, "Loads a terrain from a specified file.");
  921. loadFromFileCommand.AddArgument("filename",
  922. "The file you wish to load from, the file extension determines the loader to be used. Supported extensions include: " +
  923. supportedFileExtensions, "String");
  924. Command saveToFileCommand =
  925. new Command("save", CommandIntentions.COMMAND_NON_HAZARDOUS, InterfaceSaveFile, "Saves the current heightmap to a specified file.");
  926. saveToFileCommand.AddArgument("filename",
  927. "The destination filename for your heightmap, the file extension determines the format to save in. Supported extensions include: " +
  928. supportedFileExtensions, "String");
  929. Command loadFromTileCommand =
  930. new Command("load-tile", CommandIntentions.COMMAND_HAZARDOUS, InterfaceLoadTileFile, "Loads a terrain from a section of a larger file.");
  931. loadFromTileCommand.AddArgument("filename",
  932. "The file you wish to load from, the file extension determines the loader to be used. Supported extensions include: " +
  933. supportedFileExtensions, "String");
  934. loadFromTileCommand.AddArgument("file width", "The width of the file in tiles", "Integer");
  935. loadFromTileCommand.AddArgument("file height", "The height of the file in tiles", "Integer");
  936. loadFromTileCommand.AddArgument("minimum X tile", "The X region coordinate of the first section on the file",
  937. "Integer");
  938. loadFromTileCommand.AddArgument("minimum Y tile", "The Y region coordinate of the first section on the file",
  939. "Integer");
  940. // Terrain adjustments
  941. Command fillRegionCommand =
  942. new Command("fill", CommandIntentions.COMMAND_HAZARDOUS, InterfaceFillTerrain, "Fills the current heightmap with a specified value.");
  943. fillRegionCommand.AddArgument("value", "The numeric value of the height you wish to set your region to.",
  944. "Double");
  945. Command elevateCommand =
  946. new Command("elevate", CommandIntentions.COMMAND_HAZARDOUS, InterfaceElevateTerrain, "Raises the current heightmap by the specified amount.");
  947. elevateCommand.AddArgument("amount", "The amount of height to add to the terrain in meters.", "Double");
  948. Command lowerCommand =
  949. new Command("lower", CommandIntentions.COMMAND_HAZARDOUS, InterfaceLowerTerrain, "Lowers the current heightmap by the specified amount.");
  950. lowerCommand.AddArgument("amount", "The amount of height to remove from the terrain in meters.", "Double");
  951. Command multiplyCommand =
  952. new Command("multiply", CommandIntentions.COMMAND_HAZARDOUS, InterfaceMultiplyTerrain, "Multiplies the heightmap by the value specified.");
  953. multiplyCommand.AddArgument("value", "The value to multiply the heightmap by.", "Double");
  954. Command bakeRegionCommand =
  955. new Command("bake", CommandIntentions.COMMAND_HAZARDOUS, InterfaceBakeTerrain, "Saves the current terrain into the regions revert map.");
  956. Command revertRegionCommand =
  957. new Command("revert", CommandIntentions.COMMAND_HAZARDOUS, InterfaceRevertTerrain, "Loads the revert map terrain into the regions heightmap.");
  958. Command flipCommand =
  959. new Command("flip", CommandIntentions.COMMAND_HAZARDOUS, InterfaceFlipTerrain, "Flips the current terrain about the X or Y axis");
  960. flipCommand.AddArgument("direction", "[x|y] the direction to flip the terrain in", "String");
  961. Command rescaleCommand =
  962. new Command("rescale", CommandIntentions.COMMAND_HAZARDOUS, InterfaceRescaleTerrain, "Rescales the current terrain to fit between the given min and max heights");
  963. rescaleCommand.AddArgument("min", "min terrain height after rescaling", "Double");
  964. rescaleCommand.AddArgument("max", "max terrain height after rescaling", "Double");
  965. // Debug
  966. Command showDebugStatsCommand =
  967. new Command("stats", CommandIntentions.COMMAND_STATISTICAL, InterfaceShowDebugStats,
  968. "Shows some information about the regions heightmap for debugging purposes.");
  969. Command experimentalBrushesCommand =
  970. new Command("newbrushes", CommandIntentions.COMMAND_HAZARDOUS, InterfaceEnableExperimentalBrushes,
  971. "Enables experimental brushes which replace the standard terrain brushes. WARNING: This is a debug setting and may be removed at any time.");
  972. experimentalBrushesCommand.AddArgument("Enabled?", "true / false - Enable new brushes", "Boolean");
  973. //Plugins
  974. Command pluginRunCommand =
  975. new Command("effect", CommandIntentions.COMMAND_HAZARDOUS, InterfaceRunPluginEffect, "Runs a specified plugin effect");
  976. pluginRunCommand.AddArgument("name", "The plugin effect you wish to run, or 'list' to see all plugins", "String");
  977. m_commander.RegisterCommand("load", loadFromFileCommand);
  978. m_commander.RegisterCommand("load-tile", loadFromTileCommand);
  979. m_commander.RegisterCommand("save", saveToFileCommand);
  980. m_commander.RegisterCommand("fill", fillRegionCommand);
  981. m_commander.RegisterCommand("elevate", elevateCommand);
  982. m_commander.RegisterCommand("lower", lowerCommand);
  983. m_commander.RegisterCommand("multiply", multiplyCommand);
  984. m_commander.RegisterCommand("bake", bakeRegionCommand);
  985. m_commander.RegisterCommand("revert", revertRegionCommand);
  986. m_commander.RegisterCommand("newbrushes", experimentalBrushesCommand);
  987. m_commander.RegisterCommand("stats", showDebugStatsCommand);
  988. m_commander.RegisterCommand("effect", pluginRunCommand);
  989. m_commander.RegisterCommand("flip", flipCommand);
  990. m_commander.RegisterCommand("rescale", rescaleCommand);
  991. // Add this to our scene so scripts can call these functions
  992. m_scene.RegisterModuleCommander(m_commander);
  993. }
  994. #endregion
  995. }
  996. }