XMREngine.cs 74 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958
  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. // based on XMREngine from Mike Rieker (DreamNation), Melanie Thielker and meta7
  28. // but with several changes to be more cross platform.
  29. using log4net;
  30. using Mono.Addins;
  31. using Nini.Config;
  32. using OpenSim.Framework;
  33. using OpenSim.Framework.Console;
  34. using OpenSim.Framework.Monitoring;
  35. using OpenSim.Region.ClientStack.Linden;
  36. using OpenSim.Region.Framework.Interfaces;
  37. using OpenSim.Region.Framework.Scenes;
  38. using OpenSim.Region.ScriptEngine.Interfaces;
  39. using OpenSim.Region.ScriptEngine.Shared;
  40. using OpenSim.Region.ScriptEngine.Shared.Api;
  41. using OpenMetaverse;
  42. using System;
  43. using System.Collections;
  44. using System.Collections.Generic;
  45. using System.IO;
  46. using System.Reflection;
  47. using System.Reflection.Emit;
  48. using System.Text;
  49. using System.Threading;
  50. using System.Timers;
  51. using System.Xml;
  52. using LSL_Float = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLFloat;
  53. using LSL_Integer = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLInteger;
  54. using LSL_Key = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLString;
  55. using LSL_List = OpenSim.Region.ScriptEngine.Shared.LSL_Types.list;
  56. using LSL_Rotation = OpenSim.Region.ScriptEngine.Shared.LSL_Types.Quaternion;
  57. using LSL_String = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLString;
  58. using LSL_Vector = OpenSim.Region.ScriptEngine.Shared.LSL_Types.Vector3;
  59. [assembly: Addin("YEngine", OpenSim.VersionInfo.VersionNumber)]
  60. [assembly: AddinDependency("OpenSim.Region.Framework", OpenSim.VersionInfo.VersionNumber)]
  61. namespace OpenSim.Region.ScriptEngine.Yengine
  62. {
  63. [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "YEngine")]
  64. public partial class Yengine: INonSharedRegionModule, IScriptEngine,
  65. IScriptModule
  66. {
  67. public static readonly DetectParams[] zeroDetectParams = new DetectParams[0];
  68. private static ArrayList noScriptErrors = new ArrayList();
  69. public static readonly ILog m_log =
  70. LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  71. private static readonly string[] scriptReferencedAssemblies = new string[0];
  72. private bool m_LateInit;
  73. private bool m_TraceCalls;
  74. public bool m_Verbose;
  75. public bool m_ScriptDebug;
  76. public bool m_ScriptDebugSaveSource;
  77. public bool m_ScriptDebugSaveIL;
  78. public Scene m_Scene;
  79. private IConfigSource m_ConfigSource;
  80. private IConfig m_Config;
  81. private string m_ScriptBasePath;
  82. private bool m_Enabled = false;
  83. public bool m_StartProcessing = false;
  84. private Dictionary<UUID, ArrayList> m_ScriptErrors =
  85. new Dictionary<UUID, ArrayList>();
  86. private Dictionary<UUID, List<UUID>> m_ObjectItemList =
  87. new Dictionary<UUID, List<UUID>>();
  88. private Dictionary<UUID, XMRInstance[]> m_ObjectInstArray =
  89. new Dictionary<UUID, XMRInstance[]>();
  90. public Dictionary<string, FieldInfo> m_XMRInstanceApiCtxFieldInfos =
  91. new Dictionary<string, FieldInfo>();
  92. public int m_StackSize;
  93. private int m_HeapSize;
  94. private Thread m_SleepThread = null;
  95. private bool m_Exiting = false;
  96. private int m_MaintenanceInterval = 10;
  97. private System.Timers.Timer m_MaintenanceTimer;
  98. public int numThreadScriptWorkers;
  99. private object m_FrameUpdateLock = new object();
  100. private event ThreadStart m_FrameUpdateList = null;
  101. // Various instance lists:
  102. // m_InstancesDict = all known instances
  103. // find an instance given its itemID
  104. // m_StartQueue = instances that have just had event queued to them
  105. // m_YieldQueue = instances that are ready to run right now
  106. // m_SleepQueue = instances that have m_SleepUntil valid
  107. // sorted by ascending m_SleepUntil
  108. private Dictionary<UUID, XMRInstance> m_InstancesDict =
  109. new Dictionary<UUID, XMRInstance>();
  110. public Queue<ThreadStart> m_ThunkQueue = new Queue<ThreadStart>();
  111. public XMRInstQueue m_StartQueue = new XMRInstQueue();
  112. public XMRInstQueue m_YieldQueue = new XMRInstQueue();
  113. public XMRInstQueue m_SleepQueue = new XMRInstQueue();
  114. private string m_LockedDict = "nobody";
  115. public Yengine()
  116. {
  117. }
  118. public string Name
  119. {
  120. get
  121. {
  122. return "YEngine";
  123. }
  124. }
  125. public Type ReplaceableInterface
  126. {
  127. get
  128. {
  129. return null;
  130. }
  131. }
  132. public string ScriptEnginePath
  133. {
  134. get
  135. {
  136. return m_ScriptBasePath;
  137. }
  138. }
  139. public string ScriptClassName
  140. {
  141. get
  142. {
  143. return "YEngineScript";
  144. }
  145. }
  146. public string ScriptBaseClassName
  147. {
  148. get
  149. {
  150. return typeof(XMRInstance).FullName;
  151. }
  152. }
  153. public ParameterInfo[] ScriptBaseClassParameters
  154. {
  155. get
  156. {
  157. return typeof(XMRInstance).GetConstructor(new Type[] { typeof(WaitHandle) }).GetParameters();
  158. }
  159. }
  160. public string[] ScriptReferencedAssemblies
  161. {
  162. get
  163. {
  164. return scriptReferencedAssemblies;
  165. }
  166. }
  167. public void Initialise(IConfigSource config)
  168. {
  169. TraceCalls("[YEngine]: Initialize entry");
  170. m_ConfigSource = config;
  171. ////foreach (IConfig icfg in config.Configs) {
  172. //// m_log.Debug("[YEngine]: Initialise: configs[" + icfg.Name + "]");
  173. //// foreach (string key in icfg.GetKeys ()) {
  174. //// m_log.Debug("[YEngine]: Initialise: " + key + "=" + icfg.GetExpanded (key));
  175. //// }
  176. ////}
  177. m_Enabled = false;
  178. m_Config = config.Configs["YEngine"];
  179. if(m_Config == null)
  180. {
  181. m_log.Info("[YEngine]: no config, assuming disabled");
  182. return;
  183. }
  184. m_Enabled = m_Config.GetBoolean("Enabled", false);
  185. m_log.InfoFormat("[YEngine]: config enabled={0}", m_Enabled);
  186. if(!m_Enabled)
  187. return;
  188. numThreadScriptWorkers = m_Config.GetInt("NumThreadScriptWorkers", 1);
  189. m_TraceCalls = m_Config.GetBoolean("TraceCalls", false);
  190. m_Verbose = m_Config.GetBoolean("Verbose", false);
  191. m_ScriptDebug = m_Config.GetBoolean("ScriptDebug", false);
  192. m_ScriptDebugSaveSource = m_Config.GetBoolean("ScriptDebugSaveSource", false);
  193. m_ScriptDebugSaveIL = m_Config.GetBoolean("ScriptDebugSaveIL", false);
  194. m_StackSize = m_Config.GetInt("ScriptStackSize", 2048) << 10;
  195. m_HeapSize = m_Config.GetInt("ScriptHeapSize", 1024) << 10;
  196. // Verify that our ScriptEventCode's match OpenSim's scriptEvent's.
  197. bool err = false;
  198. for(int i = 0; i < 32; i++)
  199. {
  200. string mycode = "undefined";
  201. string oscode = "undefined";
  202. try
  203. {
  204. mycode = ((ScriptEventCode)i).ToString();
  205. Convert.ToInt32(mycode);
  206. mycode = "undefined";
  207. }
  208. catch { }
  209. try
  210. {
  211. oscode = ((OpenSim.Region.Framework.Scenes.scriptEvents)(1 << i)).ToString();
  212. Convert.ToInt32(oscode);
  213. oscode = "undefined";
  214. }
  215. catch { }
  216. if(mycode != oscode)
  217. {
  218. m_log.ErrorFormat("[YEngine]: {0} mycode={1}, oscode={2}", i, mycode, oscode);
  219. err = true;
  220. }
  221. }
  222. if(err)
  223. {
  224. m_Enabled = false;
  225. return;
  226. }
  227. m_SleepThread = StartMyThread(RunSleepThread, "Yengine sleep", ThreadPriority.Normal);
  228. for(int i = 0; i < numThreadScriptWorkers; i++)
  229. StartThreadWorker(i);
  230. m_log.InfoFormat("[YEngine]: Enabled, {0}.{1} Meg (0x{2}) stacks",
  231. (m_StackSize >> 20).ToString(),
  232. (((m_StackSize % 0x100000) * 1000)
  233. >> 20).ToString("D3"),
  234. m_StackSize.ToString("X"));
  235. m_log.InfoFormat("[YEngine]: ... {0}.{1} Meg (0x{2}) heaps",
  236. (m_HeapSize >> 20).ToString(),
  237. (((m_HeapSize % 0x100000) * 1000)
  238. >> 20).ToString("D3"),
  239. m_HeapSize.ToString("X"));
  240. m_MaintenanceInterval = m_Config.GetInt("MaintenanceInterval", 10);
  241. if(m_MaintenanceInterval > 0)
  242. {
  243. m_MaintenanceTimer = new System.Timers.Timer(m_MaintenanceInterval * 60000);
  244. m_MaintenanceTimer.Elapsed += DoMaintenance;
  245. m_MaintenanceTimer.Start();
  246. }
  247. MainConsole.Instance.Commands.AddCommand("yeng", false,
  248. "yeng",
  249. "yeng [...|help|...] ...",
  250. "Run YEngine script engine commands",
  251. RunTest);
  252. TraceCalls("[YEngine]: Initialize successful");
  253. }
  254. public void AddRegion(Scene scene)
  255. {
  256. if(!m_Enabled)
  257. return;
  258. TraceCalls("[YEngine]: YEngine.AddRegion({0})", scene.RegionInfo.RegionName);
  259. m_Scene = scene;
  260. m_Scene.RegisterModuleInterface<IScriptModule>(this);
  261. m_ScriptBasePath = m_Config.GetString("ScriptBasePath", "ScriptEngines");
  262. m_ScriptBasePath = Path.Combine(m_ScriptBasePath, "Yengine");
  263. m_ScriptBasePath = Path.Combine(m_ScriptBasePath, scene.RegionInfo.RegionID.ToString());
  264. Directory.CreateDirectory(m_ScriptBasePath);
  265. m_Scene.EventManager.OnRezScript += OnRezScript;
  266. m_Scene.StackModuleInterface<IScriptModule>(this);
  267. }
  268. private void OneTimeLateInitialization()
  269. {
  270. // Build list of defined APIs and their 'this' types and define a field in XMRInstanceSuperType.
  271. ApiManager am = new ApiManager();
  272. Dictionary<string, Type> apiCtxTypes = new Dictionary<string, Type>();
  273. foreach(string api in am.GetApis())
  274. {
  275. m_log.Debug("[YEngine]: adding api " + api);
  276. IScriptApi scriptApi = am.CreateApi(api);
  277. Type apiCtxType = scriptApi.GetType();
  278. if(api == "LSL")
  279. apiCtxType = typeof(XMRLSL_Api);
  280. apiCtxTypes[api] = apiCtxType;
  281. }
  282. if(ScriptCodeGen.xmrInstSuperType == null) // Only create type once!
  283. {
  284. // Start creating type XMRInstanceSuperType that contains a field
  285. // m_ApiManager_<APINAME> that points to the per-instance context
  286. // struct for that API, ie, the 'this' value passed to all methods
  287. // in that API. It is in essence:
  288. // public class XMRInstanceSuperType : XMRInstance {
  289. // public XMRLSL_Api m_ApiManager_LSL; // 'this' value for all ll...() functions
  290. // public MOD_Api m_ApiManager_MOD; // 'this' value for all mod...() functions
  291. // public OSSL_Api m_ApiManager_OSSL; // 'this' value for all os...() functions
  292. // ....
  293. // }
  294. AssemblyName assemblyName = new AssemblyName();
  295. assemblyName.Name = "XMRInstanceSuperAssembly";
  296. AssemblyBuilder assemblyBuilder = Thread.GetDomain().DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run);
  297. ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule("XMRInstanceSuperModule");
  298. TypeBuilder typeBuilder = moduleBuilder.DefineType("XMRInstanceSuperType", TypeAttributes.Public | TypeAttributes.Class);
  299. typeBuilder.SetParent(typeof(XMRInstance));
  300. foreach(string apiname in apiCtxTypes.Keys)
  301. {
  302. string fieldName = "m_ApiManager_" + apiname;
  303. typeBuilder.DefineField(fieldName, apiCtxTypes[apiname], FieldAttributes.Public);
  304. }
  305. // Finalize definition of XMRInstanceSuperType.
  306. // Give the compiler a short name to reference it by,
  307. // otherwise it will try to use the AssemblyQualifiedName
  308. // and fail miserably.
  309. ScriptCodeGen.xmrInstSuperType = typeBuilder.CreateType();
  310. ScriptObjWriter.DefineInternalType("xmrsuper", ScriptCodeGen.xmrInstSuperType);
  311. }
  312. // Tell the compiler about all the constants and methods for each API.
  313. // We also tell the compiler how to get the per-instance context for each API
  314. // by reading the corresponding m_ApiManager_<APINAME> field of XMRInstanceSuperType.
  315. foreach(KeyValuePair<string, Type> kvp in apiCtxTypes)
  316. {
  317. // get API name and the corresponding per-instance context type
  318. string api = kvp.Key;
  319. Type apiCtxType = kvp.Value;
  320. // give script compiler an abbreviated name for the API context type
  321. ScriptObjWriter.DefineInternalType("apimanager_" + api, apiCtxType);
  322. // this field tells the compiled code where the per-instance API context object is
  323. // eg, for the OSSL API, it is in ((XMRInstanceSuperType)inst).m_ApiManager_OSSL
  324. string fieldName = "m_ApiManager_" + api;
  325. FieldInfo fieldInfo = ScriptCodeGen.xmrInstSuperType.GetField(fieldName);
  326. m_XMRInstanceApiCtxFieldInfos[api] = fieldInfo;
  327. // now tell the compiler about the constants and methods for the API
  328. ScriptConst.AddInterfaceConstants(null, apiCtxType.GetFields());
  329. TokenDeclInline.AddInterfaceMethods(null, apiCtxType.GetMethods(), fieldInfo);
  330. }
  331. // Add sim-specific APIs to the compiler.
  332. IScriptModuleComms comms = m_Scene.RequestModuleInterface<IScriptModuleComms>();
  333. if(comms != null)
  334. {
  335. // Add methods to list of built-in functions.
  336. Delegate[] methods = comms.GetScriptInvocationList();
  337. foreach(Delegate m in methods)
  338. {
  339. MethodInfo mi = m.Method;
  340. try
  341. {
  342. CommsCallCodeGen cccg = new CommsCallCodeGen(mi, comms, m_XMRInstanceApiCtxFieldInfos["MOD"]);
  343. Verbose("[YEngine]: added comms function " + cccg.fullName);
  344. }
  345. catch(Exception e)
  346. {
  347. m_log.Error("[YEngine]: failed to add comms function " + mi.Name);
  348. m_log.Error("[YEngine]: - " + e.ToString());
  349. }
  350. }
  351. // Add constants to list of built-in constants.
  352. Dictionary<string, object> consts = comms.GetConstants();
  353. foreach(KeyValuePair<string, object> kvp in consts)
  354. {
  355. try
  356. {
  357. ScriptConst sc = ScriptConst.AddConstant(kvp.Key, kvp.Value);
  358. Verbose("[YEngine]: added comms constant " + sc.name);
  359. }
  360. catch(Exception e)
  361. {
  362. m_log.Error("[YEngine]: failed to add comms constant " + kvp.Key);
  363. m_log.Error("[YEngine]: - " + e.Message);
  364. }
  365. }
  366. }
  367. else
  368. {
  369. Verbose("[YEngine]: comms not enabled");
  370. }
  371. }
  372. /**
  373. * @brief Generate code for the calls to the comms functions.
  374. * It is a tRUlY EvIL interface.
  375. * To call the function we must call an XMRInstanceSuperType.m_ApiManager_MOD.modInvoker?()
  376. * method passing it the name of the function as a string and the script
  377. * argument list wrapped up in an object[] array. The modInvoker?() methods
  378. * do some sick type conversions (with corresponding mallocs) so we can't
  379. * call the methods directly.
  380. */
  381. private class CommsCallCodeGen: TokenDeclInline
  382. {
  383. private static Type[] modInvokerArgTypes = new Type[] { typeof(string), typeof(object[]) };
  384. public static FieldInfo xmrInstModApiCtxField;
  385. private MethodInfo modInvokerMeth;
  386. private string methName;
  387. /**
  388. * @brief Constructor
  389. * @param mi = method to make available to scripts
  390. * mi.Name = name that is used by scripts
  391. * mi.GetParameters() = parameter list as defined by module
  392. * includes the 'UUID host','UUID script' parameters that script does not see
  393. * allowed types for script-visible parameters are as follows:
  394. * Single -> float
  395. * Int32 -> integer
  396. * OpenMetaverse.UUID -> key
  397. * Object[] -> list
  398. * OpenMetaverse.Quaternion -> rotation
  399. * String -> string
  400. * OpenMetaverse.Vector3 -> vector
  401. * mi.ReturnType = return type as defined by module
  402. * types are same as allowed for parameters
  403. * @param comms = comms module the method came from
  404. * @param apictxfi = what field in XMRInstanceSuperType the 'this' value is for this method
  405. */
  406. public CommsCallCodeGen(MethodInfo mi, IScriptModuleComms comms, FieldInfo apictxfi)
  407. : base(null, false, NameArgSig(mi), RetType(mi))
  408. {
  409. methName = mi.Name;
  410. string modInvokerName = comms.LookupModInvocation(methName);
  411. if(modInvokerName == null)
  412. throw new Exception("cannot find comms method " + methName);
  413. modInvokerMeth = typeof(MOD_Api).GetMethod(modInvokerName, modInvokerArgTypes);
  414. xmrInstModApiCtxField = apictxfi;
  415. }
  416. // script-visible name(argtype,...) signature string
  417. private static string NameArgSig(MethodInfo mi)
  418. {
  419. StringBuilder sb = new StringBuilder();
  420. sb.Append(mi.Name);
  421. sb.Append('(');
  422. ParameterInfo[] mps = mi.GetParameters();
  423. for(int i = 2; i < mps.Length; i++)
  424. {
  425. ParameterInfo pi = mps[i];
  426. if(i > 2)
  427. sb.Append(',');
  428. sb.Append(ParamType(pi.ParameterType));
  429. }
  430. sb.Append(')');
  431. return sb.ToString();
  432. }
  433. // script-visible return type
  434. // note that although we support void, the comms stuff does not
  435. private static TokenType RetType(MethodInfo mi)
  436. {
  437. Type rt = mi.ReturnType;
  438. if(rt == typeof(float))
  439. return new TokenTypeFloat(null);
  440. if(rt == typeof(int))
  441. return new TokenTypeInt(null);
  442. if(rt == typeof(object[]))
  443. return new TokenTypeList(null);
  444. if(rt == typeof(OpenMetaverse.UUID))
  445. return new TokenTypeKey(null);
  446. if(rt == typeof(OpenMetaverse.Quaternion))
  447. return new TokenTypeRot(null);
  448. if(rt == typeof(string))
  449. return new TokenTypeStr(null);
  450. if(rt == typeof(OpenMetaverse.Vector3))
  451. return new TokenTypeVec(null);
  452. if(rt == null || rt == typeof(void))
  453. return new TokenTypeVoid(null);
  454. throw new Exception("unsupported return type " + rt.Name);
  455. }
  456. // script-visible parameter type
  457. private static string ParamType(Type t)
  458. {
  459. if(t == typeof(float))
  460. return "float";
  461. if(t == typeof(int))
  462. return "integer";
  463. if(t == typeof(OpenMetaverse.UUID))
  464. return "key";
  465. if(t == typeof(object[]))
  466. return "list";
  467. if(t == typeof(OpenMetaverse.Quaternion))
  468. return "rotation";
  469. if(t == typeof(string))
  470. return "string";
  471. if(t == typeof(OpenMetaverse.Vector3))
  472. return "vector";
  473. throw new Exception("unsupported parameter type " + t.Name);
  474. }
  475. /**
  476. * @brief Called by the compiler to generate a call to the comms function.
  477. * @param scg = which script is being compiled
  478. * @param errorAt = where in the source code the call is being made (for error messages)
  479. * @param result = a temp location to put the return value in if any
  480. * @param args = array of script-visible arguments being passed to the function
  481. */
  482. public override void CodeGen(ScriptCodeGen scg, Token errorAt, CompValuTemp result, CompValu[] args)
  483. {
  484. // Set up 'this' pointer for modInvoker?() = value from ApiManager.CreateApi("MOD").
  485. scg.PushXMRInst();
  486. scg.ilGen.Emit(errorAt, OpCodes.Castclass, xmrInstModApiCtxField.DeclaringType);
  487. scg.ilGen.Emit(errorAt, OpCodes.Ldfld, xmrInstModApiCtxField);
  488. // Set up 'fname' argument to modInvoker?() = name of the function to be called.
  489. scg.ilGen.Emit(errorAt, OpCodes.Ldstr, methName);
  490. // Set up 'parms' argument to modInvoker?() = object[] of the script-visible parameters,
  491. // in their LSL-wrapped form. Of course, the modInvoker?() method will malloc yet another
  492. // object[] and type-convert these parameters one-by-one with another round of unwrapping
  493. // and wrapping.
  494. // Types allowed in this object[]:
  495. // LSL_Float, LSL_Integer, LSL_Key, LSL_List, LSL_Rotation, LSL_String, LSL_Vector
  496. int nargs = args.Length;
  497. scg.ilGen.Emit(errorAt, OpCodes.Ldc_I4, nargs);
  498. scg.ilGen.Emit(errorAt, OpCodes.Newarr, typeof(object));
  499. for(int i = 0; i < nargs; i++)
  500. {
  501. scg.ilGen.Emit(errorAt, OpCodes.Dup);
  502. scg.ilGen.Emit(errorAt, OpCodes.Ldc_I4, i);
  503. // get location and type of argument
  504. CompValu arg = args[i];
  505. TokenType argtype = arg.type;
  506. // if already in a form acceptable to modInvoker?(),
  507. // just push it to the stack and convert to object
  508. // by boxing it if necessary
  509. // but if something like a double, int, string, etc
  510. // push to stack converting to the LSL-wrapped type
  511. // then convert to object by boxing if necessary
  512. Type boxit = null;
  513. if(argtype is TokenTypeLSLFloat)
  514. {
  515. args[i].PushVal(scg, errorAt);
  516. boxit = typeof(LSL_Float);
  517. }
  518. else if(argtype is TokenTypeLSLInt)
  519. {
  520. args[i].PushVal(scg, errorAt);
  521. boxit = typeof(LSL_Integer);
  522. }
  523. else if(argtype is TokenTypeLSLKey)
  524. {
  525. args[i].PushVal(scg, errorAt);
  526. boxit = typeof(LSL_Key);
  527. }
  528. else if(argtype is TokenTypeList)
  529. {
  530. args[i].PushVal(scg, errorAt);
  531. boxit = typeof(LSL_List);
  532. }
  533. else if(argtype is TokenTypeRot)
  534. {
  535. args[i].PushVal(scg, errorAt);
  536. boxit = typeof(LSL_Rotation);
  537. }
  538. else if(argtype is TokenTypeLSLString)
  539. {
  540. args[i].PushVal(scg, errorAt);
  541. boxit = typeof(LSL_String);
  542. }
  543. else if(argtype is TokenTypeVec)
  544. {
  545. args[i].PushVal(scg, errorAt);
  546. boxit = typeof(LSL_Vector);
  547. }
  548. else if(argtype is TokenTypeFloat)
  549. {
  550. args[i].PushVal(scg, errorAt, new TokenTypeLSLFloat(argtype));
  551. boxit = typeof(LSL_Float);
  552. }
  553. else if(argtype is TokenTypeInt)
  554. {
  555. args[i].PushVal(scg, errorAt, new TokenTypeLSLInt(argtype));
  556. boxit = typeof(LSL_Integer);
  557. }
  558. else if(argtype is TokenTypeKey)
  559. {
  560. args[i].PushVal(scg, errorAt, new TokenTypeLSLKey(argtype));
  561. boxit = typeof(LSL_Key);
  562. }
  563. else if(argtype is TokenTypeStr)
  564. {
  565. args[i].PushVal(scg, errorAt, new TokenTypeLSLString(argtype));
  566. boxit = typeof(LSL_String);
  567. }
  568. else
  569. throw new Exception("unsupported arg type " + argtype.GetType().Name);
  570. if(boxit.IsValueType)
  571. scg.ilGen.Emit(errorAt, OpCodes.Box, boxit);
  572. // pop the object into the object[]
  573. scg.ilGen.Emit(errorAt, OpCodes.Stelem, typeof(object));
  574. }
  575. // Call the modInvoker?() method.
  576. // It leaves an LSL-wrapped type on the stack.
  577. if(modInvokerMeth.IsVirtual)
  578. scg.ilGen.Emit(errorAt, OpCodes.Callvirt, modInvokerMeth);
  579. else
  580. scg.ilGen.Emit(errorAt, OpCodes.Call, modInvokerMeth);
  581. // The 3rd arg to Pop() is the type on the stack,
  582. // ie, what modInvoker?() actually returns.
  583. // The Pop() method will wrap/unwrap as needed.
  584. Type retSysType = modInvokerMeth.ReturnType;
  585. if(retSysType == null)
  586. retSysType = typeof(void);
  587. TokenType retTokType = TokenType.FromSysType(errorAt, retSysType);
  588. result.Pop(scg, errorAt, retTokType);
  589. }
  590. }
  591. /**
  592. * @brief Called late in shutdown procedure,
  593. * after the 'Shutting down..." message.
  594. */
  595. public void RemoveRegion(Scene scene)
  596. {
  597. if(!m_Enabled)
  598. return;
  599. TraceCalls("[YEngine]: YEngine.RemoveRegion({0})", scene.RegionInfo.RegionName);
  600. if(m_MaintenanceTimer != null)
  601. {
  602. m_MaintenanceTimer.Stop();
  603. m_MaintenanceTimer.Dispose();
  604. }
  605. // Write script states out to .state files so it will be
  606. // available when the region is restarted.
  607. DoMaintenance(null, null);
  608. // Stop executing script threads and wait for final
  609. // one to finish (ie, script gets to CheckRun() call).
  610. m_Exiting = true;
  611. if(m_SleepThread != null)
  612. {
  613. lock(m_SleepQueue)
  614. Monitor.PulseAll(m_SleepQueue);
  615. if(!m_SleepThread.Join(250))
  616. m_SleepThread.Abort();
  617. m_SleepThread = null;
  618. }
  619. StopThreadWorkers();
  620. m_Scene.EventManager.OnFrame -= OnFrame;
  621. m_Scene.EventManager.OnRezScript -= OnRezScript;
  622. m_Scene.EventManager.OnRemoveScript -= OnRemoveScript;
  623. m_Scene.EventManager.OnScriptReset -= OnScriptReset;
  624. m_Scene.EventManager.OnStartScript -= OnStartScript;
  625. m_Scene.EventManager.OnStopScript -= OnStopScript;
  626. m_Scene.EventManager.OnGetScriptRunning -= OnGetScriptRunning;
  627. m_Scene.EventManager.OnShutdown -= OnShutdown;
  628. m_Enabled = false;
  629. m_Scene = null;
  630. }
  631. public void RegionLoaded(Scene scene)
  632. {
  633. if(!m_Enabled)
  634. return;
  635. TraceCalls("[YEngine]: YEngine.RegionLoaded({0})", scene.RegionInfo.RegionName);
  636. m_Scene.EventManager.OnFrame += OnFrame;
  637. m_Scene.EventManager.OnRemoveScript += OnRemoveScript;
  638. m_Scene.EventManager.OnScriptReset += OnScriptReset;
  639. m_Scene.EventManager.OnStartScript += OnStartScript;
  640. m_Scene.EventManager.OnStopScript += OnStopScript;
  641. m_Scene.EventManager.OnGetScriptRunning += OnGetScriptRunning;
  642. m_Scene.EventManager.OnShutdown += OnShutdown;
  643. InitEvents();
  644. }
  645. public void StartProcessing()
  646. {
  647. m_log.Debug("[YEngine]: StartProcessing entry");
  648. m_StartProcessing = true;
  649. ResumeThreads();
  650. m_log.Debug("[YEngine]: StartProcessing return");
  651. m_Scene.EventManager.TriggerEmptyScriptCompileQueue(0, "");
  652. }
  653. public void Close()
  654. {
  655. TraceCalls("[YEngine]: YEngine.Close()");
  656. }
  657. private void RunTest(string module, string[] args)
  658. {
  659. if(args.Length < 2)
  660. {
  661. m_log.Info("[YEngine]: missing command, try 'yeng help'");
  662. return;
  663. }
  664. m_log.Info("[YEngine]: " + m_Scene.RegionInfo.RegionName);
  665. switch(args[1])
  666. {
  667. case "cvv":
  668. m_log.InfoFormat("[YEngine]: compiled version value = {0}",
  669. ScriptCodeGen.COMPILED_VERSION_VALUE);
  670. break;
  671. case "help":
  672. case "?":
  673. m_log.Info("[YEngine]: yeng reset [-help ...]");
  674. m_log.Info("[YEngine]: yeng resume - resume script processing");
  675. m_log.Info("[YEngine]: yeng suspend - suspend script processing");
  676. m_log.Info("[YEngine]: yeng ls [-help ...]");
  677. m_log.Info("[YEngine]: yeng cvv - show compiler version value");
  678. m_log.Info("[YEngine]: yeng mvv [<newvalue>] - show migration version value");
  679. m_log.Info("[YEngine]: yeng tracecalls [yes | no]");
  680. m_log.Info("[YEngine]: yeng verbose [yes | no]");
  681. m_log.Info("[YEngine]: yeng pev [-help ...] - post event");
  682. break;
  683. case "ls":
  684. XmrTestLs(args, 2);
  685. break;
  686. case "mvv":
  687. m_log.InfoFormat("[YEngine]: migration version value = {0}",
  688. XMRInstance.migrationVersion);
  689. break;
  690. case "pev":
  691. XmrTestPev(args, 2);
  692. break;
  693. case "reset":
  694. XmrTestReset(args, 2);
  695. break;
  696. case "resume":
  697. m_log.Info("[YEngine]: resuming scripts");
  698. ResumeThreads();
  699. break;
  700. case "suspend":
  701. m_log.Info("[YEngine]: suspending scripts");
  702. SuspendThreads();
  703. break;
  704. case "tracecalls":
  705. if(args.Length > 2)
  706. m_TraceCalls = (args[2][0] & 1) != 0;
  707. m_log.Info("[YEngine]: tracecalls " + (m_TraceCalls ? "yes" : "no"));
  708. break;
  709. case "verbose":
  710. if(args.Length > 2)
  711. m_Verbose = (args[2][0] & 1) != 0;
  712. m_log.Info("[YEngine]: verbose " + (m_Verbose ? "yes" : "no"));
  713. break;
  714. default:
  715. m_log.Error("[YEngine]: unknown command " + args[1] + ", try 'yeng help'");
  716. break;
  717. }
  718. }
  719. // Not required when not using IScriptInstance
  720. //
  721. public IScriptWorkItem QueueEventHandler(object parms)
  722. {
  723. return null;
  724. }
  725. public Scene World
  726. {
  727. get
  728. {
  729. return m_Scene;
  730. }
  731. }
  732. public IScriptModule ScriptModule
  733. {
  734. get
  735. {
  736. return this;
  737. }
  738. }
  739. public void SaveAllState()
  740. {
  741. m_log.Error("[YEngine]: YEngine.SaveAllState() called!!");
  742. }
  743. #pragma warning disable 0067
  744. public event ScriptRemoved OnScriptRemoved;
  745. public event ObjectRemoved OnObjectRemoved;
  746. #pragma warning restore 0067
  747. // Events targeted at a specific script
  748. // ... like listen() for an llListen() call
  749. //
  750. public bool PostScriptEvent(UUID itemID, EventParams parms)
  751. {
  752. XMRInstance instance = GetInstance(itemID);
  753. if (instance == null)
  754. return false;
  755. TraceCalls("[YEngine]: YEngine.PostScriptEvent({0},{1})", itemID.ToString(), parms.EventName);
  756. instance.PostEvent(parms);
  757. return true;
  758. }
  759. public void CancelScriptEvent(UUID itemID, string eventName)
  760. {
  761. XMRInstance instance = GetInstance(itemID);
  762. if (instance == null)
  763. return;
  764. TraceCalls("[YEngine]: YEngine.CancelScriptEvent({0},{1})", itemID.ToString(), eventName);
  765. instance.CancelEvent(eventName);
  766. }
  767. // Events targeted at all scripts in the given prim.
  768. // localID = which prim
  769. // parms = event to post
  770. //
  771. public bool PostObjectEvent(uint localID, EventParams parms)
  772. {
  773. SceneObjectPart part = m_Scene.GetSceneObjectPart(localID);
  774. if(part == null)
  775. return false;
  776. TraceCalls("[YEngine]: YEngine.PostObjectEvent({0},{1})", localID.ToString(), parms.EventName);
  777. // In SecondLife, attach events go to all scripts of all prims
  778. // in a linked object. So here we duplicate that functionality,
  779. // as all we ever get is a single attach event for the whole
  780. // object.
  781. if(parms.EventName == "attach")
  782. {
  783. bool posted = false;
  784. foreach(SceneObjectPart primpart in part.ParentGroup.Parts)
  785. posted |= PostPrimEvent(primpart, parms);
  786. return posted;
  787. }
  788. // Other events go to just the scripts in that prim.
  789. return PostPrimEvent(part, parms);
  790. }
  791. private bool PostPrimEvent(SceneObjectPart part, EventParams parms)
  792. {
  793. UUID partUUID = part.UUID;
  794. // Get list of script instances running in the object.
  795. XMRInstance[] objInstArray;
  796. lock(m_InstancesDict)
  797. {
  798. if(!m_ObjectInstArray.TryGetValue(partUUID, out objInstArray))
  799. return false;
  800. if(objInstArray == null)
  801. {
  802. objInstArray = RebuildObjectInstArray(partUUID);
  803. m_ObjectInstArray[partUUID] = objInstArray;
  804. }
  805. }
  806. // Post event to all script instances in the object.
  807. if(objInstArray.Length <= 0)
  808. return false;
  809. foreach(XMRInstance inst in objInstArray)
  810. inst.PostEvent(parms);
  811. return true;
  812. }
  813. public DetectParams GetDetectParams(UUID itemID, int number)
  814. {
  815. XMRInstance instance = GetInstance(itemID);
  816. if(instance == null)
  817. return null;
  818. return instance.GetDetectParams(number);
  819. }
  820. public void SetMinEventDelay(UUID itemID, double delay)
  821. {
  822. XMRInstance instance = GetInstance(itemID);
  823. if (instance != null)
  824. instance.MinEventDelay = delay;
  825. }
  826. public int GetStartParameter(UUID itemID)
  827. {
  828. XMRInstance instance = GetInstance(itemID);
  829. if (instance == null)
  830. return 0;
  831. return instance.StartParam;
  832. }
  833. // This is the "set running" method
  834. //
  835. public void SetScriptState(UUID itemID, bool state, bool self)
  836. {
  837. SetScriptState(itemID, state);
  838. }
  839. public void SetScriptState(UUID itemID, bool state)
  840. {
  841. XMRInstance instance = GetInstance(itemID);
  842. if(instance != null)
  843. instance.Running = state;
  844. }
  845. // Control display of the "running" checkbox
  846. //
  847. public bool GetScriptState(UUID itemID)
  848. {
  849. XMRInstance instance = GetInstance(itemID);
  850. if(instance == null)
  851. return false;
  852. return instance.Running;
  853. }
  854. public void SetState(UUID itemID, string newState)
  855. {
  856. TraceCalls("[YEngine]: YEngine.SetState({0},{1})", itemID.ToString(), newState);
  857. }
  858. public void ApiResetScript(UUID itemID)
  859. {
  860. XMRInstance instance = GetInstance(itemID);
  861. if(instance != null)
  862. instance.ApiReset();
  863. }
  864. public void ResetScript(UUID itemID)
  865. {
  866. XMRInstance instance = GetInstance(itemID);
  867. if(instance != null)
  868. {
  869. IUrlModule urlModule = m_Scene.RequestModuleInterface<IUrlModule>();
  870. if(urlModule != null)
  871. urlModule.ScriptRemoved(itemID);
  872. instance.Reset();
  873. }
  874. }
  875. public IConfig Config
  876. {
  877. get
  878. {
  879. return m_Config;
  880. }
  881. }
  882. public IConfigSource ConfigSource
  883. {
  884. get
  885. {
  886. return m_ConfigSource;
  887. }
  888. }
  889. public string ScriptEngineName
  890. {
  891. get
  892. {
  893. return "YEngine";
  894. }
  895. }
  896. public IScriptApi GetApi(UUID itemID, string name)
  897. {
  898. FieldInfo fi;
  899. if(!m_XMRInstanceApiCtxFieldInfos.TryGetValue(name, out fi))
  900. return null;
  901. XMRInstance inst = GetInstance(itemID);
  902. if(inst == null)
  903. return null;
  904. return (IScriptApi)fi.GetValue(inst);
  905. }
  906. /**
  907. * @brief Get script's current state as an XML string
  908. * - called by "Take", "Take Copy" and when object deleted (ie, moved to Trash)
  909. * This includes the .state file
  910. */
  911. public string GetXMLState(UUID itemID)
  912. {
  913. XMRInstance instance = GetInstance(itemID);
  914. if(instance == null)
  915. return String.Empty;
  916. TraceCalls("[YEngine]: YEngine.GetXMLState({0})", itemID.ToString());
  917. if(!instance.m_HasRun)
  918. return String.Empty;
  919. XmlDocument doc = new XmlDocument();
  920. /*
  921. * Set up <State Engine="YEngine" UUID="itemID" Asset="assetID"> tag.
  922. */
  923. XmlElement stateN = doc.CreateElement("", "State", "");
  924. doc.AppendChild(stateN);
  925. XmlAttribute engineA = doc.CreateAttribute("", "Engine", "");
  926. engineA.Value = ScriptEngineName;
  927. stateN.Attributes.Append(engineA);
  928. XmlAttribute uuidA = doc.CreateAttribute("", "UUID", "");
  929. uuidA.Value = itemID.ToString();
  930. stateN.Attributes.Append(uuidA);
  931. XmlAttribute assetA = doc.CreateAttribute("", "Asset", "");
  932. string assetID = instance.AssetID.ToString();
  933. assetA.Value = assetID;
  934. stateN.Attributes.Append(assetA);
  935. // Get <ScriptState>...</ScriptState> item that hold's script's state.
  936. // This suspends the script if necessary then takes a snapshot.
  937. XmlElement scriptStateN = instance.GetExecutionState(doc);
  938. stateN.AppendChild(scriptStateN);
  939. return doc.OuterXml;
  940. }
  941. // Set script's current state from an XML string
  942. // - called just before a script is instantiated
  943. // So we write the .state file so the .state file will be seen when
  944. // the script is instantiated.
  945. public bool SetXMLState(UUID itemID, string xml)
  946. {
  947. XmlDocument doc = new XmlDocument();
  948. try
  949. {
  950. doc.LoadXml(xml);
  951. }
  952. catch
  953. {
  954. return false;
  955. }
  956. TraceCalls("[YEngine]: YEngine.SetXMLState({0})", itemID.ToString());
  957. // Make sure <State Engine="YEngine"> so we know it is in our
  958. // format.
  959. XmlElement stateN = (XmlElement)doc.SelectSingleNode("State");
  960. if(stateN == null)
  961. return false;
  962. bool isX = false;
  963. string sen = stateN.GetAttribute("Engine");
  964. if (sen == null)
  965. return false;
  966. if (sen != ScriptEngineName)
  967. {
  968. if(sen != "XEngine")
  969. return false;
  970. isX = true;
  971. }
  972. // <ScriptState>...</ScriptState> contains contents of .state file.
  973. XmlElement scriptStateN = (XmlElement)stateN.SelectSingleNode("ScriptState");
  974. if(scriptStateN == null)
  975. return false;
  976. if(!isX)
  977. {
  978. sen = stateN.GetAttribute("Engine");
  979. if ((sen == null) || (sen != ScriptEngineName))
  980. return false;
  981. }
  982. XmlAttribute assetA = doc.CreateAttribute("", "Asset", "");
  983. assetA.Value = stateN.GetAttribute("Asset");
  984. scriptStateN.Attributes.Append(assetA);
  985. // Write out the .state file with the <ScriptState ...>...</ScriptState> XML text
  986. string statePath = XMRInstance.GetStateFileName(m_ScriptBasePath, itemID);
  987. using (FileStream ss = File.Create(statePath))
  988. {
  989. using (StreamWriter sw = new StreamWriter(ss))
  990. sw.Write(scriptStateN.OuterXml);
  991. }
  992. return true;
  993. }
  994. public bool PostScriptEvent(UUID itemID, string name, Object[] p)
  995. {
  996. if(!m_Enabled)
  997. return false;
  998. TraceCalls("[YEngine]: YEngine.PostScriptEvent({0},{1})", itemID.ToString(), name);
  999. return PostScriptEvent(itemID, new EventParams(name, p, zeroDetectParams));
  1000. }
  1001. public bool PostObjectEvent(UUID itemID, string name, Object[] p)
  1002. {
  1003. if(!m_Enabled)
  1004. return false;
  1005. TraceCalls("[YEngine]: YEngine.PostObjectEvent({0},{1})", itemID.ToString(), name);
  1006. SceneObjectPart part = m_Scene.GetSceneObjectPart(itemID);
  1007. if(part == null)
  1008. return false;
  1009. return PostObjectEvent(part.LocalId, new EventParams(name, p, zeroDetectParams));
  1010. }
  1011. // about the 3523rd entrypoint for a script to put itself to sleep
  1012. public void SleepScript(UUID itemID, int delay)
  1013. {
  1014. XMRInstance instance = GetInstance(itemID);
  1015. if(instance != null)
  1016. instance.Sleep(delay);
  1017. }
  1018. // Get a script instance loaded, compiling it if necessary
  1019. //
  1020. // localID = the object as a whole, may contain many scripts
  1021. // itemID = this instance of the script in this object
  1022. // script = script source code
  1023. // startParam = value passed to 'on_rez' event handler
  1024. // postOnRez = true to post an 'on_rez' event to script on load
  1025. // defEngine = default script engine
  1026. // stateSource = post this event to script on load
  1027. public void OnRezScript(uint localID, UUID itemID, string script,
  1028. int startParam, bool postOnRez, string defEngine, int stateSource)
  1029. {
  1030. if (script.StartsWith("//MRM:"))
  1031. return;
  1032. SceneObjectPart part = m_Scene.GetSceneObjectPart(localID);
  1033. TaskInventoryItem item = part.Inventory.GetInventoryItem(itemID);
  1034. if(!m_LateInit)
  1035. {
  1036. m_LateInit = true;
  1037. OneTimeLateInitialization();
  1038. }
  1039. TraceCalls("[YEngine]: OnRezScript(...,{0},...)", itemID.ToString());
  1040. // Assume script uses the default engine
  1041. string engineName = defEngine;
  1042. // Very first line might contain // scriptengine : language
  1043. string langsrt = "";
  1044. if (script.StartsWith("//"))
  1045. {
  1046. int lineEnd = script.IndexOf('\n');
  1047. if(lineEnd > 5)
  1048. {
  1049. string firstline = script.Substring(2, lineEnd - 2).Trim();
  1050. int colon = firstline.IndexOf(':');
  1051. if(colon >= 3)
  1052. {
  1053. engineName = firstline.Substring(0, colon).TrimEnd();
  1054. if(string.IsNullOrEmpty(engineName))
  1055. engineName = defEngine;
  1056. }
  1057. if (colon > 0 && colon < firstline.Length - 2)
  1058. {
  1059. langsrt = firstline.Substring(colon + 1).Trim();
  1060. langsrt = langsrt.ToLower();
  1061. }
  1062. }
  1063. }
  1064. // Make sure the default or requested engine is us.
  1065. if(engineName != ScriptEngineName)
  1066. {
  1067. // Not us, if requested engine exists, silently ignore script and let
  1068. // requested engine handle it.
  1069. IScriptModule[] engines = m_Scene.RequestModuleInterfaces<IScriptModule>();
  1070. foreach(IScriptModule eng in engines)
  1071. {
  1072. if(eng.ScriptEngineName == engineName)
  1073. return;
  1074. }
  1075. // Requested engine not defined, warn on console.
  1076. // Then we try to handle it if we're the default engine, else we ignore it.
  1077. //m_log.Warn("[YEngine]: " + itemID.ToString() + " requests undefined/disabled engine " + engineName);
  1078. //m_log.Info("[YEngine]: - " + part.GetWorldPosition());
  1079. //m_log.Info("[YEngine]: first line: " + firstline);
  1080. if(defEngine != ScriptEngineName)
  1081. {
  1082. //m_log.Info("[YEngine]: leaving it to the default script engine (" + defEngine + ") to process it");
  1083. return;
  1084. }
  1085. // m_log.Info("[YEngine]: will attempt to processing it anyway as default script engine");
  1086. langsrt = "";
  1087. }
  1088. if(!string.IsNullOrEmpty(langsrt) && langsrt !="lsl")
  1089. return;
  1090. // Put on object/instance lists.
  1091. XMRInstance instance = (XMRInstance)Activator.CreateInstance(ScriptCodeGen.xmrInstSuperType);
  1092. instance.m_LocalID = localID;
  1093. instance.m_ItemID = itemID;
  1094. instance.m_SourceCode = script;
  1095. instance.m_StartParam = startParam;
  1096. instance.m_PostOnRez = postOnRez;
  1097. instance.m_StateSource = (StateSource)stateSource;
  1098. instance.m_Part = part;
  1099. instance.m_PartUUID = part.UUID;
  1100. instance.m_Item = item;
  1101. instance.m_DescName = part.Name + ":" + item.Name;
  1102. instance.m_IState = XMRInstState.CONSTRUCT;
  1103. lock(m_InstancesDict)
  1104. {
  1105. m_LockedDict = "RegisterInstance";
  1106. // Insert on internal list of all scripts being handled by this engine instance.
  1107. m_InstancesDict[instance.m_ItemID] = instance;
  1108. // Insert on internal list of all scripts being handled by this engine instance
  1109. // that are part of the object.
  1110. List<UUID> itemIDList;
  1111. if(!m_ObjectItemList.TryGetValue(instance.m_PartUUID, out itemIDList))
  1112. {
  1113. itemIDList = new List<UUID>();
  1114. m_ObjectItemList[instance.m_PartUUID] = itemIDList;
  1115. }
  1116. if(!itemIDList.Contains(instance.m_ItemID))
  1117. {
  1118. itemIDList.Add(instance.m_ItemID);
  1119. m_ObjectInstArray[instance.m_PartUUID] = null;
  1120. }
  1121. m_LockedDict = "~RegisterInstance";
  1122. }
  1123. // Compile and load it.
  1124. lock(m_ScriptErrors)
  1125. m_ScriptErrors.Remove(instance.m_ItemID);
  1126. LoadThreadWork(instance);
  1127. }
  1128. /**
  1129. * @brief This routine instantiates one script.
  1130. */
  1131. private void LoadThreadWork(XMRInstance instance)
  1132. {
  1133. // Compile and load the script in memory.
  1134. ArrayList errors = new ArrayList();
  1135. Exception initerr = null;
  1136. try
  1137. {
  1138. instance.Initialize(this, m_ScriptBasePath, m_StackSize, m_HeapSize, errors);
  1139. }
  1140. catch(Exception e1)
  1141. {
  1142. initerr = e1;
  1143. }
  1144. if(initerr != null && !instance.m_ForceRecomp && initerr is CVVMismatchException)
  1145. {
  1146. UUID itemID = instance.m_ItemID;
  1147. Verbose("[YEngine]: {0}/{2} first load failed ({1}), retrying after recompile",
  1148. itemID.ToString(), initerr.Message, instance.m_Item.AssetID.ToString());
  1149. Verbose("[YEngine]:\n{0}", initerr.ToString());
  1150. initerr = null;
  1151. errors = new ArrayList();
  1152. instance.m_ForceRecomp = true;
  1153. try
  1154. {
  1155. instance.Initialize(this, m_ScriptBasePath, m_StackSize, m_HeapSize, errors);
  1156. }
  1157. catch(Exception e2)
  1158. {
  1159. initerr = e2;
  1160. }
  1161. }
  1162. if(initerr != null)
  1163. {
  1164. UUID itemID = instance.m_ItemID;
  1165. Verbose("[YEngine]: Error starting script {0}/{2}: {1}",
  1166. itemID.ToString(), initerr.Message, instance.m_Item.AssetID.ToString());
  1167. if(initerr.Message != "compilation errors")
  1168. {
  1169. Verbose("[YEngine]: - " + instance.m_Part.GetWorldPosition() + " " + instance.m_DescName);
  1170. Verbose("[YEngine]: exception:\n{0}", initerr.ToString());
  1171. }
  1172. OnRemoveScript(0, itemID);
  1173. // Post errors where GetScriptErrors() can see them.
  1174. if(errors.Count == 0)
  1175. errors.Add(initerr.Message);
  1176. else
  1177. {
  1178. foreach(Object err in errors)
  1179. {
  1180. if(m_ScriptDebug)
  1181. m_log.DebugFormat("[YEngine]: {0}", err.ToString());
  1182. }
  1183. }
  1184. lock(m_ScriptErrors)
  1185. m_ScriptErrors[instance.m_ItemID] = errors;
  1186. return;
  1187. }
  1188. // Tell GetScriptErrors() that we have finished compiling/loading
  1189. // successfully (by posting a 0 element array).
  1190. lock(m_ScriptErrors)
  1191. {
  1192. if(instance.m_IState != XMRInstState.CONSTRUCT)
  1193. throw new Exception("bad state");
  1194. m_ScriptErrors[instance.m_ItemID] = noScriptErrors;
  1195. }
  1196. // Transition from CONSTRUCT->ONSTARTQ and give to RunScriptThread().
  1197. // Put it on the start queue so it will run any queued event handlers,
  1198. // such as state_entry() or on_rez(). If there aren't any queued, it
  1199. // will just go to idle state when RunOne() tries to dequeue an event.
  1200. lock(instance.m_QueueLock)
  1201. {
  1202. if(instance.m_IState != XMRInstState.CONSTRUCT)
  1203. throw new Exception("bad state");
  1204. instance.m_IState = XMRInstState.ONSTARTQ;
  1205. if(!instance.m_Running)
  1206. instance.EmptyEventQueues();
  1207. }
  1208. QueueToStart(instance);
  1209. }
  1210. public void OnRemoveScript(uint localID, UUID itemID)
  1211. {
  1212. TraceCalls("[YEngine]: OnRemoveScript(...,{0})", itemID.ToString());
  1213. // Remove from our list of known scripts.
  1214. // After this, no more events can queue because we won't be
  1215. // able to translate the itemID to an XMRInstance pointer.
  1216. XMRInstance instance = null;
  1217. lock(m_InstancesDict)
  1218. {
  1219. m_LockedDict = "OnRemoveScript:" + itemID.ToString();
  1220. // Tell the instance to free off everything it can.
  1221. if(!m_InstancesDict.TryGetValue(itemID, out instance))
  1222. {
  1223. m_LockedDict = "~OnRemoveScript";
  1224. return;
  1225. }
  1226. // Tell it to stop executing anything.
  1227. instance.suspendOnCheckRunHold = true;
  1228. // Remove it from our list of known script instances
  1229. // mostly so no more events can queue to it.
  1230. m_InstancesDict.Remove(itemID);
  1231. List<UUID> itemIDList;
  1232. if(m_ObjectItemList.TryGetValue(instance.m_PartUUID, out itemIDList))
  1233. {
  1234. itemIDList.Remove(itemID);
  1235. if(itemIDList.Count == 0)
  1236. {
  1237. m_ObjectItemList.Remove(instance.m_PartUUID);
  1238. m_ObjectInstArray.Remove(instance.m_PartUUID);
  1239. }
  1240. else
  1241. m_ObjectInstArray[instance.m_PartUUID] = null;
  1242. }
  1243. // Delete the .state file as any needed contents were fetched with GetXMLState()
  1244. // and stored on the database server.
  1245. string stateFileName = XMRInstance.GetStateFileName(m_ScriptBasePath, itemID);
  1246. File.Delete(stateFileName);
  1247. ScriptRemoved handlerScriptRemoved = OnScriptRemoved;
  1248. if(handlerScriptRemoved != null)
  1249. handlerScriptRemoved(itemID);
  1250. m_LockedDict = "~~OnRemoveScript";
  1251. }
  1252. // Free off its stack and fun things like that.
  1253. // If it is running, abort it.
  1254. instance.Dispose();
  1255. }
  1256. public void OnScriptReset(uint localID, UUID itemID)
  1257. {
  1258. TraceCalls("[YEngine]: YEngine.OnScriptReset({0},{1})", localID.ToString(), itemID.ToString());
  1259. ResetScript(itemID);
  1260. }
  1261. public void OnStartScript(uint localID, UUID itemID)
  1262. {
  1263. XMRInstance instance = GetInstance(itemID);
  1264. if(instance != null)
  1265. instance.Running = true;
  1266. }
  1267. public void OnStopScript(uint localID, UUID itemID)
  1268. {
  1269. XMRInstance instance = GetInstance(itemID);
  1270. if(instance != null)
  1271. instance.Running = false;
  1272. }
  1273. public void OnGetScriptRunning(IClientAPI controllingClient,
  1274. UUID objectID, UUID itemID)
  1275. {
  1276. XMRInstance instance = GetInstance(itemID);
  1277. if(instance != null)
  1278. {
  1279. TraceCalls("[YEngine]: YEngine.OnGetScriptRunning({0},{1})", objectID.ToString(), itemID.ToString());
  1280. IEventQueue eq = World.RequestModuleInterface<IEventQueue>();
  1281. if(eq == null)
  1282. {
  1283. controllingClient.SendScriptRunningReply(objectID, itemID,
  1284. instance.Running);
  1285. }
  1286. else
  1287. {
  1288. eq.ScriptRunningEvent(objectID, itemID, instance.Running, controllingClient.AgentId);
  1289. }
  1290. }
  1291. }
  1292. public bool HasScript(UUID itemID, out bool running)
  1293. {
  1294. XMRInstance instance = GetInstance(itemID);
  1295. if(instance == null)
  1296. {
  1297. running = true;
  1298. return false;
  1299. }
  1300. running = instance.Running;
  1301. return true;
  1302. }
  1303. /**
  1304. * @brief Called once per frame update to see if scripts have
  1305. * any such work to do.
  1306. */
  1307. private void OnFrame()
  1308. {
  1309. if(m_FrameUpdateList != null)
  1310. {
  1311. ThreadStart frameupdates;
  1312. lock(m_FrameUpdateLock)
  1313. {
  1314. frameupdates = m_FrameUpdateList;
  1315. m_FrameUpdateList = null;
  1316. }
  1317. frameupdates();
  1318. }
  1319. }
  1320. /**
  1321. * @brief Add a one-shot delegate to list of things to do
  1322. * synchronized with frame updates.
  1323. */
  1324. public void AddOnFrameUpdate(ThreadStart thunk)
  1325. {
  1326. lock(m_FrameUpdateLock)
  1327. m_FrameUpdateList += thunk;
  1328. }
  1329. /**
  1330. * @brief Gets called early as part of shutdown,
  1331. * right after "Persisting changed objects" message.
  1332. */
  1333. public void OnShutdown()
  1334. {
  1335. TraceCalls("[YEngine]: YEngine.OnShutdown()");
  1336. }
  1337. /**
  1338. * @brief Queue an instance to the StartQueue so it will run.
  1339. * This queue is used for instances that have just had
  1340. * an event queued to them when they were previously
  1341. * idle. It must only be called by the thread that
  1342. * transitioned the thread to XMRInstState.ONSTARTQ so
  1343. * we don't get two threads trying to queue the same
  1344. * instance to the m_StartQueue at the same time.
  1345. */
  1346. public void QueueToStart(XMRInstance inst)
  1347. {
  1348. if (inst.m_IState != XMRInstState.ONSTARTQ)
  1349. throw new Exception("bad state");
  1350. lock (m_StartQueue)
  1351. m_StartQueue.InsertTail(inst);
  1352. WakeUpOne();
  1353. }
  1354. public void QueueToYield(XMRInstance inst)
  1355. {
  1356. if (inst.m_IState != XMRInstState.ONYIELDQ)
  1357. throw new Exception("bad state");
  1358. lock (m_YieldQueue)
  1359. m_YieldQueue.InsertTail(inst);
  1360. WakeUpOne();
  1361. }
  1362. public void RemoveFromSleep(XMRInstance inst)
  1363. {
  1364. lock (m_SleepQueue)
  1365. {
  1366. if (inst.m_IState != XMRInstState.ONSLEEPQ)
  1367. return;
  1368. m_SleepQueue.Remove(inst);
  1369. inst.m_IState = XMRInstState.REMDFROMSLPQ;
  1370. }
  1371. }
  1372. /**
  1373. * @brief A script may be sleeping, in which case we wake it.
  1374. */
  1375. public void WakeFromSleep(XMRInstance inst)
  1376. {
  1377. // Remove from sleep queue unless someone else already woke it.
  1378. lock(m_SleepQueue)
  1379. {
  1380. if(inst.m_IState != XMRInstState.ONSLEEPQ)
  1381. return;
  1382. m_SleepQueue.Remove(inst);
  1383. inst.m_IState = XMRInstState.REMDFROMSLPQ;
  1384. }
  1385. // Put on end of list of scripts that are ready to run.
  1386. lock(m_YieldQueue)
  1387. {
  1388. inst.m_IState = XMRInstState.ONYIELDQ;
  1389. m_YieldQueue.InsertTail(inst);
  1390. }
  1391. // Make sure the OS thread is running so it will see the script.
  1392. WakeUpOne();
  1393. }
  1394. /**
  1395. * @brief An instance has just finished running for now,
  1396. * figure out what to do with it next.
  1397. * @param inst = instance in question, not on any queue at the moment
  1398. * @param newIState = its new state
  1399. * @returns with instance inserted onto proper queue (if any)
  1400. */
  1401. public void HandleNewIState(XMRInstance inst, XMRInstState newIState)
  1402. {
  1403. // RunOne() should have left the instance in RUNNING state.
  1404. if(inst.m_IState != XMRInstState.RUNNING)
  1405. throw new Exception("bad state");
  1406. // Now see what RunOne() wants us to do with the instance next.
  1407. switch(newIState)
  1408. {
  1409. // Instance has set m_SleepUntil to when it wants to sleep until.
  1410. // So insert instance in sleep queue by ascending wake time.
  1411. // Then wake the timer thread if this is the new first entry
  1412. // so it will reset its timer.
  1413. case XMRInstState.ONSLEEPQ:
  1414. lock(m_SleepQueue)
  1415. {
  1416. XMRInstance after;
  1417. inst.m_IState = XMRInstState.ONSLEEPQ;
  1418. for(after = m_SleepQueue.PeekHead(); after != null; after = after.m_NextInst)
  1419. {
  1420. if(after.m_SleepUntil > inst.m_SleepUntil)
  1421. break;
  1422. }
  1423. m_SleepQueue.InsertBefore(inst, after);
  1424. if(m_SleepQueue.PeekHead() == inst)
  1425. Monitor.Pulse(m_SleepQueue);
  1426. }
  1427. break;
  1428. // Instance just took a long time to run and got wacked by the
  1429. // slicer. So put on end of yield queue to let someone else
  1430. // run. If there is no one else, it will run again right away.
  1431. case XMRInstState.ONYIELDQ:
  1432. lock(m_YieldQueue)
  1433. {
  1434. inst.m_IState = XMRInstState.ONYIELDQ;
  1435. m_YieldQueue.InsertTail(inst);
  1436. }
  1437. break;
  1438. // Instance finished executing an event handler. So if there is
  1439. // another event queued for it, put it on the start queue so it
  1440. // will process the new event. Otherwise, mark it idle and the
  1441. // next event to queue to it will start it up.
  1442. case XMRInstState.FINISHED:
  1443. Monitor.Enter(inst.m_QueueLock);
  1444. if(!inst.m_Suspended && (inst.m_EventQueue.Count > 0))
  1445. {
  1446. inst.m_IState = XMRInstState.ONSTARTQ;
  1447. Monitor.Exit(inst.m_QueueLock);
  1448. lock(m_StartQueue)
  1449. m_StartQueue.InsertTail(inst);
  1450. }
  1451. else
  1452. {
  1453. inst.m_IState = XMRInstState.IDLE;
  1454. Monitor.Exit(inst.m_QueueLock);
  1455. }
  1456. break;
  1457. // Its m_SuspendCount > 0.
  1458. // Don't put it on any queue and it won't run.
  1459. // Since it's not IDLE, even queuing an event won't start it.
  1460. case XMRInstState.SUSPENDED:
  1461. inst.m_IState = XMRInstState.SUSPENDED;
  1462. break;
  1463. // It has been disposed of.
  1464. // Just set the new state and all refs should theoretically drop off
  1465. // as the instance is no longer in any list.
  1466. case XMRInstState.DISPOSED:
  1467. inst.m_IState = XMRInstState.DISPOSED;
  1468. break;
  1469. // RunOne returned something bad.
  1470. default:
  1471. throw new Exception("bad new state");
  1472. }
  1473. }
  1474. /**
  1475. * @brief Thread that moves instances from the Sleep queue to the Yield queue.
  1476. */
  1477. private void RunSleepThread()
  1478. {
  1479. double deltaTS;
  1480. int deltaMS;
  1481. XMRInstance inst;
  1482. while(true)
  1483. {
  1484. lock(m_SleepQueue)
  1485. {
  1486. // Wait here until there is a script on the timer queue that has expired.
  1487. while(true)
  1488. {
  1489. UpdateMyThread();
  1490. if(m_Exiting)
  1491. {
  1492. MyThreadExiting();
  1493. return;
  1494. }
  1495. inst = m_SleepQueue.PeekHead();
  1496. if(inst == null)
  1497. {
  1498. Monitor.Wait(m_SleepQueue, Watchdog.DEFAULT_WATCHDOG_TIMEOUT_MS / 2);
  1499. continue;
  1500. }
  1501. if(inst.m_IState != XMRInstState.ONSLEEPQ)
  1502. throw new Exception("bad state");
  1503. deltaTS = (inst.m_SleepUntil - DateTime.UtcNow).TotalMilliseconds;
  1504. if(deltaTS <= 0.0)
  1505. break;
  1506. deltaMS = Int32.MaxValue;
  1507. if(deltaTS < Int32.MaxValue)
  1508. deltaMS = (int)deltaTS;
  1509. if(deltaMS > Watchdog.DEFAULT_WATCHDOG_TIMEOUT_MS / 2)
  1510. deltaMS = Watchdog.DEFAULT_WATCHDOG_TIMEOUT_MS / 2;
  1511. Monitor.Wait(m_SleepQueue, deltaMS);
  1512. }
  1513. // Remove the expired entry from the timer queue.
  1514. m_SleepQueue.RemoveHead();
  1515. inst.m_IState = XMRInstState.REMDFROMSLPQ;
  1516. }
  1517. // Post the script to the yield queue so it will run and wake a script thread to run it.
  1518. lock(m_YieldQueue)
  1519. {
  1520. inst.m_IState = XMRInstState.ONYIELDQ;
  1521. m_YieldQueue.InsertTail(inst);
  1522. }
  1523. WakeUpOne();
  1524. }
  1525. }
  1526. public void Suspend(UUID itemID, int ms)
  1527. {
  1528. XMRInstance instance = GetInstance(itemID);
  1529. if(instance != null)
  1530. instance.Sleep(ms);
  1531. }
  1532. public void Die(UUID itemID)
  1533. {
  1534. XMRInstance instance = GetInstance(itemID);
  1535. if(instance != null)
  1536. {
  1537. TraceCalls("[YEngine]: YEngine.Die({0})", itemID.ToString());
  1538. instance.Die();
  1539. }
  1540. }
  1541. /**
  1542. * @brief Get specific script instance for which OnRezScript()
  1543. * has been called for an YEngine script, and that
  1544. * OnRemoveScript() has not been called since.
  1545. * @param itemID = as passed to OnRezScript() identifying a specific script instance
  1546. * @returns null: not one of our scripts (maybe XEngine etc)
  1547. * else: points to the script instance
  1548. */
  1549. public XMRInstance GetInstance(UUID itemID)
  1550. {
  1551. XMRInstance instance;
  1552. lock(m_InstancesDict)
  1553. {
  1554. if(!m_InstancesDict.TryGetValue(itemID, out instance))
  1555. instance = null;
  1556. }
  1557. return instance;
  1558. }
  1559. // Called occasionally to write script state to .state file so the
  1560. // script will restart from its last known state if the region crashes
  1561. // and gets restarted.
  1562. private void DoMaintenance(object source, ElapsedEventArgs e)
  1563. {
  1564. XMRInstance[] instanceArray;
  1565. lock(m_InstancesDict)
  1566. instanceArray = System.Linq.Enumerable.ToArray(m_InstancesDict.Values);
  1567. foreach(XMRInstance ins in instanceArray)
  1568. {
  1569. // Don't save attachments
  1570. if(ins.m_Part.ParentGroup.IsAttachment)
  1571. continue;
  1572. ins.GetExecutionState(new XmlDocument());
  1573. }
  1574. }
  1575. /**
  1576. * @brief Retrieve errors generated by a previous call to OnRezScript().
  1577. * We are guaranteed this routine will not be called before the
  1578. * corresponding OnRezScript() has returned. It blocks until the
  1579. * compile has completed.
  1580. */
  1581. public ArrayList GetScriptErrors(UUID itemID)
  1582. {
  1583. ArrayList errors;
  1584. lock(m_ScriptErrors)
  1585. {
  1586. while(!m_ScriptErrors.TryGetValue(itemID, out errors))
  1587. {
  1588. Monitor.Wait(m_ScriptErrors);
  1589. }
  1590. m_ScriptErrors.Remove(itemID);
  1591. }
  1592. return errors;
  1593. }
  1594. /**
  1595. * @brief Return a list of all script execution times.
  1596. */
  1597. public Dictionary<uint, float> GetObjectScriptsExecutionTimes()
  1598. {
  1599. Dictionary<uint, float> topScripts = new Dictionary<uint, float>();
  1600. lock(m_InstancesDict)
  1601. {
  1602. foreach(XMRInstance instance in m_InstancesDict.Values)
  1603. {
  1604. uint rootLocalID = instance.m_Part.ParentGroup.LocalId;
  1605. float oldTotal;
  1606. if(!topScripts.TryGetValue(rootLocalID, out oldTotal))
  1607. oldTotal = 0;
  1608. topScripts[rootLocalID] = (float)instance.m_CPUTime + oldTotal;
  1609. }
  1610. }
  1611. return topScripts;
  1612. }
  1613. /**
  1614. * @brief A float the value is a representative execution time in
  1615. * milliseconds of all scripts in the link set.
  1616. * @param itemIDs = list of scripts in the link set
  1617. * @returns milliseconds for all those scripts
  1618. */
  1619. public float GetScriptExecutionTime(List<UUID> itemIDs)
  1620. {
  1621. if((itemIDs == null) || (itemIDs.Count == 0))
  1622. return 0;
  1623. float time = 0;
  1624. foreach(UUID itemID in itemIDs)
  1625. {
  1626. XMRInstance instance = GetInstance(itemID);
  1627. if((instance != null) && instance.Running)
  1628. time += (float)instance.m_CPUTime;
  1629. }
  1630. return time;
  1631. }
  1632. /**
  1633. * @brief Block script from dequeuing events.
  1634. */
  1635. public void SuspendScript(UUID itemID)
  1636. {
  1637. XMRInstance instance = GetInstance(itemID);
  1638. if(instance != null)
  1639. {
  1640. TraceCalls("[YEngine]: YEngine.SuspendScript({0})", itemID.ToString());
  1641. instance.SuspendIt();
  1642. }
  1643. }
  1644. /**
  1645. * @brief Allow script to dequeue events.
  1646. */
  1647. public void ResumeScript(UUID itemID)
  1648. {
  1649. XMRInstance instance = GetInstance(itemID);
  1650. if(instance != null)
  1651. {
  1652. TraceCalls("[YEngine]: YEngine.ResumeScript({0})", itemID.ToString());
  1653. instance.ResumeIt();
  1654. }
  1655. else
  1656. {
  1657. // probably an XEngine script
  1658. }
  1659. }
  1660. /**
  1661. * @brief Rebuild m_ObjectInstArray[partUUID] from m_ObjectItemList[partUUID]
  1662. * @param partUUID = which object in scene to rebuild for
  1663. */
  1664. private XMRInstance[] RebuildObjectInstArray(UUID partUUID)
  1665. {
  1666. List<UUID> itemIDList = m_ObjectItemList[partUUID];
  1667. int n = 0;
  1668. foreach(UUID itemID in itemIDList)
  1669. {
  1670. if(m_InstancesDict.ContainsKey(itemID))
  1671. n++;
  1672. }
  1673. XMRInstance[] a = new XMRInstance[n];
  1674. n = 0;
  1675. foreach(UUID itemID in itemIDList)
  1676. {
  1677. if(m_InstancesDict.TryGetValue(itemID, out a[n]))
  1678. n++;
  1679. }
  1680. m_ObjectInstArray[partUUID] = a;
  1681. return a;
  1682. }
  1683. public void TraceCalls(string format, params object[] args)
  1684. {
  1685. if(m_TraceCalls)
  1686. m_log.DebugFormat(format, args);
  1687. }
  1688. public void Verbose(string format, params object[] args)
  1689. {
  1690. if(m_Verbose)
  1691. m_log.DebugFormat(format, args);
  1692. }
  1693. /**
  1694. * @brief Manage our threads.
  1695. */
  1696. public static Thread StartMyThread(ThreadStart start, string name, ThreadPriority priority)
  1697. {
  1698. m_log.Debug("[YEngine]: starting thread " + name);
  1699. Thread thread = WorkManager.StartThread(start, name, priority, false, false);
  1700. return thread;
  1701. }
  1702. public static void UpdateMyThread()
  1703. {
  1704. Watchdog.UpdateThread();
  1705. }
  1706. public static void MyThreadExiting()
  1707. {
  1708. Watchdog.RemoveThread(true);
  1709. }
  1710. }
  1711. }