SunModule.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436
  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 OpenSim 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 : IRegionModule
  39. {
  40. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  41. private const double SeasonalTilt = 0.03 * Math.PI; // A daily shift of approximately 1.7188 degrees
  42. private const double AverageTilt = -0.25 * Math.PI; // A 45 degree tilt
  43. private const double SunCycle = 2.0D * Math.PI; // A perfect circle measured in radians
  44. private const double SeasonalCycle = 2.0D * Math.PI; // Ditto
  45. //
  46. // Per Region Values
  47. //
  48. private bool ready = false;
  49. // Configurable values
  50. private string m_mode = "SL";
  51. private int m_frame_mod = 0;
  52. private double m_day_length = 0;
  53. private int m_year_length = 0;
  54. private double m_day_night = 0;
  55. // private double m_longitude = 0;
  56. // private double m_latitude = 0;
  57. // Configurable defaults Defaults close to SL
  58. private string d_mode = "SL";
  59. private int d_frame_mod = 100; // Every 10 seconds (actually less)
  60. private double d_day_length = 4; // A VW day is 4 RW hours long
  61. private int d_year_length = 60; // There are 60 VW days in a VW year
  62. private double d_day_night = 0.45; // axis offset: ratio of light-to-dark, approx 1:3
  63. // private double d_longitude = -73.53;
  64. // private double d_latitude = 41.29;
  65. // Frame counter
  66. private uint m_frame = 0;
  67. // Cached Scene reference
  68. private Scene m_scene = null;
  69. // Calculated Once in the lifetime of a region
  70. private long TicksToEpoch; // Elapsed time for 1/1/1970
  71. private uint SecondsPerSunCycle; // Length of a virtual day in RW seconds
  72. private uint SecondsPerYear; // Length of a virtual year in RW seconds
  73. private double SunSpeed; // Rate of passage in radians/second
  74. private double SeasonSpeed; // Rate of change for seasonal effects
  75. // private double HoursToRadians; // Rate of change for seasonal effects
  76. private long TicksOffset = 0; // seconds offset from UTC
  77. // Calculated every update
  78. private float OrbitalPosition; // Orbital placement at a point in time
  79. private double HorizonShift; // Axis offset to skew day and night
  80. private double TotalDistanceTravelled; // Distance since beginning of time (in radians)
  81. private double SeasonalOffset; // Seaonal variation of tilt
  82. private float Magnitude; // Normal tilt
  83. // private double VWTimeRatio; // VW time as a ratio of real time
  84. // Working values
  85. private Vector3 Position = Vector3.Zero;
  86. private Vector3 Velocity = Vector3.Zero;
  87. private Quaternion Tilt = new Quaternion(1.0f, 0.0f, 0.0f, 0.0f);
  88. private long LindenHourOffset = 0;
  89. private bool sunFixed = false;
  90. private Dictionary<UUID, ulong> m_rootAgents = new Dictionary<UUID, ulong>();
  91. // Current time in elapsed seconds since Jan 1st 1970
  92. private ulong CurrentTime
  93. {
  94. get {
  95. return (ulong)(((DateTime.Now.Ticks) - TicksToEpoch + TicksOffset + LindenHourOffset)/10000000);
  96. }
  97. }
  98. private float GetLindenEstateHourFromCurrentTime()
  99. {
  100. float ticksleftover = ((float)CurrentTime) % ((float)SecondsPerSunCycle);
  101. float hour = (24 * (ticksleftover / SecondsPerSunCycle)) + 6;
  102. return hour;
  103. }
  104. private void SetTimeByLindenHour(float LindenHour)
  105. {
  106. // Linden hour is 24 hours with a 6 hour offset. 6-30
  107. if (LindenHour - 6 == 0)
  108. {
  109. LindenHourOffset = 0;
  110. return;
  111. }
  112. // Remove LindenHourOffset to calculate it from LocalTime
  113. float ticksleftover = ((float)(((long)(CurrentTime * 10000000) - (long)LindenHourOffset)/ 10000000) % ((float)SecondsPerSunCycle));
  114. float hour = (24 * (ticksleftover / SecondsPerSunCycle));
  115. float offsethours = 0;
  116. if (LindenHour - 6 > hour)
  117. {
  118. offsethours = hour + ((LindenHour-6) - hour);
  119. }
  120. else
  121. {
  122. offsethours = hour - (hour - (LindenHour - 6));
  123. }
  124. //m_log.Debug("[OFFSET]: " + hour + " - " + LindenHour + " - " + offsethours.ToString());
  125. LindenHourOffset = (long)((float)offsethours * (36000000000/m_day_length));
  126. m_log.Debug("[SUN]: Directive from the Estate Tools to set the sun phase to LindenHour " + GetLindenEstateHourFromCurrentTime().ToString());
  127. }
  128. // Called immediately after the module is loaded for a given region
  129. // i.e. Immediately after instance creation.
  130. public void Initialise(Scene scene, IConfigSource config)
  131. {
  132. m_scene = scene;
  133. m_frame = 0;
  134. TimeZone local = TimeZone.CurrentTimeZone;
  135. TicksOffset = local.GetUtcOffset(local.ToLocalTime(DateTime.Now)).Ticks;
  136. m_log.Debug("[SUN]: localtime offset is " + TicksOffset);
  137. // Align ticks with Second Life
  138. TicksToEpoch = new DateTime(1970,1,1).Ticks;
  139. // Just in case they don't have the stanzas
  140. try
  141. {
  142. // Mode: determines how the sun is handled
  143. m_mode = config.Configs["Sun"].GetString("mode", d_mode);
  144. // Mode: determines how the sun is handled
  145. // m_latitude = config.Configs["Sun"].GetDouble("latitude", d_latitude);
  146. // Mode: determines how the sun is handled
  147. // m_longitude = config.Configs["Sun"].GetDouble("longitude", d_longitude);
  148. // Year length in days
  149. m_year_length = config.Configs["Sun"].GetInt("year_length", d_year_length);
  150. // Day length in decimal hours
  151. m_day_length = config.Configs["Sun"].GetDouble("day_length", d_day_length);
  152. // Day to Night Ratio
  153. m_day_night = config.Configs["Sun"].GetDouble("day_night_offset", d_day_night);
  154. // Update frequency in frames
  155. m_frame_mod = config.Configs["Sun"].GetInt("update_interval", d_frame_mod);
  156. }
  157. catch (Exception e)
  158. {
  159. m_log.Debug("[SUN]: Configuration access failed, using defaults. Reason: "+e.Message);
  160. m_mode = d_mode;
  161. m_year_length = d_year_length;
  162. m_day_length = d_day_length;
  163. m_day_night = d_day_night;
  164. m_frame_mod = d_frame_mod;
  165. // m_latitude = d_latitude;
  166. // m_longitude = d_longitude;
  167. }
  168. switch (m_mode)
  169. {
  170. case "T1":
  171. default:
  172. case "SL":
  173. // Time taken to complete a cycle (day and season)
  174. SecondsPerSunCycle = (uint) (m_day_length * 60 * 60);
  175. SecondsPerYear = (uint) (SecondsPerSunCycle*m_year_length);
  176. // Ration of real-to-virtual time
  177. // VWTimeRatio = 24/m_day_length;
  178. // Speed of rotation needed to complete a cycle in the
  179. // designated period (day and season)
  180. SunSpeed = SunCycle/SecondsPerSunCycle;
  181. SeasonSpeed = SeasonalCycle/SecondsPerYear;
  182. // Horizon translation
  183. HorizonShift = m_day_night; // Z axis translation
  184. // HoursToRadians = (SunCycle/24)*VWTimeRatio;
  185. // Insert our event handling hooks
  186. scene.EventManager.OnFrame += SunUpdate;
  187. scene.EventManager.OnMakeChildAgent += MakeChildAgent;
  188. scene.EventManager.OnAvatarEnteringNewParcel += AvatarEnteringParcel;
  189. scene.EventManager.OnClientClosed += ClientLoggedOut;
  190. scene.EventManager.OnEstateToolsTimeUpdate += EstateToolsTimeUpdate;
  191. scene.EventManager.OnGetSunLindenHour += GetLindenEstateHourFromCurrentTime;
  192. ready = true;
  193. m_log.Debug("[SUN]: Mode is "+m_mode);
  194. m_log.Debug("[SUN]: Initialization completed. Day is "+SecondsPerSunCycle+" seconds, and year is "+m_year_length+" days");
  195. m_log.Debug("[SUN]: Axis offset is "+m_day_night);
  196. m_log.Debug("[SUN]: Positional data updated every "+m_frame_mod+" frames");
  197. break;
  198. }
  199. }
  200. public void PostInitialise()
  201. {
  202. }
  203. public void Close()
  204. {
  205. ready = false;
  206. // Remove our hooks
  207. m_scene.EventManager.OnFrame -= SunUpdate;
  208. m_scene.EventManager.OnMakeChildAgent -= MakeChildAgent;
  209. m_scene.EventManager.OnAvatarEnteringNewParcel -= AvatarEnteringParcel;
  210. m_scene.EventManager.OnClientClosed -= ClientLoggedOut;
  211. m_scene.EventManager.OnEstateToolsTimeUpdate -= EstateToolsTimeUpdate;
  212. m_scene.EventManager.OnGetSunLindenHour -= GetLindenEstateHourFromCurrentTime;
  213. }
  214. public string Name
  215. {
  216. get { return "SunModule"; }
  217. }
  218. public bool IsSharedModule
  219. {
  220. get { return false; }
  221. }
  222. public void SunToClient(IClientAPI client)
  223. {
  224. if (m_mode != "T1")
  225. {
  226. if (ready)
  227. {
  228. if (!sunFixed)
  229. GenSunPos(); // Generate shared values once
  230. client.SendSunPos(Position, Velocity, CurrentTime, SecondsPerSunCycle, SecondsPerYear, OrbitalPosition);
  231. }
  232. }
  233. }
  234. public void SunUpdate()
  235. {
  236. if (((m_frame++%m_frame_mod) != 0) || !ready || sunFixed)
  237. {
  238. return;
  239. }
  240. GenSunPos(); // Generate shared values once
  241. List<ScenePresence> avatars = m_scene.GetAvatars();
  242. foreach (ScenePresence avatar in avatars)
  243. {
  244. if (!avatar.IsChildAgent)
  245. avatar.ControllingClient.SendSunPos(Position, Velocity, CurrentTime, SecondsPerSunCycle, SecondsPerYear, OrbitalPosition);
  246. }
  247. // set estate settings for region access to sun position
  248. m_scene.RegionInfo.RegionSettings.SunVector = Position;
  249. //m_scene.RegionInfo.EstateSettings.sunHour = GetLindenEstateHourFromCurrentTime();
  250. }
  251. public void ForceSunUpdateToAllClients()
  252. {
  253. GenSunPos(); // Generate shared values once
  254. List<ScenePresence> avatars = m_scene.GetAvatars();
  255. foreach (ScenePresence avatar in avatars)
  256. {
  257. if (!avatar.IsChildAgent)
  258. avatar.ControllingClient.SendSunPos(Position, Velocity, CurrentTime, SecondsPerSunCycle, SecondsPerYear, OrbitalPosition);
  259. }
  260. // set estate settings for region access to sun position
  261. m_scene.RegionInfo.RegionSettings.SunVector = Position;
  262. m_scene.RegionInfo.RegionSettings.SunPosition = GetLindenEstateHourFromCurrentTime();
  263. }
  264. /// <summary>
  265. /// Calculate the sun's orbital position and its velocity.
  266. /// </summary>
  267. private void GenSunPos()
  268. {
  269. TotalDistanceTravelled = SunSpeed * CurrentTime; // distance measured in radians
  270. OrbitalPosition = (float) (TotalDistanceTravelled%SunCycle); // position measured in radians
  271. // TotalDistanceTravelled += HoursToRadians-(0.25*Math.PI)*Math.Cos(HoursToRadians)-OrbitalPosition;
  272. // OrbitalPosition = (float) (TotalDistanceTravelled%SunCycle);
  273. SeasonalOffset = SeasonSpeed * CurrentTime; // Present season determined as total radians travelled around season cycle
  274. Tilt.W = (float) (AverageTilt + (SeasonalTilt*Math.Sin(SeasonalOffset))); // Calculate seasonal orbital N/S tilt
  275. // m_log.Debug("[SUN] Total distance travelled = "+TotalDistanceTravelled+", present position = "+OrbitalPosition+".");
  276. // m_log.Debug("[SUN] Total seasonal progress = "+SeasonalOffset+", present tilt = "+Tilt.W+".");
  277. // The sun rotates about the Z axis
  278. Position.X = (float) Math.Cos(-TotalDistanceTravelled);
  279. Position.Y = (float) Math.Sin(-TotalDistanceTravelled);
  280. Position.Z = 0;
  281. // For interest we rotate it slightly about the X access.
  282. // Celestial tilt is a value that ranges .025
  283. Position *= Tilt;
  284. // Finally we shift the axis so that more of the
  285. // circle is above the horizon than below. This
  286. // makes the nights shorter than the days.
  287. Position.Z = Position.Z + (float) HorizonShift;
  288. Position = Vector3.Normalize(Position);
  289. // m_log.Debug("[SUN] Position("+Position.X+","+Position.Y+","+Position.Z+")");
  290. Velocity.X = 0;
  291. Velocity.Y = 0;
  292. Velocity.Z = (float) SunSpeed;
  293. // Correct angular velocity to reflect the seasonal rotation
  294. Magnitude = Position.Length();
  295. if (sunFixed)
  296. {
  297. Velocity.X = 0;
  298. Velocity.Y = 0;
  299. Velocity.Z = 0;
  300. return;
  301. }
  302. Velocity = (Velocity * Tilt) * (1.0f / Magnitude);
  303. // m_log.Debug("[SUN] Velocity("+Velocity.X+","+Velocity.Y+","+Velocity.Z+")");
  304. }
  305. private void ClientLoggedOut(UUID AgentId)
  306. {
  307. lock (m_rootAgents)
  308. {
  309. if (m_rootAgents.ContainsKey(AgentId))
  310. {
  311. m_rootAgents.Remove(AgentId);
  312. }
  313. }
  314. }
  315. private void AvatarEnteringParcel(ScenePresence avatar, int localLandID, UUID regionID)
  316. {
  317. lock (m_rootAgents)
  318. {
  319. if (m_rootAgents.ContainsKey(avatar.UUID))
  320. {
  321. m_rootAgents[avatar.UUID] = avatar.RegionHandle;
  322. }
  323. else
  324. {
  325. m_rootAgents.Add(avatar.UUID, avatar.RegionHandle);
  326. SunToClient(avatar.ControllingClient);
  327. }
  328. }
  329. //m_log.Info("[FRIEND]: " + avatar.Name + " status:" + (!avatar.IsChildAgent).ToString());
  330. }
  331. private void MakeChildAgent(ScenePresence avatar)
  332. {
  333. lock (m_rootAgents)
  334. {
  335. if (m_rootAgents.ContainsKey(avatar.UUID))
  336. {
  337. if (m_rootAgents[avatar.UUID] == avatar.RegionHandle)
  338. {
  339. m_rootAgents.Remove(avatar.UUID);
  340. }
  341. }
  342. }
  343. }
  344. public void EstateToolsTimeUpdate(ulong regionHandle, bool FixedTime, bool useEstateTime, float LindenHour)
  345. {
  346. if (m_scene.RegionInfo.RegionHandle == regionHandle)
  347. {
  348. SetTimeByLindenHour(LindenHour);
  349. //if (useEstateTime)
  350. //LindenHourOffset = 0;
  351. ForceSunUpdateToAllClients();
  352. sunFixed = FixedTime;
  353. if (sunFixed)
  354. GenSunPos();
  355. }
  356. }
  357. }
  358. }