Weight Paint Scripting Context Issue

I’m attempting to set up a weight paint gradient on a basic object, and I’m running into context issues. I’m not very familiar with python, but I assume that I’m supposed to indicate that the desired mode for this to take effect is weight paint, and not object/edit/whatever the default is (though I could be way off).

The problem is in the last line of code…

import bpy

#Emitter Object
bpy.ops.mesh.primitive_plane_add()


#Object Name
bpy.data.objects["Plane"].name = "Emitter"


#Subsurf Modifier
bpy.ops.object.modifier_add(type='SUBSURF')
bpy.data.objects["Emitter"].modifiers["Subsurf"].levels = 7
bpy.data.objects["Emitter"].modifiers["Subsurf"].render_levels = 7
bpy.ops.object.modifier_apply(modifier = "Subsurf")


#Vertex Groups
<b>bpy.ops.paint.weight_gradient(type='LINEAR', xstart=0, xend=1, ystart=0, yend=1, cursor=1002)</b>

The console displays “RuntimeError: Operator bpy.ops.paint.weight_gradient.poll() failed, context is incorrect”

here you need to add the code that I wrote for another addon:

import bpy


#Emitter Object
bpy.ops.mesh.primitive_plane_add()


#Object Name
bpy.data.objects["Plane"].name = "Emitter"


#Subsurf Modifier
bpy.ops.object.modifier_add(type='SUBSURF')
bpy.data.objects["Emitter"].modifiers["Subsurf"].levels = 7
bpy.data.objects["Emitter"].modifiers["Subsurf"].render_levels = 7
bpy.ops.object.modifier_apply(modifier = "Subsurf")



obj = bpy.context.object
obv = obj.data.vertices
if not obj.vertex_groups:
    obj.vertex_groups.new(name='Sv_VGroup')
ovgs = obj.vertex_groups[0]

for i in obv:
    ovgs.add([i.index], i.co.length, "REPLACE")
    # or inverted:
    # ovgs.add([i.index], (1-i.co.length), "REPLACE")
    # or linear:
    # ovgs.add([i.index], (i.co.y+1)/2, "REPLACE")

obj.data.update()


Attachments


Awesome! That worked perfectly.

If you (or anyone else) sees this and has time to respond, what does “obv” indicate in the second line of (new) code, and how does “i” tie into that? I haven’t been able to find much on the API so far…

Thank you again!

obv is a collection of all vertices of the object.
i is the enumerator in the for loop and specifies the current vertex object element in the obv collection.

You won’t find anything “about it” in the api as your problem derives from lack of python/coding knowledge, not from unfamiliarity with blender’s python api. Unless I’m misunderstanding you here.

Thank you!

And yes, that’s the issue; I haven’t been able to find any (up to date) resources on using python in Blender…