Baking AO, Proxy Objects, and Python

Hello. I’m trying to write a python script to bake the AO of each object in a scene to a file, named after the object.

Here is my blender workspace:


All objects in the scene are loaded in from external blend files, then made into proxy objects. I then duplicate-link them around and give them nice names. I then link several materials in from more external blends. I then give the various objects materials. I’m doing things this way, because it’s very similar to the way my game engine works. In the linked files, the objects and materials are given all needed custom properties, which are used in another python script I’ve written the exports the scene to my map format.

Anyway, the problem is the baking. Here is my current script:

import bpy
import os

def sqee_export_aobake():
    exportDir = os.path.join(os.path.dirname(bpy.data.filepath), "exported")
    
    scene = bpy.context.scene
    for obj in scene.objects:
        obj.select = False
    
    for k, v in bpy.data.scenes['Render'].objects.items():
        fp = os.path.join(exportDir, k)
        v.select = True
        scene.objects.active = v
        bpy.ops.object.bake(type='AO',
                            filepath=fp,
                            width=v.active_material["bakeX"],
                            height=v.active_material["bakeY"],
                            margin=1, save_mode='EXTERNAL')
        v.select = False
    
sqee_export_aobake()

If I run this as it is, I get “RuntimeError: Operator bpy.ops.object.bake.poll() failed, context is incorrect” in the console. However, I have noticed that even if I change the material of an object to a local material, I can’t even bake from the GUI.

However, if I convert everything in the map to local objects, I can then run my script. However, it just bakes ao onto some of the objects’ textures (same as clicking bake button), giving the original error after doing the trees and middle bridge tiles. It then does not save the files.

I only started using python in blender today, so I’m probably going about this all wrong.

What’s going on?

So, this is impossible? Sorry for the bump, but it seems I’m doing something wrong with my posts on this forum.