SunModule.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439
  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.Info("[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_log.Debug("[SUN] Initializing");
  131. m_scene = scene;
  132. m_frame = 0;
  133. TimeZone local = TimeZone.CurrentTimeZone;
  134. TicksOffset = local.GetUtcOffset(local.ToLocalTime(DateTime.Now)).Ticks;
  135. m_log.Debug("[SUN] localtime offset is " + TicksOffset);
  136. // Align ticks with Second Life
  137. TicksToEpoch = new System.DateTime(1970,1,1).Ticks;
  138. // Just in case they don't have the stanzas
  139. try
  140. {
  141. // Mode: determines how the sun is handled
  142. m_mode = config.Configs["Sun"].GetString("mode", d_mode);
  143. // Mode: determines how the sun is handled
  144. // m_latitude = config.Configs["Sun"].GetDouble("latitude", d_latitude);
  145. // Mode: determines how the sun is handled
  146. // m_longitude = config.Configs["Sun"].GetDouble("longitude", d_longitude);
  147. // Year length in days
  148. m_year_length = config.Configs["Sun"].GetInt("year_length", d_year_length);
  149. // Day length in decimal hours
  150. m_day_length = config.Configs["Sun"].GetDouble("day_length", d_day_length);
  151. // Day to Night Ratio
  152. m_day_night = config.Configs["Sun"].GetDouble("day_night_offset", d_day_night);
  153. // Update frequency in frames
  154. m_frame_mod = config.Configs["Sun"].GetInt("update_interval", d_frame_mod);
  155. }
  156. catch (Exception e)
  157. {
  158. m_log.Debug("[SUN] Configuration access failed, using defaults. Reason: "+e.Message);
  159. m_mode = d_mode;
  160. m_year_length = d_year_length;
  161. m_day_length = d_day_length;
  162. m_day_night = d_day_night;
  163. m_frame_mod = d_frame_mod;
  164. // m_latitude = d_latitude;
  165. // m_longitude = d_longitude;
  166. }
  167. switch (m_mode)
  168. {
  169. case "T1":
  170. default:
  171. case "SL":
  172. // Time taken to complete a cycle (day and season)
  173. SecondsPerSunCycle = (uint) (m_day_length * 60 * 60);
  174. SecondsPerYear = (uint) (SecondsPerSunCycle*m_year_length);
  175. // Ration of real-to-virtual time
  176. // VWTimeRatio = 24/m_day_length;
  177. // Speed of rotation needed to complete a cycle in the
  178. // designated period (day and season)
  179. SunSpeed = SunCycle/SecondsPerSunCycle;
  180. SeasonSpeed = SeasonalCycle/SecondsPerYear;
  181. // Horizon translation
  182. HorizonShift = m_day_night; // Z axis translation
  183. // HoursToRadians = (SunCycle/24)*VWTimeRatio;
  184. // Insert our event handling hooks
  185. scene.EventManager.OnFrame += SunUpdate;
  186. //scene.EventManager.OnNewClient += SunToClient;
  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.OnNewClient -= SunToClient;
  209. m_scene.EventManager.OnMakeChildAgent -= MakeChildAgent;
  210. m_scene.EventManager.OnAvatarEnteringNewParcel -= AvatarEnteringParcel;
  211. m_scene.EventManager.OnClientClosed -= ClientLoggedOut;
  212. m_scene.EventManager.OnEstateToolsTimeUpdate -= EstateToolsTimeUpdate;
  213. m_scene.EventManager.OnGetSunLindenHour -= GetLindenEstateHourFromCurrentTime;
  214. }
  215. public string Name
  216. {
  217. get { return "SunModule"; }
  218. }
  219. public bool IsSharedModule
  220. {
  221. get { return false; }
  222. }
  223. public void SunToClient(IClientAPI client)
  224. {
  225. if (m_mode != "T1")
  226. {
  227. if (ready)
  228. {
  229. if (!sunFixed)
  230. GenSunPos(); // Generate shared values once
  231. client.SendSunPos(Position, Velocity, CurrentTime, SecondsPerSunCycle, SecondsPerYear, OrbitalPosition);
  232. m_log.Debug("[SUN] Initial update for new client");
  233. }
  234. }
  235. }
  236. public void SunUpdate()
  237. {
  238. if (((m_frame++%m_frame_mod) != 0) || !ready || sunFixed)
  239. {
  240. return;
  241. }
  242. GenSunPos(); // Generate shared values once
  243. List<ScenePresence> avatars = m_scene.GetAvatars();
  244. foreach (ScenePresence avatar in avatars)
  245. {
  246. if (!avatar.IsChildAgent)
  247. avatar.ControllingClient.SendSunPos(Position, Velocity, CurrentTime, SecondsPerSunCycle, SecondsPerYear, OrbitalPosition);
  248. }
  249. // set estate settings for region access to sun position
  250. m_scene.RegionInfo.RegionSettings.SunVector = Position;
  251. //m_scene.RegionInfo.EstateSettings.sunHour = GetLindenEstateHourFromCurrentTime();
  252. }
  253. public void ForceSunUpdateToAllClients()
  254. {
  255. GenSunPos(); // Generate shared values once
  256. List<ScenePresence> avatars = m_scene.GetAvatars();
  257. foreach (ScenePresence avatar in avatars)
  258. {
  259. if (!avatar.IsChildAgent)
  260. avatar.ControllingClient.SendSunPos(Position, Velocity, CurrentTime, SecondsPerSunCycle, SecondsPerYear, OrbitalPosition);
  261. }
  262. // set estate settings for region access to sun position
  263. m_scene.RegionInfo.RegionSettings.SunVector = Position;
  264. m_scene.RegionInfo.RegionSettings.SunPosition = GetLindenEstateHourFromCurrentTime();
  265. }
  266. /// <summary>
  267. /// Calculate the sun's orbital position and its velocity.
  268. /// </summary>
  269. private void GenSunPos()
  270. {
  271. TotalDistanceTravelled = SunSpeed * CurrentTime; // distance measured in radians
  272. OrbitalPosition = (float) (TotalDistanceTravelled%SunCycle); // position measured in radians
  273. // TotalDistanceTravelled += HoursToRadians-(0.25*Math.PI)*Math.Cos(HoursToRadians)-OrbitalPosition;
  274. // OrbitalPosition = (float) (TotalDistanceTravelled%SunCycle);
  275. SeasonalOffset = SeasonSpeed * CurrentTime; // Present season determined as total radians travelled around season cycle
  276. Tilt.W = (float) (AverageTilt + (SeasonalTilt*Math.Sin(SeasonalOffset))); // Calculate seasonal orbital N/S tilt
  277. // m_log.Debug("[SUN] Total distance travelled = "+TotalDistanceTravelled+", present position = "+OrbitalPosition+".");
  278. // m_log.Debug("[SUN] Total seasonal progress = "+SeasonalOffset+", present tilt = "+Tilt.W+".");
  279. // The sun rotates about the Z axis
  280. Position.X = (float) Math.Cos(-TotalDistanceTravelled);
  281. Position.Y = (float) Math.Sin(-TotalDistanceTravelled);
  282. Position.Z = 0;
  283. // For interest we rotate it slightly about the X access.
  284. // Celestial tilt is a value that ranges .025
  285. Position *= Tilt;
  286. // Finally we shift the axis so that more of the
  287. // circle is above the horizon than below. This
  288. // makes the nights shorter than the days.
  289. Position.Z = Position.Z + (float) HorizonShift;
  290. Position = Vector3.Normalize(Position);
  291. // m_log.Debug("[SUN] Position("+Position.X+","+Position.Y+","+Position.Z+")");
  292. Velocity.X = 0;
  293. Velocity.Y = 0;
  294. Velocity.Z = (float) SunSpeed;
  295. // Correct angular velocity to reflect the seasonal rotation
  296. Magnitude = Position.Length();
  297. if (sunFixed)
  298. {
  299. Velocity.X = 0;
  300. Velocity.Y = 0;
  301. Velocity.Z = 0;
  302. return;
  303. }
  304. Velocity = (Velocity * Tilt) * (1.0f / Magnitude);
  305. // m_log.Debug("[SUN] Velocity("+Velocity.X+","+Velocity.Y+","+Velocity.Z+")");
  306. }
  307. private void ClientLoggedOut(UUID AgentId)
  308. {
  309. lock (m_rootAgents)
  310. {
  311. if (m_rootAgents.ContainsKey(AgentId))
  312. {
  313. m_rootAgents.Remove(AgentId);
  314. m_log.Info("[SUN]: Removing " + AgentId + ". Agent logged out.");
  315. }
  316. }
  317. }
  318. private void AvatarEnteringParcel(ScenePresence avatar, int localLandID, UUID regionID)
  319. {
  320. lock (m_rootAgents)
  321. {
  322. if (m_rootAgents.ContainsKey(avatar.UUID))
  323. {
  324. m_rootAgents[avatar.UUID] = avatar.RegionHandle;
  325. }
  326. else
  327. {
  328. m_rootAgents.Add(avatar.UUID, avatar.RegionHandle);
  329. SunToClient(avatar.ControllingClient);
  330. }
  331. }
  332. //m_log.Info("[FRIEND]: " + avatar.Name + " status:" + (!avatar.IsChildAgent).ToString());
  333. }
  334. private void MakeChildAgent(ScenePresence avatar)
  335. {
  336. lock (m_rootAgents)
  337. {
  338. if (m_rootAgents.ContainsKey(avatar.UUID))
  339. {
  340. if (m_rootAgents[avatar.UUID] == avatar.RegionHandle)
  341. {
  342. m_rootAgents.Remove(avatar.UUID);
  343. }
  344. }
  345. }
  346. }
  347. public void EstateToolsTimeUpdate(ulong regionHandle, bool FixedTime, bool useEstateTime, float LindenHour)
  348. {
  349. if (m_scene.RegionInfo.RegionHandle == regionHandle)
  350. {
  351. SetTimeByLindenHour(LindenHour);
  352. //if (useEstateTime)
  353. //LindenHourOffset = 0;
  354. ForceSunUpdateToAllClients();
  355. sunFixed = FixedTime;
  356. if (sunFixed)
  357. GenSunPos();
  358. }
  359. }
  360. }
  361. }