SunModule.cs 18 KB

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