public void ApiResetScript() { // bool running = Running; RemoveState(); ReleaseControls(); m_Script.ResetVars(); SceneObjectPart part = Engine.World.GetSceneObjectPart(LocalID); part.Inventory.GetInventoryItem(ItemID).PermsMask = 0; part.Inventory.GetInventoryItem(ItemID).PermsGranter = UUID.Zero; AsyncCommandManager.RemoveScript(Engine, LocalID, ItemID); EventQueue.Clear(); m_Script.ResetVars(); State = "default"; part.SetScriptEvents(ItemID, (int)m_Script.GetStateEventFlags(State)); if (m_CurrentEvent != "state_entry") { m_SaveState = true; PostEvent(new EventParams("state_entry", new Object[0], new DetectParams[0])); throw new EventAbortException(); } }
public void ResetScript() { if (m_Script == null) { return; } bool running = Running; RemoveState(); ReleaseControls(); Stop(0); SceneObjectPart part = Engine.World.GetSceneObjectPart(LocalID); part.Inventory.GetInventoryItem(ItemID).PermsMask = 0; part.Inventory.GetInventoryItem(ItemID).PermsGranter = UUID.Zero; AsyncCommandManager.RemoveScript(Engine, LocalID, ItemID); EventQueue.Clear(); m_Script.ResetVars(); State = "default"; part.SetScriptEvents(ItemID, (int)m_Script.GetStateEventFlags(State)); if (running) { Start(); } m_SaveState = true; PostEvent(new EventParams("state_entry", new Object[0], new DetectParams[0])); }
public void SetState(UUID itemID, string state) { uint localID = m_ScriptManager.GetLocalID(itemID); if (localID == 0) { return; } InstanceData id = m_ScriptManager.GetScript(localID, itemID); if (id == null) { return; } string currentState = id.State; if (currentState != state) { try { m_EventManager.state_exit(localID); } catch (AppDomainUnloadedException) { m_log.Error("[SCRIPT]: state change called when " + "script was unloaded. Nothing to worry about, " + "but noting the occurance"); } id.State = state; try { int eventFlags = m_ScriptManager.GetStateEventFlags(localID, itemID); SceneObjectPart part = m_Scene.GetSceneObjectPart(localID); if (part != null) { part.SetScriptEvents(itemID, eventFlags); } m_EventManager.state_entry(localID); } catch (AppDomainUnloadedException) { m_log.Error("[SCRIPT]: state change called when " + "script was unloaded. Nothing to worry about, but " + "noting the occurance"); } } }
private Hashtable changePrimPermissions(Hashtable requestData) { Hashtable rparms = new Hashtable(); try { UUID primUUID = UUID.Parse((string)requestData["primUUID"]); SceneObjectPart part = SceneHandler.Instance.FindPrim(primUUID); if (part == null) { throw new Exception("Could not find the requested prim"); } string inventoryItemsString = (string)requestData["inventoryItems"]; Dictionary <string, string> inventoryItems = JsonMapper.ToObject <Dictionary <string, string> >(inventoryItemsString); foreach (KeyValuePair <string, string> inventoryItem in inventoryItems) { if (inventoryItem.Value == "0") { part.RemoveScriptEvents(UUID.Parse(inventoryItem.Key)); } else { part.SetScriptEvents(UUID.Parse(inventoryItem.Key), Convert.ToInt32(inventoryItem.Value)); } } rparms["success"] = true; } catch (Exception e) { m_log.ErrorFormat("[OMECONOMY]: changePrimPermissions() Exception: {1} - {2}", Name, e.Message, e.StackTrace); rparms["success"] = false; } return(rparms); }
/// <summary> /// Process the next event queued for this script /// </summary> /// <returns></returns> public object EventProcessor() { // We check here as the thread stopping this instance from running may itself hold the m_Script lock. if (!Running) { return(0); } lock (m_Script) { // m_log.DebugFormat("[XEngine]: EventProcessor() invoked for {0}.{1}", PrimName, ScriptName); if (Suspended) { return(0); } EventParams data = null; lock (EventQueue) { data = (EventParams)EventQueue.Dequeue(); if (data == null) // Shouldn't happen { if (EventQueue.Count > 0 && Running && !ShuttingDown) { m_CurrentWorkItem = Engine.QueueEventHandler(this); } else { m_CurrentWorkItem = null; } return(0); } if (data.EventName == "timer") { m_TimerQueued = false; } if (data.EventName == "control") { if (m_ControlEventsInQueue > 0) { m_ControlEventsInQueue--; } } if (data.EventName == "collision") { m_CollisionInQueue = false; } } // m_log.DebugFormat("[XEngine]: Processing event {0} for {1}", data.EventName, this); m_DetectParams = data.DetectParams; if (data.EventName == "state") // Hardcoded state change { // m_log.DebugFormat("[Script] Script {0}.{1} state set to {2}", // PrimName, ScriptName, data.Params[0].ToString()); State = data.Params[0].ToString(); AsyncCommandManager.RemoveScript(Engine, LocalID, ItemID); SceneObjectPart part = Engine.World.GetSceneObjectPart( LocalID); if (part != null) { part.SetScriptEvents(ItemID, (int)m_Script.GetStateEventFlags(State)); } } else { if (Engine.World.PipeEventsForScript(LocalID) || data.EventName == "control") // Don't freeze avies! { SceneObjectPart part = Engine.World.GetSceneObjectPart( LocalID); // m_log.DebugFormat("[Script] Delivered event {2} in state {3} to {0}.{1}", // PrimName, ScriptName, data.EventName, State); try { m_CurrentEvent = data.EventName; m_EventStart = DateTime.Now; m_InEvent = true; int start = Util.EnvironmentTickCount(); // Reset the measurement period when we reach the end of the current one. if (start - MeasurementPeriodTickStart > MaxMeasurementPeriod) { MeasurementPeriodTickStart = start; } m_Script.ExecuteEvent(State, data.EventName, data.Params); MeasurementPeriodExecutionTime += Util.EnvironmentTickCount() - start; m_InEvent = false; m_CurrentEvent = String.Empty; if (m_SaveState) { // This will be the very first event we deliver // (state_entry) in default state // SaveState(m_Assembly); m_SaveState = false; } } catch (Exception e) { // m_log.DebugFormat( // "[SCRIPT] Exception in script {0} {1}: {2}{3}", // ScriptName, ItemID, e.Message, e.StackTrace); m_InEvent = false; m_CurrentEvent = String.Empty; if ((!(e is TargetInvocationException) || (!(e.InnerException is SelfDeleteException) && !(e.InnerException is ScriptDeleteException))) && !(e is ThreadAbortException)) { try { // DISPLAY ERROR INWORLD string text = FormatException(e); if (text.Length > 1000) { text = text.Substring(0, 1000); } Engine.World.SimChat(Utils.StringToBytes(text), ChatTypeEnum.DebugChannel, 2147483647, part.AbsolutePosition, part.Name, part.UUID, false); } catch (Exception) { } // catch (Exception e2) // LEGIT: User Scripting // { // m_log.Error("[SCRIPT]: "+ // "Error displaying error in-world: " + // e2.ToString()); // m_log.Error("[SCRIPT]: " + // "Errormessage: Error compiling script:\r\n" + // e.ToString()); // } } else if ((e is TargetInvocationException) && (e.InnerException is SelfDeleteException)) { m_InSelfDelete = true; if (part != null) { Engine.World.DeleteSceneObject(part.ParentGroup, false); } } else if ((e is TargetInvocationException) && (e.InnerException is ScriptDeleteException)) { m_InSelfDelete = true; if (part != null) { part.Inventory.RemoveInventoryItem(ItemID); } } } } } // If there are more events and we are currently running and not shutting down, then ask the // script engine to run the next event. lock (EventQueue) { if (EventQueue.Count > 0 && Running && !ShuttingDown) { m_CurrentWorkItem = Engine.QueueEventHandler(this); } else { m_CurrentWorkItem = null; } } m_DetectParams = null; return(0); } }
public ScriptInstance(IScriptEngine engine, SceneObjectPart part, UUID itemID, UUID assetID, string assembly, AppDomain dom, string primName, string scriptName, int startParam, bool postOnRez, StateSource stateSource, int maxScriptQueue) { State = "default"; EventQueue = new Queue(32); Engine = engine; LocalID = part.LocalId; ObjectID = part.UUID; RootLocalID = part.ParentGroup.LocalId; RootObjectID = part.ParentGroup.UUID; ItemID = itemID; AssetID = assetID; PrimName = primName; ScriptName = scriptName; m_Assembly = assembly; StartParam = startParam; m_MaxScriptQueue = maxScriptQueue; m_stateSource = stateSource; m_postOnRez = postOnRez; m_AttachedAvatar = part.ParentGroup.AttachedAvatar; m_RegionID = part.ParentGroup.Scene.RegionInfo.RegionID; if (part != null) { lock (part.TaskInventory) { if (part.TaskInventory.ContainsKey(ItemID)) { ScriptTask = part.TaskInventory[ItemID]; } } } ApiManager am = new ApiManager(); foreach (string api in am.GetApis()) { m_Apis[api] = am.CreateApi(api); m_Apis[api].Initialize(engine, part, LocalID, itemID); } try { if (dom != System.AppDomain.CurrentDomain) { m_Script = (IScript)dom.CreateInstanceAndUnwrap( Path.GetFileNameWithoutExtension(assembly), "SecondLife.Script"); } else { m_Script = (IScript)Assembly.Load( Path.GetFileNameWithoutExtension(assembly)).CreateInstance( "SecondLife.Script"); } //ILease lease = (ILease)RemotingServices.GetLifetimeService(m_Script as ScriptBaseClass); //RemotingServices.GetLifetimeService(m_Script as ScriptBaseClass); // lease.Register(this); } catch (Exception e) { m_log.ErrorFormat( "[SCRIPT INSTANCE]: Error loading assembly {0}. Exception {1}{2}", assembly, e.Message, e.StackTrace); } try { foreach (KeyValuePair <string, IScriptApi> kv in m_Apis) { m_Script.InitApi(kv.Key, kv.Value); } // // m_log.Debug("[Script] Script instance created"); part.SetScriptEvents(ItemID, (int)m_Script.GetStateEventFlags(State)); } catch (Exception e) { m_log.ErrorFormat( "[SCRIPT INSTANCE]: Error loading script instance from assembly {0}. Exception {1}{2}", assembly, e.Message, e.StackTrace); return; } m_SaveState = true; string savedState = Path.Combine(Path.GetDirectoryName(assembly), ItemID.ToString() + ".state"); if (File.Exists(savedState)) { string xml = String.Empty; try { FileInfo fi = new FileInfo(savedState); int size = (int)fi.Length; if (size < 512000) { using (FileStream fs = File.Open(savedState, FileMode.Open, FileAccess.Read, FileShare.None)) { System.Text.UTF8Encoding enc = new System.Text.UTF8Encoding(); Byte[] data = new Byte[size]; fs.Read(data, 0, size); xml = enc.GetString(data); ScriptSerializer.Deserialize(xml, this); AsyncCommandManager.CreateFromData(Engine, LocalID, ItemID, ObjectID, PluginData); // m_log.DebugFormat("[Script] Successfully retrieved state for script {0}.{1}", PrimName, m_ScriptName); part.SetScriptEvents(ItemID, (int)m_Script.GetStateEventFlags(State)); Running = false; if (ShuttingDown) { m_startOnInit = false; } // we get new rez events on sim restart, too // but if there is state, then we fire the change // event // We loaded state, don't force a re-save m_SaveState = false; m_startedFromSavedState = true; } } else { m_log.ErrorFormat( "[SCRIPT INSTANCE]: Unable to load script state from assembly {0}: Memory limit exceeded", assembly); } } catch (Exception e) { m_log.ErrorFormat( "[SCRIPT INSTANCE]: Unable to load script state from assembly {0}. XML is {1}. Exception {2}{3}", assembly, xml, e.Message, e.StackTrace); } } // else // { // ScenePresence presence = Engine.World.GetScenePresence(part.OwnerID); // if (presence != null && (!postOnRez)) // presence.ControllingClient.SendAgentAlertMessage("Compile successful", false); // } }
/// <summary> /// Process the next event queued for this script /// </summary> /// <returns></returns> public object EventProcessor() { if (m_Suspended) { return(0); } lock (m_Script) { EventParams data = null; lock (m_EventQueue) { data = (EventParams)m_EventQueue.Dequeue(); if (data == null) // Shouldn't happen { if ((m_EventQueue.Count > 0) && m_RunEvents && (!m_ShuttingDown)) { m_CurrentResult = m_Engine.QueueEventHandler(this); } else { m_CurrentResult = null; } return(0); } if (data.EventName == "timer") { m_TimerQueued = false; } if (data.EventName == "control") { if (m_ControlEventsInQueue > 0) { m_ControlEventsInQueue--; } } if (data.EventName == "collision") { m_CollisionInQueue = false; } } //m_log.DebugFormat("[XENGINE]: Processing event {0} for {1}", data.EventName, this); m_DetectParams = data.DetectParams; if (data.EventName == "state") // Hardcoded state change { // m_log.DebugFormat("[Script] Script {0}.{1} state set to {2}", // m_PrimName, m_ScriptName, data.Params[0].ToString()); m_State = data.Params[0].ToString(); AsyncCommandManager.RemoveScript(m_Engine, m_LocalID, m_ItemID); SceneObjectPart part = m_Engine.World.GetSceneObjectPart( m_LocalID); if (part != null) { part.SetScriptEvents(m_ItemID, (int)m_Script.GetStateEventFlags(State)); } } else { if (m_Engine.World.PipeEventsForScript(m_LocalID) || data.EventName == "control") // Don't freeze avies! { SceneObjectPart part = m_Engine.World.GetSceneObjectPart( m_LocalID); // m_log.DebugFormat("[Script] Delivered event {2} in state {3} to {0}.{1}", // m_PrimName, m_ScriptName, data.EventName, m_State); try { m_CurrentEvent = data.EventName; m_EventStart = DateTime.Now; m_InEvent = true; m_Script.ExecuteEvent(State, data.EventName, data.Params); m_InEvent = false; m_CurrentEvent = String.Empty; if (m_SaveState) { // This will be the very first event we deliver // (state_entry) in default state // SaveState(m_Assembly); m_SaveState = false; } } catch (Exception e) { // m_log.DebugFormat("[SCRIPT] Exception: {0}", e.Message); m_InEvent = false; m_CurrentEvent = String.Empty; if ((!(e is TargetInvocationException) || (!(e.InnerException is SelfDeleteException) && !(e.InnerException is ScriptDeleteException))) && !(e is ThreadAbortException)) { try { // DISPLAY ERROR INWORLD string text = FormatException(e); if (text.Length > 1000) { text = text.Substring(0, 1000); } m_Engine.World.SimChat(Utils.StringToBytes(text), ChatTypeEnum.DebugChannel, 2147483647, part.AbsolutePosition, part.Name, part.UUID, false); } catch (Exception) { } // catch (Exception e2) // LEGIT: User Scripting // { // m_log.Error("[SCRIPT]: "+ // "Error displaying error in-world: " + // e2.ToString()); // m_log.Error("[SCRIPT]: " + // "Errormessage: Error compiling script:\r\n" + // e.ToString()); // } } else if ((e is TargetInvocationException) && (e.InnerException is SelfDeleteException)) { m_InSelfDelete = true; if (part != null && part.ParentGroup != null) { m_Engine.World.DeleteSceneObject(part.ParentGroup, false); } } else if ((e is TargetInvocationException) && (e.InnerException is ScriptDeleteException)) { m_InSelfDelete = true; if (part != null && part.ParentGroup != null) { part.Inventory.RemoveInventoryItem(m_ItemID); } } } } } lock (m_EventQueue) { if ((m_EventQueue.Count > 0) && m_RunEvents && (!m_ShuttingDown)) { m_CurrentResult = m_Engine.QueueEventHandler(this); } else { m_CurrentResult = null; } } m_DetectParams = null; return(0); } }
protected void DisableEvents() { m_part.SetScriptEvents(DUMMY_SCRIPT_UUID, (int)scriptEvents.None); m_eventManager.OnObjectGrab -= OnOsTouch; m_eventManager.OnChatFromClient -= OnOsChat; }
public void _StartScript(uint localID, UUID itemID, string Script, int startParam, bool postOnRez) { m_log.DebugFormat( "[{0}]: ScriptManager StartScript: localID: {1}, itemID: {2}", m_scriptEngine.ScriptEngineName, localID, itemID); // We will initialize and start the script. // It will be up to the script itself to hook up the correct events. string CompiledScriptFile = String.Empty; SceneObjectPart m_host = World.GetSceneObjectPart(localID); if (null == m_host) { m_log.ErrorFormat( "[{0}]: Could not find scene object part corresponding " + "to localID {1} to start script", m_scriptEngine.ScriptEngineName, localID); return; } UUID assetID = UUID.Zero; TaskInventoryItem taskInventoryItem = new TaskInventoryItem(); if (m_host.TaskInventory.TryGetValue(itemID, out taskInventoryItem)) { assetID = taskInventoryItem.AssetID; } ScenePresence presence = World.GetScenePresence(taskInventoryItem.OwnerID); CultureInfo USCulture = new CultureInfo("en-US"); Thread.CurrentThread.CurrentCulture = USCulture; try { // Compile (We assume LSL) CompiledScriptFile = LSLCompiler.PerformScriptCompile(Script, assetID.ToString()); if (presence != null && (!postOnRez)) { presence.ControllingClient.SendAgentAlertMessage( "Compile successful", false); } m_log.InfoFormat("[SCRIPT]: Compiled assetID {0}: {1}", assetID, CompiledScriptFile); InstanceData id = new InstanceData(); IScript CompiledScript; CompiledScript = m_scriptEngine.m_AppDomainManager.LoadScript( CompiledScriptFile, out id.AppDomain); //Register the sponsor // ISponsor scriptSponsor = new ScriptSponsor(); // ILease lease = (ILease)RemotingServices.GetLifetimeService(CompiledScript as MarshalByRefObject); // lease.Register(scriptSponsor); // id.ScriptSponsor = scriptSponsor; id.LineMap = LSLCompiler.LineMap(); id.Script = CompiledScript; id.Source = Script; id.StartParam = startParam; id.State = "default"; id.Running = true; id.Disabled = false; // Add it to our script memstruct m_scriptEngine.m_ScriptManager.SetScript(localID, itemID, id); id.Apis = new Dictionary <string, IScriptApi>(); ApiManager am = new ApiManager(); foreach (string api in am.GetApis()) { id.Apis[api] = am.CreateApi(api); id.Apis[api].Initialize(m_scriptEngine, m_host, localID, itemID); } foreach (KeyValuePair <string, IScriptApi> kv in id.Apis) { CompiledScript.InitApi(kv.Key, kv.Value); } // Fire the first start-event int eventFlags = m_scriptEngine.m_ScriptManager.GetStateEventFlags( localID, itemID); m_host.SetScriptEvents(itemID, eventFlags); m_scriptEngine.m_EventQueueManager.AddToScriptQueue( localID, itemID, "state_entry", new DetectParams[0], new object[] { }); if (postOnRez) { m_scriptEngine.m_EventQueueManager.AddToScriptQueue( localID, itemID, "on_rez", new DetectParams[0], new object[] { new LSL_Types.LSLInteger(startParam) }); } string[] warnings = LSLCompiler.GetWarnings(); if (warnings != null && warnings.Length != 0) { if (presence != null && (!postOnRez)) { presence.ControllingClient.SendAgentAlertMessage( "Script saved with warnings, check debug window!", false); } foreach (string warning in warnings) { try { // DISPLAY WARNING INWORLD string text = "Warning:\n" + warning; if (text.Length > 1100) { text = text.Substring(0, 1099); } World.SimChat(Utils.StringToBytes(text), ChatTypeEnum.DebugChannel, 2147483647, m_host.AbsolutePosition, m_host.Name, m_host.UUID, false); } catch (Exception e2) // LEGIT: User Scripting { m_log.Error("[" + m_scriptEngine.ScriptEngineName + "]: Error displaying warning in-world: " + e2.ToString()); m_log.Error("[" + m_scriptEngine.ScriptEngineName + "]: " + "Warning:\r\n" + warning); } } } } catch (Exception e) // LEGIT: User Scripting { if (presence != null && (!postOnRez)) { presence.ControllingClient.SendAgentAlertMessage( "Script saved with errors, check debug window!", false); } try { // DISPLAY ERROR INWORLD string text = "Error compiling script:\n" + e.Message.ToString(); if (text.Length > 1100) { text = text.Substring(0, 1099); } World.SimChat(Utils.StringToBytes(text), ChatTypeEnum.DebugChannel, 2147483647, m_host.AbsolutePosition, m_host.Name, m_host.UUID, false); } catch (Exception e2) // LEGIT: User Scripting { m_log.Error("[" + m_scriptEngine.ScriptEngineName + "]: Error displaying error in-world: " + e2.ToString()); m_log.Error("[" + m_scriptEngine.ScriptEngineName + "]: " + "Errormessage: Error compiling script:\r\n" + e2.Message.ToString()); } } }
public ScriptInstance(IScriptEngine engine, SceneObjectPart part, UUID itemID, UUID assetID, string assembly, AppDomain dom, string primName, string scriptName, int startParam, bool postOnRez, StateSource stateSource, int maxScriptQueue) { m_Engine = engine; m_LocalID = part.LocalId; m_ObjectID = part.UUID; m_ItemID = itemID; m_AssetID = assetID; m_PrimName = primName; m_ScriptName = scriptName; m_Assembly = assembly; m_StartParam = startParam; m_MaxScriptQueue = maxScriptQueue; m_stateSource = stateSource; m_postOnRez = postOnRez; m_RegionID = part.ParentGroup.Scene.RegionInfo.RegionID; if (part != null) { lock (part.TaskInventory) { if (part.TaskInventory.ContainsKey(m_ItemID)) { m_thisScriptTask = part.TaskInventory[m_ItemID]; } } } ApiManager am = new ApiManager(); foreach (string api in am.GetApis()) { m_Apis[api] = am.CreateApi(api); m_Apis[api].Initialize(engine, part, m_LocalID, itemID); } try { m_Script = (IScript)dom.CreateInstanceAndUnwrap( Path.GetFileNameWithoutExtension(assembly), "SecondLife.Script"); // Add a sponsor to the script // ISponsor scriptSponsor = new ScriptSponsor(); // ILease lease = (ILease)RemotingServices.GetLifetimeService(m_Script as MarshalByRefObject); // lease.Register(scriptSponsor); //m_ScriptSponsor = scriptSponsor; } catch (Exception e) { m_log.ErrorFormat("[Script] Error loading assembly {0}\n" + e.ToString(), assembly); } try { foreach (KeyValuePair <string, IScriptApi> kv in m_Apis) { m_Script.InitApi(kv.Key, kv.Value); } // m_log.Debug("[Script] Script instance created"); part.SetScriptEvents(m_ItemID, (int)m_Script.GetStateEventFlags(State)); } catch (Exception e) { m_log.Error("[Script] Error loading script instance\n" + e.ToString()); return; } m_SaveState = true; string savedState = Path.Combine(Path.GetDirectoryName(assembly), m_ItemID.ToString() + ".state"); if (File.Exists(savedState)) { string xml = String.Empty; try { FileInfo fi = new FileInfo(savedState); int size = (int)fi.Length; if (size < 512000) { using (FileStream fs = File.Open(savedState, FileMode.Open, FileAccess.Read, FileShare.None)) { System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding(); Byte[] data = new Byte[size]; fs.Read(data, 0, size); xml = enc.GetString(data); ScriptSerializer.Deserialize(xml, this); AsyncCommandManager.CreateFromData(m_Engine, m_LocalID, m_ItemID, m_ObjectID, PluginData); // m_log.DebugFormat("[Script] Successfully retrieved state for script {0}.{1}", m_PrimName, m_ScriptName); part.SetScriptEvents(m_ItemID, (int)m_Script.GetStateEventFlags(State)); if (m_RunEvents && (!m_ShuttingDown)) { m_RunEvents = false; } else { m_RunEvents = false; m_startOnInit = false; } // we get new rez events on sim restart, too // but if there is state, then we fire the change // event // We loaded state, don't force a re-save m_SaveState = false; m_startedFromSavedState = true; } } else { m_log.Error("[Script] Unable to load script state: Memory limit exceeded"); } } catch (Exception e) { m_log.ErrorFormat("[Script] Unable to load script state from xml: {0}\n" + e.ToString(), xml); } } else { ScenePresence presence = m_Engine.World.GetScenePresence(part.OwnerID); if (presence != null && (!postOnRez)) { presence.ControllingClient.SendAgentAlertMessage("Compile successful", false); } // m_log.ErrorFormat("[Script] Unable to load script state, file not found"); } }