Skip to content

G

Source code in core/nodeclass.py
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
class G:

    def __init__(self, prefix: str = ""):
        """ Group functional call

        This class is provided to expose ***Group*** nodes as functions with keyword arguments.
        When a Group named "Do Something" is created, it can be called with two syntaxes:
        - Using `Group` node: `node = Group("Do Something", ...)`
        - Using `G` function with the snake case name : `node = G().do_someting(...)`

        This facility can be particularilty usedful for projects with a lot of groups. The groups
        can be grouped by prefixes. The prefixes are hidden in the code.


        ``` python

        from geonodes import GeoNodes, Geometry, Float, Mesh, G

        with GeoNodes("Do Something", is_group=True, prefix="Utils"):

            g = Geometry()
            a = Float(3.14, "Pi")
            b = Float(6.28, "Tau")
            g += Mesh.Cube()

            g = Mesh(g)
            g.points.Pi = a + b

            g.out()

            a.out("Pi")

        with GeoNodes("Do Something Else", is_group=True, prefix="Utils"):

            g = Geometry()
            a = Float(3.14, "Pi")
            b = Float(6.28, "Tau")
            g += Mesh.Cube()

            g = Mesh(g)
            g.points.Pi = a + b

            g.out()

        with GeoNodes("Calling Groups"):

            utils = G("Utils")

            g = utils.do_something(Geometry(), pi=6.28)
            g = utils.do_something_else(g, g.pi, tau=7)
            g.out()   
        ```

        Parameters
        ----------
        prefix
            prefix to use when searching a tree

        """
        if prefix is None:
            self.prefix = ""
        else:
            self.prefix = str(prefix)
            if len(self.prefix):
                self.prefix += " "
        self.functions = {}

    # ====================================================================================================
    # Str returns a string to be compatible with prefix argument in Tree initialization

    def __str__(self):
        if self.prefix == "":
            return ""
        else:
            return self.prefix[:-1]

    # ====================================================================================================
    # Build a function from a node
    # ====================================================================================================

    def build_function(self, btree):
        """ Dynamically create a function to call the tree as Group

        The name of the function is the snake case version of the tree name.

        Parameters
        ----------
        btree : Blender GeometryNodeTree | ShaderNodeTree
            the tree

        Returns
        -------
        None
        """

        func_name = utils.snake_case(btree.name)
        if func_name in self.functions:
            return self.functions[func_name]['f']

        # ---------------------------------------------------------------------------
        # Calling the node
        # ---------------------------------------------------------------------------

        def f(*args, **kwargs):
            node = Group(btree.name)
            return node.method_call(*args, **kwargs)

        # ---------------------------------------------------------------------------
        # Adding the function
        # ---------------------------------------------------------------------------

        self.functions[func_name] = {'f': f, 'source': ""}

        return f

    # ====================================================================================================
    # Source code
    # ====================================================================================================

    def error(self, f, exception=None):
        """ Raise an error when function call fails.

        Raises
        ------
        - NodeError

        Parameters
        ----------
        f : function
            the function in error

        exception : Exception
            the exception that was raised

        """

        spec = self.functions.get(f.__name__)
        if spec is None:
            source = f"No source code found for function: {f.__name__}. Existing functions are {list(self.functions.keys())}."
        else:
            source = spec['source']

        se = "No exception " if exception is None else str(exception)

        raise NodeError(f"Error when calling function '{f.__name__}' of group {self}.\n\n"
                        f"Signature is:\n\n{source}\n",
                        error_message = se)


    # ====================================================================================================
    # Get a tree by its snake case name

    def __getattr__(self, name):

        if name in {"__dict__", "__weakref__"}:
            raise AttributeError(name)

        tree_type = Tree.current_tree()._btree.bl_idname
        groups = utils.get_available_groups(tree_type)

        target = utils.snake_case(self.prefix + name)
        group_name = utils.find_snake_case_name(target, list(groups.keys()))
        if group_name is None:
            raise AttributeError(f"Group '{self.prefix + name}' not found")

        group = blender.load_node_group(groups[group_name])

        return self.build_function(group)


    @staticmethod
    def _class_test():

        from geonodes import GeoNodes, Geometry, Float, Mesh, G

        with GeoNodes("Do Something", is_group=True, prefix="Utils"):

            g = Geometry()
            a = Float(3.14, "Pi")
            b = Float(6.28, "Tau")
            g += Mesh.Cube()

            g = Mesh(g)
            g.points.Pi = a + b

            g.out()

            a.out("Pi")

        with GeoNodes("Do Something Else", is_group=True, prefix="Utils"):

            g = Geometry()
            a = Float(3.14, "Pi")
            b = Float(6.28, "Tau")
            g += Mesh.Cube()

            g = Mesh(g)
            g.points.Pi = a + b

            g.out()

        with GeoNodes("Calling Groups"):

            utils = G("Utils")

            g = utils.do_something(Geometry(), pi=6.28)
            g = utils.do_something_else(g, g.pi, tau=7)
            g.out()  

__init__(prefix='')

Group functional call

This class is provided to expose Group nodes as functions with keyword arguments. When a Group named "Do Something" is created, it can be called with two syntaxes: - Using Group node: node = Group("Do Something", ...) - Using G function with the snake case name : node = G().do_someting(...)

This facility can be particularilty usedful for projects with a lot of groups. The groups can be grouped by prefixes. The prefixes are hidden in the code.

from geonodes import GeoNodes, Geometry, Float, Mesh, G

with GeoNodes("Do Something", is_group=True, prefix="Utils"):

    g = Geometry()
    a = Float(3.14, "Pi")
    b = Float(6.28, "Tau")
    g += Mesh.Cube()

    g = Mesh(g)
    g.points.Pi = a + b

    g.out()

    a.out("Pi")

with GeoNodes("Do Something Else", is_group=True, prefix="Utils"):

    g = Geometry()
    a = Float(3.14, "Pi")
    b = Float(6.28, "Tau")
    g += Mesh.Cube()

    g = Mesh(g)
    g.points.Pi = a + b

    g.out()

with GeoNodes("Calling Groups"):

    utils = G("Utils")

    g = utils.do_something(Geometry(), pi=6.28)
    g = utils.do_something_else(g, g.pi, tau=7)
    g.out()   

Parameters:

Name Type Description Default
prefix str

prefix to use when searching a tree

''
Source code in core/nodeclass.py
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
def __init__(self, prefix: str = ""):
    """ Group functional call

    This class is provided to expose ***Group*** nodes as functions with keyword arguments.
    When a Group named "Do Something" is created, it can be called with two syntaxes:
    - Using `Group` node: `node = Group("Do Something", ...)`
    - Using `G` function with the snake case name : `node = G().do_someting(...)`

    This facility can be particularilty usedful for projects with a lot of groups. The groups
    can be grouped by prefixes. The prefixes are hidden in the code.


    ``` python

    from geonodes import GeoNodes, Geometry, Float, Mesh, G

    with GeoNodes("Do Something", is_group=True, prefix="Utils"):

        g = Geometry()
        a = Float(3.14, "Pi")
        b = Float(6.28, "Tau")
        g += Mesh.Cube()

        g = Mesh(g)
        g.points.Pi = a + b

        g.out()

        a.out("Pi")

    with GeoNodes("Do Something Else", is_group=True, prefix="Utils"):

        g = Geometry()
        a = Float(3.14, "Pi")
        b = Float(6.28, "Tau")
        g += Mesh.Cube()

        g = Mesh(g)
        g.points.Pi = a + b

        g.out()

    with GeoNodes("Calling Groups"):

        utils = G("Utils")

        g = utils.do_something(Geometry(), pi=6.28)
        g = utils.do_something_else(g, g.pi, tau=7)
        g.out()   
    ```

    Parameters
    ----------
    prefix
        prefix to use when searching a tree

    """
    if prefix is None:
        self.prefix = ""
    else:
        self.prefix = str(prefix)
        if len(self.prefix):
            self.prefix += " "
    self.functions = {}

build_function(btree)

Dynamically create a function to call the tree as Group

The name of the function is the snake case version of the tree name.

Parameters:

Name Type Description Default
btree Blender GeometryNodeTree | ShaderNodeTree

the tree

required

Returns:

Type Description
None
Source code in core/nodeclass.py
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
def build_function(self, btree):
    """ Dynamically create a function to call the tree as Group

    The name of the function is the snake case version of the tree name.

    Parameters
    ----------
    btree : Blender GeometryNodeTree | ShaderNodeTree
        the tree

    Returns
    -------
    None
    """

    func_name = utils.snake_case(btree.name)
    if func_name in self.functions:
        return self.functions[func_name]['f']

    # ---------------------------------------------------------------------------
    # Calling the node
    # ---------------------------------------------------------------------------

    def f(*args, **kwargs):
        node = Group(btree.name)
        return node.method_call(*args, **kwargs)

    # ---------------------------------------------------------------------------
    # Adding the function
    # ---------------------------------------------------------------------------

    self.functions[func_name] = {'f': f, 'source': ""}

    return f

error(f, exception=None)

Raise an error when function call fails.

Raises:

Type Description
-NodeError

Parameters:

Name Type Description Default
f function

the function in error

required
exception Exception

the exception that was raised

None
Source code in core/nodeclass.py
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
def error(self, f, exception=None):
    """ Raise an error when function call fails.

    Raises
    ------
    - NodeError

    Parameters
    ----------
    f : function
        the function in error

    exception : Exception
        the exception that was raised

    """

    spec = self.functions.get(f.__name__)
    if spec is None:
        source = f"No source code found for function: {f.__name__}. Existing functions are {list(self.functions.keys())}."
    else:
        source = spec['source']

    se = "No exception " if exception is None else str(exception)

    raise NodeError(f"Error when calling function '{f.__name__}' of group {self}.\n\n"
                    f"Signature is:\n\n{source}\n",
                    error_message = se)