TerrainModule.cs 81 KB

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