MRが楽しい

MRやVRについて学習したことを書き残す

Blender2.8のPython実行でUIパネルを追加する

本日は Blender2.8 の python 利用の技術調査枠です。
Blender2.8のPython実行でUIパネルを追加する方法を記事にします。
f:id:bluebirdofoz:20191110232050j:plain

Blender2.8でUIパネルを追加する

パネルは自作クラスを作成して登録する事で作成できます。
登録に必要な操作は以下の記事を参照ください。
bluebirdofoz.hatenablog.com

今回は更に[bl_]の先頭文字を持つ各変数に設定を行うことで、どの位置にパネルを追加するかを調整してみます。
例えば、3DビューのUIにパネルを追加する以下のスクリプトを作成してみました。
・AddPanelTest.py

import bpy

# HelloWorldPanelクラスの作成
class HelloWorldPanel_PT_ui(bpy.types.Panel):
    bl_label = "Hello World Panel"
    bl_idname = "OBJECT_PT_hello"
    bl_space_type = "VIEW_3D"
    bl_region_type = "UI"
    bl_category = "AddPanel"

# 描画の定義
    def draw(self, context):
        self.layout.operator("hello.button")

class HelloWorldPanel_OT_button(bpy.types.Operator):
    bl_label = "text"
    bl_idname = "hello.button"

    def execute(self, context):
        print("pushed")
        return{'FINISHED'}


# 登録対象のクラス名
regist_classes = (
    HelloWorldPanel_PT_ui,
    HelloWorldPanel_OT_button
)


# HelloWorldPanelの登録
def register():
    for regist_cls in regist_classes:
        bpy.utils.register_class(regist_cls)

# HelloWorldPanelの解除
def unregister():
    for regist_cls in regist_classes:
        bpy.utils.unregister_class(regist_cls)

# 実行例:[HelloWorldPanelの登録]を実施
if __name__ == "__main__":
    register()

スクリプトを実行した結果が以下になります。
「3Dビュー」のウィンドウのサイドバーに「AddPanel」が追加されています。
これを開くと「Hello World Panel」という draw 関数で定義した内容のパネルが表示されます。
f:id:bluebirdofoz:20191110232103j:plain

[bl_]の変数はそれぞれ以下の意味を持ちます。
bl_label:パネルラベル名を設定します。
bl_idname:カスタムIDを設定します。設定しない場合、クラス名がカスタムIDとなります。
bl_space_type:パネルが配置されるウィンドウスペースを設定します。
bl_region_type:パネルが配置される領域を設定します。
bl_category:パネルが配置されるカテゴリを設定します。

パネル配置の変更

bl_space_type, bl_region_type, bl_context の変数の定義を変更することでウィンドウの様々な位置にパネルを配置できます。
設定には幾つかの組合せがありますが、組合せの位置が存在しない場合、エラーが発生します。
例えば、 bl_space_type:VIEW_3D/bl_region_type:WINDOW で実行するとエラーが発生し、パネルは配置されません。
f:id:bluebirdofoz:20191110232113j:plain

bl_category, bl_context を組み合わせることで、さらに詳細な位置を指定する組合せもあります。
bl_space_type:VIEW_3D/bl_region_type:UI の場合、bl_category を指定しないと[その他]タブにパネルが配置されます。
f:id:bluebirdofoz:20191110232124j:plain

bl_context はプロパティ領域にパネルを配置する際に利用します。
例えば、bl_space_type:PROPERTIES/bl_region_type:WINDOW/bl_context:object を指定すると、オブジェクトタブにパネルが配置されます。
f:id:bluebirdofoz:20191110232132j:plain

サンプルを利用する

[テキストエディタ―]の[テンプレート]からUIパネル作成のテンプレートファイルを開くことができます。
こちらを参考にスクリプトを作成することもできます。
・UI_Panel
f:id:bluebirdofoz:20191110232141j:plain
・UI_Panel_Sample
f:id:bluebirdofoz:20191110232151j:plain

参考ページ

その他、[bl_]変数で定義可能な情報の詳細は以下の公式ページを参照してください。
docs.blender.org