forked from bartvdbraak/blender
fixed many errors in Cal3D that didnt show up with the testmodel I was using.
Mostly problems with vertex index, and splitting off new verts. removing truespace_export.py truespace_import.py, (decieded by letterrip and myself) both truespace and blender have enough formats in common that we dont need to support this format thats spesific to truespace and not used for 3d data interchange.
This commit is contained in:
parent
dae5f38f55
commit
b655d5e817
@ -433,28 +433,29 @@ class Cal3DSubMesh(object):
|
||||
self.springs = []
|
||||
self.id = id
|
||||
|
||||
def getVertex(self, blend_mesh, blend_index, loc, normal, maps):
|
||||
def getVertex(self, blend_mesh, blend_index, loc, normal, maps):
|
||||
|
||||
index_map = self.vert_mapping.get(blend_index)
|
||||
|
||||
if index_map == None:
|
||||
self.vert_mapping[blend_index] = self.vert_count
|
||||
vertex = Cal3DVertex(loc, normal, maps, blend_mesh.getVertexInfluences(blend_index))
|
||||
self.vertices.append([vertex])
|
||||
self.vert_mapping[blend_index] = len(self.vert_mapping)
|
||||
self.vert_count +=1
|
||||
return vertex
|
||||
else:
|
||||
vertex_list = self.vertices[index_map]
|
||||
|
||||
for v in vertex_list:
|
||||
#print "TEST", v.normal, normal
|
||||
if v.normal == normal and\
|
||||
v.maps == maps:
|
||||
# print "reuseing"
|
||||
return v
|
||||
return v # reusing
|
||||
|
||||
# No match, add a new vert
|
||||
# Use the first verts influences
|
||||
vertex = Cal3DVertex(coord, normal, uv, vertex_list[0].influences)
|
||||
vertex = Cal3DVertex(loc, normal, maps, vertex_list[0].influences)
|
||||
vertex_list.append(vertex)
|
||||
# self.vert_mapping[blend_index] = len(self.vert_mapping)
|
||||
self.vert_count +=1
|
||||
return vertex
|
||||
|
||||
@ -554,11 +555,7 @@ class Cal3DSubMesh(object):
|
||||
self.faces = new_faces
|
||||
|
||||
print "LODs computed : %s vertices can be removed (from a total of %s)." % (self.nb_lodsteps, len(self.vertices))
|
||||
|
||||
def rename_vertices(self, new_vertices):
|
||||
"""Rename (change ID) of all vertices, such as self.vertices == new_vertices."""
|
||||
for i in xrange(len(new_vertices)): new_vertices[i].id = i
|
||||
self.vertices = new_vertices
|
||||
|
||||
|
||||
def writeCal3D(self, file, matrix, matrix_normal):
|
||||
|
||||
@ -597,28 +594,35 @@ class Cal3DVertex(object):
|
||||
|
||||
self.id = -1
|
||||
|
||||
self.influences = []
|
||||
# should this really be a warning? (well currently enabled,
|
||||
# because blender has some bugs where it doesn't return
|
||||
# influences in python api though they are set, and because
|
||||
# cal3d<=0.9.1 had bugs where objects without influences
|
||||
# aren't drawn.
|
||||
#if not blend_influences:
|
||||
# print 'A vertex of object "%s" has no influences.\n(This occurs on objects placed in an invisible layer, you can fix it by using a single layer)' % ob.name
|
||||
|
||||
# sum of influences is not always 1.0 in Blender ?!?!
|
||||
sum = 0.0
|
||||
for bone_name, weight in blend_influences:
|
||||
sum += weight
|
||||
|
||||
for bone_name, weight in blend_influences:
|
||||
bone = BONES.get(bone_name)
|
||||
if not bone: # keys
|
||||
# print 'Couldnt find bone "%s" which influences object "%s"' % (bone_name, ob.name)
|
||||
continue
|
||||
if len(blend_influences) == 0 or isinstance(blend_influences[0], Cal3DInfluence):
|
||||
# This is a copy from another vert
|
||||
self.influences = blend_influences
|
||||
else:
|
||||
# Pass the blender influences
|
||||
|
||||
if weight:
|
||||
self.influences.append(Cal3DInfluence(BONES[bone_name], weight / sum))
|
||||
self.influences = []
|
||||
# should this really be a warning? (well currently enabled,
|
||||
# because blender has some bugs where it doesn't return
|
||||
# influences in python api though they are set, and because
|
||||
# cal3d<=0.9.1 had bugs where objects without influences
|
||||
# aren't drawn.
|
||||
#if not blend_influences:
|
||||
# print 'A vertex of object "%s" has no influences.\n(This occurs on objects placed in an invisible layer, you can fix it by using a single layer)' % ob.name
|
||||
|
||||
# sum of influences is not always 1.0 in Blender ?!?!
|
||||
sum = 0.0
|
||||
|
||||
for bone_name, weight in blend_influences:
|
||||
sum += weight
|
||||
|
||||
for bone_name, weight in blend_influences:
|
||||
bone = BONES.get(bone_name)
|
||||
if not bone: # keys
|
||||
# print 'Couldnt find bone "%s" which influences object "%s"' % (bone_name, ob.name)
|
||||
continue
|
||||
|
||||
if weight:
|
||||
self.influences.append(Cal3DInfluence(bone, weight / sum))
|
||||
|
||||
|
||||
def writeCal3D(self, file, matrix, matrix_normal):
|
||||
@ -838,7 +842,7 @@ class Cal3DKeyFrame(object):
|
||||
(self.quat[0], self.quat[1], self.quat[2], -self.quat[3]))
|
||||
file.write('\t\t</KEYFRAME>\n')
|
||||
|
||||
def export_cal3d(filename, PREF_SCALE=0.1, PREF_BAKE_MOTION = True, PREF_ACT_ACTION_ONLY=True):
|
||||
def export_cal3d(filename, PREF_SCALE=0.1, PREF_BAKE_MOTION = True, PREF_ACT_ACTION_ONLY=True, PREF_SCENE_FRAMES=False):
|
||||
if not filename.endswith('.cfg'):
|
||||
filename += '.cfg'
|
||||
|
||||
@ -892,7 +896,7 @@ def export_cal3d(filename, PREF_SCALE=0.1, PREF_BAKE_MOTION = True, PREF_ACT_ACT
|
||||
backup_action = blender_armature.action
|
||||
|
||||
ANIMATIONS = []
|
||||
SUPPORTED_IPOS = "QuatW", "QuatX", "QuatY", "QuatZ", "LocX", "LocY", "LocZ"
|
||||
SUPPORTED_IPOS = 'QuatW', 'QuatX', 'QuatY', 'QuatZ', 'LocX', 'LocY', 'LocZ'
|
||||
|
||||
if PREF_ACT_ACTION_ONLY: action_items = [(blender_armature.action.name, blender_armature.action)]
|
||||
else: action_items = Blender.Armature.NLA.GetActions().iteritems()
|
||||
@ -900,10 +904,14 @@ def export_cal3d(filename, PREF_SCALE=0.1, PREF_BAKE_MOTION = True, PREF_ACT_ACT
|
||||
for animation_name, blend_action in action_items:
|
||||
|
||||
# get frame range
|
||||
_frames = blend_action.getFrameNumbers()
|
||||
action_start= min(_frames);
|
||||
action_end= max(_frames);
|
||||
del _frames
|
||||
if PREF_SCENE_FRAMES:
|
||||
action_start= Blender.Get('staframe')
|
||||
action_end= Blender.Get('endframe')
|
||||
else:
|
||||
_frames = blend_action.getFrameNumbers()
|
||||
action_start= min(_frames);
|
||||
action_end= max(_frames);
|
||||
del _frames
|
||||
|
||||
if PREF_BAKE_MOTION:
|
||||
# We need to set the action active if we are getting baked data
|
||||
@ -947,10 +955,6 @@ def export_cal3d(filename, PREF_SCALE=0.1, PREF_BAKE_MOTION = True, PREF_ACT_ACT
|
||||
|
||||
#print pose_data[i][bone_name], i
|
||||
loc, quat = pose_data[i][bone_name]
|
||||
if bone_name == 'top':
|
||||
print 'myquat', quat
|
||||
#print 'rot', quat
|
||||
|
||||
|
||||
loc = vector_by_matrix_3x3(loc, bone.matrix)
|
||||
loc = vector_add(bone.loc, loc)
|
||||
@ -1076,23 +1080,26 @@ def export_cal3d_ui(filename):
|
||||
PREF_SCALE= Blender.Draw.Create(1.0)
|
||||
PREF_BAKE_MOTION = Blender.Draw.Create(1)
|
||||
PREF_ACT_ACTION_ONLY= Blender.Draw.Create(1)
|
||||
PREF_SCENE_FRAMES= Blender.Draw.Create(0)
|
||||
|
||||
block = [\
|
||||
('Scale: ', PREF_SCALE, 0.01, 100, "The scale to set in the Cal3d .cfg file (unsupported by soya)"),\
|
||||
('Baked Motion', PREF_BAKE_MOTION, 'use final pose position instead of ipo keyframes (IK and constraint support)'),\
|
||||
('Active Action', PREF_ACT_ACTION_ONLY, 'Only export the active action applied to this armature, otherwise export all'),\
|
||||
('Active Action', PREF_ACT_ACTION_ONLY, 'Only export action applied to this armature, else export all actions.'),\
|
||||
('Scene Frames', PREF_SCENE_FRAMES, 'Use scene frame range, else the actions start/end'),\
|
||||
]
|
||||
|
||||
if not Blender.Draw.PupBlock("Cal3D Options", block):
|
||||
return
|
||||
|
||||
Blender.Window.WaitCursor(1)
|
||||
export_cal3d(filename, 1.0/PREF_SCALE.val, PREF_BAKE_MOTION.val, PREF_ACT_ACTION_ONLY.val)
|
||||
export_cal3d(filename, 1.0/PREF_SCALE.val, PREF_BAKE_MOTION.val, PREF_ACT_ACTION_ONLY.val, PREF_SCENE_FRAMES.val)
|
||||
Blender.Window.WaitCursor(0)
|
||||
|
||||
|
||||
# import os
|
||||
#import os
|
||||
if __name__ == '__main__':
|
||||
Blender.Window.FileSelector(export_cal3d_ui, "Cal3D Export", Blender.Get('filename').replace('.blend', '.cfg'))
|
||||
#export_cal3d('/test' + '.cfg')
|
||||
#export_cal3d_ui('/test' + '.cfg')
|
||||
#os.system('cd /; wine /cal3d_miniviewer.exe /test.cfg')
|
||||
|
@ -1,339 +0,0 @@
|
||||
#!BPY
|
||||
|
||||
"""
|
||||
Name: 'TrueSpace (.cob)...'
|
||||
Blender: 232
|
||||
Group: 'Export'
|
||||
Tooltip: 'Export selected meshes to TrueSpace File Format (.cob)'
|
||||
"""
|
||||
|
||||
__author__ = "Anthony D'Agostino (Scorpius)"
|
||||
__url__ = ("blender", "elysiun",
|
||||
"Author's homepage, http://www.redrival.com/scorpius")
|
||||
__version__ = "Part of IOSuite 0.5"
|
||||
|
||||
__bpydoc__ = """\
|
||||
This script exports meshes to TrueSpace file format.
|
||||
|
||||
TrueSpace is a commercial modeling and rendering application. The .cob
|
||||
file format is composed of 'chunks,' is well defined, and easy to read and
|
||||
write. It's very similar to LightWave's lwo format.
|
||||
|
||||
Usage:<br>
|
||||
Select meshes to be exported and run this script from "File->Export" menu.
|
||||
|
||||
Supported:<br>
|
||||
Vertex colors will be exported, if they are present.
|
||||
|
||||
Known issues:<br>
|
||||
Before exporting to .cob format, the mesh must have real-time UV
|
||||
coordinates. Press the FKEY to assign them.
|
||||
|
||||
Notes:<br>
|
||||
There are a few differences between how Blender & TrueSpace represent
|
||||
their objects' transformation matrices. Blender simply uses a 4x4 matrix,
|
||||
and trueSpace splits it into the following two fields.
|
||||
|
||||
For the 'Local Axes' values: The x, y, and z-axis represent a simple
|
||||
rotation matrix. This is equivalent to Blender's object matrix before
|
||||
it was combined with the object's scaling matrix. Dividing each value by
|
||||
the appropriate scaling factor (and transposing at the same time)
|
||||
produces the original rotation matrix.
|
||||
|
||||
For the 'Current Position' values: This is equivalent to Blender's
|
||||
object matrix except that the last row is omitted and the xyz location
|
||||
is used in the last column. Binary format uses a 4x3 matrix, ascii
|
||||
format uses a 4x4 matrix.
|
||||
|
||||
For Cameras: The matrix here gets a little confusing, and I'm not sure of
|
||||
how to handle it.
|
||||
"""
|
||||
|
||||
# $Id$
|
||||
#
|
||||
# +---------------------------------------------------------+
|
||||
# | Copyright (c) 2001 Anthony D'Agostino |
|
||||
# | http://www.redrival.com/scorpius |
|
||||
# | scorpius@netzero.com |
|
||||
# | June 12, 2001 |
|
||||
# | Read and write Caligari trueSpace File Format (*.cob) |
|
||||
# +---------------------------------------------------------+
|
||||
|
||||
# ***** BEGIN GPL LICENSE BLOCK *****
|
||||
#
|
||||
# This program is free software; you can redistribute it and/or
|
||||
# modify it under the terms of the GNU General Public License
|
||||
# as published by the Free Software Foundation; either version 2
|
||||
# of the License, or (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU General Public License
|
||||
# along with this program; if not, write to the Free Software Foundation,
|
||||
# Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
|
||||
#
|
||||
# ***** END GPL LICENCE BLOCK *****
|
||||
|
||||
import Blender, meshtools
|
||||
import struct, cStringIO, time
|
||||
|
||||
# ==============================
|
||||
# === Write trueSpace Format ===
|
||||
# ==============================
|
||||
def write(filename):
|
||||
start = time.clock()
|
||||
file = open(filename, "wb")
|
||||
objects = Blender.Object.GetSelected()
|
||||
|
||||
write_header(file)
|
||||
|
||||
G,P,V,U,M = 1000,2000,3000,4000,5000
|
||||
for obj_index, obj in enumerate(objects):
|
||||
objname = obj.name
|
||||
meshname = obj.getData(name_only=1)
|
||||
mesh = Blender.NMesh.GetRaw(meshname)
|
||||
|
||||
if not mesh: continue
|
||||
|
||||
grou = generate_grou('Group ' + `obj_index+1`)
|
||||
polh = generate_polh(objname, obj, mesh)
|
||||
if meshtools.has_vertex_colors(mesh): vcol = generate_vcol(mesh)
|
||||
unit = generate_unit()
|
||||
mat1 = generate_mat1(mesh)
|
||||
|
||||
if obj_index == 0: X = 0
|
||||
|
||||
write_chunk(file, "Grou", 0, 1, G, X, grou)
|
||||
write_chunk(file, "PolH", 0, 4, P, G, polh)
|
||||
if meshtools.has_vertex_colors(mesh) and vcol:
|
||||
write_chunk(file, "VCol", 1, 0, V, P, vcol)
|
||||
write_chunk(file, "Unit", 0, 1, U, P, unit)
|
||||
write_chunk(file, "Mat1", 0, 5, M, P, mat1)
|
||||
|
||||
X = G
|
||||
G,P,V,U,M = map(lambda x: x+1, [G,P,V,U,M])
|
||||
|
||||
write_chunk(file, "END ", 1, 0, 0, 0, '') # End Of File Chunk
|
||||
|
||||
Blender.Window.DrawProgressBar(1.0, '') # clear progressbar
|
||||
file.close()
|
||||
end = time.clock()
|
||||
seconds = " in %.2f %s" % (end-start, "seconds")
|
||||
message = "Successfully exported " + filename.split('\\')[-1].split('/')[-1] + seconds
|
||||
meshtools.print_boxed(message)
|
||||
|
||||
# =============================
|
||||
# === Write COB File Header ===
|
||||
# =============================
|
||||
def write_header(file):
|
||||
file.write("Caligari V00.01BLH"+" "*13+"\n")
|
||||
|
||||
# ===================
|
||||
# === Write Chunk ===
|
||||
# ===================
|
||||
def write_chunk(file, name, major, minor, chunk_id, parent_id, data):
|
||||
file.write(name)
|
||||
file.write(struct.pack("<2h", major, minor))
|
||||
file.write(struct.pack("<2l", chunk_id, parent_id))
|
||||
file.write(struct.pack("<1l", len(data)))
|
||||
file.write(data)
|
||||
|
||||
# ============================================
|
||||
# === Generate PolH (Polygonal Data) Chunk ===
|
||||
# ============================================
|
||||
def generate_polh(objname, obj, mesh):
|
||||
data = cStringIO.StringIO()
|
||||
write_ObjectName(data, objname)
|
||||
write_LocalAxes(data, obj)
|
||||
write_CurrentPosition(data, obj)
|
||||
write_VertexList(data, mesh)
|
||||
uvcoords = write_UVCoordsList(data, mesh)
|
||||
write_FaceList(data, mesh, uvcoords)
|
||||
return data.getvalue()
|
||||
|
||||
# === Write Object Name ===
|
||||
def write_ObjectName(data, objname):
|
||||
data.write(struct.pack("<h", 0)) # dupecount
|
||||
data.write(struct.pack("<h", len(objname)))
|
||||
data.write(objname)
|
||||
|
||||
# === Write Local Axes ===
|
||||
def write_LocalAxes(data, obj):
|
||||
mat = obj.mat
|
||||
data.write(struct.pack("<fff", mat[3][0], mat[3][1], mat[3][2]))
|
||||
data.write(struct.pack("<fff", mat[0][0]/obj.SizeX, mat[1][0]/obj.SizeX, mat[2][0]/obj.SizeX))
|
||||
data.write(struct.pack("<fff", mat[0][1]/obj.SizeY, mat[1][1]/obj.SizeY, mat[2][1]/obj.SizeY))
|
||||
data.write(struct.pack("<fff", mat[0][2]/obj.SizeZ, mat[1][2]/obj.SizeZ, mat[2][2]/obj.SizeZ))
|
||||
|
||||
# === Write Current Position ===
|
||||
def write_CurrentPosition(data, obj):
|
||||
mat = obj.mat
|
||||
data.write(struct.pack("<ffff", mat[0][0], mat[0][1], mat[0][2], mat[3][0]))
|
||||
data.write(struct.pack("<ffff", mat[1][0], mat[1][1], mat[1][2], mat[3][1]))
|
||||
data.write(struct.pack("<ffff", mat[2][0], mat[2][1], mat[2][2], mat[3][2]))
|
||||
|
||||
# === Write Vertex List ===
|
||||
def write_VertexList(data, mesh):
|
||||
data.write(struct.pack("<l", len(mesh.verts)))
|
||||
for i, v in enumerate(mesh.verts):
|
||||
if not i%100 and meshtools.show_progress:
|
||||
Blender.Window.DrawProgressBar(float(i)/len(mesh.verts), "Writing Verts")
|
||||
x, y, z = v.co
|
||||
data.write(struct.pack("<fff", -y, x, z))
|
||||
|
||||
# === Write UV Vertex List ===
|
||||
def write_UVCoordsList(data, mesh):
|
||||
if not mesh.hasFaceUV():
|
||||
data.write(struct.pack("<l", 1))
|
||||
data.write(struct.pack("<2f", 0,0))
|
||||
return {(0,0): 0}
|
||||
# === Default UV Coords (one image per face) ===
|
||||
# data.write(struct.pack("<l", 4))
|
||||
# data.write(struct.pack("<8f", 0,0, 0,1, 1,1, 1,0))
|
||||
# return {(0,0): 0, (0,1): 1, (1,1): 2, (1,0): 3}
|
||||
# === Default UV Coords (one image per face) ===
|
||||
|
||||
# === collect, remove duplicates, add indices, and write the uv list ===
|
||||
uvdata = cStringIO.StringIO()
|
||||
uvcoords = {}
|
||||
uvidx = 0
|
||||
for i, f in enumerate(mesh.faces):
|
||||
if not i%100 and meshtools.show_progress:
|
||||
Blender.Window.DrawProgressBar(float(i)/len(mesh.faces), "Writing UV Coords")
|
||||
numfaceverts = len(f)
|
||||
for j in xrange(numfaceverts-1, -1, -1): # Reverse order
|
||||
u,v = f.uv[j]
|
||||
if not uvcoords.has_key((u,v)):
|
||||
uvcoords[(u,v)] = uvidx
|
||||
uvidx += 1
|
||||
uvdata.write(struct.pack("<ff", u,v))
|
||||
uvdata = uvdata.getvalue()
|
||||
|
||||
numuvcoords = len(uvdata)/8
|
||||
data.write(struct.pack("<l", numuvcoords))
|
||||
data.write(uvdata)
|
||||
#print "Number of uvcoords:", numuvcoords, '=', len(uvcoords)
|
||||
return uvcoords
|
||||
|
||||
# === Write Face List ===
|
||||
def write_FaceList(data, mesh, uvcoords):
|
||||
data.write(struct.pack("<l", len(mesh.faces)))
|
||||
for i in xrange(len(mesh.faces)):
|
||||
if not i%100 and meshtools.show_progress:
|
||||
Blender.Window.DrawProgressBar(float(i)/len(mesh.faces), "Writing Faces")
|
||||
numfaceverts = len(mesh.faces[i].v)
|
||||
data.write(struct.pack("<B", 0x10)) # Cull Back Faces Flag
|
||||
data.write(struct.pack("<h", numfaceverts))
|
||||
data.write(struct.pack("<h", 0)) # Material Index
|
||||
for j in xrange(numfaceverts-1, -1, -1): # Reverse order
|
||||
index = mesh.faces[i].v[j].index
|
||||
if mesh.hasFaceUV():
|
||||
uv = mesh.faces[i].uv[j]
|
||||
uvidx = uvcoords[uv]
|
||||
else:
|
||||
uvidx = 0
|
||||
data.write(struct.pack("<ll", index, uvidx))
|
||||
|
||||
# ===========================================
|
||||
# === Generate VCol (Vertex Colors) Chunk ===
|
||||
# ===========================================
|
||||
def generate_vcol(mesh):
|
||||
data = cStringIO.StringIO()
|
||||
data.write(struct.pack("<l", len(mesh.faces)))
|
||||
uniquecolors = {}
|
||||
unique_alpha = {}
|
||||
for i in xrange(len(mesh.faces)):
|
||||
if not i%100 and meshtools.show_progress:
|
||||
Blender.Window.DrawProgressBar(float(i)/len(mesh.faces), "Writing Vertex Colors")
|
||||
numfaceverts = len(mesh.faces[i].v)
|
||||
data.write(struct.pack("<ll", i, numfaceverts))
|
||||
for j in xrange(numfaceverts-1, -1, -1): # Reverse order
|
||||
r = mesh.faces[i].col[j].r
|
||||
g = mesh.faces[i].col[j].g
|
||||
b = mesh.faces[i].col[j].b
|
||||
a = 100 # 100 is opaque in ts
|
||||
uniquecolors[(r,g,b)] = None
|
||||
unique_alpha[mesh.faces[i].col[j].a] = None
|
||||
data.write(struct.pack("<BBBB", r,g,b,a))
|
||||
|
||||
#print "uniquecolors:", uniquecolors.keys()
|
||||
#print "unique_alpha:", unique_alpha.keys()
|
||||
if len(uniquecolors) == 1:
|
||||
return None
|
||||
else:
|
||||
return data.getvalue()
|
||||
|
||||
# ==================================
|
||||
# === Generate Unit (Size) Chunk ===
|
||||
# ==================================
|
||||
def generate_unit():
|
||||
data = cStringIO.StringIO()
|
||||
data.write(struct.pack("<h", 2))
|
||||
return data.getvalue()
|
||||
|
||||
# ======================================
|
||||
# === Generate Mat1 (Material) Chunk ===
|
||||
# ======================================
|
||||
def generate_mat1(mesh):
|
||||
|
||||
def get_crufty_mesh_image():
|
||||
'''Crufty because it only uses 1 image
|
||||
'''
|
||||
if mesh.hasFaceUV():
|
||||
for f in me.faces:
|
||||
i = f.image
|
||||
if i:
|
||||
return i.filename
|
||||
|
||||
data = cStringIO.StringIO()
|
||||
data.write(struct.pack("<h", 0))
|
||||
data.write(struct.pack("<ccB", "p", "a", 0))
|
||||
data.write(struct.pack("<fff", 1.0, 1.0, 1.0)) # rgb (0.0 - 1.0)
|
||||
data.write(struct.pack("<fffff", 1, 1, 0, 0, 1))
|
||||
|
||||
tex_mapname = get_crufty_mesh_image()
|
||||
|
||||
if tex_mapname:
|
||||
data.write("t:")
|
||||
data.write(struct.pack("<B", 0x00))
|
||||
data.write(struct.pack("<h", len(tex_mapname)))
|
||||
data.write(tex_mapname)
|
||||
data.write(struct.pack("<4f", 0,0, 1,1))
|
||||
return data.getvalue()
|
||||
|
||||
# ============================
|
||||
# === Generate Group Chunk ===
|
||||
# ============================
|
||||
def generate_grou(name):
|
||||
data = cStringIO.StringIO()
|
||||
write_ObjectName(data, name)
|
||||
data.write(struct.pack("<12f", 0,0,0, 1,0,0, 0,1,0, 0,0,1))
|
||||
data.write(struct.pack("<12f", 1,0,0,0, 0,1,0,0, 0,0,1,0))
|
||||
return data.getvalue()
|
||||
|
||||
def fs_callback(filename):
|
||||
if not filename.lower().endswith('.cob'): filename += '.cob'
|
||||
write(filename)
|
||||
|
||||
if __name__ == '__main__':
|
||||
Blender.Window.FileSelector(fs_callback, "Export COB", Blender.sys.makename(ext='.cob'))
|
||||
|
||||
# === Matrix Differences between Blender & trueSpace ===
|
||||
#
|
||||
# For the 'Local Axes' values:
|
||||
# The x, y, and z-axis represent a simple rotation matrix.
|
||||
# This is equivalent to Blender's object matrix before it was
|
||||
# combined with the object's scaling matrix. Dividing each value
|
||||
# by the appropriate scaling factor (and transposing at the same
|
||||
# time) produces the original rotation matrix.
|
||||
#
|
||||
# For the 'Current Position' values:
|
||||
# This is equivalent to Blender's object matrix except that the
|
||||
# last row is omitted and the xyz location is used in the last
|
||||
# column. Binary format uses a 4x3 matrix, ascii format uses a 4x4
|
||||
# matrix.
|
||||
#
|
||||
# For Cameras: The matrix is a little confusing.
|
@ -1,279 +0,0 @@
|
||||
#!BPY
|
||||
|
||||
"""
|
||||
Name: 'TrueSpace (.cob)...'
|
||||
Blender: 232
|
||||
Group: 'Import'
|
||||
Tooltip: 'Import TrueSpace Object File Format (.cob)'
|
||||
"""
|
||||
|
||||
__author__ = "Anthony D'Agostino (Scorpius)"
|
||||
__url__ = ("blender", "elysiun",
|
||||
"Author's homepage, http://www.redrival.com/scorpius")
|
||||
__version__ = "Part of IOSuite 0.5"
|
||||
|
||||
__bpydoc__ = """\
|
||||
This script imports TrueSpace files to Blender
|
||||
|
||||
TrueSpace is a commercial modeling and rendering application. The .cob
|
||||
file format is composed of 'chunks,' is well defined, and easy to read and
|
||||
write. It's very similar to LightWave's lwo format.
|
||||
|
||||
Usage:<br>
|
||||
Execute this script from the "File->Import" menu and choose a TrueSpace
|
||||
file to open.
|
||||
|
||||
Supported:<br>
|
||||
Meshes only. Supports UV Coordinates. COB files in ascii format can't be
|
||||
read.
|
||||
|
||||
Missing:<br>
|
||||
Materials, and Vertex Color info will be ignored.
|
||||
|
||||
Known issues:<br>
|
||||
Triangulation of convex polygons works fine, and uses a very simple
|
||||
fanning algorithm. Convex polygons (i.e., shaped like the letter "U")
|
||||
require a different algorithm, and will be triagulated incorrectly.
|
||||
|
||||
Notes:<br>
|
||||
There are a few differences between how Blender & TrueSpace represent
|
||||
their objects' transformation matrices. Blender simply uses a 4x4 matrix,
|
||||
and trueSpace splits it into the following two fields.
|
||||
|
||||
For the 'Local Axes' values: The x, y, and z-axis represent a simple
|
||||
rotation matrix. This is equivalent to Blender's object matrix before
|
||||
it was combined with the object's scaling matrix. Dividing each value by
|
||||
the appropriate scaling factor (and transposing at the same time)
|
||||
produces the original rotation matrix.
|
||||
|
||||
For the 'Current Position' values: This is equivalent to Blender's
|
||||
object matrix except that the last row is omitted and the xyz location
|
||||
is used in the last column. Binary format uses a 4x3 matrix, ascii
|
||||
format uses a 4x4 matrix.
|
||||
|
||||
For Cameras: The matrix here gets a little confusing, and I'm not sure of
|
||||
how to handle it.
|
||||
"""
|
||||
|
||||
# $Id$
|
||||
#
|
||||
# +---------------------------------------------------------+
|
||||
# | Copyright (c) 2001 Anthony D'Agostino |
|
||||
# | http://www.redrival.com/scorpius |
|
||||
# | scorpius@netzero.com |
|
||||
# | June 12, 2001 |
|
||||
# | Read and write Caligari trueSpace File Format (*.cob) |
|
||||
# +---------------------------------------------------------+
|
||||
|
||||
# ***** BEGIN GPL LICENSE BLOCK *****
|
||||
#
|
||||
# This program is free software; you can redistribute it and/or
|
||||
# modify it under the terms of the GNU General Public License
|
||||
# as published by the Free Software Foundation; either version 2
|
||||
# of the License, or (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU General Public License
|
||||
# along with this program; if not, write to the Free Software Foundation,
|
||||
# Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
|
||||
#
|
||||
# ***** END GPL LICENCE BLOCK *****
|
||||
|
||||
import Blender, meshtools
|
||||
import struct, chunk, os, cStringIO, time
|
||||
|
||||
# =======================
|
||||
# === COB Chunk Class ===
|
||||
# =======================
|
||||
class CobChunk(chunk.Chunk):
|
||||
def __init__(self, file, align = 0, bigendian = 0, inclheader = 0): #$ COB
|
||||
self.closed = 0
|
||||
self.align = align # whether to align to word (2-byte) boundaries
|
||||
if bigendian:
|
||||
strflag = '>'
|
||||
else:
|
||||
strflag = '<'
|
||||
self.file = file
|
||||
self.chunkname = file.read(4)
|
||||
if len(self.chunkname) < 4:
|
||||
raise EOFError
|
||||
self.major_ver, = struct.unpack(strflag+'h', file.read(2)) #$ COB
|
||||
self.minor_ver, = struct.unpack(strflag+'h', file.read(2)) #$ COB
|
||||
self.chunk_id, = struct.unpack(strflag+'l', file.read(4)) #$ COB
|
||||
self.parent_id, = struct.unpack(strflag+'l', file.read(4)) #$ COB
|
||||
try:
|
||||
self.chunksize = struct.unpack(strflag+'l', file.read(4))[0]
|
||||
except struct.error:
|
||||
raise EOFError
|
||||
if inclheader:
|
||||
self.chunksize = self.chunksize - 20 #$ COB
|
||||
self.size_read = 0
|
||||
try:
|
||||
self.offset = self.file.tell()
|
||||
except:
|
||||
self.seekable = 0
|
||||
else:
|
||||
self.seekable = 1
|
||||
|
||||
# ============================
|
||||
# === Read COB File Header ===
|
||||
# ============================
|
||||
def read_header(file):
|
||||
magic, = struct.unpack("<9s", file.read(9))
|
||||
version, = struct.unpack("<6s", file.read(6))
|
||||
format, = struct.unpack("<1c", file.read(1))
|
||||
endian, = struct.unpack("<2s", file.read(2))
|
||||
misc, = struct.unpack("13s", file.read(13))
|
||||
newline, = struct.unpack("<1B", file.read(1))
|
||||
return format
|
||||
|
||||
# ========================================
|
||||
# === Read PolH (Polygonal Data) Chunk ===
|
||||
# ========================================
|
||||
def read_polh(chunk):
|
||||
data = cStringIO.StringIO(chunk.read())
|
||||
oname = read_ObjectName(data)
|
||||
local = read_LocalAxes(data)
|
||||
crpos = read_CurrentPosition(data)
|
||||
verts = read_VertexList(data)
|
||||
uvcoords = read_UVCoords(data)
|
||||
faces, facesuv = read_FaceList(data, chunk)
|
||||
return verts, faces, oname, facesuv, uvcoords
|
||||
|
||||
# === Read Object Name ===
|
||||
def read_ObjectName(data):
|
||||
dupecount, namelen = struct.unpack("<hh", data.read(4))
|
||||
objname = data.read(namelen)
|
||||
if objname == '': objname = 'NoName'
|
||||
if dupecount > 0: objname = objname + ', ' + `dupecount`
|
||||
return objname
|
||||
|
||||
# === Read Local Axes ===
|
||||
def read_LocalAxes(data):
|
||||
location = struct.unpack("<fff", data.read(12))
|
||||
rotation_matrix=[]
|
||||
for i in xrange(3):
|
||||
row = struct.unpack("<fff", data.read(12))
|
||||
#print "% f % f % f" % row
|
||||
rotation_matrix.append(list(row))
|
||||
#print
|
||||
rotation_matrix = meshtools.transpose(rotation_matrix)
|
||||
|
||||
# === Read Current Position ===
|
||||
def read_CurrentPosition(data):
|
||||
transformation_matrix=[]
|
||||
for i in xrange(3):
|
||||
row = struct.unpack("<ffff", data.read(16))
|
||||
#print "% f % f % f % f" % row
|
||||
transformation_matrix.append(list(row))
|
||||
#print
|
||||
|
||||
# === Read Vertex List ===
|
||||
def read_VertexList(data):
|
||||
verts = []
|
||||
numverts, = struct.unpack("<l", data.read(4))
|
||||
for i in xrange(numverts):
|
||||
if not i%100 and meshtools.show_progress:
|
||||
Blender.Window.DrawProgressBar(float(i)/numverts, "Reading Verts")
|
||||
x, y, z = struct.unpack("<fff", data.read(12))
|
||||
verts.append((y, -x, z))
|
||||
return verts
|
||||
|
||||
# === Read UV Vertex List ===
|
||||
def read_UVCoords(data):
|
||||
uvcoords = []
|
||||
numuvcoords, = struct.unpack("<l", data.read(4))
|
||||
for i in xrange(numuvcoords):
|
||||
if not i%100 and meshtools.show_progress:
|
||||
Blender.Window.DrawProgressBar(float(i)/numuvcoords, "Reading UV Coords")
|
||||
uv = struct.unpack("<ff", data.read(8))
|
||||
uvcoords.append(uv)
|
||||
|
||||
#print "num uvcoords:", len(uvcoords)
|
||||
#for i in range(len(uvcoords)): print "%.4f, %.4f" % uvcoords[i]
|
||||
return uvcoords
|
||||
|
||||
# === Read Face List ===
|
||||
def read_FaceList(data, chunk):
|
||||
faces = [] ; facesuv = []
|
||||
numfaces, = struct.unpack("<l", data.read(4))
|
||||
for i in xrange(numfaces):
|
||||
if not i%100 and meshtools.show_progress:
|
||||
Blender.Window.DrawProgressBar(float(i)/numfaces, "Reading Faces")
|
||||
|
||||
face_flags, numfaceverts = struct.unpack("<Bh", data.read(3))
|
||||
|
||||
if (face_flags & 0x08) == 0x08:
|
||||
print "face #" + `i-1` + " contains a hole."
|
||||
pass
|
||||
else:
|
||||
data.read(2) # Material Index
|
||||
|
||||
facev = [] ; faceuv = []
|
||||
for j in xrange(numfaceverts):
|
||||
index, uvidx = struct.unpack("<ll", data.read(8))
|
||||
facev.append(index); faceuv.append(uvidx)
|
||||
facev.reverse() ; faceuv.reverse()
|
||||
faces.append(facev) ; facesuv.append(faceuv)
|
||||
|
||||
if chunk.minor_ver == 6:
|
||||
DrawFlags, RadiosityQuality = struct.unpack("<lh", data.read(6))
|
||||
if chunk.minor_ver == 8:
|
||||
DrawFlags, = struct.unpack("<l", data.read(4))
|
||||
|
||||
return faces , facesuv
|
||||
|
||||
# =============================
|
||||
# === Read trueSpace Format ===
|
||||
# =============================
|
||||
def read(filename):
|
||||
start = time.clock()
|
||||
file = open(filename, "rb")
|
||||
|
||||
# === COB header ===
|
||||
if read_header(file) == 'A':
|
||||
print "Can't read ASCII format"
|
||||
return
|
||||
|
||||
while 1:
|
||||
try:
|
||||
cobchunk = CobChunk(file)
|
||||
except EOFError:
|
||||
break
|
||||
if cobchunk.chunkname == "PolH":
|
||||
verts, faces, objname, facesuv, uvcoords = read_polh(cobchunk)
|
||||
meshtools.create_mesh(verts, faces, objname, facesuv, uvcoords)
|
||||
|
||||
'''
|
||||
object = Blender.Object.GetSelected()
|
||||
obj = Blender.Object.Get(objname)
|
||||
obj.loc = location
|
||||
obj.rot = meshtools.mat2euler(rotation_matrix)
|
||||
obj.size = (transformation_matrix[0][0]/rotation_matrix[0][0],
|
||||
transformation_matrix[1][1]/rotation_matrix[1][1],
|
||||
transformation_matrix[2][2]/rotation_matrix[2][2])
|
||||
|
||||
'''
|
||||
else:
|
||||
cobchunk.skip()
|
||||
|
||||
Blender.Window.DrawProgressBar(1.0, '') # clear progressbar
|
||||
file.close()
|
||||
end = time.clock()
|
||||
seconds = " in %.2f %s" % (end-start, "seconds")
|
||||
message = "Successfully imported " + os.path.basename(filename) + seconds
|
||||
meshtools.print_boxed(message)
|
||||
#print "objname :", objname
|
||||
#print "numverts:", len(verts)
|
||||
#print "numfaces:", len(faces)
|
||||
|
||||
def fs_callback(filename):
|
||||
read(filename)
|
||||
|
||||
if __name__ == '__main__':
|
||||
Blender.Window.FileSelector(fs_callback, "Import COB", '*.cob')
|
||||
|
Loading…
Reference in New Issue
Block a user