pythonblender

quickly adding large numbers of mesh primitives in blender


I'm trying to add tens of thousands of mesh primitives to a scene in blender using its Python interface. I've been using something to the effect of:

for i in range(10000):
    bpy.ops.mesh.primitive_cube_add(radius=1, location=(i, i, i))

This approach takes many minutes, though. Is there a more efficient way of doing this?


Solution

  • import bpy
    from mathutils import Vector;
    
    n = "cube";
    bpy.ops.mesh.primitive_cube_add(radius=1);
    orig_cube = bpy.context.active_object;
    
    for i in range(10000):
        m = orig_cube.data.copy();
        o = bpy.data.objects.new(n, m);
        o.location = Vector((i, i, i));
        bpy.context.scene.objects.link(o);
        # for blender versions >= 2.8, replaced the line above with the next line
        # bpy.context.collection.objects.link(o)
    
    
    bpy.ops.object.delete();
    

    Takes about 15 seconds on my machine. If you don't need to have unique cubes (i.e. don't intend to modify their geometry separately) then you can attach the same mesh to multiple objects. There are probably faster ways like creating single mesh and point cloud and using dupliverts (duplicating child object on each vertex of point cloud).

    Example with just points and dupliverts (which, as expected, completes in a moment, but of course is not the same thing):

    import bpy;
    import bmesh;
    from mathutils import Vector;
    
    bpy.ops.mesh.primitive_cube_add(radius=1);
    orig_cube = bpy.context.active_object;
    
    bpy.ops.mesh.primitive_plane_add();
    o = bpy.context.active_object;
    me = o.data;
    bm = bmesh.new();
    for i in range(10000):
        bm.verts.new().co=Vector((i, i, i));
    bm.to_mesh(me);
    o.dupli_type = 'VERTS';
    orig_cube.parent = o;