Exporting an object to C

This little python script can be used to export a selected object in Blender into a float array with vertex position and normals. Easy way to add meshes into your openGL application.

We transform from the default Blender orientation to the default openGL orientation (z pointing into the screen).

"""

Exports the selected object in blender to an float array with 
vertices and normals. We do not use vertex indices but rather 
duplicate each triangle. 

"""

import bpy
import math
import mathutils
from mathutils import Vector, Matrix
o = bpy.context.active_object
print("="*40)
output = []
mat_x90 = mathutils.Matrix.Rotation(-math.pi/2, 4, 'X')
conv_mat = o.matrix_world

def add_vert(face_index, n):
    v = o.data.vertices[face_index].co
    v = conv_mat * v 
    v = mat_x90 * v 
    output.append(v.x)
    output.append(v.y)
    output.append(v.z)
    output.append(n.x)
    output.append(n.y)
    output.append(n.z)

    
def add_face(face, norm):
    if len(face) == 4:
        add_vert(face[0], norm)
        add_vert(face[1], norm)
        add_vert(face[2], norm)
        add_vert(face[0], norm)
        add_vert(face[2], norm)
        add_vert(face[3], norm)
    elif len(face) == 3:
        add_vert(face[0], norm)
        add_vert(face[1], norm)
        add_vert(face[2], norm)
            
        
for face in o.data.polygons:
    verts = face.vertices[:]
    n = face.normal
    add_face(verts, n)

out_str = "int nvertices = " +str(len(output)) +";\n"
out_str += "float vertices[] = {" +",".join(map(str, output)) +"};"
       
dest = "path_to_your_header_file/bone.h"
f = open(dest, 'w+')
f.write(out_str)
f.close()
print("Created.")