ScriptModuleCommsModule.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392
  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.Reflection;
  29. using System.Collections.Generic;
  30. using Nini.Config;
  31. using log4net;
  32. using OpenSim.Framework;
  33. using OpenSim.Region.Framework.Interfaces;
  34. using OpenSim.Region.Framework.Scenes;
  35. using Mono.Addins;
  36. using OpenMetaverse;
  37. using System.Linq;
  38. using System.Linq.Expressions;
  39. namespace OpenSim.Region.CoreModules.Scripting.ScriptModuleComms
  40. {
  41. [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "ScriptModuleCommsModule")]
  42. public class ScriptModuleCommsModule : INonSharedRegionModule, IScriptModuleComms
  43. {
  44. private static readonly ILog m_log =
  45. LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  46. private static string LogHeader = "[MODULE COMMS]";
  47. private Dictionary<string,object> m_constants = new Dictionary<string,object>();
  48. #region ScriptInvocation
  49. protected class ScriptInvocationData
  50. {
  51. public Delegate ScriptInvocationDelegate { get; private set; }
  52. public string FunctionName { get; private set; }
  53. public Type[] TypeSignature { get; private set; }
  54. public Type ReturnType { get; private set; }
  55. public ScriptInvocationData(string fname, Delegate fn, Type[] callsig, Type returnsig)
  56. {
  57. FunctionName = fname;
  58. ScriptInvocationDelegate = fn;
  59. TypeSignature = callsig;
  60. ReturnType = returnsig;
  61. }
  62. }
  63. private Dictionary<string,ScriptInvocationData> m_scriptInvocation = new Dictionary<string,ScriptInvocationData>();
  64. #endregion
  65. private IScriptModule m_scriptModule = null;
  66. public event ScriptCommand OnScriptCommand;
  67. #region RegionModuleInterface
  68. public void Initialise(IConfigSource config)
  69. {
  70. }
  71. public void AddRegion(Scene scene)
  72. {
  73. scene.RegisterModuleInterface<IScriptModuleComms>(this);
  74. }
  75. public void RemoveRegion(Scene scene)
  76. {
  77. }
  78. public void RegionLoaded(Scene scene)
  79. {
  80. m_scriptModule = scene.RequestModuleInterface<IScriptModule>();
  81. if (m_scriptModule != null)
  82. m_log.Info("[MODULE COMMANDS]: Script engine found, module active");
  83. }
  84. public string Name
  85. {
  86. get { return "ScriptModuleCommsModule"; }
  87. }
  88. public Type ReplaceableInterface
  89. {
  90. get { return null; }
  91. }
  92. public void Close()
  93. {
  94. }
  95. #endregion
  96. #region ScriptModuleComms
  97. public void RaiseEvent(UUID script, string id, string module, string command, string k)
  98. {
  99. ScriptCommand c = OnScriptCommand;
  100. if (c == null)
  101. return;
  102. c(script, id, module, command, k);
  103. }
  104. public void DispatchReply(UUID script, int code, string text, string k)
  105. {
  106. if (m_scriptModule == null)
  107. return;
  108. Object[] args = new Object[] {-1, code, text, k};
  109. m_scriptModule.PostScriptEvent(script, "link_message", args);
  110. }
  111. private static MethodInfo GetMethodInfoFromType(Type target, string meth, bool searchInstanceMethods)
  112. {
  113. BindingFlags getMethodFlags =
  114. BindingFlags.NonPublic | BindingFlags.Public;
  115. if (searchInstanceMethods)
  116. getMethodFlags |= BindingFlags.Instance;
  117. else
  118. getMethodFlags |= BindingFlags.Static;
  119. return target.GetMethod(meth, getMethodFlags);
  120. }
  121. public void RegisterScriptInvocation(object target, string meth)
  122. {
  123. MethodInfo mi = GetMethodInfoFromType(target.GetType(), meth, true);
  124. if (mi == null)
  125. {
  126. m_log.WarnFormat("{0} Failed to register method {1}", LogHeader, meth);
  127. return;
  128. }
  129. RegisterScriptInvocation(target, mi);
  130. }
  131. public void RegisterScriptInvocation(object target, string[] meth)
  132. {
  133. foreach (string m in meth)
  134. RegisterScriptInvocation(target, m);
  135. }
  136. public void RegisterScriptInvocation(object target, MethodInfo mi)
  137. {
  138. // m_log.DebugFormat("[MODULE COMMANDS] Register method {0} from type {1}", mi.Name, (target is Type) ? ((Type)target).Name : target.GetType().Name);
  139. Type delegateType = typeof(void);
  140. List<Type> typeArgs = mi.GetParameters()
  141. .Select(p => p.ParameterType)
  142. .ToList();
  143. if (mi.ReturnType == typeof(void))
  144. {
  145. delegateType = Expression.GetActionType(typeArgs.ToArray());
  146. }
  147. else
  148. {
  149. try
  150. {
  151. typeArgs.Add(mi.ReturnType);
  152. delegateType = Expression.GetFuncType(typeArgs.ToArray());
  153. }
  154. catch (Exception e)
  155. {
  156. m_log.ErrorFormat("{0} Failed to create function signature. Most likely more than 5 parameters. Method={1}. Error={2}",
  157. LogHeader, mi.Name, e);
  158. }
  159. }
  160. Delegate fcall;
  161. if (!(target is Type))
  162. fcall = Delegate.CreateDelegate(delegateType, target, mi);
  163. else
  164. fcall = Delegate.CreateDelegate(delegateType, (Type)target, mi.Name);
  165. lock (m_scriptInvocation)
  166. {
  167. ParameterInfo[] parameters = fcall.Method.GetParameters();
  168. if (parameters.Length < 2) // Must have two UUID params
  169. return;
  170. // Hide the first two parameters
  171. Type[] parmTypes = new Type[parameters.Length - 2];
  172. for (int i = 2; i < parameters.Length; i++)
  173. parmTypes[i - 2] = parameters[i].ParameterType;
  174. m_scriptInvocation[fcall.Method.Name] = new ScriptInvocationData(fcall.Method.Name, fcall, parmTypes, fcall.Method.ReturnType);
  175. }
  176. }
  177. public void RegisterScriptInvocation(Type target, string[] methods)
  178. {
  179. foreach (string method in methods)
  180. {
  181. MethodInfo mi = GetMethodInfoFromType(target, method, false);
  182. if (mi == null)
  183. m_log.WarnFormat("[MODULE COMMANDS] Failed to register method {0}", method);
  184. else
  185. RegisterScriptInvocation(target, mi);
  186. }
  187. }
  188. public void RegisterScriptInvocations(IRegionModuleBase target)
  189. {
  190. foreach(MethodInfo method in target.GetType().GetMethods(
  191. BindingFlags.Public | BindingFlags.Instance |
  192. BindingFlags.Static))
  193. {
  194. if(method.GetCustomAttributes(
  195. typeof(ScriptInvocationAttribute), true).Any())
  196. {
  197. if(method.IsStatic)
  198. RegisterScriptInvocation(target.GetType(), method);
  199. else
  200. RegisterScriptInvocation(target, method);
  201. }
  202. }
  203. }
  204. public Delegate[] GetScriptInvocationList()
  205. {
  206. List<Delegate> ret = new List<Delegate>();
  207. lock (m_scriptInvocation)
  208. {
  209. foreach (ScriptInvocationData d in m_scriptInvocation.Values)
  210. ret.Add(d.ScriptInvocationDelegate);
  211. }
  212. return ret.ToArray();
  213. }
  214. public string LookupModInvocation(string fname)
  215. {
  216. lock (m_scriptInvocation)
  217. {
  218. ScriptInvocationData sid;
  219. if (m_scriptInvocation.TryGetValue(fname,out sid))
  220. {
  221. if (sid.ReturnType == typeof(string))
  222. return "modInvokeS";
  223. else if (sid.ReturnType == typeof(int))
  224. return "modInvokeI";
  225. else if (sid.ReturnType == typeof(float))
  226. return "modInvokeF";
  227. else if (sid.ReturnType == typeof(UUID))
  228. return "modInvokeK";
  229. else if (sid.ReturnType == typeof(OpenMetaverse.Vector3))
  230. return "modInvokeV";
  231. else if (sid.ReturnType == typeof(OpenMetaverse.Quaternion))
  232. return "modInvokeR";
  233. else if (sid.ReturnType == typeof(object[]))
  234. return "modInvokeL";
  235. m_log.WarnFormat("[MODULE COMMANDS] failed to find match for {0} with return type {1}",fname,sid.ReturnType.Name);
  236. }
  237. }
  238. return null;
  239. }
  240. public Delegate LookupScriptInvocation(string fname)
  241. {
  242. lock (m_scriptInvocation)
  243. {
  244. ScriptInvocationData sid;
  245. if (m_scriptInvocation.TryGetValue(fname,out sid))
  246. return sid.ScriptInvocationDelegate;
  247. }
  248. return null;
  249. }
  250. public Type[] LookupTypeSignature(string fname)
  251. {
  252. lock (m_scriptInvocation)
  253. {
  254. ScriptInvocationData sid;
  255. if (m_scriptInvocation.TryGetValue(fname,out sid))
  256. return sid.TypeSignature;
  257. }
  258. return null;
  259. }
  260. public Type LookupReturnType(string fname)
  261. {
  262. lock (m_scriptInvocation)
  263. {
  264. ScriptInvocationData sid;
  265. if (m_scriptInvocation.TryGetValue(fname,out sid))
  266. return sid.ReturnType;
  267. }
  268. return null;
  269. }
  270. public object InvokeOperation(UUID hostid, UUID scriptid, string fname, params object[] parms)
  271. {
  272. List<object> olist = new List<object>();
  273. olist.Add(hostid);
  274. olist.Add(scriptid);
  275. foreach (object o in parms)
  276. olist.Add(o);
  277. Delegate fn = LookupScriptInvocation(fname);
  278. return fn.DynamicInvoke(olist.ToArray());
  279. }
  280. /// <summary>
  281. /// Operation to for a region module to register a constant to be used
  282. /// by the script engine
  283. /// </summary>
  284. public void RegisterConstant(string cname, object value)
  285. {
  286. // m_log.DebugFormat("[MODULE COMMANDS] register constant <{0}> with value {1}",cname,value.ToString());
  287. lock (m_constants)
  288. {
  289. m_constants.Add(cname,value);
  290. }
  291. }
  292. public void RegisterConstants(IRegionModuleBase target)
  293. {
  294. foreach (FieldInfo field in target.GetType().GetFields(
  295. BindingFlags.Public | BindingFlags.Static |
  296. BindingFlags.Instance))
  297. {
  298. if (field.GetCustomAttributes(
  299. typeof(ScriptConstantAttribute), true).Any())
  300. {
  301. RegisterConstant(field.Name, field.GetValue(target));
  302. }
  303. }
  304. }
  305. /// <summary>
  306. /// Operation to check for a registered constant
  307. /// </summary>
  308. public object LookupModConstant(string cname)
  309. {
  310. // m_log.DebugFormat("[MODULE COMMANDS] lookup constant <{0}>",cname);
  311. lock (m_constants)
  312. {
  313. object value = null;
  314. if (m_constants.TryGetValue(cname,out value))
  315. return value;
  316. }
  317. return null;
  318. }
  319. /// <summary>
  320. /// Get all registered constants
  321. /// </summary>
  322. public Dictionary<string, object> GetConstants()
  323. {
  324. Dictionary<string, object> ret = new Dictionary<string, object>();
  325. lock (m_constants)
  326. {
  327. foreach (KeyValuePair<string, object> kvp in m_constants)
  328. ret[kvp.Key] = kvp.Value;
  329. }
  330. return ret;
  331. }
  332. #endregion
  333. }
  334. }