TreePopulatorModule.cs 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774
  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 System.Timers;
  31. using OpenMetaverse;
  32. using log4net;
  33. using Nini.Config;
  34. using OpenSim.Framework;
  35. using OpenSim.Region.CoreModules.Framework.InterfaceCommander;
  36. using OpenSim.Region.Framework.Interfaces;
  37. using OpenSim.Region.Framework.Scenes;
  38. using System.Xml;
  39. using System.Xml.Serialization;
  40. using System.IO;
  41. namespace OpenSim.Region.OptionalModules.World.TreePopulator
  42. {
  43. /// <summary>
  44. /// Version 2.02 - Still hacky
  45. /// </summary>
  46. public class TreePopulatorModule : IRegionModule, ICommandableModule, IVegetationModule
  47. {
  48. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  49. private readonly Commander m_commander = new Commander("tree");
  50. private Scene m_scene;
  51. [XmlRootAttribute(ElementName = "Copse", IsNullable = false)]
  52. public class Copse
  53. {
  54. public string m_name;
  55. public Boolean m_frozen;
  56. public Tree m_tree_type;
  57. public int m_tree_quantity;
  58. public float m_treeline_low;
  59. public float m_treeline_high;
  60. public Vector3 m_seed_point;
  61. public double m_range;
  62. public Vector3 m_initial_scale;
  63. public Vector3 m_maximum_scale;
  64. public Vector3 m_rate;
  65. [XmlIgnore]
  66. public Boolean m_planted;
  67. [XmlIgnore]
  68. public List<UUID> m_trees;
  69. public Copse()
  70. {
  71. }
  72. public Copse(string fileName, Boolean planted)
  73. {
  74. Copse cp = (Copse)DeserializeObject(fileName);
  75. this.m_name = cp.m_name;
  76. this.m_frozen = cp.m_frozen;
  77. this.m_tree_quantity = cp.m_tree_quantity;
  78. this.m_treeline_high = cp.m_treeline_high;
  79. this.m_treeline_low = cp.m_treeline_low;
  80. this.m_range = cp.m_range;
  81. this.m_tree_type = cp.m_tree_type;
  82. this.m_seed_point = cp.m_seed_point;
  83. this.m_initial_scale = cp.m_initial_scale;
  84. this.m_maximum_scale = cp.m_maximum_scale;
  85. this.m_initial_scale = cp.m_initial_scale;
  86. this.m_rate = cp.m_rate;
  87. this.m_planted = planted;
  88. this.m_trees = new List<UUID>();
  89. }
  90. public Copse(string copsedef)
  91. {
  92. char[] delimiterChars = {':', ';'};
  93. string[] field = copsedef.Split(delimiterChars);
  94. this.m_name = field[1].Trim();
  95. this.m_frozen = (copsedef[0] == 'F');
  96. this.m_tree_quantity = int.Parse(field[2]);
  97. this.m_treeline_high = float.Parse(field[3], Culture.NumberFormatInfo);
  98. this.m_treeline_low = float.Parse(field[4], Culture.NumberFormatInfo);
  99. this.m_range = double.Parse(field[5], Culture.NumberFormatInfo);
  100. this.m_tree_type = (Tree) Enum.Parse(typeof(Tree),field[6]);
  101. this.m_seed_point = Vector3.Parse(field[7]);
  102. this.m_initial_scale = Vector3.Parse(field[8]);
  103. this.m_maximum_scale = Vector3.Parse(field[9]);
  104. this.m_rate = Vector3.Parse(field[10]);
  105. this.m_planted = true;
  106. this.m_trees = new List<UUID>();
  107. }
  108. public Copse(string name, int quantity, float high, float low, double range, Vector3 point, Tree type, Vector3 scale, Vector3 max_scale, Vector3 rate, List<UUID> trees)
  109. {
  110. this.m_name = name;
  111. this.m_frozen = false;
  112. this.m_tree_quantity = quantity;
  113. this.m_treeline_high = high;
  114. this.m_treeline_low = low;
  115. this.m_range = range;
  116. this.m_tree_type = type;
  117. this.m_seed_point = point;
  118. this.m_initial_scale = scale;
  119. this.m_maximum_scale = max_scale;
  120. this.m_rate = rate;
  121. this.m_planted = false;
  122. this.m_trees = trees;
  123. }
  124. public override string ToString()
  125. {
  126. string frozen = (this.m_frozen ? "F" : "A");
  127. return string.Format("{0}TPM: {1}; {2}; {3:0.0}; {4:0.0}; {5:0.0}; {6}; {7:0.0}; {8:0.0}; {9:0.0}; {10:0.00};",
  128. frozen,
  129. this.m_name,
  130. this.m_tree_quantity,
  131. this.m_treeline_high,
  132. this.m_treeline_low,
  133. this.m_range,
  134. this.m_tree_type,
  135. this.m_seed_point.ToString(),
  136. this.m_initial_scale.ToString(),
  137. this.m_maximum_scale.ToString(),
  138. this.m_rate.ToString());
  139. }
  140. }
  141. private List<Copse> m_copse;
  142. private double m_update_ms = 1000.0; // msec between updates
  143. private bool m_active_trees = false;
  144. Timer CalculateTrees;
  145. #region ICommandableModule Members
  146. public ICommander CommandInterface
  147. {
  148. get { return m_commander; }
  149. }
  150. #endregion
  151. #region IRegionModule Members
  152. public void Initialise(Scene scene, IConfigSource config)
  153. {
  154. m_scene = scene;
  155. m_scene.RegisterModuleInterface<IRegionModule>(this);
  156. m_scene.EventManager.OnPluginConsole += EventManager_OnPluginConsole;
  157. // ini file settings
  158. try
  159. {
  160. m_active_trees = config.Configs["Trees"].GetBoolean("active_trees", m_active_trees);
  161. }
  162. catch (Exception)
  163. {
  164. m_log.Debug("[TREES]: ini failure for active_trees - using default");
  165. }
  166. try
  167. {
  168. m_update_ms = config.Configs["Trees"].GetDouble("update_rate", m_update_ms);
  169. }
  170. catch (Exception)
  171. {
  172. m_log.Debug("[TREES]: ini failure for update_rate - using default");
  173. }
  174. InstallCommands();
  175. m_log.Debug("[TREES]: Initialised tree module");
  176. }
  177. public void PostInitialise()
  178. {
  179. ReloadCopse();
  180. if (m_copse.Count > 0)
  181. m_log.Info("[TREES]: Copse load complete");
  182. if (m_active_trees)
  183. activeizeTreeze(true);
  184. }
  185. public void Close()
  186. {
  187. }
  188. public string Name
  189. {
  190. get { return "TreePopulatorModule"; }
  191. }
  192. public bool IsSharedModule
  193. {
  194. get { return false; }
  195. }
  196. #endregion
  197. //--------------------------------------------------------------
  198. #region ICommandableModule Members
  199. private void HandleTreeActive(Object[] args)
  200. {
  201. if ((Boolean)args[0] && !m_active_trees)
  202. {
  203. m_log.InfoFormat("[TREES]: Activating Trees");
  204. m_active_trees = true;
  205. activeizeTreeze(m_active_trees);
  206. }
  207. else if (!(Boolean)args[0] && m_active_trees)
  208. {
  209. m_log.InfoFormat("[TREES]: Trees module is no longer active");
  210. m_active_trees = false;
  211. activeizeTreeze(m_active_trees);
  212. }
  213. else
  214. {
  215. m_log.InfoFormat("[TREES]: Trees module is already in the required state");
  216. }
  217. }
  218. private void HandleTreeFreeze(Object[] args)
  219. {
  220. string copsename = ((string)args[0]).Trim();
  221. Boolean freezeState = (Boolean) args[1];
  222. foreach (Copse cp in m_copse)
  223. {
  224. if (cp.m_name == copsename && (!cp.m_frozen && freezeState || cp.m_frozen && !freezeState))
  225. {
  226. cp.m_frozen = freezeState;
  227. foreach (UUID tree in cp.m_trees)
  228. {
  229. SceneObjectPart sop = ((SceneObjectGroup)m_scene.Entities[tree]).RootPart;
  230. sop.Name = (freezeState ? sop.Name.Replace("ATPM", "FTPM") : sop.Name.Replace("FTPM", "ATPM"));
  231. sop.ParentGroup.HasGroupChanged = true;
  232. }
  233. m_log.InfoFormat("[TREES]: Activity for copse {0} is frozen {1}", copsename, freezeState);
  234. return;
  235. }
  236. else if (cp.m_name == copsename && (cp.m_frozen && freezeState || !cp.m_frozen && !freezeState))
  237. {
  238. m_log.InfoFormat("[TREES]: Copse {0} is already in the requested freeze state", copsename);
  239. return;
  240. }
  241. }
  242. m_log.InfoFormat("[TREES]: Copse {0} was not found - command failed", copsename);
  243. }
  244. private void HandleTreeLoad(Object[] args)
  245. {
  246. Copse copse;
  247. m_log.InfoFormat("[TREES]: Loading copse definition....");
  248. copse = new Copse(((string)args[0]), false);
  249. foreach (Copse cp in m_copse)
  250. {
  251. if (cp.m_name == copse.m_name)
  252. {
  253. m_log.InfoFormat("[TREES]: Copse: {0} is already defined - command failed", copse.m_name);
  254. return;
  255. }
  256. }
  257. m_copse.Add(copse);
  258. m_log.InfoFormat("[TREES]: Loaded copse: {0}", copse.ToString());
  259. }
  260. private void HandleTreePlant(Object[] args)
  261. {
  262. string copsename = ((string)args[0]).Trim();
  263. m_log.InfoFormat("[TREES]: New tree planting for copse {0}", copsename);
  264. UUID uuid = m_scene.RegionInfo.EstateSettings.EstateOwner;
  265. foreach (Copse copse in m_copse)
  266. {
  267. if (copse.m_name == copsename)
  268. {
  269. if (!copse.m_planted)
  270. {
  271. // The first tree for a copse is created here
  272. CreateTree(uuid, copse, copse.m_seed_point);
  273. copse.m_planted = true;
  274. return;
  275. }
  276. else
  277. {
  278. m_log.InfoFormat("[TREES]: Copse {0} has already been planted", copsename);
  279. }
  280. }
  281. }
  282. m_log.InfoFormat("[TREES]: Copse {0} not found for planting", copsename);
  283. }
  284. private void HandleTreeRate(Object[] args)
  285. {
  286. m_update_ms = (double)args[0];
  287. if (m_update_ms >= 1000.0)
  288. {
  289. if (m_active_trees)
  290. {
  291. activeizeTreeze(false);
  292. activeizeTreeze(true);
  293. }
  294. m_log.InfoFormat("[TREES]: Update rate set to {0} mSec", m_update_ms);
  295. }
  296. else
  297. {
  298. m_log.InfoFormat("[TREES]: minimum rate is 1000.0 mSec - command failed");
  299. }
  300. }
  301. private void HandleTreeReload(Object[] args)
  302. {
  303. if (m_active_trees)
  304. {
  305. CalculateTrees.Stop();
  306. }
  307. ReloadCopse();
  308. if (m_active_trees)
  309. {
  310. CalculateTrees.Start();
  311. }
  312. }
  313. private void HandleTreeRemove(Object[] args)
  314. {
  315. string copsename = ((string)args[0]).Trim();
  316. Copse copseIdentity = null;
  317. foreach (Copse cp in m_copse)
  318. {
  319. if (cp.m_name == copsename)
  320. {
  321. copseIdentity = cp;
  322. }
  323. }
  324. if (copseIdentity != null)
  325. {
  326. foreach (UUID tree in copseIdentity.m_trees)
  327. {
  328. if (m_scene.Entities.ContainsKey(tree))
  329. {
  330. SceneObjectPart selectedTree = ((SceneObjectGroup)m_scene.Entities[tree]).RootPart;
  331. // Delete tree and alert clients (not silent)
  332. m_scene.DeleteSceneObject(selectedTree.ParentGroup, false);
  333. }
  334. else
  335. {
  336. m_log.DebugFormat("[TREES]: Tree not in scene {0}", tree);
  337. }
  338. }
  339. copseIdentity.m_trees = new List<UUID>();
  340. m_copse.Remove(copseIdentity);
  341. m_log.InfoFormat("[TREES]: Copse {0} has been removed", copsename);
  342. }
  343. else
  344. {
  345. m_log.InfoFormat("[TREES]: Copse {0} was not found - command failed", copsename);
  346. }
  347. }
  348. private void HandleTreeStatistics(Object[] args)
  349. {
  350. m_log.InfoFormat("[TREES]: Activity State: {0}; Update Rate: {1}", m_active_trees, m_update_ms);
  351. foreach (Copse cp in m_copse)
  352. {
  353. m_log.InfoFormat("[TREES]: Copse {0}; {1} trees; frozen {2}", cp.m_name, cp.m_trees.Count, cp.m_frozen);
  354. }
  355. }
  356. private void InstallCommands()
  357. {
  358. Command treeActiveCommand =
  359. new Command("active", CommandIntentions.COMMAND_HAZARDOUS, HandleTreeActive, "Change activity state for the trees module");
  360. treeActiveCommand.AddArgument("activeTF", "The required activity state", "Boolean");
  361. Command treeFreezeCommand =
  362. new Command("freeze", CommandIntentions.COMMAND_HAZARDOUS, HandleTreeFreeze, "Freeze/Unfreeze activity for a defined copse");
  363. treeFreezeCommand.AddArgument("copse", "The required copse", "String");
  364. treeFreezeCommand.AddArgument("freezeTF", "The required freeze state", "Boolean");
  365. Command treeLoadCommand =
  366. new Command("load", CommandIntentions.COMMAND_HAZARDOUS, HandleTreeLoad, "Load a copse definition from an xml file");
  367. treeLoadCommand.AddArgument("filename", "The (xml) file you wish to load", "String");
  368. Command treePlantCommand =
  369. new Command("plant", CommandIntentions.COMMAND_HAZARDOUS, HandleTreePlant, "Start the planting on a copse");
  370. treePlantCommand.AddArgument("copse", "The required copse", "String");
  371. Command treeRateCommand =
  372. new Command("rate", CommandIntentions.COMMAND_HAZARDOUS, HandleTreeRate, "Reset the tree update rate (mSec)");
  373. treeRateCommand.AddArgument("updateRate", "The required update rate (minimum 1000.0)", "Double");
  374. Command treeReloadCommand =
  375. new Command("reload", CommandIntentions.COMMAND_HAZARDOUS, HandleTreeReload, "Reload copse definitions from the in-scene trees");
  376. Command treeRemoveCommand =
  377. new Command("remove", CommandIntentions.COMMAND_HAZARDOUS, HandleTreeRemove, "Remove a copse definition and all its in-scene trees");
  378. treeRemoveCommand.AddArgument("copse", "The required copse", "String");
  379. Command treeStatisticsCommand =
  380. new Command("statistics", CommandIntentions.COMMAND_STATISTICAL, HandleTreeStatistics, "Log statistics about the trees");
  381. m_commander.RegisterCommand("active", treeActiveCommand);
  382. m_commander.RegisterCommand("freeze", treeFreezeCommand);
  383. m_commander.RegisterCommand("load", treeLoadCommand);
  384. m_commander.RegisterCommand("plant", treePlantCommand);
  385. m_commander.RegisterCommand("rate", treeRateCommand);
  386. m_commander.RegisterCommand("reload", treeReloadCommand);
  387. m_commander.RegisterCommand("remove", treeRemoveCommand);
  388. m_commander.RegisterCommand("statistics", treeStatisticsCommand);
  389. m_scene.RegisterModuleCommander(m_commander);
  390. }
  391. /// <summary>
  392. /// Processes commandline input. Do not call directly.
  393. /// </summary>
  394. /// <param name="args">Commandline arguments</param>
  395. private void EventManager_OnPluginConsole(string[] args)
  396. {
  397. if (args[0] == "tree")
  398. {
  399. if (args.Length == 1)
  400. {
  401. m_commander.ProcessConsoleCommand("help", new string[0]);
  402. return;
  403. }
  404. string[] tmpArgs = new string[args.Length - 2];
  405. int i;
  406. for (i = 2; i < args.Length; i++)
  407. {
  408. tmpArgs[i - 2] = args[i];
  409. }
  410. m_commander.ProcessConsoleCommand(args[1], tmpArgs);
  411. }
  412. }
  413. #endregion
  414. #region IVegetationModule Members
  415. public SceneObjectGroup AddTree(
  416. UUID uuid, UUID groupID, Vector3 scale, Quaternion rotation, Vector3 position, Tree treeType, bool newTree)
  417. {
  418. PrimitiveBaseShape treeShape = new PrimitiveBaseShape();
  419. treeShape.PathCurve = 16;
  420. treeShape.PathEnd = 49900;
  421. treeShape.PCode = newTree ? (byte)PCode.NewTree : (byte)PCode.Tree;
  422. treeShape.Scale = scale;
  423. treeShape.State = (byte)treeType;
  424. return m_scene.AddNewPrim(uuid, groupID, position, rotation, treeShape);
  425. }
  426. #endregion
  427. #region IEntityCreator Members
  428. protected static readonly PCode[] creationCapabilities = new PCode[] { PCode.NewTree, PCode.Tree };
  429. public PCode[] CreationCapabilities { get { return creationCapabilities; } }
  430. public SceneObjectGroup CreateEntity(
  431. UUID ownerID, UUID groupID, Vector3 pos, Quaternion rot, PrimitiveBaseShape shape)
  432. {
  433. if (Array.IndexOf(creationCapabilities, (PCode)shape.PCode) < 0)
  434. {
  435. m_log.DebugFormat("[VEGETATION]: PCode {0} not handled by {1}", shape.PCode, Name);
  436. return null;
  437. }
  438. SceneObjectGroup sceneObject = new SceneObjectGroup(ownerID, pos, rot, shape);
  439. SceneObjectPart rootPart = sceneObject.GetChildPart(sceneObject.UUID);
  440. rootPart.AddFlag(PrimFlags.Phantom);
  441. m_scene.AddNewSceneObject(sceneObject, true);
  442. sceneObject.SetGroup(groupID, null);
  443. return sceneObject;
  444. }
  445. #endregion
  446. //--------------------------------------------------------------
  447. #region Tree Utilities
  448. static public void SerializeObject(string fileName, Object obj)
  449. {
  450. try
  451. {
  452. XmlSerializer xs = new XmlSerializer(typeof(Copse));
  453. using (XmlTextWriter writer = new XmlTextWriter(fileName, Util.UTF8))
  454. {
  455. writer.Formatting = Formatting.Indented;
  456. xs.Serialize(writer, obj);
  457. }
  458. }
  459. catch (SystemException ex)
  460. {
  461. throw new ApplicationException("Unexpected failure in Tree serialization", ex);
  462. }
  463. }
  464. static public object DeserializeObject(string fileName)
  465. {
  466. try
  467. {
  468. XmlSerializer xs = new XmlSerializer(typeof(Copse));
  469. using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read))
  470. return xs.Deserialize(fs);
  471. }
  472. catch (SystemException ex)
  473. {
  474. throw new ApplicationException("Unexpected failure in Tree de-serialization", ex);
  475. }
  476. }
  477. private void ReloadCopse()
  478. {
  479. m_copse = new List<Copse>();
  480. EntityBase[] objs = m_scene.GetEntities();
  481. foreach (EntityBase obj in objs)
  482. {
  483. if (obj is SceneObjectGroup)
  484. {
  485. SceneObjectGroup grp = (SceneObjectGroup)obj;
  486. if (grp.Name.Length > 5 && (grp.Name.Substring(0, 5) == "ATPM:" || grp.Name.Substring(0, 5) == "FTPM:"))
  487. {
  488. // Create a new copse definition or add uuid to an existing definition
  489. try
  490. {
  491. Boolean copsefound = false;
  492. Copse copse = new Copse(grp.Name);
  493. foreach (Copse cp in m_copse)
  494. {
  495. if (cp.m_name == copse.m_name)
  496. {
  497. copsefound = true;
  498. cp.m_trees.Add(grp.UUID);
  499. //m_log.DebugFormat("[TREES]: Found tree {0}", grp.UUID);
  500. }
  501. }
  502. if (!copsefound)
  503. {
  504. m_log.InfoFormat("[TREES]: Found copse {0}", grp.Name);
  505. m_copse.Add(copse);
  506. copse.m_trees.Add(grp.UUID);
  507. }
  508. }
  509. catch
  510. {
  511. m_log.InfoFormat("[TREES]: Ill formed copse definition {0} - ignoring", grp.Name);
  512. }
  513. }
  514. }
  515. }
  516. }
  517. #endregion
  518. private void activeizeTreeze(bool activeYN)
  519. {
  520. if (activeYN)
  521. {
  522. CalculateTrees = new Timer(m_update_ms);
  523. CalculateTrees.Elapsed += CalculateTrees_Elapsed;
  524. CalculateTrees.Start();
  525. }
  526. else
  527. {
  528. CalculateTrees.Stop();
  529. }
  530. }
  531. private void growTrees()
  532. {
  533. foreach (Copse copse in m_copse)
  534. {
  535. if (!copse.m_frozen)
  536. {
  537. foreach (UUID tree in copse.m_trees)
  538. {
  539. if (m_scene.Entities.ContainsKey(tree))
  540. {
  541. SceneObjectPart s_tree = ((SceneObjectGroup)m_scene.Entities[tree]).RootPart;
  542. if (s_tree.Scale.X < copse.m_maximum_scale.X && s_tree.Scale.Y < copse.m_maximum_scale.Y && s_tree.Scale.Z < copse.m_maximum_scale.Z)
  543. {
  544. s_tree.Scale += copse.m_rate;
  545. s_tree.ParentGroup.HasGroupChanged = true;
  546. s_tree.ScheduleFullUpdate();
  547. }
  548. }
  549. else
  550. {
  551. m_log.DebugFormat("[TREES]: Tree not in scene {0}", tree);
  552. }
  553. }
  554. }
  555. }
  556. }
  557. private void seedTrees()
  558. {
  559. foreach (Copse copse in m_copse)
  560. {
  561. if (!copse.m_frozen)
  562. {
  563. foreach (UUID tree in copse.m_trees)
  564. {
  565. if (m_scene.Entities.ContainsKey(tree))
  566. {
  567. SceneObjectPart s_tree = ((SceneObjectGroup)m_scene.Entities[tree]).RootPart;
  568. if (copse.m_trees.Count < copse.m_tree_quantity)
  569. {
  570. // Tree has grown enough to seed if it has grown by at least 25% of seeded to full grown height
  571. if (s_tree.Scale.Z > copse.m_initial_scale.Z + (copse.m_maximum_scale.Z - copse.m_initial_scale.Z) / 4.0)
  572. {
  573. if (Util.RandomClass.NextDouble() > 0.75)
  574. {
  575. SpawnChild(copse, s_tree);
  576. }
  577. }
  578. }
  579. }
  580. else
  581. {
  582. m_log.DebugFormat("[TREES]: Tree not in scene {0}", tree);
  583. }
  584. }
  585. }
  586. }
  587. }
  588. private void killTrees()
  589. {
  590. foreach (Copse copse in m_copse)
  591. {
  592. if (!copse.m_frozen && copse.m_trees.Count >= copse.m_tree_quantity)
  593. {
  594. foreach (UUID tree in copse.m_trees)
  595. {
  596. double killLikelyhood = 0.0;
  597. if (m_scene.Entities.ContainsKey(tree))
  598. {
  599. SceneObjectPart selectedTree = ((SceneObjectGroup)m_scene.Entities[tree]).RootPart;
  600. double selectedTreeScale = Math.Sqrt(Math.Pow(selectedTree.Scale.X, 2) +
  601. Math.Pow(selectedTree.Scale.Y, 2) +
  602. Math.Pow(selectedTree.Scale.Z, 2));
  603. foreach (UUID picktree in copse.m_trees)
  604. {
  605. if (picktree != tree)
  606. {
  607. SceneObjectPart pickedTree = ((SceneObjectGroup)m_scene.Entities[picktree]).RootPart;
  608. double pickedTreeScale = Math.Sqrt(Math.Pow(pickedTree.Scale.X, 2) +
  609. Math.Pow(pickedTree.Scale.Y, 2) +
  610. Math.Pow(pickedTree.Scale.Z, 2));
  611. double pickedTreeDistance = Vector3.Distance(pickedTree.AbsolutePosition, selectedTree.AbsolutePosition);
  612. killLikelyhood += (selectedTreeScale / (pickedTreeScale * pickedTreeDistance)) * 0.1;
  613. }
  614. }
  615. if (Util.RandomClass.NextDouble() < killLikelyhood)
  616. {
  617. // Delete tree and alert clients (not silent)
  618. m_scene.DeleteSceneObject(selectedTree.ParentGroup, false);
  619. copse.m_trees.Remove(selectedTree.ParentGroup.UUID);
  620. break;
  621. }
  622. }
  623. else
  624. {
  625. m_log.DebugFormat("[TREES]: Tree not in scene {0}", tree);
  626. }
  627. }
  628. }
  629. }
  630. }
  631. private void SpawnChild(Copse copse, SceneObjectPart s_tree)
  632. {
  633. Vector3 position = new Vector3();
  634. double randX = ((Util.RandomClass.NextDouble() * 2.0) - 1.0) * (s_tree.Scale.X * 3);
  635. double randY = ((Util.RandomClass.NextDouble() * 2.0) - 1.0) * (s_tree.Scale.X * 3);
  636. position.X = s_tree.AbsolutePosition.X + (float)randX;
  637. position.Y = s_tree.AbsolutePosition.Y + (float)randY;
  638. if (position.X <= ((int)Constants.RegionSize - 1) && position.X >= 0 &&
  639. position.Y <= ((int)Constants.RegionSize - 1) && position.Y >= 0 &&
  640. Util.GetDistanceTo(position, copse.m_seed_point) <= copse.m_range)
  641. {
  642. UUID uuid = m_scene.RegionInfo.EstateSettings.EstateOwner;
  643. CreateTree(uuid, copse, position);
  644. }
  645. }
  646. private void CreateTree(UUID uuid, Copse copse, Vector3 position)
  647. {
  648. position.Z = (float)m_scene.Heightmap[(int)position.X, (int)position.Y];
  649. if (position.Z >= copse.m_treeline_low && position.Z <= copse.m_treeline_high)
  650. {
  651. SceneObjectGroup tree = AddTree(uuid, UUID.Zero, copse.m_initial_scale, Quaternion.Identity, position, copse.m_tree_type, false);
  652. tree.Name = copse.ToString();
  653. copse.m_trees.Add(tree.UUID);
  654. tree.SendGroupFullUpdate();
  655. }
  656. }
  657. private void CalculateTrees_Elapsed(object sender, ElapsedEventArgs e)
  658. {
  659. growTrees();
  660. seedTrees();
  661. killTrees();
  662. }
  663. }
  664. }