Skip to content

Instantly share code, notes, and snippets.

@wakarase
Last active March 15, 2023 10:37
Show Gist options
  • Save wakarase/02ce362f85a7678e82f9e54836e9c493 to your computer and use it in GitHub Desktop.
Save wakarase/02ce362f85a7678e82f9e54836e9c493 to your computer and use it in GitHub Desktop.
# Blender 質感・マテリアル設定実践テクニック 3-02-1.blend
import bpy
object = bpy.data.objects['export3dcoat'] # シーンに配置済みのオブジェクト
slot = object.material_slots[0] # そのマテリアルスロット
material = slot.material # に設定されているマテリアル
node_tree = material.node_tree # のノードネットワーク
nodes = node_tree.nodes # にある各ノード
def delete():
"""過去に生成したノードを削除します。"""
for node in nodes:
if node.label.endswith(' del'):
nodes.remove(node)
delete()
def show():
"""既存のノードの情報を表示します。"""
for node in nodes:
s = 'node "{}" at {}'
s = s.format(node.name, list(node.location))
print(s, type(node))
show()
def format_key(key):
"""与えられた文字列を加工して必要なら整数にします。"""
if key.startswith('_'): # 先頭の下線で整数を表すことにします。
return int(key[1:])
else: # 中間の下線で空白を表すことにします。
return key.replace('_', ' ')
def create(name, location, **args):
"""新しくノードを作ってlocationに配置します。"""
node = nodes.new('ShaderNode' + name)
node.label = node.name + ' del' # 自動生成したノードだというフラグです。
y_offset = -500
node.location = (location[0], location[1] + y_offset)
for key, value in args.items():
node.inputs[format_key(key)].default_value = value
return node
def link(**args):
"""2つのノードを接続します。"""
(k_left, v_left), (k_right, v_right) = args.items()
k_left, k_right = format_key(k_left), format_key(k_right)
node_tree.links.new(v_right.inputs[k_right], v_left.outputs[k_left])
# テクスチャ座標ノードによって、オブジェクトのローカル座標を得ます。
texture_coordinate = create('TexCoord', (-897, 114))
# Detailが最大の最も複雑なマスグレイブテクスチャを得ます。
musgrave_texture = create('TexMusgrave', (-693, 275), Scale=2, Detail=15, Dimension=0, Lacunarity=1.4)
link(Object=texture_coordinate, Vector=musgrave_texture)
# マスグレイブテクスチャは平均0標準偏差1で正規分布?しているので、[0, 1]の範囲で左右対称に分布するように+0.5加算します。
add = create('Math', (-509, 262))
link(Fac=musgrave_texture, Value=add)
# Lacunarityをずらしたマスグレイブテクスチャで異なる詳細を追加します。
musgrave_texture = create('TexMusgrave', (-346, 69), Scale=2, Detail=15, Dimension=0, Lacunarity=1.5)
link(Object=texture_coordinate, Vector=musgrave_texture)
# 青をベースに、マスグレイブの値が高い部分を茶色にします。
mix = create('Mix', (-332, 277), _6=(0.089, 0.258, 0.761, 1.000), _7=(0.223, 0.044, 0.027, 1.000))
mix.data_type = 'RGBA'
link(Value=add, Factor=mix)
# 第2のマスグレイブで「覆い焼き」します。
# つまり、第2のマスグレイブが0に近い(黒い)部分はそのまま、1に近い(白い)部分は明るくなります。
# マスグレイブは平均0標準偏差1の正規分布?をしますが、影響を0.2倍に抑えます。
color_dudge = create('Mix', (-154, 270), _0=0.2)
color_dudge.data_type = 'RGBA'
color_dudge.blend_type = 'DODGE'
link(_2=mix, _6=color_dudge)
link(Fac=musgrave_texture, _7=color_dudge)
# 既存のPrincipled BSDFシェーダのBase Colorとして入力します。
link(_2=color_dudge, Base_Color=nodes['Principled BSDF.001'])
print('Done.')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment