日々適当

hibitekitou

スクリプトからシェーダノードを触ってみる

cg |2021-06-21

メモっす。読み込んだfbxファイルのマテリアルの中の接続を一括で変えたい事情ができたような気がするので、その予習というか。

import bpy

for obj in bpy.context.selected_objects:
    #mat = obj.active_material
    material_slots = obj.material_slots
    for material_slot in material_slots:
        #マテリアルスロットごとのマテリアルを取得
        material = material_slot.material
        #マテリアルのノードツリー
        nodetree = material.node_tree
        #シェーダーノード内のノードタイプの一覧
        for node in nodetree.nodes:
            print( node.type )
            #以下 Principled BSDF を探しているが、
            #inputs = material.node_tree.nodes[ "Principled BSDF" ].inputs
            #で直接取得もできる模様
            if node.type == 'BSDF_PRINCIPLED':
                inputs = node.inputs
                #Principled BSDFのベースカラーの色を設定
                inputs['Base Color'].default_value = [ 1.0, 1.0, 0.0, 1.0 ]
                #後の行程で使うために取っておく
                principledBsdfNode = node
        
        #Principled BSDFのベースカラーにテクスチャを設定
        img = bpy.data.images.load( 'テクスチャファイルへのパス', check_existing=False )      
        imgTex_node = nodetree.nodes.new('ShaderNodeTexImage')
        imgTex_node.location =  ( principledBsdfNode.location.x -300 , principledBsdfNode.location.y )
        imgTex_node.image = img
        
        nodetree.links.new( imgTex_node.outputs[ 0 ], principledBsdfNode.inputs[0] )
        
#ちなみに以下をコメントアウトすると、上でせっかく繋いだリンクを切断する  
#        link = principledBsdfNode.inputs[0].links[0]
#        if link is not None:
#            nodetree.links.remove( link )

コメント ( 0 )|Trackback ( )
  ・