I am trying to bake image from the script in cycles mode. In my node structure, since I am baking in cycles engine, I am adding an extra image texture node, with image input of a newly created image (named uv_image) and I am making this uv_image texture node my active node. Now I select the object and do a bake using bpy.ops.object.bake(). Here is the code I am executing :
uv_image = "UV_image" bpy.data.images.new(name=uv_image,width = 1024,height = 1024) mat = bpy.data.materials[material.name] nodes = mat.node_tree.nodes node = nodes.new('ShaderNodeTexImage') node.location = 300,0 node.label = 'uv_image' node.name = 'uv_image' node.image = bpy.data.images[uv_image] uv_img = bpy.data.images[uv_image] node.select = True nodes.active = node for area in bpy.context.screen.areas : if area.type == 'IMAGE_EDITOR' : area.spaces.active.image = uv_img for ob in bpy.data.objects: if 'pattern' in ob.name: #object of interest has the name pattern) ob.select = True bpy.context.scene.objects.active = ob else: ob.select = False bpy.ops.object.bake(type='COMBINED')
The output baked image is blank when I am doing this from the script without any texture baked and it happens instantaneously. (Usually bake takes a few seconds) But when I execute the code without the bpy.ops.object.bake() statement and hit the bake button in GUI, the baked image is perfect. Another observation is that, once I bake in GUI, from then on, when I execute and bake from script, it works. So, everytime I need to bake it in GUI once to get this code working from script. It is really frustating!
By using bpy.ops.object.bake('INVOKE_DEFAULT', type='COMBINED'), I can see the texture getting baked well on the uv_image but when I tried to save the baked image through the following lines of code which follow the bake statement, I get a blank image in the destination folder. I think image is getting saved before it is getting updated with the baked texture. I tried to include image.update() before saving but that did not help.
for image in bpy.data.images: if "UV_" in image.name: image = bpy.data.images[image.name] scene=bpy.context.scene scene.render.image_settings.file_format='JPEG' image_path = img_path + str(cg)+"_"+image.name+".jpg" image.save_render(image_path,scene)
If I add a time delay in the following way:
import time time.sleep(60)
and I wait till the bake is complete and then save, then the image is saved after the entire bake. So, I am guessing that INVOKE_DEFAULT runs the baking in parallel without blocking the image being baked? Is this correct? Can someone help me find the documentation for INVOKE_DEFAULT along with other parameters ?