[Bf-blender-cvs] SVN commit: /data/svn/bf-blender [56012] trunk/blender: Replacing the node Add menu and making the toolbar useful

Lukas Toenne lukas.toenne at googlemail.com
Sat Apr 13 17:38:03 CEST 2013


Revision: 56012
          http://projects.blender.org/scm/viewvc.php?view=rev&root=bf-blender&revision=56012
Author:   lukastoenne
Date:     2013-04-13 15:38:02 +0000 (Sat, 13 Apr 2013)
Log Message:
-----------
Replacing the node Add menu and making the toolbar useful

As some people have already noticed, the "Add" menu for nodes is a bit messy since pynodes merge. The reason for this is that the order of nodes in submenus (categories) was previously defined by the order in which all nodes are registered (at the bottom of blenkernel/intern/node.c). For the dynamic registration of node types now possible this system of defining node order along with registration is no longer viable: while it would still sort of work for C nodes, it is completely meaningless for dynamic (python) nodes, which are basically registered automatically in whatever order modules and addons are loaded, with the added complexity of unloading and reloading.

To fix this problem and add a bunch of desirable features this commit replaces the C menu with a python implementation. The new menu does not rely on any particular order of types in the node registry, but instead uses a simple explicit list of all the available nodes, grouped by categories (in scripts/nodeitems_builtins.py).

There are a number of additional features that become possible with this implementation:

1) Node Toolbar can be populated!
The list of nodes is used to create 2 UI items for each node: 1 entry in a submenu of "Add" menu and 1 item in a node toolbar panel with basically the same functionality. Clicking a button in the toolbar will add a new node of this type, just like selecting an item in the menu. The toolbar has the advantage of having collapsible panels for each category, so users can decide if they don't need certain nodes categories and have the rest more easily accessible.

2) Each node item is a true operator call.
The old Add menu is a pretty old piece of C code which doesn't even use proper operator buttons. Now there is a generic node_add operator which can be used very flexibly for adding any of the available nodes.

3) Node Items support additional settings.
Each "NodeItem" consists of the basic node type plus an optional list of initial settings that shall be applied to a new instance. This gives additional flexibility for creating variants of the same node or for defining preferred initial settings. E.g. it has been requested to disable previews for all nodes except inputs, this would be simple change in the py code and much less intrusive than in C.

4) Node items can be generated with a function.
A callback can be used in any category instead of the fixed list, which generates a set of items based on the context (much like dynamic enum items in bpy.props). Originally this was implemented for group nodes, because these nodes only make sense when linked to a node tree from the library data. This principle could come in handy for a number of other nodes, e.g. Image nodes could provide a similar list of node variants based on images in the library - no need to first add node, then select an image.

WARNING: pynodes scripters will have to rework their "draw_add_menu" callback in node tree types, this has been removed now! It was already pretty redundant, since one can add draw functions to the Add menu just like for any other menu. In the future i'd like to improve the categories system further so scripters can use it for custom node systems too, for now just make a draw callback and attach it to the Add menu.

Modified Paths:
--------------
    trunk/blender/release/scripts/startup/bl_operators/node.py
    trunk/blender/source/blender/blenkernel/BKE_node.h
    trunk/blender/source/blender/editors/space_node/CMakeLists.txt
    trunk/blender/source/blender/editors/space_node/drawnode.c
    trunk/blender/source/blender/editors/space_node/node_intern.h
    trunk/blender/source/blender/editors/space_node/space_node.c
    trunk/blender/source/blender/makesrna/intern/rna_nodetree.c

Added Paths:
-----------
    trunk/blender/release/scripts/modules/nodeitems_utils.py
    trunk/blender/release/scripts/startup/nodeitems_builtins.py

Removed Paths:
-------------
    trunk/blender/source/blender/editors/space_node/node_header.c

Added: trunk/blender/release/scripts/modules/nodeitems_utils.py
===================================================================
--- trunk/blender/release/scripts/modules/nodeitems_utils.py	                        (rev 0)
+++ trunk/blender/release/scripts/modules/nodeitems_utils.py	2013-04-13 15:38:02 UTC (rev 56012)
@@ -0,0 +1,123 @@
+# ##### BEGIN GPL LICENSE BLOCK #####
+#
+#  This program is free software; you can redistribute it and/or
+#  modify it under the terms of the GNU General Public License
+#  as published by the Free Software Foundation; either version 2
+#  of the License, or (at your option) any later version.
+#
+#  This program is distributed in the hope that it will be useful,
+#  but WITHOUT ANY WARRANTY; without even the implied warranty of
+#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+#  GNU General Public License for more details.
+#
+#  You should have received a copy of the GNU General Public License
+#  along with this program; if not, write to the Free Software Foundation,
+#  Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+#
+# ##### END GPL LICENSE BLOCK #####
+
+# <pep8 compliant>
+import bpy
+from bpy.types import Menu, Panel
+
+
+node_categories = []
+
+
+class NodeCategory():
+    @classmethod
+    def poll(cls, context):
+        return True
+
+    @property
+    def items(self):
+        if hasattr(self, '_items'):
+            return self._items
+        elif hasattr(self, '_itemfunc'):
+            return self._itemfunc(self)
+
+    def __init__(self, identifier, name, description="", items=[]):
+        self.identifier = identifier
+        self.name = name
+        self.description = description
+        if callable(items):
+            self._itemfunc = items
+        else:
+            self._items = items
+
+class NodeItem():
+    def __init__(self, nodetype, label=None, settings={}):
+        self.nodetype = nodetype
+        self._label = label
+        self.settings = settings
+
+    @property
+    def label(self):
+        if self._label:
+            return self._label
+        else:
+            # if no custom label is defined, fall back to the node type UI name
+            return getattr(bpy.types, self.nodetype).bl_rna.name
+
+
+# Empty base class to detect subclasses in bpy.types
+class NodeCategoryUI():
+    pass
+
+
+def register_node_ui():
+    # works as draw function for both menus and panels
+    def draw_node_item(self, context):
+        layout = self.layout
+        for item in self.category.items:
+            op = layout.operator("node.add_node", text=item.label)
+            op.type = item.nodetype
+            op.use_transform = True
+
+            for setting in item.settings.items():
+                ops = op.settings.add()
+                ops.name = setting[0]
+                ops.value = setting[1]
+
+    for cat in node_categories:
+        menu = type("NODE_MT_category_"+cat.identifier, (bpy.types.Menu, NodeCategoryUI), {
+            "bl_space_type" : 'NODE_EDITOR',
+            "bl_label" : cat.name,
+            "category" : cat,
+            "poll" : cat.poll,
+            "draw" : draw_node_item,
+            })
+        panel = type("NODE_PT_category_"+cat.identifier, (bpy.types.Panel, NodeCategoryUI), {
+            "bl_space_type" : 'NODE_EDITOR',
+            "bl_region_type" : 'TOOLS',
+            "bl_label" : cat.name,
+            "category" : cat,
+            "poll" : cat.poll,
+            "draw" : draw_node_item,
+            })
+        bpy.utils.register_class(menu)
+        bpy.utils.register_class(panel)
+
+
+    def draw_add_menu(self, context):
+        layout = self.layout
+
+        for cat in node_categories:
+            if cat.poll(context):
+                layout.menu("NODE_MT_category_%s" % cat.identifier)
+
+    add_menu = type("NODE_MT_add", (bpy.types.Menu, NodeCategoryUI), {
+        "bl_space_type" : 'NODE_EDITOR',
+        "bl_label" : "Add",
+        "draw" : draw_add_menu,
+        })
+    bpy.utils.register_class(add_menu)
+
+
+def unregister_node_ui():
+    # unregister existing UI classes
+    for c in NodeCategoryUI.__subclasses__():
+        if hasattr(c, "bl_rna"):
+            bpy.utils.unregister_class(c)
+            del c
+

Modified: trunk/blender/release/scripts/startup/bl_operators/node.py
===================================================================
--- trunk/blender/release/scripts/startup/bl_operators/node.py	2013-04-13 15:14:34 UTC (rev 56011)
+++ trunk/blender/release/scripts/startup/bl_operators/node.py	2013-04-13 15:38:02 UTC (rev 56012)
@@ -19,8 +19,8 @@
 # <pep8-80 compliant>
 
 import bpy
-from bpy.types import Operator
-from bpy.props import BoolProperty, EnumProperty, StringProperty
+from bpy.types import Operator, PropertyGroup
+from bpy.props import BoolProperty, CollectionProperty, EnumProperty, StringProperty
 
 
 # Base class for node 'Add' operators
@@ -68,6 +68,13 @@
         return self.execute(context)
 
 
+class NodeSetting(PropertyGroup):
+    value = StringProperty(
+            name="Value",
+            description="Python expression to be evaluated as the initial node setting",
+            default="",
+            )
+
 # Simple basic operator for adding a node
 class NODE_OT_add_node(NodeAddOperator, Operator):
     '''Add a node to the active tree'''
@@ -78,35 +85,43 @@
             name="Node Type",
             description="Node type",
             )
-    # optional group tree parameter for group nodes
-    group_tree = StringProperty(
-            name="Group tree",
-            description="Group node tree name",
-            )
     use_transform = BoolProperty(
             name="Use Transform",
             description="Start transform operator after inserting the node",
             default=False,
             )
+    settings = CollectionProperty(
+            name="Settings",
+            description="Settings to be applied on the newly created node",
+            type=NodeSetting,
+            )
 
     def execute(self, context):
         node = self.create_node(context, self.type)
 
-        # set the node group tree of a group node
-        if self.properties.is_property_set('group_tree'):
-            node.node_tree = bpy.data.node_groups[self.group_tree]
+        for setting in self.settings:
+            # XXX catch exceptions here?
+            value = eval(setting.value)
+                
+            try:
+                setattr(node, setting.name, value)
+            except AttributeError as e:
+                self.report({'ERROR_INVALID_INPUT'}, "Node has no attribute "+setting.name)
+                print (str(e))
+                # Continue despite invalid attribute
 
         return {'FINISHED'}
 
     def invoke(self, context, event):
         self.store_mouse_cursor(context, event)
         result = self.execute(context)
+
         if self.use_transform and ('FINISHED' in result):
-            return bpy.ops.transform.translate('INVOKE_DEFAULT')
-        else:
-            return result
+            bpy.ops.transform.translate('INVOKE_DEFAULT')
 
+        return result
 
+
 def node_classes_iter(base=bpy.types.Node):
     """
     Yields all true node classes by checking for the is_registered_node_type classmethod.
@@ -186,19 +201,6 @@
         return {'CANCELLED'}
 
 
-# Simple basic operator for adding a node without further initialization
-class NODE_OT_add_node(NodeAddOperator, bpy.types.Operator):
-    '''Add a node to the active tree'''
-    bl_idname = "node.add_node"
-    bl_label = "Add Node"
-
-    type = StringProperty(name="Node Type", description="Node type")
-
-    def execute(self, context):
-        node = self.create_node(context, self.type)
-        return {'FINISHED'}
-
-
 class NODE_OT_add_group_node(NodeAddOperator, bpy.types.Operator):
     '''Add a group node to the active tree'''
     bl_idname = "node.add_group_node"

Added: trunk/blender/release/scripts/startup/nodeitems_builtins.py
===================================================================
--- trunk/blender/release/scripts/startup/nodeitems_builtins.py	                        (rev 0)
+++ trunk/blender/release/scripts/startup/nodeitems_builtins.py	2013-04-13 15:38:02 UTC (rev 56012)
@@ -0,0 +1,356 @@
+# ##### BEGIN GPL LICENSE BLOCK #####
+#
+#  This program is free software; you can redistribute it and/or
+#  modify it under the terms of the GNU General Public License
+#  as published by the Free Software Foundation; either version 2
+#  of the License, or (at your option) any later version.
+#
+#  This program is distributed in the hope that it will be useful,
+#  but WITHOUT ANY WARRANTY; without even the implied warranty of
+#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+#  GNU General Public License for more details.
+#
+#  You should have received a copy of the GNU General Public License
+#  along with this program; if not, write to the Free Software Foundation,
+#  Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+#
+# ##### END GPL LICENSE BLOCK #####
+
+# <pep8 compliant>
+import bpy
+import nodeitems_utils
+from nodeitems_utils import NodeCategory, NodeItem
+
+
+# Subclasses for standard node types
+
+class CompositorNodeCategory(NodeCategory):
+    @classmethod
+    def poll(cls, context):
+        return context.space_data.tree_type == 'CompositorNodeTree'
+
+class ShaderNewNodeCategory(NodeCategory):
+    @classmethod
+    def poll(cls, context):
+        return context.space_data.tree_type == 'ShaderNodeTree' and \
+               context.scene.render.use_shading_nodes
+
+class ShaderOldNodeCategory(NodeCategory):
+    @classmethod
+    def poll(cls, context):
+        return context.space_data.tree_type == 'ShaderNodeTree' and \
+               not context.scene.render.use_shading_nodes
+
+class TextureNodeCategory(NodeCategory):
+    @classmethod
+    def poll(cls, context):
+        return context.space_data.tree_type == 'TextureNodeTree'
+
+
+def compositor_node_group_items(self):
+    return [NodeItem('CompositorNodeGroup', group.name, { "node_tree" : "bpy.data.node_groups['%s']" % group.name })
+            for group in bpy.data.node_groups if group.bl_idname == 'CompositorNodeTree']
+
+# Note: node groups not distinguished by old/new shader nodes
+def shader_node_group_items(self):
+    return [NodeItem('ShaderNodeGroup', group.name, { "node_tree" : "bpy.data.node_groups['%s']" % group.name })

@@ Diff output truncated at 10240 characters. @@



More information about the Bf-blender-cvs mailing list