Blender程序化分配材质

本文介绍如何使用 Python 创建新材质、添加着色器、创建新对象并将材质分配给 Blender 中的对象。

首先,创建一种新材质。该函数将字符串作为新材质的名称:

import bpy

def newMaterial(id):

    mat = bpy.data.materials.get(id)

    if mat is None:
        mat = bpy.data.materials.new(name=id)

    mat.use_nodes = True

    if mat.node_tree:
        mat.node_tree.links.clear()
        mat.node_tree.nodes.clear()

    return mat

然后为材质添加着色器。输入着色器的类型(即漫反射、发射、光泽)和 rgb 颜色:

def newShader(id, type, r, g, b):

    mat = newMaterial(id)

    nodes = mat.node_tree.nodes
    links = mat.node_tree.links
    output = nodes.new(type='ShaderNodeOutputMaterial')

    if type == "diffuse":
        shader = nodes.new(type='ShaderNodeBsdfDiffuse')
        nodes["Diffuse BSDF"].inputs[0].default_value = (r, g, b, 1)

    elif type == "emission":
        shader = nodes.new(type='ShaderNodeEmission')
        nodes["Emission"].inputs[0].default_value = (r, g, b, 1)
        nodes["Emission"].inputs[1].default_value = 1

    elif type == "glossy":
        shader = nodes.new(type='ShaderNodeBsdfGlossy')
        nodes["Glossy BSDF"].inputs[0].default_value = (r, g, b, 1)
        nodes["Glossy BSDF"].inputs[1].default_value = 0

    links.new(shader.outputs[0], output.inputs[0])

    return mat

然后创建对象,分配材质并调用函数:

def drawObject():

    mat = newShader("Shader1", "diffuse", 1, 1, 1)
    bpy.ops.mesh.primitive_cube_add(size=2, align='WORLD', location=(0, 0, 0))
    bpy.context.active_object.data.materials.append(mat)

drawObject()

原文链接:Assign a material to an object in Blender using Python

BimAnt翻译整理,转载请标明出处