TerrainModule.cs 76 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746
  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 Mono.Addins;
  36. using OpenSim.Data;
  37. using OpenSim.Framework;
  38. using OpenSim.Framework.Console;
  39. using OpenSim.Region.CoreModules.Framework.InterfaceCommander;
  40. using OpenSim.Region.CoreModules.World.Terrain.FileLoaders;
  41. using OpenSim.Region.CoreModules.World.Terrain.Modifiers;
  42. using OpenSim.Region.CoreModules.World.Terrain.FloodBrushes;
  43. using OpenSim.Region.CoreModules.World.Terrain.PaintBrushes;
  44. using OpenSim.Region.Framework.Interfaces;
  45. using OpenSim.Region.Framework.Scenes;
  46. namespace OpenSim.Region.CoreModules.World.Terrain
  47. {
  48. [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "TerrainModule")]
  49. public class TerrainModule : INonSharedRegionModule, ICommandableModule, ITerrainModule
  50. {
  51. #region StandardTerrainEffects enum
  52. /// <summary>
  53. /// A standard set of terrain brushes and effects recognised by viewers
  54. /// </summary>
  55. public enum StandardTerrainEffects : byte
  56. {
  57. Flatten = 0,
  58. Raise = 1,
  59. Lower = 2,
  60. Smooth = 3,
  61. Noise = 4,
  62. Revert = 5,
  63. // Extended brushes
  64. Erode = 255,
  65. Weather = 254,
  66. Olsen = 253
  67. }
  68. #endregion
  69. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  70. #pragma warning disable 414
  71. private static readonly string LogHeader = "[TERRAIN MODULE]";
  72. #pragma warning restore 414
  73. private readonly Commander m_commander = new Commander("terrain");
  74. private readonly Dictionary<StandardTerrainEffects, ITerrainFloodEffect> m_floodeffects =
  75. new Dictionary<StandardTerrainEffects, ITerrainFloodEffect>();
  76. private readonly Dictionary<string, ITerrainLoader> m_loaders = new Dictionary<string, ITerrainLoader>();
  77. private readonly Dictionary<StandardTerrainEffects, ITerrainPaintableEffect> m_painteffects =
  78. new Dictionary<StandardTerrainEffects, ITerrainPaintableEffect>();
  79. private Dictionary<string, ITerrainEffect> m_plugineffects;
  80. private Dictionary<string, ITerrainModifier> m_modifyOperations =
  81. new Dictionary<string, ITerrainModifier>();
  82. private ITerrainChannel m_channel;
  83. private ITerrainChannel m_revert;
  84. private Scene m_scene;
  85. private volatile bool m_tainted;
  86. private readonly Stack<LandUndoState> m_undo = new Stack<LandUndoState>(5);
  87. private String m_InitialTerrain = "pinhead-island";
  88. // If true, send terrain patch updates to clients based on their view distance
  89. private bool m_sendTerrainUpdatesByViewDistance = true;
  90. // Class to keep the per client collection of terrain patches that must be sent.
  91. // A patch is set to 'true' meaning it should be sent to the client. Once the
  92. // patch packet is queued to the client, the bit for that patch is set to 'false'.
  93. private class PatchUpdates
  94. {
  95. private bool[,] updated; // for each patch, whether it needs to be sent to this client
  96. private int updateCount; // number of patches that need to be sent
  97. public ScenePresence Presence; // a reference to the client to send to
  98. public TerrainData Terrain; // reference to the underlying terrain
  99. public PatchUpdates(TerrainData terrData, ScenePresence pPresence)
  100. {
  101. updated = new bool[terrData.SizeX / Constants.TerrainPatchSize, terrData.SizeY / Constants.TerrainPatchSize];
  102. updateCount = 0;
  103. Presence = pPresence;
  104. Terrain = terrData;
  105. // Initially, send all patches to the client
  106. SetAll(true);
  107. }
  108. // Returns 'true' if there are any patches marked for sending
  109. public bool HasUpdates()
  110. {
  111. return (updateCount > 0);
  112. }
  113. public void SetByXY(int x, int y, bool state)
  114. {
  115. this.SetByPatch(x / Constants.TerrainPatchSize, y / Constants.TerrainPatchSize, state);
  116. }
  117. public bool GetByPatch(int patchX, int patchY)
  118. {
  119. return updated[patchX, patchY];
  120. }
  121. public void SetByPatch(int patchX, int patchY, bool state)
  122. {
  123. bool prevState = updated[patchX, patchY];
  124. if (!prevState && state)
  125. updateCount++;
  126. if (prevState && !state)
  127. updateCount--;
  128. updated[patchX, patchY] = state;
  129. }
  130. public void SetAll(bool state)
  131. {
  132. updateCount = 0;
  133. for(int xx = 0; xx < updated.GetLength(0); xx++)
  134. for(int yy = 0; yy < updated.GetLength(1); yy++)
  135. updated[xx, yy] = state;
  136. if (state)
  137. updateCount = updated.GetLength(0) * updated.GetLength(1);
  138. }
  139. // Logically OR's the terrain data's patch taint map into this client's update map.
  140. public void SetAll(TerrainData terrData)
  141. {
  142. if (updated.GetLength(0) != (terrData.SizeX / Constants.TerrainPatchSize)
  143. || updated.GetLength(1) != (terrData.SizeY / Constants.TerrainPatchSize))
  144. {
  145. throw new Exception(
  146. String.Format("{0} PatchUpdates.SetAll: patch array not same size as terrain. arr=<{1},{2}>, terr=<{3},{4}>",
  147. LogHeader, updated.GetLength(0), updated.GetLength(1),
  148. terrData.SizeX / Constants.TerrainPatchSize, terrData.SizeY / Constants.TerrainPatchSize)
  149. );
  150. }
  151. for(int xx = 0; xx < terrData.SizeX; xx += Constants.TerrainPatchSize)
  152. {
  153. for(int yy = 0; yy < terrData.SizeY; yy += Constants.TerrainPatchSize)
  154. {
  155. // Only set tainted. The patch bit may be set if the patch was to be sent later.
  156. if (terrData.IsTaintedAt(xx, yy, false))
  157. {
  158. this.SetByXY(xx, yy, true);
  159. }
  160. }
  161. }
  162. }
  163. }
  164. // The flags of which terrain patches to send for each of the ScenePresence's
  165. private Dictionary<UUID, PatchUpdates> m_perClientPatchUpdates = new Dictionary<UUID, PatchUpdates>();
  166. /// <summary>
  167. /// Human readable list of terrain file extensions that are supported.
  168. /// </summary>
  169. private string m_supportedFileExtensions = "";
  170. //For terrain save-tile file extensions
  171. private string m_supportFileExtensionsForTileSave = "";
  172. #region ICommandableModule Members
  173. public ICommander CommandInterface {
  174. get { return m_commander; }
  175. }
  176. #endregion
  177. #region INonSharedRegionModule Members
  178. /// <summary>
  179. /// Creates and initialises a terrain module for a region
  180. /// </summary>
  181. /// <param name="scene">Region initialising</param>
  182. /// <param name="config">Config for the region</param>
  183. public void Initialise(IConfigSource config)
  184. {
  185. IConfig terrainConfig = config.Configs["Terrain"];
  186. if (terrainConfig != null)
  187. {
  188. m_InitialTerrain = terrainConfig.GetString("InitialTerrain", m_InitialTerrain);
  189. m_sendTerrainUpdatesByViewDistance = terrainConfig.GetBoolean("SendTerrainUpdatesByViewDistance", m_sendTerrainUpdatesByViewDistance);
  190. }
  191. }
  192. public void AddRegion(Scene scene)
  193. {
  194. m_scene = scene;
  195. // Install terrain module in the simulator
  196. lock(m_scene)
  197. {
  198. if (m_scene.Heightmap == null)
  199. {
  200. m_channel = new TerrainChannel(m_InitialTerrain, (int)m_scene.RegionInfo.RegionSizeX,
  201. (int)m_scene.RegionInfo.RegionSizeY,
  202. (int)m_scene.RegionInfo.RegionSizeZ);
  203. m_scene.Heightmap = m_channel;
  204. UpdateRevertMap();
  205. }
  206. else
  207. {
  208. m_channel = m_scene.Heightmap;
  209. UpdateRevertMap();
  210. }
  211. m_scene.RegisterModuleInterface<ITerrainModule>(this);
  212. m_scene.EventManager.OnNewClient += EventManager_OnNewClient;
  213. m_scene.EventManager.OnClientClosed += EventManager_OnClientClosed;
  214. m_scene.EventManager.OnPluginConsole += EventManager_OnPluginConsole;
  215. m_scene.EventManager.OnTerrainTick += EventManager_OnTerrainTick;
  216. m_scene.EventManager.OnFrame += EventManager_OnFrame;
  217. }
  218. InstallDefaultEffects();
  219. LoadPlugins();
  220. // Generate user-readable extensions list
  221. string supportedFilesSeparator = "";
  222. string supportedFilesSeparatorForTileSave = "";
  223. m_supportFileExtensionsForTileSave = "";
  224. foreach(KeyValuePair<string, ITerrainLoader> loader in m_loaders)
  225. {
  226. m_supportedFileExtensions += supportedFilesSeparator + loader.Key + " (" + loader.Value + ")";
  227. supportedFilesSeparator = ", ";
  228. //For terrain save-tile file extensions
  229. if (loader.Value.SupportsTileSave() == true)
  230. {
  231. m_supportFileExtensionsForTileSave += supportedFilesSeparatorForTileSave + loader.Key + " (" + loader.Value + ")";
  232. supportedFilesSeparatorForTileSave = ", ";
  233. }
  234. }
  235. }
  236. public void RegionLoaded(Scene scene)
  237. {
  238. //Do this here to give file loaders time to initialize and
  239. //register their supported file extensions and file formats.
  240. InstallInterfaces();
  241. }
  242. public void RemoveRegion(Scene scene)
  243. {
  244. lock(m_scene)
  245. {
  246. // remove the commands
  247. m_scene.UnregisterModuleCommander(m_commander.Name);
  248. // remove the event-handlers
  249. m_scene.EventManager.OnFrame -= EventManager_OnFrame;
  250. m_scene.EventManager.OnTerrainTick -= EventManager_OnTerrainTick;
  251. m_scene.EventManager.OnPluginConsole -= EventManager_OnPluginConsole;
  252. m_scene.EventManager.OnClientClosed -= EventManager_OnClientClosed;
  253. m_scene.EventManager.OnNewClient -= EventManager_OnNewClient;
  254. // remove the interface
  255. m_scene.UnregisterModuleInterface<ITerrainModule>(this);
  256. }
  257. }
  258. public void Close()
  259. {
  260. }
  261. public Type ReplaceableInterface {
  262. get { return null; }
  263. }
  264. public string Name {
  265. get { return "TerrainModule"; }
  266. }
  267. #endregion
  268. #region ITerrainModule Members
  269. public void UndoTerrain(ITerrainChannel channel)
  270. {
  271. m_channel = channel;
  272. }
  273. /// <summary>
  274. /// Loads a terrain file from disk and installs it in the scene.
  275. /// </summary>
  276. /// <param name="filename">Filename to terrain file. Type is determined by extension.</param>
  277. public void LoadFromFile(string filename)
  278. {
  279. foreach(KeyValuePair<string, ITerrainLoader> loader in m_loaders)
  280. {
  281. if (filename.EndsWith(loader.Key))
  282. {
  283. lock(m_scene)
  284. {
  285. try
  286. {
  287. ITerrainChannel channel = loader.Value.LoadFile(filename);
  288. if (channel.Width != m_scene.RegionInfo.RegionSizeX || channel.Height != m_scene.RegionInfo.RegionSizeY)
  289. {
  290. // TerrainChannel expects a RegionSize x RegionSize map, currently
  291. throw new ArgumentException(String.Format("wrong size, use a file with size {0} x {1}",
  292. m_scene.RegionInfo.RegionSizeX, m_scene.RegionInfo.RegionSizeY));
  293. }
  294. m_log.DebugFormat("[TERRAIN]: Loaded terrain, wd/ht: {0}/{1}", channel.Width, channel.Height);
  295. m_scene.Heightmap = channel;
  296. m_channel = channel;
  297. UpdateRevertMap();
  298. }
  299. catch(NotImplementedException)
  300. {
  301. m_log.Error("[TERRAIN]: Unable to load heightmap, the " + loader.Value +
  302. " parser does not support file loading. (May be save only)");
  303. throw new TerrainException(String.Format("unable to load heightmap: parser {0} does not support loading", loader.Value));
  304. }
  305. catch(FileNotFoundException)
  306. {
  307. m_log.Error(
  308. "[TERRAIN]: Unable to load heightmap, file not found. (A directory permissions error may also cause this)");
  309. throw new TerrainException(
  310. String.Format("unable to load heightmap: file {0} not found (or permissions do not allow access", filename));
  311. }
  312. catch(ArgumentException e)
  313. {
  314. m_log.ErrorFormat("[TERRAIN]: Unable to load heightmap: {0}", e.Message);
  315. throw new TerrainException(
  316. String.Format("Unable to load heightmap: {0}", e.Message));
  317. }
  318. }
  319. m_log.Info("[TERRAIN]: File (" + filename + ") loaded successfully");
  320. return;
  321. }
  322. }
  323. m_log.Error("[TERRAIN]: Unable to load heightmap, no file loader available for that format.");
  324. throw new TerrainException(String.Format("unable to load heightmap from file {0}: no loader available for that format", filename));
  325. }
  326. /// <summary>
  327. /// Saves the current heightmap to a specified file.
  328. /// </summary>
  329. /// <param name="filename">The destination filename</param>
  330. public void SaveToFile(string filename)
  331. {
  332. try
  333. {
  334. foreach(KeyValuePair<string, ITerrainLoader> loader in m_loaders)
  335. {
  336. if (filename.EndsWith(loader.Key))
  337. {
  338. loader.Value.SaveFile(filename, m_channel);
  339. m_log.InfoFormat("[TERRAIN]: Saved terrain from {0} to {1}", m_scene.RegionInfo.RegionName, filename);
  340. return;
  341. }
  342. }
  343. }
  344. catch(IOException ioe)
  345. {
  346. m_log.Error(String.Format("[TERRAIN]: Unable to save to {0}, {1}", filename, ioe.Message));
  347. }
  348. m_log.ErrorFormat(
  349. "[TERRAIN]: Could not save terrain from {0} to {1}. Valid file extensions are {2}",
  350. m_scene.RegionInfo.RegionName, filename, m_supportedFileExtensions);
  351. }
  352. /// <summary>
  353. /// Loads a terrain file from the specified URI
  354. /// </summary>
  355. /// <param name="filename">The name of the terrain to load</param>
  356. /// <param name="pathToTerrainHeightmap">The URI to the terrain height map</param>
  357. public void LoadFromStream(string filename, Uri pathToTerrainHeightmap)
  358. {
  359. LoadFromStream(filename, URIFetch(pathToTerrainHeightmap));
  360. }
  361. public void LoadFromStream(string filename, Stream stream)
  362. {
  363. LoadFromStream(filename, Vector3.Zero, 0f, Vector2.Zero, stream);
  364. }
  365. /// <summary>
  366. /// Loads a terrain file from a stream and installs it in the scene.
  367. /// </summary>
  368. /// <param name="filename">Filename to terrain file. Type is determined by extension.</param>
  369. /// <param name="stream"></param>
  370. public void LoadFromStream(string filename, Vector3 displacement,
  371. float radianRotation, Vector2 rotationDisplacement, Stream stream)
  372. {
  373. foreach(KeyValuePair<string, ITerrainLoader> loader in m_loaders)
  374. {
  375. if (filename.EndsWith(loader.Key))
  376. {
  377. lock(m_scene)
  378. {
  379. try
  380. {
  381. ITerrainChannel channel = loader.Value.LoadStream(stream);
  382. m_channel.Merge(channel, displacement, radianRotation, rotationDisplacement);
  383. UpdateRevertMap();
  384. }
  385. catch(NotImplementedException)
  386. {
  387. m_log.Error("[TERRAIN]: Unable to load heightmap, the " + loader.Value +
  388. " parser does not support file loading. (May be save only)");
  389. throw new TerrainException(String.Format("unable to load heightmap: parser {0} does not support loading", loader.Value));
  390. }
  391. }
  392. m_log.Info("[TERRAIN]: File (" + filename + ") loaded successfully");
  393. return;
  394. }
  395. }
  396. m_log.Error("[TERRAIN]: Unable to load heightmap, no file loader available for that format.");
  397. throw new TerrainException(String.Format("unable to load heightmap from file {0}: no loader available for that format", filename));
  398. }
  399. private static Stream URIFetch(Uri uri)
  400. {
  401. HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
  402. // request.Credentials = credentials;
  403. request.ContentLength = 0;
  404. request.KeepAlive = false;
  405. WebResponse response = request.GetResponse();
  406. Stream file = response.GetResponseStream();
  407. if (response.ContentLength == 0)
  408. throw new Exception(String.Format("{0} returned an empty file", uri.ToString()));
  409. // return new BufferedStream(file, (int) response.ContentLength);
  410. return new BufferedStream(file, 1000000);
  411. }
  412. /// <summary>
  413. /// Modify Land
  414. /// </summary>
  415. /// <param name="pos">Land-position (X,Y,0)</param>
  416. /// <param name="size">The size of the brush (0=small, 1=medium, 2=large)</param>
  417. /// <param name="action">0=LAND_LEVEL, 1=LAND_RAISE, 2=LAND_LOWER, 3=LAND_SMOOTH, 4=LAND_NOISE, 5=LAND_REVERT</param>
  418. /// <param name="agentId">UUID of script-owner</param>
  419. public void ModifyTerrain(UUID user, Vector3 pos, byte size, byte action, UUID agentId)
  420. {
  421. float duration = 0.25f;
  422. if (action == 0)
  423. duration = 4.0f;
  424. client_OnModifyTerrain(user, (float)pos.Z, duration, size, action, pos.Y, pos.X, pos.Y, pos.X, agentId);
  425. }
  426. /// <summary>
  427. /// Saves the current heightmap to a specified stream.
  428. /// </summary>
  429. /// <param name="filename">The destination filename. Used here only to identify the image type</param>
  430. /// <param name="stream"></param>
  431. public void SaveToStream(string filename, Stream stream)
  432. {
  433. try
  434. {
  435. foreach(KeyValuePair<string, ITerrainLoader> loader in m_loaders)
  436. {
  437. if (filename.EndsWith(loader.Key))
  438. {
  439. loader.Value.SaveStream(stream, m_channel);
  440. return;
  441. }
  442. }
  443. }
  444. catch(NotImplementedException)
  445. {
  446. m_log.Error("Unable to save to " + filename + ", saving of this file format has not been implemented.");
  447. throw new TerrainException(String.Format("Unable to save heightmap: saving of this file format not implemented"));
  448. }
  449. }
  450. // Someone diddled terrain outside the normal code paths. Set the taintedness for all clients.
  451. // ITerrainModule.TaintTerrain()
  452. public void TaintTerrain()
  453. {
  454. lock(m_perClientPatchUpdates)
  455. {
  456. // Set the flags for all clients so the tainted patches will be sent out
  457. foreach(PatchUpdates pups in m_perClientPatchUpdates.Values)
  458. {
  459. pups.SetAll(m_scene.Heightmap.GetTerrainData());
  460. }
  461. }
  462. }
  463. // ITerrainModule.PushTerrain()
  464. public void PushTerrain(IClientAPI pClient)
  465. {
  466. // If view distance based, set the modified patch bits and the frame event will send the updates
  467. if (m_sendTerrainUpdatesByViewDistance)
  468. {
  469. ScenePresence presence = m_scene.GetScenePresence(pClient.AgentId);
  470. if (presence != null)
  471. {
  472. lock(m_perClientPatchUpdates)
  473. {
  474. PatchUpdates pups;
  475. if (!m_perClientPatchUpdates.TryGetValue(pClient.AgentId, out pups))
  476. {
  477. // There is a ScenePresence without a send patch map. Create one.
  478. pups = new PatchUpdates(m_scene.Heightmap.GetTerrainData(), presence);
  479. m_perClientPatchUpdates.Add(presence.UUID, pups);
  480. }
  481. // By setting all to modified, the next update tick will send the patches
  482. pups.SetAll(true);
  483. }
  484. }
  485. }
  486. else
  487. {
  488. // The traditional way is to call into the protocol stack to send them all.
  489. pClient.SendLayerData(new float[10]);
  490. }
  491. }
  492. #region Plugin Loading Methods
  493. private void LoadPlugins()
  494. {
  495. m_plugineffects = new Dictionary<string, ITerrainEffect>();
  496. LoadPlugins(Assembly.GetCallingAssembly());
  497. string plugineffectsPath = "Terrain";
  498. // Load the files in the Terrain/ dir
  499. if (!Directory.Exists(plugineffectsPath))
  500. return;
  501. string[] files = Directory.GetFiles(plugineffectsPath);
  502. foreach(string file in files)
  503. {
  504. m_log.Info("Loading effects in " + file);
  505. try
  506. {
  507. Assembly library = Assembly.LoadFrom(file);
  508. LoadPlugins(library);
  509. }
  510. catch(BadImageFormatException)
  511. {
  512. }
  513. }
  514. }
  515. private void LoadPlugins(Assembly library)
  516. {
  517. foreach(Type pluginType in library.GetTypes())
  518. {
  519. try
  520. {
  521. if (pluginType.IsAbstract || pluginType.IsNotPublic)
  522. continue;
  523. string typeName = pluginType.Name;
  524. if (pluginType.GetInterface("ITerrainEffect", false) != null)
  525. {
  526. ITerrainEffect terEffect = (ITerrainEffect)Activator.CreateInstance(library.GetType(pluginType.ToString()));
  527. InstallPlugin(typeName, terEffect);
  528. }
  529. else if (pluginType.GetInterface("ITerrainLoader", false) != null)
  530. {
  531. ITerrainLoader terLoader = (ITerrainLoader)Activator.CreateInstance(library.GetType(pluginType.ToString()));
  532. m_loaders[terLoader.FileExtension] = terLoader;
  533. m_log.Info("L ... " + typeName);
  534. }
  535. }
  536. catch(AmbiguousMatchException)
  537. {
  538. }
  539. }
  540. }
  541. public void InstallPlugin(string pluginName, ITerrainEffect effect)
  542. {
  543. lock(m_plugineffects)
  544. {
  545. if (!m_plugineffects.ContainsKey(pluginName))
  546. {
  547. m_plugineffects.Add(pluginName, effect);
  548. m_log.Info("E ... " + pluginName);
  549. }
  550. else
  551. {
  552. m_plugineffects[pluginName] = effect;
  553. m_log.Info("E ... " + pluginName + " (Replaced)");
  554. }
  555. }
  556. }
  557. #endregion
  558. #endregion
  559. /// <summary>
  560. /// Installs into terrain module the standard suite of brushes
  561. /// </summary>
  562. private void InstallDefaultEffects()
  563. {
  564. // Draggable Paint Brush Effects
  565. m_painteffects[StandardTerrainEffects.Raise] = new RaiseSphere();
  566. m_painteffects[StandardTerrainEffects.Lower] = new LowerSphere();
  567. m_painteffects[StandardTerrainEffects.Smooth] = new SmoothSphere();
  568. m_painteffects[StandardTerrainEffects.Noise] = new NoiseSphere();
  569. m_painteffects[StandardTerrainEffects.Flatten] = new FlattenSphere();
  570. m_painteffects[StandardTerrainEffects.Revert] = new RevertSphere(m_revert);
  571. m_painteffects[StandardTerrainEffects.Erode] = new ErodeSphere();
  572. m_painteffects[StandardTerrainEffects.Weather] = new WeatherSphere();
  573. m_painteffects[StandardTerrainEffects.Olsen] = new OlsenSphere();
  574. // Area of effect selection effects
  575. m_floodeffects[StandardTerrainEffects.Raise] = new RaiseArea();
  576. m_floodeffects[StandardTerrainEffects.Lower] = new LowerArea();
  577. m_floodeffects[StandardTerrainEffects.Smooth] = new SmoothArea();
  578. m_floodeffects[StandardTerrainEffects.Noise] = new NoiseArea();
  579. m_floodeffects[StandardTerrainEffects.Flatten] = new FlattenArea();
  580. m_floodeffects[StandardTerrainEffects.Revert] = new RevertArea(m_revert);
  581. // Terrain Modifier operations
  582. m_modifyOperations["min"] = new MinModifier(this);
  583. m_modifyOperations["max"] = new MaxModifier(this);
  584. m_modifyOperations["raise"] = new RaiseModifier(this);
  585. m_modifyOperations["lower"] = new LowerModifier(this);
  586. m_modifyOperations["fill"] = new FillModifier(this);
  587. m_modifyOperations["smooth"] = new SmoothModifier(this);
  588. m_modifyOperations["noise"] = new NoiseModifier(this);
  589. // Filesystem load/save loaders
  590. m_loaders[".r32"] = new RAW32();
  591. m_loaders[".f32"] = m_loaders[".r32"];
  592. m_loaders[".ter"] = new Terragen();
  593. m_loaders[".raw"] = new LLRAW();
  594. m_loaders[".jpg"] = new JPEG();
  595. m_loaders[".jpeg"] = m_loaders[".jpg"];
  596. m_loaders[".bmp"] = new BMP();
  597. m_loaders[".png"] = new PNG();
  598. m_loaders[".gif"] = new GIF();
  599. m_loaders[".tif"] = new TIFF();
  600. m_loaders[".tiff"] = m_loaders[".tif"];
  601. }
  602. /// <summary>
  603. /// Saves the current state of the region into the revert map buffer.
  604. /// </summary>
  605. public void UpdateRevertMap()
  606. {
  607. /*
  608. int x;
  609. for (x = 0; x < m_channel.Width; x++)
  610. {
  611. int y;
  612. for (y = 0; y < m_channel.Height; y++)
  613. {
  614. m_revert[x, y] = m_channel[x, y];
  615. }
  616. }
  617. */
  618. m_revert = m_channel.MakeCopy();
  619. }
  620. /// <summary>
  621. /// Loads a tile from a larger terrain file and installs it into the region.
  622. /// </summary>
  623. /// <param name="filename">The terrain file to load</param>
  624. /// <param name="fileWidth">The width of the file in units</param>
  625. /// <param name="fileHeight">The height of the file in units</param>
  626. /// <param name="fileStartX">Where to begin our slice</param>
  627. /// <param name="fileStartY">Where to begin our slice</param>
  628. public void LoadFromFile(string filename, int fileWidth, int fileHeight, int fileStartX, int fileStartY)
  629. {
  630. int offsetX = (int)m_scene.RegionInfo.RegionLocX - fileStartX;
  631. int offsetY = (int)m_scene.RegionInfo.RegionLocY - fileStartY;
  632. if (offsetX >= 0 && offsetX < fileWidth && offsetY >= 0 && offsetY < fileHeight)
  633. {
  634. // this region is included in the tile request
  635. foreach(KeyValuePair<string, ITerrainLoader> loader in m_loaders)
  636. {
  637. if (filename.EndsWith(loader.Key))
  638. {
  639. lock(m_scene)
  640. {
  641. ITerrainChannel channel = loader.Value.LoadFile(filename, offsetX, offsetY,
  642. fileWidth, fileHeight,
  643. (int)m_scene.RegionInfo.RegionSizeX,
  644. (int)m_scene.RegionInfo.RegionSizeY);
  645. m_scene.Heightmap = channel;
  646. m_channel = channel;
  647. UpdateRevertMap();
  648. }
  649. return;
  650. }
  651. }
  652. }
  653. }
  654. /// <summary>
  655. /// Save a number of map tiles to a single big image file.
  656. /// </summary>
  657. /// <remarks>
  658. /// If the image file already exists then the tiles saved will replace those already in the file - other tiles
  659. /// will be untouched.
  660. /// </remarks>
  661. /// <param name="filename">The terrain file to save</param>
  662. /// <param name="fileWidth">The number of tiles to save along the X axis.</param>
  663. /// <param name="fileHeight">The number of tiles to save along the Y axis.</param>
  664. /// <param name="fileStartX">The map x co-ordinate at which to begin the save.</param>
  665. /// <param name="fileStartY">The may y co-ordinate at which to begin the save.</param>
  666. public void SaveToFile(string filename, int fileWidth, int fileHeight, int fileStartX, int fileStartY)
  667. {
  668. int offsetX = (int)m_scene.RegionInfo.RegionLocX - fileStartX;
  669. int offsetY = (int)m_scene.RegionInfo.RegionLocY - fileStartY;
  670. if (offsetX < 0 || offsetX >= fileWidth || offsetY < 0 || offsetY >= fileHeight)
  671. {
  672. MainConsole.Instance.OutputFormat(
  673. "ERROR: file width + minimum X tile and file height + minimum Y tile must incorporate the current region at ({0},{1}). File width {2} from {3} and file height {4} from {5} does not.",
  674. m_scene.RegionInfo.RegionLocX, m_scene.RegionInfo.RegionLocY, fileWidth, fileStartX, fileHeight, fileStartY);
  675. return;
  676. }
  677. // this region is included in the tile request
  678. foreach(KeyValuePair<string, ITerrainLoader> loader in m_loaders)
  679. {
  680. if (filename.EndsWith(loader.Key) && loader.Value.SupportsTileSave())
  681. {
  682. lock(m_scene)
  683. {
  684. loader.Value.SaveFile(m_channel, filename, offsetX, offsetY,
  685. fileWidth, fileHeight,
  686. (int)m_scene.RegionInfo.RegionSizeX,
  687. (int)m_scene.RegionInfo.RegionSizeY);
  688. MainConsole.Instance.OutputFormat(
  689. "Saved terrain from ({0},{1}) to ({2},{3}) from {4} to {5}",
  690. fileStartX, fileStartY, fileStartX + fileWidth - 1, fileStartY + fileHeight - 1,
  691. m_scene.RegionInfo.RegionName, filename);
  692. }
  693. return;
  694. }
  695. }
  696. MainConsole.Instance.OutputFormat(
  697. "ERROR: Could not save terrain from {0} to {1}. Valid file extensions are {2}",
  698. m_scene.RegionInfo.RegionName, filename, m_supportFileExtensionsForTileSave);
  699. }
  700. /// <summary>
  701. /// Called before processing of every simulation frame.
  702. /// This is used to check to see of any of the terrain is tainted and, if so, schedule
  703. /// updates for all the presences.
  704. /// This also checks to see if there are updates that need to be sent for each presence.
  705. /// This is where the logic is to send terrain updates to clients.
  706. /// </summary>
  707. private void EventManager_OnFrame()
  708. {
  709. TerrainData terrData = m_channel.GetTerrainData();
  710. bool shouldTaint = false;
  711. for(int x = 0; x < terrData.SizeX; x += Constants.TerrainPatchSize)
  712. {
  713. for(int y = 0; y < terrData.SizeY; y += Constants.TerrainPatchSize)
  714. {
  715. if (terrData.IsTaintedAt(x, y))
  716. {
  717. // Found a patch that was modified. Push this flag into the clients.
  718. SendToClients(terrData, x, y);
  719. shouldTaint = true;
  720. }
  721. }
  722. }
  723. // This event also causes changes to be sent to the clients
  724. CheckSendingPatchesToClients();
  725. // If things changes, generate some events
  726. if (shouldTaint)
  727. {
  728. m_scene.EventManager.TriggerTerrainTainted();
  729. m_tainted = true;
  730. }
  731. }
  732. /// <summary>
  733. /// Performs updates to the region periodically, synchronising physics and other heightmap aware sections
  734. /// Called infrequently (like every 5 seconds or so). Best used for storing terrain.
  735. /// </summary>
  736. private void EventManager_OnTerrainTick()
  737. {
  738. if (m_tainted)
  739. {
  740. m_tainted = false;
  741. m_scene.PhysicsScene.SetTerrain(m_channel.GetFloatsSerialised());
  742. m_scene.SaveTerrain();
  743. // Clients who look at the map will never see changes after they looked at the map, so i've commented this out.
  744. //m_scene.CreateTerrainTexture(true);
  745. }
  746. }
  747. /// <summary>
  748. /// Processes commandline input. Do not call directly.
  749. /// </summary>
  750. /// <param name="args">Commandline arguments</param>
  751. private void EventManager_OnPluginConsole(string[] args)
  752. {
  753. if (args[0] == "terrain")
  754. {
  755. if (args.Length == 1)
  756. {
  757. m_commander.ProcessConsoleCommand("help", new string[0]);
  758. return;
  759. }
  760. string[] tmpArgs = new string[args.Length - 2];
  761. int i;
  762. for(i = 2; i < args.Length; i++)
  763. tmpArgs[i - 2] = args[i];
  764. m_commander.ProcessConsoleCommand(args[1], tmpArgs);
  765. }
  766. }
  767. /// <summary>
  768. /// Installs terrain brush hook to IClientAPI
  769. /// </summary>
  770. /// <param name="client"></param>
  771. private void EventManager_OnNewClient(IClientAPI client)
  772. {
  773. client.OnModifyTerrain += client_OnModifyTerrain;
  774. client.OnBakeTerrain += client_OnBakeTerrain;
  775. client.OnLandUndo += client_OnLandUndo;
  776. client.OnUnackedTerrain += client_OnUnackedTerrain;
  777. }
  778. /// <summary>
  779. /// Installs terrain brush hook to IClientAPI
  780. /// </summary>
  781. /// <param name="client"></param>
  782. private void EventManager_OnClientClosed(UUID client, Scene scene)
  783. {
  784. ScenePresence presence = scene.GetScenePresence(client);
  785. if (presence != null)
  786. {
  787. presence.ControllingClient.OnModifyTerrain -= client_OnModifyTerrain;
  788. presence.ControllingClient.OnBakeTerrain -= client_OnBakeTerrain;
  789. presence.ControllingClient.OnLandUndo -= client_OnLandUndo;
  790. presence.ControllingClient.OnUnackedTerrain -= client_OnUnackedTerrain;
  791. }
  792. lock(m_perClientPatchUpdates)
  793. m_perClientPatchUpdates.Remove(client);
  794. }
  795. /// <summary>
  796. /// Scan over changes in the terrain and limit height changes. This enforces the
  797. /// non-estate owner limits on rate of terrain editting.
  798. /// Returns 'true' if any heights were limited.
  799. /// </summary>
  800. private bool EnforceEstateLimits()
  801. {
  802. TerrainData terrData = m_channel.GetTerrainData();
  803. bool wasLimited = false;
  804. for(int x = 0; x < terrData.SizeX; x += Constants.TerrainPatchSize)
  805. {
  806. for(int y = 0; y < terrData.SizeY; y += Constants.TerrainPatchSize)
  807. {
  808. if (terrData.IsTaintedAt(x, y, false /* clearOnTest */))
  809. {
  810. // If we should respect the estate settings then
  811. // fixup and height deltas that don't respect them.
  812. // Note that LimitChannelChanges() modifies the TerrainChannel with the limited height values.
  813. wasLimited |= LimitChannelChanges(terrData, x, y);
  814. }
  815. }
  816. }
  817. return wasLimited;
  818. }
  819. /// <summary>
  820. /// Checks to see height deltas in the tainted terrain patch at xStart ,yStart
  821. /// are all within the current estate limits
  822. /// <returns>true if changes were limited, false otherwise</returns>
  823. /// </summary>
  824. private bool LimitChannelChanges(TerrainData terrData, int xStart, int yStart)
  825. {
  826. bool changesLimited = false;
  827. float minDelta = (float)m_scene.RegionInfo.RegionSettings.TerrainLowerLimit;
  828. float maxDelta = (float)m_scene.RegionInfo.RegionSettings.TerrainRaiseLimit;
  829. // loop through the height map for this patch and compare it against
  830. // the revert map
  831. for(int x = xStart; x < xStart + Constants.TerrainPatchSize; x++)
  832. {
  833. for(int y = yStart; y < yStart + Constants.TerrainPatchSize; y++)
  834. {
  835. float requestedHeight = terrData[x, y];
  836. float bakedHeight = (float)m_revert[x, y];
  837. float requestedDelta = requestedHeight - bakedHeight;
  838. if (requestedDelta > maxDelta)
  839. {
  840. terrData[x, y] = bakedHeight + maxDelta;
  841. changesLimited = true;
  842. }
  843. else if (requestedDelta < minDelta)
  844. {
  845. terrData[x, y] = bakedHeight + minDelta; //as lower is a -ve delta
  846. changesLimited = true;
  847. }
  848. }
  849. }
  850. return changesLimited;
  851. }
  852. private void client_OnLandUndo(IClientAPI client)
  853. {
  854. lock(m_undo)
  855. {
  856. if (m_undo.Count > 0)
  857. {
  858. LandUndoState goback = m_undo.Pop();
  859. if (goback != null)
  860. goback.PlaybackState();
  861. }
  862. }
  863. }
  864. /// <summary>
  865. /// Sends a copy of the current terrain to the scenes clients
  866. /// </summary>
  867. /// <param name="serialised">A copy of the terrain as a 1D float array of size w*h</param>
  868. /// <param name="x">The patch corner to send</param>
  869. /// <param name="y">The patch corner to send</param>
  870. private void SendToClients(TerrainData terrData, int x, int y)
  871. {
  872. if (m_sendTerrainUpdatesByViewDistance)
  873. {
  874. // Add that this patch needs to be sent to the accounting for each client.
  875. lock(m_perClientPatchUpdates)
  876. {
  877. m_scene.ForEachScenePresence(presence =>
  878. {
  879. PatchUpdates thisClientUpdates;
  880. if (!m_perClientPatchUpdates.TryGetValue(presence.UUID, out thisClientUpdates))
  881. {
  882. // There is a ScenePresence without a send patch map. Create one.
  883. thisClientUpdates = new PatchUpdates(terrData, presence);
  884. m_perClientPatchUpdates.Add(presence.UUID, thisClientUpdates);
  885. }
  886. thisClientUpdates.SetByXY(x, y, true);
  887. }
  888. );
  889. }
  890. }
  891. else
  892. {
  893. // Legacy update sending where the update is sent out as soon as noticed
  894. // We know the actual terrain data that is passed is ignored so this passes a dummy heightmap.
  895. //float[] heightMap = terrData.GetFloatsSerialized();
  896. float[] heightMap = new float[10];
  897. m_scene.ForEachClient(
  898. delegate(IClientAPI controller)
  899. {
  900. controller.SendLayerData(x / Constants.TerrainPatchSize,
  901. y / Constants.TerrainPatchSize,
  902. heightMap);
  903. }
  904. );
  905. }
  906. }
  907. private class PatchesToSend : IComparable<PatchesToSend>
  908. {
  909. public int PatchX;
  910. public int PatchY;
  911. public float Dist;
  912. public PatchesToSend(int pX, int pY, float pDist)
  913. {
  914. PatchX = pX;
  915. PatchY = pY;
  916. Dist = pDist;
  917. }
  918. public int CompareTo(PatchesToSend other)
  919. {
  920. return Dist.CompareTo(other.Dist);
  921. }
  922. }
  923. // Called each frame time to see if there are any patches to send to any of the
  924. // ScenePresences.
  925. // We know this is only called if we are doing view distance patch sending so some
  926. // tests are not made.
  927. // Loop through all the per-client info and send any patches necessary.
  928. private void CheckSendingPatchesToClients()
  929. {
  930. lock(m_perClientPatchUpdates)
  931. {
  932. foreach(PatchUpdates pups in m_perClientPatchUpdates.Values)
  933. {
  934. if (pups.HasUpdates())
  935. {
  936. // There is something that could be sent to this client.
  937. List<PatchesToSend> toSend = GetModifiedPatchesInViewDistance(pups);
  938. if (toSend.Count > 0)
  939. {
  940. // m_log.DebugFormat("{0} CheckSendingPatchesToClient: sending {1} patches to {2} in region {3}",
  941. // LogHeader, toSend.Count, pups.Presence.Name, m_scene.RegionInfo.RegionName);
  942. // Sort the patches to send by the distance from the presence
  943. toSend.Sort();
  944. /* old way that sent individual patches
  945. foreach (PatchesToSend pts in toSend)
  946. {
  947. pups.Presence.ControllingClient.SendLayerData(pts.PatchX, pts.PatchY, null);
  948. // presence.ControllingClient.SendLayerData(xs.ToArray(), ys.ToArray(), null, TerrainPatch.LayerType.Land);
  949. }
  950. */
  951. // new way that sends all patches to the protocol so they can be sent in one block
  952. int[] xPieces = new int[toSend.Count];
  953. int[] yPieces = new int[toSend.Count];
  954. float[] patchPieces = new float[toSend.Count * 2];
  955. int pieceIndex = 0;
  956. foreach(PatchesToSend pts in toSend)
  957. {
  958. patchPieces[pieceIndex++] = pts.PatchX;
  959. patchPieces[pieceIndex++] = pts.PatchY;
  960. }
  961. pups.Presence.ControllingClient.SendLayerData(-toSend.Count, 0, patchPieces);
  962. }
  963. }
  964. }
  965. }
  966. }
  967. // Compute a list of modified patches that are within our view distance.
  968. private List<PatchesToSend> GetModifiedPatchesInViewDistance(PatchUpdates pups)
  969. {
  970. List<PatchesToSend> ret = new List<PatchesToSend>();
  971. ScenePresence presence = pups.Presence;
  972. if (presence == null)
  973. return ret;
  974. Vector3 presencePos = presence.AbsolutePosition;
  975. // Before this distance check, the whole region just showed up. Adding the distance
  976. // check causes different things to happen for the current and adjacent regions.
  977. // So, to keep legacy views, if the region is legacy sized, don't do distance check.
  978. bool isLegacySizedRegion = pups.Terrain.SizeX == Constants.RegionSize && pups.Terrain.SizeY == Constants.RegionSize;
  979. bool shouldCheckViewDistance = m_sendTerrainUpdatesByViewDistance && !isLegacySizedRegion;
  980. int startX = 0;
  981. int endX = (int)m_scene.RegionInfo.RegionSizeX / Constants.TerrainPatchSize;
  982. int startY = 0;
  983. int endY = (int)m_scene.RegionInfo.RegionSizeY / Constants.TerrainPatchSize;
  984. // The following only reduces the size of area scanned for updates. Only significant for very large varregions.
  985. if (shouldCheckViewDistance)
  986. {
  987. // Compute the area of patches within our draw distance
  988. startX = (((int)(presencePos.X - presence.DrawDistance)) / Constants.TerrainPatchSize) - 2;
  989. startX = Math.Max(startX, 0);
  990. startX = Math.Min(startX, (int)m_scene.RegionInfo.RegionSizeX / Constants.TerrainPatchSize);
  991. startY = (((int)(presencePos.Y - presence.DrawDistance)) / Constants.TerrainPatchSize) - 2;
  992. startY = Math.Max(startY, 0);
  993. startY = Math.Min(startY, (int)m_scene.RegionInfo.RegionSizeY / Constants.TerrainPatchSize);
  994. endX = (((int)(presencePos.X + presence.DrawDistance)) / Constants.TerrainPatchSize) + 2;
  995. endX = Math.Max(endX, 0);
  996. endX = Math.Min(endX, (int)m_scene.RegionInfo.RegionSizeX / Constants.TerrainPatchSize);
  997. endY = (((int)(presencePos.Y + presence.DrawDistance)) / Constants.TerrainPatchSize) + 2;
  998. endY = Math.Max(endY, 0);
  999. endY = Math.Min(endY, (int)m_scene.RegionInfo.RegionSizeY / Constants.TerrainPatchSize);
  1000. }
  1001. // m_log.DebugFormat("{0} GetModifiedPatchesInViewDistance. rName={1}, ddist={2}, apos={3}, cpos={4}, isChild={5}, start=<{6},{7}>, end=<{8},{9}>",
  1002. // LogHeader, m_scene.RegionInfo.RegionName,
  1003. // presence.DrawDistance, presencePos, presence.CameraPosition,
  1004. // isLegacySizeChildRegion,
  1005. // startX, startY, endX, endY);
  1006. for(int x = startX; x < endX; x++)
  1007. {
  1008. for(int y = startY; y < endY; y++)
  1009. {
  1010. //Need to make sure we don't send the same ones over and over
  1011. Vector3 patchPos = new Vector3(x * Constants.TerrainPatchSize, y * Constants.TerrainPatchSize, presencePos.Z);
  1012. if (pups.GetByPatch(x, y))
  1013. {
  1014. //Check which has less distance, camera or avatar position, both have to be done.
  1015. //Its not a radius, its a diameter and we add 50 so that it doesn't look like it cuts off
  1016. if (!shouldCheckViewDistance
  1017. || Util.DistanceLessThan(presencePos, patchPos, presence.DrawDistance + 50)
  1018. || Util.DistanceLessThan(presence.CameraPosition, patchPos, presence.DrawDistance + 50))
  1019. {
  1020. //They can see it, send it to them
  1021. pups.SetByPatch(x, y, false);
  1022. float dist = Vector3.DistanceSquared(presencePos, patchPos);
  1023. ret.Add(new PatchesToSend(x, y, dist));
  1024. }
  1025. }
  1026. }
  1027. }
  1028. return ret;
  1029. }
  1030. private void client_OnModifyTerrain(UUID user, float height, float seconds, byte size, byte action,
  1031. float north, float west, float south, float east, UUID agentId)
  1032. {
  1033. bool god = m_scene.Permissions.IsGod(user);
  1034. bool allowed = false;
  1035. if (north == south && east == west)
  1036. {
  1037. if (m_painteffects.ContainsKey((StandardTerrainEffects)action))
  1038. {
  1039. bool[,] allowMask = new bool[m_channel.Width, m_channel.Height];
  1040. allowMask.Initialize();
  1041. int n = size + 1;
  1042. if (n > 2)
  1043. n = 4;
  1044. int zx = (int)(west + 0.5);
  1045. int zy = (int)(north + 0.5);
  1046. int dx;
  1047. for(dx=-n; dx<=n; dx++)
  1048. {
  1049. int dy;
  1050. for(dy=-n; dy<=n; dy++)
  1051. {
  1052. int x = zx + dx;
  1053. int y = zy + dy;
  1054. if (x >= 0 && y >= 0 && x < m_channel.Width && y < m_channel.Height)
  1055. {
  1056. if (m_scene.Permissions.CanTerraformLand(agentId, new Vector3(x, y, 0)))
  1057. {
  1058. allowMask[x, y] = true;
  1059. allowed = true;
  1060. }
  1061. }
  1062. }
  1063. }
  1064. if (allowed)
  1065. {
  1066. StoreUndoState();
  1067. m_painteffects[(StandardTerrainEffects)action].PaintEffect(
  1068. m_channel, allowMask, west, south, height, size, seconds);
  1069. //revert changes outside estate limits
  1070. if (!god)
  1071. EnforceEstateLimits();
  1072. }
  1073. }
  1074. else
  1075. {
  1076. m_log.Debug("Unknown terrain brush type " + action);
  1077. }
  1078. }
  1079. else
  1080. {
  1081. if (m_floodeffects.ContainsKey((StandardTerrainEffects)action))
  1082. {
  1083. bool[,] fillArea = new bool[m_channel.Width, m_channel.Height];
  1084. fillArea.Initialize();
  1085. int x;
  1086. for(x = 0; x < m_channel.Width; x++)
  1087. {
  1088. int y;
  1089. for(y = 0; y < m_channel.Height; y++)
  1090. {
  1091. if (x < east && x > west)
  1092. {
  1093. if (y < north && y > south)
  1094. {
  1095. if (m_scene.Permissions.CanTerraformLand(agentId, new Vector3(x, y, 0)))
  1096. {
  1097. fillArea[x, y] = true;
  1098. allowed = true;
  1099. }
  1100. }
  1101. }
  1102. }
  1103. }
  1104. if (allowed)
  1105. {
  1106. StoreUndoState();
  1107. m_floodeffects[(StandardTerrainEffects)action].FloodEffect(m_channel, fillArea, size);
  1108. //revert changes outside estate limits
  1109. if (!god)
  1110. EnforceEstateLimits();
  1111. }
  1112. }
  1113. else
  1114. {
  1115. m_log.Debug("Unknown terrain flood type " + action);
  1116. }
  1117. }
  1118. }
  1119. private void client_OnBakeTerrain(IClientAPI remoteClient)
  1120. {
  1121. // Not a good permissions check (see client_OnModifyTerrain above), need to check the entire area.
  1122. // for now check a point in the centre of the region
  1123. if (m_scene.Permissions.CanIssueEstateCommand(remoteClient.AgentId, true))
  1124. {
  1125. InterfaceBakeTerrain(null); //bake terrain does not use the passed in parameter
  1126. }
  1127. }
  1128. protected void client_OnUnackedTerrain(IClientAPI client, int patchX, int patchY)
  1129. {
  1130. //m_log.Debug("Terrain packet unacked, resending patch: " + patchX + " , " + patchY);
  1131. // SendLayerData does not use the heightmap parameter. This kludge is so as to not change IClientAPI.
  1132. float[] heightMap = new float[10];
  1133. client.SendLayerData(patchX, patchY, heightMap);
  1134. }
  1135. private void StoreUndoState()
  1136. {
  1137. lock(m_undo)
  1138. {
  1139. if (m_undo.Count > 0)
  1140. {
  1141. LandUndoState last = m_undo.Peek();
  1142. if (last != null)
  1143. {
  1144. if (last.Compare(m_channel))
  1145. return;
  1146. }
  1147. }
  1148. LandUndoState nUndo = new LandUndoState(this, m_channel);
  1149. m_undo.Push(nUndo);
  1150. }
  1151. }
  1152. #region Console Commands
  1153. private void InterfaceLoadFile(Object[] args)
  1154. {
  1155. LoadFromFile((string)args[0]);
  1156. }
  1157. private void InterfaceLoadTileFile(Object[] args)
  1158. {
  1159. LoadFromFile((string)args[0],
  1160. (int)args[1],
  1161. (int)args[2],
  1162. (int)args[3],
  1163. (int)args[4]);
  1164. }
  1165. private void InterfaceSaveFile(Object[] args)
  1166. {
  1167. SaveToFile((string)args[0]);
  1168. }
  1169. private void InterfaceSaveTileFile(Object[] args)
  1170. {
  1171. SaveToFile((string)args[0],
  1172. (int)args[1],
  1173. (int)args[2],
  1174. (int)args[3],
  1175. (int)args[4]);
  1176. }
  1177. private void InterfaceBakeTerrain(Object[] args)
  1178. {
  1179. UpdateRevertMap();
  1180. }
  1181. private void InterfaceRevertTerrain(Object[] args)
  1182. {
  1183. int x, y;
  1184. for(x = 0; x < m_channel.Width; x++)
  1185. for(y = 0; y < m_channel.Height; y++)
  1186. m_channel[x, y] = m_revert[x, y];
  1187. }
  1188. private void InterfaceFlipTerrain(Object[] args)
  1189. {
  1190. String direction = (String)args[0];
  1191. if (direction.ToLower().StartsWith("y"))
  1192. {
  1193. for(int x = 0; x < m_channel.Width; x++)
  1194. {
  1195. for(int y = 0; y < m_channel.Height / 2; y++)
  1196. {
  1197. double height = m_channel[x, y];
  1198. double flippedHeight = m_channel[x, (int)m_channel.Height - 1 - y];
  1199. m_channel[x, y] = flippedHeight;
  1200. m_channel[x, (int)m_channel.Height - 1 - y] = height;
  1201. }
  1202. }
  1203. }
  1204. else if (direction.ToLower().StartsWith("x"))
  1205. {
  1206. for(int y = 0; y < m_channel.Height; y++)
  1207. {
  1208. for(int x = 0; x < m_channel.Width / 2; x++)
  1209. {
  1210. double height = m_channel[x, y];
  1211. double flippedHeight = m_channel[(int)m_channel.Width - 1 - x, y];
  1212. m_channel[x, y] = flippedHeight;
  1213. m_channel[(int)m_channel.Width - 1 - x, y] = height;
  1214. }
  1215. }
  1216. }
  1217. else
  1218. {
  1219. MainConsole.Instance.OutputFormat("ERROR: Unrecognised direction {0} - need x or y", direction);
  1220. }
  1221. }
  1222. private void InterfaceRescaleTerrain(Object[] args)
  1223. {
  1224. double desiredMin = (double)args[0];
  1225. double desiredMax = (double)args[1];
  1226. // determine desired scaling factor
  1227. double desiredRange = desiredMax - desiredMin;
  1228. //m_log.InfoFormat("Desired {0}, {1} = {2}", new Object[] { desiredMin, desiredMax, desiredRange });
  1229. if (desiredRange == 0d)
  1230. {
  1231. // delta is zero so flatten at requested height
  1232. InterfaceFillTerrain(new Object[] { args[1] });
  1233. }
  1234. else
  1235. {
  1236. //work out current heightmap range
  1237. double currMin = double.MaxValue;
  1238. double currMax = double.MinValue;
  1239. int width = m_channel.Width;
  1240. int height = m_channel.Height;
  1241. for(int x = 0; x < width; x++)
  1242. {
  1243. for(int y = 0; y < height; y++)
  1244. {
  1245. double currHeight = m_channel[x, y];
  1246. if (currHeight < currMin)
  1247. {
  1248. currMin = currHeight;
  1249. }
  1250. else if (currHeight > currMax)
  1251. {
  1252. currMax = currHeight;
  1253. }
  1254. }
  1255. }
  1256. double currRange = currMax - currMin;
  1257. double scale = desiredRange / currRange;
  1258. //m_log.InfoFormat("Current {0}, {1} = {2}", new Object[] { currMin, currMax, currRange });
  1259. //m_log.InfoFormat("Scale = {0}", scale);
  1260. // scale the heightmap accordingly
  1261. for(int x = 0; x < width; x++)
  1262. {
  1263. for(int y = 0; y < height; y++)
  1264. {
  1265. double currHeight = m_channel[x, y] - currMin;
  1266. m_channel[x, y] = desiredMin + (currHeight * scale);
  1267. }
  1268. }
  1269. }
  1270. }
  1271. private void InterfaceElevateTerrain(Object[] args)
  1272. {
  1273. int x, y;
  1274. for(x = 0; x < m_channel.Width; x++)
  1275. for(y = 0; y < m_channel.Height; y++)
  1276. m_channel[x, y] += (double)args[0];
  1277. }
  1278. private void InterfaceMultiplyTerrain(Object[] args)
  1279. {
  1280. int x, y;
  1281. for(x = 0; x < m_channel.Width; x++)
  1282. for(y = 0; y < m_channel.Height; y++)
  1283. m_channel[x, y] *= (double)args[0];
  1284. }
  1285. private void InterfaceLowerTerrain(Object[] args)
  1286. {
  1287. int x, y;
  1288. for(x = 0; x < m_channel.Width; x++)
  1289. for(y = 0; y < m_channel.Height; y++)
  1290. m_channel[x, y] -= (double)args[0];
  1291. }
  1292. public void InterfaceFillTerrain(Object[] args)
  1293. {
  1294. int x, y;
  1295. for(x = 0; x < m_channel.Width; x++)
  1296. for(y = 0; y < m_channel.Height; y++)
  1297. m_channel[x, y] = (double)args[0];
  1298. }
  1299. private void InterfaceMinTerrain(Object[] args)
  1300. {
  1301. int x, y;
  1302. for(x = 0; x < m_channel.Width; x++)
  1303. {
  1304. for(y = 0; y < m_channel.Height; y++)
  1305. {
  1306. m_channel[x, y] = Math.Max((double)args[0], m_channel[x, y]);
  1307. }
  1308. }
  1309. }
  1310. private void InterfaceMaxTerrain(Object[] args)
  1311. {
  1312. int x, y;
  1313. for(x = 0; x < m_channel.Width; x++)
  1314. {
  1315. for(y = 0; y < m_channel.Height; y++)
  1316. {
  1317. m_channel[x, y] = Math.Min((double)args[0], m_channel[x, y]);
  1318. }
  1319. }
  1320. }
  1321. private void InterfaceShow(Object[] args)
  1322. {
  1323. Vector2 point;
  1324. if (!ConsoleUtil.TryParseConsole2DVector((string)args[0], null, out point))
  1325. {
  1326. Console.WriteLine("ERROR: {0} is not a valid vector", args[0]);
  1327. return;
  1328. }
  1329. double height = m_channel[(int)point.X, (int)point.Y];
  1330. Console.WriteLine("Terrain height at {0} is {1}", point, height);
  1331. }
  1332. private void InterfaceShowDebugStats(Object[] args)
  1333. {
  1334. double max = Double.MinValue;
  1335. double min = double.MaxValue;
  1336. double sum = 0;
  1337. int x;
  1338. for(x = 0; x < m_channel.Width; x++)
  1339. {
  1340. int y;
  1341. for(y = 0; y < m_channel.Height; y++)
  1342. {
  1343. sum += m_channel[x, y];
  1344. if (max < m_channel[x, y])
  1345. max = m_channel[x, y];
  1346. if (min > m_channel[x, y])
  1347. min = m_channel[x, y];
  1348. }
  1349. }
  1350. double avg = sum / (m_channel.Height * m_channel.Width);
  1351. MainConsole.Instance.OutputFormat("Channel {0}x{1}", m_channel.Width, m_channel.Height);
  1352. MainConsole.Instance.OutputFormat("max/min/avg/sum: {0}/{1}/{2}/{3}", max, min, avg, sum);
  1353. }
  1354. private void InterfaceEnableExperimentalBrushes(Object[] args)
  1355. {
  1356. if ((bool)args[0])
  1357. {
  1358. m_painteffects[StandardTerrainEffects.Revert] = new WeatherSphere();
  1359. m_painteffects[StandardTerrainEffects.Flatten] = new OlsenSphere();
  1360. m_painteffects[StandardTerrainEffects.Smooth] = new ErodeSphere();
  1361. }
  1362. else
  1363. {
  1364. InstallDefaultEffects();
  1365. }
  1366. }
  1367. private void InterfaceRunPluginEffect(Object[] args)
  1368. {
  1369. string firstArg = (string)args[0];
  1370. if (firstArg == "list")
  1371. {
  1372. MainConsole.Instance.Output("List of loaded plugins");
  1373. foreach(KeyValuePair<string, ITerrainEffect> kvp in m_plugineffects)
  1374. {
  1375. MainConsole.Instance.Output(kvp.Key);
  1376. }
  1377. return;
  1378. }
  1379. if (firstArg == "reload")
  1380. {
  1381. LoadPlugins();
  1382. return;
  1383. }
  1384. if (m_plugineffects.ContainsKey(firstArg))
  1385. {
  1386. m_plugineffects[firstArg].RunEffect(m_channel);
  1387. }
  1388. else
  1389. {
  1390. MainConsole.Instance.Output("WARNING: No such plugin effect {0} loaded.", firstArg);
  1391. }
  1392. }
  1393. private void InstallInterfaces()
  1394. {
  1395. Command loadFromFileCommand =
  1396. new Command("load", CommandIntentions.COMMAND_HAZARDOUS, InterfaceLoadFile, "Loads a terrain from a specified file.");
  1397. loadFromFileCommand.AddArgument("filename",
  1398. "The file you wish to load from, the file extension determines the loader to be used. Supported extensions include: " +
  1399. m_supportedFileExtensions, "String");
  1400. Command saveToFileCommand =
  1401. new Command("save", CommandIntentions.COMMAND_NON_HAZARDOUS, InterfaceSaveFile, "Saves the current heightmap to a specified file.");
  1402. saveToFileCommand.AddArgument("filename",
  1403. "The destination filename for your heightmap, the file extension determines the format to save in. Supported extensions include: " +
  1404. m_supportedFileExtensions, "String");
  1405. Command loadFromTileCommand =
  1406. new Command("load-tile", CommandIntentions.COMMAND_HAZARDOUS, InterfaceLoadTileFile, "Loads a terrain from a section of a larger file.");
  1407. loadFromTileCommand.AddArgument("filename",
  1408. "The file you wish to load from, the file extension determines the loader to be used. Supported extensions include: " +
  1409. m_supportedFileExtensions, "String");
  1410. loadFromTileCommand.AddArgument("file width", "The width of the file in tiles", "Integer");
  1411. loadFromTileCommand.AddArgument("file height", "The height of the file in tiles", "Integer");
  1412. loadFromTileCommand.AddArgument("minimum X tile", "The X region coordinate of the first section on the file",
  1413. "Integer");
  1414. loadFromTileCommand.AddArgument("minimum Y tile", "The Y region coordinate of the first section on the file",
  1415. "Integer");
  1416. Command saveToTileCommand =
  1417. new Command("save-tile", CommandIntentions.COMMAND_HAZARDOUS, InterfaceSaveTileFile, "Saves the current heightmap to the larger file.");
  1418. saveToTileCommand.AddArgument("filename",
  1419. "The file you wish to save to, the file extension determines the loader to be used. Supported extensions include: " +
  1420. m_supportFileExtensionsForTileSave, "String");
  1421. saveToTileCommand.AddArgument("file width", "The width of the file in tiles", "Integer");
  1422. saveToTileCommand.AddArgument("file height", "The height of the file in tiles", "Integer");
  1423. saveToTileCommand.AddArgument("minimum X tile", "The X region coordinate of the first section on the file",
  1424. "Integer");
  1425. saveToTileCommand.AddArgument("minimum Y tile", "The Y region coordinate of the first tile on the file\n"
  1426. + "= Example =\n"
  1427. + "To save a PNG file for a set of map tiles 2 regions wide and 3 regions high from map co-ordinate (9910,10234)\n"
  1428. + " # terrain save-tile ST06.png 2 3 9910 10234\n",
  1429. "Integer");
  1430. // Terrain adjustments
  1431. Command fillRegionCommand =
  1432. new Command("fill", CommandIntentions.COMMAND_HAZARDOUS, InterfaceFillTerrain, "Fills the current heightmap with a specified value.");
  1433. fillRegionCommand.AddArgument("value", "The numeric value of the height you wish to set your region to.",
  1434. "Double");
  1435. Command elevateCommand =
  1436. new Command("elevate", CommandIntentions.COMMAND_HAZARDOUS, InterfaceElevateTerrain, "Raises the current heightmap by the specified amount.");
  1437. elevateCommand.AddArgument("amount", "The amount of height to add to the terrain in meters.", "Double");
  1438. Command lowerCommand =
  1439. new Command("lower", CommandIntentions.COMMAND_HAZARDOUS, InterfaceLowerTerrain, "Lowers the current heightmap by the specified amount.");
  1440. lowerCommand.AddArgument("amount", "The amount of height to remove from the terrain in meters.", "Double");
  1441. Command multiplyCommand =
  1442. new Command("multiply", CommandIntentions.COMMAND_HAZARDOUS, InterfaceMultiplyTerrain, "Multiplies the heightmap by the value specified.");
  1443. multiplyCommand.AddArgument("value", "The value to multiply the heightmap by.", "Double");
  1444. Command bakeRegionCommand =
  1445. new Command("bake", CommandIntentions.COMMAND_HAZARDOUS, InterfaceBakeTerrain, "Saves the current terrain into the regions revert map.");
  1446. Command revertRegionCommand =
  1447. new Command("revert", CommandIntentions.COMMAND_HAZARDOUS, InterfaceRevertTerrain, "Loads the revert map terrain into the regions heightmap.");
  1448. Command flipCommand =
  1449. new Command("flip", CommandIntentions.COMMAND_HAZARDOUS, InterfaceFlipTerrain, "Flips the current terrain about the X or Y axis");
  1450. flipCommand.AddArgument("direction", "[x|y] the direction to flip the terrain in", "String");
  1451. Command rescaleCommand =
  1452. new Command("rescale", CommandIntentions.COMMAND_HAZARDOUS, InterfaceRescaleTerrain, "Rescales the current terrain to fit between the given min and max heights");
  1453. rescaleCommand.AddArgument("min", "min terrain height after rescaling", "Double");
  1454. rescaleCommand.AddArgument("max", "max terrain height after rescaling", "Double");
  1455. Command minCommand = new Command("min", CommandIntentions.COMMAND_HAZARDOUS, InterfaceMinTerrain, "Sets the minimum terrain height to the specified value.");
  1456. minCommand.AddArgument("min", "terrain height to use as minimum", "Double");
  1457. Command maxCommand = new Command("max", CommandIntentions.COMMAND_HAZARDOUS, InterfaceMaxTerrain, "Sets the maximum terrain height to the specified value.");
  1458. maxCommand.AddArgument("min", "terrain height to use as maximum", "Double");
  1459. // Debug
  1460. Command showDebugStatsCommand =
  1461. new Command("stats", CommandIntentions.COMMAND_STATISTICAL, InterfaceShowDebugStats,
  1462. "Shows some information about the regions heightmap for debugging purposes.");
  1463. Command showCommand =
  1464. new Command("show", CommandIntentions.COMMAND_NON_HAZARDOUS, InterfaceShow,
  1465. "Shows terrain height at a given co-ordinate.");
  1466. showCommand.AddArgument("point", "point in <x>,<y> format with no spaces (e.g. 45,45)", "String");
  1467. Command experimentalBrushesCommand =
  1468. new Command("newbrushes", CommandIntentions.COMMAND_HAZARDOUS, InterfaceEnableExperimentalBrushes,
  1469. "Enables experimental brushes which replace the standard terrain brushes. WARNING: This is a debug setting and may be removed at any time.");
  1470. experimentalBrushesCommand.AddArgument("Enabled?", "true / false - Enable new brushes", "Boolean");
  1471. // Plugins
  1472. Command pluginRunCommand =
  1473. new Command("effect", CommandIntentions.COMMAND_HAZARDOUS, InterfaceRunPluginEffect, "Runs a specified plugin effect");
  1474. pluginRunCommand.AddArgument("name", "The plugin effect you wish to run, or 'list' to see all plugins", "String");
  1475. m_commander.RegisterCommand("load", loadFromFileCommand);
  1476. m_commander.RegisterCommand("load-tile", loadFromTileCommand);
  1477. m_commander.RegisterCommand("save", saveToFileCommand);
  1478. m_commander.RegisterCommand("save-tile", saveToTileCommand);
  1479. m_commander.RegisterCommand("fill", fillRegionCommand);
  1480. m_commander.RegisterCommand("elevate", elevateCommand);
  1481. m_commander.RegisterCommand("lower", lowerCommand);
  1482. m_commander.RegisterCommand("multiply", multiplyCommand);
  1483. m_commander.RegisterCommand("bake", bakeRegionCommand);
  1484. m_commander.RegisterCommand("revert", revertRegionCommand);
  1485. m_commander.RegisterCommand("newbrushes", experimentalBrushesCommand);
  1486. m_commander.RegisterCommand("show", showCommand);
  1487. m_commander.RegisterCommand("stats", showDebugStatsCommand);
  1488. m_commander.RegisterCommand("effect", pluginRunCommand);
  1489. m_commander.RegisterCommand("flip", flipCommand);
  1490. m_commander.RegisterCommand("rescale", rescaleCommand);
  1491. m_commander.RegisterCommand("min", minCommand);
  1492. m_commander.RegisterCommand("max", maxCommand);
  1493. // Add this to our scene so scripts can call these functions
  1494. m_scene.RegisterModuleCommander(m_commander);
  1495. // Add Modify command to Scene, since Command object requires fixed-length arglists
  1496. m_scene.AddCommand("Terrain", this, "terrain modify",
  1497. "terrain modify <operation> <value> [<area>] [<taper>]",
  1498. "Modifies the terrain as instructed." +
  1499. "\nEach operation can be limited to an area of effect:" +
  1500. "\n * -ell=x,y,rx[,ry] constrains the operation to an ellipse centred at x,y" +
  1501. "\n * -rec=x,y,dx[,dy] constrains the operation to a rectangle based at x,y" +
  1502. "\nEach operation can have its effect tapered based on distance from centre:" +
  1503. "\n * elliptical operations taper as cones" +
  1504. "\n * rectangular operations taper as pyramids"
  1505. ,
  1506. ModifyCommand);
  1507. }
  1508. public void ModifyCommand(string module, string[] cmd)
  1509. {
  1510. string result;
  1511. Scene scene = SceneManager.Instance.CurrentScene;
  1512. if ((scene != null) && (scene != m_scene))
  1513. {
  1514. result = String.Empty;
  1515. }
  1516. else if (cmd.Length > 2)
  1517. {
  1518. string operationType = cmd[2];
  1519. ITerrainModifier operation;
  1520. if (!m_modifyOperations.TryGetValue(operationType, out operation))
  1521. {
  1522. result = String.Format("Terrain Modify \"{0}\" not found.", operationType);
  1523. }
  1524. else if ((cmd.Length > 3) && (cmd[3] == "usage"))
  1525. {
  1526. result = "Usage: " + operation.GetUsage();
  1527. }
  1528. else
  1529. {
  1530. result = operation.ModifyTerrain(m_channel, cmd);
  1531. }
  1532. if (result == String.Empty)
  1533. {
  1534. result = "Modified terrain";
  1535. m_log.DebugFormat("Performed terrain operation {0}", operationType);
  1536. }
  1537. }
  1538. else
  1539. {
  1540. result = "Usage: <operation-name> <arg1> <arg2>...";
  1541. }
  1542. if (result != String.Empty)
  1543. {
  1544. MainConsole.Instance.Output(result);
  1545. }
  1546. }
  1547. #endregion
  1548. }
  1549. }