TerrainModule.cs 81 KB

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