5

いくつかのオブジェクトをブレンダーから独自の形式にエクスポートしようとしています。私が書いたスクリプトで、ファイルドロップダウンとコマンドラインからblenderからオブジェクトをエクスポートできるようにしたいと思います。ubuntu 12.04 LTSでブレンダー2.66を使用しています。以下は、現在実行しようとしているファイルです。

# Required Blender information.
bl_info = {
           "name": "My Exporter",
           "author": "",
           "version": (1, 0),
           "blender": (2, 65, 0),
           "location": "File > Export > Test (.tst)",
           "description": "",
           "warning": "",
           "wiki_url": "",
           "tracker_url": "",
           "category": "Import-Export"
          }

# Import the Blender required namespaces.
import bpy
from bpy_extras.io_utils import ExportHelper


# The main exporter class.
class MyExporter(bpy.types.Operator, ExportHelper):
   bl_idname       = "test.tst";
   bl_label        = "My Exporter";
   bl_options      = {'PRESET'};

   filename_ext    = ".tst";

   object_count    = 0;

   def __init__(self):
      pass

   def execute(self, context):
      print("Execute was called.");

      # Parse all the objects in the scene.
      return {'FINISHED'};

   def export_object(self, gameObject):
      if (gameObject.type != "MESH"):
         print("Object was not of type mesh.");
      else:
         object_count += 1;

      return;


# Define a function to create the menu option for exporting.
def create_menu(self, context):
   self.layout.operator(MyExporter.bl_idname,text="test (.tst)");

# Define the Blender required registration functions.
def register():
   """
   Handles the registration of the Blender Addon.
   """
   bpy.utils.register_module(__name__);
   bpy.types.INFO_MT_file_export.append(create_menu);

def unregister():
   """
   Handles the unregistering of this Blender Addon.
   """
   bpy.utils.unregister_module(__name__);
   bpy.types.INFO_MT_file_export.remove(create_menu);

# Handle running the script from Blender's text editor.
if (__name__ == "__main__"):
   print("Registering.");
   register();

   print("Executing.");

   # I have tried with these lines uncommented to force it to run
   # the execute function, but I get an error saying:
   #    exporter = MyExporter();
   #    TypeError: bpy_struct.__new__(type): expected a single argument

   #exporter = MyExporter();
   #exporter.execute(bpy.context.scene);

次のコマンドを試しました:

blender model.blend --background --python myexporter.py

そこから、出力として次のものが得られます。

Note: No (valid) '~/.config/blender/2.66/config/startup.blend' found,
      fall back to built-in default.

Read new prefs: ~/.config/blender/2.66/config/userpref.blend
found bundled python: ~/blender/2.66/python
read blend: ~/model.blend
Registering.
Executing.

Blender quit

MyExporter クラスの execute 関数が呼び出されることはないようです。実行関数を直接呼び出してみましたが、その領域の上のコメントを読むと、そこにも何かが欠けているようです。

スクリプトがブレンダーのアドオンとして追加されると、すべてが正常に機能します。それは完全に実行を呼び出します。したがって、少なくとも半分は機能しています。

どうぞよろしくお願いいたします。私が愚かな間違いを犯した場合は、申し訳ありませんが、私はこのスクリプトを書くと同時に Python を学んでいます。

4

1 に答える 1

14

私はついにこれを理解し、戻ってきて答えを共有するのは良い考えだと思いました. まず、動作するファイルを次に示します。

# Required Blender information.
bl_info = {
           "name": "My Exporter",
           "author": "",
           "version": (1, 0),
           "blender": (2, 65, 0),
           "location": "File > Export > Test (.tst)",
           "description": "",
           "warning": "",
           "wiki_url": "",
           "tracker_url": "",
           "category": "Import-Export"
          }

# Import the Blender required namespaces.
import sys, getopt

import bpy
from bpy_extras.io_utils import ExportHelper



# The main exporter class.
class MyExporter(bpy.types.Operator, ExportHelper):
   bl_idname       = "export_scene.my_exporter";
   bl_label        = "My Exporter";
   bl_options      = {'PRESET'};

   filename_ext    = ".tst";

   object_count    = 0;

   def __init__(self):
      pass

   def execute(self, context):
      print("Execute was called.");

      self.parse_command_line_options();

      if (self.filepath == ""):
         print("No sutable filename was provided to save to.");
         return {'FINISHED'};

      # Get all the mesh objects in the scene.
      objList = [object for object in bpy.context.scene.objects if object.type == 'MESH'];

      # Now process all the objects that we found.
      for gameObject in objList:
         self.export_object(gameObject);

      # Parse all the objects in the scene.
      return {'FINISHED'};


   def export_object(self, gameObject):
      if (gameObject.type != "MESH"):
         print("Object was not of type mesh.");
      else:
         self.object_count += 1;

      return;


   def parse_command_line_options(self):
      modelFile = "";
      myArgs = [];
      argsStartPos = 0;

      if (("--" in sys.argv) == False):
         return;

      argsStartPos = sys.argv.index("--");
      argsStartPos += 1;
      myArgs = sys.argv[argsStartPos:];

      try:
         opts, args = getopt.getopt(myArgs, 'hm:', ["help", "model-file="]);
      except getOpt.GetoptError:
         print("Opt Error.");
         return;

      for opt, arg in opts:
         if (opt in ("-h", "--help")):
            print("Run this as the following blender command.");
            print("\tblender <blend file> --background --python <script file> -- -m <output file>");
         elif (opt in ("-m", "--model-file")):
            modelFile = arg;

      if (modelFile != ""):
         self.filepath = modelFile;



# Define a function to create the menu option for exporting.
def create_menu(self, context):
   self.layout.operator(MyExporter.bl_idname,text="test (.tst)");

# Define the Blender required registration functions.
def register():
   """
   Handles the registration of the Blender Addon.
   """
   bpy.utils.register_module(__name__);
   bpy.types.INFO_MT_file_export.append(create_menu);

def unregister():
   """
   Handles the unregistering of this Blender Addon.
   """
   bpy.utils.unregister_module(__name__);
   bpy.types.INFO_MT_file_export.remove(create_menu);


# Handle running the script from Blender's text editor.
if (__name__ == "__main__"):
   print("Registering.");
   register();

   print("Executing.");
   bpy.ops.export_scene.my_exporter();

私が見逃していた重要な点は、エクスポーター クラスの bl_idname の設定が間違っていたことと、bpy.ops.export_scene.my_exporter(); の呼び出しでした。

私が台無しにしたことの詳細については、http ://www.blender.org/documentation/blender_python_api_2_66_release/bpy.ops.html を参照してください。

Fileドロップダウンメニューだけでなく、コマンドラインからもこれを実行したかったので、Blenderに送信されたコマンドラインオプションを解析する解析関数を追加しました。Blender には、blender 引数入力の終了を定義するスイッチ「--」があるため、そのスイッチが検出された場合、その後の引数をすべて取得し、それらをスクリプト引数として解析します。これまでのところ、これは完全に機能しているようです。

現在、モデル ファイルは、いくつかのヘルプ情報を出力する -h と、変換データを保存するファイルを指定する -m をサポートしています。

さて、この情報が他の誰かに役立つことを願っています。幸運を。

更新: スクリプトの実行時にコマンド ラインに次のようなメッセージが 1 つ以上表示される場合は、この質問の回答を使用してその問題を解決してください。

skipping driver 'alpha * auto', automatic scripts are disabled
于 2013-06-13T18:32:12.717 に答える