TerrainModule.cs 81 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940
  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();
  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.Output(
  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. null,
  708. m_scene.RegionInfo.RegionLocX, m_scene.RegionInfo.RegionLocY, fileWidth, fileStartX, fileHeight, fileStartY);
  709. return;
  710. }
  711. // this region is included in the tile request
  712. foreach(KeyValuePair<string, ITerrainLoader> loader in m_loaders)
  713. {
  714. if (filename.EndsWith(loader.Key) && loader.Value.SupportsTileSave())
  715. {
  716. lock(m_scene)
  717. {
  718. loader.Value.SaveFile(m_channel, filename, offsetX, offsetY,
  719. fileWidth, fileHeight,
  720. (int)m_scene.RegionInfo.RegionSizeX,
  721. (int)m_scene.RegionInfo.RegionSizeY);
  722. MainConsole.Instance.Output(
  723. "Saved terrain from ({0},{1}) to ({2},{3}) from {4} to {5}",
  724. null,
  725. fileStartX, fileStartY, fileStartX + fileWidth - 1, fileStartY + fileHeight - 1,
  726. m_scene.RegionInfo.RegionName, filename);
  727. }
  728. return;
  729. }
  730. }
  731. MainConsole.Instance.Output(
  732. "ERROR: Could not save terrain from {0} to {1}. Valid file extensions are {2}",
  733. null,
  734. m_scene.RegionInfo.RegionName, filename, m_supportFileExtensionsForTileSave);
  735. }
  736. /// <summary>
  737. /// This is used to check to see of any of the terrain is tainted and, if so, schedule
  738. /// updates for all the presences.
  739. /// This also checks to see if there are updates that need to be sent for each presence.
  740. /// This is where the logic is to send terrain updates to clients.
  741. /// </summary>
  742. /// doing it async, since currently this is 2 heavy for heartbeat
  743. private void EventManager_TerrainCheckUpdates()
  744. {
  745. Util.FireAndForget(
  746. EventManager_TerrainCheckUpdatesAsync);
  747. }
  748. object TerrainCheckUpdatesLock = new object();
  749. private void EventManager_TerrainCheckUpdatesAsync(object o)
  750. {
  751. // dont overlap execution
  752. if(Monitor.TryEnter(TerrainCheckUpdatesLock))
  753. {
  754. // this needs fixing
  755. TerrainData terrData = m_channel.GetTerrainData();
  756. bool shouldTaint = false;
  757. for (int x = 0; x < terrData.SizeX; x += Constants.TerrainPatchSize)
  758. {
  759. for (int y = 0; y < terrData.SizeY; y += Constants.TerrainPatchSize)
  760. {
  761. if (terrData.IsTaintedAt(x, y,true))
  762. {
  763. // Found a patch that was modified. Push this flag into the clients.
  764. SendToClients(terrData, x, y);
  765. shouldTaint = true;
  766. }
  767. }
  768. }
  769. // This event also causes changes to be sent to the clients
  770. CheckSendingPatchesToClients();
  771. // If things changes, generate some events
  772. if (shouldTaint)
  773. {
  774. m_scene.EventManager.TriggerTerrainTainted();
  775. m_tainted = true;
  776. }
  777. Monitor.Exit(TerrainCheckUpdatesLock);
  778. }
  779. }
  780. /// <summary>
  781. /// Performs updates to the region periodically, synchronising physics and other heightmap aware sections
  782. /// Called infrequently (like every 5 seconds or so). Best used for storing terrain.
  783. /// </summary>
  784. private void EventManager_OnTerrainTick()
  785. {
  786. if (m_tainted)
  787. {
  788. m_tainted = false;
  789. m_scene.PhysicsScene.SetTerrain(m_channel.GetFloatsSerialised());
  790. m_scene.SaveTerrain();
  791. // Clients who look at the map will never see changes after they looked at the map, so i've commented this out.
  792. //m_scene.CreateTerrainTexture(true);
  793. }
  794. }
  795. /// <summary>
  796. /// Processes commandline input. Do not call directly.
  797. /// </summary>
  798. /// <param name="args">Commandline arguments</param>
  799. private void EventManager_OnPluginConsole(string[] args)
  800. {
  801. if (args[0] == "terrain")
  802. {
  803. if (args.Length == 1)
  804. {
  805. m_commander.ProcessConsoleCommand("help", new string[0]);
  806. return;
  807. }
  808. string[] tmpArgs = new string[args.Length - 2];
  809. int i;
  810. for(i = 2; i < args.Length; i++)
  811. tmpArgs[i - 2] = args[i];
  812. m_commander.ProcessConsoleCommand(args[1], tmpArgs);
  813. }
  814. }
  815. /// <summary>
  816. /// Installs terrain brush hook to IClientAPI
  817. /// </summary>
  818. /// <param name="client"></param>
  819. private void EventManager_OnNewClient(IClientAPI client)
  820. {
  821. client.OnModifyTerrain += client_OnModifyTerrain;
  822. client.OnBakeTerrain += client_OnBakeTerrain;
  823. client.OnLandUndo += client_OnLandUndo;
  824. client.OnUnackedTerrain += client_OnUnackedTerrain;
  825. }
  826. /// <summary>
  827. /// Installs terrain brush hook to IClientAPI
  828. /// </summary>
  829. /// <param name="client"></param>
  830. private void EventManager_OnClientClosed(UUID client, Scene scene)
  831. {
  832. ScenePresence presence = scene.GetScenePresence(client);
  833. if (presence != null)
  834. {
  835. presence.ControllingClient.OnModifyTerrain -= client_OnModifyTerrain;
  836. presence.ControllingClient.OnBakeTerrain -= client_OnBakeTerrain;
  837. presence.ControllingClient.OnLandUndo -= client_OnLandUndo;
  838. presence.ControllingClient.OnUnackedTerrain -= client_OnUnackedTerrain;
  839. }
  840. lock (m_perClientPatchUpdates)
  841. m_perClientPatchUpdates.Remove(client);
  842. }
  843. /// <summary>
  844. /// Scan over changes in the terrain and limit height changes. This enforces the
  845. /// non-estate owner limits on rate of terrain editting.
  846. /// Returns 'true' if any heights were limited.
  847. /// </summary>
  848. private bool EnforceEstateLimits()
  849. {
  850. TerrainData terrData = m_channel.GetTerrainData();
  851. bool wasLimited = false;
  852. for (int x = 0; x < terrData.SizeX; x += Constants.TerrainPatchSize)
  853. {
  854. for (int y = 0; y < terrData.SizeY; y += Constants.TerrainPatchSize)
  855. {
  856. if (terrData.IsTaintedAt(x, y, false /* clearOnTest */))
  857. {
  858. // If we should respect the estate settings then
  859. // fixup and height deltas that don't respect them.
  860. // Note that LimitChannelChanges() modifies the TerrainChannel with the limited height values.
  861. wasLimited |= LimitChannelChanges(terrData, x, y);
  862. }
  863. }
  864. }
  865. return wasLimited;
  866. }
  867. private bool EnforceEstateLimits(int startX, int startY, int endX, int endY)
  868. {
  869. TerrainData terrData = m_channel.GetTerrainData();
  870. bool wasLimited = false;
  871. for (int x = startX; x <= endX; x += Constants.TerrainPatchSize)
  872. {
  873. for (int y = startX; y <= endY; y += Constants.TerrainPatchSize)
  874. {
  875. if (terrData.IsTaintedAt(x, y, false /* clearOnTest */))
  876. {
  877. // If we should respect the estate settings then
  878. // fixup and height deltas that don't respect them.
  879. // Note that LimitChannelChanges() modifies the TerrainChannel with the limited height values.
  880. wasLimited |= LimitChannelChanges(terrData, x, y);
  881. }
  882. }
  883. }
  884. return wasLimited;
  885. }
  886. /// <summary>
  887. /// Checks to see height deltas in the tainted terrain patch at xStart ,yStart
  888. /// are all within the current estate limits
  889. /// <returns>true if changes were limited, false otherwise</returns>
  890. /// </summary>
  891. private bool LimitChannelChanges(TerrainData terrData, int xStart, int yStart)
  892. {
  893. bool changesLimited = false;
  894. float minDelta = (float)m_scene.RegionInfo.RegionSettings.TerrainLowerLimit;
  895. float maxDelta = (float)m_scene.RegionInfo.RegionSettings.TerrainRaiseLimit;
  896. // loop through the height map for this patch and compare it against
  897. // the baked map
  898. for (int x = xStart; x < xStart + Constants.TerrainPatchSize; x++)
  899. {
  900. for(int y = yStart; y < yStart + Constants.TerrainPatchSize; y++)
  901. {
  902. float requestedHeight = terrData[x, y];
  903. float bakedHeight = (float)m_baked[x, y];
  904. float requestedDelta = requestedHeight - bakedHeight;
  905. if (requestedDelta > maxDelta)
  906. {
  907. terrData[x, y] = bakedHeight + maxDelta;
  908. changesLimited = true;
  909. }
  910. else if (requestedDelta < minDelta)
  911. {
  912. terrData[x, y] = bakedHeight + minDelta; //as lower is a -ve delta
  913. changesLimited = true;
  914. }
  915. }
  916. }
  917. return changesLimited;
  918. }
  919. private void client_OnLandUndo(IClientAPI client)
  920. {
  921. }
  922. /// <summary>
  923. /// Sends a copy of the current terrain to the scenes clients
  924. /// </summary>
  925. /// <param name="serialised">A copy of the terrain as a 1D float array of size w*h</param>
  926. /// <param name="x">The patch corner to send</param>
  927. /// <param name="y">The patch corner to send</param>
  928. private void SendToClients(TerrainData terrData, int x, int y)
  929. {
  930. if (m_sendTerrainUpdatesByViewDistance)
  931. {
  932. // Add that this patch needs to be sent to the accounting for each client.
  933. lock (m_perClientPatchUpdates)
  934. {
  935. m_scene.ForEachScenePresence(presence =>
  936. {
  937. PatchUpdates thisClientUpdates;
  938. if (!m_perClientPatchUpdates.TryGetValue(presence.UUID, out thisClientUpdates))
  939. {
  940. // There is a ScenePresence without a send patch map. Create one.
  941. thisClientUpdates = new PatchUpdates(terrData, presence);
  942. m_perClientPatchUpdates.Add(presence.UUID, thisClientUpdates);
  943. }
  944. thisClientUpdates.SetByXY(x, y, true);
  945. }
  946. );
  947. }
  948. }
  949. else
  950. {
  951. // Legacy update sending where the update is sent out as soon as noticed
  952. // We know the actual terrain data that is passed is ignored so this passes a dummy heightmap.
  953. //float[] heightMap = terrData.GetFloatsSerialized();
  954. int[] map = new int[]{ x / Constants.TerrainPatchSize, y / Constants.TerrainPatchSize };
  955. m_scene.ForEachClient(
  956. delegate (IClientAPI controller)
  957. {
  958. controller.SendLayerData(map);
  959. }
  960. );
  961. }
  962. }
  963. private class PatchesToSend : IComparable<PatchesToSend>
  964. {
  965. public int PatchX;
  966. public int PatchY;
  967. public float Dist;
  968. public PatchesToSend(int pX, int pY, float pDist)
  969. {
  970. PatchX = pX;
  971. PatchY = pY;
  972. Dist = pDist;
  973. }
  974. public int CompareTo(PatchesToSend other)
  975. {
  976. return Dist.CompareTo(other.Dist);
  977. }
  978. }
  979. // Called each frame time to see if there are any patches to send to any of the
  980. // ScenePresences.
  981. // Loop through all the per-client info and send any patches necessary.
  982. private void CheckSendingPatchesToClients()
  983. {
  984. lock (m_perClientPatchUpdates)
  985. {
  986. foreach (PatchUpdates pups in m_perClientPatchUpdates.Values)
  987. {
  988. if(pups.Presence.IsDeleted)
  989. continue;
  990. // limit rate acording to udp land queue state
  991. if (!pups.Presence.ControllingClient.CanSendLayerData())
  992. continue;
  993. if (pups.HasUpdates())
  994. {
  995. if (m_sendTerrainUpdatesByViewDistance)
  996. {
  997. // There is something that could be sent to this client.
  998. List<PatchesToSend> toSend = GetModifiedPatchesInViewDistance(pups);
  999. if (toSend.Count > 0)
  1000. {
  1001. // m_log.DebugFormat("{0} CheckSendingPatchesToClient: sending {1} patches to {2} in region {3}",
  1002. // LogHeader, toSend.Count, pups.Presence.Name, m_scene.RegionInfo.RegionName);
  1003. // Sort the patches to send by the distance from the presence
  1004. toSend.Sort();
  1005. /*
  1006. foreach (PatchesToSend pts in toSend)
  1007. {
  1008. pups.Presence.ControllingClient.SendLayerData(pts.PatchX, pts.PatchY, null);
  1009. // presence.ControllingClient.SendLayerData(xs.ToArray(), ys.ToArray(), null, TerrainPatch.LayerType.Land);
  1010. }
  1011. */
  1012. int[] patchPieces = new int[toSend.Count * 2];
  1013. int pieceIndex = 0;
  1014. foreach (PatchesToSend pts in toSend)
  1015. {
  1016. patchPieces[pieceIndex++] = pts.PatchX;
  1017. patchPieces[pieceIndex++] = pts.PatchY;
  1018. }
  1019. pups.Presence.ControllingClient.SendLayerData(patchPieces);
  1020. }
  1021. if (pups.sendAll && toSend.Count < 1024)
  1022. SendAllModifiedPatchs(pups);
  1023. }
  1024. else
  1025. SendAllModifiedPatchs(pups);
  1026. }
  1027. }
  1028. }
  1029. }
  1030. private void SendAllModifiedPatchs(PatchUpdates pups)
  1031. {
  1032. if (!pups.sendAll) // sanity
  1033. return;
  1034. int limitX = (int)m_scene.RegionInfo.RegionSizeX / Constants.TerrainPatchSize;
  1035. int limitY = (int)m_scene.RegionInfo.RegionSizeY / Constants.TerrainPatchSize;
  1036. if (pups.sendAllcurrentX >= limitX && pups.sendAllcurrentY >= limitY)
  1037. {
  1038. pups.sendAll = false;
  1039. pups.sendAllcurrentX = 0;
  1040. pups.sendAllcurrentY = 0;
  1041. return;
  1042. }
  1043. int npatchs = 0;
  1044. List<PatchesToSend> patchs = new List<PatchesToSend>();
  1045. int x = pups.sendAllcurrentX;
  1046. int y = pups.sendAllcurrentY;
  1047. // send it in the order viewer draws it
  1048. // even if not best for memory scan
  1049. for (; y < limitY; y++)
  1050. {
  1051. for (; x < limitX; x++)
  1052. {
  1053. if (pups.GetByPatch(x, y))
  1054. {
  1055. pups.SetByPatch(x, y, false);
  1056. patchs.Add(new PatchesToSend(x, y, 0));
  1057. if (++npatchs >= 128)
  1058. {
  1059. x++;
  1060. break;
  1061. }
  1062. }
  1063. }
  1064. if (npatchs >= 128)
  1065. break;
  1066. x = 0;
  1067. }
  1068. if (x >= limitX && y >= limitY)
  1069. {
  1070. pups.sendAll = false;
  1071. pups.sendAllcurrentX = 0;
  1072. pups.sendAllcurrentY = 0;
  1073. }
  1074. else
  1075. {
  1076. pups.sendAllcurrentX = x;
  1077. pups.sendAllcurrentY = y;
  1078. }
  1079. npatchs = patchs.Count;
  1080. if (npatchs > 0)
  1081. {
  1082. int[] patchPieces = new int[npatchs * 2];
  1083. int pieceIndex = 0;
  1084. foreach (PatchesToSend pts in patchs)
  1085. {
  1086. patchPieces[pieceIndex++] = pts.PatchX;
  1087. patchPieces[pieceIndex++] = pts.PatchY;
  1088. }
  1089. pups.Presence.ControllingClient.SendLayerData(patchPieces);
  1090. }
  1091. }
  1092. private List<PatchesToSend> GetModifiedPatchesInViewDistance(PatchUpdates pups)
  1093. {
  1094. List<PatchesToSend> ret = new List<PatchesToSend>();
  1095. int npatchs = 0;
  1096. ScenePresence presence = pups.Presence;
  1097. if (presence == null)
  1098. return ret;
  1099. float minz = presence.AbsolutePosition.Z;
  1100. if (presence.CameraPosition.Z < minz)
  1101. minz = presence.CameraPosition.Z;
  1102. // this limit should be max terrainheight + max draw
  1103. if (minz > 1500f)
  1104. return ret;
  1105. int DrawDistance = (int)presence.DrawDistance;
  1106. DrawDistance = DrawDistance / Constants.TerrainPatchSize;
  1107. int testposX;
  1108. int testposY;
  1109. if (Math.Abs(presence.AbsolutePosition.X - presence.CameraPosition.X) > 30
  1110. || Math.Abs(presence.AbsolutePosition.Y - presence.CameraPosition.Y) > 30)
  1111. {
  1112. testposX = (int)presence.CameraPosition.X / Constants.TerrainPatchSize;
  1113. testposY = (int)presence.CameraPosition.Y / Constants.TerrainPatchSize;
  1114. }
  1115. else
  1116. {
  1117. testposX = (int)presence.AbsolutePosition.X / Constants.TerrainPatchSize;
  1118. testposY = (int)presence.AbsolutePosition.Y / Constants.TerrainPatchSize;
  1119. }
  1120. int limitX = (int)m_scene.RegionInfo.RegionSizeX / Constants.TerrainPatchSize;
  1121. int limitY = (int)m_scene.RegionInfo.RegionSizeY / Constants.TerrainPatchSize;
  1122. // Compute the area of patches within our draw distance
  1123. int startX = testposX - DrawDistance;
  1124. if (startX < 0)
  1125. startX = 0;
  1126. else if (startX >= limitX)
  1127. startX = limitX - 1;
  1128. int startY = testposY - DrawDistance;
  1129. if (startY < 0)
  1130. startY = 0;
  1131. else if (startY >= limitY)
  1132. startY = limitY - 1;
  1133. int endX = testposX + DrawDistance;
  1134. if (endX < 0)
  1135. endX = 0;
  1136. else if (endX > limitX)
  1137. endX = limitX;
  1138. int endY = testposY + DrawDistance;
  1139. if (endY < 0)
  1140. endY = 0;
  1141. else if (endY > limitY)
  1142. endY = limitY;
  1143. int distx;
  1144. int disty;
  1145. int distsq;
  1146. DrawDistance *= DrawDistance;
  1147. for (int x = startX; x < endX; x++)
  1148. {
  1149. for (int y = startY; y < endY; y++)
  1150. {
  1151. if (pups.GetByPatch(x, y))
  1152. {
  1153. distx = x - testposX;
  1154. disty = y - testposY;
  1155. distsq = distx * distx + disty * disty;
  1156. if (distsq < DrawDistance)
  1157. {
  1158. pups.SetByPatch(x, y, false);
  1159. ret.Add(new PatchesToSend(x, y, (float)distsq));
  1160. if (npatchs++ > 1024)
  1161. {
  1162. y = endY;
  1163. x = endX;
  1164. }
  1165. }
  1166. }
  1167. }
  1168. }
  1169. return ret;
  1170. }
  1171. private void client_OnModifyTerrain(UUID user, float height, float seconds, byte size, byte action,
  1172. float north, float west, float south, float east, UUID agentId)
  1173. {
  1174. bool god = m_scene.Permissions.IsGod(user);
  1175. bool allowed = false;
  1176. if (north == south && east == west)
  1177. {
  1178. if (m_painteffects.ContainsKey((StandardTerrainEffects)action))
  1179. {
  1180. bool[,] allowMask = new bool[m_channel.Width, m_channel.Height];
  1181. allowMask.Initialize();
  1182. int n = size + 1;
  1183. if (n > 2)
  1184. n = 4;
  1185. int zx = (int)(west + 0.5);
  1186. int zy = (int)(north + 0.5);
  1187. int startX = zx - n;
  1188. if (startX < 0)
  1189. startX = 0;
  1190. int startY = zy - n;
  1191. if (startY < 0)
  1192. startY = 0;
  1193. int endX = zx + n;
  1194. if (endX >= m_channel.Width)
  1195. endX = m_channel.Width - 1;
  1196. int endY = zy + n;
  1197. if (endY >= m_channel.Height)
  1198. endY = m_channel.Height - 1;
  1199. int x, y;
  1200. for (x = startX; x <= endX; x++)
  1201. {
  1202. for (y = startY; y <= endY; y++)
  1203. {
  1204. if (m_scene.Permissions.CanTerraformLand(agentId, new Vector3(x, y, 0)))
  1205. {
  1206. allowMask[x, y] = true;
  1207. allowed = true;
  1208. }
  1209. }
  1210. }
  1211. if (allowed)
  1212. {
  1213. StoreUndoState();
  1214. m_painteffects[(StandardTerrainEffects) action].PaintEffect(
  1215. m_channel, allowMask, west, south, height, size, seconds,
  1216. startX, endX, startY, endY);
  1217. //block changes outside estate limits
  1218. if (!god)
  1219. EnforceEstateLimits(startX, endX, startY, endY);
  1220. }
  1221. }
  1222. else
  1223. {
  1224. m_log.Debug("Unknown terrain brush type " + action);
  1225. }
  1226. }
  1227. else
  1228. {
  1229. if (m_floodeffects.ContainsKey((StandardTerrainEffects)action))
  1230. {
  1231. bool[,] fillArea = new bool[m_channel.Width, m_channel.Height];
  1232. fillArea.Initialize();
  1233. int startX = (int)west;
  1234. int startY = (int)south;
  1235. int endX = (int)east;
  1236. int endY = (int)north;
  1237. if (startX < 0)
  1238. startX = 0;
  1239. else if (startX >= m_channel.Width)
  1240. startX = m_channel.Width - 1;
  1241. if (endX < 0)
  1242. endX = 0;
  1243. else if (endX >= m_channel.Width)
  1244. endX = m_channel.Width - 1;
  1245. if (startY < 0)
  1246. startY = 0;
  1247. else if (startY >= m_channel.Height)
  1248. startY = m_channel.Height - 1;
  1249. if (endY < 0)
  1250. endY = 0;
  1251. else if (endY >= m_channel.Height)
  1252. endY = m_channel.Height - 1;
  1253. int x, y;
  1254. for (x = startX; x <= endX; x++)
  1255. {
  1256. for (y = startY; y <= endY; y++)
  1257. {
  1258. if (m_scene.Permissions.CanTerraformLand(agentId, new Vector3(x, y, 0)))
  1259. {
  1260. fillArea[x, y] = true;
  1261. allowed = true;
  1262. }
  1263. }
  1264. }
  1265. if (allowed)
  1266. {
  1267. StoreUndoState();
  1268. m_floodeffects[(StandardTerrainEffects)action].FloodEffect(m_channel, fillArea, size,
  1269. startX, endX, startY, endY);
  1270. //block changes outside estate limits
  1271. if (!god)
  1272. EnforceEstateLimits(startX, endX, startY, endY);
  1273. }
  1274. }
  1275. else
  1276. {
  1277. m_log.Debug("Unknown terrain flood type " + action);
  1278. }
  1279. }
  1280. }
  1281. private void client_OnBakeTerrain(IClientAPI remoteClient)
  1282. {
  1283. // Not a good permissions check (see client_OnModifyTerrain above), need to check the entire area.
  1284. // for now check a point in the centre of the region
  1285. if (m_scene.Permissions.CanIssueEstateCommand(remoteClient.AgentId, true))
  1286. {
  1287. InterfaceBakeTerrain(null); //bake terrain does not use the passed in parameter
  1288. }
  1289. }
  1290. protected void client_OnUnackedTerrain(IClientAPI client, int patchX, int patchY)
  1291. {
  1292. //m_log.Debug("Terrain packet unacked, resending patch: " + patchX + " , " + patchY);
  1293. // SendLayerData does not use the heightmap parameter. This kludge is so as to not change IClientAPI.
  1294. client.SendLayerData(new int[]{patchX, patchY});
  1295. }
  1296. private void StoreUndoState()
  1297. {
  1298. }
  1299. #region Console Commands
  1300. private void InterfaceLoadFile(Object[] args)
  1301. {
  1302. LoadFromFile((string) args[0]);
  1303. }
  1304. private void InterfaceLoadTileFile(Object[] args)
  1305. {
  1306. LoadFromFile((string) args[0],
  1307. (int) args[1],
  1308. (int) args[2],
  1309. (int) args[3],
  1310. (int) args[4]);
  1311. }
  1312. private void InterfaceSaveFile(Object[] args)
  1313. {
  1314. SaveToFile((string)args[0]);
  1315. }
  1316. private void InterfaceSaveTileFile(Object[] args)
  1317. {
  1318. SaveToFile((string)args[0],
  1319. (int)args[1],
  1320. (int)args[2],
  1321. (int)args[3],
  1322. (int)args[4]);
  1323. }
  1324. private void InterfaceBakeTerrain(Object[] args)
  1325. {
  1326. UpdateBakedMap();
  1327. }
  1328. private void InterfaceRevertTerrain(Object[] args)
  1329. {
  1330. int x, y;
  1331. for (x = 0; x < m_channel.Width; x++)
  1332. for (y = 0; y < m_channel.Height; y++)
  1333. m_channel[x, y] = m_baked[x, y];
  1334. }
  1335. private void InterfaceFlipTerrain(Object[] args)
  1336. {
  1337. String direction = (String)args[0];
  1338. if (direction.ToLower().StartsWith("y"))
  1339. {
  1340. for (int x = 0; x < m_channel.Width; x++)
  1341. {
  1342. for (int y = 0; y < m_channel.Height / 2; y++)
  1343. {
  1344. double height = m_channel[x, y];
  1345. double flippedHeight = m_channel[x, (int)m_channel.Height - 1 - y];
  1346. m_channel[x, y] = flippedHeight;
  1347. m_channel[x, (int)m_channel.Height - 1 - y] = height;
  1348. }
  1349. }
  1350. }
  1351. else if (direction.ToLower().StartsWith("x"))
  1352. {
  1353. for (int y = 0; y < m_channel.Height; y++)
  1354. {
  1355. for (int x = 0; x < m_channel.Width / 2; x++)
  1356. {
  1357. double height = m_channel[x, y];
  1358. double flippedHeight = m_channel[(int)m_channel.Width - 1 - x, y];
  1359. m_channel[x, y] = flippedHeight;
  1360. m_channel[(int)m_channel.Width - 1 - x, y] = height;
  1361. }
  1362. }
  1363. }
  1364. else
  1365. {
  1366. MainConsole.Instance.Output("ERROR: Unrecognised direction {0} - need x or y", null, direction);
  1367. }
  1368. }
  1369. private void InterfaceRescaleTerrain(Object[] args)
  1370. {
  1371. double desiredMin = (double)args[0];
  1372. double desiredMax = (double)args[1];
  1373. // determine desired scaling factor
  1374. double desiredRange = desiredMax - desiredMin;
  1375. //m_log.InfoFormat("Desired {0}, {1} = {2}", new Object[] { desiredMin, desiredMax, desiredRange });
  1376. if (desiredRange == 0d)
  1377. {
  1378. // delta is zero so flatten at requested height
  1379. InterfaceFillTerrain(new Object[] { args[1] });
  1380. }
  1381. else
  1382. {
  1383. //work out current heightmap range
  1384. double currMin = double.MaxValue;
  1385. double currMax = double.MinValue;
  1386. int width = m_channel.Width;
  1387. int height = m_channel.Height;
  1388. for(int x = 0; x < width; x++)
  1389. {
  1390. for(int y = 0; y < height; y++)
  1391. {
  1392. double currHeight = m_channel[x, y];
  1393. if (currHeight < currMin)
  1394. {
  1395. currMin = currHeight;
  1396. }
  1397. else if (currHeight > currMax)
  1398. {
  1399. currMax = currHeight;
  1400. }
  1401. }
  1402. }
  1403. double currRange = currMax - currMin;
  1404. double scale = desiredRange / currRange;
  1405. //m_log.InfoFormat("Current {0}, {1} = {2}", new Object[] { currMin, currMax, currRange });
  1406. //m_log.InfoFormat("Scale = {0}", scale);
  1407. // scale the heightmap accordingly
  1408. for(int x = 0; x < width; x++)
  1409. {
  1410. for(int y = 0; y < height; y++)
  1411. {
  1412. double currHeight = m_channel[x, y] - currMin;
  1413. m_channel[x, y] = desiredMin + (currHeight * scale);
  1414. }
  1415. }
  1416. }
  1417. }
  1418. private void InterfaceElevateTerrain(Object[] args)
  1419. {
  1420. double val = (double)args[0];
  1421. int x, y;
  1422. for (x = 0; x < m_channel.Width; x++)
  1423. for (y = 0; y < m_channel.Height; y++)
  1424. m_channel[x, y] += val;
  1425. }
  1426. private void InterfaceMultiplyTerrain(Object[] args)
  1427. {
  1428. int x, y;
  1429. double val = (double)args[0];
  1430. for (x = 0; x < m_channel.Width; x++)
  1431. for (y = 0; y < m_channel.Height; y++)
  1432. m_channel[x, y] *= val;
  1433. }
  1434. private void InterfaceLowerTerrain(Object[] args)
  1435. {
  1436. int x, y;
  1437. double val = (double)args[0];
  1438. for (x = 0; x < m_channel.Width; x++)
  1439. for (y = 0; y < m_channel.Height; y++)
  1440. m_channel[x, y] -= val;
  1441. }
  1442. public void InterfaceFillTerrain(Object[] args)
  1443. {
  1444. int x, y;
  1445. double val = (double)args[0];
  1446. for (x = 0; x < m_channel.Width; x++)
  1447. for (y = 0; y < m_channel.Height; y++)
  1448. m_channel[x, y] = val;
  1449. }
  1450. private void InterfaceMinTerrain(Object[] args)
  1451. {
  1452. int x, y;
  1453. double val = (double)args[0];
  1454. for (x = 0; x < m_channel.Width; x++)
  1455. {
  1456. for(y = 0; y < m_channel.Height; y++)
  1457. {
  1458. m_channel[x, y] = Math.Max(val, m_channel[x, y]);
  1459. }
  1460. }
  1461. }
  1462. private void InterfaceMaxTerrain(Object[] args)
  1463. {
  1464. int x, y;
  1465. double val = (double)args[0];
  1466. for (x = 0; x < m_channel.Width; x++)
  1467. {
  1468. for(y = 0; y < m_channel.Height; y++)
  1469. {
  1470. m_channel[x, y] = Math.Min(val, m_channel[x, y]);
  1471. }
  1472. }
  1473. }
  1474. private void InterfaceShow(Object[] args)
  1475. {
  1476. Vector2 point;
  1477. if (!ConsoleUtil.TryParseConsole2DVector((string)args[0], null, out point))
  1478. {
  1479. Console.WriteLine("ERROR: {0} is not a valid vector", args[0]);
  1480. return;
  1481. }
  1482. double height = m_channel[(int)point.X, (int)point.Y];
  1483. Console.WriteLine("Terrain height at {0} is {1}", point, height);
  1484. }
  1485. private void InterfaceShowDebugStats(Object[] args)
  1486. {
  1487. double max = Double.MinValue;
  1488. double min = double.MaxValue;
  1489. double sum = 0;
  1490. int x;
  1491. for(x = 0; x < m_channel.Width; x++)
  1492. {
  1493. int y;
  1494. for(y = 0; y < m_channel.Height; y++)
  1495. {
  1496. sum += m_channel[x, y];
  1497. if (max < m_channel[x, y])
  1498. max = m_channel[x, y];
  1499. if (min > m_channel[x, y])
  1500. min = m_channel[x, y];
  1501. }
  1502. }
  1503. double avg = sum / (m_channel.Height * m_channel.Width);
  1504. MainConsole.Instance.Output("Channel {0}x{1}", null, m_channel.Width, m_channel.Height);
  1505. MainConsole.Instance.Output("max/min/avg/sum: {0}/{1}/{2}/{3}", null, max, min, avg, sum);
  1506. }
  1507. private void InterfaceEnableExperimentalBrushes(Object[] args)
  1508. {
  1509. if ((bool)args[0])
  1510. {
  1511. m_painteffects[StandardTerrainEffects.Revert] = new WeatherSphere();
  1512. m_painteffects[StandardTerrainEffects.Flatten] = new OlsenSphere();
  1513. m_painteffects[StandardTerrainEffects.Smooth] = new ErodeSphere();
  1514. }
  1515. else
  1516. {
  1517. InstallDefaultEffects();
  1518. }
  1519. }
  1520. private void InterfaceRunPluginEffect(Object[] args)
  1521. {
  1522. string firstArg = (string)args[0];
  1523. if (firstArg == "list")
  1524. {
  1525. MainConsole.Instance.Output("List of loaded plugins");
  1526. foreach(KeyValuePair<string, ITerrainEffect> kvp in m_plugineffects)
  1527. {
  1528. MainConsole.Instance.Output(kvp.Key);
  1529. }
  1530. return;
  1531. }
  1532. if (firstArg == "reload")
  1533. {
  1534. LoadPlugins();
  1535. return;
  1536. }
  1537. if (m_plugineffects.ContainsKey(firstArg))
  1538. {
  1539. m_plugineffects[firstArg].RunEffect(m_channel);
  1540. }
  1541. else
  1542. {
  1543. MainConsole.Instance.Output("WARNING: No such plugin effect {0} loaded.", firstArg);
  1544. }
  1545. }
  1546. private void InstallInterfaces()
  1547. {
  1548. Command loadFromFileCommand =
  1549. new Command("load", CommandIntentions.COMMAND_HAZARDOUS, InterfaceLoadFile, "Loads a terrain from a specified file.");
  1550. loadFromFileCommand.AddArgument("filename",
  1551. "The file you wish to load from, the file extension determines the loader to be used. Supported extensions include: " +
  1552. m_supportedFileExtensions, "String");
  1553. Command saveToFileCommand =
  1554. new Command("save", CommandIntentions.COMMAND_NON_HAZARDOUS, InterfaceSaveFile, "Saves the current heightmap to a specified file.");
  1555. saveToFileCommand.AddArgument("filename",
  1556. "The destination filename for your heightmap, the file extension determines the format to save in. Supported extensions include: " +
  1557. m_supportedFileExtensions, "String");
  1558. Command loadFromTileCommand =
  1559. new Command("load-tile", CommandIntentions.COMMAND_HAZARDOUS, InterfaceLoadTileFile, "Loads a terrain from a section of a larger file.");
  1560. loadFromTileCommand.AddArgument("filename",
  1561. "The file you wish to load from, the file extension determines the loader to be used. Supported extensions include: " +
  1562. m_supportedFileExtensions, "String");
  1563. loadFromTileCommand.AddArgument("file width", "The width of the file in tiles", "Integer");
  1564. loadFromTileCommand.AddArgument("file height", "The height of the file in tiles", "Integer");
  1565. loadFromTileCommand.AddArgument("minimum X tile", "The X region coordinate of the first section on the file",
  1566. "Integer");
  1567. loadFromTileCommand.AddArgument("minimum Y tile", "The Y region coordinate of the first section on the file",
  1568. "Integer");
  1569. Command saveToTileCommand =
  1570. new Command("save-tile", CommandIntentions.COMMAND_HAZARDOUS, InterfaceSaveTileFile, "Saves the current heightmap to the larger file.");
  1571. saveToTileCommand.AddArgument("filename",
  1572. "The file you wish to save to, the file extension determines the loader to be used. Supported extensions include: " +
  1573. m_supportFileExtensionsForTileSave, "String");
  1574. saveToTileCommand.AddArgument("file width", "The width of the file in tiles", "Integer");
  1575. saveToTileCommand.AddArgument("file height", "The height of the file in tiles", "Integer");
  1576. saveToTileCommand.AddArgument("minimum X tile", "The X region coordinate of the first section on the file",
  1577. "Integer");
  1578. saveToTileCommand.AddArgument("minimum Y tile", "The Y region coordinate of the first tile on the file\n"
  1579. + "= Example =\n"
  1580. + "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"
  1581. + " # terrain save-tile ST06.png 2 3 9910 10234\n",
  1582. "Integer");
  1583. // Terrain adjustments
  1584. Command fillRegionCommand =
  1585. new Command("fill", CommandIntentions.COMMAND_HAZARDOUS, InterfaceFillTerrain, "Fills the current heightmap with a specified value.");
  1586. fillRegionCommand.AddArgument("value", "The numeric value of the height you wish to set your region to.",
  1587. "Double");
  1588. Command elevateCommand =
  1589. new Command("elevate", CommandIntentions.COMMAND_HAZARDOUS, InterfaceElevateTerrain, "Raises the current heightmap by the specified amount.");
  1590. elevateCommand.AddArgument("amount", "The amount of height to add to the terrain in meters.", "Double");
  1591. Command lowerCommand =
  1592. new Command("lower", CommandIntentions.COMMAND_HAZARDOUS, InterfaceLowerTerrain, "Lowers the current heightmap by the specified amount.");
  1593. lowerCommand.AddArgument("amount", "The amount of height to remove from the terrain in meters.", "Double");
  1594. Command multiplyCommand =
  1595. new Command("multiply", CommandIntentions.COMMAND_HAZARDOUS, InterfaceMultiplyTerrain, "Multiplies the heightmap by the value specified.");
  1596. multiplyCommand.AddArgument("value", "The value to multiply the heightmap by.", "Double");
  1597. Command bakeRegionCommand =
  1598. new Command("bake", CommandIntentions.COMMAND_HAZARDOUS, InterfaceBakeTerrain, "Saves the current terrain into the regions baked map.");
  1599. Command revertRegionCommand =
  1600. new Command("revert", CommandIntentions.COMMAND_HAZARDOUS, InterfaceRevertTerrain, "Loads the baked map terrain into the regions heightmap.");
  1601. Command flipCommand =
  1602. new Command("flip", CommandIntentions.COMMAND_HAZARDOUS, InterfaceFlipTerrain, "Flips the current terrain about the X or Y axis");
  1603. flipCommand.AddArgument("direction", "[x|y] the direction to flip the terrain in", "String");
  1604. Command rescaleCommand =
  1605. new Command("rescale", CommandIntentions.COMMAND_HAZARDOUS, InterfaceRescaleTerrain, "Rescales the current terrain to fit between the given min and max heights");
  1606. rescaleCommand.AddArgument("min", "min terrain height after rescaling", "Double");
  1607. rescaleCommand.AddArgument("max", "max terrain height after rescaling", "Double");
  1608. Command minCommand = new Command("min", CommandIntentions.COMMAND_HAZARDOUS, InterfaceMinTerrain, "Sets the minimum terrain height to the specified value.");
  1609. minCommand.AddArgument("min", "terrain height to use as minimum", "Double");
  1610. Command maxCommand = new Command("max", CommandIntentions.COMMAND_HAZARDOUS, InterfaceMaxTerrain, "Sets the maximum terrain height to the specified value.");
  1611. maxCommand.AddArgument("min", "terrain height to use as maximum", "Double");
  1612. // Debug
  1613. Command showDebugStatsCommand =
  1614. new Command("stats", CommandIntentions.COMMAND_STATISTICAL, InterfaceShowDebugStats,
  1615. "Shows some information about the regions heightmap for debugging purposes.");
  1616. Command showCommand =
  1617. new Command("show", CommandIntentions.COMMAND_NON_HAZARDOUS, InterfaceShow,
  1618. "Shows terrain height at a given co-ordinate.");
  1619. showCommand.AddArgument("point", "point in <x>,<y> format with no spaces (e.g. 45,45)", "String");
  1620. Command experimentalBrushesCommand =
  1621. new Command("newbrushes", CommandIntentions.COMMAND_HAZARDOUS, InterfaceEnableExperimentalBrushes,
  1622. "Enables experimental brushes which replace the standard terrain brushes. WARNING: This is a debug setting and may be removed at any time.");
  1623. experimentalBrushesCommand.AddArgument("Enabled?", "true / false - Enable new brushes", "Boolean");
  1624. // Plugins
  1625. Command pluginRunCommand =
  1626. new Command("effect", CommandIntentions.COMMAND_HAZARDOUS, InterfaceRunPluginEffect, "Runs a specified plugin effect");
  1627. pluginRunCommand.AddArgument("name", "The plugin effect you wish to run, or 'list' to see all plugins", "String");
  1628. m_commander.RegisterCommand("load", loadFromFileCommand);
  1629. m_commander.RegisterCommand("load-tile", loadFromTileCommand);
  1630. m_commander.RegisterCommand("save", saveToFileCommand);
  1631. m_commander.RegisterCommand("save-tile", saveToTileCommand);
  1632. m_commander.RegisterCommand("fill", fillRegionCommand);
  1633. m_commander.RegisterCommand("elevate", elevateCommand);
  1634. m_commander.RegisterCommand("lower", lowerCommand);
  1635. m_commander.RegisterCommand("multiply", multiplyCommand);
  1636. m_commander.RegisterCommand("bake", bakeRegionCommand);
  1637. m_commander.RegisterCommand("revert", revertRegionCommand);
  1638. m_commander.RegisterCommand("newbrushes", experimentalBrushesCommand);
  1639. m_commander.RegisterCommand("show", showCommand);
  1640. m_commander.RegisterCommand("stats", showDebugStatsCommand);
  1641. m_commander.RegisterCommand("effect", pluginRunCommand);
  1642. m_commander.RegisterCommand("flip", flipCommand);
  1643. m_commander.RegisterCommand("rescale", rescaleCommand);
  1644. m_commander.RegisterCommand("min", minCommand);
  1645. m_commander.RegisterCommand("max", maxCommand);
  1646. // Add this to our scene so scripts can call these functions
  1647. m_scene.RegisterModuleCommander(m_commander);
  1648. // Add Modify command to Scene, since Command object requires fixed-length arglists
  1649. m_scene.AddCommand("Terrain", this, "terrain modify",
  1650. "terrain modify <operation> <value> [<area>] [<taper>]",
  1651. "Modifies the terrain as instructed." +
  1652. "\nEach operation can be limited to an area of effect:" +
  1653. "\n * -ell=x,y,rx[,ry] constrains the operation to an ellipse centred at x,y" +
  1654. "\n * -rec=x,y,dx[,dy] constrains the operation to a rectangle based at x,y" +
  1655. "\nEach operation can have its effect tapered based on distance from centre:" +
  1656. "\n * elliptical operations taper as cones" +
  1657. "\n * rectangular operations taper as pyramids"
  1658. ,
  1659. ModifyCommand);
  1660. }
  1661. public void ModifyCommand(string module, string[] cmd)
  1662. {
  1663. string result;
  1664. Scene scene = SceneManager.Instance.CurrentScene;
  1665. if ((scene != null) && (scene != m_scene))
  1666. {
  1667. result = String.Empty;
  1668. }
  1669. else if (cmd.Length > 2)
  1670. {
  1671. string operationType = cmd[2];
  1672. ITerrainModifier operation;
  1673. if (!m_modifyOperations.TryGetValue(operationType, out operation))
  1674. {
  1675. result = String.Format("Terrain Modify \"{0}\" not found.", operationType);
  1676. }
  1677. else if ((cmd.Length > 3) && (cmd[3] == "usage"))
  1678. {
  1679. result = "Usage: " + operation.GetUsage();
  1680. }
  1681. else
  1682. {
  1683. result = operation.ModifyTerrain(m_channel, cmd);
  1684. }
  1685. if (result == String.Empty)
  1686. {
  1687. result = "Modified terrain";
  1688. m_log.DebugFormat("Performed terrain operation {0}", operationType);
  1689. }
  1690. }
  1691. else
  1692. {
  1693. result = "Usage: <operation-name> <arg1> <arg2>...";
  1694. }
  1695. if (result != String.Empty)
  1696. {
  1697. MainConsole.Instance.Output(result);
  1698. }
  1699. }
  1700. #endregion
  1701. }
  1702. }