TerrainModule.cs 78 KB

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