TerrainModule.cs 82 KB

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