WindModule.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482
  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.Reflection;
  30. using log4net;
  31. using Mono.Addins;
  32. using Nini.Config;
  33. using OpenMetaverse;
  34. using OpenSim.Framework;
  35. using OpenSim.Region.Framework.Interfaces;
  36. using OpenSim.Region.Framework.Scenes;
  37. using OpenSim.Region.CoreModules.World.Wind;
  38. namespace OpenSim.Region.CoreModules
  39. {
  40. [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "WindModule")]
  41. public class WindModule : IWindModule
  42. {
  43. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  44. private uint m_frame = 0;
  45. private uint m_frameLastUpdateClientArray = 0;
  46. private int m_frameUpdateRate = 150;
  47. //private Random m_rndnums = new Random(Environment.TickCount);
  48. private Scene m_scene = null;
  49. private bool m_ready = false;
  50. private bool m_enabled = false;
  51. private IConfig m_windConfig;
  52. private IWindModelPlugin m_activeWindPlugin = null;
  53. private string m_dWindPluginName = "SimpleRandomWind";
  54. private Dictionary<string, IWindModelPlugin> m_availableWindPlugins = new Dictionary<string, IWindModelPlugin>();
  55. // Simplified windSpeeds based on the fact that the client protocal tracks at a resolution of 16m
  56. private Vector2[] windSpeeds = new Vector2[16 * 16];
  57. #region INonSharedRegionModule Methods
  58. public void Initialise(IConfigSource config)
  59. {
  60. m_windConfig = config.Configs["Wind"];
  61. // string desiredWindPlugin = m_dWindPluginName;
  62. if (m_windConfig != null)
  63. {
  64. m_enabled = m_windConfig.GetBoolean("enabled", true);
  65. m_frameUpdateRate = m_windConfig.GetInt("wind_update_rate", 150);
  66. // Determine which wind model plugin is desired
  67. if (m_windConfig.Contains("wind_plugin"))
  68. {
  69. m_dWindPluginName = m_windConfig.GetString("wind_plugin", m_dWindPluginName);
  70. }
  71. }
  72. if (m_enabled)
  73. {
  74. m_log.InfoFormat("[WIND] Enabled with an update rate of {0} frames.", m_frameUpdateRate);
  75. }
  76. }
  77. public void AddRegion(Scene scene)
  78. {
  79. if (!m_enabled)
  80. return;
  81. m_scene = scene;
  82. m_frame = 0;
  83. // Register all the Wind Model Plug-ins
  84. foreach (IWindModelPlugin windPlugin in AddinManager.GetExtensionObjects("/OpenSim/WindModule", false))
  85. {
  86. m_log.InfoFormat("[WIND] Found Plugin: {0}", windPlugin.Name);
  87. m_availableWindPlugins.Add(windPlugin.Name, windPlugin);
  88. }
  89. // Check for desired plugin
  90. if (m_availableWindPlugins.ContainsKey(m_dWindPluginName))
  91. {
  92. m_activeWindPlugin = m_availableWindPlugins[m_dWindPluginName];
  93. m_log.InfoFormat("[WIND] {0} plugin found, initializing.", m_dWindPluginName);
  94. if (m_windConfig != null)
  95. {
  96. m_activeWindPlugin.Initialise();
  97. m_activeWindPlugin.WindConfig(m_scene, m_windConfig);
  98. }
  99. }
  100. // if the plug-in wasn't found, default to no wind.
  101. if (m_activeWindPlugin == null)
  102. {
  103. m_log.ErrorFormat("[WIND] Could not find specified wind plug-in: {0}", m_dWindPluginName);
  104. m_log.ErrorFormat("[WIND] Defaulting to no wind.");
  105. }
  106. // This one puts an entry in the main help screen
  107. // m_scene.AddCommand("Regions", this, "wind", "wind", "Usage: wind <plugin> <param> [value] - Get or Update Wind paramaters", null);
  108. // This one enables the ability to type just the base command without any parameters
  109. // m_scene.AddCommand("Regions", this, "wind", "", "", HandleConsoleCommand);
  110. // Get a list of the parameters for each plugin
  111. foreach (IWindModelPlugin windPlugin in m_availableWindPlugins.Values)
  112. {
  113. // m_scene.AddCommand("Regions", this, String.Format("wind base wind_plugin {0}", windPlugin.Name), String.Format("{0} - {1}", windPlugin.Name, windPlugin.Description), "", HandleConsoleBaseCommand);
  114. m_scene.AddCommand(
  115. "Regions",
  116. this,
  117. "wind base wind_update_rate",
  118. "wind base wind_update_rate [<value>]",
  119. "Get or set the wind update rate.",
  120. "",
  121. HandleConsoleBaseCommand);
  122. foreach (KeyValuePair<string, string> kvp in windPlugin.WindParams())
  123. {
  124. string windCommand = String.Format("wind {0} {1}", windPlugin.Name, kvp.Key);
  125. m_scene.AddCommand("Regions", this, windCommand, string.Format("{0} [<value>]", windCommand), kvp.Value, "", HandleConsoleParamCommand);
  126. }
  127. }
  128. // Register event handlers for when Avatars enter the region, and frame ticks
  129. m_scene.EventManager.OnFrame += WindUpdate;
  130. m_scene.EventManager.OnMakeRootAgent += OnAgentEnteredRegion;
  131. // Register the wind module
  132. m_scene.RegisterModuleInterface<IWindModule>(this);
  133. // Generate initial wind values
  134. GenWindPos();
  135. // Mark Module Ready for duty
  136. m_ready = true;
  137. }
  138. public void RemoveRegion(Scene scene)
  139. {
  140. if (!m_enabled)
  141. return;
  142. m_ready = false;
  143. // REVIEW: If a region module is closed, is there a possibility that it'll re-open/initialize ??
  144. m_activeWindPlugin = null;
  145. foreach (IWindModelPlugin windPlugin in m_availableWindPlugins.Values)
  146. {
  147. windPlugin.Dispose();
  148. }
  149. m_availableWindPlugins.Clear();
  150. // Remove our hooks
  151. m_scene.EventManager.OnFrame -= WindUpdate;
  152. m_scene.EventManager.OnMakeRootAgent -= OnAgentEnteredRegion;
  153. }
  154. public void Close()
  155. {
  156. }
  157. public string Name
  158. {
  159. get { return "WindModule"; }
  160. }
  161. public Type ReplaceableInterface
  162. {
  163. get { return null; }
  164. }
  165. public void RegionLoaded(Scene scene)
  166. {
  167. }
  168. #endregion
  169. #region Console Commands
  170. private void ValidateConsole()
  171. {
  172. if (m_scene.ConsoleScene() == null)
  173. {
  174. // FIXME: If console region is root then this will be printed by every module. Currently, there is no
  175. // way to prevent this, short of making the entire module shared (which is complete overkill).
  176. // One possibility is to return a bool to signal whether the module has completely handled the command
  177. MainConsole.Instance.Output("Please change to a specific region in order to set Sun parameters.");
  178. return;
  179. }
  180. if (m_scene.ConsoleScene() != m_scene)
  181. {
  182. MainConsole.Instance.Output("Console Scene is not my scene.");
  183. return;
  184. }
  185. }
  186. /// <summary>
  187. /// Base console command handler, only used if a person specifies the base command with now options
  188. /// </summary>
  189. private void HandleConsoleCommand(string module, string[] cmdparams)
  190. {
  191. ValidateConsole();
  192. MainConsole.Instance.Output(
  193. "The wind command can be used to change the currently active wind model plugin and update the parameters for wind plugins.");
  194. }
  195. /// <summary>
  196. /// Called to change the active wind model plugin
  197. /// </summary>
  198. private void HandleConsoleBaseCommand(string module, string[] cmdparams)
  199. {
  200. ValidateConsole();
  201. if ((cmdparams.Length != 4)
  202. || !cmdparams[1].Equals("base"))
  203. {
  204. MainConsole.Instance.Output(
  205. "Invalid parameters to change parameters for Wind module base, usage: wind base <parameter> <value>");
  206. return;
  207. }
  208. switch (cmdparams[2])
  209. {
  210. case "wind_update_rate":
  211. int newRate = 1;
  212. if (int.TryParse(cmdparams[3], out newRate))
  213. {
  214. m_frameUpdateRate = newRate;
  215. }
  216. else
  217. {
  218. MainConsole.Instance.OutputFormat(
  219. "Invalid value {0} specified for {1}", cmdparams[3], cmdparams[2]);
  220. return;
  221. }
  222. break;
  223. case "wind_plugin":
  224. string desiredPlugin = cmdparams[3];
  225. if (desiredPlugin.Equals(m_activeWindPlugin.Name))
  226. {
  227. MainConsole.Instance.OutputFormat("Wind model plugin {0} is already active", cmdparams[3]);
  228. return;
  229. }
  230. if (m_availableWindPlugins.ContainsKey(desiredPlugin))
  231. {
  232. m_activeWindPlugin = m_availableWindPlugins[cmdparams[3]];
  233. MainConsole.Instance.OutputFormat("{0} wind model plugin now active", m_activeWindPlugin.Name);
  234. }
  235. else
  236. {
  237. MainConsole.Instance.OutputFormat("Could not find wind model plugin {0}", desiredPlugin);
  238. }
  239. break;
  240. }
  241. }
  242. /// <summary>
  243. /// Called to change plugin parameters.
  244. /// </summary>
  245. private void HandleConsoleParamCommand(string module, string[] cmdparams)
  246. {
  247. ValidateConsole();
  248. // wind <plugin> <param> [value]
  249. if ((cmdparams.Length != 4)
  250. && (cmdparams.Length != 3))
  251. {
  252. MainConsole.Instance.Output("Usage: wind <plugin> <param> [value]");
  253. return;
  254. }
  255. string plugin = cmdparams[1];
  256. string param = cmdparams[2];
  257. float value = 0f;
  258. if (cmdparams.Length == 4)
  259. {
  260. if (!float.TryParse(cmdparams[3], out value))
  261. {
  262. MainConsole.Instance.OutputFormat("Invalid value {0}", cmdparams[3]);
  263. }
  264. try
  265. {
  266. WindParamSet(plugin, param, value);
  267. MainConsole.Instance.OutputFormat("{0} set to {1}", param, value);
  268. }
  269. catch (Exception e)
  270. {
  271. MainConsole.Instance.OutputFormat("{0}", e.Message);
  272. }
  273. }
  274. else
  275. {
  276. try
  277. {
  278. value = WindParamGet(plugin, param);
  279. MainConsole.Instance.OutputFormat("{0} : {1}", param, value);
  280. }
  281. catch (Exception e)
  282. {
  283. MainConsole.Instance.OutputFormat("{0}", e.Message);
  284. }
  285. }
  286. }
  287. #endregion
  288. #region IWindModule Methods
  289. /// <summary>
  290. /// Retrieve the wind speed at the given region coordinate. This
  291. /// implimentation ignores Z.
  292. /// </summary>
  293. /// <param name="x">0...255</param>
  294. /// <param name="y">0...255</param>
  295. public Vector3 WindSpeed(int x, int y, int z)
  296. {
  297. if (m_activeWindPlugin != null)
  298. {
  299. return m_activeWindPlugin.WindSpeed(x, y, z);
  300. }
  301. else
  302. {
  303. return new Vector3(0.0f, 0.0f, 0.0f);
  304. }
  305. }
  306. public void WindParamSet(string plugin, string param, float value)
  307. {
  308. if (m_availableWindPlugins.ContainsKey(plugin))
  309. {
  310. IWindModelPlugin windPlugin = m_availableWindPlugins[plugin];
  311. windPlugin.WindParamSet(param, value);
  312. }
  313. else
  314. {
  315. throw new Exception(String.Format("Could not find plugin {0}", plugin));
  316. }
  317. }
  318. public float WindParamGet(string plugin, string param)
  319. {
  320. if (m_availableWindPlugins.ContainsKey(plugin))
  321. {
  322. IWindModelPlugin windPlugin = m_availableWindPlugins[plugin];
  323. return windPlugin.WindParamGet(param);
  324. }
  325. else
  326. {
  327. throw new Exception(String.Format("Could not find plugin {0}", plugin));
  328. }
  329. }
  330. public string WindActiveModelPluginName
  331. {
  332. get
  333. {
  334. if (m_activeWindPlugin != null)
  335. {
  336. return m_activeWindPlugin.Name;
  337. }
  338. else
  339. {
  340. return String.Empty;
  341. }
  342. }
  343. }
  344. #endregion
  345. /// <summary>
  346. /// Called on each frame update. Updates the wind model and clients as necessary.
  347. /// </summary>
  348. public void WindUpdate()
  349. {
  350. if (((m_frame++ % m_frameUpdateRate) != 0) || !m_ready)
  351. {
  352. return;
  353. }
  354. GenWindPos();
  355. SendWindAllClients();
  356. }
  357. public void OnAgentEnteredRegion(ScenePresence avatar)
  358. {
  359. if (m_ready)
  360. {
  361. if (m_activeWindPlugin != null)
  362. {
  363. // Ask wind plugin to generate a LL wind array to be cached locally
  364. // Try not to update this too often, as it may involve array copies
  365. if (m_frame >= (m_frameLastUpdateClientArray + m_frameUpdateRate))
  366. {
  367. windSpeeds = m_activeWindPlugin.WindLLClientArray();
  368. m_frameLastUpdateClientArray = m_frame;
  369. }
  370. }
  371. avatar.ControllingClient.SendWindData(windSpeeds);
  372. }
  373. }
  374. private void SendWindAllClients()
  375. {
  376. if (m_ready)
  377. {
  378. if (m_scene.GetRootAgentCount() > 0)
  379. {
  380. // Ask wind plugin to generate a LL wind array to be cached locally
  381. // Try not to update this too often, as it may involve array copies
  382. if (m_frame >= (m_frameLastUpdateClientArray + m_frameUpdateRate))
  383. {
  384. windSpeeds = m_activeWindPlugin.WindLLClientArray();
  385. m_frameLastUpdateClientArray = m_frame;
  386. }
  387. m_scene.ForEachRootClient(delegate(IClientAPI client)
  388. {
  389. client.SendWindData(windSpeeds);
  390. });
  391. }
  392. }
  393. }
  394. /// <summary>
  395. /// Calculate the sun's orbital position and its velocity.
  396. /// </summary>
  397. private void GenWindPos()
  398. {
  399. if (m_activeWindPlugin != null)
  400. {
  401. // Tell Wind Plugin to update it's wind data
  402. m_activeWindPlugin.WindUpdate(m_frame);
  403. }
  404. }
  405. }
  406. }