XMREngine.cs 78 KB

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