SunModule.cs 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652
  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 Nini.Config;
  32. using OpenMetaverse;
  33. using OpenSim.Framework;
  34. using OpenSim.Region.Framework.Interfaces;
  35. using OpenSim.Region.Framework.Scenes;
  36. namespace OpenSim.Region.CoreModules
  37. {
  38. public class SunModule : ISunModule
  39. {
  40. /// <summary>
  41. /// Note: Sun Hour can be a little deceaving. Although it's based on a 24 hour clock
  42. /// it is not based on ~06:00 == Sun Rise. Rather it is based on 00:00 being sun-rise.
  43. /// </summary>
  44. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  45. //
  46. // Global Constants used to determine where in the sky the sun is
  47. //
  48. private const double m_SeasonalTilt = 0.03 * Math.PI; // A daily shift of approximately 1.7188 degrees
  49. private const double m_AverageTilt = -0.25 * Math.PI; // A 45 degree tilt
  50. private const double m_SunCycle = 2.0D * Math.PI; // A perfect circle measured in radians
  51. private const double m_SeasonalCycle = 2.0D * Math.PI; // Ditto
  52. //
  53. // Per Region Values
  54. //
  55. private bool ready = false;
  56. // This solves a chick before the egg problem
  57. // the local SunFixedHour and SunFixed variables MUST be updated
  58. // at least once with the proper Region Settings before we start
  59. // updating those region settings in GenSunPos()
  60. private bool receivedEstateToolsSunUpdate = false;
  61. // Configurable values
  62. private string m_RegionMode = "SL";
  63. // Sun's position information is updated and sent to clients every m_UpdateInterval frames
  64. private int m_UpdateInterval = 0;
  65. // Number of real time hours per virtual day
  66. private double m_DayLengthHours = 0;
  67. // Number of virtual days to a virtual year
  68. private int m_YearLengthDays = 0;
  69. // Ratio of Daylight hours to Night time hours. This is accomplished by shifting the
  70. // sun's orbit above the horizon
  71. private double m_HorizonShift = 0;
  72. // Used to scale current and positional time to adjust length of an hour during day vs night.
  73. private double m_DayTimeSunHourScale;
  74. // private double m_longitude = 0;
  75. // private double m_latitude = 0;
  76. // Configurable defaults Defaults close to SL
  77. private string d_mode = "SL";
  78. private int d_frame_mod = 100; // Every 10 seconds (actually less)
  79. private double d_day_length = 4; // A VW day is 4 RW hours long
  80. private int d_year_length = 60; // There are 60 VW days in a VW year
  81. private double d_day_night = 0.5; // axis offset: Default Hoizon shift to try and closely match the sun model in LL Viewer
  82. private double d_DayTimeSunHourScale = 0.5; // Day/Night hours are equal
  83. // private double d_longitude = -73.53;
  84. // private double d_latitude = 41.29;
  85. // Frame counter
  86. private uint m_frame = 0;
  87. // Cached Scene reference
  88. private Scene m_scene = null;
  89. // Calculated Once in the lifetime of a region
  90. private long TicksToEpoch; // Elapsed time for 1/1/1970
  91. private uint SecondsPerSunCycle; // Length of a virtual day in RW seconds
  92. private uint SecondsPerYear; // Length of a virtual year in RW seconds
  93. private double SunSpeed; // Rate of passage in radians/second
  94. private double SeasonSpeed; // Rate of change for seasonal effects
  95. // private double HoursToRadians; // Rate of change for seasonal effects
  96. private long TicksUTCOffset = 0; // seconds offset from UTC
  97. // Calculated every update
  98. private float OrbitalPosition; // Orbital placement at a point in time
  99. private double HorizonShift; // Axis offset to skew day and night
  100. private double TotalDistanceTravelled; // Distance since beginning of time (in radians)
  101. private double SeasonalOffset; // Seaonal variation of tilt
  102. private float Magnitude; // Normal tilt
  103. // private double VWTimeRatio; // VW time as a ratio of real time
  104. // Working values
  105. private Vector3 Position = Vector3.Zero;
  106. private Vector3 Velocity = Vector3.Zero;
  107. private Quaternion Tilt = new Quaternion(1.0f, 0.0f, 0.0f, 0.0f);
  108. // Used to fix the sun in the sky so it doesn't move based on current time
  109. private bool m_SunFixed = false;
  110. private float m_SunFixedHour = 0f;
  111. private const int TICKS_PER_SECOND = 10000000;
  112. // Current time in elapsed seconds since Jan 1st 1970
  113. private ulong CurrentTime
  114. {
  115. get
  116. {
  117. return (ulong)(((DateTime.Now.Ticks) - TicksToEpoch + TicksUTCOffset) / TICKS_PER_SECOND);
  118. }
  119. }
  120. // Time in seconds since UTC to use to calculate sun position.
  121. ulong PosTime = 0;
  122. /// <summary>
  123. /// Calculate the sun's orbital position and its velocity.
  124. /// </summary>
  125. private void GenSunPos()
  126. {
  127. // Time in seconds since UTC to use to calculate sun position.
  128. PosTime = CurrentTime;
  129. if (m_SunFixed)
  130. {
  131. // SunFixedHour represents the "hour of day" we would like
  132. // It's represented in 24hr time, with 0 hour being sun-rise
  133. // Because our day length is probably not 24hrs {LL is 6} we need to do a bit of math
  134. // Determine the current "day" from current time, so we can use "today"
  135. // to determine Seasonal Tilt and what'not
  136. // Integer math rounded is on purpose to drop fractional day, determines number
  137. // of virtual days since Epoch
  138. PosTime = CurrentTime / SecondsPerSunCycle;
  139. // Since we want number of seconds since Epoch, multiply back up
  140. PosTime *= SecondsPerSunCycle;
  141. // Then offset by the current Fixed Sun Hour
  142. // Fixed Sun Hour needs to be scaled to reflect the user configured Seconds Per Sun Cycle
  143. PosTime += (ulong)((m_SunFixedHour / 24.0) * (ulong)SecondsPerSunCycle);
  144. }
  145. else
  146. {
  147. if (m_DayTimeSunHourScale != 0.5f)
  148. {
  149. ulong CurDaySeconds = CurrentTime % SecondsPerSunCycle;
  150. double CurDayPercentage = (double)CurDaySeconds / SecondsPerSunCycle;
  151. ulong DayLightSeconds = (ulong)(m_DayTimeSunHourScale * SecondsPerSunCycle);
  152. ulong NightSeconds = SecondsPerSunCycle - DayLightSeconds;
  153. PosTime = CurrentTime / SecondsPerSunCycle;
  154. PosTime *= SecondsPerSunCycle;
  155. if (CurDayPercentage < 0.5)
  156. {
  157. PosTime += (ulong)((CurDayPercentage / .5) * DayLightSeconds);
  158. }
  159. else
  160. {
  161. PosTime += DayLightSeconds;
  162. PosTime += (ulong)(((CurDayPercentage - 0.5) / .5) * NightSeconds);
  163. }
  164. }
  165. }
  166. TotalDistanceTravelled = SunSpeed * PosTime; // distance measured in radians
  167. OrbitalPosition = (float)(TotalDistanceTravelled % m_SunCycle); // position measured in radians
  168. // TotalDistanceTravelled += HoursToRadians-(0.25*Math.PI)*Math.Cos(HoursToRadians)-OrbitalPosition;
  169. // OrbitalPosition = (float) (TotalDistanceTravelled%SunCycle);
  170. SeasonalOffset = SeasonSpeed * PosTime; // Present season determined as total radians travelled around season cycle
  171. Tilt.W = (float)(m_AverageTilt + (m_SeasonalTilt * Math.Sin(SeasonalOffset))); // Calculate seasonal orbital N/S tilt
  172. // m_log.Debug("[SUN] Total distance travelled = "+TotalDistanceTravelled+", present position = "+OrbitalPosition+".");
  173. // m_log.Debug("[SUN] Total seasonal progress = "+SeasonalOffset+", present tilt = "+Tilt.W+".");
  174. // The sun rotates about the Z axis
  175. Position.X = (float)Math.Cos(-TotalDistanceTravelled);
  176. Position.Y = (float)Math.Sin(-TotalDistanceTravelled);
  177. Position.Z = 0;
  178. // For interest we rotate it slightly about the X access.
  179. // Celestial tilt is a value that ranges .025
  180. Position *= Tilt;
  181. // Finally we shift the axis so that more of the
  182. // circle is above the horizon than below. This
  183. // makes the nights shorter than the days.
  184. Position = Vector3.Normalize(Position);
  185. Position.Z = Position.Z + (float)HorizonShift;
  186. Position = Vector3.Normalize(Position);
  187. // m_log.Debug("[SUN] Position("+Position.X+","+Position.Y+","+Position.Z+")");
  188. Velocity.X = 0;
  189. Velocity.Y = 0;
  190. Velocity.Z = (float)SunSpeed;
  191. // Correct angular velocity to reflect the seasonal rotation
  192. Magnitude = Position.Length();
  193. if (m_SunFixed)
  194. {
  195. Velocity.X = 0;
  196. Velocity.Y = 0;
  197. Velocity.Z = 0;
  198. }
  199. else
  200. {
  201. Velocity = (Velocity * Tilt) * (1.0f / Magnitude);
  202. }
  203. // TODO: Decouple this, so we can get rid of Linden Hour info
  204. // Update Region infor with new Sun Position and Hour
  205. // set estate settings for region access to sun position
  206. if (receivedEstateToolsSunUpdate)
  207. {
  208. m_scene.RegionInfo.RegionSettings.SunVector = Position;
  209. m_scene.RegionInfo.RegionSettings.SunPosition = GetCurrentTimeAsLindenSunHour();
  210. }
  211. }
  212. private float GetCurrentTimeAsLindenSunHour()
  213. {
  214. if (m_SunFixed)
  215. return m_SunFixedHour + 6;
  216. return GetCurrentSunHour() + 6.0f;
  217. }
  218. #region IRegion Methods
  219. // Called immediately after the module is loaded for a given region
  220. // i.e. Immediately after instance creation.
  221. public void Initialise(Scene scene, IConfigSource config)
  222. {
  223. m_scene = scene;
  224. m_frame = 0;
  225. // This one puts an entry in the main help screen
  226. m_scene.AddCommand(this, String.Empty, "sun", "Usage: sun [param] [value] - Get or Update Sun module paramater", null);
  227. // This one enables the ability to type just "sun" without any parameters
  228. m_scene.AddCommand(this, "sun", "", "", HandleSunConsoleCommand);
  229. foreach (KeyValuePair<string, string> kvp in GetParamList())
  230. {
  231. m_scene.AddCommand(this, String.Format("sun {0}", kvp.Key), String.Format("{0} - {1}", kvp.Key, kvp.Value), "", HandleSunConsoleCommand);
  232. }
  233. TimeZone local = TimeZone.CurrentTimeZone;
  234. TicksUTCOffset = local.GetUtcOffset(local.ToLocalTime(DateTime.Now)).Ticks;
  235. m_log.Debug("[SUN]: localtime offset is " + TicksUTCOffset);
  236. // Align ticks with Second Life
  237. TicksToEpoch = new DateTime(1970, 1, 1).Ticks;
  238. // Just in case they don't have the stanzas
  239. try
  240. {
  241. // Mode: determines how the sun is handled
  242. m_RegionMode = config.Configs["Sun"].GetString("mode", d_mode);
  243. // Mode: determines how the sun is handled
  244. // m_latitude = config.Configs["Sun"].GetDouble("latitude", d_latitude);
  245. // Mode: determines how the sun is handled
  246. // m_longitude = config.Configs["Sun"].GetDouble("longitude", d_longitude);
  247. // Year length in days
  248. m_YearLengthDays = config.Configs["Sun"].GetInt("year_length", d_year_length);
  249. // Day length in decimal hours
  250. m_DayLengthHours = config.Configs["Sun"].GetDouble("day_length", d_day_length);
  251. // Horizon shift, this is used to shift the sun's orbit, this affects the day / night ratio
  252. // must hard code to ~.5 to match sun position in LL based viewers
  253. m_HorizonShift = config.Configs["Sun"].GetDouble("day_night_offset", d_day_night);
  254. // Scales the sun hours 0...12 vs 12...24, essentially makes daylight hours longer/shorter vs nighttime hours
  255. m_DayTimeSunHourScale = config.Configs["Sun"].GetDouble("day_time_sun_hour_scale", d_DayTimeSunHourScale);
  256. // Update frequency in frames
  257. m_UpdateInterval = config.Configs["Sun"].GetInt("update_interval", d_frame_mod);
  258. }
  259. catch (Exception e)
  260. {
  261. m_log.Debug("[SUN]: Configuration access failed, using defaults. Reason: " + e.Message);
  262. m_RegionMode = d_mode;
  263. m_YearLengthDays = d_year_length;
  264. m_DayLengthHours = d_day_length;
  265. m_HorizonShift = d_day_night;
  266. m_UpdateInterval = d_frame_mod;
  267. m_DayTimeSunHourScale = d_DayTimeSunHourScale;
  268. // m_latitude = d_latitude;
  269. // m_longitude = d_longitude;
  270. }
  271. switch (m_RegionMode)
  272. {
  273. case "T1":
  274. default:
  275. case "SL":
  276. // Time taken to complete a cycle (day and season)
  277. SecondsPerSunCycle = (uint) (m_DayLengthHours * 60 * 60);
  278. SecondsPerYear = (uint) (SecondsPerSunCycle*m_YearLengthDays);
  279. // Ration of real-to-virtual time
  280. // VWTimeRatio = 24/m_day_length;
  281. // Speed of rotation needed to complete a cycle in the
  282. // designated period (day and season)
  283. SunSpeed = m_SunCycle/SecondsPerSunCycle;
  284. SeasonSpeed = m_SeasonalCycle/SecondsPerYear;
  285. // Horizon translation
  286. HorizonShift = m_HorizonShift; // Z axis translation
  287. // HoursToRadians = (SunCycle/24)*VWTimeRatio;
  288. // Insert our event handling hooks
  289. scene.EventManager.OnFrame += SunUpdate;
  290. scene.EventManager.OnAvatarEnteringNewParcel += AvatarEnteringParcel;
  291. scene.EventManager.OnEstateToolsSunUpdate += EstateToolsSunUpdate;
  292. scene.EventManager.OnGetCurrentTimeAsLindenSunHour += GetCurrentTimeAsLindenSunHour;
  293. ready = true;
  294. m_log.Debug("[SUN]: Mode is " + m_RegionMode);
  295. m_log.Debug("[SUN]: Initialization completed. Day is " + SecondsPerSunCycle + " seconds, and year is " + m_YearLengthDays + " days");
  296. m_log.Debug("[SUN]: Axis offset is " + m_HorizonShift);
  297. m_log.Debug("[SUN]: Percentage of time for daylight " + m_DayTimeSunHourScale);
  298. m_log.Debug("[SUN]: Positional data updated every " + m_UpdateInterval + " frames");
  299. break;
  300. }
  301. scene.RegisterModuleInterface<ISunModule>(this);
  302. }
  303. public void PostInitialise()
  304. {
  305. }
  306. public void Close()
  307. {
  308. ready = false;
  309. // Remove our hooks
  310. m_scene.EventManager.OnFrame -= SunUpdate;
  311. m_scene.EventManager.OnAvatarEnteringNewParcel -= AvatarEnteringParcel;
  312. m_scene.EventManager.OnEstateToolsSunUpdate -= EstateToolsSunUpdate;
  313. m_scene.EventManager.OnGetCurrentTimeAsLindenSunHour -= GetCurrentTimeAsLindenSunHour;
  314. }
  315. public string Name
  316. {
  317. get { return "SunModule"; }
  318. }
  319. public bool IsSharedModule
  320. {
  321. get { return false; }
  322. }
  323. #endregion
  324. #region EventManager Events
  325. public void SunToClient(IClientAPI client)
  326. {
  327. if (m_RegionMode != "T1")
  328. {
  329. if (ready)
  330. {
  331. if (m_SunFixed)
  332. {
  333. // m_log.DebugFormat("[SUN]: SunHour {0}, Position {1}, PosTime {2}, OrbitalPosition : {3} ", m_SunFixedHour, Position.ToString(), PosTime.ToString(), OrbitalPosition.ToString());
  334. client.SendSunPos(Position, Velocity, PosTime, SecondsPerSunCycle, SecondsPerYear, OrbitalPosition);
  335. }
  336. else
  337. {
  338. // m_log.DebugFormat("[SUN]: SunHour {0}, Position {1}, PosTime {2}, OrbitalPosition : {3} ", m_SunFixedHour, Position.ToString(), PosTime.ToString(), OrbitalPosition.ToString());
  339. client.SendSunPos(Position, Velocity, CurrentTime, SecondsPerSunCycle, SecondsPerYear, OrbitalPosition);
  340. }
  341. }
  342. }
  343. }
  344. public void SunUpdate()
  345. {
  346. if (((m_frame++ % m_UpdateInterval) != 0) || !ready || m_SunFixed || !receivedEstateToolsSunUpdate)
  347. return;
  348. GenSunPos(); // Generate shared values once
  349. SunUpdateToAllClients();
  350. }
  351. /// <summary>
  352. /// When an avatar enters the region, it's probably a good idea to send them the current sun info
  353. /// </summary>
  354. /// <param name="avatar"></param>
  355. /// <param name="localLandID"></param>
  356. /// <param name="regionID"></param>
  357. private void AvatarEnteringParcel(ScenePresence avatar, int localLandID, UUID regionID)
  358. {
  359. SunToClient(avatar.ControllingClient);
  360. }
  361. /// <summary>
  362. ///
  363. /// </summary>
  364. /// <param name="regionHandle"></param>
  365. /// <param name="FixedTime">Is the sun's position fixed?</param>
  366. /// <param name="useEstateTime">Use the Region or Estate Sun hour?</param>
  367. /// <param name="FixedSunHour">What hour of the day is the Sun Fixed at?</param>
  368. public void EstateToolsSunUpdate(ulong regionHandle, bool FixedSun, bool useEstateTime, float FixedSunHour)
  369. {
  370. if (m_scene.RegionInfo.RegionHandle == regionHandle)
  371. {
  372. // Must limit the Sun Hour to 0 ... 24
  373. while (FixedSunHour > 24.0f)
  374. FixedSunHour -= 24;
  375. while (FixedSunHour < 0)
  376. FixedSunHour += 24;
  377. m_SunFixedHour = FixedSunHour;
  378. m_SunFixed = FixedSun;
  379. // m_log.DebugFormat("[SUN]: Sun Settings Update: Fixed Sun? : {0}", m_SunFixed.ToString());
  380. // m_log.DebugFormat("[SUN]: Sun Settings Update: Sun Hour : {0}", m_SunFixedHour.ToString());
  381. receivedEstateToolsSunUpdate = true;
  382. // Generate shared values
  383. GenSunPos();
  384. // When sun settings are updated, we should update all clients with new settings.
  385. SunUpdateToAllClients();
  386. // m_log.DebugFormat("[SUN]: PosTime : {0}", PosTime.ToString());
  387. }
  388. }
  389. #endregion
  390. private void SunUpdateToAllClients()
  391. {
  392. m_scene.ForEachScenePresence(delegate(ScenePresence sp)
  393. {
  394. if (!sp.IsChildAgent)
  395. {
  396. SunToClient(sp.ControllingClient);
  397. }
  398. });
  399. }
  400. #region ISunModule Members
  401. public double GetSunParameter(string param)
  402. {
  403. switch (param.ToLower())
  404. {
  405. case "year_length":
  406. return m_YearLengthDays;
  407. case "day_length":
  408. return m_DayLengthHours;
  409. case "day_night_offset":
  410. return m_HorizonShift;
  411. case "day_time_sun_hour_scale":
  412. return m_DayTimeSunHourScale;
  413. case "update_interval":
  414. return m_UpdateInterval;
  415. default:
  416. throw new Exception("Unknown sun parameter.");
  417. }
  418. }
  419. public void SetSunParameter(string param, double value)
  420. {
  421. HandleSunConsoleCommand("sun", new string[] {param, value.ToString() });
  422. }
  423. public float GetCurrentSunHour()
  424. {
  425. float ticksleftover = CurrentTime % SecondsPerSunCycle;
  426. return (24.0f * (ticksleftover / SecondsPerSunCycle));
  427. }
  428. #endregion
  429. public void HandleSunConsoleCommand(string module, string[] cmdparams)
  430. {
  431. if (m_scene.ConsoleScene() == null)
  432. {
  433. // FIXME: If console region is root then this will be printed by every module. Currently, there is no
  434. // way to prevent this, short of making the entire module shared (which is complete overkill).
  435. // One possibility is to return a bool to signal whether the module has completely handled the command
  436. m_log.InfoFormat("[Sun]: Please change to a specific region in order to set Sun parameters.");
  437. return;
  438. }
  439. if (m_scene.ConsoleScene() != m_scene)
  440. {
  441. m_log.InfoFormat("[Sun]: Console Scene is not my scene.");
  442. return;
  443. }
  444. m_log.InfoFormat("[Sun]: Processing command.");
  445. foreach (string output in ParseCmdParams(cmdparams))
  446. {
  447. m_log.Info("[SUN] " + output);
  448. }
  449. }
  450. private Dictionary<string, string> GetParamList()
  451. {
  452. Dictionary<string, string> Params = new Dictionary<string, string>();
  453. Params.Add("year_length", "number of days to a year");
  454. Params.Add("day_length", "number of seconds to a day");
  455. Params.Add("day_night_offset", "induces a horizon shift");
  456. Params.Add("update_interval", "how often to update the sun's position in frames");
  457. Params.Add("day_time_sun_hour_scale", "scales day light vs nite hours to change day/night ratio");
  458. return Params;
  459. }
  460. private List<string> ParseCmdParams(string[] args)
  461. {
  462. List<string> Output = new List<string>();
  463. if ((args.Length == 1) || (args[1].ToLower() == "help") || (args[1].ToLower() == "list"))
  464. {
  465. Output.Add("The following parameters can be changed or viewed:");
  466. foreach (KeyValuePair<string, string> kvp in GetParamList())
  467. {
  468. Output.Add(String.Format("{0} - {1}",kvp.Key, kvp.Value));
  469. }
  470. return Output;
  471. }
  472. if (args.Length == 2)
  473. {
  474. try
  475. {
  476. double value = GetSunParameter(args[1]);
  477. Output.Add(String.Format("Parameter {0} is {1}.", args[1], value.ToString()));
  478. }
  479. catch (Exception)
  480. {
  481. Output.Add(String.Format("Unknown parameter {0}.", args[1]));
  482. }
  483. }
  484. else if (args.Length == 3)
  485. {
  486. float value = 0.0f;
  487. if (!float.TryParse(args[2], out value))
  488. {
  489. Output.Add(String.Format("The parameter value {0} is not a valid number.", args[2]));
  490. }
  491. switch (args[1].ToLower())
  492. {
  493. case "year_length":
  494. m_YearLengthDays = (int)value;
  495. break;
  496. case "day_length":
  497. m_DayLengthHours = value;
  498. break;
  499. case "day_night_offset":
  500. m_HorizonShift = value;
  501. break;
  502. case "day_time_sun_hour_scale":
  503. m_DayTimeSunHourScale = value;
  504. break;
  505. case "update_interval":
  506. m_UpdateInterval = (int)value;
  507. break;
  508. default:
  509. Output.Add(String.Format("Unknown parameter {0}.", args[1]));
  510. return Output;
  511. }
  512. Output.Add(String.Format("Parameter {0} set to {1}.", args[1], value.ToString()));
  513. // Generate shared values
  514. GenSunPos();
  515. // When sun settings are updated, we should update all clients with new settings.
  516. SunUpdateToAllClients();
  517. }
  518. return Output;
  519. }
  520. }
  521. }