ScriptInstance.cs 37 KB

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