WorldCommModule.cs 35 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036
  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;
  29. using System.Collections.Concurrent;
  30. using System.Collections.Generic;
  31. using System.Text.RegularExpressions;
  32. using Nini.Config;
  33. using Mono.Addins;
  34. using OpenMetaverse;
  35. using OpenSim.Framework;
  36. using OpenSim.Region.Framework.Interfaces;
  37. using OpenSim.Region.Framework.Scenes;
  38. // using log4net;
  39. // using System.Reflection;
  40. /*****************************************************
  41. *
  42. * WorldCommModule
  43. *
  44. *
  45. * Holding place for world comms - basically llListen
  46. * function implementation.
  47. *
  48. * lLListen(integer channel, string name, key id, string msg)
  49. * The name, id, and msg arguments specify the filtering
  50. * criteria. You can pass the empty string
  51. * (or NULL_KEY for id) for these to set a completely
  52. * open filter; this causes the listen() event handler to be
  53. * invoked for all chat on the channel. To listen only
  54. * for chat spoken by a specific object or avatar,
  55. * specify the name and/or id arguments. To listen
  56. * only for a specific command, specify the
  57. * (case-sensitive) msg argument. If msg is not empty,
  58. * listener will only hear strings which are exactly equal
  59. * to msg. You can also use all the arguments to establish
  60. * the most restrictive filtering criteria.
  61. *
  62. * It might be useful for each listener to maintain a message
  63. * digest, with a list of recent messages by UUID. This can
  64. * be used to prevent in-world repeater loops. However, the
  65. * linden functions do not have this capability, so for now
  66. * thats the way it works.
  67. * Instead it blocks messages originating from the same prim.
  68. * (not Object!)
  69. *
  70. * For LSL compliance, note the following:
  71. * (Tested again 1.21.1 on May 2, 2008)
  72. * 1. 'id' has to be parsed into a UUID. None-UUID keys are
  73. * to be replaced by the ZeroID key. (Well, TryParse does
  74. * that for us.
  75. * 2. Setting up an listen event from the same script, with the
  76. * same filter settings (including step 1), returns the same
  77. * handle as the original filter.
  78. * 3. (TODO) handles should be script-local. Starting from 1.
  79. * Might be actually easier to map the global handle into
  80. * script-local handle in the ScriptEngine. Not sure if its
  81. * worth the effort tho.
  82. *
  83. * **************************************************/
  84. namespace OpenSim.Region.CoreModules.Scripting.WorldComm
  85. {
  86. [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "WorldCommModule")]
  87. public class WorldCommModule : IWorldComm, INonSharedRegionModule
  88. {
  89. // private static readonly ILog m_log =
  90. // LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  91. private const int DEBUG_CHANNEL = 0x7fffffff;
  92. private ListenerManager m_listenerManager;
  93. private ConcurrentQueue<ListenerInfo> m_pending;
  94. private Scene m_scene;
  95. private int m_whisperdistance = 10;
  96. private int m_saydistance = 20;
  97. private int m_shoutdistance = 100;
  98. #region INonSharedRegionModule Members
  99. public void Initialise(IConfigSource config)
  100. {
  101. // wrap this in a try block so that defaults will work if
  102. // the config file doesn't specify otherwise.
  103. int maxlisteners = 1000;
  104. int maxhandles = 65;
  105. try
  106. {
  107. m_whisperdistance = config.Configs["Chat"].GetInt(
  108. "whisper_distance", m_whisperdistance);
  109. m_saydistance = config.Configs["Chat"].GetInt(
  110. "say_distance", m_saydistance);
  111. m_shoutdistance = config.Configs["Chat"].GetInt(
  112. "shout_distance", m_shoutdistance);
  113. maxlisteners = config.Configs["LL-Functions"].GetInt(
  114. "max_listens_per_region", maxlisteners);
  115. maxhandles = config.Configs["LL-Functions"].GetInt(
  116. "max_listens_per_script", maxhandles);
  117. }
  118. catch (Exception)
  119. {
  120. }
  121. m_whisperdistance *= m_whisperdistance;
  122. m_saydistance *= m_saydistance;
  123. m_shoutdistance *= m_shoutdistance;
  124. if (maxlisteners < 1)
  125. maxlisteners = int.MaxValue;
  126. if (maxhandles < 1)
  127. maxhandles = int.MaxValue;
  128. if (maxlisteners < maxhandles)
  129. maxlisteners = maxhandles;
  130. m_listenerManager = new ListenerManager(maxlisteners, maxhandles);
  131. m_pending = new ConcurrentQueue<ListenerInfo>();
  132. }
  133. public void PostInitialise()
  134. {
  135. }
  136. public void AddRegion(Scene scene)
  137. {
  138. m_scene = scene;
  139. m_scene.RegisterModuleInterface<IWorldComm>(this);
  140. m_scene.EventManager.OnChatFromClient += DeliverClientMessage;
  141. m_scene.EventManager.OnChatBroadcast += DeliverClientMessage;
  142. }
  143. public void RegionLoaded(Scene scene) { }
  144. public void RemoveRegion(Scene scene)
  145. {
  146. if (scene != m_scene)
  147. return;
  148. m_scene.UnregisterModuleInterface<IWorldComm>(this);
  149. m_scene.EventManager.OnChatBroadcast -= DeliverClientMessage;
  150. m_scene.EventManager.OnChatBroadcast -= DeliverClientMessage;
  151. }
  152. public void Close()
  153. {
  154. }
  155. public string Name
  156. {
  157. get { return "WorldCommModule"; }
  158. }
  159. public Type ReplaceableInterface { get { return null; } }
  160. #endregion
  161. #region IWorldComm Members
  162. public int ListenerCount
  163. {
  164. get
  165. {
  166. return m_listenerManager.ListenerCount;
  167. }
  168. }
  169. /// <summary>
  170. /// Create a listen event callback with the specified filters.
  171. /// The parameters localID,itemID are needed to uniquely identify
  172. /// the script during 'peek' time. Parameter hostID is needed to
  173. /// determine the position of the script.
  174. /// </summary>
  175. /// <param name="localID">localID of the script engine</param>
  176. /// <param name="itemID">UUID of the script engine</param>
  177. /// <param name="hostID">UUID of the SceneObjectPart</param>
  178. /// <param name="channel">channel to listen on</param>
  179. /// <param name="name">name to filter on</param>
  180. /// <param name="id">
  181. /// key to filter on (user given, could be totally faked)
  182. /// </param>
  183. /// <param name="msg">msg to filter on</param>
  184. /// <returns>number of the scripts handle</returns>
  185. public int Listen(uint localID, UUID itemID, UUID hostID, int channel,
  186. string name, UUID id, string msg)
  187. {
  188. return m_listenerManager.AddListener(localID, itemID, hostID,
  189. channel, name, id, msg);
  190. }
  191. /// <summary>
  192. /// Create a listen event callback with the specified filters.
  193. /// The parameters localID,itemID are needed to uniquely identify
  194. /// the script during 'peek' time. Parameter hostID is needed to
  195. /// determine the position of the script.
  196. /// </summary>
  197. /// <param name="localID">localID of the script engine</param>
  198. /// <param name="itemID">UUID of the script engine</param>
  199. /// <param name="hostID">UUID of the SceneObjectPart</param>
  200. /// <param name="channel">channel to listen on</param>
  201. /// <param name="name">name to filter on</param>
  202. /// <param name="id">
  203. /// key to filter on (user given, could be totally faked)
  204. /// </param>
  205. /// <param name="msg">msg to filter on</param>
  206. /// <param name="regexBitfield">
  207. /// Bitfield indicating which strings should be processed as regex.
  208. /// </param>
  209. /// <returns>number of the scripts handle</returns>
  210. public int Listen(uint localID, UUID itemID, UUID hostID, int channel,
  211. string name, UUID id, string msg, int regexBitfield)
  212. {
  213. return m_listenerManager.AddListener(localID, itemID, hostID,
  214. channel, name, id, msg, regexBitfield);
  215. }
  216. /// <summary>
  217. /// Sets the listen event with handle as active (active = TRUE) or inactive (active = FALSE).
  218. /// The handle used is returned from Listen()
  219. /// </summary>
  220. /// <param name="itemID">UUID of the script engine</param>
  221. /// <param name="handle">handle returned by Listen()</param>
  222. /// <param name="active">temp. activate or deactivate the Listen()</param>
  223. public void ListenControl(UUID itemID, int handle, int active)
  224. {
  225. if (active == 1)
  226. m_listenerManager.Activate(itemID, handle);
  227. else if (active == 0)
  228. m_listenerManager.Dectivate(itemID, handle);
  229. }
  230. /// <summary>
  231. /// Removes the listen event callback with handle
  232. /// </summary>
  233. /// <param name="itemID">UUID of the script engine</param>
  234. /// <param name="handle">handle returned by Listen()</param>
  235. public void ListenRemove(UUID itemID, int handle)
  236. {
  237. m_listenerManager.Remove(itemID, handle);
  238. }
  239. /// <summary>
  240. /// Removes all listen event callbacks for the given itemID
  241. /// (script engine)
  242. /// </summary>
  243. /// <param name="itemID">UUID of the script engine</param>
  244. public void DeleteListener(UUID itemID)
  245. {
  246. m_listenerManager.DeleteListener(itemID);
  247. }
  248. protected static Vector3 CenterOfRegion = new Vector3(128, 128, 20);
  249. public void DeliverMessage(ChatTypeEnum type, int channel, string name, UUID id, string msg)
  250. {
  251. Vector3 position;
  252. SceneObjectPart source;
  253. ScenePresence avatar;
  254. if ((source = m_scene.GetSceneObjectPart(id)) != null)
  255. position = source.AbsolutePosition;
  256. else if ((avatar = m_scene.GetScenePresence(id)) != null)
  257. position = avatar.AbsolutePosition;
  258. else if (ChatTypeEnum.Region == type)
  259. position = CenterOfRegion;
  260. else
  261. return;
  262. DeliverMessage(type, channel, name, id, msg, position);
  263. }
  264. /// <summary>
  265. /// This method scans over the objects which registered an interest in listen callbacks.
  266. /// For everyone it finds, it checks if it fits the given filter. If it does, then
  267. /// enqueue the message for delivery to the objects listen event handler.
  268. /// The enqueued ListenerInfo no longer has filter values, but the actually trigged values.
  269. /// Objects that do an llSay have their messages delivered here and for nearby avatars,
  270. /// the OnChatFromClient event is used.
  271. /// </summary>
  272. /// <param name="type">type of delvery (whisper,say,shout or regionwide)</param>
  273. /// <param name="channel">channel to sent on</param>
  274. /// <param name="name">name of sender (object or avatar)</param>
  275. /// <param name="id">key of sender (object or avatar)</param>
  276. /// <param name="msg">msg to sent</param>
  277. public void DeliverMessage(ChatTypeEnum type, int channel,
  278. string name, UUID id, string msg, Vector3 position)
  279. {
  280. // m_log.DebugFormat("[WorldComm] got[2] type {0}, channel {1}, name {2}, id {3}, msg {4}",
  281. // type, channel, name, id, msg);
  282. // validate type and set range
  283. float maxDistanceSQ;
  284. switch (type)
  285. {
  286. case ChatTypeEnum.Whisper:
  287. maxDistanceSQ = m_whisperdistance;
  288. break;
  289. case ChatTypeEnum.Say:
  290. maxDistanceSQ = m_saydistance;
  291. break;
  292. case ChatTypeEnum.Shout:
  293. maxDistanceSQ = m_shoutdistance;
  294. break;
  295. case ChatTypeEnum.Region:
  296. maxDistanceSQ = -1f;
  297. break;
  298. default:
  299. return;
  300. }
  301. // Determine which listen event filters match the given set of arguments, this results
  302. // in a limited set of listeners, each belonging a host. If the host is in range, add them
  303. // to the pending queue.
  304. UUID hostID;
  305. foreach (ListenerInfo li in m_listenerManager.GetListeners(UUID.Zero, channel, name, id, msg))
  306. {
  307. hostID = li.GetHostID();
  308. // Dont process if this message is from yourself!
  309. if (id == hostID)
  310. continue;
  311. if(maxDistanceSQ < 0)
  312. {
  313. QueueMessage(new ListenerInfo(li, name, id, msg));
  314. continue;
  315. }
  316. SceneObjectPart sPart = m_scene.GetSceneObjectPart(hostID);
  317. if (sPart == null)
  318. continue;
  319. if(maxDistanceSQ > Vector3.DistanceSquared(sPart.AbsolutePosition, position))
  320. QueueMessage(new ListenerInfo(li, name, id, msg));
  321. }
  322. }
  323. /// <summary>
  324. /// Delivers the message to a scene entity.
  325. /// </summary>
  326. /// <param name='target'>
  327. /// Target.
  328. /// </param>
  329. /// <param name='channel'>
  330. /// Channel.
  331. /// </param>
  332. /// <param name='name'>
  333. /// Name.
  334. /// </param>
  335. /// <param name='id'>
  336. /// Identifier.
  337. /// </param>
  338. /// <param name='msg'>
  339. /// Message.
  340. /// </param>
  341. public void DeliverMessageTo(UUID target, int channel, Vector3 pos, string name, UUID id, string msg)
  342. {
  343. if (channel == DEBUG_CHANNEL)
  344. return;
  345. if(target == UUID.Zero)
  346. return;
  347. // Is target an avatar?
  348. ScenePresence sp = m_scene.GetScenePresence(target);
  349. if (sp != null)
  350. {
  351. // Send message to avatar
  352. if (channel == 0)
  353. {
  354. // Channel 0 goes to viewer ONLY
  355. m_scene.SimChat(Utils.StringToBytes(msg), ChatTypeEnum.Direct, 0, pos, name, id, target, false, false);
  356. return;
  357. }
  358. // for now messages to prims don't cross regions
  359. if(sp.IsChildAgent)
  360. return;
  361. List<SceneObjectGroup> attachments = sp.GetAttachments();
  362. if (attachments.Count == 0)
  363. return;
  364. // Get uuid of attachments
  365. List<UUID> targets = new List<UUID>();
  366. foreach (SceneObjectGroup sog in attachments)
  367. {
  368. if (!sog.IsDeleted)
  369. {
  370. SceneObjectPart[] parts = sog.Parts;
  371. foreach(SceneObjectPart p in parts)
  372. targets.Add(p.UUID);
  373. }
  374. }
  375. foreach (ListenerInfo li in m_listenerManager.GetListeners(UUID.Zero, channel, name, id, msg))
  376. {
  377. UUID liHostID = li.GetHostID();
  378. if (liHostID.Equals(id))
  379. continue;
  380. if (m_scene.GetSceneObjectPart(liHostID) == null)
  381. continue;
  382. if (targets.Contains(liHostID))
  383. QueueMessage(new ListenerInfo(li, name, id, msg));
  384. }
  385. return;
  386. }
  387. SceneObjectPart part = m_scene.GetSceneObjectPart(target);
  388. if (part == null) // Not even an object
  389. return; // No error
  390. foreach (ListenerInfo li in m_listenerManager.GetListeners(UUID.Zero, channel, name, id, msg))
  391. {
  392. UUID liHostID = li.GetHostID();
  393. // Dont process if this message is from yourself!
  394. if (liHostID.Equals(id))
  395. continue;
  396. if (!liHostID.Equals(target))
  397. continue;
  398. if (m_scene.GetSceneObjectPart(liHostID) == null)
  399. continue;
  400. QueueMessage(new ListenerInfo(li, name, id, msg));
  401. }
  402. }
  403. protected void QueueMessage(ListenerInfo li)
  404. {
  405. m_pending.Enqueue(li);
  406. }
  407. /// <summary>
  408. /// Are there any listen events ready to be dispatched?
  409. /// </summary>
  410. /// <returns>boolean indication</returns>
  411. public bool HasMessages()
  412. {
  413. return (m_pending.Count > 0);
  414. }
  415. /// <summary>
  416. /// Pop the first availlable listen event from the queue
  417. /// </summary>
  418. /// <returns>ListenerInfo with filter filled in</returns>
  419. public IWorldCommListenerInfo GetNextMessage()
  420. {
  421. m_pending.TryDequeue(out ListenerInfo li);
  422. return li;
  423. }
  424. #endregion
  425. /********************************************************************
  426. *
  427. * Listener Stuff
  428. *
  429. * *****************************************************************/
  430. private void DeliverClientMessage(Object sender, OSChatMessage e)
  431. {
  432. if (null != e.Sender)
  433. {
  434. DeliverMessage(e.Type, e.Channel, e.Sender.Name,
  435. e.Sender.AgentId, e.Message, e.Position);
  436. }
  437. else
  438. {
  439. DeliverMessage(e.Type, e.Channel, e.From, UUID.Zero,
  440. e.Message, e.Position);
  441. }
  442. }
  443. public Object[] GetSerializationData(UUID itemID)
  444. {
  445. return m_listenerManager.GetSerializationData(itemID);
  446. }
  447. public void CreateFromData(uint localID, UUID itemID, UUID hostID,
  448. Object[] data)
  449. {
  450. m_listenerManager.AddFromData(localID, itemID, hostID, data);
  451. }
  452. }
  453. public class ListenerManager
  454. {
  455. private object mainLock = new object();
  456. private Dictionary<int, List<ListenerInfo>> m_listenersByChannel = new Dictionary<int, List<ListenerInfo>>();
  457. private int m_maxlisteners;
  458. private int m_maxhandles;
  459. private int m_curlisteners;
  460. /// <summary>
  461. /// Total number of listeners
  462. /// </summary>
  463. public int ListenerCount
  464. {
  465. get
  466. {
  467. lock (mainLock)
  468. return m_listenersByChannel.Count;
  469. }
  470. }
  471. public ListenerManager(int maxlisteners, int maxhandles)
  472. {
  473. m_maxlisteners = maxlisteners;
  474. m_maxhandles = maxhandles;
  475. m_curlisteners = 0;
  476. }
  477. public int AddListener(uint localID, UUID itemID, UUID hostID,
  478. int channel, string name, UUID id, string msg)
  479. {
  480. return AddListener(localID, itemID, hostID, channel, name, id,
  481. msg, 0);
  482. }
  483. public int AddListener(uint localID, UUID itemID, UUID hostID,
  484. int channel, string name, UUID id, string msg,
  485. int regexBitfield)
  486. {
  487. // do we already have a match on this particular filter event?
  488. List<ListenerInfo> coll = GetListeners(itemID, channel, name, id, msg);
  489. if (coll.Count > 0)
  490. {
  491. // special case, called with same filter settings, return same
  492. // handle (2008-05-02, tested on 1.21.1 server, still holds)
  493. return coll[0].GetHandle();
  494. }
  495. lock (mainLock)
  496. {
  497. if (m_curlisteners < m_maxlisteners)
  498. {
  499. int newHandle = GetNewHandle(itemID);
  500. if (newHandle > 0)
  501. {
  502. ListenerInfo li = new ListenerInfo(newHandle, localID,
  503. itemID, hostID, channel, name, id, msg,
  504. regexBitfield);
  505. if (!m_listenersByChannel.TryGetValue(channel, out List<ListenerInfo> listeners))
  506. {
  507. listeners = new List<ListenerInfo>();
  508. m_listenersByChannel.Add(channel, listeners);
  509. }
  510. listeners.Add(li);
  511. m_curlisteners++;
  512. return newHandle;
  513. }
  514. }
  515. }
  516. return -1;
  517. }
  518. public void Remove(UUID itemID, int handle)
  519. {
  520. lock (mainLock)
  521. {
  522. foreach (KeyValuePair<int, List<ListenerInfo>> lis in m_listenersByChannel)
  523. {
  524. foreach (ListenerInfo li in lis.Value)
  525. {
  526. if (handle == li.GetHandle() && itemID == li.GetItemID())
  527. {
  528. lis.Value.Remove(li);
  529. m_curlisteners--;
  530. if (lis.Value.Count == 0)
  531. m_listenersByChannel.Remove(lis.Key); // bailing of loop so this does not smoke
  532. // there should be only one, so we bail out early
  533. return;
  534. }
  535. }
  536. }
  537. }
  538. }
  539. public void DeleteListener(UUID itemID)
  540. {
  541. List<int> emptyChannels = new List<int>();
  542. List<ListenerInfo> removedListeners = new List<ListenerInfo>();
  543. lock (mainLock)
  544. {
  545. foreach (KeyValuePair<int, List<ListenerInfo>> lis in m_listenersByChannel)
  546. {
  547. foreach (ListenerInfo li in lis.Value)
  548. {
  549. if (itemID == li.GetItemID())
  550. removedListeners.Add(li);
  551. }
  552. foreach (ListenerInfo li in removedListeners)
  553. {
  554. lis.Value.Remove(li);
  555. m_curlisteners--;
  556. }
  557. removedListeners.Clear();
  558. if (lis.Value.Count == 0)
  559. emptyChannels.Add(lis.Key);
  560. }
  561. foreach (int channel in emptyChannels)
  562. {
  563. m_listenersByChannel.Remove(channel);
  564. }
  565. }
  566. }
  567. public void Activate(UUID itemID, int handle)
  568. {
  569. lock (mainLock)
  570. {
  571. foreach (KeyValuePair<int, List<ListenerInfo>> lis in m_listenersByChannel)
  572. {
  573. foreach (ListenerInfo li in lis.Value)
  574. {
  575. if (handle == li.GetHandle() && itemID == li.GetItemID())
  576. {
  577. li.Activate();
  578. return;
  579. }
  580. }
  581. }
  582. }
  583. }
  584. public void Dectivate(UUID itemID, int handle)
  585. {
  586. lock (mainLock)
  587. {
  588. foreach (KeyValuePair<int, List<ListenerInfo>> lis in m_listenersByChannel)
  589. {
  590. foreach (ListenerInfo li in lis.Value)
  591. {
  592. if (handle == li.GetHandle() && itemID == li.GetItemID())
  593. {
  594. li.Deactivate();
  595. return;
  596. }
  597. }
  598. }
  599. }
  600. }
  601. /// <summary>
  602. /// non-locked access, since its always called in the context of the
  603. /// lock
  604. /// </summary>
  605. /// <param name="itemID"></param>
  606. /// <returns></returns>
  607. private int GetNewHandle(UUID itemID)
  608. {
  609. List<int> handles = new List<int>();
  610. // build a list of used keys for this specific itemID...
  611. foreach (KeyValuePair<int, List<ListenerInfo>> lis in m_listenersByChannel)
  612. {
  613. foreach (ListenerInfo li in lis.Value)
  614. {
  615. if (itemID == li.GetItemID())
  616. handles.Add(li.GetHandle());
  617. }
  618. }
  619. if(handles.Count >= m_maxhandles)
  620. return -1;
  621. // Note: 0 is NOT a valid handle for llListen() to return
  622. for (int i = 1; i <= m_maxhandles; i++)
  623. {
  624. if (!handles.Contains(i))
  625. return i;
  626. }
  627. return -1;
  628. }
  629. /// These are duplicated from ScriptBaseClass
  630. /// http://opensimulator.org/mantis/view.php?id=6106#c21945
  631. #region Constants for the bitfield parameter of osListenRegex
  632. /// <summary>
  633. /// process name parameter as regex
  634. /// </summary>
  635. public const int OS_LISTEN_REGEX_NAME = 0x1;
  636. /// <summary>
  637. /// process message parameter as regex
  638. /// </summary>
  639. public const int OS_LISTEN_REGEX_MESSAGE = 0x2;
  640. #endregion
  641. /// <summary>
  642. /// Get listeners matching the input parameters.
  643. /// </summary>
  644. /// <remarks>
  645. /// Theres probably a more clever and efficient way to do this, maybe
  646. /// with regex.
  647. /// </remarks>
  648. /// <param name="itemID"></param>
  649. /// <param name="channel"></param>
  650. /// <param name="name"></param>
  651. /// <param name="id"></param>
  652. /// <param name="msg"></param>
  653. /// <returns></returns>
  654. public List<ListenerInfo> GetListeners(UUID itemID, int channel,
  655. string name, UUID id, string msg)
  656. {
  657. List<ListenerInfo> collection = new List<ListenerInfo>();
  658. lock (mainLock)
  659. {
  660. List<ListenerInfo> listeners;
  661. if (!m_listenersByChannel.TryGetValue(channel, out listeners))
  662. {
  663. return collection;
  664. }
  665. bool itemIDNotZero = itemID != UUID.Zero;
  666. foreach (ListenerInfo li in listeners)
  667. {
  668. if (!li.IsActive())
  669. continue;
  670. if (itemIDNotZero && itemID != li.GetItemID())
  671. continue;
  672. if (li.GetID() != UUID.Zero && id != li.GetID())
  673. continue;
  674. if (li.GetName().Length > 0)
  675. {
  676. if((li.RegexBitfield & OS_LISTEN_REGEX_NAME) == OS_LISTEN_REGEX_NAME)
  677. {
  678. if (!Regex.IsMatch(name, li.GetName()))
  679. continue;
  680. }
  681. else
  682. {
  683. if (!li.GetName().Equals(name))
  684. continue;
  685. }
  686. }
  687. if (li.GetMessage().Length > 0)
  688. {
  689. if((li.RegexBitfield & OS_LISTEN_REGEX_MESSAGE) == OS_LISTEN_REGEX_MESSAGE)
  690. {
  691. if(!Regex.IsMatch(msg, li.GetMessage()))
  692. continue;
  693. }
  694. else
  695. {
  696. if(!li.GetMessage().Equals(msg))
  697. continue;
  698. }
  699. }
  700. collection.Add(li);
  701. }
  702. }
  703. return collection;
  704. }
  705. public Object[] GetSerializationData(UUID itemID)
  706. {
  707. List<Object> data = new List<Object>();
  708. lock (mainLock)
  709. {
  710. foreach (List<ListenerInfo> list in m_listenersByChannel.Values)
  711. {
  712. foreach (ListenerInfo l in list)
  713. {
  714. if (l.GetItemID() == itemID)
  715. data.AddRange(l.GetSerializationData());
  716. }
  717. }
  718. }
  719. return (Object[])data.ToArray();
  720. }
  721. public void AddFromData(uint localID, UUID itemID, UUID hostID,
  722. Object[] data)
  723. {
  724. int idx = 0;
  725. Object[] item = new Object[6];
  726. int dataItemLength = 6;
  727. while (idx < data.Length)
  728. {
  729. dataItemLength = (idx + 7 == data.Length || (idx + 7 < data.Length && data[idx + 7] is bool)) ? 7 : 6;
  730. item = new Object[dataItemLength];
  731. Array.Copy(data, idx, item, 0, dataItemLength);
  732. ListenerInfo info =
  733. ListenerInfo.FromData(localID, itemID, hostID, item);
  734. lock (mainLock)
  735. {
  736. if (!m_listenersByChannel.ContainsKey((int)item[2]))
  737. {
  738. m_listenersByChannel.Add((int)item[2], new List<ListenerInfo>());
  739. }
  740. m_listenersByChannel[(int)item[2]].Add(info);
  741. }
  742. idx += dataItemLength;
  743. }
  744. }
  745. }
  746. public class ListenerInfo : IWorldCommListenerInfo
  747. {
  748. /// <summary>
  749. /// Listener is active or not
  750. /// </summary>
  751. private bool m_active;
  752. /// <summary>
  753. /// Assigned handle of this listener
  754. /// </summary>
  755. private int m_handle;
  756. /// <summary>
  757. /// Local ID from script engine
  758. /// </summary>
  759. private uint m_localID;
  760. /// <summary>
  761. /// ID of the host script engine
  762. /// </summary>
  763. private UUID m_itemID;
  764. /// <summary>
  765. /// ID of the host/scene part
  766. /// </summary>
  767. private UUID m_hostID;
  768. /// <summary>
  769. /// Channel
  770. /// </summary>
  771. private int m_channel;
  772. /// <summary>
  773. /// ID to filter messages from
  774. /// </summary>
  775. private UUID m_id;
  776. /// <summary>
  777. /// Object name to filter messages from
  778. /// </summary>
  779. private string m_name;
  780. /// <summary>
  781. /// The message
  782. /// </summary>
  783. private string m_message;
  784. public ListenerInfo(int handle, uint localID, UUID ItemID,
  785. UUID hostID, int channel, string name, UUID id,
  786. string message)
  787. {
  788. Initialise(handle, localID, ItemID, hostID, channel, name, id,
  789. message, 0);
  790. }
  791. public ListenerInfo(int handle, uint localID, UUID ItemID,
  792. UUID hostID, int channel, string name, UUID id,
  793. string message, int regexBitfield)
  794. {
  795. Initialise(handle, localID, ItemID, hostID, channel, name, id,
  796. message, regexBitfield);
  797. }
  798. public ListenerInfo(ListenerInfo li, string name, UUID id,
  799. string message)
  800. {
  801. Initialise(li.m_handle, li.m_localID, li.m_itemID, li.m_hostID,
  802. li.m_channel, name, id, message, 0);
  803. }
  804. public ListenerInfo(ListenerInfo li, string name, UUID id,
  805. string message, int regexBitfield)
  806. {
  807. Initialise(li.m_handle, li.m_localID, li.m_itemID, li.m_hostID,
  808. li.m_channel, name, id, message, regexBitfield);
  809. }
  810. private void Initialise(int handle, uint localID, UUID ItemID,
  811. UUID hostID, int channel, string name, UUID id,
  812. string message, int regexBitfield)
  813. {
  814. m_active = true;
  815. m_handle = handle;
  816. m_localID = localID;
  817. m_itemID = ItemID;
  818. m_hostID = hostID;
  819. m_channel = channel;
  820. m_name = name;
  821. m_id = id;
  822. m_message = message;
  823. RegexBitfield = regexBitfield;
  824. }
  825. public Object[] GetSerializationData()
  826. {
  827. Object[] data = new Object[7];
  828. data[0] = m_active;
  829. data[1] = m_handle;
  830. data[2] = m_channel;
  831. data[3] = m_name;
  832. data[4] = m_id;
  833. data[5] = m_message;
  834. data[6] = RegexBitfield;
  835. return data;
  836. }
  837. public static ListenerInfo FromData(uint localID, UUID ItemID,
  838. UUID hostID, Object[] data)
  839. {
  840. ListenerInfo linfo = new ListenerInfo((int)data[1], localID,
  841. ItemID, hostID, (int)data[2], (string)data[3],
  842. (UUID)data[4], (string)data[5]);
  843. linfo.m_active = (bool)data[0];
  844. if (data.Length >= 7)
  845. {
  846. linfo.RegexBitfield = (int)data[6];
  847. }
  848. return linfo;
  849. }
  850. public UUID GetItemID()
  851. {
  852. return m_itemID;
  853. }
  854. public UUID GetHostID()
  855. {
  856. return m_hostID;
  857. }
  858. public int GetChannel()
  859. {
  860. return m_channel;
  861. }
  862. public uint GetLocalID()
  863. {
  864. return m_localID;
  865. }
  866. public int GetHandle()
  867. {
  868. return m_handle;
  869. }
  870. public string GetMessage()
  871. {
  872. return m_message;
  873. }
  874. public string GetName()
  875. {
  876. return m_name;
  877. }
  878. public bool IsActive()
  879. {
  880. return m_active;
  881. }
  882. public void Deactivate()
  883. {
  884. m_active = false;
  885. }
  886. public void Activate()
  887. {
  888. m_active = true;
  889. }
  890. public UUID GetID()
  891. {
  892. return m_id;
  893. }
  894. public int RegexBitfield { get; private set; }
  895. }
  896. }