How to add texture via scripting

I’m reading an addon codes. It’s used to automatically add an image(texture) on an model and render out an image. User can feed any image and model. Here is the code snippet:

def addMaterialImg():
for img in bpy.data.images:
    name = img.name_full
    material = bpy.data.materials.new(name= name)
    material.use_nodes = True
    #create a reference to the material output
    material_output = material.node_tree.nodes.get('Material Output')
    Principled_BSDF = material.node_tree.nodes.get('Principled BSDF')                                 

    texImage_node = material.node_tree.nodes.new('ShaderNodeTexImage')
    texImage_node.image = img
    #set location of node
    material_output.location = (400, 20)
    Principled_BSDF.location = (0, 0)
    texImage_node.location = (-400, -500)

    material.node_tree.links.new(texImage_node.outputs[0], Principled_BSDF.inputs[0])
    material.node_tree.nodes["Principled BSDF"].inputs['Specular'].default_value = 0
    material.node_tree.nodes["Principled BSDF"].inputs['Roughness'].default_value = 0.5
    mat = bpy.data.materials.get(name)
    mat.blend_method = 'CLIP'
return mat

What I’m confused is, how addon find the particular mesh which I want to add image(texture) on? Here it seems the addon follows the node location. If so, what the value (400,20) (0,0) (-400,-500) mean?

I need to make it clear, because I’m creating models for it. There must be some standards should be followed.

The developer figure out that the models here should be merged into one mesh so the script could operate them. I checked the sample model from the developer, there are 2 material slots. The image mesh is on one of them.

So the addon should know which material slot and which node, right? How?

A material doesn’t need a mesh to exist. The code simply creates a new material with the given name and builds a node tree for it.

the coordinates are just there to position some nodes in the tree in a nicer way I guess. I don’t think they have any effect on how the tree behaves, just make it look a bit nicer if you later want to manually change something in it.

The association of this material with a material slot in a specific mesh does not happen in the code you posted.

Yes, this material is associated with a material slot via this code:

bpy.context.active_object.material_slots[1].material = bpy.data.materials[block.name_full]

Then what is the function of those coordinates (400,20) (0,0) (-400,-500)?

Those are just the positions of the nodes on the canvas of the material editor. Makes the resulting material node tree nicer to look at if the nodes aren’t all on top of each other.

It’s not important for the functionality, just for how it looks.

1 Like