3
$\begingroup$

I have a script that generates a tower of blocks, and I want to simulate this tower's collapse, tracking the position of each block as the tower collapses. (And then do this again and again for thousands of arbitrary towers.) I can do this for a given tower in the GUI by setting the current frame to some late frame, baking to the current frame, and then calling object.matrix_world.translation in the console to get a given object's location at the current frame. (If I don't bake first, then object.matrix_world.translation just gives me the initial location of each object.)

However, when I try to do this with scripting, bpy.ops.ptcache.bake(bake=False) gives me the error Operator bpy.ops.ptcache.bake.poll() failed, context is incorrect. The solution seems to be to "override the context" (e.g. Setting the context for cloth bake), but I couldn't figure out how to do that in my case (which should be even simpler, since I'm just doing a rigid body simulation).

Any idea how to make bpy.ops.ptcache.bake(bake=False) work?

(I included some background on what I'm trying to do in case there's a simpler way to get each rigid body's location at a given frame of the animation. This seemed relevant [ Getting the location of rigid body object at current keyframe ] but, as I said earlier, if I don't bake first, then object.matrix_world.translation just gives me the initial location of each object, not its simulated location at the current frame.)

$\endgroup$

1 Answer 1

8
$\begingroup$

bpy.ops.ptcache.bake(bake=False) for Rigid Body doesn't work, because it needs the point cache and scene passed explicitly as context, so:

# override operator context
with bpy.context.temp_override(
    scene = bpy.context.scene,
    point_cache = bpy.context.scene.rigidbody_world.point_cache
):
    # bake to current frame under custom ops context
    bpy.ops.ptcache.bake(bake=False)
$\endgroup$
2
  • $\begingroup$ Thank you! Worked like a charm. (I get a bunch of PyContext warnings now, but I guess that's the point.) $\endgroup$
    – czf
    Aug 13, 2015 at 14:44
  • 2
    $\begingroup$ Could this answer be updated, now that this was deprecated and context.temp_override(...) and non-dictionary forms are the way forward? $\endgroup$
    – james_t
    Jan 5 at 19:16

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .