TerrainModule.cs 85 KB

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