最近、発信したり記録に残すって大切だなと思い、Qiitaで記事を書いてみることにしました。
まだまだTouchDesignerは始めたばかりですがよろしくお願いします。
さて、toeファイルを起動した瞬間になんか処理したい時ってないですかね?
そんな時の小ネタ備忘録になります。
Extension Code
COMPの機能としてExtension Codeというものがあり、Componentを拡張できます。
これを使っていろいろ試してみます。
詳しい解説はおなじみMatthewさんのTouchDesigner | Understanding Extensionsに載ってるので興味がある人はこちらをどうぞ!
まずは基本的な操作。
Base COMPの上で、右クリックしてCustomize Componentを選択します。

するとComponent Editorが出てきます。ここでParameterの追加やTagの変更ができるのですが、今回はExtension Codeのタブの左にある三角を押して開きます。

このbase1のCOMPにExtClassというクラスを追加していきます。ExtClassと入力してAddを押します。

するとExtClassが追加され、編集できるようになります。

Editを押すとText Editが立ち上がります。

色々書いてありますが、一旦無視して↑のExtClass descriptionとコメントアウトしてあるところにExtClassのFunctionを追加していきます。
class ExtClass:
def passThrough(self, x):
return x
def double(self, x):
return 2 * x
そのまま受け流すものと、2倍して返すFunctionを定義します。保存してNetworkEditorに戻り、EditボタンのとなりにあるInitボタンを押します。
Geometry COMPを出して、確認してみます。
Translateのパラメータにop('base1').ext.ExtClass.passThrough(1.5)
やop('base1').ext.ExtClass.double(1.5)
と入力してみると

op('base1').ext.ExtClass.double(1.5)
の方は引数の2倍の値が返ってきてgeo1が移動してますね!
もちろんCHOPの値を読み出すといったことも可能です。Lfo CHOPの値をbase内のnullに格納して
ExtClassに以下を追記すると
class ExtClass:
def wave(self, x):
y = op('null1')['chan1']
return x * y

lfoの値によってgeo1が動きますね!
0フレーム目に乱数を出す
前段が長くなってしまいましたが、今回はtoeファイルを起動して0フレーム目に乱数を出してみます。
先ほどの要領でBase COMPのExtension Codeを作り、乱数を生成します。
import random
class ExtClass:
def Setup(self):
frame = absTime.frame;
rand = random.randint(1, 10)
text = 'Frame : ' + str(frame) + ' Number : ' + str(rand)
print(text)
return
Excute DATのonStart()
で起動時に呼び出します。(ちゃんと書くとop('base1').ext.ExtClass.Setup()
ですかね)

この状態でtoeファイルを起動してみると

0フレーム目に乱数が生成できました!
おわりに
初めて自分で記事を書いてみて、すばらしい先輩方へのリスペクトがより深まりました。
もっとこうした方がいいんじゃない?などご指摘ありましたらありがたいです!!
余談
TouchdesignerはDAT系のオペレーターでPythonによる処理も可能ですが、処理速度を気にする場合、Extensionsを利用するのがベターのようです。とはいえ基本はCHOPで頑張るのがセオリーですかね?
詳細は公式wikiへ。よきTouchDesignerライフを!