• Advertisement
Sign in to follow this  

Writing export scripts for blender

This topic is 2316 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Does anyone know any tutorials for writing an export script for blender 2.5/2.6, I need write a script to export 3d models for my game. If anyone knows an existing script that I can modify to fit my purposes could they post a link, my format is pretty simple:

For each face output three vertices:



-0.5 -0.5 -0.5 0.0 0.0 0.0 -1.0 0.0
0.5 -0.5 -0.5 0.5 0.0 0.0 -1.0 0.0
-0.5 -0.5 0.5 0.0 0.5 0.0 -1.0 0.0



each line represents a vertex and the attributes of said vertex in the order: x y z u v nx ny nz, where the last three numbers represent the normal vector.

It does other stuff like define textures and normal maps but the script doesn't need to do that as I could input them manually.

So once again my question is where could I find a tutorial to write blender exports scripts or does anyone know of a similar existing script that I could modify?

Share this post


Link to post
Share on other sites
Advertisement
Maybe it would be easier to simply export as Wavefront OBJ, and then write a small utility to convert that to your format. Since most 3d applications support OBJ, you wouldn't even be limiting yourself to Blender.

Share this post


Link to post
Share on other sites
I have to agree with Chris_F, it is much better to write an importer for your rendering engine that accepts known formats than to write a new format exporter for blender. The idea of manually inputing UV coords makes me shudder. Obj is a great way to go for static meshes. For animated meshes its a different story, lots of "depends" answers.

Cheers,

Bob

Share this post


Link to post
Share on other sites
Writing an exporter is a good idea, since you can choose what to export, and in a format that can loaded without any processing (e.g. organising triangles, indices).

You should look at how the exporter for easy formats like the .obj works, to learn how to do it, which is what I did.

Here's my exporter, though note lots of it is commented out since it was originally made to work with the previous version of blender before the update, and I haven't gotten around to fixing it.

The file format I used was a tree structure with tag names, similar to xml. You might want to use xml initially to save in, then switch to storing things in bytes later on to speed up loading times.


import bpy, os, struct, random, re, time, math, mathutils
from datetime import datetime
from myfile import *

def objectCompare(x, y):
if x.parent == y.parent:
return 0

if x.parent == None:
return -1

if y.parent == None:
return 1

return objectCompare(x.parent, y.parent)

def writeString(out, name):
if len(name) == 0:
out.write(struct.pack('i', 0))
else:
out.write(struct.pack('i', len(name)))
out.write(name.encode('utf8'))

total_vertices_count = 0
total_indices_count = 0
materialIndices = dict()
meshIndices = dict()
lampIndices = dict()

def writeMaterials(out):
materials = [ma for ma in bpy.data.materials.values()] # if ma.users > 0

for i, ma in enumerate(materials):
materialNode = OutNode("material", [])

materialIndices[ma.name] = i

materialNode.data.append(
OutNode("name", bytes(ma.name.encode('utf8'))))

materialNode.data.append(
OutNode("alpha", struct.pack('f', ma.alpha)))

materialNode.data.append(
OutNode("emit", struct.pack('f', ma.emit)))

materialNode.data.append(
OutNode("diffuse",
struct.pack('f', ma.diffuse_color.r) +
struct.pack('f', ma.diffuse_color.g) +
struct.pack('f', ma.diffuse_color.b)))

materialNode.data.append(
OutNode("specular",
struct.pack('f', ma.specular_color.r) +
struct.pack('f', ma.specular_color.g) +
struct.pack('f', ma.specular_color.b)))

materialNode.data.append(
OutNode("specular_intensity",
struct.pack('f', ma.specular_intensity)))

#material textures
# mts = [mt for mt in ma.texture_slots if mt != None and mt.texture != None and mt.texture.type == 'IMAGE']

# out.write(struct.pack('i', len(mts))) #material_textures_num

# for mt in mts:
# #out.write(struct.pack('i', textureIndices[mt.tex.name])) #material_texture_index
# writeString(out, mt.texture.name)
# writeString(out, mt.uv_layer)
# writeString(out, re.sub('(\\\)', '/', mt.texture.image.filename if mt.texture.image.filename[0:2] != '//' else mt.texture.image.filename[2:]))

materialNode.write(out)

def writeMeshes(out):
global total_vertices_count
global total_indices_count

meshes = [me for me in bpy.data.meshes.values()
if me.users > 0 and len(me.faces) > 0]

for i,me in enumerate(meshes):
meshNode = OutNode("mesh", [])

meshIndices[me.name] = i

meshNode.data.append(
OutNode("name", bytes(me.name.encode('utf8'))))

colLayerNames = me.vertex_colors
uvLayerNames = me.uv_textures

#tangents = [] #[uvLayer_ind][faceInd][faceVertInd] = tangent
#smooth_tangents = [[Vector(0,0,0) for v in me.vertices] for u in uvLayerNames] #[uvLayer_ind][meshVertInd] = smooth_tangent
#smooth_tangent_sums = [[0 for v in me.vertices] for u in uvLayerNames] #[uvLayer_ind][meshVertInd] = smooth_tangent_sum

#todo
# #get + store tangents
# for uvLayerName in uvLayerNames:
# me.activeUVLayer = uvLayerName
# tangents.append(me.getTangents())

# #get + store smooth_tangents
# for faceInd, face in enumerate(me.faces):
# for fvInd,fv in enumerate(face.vertices):
# for uvLayerInd, uvLayerName in enumerate(uvLayerNames):
# smooth_tangents[uvLayerInd][fv.index] += tangents[uvLayerInd][faceInd][fvInd]
# smooth_tangent_sums[uvLayerInd][fv.index] += 1

# for a in range(0,len(uvLayerNames)):
# for b in range(0, len(me.vertices)):
# #print(smooth_tangents[a], smooth_tangent_sums[a])
# smooth_tangents[a] /= smooth_tangent_sums[a]

# for a in range(0,len(uvLayerNames)):
# for b in range(0, len(me.vertices)):
# smooth_tangents[a] = smooth_tangents[a].normalize()
# #print(smooth_tangents[a])


#
out_positions = []
out_normals = []
out_texCoords = [[] for n in uvLayerNames] #[uvLayer][out_vertInd] = texCoord
out_tangents = [[] for n in uvLayerNames] #[uvLayer][out_vertInd] = tangent
out_colors = [[] for n in colLayerNames] #[colLayer][out_vertInd] = color
out_indices = [[]] if len(me.materials) == 0 else [[] for ma in me.materials] #[meMaInd] = face_indices
out_vertInds = dict() #['p n tcs tgs cs'] = out_vertexInd

#get out verts
for faceInd, face in enumerate(me.faces):
triIndices = [[0,1,2]]

if len(face.vertices) == 4:
triIndices.append([0,2,3])

for triIndex in triIndices:
for faceVecIndex in triIndex:
key = ''

#position
p = me.vertices[face.vertices[faceVecIndex]].co
key += '%f %f %f '%(p.x,p.y,p.z)

#normal
n = (me.vertices[face.vertices[faceVecIndex]].normal if face.use_smooth == 1 else face.normal).normalized()
key += '%f %f %f '%(n.x,n.y,n.z)

#texCoord
# tcs = []

# for uvLayerInd, uvLayerName in enumerate(uvLayerNames):
# me.activeUVLayer = uvLayerName
# tc = face.uv[faceVecIndex]
# key += '%f %f '%(tc[0],tc[1])
# tcs.append(tc)

#tangent
# tgs = []

# for uvLayerInd, uvLayerName in enumerate(uvLayerNames):
# me.activeUVLayer = uvLayerName
# tg = smooth_tangents[uvLayerInd][face.vertices[faceVecIndex].index] if face.use_smooth == 1 else tangents[uvLayerInd][faceInd][faceVecIndex] #tangents[uvLayerInd][faceInd][faceVecIndex] #
# key += '%f %f %f '%(tg.x,tg.y,tg.z)
# tgs.append(tg)

#color
# cs = []

# for colLayerInd, colLayerName in enumerate(colLayerNames):
# me.activeColorLayer = colLayerName
# c = face.col[faceVecIndex]
# key += '%i %i %i %i '%(c[0],c[1],c[2],c[3])
# cs.append(c)

#
if key not in out_vertInds:
out_vertInds[key] = len(out_vertInds)
out_positions.append(p)
out_normals.append(n)

# for k in range(0,len(uvLayerNames)):
# out_texCoords[k].append(tcs[k])
# out_tangents[k].append(tgs[k])

# for k in range(0,len(colLayerNames)):
# out_colors[k].append(cs[k])

out_indices[face.material_index].append(out_vertInds[key])

#
indicesNum = 0

for meMatIndices in out_indices:
indicesNum += len(meMatIndices)

#
total_vertices_count += len(out_vertInds)
total_indices_count += indicesNum

#
meshNode.data.append(OutNode("vertices_num", struct.pack('i', len(out_vertInds))))
meshNode.data.append(OutNode("indices_num", struct.pack('i', indicesNum)))
positionsData = b""
normalsData = b""
indicesData = b""

#write positions
for p in out_positions:

positionsData += struct.pack('f', p.y)
positionsData += struct.pack('f', p.z)
positionsData += struct.pack('f', p.x)

meshNode.data.append(OutNode("positions", positionsData))

#write normals
for n in out_normals:
normalsData += struct.pack('f', n.y)
normalsData += struct.pack('f', n.z)
normalsData += struct.pack('f', n.x)

meshNode.data.append(OutNode("normals", normalsData))

#write uvLayersNum
#out.write(struct.pack('i',len(uvLayerNames)))

#
# for uvLayerInd, uvLayerName in enumerate(uvLayerNames):
# #write uvLayerName
# writeString(out, uvLayerNames[uvLayerInd])

# #write texCoords
# for tc in out_texCoords[uvLayerInd]:
# out.write(struct.pack('f', tc[0]))
# out.write(struct.pack('f', tc[1]))

# #write tangents
# for tg in out_tangents[uvLayerInd]:
# out.write(struct.pack('f', 0))
# out.write(struct.pack('f', 0))
# out.write(struct.pack('f', 1))

# #out.write(struct.pack('f', tg.y))
# #out.write(struct.pack('f', tg.z))
# #out.write(struct.pack('f', tg.x))

# #write bitangents
# for i in range(0,len(out_vertInds)):
# btg = out_normals.cross(out_tangents[uvLayerInd]).normalize()
# out.write(struct.pack('f', btg.y))
# out.write(struct.pack('f', btg.z))
# out.write(struct.pack('f', btg.x))

#write colLayersNum
#out.write(struct.pack('i',len(colLayerNames)))

#
# for colLayerInd, colLayerName in enumerate(colLayerNames):
# #write colLayerName
# writeString(out, colLayerNames[colLayerInd])

# #write colors
# for c in out_colors[colLayerInd]:
# out.write(struct.pack('f', c[0]/255.0))
# out.write(struct.pack('f', c[1]/255.0))
# out.write(struct.pack('f', c[2]/255.0))
# out.write(struct.pack('f', c[3]/255.0))

#write indices
for meMatIndices in out_indices:
for i in meMatIndices:
indicesData += struct.pack('I', i)

meshNode.data.append(OutNode("indices", indicesData))

# #write subsetsNum
# out.write(struct.pack('i',len(me.materials)))

# #subsets
# subsetIndicesStart = 0

# for meMaInd, meMa in enumerate(me.materials):
# subset_indicesNum = len(out_indices[meMaInd])

# #write maInd
# out.write(struct.pack('i',materialIndices[meMa.name]))

# #write indicesStart
# out.write(struct.pack('i',subsetIndicesStart))

# #write indicesNum
# out.write(struct.pack('i',subset_indicesNum))

# #
# subsetIndicesStart += subset_indicesNum


# #shape info, for physics
# if True:
# points = []
# pointIndices = dict()
# shapeIndices = []

# vertPointIndices = []

# for v in me.vertices:
# k = '%f %f %f'%(v.co.x,v.co.y,v.co.z)

# if k not in pointIndices:
# pointIndices[k] = len(points)
# points.append(v.co)

# vertPointIndices.append(pointIndices[k])

# for f in me.faces:
# inds = [[0,1,2],[0,2,3]] if len(f.vertices) == 4 else [[0,1,2]]

# for ind in inds:
# for a in ind:
# shapeIndices.append(vertPointIndices[f.vertices[a]])

# #
# radius2 = 0
# radiusX2 = 0
# radiusY2 = 0
# radiusZ2 = 0

# x = 0
# y = 0
# z = 0

# posX = 0
# posY = 0
# posZ = 0

# negX = 0
# negY = 0
# negZ = 0

# for p in points:
# yz = mathutils.Vector((0,p.y,p.z))
# xz = mathutils.Vector((p.x,0,p.z))
# xy = mathutils.Vector((p.x,p.y,0))

# #
# new_radius2 = p.dot(p)

# if new_radius2 > radius2:
# radius2 = new_radius2

# #
# new_radiusX2 = yz.dot(yz)

# if new_radiusX2 > radiusX2:
# radiusX2 = new_radiusX2

# #
# new_radiusY2 = xz.dot(xz)

# if new_radiusY2 > radiusY2:
# radiusY2 = new_radiusY2

# #
# new_radiusZ2 = xy.dot(xy)

# if new_radiusZ2 > radiusZ2:
# radiusZ2 = new_radiusZ2

# #
# if p.x > posX:
# posX = p.x

# if p.x < negX:
# negX = p.x

# if abs(p.x) > x:
# x = abs(p.x)

# #
# if p.y > posY:
# posY = p.y

# if p.y < negY:
# negY = p.y

# if abs(p.y) > y:
# y = abs(p.y)
# #
# if p.z > posZ:
# posZ = p.z

# if p.z < negZ:
# negZ = p.z

# if abs(p.z) > z:
# z = abs(p.z)

# #
# out.write(struct.pack('d', x))
# out.write(struct.pack('d', y))
# out.write(struct.pack('d', z))

# out.write(struct.pack('d', posX))
# out.write(struct.pack('d', posY))
# out.write(struct.pack('d', posZ))

# out.write(struct.pack('d', negX))
# out.write(struct.pack('d', negY))
# out.write(struct.pack('d', negZ))

# out.write(struct.pack('d', math.sqrt(radius2)))
# out.write(struct.pack('d', math.sqrt(radiusX2)))
# out.write(struct.pack('d', math.sqrt(radiusY2)))
# out.write(struct.pack('d', math.sqrt(radiusZ2)))

# #
# out.write(struct.pack('i', len(points)))

# #
# for p in points:
# out.write(struct.pack('d', p.y))
# out.write(struct.pack('d', p.z))
# out.write(struct.pack('d', p.x))

# #
# for i in shapeIndices:
# out.write(struct.pack('I', i))
meshNode.write(out)

# def writeLamps(out):
# #LampTypes = [k.lower() for k,v in Lamp.Types.items()]

# lamps = [la for la in bpy.data.lamps.values() if la.users > 0]

# out.write(struct.pack('i', len(lamps)))

# for laInd, la in enumerate(lamps):
# lampIndices[la.name] = laInd

# writeString(out, la.name)

# writeString(out, la.type)


# out.write(struct.pack('f', la.color.r))
# out.write(struct.pack('f', la.color.g))
# out.write(struct.pack('f', la.color.b))
# out.write(struct.pack('f', la.distance))
# out.write(struct.pack('f', la.energy))


# if la.type == 'POINT':
# ""
# elif la.type == 'SUN':
# ""
# elif la.type == 'SPOT':
# ""
# elif la.type == 'HEMI':
# ""
# elif la.type == 'AREA':
# ""

# #out.write(struct.pack('f', la.quad1))
# #out.write(struct.pack('f', la.quad2))
# #out.write(struct.pack('f', la.spotSize))
# #out.write(struct.pack('f', la.spotBlend))

def writeObjects(out):
objects = [ob for ob in bpy.data.objects.values() if ob.users > 0]
#objects.sort(objectCompare)

objectIndices = dict()

for obInd, ob in enumerate(objects):
objectNode = OutNode("object", [])
objectNode.data.append(OutNode("name", bytes(ob.name.encode('utf8'))))

objectIndices[ob.name] = obInd

if ob.parent != None:
objectNode.data.append(OutNode("parent_index", struct.pack('i', objectIndices[ob.parent.name])))

objectNode.data.append(OutNode("position", struct.pack('f', ob.location[1]) +
struct.pack('f', ob.location[2]) + struct.pack('f', ob.location[0])))

objectNode.data.append(OutNode("axis_angle", struct.pack('f', ob.rotation_axis_angle[1]) +
struct.pack('f', ob.rotation_axis_angle[2]) + struct.pack('f', ob.rotation_axis_angle[0]) +
struct.pack('f', ob.rotation_axis_angle[3])))

objectNode.data.append(OutNode("scale", struct.pack('f', ob.scale[1]) +
struct.pack('f', ob.scale[2]) + struct.pack('f', ob.scale[0])))

if ob.type == 'MESH':
objectNode.data.append(OutNode("mesh_index", struct.pack('i', meshIndices[ob.data.name])))

objectNode.write(out)

def main():

fileName = 'untitled.model' if bpy.data.filepath == '' else os.path.splitext(bpy.data.filepath)[0]+".model"

#Window.DrawProgressBar (0.0, '')
#Window.DrawProgressBar (0.9, 'Exporting...')

t = time.time()

out = open(fileName, 'wb')

#writeTextures(out)
writeMaterials(out)
writeMeshes(out)
#writeLamps(out)
writeObjects(out)
out.close()

print(datetime.now().strftime("%H:%M:%S") + " Export to %s took %s secs with %i verts, %i tris."%(os.path.basename(fileName), str(round(time.time() - t,4)), total_vertices_count, total_indices_count/3))
#Window.DrawProgressBar (1.0, '')


if __name__ == "__main__":
main()

#http://www.blender.org/documentation/blender_python_api_2_57_release/bpy.types.html
"""
with open("D:/temp/oldocs/App/model_export.py", "r") as fh:
exec(fh.read()+"\n", globals(), locals())
"""






Right now the exporter only exports meshes (positions, normals and indices), objects (position, scale, rotation, name, etc), and some material info.




You should just look at my code to get an idea, since explaining the file format and loader might be too much hassle, especially since the loader is written in scheme.


Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement