TerrainModule.cs 71 KB

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