Home  >  Article  >  Backend Development  >  Blender Python programming introduction example analysis

Blender Python programming introduction example analysis

王林
王林forward
2023-05-12 10:55:051801browse

    Blender Python Programming

    Supported Features:

    • Editing User Interface Yes Edit any data (scene, mesh, particles, etc.).

    • Modify user preferences, keymaps and themes.

    • Run the tool with your own settings.

    • Create user interface elements such as menus, headers, and panels.

    • Create new tools.

    • Create interactive tools.

    • Create a new rendering engine integrated with Blender.

    • Subscribe to changes to data and its properties.

    • Define new settings within existing Blender data.

    • Use Python to draw 3D views.

    (Still) Missing Features:

    • Create new space types.

    • Assign custom properties to each type.

    Data Access

    Python accesses Blender's data in the same way as the animation system and user interface. This means that any setting that can be changed via a button can also be changed from Python.

    Accessing data from the currently loaded Blender file can be accomplished using the module bpy.data . This provides access to library data. For example:

    >>> bpy.data.objects
    <bpy_collection[3], BlendDataObjects>
    >>> bpy.data.scenes
    <bpy_collection[1], BlendDataScenes>
    >>> bpy.data.materials
    <bpy_collection[1], BlendDataMaterials>

    Accessing Collections

    You will notice that both indexes and strings can be used to access the members of a collection. Unlike Python dictionaries, both methods are available; however, the index of a member may change when running Blender.

    list(bpy.data.objects)
    [bpy.data.objects["Cube"], bpy.data.objects["Plane"]]
    >>> bpy.data.objects[&#39;Cube&#39;]
    bpy.data.objects["Cube"]
    >>> bpy.data.objects[0]
    bpy.data.objects["Cube"]

    Accessing properties

    Once you have a block of data, such as a material, object, collection, etc., its properties can be accessed just like changing settings using the graphical interface. In fact, each button's tooltip also shows Python properties, which can help find which settings were changed in the script.

    bpy.data.objects[0].name
    &#39;Camera&#39;
    >>> bpy.data.scenes["Scene"]
    bpy.data.scenes[&#39;Scene&#39;]
    >>> bpy.data.materials.new("MyMaterial")
    bpy.data.materials[&#39;MyMaterial&#39;]

    For testing what data you want to access, it is useful to use the Python Console, which is its own spatial type. This supports auto-completion, giving you a quick way to explore the data in your files.

    Examples of data paths that can be quickly found through the console:

    bpy.data.scenes[0].render.resolution_percentage
    100
    >>> bpy.data.scenes[0].objects["Torus"].data.vertices[0].co.x
    1.0

    Data creation/deletion

    When you are familiar with other Python APIs, you may be surprised by the bpy API New data blocks cannot be created by calling the class:

    bpy.types.Mesh()
    Traceback (most recent call last):
      File "<blender_console>", line 1, in <module>
    TypeError: bpy_struct.__new__(type): expected a single argument

    Users cannot create new data anywhere outside the Blender database (the one accessed by bpy.data) because this data is created by Blender Management (save, load, undo, append, etc.).

    You can only use the following methods to add and delete data:

    mesh = bpy.data.meshes.new(name="MyMesh")
    >>> print(mesh)
    <bpy_struct, Mesh("MyMesh.001")>
    bpy.data.meshes.remove(mesh)

    Custom attributes

    Python can access attributes on any data block with ID . When assigning an attribute, if the attribute does not exist, it will be created.

    These properties are also saved in the Blender file and inherited or copied with the object.

    bpy.context.object["MyOwnProperty"] = 42
    if "SomeProp" in bpy.context.object:
        print("Property found")
    # Use the get function like a Python dictionary
    # which can have a fallback value.
    value = bpy.data.scenes["Scene"].get("test_prop", "fallback value")
    # dictionaries can be assigned as long as they only use basic types.
    collection = bpy.data.collections.new("MyTestCollection")
    collection["MySettings"] = {"foo": 10, "bar": "spam", "baz": {}}
    del collection["MySettings"]

    However, the values ​​of these custom properties must be basic Python data types. Such as:

    • int/float/string

    • int/ float Array

    • Dictionary (only string keys are supported, values ​​must also be basic types)

    Custom attributes are also valid outside Python. They can be animated via curves or used in drive paths.

    Context Context

    Being able to access data directly by name or list is very useful, but more commonly it is done based on user selection. This context information is always available from bpy.context.

    Common cases:

    >>> bpy.context.object
    >>> bpy.context.selected_objects
    >>> bpy.context.visible_bones

    Please note that the context is read-only. These values ​​cannot be modified directly, although they can be changed by running API functions or using the data API.

    So this will raise the error : bpy.context.object = obj

    But this will work fine: bpy.context. scene.objects.active = obj

    Operators (Tools)

    Operators are typically tools that users access from buttons, menu items, or shortcut keys. From the user's perspective, they are a tool, but Python can access, set up, and run them through the bpy.ops module.

    Example:

    bpy.ops.mesh.flip_normals()
    {&#39;FINISHED&#39;}
    >>> bpy.ops.mesh.hide(unselected=False)
    {&#39;FINISHED&#39;}
    >>> bpy.ops.object.transform_apply()
    {&#39;FINISHED&#39;}

    Operator Cheat Sheet gives a list of all operators in Python syntax and their default values, as well as the generated documentation. This is a great way to learn about all of Blender's operators.

    Operator Poll()

    Many Operators have their own Poll() method, which can check whether the current Blender context meets the conditions for the Operator to run. When not satisfied, calling the Operator directly will generate an error. Therefore, when operating an Operator, It is recommended that first check the context in the following way:

    if bpy.ops.view3d.render_border.poll():
        bpy.ops.view3d.render_border()

    How to integrate Python into Blender

    Python script Integration with Blender can be done in the following ways:

    • By defining a rendering engine.

    • By defining operators.

    • 通过定义菜单,标题和面板。

    • 通过将新按钮插入现有菜单,标题和面板

    在 Python 中,这是通过定义一个类来完成的,该类是现有类型的子类。

    Blender 官方文档中提供了实例的类模板。如:

    示例运算符

    import bpy
    def main(context):
        for ob in context.scene.objects:
            print(ob)
    class SimpleOperator(bpy.types.Operator):
        """Tooltip"""
        bl_idname = "object.simple_operator"
        bl_label = "Simple Object Operator"
        @classmethod
        def poll(cls, context):
            return context.active_object is not None
        def execute(self, context):
            main(context)
            return {&#39;FINISHED&#39;}
    def register():
        bpy.utils.register_class(SimpleOperator)
    def unregister():
        bpy.utils.unregister_class(SimpleOperator)
    if __name__ == "__main__":
        register()
    # test call
    bpy.ops.object.simple_operator()

    一旦这个脚本运行,SimpleOperator 在 Blender 中注册,可以从 Operator Search 中调用或添加到工具栏中。

    运行脚本:

    • 启动 Blender 并切换到脚本工作区。

    • 单击文本编辑器中的 New 按钮以创建新的文本数据块。

    • 从上面并将其粘贴到文本编辑器中。

    • 单击 Run Script 按钮。

    • 将光标移至 3D 视口,打开运算符搜索菜单,输入 “Simple”。

    • 点击搜索中找到的 “SimpleOperator” 项目。

    示例面板

    面板注册为一个类,就像操作符一样。请注意用于设置它们所显示的上下文的额外 bl_ 变量。

    import bpy
    class HelloWorldPanel(bpy.types.Panel):
        """Creates a Panel in the Object properties window"""
        bl_label = "Hello World Panel"
        bl_idname = "OBJECT_PT_hello"
        bl_space_type = &#39;PROPERTIES&#39;
        bl_region_type = &#39;WINDOW&#39;
        bl_context = "object"
        def draw(self, context):
            layout = self.layout
            obj = context.object
            row = layout.row()
            row.label(text="Hello world!", icon=&#39;WORLD_DATA&#39;)
            row = layout.row()
            row.label(text="Active object is: " + obj.name)
            row = layout.row()
            row.prop(obj, "name")
            row = layout.row()
            row.operator("mesh.primitive_cube_add")
    def register():
        bpy.utils.register_class(HelloWorldPanel)
    def unregister():
        bpy.utils.unregister_class(HelloWorldPanel)
    if __name__ == "__main__":
        register()

    运行脚本:

    • 启动 Blender 并切换到脚本工作区。

    • 单击文本编辑器中的 New 按钮以创建新的文本数据块。

    • 从上面并将其粘贴到文本编辑器中。

    • 单击 Run Script 按钮。

    要查看结果:

    • 选择默认立方体。

    • 点击按钮面板中的对象属性图标(最右边;出现为一个小立方体)。

    • 向下滚动查看名为 “Hello World Panel” 的面板。

    • 更改对象名称也会更新 Hello World Panel 的 name:字段。

    请注意通过代码定义的行分布以及标签和属性。

    数据类型

    Blender 定义了许多 Python 类型,但也使用 Python 本机类型。

    原生类型

    在简单的情况下,将数字或字符串作为自定义类型会很麻烦,因此可以将它们作为普通的 Python 类型进行访问。

    • Blender float / int / boolean-> float / int / boolean

    • Blender 枚举器->字符串

    >>> C.object.rotation_mode = &#39;AXIS_ANGLE&#39;
    • Blender枚举器(多个)->字符串集

    # setting multiple camera overlay guides
    bpy.context.scene.camera.data.show_guide = {&#39;GOLDEN&#39;, &#39;CENTER&#39;}
    # passing as an operator argument for report types
    self.report({&#39;WARNING&#39;, &#39;INFO&#39;}, "Some message!")

    内部类型

    用于 Blender 数据块和 Blender 集合: bpy.types.bpy_struct

    用于包含 collections/meshes/bones/scenes 等属性的数据。

    包装 Blenders 数据的主要类型有 2 种,

    • 一种用于数据块(内部称为 bpy_struct

    >>> bpy.context.object
    bpy.data.objects[&#39;Cube&#39;]
    • 另一种用于属性。

    >>> C.scene.objects
    bpy.data.scenes[&#39;Scene&#39;].objects

    Mathutils 类型

    用于表示向量,四元数,euler,矩阵和颜色类型等,可从 mathutils 模块访问它们。

    一些属性,如 bpy.types.Object.location, bpy.types.PoseBone.rotation_eulerbpy.types.Scene.Cursor_location 可以作为特殊的数学类型访问,这些类型可以一起使用并以各种有用的方式进行操作。

    例如,矩阵向量的乘法

    bpy.context.object.matrix_world @ bpy.context.object.data.verts[0].co

    注意:mathutils 类型保留对 Blender 内部数据的引用,这样更改就可以应用回来。

    举个例子

    # modifies the Z axis in place.
    bpy.context.object.location.z += 2.0
    # location variable holds a reference to the object too.
    location = bpy.context.object.location
    location *= 2.0
    # Copying the value drops the reference so the value can be passed to
    # functions and modified without unwanted side effects.
    location = bpy.context.object.location.copy()

    动画

    有两种方法可以通过 Python 添加关键帧。

    • 第一种是直接通过键属性,这类似于用户从按钮插入关键帧。

    • 您也可以手动创建曲线和关键帧数据,然后将路径设置为属性。

    这是这两种方法的示例。这两个示例都在活动对象的 Z 轴上插入关键帧。

    简单的例子:

    obj = bpy.context.object
    obj.location[2] = 0.0
    obj.keyframe_insert(data_path="location", frame=10.0, index=2)
    obj.location[2] = 1.0
    obj.keyframe_insert(data_path="location", frame=20.0, index=2)

    使用低级功能:

    obj = bpy.context.object
    obj.animation_data_create()
    obj.animation_data.action = bpy.data.actions.new(name="MyAction")
    fcu_z = obj.animation_data.action.fcurves.new(data_path="location", index=2)
    fcu_z.keyframe_points.add(2)
    fcu_z.keyframe_points[0].co = 10.0, 0.0
    fcu_z.keyframe_points[1].co = 20.0, 1.0

    The above is the detailed content of Blender Python programming introduction example analysis. For more information, please follow other related articles on the PHP Chinese website!

    Statement:
    This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete