LoginSignup
0
2

More than 5 years have passed since last update.

Diffuse色とSpecularの強さからマテリアル名を決める (Python for Blender クックブック)

Last updated at Posted at 2018-10-31

Diffuse色とSpecularの強さからマテリアル名を決める

Pythonを使ってBlenderでできる事をまとめています。解説もあります。
はじめに
レシピ一覧

Pythonの難易度: ★★☆☆☆

動機

気がついたらMaterial.004みたいな名前のマテリアルが増えていて困りますよね?
マテリアルの特徴を元にマテリアル名を改名しましょう。

細かい仕様

  • Diffuse色は下表の通りです。0~1の間の値は四捨五入してください
色名 大体のRGB値(0〜1)
black (0,0,0)
red (1,0,0)
green (0,1,0)
blue (0,0,1)
aqua (0,1,1)
purple (1,0,1)
yellow (1,1,0)
white (1,1,1)
  • Specularの強さを四捨五入した結果が0ならrough、1ならsmoothです。
  • 「M_black_smooth」のように「M_Diffuse色_Specularの強さ」とマテリアルを改名してください。
  • マテリアル名の重複は気にしないでください。

サンプルコード

color_dict = {
  (0,0,0):"black",
  (1,0,0):"red",
  (0,1,0):"green",
  (0,0,1):"blue",
  (0,1,1):"aqua",
  (1,0,1):"purple",
  (1,1,0):"yellow",
  (1,1,1):"white"}
spclr_dict = {0:"rough", 1:"smooth"}

def describe_color(rgb):
  """rgbを文字列で表現する

  引数
  rgb: (float, float, float)
    文字列で表現したい色のrgb値

  返り値: str
    color_dictのvalueのどれか
  """
  round_rgb = (int(0.5 <= rgb[0]), # 四捨五入
               int(0.5 <= rgb[1]),
               int(0.5 <= rgb[2]))
  return color_dict[round_rgb]

def describe_spclr(spclr):
  """Specularの強さを文字列で表現する

  引数
  spclr: (float, float, float)
    文字列で表現したい色のrgb値

  返り値: str
    spclr_dict
  """
  return spclr_dict[int(0.5 <= spclr)]

import bpy
for mat in bpy.data.materials:
    dif_color = mat.diffuse_color
    spclr = mat.specular_intensity
    new_name = "M_" + describe_color(dif_color) + "_" + describe_spclr(spclr)
    mat.name = new_name

上記サンプルコードを、Blender内蔵のテキストエディタに貼り付けた後、Alt-Pを実行してください。

解説

bpy.data.materials

PythonからBlenderを使うにはbpyというライブラリを使います。
例えば、bpy.opsには編集のための関数が格納されています。

bpy.dataにはBlender内の様々な変数(オブジェクトのインスタンス)が格納されています。
オブジェクト一覧はbpy.data.objectsから、マテリアル一覧はbpy.data.materialsからアクセスできます。

mat.diffuse_colormat.specular_intensity

mat.diffuse_colormat.specular_intensityからはどちらもMaterial共通のプロパティーです。
それぞれ、Diffuse色とSpecularの強さを指します。

「OOのXXという設定のpythonの名前ってなんだろうなぁ」と思った時は、その設定の上でマウスをかざすとわかります。

0
2
0

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
0
2