您好,欢迎访问一九零五行业门户网

Blender Python编程入门实例分析

blender python 编程支持的特性:
编辑用户界面可以编辑的任何数据(场景,网格,粒子等)。
修改用户首选项、键映射和主题。
使用自己的设置运行工具。
创建用户界面元素,如菜单、标题和面板。
创建新的工具。
创建交互式工具。
创建与 blender 集成的新渲染引擎。
订阅对数据及其属性的更改。
在现有的 blender 数据中定义新设置。
使用 python 绘制3d视图。
(仍然)缺失的特性:
创建新的空间类型。
为每个类型分配自定义属性。
数据访问python 以与动画系统和用户界面相同的方式访问 blender 的数据。这意味着可以通过按钮更改的任何设置也可以从 python 更改。
使用模块可以完成从当前加载的 blender 文件访问数据的操作 bpy.data 。这样就可以访问库数据。例如:
>>> bpy.data.objects<bpy_collection[3], blenddataobjects>
>>> bpy.data.scenes<bpy_collection[1], blenddatascenes>
>>> bpy.data.materials<bpy_collection[1], blenddatamaterials>
访问集合您会注意到索引和字符串都可以用来访问集合的成员。与 python 字典不同,这两种方法都是可用的; 但是,在运行 blender 时,成员的索引可能会改变。
list(bpy.data.objects)[bpy.data.objects["cube"], bpy.data.objects["plane"]]
>>> bpy.data.objects['cube']bpy.data.objects["cube"]
>>> bpy.data.objects[0]bpy.data.objects["cube"]
访问属性一旦你有了一个数据块,比如一个材料、对象、集合等,它的属性就可以被访问,就像使用图形界面更改设置一样。事实上,每个按钮的工具提示还显示了 python 属性,它可以帮助查找在脚本中更改哪些设置。
bpy.data.objects[0].name'camera'
>>> bpy.data.scenes["scene"]bpy.data.scenes['scene']
>>> bpy.data.materials.new("mymaterial")bpy.data.materials['mymaterial']
对于测试要访问哪些数据,使用 python console 是很有用的,它是自己的空间类型。这支持自动完成,为您提供了一种快速探索文件中的数据的方法。
可以通过控制台快速找到的数据路径示例:
bpy.data.scenes[0].render.resolution_percentage100>>> bpy.data.scenes[0].objects["torus"].data.vertices[0].co.x1.0
数据创建/删除当你熟悉其他 python api 时,你可能会惊讶于 bpy api 中新的数据块不能通过调用类来创建:
bpy.types.mesh()traceback (most recent call last): file "<blender_console>", line 1, in <module>typeerror: bpy_struct.__new__(type): expected a single argument
用户不能在 blender 数据库(bpy.data访问的那个)外的任何地方新建数据,因为这些数据是由 blender 管理的(保存、加载、撤销、追加等)。
而只能使用以下方法进行数据增删:
mesh = bpy.data.meshes.new(name="mymesh")>>> print(mesh)<bpy_struct, mesh("mymesh.001")>
bpy.data.meshes.remove(mesh)
自定义属性python 可以访问具有 id 的任何数据块上的属性。当分配属性时候,如果该属性本不存在,就会新建该属性。
这些属性同样保存在 blender 文件中,并随着对象一同继承或者复制。
bpy.context.object["myownproperty"] = 42if "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"]
但是,这些自定义属性的值必须是基本的 python 数据类型。如:
int/float/string
int/ float 的数组
字典(仅支持字符串键,值也必须是基本类型)
自定义属性在 python 外部同样有效。它们可以通过曲线设置动画或在驱动路径中使用。
上下文 context能够直接通过名称或列表访问数据非常有用,但更常见的是根据用户的选择进行操作。这些上下文信息始终可从 bpy.context 中获得。
常用案例:
>>> bpy.context.object>>> bpy.context.selected_objects>>> bpy.context.visible_bones
请注意,上下文是只读的。这些值不能直接修改,尽管可以通过运行 api 函数或使用数据 api 进行更改。
因此这样会引发错误:bpy.context.object = obj
但是这样会正常工作:bpy.context.scene.objects.active = obj
运算符 operators (tools)operators 通常是用户从按钮、菜单项或快捷键访问的工具。从用户的角度来看,它们是一个工具,但是 python 可以通过 bpy.ops 模块访问、设置并运行他们。
举例:
bpy.ops.mesh.flip_normals(){'finished'}>>> bpy.ops.mesh.hide(unselected=false){'finished'}>>> bpy.ops.object.transform_apply(){'finished'}
operator cheat sheet 给出了 python 语法中所有操作符及其默认值的列表,以及生成的文档。这是一个了解 blender 所有操作符的好方法。
operator poll()许多的 operators 都有自己的 poll() 方法,该方法能检查现在的 blender 上下文是否满足该 operator 运行的条件。不满足时,直接调用该 operator 将会产生错误。所以在操作一个 operators 的时候,建议先用一下方式检查 context:
if bpy.ops.view3d.render_border.poll(): bpy.ops.view3d.render_border()
将 python 集成到 blender 的方式python 脚本可以通过以下方式与 blender 集成:
通过定义渲染引擎。
通过定义运算符。
通过定义菜单,标题和面板。
通过将新按钮插入现有菜单,标题和面板
在 python 中,这是通过定义一个类来完成的,该类是现有类型的子类。
blender 官方文档中提供了实例的类模板。如:
示例运算符import bpydef 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 {'finished'}def register(): bpy.utils.register_class(simpleoperator)def unregister(): bpy.utils.unregister_class(simpleoperator)if __name__ == "__main__": register()# test callbpy.ops.object.simple_operator()
一旦这个脚本运行,simpleoperator 在 blender 中注册,可以从 operator search 中调用或添加到工具栏中。
运行脚本:
启动 blender 并切换到脚本工作区。
单击文本编辑器中的 new 按钮以创建新的文本数据块。
从上面并将其粘贴到文本编辑器中。
单击 run script 按钮。
将光标移至 3d 视口,打开运算符搜索菜单,输入 “simple”。
点击搜索中找到的 “simpleoperator” 项目。
示例面板面板注册为一个类,就像操作符一样。请注意用于设置它们所显示的上下文的额外 bl_ 变量。
import bpyclass 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 = 'properties' bl_region_type = 'window' bl_context = "object" def draw(self, context): layout = self.layout obj = context.object row = layout.row() row.label(text="hello world!", icon='world_data') 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 = 'axis_angle'
blender枚举器(多个)->字符串集
# setting multiple camera overlay guidesbpy.context.scene.camera.data.show_guide = {'golden', 'center'}# passing as an operator argument for report typesself.report({'warning', 'info'}, "some message!")
内部类型用于 blender 数据块和 blender 集合: bpy.types.bpy_struct
用于包含 collections/meshes/bones/scenes 等属性的数据。
包装 blenders 数据的主要类型有 2 种,
一种用于数据块(内部称为 bpy_struct)
>>> bpy.context.objectbpy.data.objects['cube']
另一种用于属性。
>>> c.scene.objectsbpy.data.scenes['scene'].objects
mathutils 类型用于表示向量,四元数,euler,矩阵和颜色类型等,可从 mathutils 模块访问它们。
一些属性,如 bpy.types.object.location, bpy.types.posebone.rotation_euler 和 bpy.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.locationlocation *= 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.objectobj.location[2] = 0.0obj.keyframe_insert(data_path="location", frame=10.0, index=2)obj.location[2] = 1.0obj.keyframe_insert(data_path="location", frame=20.0, index=2)
使用低级功能:
obj = bpy.context.objectobj.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.0fcu_z.keyframe_points[1].co = 20.0, 1.0
以上就是blender python编程入门实例分析的详细内容。
其它类似信息

推荐信息