void requestroute_get(LanguageInterpreter sender, FunctionArgs args) { if (EUtils.CheckArgs(2, args)) { object param = args.EvaluateParameters()[0]; object param2 = args.EvaluateParameters()[1]; /**/ if (EUtils.CheckArgType(param, typeof(string))) { if (EUtils.CheckArgType(param2, typeof(UserFunction)) || EUtils.CheckArgType(param2, typeof(String))) { string relative_path = (string)param; //sender.Interpreter.HandleException(new AzLang.Exception(sender.Interpreter.CurrentFile, sender.Interpreter.CurrentLine, "info: new get request handler [" + relative_path + "]", "detail", "dunno")); if (EUtils.CheckArgType(param2, typeof(UserFunction))) { UserFunction handler = (UserFunction)param2; routedHTTPInterpreterServer.RequestHandlers.Add(relative_path, new RequestHandler(handler, RequestMethod.GET, relative_path)); } else { string file = (string)param2; if (!System.IO.File.Exists(file) && !System.IO.Directory.Exists(file)) { sender.Interpreter.HandleException(new AzLang.Exception(sender.Interpreter.CurrentFile, sender.Interpreter.CurrentLine, "File or folder non-existent", "The specified file or folder '" + file + "' does not exist.", "Check the file path provided for errors.")); } else { routedHTTPInterpreterServer.RequestHandlers.Add(relative_path, new RequestHandler(file, RequestMethod.GET, relative_path)); } } } else { sender.Interpreter.HandleException(new AzLang.Exception(sender.Interpreter.CurrentFile, sender.Interpreter.CurrentLine, "Invalid parameter type.", "Function expects parameter of type 'UserFunction' or 'String', got '" + param2.GetType().Name + "'.", "")); } } else { sender.Interpreter.HandleException(new AzLang.Exception(sender.Interpreter.CurrentFile, sender.Interpreter.CurrentLine, "Invalid parameter type.", "Function expects parameter of type 'String', got '" + param.GetType().Name + "'.", "")); } } else { sender.Interpreter.HandleException(Consts.Exceptions.ParameterCountMismatch(sender.Interpreter.CurrentFile, sender.Interpreter.CurrentLine, 1)); } }
private static bool GetCanvas(FunctionArgs p_args) { if (p_args.Parameters.Length != 1) { errorMessage = "Invalid number of parameters in GetSprite function."; return(false); } object[] evalParams = p_args.EvaluateParameters(); if (typeof(Transform).IsAssignableFrom(evalParams[0].GetType())) { Transform transform = (Transform)evalParams[0]; Canvas canvas = transform.GetComponentInParent <Canvas>(); if (canvas != null) { p_args.HasResult = true; p_args.Result = canvas; return(true); } else { errorMessage = "Transform or its parents has no Canvas component in GetCanvas function."; return(false); } } errorMessage = "Invalid parameters in GetCanvas function."; return(false); }
// /** // * Get parent of a transform // */ // private static bool GetParent(FunctionArgs p_args) // { // if (p_args.Parameters.Length != 1) // { // errorMessage = "Invalid parameters in GetParent function."; // return false; // } // // object[] evalParams = p_args.EvaluateParameters(); // // if (typeof(Transform).IsAssignableFrom(evalParams[0].GetType())) // { // p_args.HasResult = true; // p_args.Result = ((Transform) evalParams[0]).parent; // return true; // } // // errorMessage = "Invalid parameters in GetParent function."; // return false; // } /** * Get child of transform at index */ private static bool GetChildAt(FunctionArgs p_args) { if (p_args.Parameters.Length != 2) { errorMessage = "Invalid number of parameters in GetChild function."; return(false); } object[] evalParams = p_args.EvaluateParameters(); if (typeof(Transform).IsAssignableFrom(evalParams[0].GetType()) && evalParams[1].GetType() == typeof(int)) { Transform transform = (Transform)evalParams[0]; int childIndex = (int)evalParams[1]; if (transform != null && transform.childCount > childIndex) { p_args.HasResult = true; p_args.Result = transform.GetChild(childIndex); return(true); } else { errorMessage = "Invalid transform or child index in GetChildAt function."; return(false); } } errorMessage = "Invalid parameters in GetChildAt function."; return(false); }
/** * Normalize Vector type */ private static bool Normalize(FunctionArgs p_args) { if (p_args.Parameters.Length != 1) { errorMessage = "Invalid parameters in Normalize function."; return(false); } object[] evalParams = p_args.EvaluateParameters(); Type paramType = evalParams[0].GetType(); if (paramType == typeof(Vector2)) { p_args.HasResult = true; p_args.Result = ((Vector2)evalParams[0]).normalized; return(true); } if (paramType == typeof(Vector3)) { p_args.HasResult = true; p_args.Result = ((Vector3)evalParams[0]).normalized; return(true); } errorMessage = "Normalize function for type " + paramType + " is not implemented"; return(false); }
public static void Create(LanguageInterpreter sender, FunctionArgs args) { if (EUtils.CheckArgs(1, args)) { object param = args.EvaluateParameters()[0]; if (EUtils.CheckArgType(param, typeof(string))) { string filepath = (string)param; if (!File.Exists(filepath)) { // could just use .Dispose(); ... using (File.Create(filepath)) { } } else { sender.Interpreter.HandleException(new Exception(sender.Interpreter.CurrentFile, sender.Interpreter.CurrentLine, "Error creating file.", "A file already exists at the specified path.", "")); } } else { sender.Interpreter.HandleException(new Exception(sender.Interpreter.CurrentFile, sender.Interpreter.CurrentLine, "Invalid parameter type.", "Function expects parameter of type 'String', got '" + param.GetType().Name + "'.", "")); } } else { sender.Interpreter.HandleException(Consts.Exceptions.ParameterCountMismatch(sender.Interpreter.CurrentFile, sender.Interpreter.CurrentLine, 1)); } }
void json_parse(LanguageInterpreter sender, FunctionArgs args) { if (EUtils.CheckArgs(1, args)) { object param = args.EvaluateParameters()[0]; if (EUtils.CheckArgType(param, typeof(string))) { string json_str = (string)param; dynamic parsed_json = DynamicJson.Parse(json_str); if (parsed_json.IsArray) { AnonymousVariableArray finalArray = VariableArrayFromDynamic(parsed_json); args.HasResult = true; args.Result = finalArray; } else { sender.Interpreter.HandleException(new Exception(sender.Interpreter.CurrentFile, sender.Interpreter.CurrentLine, "Unimplemented", "Only arrays are implemented in the JSON parser.", "")); } } else { sender.Interpreter.HandleException(new Exception(sender.Interpreter.CurrentFile, sender.Interpreter.CurrentLine, "Invalid parameter type.", "Function expects parameter of type 'String', got '" + param.GetType().Name + "'.", "")); } } else { sender.Interpreter.HandleException(Consts.Exceptions.ParameterCountMismatch(sender.Interpreter.CurrentFile, sender.Interpreter.CurrentLine, 1)); } }
private static bool RandomInsideCircle(FunctionArgs p_args) { if (p_args.Parameters.Length != 0 && p_args.Parameters.Length != 1 && p_args.Parameters.Length != 2) { errorMessage = "Invalid parameters in RandomInsideCircle function"; return(false); } object[] evalParams = p_args.EvaluateParameters(); switch (evalParams.Length) { case 0: p_args.HasResult = true; p_args.Result = UnityEngine.Random.insideUnitCircle; return(true); case 2: // TODO type checking? p_args.HasResult = true; p_args.Result = UnityEngine.Random.insideUnitCircle * Convert.ToSingle(evalParams[0]); return(true); case 4: p_args.HasResult = true; var vector = UnityEngine.Random.insideUnitCircle; vector.Scale(new Vector2(Convert.ToSingle(evalParams[0]), Convert.ToSingle(evalParams[1]))); p_args.Result = vector; return(true); } errorMessage = "Unknown error in function RandomInsideCircle"; return(false); }
private static bool GetSprite(FunctionArgs p_args) { if (p_args.Parameters.Length != 1) { errorMessage = "Invalid number of parameters in GetSprite function."; return(false); } object[] evalParams = p_args.EvaluateParameters(); if (typeof(Transform).IsAssignableFrom(evalParams[0].GetType())) { Transform transform = (Transform)evalParams[0]; Image image = transform.GetComponent <Image>(); if (image != null) { p_args.HasResult = true; p_args.Result = image.sprite; return(true); } else { errorMessage = "Transform has no Image component in GetSprite function."; return(false); } } errorMessage = "Invalid parameters in GetImage function."; return(false); }
/** * Add two values of type T together */ private static bool Add(FunctionArgs p_args) { if (p_args.Parameters.Length != 2) { errorMessage = "Invalid parameters in Add function."; return(false); } object[] evalParams = p_args.EvaluateParameters(); if (evalParams[0].GetType() == typeof(Vector2) && evalParams[1].GetType() == typeof(Vector2)) { p_args.HasResult = true; p_args.Result = (Vector2)evalParams[0] + (Vector2)evalParams[1]; return(true); } if (evalParams[0].GetType() == typeof(Vector3) && evalParams[1].GetType() == typeof(Vector3)) { p_args.HasResult = true; p_args.Result = (Vector3)evalParams[0] + (Vector3)evalParams[1]; return(true); } errorMessage = "Add function not implemented for parameters " + evalParams[0].GetType() + " and " + evalParams[1].GetType(); return(false); }
private static int Random(FunctionArgs args) { if (args.Parameters == null) { throw new ArgumentNullException(nameof(args.Parameters)); } var parameters = args.EvaluateParameters() ?? throw new NullReferenceException($"{nameof(args.EvaluateParameters)}() returned null."); if (parameters.Length < 2) { throw new ArgumentException($"{nameof(Random)}() requires 2 numerical parameters."); } var min = (int)Math.Round( (double)(parameters[0] ?? throw new NullReferenceException("First parameter is null.")) ); var max = (int)Math.Round( (double)(parameters[1] ?? throw new NullReferenceException("First parameter is null.")) ); return(min >= max ? min : Randomization.Next(min, max + 1)); }
public static void Delete(LanguageInterpreter sender, FunctionArgs args) { if (EUtils.CheckArgs(1, args)) { object param = args.EvaluateParameters()[0]; if (EUtils.CheckArgType(param, typeof(string))) { string filepath = (string)param; if (File.Exists(filepath)) { File.Delete(filepath); } else { sender.Interpreter.HandleException(new Exception(sender.Interpreter.CurrentFile, sender.Interpreter.CurrentLine, "Error deleting file.", "The specified file does not exist.", "")); } } else { sender.Interpreter.HandleException(new Exception(sender.Interpreter.CurrentFile, sender.Interpreter.CurrentLine, "Invalid parameter type.", "Function expects parameter of type 'String', got '" + param.GetType().Name + "'.", "")); } } else { sender.Interpreter.HandleException(Consts.Exceptions.ParameterCountMismatch(sender.Interpreter.CurrentFile, sender.Interpreter.CurrentLine, 1)); } }
/** * Scaling function for vector types, standard by components or by a scalar value */ private static bool Scale(FunctionArgs p_args) { if (p_args.Parameters.Length != 2) { errorMessage = "Invalid parameters in Scale function."; return(false); } object[] evalParams = p_args.EvaluateParameters(); if (evalParams[0].GetType() == typeof(Vector2)) { if (evalParams[1].GetType() == typeof(int) || evalParams[1].GetType() == typeof(float) || evalParams[1].GetType() == typeof(double)) { p_args.HasResult = true; p_args.Result = (Vector2)evalParams[0] * Convert.ToSingle(evalParams[1]); return(true); } if (evalParams[1].GetType() == typeof(Vector2)) { p_args.HasResult = true; Vector2 v2 = (Vector2)evalParams[0]; v2.Scale((Vector2)evalParams[1]); p_args.Result = v2; return(true); } errorMessage = "Invalid second parameter in Scale function."; return(true); } if (evalParams[0].GetType() == typeof(Vector3)) { if (evalParams[1].GetType() == typeof(int) || evalParams[1].GetType() == typeof(float) || evalParams[1].GetType() == typeof(double)) { p_args.HasResult = true; p_args.Result = (Vector3)evalParams[0] * Convert.ToSingle(evalParams[1]); return(true); } if (evalParams[1].GetType() == typeof(Vector3)) { p_args.HasResult = true; Vector3 v3 = (Vector3)evalParams[0]; v3.Scale((Vector3)evalParams[1]); p_args.Result = v3; return(true); } errorMessage = "Invalid second parameter of type " + evalParams[1].GetType() + " for Scale function."; return(false); } errorMessage = "Scale function for types " + evalParams[0].GetType() + ", " + evalParams[1].GetType() + " is not implemented."; return(false); }
/** * Multiply two values of type T together */ private static bool Mul(FunctionArgs p_args) { if (p_args.Parameters.Length != 2) { errorMessage = "Invalid parameters in Mul function."; return(false); } object[] evalParams = p_args.EvaluateParameters(); if (evalParams[0].GetType() == typeof(Vector2) && evalParams[1].GetType() == typeof(float)) { p_args.HasResult = true; p_args.Result = (Vector2)evalParams[0] * (float)evalParams[1]; return(true); } if (evalParams[0].GetType() == typeof(float) && evalParams[1].GetType() == typeof(Vector2)) { p_args.HasResult = true; p_args.Result = (float)evalParams[0] * (Vector2)evalParams[1]; return(true); } if (evalParams[0].GetType() == typeof(Vector2) && evalParams[1].GetType() == typeof(Vector2)) { p_args.HasResult = true; p_args.Result = (Vector2)evalParams[0] * (Vector2)evalParams[1]; return(true); } if (evalParams[0].GetType() == typeof(Vector3) && evalParams[1].GetType() == typeof(float)) { p_args.HasResult = true; p_args.Result = (Vector3)evalParams[0] * (float)evalParams[1]; return(true); } if (evalParams[0].GetType() == typeof(float) && evalParams[1].GetType() == typeof(Vector3)) { p_args.HasResult = true; p_args.Result = (float)evalParams[0] * (Vector3)evalParams[1]; return(true); } if (evalParams[0].GetType() == typeof(Vector3) && evalParams[1].GetType() == typeof(Vector3)) { p_args.HasResult = true; Vector3 scaled = (Vector3)evalParams[0]; scaled.Scale((Vector3)evalParams[1]); p_args.Result = scaled; return(true); } errorMessage = "Mul function not implemented for parameters " + evalParams[0].GetType() + " and " + evalParams[1].GetType(); return(false); }
public static void Append(LanguageInterpreter sender, FunctionArgs args) { if (EUtils.CheckArgs(2, args)) { object param = args.EvaluateParameters()[0]; object param2 = args.EvaluateParameters()[1]; if (EUtils.CheckArgType(param, typeof(string))) { if (EUtils.CheckArgType(param2, typeof(string))) { string filepath = (string)param; string text = (string)param2; if (File.Exists(filepath)) { args.HasResult = true; File.AppendAllText(filepath, text); } else { sender.Interpreter.HandleException(new Exception(sender.Interpreter.CurrentFile, sender.Interpreter.CurrentLine, "Error appending to file.", "The specified file does not exist.", "")); } } else { sender.Interpreter.HandleException(new Exception(sender.Interpreter.CurrentFile, sender.Interpreter.CurrentLine, "Invalid parameter type.", "Function expects parameter of type 'String', got '" + param2.GetType().Name + "'.", "")); } } else { sender.Interpreter.HandleException(new Exception(sender.Interpreter.CurrentFile, sender.Interpreter.CurrentLine, "Invalid parameter type.", "Function expects parameter of type 'String', got '" + param.GetType().Name + "'.", "")); } } else { sender.Interpreter.HandleException(Consts.Exceptions.ParameterCountMismatch(sender.Interpreter.CurrentFile, sender.Interpreter.CurrentLine, 1)); } }
private static bool String(FunctionArgs p_args) { if (p_args.Parameters.Length != 1) { errorMessage = "Invalid number of parameters in String function " + p_args.Parameters.Length; return(false); } object[] evalParams = p_args.EvaluateParameters(); p_args.HasResult = true; p_args.Result = evalParams[0].ToString(); return(true); }
/** * Create a Vector3 value */ private static bool Vector3(FunctionArgs p_args) { if (p_args.Parameters.Length != 3) { errorMessage = "Invalid parameters in Vector3 function."; return(false); } object[] evalParams = p_args.EvaluateParameters(); p_args.HasResult = true; p_args.Result = new Vector3(Convert.ToSingle(evalParams[0]), Convert.ToSingle(evalParams[1]), Convert.ToSingle(evalParams[2])); return(true); }
/** * Find child of transform */ private static bool GetChild(FunctionArgs p_args) { if (p_args.Parameters.Length != 2) { errorMessage = "Invalid parameters in GetChild function."; return(false); } object[] evalParams = p_args.EvaluateParameters(); if (typeof(Transform).IsAssignableFrom(evalParams[0].GetType()) && evalParams[1].GetType() == typeof(string)) { p_args.HasResult = true; p_args.Result = ((Transform)evalParams[0]).Find(evalParams[1].ToString()); return(true); } errorMessage = "Invalid parameters in GetChild function."; return(false); }
/** * Get index of transform child */ private static bool GetSiblingIndex(FunctionArgs p_args) { if (p_args.Parameters.Length != 1) { errorMessage = "Invalid parameters in GetChildIndex function."; return(false); } object[] evalParams = p_args.EvaluateParameters(); if (typeof(Transform).IsAssignableFrom(evalParams[0].GetType())) { p_args.HasResult = true; p_args.Result = ((Transform)evalParams[0]).GetSiblingIndex(); return(true); } errorMessage = "Invalid parameters in GetChildIndex function."; return(false); }
public static void Exists(LanguageInterpreter sender, FunctionArgs args) { if (EUtils.CheckArgs(1, args)) { object param = args.EvaluateParameters()[0]; if (EUtils.CheckArgType(param, typeof(string))) { args.HasResult = true; args.Result = File.Exists((string)param); } else { sender.Interpreter.HandleException(new Exception(sender.Interpreter.CurrentFile, sender.Interpreter.CurrentLine, "Invalid parameter type.", "Function expects parameter of type 'String', got '" + param.GetType().Name + "'.", "")); } } else { sender.Interpreter.HandleException(Consts.Exceptions.ParameterCountMismatch(sender.Interpreter.CurrentFile, sender.Interpreter.CurrentLine, 1)); } }
/** * Ceiling function for number types */ private static bool Ceil(FunctionArgs p_args) { object[] evalParams = p_args.EvaluateParameters(); if (evalParams.Length != 1) { errorMessage = "Invalid parameters in Ceil function."; return(false); } Type paramType = evalParams[0].GetType(); if (paramType == typeof(float) || paramType == typeof(double)) { p_args.HasResult = true; p_args.Result = Mathf.CeilToInt(Convert.ToSingle(evalParams[0])); return(true); } errorMessage = "Ceil function for type " + paramType + " is not implemented."; return(false); }
/** * Create a Color value */ private static bool Color(FunctionArgs p_args) { if (p_args.Parameters.Length != 4 && p_args.Parameters.Length != 3) { errorMessage = "Invalid parameters in Color function."; return(false); } object[] evalParams = p_args.EvaluateParameters(); p_args.HasResult = true; if (p_args.Parameters.Length == 3) { p_args.Result = new Color(Convert.ToSingle(evalParams[0]), Convert.ToSingle(evalParams[1]), Convert.ToSingle(evalParams[2])); } else { p_args.Result = new Color(Convert.ToSingle(evalParams[0]), Convert.ToSingle(evalParams[1]), Convert.ToSingle(evalParams[2]), Convert.ToSingle(evalParams[3])); } return(true); }
private static bool RandomV3(FunctionArgs p_args) { if (p_args.Parameters.Length != 0 && p_args.Parameters.Length != 2 && p_args.Parameters.Length != 6) { errorMessage = "Invalid parameters in RandomV3 function"; return(false); } object[] evalParams = p_args.EvaluateParameters(); switch (evalParams.Length) { case 0: p_args.HasResult = true; p_args.Result = new Vector3(UnityEngine.Random.Range(0, 1), UnityEngine.Random.Range(0, 1), UnityEngine.Random.Range(0, 1)); return(true); case 2: // TODO type checking? p_args.HasResult = true; p_args.Result = new Vector3( UnityEngine.Random.Range(Convert.ToSingle(evalParams[0]), Convert.ToSingle(evalParams[1])), UnityEngine.Random.Range(Convert.ToSingle(evalParams[0]), Convert.ToSingle(evalParams[1])), UnityEngine.Random.Range(Convert.ToSingle(evalParams[0]), Convert.ToSingle(evalParams[1]))); return(true); case 6: p_args.HasResult = true; p_args.Result = new Vector3( UnityEngine.Random.Range(Convert.ToSingle(evalParams[0]), Convert.ToSingle(evalParams[1])), UnityEngine.Random.Range(Convert.ToSingle(evalParams[2]), Convert.ToSingle(evalParams[3])), UnityEngine.Random.Range(Convert.ToSingle(evalParams[4]), Convert.ToSingle(evalParams[5]))); return(true); } errorMessage = "Unknown error in function RandomV3"; return(false); }
/** * Calculate Vector2 from one rect to another */ private static bool FromToRect(FunctionArgs p_args) { if (p_args.Parameters.Length != 2) { errorMessage = "Invalid parameters in FromToRect function."; return(false); } object[] evalParams = p_args.EvaluateParameters(); if (typeof(Transform).IsAssignableFrom(evalParams[0].GetType()) && typeof(Transform).IsAssignableFrom(evalParams[1].GetType())) { p_args.HasResult = true; RectTransform r1 = (RectTransform)evalParams[0]; RectTransform r2 = (RectTransform)evalParams[1]; p_args.Result = (Vector2)TransformUtils.FromToRectTransform(r1, r2); return(true); } errorMessage = "Invalid parameters in FromToRect function."; return(false); }
void json_stringify(LanguageInterpreter sender, FunctionArgs args) { if (EUtils.CheckArgs(1, args)) { object param = args.EvaluateParameters()[0]; if (EUtils.CheckArgType(param, typeof(AnonymousVariableArray))) { AnonymousVariableArray array = (AnonymousVariableArray)param; args.HasResult = true; args.Result = array.SerializeToJSON(); } else { sender.Interpreter.HandleException(new Exception(sender.Interpreter.CurrentFile, sender.Interpreter.CurrentLine, "Invalid parameter type.", "Function expects parameter of type 'AnonymousVariableArray', got '" + param.GetType().Name + "'.", "")); } } else { sender.Interpreter.HandleException(Consts.Exceptions.ParameterCountMismatch(sender.Interpreter.CurrentFile, sender.Interpreter.CurrentLine, 1)); } }
/** * ScreenToLocal function to conver screen space to local space */ private static bool ScreenToLocal(FunctionArgs p_args) { if (p_args.Parameters.Length != 2) { errorMessage = "Invalid parameters in ScreenToLocal function."; return(false); } object[] evalParams = p_args.EvaluateParameters(); if (evalParams[0].GetType() == typeof(RectTransform) && evalParams[1].GetType() == typeof(Vector2)) { Vector2 local; RectTransformUtility.ScreenPointToLocalPointInRectangle((RectTransform)evalParams[0], (Vector2)evalParams[1], Camera.main, out local); p_args.HasResult = true; p_args.Result = local; return(true); } errorMessage = "ScreenToLocal function for types " + evalParams[0].GetType() + ", " + evalParams[1].GetType() + " is not implemented."; return(false); }
private static bool RandomF(FunctionArgs p_args) { if (p_args.Parameters.Length != 0 && p_args.Parameters.Length != 2) { errorMessage = "Invalid parameters in RandomF function"; return(false); } object[] evalParams = p_args.EvaluateParameters(); p_args.HasResult = true; if (p_args.Parameters.Length == 0) { p_args.Result = UnityEngine.Random.Range(0f, 1f); } else { p_args.Result = UnityEngine.Random.Range(Convert.ToSingle(evalParams[0]), Convert.ToSingle(evalParams[1])); } return(true); }
private void Exp_EvaluateFunction(string name, FunctionArgs args) { string funcname = name.ToLower(); if (funcname == "tanh") { double d = 0d; double.TryParse(args.EvaluateParameters()[0].ToString(), out d); args.Result = Math.Tanh(d); } if (funcname == "sinh") { double.TryParse(args.EvaluateParameters()[0].ToString(), out double d); args.Result = Math.Sinh(d); } if (funcname == "cosh") { double.TryParse(args.EvaluateParameters()[0].ToString(), out double d); args.Result = Math.Cosh(d); } //if (funcname == "fib") //{ // long.TryParse(args.EvaluateParameters()[0].ToString(), out long a); // // args.Result = Fibonacci(a); //} if (funcname == "fac") { long.TryParse(args.EvaluateParameters()[0].ToString(), out long a); args.Result = Factorial(a); } if (funcname == "log" && args.EvaluateParameters().Length == 1) { double.TryParse(args.EvaluateParameters()[0].ToString(), out double d); args.Result = Math.Log(d); } if (funcname == "logfac") { long.TryParse(args.EvaluateParameters()[0].ToString(), out long a); args.Result = LogFactorial(a); } if (funcname == "hermite") { object[] arr = args.EvaluateParameters(); if (arr.Length == 5) { float.TryParse(arr[0].ToString(), out float val1); float.TryParse(arr[1].ToString(), out float tang1); float.TryParse(arr[2].ToString(), out float val2); float.TryParse(arr[3].ToString(), out float tang2); float.TryParse(arr[4].ToString(), out float amt); args.Result = Hermite(val1, tang1, val2, tang2, amt); } } }
/// <summary> /// extra custom functinos go in here. /// </summary> /// <param name="name"></param> /// <param name="args"></param> private void NCalcPulsarFunctions(string name, FunctionArgs args) { if (name == "Ability") { int index = 0; try { index = (int)args.Parameters[0].Evaluate(); ChainedExpression result = _design.ComponentDesignAbilities[index].Formula; if (result.Result == null) { result.Evaluate(); } MakeThisDependant(result); args.Result = result.Result; } catch (InvalidCastException e) { throw new Exception("Parameter must be an intiger. " + e); } catch (IndexOutOfRangeException e) { throw new Exception("This component does not have an ComponentAbilitySD at index " + index + ". " + e); } } if (name == "SetAbilityValue") //I might remove this.. { int index = 0; try { index = (int)args.Parameters[0].Evaluate(); ChainedExpression expression = _design.ComponentDesignAbilities[index].Formula; expression.SetResult = args.Parameters[1].Evaluate(); } catch (InvalidCastException e) { throw new Exception("Parameter must be an intiger. " + e); } catch (IndexOutOfRangeException e) { throw new Exception("This component does not have an ComponentAbilitySD at index " + index + ". " + e); } } if (name == "EnumDict") { string typeAsString = (string)args.Parameters[0].Evaluate(); Type type = Type.GetType(typeAsString); Type dictType = typeof(Dictionary <,>).MakeGenericType(type, typeof(double)); dynamic dict = Activator.CreateInstance(dictType); Type enumDictType = typeof(Dictionary <,>).MakeGenericType(typeof(string), type); dynamic enumConstants = Activator.CreateInstance(enumDictType); foreach (dynamic value in Enum.GetValues(type)) { enumConstants.Add(Enum.GetName(type, value), value); } foreach (var kvp in _designAbility.GuidDictionary) { dynamic key = enumConstants[(string)kvp.Key]; dict.Add(key, kvp.Value.DResult); } args.Result = dict; } if (name == "TechData") { Guid techGuid = Guid.Parse((string)args.EvaluateParameters()[0]); TechSD techSD = _staticDataStore.Techs[techGuid]; args.Result = TechProcessor.DataFormula(_factionTechDB, techSD); } //Returns the tech level for the given guid if (name == "TechLevel") { Guid techGuid = Guid.Parse((string)args.EvaluateParameters()[0]); if (_factionTechDB.ResearchedTechs.ContainsKey(techGuid)) { args.Result = _factionTechDB.ResearchedTechs[techGuid]; } else { args.Result = 0; } } //currently not used, but an future experiment to pass the CargoTypeSD as a parameter if (name == "CargoType") { Guid typeGuid = Guid.Parse((string)args.EvaluateParameters()[0]); CargoTypeSD typeSD = _staticDataStore.CargoTypes[typeGuid]; args.Result = typeSD; } //used for datablob args for when a guid is required as a parameter if (name == "GuidString") { Guid typeGuid = Guid.Parse((string)args.EvaluateParameters()[0]); args.Result = typeGuid; } //This sets the DatablobArgs. it's up to the user to ensure the right number of args for a specific datablob //The datablob will be the one defined in designAbility.DataBlobType //TODO document blobs and what args they take!! if (name == "DataBlobArgs") { if (_designAbility.DataBlobType == null) { throw new Exception("This Ability does not have a DataBlob defined! define a datablob for this ability!"); } //_designAbility.DataBlobArgs = new List<double>(); List <object> argList = new List <object>(); foreach (var argParam in args.Parameters) { ChainedExpression argExpression = new ChainedExpression(argParam, _designAbility, _factionTechDB, _staticDataStore); _isDependant = false; argExpression.Evaluate(); argList.Add(argExpression.Result); } _designAbility.DataBlobArgs = argList.ToArray(); args.Result = argList; } }
void EvaluateFunction(object target, string name, FunctionArgs args, Dictionary <string, object> extras, bool caseSensitive) { if (!caseSensitive) { name = name.ToLowerInvariant(); } // If a dotted name then do a slow evaluation, for functions we can only have a list of properties then a function call if (!_funcs.ContainsKey(name) && name.Contains(".")) { string[] parts = name.Split('.'); object ret = EvaluateParameter(target, parts[0], extras, caseSensitive); for (int i = 1; i < parts.Length - 1; ++i) { ret = GetValue(ret, parts[i], caseSensitive); } object[] oa = args.EvaluateParameters(); Type type = ret as Type; if ((type != null) && typeof(PySnippet).IsAssignableFrom(type)) { PySnippet snippet = (PySnippet)Activator.CreateInstance(type); _funcs.Add(name, (o, a) => snippet.Invoke(o, parts[parts.Length - 1], a)); args.Result = _funcs[name](target, oa); } else { ret = ret.GetType(); Type[] ta = new Type[oa.Length]; for (int i = 0; i < oa.Length; ++i) { ta[i] = oa[i].GetType(); } MethodInfo method = null; try { method = type.GetMethod(parts[parts.Length - 1], GetFlags(caseSensitive), null, ta, null); } catch (AmbiguousMatchException) { } if (method == null) { throw new ArgumentException(String.Format(Properties.Resources.ExpressionResolver_CannotFuncFunction, name)); } args.Result = method.Invoke(ret, oa); } } else { if (!_funcs.ContainsKey(name)) { if (_targetType == null) { throw new ArgumentException(String.Format(Properties.Resources.ExpressionResolver_CannotFuncFunction, name)); } Type baseType = _targetType; MethodInfo method = baseType.GetMethod(name, GetFlags(caseSensitive)); if (method == null) { // Not a method, try a type name which we expect to be a script Type type = baseType.Assembly.GetType(name); if ((type == null) || !typeof(PySnippet).IsAssignableFrom(type)) { throw new ArgumentException(String.Format(Properties.Resources.ExpressionResolver_CannotFuncFunction, name)); } PySnippet snippet = (PySnippet)Activator.CreateInstance(type); _funcs.Add(name, (o, a) => snippet.Invoke(o, null, a)); } else { _funcs.Add(name, (o, a) => method.Invoke(o, a)); } } args.Result = _funcs[name](target, args.EvaluateParameters()); } }
/// <summary> /// extra custom functinos go in here. /// </summary> /// <param name="name"></param> /// <param name="args"></param> private void NCalcPulsarFunctions(string name, FunctionArgs args) { string key = "Unknown Key"; int index = -1; Guid techGuid; Guid typeGuid; switch (name) { case "Ability": try { //TODO: get rid of this once json data is rewritten to use names instead of indexes if (args.Parameters[0].Evaluate() is int) { index = (int)args.Parameters[0].Evaluate(); ChainedExpression result = _designer.ComponentDesignAttributeList[index].Formula; if (result.Result == null) { result.Evaluate(); } MakeThisDependant(result); args.Result = result.Result; } else { key = (string)args.Parameters[0].Evaluate(); ChainedExpression result = _designer.ComponentDesignAttributes[key].Formula; if (result.Result == null) { result.Evaluate(); } MakeThisDependant(result); args.Result = result.Result; } } //TODO: maybe log this catch and throw the component out. (instead of throwing) catch (KeyNotFoundException e) { throw new Exception("Cannot find an ability named " + key + ", in " + _designer.Name + " " + e); } //TODO: the two catches below will be unnesiary once ComponentDesignAttributeList is gone. catch (InvalidCastException e) { throw new Exception("Parameter must be an intiger. " + e); } catch (IndexOutOfRangeException e) { throw new Exception("This component does not have an ComponentAbilitySD at index " + index + ". " + e); } break; case "SetAbilityValue": //I might remove this.. try { //TODO: get rid of this once json data is rewritten to use names instead of indexes if (args.Parameters[0].Evaluate() is int) { index = (int)args.Parameters[0].Evaluate(); ChainedExpression expression = _designer.ComponentDesignAttributeList[index].Formula; expression.SetResult = args.Parameters[1].Evaluate(); } else { key = (string)args.Parameters[0].Evaluate(); ChainedExpression expression = _designer.ComponentDesignAttributes[key].Formula; expression.SetResult = args.Parameters[1].Evaluate(); } } //TODO: maybe log this catch and throw the component out. (instead of throwing) catch (KeyNotFoundException e) { throw new Exception("Cannot find an ability named " + key + ". " + e); } //TODO: the two catches below will be unnesiary once ComponentDesignAttributeList is gone. catch (InvalidCastException e) { throw new Exception("Parameter must be an intiger. " + e); } catch (IndexOutOfRangeException e) { throw new Exception("This component does not have an ComponentAbilitySD at index " + index + ". " + e); } break; case "EnumDict": string typeAsString = (string)args.Parameters[0].Evaluate(); Type type = Type.GetType(typeAsString); if (type == null) { throw new Exception("Type not found: " + typeAsString + " Check spelling and namespaces"); } Type dictType = typeof(Dictionary <,>).MakeGenericType(type, typeof(double)); dynamic dict = Activator.CreateInstance(dictType); Type enumDictType = typeof(Dictionary <,>).MakeGenericType(typeof(string), type); dynamic enumConstants = Activator.CreateInstance(enumDictType); foreach (dynamic value in Enum.GetValues(type)) { enumConstants.Add(Enum.GetName(type, value), value); } foreach (var kvp in _designAttribute.GuidDictionary) { dynamic keyd = enumConstants[(string)kvp.Key]; dict.Add(keyd, kvp.Value.DResult); } args.Result = dict; break; case "TechData": techGuid = Guid.Parse((string)args.EvaluateParameters()[0]); TechSD techSD = _staticDataStore.Techs[techGuid]; args.Result = ResearchProcessor.DataFormula(_factionTechDB, techSD); break; //Returns the tech level for the given guid case "TechLevel": techGuid = Guid.Parse((string)args.EvaluateParameters()[0]); if (_factionTechDB.ResearchedTechs.ContainsKey(techGuid)) { args.Result = _factionTechDB.ResearchedTechs[techGuid]; } else { args.Result = 0; } break; //currently not used, but an future experiment to pass the CargoTypeSD as a parameter case "CargoType": typeGuid = Guid.Parse((string)args.EvaluateParameters()[0]); CargoTypeSD typeSD = _staticDataStore.CargoTypes[typeGuid]; args.Result = typeSD; break; //used for datablob args for when a guid is required as a parameter case "GuidString": typeGuid = Guid.Parse((string)args.EvaluateParameters()[0]); args.Result = typeGuid; break; //This sets the DatablobArgs. it's up to the user to ensure the right number of args for a specific datablob //The datablob will be the one defined in designAbility.AttributeType //TODO document blobs and what args they take!! case "AtbConstrArgs": if (_designAttribute.AttributeType == null) { throw new Exception(_designAttribute.Name + " does not have a type defined! define an AttributeType for this Attribute!"); } //_designAbility.AtbConstrArgs = new List<double>(); List <object> argList = new List <object>(); foreach (var argParam in args.Parameters) { ChainedExpression argExpression = new ChainedExpression(argParam, _designAttribute, _factionTechDB, _staticDataStore); _isDependant = false; argExpression.Evaluate(); argList.Add(argExpression.Result); } _designAttribute.AtbConstrArgs = argList.ToArray(); args.Result = argList; break; } }