Search Unity

Formula Parser

Discussion in 'Assets and Asset Store' started by subchannel13, Mar 29, 2022.

  1. subchannel13

    subchannel13

    Joined:
    Mar 22, 2015
    Posts:
    5
    Hi all!

    I've made an expression parsing asset that can convert raw strings into func<T, doule> delegates. For example:

    3.5 * x * 1.2 ^ y
    parses into
    3.5 * x * Math.Pow(1.2, y)


    What sets this parser apart from similar assets in the store its focus on game math:
    1) The syntax is geared toward expressions one would encounter in the game logic.
    2) Arbitrary variable names and an easy way to bind them with C# object properties.
    3) High evaluation performance.

    Examples of syntax:

    "10 ^ -x" - exponentiation as a simple operator
    "i [0.5, 1, 2, 3]" - lookup table syntax
    "case(lowG, normalG, highG) [0.25, 1, 0.5]" - reverse lookup function
    "10 * 1.5 ? boost" - conditional operands (*1.5 is applied if "boost" is true)

    Examples of a usage:

    Code (CSharp):
    1. var formula = "3 + 5 ? autoMine + 7 ? tech.Replicators";
    2.  
    3. func<GameVariables, double> prodFormula = new ExpressionParser().
    4.    Parse(formula).
    5.    Resolve(new GameVariables());
    6.  
    7. ...
    8.  
    9. var vars = new GameVariables
    10. {
    11.    Techs = colony.Owner.Techs,
    12.    Buildings = colony.Buildings
    13. }
    14.  
    15. double production = prodFormula(vars);
    The parser is a rewrite of a moddability code used in the Dominus Galaxia and Stareater, both 4X strategy games on par with the Civilization series in terms of game mechanics complexity. So the asset has a lot of benefits of hindsight when it comes to scaling up game math moddability. This is especially true with variable handling which is usually not part of the expression parsing package and can become a performance bottleneck if not handled properly. This asset comes with the tools for making a performant and easy-to-use variable handler.

    If you have any questions or suggestions, feel free to ask!