WindModule.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476
  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. m_log.InfoFormat("[WIND]: Please change to a specific region in order to set Sun parameters.");
  178. return;
  179. }
  180. if (m_scene.ConsoleScene() != m_scene)
  181. {
  182. m_log.InfoFormat("[WIND]: 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. m_log.Info("[WIND] The wind command can be used to change the currently active wind model plugin and update the parameters for wind plugins.");
  193. }
  194. /// <summary>
  195. /// Called to change the active wind model plugin
  196. /// </summary>
  197. private void HandleConsoleBaseCommand(string module, string[] cmdparams)
  198. {
  199. ValidateConsole();
  200. if ((cmdparams.Length != 4)
  201. || !cmdparams[1].Equals("base"))
  202. {
  203. m_log.Info("[WIND] Invalid parameters to change parameters for Wind module base, usage: wind base <parameter> <value>");
  204. return;
  205. }
  206. switch (cmdparams[2])
  207. {
  208. case "wind_update_rate":
  209. int newRate = 1;
  210. if (int.TryParse(cmdparams[3], out newRate))
  211. {
  212. m_frameUpdateRate = newRate;
  213. }
  214. else
  215. {
  216. m_log.InfoFormat("[WIND] Invalid value {0} specified for {1}", cmdparams[3], cmdparams[2]);
  217. return;
  218. }
  219. break;
  220. case "wind_plugin":
  221. string desiredPlugin = cmdparams[3];
  222. if (desiredPlugin.Equals(m_activeWindPlugin.Name))
  223. {
  224. m_log.InfoFormat("[WIND] Wind model plugin {0} is already active", cmdparams[3]);
  225. return;
  226. }
  227. if (m_availableWindPlugins.ContainsKey(desiredPlugin))
  228. {
  229. m_activeWindPlugin = m_availableWindPlugins[cmdparams[3]];
  230. m_log.InfoFormat("[WIND] {0} wind model plugin now active", m_activeWindPlugin.Name);
  231. }
  232. else
  233. {
  234. m_log.InfoFormat("[WIND] Could not find wind model plugin {0}", desiredPlugin);
  235. }
  236. break;
  237. }
  238. }
  239. /// <summary>
  240. /// Called to change plugin parameters.
  241. /// </summary>
  242. private void HandleConsoleParamCommand(string module, string[] cmdparams)
  243. {
  244. ValidateConsole();
  245. // wind <plugin> <param> [value]
  246. if ((cmdparams.Length != 4)
  247. && (cmdparams.Length != 3))
  248. {
  249. m_log.Info("[WIND] Usage: wind <plugin> <param> [value]");
  250. return;
  251. }
  252. string plugin = cmdparams[1];
  253. string param = cmdparams[2];
  254. float value = 0f;
  255. if (cmdparams.Length == 4)
  256. {
  257. if (!float.TryParse(cmdparams[3], out value))
  258. {
  259. m_log.InfoFormat("[WIND] Invalid value {0}", cmdparams[3]);
  260. }
  261. try
  262. {
  263. WindParamSet(plugin, param, value);
  264. }
  265. catch (Exception e)
  266. {
  267. m_log.InfoFormat("[WIND] {0}", e.Message);
  268. }
  269. }
  270. else
  271. {
  272. try
  273. {
  274. value = WindParamGet(plugin, param);
  275. m_log.InfoFormat("[WIND] {0} : {1}", param, value);
  276. }
  277. catch (Exception e)
  278. {
  279. m_log.InfoFormat("[WIND] {0}", e.Message);
  280. }
  281. }
  282. }
  283. #endregion
  284. #region IWindModule Methods
  285. /// <summary>
  286. /// Retrieve the wind speed at the given region coordinate. This
  287. /// implimentation ignores Z.
  288. /// </summary>
  289. /// <param name="x">0...255</param>
  290. /// <param name="y">0...255</param>
  291. public Vector3 WindSpeed(int x, int y, int z)
  292. {
  293. if (m_activeWindPlugin != null)
  294. {
  295. return m_activeWindPlugin.WindSpeed(x, y, z);
  296. }
  297. else
  298. {
  299. return new Vector3(0.0f, 0.0f, 0.0f);
  300. }
  301. }
  302. public void WindParamSet(string plugin, string param, float value)
  303. {
  304. if (m_availableWindPlugins.ContainsKey(plugin))
  305. {
  306. IWindModelPlugin windPlugin = m_availableWindPlugins[plugin];
  307. windPlugin.WindParamSet(param, value);
  308. m_log.InfoFormat("[WIND] {0} set to {1}", param, value);
  309. }
  310. else
  311. {
  312. throw new Exception(String.Format("Could not find plugin {0}", plugin));
  313. }
  314. }
  315. public float WindParamGet(string plugin, string param)
  316. {
  317. if (m_availableWindPlugins.ContainsKey(plugin))
  318. {
  319. IWindModelPlugin windPlugin = m_availableWindPlugins[plugin];
  320. return windPlugin.WindParamGet(param);
  321. }
  322. else
  323. {
  324. throw new Exception(String.Format("Could not find plugin {0}", plugin));
  325. }
  326. }
  327. public string WindActiveModelPluginName
  328. {
  329. get
  330. {
  331. if (m_activeWindPlugin != null)
  332. {
  333. return m_activeWindPlugin.Name;
  334. }
  335. else
  336. {
  337. return String.Empty;
  338. }
  339. }
  340. }
  341. #endregion
  342. /// <summary>
  343. /// Called on each frame update. Updates the wind model and clients as necessary.
  344. /// </summary>
  345. public void WindUpdate()
  346. {
  347. if (((m_frame++ % m_frameUpdateRate) != 0) || !m_ready)
  348. {
  349. return;
  350. }
  351. GenWindPos();
  352. SendWindAllClients();
  353. }
  354. public void OnAgentEnteredRegion(ScenePresence avatar)
  355. {
  356. if (m_ready)
  357. {
  358. if (m_activeWindPlugin != null)
  359. {
  360. // Ask wind plugin to generate a LL wind array to be cached locally
  361. // Try not to update this too often, as it may involve array copies
  362. if (m_frame >= (m_frameLastUpdateClientArray + m_frameUpdateRate))
  363. {
  364. windSpeeds = m_activeWindPlugin.WindLLClientArray();
  365. m_frameLastUpdateClientArray = m_frame;
  366. }
  367. }
  368. avatar.ControllingClient.SendWindData(windSpeeds);
  369. }
  370. }
  371. private void SendWindAllClients()
  372. {
  373. if (m_ready)
  374. {
  375. if (m_scene.GetRootAgentCount() > 0)
  376. {
  377. // Ask wind plugin to generate a LL wind array to be cached locally
  378. // Try not to update this too often, as it may involve array copies
  379. if (m_frame >= (m_frameLastUpdateClientArray + m_frameUpdateRate))
  380. {
  381. windSpeeds = m_activeWindPlugin.WindLLClientArray();
  382. m_frameLastUpdateClientArray = m_frame;
  383. }
  384. m_scene.ForEachRootClient(delegate(IClientAPI client)
  385. {
  386. client.SendWindData(windSpeeds);
  387. });
  388. }
  389. }
  390. }
  391. /// <summary>
  392. /// Calculate the sun's orbital position and its velocity.
  393. /// </summary>
  394. private void GenWindPos()
  395. {
  396. if (m_activeWindPlugin != null)
  397. {
  398. // Tell Wind Plugin to update it's wind data
  399. m_activeWindPlugin.WindUpdate(m_frame);
  400. }
  401. }
  402. }
  403. }