LoginSignup
7

More than 5 years have passed since last update.

初めてのコマンドプラグイン

Posted at

概要

Mayaコマンドプラグインについて初学者向けの内容を記載しています。

  • コマンドプラグインとは何なのか?
  • コマンドプラグインはどう使えそうなのか?
  • どういった参考記事があるのか?

モチベーション

コマンドプラグインってあまり情報を見かけませんよね。
そういえば自分も全く使ってないなぁと…
ということで自分自身も対象にした入門記事を書こうという狙いです。
とにかくMayaPythonに関する記事を増やそうかなということで内容は軽めです。

コマンドプラグインとは?

公式ヘルプにはこのように書いてあります。

新しいカスタム MEL コマンドを定義して、それに応じて
maya.cmds Python モジュールに関数を追加してスクリプトで使用できるようにします。

要するに自作したPythonモジュールがcmdsから直接呼び出せるということですね。

cmds.ls(sl=True)するコマンドプラグイン

とにかく書いて使ってみるのが手っ取り早い。
ということで、cmds.ls(sl=True)の機能をコマンドプラグインで書いてみます。
Maya ヘルプを参考に(というかコピペして)したのが下記のコードです。

command_select.py
# -*- coding: utf-8 -*-
import maya.api.OpenMaya as OpenMaya


def maya_useNewAPI():
    pass

class CommandSelection(OpenMaya.MPxCommand):
    kPluginCmdName = "selection"

    def __init__(self):
        OpenMaya.MPxCommand.__init__(self)

    @staticmethod
    def cmdCreator():
        return CommandSelection()

    def doIt(self, args):
        self.setResult(list(OpenMaya.MGlobal.getActiveSelectionList().getSelectionStrings()))

def initializePlugin(mobject):
    plugin = OpenMaya.MFnPlugin(mobject)
    plugin.registerCommand(CommandSelection.kPluginCmdName, CommandSelection.cmdCreator)

def uninitializePlugin(mobject):
    pluginFn = OpenMaya.MFnPlugin(mobject)
    pluginFn.deregisterCommand(CommandSelection.kPluginCmdName)
command_select_doit.py
cmds.selection()
>>> # Result: [u'pPlane2', u'pPlane1'] # 

コードの内容

戻り値について

コマンドの戻り値は return文 じゃないんですね!(先入観が)
ヘルプを調べると setResult()だと書いてありますので doIt()で呼び出しています。

ちょっと改良しようと思って独自クラスを setResult()しようとしたところ、
# Command results must be string or numeric. とエラーが発生。
他の親クラスの場合を調べていませんが、コマンドプラグインでは文字列か数値しか返せないんでしょうかね。

親クラスについて

MPx というプリフィックスが付けられたクラスはプロキシ クラスと呼ばれ、
さまざまなプラグイン タイプを作成するために使用されます。

ということで他にどんなクラスがあるのかリファレンスを見てみました。
作りたいプラグインに合わせてどの親を継承するか?さらなるお勉強が必要ですね。

Class Description
MPxAttributePatternFactory Base class for custom attribute pattern factories.
MPxCommand Base class for custom commands.
MPxData Base Class for User-defined Dependency Graph Data Types.
MPxGeometryData Base Class for User-defined Dependency Graph Geometry Data Types.
MPxGeometryIterator Base class for user defined geometry iterators.
MPxNode Base class for user defined dependency nodes.
MPxSurfaceShape Parent class of all user defined shapes.

感想

非常によく使いそうな処理はコマンドプラグインにしておくとコード量が減って楽になるかも。
MELコマンドとしても使えるのでMELerなアーティストにも便利なのかもしれないですね。
多方面からのツッコミやアドバイスも待ちつつ、追加のお勉強をしていきたいと思います。

参考サイト

 

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7