ScriptInstance.cs 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972
  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 OpenSim Project nor the
  13. * names of its contributors may be used to endorse or promote products
  14. * derived from this software without specific prior written permission.
  15. *
  16. * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
  17. * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  18. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  19. * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
  20. * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  21. * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  22. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  23. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  24. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  25. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  26. */
  27. using System;
  28. using System.IO;
  29. using System.Runtime.Remoting;
  30. using System.Runtime.Remoting.Lifetime;
  31. using System.Threading;
  32. using System.Collections;
  33. using System.Collections.Generic;
  34. using System.Security.Policy;
  35. using System.Reflection;
  36. using System.Globalization;
  37. using System.Xml;
  38. using OpenMetaverse;
  39. using log4net;
  40. using Nini.Config;
  41. using Amib.Threading;
  42. using OpenSim.Framework;
  43. using OpenSim.Region.CoreModules;
  44. using OpenSim.Region.Framework.Scenes;
  45. using OpenSim.Region.Framework.Interfaces;
  46. using OpenSim.Region.ScriptEngine.Shared;
  47. using OpenSim.Region.ScriptEngine.Shared.Api;
  48. using OpenSim.Region.ScriptEngine.Shared.Api.Runtime;
  49. using OpenSim.Region.ScriptEngine.Shared.ScriptBase;
  50. using OpenSim.Region.ScriptEngine.Shared.CodeTools;
  51. using OpenSim.Region.ScriptEngine.Interfaces;
  52. namespace OpenSim.Region.ScriptEngine.Shared.Instance
  53. {
  54. public class ScriptInstance : IScriptInstance
  55. {
  56. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  57. private IScriptEngine m_Engine;
  58. private IScriptWorkItem m_CurrentResult = null;
  59. private Queue m_EventQueue = new Queue(32);
  60. private bool m_RunEvents = false;
  61. private UUID m_ItemID;
  62. private uint m_LocalID;
  63. private UUID m_ObjectID;
  64. private UUID m_AssetID;
  65. private IScript m_Script;
  66. private UUID m_AppDomain;
  67. private DetectParams[] m_DetectParams;
  68. private bool m_TimerQueued;
  69. private DateTime m_EventStart;
  70. private bool m_InEvent;
  71. private string m_PrimName;
  72. private string m_ScriptName;
  73. private string m_Assembly;
  74. private int m_StartParam = 0;
  75. private string m_CurrentEvent = String.Empty;
  76. private bool m_InSelfDelete = false;
  77. private int m_MaxScriptQueue;
  78. private bool m_SaveState = true;
  79. private bool m_ShuttingDown = false;
  80. private int m_ControlEventsInQueue = 0;
  81. private int m_LastControlLevel = 0;
  82. private bool m_CollisionInQueue = false;
  83. private TaskInventoryItem m_thisScriptTask;
  84. // The following is for setting a minimum delay between events
  85. private double m_minEventDelay = 0;
  86. private long m_eventDelayTicks = 0;
  87. private long m_nextEventTimeTicks = 0;
  88. private bool m_startOnInit = true;
  89. private StateSource m_stateSource;
  90. private bool m_postOnRez;
  91. private bool m_startedFromSavedState = false;
  92. //private ISponsor m_ScriptSponsor;
  93. private Dictionary<KeyValuePair<int, int>, KeyValuePair<int, int>>
  94. m_LineMap;
  95. public Dictionary<KeyValuePair<int, int>, KeyValuePair<int, int>>
  96. LineMap
  97. {
  98. get { return m_LineMap; }
  99. set { m_LineMap = value; }
  100. }
  101. private Dictionary<string,IScriptApi> m_Apis = new Dictionary<string,IScriptApi>();
  102. // Script state
  103. private string m_State="default";
  104. public Object[] PluginData = new Object[0];
  105. /// <summary>
  106. /// Used by llMinEventDelay to suppress events happening any faster than this speed.
  107. /// This currently restricts all events in one go. Not sure if each event type has
  108. /// its own check so take the simple route first.
  109. /// </summary>
  110. public double MinEventDelay
  111. {
  112. get { return m_minEventDelay; }
  113. set
  114. {
  115. if (value > 0.001)
  116. m_minEventDelay = value;
  117. else
  118. m_minEventDelay = 0.0;
  119. m_eventDelayTicks = (long)(m_minEventDelay * 10000000L);
  120. m_nextEventTimeTicks = DateTime.Now.Ticks;
  121. }
  122. }
  123. public bool Running
  124. {
  125. get { return m_RunEvents; }
  126. set { m_RunEvents = value; }
  127. }
  128. public bool ShuttingDown
  129. {
  130. get { return m_ShuttingDown; }
  131. set { m_ShuttingDown = value; }
  132. }
  133. public string State
  134. {
  135. get { return m_State; }
  136. set { m_State = value; }
  137. }
  138. public IScriptEngine Engine
  139. {
  140. get { return m_Engine; }
  141. }
  142. public UUID AppDomain
  143. {
  144. get { return m_AppDomain; }
  145. set { m_AppDomain = value; }
  146. }
  147. public string PrimName
  148. {
  149. get { return m_PrimName; }
  150. }
  151. public string ScriptName
  152. {
  153. get { return m_ScriptName; }
  154. }
  155. public UUID ItemID
  156. {
  157. get { return m_ItemID; }
  158. }
  159. public UUID ObjectID
  160. {
  161. get { return m_ObjectID; }
  162. }
  163. public uint LocalID
  164. {
  165. get { return m_LocalID; }
  166. }
  167. public UUID AssetID
  168. {
  169. get { return m_AssetID; }
  170. }
  171. public Queue EventQueue
  172. {
  173. get { return m_EventQueue; }
  174. }
  175. public void ClearQueue()
  176. {
  177. m_TimerQueued = false;
  178. m_EventQueue.Clear();
  179. }
  180. public int StartParam
  181. {
  182. get { return m_StartParam; }
  183. set { m_StartParam = value; }
  184. }
  185. public TaskInventoryItem ScriptTask
  186. {
  187. get { return m_thisScriptTask; }
  188. }
  189. public ScriptInstance(IScriptEngine engine, SceneObjectPart part,
  190. UUID itemID, UUID assetID, string assembly,
  191. AppDomain dom, string primName, string scriptName,
  192. int startParam, bool postOnRez, StateSource stateSource,
  193. int maxScriptQueue)
  194. {
  195. m_Engine = engine;
  196. m_LocalID = part.LocalId;
  197. m_ObjectID = part.UUID;
  198. m_ItemID = itemID;
  199. m_AssetID = assetID;
  200. m_PrimName = primName;
  201. m_ScriptName = scriptName;
  202. m_Assembly = assembly;
  203. m_StartParam = startParam;
  204. m_MaxScriptQueue = maxScriptQueue;
  205. m_stateSource = stateSource;
  206. m_postOnRez = postOnRez;
  207. if (part != null)
  208. {
  209. lock (part.TaskInventory)
  210. {
  211. if (part.TaskInventory.ContainsKey(m_ItemID))
  212. {
  213. m_thisScriptTask = part.TaskInventory[m_ItemID];
  214. }
  215. }
  216. }
  217. ApiManager am = new ApiManager();
  218. foreach (string api in am.GetApis())
  219. {
  220. m_Apis[api] = am.CreateApi(api);
  221. m_Apis[api].Initialize(engine, part, m_LocalID, itemID);
  222. }
  223. try
  224. {
  225. m_Script = (IScript)dom.CreateInstanceAndUnwrap(
  226. Path.GetFileNameWithoutExtension(assembly),
  227. "SecondLife.Script");
  228. // Add a sponsor to the script
  229. // ISponsor scriptSponsor = new ScriptSponsor();
  230. // ILease lease = (ILease)RemotingServices.GetLifetimeService(m_Script as MarshalByRefObject);
  231. // lease.Register(scriptSponsor);
  232. //m_ScriptSponsor = scriptSponsor;
  233. }
  234. catch (Exception e)
  235. {
  236. m_log.ErrorFormat("[Script] Error loading assembly {0}\n"+e.ToString(), assembly);
  237. }
  238. try
  239. {
  240. foreach (KeyValuePair<string,IScriptApi> kv in m_Apis)
  241. {
  242. m_Script.InitApi(kv.Key, kv.Value);
  243. }
  244. // m_log.Debug("[Script] Script instance created");
  245. part.SetScriptEvents(m_ItemID,
  246. (int)m_Script.GetStateEventFlags(State));
  247. }
  248. catch (Exception e)
  249. {
  250. m_log.Error("[Script] Error loading script instance\n"+e.ToString());
  251. return;
  252. }
  253. m_SaveState = true;
  254. string savedState = Path.Combine(Path.GetDirectoryName(assembly),
  255. m_ItemID.ToString() + ".state");
  256. if (File.Exists(savedState))
  257. {
  258. string xml = String.Empty;
  259. try
  260. {
  261. FileInfo fi = new FileInfo(savedState);
  262. int size=(int)fi.Length;
  263. if (size < 512000)
  264. {
  265. using (FileStream fs = File.Open(savedState,
  266. FileMode.Open, FileAccess.Read, FileShare.None))
  267. {
  268. System.Text.ASCIIEncoding enc =
  269. new System.Text.ASCIIEncoding();
  270. Byte[] data = new Byte[size];
  271. fs.Read(data, 0, size);
  272. xml = enc.GetString(data);
  273. ScriptSerializer.Deserialize(xml, this);
  274. AsyncCommandManager.CreateFromData(m_Engine,
  275. m_LocalID, m_ItemID, m_ObjectID,
  276. PluginData);
  277. // m_log.DebugFormat("[Script] Successfully retrieved state for script {0}.{1}", m_PrimName, m_ScriptName);
  278. part.SetScriptEvents(m_ItemID,
  279. (int)m_Script.GetStateEventFlags(State));
  280. if (m_RunEvents && (!m_ShuttingDown))
  281. {
  282. m_RunEvents = false;
  283. }
  284. else
  285. {
  286. m_RunEvents = false;
  287. m_startOnInit = false;
  288. }
  289. // we get new rez events on sim restart, too
  290. // but if there is state, then we fire the change
  291. // event
  292. // We loaded state, don't force a re-save
  293. m_SaveState = false;
  294. m_startedFromSavedState = true;
  295. }
  296. }
  297. else
  298. {
  299. m_log.Error("[Script] Unable to load script state: Memory limit exceeded");
  300. }
  301. }
  302. catch (Exception e)
  303. {
  304. m_log.ErrorFormat("[Script] Unable to load script state from xml: {0}\n"+e.ToString(), xml);
  305. }
  306. }
  307. else
  308. {
  309. ScenePresence presence = m_Engine.World.GetScenePresence(part.OwnerID);
  310. if (presence != null && (!postOnRez))
  311. presence.ControllingClient.SendAgentAlertMessage("Compile successful", false);
  312. // m_log.ErrorFormat("[Script] Unable to load script state, file not found");
  313. }
  314. }
  315. public void Init()
  316. {
  317. if (!m_startOnInit) return;
  318. if (m_startedFromSavedState)
  319. {
  320. Start();
  321. if (m_postOnRez)
  322. {
  323. PostEvent(new EventParams("on_rez",
  324. new Object[] {new LSL_Types.LSLInteger(m_StartParam)}, new DetectParams[0]));
  325. }
  326. if (m_stateSource == StateSource.NewRez)
  327. {
  328. // m_log.Debug("[Script] Posted changed(CHANGED_REGION_RESTART) to script");
  329. PostEvent(new EventParams("changed",
  330. new Object[] {new LSL_Types.LSLInteger(256)}, new DetectParams[0]));
  331. }
  332. else if (m_stateSource == StateSource.PrimCrossing)
  333. {
  334. // CHANGED_REGION
  335. PostEvent(new EventParams("changed",
  336. new Object[] {new LSL_Types.LSLInteger(512)}, new DetectParams[0]));
  337. }
  338. }
  339. else
  340. {
  341. Start();
  342. PostEvent(new EventParams("state_entry",
  343. new Object[0], new DetectParams[0]));
  344. if (m_postOnRez)
  345. {
  346. PostEvent(new EventParams("on_rez",
  347. new Object[] {new LSL_Types.LSLInteger(m_StartParam)}, new DetectParams[0]));
  348. }
  349. }
  350. }
  351. private void ReleaseControls()
  352. {
  353. SceneObjectPart part = m_Engine.World.GetSceneObjectPart(m_LocalID);
  354. if (part != null)
  355. {
  356. int permsMask;
  357. UUID permsGranter;
  358. lock (part.TaskInventory)
  359. {
  360. if (!part.TaskInventory.ContainsKey(m_ItemID))
  361. return;
  362. permsGranter = part.TaskInventory[m_ItemID].PermsGranter;
  363. permsMask = part.TaskInventory[m_ItemID].PermsMask;
  364. }
  365. if ((permsMask & ScriptBaseClass.PERMISSION_TAKE_CONTROLS) != 0)
  366. {
  367. ScenePresence presence = m_Engine.World.GetScenePresence(permsGranter);
  368. if (presence != null)
  369. presence.UnRegisterControlEventsToScript(m_LocalID, m_ItemID);
  370. }
  371. }
  372. }
  373. public void DestroyScriptInstance()
  374. {
  375. ReleaseControls();
  376. AsyncCommandManager.RemoveScript(m_Engine, m_LocalID, m_ItemID);
  377. }
  378. public void RemoveState()
  379. {
  380. string savedState = Path.Combine(Path.GetDirectoryName(m_Assembly),
  381. m_ItemID.ToString() + ".state");
  382. try
  383. {
  384. File.Delete(savedState);
  385. }
  386. catch(Exception)
  387. {
  388. }
  389. }
  390. public void VarDump(Dictionary<string, object> vars)
  391. {
  392. m_log.Info("Variable dump for script "+ m_ItemID.ToString());
  393. foreach (KeyValuePair<string, object> v in vars)
  394. {
  395. m_log.Info("Variable: "+v.Key+" = "+v.Value.ToString());
  396. }
  397. }
  398. public void Start()
  399. {
  400. lock (m_EventQueue)
  401. {
  402. if (Running)
  403. return;
  404. m_RunEvents = true;
  405. if (m_EventQueue.Count > 0)
  406. {
  407. if (m_CurrentResult == null)
  408. m_CurrentResult = m_Engine.QueueEventHandler(this);
  409. else
  410. m_log.Error("[Script] Tried to start a script that was already queued");
  411. }
  412. }
  413. }
  414. public bool Stop(int timeout)
  415. {
  416. IScriptWorkItem result;
  417. lock (m_EventQueue)
  418. {
  419. if (!Running)
  420. return true;
  421. if (m_CurrentResult == null)
  422. {
  423. m_RunEvents = false;
  424. return true;
  425. }
  426. if (m_CurrentResult.Cancel())
  427. {
  428. m_CurrentResult = null;
  429. m_RunEvents = false;
  430. return true;
  431. }
  432. result = m_CurrentResult;
  433. m_RunEvents = false;
  434. }
  435. if (result.Wait(new TimeSpan((long)timeout * 100000)))
  436. {
  437. return true;
  438. }
  439. lock (m_EventQueue)
  440. {
  441. result = m_CurrentResult;
  442. }
  443. if (result == null)
  444. return true;
  445. if (!m_InSelfDelete)
  446. result.Abort();
  447. lock (m_EventQueue)
  448. {
  449. m_CurrentResult = null;
  450. }
  451. return true;
  452. }
  453. public void SetState(string state)
  454. {
  455. if (state == State)
  456. return;
  457. PostEvent(new EventParams("state_exit", new Object[0],
  458. new DetectParams[0]));
  459. PostEvent(new EventParams("state", new Object[] { state },
  460. new DetectParams[0]));
  461. PostEvent(new EventParams("state_entry", new Object[0],
  462. new DetectParams[0]));
  463. throw new EventAbortException();
  464. }
  465. public void PostEvent(EventParams data)
  466. {
  467. // m_log.DebugFormat("[Script] Posted event {2} in state {3} to {0}.{1}",
  468. // m_PrimName, m_ScriptName, data.EventName, m_State);
  469. if (!Running)
  470. return;
  471. // If min event delay is set then ignore any events untill the time has expired
  472. // This currently only allows 1 event of any type in the given time period.
  473. // This may need extending to allow for a time for each individual event type.
  474. if (m_eventDelayTicks != 0)
  475. {
  476. if (DateTime.Now.Ticks < m_nextEventTimeTicks)
  477. return;
  478. m_nextEventTimeTicks = DateTime.Now.Ticks + m_eventDelayTicks;
  479. }
  480. lock (m_EventQueue)
  481. {
  482. if (m_EventQueue.Count >= m_MaxScriptQueue)
  483. return;
  484. if (data.EventName == "timer")
  485. {
  486. if (m_TimerQueued)
  487. return;
  488. m_TimerQueued = true;
  489. }
  490. if (data.EventName == "control")
  491. {
  492. int held = ((LSL_Types.LSLInteger)data.Params[1]).value;
  493. // int changed = ((LSL_Types.LSLInteger)data.Params[2]).value;
  494. // If the last message was a 0 (nothing held)
  495. // and this one is also nothing held, drop it
  496. //
  497. if (m_LastControlLevel == held && held == 0)
  498. return;
  499. // If there is one or more queued, then queue
  500. // only changed ones, else queue unconditionally
  501. //
  502. if (m_ControlEventsInQueue > 0)
  503. {
  504. if (m_LastControlLevel == held)
  505. return;
  506. }
  507. m_LastControlLevel = held;
  508. m_ControlEventsInQueue++;
  509. }
  510. if (data.EventName == "collision")
  511. {
  512. if (m_CollisionInQueue)
  513. return;
  514. if (data.DetectParams == null)
  515. return;
  516. m_CollisionInQueue = true;
  517. }
  518. m_EventQueue.Enqueue(data);
  519. if (m_CurrentResult == null)
  520. {
  521. m_CurrentResult = m_Engine.QueueEventHandler(this);
  522. }
  523. }
  524. }
  525. /// <summary>
  526. /// Process the next event queued for this script
  527. /// </summary>
  528. /// <returns></returns>
  529. public object EventProcessor()
  530. {
  531. lock (m_Script)
  532. {
  533. EventParams data = null;
  534. lock (m_EventQueue)
  535. {
  536. data = (EventParams) m_EventQueue.Dequeue();
  537. if (data == null) // Shouldn't happen
  538. {
  539. if ((m_EventQueue.Count > 0) && m_RunEvents && (!m_ShuttingDown))
  540. {
  541. m_CurrentResult = m_Engine.QueueEventHandler(this);
  542. }
  543. else
  544. {
  545. m_CurrentResult = null;
  546. }
  547. return 0;
  548. }
  549. if (data.EventName == "timer")
  550. m_TimerQueued = false;
  551. if (data.EventName == "control")
  552. {
  553. if (m_ControlEventsInQueue > 0)
  554. m_ControlEventsInQueue--;
  555. }
  556. if (data.EventName == "collision")
  557. m_CollisionInQueue = false;
  558. }
  559. //m_log.DebugFormat("[XENGINE]: Processing event {0} for {1}", data.EventName, this);
  560. m_DetectParams = data.DetectParams;
  561. if (data.EventName == "state") // Hardcoded state change
  562. {
  563. // m_log.DebugFormat("[Script] Script {0}.{1} state set to {2}",
  564. // m_PrimName, m_ScriptName, data.Params[0].ToString());
  565. m_State=data.Params[0].ToString();
  566. AsyncCommandManager.RemoveScript(m_Engine,
  567. m_LocalID, m_ItemID);
  568. SceneObjectPart part = m_Engine.World.GetSceneObjectPart(
  569. m_LocalID);
  570. if (part != null)
  571. {
  572. part.SetScriptEvents(m_ItemID,
  573. (int)m_Script.GetStateEventFlags(State));
  574. }
  575. }
  576. else
  577. {
  578. if (m_Engine.World.PipeEventsForScript(m_LocalID) ||
  579. data.EventName == "control") // Don't freeze avies!
  580. {
  581. SceneObjectPart part = m_Engine.World.GetSceneObjectPart(
  582. m_LocalID);
  583. // m_log.DebugFormat("[Script] Delivered event {2} in state {3} to {0}.{1}",
  584. // m_PrimName, m_ScriptName, data.EventName, m_State);
  585. try
  586. {
  587. m_CurrentEvent = data.EventName;
  588. m_EventStart = DateTime.Now;
  589. m_InEvent = true;
  590. m_Script.ExecuteEvent(State, data.EventName, data.Params);
  591. m_InEvent = false;
  592. m_CurrentEvent = String.Empty;
  593. if (m_SaveState)
  594. {
  595. // This will be the very first event we deliver
  596. // (state_entry) in default state
  597. //
  598. SaveState(m_Assembly);
  599. m_SaveState = false;
  600. }
  601. }
  602. catch (Exception e)
  603. {
  604. m_InEvent = false;
  605. m_CurrentEvent = String.Empty;
  606. if ((!(e is TargetInvocationException) || !(e.InnerException is SelfDeleteException)) && (!(e is ThreadAbortException)))
  607. {
  608. try
  609. {
  610. // DISPLAY ERROR INWORLD
  611. string text = FormatException(e);
  612. if (text.Length > 1000)
  613. text = text.Substring(0, 1000);
  614. m_Engine.World.SimChat(Utils.StringToBytes(text),
  615. ChatTypeEnum.DebugChannel, 2147483647,
  616. part.AbsolutePosition,
  617. part.Name, part.UUID, false);
  618. }
  619. catch (Exception e2) // LEGIT: User Scripting
  620. {
  621. m_log.Error("[Script]: "+
  622. "Error displaying error in-world: " +
  623. e2.ToString());
  624. m_log.Error("[Script]: " +
  625. "Errormessage: Error compiling script:\r\n" +
  626. e.ToString());
  627. }
  628. }
  629. else if ((e is TargetInvocationException) && (e.InnerException is SelfDeleteException))
  630. {
  631. m_InSelfDelete = true;
  632. if (part != null && part.ParentGroup != null)
  633. m_Engine.World.DeleteSceneObject(part.ParentGroup, false);
  634. }
  635. }
  636. }
  637. }
  638. lock (m_EventQueue)
  639. {
  640. if ((m_EventQueue.Count > 0) && m_RunEvents && (!m_ShuttingDown))
  641. {
  642. m_CurrentResult = m_Engine.QueueEventHandler(this);
  643. }
  644. else
  645. {
  646. m_CurrentResult = null;
  647. }
  648. }
  649. m_DetectParams = null;
  650. return 0;
  651. }
  652. }
  653. public int EventTime()
  654. {
  655. if (!m_InEvent)
  656. return 0;
  657. return (DateTime.Now - m_EventStart).Seconds;
  658. }
  659. public void ResetScript()
  660. {
  661. if (m_Script == null)
  662. return;
  663. bool running = Running;
  664. RemoveState();
  665. ReleaseControls();
  666. Stop(0);
  667. SceneObjectPart part=m_Engine.World.GetSceneObjectPart(m_LocalID);
  668. part.Inventory.GetInventoryItem(m_ItemID).PermsMask = 0;
  669. part.Inventory.GetInventoryItem(m_ItemID).PermsGranter = UUID.Zero;
  670. AsyncCommandManager.RemoveScript(m_Engine, m_LocalID, m_ItemID);
  671. m_EventQueue.Clear();
  672. m_Script.ResetVars();
  673. m_State = "default";
  674. part.SetScriptEvents(m_ItemID,
  675. (int)m_Script.GetStateEventFlags(State));
  676. if (running)
  677. Start();
  678. m_SaveState = true;
  679. PostEvent(new EventParams("state_entry",
  680. new Object[0], new DetectParams[0]));
  681. }
  682. public void ApiResetScript()
  683. {
  684. // bool running = Running;
  685. RemoveState();
  686. ReleaseControls();
  687. m_Script.ResetVars();
  688. SceneObjectPart part=m_Engine.World.GetSceneObjectPart(m_LocalID);
  689. part.Inventory.GetInventoryItem(m_ItemID).PermsMask = 0;
  690. part.Inventory.GetInventoryItem(m_ItemID).PermsGranter = UUID.Zero;
  691. AsyncCommandManager.RemoveScript(m_Engine, m_LocalID, m_ItemID);
  692. m_EventQueue.Clear();
  693. m_Script.ResetVars();
  694. m_State = "default";
  695. part.SetScriptEvents(m_ItemID,
  696. (int)m_Script.GetStateEventFlags(State));
  697. if (m_CurrentEvent != "state_entry")
  698. {
  699. m_SaveState = true;
  700. PostEvent(new EventParams("state_entry",
  701. new Object[0], new DetectParams[0]));
  702. throw new EventAbortException();
  703. }
  704. }
  705. public Dictionary<string, object> GetVars()
  706. {
  707. return m_Script.GetVars();
  708. }
  709. public void SetVars(Dictionary<string, object> vars)
  710. {
  711. m_Script.SetVars(vars);
  712. }
  713. public DetectParams GetDetectParams(int idx)
  714. {
  715. if (m_DetectParams == null)
  716. return null;
  717. if (idx < 0 || idx >= m_DetectParams.Length)
  718. return null;
  719. return m_DetectParams[idx];
  720. }
  721. public UUID GetDetectID(int idx)
  722. {
  723. if (m_DetectParams == null)
  724. return UUID.Zero;
  725. if (idx < 0 || idx >= m_DetectParams.Length)
  726. return UUID.Zero;
  727. return m_DetectParams[idx].Key;
  728. }
  729. public void SaveState(string assembly)
  730. {
  731. // If we're currently in an event, just tell it to save upon return
  732. //
  733. if (m_InEvent)
  734. {
  735. m_SaveState = true;
  736. return;
  737. }
  738. PluginData = AsyncCommandManager.GetSerializationData(m_Engine, m_ItemID);
  739. string xml = ScriptSerializer.Serialize(this);
  740. try
  741. {
  742. FileStream fs = File.Create(Path.Combine(Path.GetDirectoryName(assembly), m_ItemID.ToString() + ".state"));
  743. System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
  744. Byte[] buf = enc.GetBytes(xml);
  745. fs.Write(buf, 0, buf.Length);
  746. fs.Close();
  747. }
  748. catch(Exception e)
  749. {
  750. m_log.Error("Unable to save xml\n"+e.ToString());
  751. }
  752. if (!File.Exists(Path.Combine(Path.GetDirectoryName(assembly), m_ItemID.ToString() + ".state")))
  753. {
  754. throw new Exception("Completed persistence save, but no file was created");
  755. }
  756. }
  757. public IScriptApi GetApi(string name)
  758. {
  759. if (m_Apis.ContainsKey(name))
  760. return m_Apis[name];
  761. return null;
  762. }
  763. public override string ToString()
  764. {
  765. return String.Format("{0} {1} on {2}", m_ScriptName, m_ItemID, m_PrimName);
  766. }
  767. string FormatException(Exception e)
  768. {
  769. if (e.InnerException == null) // Not a normal runtime error
  770. return e.ToString();
  771. string message = "Runtime error:\n" + e.InnerException.StackTrace;
  772. string[] lines = message.Split(new char[] {'\n'});
  773. foreach (string line in lines)
  774. {
  775. if (line.Contains("SecondLife.Script"))
  776. {
  777. int idx = line.IndexOf(':');
  778. if (idx != -1)
  779. {
  780. string val = line.Substring(idx+1);
  781. int lineNum = 0;
  782. if (int.TryParse(val, out lineNum))
  783. {
  784. KeyValuePair<int, int> pos =
  785. Compiler.FindErrorPosition(
  786. lineNum, 0, LineMap);
  787. int scriptLine = pos.Key;
  788. int col = pos.Value;
  789. if (scriptLine == 0)
  790. scriptLine++;
  791. if (col == 0)
  792. col++;
  793. message = string.Format("Runtime error:\n" +
  794. "Line ({0}): {1}", scriptLine - 1,
  795. e.InnerException.Message);
  796. return message;
  797. }
  798. }
  799. }
  800. }
  801. m_log.ErrorFormat("Scripting exception:");
  802. m_log.ErrorFormat(e.ToString());
  803. return e.ToString();
  804. }
  805. public string GetAssemblyName()
  806. {
  807. return m_Assembly;
  808. }
  809. public string GetXMLState()
  810. {
  811. bool run = Running;
  812. Stop(100);
  813. Running = run;
  814. // We should not be doing this, but since we are about to
  815. // dispose this, it really doesn't make a difference
  816. // This is meant to work around a Windows only race
  817. //
  818. m_InEvent = false;
  819. // Force an update of the in-memory plugin data
  820. //
  821. PluginData = AsyncCommandManager.GetSerializationData(m_Engine, m_ItemID);
  822. return ScriptSerializer.Serialize(this);
  823. }
  824. }
  825. }