protected override Variant fixupImpl() { if (_pythonFixup == null) { Dictionary <string, object> state = new Dictionary <string, object>(); state["fixupSelf"] = this; _pythonFixup = Scripting.EvalExpression( string.Format("{0}(fixupSelf)", (string)args["class"]), state); } var from = elements["ref"]; logger.Debug("fixupImpl(): ref: " + from.GetHashCode().ToString()); object data = _pythonFixup.fixup(from); if (data is byte[]) { return(new Variant((byte[])data)); } else if (data is string) { return(new Variant((string)data)); } else if (data is int) { return(new Variant((int)data)); } logger.Error("Error, unknown type [" + data.GetType().ToString() + "]."); throw new ApplicationException("Error, unknown type [" + data.GetType().ToString() + "]."); }
public void TestOnBackupCompletedJScript() { Scripting scripting = _settings.Scripting; scripting.Language = "JScript"; // First set up a script string script = @"function OnBackupCompleted() { EventLog.Write('Backup process completed') }"; string file = scripting.CurrentScriptFile; File.WriteAllText(file, script); scripting.Enabled = true; scripting.Reload(); var back = new BackupRestore(); back.InitializeBackupSettings(); back.TestWithMessages(); string eventLogText = TestSetup.ReadExistingTextFile(LogHandler.GetEventLogFileName()); Assert.IsTrue(eventLogText.Contains("Backup process completed")); }
public ScriptFixup(DataElement parent, Dictionary <string, Variant> args) : base(parent, args, "ref") { try { Dictionary <string, object> state = new Dictionary <string, object>(); state["fixupSelf"] = this; _pythonFixup = Scripting.EvalExpression( string.Format("{0}(fixupSelf)", (string)args["class"]), state); if (_pythonFixup == null) { throw new PeachException("Error, unable to create an instance of the \"" + (string)args["class"] + "\" script class."); } logger.Debug("ScriptFixup(): _pythonFixup != null"); } catch (Exception ex) { logger.Debug("class: " + (string)args["class"]); logger.Error(ex.Message); throw; } }
public void TestOnDeliveryFailedVBScript() { // First set up a script string script = "Sub OnDeliveryFailed(oMessage, sRecipient, sErrorMessage)" + Environment.NewLine + " EventLog.Write(\"File: \" & oMessage.FileName) " + Environment.NewLine + " EventLog.Write(\"Recipient: \" & sRecipient) " + Environment.NewLine + " EventLog.Write(\"Error: \" & sErrorMessage) " + Environment.NewLine + " End Sub"; Scripting scripting = _settings.Scripting; string file = scripting.CurrentScriptFile; File.WriteAllText(file, script); scripting.Enabled = true; scripting.Reload(); // Add an account and send a message to it. Account oAccount1 = SingletonProvider <TestSetup> .Instance.AddAccount(_domain, "*****@*****.**", "test"); SmtpClientSimulator.StaticSend(oAccount1.Address, "*****@*****.**", "Test", "SampleBody"); // Make sure that the message is deliverd and bounced. CustomAsserts.AssertRecipientsInDeliveryQueue(0); string eventLogText = TestSetup.ReadExistingTextFile(LogHandler.GetEventLogFileName()); Assert.IsTrue(eventLogText.Contains("File: ")); Assert.IsTrue(eventLogText.Contains("Recipient: [email protected]")); Assert.IsTrue(eventLogText.Contains("No mail servers appear to exists")); }
public void TestOnDeliveryStartVBScript() { Application app = SingletonProvider <TestSetup> .Instance.GetApp(); Scripting scripting = app.Settings.Scripting; string script = "Sub OnDeliveryStart(oMessage) " + Environment.NewLine + " EventLog.Write(\"Delivering message: \" & oMessage.FileName) " + Environment.NewLine + "End Sub" + Environment.NewLine + Environment.NewLine; File.WriteAllText(scripting.CurrentScriptFile, script); scripting.Enabled = true; scripting.Reload(); Account account = SingletonProvider <TestSetup> .Instance.AddAccount(_domain, "*****@*****.**", "test"); SmtpClientSimulator.StaticSend(account.Address, account.Address, "Test", "SampleBody"); // Wait for the message to be delivered. Pop3ClientSimulator.AssertGetFirstMessageText(account.Address, "test"); string eventLogText = TestSetup.ReadExistingTextFile(app.Settings.Logging.CurrentEventLog); Assert.IsTrue(eventLogText.Contains("Delivering message")); }
public void TestOnBackupFailedVBScript() { // First set up a script string script = @"Sub OnBackupFailed(reason) EventLog.Write(""Failed: "" & reason) End Sub"; Scripting scripting = _settings.Scripting; string file = scripting.CurrentScriptFile; File.WriteAllText(file, script); scripting.Enabled = true; scripting.Reload(); var back = new BackupRestore(); back.InitializeBackupSettings(); back.SetBackupDir(@"C:\some-non-existant-directory"); Assert.IsFalse(back.Execute()); CustomAsserts.AssertReportedError("BACKUP ERROR: The specified backup directory is not accessible:"); string eventLogText = TestSetup.ReadExistingTextFile(LogHandler.GetEventLogFileName()); Assert.IsTrue(eventLogText.Contains("The specified backup directory is not accessible")); }
public void TestOnDeliverMessageJScript() { Scripting scripting = _settings.Scripting; scripting.Language = "JScript"; // First set up a script string script = @"function OnDeliverMessage(oMessage) { oMessage.HeaderValue('X-SpamResult') = 'TEST2'; oMessage.Save(); }"; string file = scripting.CurrentScriptFile; File.WriteAllText(file, script); scripting.Enabled = true; scripting.Reload(); // Add an account and send a message to it. Account oAccount1 = SingletonProvider <TestSetup> .Instance.AddAccount(_domain, "*****@*****.**", "test"); SmtpClientSimulator.StaticSend(oAccount1.Address, oAccount1.Address, "Test", "SampleBody"); // Check that the message exists string message = Pop3ClientSimulator.AssertGetFirstMessageText(oAccount1.Address, "test"); Assert.IsNotEmpty(message); Assert.Less(0, message.IndexOf("X-SpamResult: TEST2")); }
protected virtual void RunScript(string expr) { if (!string.IsNullOrEmpty(expr)) { Scripting.Exec(expr, scope); } }
public override long GetValue() { if (_isRecursing) { return(0); } try { _isRecursing = true; long count = (long)From.DefaultValue; if (_expressionGet != null) { Dictionary <string, object> state = new Dictionary <string, object>(); state["count"] = count; state["value"] = count; state["self"] = this._parent; object value = Scripting.EvalExpression(_expressionGet, state); count = Convert.ToInt64(value); } return(count); } finally { _isRecursing = false; } }
private void ReceiveLoop() { _running = true; while (_running) { if (!_socket.Connected) { _running = false; } else if (_socket.Available != 0) { int senderId = _reader.ReadInt32(); string s = _reader.ReadString(); Packet p = (Packet)Activator.CreateInstance(PacketTypeManager.SubclassTypes.First((t) => t.Name.Equals(s))); p.Author = senderId; p.Read(_reader); if (EditingSessionPlugin.Instance.IsPlayMode) { _backlog.AddLast(p); } else { Scripting.InvokeOnUpdate(() => { p.Execute(); }); } } else { Thread.Sleep(0); } } }
public override long GetValue() { if (_isRecursing) { return(0); } try { _isRecursing = true; long size = (long)From.DefaultValue; if (_expressionGet != null) { Dictionary <string, object> state = new Dictionary <string, object>(); state["size"] = size; state["value"] = size; state["self"] = this._parent; object value = Scripting.EvalExpression(_expressionGet, state); size = Convert.ToInt64(value); } if (_isByteRelation) { size = size * 8; } return(size); } finally { _isRecursing = false; } }
public void TestEventLog() { Application application = SingletonProvider <TestSetup> .Instance.GetApp(); // First set up a script string script = @"Sub OnAcceptMessage(oClient, oMessage) EventLog.Write(""HOWDY"") End Sub"; Scripting scripting = _settings.Scripting; string file = scripting.CurrentScriptFile; TestSetup.WriteFile(file, script); scripting.Enabled = true; scripting.Reload(); // Drop the current event log string eventLogFile = _settings.Logging.CurrentEventLog; SingletonProvider <TestSetup> .Instance.DeleteEventLog(); // Add an account and send a message to it. Account oAccount1 = SingletonProvider <TestSetup> .Instance.AddAccount(_domain, "*****@*****.**", "test"); SendMessageToTest(); POP3ClientSimulator.AssertGetFirstMessageText(oAccount1.Address, "test"); TestSetup.AssertFileExists(eventLogFile, false); // Check that it starts with Unicode markers. for (int i = 0; i <= 400; i++) { try { var fs = new FileStream(eventLogFile, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); var br = new BinaryReader(fs); int i1 = br.ReadByte(); int i2 = br.ReadByte(); br.Close(); fs.Close(); CustomAssert.AreEqual(255, i1); CustomAssert.AreEqual(254, i2); break; } catch (Exception e) { if (i == 40) { throw e; } } Thread.Sleep(25); } }
/// <summary> /// Initialize the execution state for the compiler using a blam-script definition /// </summary> /// <param name="definition"></param> internal Data(Scripting.XmlInterface definition) { this.definition = definition; Nodes = new List<ScriptNode>(this.definition.MaxNodes); StringData = new Util.StringPool(false); Scripts = new List<ScriptBlock>(); Globals = new List<GlobalsBlock>(); }
private void ExecutionCompleted(Scripting.ExecutionResult result) { PrintCommand(prompt.Text); PrintResult(result.Output); PrintError(result.Error); prompt.Text = ""; prompt.IsEnabled = true; }
public static void InitSettingsHandlers() { Webserver.DefaultWebserver.RegisterDynamicContent(UpvoidMiner.ModDomain, "Settings", webSettings); Webserver.DefaultWebserver.RegisterDynamicContent(UpvoidMiner.ModDomain, "FieldOfView", fieldOfViewSettings); FieldOfView = (float)Scripting.GetUserSettingNumber("Graphics/Field of View", 75f); LocalScript.camera.HorizontalFieldOfView = FieldOfView; }
static void getSettings(WebResponse response) { SettingsInfo info = new SettingsInfo(); // Read the current graphics flags info.lensFlares = Scripting.GetUserSetting("Graphics/Enable Lensflares", false); info.volumetricScattering = Scripting.GetUserSetting("Graphics/Enable Volumetric Scattering", true); info.bloom = Scripting.GetUserSetting("Graphics/Enable Bloom", true); info.afterImage = Scripting.GetUserSetting("Graphics/Enable AfterImage", true); info.tonemapping = Scripting.GetUserSetting("Graphics/Enable Tonemapping", true); info.noise = Scripting.GetUserSetting("Graphics/Enable Noise", false); info.shadows = Scripting.GetUserSetting("Graphics/Enable Shadows", true); info.ssao = Scripting.GetUserSetting("Graphics/Enable SSAO", true); info.fog = Scripting.GetUserSetting("Graphics/Enable Fog", true); info.fxaa = Scripting.GetUserSetting("Graphics/Enable FXAA", true); // Currently, only the main screen can be set for fullscreen mode. info.fullscreen = Scripting.GetUserSettingString("WindowManager/Fullscreen", "-1") != "-1"; // Read the supported video modes List <string> modes = Rendering.GetSupportedVideoModes(); modes.Insert(0, "Native Resolution"); info.resolution = Scripting.GetUserSettingString("WindowManager/Resolution", "-1x-1"); if (info.resolution == "-1x-1") { info.resolution = "Native Resolution"; } info.supportedModes = modes.Distinct().ToArray(); double lod = (Scripting.GetUserSettingNumber("Graphics/Lod Falloff", 40.0) - 10.0) / 30.0; lod += Scripting.GetUserSettingNumber("Graphics/Min Lod Range", 0.0) / 30.0; if (lod < 0) { lod = 0; } if (lod > 2) { lod = 2; } info.lod = lod; // Serialize to json to be read by the gui StringWriter writer = new StringWriter(); JsonSerializer json = new JsonSerializer(); JsonTextWriter jsonWriter = new JsonTextWriter(writer); json.Formatting = Formatting.Indented; json.Serialize(jsonWriter, info); response.AddHeader("Content-Type", "application/json"); response.AppendBody(writer.GetStringBuilder().ToString()); }
public static TextBlock CreateBlockFromStanza(Stanza stanza, Language translationLanguage, Color foreground) { TextBlock contentBlock = null; if (stanza.Language == Language.Default) { stanza.Language = translationLanguage; } switch (stanza.Language) { #region English case Language.English: contentBlock = new TextBlock { Text = Scripting.ParseTextCommands(stanza.Text), FontFamily = Common.Segoe, FontSize = Common.GetEnglishFontSize(), TextWrapping = TextWrapping.Wrap, Foreground = new SolidColorBrush(foreground) }; break; #endregion #region Coptic case Language.Coptic: contentBlock = new TextBlock { // TextBlock doesn't seem to know where to break Coptic (Unicode?) // lines, so insert a zero-width space at every space so // word wrap acutally works Text = Scripting.ParseTextCommands(stanza.Text.Replace(" ", " \u200B")), FontFamily = Common.Segoe, FontSize = Common.GetCopticFontSize(), TextWrapping = TextWrapping.Wrap, Foreground = new SolidColorBrush(foreground) }; return(contentBlock); #endregion #region Arabic case Language.Arabic: contentBlock = new TextBlock { Text = Scripting.ParseTextCommands(stanza.Text), FontFamily = Common.Segoe, FontSize = Common.GetEnglishFontSize(), TextWrapping = TextWrapping.Wrap, TextAlignment = TextAlignment.Right, Foreground = new SolidColorBrush(foreground) }; break; #endregion } return(contentBlock); }
public static bool Gamemode(string Name) { if (Net.Work.GetNetworkPeer() != null && Net.Work.IsNetworkServer()) { return(Scripting.LoadGamemode(Name)); } Console.ThrowPrint("Cannot set gamemode when not hosting"); return(false); }
/// <inheritdoc /> public override void OnEndContainsFocus() { base.OnEndContainsFocus(); // Call event after this 'focus contains flag' propagation ends to prevent focus issues if (LostFocus != null) { Scripting.RunOnUpdate(LostFocus); } }
public Scripting.ScriptNode GetNext(Scripting.ScriptNode node, bool throw_exception) { if (node.NextExpression.Index < 0 || node.NextExpression.Index > Nodes.Count) if (throw_exception) throw new Debug.ExceptionLog("NextExpression is not valid. {0:X} {1:X}", node.Index, node.NextExpression.Index); else return null; return Nodes[node.NextExpression]; }
/// <summary> /// Registers scripting class /// </summary> public void RegisterClass <TType>() where TType : new() { #region Precondition checking if (View == null) { throw new InvalidOperationException("View should be initialized first"); } #endregion Scripting.RegisterClass <TType>(View); }
public static void AddTween(FTweener tween) { if (!Platform.IsInMainThread) { Scripting.InvokeOnUpdate(() => { AddTween(tween); }); return; } Instance.AddT(tween); }
public void Init() { if (GlobalStuff.FindSetting("isNew") == "1") { MessageBox.Show("Please initialize the database in Misc > Database with Scan"); this.BeginInvoke(new MethodInvoker(Close)); return; } Scripting.SetScriptOutput(rtb2); init = true; }
public override Variant CalculateFromValue() { if (_isRecursing) { return(new Variant(0)); } try { if (Of == null) { logger.Error("Error, Of returned null"); return(null); } _isRecursing = true; long size = Of.Value.LengthBits; if (lengthType == LengthType.Bytes) { if (_expressionSet != null) { Dictionary <string, object> state = new Dictionary <string, object>(); state["size"] = size / 8; state["value"] = size / 8; state["self"] = From; object newValue = Scripting.EvalExpression(_expressionSet, state); size = Convert.ToInt64(newValue) * 8; } size = size / 8; } else { if (_expressionSet != null) { Dictionary <string, object> state = new Dictionary <string, object>(); state["size"] = size; state["value"] = size; state["self"] = From; object newValue = Scripting.EvalExpression(_expressionSet, state); size = Convert.ToInt64(newValue); } } return(new Variant(size)); } finally { _isRecursing = false; } }
public override Variant CalculateFromValue() { if (_isRecursing) { return(new Variant(0)); } try { _isRecursing = true; if (Of == null) { logger.Error("Error, Of returned null"); return(null); } Array OfArray = Of as Array; if (OfArray == null) { logger.Error( string.Format("Count Relation requires '{0}' to be an array. Set the minOccurs and maxOccurs properties.", OfName)); return(null); } int count = OfArray.Count; // Allow us to override the count of the array if (OfArray.overrideCount.HasValue) { count = (int)OfArray.overrideCount; } if (_expressionSet != null) { Dictionary <string, object> state = new Dictionary <string, object>(); state["count"] = count; state["value"] = count; state["self"] = this._parent; object value = Scripting.EvalExpression(_expressionSet, state); count = Convert.ToInt32(value); } return(new Variant(count)); } finally { _isRecursing = false; } }
public void Message(Scripting.Personality p, string text) { if (InvokeRequired) { Invoke(new MessageDelegate(Message), p, text); } else { chatHistory.Append(p, text); } }
public void loadPalettes() { palettes = new Dictionary <string, List <Color> >(); List <String> fileArray = Scripting.getFilesFromFolder(gfxFolder + "palettes"); foreach (string t in fileArray) { palettes.Add(t, Scripting.loadImage(gfxFolder + "palettes/" + t + ".png").getPalette()); } }
private void Scripting_SelectScripts(object sender, RoutedEventArgs e) { var scriptView = new ScriptSelectView("Scripts"); scriptView.ShowDialog(); var toLoad = scriptView.GetSelectedScripts(); ScriptProvider = new Scripting(); ScriptProvider.LoadScripts(toLoad); _selectedScripts = toLoad; }
private void Scripting_ReloadScripts(object sender, RoutedEventArgs e) { if (_selectedScripts.Length == 0) { MessageBox.Show("No scripts were selected.", "Error", MessageBoxButton.OK, MessageBoxImage.Error); return; } ScriptProvider = new Scripting(); ScriptProvider.LoadScripts(_selectedScripts); }
public static void Execute(string Command) { Console.Print("\n>>> " + Command); if (History.Count <= 0 || History[History.Count - 1] != Command) { History.Add(Command); } HistoryLocation = History.Count; Scripting.RunConsoleLine(Command); }
public static bool UnloadGm() { if (Scripting.GamemodeName != "") { Console.Print($"Successfully unloaded gamemode '{Scripting.GamemodeName}'"); Scripting.UnloadGamemode(); return(true); } Console.ThrowPrint("No gamemode loaded to unload"); return(false); }
static void applySettings(WebRequest request) { Scripting.SetUserSetting("Graphics/Enable Lensflares", Boolean.Parse(request.GetQuery("lensFlares"))); Scripting.SetUserSetting("Graphics/Enable Volumetric Scattering", Boolean.Parse(request.GetQuery("volumetricScattering"))); Scripting.SetUserSetting("Graphics/Enable Bloom", Boolean.Parse(request.GetQuery("bloom"))); Scripting.SetUserSetting("Graphics/Enable AfterImage", Boolean.Parse(request.GetQuery("afterImage"))); Scripting.SetUserSetting("Graphics/Enable Tonemapping", Boolean.Parse(request.GetQuery("tonemapping"))); Scripting.SetUserSetting("Graphics/Enable Noise", Boolean.Parse(request.GetQuery("noise"))); Scripting.SetUserSetting("Graphics/Enable Shadows", Boolean.Parse(request.GetQuery("shadows"))); Scripting.SetUserSetting("Graphics/Enable SSAO", Boolean.Parse(request.GetQuery("ssao"))); Scripting.SetUserSetting("Graphics/Enable Fog", Boolean.Parse(request.GetQuery("fog"))); Scripting.SetUserSetting("Graphics/Enable FXAA", Boolean.Parse(request.GetQuery("fxaa"))); bool fullscreen = Boolean.Parse(request.GetQuery("fullscreen")); if (fullscreen) { Scripting.SetUserSettingString("WindowManager/Fullscreen", "0"); } else { Scripting.SetUserSettingString("WindowManager/Fullscreen", "-1"); } string resolution = request.GetQuery("resolution"); if (resolution == "Native Resolution" || resolution == "Native+Resolution") { resolution = "-1x-1"; } Scripting.SetUserSettingString("WindowManager/Resolution", resolution); // Compute both lod settings from the single GUI slider value. double falloff = 10; double minDis = 0; double lod = Double.Parse(request.GetQuery("lod")); if (lod < 1 && lod >= 0) { falloff = 10 + lod * 30.0; minDis = 0; } else if (lod <= 2) { falloff = 40; minDis = (lod - 1) * 30.0; } Scripting.SetUserSettingNumber("Graphics/Lod Falloff", falloff); Scripting.SetUserSettingNumber("Graphics/Min Lod Range", minDis); }
Scripting() { Self = this; ConsoleEngine = new Jurassic.ScriptEngine(); foreach (List <object> List in API.Expose(API.LEVEL.CONSOLE, this)) { ConsoleEngine.SetGlobalFunction((string)List[0], (Delegate)List[1]); } SetupServerEngine(); SetupClientEngine(); }
public static List <List <object> > Expose(LEVEL ApiLevel, Scripting ScriptingRef) { List <List <object> > Output = new List <List <object> >(); switch (ApiLevel) { case LEVEL.CONSOLE: Output.Add(GetDelCall("print")); Output.Add(GetDelCall("log")); Output.Add(GetDelCall("ms_get")); Output.Add(GetDelCall("host")); Output.Add(GetDelCall("connect")); Output.Add(GetDelCall("peerlist_get")); Output.Add(GetDelCall("bind")); Output.Add(GetDelCall("unbind")); Output.Add(GetDelCall("player_input_forward_set")); Output.Add(GetDelCall("player_input_forward_get")); Output.Add(GetDelCall("player_input_backward_set")); Output.Add(GetDelCall("player_input_backward_get")); Output.Add(GetDelCall("player_input_right_set")); Output.Add(GetDelCall("player_input_right_get")); Output.Add(GetDelCall("player_input_left_set")); Output.Add(GetDelCall("player_input_left_get")); Output.Add(GetDelCall("player_input_sprint_set")); Output.Add(GetDelCall("player_input_sprint_get")); Output.Add(GetDelCall("player_input_jump_set")); Output.Add(GetDelCall("player_input_jump_get")); Output.Add(GetDelCall("player_input_inventory_up")); Output.Add(GetDelCall("player_input_inventory_down")); Output.Add(GetDelCall("player_input_look_up")); Output.Add(GetDelCall("player_input_look_down")); Output.Add(GetDelCall("player_input_look_right")); Output.Add(GetDelCall("player_input_look_left")); Output.Add(GetDelCall("player_input_primary_fire")); break; case LEVEL.SERVER_GM: Output.Add(GetDelCall("log")); Output.Add(GetDelCall("ms_get")); Output.Add(GetDelCall("peerlist_get")); break; case LEVEL.CLIENT_GM: Output.Add(GetDelCall("log")); Output.Add(GetDelCall("ms_get")); Output.Add(GetDelCall("peerlist_get")); break; } return(Output); }
public override void Translate( Scripting.Compiler.ScriptCompiler compiler, Scripting.Compiler.AST.AbstractNode node ) { var obj = (ObjectAbstractNode)node; var parent = (ObjectAbstractNode)obj.Parent; //Translate section within a pass context if ( parent.Cls == "pass" ) { TranslatePass( compiler, node ); } if ( parent.Cls == "texture_unit" ) { TranslateTextureUnit( compiler, node ); } }
public override SubRenderState CreateInstance( Scripting.Compiler.ScriptCompiler compiler, Scripting.Compiler.AST.PropertyAbstractNode prop, Graphics.Pass pass, SGScriptTranslator stranslator ) { if ( prop.Name == "fog_stage" ) { if ( prop.Values.Count >= 1 ) { string strValue; if ( !SGScriptTranslator.GetString( prop.Values[ 0 ], out strValue ) ) { //compiler.AddError(...); return null; } if ( strValue == "ffp" ) { SubRenderState subRenderState = CreateOrRetrieveInstance( stranslator ); var fogSubRenderState = (FFPFog)subRenderState; int it = 0; if ( prop.Values.Count >= 2 ) { it++; if ( !SGScriptTranslator.GetString( prop.Values[ it ], out strValue ) ) { //compiler.AddError(...); return null; } if ( strValue == "per_vertex" ) { fogSubRenderState.CalculationMode = FFPFog.CalcMode.PerVertex; } else if ( strValue == "per_pixel" ) { fogSubRenderState.CalculationMode = FFPFog.CalcMode.PerPixel; } } return subRenderState; } } } return null; }
public override SubRenderState CreateInstance( Scripting.Compiler.ScriptCompiler compiler, Scripting.Compiler.AST.PropertyAbstractNode prop, Graphics.Pass pass, SGScriptTranslator stranslator ) { if ( prop.Name == "integrated_pssm4" ) { if ( prop.Values.Count != 4 ) { //TODO // compiler.AddError(...); } else { var splitPointList = new List<Real>(); foreach ( var it in prop.Values ) { Real curSplitValue; if ( !SGScriptTranslator.GetReal( it, out curSplitValue ) ) { //TODO //compiler.AddError(...); break; } splitPointList.Add( curSplitValue ); } if ( splitPointList.Count == 4 ) { SubRenderState subRenderState = CreateOrRetrieveInstance( stranslator ); var pssmSubRenderState = (IntegratedPSSM3)subRenderState; pssmSubRenderState.SetSplitPoints( splitPointList ); return pssmSubRenderState; } } } return null; }
public override SubRenderState CreateInstance( Scripting.Compiler.ScriptCompiler compiler, Scripting.Compiler.AST.PropertyAbstractNode prop, Graphics.Pass pass, SGScriptTranslator stranslator ) { if ( prop.Name == "lighting_stage" ) { if ( prop.Values.Count == 1 ) { string modelType; if ( SGScriptTranslator.GetString( prop.Values[ 0 ], out modelType ) == false ) { //compiler.AddError(...) return null; } if ( modelType == "per_pixel" ) { return CreateOrRetrieveInstance( stranslator ); } } } return null; }
bool ParseFunction(short index, Scripting.ScriptNode _node) { return true; }
bool ParseVariable(Scripting.ScriptNode _node) { return true; }
void CallPredicate(Scripting.ScriptNode _node) { }
internal static bool GetString(Scripting.Compiler.AST.AbstractNode it, out string strValue) { throw new NotImplementedException(); }
private void TranslatePass( Scripting.Compiler.ScriptCompiler compiler, AbstractNode node ) { var obj = (ObjectAbstractNode)node; var pass = (Pass)obj.Parent.Context; Technique technique = pass.Parent; Material material = technique.Parent; ShaderGenerator shaderGenerator = ShaderGenerator.Instance; string dstTechniqueSchemeName = obj.Name; bool techniqueCreated; //Make sure scheme name is valid - use default if none exists if ( dstTechniqueSchemeName == string.Empty ) { dstTechniqueSchemeName = ShaderGenerator.DefaultSchemeName; } //Create the shader based tedchnique techniqueCreated = shaderGenerator.CreateShaderBasedTechnique( material.Name, material.Group, technique.SchemeName, dstTechniqueSchemeName, shaderGenerator. CreateShaderOverProgrammablePass ); if ( techniqueCreated ) { //Go over all render state properties for ( int i = 0; i < obj.Children.Count; i++ ) { if ( obj.Children[ i ] is PropertyAbstractNode ) { var prop = obj.Children[ i ] as PropertyAbstractNode; SubRenderState subRenderState; //Handle light count property. if ( prop != null && prop.Name == "light_count" ) { if ( prop.Values.Count != 3 ) { //compiler.AddError(...); } else { var lightCount = new int[3]; if ( !getInts( prop.Values, 0, out lightCount, 3 ) ) { //compiler.addError(...); } else { shaderGenerator.CreateScheme( dstTechniqueSchemeName ); RenderState renderState = shaderGenerator.GetRenderState( dstTechniqueSchemeName, material.Name, material.Group, (ushort)pass.Index ); renderState.SetLightCount( lightCount ); renderState.LightCountAutoUpdate = false; } } } else { subRenderState = ShaderGenerator.Instance.createSubRenderState( compiler, prop, pass, this ); if ( subRenderState != null ) { AddSubRenderState( subRenderState, dstTechniqueSchemeName, material.Name, material.Group, pass.Index ); } } } else { processNode( compiler, obj.Children[ i ] ); } } } }
private void TranslateTextureUnit( Scripting.Compiler.ScriptCompiler compiler, AbstractNode node ) { var obj = (ObjectAbstractNode)node; var texState = (TextureUnitState)obj.Parent.Context; Pass pass = texState.Parent; Technique technique = pass.Parent; Material material = technique.Parent; ShaderGenerator shaderGenerator = ShaderGenerator.Instance; string dstTechniqueSchemeName = obj.Name; bool techniqueCreated; //Make sure teh scheme is valid - use default if none exists if ( dstTechniqueSchemeName == string.Empty ) { dstTechniqueSchemeName = ShaderGenerator.DefaultSchemeName; } //check if technique already created techniqueCreated = shaderGenerator.HasShaderBasedTechnique( material.Name, material.Group, technique.SchemeName, dstTechniqueSchemeName ); if ( techniqueCreated == false ) { //Create the shader based techniqe techniqueCreated = shaderGenerator.CreateShaderBasedTechnique( material.Name, material.Group, technique.SchemeName, dstTechniqueSchemeName, shaderGenerator. CreateShaderOverProgrammablePass ); } if ( techniqueCreated ) { //Attempt to get the render state which might have been created by the pass parsing this.generatedRenderState = shaderGenerator.GetRenderState( dstTechniqueSchemeName, material.Name, material.Group, (ushort)pass.Index ); //Go over all the render state properties for ( int i = 0; i < obj.Children.Count; i++ ) { if ( obj.Children[ i ] is PropertyAbstractNode ) { var prop = obj.Children[ i ] as PropertyAbstractNode; SubRenderState subRenderState = ShaderGenerator.Instance.createSubRenderState( compiler, prop, texState, this ); if ( subRenderState != null ) { AddSubRenderState( subRenderState, dstTechniqueSchemeName, material.Name, material.Group, pass.Index ); } } else { processNode( compiler, obj.Children[ i ] ); } } } }
internal IList<ScriptToRun> GetScriptsFor(string operationName, ObjectClass objectClass, Scripting.Position position) { List<ScriptToRun> rv = new List<ScriptToRun>(); foreach (OperationInfo operationInfo in OperationInfo) { // does operation name match? bool match; if (operationInfo.OpType == null || operationInfo.OpType.Length == 0) { match = true; } else { match = false; foreach (string specifiedOpType in operationInfo.OpType) { if (specifiedOpType.Equals(operationName, StringComparison.CurrentCultureIgnoreCase)) { match = true; } } } if (match) { CollectionUtil.AddAll(rv, operationInfo.GetScriptsFor(objectClass, position)); } } rv.Sort((x, y) => x.Order.CompareTo(y.Order)); return rv; }
internal IList<ScriptToRun> GetScriptsFor(ObjectClass objectClass, Scripting.Position position) { var rv = new List<ScriptToRun>(); ScriptToRun[] scripts; switch (position) { case Scripting.Position.BeforeMain: scripts = BeforeMain; break; case Scripting.Position.InsteadOfMain: scripts = InsteadOfMain; break; case Scripting.Position.AfterMain: scripts = AfterMain; break; default: throw new ArgumentException("Invalid position: " + position); } if (scripts != null) { foreach (ScriptToRun scriptInfo in scripts) { if (scriptInfo.IsRelevantFor(objectClass)) { rv.Add(scriptInfo); } } } return rv; }
/// <summary> /// Creates a new universe of a particular shape, size, boundary type, and number of dimensions. /// </summary> /// <param name="NumberDimensions">The maximum number of dimensions that this universe occupies</param> /// <param name="ResolveScript">The boundary resolve script attached to this universe</param> /// <param name="Radius">The radius (size) of this universe (if the boundary isn't infinate)</param> public Universe(int NumberDimensions, Scripting.BoundaryScript ResolveScript, double Radius) { this.Boundary = new UniverseBoundary(Radius, ResolveScript); this.NumberDimensions = NumberDimensions; }
public override SubRenderState CreateInstance( Scripting.Compiler.ScriptCompiler compiler, Scripting.Compiler.AST.PropertyAbstractNode prop, Graphics.Pass pass, SGScriptTranslator stranslator ) { return null; }
internal static bool GetReal(Scripting.Compiler.AST.AbstractNode it, out Math.Real curSplitValue) { throw new NotImplementedException(); }
internal static void GetBoolean(Scripting.Compiler.AST.AbstractNode abstractNode, out bool correctAntipodalityHandling) { throw new NotImplementedException(); }
internal static bool GetInt(Scripting.Compiler.AST.AbstractNode it, out int boneCount) { throw new NotImplementedException(); }
bool ParseNonPrimitive(Scripting.ScriptNode _node) { #region if the node is actually a primitive... if (Util.Flags.Test(_node.PointerType, (short)NodeFlags.Primitive)) { throw new CompileException("i expected {0}, but i got an expression. {1}:0x{2:X}", "File offset", (_node.Type == _SpecialForm) ? "\"script\" or \"global\"" : "a function name", "File offset", _node.Pointer ); } #endregion #region if a special form (ie, global or script) if (_node.Type == _SpecialForm) { if (StrCmp(_node.Pointer, "global")) return AddGlobal(_node); else if (StrCmp(_node.Pointer, "script")) return AddScript(_node); else throw new CompileException("i expected \"script\" or \"global\"."); } #endregion #region else everything else else { CallPredicate(_node); // script or function index short proc_index = _node.Opcode; if (proc_index == -1) throw new CompileException("this is not a valid function or script name. {0}:0x{1:X}", "File offset", _node.Pointer); Scripting.XmlInterface BSD = State.Definition; #region if node is script return expression if (!Util.Flags.Test(_node.PointerType, (short)NodeFlags.ReturnFuncValue)) { if (State.Scripts[proc_index].ScriptType != _Static || State.Scripts[proc_index].ScriptType != _Stub) throw new CompileException("this is not a static script. {0}:0x{1:X}", "File offset", _node.Pointer); else { if (_node.Type != _Unparsed || TypeCanCast(State.Scripts[proc_index].ReturnType, _node.Type)) { if (_node.Type == _Unparsed) _node.Type = State.Scripts[proc_index].ReturnType; } else { throw new CompileException("i expected a {0}, but this script returns a {1}. {2}:0x{3:X}", BSD.GetValueType(_node.Type).Name, BSD.GetValueType(State.Scripts[proc_index].ReturnType).Name, "File offset", _node.Pointer); } } return true; } #endregion #region else its a function call else { if (_node.Type != _Unparsed) { if (!TypeCanCast(BSD.GetFunction(proc_index).ReturnType, _node.Type)) throw new CompileException("i expected a {0}, but this function returns a {1}. {2}:0x{3:X}", BSD.GetValueType(BSD.GetFunction(proc_index).ReturnType).Name, BSD.GetValueType(_node.Type).Name, "File offset", _node.Pointer); } if (CantCompileBlocks && IsSleeperFunction(proc_index)) throw new CompileException("it is illegal to block in this context. {0}:0x{1:X}", "File offset", _node.Pointer); else if (CantCompileVariableSets && IsVarSetterFunction(proc_index)) throw new CompileException("it is illegal to set the value of variables in this context. {0}:0x{1:X}", "File offset", _node.Pointer); if (_node.Type == _Unparsed && BSD.GetFunction(proc_index).ReturnType != _Passthrough) _node.Type = BSD.GetFunction(_node.Opcode).ReturnType; return ParseFunction(proc_index, _node); } #endregion } #endregion }
bool ParsePrimitive(Scripting.ScriptNode _node) { Debug.Assert.If(_node.Type == _Unparsed || _node.Type == _SpecialForm); if (_node.Type == _SpecialForm) throw new CompileException("i expected a script or variable definition."); if (_node.Type == _Void) throw new CompileException("the value of this expression (in a <void> slot) can never be used"); if (!PostProcessing || Util.Flags.Test(_node.PointerType, (short)NodeFlags.Variable)) if (ParseVariable(_node)) return false; if (_node.Type == _Unparsed || ParserError || !PostProcessing && Util.Flags.Test(_node.PointerType, (short)NodeFlags.Variable)) return false; int parse_index = _node.Type << 2; Parser parser_func = null; if (parse_index < PrimitiveParsers.Count) { parser_func = PrimitiveParsers[parse_index]; if (parser_func == null) throw new CompileException("expressions of type {0} are currently unsupported. {1}:0x{2:X}", State.Definition.GetValueType(_node.Type).Name, "File offset", _node.Pointer - 1); return parser_func(_node); } return true; }
bool AddScript(Scripting.ScriptNode _node) { return true; }
bool Parse(Scripting.ScriptNode _node, short expected_type) { Debug.Assert.If(!ParserError, "Tried to {0} with an unhandled error!", "parse"); Debug.Assert.If(expected_type == _Unparsed || expected_type == _SpecialForm); if (_node.Type == 0) { _node.Type = expected_type; if (Util.Flags.Test(_node.PointerType, (short)NodeFlags.Primitive)) { _node.Opcode = expected_type; return ParsePrimitive(_node); } else return ParseNonPrimitive(_node); } return true; }
public override SubRenderState CreateInstance( Scripting.Compiler.ScriptCompiler compiler, PropertyAbstractNode prop, Graphics.Pass pass, SGScriptTranslator stranslator ) { if ( prop.Name == "lighting_stage" ) { if ( prop.Values.Count >= 2 ) { string strValue; int it = 0; //Read light model type. if ( !SGScriptTranslator.GetString( prop.Values[ it ], out strValue ) ) { //compiler.AddError(...) return null; } //Case light model type is normal map if ( strValue == "normal_map" ) { it++; if ( !SGScriptTranslator.GetString( prop.Values[ it ], out strValue ) ) { //compiler.AddError(...) return null; } SubRenderState subRenderState = CreateOrRetrieveInstance( stranslator ); var normalMapSubRenderState = subRenderState as NormalMapLighting; normalMapSubRenderState.NormalMapTextureName = strValue; //Read normal map space type. if ( prop.Values.Count >= 3 ) { it++; if ( !SGScriptTranslator.GetString( prop.Values[ it ], out strValue ) ) { //compiler.AddError(...) return null; } //Normal map defines normals in tangent space. if ( strValue == "tangent_space" ) { normalMapSubRenderState.NormalMapSpace = NormalMapSpace.Tangent; } //Normal map defines normals in object space if ( strValue == "object_space" ) { normalMapSubRenderState.NormalMapSpace = NormalMapSpace.Object; } } //Read texture coordinate index. if ( prop.Values.Count >= 4 ) { int textureCoordinatesIndex = 0; it++; if ( !SGScriptTranslator.GetInt( prop.Values[ it ], out textureCoordinatesIndex ) ) { normalMapSubRenderState.TexCoordIndex = textureCoordinatesIndex; } } //Read texture filtering format if ( prop.Values.Count >= 5 ) { it++; if ( !SGScriptTranslator.GetString( prop.Values[ it ], out strValue ) ) { //compiler.AddError(...) return null; } if ( strValue == "none" ) { normalMapSubRenderState.SetNormalMapFiltering( Graphics.FilterOptions.Point, Graphics.FilterOptions.Point, Graphics.FilterOptions.None ); } else if ( strValue == "bilinear" ) { normalMapSubRenderState.SetNormalMapFiltering( Graphics.FilterOptions.Linear, Graphics.FilterOptions.Linear, Graphics.FilterOptions.Point ); } else if ( strValue == "trilinear" ) { normalMapSubRenderState.SetNormalMapFiltering( Graphics.FilterOptions.Linear, Graphics.FilterOptions.Linear, Graphics.FilterOptions.Linear ); } else if ( strValue == "anisotropic" ) { normalMapSubRenderState.SetNormalMapFiltering( Graphics.FilterOptions.Anisotropic, Graphics.FilterOptions.Anisotropic, Graphics.FilterOptions.Linear ); } } //Read max anisotropy value if ( prop.Values.Count >= 6 ) { int maxAnisotropy = 0; it++; if ( SGScriptTranslator.GetInt( prop.Values[ it ], out maxAnisotropy ) ) { normalMapSubRenderState.NormalMapAnisotropy = maxAnisotropy; } } //Read mip bias value. if ( prop.Values.Count >= 7 ) { Real mipBias = 0; it++; if ( SGScriptTranslator.GetReal( prop.Values[ it ], out mipBias ) ) { normalMapSubRenderState.NormalMapMipBias = mipBias; } } return subRenderState; } } } return null; }
public override bool CheckFor( Scripting.Compiler.Keywords nodeId, Scripting.Compiler.Keywords parentId ) { return true; }
bool AddGlobal(Scripting.ScriptNode _node) { return true; }
public override SubRenderState CreateInstance( Scripting.Compiler.ScriptCompiler compiler, Scripting.Compiler.AST.PropertyAbstractNode prop, Pass pass, SGScriptTranslator stranslator ) { if ( prop.Name == "hardware_skinning" ) { bool hasError = false; int boneCount = 0; int weightCount = 0; string skinningType = string.Empty; SkinningType skinType = SkinningType.Linear; bool correctAntipodalityHandling = false; bool scalingShearingSupport = false; if ( prop.Values.Count >= 2 ) { int it = 0; if ( SGScriptTranslator.GetInt( prop.Values[ it ], out boneCount ) == false ) { hasError = true; } it++; if ( SGScriptTranslator.GetInt( prop.Values[ it ], out weightCount ) == false ) { hasError = true; } if ( prop.Values.Count >= 5 ) { it++; SGScriptTranslator.GetString( prop.Values[ it ], out skinningType ); it++; SGScriptTranslator.GetBoolean( prop.Values[ it ], out correctAntipodalityHandling ); it++; SGScriptTranslator.GetBoolean( prop.Values[ it ], out scalingShearingSupport ); } //If the skinningType is not specified or is specified incorretly, default to linear if ( skinningType == "dual_quaternion" ) { skinType = SkinningType.DualQuaternion; } else { skinType = SkinningType.Linear; } } if ( hasError ) { //TODO //compiler.AddError(...); return null; } else { //create and update the hardware skinning sub render state SubRenderState subRenderState = CreateOrRetrieveInstance( stranslator ); var hardSkinSrs = (HardwareSkinning)subRenderState; hardSkinSrs.SetHardwareSkinningParam( boneCount, weightCount, skinType, correctAntipodalityHandling, scalingShearingSupport ); return subRenderState; } } return null; }
public Scripting.ScriptNode GetNext(Scripting.ScriptNode node) { return GetNext(node, false); }