TreePopulatorModule.cs 30 KB

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