Rotate, translate, and duplicate a mesh in Python (2.70a)

Hello,

In Python (2.70a) I create a triangle on the xy plane as shown in the code below. I would like to do three things

  1. Duplicate the triangle
  2. Translate the duplicated triangle one unit along the + z axis
  3. Rotate the duplicated triangle 90 degree

Can anyone give some hint how to do this? I know about the Python API, been there, but I find it difficult to translate into working code.

Here is my python code:


#Blender 2.70a

import bpy
from bpy import context
from math import sin, cos, radians

coords=[(0,0.5,0),(0.5,-0.5,0),(-0.5,-0.5,0)] # Vertices for a triangle on the x-y plane
faces=[(2,1,0)] # Create a face with the normal pointing up (along +z)

me = bpy.data.meshes.new(“MyMesh”) # create a new mesh

I guess the additional code should go here

Duplicate the mesh

Translate the duplicate one unit along +z

Rotate the duplicate 90 degree

ob = bpy.data.objects.new(“triangle”, me) # create an object with that mesh
bpy.context.scene.objects.link(ob) # Link object to scene

me.from_pydata(coords,[], faces ) # edges or faces should be [], or you ask for problems
me.update(calc_edges=True) # Update mesh with new data


Sounds like a job for the bmesh module:

BMesh Module (bmesh)

There are bmesh operations to transform and duplicate, and has the advantage that you can run them on certain geometry elements without the need to change selection state as with standard API

Here is an attempt at that.


import bpy, math
from mathutils import Vector, Matrix

def returnSingleTriangleMesh(passedName):
    # this is our place holder shape in the event that we can not locate a mesh file for our object.
    vp_points = []
    vp_faces = []
    vp_objects = []
    
    # A triangle that points to top of screen when looking straight down on it.
    vp_D1 = Vector([0.5, 0.5, 0.0])
    vp_D2 = Vector([0.0, -1.0, 0.0])
    vp_D3 = Vector([1.0, -1.0, 0.0])
    vp_scale = 1.0
    c = 0

    # Single triangle object at world origin.
    dd = Vector([0.0, 0.0, 0.0])
    vp_points.append(dd+vp_D1*vp_scale)
    vp_points.append(dd+vp_D2*vp_scale)
    vp_points.append(dd+vp_D3*vp_scale)
    vp_faces.append([c,c+1,c+2])        

    me = bpy.data.meshes.new(passedName)
    me.from_pydata(vp_points,[],vp_faces)
    
    # Make sure all verts are deselected.
    for v in me.vertices:
        v.select = False
    me.update()
    return me

scene = bpy.data.scenes[0]

# Create a triangle at world origin.
me =returnSingleTriangleMesh("me_triangle-1")
ob = bpy.data.objects.new("triangle-1", me)
scene.objects.link(ob)

# Create a triangle at world origin.
me =returnSingleTriangleMesh("me_triangle-2")
ob = bpy.data.objects.new("triangle-2", me)
scene.objects.link(ob)
ob.location.z += 1.0
ob.rotation_euler.x = math.radians(90)