TerrainModule.cs 46 KB

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