adding back changes from soc-2009-kaz branch.
This commit is contained in:
@@ -46,14 +46,35 @@ from the lib3ds project (http://lib3ds.sourceforge.net/) sourcecode.
|
||||
# Importing modules
|
||||
######################################################
|
||||
|
||||
import Blender
|
||||
import struct
|
||||
import os
|
||||
import time
|
||||
|
||||
import bpy
|
||||
from BPyMesh import getMeshFromObject
|
||||
from BPyObject import getDerivedObjects
|
||||
try:
|
||||
import struct
|
||||
except:
|
||||
struct = None
|
||||
|
||||
# import Blender
|
||||
# from BPyMesh import getMeshFromObject
|
||||
# from BPyObject import getDerivedObjects
|
||||
# try:
|
||||
# import struct
|
||||
# except:
|
||||
# struct = None
|
||||
|
||||
# also used by X3D exporter
|
||||
# return a tuple (free, object list), free is True if memory should be freed later with free_derived_objects()
|
||||
def create_derived_objects(ob):
|
||||
if ob.parent and ob.parent.dupli_type != 'NONE':
|
||||
return False, None
|
||||
|
||||
if ob.dupli_type != 'NONE':
|
||||
ob.create_dupli_list()
|
||||
return True, [(dob.object, dob.matrix) for dob in ob.dupli_list]
|
||||
else:
|
||||
return False, [(ob, ob.matrix)]
|
||||
|
||||
# also used by X3D exporter
|
||||
def free_derived_objects(ob):
|
||||
ob.free_dupli_list()
|
||||
|
||||
# So 3ds max can open files, limit names to 12 in length
|
||||
# this is verry annoying for filenames!
|
||||
@@ -85,61 +106,62 @@ def sane_name(name):
|
||||
|
||||
#Some of the chunks that we will export
|
||||
#----- Primary Chunk, at the beginning of each file
|
||||
PRIMARY= long("0x4D4D",16)
|
||||
PRIMARY= int("0x4D4D",16)
|
||||
|
||||
#------ Main Chunks
|
||||
OBJECTINFO = long("0x3D3D",16); #This gives the version of the mesh and is found right before the material and object information
|
||||
VERSION = long("0x0002",16); #This gives the version of the .3ds file
|
||||
KFDATA = long("0xB000",16); #This is the header for all of the key frame info
|
||||
OBJECTINFO = int("0x3D3D",16); #This gives the version of the mesh and is found right before the material and object information
|
||||
VERSION = int("0x0002",16); #This gives the version of the .3ds file
|
||||
KFDATA = int("0xB000",16); #This is the header for all of the key frame info
|
||||
|
||||
#------ sub defines of OBJECTINFO
|
||||
MATERIAL=45055 #0xAFFF // This stored the texture info
|
||||
OBJECT=16384 #0x4000 // This stores the faces, vertices, etc...
|
||||
|
||||
#>------ sub defines of MATERIAL
|
||||
MATNAME = long("0xA000",16); # This holds the material name
|
||||
MATAMBIENT = long("0xA010",16); # Ambient color of the object/material
|
||||
MATDIFFUSE = long("0xA020",16); # This holds the color of the object/material
|
||||
MATSPECULAR = long("0xA030",16); # SPecular color of the object/material
|
||||
MATSHINESS = long("0xA040",16); # ??
|
||||
MATMAP = long("0xA200",16); # This is a header for a new material
|
||||
MATMAPFILE = long("0xA300",16); # This holds the file name of the texture
|
||||
MATNAME = int("0xA000",16); # This holds the material name
|
||||
MATAMBIENT = int("0xA010",16); # Ambient color of the object/material
|
||||
MATDIFFUSE = int("0xA020",16); # This holds the color of the object/material
|
||||
MATSPECULAR = int("0xA030",16); # SPecular color of the object/material
|
||||
MATSHINESS = int("0xA040",16); # ??
|
||||
MATMAP = int("0xA200",16); # This is a header for a new material
|
||||
MATMAPFILE = int("0xA300",16); # This holds the file name of the texture
|
||||
|
||||
RGB1= long("0x0011",16)
|
||||
RGB2= long("0x0012",16)
|
||||
RGB1= int("0x0011",16)
|
||||
RGB2= int("0x0012",16)
|
||||
|
||||
#>------ sub defines of OBJECT
|
||||
OBJECT_MESH = long("0x4100",16); # This lets us know that we are reading a new object
|
||||
OBJECT_LIGHT = long("0x4600",16); # This lets un know we are reading a light object
|
||||
OBJECT_CAMERA= long("0x4700",16); # This lets un know we are reading a camera object
|
||||
OBJECT_MESH = int("0x4100",16); # This lets us know that we are reading a new object
|
||||
OBJECT_LIGHT = int("0x4600",16); # This lets un know we are reading a light object
|
||||
OBJECT_CAMERA= int("0x4700",16); # This lets un know we are reading a camera object
|
||||
|
||||
#>------ sub defines of CAMERA
|
||||
OBJECT_CAM_RANGES= long("0x4720",16); # The camera range values
|
||||
OBJECT_CAM_RANGES= int("0x4720",16); # The camera range values
|
||||
|
||||
#>------ sub defines of OBJECT_MESH
|
||||
OBJECT_VERTICES = long("0x4110",16); # The objects vertices
|
||||
OBJECT_FACES = long("0x4120",16); # The objects faces
|
||||
OBJECT_MATERIAL = long("0x4130",16); # This is found if the object has a material, either texture map or color
|
||||
OBJECT_UV = long("0x4140",16); # The UV texture coordinates
|
||||
OBJECT_TRANS_MATRIX = long("0x4160",16); # The Object Matrix
|
||||
OBJECT_VERTICES = int("0x4110",16); # The objects vertices
|
||||
OBJECT_FACES = int("0x4120",16); # The objects faces
|
||||
OBJECT_MATERIAL = int("0x4130",16); # This is found if the object has a material, either texture map or color
|
||||
OBJECT_UV = int("0x4140",16); # The UV texture coordinates
|
||||
OBJECT_TRANS_MATRIX = int("0x4160",16); # The Object Matrix
|
||||
|
||||
#>------ sub defines of KFDATA
|
||||
KFDATA_KFHDR = long("0xB00A",16);
|
||||
KFDATA_KFSEG = long("0xB008",16);
|
||||
KFDATA_KFCURTIME = long("0xB009",16);
|
||||
KFDATA_OBJECT_NODE_TAG = long("0xB002",16);
|
||||
KFDATA_KFHDR = int("0xB00A",16);
|
||||
KFDATA_KFSEG = int("0xB008",16);
|
||||
KFDATA_KFCURTIME = int("0xB009",16);
|
||||
KFDATA_OBJECT_NODE_TAG = int("0xB002",16);
|
||||
|
||||
#>------ sub defines of OBJECT_NODE_TAG
|
||||
OBJECT_NODE_ID = long("0xB030",16);
|
||||
OBJECT_NODE_HDR = long("0xB010",16);
|
||||
OBJECT_PIVOT = long("0xB013",16);
|
||||
OBJECT_INSTANCE_NAME = long("0xB011",16);
|
||||
POS_TRACK_TAG = long("0xB020",16);
|
||||
ROT_TRACK_TAG = long("0xB021",16);
|
||||
SCL_TRACK_TAG = long("0xB022",16);
|
||||
OBJECT_NODE_ID = int("0xB030",16);
|
||||
OBJECT_NODE_HDR = int("0xB010",16);
|
||||
OBJECT_PIVOT = int("0xB013",16);
|
||||
OBJECT_INSTANCE_NAME = int("0xB011",16);
|
||||
POS_TRACK_TAG = int("0xB020",16);
|
||||
ROT_TRACK_TAG = int("0xB021",16);
|
||||
SCL_TRACK_TAG = int("0xB022",16);
|
||||
|
||||
def uv_key(uv):
|
||||
return round(uv.x, 6), round(uv.y, 6)
|
||||
return round(uv[0], 6), round(uv[1], 6)
|
||||
# return round(uv.x, 6), round(uv.y, 6)
|
||||
|
||||
# size defines:
|
||||
SZ_SHORT = 2
|
||||
@@ -272,7 +294,8 @@ class _3ds_rgb_color(object):
|
||||
return 3
|
||||
|
||||
def write(self,file):
|
||||
file.write( struct.pack('<3c', chr(int(255*self.r)), chr(int(255*self.g)), chr(int(255*self.b)) ) )
|
||||
file.write( struct.pack('<3B', int(255*self.r), int(255*self.g), int(255*self.b) ) )
|
||||
# file.write( struct.pack('<3c', chr(int(255*self.r)), chr(int(255*self.g)), chr(int(255*self.b)) ) )
|
||||
|
||||
def __str__(self):
|
||||
return '{%f, %f, %f}' % (self.r, self.g, self.b)
|
||||
@@ -343,12 +366,12 @@ class _3ds_named_variable(object):
|
||||
def dump(self,indent):
|
||||
if (self.value!=None):
|
||||
spaces=""
|
||||
for i in xrange(indent):
|
||||
for i in range(indent):
|
||||
spaces+=" ";
|
||||
if (self.name!=""):
|
||||
print spaces, self.name, " = ", self.value
|
||||
print(spaces, self.name, " = ", self.value)
|
||||
else:
|
||||
print spaces, "[unnamed]", " = ", self.value
|
||||
print(spaces, "[unnamed]", " = ", self.value)
|
||||
|
||||
|
||||
#the chunk class
|
||||
@@ -408,9 +431,9 @@ class _3ds_chunk(object):
|
||||
Dump is used for debugging purposes, to dump the contents of a chunk to the standard output.
|
||||
Uses the dump function of the named variables and the subchunks to do the actual work.'''
|
||||
spaces=""
|
||||
for i in xrange(indent):
|
||||
for i in range(indent):
|
||||
spaces+=" ";
|
||||
print spaces, "ID=", hex(self.ID.value), "size=", self.get_size()
|
||||
print(spaces, "ID=", hex(self.ID.value), "size=", self.get_size())
|
||||
for variable in self.variables:
|
||||
variable.dump(indent+1)
|
||||
for subchunk in self.subchunks:
|
||||
@@ -424,14 +447,19 @@ class _3ds_chunk(object):
|
||||
|
||||
def get_material_images(material):
|
||||
# blender utility func.
|
||||
images = []
|
||||
if material:
|
||||
for mtex in material.getTextures():
|
||||
if mtex and mtex.tex.type == Blender.Texture.Types.IMAGE:
|
||||
image = mtex.tex.image
|
||||
if image:
|
||||
images.append(image) # maye want to include info like diffuse, spec here.
|
||||
return images
|
||||
return [s.texture.image for s in material.textures if s and s.texture.type == 'IMAGE' and s.texture.image]
|
||||
|
||||
return []
|
||||
# images = []
|
||||
# if material:
|
||||
# for mtex in material.getTextures():
|
||||
# if mtex and mtex.tex.type == Blender.Texture.Types.IMAGE:
|
||||
# image = mtex.tex.image
|
||||
# if image:
|
||||
# images.append(image) # maye want to include info like diffuse, spec here.
|
||||
# return images
|
||||
|
||||
|
||||
def make_material_subchunk(id, color):
|
||||
'''Make a material subchunk.
|
||||
@@ -454,7 +482,8 @@ def make_material_texture_chunk(id, images):
|
||||
mat_sub = _3ds_chunk(id)
|
||||
|
||||
def add_image(img):
|
||||
filename = image.filename.split('\\')[-1].split('/')[-1]
|
||||
filename = os.path.basename(image.filename)
|
||||
# filename = image.filename.split('\\')[-1].split('/')[-1]
|
||||
mat_sub_file = _3ds_chunk(MATMAPFILE)
|
||||
mat_sub_file.add_variable("mapfile", _3ds_string(sane_name(filename)))
|
||||
mat_sub.add_subchunk(mat_sub_file)
|
||||
@@ -482,9 +511,12 @@ def make_material_chunk(material, image):
|
||||
material_chunk.add_subchunk(make_material_subchunk(MATSPECULAR, (1,1,1) ))
|
||||
|
||||
else:
|
||||
material_chunk.add_subchunk(make_material_subchunk(MATAMBIENT, [a*material.amb for a in material.rgbCol] ))
|
||||
material_chunk.add_subchunk(make_material_subchunk(MATDIFFUSE, material.rgbCol))
|
||||
material_chunk.add_subchunk(make_material_subchunk(MATSPECULAR, material.specCol))
|
||||
material_chunk.add_subchunk(make_material_subchunk(MATAMBIENT, [a*material.ambient for a in material.diffuse_color] ))
|
||||
# material_chunk.add_subchunk(make_material_subchunk(MATAMBIENT, [a*material.amb for a in material.rgbCol] ))
|
||||
material_chunk.add_subchunk(make_material_subchunk(MATDIFFUSE, material.diffuse_color))
|
||||
# material_chunk.add_subchunk(make_material_subchunk(MATDIFFUSE, material.rgbCol))
|
||||
material_chunk.add_subchunk(make_material_subchunk(MATSPECULAR, material.specular_color))
|
||||
# material_chunk.add_subchunk(make_material_subchunk(MATSPECULAR, material.specCol))
|
||||
|
||||
images = get_material_images(material) # can be None
|
||||
if image: images.append(image)
|
||||
@@ -513,28 +545,39 @@ def extract_triangles(mesh):
|
||||
|
||||
If the mesh contains quads, they will be split into triangles.'''
|
||||
tri_list = []
|
||||
do_uv = mesh.faceUV
|
||||
do_uv = len(mesh.uv_textures)
|
||||
# do_uv = mesh.faceUV
|
||||
|
||||
if not do_uv:
|
||||
face_uv = None
|
||||
# if not do_uv:
|
||||
# face_uv = None
|
||||
|
||||
img = None
|
||||
for face in mesh.faces:
|
||||
f_v = face.v
|
||||
for i, face in enumerate(mesh.faces):
|
||||
f_v = face.verts
|
||||
# f_v = face.v
|
||||
|
||||
uf = mesh.active_uv_texture.data[i] if do_uv else None
|
||||
|
||||
if do_uv:
|
||||
f_uv = face.uv
|
||||
img = face.image
|
||||
f_uv = uf.uv
|
||||
# f_uv = (uf.uv1, uf.uv2, uf.uv3, uf.uv4) if face.verts[3] else (uf.uv1, uf.uv2, uf.uv3)
|
||||
# f_uv = face.uv
|
||||
img = uf.image if uf else None
|
||||
# img = face.image
|
||||
if img: img = img.name
|
||||
|
||||
# if f_v[3] == 0:
|
||||
if len(f_v)==3:
|
||||
new_tri = tri_wrapper((f_v[0].index, f_v[1].index, f_v[2].index), face.mat, img)
|
||||
new_tri = tri_wrapper((f_v[0], f_v[1], f_v[2]), face.material_index, img)
|
||||
# new_tri = tri_wrapper((f_v[0].index, f_v[1].index, f_v[2].index), face.mat, img)
|
||||
if (do_uv): new_tri.faceuvs= uv_key(f_uv[0]), uv_key(f_uv[1]), uv_key(f_uv[2])
|
||||
tri_list.append(new_tri)
|
||||
|
||||
else: #it's a quad
|
||||
new_tri = tri_wrapper((f_v[0].index, f_v[1].index, f_v[2].index), face.mat, img)
|
||||
new_tri_2 = tri_wrapper((f_v[0].index, f_v[2].index, f_v[3].index), face.mat, img)
|
||||
new_tri = tri_wrapper((f_v[0], f_v[1], f_v[2]), face.material_index, img)
|
||||
# new_tri = tri_wrapper((f_v[0].index, f_v[1].index, f_v[2].index), face.mat, img)
|
||||
new_tri_2 = tri_wrapper((f_v[0], f_v[2], f_v[3]), face.material_index, img)
|
||||
# new_tri_2 = tri_wrapper((f_v[0].index, f_v[2].index, f_v[3].index), face.mat, img)
|
||||
|
||||
if (do_uv):
|
||||
new_tri.faceuvs= uv_key(f_uv[0]), uv_key(f_uv[1]), uv_key(f_uv[2])
|
||||
@@ -555,11 +598,11 @@ def remove_face_uv(verts, tri_list):
|
||||
|
||||
# initialize a list of UniqueLists, one per vertex:
|
||||
#uv_list = [UniqueList() for i in xrange(len(verts))]
|
||||
unique_uvs= [{} for i in xrange(len(verts))]
|
||||
unique_uvs= [{} for i in range(len(verts))]
|
||||
|
||||
# for each face uv coordinate, add it to the UniqueList of the vertex
|
||||
for tri in tri_list:
|
||||
for i in xrange(3):
|
||||
for i in range(3):
|
||||
# store the index into the UniqueList for future reference:
|
||||
# offset.append(uv_list[tri.vertex_index[i]].add(_3ds_point_uv(tri.faceuvs[i])))
|
||||
|
||||
@@ -589,7 +632,7 @@ def remove_face_uv(verts, tri_list):
|
||||
|
||||
pt = _3ds_point_3d(vert.co) # reuse, should be ok
|
||||
uvmap = [None] * len(unique_uvs[i])
|
||||
for ii, uv_3ds in unique_uvs[i].itervalues():
|
||||
for ii, uv_3ds in unique_uvs[i].values():
|
||||
# add a vertex duplicate to the vertex_array for every uv associated with this vertex:
|
||||
vert_array.add(pt)
|
||||
# add the uv coordinate to the uv array:
|
||||
@@ -607,7 +650,7 @@ def remove_face_uv(verts, tri_list):
|
||||
|
||||
# Make sure the triangle vertex indices now refer to the new vertex list:
|
||||
for tri in tri_list:
|
||||
for i in xrange(3):
|
||||
for i in range(3):
|
||||
tri.offset[i]+=index_list[tri.vertex_index[i]]
|
||||
tri.vertex_index= tri.offset
|
||||
|
||||
@@ -626,7 +669,8 @@ def make_faces_chunk(tri_list, mesh, materialDict):
|
||||
face_list = _3ds_array()
|
||||
|
||||
|
||||
if mesh.faceUV:
|
||||
if len(mesh.uv_textures):
|
||||
# if mesh.faceUV:
|
||||
# Gather materials used in this mesh - mat/image pairs
|
||||
unique_mats = {}
|
||||
for i,tri in enumerate(tri_list):
|
||||
@@ -655,7 +699,7 @@ def make_faces_chunk(tri_list, mesh, materialDict):
|
||||
# obj_material_faces[tri.mat].add(_3ds_short(i))
|
||||
|
||||
face_chunk.add_variable("faces", face_list)
|
||||
for mat_name, mat_faces in unique_mats.itervalues():
|
||||
for mat_name, mat_faces in unique_mats.values():
|
||||
obj_material_chunk=_3ds_chunk(OBJECT_MATERIAL)
|
||||
obj_material_chunk.add_variable("name", mat_name)
|
||||
obj_material_chunk.add_variable("face_list", mat_faces)
|
||||
@@ -677,7 +721,7 @@ def make_faces_chunk(tri_list, mesh, materialDict):
|
||||
obj_material_faces[tri.mat].add(_3ds_short(i))
|
||||
|
||||
face_chunk.add_variable("faces", face_list)
|
||||
for i in xrange(n_materials):
|
||||
for i in range(n_materials):
|
||||
obj_material_chunk=_3ds_chunk(OBJECT_MATERIAL)
|
||||
obj_material_chunk.add_variable("name", obj_material_names[i])
|
||||
obj_material_chunk.add_variable("face_list", obj_material_faces[i])
|
||||
@@ -703,7 +747,8 @@ def make_mesh_chunk(mesh, materialDict):
|
||||
# Extract the triangles from the mesh:
|
||||
tri_list = extract_triangles(mesh)
|
||||
|
||||
if mesh.faceUV:
|
||||
if len(mesh.uv_textures):
|
||||
# if mesh.faceUV:
|
||||
# Remove the face UVs and convert it to vertex UV:
|
||||
vert_array, uv_array, tri_list = remove_face_uv(mesh.verts, tri_list)
|
||||
else:
|
||||
@@ -712,10 +757,13 @@ def make_mesh_chunk(mesh, materialDict):
|
||||
for vert in mesh.verts:
|
||||
vert_array.add(_3ds_point_3d(vert.co))
|
||||
# If the mesh has vertex UVs, create an array of UVs:
|
||||
if mesh.vertexUV:
|
||||
if len(mesh.sticky):
|
||||
# if mesh.vertexUV:
|
||||
uv_array = _3ds_array()
|
||||
for vert in mesh.verts:
|
||||
uv_array.add(_3ds_point_uv(vert.uvco))
|
||||
for uv in mesh.sticky:
|
||||
# for vert in mesh.verts:
|
||||
uv_array.add(_3ds_point_uv(uv.co))
|
||||
# uv_array.add(_3ds_point_uv(vert.uvco))
|
||||
else:
|
||||
# no UV at all:
|
||||
uv_array = None
|
||||
@@ -862,20 +910,25 @@ def make_kf_obj_node(obj, name_to_id):
|
||||
return kf_obj_node
|
||||
"""
|
||||
|
||||
import BPyMessages
|
||||
def save_3ds(filename):
|
||||
# import BPyMessages
|
||||
def save_3ds(filename, context):
|
||||
'''Save the Blender scene to a 3ds file.'''
|
||||
# Time the export
|
||||
|
||||
if not filename.lower().endswith('.3ds'):
|
||||
filename += '.3ds'
|
||||
|
||||
if not BPyMessages.Warning_SaveOver(filename):
|
||||
return
|
||||
# XXX
|
||||
# if not BPyMessages.Warning_SaveOver(filename):
|
||||
# return
|
||||
|
||||
time1= Blender.sys.time()
|
||||
Blender.Window.WaitCursor(1)
|
||||
sce= bpy.data.scenes.active
|
||||
# XXX
|
||||
time1 = time.clock()
|
||||
# time1= Blender.sys.time()
|
||||
# Blender.Window.WaitCursor(1)
|
||||
|
||||
sce = context.scene
|
||||
# sce= bpy.data.scenes.active
|
||||
|
||||
# Initialize the main chunk (primary):
|
||||
primary = _3ds_chunk(PRIMARY)
|
||||
@@ -901,22 +954,39 @@ def save_3ds(filename):
|
||||
# each material is added once):
|
||||
materialDict = {}
|
||||
mesh_objects = []
|
||||
for ob in sce.objects.context:
|
||||
for ob_derived, mat in getDerivedObjects(ob, False):
|
||||
data = getMeshFromObject(ob_derived, None, True, False, sce)
|
||||
for ob in [ob for ob in context.scene.objects if ob.is_visible()]:
|
||||
# for ob in sce.objects.context:
|
||||
|
||||
# get derived objects
|
||||
free, derived = create_derived_objects(ob)
|
||||
|
||||
if derived == None: continue
|
||||
|
||||
for ob_derived, mat in derived:
|
||||
# for ob_derived, mat in getDerivedObjects(ob, False):
|
||||
|
||||
if ob.type not in ('MESH', 'CURVE', 'SURFACE', 'TEXT', 'META'):
|
||||
continue
|
||||
|
||||
data = ob_derived.create_mesh(True, 'PREVIEW')
|
||||
# data = getMeshFromObject(ob_derived, None, True, False, sce)
|
||||
if data:
|
||||
data.transform(mat, recalc_normals=False)
|
||||
data.transform(mat)
|
||||
# data.transform(mat, recalc_normals=False)
|
||||
mesh_objects.append((ob_derived, data))
|
||||
mat_ls = data.materials
|
||||
mat_ls_len = len(mat_ls)
|
||||
|
||||
# get material/image tuples.
|
||||
if data.faceUV:
|
||||
if len(data.uv_textures):
|
||||
# if data.faceUV:
|
||||
if not mat_ls:
|
||||
mat = mat_name = None
|
||||
|
||||
for f in data.faces:
|
||||
for f, uf in zip(data.faces, data.active_uv_texture.data):
|
||||
if mat_ls:
|
||||
mat_index = f.mat
|
||||
mat_index = f.material_index
|
||||
# mat_index = f.mat
|
||||
if mat_index >= mat_ls_len:
|
||||
mat_index = f.mat = 0
|
||||
mat = mat_ls[mat_index]
|
||||
@@ -924,7 +994,8 @@ def save_3ds(filename):
|
||||
else: mat_name = None
|
||||
# else there alredy set to none
|
||||
|
||||
img = f.image
|
||||
img = uf.image
|
||||
# img = f.image
|
||||
if img: img_name = img.name
|
||||
else: img_name = None
|
||||
|
||||
@@ -938,11 +1009,17 @@ def save_3ds(filename):
|
||||
|
||||
# Why 0 Why!
|
||||
for f in data.faces:
|
||||
if f.mat >= mat_ls_len:
|
||||
f.mat = 0
|
||||
if f.material_index >= mat_ls_len:
|
||||
# if f.mat >= mat_ls_len:
|
||||
f.material_index = 0
|
||||
# f.mat = 0
|
||||
|
||||
if free:
|
||||
free_derived_objects(ob)
|
||||
|
||||
|
||||
# Make material chunks for all materials used in the meshes:
|
||||
for mat_and_image in materialDict.itervalues():
|
||||
for mat_and_image in materialDict.values():
|
||||
object_info.add_subchunk(make_material_chunk(mat_and_image[0], mat_and_image[1]))
|
||||
|
||||
# Give all objects a unique ID and build a dictionary from object name to object id:
|
||||
@@ -971,7 +1048,10 @@ def save_3ds(filename):
|
||||
# make a kf object node for the object:
|
||||
kfdata.add_subchunk(make_kf_obj_node(ob, name_to_id))
|
||||
'''
|
||||
blender_mesh.verts = None
|
||||
# if not blender_mesh.users:
|
||||
bpy.data.remove_mesh(blender_mesh)
|
||||
# blender_mesh.verts = None
|
||||
|
||||
i+=i
|
||||
|
||||
# Create chunks for all empties:
|
||||
@@ -1004,16 +1084,47 @@ def save_3ds(filename):
|
||||
file.close()
|
||||
|
||||
# Debugging only: report the exporting time:
|
||||
Blender.Window.WaitCursor(0)
|
||||
print "3ds export time: %.2f" % (Blender.sys.time() - time1)
|
||||
# Blender.Window.WaitCursor(0)
|
||||
print("3ds export time: %.2f" % (time.clock() - time1))
|
||||
# print("3ds export time: %.2f" % (Blender.sys.time() - time1))
|
||||
|
||||
# Debugging only: dump the chunk hierarchy:
|
||||
#primary.dump()
|
||||
|
||||
|
||||
if __name__=='__main__':
|
||||
if struct:
|
||||
Blender.Window.FileSelector(save_3ds, "Export 3DS", Blender.sys.makename(ext='.3ds'))
|
||||
else:
|
||||
Blender.Draw.PupMenu("Error%t|This script requires a full python installation")
|
||||
# save_3ds('/test_b.3ds')
|
||||
# if __name__=='__main__':
|
||||
# if struct:
|
||||
# Blender.Window.FileSelector(save_3ds, "Export 3DS", Blender.sys.makename(ext='.3ds'))
|
||||
# else:
|
||||
# Blender.Draw.PupMenu("Error%t|This script requires a full python installation")
|
||||
# # save_3ds('/test_b.3ds')
|
||||
|
||||
class EXPORT_OT_3ds(bpy.types.Operator):
|
||||
'''
|
||||
3DS Exporter
|
||||
'''
|
||||
__idname__ = "export.3ds"
|
||||
__label__ = 'Export 3DS'
|
||||
|
||||
# List of operator properties, the attributes will be assigned
|
||||
# to the class instance from the operator settings before calling.
|
||||
|
||||
__props__ = [
|
||||
# bpy.props.StringProperty(attr="filename", name="File Name", description="File name used for exporting the 3DS file", maxlen= 1024, default= ""),
|
||||
bpy.props.StringProperty(attr="path", name="File Path", description="File path used for exporting the 3DS file", maxlen= 1024, default= ""),
|
||||
]
|
||||
|
||||
def execute(self, context):
|
||||
save_3ds(self.path, context)
|
||||
return ('FINISHED',)
|
||||
|
||||
def invoke(self, context, event):
|
||||
wm = context.manager
|
||||
wm.add_fileselect(self.__operator__)
|
||||
return ('RUNNING_MODAL',)
|
||||
|
||||
def poll(self, context): # Poll isnt working yet
|
||||
print("Poll")
|
||||
return context.active_object != None
|
||||
|
||||
bpy.ops.add(EXPORT_OT_3ds)
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -1,16 +1,4 @@
|
||||
#!BPY
|
||||
|
||||
"""
|
||||
Name: 'Stanford PLY (*.ply)...'
|
||||
Blender: 241
|
||||
Group: 'Export'
|
||||
Tooltip: 'Export active object to Stanford PLY format'
|
||||
"""
|
||||
|
||||
import bpy
|
||||
import Blender
|
||||
from Blender import Mesh, Scene, Window, sys, Image, Draw
|
||||
import BPyMesh
|
||||
|
||||
__author__ = "Bruce Merry"
|
||||
__version__ = "0.93"
|
||||
@@ -62,84 +50,105 @@ Only one mesh can be exported at a time.
|
||||
def rvec3d(v): return round(v[0], 6), round(v[1], 6), round(v[2], 6)
|
||||
def rvec2d(v): return round(v[0], 6), round(v[1], 6)
|
||||
|
||||
def file_callback(filename):
|
||||
def write(filename, scene, ob, \
|
||||
EXPORT_APPLY_MODIFIERS= True,\
|
||||
EXPORT_NORMALS= True,\
|
||||
EXPORT_UV= True,\
|
||||
EXPORT_COLORS= True\
|
||||
):
|
||||
|
||||
if not filename.lower().endswith('.ply'):
|
||||
filename += '.ply'
|
||||
|
||||
scn= bpy.data.scenes.active
|
||||
ob= scn.objects.active
|
||||
if not ob:
|
||||
Blender.Draw.PupMenu('Error%t|Select 1 active object')
|
||||
raise Exception("Error, Select 1 active object")
|
||||
return
|
||||
|
||||
file = open(filename, 'wb')
|
||||
file = open(filename, 'w')
|
||||
|
||||
|
||||
EXPORT_APPLY_MODIFIERS = Draw.Create(1)
|
||||
EXPORT_NORMALS = Draw.Create(1)
|
||||
EXPORT_UV = Draw.Create(1)
|
||||
EXPORT_COLORS = Draw.Create(1)
|
||||
#EXPORT_EDGES = Draw.Create(0)
|
||||
|
||||
pup_block = [\
|
||||
('Apply Modifiers', EXPORT_APPLY_MODIFIERS, 'Use transformed mesh data.'),\
|
||||
('Normals', EXPORT_NORMALS, 'Export vertex normal data.'),\
|
||||
('UVs', EXPORT_UV, 'Export texface UV coords.'),\
|
||||
('Colors', EXPORT_COLORS, 'Export vertex Colors.'),\
|
||||
#('Edges', EXPORT_EDGES, 'Edges not connected to faces.'),\
|
||||
]
|
||||
|
||||
if not Draw.PupBlock('Export...', pup_block):
|
||||
return
|
||||
|
||||
"""
|
||||
is_editmode = Blender.Window.EditMode()
|
||||
if is_editmode:
|
||||
Blender.Window.EditMode(0, '', 0)
|
||||
|
||||
Window.WaitCursor(1)
|
||||
"""
|
||||
|
||||
EXPORT_APPLY_MODIFIERS = EXPORT_APPLY_MODIFIERS.val
|
||||
EXPORT_NORMALS = EXPORT_NORMALS.val
|
||||
EXPORT_UV = EXPORT_UV.val
|
||||
EXPORT_COLORS = EXPORT_COLORS.val
|
||||
#EXPORT_EDGES = EXPORT_EDGES.val
|
||||
|
||||
mesh = BPyMesh.getMeshFromObject(ob, None, EXPORT_APPLY_MODIFIERS, False, scn)
|
||||
#mesh = BPyMesh.getMeshFromObject(ob, None, EXPORT_APPLY_MODIFIERS, False, scn) # XXX
|
||||
if EXPORT_APPLY_MODIFIERS:
|
||||
mesh = ob.create_mesh(True, 'PREVIEW')
|
||||
else:
|
||||
mesh = ob.data
|
||||
|
||||
if not mesh:
|
||||
Blender.Draw.PupMenu('Error%t|Could not get mesh data from active object')
|
||||
raise ("Error, could not get mesh data from active object")
|
||||
return
|
||||
|
||||
mesh.transform(ob.matrixWorld)
|
||||
# mesh.transform(ob.matrixWorld) # XXX
|
||||
|
||||
faceUV = mesh.faceUV
|
||||
vertexUV = mesh.vertexUV
|
||||
vertexColors = mesh.vertexColors
|
||||
faceUV = len(mesh.uv_textures) > 0
|
||||
vertexUV = len(mesh.sticky) > 0
|
||||
vertexColors = len(mesh.vertex_colors) > 0
|
||||
|
||||
if (not faceUV) and (not vertexUV): EXPORT_UV = False
|
||||
if (not faceUV) and (not vertexUV): EXPORT_UV = False
|
||||
if not vertexColors: EXPORT_COLORS = False
|
||||
|
||||
if not EXPORT_UV: faceUV = vertexUV = False
|
||||
if not EXPORT_COLORS: vertexColors = False
|
||||
|
||||
if faceUV:
|
||||
active_uv_layer = None
|
||||
for lay in mesh.uv_textures:
|
||||
if lay.active:
|
||||
active_uv_layer= lay.data
|
||||
break
|
||||
if not active_uv_layer:
|
||||
EXPORT_UV = False
|
||||
faceUV = None
|
||||
|
||||
if vertexColors:
|
||||
active_col_layer = None
|
||||
for lay in mesh.vertex_colors:
|
||||
if lay.active:
|
||||
active_col_layer= lay.data
|
||||
if not active_col_layer:
|
||||
EXPORT_COLORS = False
|
||||
vertexColors = None
|
||||
|
||||
# incase
|
||||
color = uvcoord = uvcoord_key = normal = normal_key = None
|
||||
|
||||
verts = [] # list of dictionaries
|
||||
mesh_verts = mesh.verts # save a lookup
|
||||
ply_verts = [] # list of dictionaries
|
||||
# vdict = {} # (index, normal, uv) -> new index
|
||||
vdict = [{} for i in xrange(len(mesh.verts))]
|
||||
vdict = [{} for i in range(len(mesh_verts))]
|
||||
ply_faces = [[] for f in range(len(mesh.faces))]
|
||||
vert_count = 0
|
||||
for i, f in enumerate(mesh.faces):
|
||||
|
||||
|
||||
smooth = f.smooth
|
||||
if not smooth:
|
||||
normal = tuple(f.no)
|
||||
normal = tuple(f.normal)
|
||||
normal_key = rvec3d(normal)
|
||||
|
||||
if faceUV: uv = f.uv
|
||||
if vertexColors: col = f.col
|
||||
for j, v in enumerate(f):
|
||||
if faceUV:
|
||||
uv = active_uv_layer[i]
|
||||
uv = uv.uv1, uv.uv2, uv.uv3, uv.uv4 # XXX - crufty :/
|
||||
if vertexColors:
|
||||
col = active_col_layer[i]
|
||||
col = col.color1, col.color2, col.color3, col.color4
|
||||
|
||||
f_verts= f.verts
|
||||
|
||||
pf= ply_faces[i]
|
||||
for j, vidx in enumerate(f_verts):
|
||||
v = mesh_verts[vidx]
|
||||
|
||||
if smooth:
|
||||
normal= tuple(v.no)
|
||||
normal= tuple(v.normal)
|
||||
normal_key = rvec3d(normal)
|
||||
|
||||
if faceUV:
|
||||
@@ -149,33 +158,41 @@ def file_callback(filename):
|
||||
uvcoord= v.uvco[0], 1.0-v.uvco[1]
|
||||
uvcoord_key = rvec2d(uvcoord)
|
||||
|
||||
if vertexColors: color= col[j].r, col[j].g, col[j].b
|
||||
if vertexColors:
|
||||
color= col[j]
|
||||
color= int(color[0]*255.0), int(color[1]*255.0), int(color[2]*255.0)
|
||||
|
||||
|
||||
key = normal_key, uvcoord_key, color
|
||||
|
||||
vdict_local = vdict[v.index]
|
||||
vdict_local = vdict[vidx]
|
||||
pf_vidx = vdict_local.get(key) # Will be None initially
|
||||
|
||||
if (not vdict_local) or (not vdict_local.has_key(key)):
|
||||
vdict_local[key] = vert_count;
|
||||
verts.append( (tuple(v.co), normal, uvcoord, color) )
|
||||
if pf_vidx == None: # same as vdict_local.has_key(key)
|
||||
pf_vidx = vdict_local[key] = vert_count;
|
||||
ply_verts.append((vidx, normal, uvcoord, color))
|
||||
vert_count += 1
|
||||
|
||||
pf.append(pf_vidx)
|
||||
|
||||
file.write('ply\n')
|
||||
file.write('format ascii 1.0\n')
|
||||
file.write('comment Created by Blender3D %s - www.blender.org, source file: %s\n' % (Blender.Get('version'), Blender.Get('filename').split('/')[-1].split('\\')[-1] ))
|
||||
version = "2.5" # Blender.Get('version')
|
||||
file.write('comment Created by Blender3D %s - www.blender.org, source file: %s\n' % (version, bpy.data.filename.split('/')[-1].split('\\')[-1] ))
|
||||
|
||||
file.write('element vertex %d\n' % len(verts))
|
||||
file.write('element vertex %d\n' % len(ply_verts))
|
||||
|
||||
file.write('property float x\n')
|
||||
file.write('property float y\n')
|
||||
file.write('property float z\n')
|
||||
|
||||
# XXX
|
||||
"""
|
||||
if EXPORT_NORMALS:
|
||||
file.write('property float nx\n')
|
||||
file.write('property float ny\n')
|
||||
file.write('property float nz\n')
|
||||
|
||||
"""
|
||||
if EXPORT_UV:
|
||||
file.write('property float s\n')
|
||||
file.write('property float t\n')
|
||||
@@ -188,41 +205,75 @@ def file_callback(filename):
|
||||
file.write('property list uchar uint vertex_indices\n')
|
||||
file.write('end_header\n')
|
||||
|
||||
for i, v in enumerate(verts):
|
||||
file.write('%.6f %.6f %.6f ' % v[0]) # co
|
||||
for i, v in enumerate(ply_verts):
|
||||
file.write('%.6f %.6f %.6f ' % tuple(mesh_verts[v[0]].co)) # co
|
||||
"""
|
||||
if EXPORT_NORMALS:
|
||||
file.write('%.6f %.6f %.6f ' % v[1]) # no
|
||||
|
||||
if EXPORT_UV:
|
||||
file.write('%.6f %.6f ' % v[2]) # uv
|
||||
if EXPORT_COLORS:
|
||||
file.write('%u %u %u' % v[3]) # col
|
||||
"""
|
||||
if EXPORT_UV: file.write('%.6f %.6f ' % v[2]) # uv
|
||||
if EXPORT_COLORS: file.write('%u %u %u' % v[3]) # col
|
||||
file.write('\n')
|
||||
|
||||
for (i, f) in enumerate(mesh.faces):
|
||||
file.write('%d ' % len(f))
|
||||
smooth = f.smooth
|
||||
if not smooth: no = rvec3d(f.no)
|
||||
for pf in ply_faces:
|
||||
if len(pf)==3: file.write('3 %d %d %d\n' % tuple(pf))
|
||||
else: file.write('4 %d %d %d %d\n' % tuple(pf))
|
||||
|
||||
if faceUV: uv = f.uv
|
||||
if vertexColors: col = f.col
|
||||
for j, v in enumerate(f):
|
||||
if f.smooth: normal= rvec3d(v.no)
|
||||
else: normal= no
|
||||
if faceUV: uvcoord= rvec2d((uv[j][0], 1.0-uv[j][1]))
|
||||
elif vertexUV: uvcoord= rvec2d((v.uvco[0], 1.0-v.uvco[1]))
|
||||
if vertexColors: color= col[j].r, col[j].g, col[j].b
|
||||
|
||||
file.write('%d ' % vdict[v.index][normal, uvcoord, color])
|
||||
|
||||
file.write('\n')
|
||||
file.close()
|
||||
print("writing", filename, "done")
|
||||
|
||||
if EXPORT_APPLY_MODIFIERS:
|
||||
bpy.data.remove_mesh(mesh)
|
||||
|
||||
# XXX
|
||||
"""
|
||||
if is_editmode:
|
||||
Blender.Window.EditMode(1, '', 0)
|
||||
"""
|
||||
|
||||
class EXPORT_OT_ply(bpy.types.Operator):
|
||||
'''Export a single object as a stanford PLY with normals, colours and texture coordinates.'''
|
||||
__idname__ = "export.ply"
|
||||
__label__ = "Export PLY"
|
||||
|
||||
# List of operator properties, the attributes will be assigned
|
||||
# to the class instance from the operator settings before calling.
|
||||
|
||||
__props__ = [
|
||||
bpy.props.StringProperty(attr="path", name="File Path", description="File path used for exporting the PLY file", maxlen= 1024, default= ""),
|
||||
bpy.props.BoolProperty(attr="use_modifiers", name="Apply Modifiers", description="Apply Modifiers to the exported mesh", default= True),
|
||||
bpy.props.BoolProperty(attr="use_normals", name="Export Normals", description="Export Normals for smooth and hard shaded faces", default= True),
|
||||
bpy.props.BoolProperty(attr="use_uvs", name="Export UVs", description="Exort the active UV layer", default= True),
|
||||
bpy.props.BoolProperty(attr="use_colors", name="Export Vertex Colors", description="Exort the active vertex color layer", default= True)
|
||||
]
|
||||
|
||||
def poll(self, context):
|
||||
return context.active_object != None
|
||||
|
||||
def execute(self, context):
|
||||
# print("Selected: " + context.active_object.name)
|
||||
|
||||
if not self.path:
|
||||
raise Exception("filename not set")
|
||||
|
||||
write(self.path, context.scene, context.active_object,\
|
||||
EXPORT_APPLY_MODIFIERS = self.use_modifiers,
|
||||
EXPORT_NORMALS = self.use_normals,
|
||||
EXPORT_UV = self.use_uvs,
|
||||
EXPORT_COLORS = self.use_colors,
|
||||
)
|
||||
|
||||
return ('FINISHED',)
|
||||
|
||||
def invoke(self, context, event):
|
||||
wm = context.manager
|
||||
wm.add_fileselect(self.__operator__)
|
||||
return ('RUNNING_MODAL',)
|
||||
|
||||
|
||||
bpy.ops.add(EXPORT_OT_ply)
|
||||
|
||||
if __name__ == "__main__":
|
||||
bpy.ops.EXPORT_OT_ply(path="/tmp/test.ply")
|
||||
|
||||
def main():
|
||||
Blender.Window.FileSelector(file_callback, 'PLY Export', Blender.sys.makename(ext='.ply'))
|
||||
|
||||
if __name__=='__main__':
|
||||
main()
|
||||
|
||||
@@ -53,22 +53,30 @@ Known issues:<br>
|
||||
# Library dependancies
|
||||
####################################
|
||||
|
||||
import Blender
|
||||
from Blender import Object, Lamp, Draw, Image, Text, sys, Mesh
|
||||
from Blender.Scene import Render
|
||||
import math
|
||||
import BPyObject
|
||||
import BPyMesh
|
||||
import os
|
||||
|
||||
import bpy
|
||||
import Mathutils
|
||||
|
||||
from export_3ds import create_derived_objects, free_derived_objects
|
||||
|
||||
# import Blender
|
||||
# from Blender import Object, Lamp, Draw, Image, Text, sys, Mesh
|
||||
# from Blender.Scene import Render
|
||||
# import BPyObject
|
||||
# import BPyMesh
|
||||
|
||||
#
|
||||
DEG2RAD=0.017453292519943295
|
||||
MATWORLD= Blender.Mathutils.RotationMatrix(-90, 4, 'x')
|
||||
MATWORLD= Mathutils.RotationMatrix(-90, 4, 'x')
|
||||
|
||||
####################################
|
||||
# Global Variables
|
||||
####################################
|
||||
|
||||
filename = Blender.Get('filename')
|
||||
filename = ""
|
||||
# filename = Blender.Get('filename')
|
||||
_safeOverwrite = True
|
||||
|
||||
extension = ''
|
||||
@@ -109,7 +117,7 @@ class x3d_class:
|
||||
import gzip
|
||||
self.file = gzip.open(filename, "w")
|
||||
except:
|
||||
print "failed to import compression modules, exporting uncompressed"
|
||||
print("failed to import compression modules, exporting uncompressed")
|
||||
self.filename = filename[:-1] # remove trailing z
|
||||
|
||||
if self.file == None:
|
||||
@@ -161,8 +169,10 @@ class x3d_class:
|
||||
self.file.write("<!DOCTYPE X3D PUBLIC \"ISO//Web3D//DTD X3D 3.0//EN\" \"http://www.web3d.org/specifications/x3d-3.0.dtd\">\n")
|
||||
self.file.write("<X3D version=\"3.0\" profile=\"Immersive\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema-instance\" xsd:noNamespaceSchemaLocation=\"http://www.web3d.org/specifications/x3d-3.0.xsd\">\n")
|
||||
self.file.write("<head>\n")
|
||||
self.file.write("\t<meta name=\"filename\" content=\"%s\" />\n" % sys.basename(bfile))
|
||||
self.file.write("\t<meta name=\"generator\" content=\"Blender %s\" />\n" % Blender.Get('version'))
|
||||
self.file.write("\t<meta name=\"filename\" content=\"%s\" />\n" % os.path.basename(bfile))
|
||||
# self.file.write("\t<meta name=\"filename\" content=\"%s\" />\n" % sys.basename(bfile))
|
||||
self.file.write("\t<meta name=\"generator\" content=\"Blender %s\" />\n" % '2.5')
|
||||
# self.file.write("\t<meta name=\"generator\" content=\"Blender %s\" />\n" % Blender.Get('version'))
|
||||
self.file.write("\t<meta name=\"translator\" content=\"X3D exporter v1.55 (2006/01/17)\" />\n")
|
||||
self.file.write("</head>\n")
|
||||
self.file.write("<Scene>\n")
|
||||
@@ -206,9 +216,12 @@ class x3d_class:
|
||||
'''
|
||||
|
||||
def writeViewpoint(self, ob, mat, scene):
|
||||
context = scene.render
|
||||
ratio = float(context.imageSizeY())/float(context.imageSizeX())
|
||||
lens = (360* (math.atan(ratio *16 / ob.data.getLens()) / math.pi))*(math.pi/180)
|
||||
context = scene.render_data
|
||||
# context = scene.render
|
||||
ratio = float(context.resolution_x)/float(context.resolution_y)
|
||||
# ratio = float(context.imageSizeY())/float(context.imageSizeX())
|
||||
lens = (360* (math.atan(ratio *16 / ob.data.lens) / math.pi))*(math.pi/180)
|
||||
# lens = (360* (math.atan(ratio *16 / ob.data.getLens()) / math.pi))*(math.pi/180)
|
||||
lens = min(lens, math.pi)
|
||||
|
||||
# get the camera location, subtract 90 degress from X to orient like X3D does
|
||||
@@ -216,7 +229,8 @@ class x3d_class:
|
||||
|
||||
loc = self.rotatePointForVRML(mat.translationPart())
|
||||
rot = mat.toEuler()
|
||||
rot = (((rot[0]-90)*DEG2RAD), rot[1]*DEG2RAD, rot[2]*DEG2RAD)
|
||||
rot = (((rot[0]-90)), rot[1], rot[2])
|
||||
# rot = (((rot[0]-90)*DEG2RAD), rot[1]*DEG2RAD, rot[2]*DEG2RAD)
|
||||
nRot = self.rotatePointForVRML( rot )
|
||||
# convert to Quaternion and to Angle Axis
|
||||
Q = self.eulerToQuaternions(nRot[0], nRot[1], nRot[2])
|
||||
@@ -232,13 +246,18 @@ class x3d_class:
|
||||
|
||||
def writeFog(self, world):
|
||||
if world:
|
||||
mtype = world.getMistype()
|
||||
mparam = world.getMist()
|
||||
grd = world.getHor()
|
||||
mtype = world.mist.falloff
|
||||
# mtype = world.getMistype()
|
||||
mparam = world.mist
|
||||
# mparam = world.getMist()
|
||||
grd = world.horizon_color
|
||||
# grd = world.getHor()
|
||||
grd0, grd1, grd2 = grd[0], grd[1], grd[2]
|
||||
else:
|
||||
return
|
||||
if (mtype == 1 or mtype == 2):
|
||||
if (mtype == 'LINEAR' or mtype == 'INVERSE_QUADRATIC'):
|
||||
mtype = 1 if mtype == 'LINEAR' else 2
|
||||
# if (mtype == 1 or mtype == 2):
|
||||
self.file.write("<Fog fogType=\"%s\" " % self.namesFog[mtype])
|
||||
self.file.write("color=\"%s %s %s\" " % (round(grd0,self.cp), round(grd1,self.cp), round(grd2,self.cp)))
|
||||
self.file.write("visibilityRange=\"%s\" />\n\n" % round(mparam[2],self.cp))
|
||||
@@ -251,7 +270,8 @@ class x3d_class:
|
||||
def writeSpotLight(self, ob, mtx, lamp, world):
|
||||
safeName = self.cleanStr(ob.name)
|
||||
if world:
|
||||
ambi = world.amb
|
||||
ambi = world.ambient_color
|
||||
# ambi = world.amb
|
||||
ambientIntensity = ((float(ambi[0] + ambi[1] + ambi[2]))/3)/2.5
|
||||
else:
|
||||
ambi = 0
|
||||
@@ -259,7 +279,8 @@ class x3d_class:
|
||||
|
||||
# compute cutoff and beamwidth
|
||||
intensity=min(lamp.energy/1.75,1.0)
|
||||
beamWidth=((lamp.spotSize*math.pi)/180.0)*.37;
|
||||
beamWidth=((lamp.spot_size*math.pi)/180.0)*.37;
|
||||
# beamWidth=((lamp.spotSize*math.pi)/180.0)*.37;
|
||||
cutOffAngle=beamWidth*1.3
|
||||
|
||||
dx,dy,dz=self.computeDirection(mtx)
|
||||
@@ -270,12 +291,14 @@ class x3d_class:
|
||||
#location=(ob.matrixWorld*MATWORLD).translationPart() # now passed
|
||||
location=(mtx*MATWORLD).translationPart()
|
||||
|
||||
radius = lamp.dist*math.cos(beamWidth)
|
||||
radius = lamp.distance*math.cos(beamWidth)
|
||||
# radius = lamp.dist*math.cos(beamWidth)
|
||||
self.file.write("<SpotLight DEF=\"%s\" " % safeName)
|
||||
self.file.write("radius=\"%s\" " % (round(radius,self.cp)))
|
||||
self.file.write("ambientIntensity=\"%s\" " % (round(ambientIntensity,self.cp)))
|
||||
self.file.write("intensity=\"%s\" " % (round(intensity,self.cp)))
|
||||
self.file.write("color=\"%s %s %s\" " % (round(lamp.col[0],self.cp), round(lamp.col[1],self.cp), round(lamp.col[2],self.cp)))
|
||||
self.file.write("color=\"%s %s %s\" " % (round(lamp.color[0],self.cp), round(lamp.color[1],self.cp), round(lamp.color[2],self.cp)))
|
||||
# self.file.write("color=\"%s %s %s\" " % (round(lamp.col[0],self.cp), round(lamp.col[1],self.cp), round(lamp.col[2],self.cp)))
|
||||
self.file.write("beamWidth=\"%s\" " % (round(beamWidth,self.cp)))
|
||||
self.file.write("cutOffAngle=\"%s\" " % (round(cutOffAngle,self.cp)))
|
||||
self.file.write("direction=\"%s %s %s\" " % (round(dx,3),round(dy,3),round(dz,3)))
|
||||
@@ -285,7 +308,8 @@ class x3d_class:
|
||||
def writeDirectionalLight(self, ob, mtx, lamp, world):
|
||||
safeName = self.cleanStr(ob.name)
|
||||
if world:
|
||||
ambi = world.amb
|
||||
ambi = world.ambient_color
|
||||
# ambi = world.amb
|
||||
ambientIntensity = ((float(ambi[0] + ambi[1] + ambi[2]))/3)/2.5
|
||||
else:
|
||||
ambi = 0
|
||||
@@ -295,14 +319,16 @@ class x3d_class:
|
||||
(dx,dy,dz)=self.computeDirection(mtx)
|
||||
self.file.write("<DirectionalLight DEF=\"%s\" " % safeName)
|
||||
self.file.write("ambientIntensity=\"%s\" " % (round(ambientIntensity,self.cp)))
|
||||
self.file.write("color=\"%s %s %s\" " % (round(lamp.col[0],self.cp), round(lamp.col[1],self.cp), round(lamp.col[2],self.cp)))
|
||||
self.file.write("color=\"%s %s %s\" " % (round(lamp.color[0],self.cp), round(lamp.color[1],self.cp), round(lamp.color[2],self.cp)))
|
||||
# self.file.write("color=\"%s %s %s\" " % (round(lamp.col[0],self.cp), round(lamp.col[1],self.cp), round(lamp.col[2],self.cp)))
|
||||
self.file.write("intensity=\"%s\" " % (round(intensity,self.cp)))
|
||||
self.file.write("direction=\"%s %s %s\" />\n\n" % (round(dx,4),round(dy,4),round(dz,4)))
|
||||
|
||||
def writePointLight(self, ob, mtx, lamp, world):
|
||||
safeName = self.cleanStr(ob.name)
|
||||
if world:
|
||||
ambi = world.amb
|
||||
ambi = world.ambient_color
|
||||
# ambi = world.amb
|
||||
ambientIntensity = ((float(ambi[0] + ambi[1] + ambi[2]))/3)/2.5
|
||||
else:
|
||||
ambi = 0
|
||||
@@ -313,9 +339,11 @@ class x3d_class:
|
||||
|
||||
self.file.write("<PointLight DEF=\"%s\" " % safeName)
|
||||
self.file.write("ambientIntensity=\"%s\" " % (round(ambientIntensity,self.cp)))
|
||||
self.file.write("color=\"%s %s %s\" " % (round(lamp.col[0],self.cp), round(lamp.col[1],self.cp), round(lamp.col[2],self.cp)))
|
||||
self.file.write("color=\"%s %s %s\" " % (round(lamp.color[0],self.cp), round(lamp.color[1],self.cp), round(lamp.color[2],self.cp)))
|
||||
# self.file.write("color=\"%s %s %s\" " % (round(lamp.col[0],self.cp), round(lamp.col[1],self.cp), round(lamp.col[2],self.cp)))
|
||||
self.file.write("intensity=\"%s\" " % (round( min(lamp.energy/1.75,1.0) ,self.cp)))
|
||||
self.file.write("radius=\"%s\" " % lamp.dist )
|
||||
self.file.write("radius=\"%s\" " % lamp.distance )
|
||||
# self.file.write("radius=\"%s\" " % lamp.dist )
|
||||
self.file.write("location=\"%s %s %s\" />\n\n" % (round(location[0],3), round(location[1],3), round(location[2],3)))
|
||||
'''
|
||||
def writeNode(self, ob, mtx):
|
||||
@@ -357,24 +385,41 @@ class x3d_class:
|
||||
vColors={} # 'multi':1
|
||||
meshName = self.cleanStr(ob.name)
|
||||
|
||||
meshME = self.cleanStr(ob.getData(mesh=1).name) # We dont care if its the mesh name or not
|
||||
meshME = self.cleanStr(ob.data.name) # We dont care if its the mesh name or not
|
||||
# meshME = self.cleanStr(ob.getData(mesh=1).name) # We dont care if its the mesh name or not
|
||||
if len(mesh.faces) == 0: return
|
||||
mode = 0
|
||||
if mesh.faceUV:
|
||||
for face in mesh.faces:
|
||||
mode |= face.mode
|
||||
mode = []
|
||||
# mode = 0
|
||||
if mesh.active_uv_texture:
|
||||
# if mesh.faceUV:
|
||||
for face in mesh.active_uv_texture.data:
|
||||
# for face in mesh.faces:
|
||||
if face.halo and 'HALO' not in mode:
|
||||
mode += ['HALO']
|
||||
if face.billboard and 'BILLBOARD' not in mode:
|
||||
mode += ['BILLBOARD']
|
||||
if face.object_color and 'OBJECT_COLOR' not in mode:
|
||||
mode += ['OBJECT_COLOR']
|
||||
if face.collision and 'COLLISION' not in mode:
|
||||
mode += ['COLLISION']
|
||||
# mode |= face.mode
|
||||
|
||||
if mode & Mesh.FaceModes.HALO and self.halonode == 0:
|
||||
if 'HALO' in mode and self.halonode == 0:
|
||||
# if mode & Mesh.FaceModes.HALO and self.halonode == 0:
|
||||
self.writeIndented("<Billboard axisOfRotation=\"0 0 0\">\n",1)
|
||||
self.halonode = 1
|
||||
elif mode & Mesh.FaceModes.BILLBOARD and self.billnode == 0:
|
||||
elif 'BILLBOARD' in mode and self.billnode == 0:
|
||||
# elif mode & Mesh.FaceModes.BILLBOARD and self.billnode == 0:
|
||||
self.writeIndented("<Billboard axisOfRotation=\"0 1 0\">\n",1)
|
||||
self.billnode = 1
|
||||
elif mode & Mesh.FaceModes.OBCOL and self.matonly == 0:
|
||||
elif 'OBJECT_COLOR' in mode and self.matonly == 0:
|
||||
# elif mode & Mesh.FaceModes.OBCOL and self.matonly == 0:
|
||||
self.matonly = 1
|
||||
elif mode & Mesh.FaceModes.TILES and self.tilenode == 0:
|
||||
self.tilenode = 1
|
||||
elif not mode & Mesh.FaceModes.DYNAMIC and self.collnode == 0:
|
||||
# TF_TILES is marked as deprecated in DNA_meshdata_types.h
|
||||
# elif mode & Mesh.FaceModes.TILES and self.tilenode == 0:
|
||||
# self.tilenode = 1
|
||||
elif 'COLLISION' not in mode and self.collnode == 0:
|
||||
# elif not mode & Mesh.FaceModes.DYNAMIC and self.collnode == 0:
|
||||
self.writeIndented("<Collision enabled=\"false\">\n",1)
|
||||
self.collnode = 1
|
||||
|
||||
@@ -383,7 +428,7 @@ class x3d_class:
|
||||
if nIFSCnt > 1:
|
||||
self.writeIndented("<Group DEF=\"%s%s\">\n" % ("G_", meshName),1)
|
||||
|
||||
if sided.has_key('two') and sided['two'] > 0:
|
||||
if 'two' in sided and sided['two'] > 0:
|
||||
bTwoSided=1
|
||||
else:
|
||||
bTwoSided=0
|
||||
@@ -396,34 +441,44 @@ class x3d_class:
|
||||
quat = mtx.toQuat()
|
||||
rot= quat.axis
|
||||
|
||||
# self.writeIndented('<Transform rotation="%.6f %.6f %.6f %.6f">\n' % (rot[0], rot[1], rot[2], rot[3]))
|
||||
self.writeIndented('<Transform DEF="%s" translation="%.6f %.6f %.6f" scale="%.6f %.6f %.6f" rotation="%.6f %.6f %.6f %.6f">\n' % \
|
||||
(meshName, loc[0], loc[1], loc[2], sca[0], sca[1], sca[2], rot[0], rot[1], rot[2], quat.angle*DEG2RAD) )
|
||||
(meshName, loc[0], loc[1], loc[2], sca[0], sca[1], sca[2], rot[0], rot[1], rot[2], quat.angle) )
|
||||
# self.writeIndented('<Transform DEF="%s" translation="%.6f %.6f %.6f" scale="%.6f %.6f %.6f" rotation="%.6f %.6f %.6f %.6f">\n' % \
|
||||
# (meshName, loc[0], loc[1], loc[2], sca[0], sca[1], sca[2], rot[0], rot[1], rot[2], quat.angle*DEG2RAD) )
|
||||
|
||||
self.writeIndented("<Shape>\n",1)
|
||||
maters=mesh.materials
|
||||
hasImageTexture=0
|
||||
issmooth=0
|
||||
|
||||
if len(maters) > 0 or mesh.faceUV:
|
||||
if len(maters) > 0 or mesh.active_uv_texture:
|
||||
# if len(maters) > 0 or mesh.faceUV:
|
||||
self.writeIndented("<Appearance>\n", 1)
|
||||
# right now this script can only handle a single material per mesh.
|
||||
if len(maters) >= 1:
|
||||
mat=maters[0]
|
||||
matFlags = mat.getMode()
|
||||
if not matFlags & Blender.Material.Modes['TEXFACE']:
|
||||
self.writeMaterial(mat, self.cleanStr(maters[0].name,''), world)
|
||||
# matFlags = mat.getMode()
|
||||
if not mat.face_texture:
|
||||
# if not matFlags & Blender.Material.Modes['TEXFACE']:
|
||||
self.writeMaterial(mat, self.cleanStr(mat.name,''), world)
|
||||
# self.writeMaterial(mat, self.cleanStr(maters[0].name,''), world)
|
||||
if len(maters) > 1:
|
||||
print "Warning: mesh named %s has multiple materials" % meshName
|
||||
print "Warning: only one material per object handled"
|
||||
print("Warning: mesh named %s has multiple materials" % meshName)
|
||||
print("Warning: only one material per object handled")
|
||||
|
||||
#-- textures
|
||||
if mesh.faceUV:
|
||||
for face in mesh.faces:
|
||||
if (hasImageTexture == 0) and (face.image):
|
||||
face = None
|
||||
if mesh.active_uv_texture:
|
||||
# if mesh.faceUV:
|
||||
for face in mesh.active_uv_texture.data:
|
||||
# for face in mesh.faces:
|
||||
if face.image:
|
||||
# if (hasImageTexture == 0) and (face.image):
|
||||
self.writeImageTexture(face.image)
|
||||
hasImageTexture=1 # keep track of face texture
|
||||
if self.tilenode == 1:
|
||||
# hasImageTexture=1 # keep track of face texture
|
||||
break
|
||||
if self.tilenode == 1 and face and face.image:
|
||||
# if self.tilenode == 1:
|
||||
self.writeIndented("<TextureTransform scale=\"%s %s\" />\n" % (face.image.xrep, face.image.yrep))
|
||||
self.tilenode = 0
|
||||
self.writeIndented("</Appearance>\n", -1)
|
||||
@@ -433,7 +488,7 @@ class x3d_class:
|
||||
# user selected BOUNDS=1, SOLID=3, SHARED=4, or TEXTURE=5
|
||||
ifStyle="IndexedFaceSet"
|
||||
# look up mesh name, use it if available
|
||||
if self.meshNames.has_key(meshME):
|
||||
if meshME in self.meshNames:
|
||||
self.writeIndented("<%s USE=\"ME_%s\">" % (ifStyle, meshME), 1)
|
||||
self.meshNames[meshME]+=1
|
||||
else:
|
||||
@@ -453,11 +508,13 @@ class x3d_class:
|
||||
issmooth=1
|
||||
break
|
||||
if issmooth==1:
|
||||
creaseAngle=(mesh.degr)*(math.pi/180.0)
|
||||
creaseAngle=(mesh.autosmooth_angle)*(math.pi/180.0)
|
||||
# creaseAngle=(mesh.degr)*(math.pi/180.0)
|
||||
self.file.write("creaseAngle=\"%s\" " % (round(creaseAngle,self.cp)))
|
||||
|
||||
#--- output textureCoordinates if UV texture used
|
||||
if mesh.faceUV:
|
||||
if mesh.active_uv_texture:
|
||||
# if mesh.faceUV:
|
||||
if self.matonly == 1 and self.share == 1:
|
||||
self.writeFaceColors(mesh)
|
||||
elif hasImageTexture == 1:
|
||||
@@ -471,7 +528,8 @@ class x3d_class:
|
||||
self.writeCoordinates(ob, mesh, meshName, EXPORT_TRI)
|
||||
|
||||
#--- output textureCoordinates if UV texture used
|
||||
if mesh.faceUV:
|
||||
if mesh.active_uv_texture:
|
||||
# if mesh.faceUV:
|
||||
if hasImageTexture == 1:
|
||||
self.writeTextureCoordinates(mesh)
|
||||
elif self.matonly == 1 and self.share == 1:
|
||||
@@ -511,16 +569,22 @@ class x3d_class:
|
||||
if self.writingcoords == 0:
|
||||
self.file.write('coordIndex="')
|
||||
for face in mesh.faces:
|
||||
fv = face.v
|
||||
fv = face.verts
|
||||
# fv = face.v
|
||||
|
||||
if len(face)==3:
|
||||
self.file.write("%i %i %i -1, " % (fv[0].index, fv[1].index, fv[2].index))
|
||||
if len(fv)==3:
|
||||
# if len(face)==3:
|
||||
self.file.write("%i %i %i -1, " % (fv[0], fv[1], fv[2]))
|
||||
# self.file.write("%i %i %i -1, " % (fv[0].index, fv[1].index, fv[2].index))
|
||||
else:
|
||||
if EXPORT_TRI:
|
||||
self.file.write("%i %i %i -1, " % (fv[0].index, fv[1].index, fv[2].index))
|
||||
self.file.write("%i %i %i -1, " % (fv[0].index, fv[2].index, fv[3].index))
|
||||
self.file.write("%i %i %i -1, " % (fv[0], fv[1], fv[2]))
|
||||
# self.file.write("%i %i %i -1, " % (fv[0].index, fv[1].index, fv[2].index))
|
||||
self.file.write("%i %i %i -1, " % (fv[0], fv[2], fv[3]))
|
||||
# self.file.write("%i %i %i -1, " % (fv[0].index, fv[2].index, fv[3].index))
|
||||
else:
|
||||
self.file.write("%i %i %i %i -1, " % (fv[0].index, fv[1].index, fv[2].index, fv[3].index))
|
||||
self.file.write("%i %i %i %i -1, " % (fv[0], fv[1], fv[2], fv[3]))
|
||||
# self.file.write("%i %i %i %i -1, " % (fv[0].index, fv[1].index, fv[2].index, fv[3].index))
|
||||
|
||||
self.file.write("\">\n")
|
||||
else:
|
||||
@@ -538,8 +602,13 @@ class x3d_class:
|
||||
texIndexList=[]
|
||||
j=0
|
||||
|
||||
for face in mesh.faces:
|
||||
for uv in face.uv:
|
||||
for face in mesh.active_uv_texture.data:
|
||||
# for face in mesh.faces:
|
||||
uvs = face.uv
|
||||
# uvs = [face.uv1, face.uv2, face.uv3, face.uv4] if face.verts[3] else [face.uv1, face.uv2, face.uv3]
|
||||
|
||||
for uv in uvs:
|
||||
# for uv in face.uv:
|
||||
texIndexList.append(j)
|
||||
texCoordList.append(uv)
|
||||
j=j+1
|
||||
@@ -547,7 +616,7 @@ class x3d_class:
|
||||
if self.writingtexture == 0:
|
||||
self.file.write("\n\t\t\ttexCoordIndex=\"")
|
||||
texIndxStr=""
|
||||
for i in xrange(len(texIndexList)):
|
||||
for i in range(len(texIndexList)):
|
||||
texIndxStr = texIndxStr + "%d, " % texIndexList[i]
|
||||
if texIndexList[i]==-1:
|
||||
self.file.write(texIndxStr)
|
||||
@@ -555,7 +624,7 @@ class x3d_class:
|
||||
self.file.write("\"\n\t\t\t")
|
||||
else:
|
||||
self.writeIndented("<TextureCoordinate point=\"", 1)
|
||||
for i in xrange(len(texCoordList)):
|
||||
for i in range(len(texCoordList)):
|
||||
self.file.write("%s %s, " % (round(texCoordList[i][0],self.tp), round(texCoordList[i][1],self.tp)))
|
||||
self.file.write("\" />")
|
||||
self.writeIndented("\n", -1)
|
||||
@@ -563,43 +632,61 @@ class x3d_class:
|
||||
def writeFaceColors(self, mesh):
|
||||
if self.writingcolor == 0:
|
||||
self.file.write("colorPerVertex=\"false\" ")
|
||||
else:
|
||||
elif mesh.active_vertex_color:
|
||||
# else:
|
||||
self.writeIndented("<Color color=\"", 1)
|
||||
for face in mesh.faces:
|
||||
if face.col:
|
||||
c=face.col[0]
|
||||
if self.verbose > 2:
|
||||
print "Debug: face.col r=%d g=%d b=%d" % (c.r, c.g, c.b)
|
||||
aColor = self.rgbToFS(c)
|
||||
self.file.write("%s, " % aColor)
|
||||
for face in mesh.active_vertex_color.data:
|
||||
c = face.color1
|
||||
if self.verbose > 2:
|
||||
print("Debug: face.col r=%d g=%d b=%d" % (c[0], c[1], c[2]))
|
||||
# print("Debug: face.col r=%d g=%d b=%d" % (c.r, c.g, c.b))
|
||||
aColor = self.rgbToFS(c)
|
||||
self.file.write("%s, " % aColor)
|
||||
|
||||
# for face in mesh.faces:
|
||||
# if face.col:
|
||||
# c=face.col[0]
|
||||
# if self.verbose > 2:
|
||||
# print("Debug: face.col r=%d g=%d b=%d" % (c.r, c.g, c.b))
|
||||
# aColor = self.rgbToFS(c)
|
||||
# self.file.write("%s, " % aColor)
|
||||
self.file.write("\" />")
|
||||
self.writeIndented("\n",-1)
|
||||
|
||||
def writeMaterial(self, mat, matName, world):
|
||||
# look up material name, use it if available
|
||||
if self.matNames.has_key(matName):
|
||||
if matName in self.matNames:
|
||||
self.writeIndented("<Material USE=\"MA_%s\" />\n" % matName)
|
||||
self.matNames[matName]+=1
|
||||
return;
|
||||
|
||||
self.matNames[matName]=1
|
||||
|
||||
ambient = mat.amb/3
|
||||
diffuseR, diffuseG, diffuseB = mat.rgbCol[0], mat.rgbCol[1],mat.rgbCol[2]
|
||||
ambient = mat.ambient/3
|
||||
# ambient = mat.amb/3
|
||||
diffuseR, diffuseG, diffuseB = tuple(mat.diffuse_color)
|
||||
# diffuseR, diffuseG, diffuseB = mat.rgbCol[0], mat.rgbCol[1],mat.rgbCol[2]
|
||||
if world:
|
||||
ambi = world.getAmb()
|
||||
ambi0, ambi1, ambi2 = (ambi[0]*mat.amb)*2, (ambi[1]*mat.amb)*2, (ambi[2]*mat.amb)*2
|
||||
ambi = world.ambient_color
|
||||
# ambi = world.getAmb()
|
||||
ambi0, ambi1, ambi2 = (ambi[0]*mat.ambient)*2, (ambi[1]*mat.ambient)*2, (ambi[2]*mat.ambient)*2
|
||||
# ambi0, ambi1, ambi2 = (ambi[0]*mat.amb)*2, (ambi[1]*mat.amb)*2, (ambi[2]*mat.amb)*2
|
||||
else:
|
||||
ambi0, ambi1, ambi2 = 0, 0, 0
|
||||
emisR, emisG, emisB = (diffuseR*mat.emit+ambi0)/2, (diffuseG*mat.emit+ambi1)/2, (diffuseB*mat.emit+ambi2)/2
|
||||
|
||||
shininess = mat.hard/512.0
|
||||
specR = (mat.specCol[0]+0.001)/(1.25/(mat.spec+0.001))
|
||||
specG = (mat.specCol[1]+0.001)/(1.25/(mat.spec+0.001))
|
||||
specB = (mat.specCol[2]+0.001)/(1.25/(mat.spec+0.001))
|
||||
shininess = mat.specular_hardness/512.0
|
||||
# shininess = mat.hard/512.0
|
||||
specR = (mat.specular_color[0]+0.001)/(1.25/(mat.specular_intensity+0.001))
|
||||
# specR = (mat.specCol[0]+0.001)/(1.25/(mat.spec+0.001))
|
||||
specG = (mat.specular_color[1]+0.001)/(1.25/(mat.specular_intensity+0.001))
|
||||
# specG = (mat.specCol[1]+0.001)/(1.25/(mat.spec+0.001))
|
||||
specB = (mat.specular_color[2]+0.001)/(1.25/(mat.specular_intensity+0.001))
|
||||
# specB = (mat.specCol[2]+0.001)/(1.25/(mat.spec+0.001))
|
||||
transp = 1-mat.alpha
|
||||
matFlags = mat.getMode()
|
||||
if matFlags & Blender.Material.Modes['SHADELESS']:
|
||||
# matFlags = mat.getMode()
|
||||
if mat.shadeless:
|
||||
# if matFlags & Blender.Material.Modes['SHADELESS']:
|
||||
ambient = 1
|
||||
shine = 1
|
||||
specR = emitR = diffuseR
|
||||
@@ -617,7 +704,7 @@ class x3d_class:
|
||||
def writeImageTexture(self, image):
|
||||
name = image.name
|
||||
filename = image.filename.split('/')[-1].split('\\')[-1]
|
||||
if self.texNames.has_key(name):
|
||||
if name in self.texNames:
|
||||
self.writeIndented("<ImageTexture USE=\"%s\" />\n" % self.cleanStr(name))
|
||||
self.texNames[name] += 1
|
||||
return
|
||||
@@ -630,10 +717,13 @@ class x3d_class:
|
||||
def writeBackground(self, world, alltextures):
|
||||
if world: worldname = world.name
|
||||
else: return
|
||||
blending = world.getSkytype()
|
||||
grd = world.getHor()
|
||||
blending = (world.blend_sky, world.paper_sky, world.real_sky)
|
||||
# blending = world.getSkytype()
|
||||
grd = world.horizon_color
|
||||
# grd = world.getHor()
|
||||
grd0, grd1, grd2 = grd[0], grd[1], grd[2]
|
||||
sky = world.getZen()
|
||||
sky = world.zenith_color
|
||||
# sky = world.getZen()
|
||||
sky0, sky1, sky2 = sky[0], sky[1], sky[2]
|
||||
mix0, mix1, mix2 = grd[0]+sky[0], grd[1]+sky[1], grd[2]+sky[2]
|
||||
mix0, mix1, mix2 = mix0/2, mix1/2, mix2/2
|
||||
@@ -641,27 +731,32 @@ class x3d_class:
|
||||
if worldname not in self.namesStandard:
|
||||
self.file.write("DEF=\"%s\" " % self.secureName(worldname))
|
||||
# No Skytype - just Hor color
|
||||
if blending == 0:
|
||||
if blending == (0, 0, 0):
|
||||
# if blending == 0:
|
||||
self.file.write("groundColor=\"%s %s %s\" " % (round(grd0,self.cp), round(grd1,self.cp), round(grd2,self.cp)))
|
||||
self.file.write("skyColor=\"%s %s %s\" " % (round(grd0,self.cp), round(grd1,self.cp), round(grd2,self.cp)))
|
||||
# Blend Gradient
|
||||
elif blending == 1:
|
||||
elif blending == (1, 0, 0):
|
||||
# elif blending == 1:
|
||||
self.file.write("groundColor=\"%s %s %s, " % (round(grd0,self.cp), round(grd1,self.cp), round(grd2,self.cp)))
|
||||
self.file.write("%s %s %s\" groundAngle=\"1.57, 1.57\" " %(round(mix0,self.cp), round(mix1,self.cp), round(mix2,self.cp)))
|
||||
self.file.write("skyColor=\"%s %s %s, " % (round(sky0,self.cp), round(sky1,self.cp), round(sky2,self.cp)))
|
||||
self.file.write("%s %s %s\" skyAngle=\"1.57, 1.57\" " %(round(mix0,self.cp), round(mix1,self.cp), round(mix2,self.cp)))
|
||||
# Blend+Real Gradient Inverse
|
||||
elif blending == 3:
|
||||
elif blending == (1, 0, 1):
|
||||
# elif blending == 3:
|
||||
self.file.write("groundColor=\"%s %s %s, " % (round(sky0,self.cp), round(sky1,self.cp), round(sky2,self.cp)))
|
||||
self.file.write("%s %s %s\" groundAngle=\"1.57, 1.57\" " %(round(mix0,self.cp), round(mix1,self.cp), round(mix2,self.cp)))
|
||||
self.file.write("skyColor=\"%s %s %s, " % (round(grd0,self.cp), round(grd1,self.cp), round(grd2,self.cp)))
|
||||
self.file.write("%s %s %s\" skyAngle=\"1.57, 1.57\" " %(round(mix0,self.cp), round(mix1,self.cp), round(mix2,self.cp)))
|
||||
# Paper - just Zen Color
|
||||
elif blending == 4:
|
||||
elif blending == (0, 0, 1):
|
||||
# elif blending == 4:
|
||||
self.file.write("groundColor=\"%s %s %s\" " % (round(sky0,self.cp), round(sky1,self.cp), round(sky2,self.cp)))
|
||||
self.file.write("skyColor=\"%s %s %s\" " % (round(sky0,self.cp), round(sky1,self.cp), round(sky2,self.cp)))
|
||||
# Blend+Real+Paper - komplex gradient
|
||||
elif blending == 7:
|
||||
elif blending == (1, 1, 1):
|
||||
# elif blending == 7:
|
||||
self.writeIndented("groundColor=\"%s %s %s, " % (round(sky0,self.cp), round(sky1,self.cp), round(sky2,self.cp)))
|
||||
self.writeIndented("%s %s %s\" groundAngle=\"1.57, 1.57\" " %(round(grd0,self.cp), round(grd1,self.cp), round(grd2,self.cp)))
|
||||
self.writeIndented("skyColor=\"%s %s %s, " % (round(sky0,self.cp), round(sky1,self.cp), round(sky2,self.cp)))
|
||||
@@ -670,22 +765,43 @@ class x3d_class:
|
||||
else:
|
||||
self.file.write("groundColor=\"%s %s %s\" " % (round(grd0,self.cp), round(grd1,self.cp), round(grd2,self.cp)))
|
||||
self.file.write("skyColor=\"%s %s %s\" " % (round(sky0,self.cp), round(sky1,self.cp), round(sky2,self.cp)))
|
||||
|
||||
alltexture = len(alltextures)
|
||||
for i in xrange(alltexture):
|
||||
namemat = alltextures[i].name
|
||||
pic = alltextures[i].getImage()
|
||||
|
||||
for i in range(alltexture):
|
||||
tex = alltextures[i]
|
||||
|
||||
if tex.type != 'IMAGE' or tex.image == None:
|
||||
continue
|
||||
|
||||
namemat = tex.name
|
||||
# namemat = alltextures[i].name
|
||||
|
||||
pic = tex.image
|
||||
|
||||
# using .expandpath just in case, os.path may not expect //
|
||||
basename = os.path.basename(pic.get_abs_filename())
|
||||
|
||||
pic = alltextures[i].image
|
||||
# pic = alltextures[i].getImage()
|
||||
if (namemat == "back") and (pic != None):
|
||||
self.file.write("\n\tbackUrl=\"%s\" " % pic.filename.split('/')[-1].split('\\')[-1])
|
||||
self.file.write("\n\tbackUrl=\"%s\" " % basename)
|
||||
# self.file.write("\n\tbackUrl=\"%s\" " % pic.filename.split('/')[-1].split('\\')[-1])
|
||||
elif (namemat == "bottom") and (pic != None):
|
||||
self.writeIndented("bottomUrl=\"%s\" " % pic.filename.split('/')[-1].split('\\')[-1])
|
||||
self.writeIndented("bottomUrl=\"%s\" " % basename)
|
||||
# self.writeIndented("bottomUrl=\"%s\" " % pic.filename.split('/')[-1].split('\\')[-1])
|
||||
elif (namemat == "front") and (pic != None):
|
||||
self.writeIndented("frontUrl=\"%s\" " % pic.filename.split('/')[-1].split('\\')[-1])
|
||||
self.writeIndented("frontUrl=\"%s\" " % basename)
|
||||
# self.writeIndented("frontUrl=\"%s\" " % pic.filename.split('/')[-1].split('\\')[-1])
|
||||
elif (namemat == "left") and (pic != None):
|
||||
self.writeIndented("leftUrl=\"%s\" " % pic.filename.split('/')[-1].split('\\')[-1])
|
||||
self.writeIndented("leftUrl=\"%s\" " % basename)
|
||||
# self.writeIndented("leftUrl=\"%s\" " % pic.filename.split('/')[-1].split('\\')[-1])
|
||||
elif (namemat == "right") and (pic != None):
|
||||
self.writeIndented("rightUrl=\"%s\" " % pic.filename.split('/')[-1].split('\\')[-1])
|
||||
self.writeIndented("rightUrl=\"%s\" " % basename)
|
||||
# self.writeIndented("rightUrl=\"%s\" " % pic.filename.split('/')[-1].split('\\')[-1])
|
||||
elif (namemat == "top") and (pic != None):
|
||||
self.writeIndented("topUrl=\"%s\" " % pic.filename.split('/')[-1].split('\\')[-1])
|
||||
self.writeIndented("topUrl=\"%s\" " % basename)
|
||||
# self.writeIndented("topUrl=\"%s\" " % pic.filename.split('/')[-1].split('\\')[-1])
|
||||
self.writeIndented("/>\n\n")
|
||||
|
||||
##########################################################
|
||||
@@ -697,7 +813,7 @@ class x3d_class:
|
||||
EXPORT_TRI= False,\
|
||||
):
|
||||
|
||||
print "Info: starting X3D export to " + self.filename + "..."
|
||||
print("Info: starting X3D export to " + self.filename + "...")
|
||||
self.writeHeader()
|
||||
# self.writeScript()
|
||||
self.writeNavigationInfo(scene)
|
||||
@@ -706,44 +822,65 @@ class x3d_class:
|
||||
self.proto = 0
|
||||
|
||||
|
||||
# COPIED FROM OBJ EXPORTER
|
||||
if EXPORT_APPLY_MODIFIERS:
|
||||
temp_mesh_name = '~tmp-mesh'
|
||||
# # COPIED FROM OBJ EXPORTER
|
||||
# if EXPORT_APPLY_MODIFIERS:
|
||||
# temp_mesh_name = '~tmp-mesh'
|
||||
|
||||
# Get the container mesh. - used for applying modifiers and non mesh objects.
|
||||
containerMesh = meshName = tempMesh = None
|
||||
for meshName in Blender.NMesh.GetNames():
|
||||
if meshName.startswith(temp_mesh_name):
|
||||
tempMesh = Mesh.Get(meshName)
|
||||
if not tempMesh.users:
|
||||
containerMesh = tempMesh
|
||||
if not containerMesh:
|
||||
containerMesh = Mesh.New(temp_mesh_name)
|
||||
# # Get the container mesh. - used for applying modifiers and non mesh objects.
|
||||
# containerMesh = meshName = tempMesh = None
|
||||
# for meshName in Blender.NMesh.GetNames():
|
||||
# if meshName.startswith(temp_mesh_name):
|
||||
# tempMesh = Mesh.Get(meshName)
|
||||
# if not tempMesh.users:
|
||||
# containerMesh = tempMesh
|
||||
# if not containerMesh:
|
||||
# containerMesh = Mesh.New(temp_mesh_name)
|
||||
# --------------------------
|
||||
|
||||
|
||||
for ob_main in scene.objects.context:
|
||||
for ob, ob_mat in BPyObject.getDerivedObjects(ob_main):
|
||||
for ob_main in [o for o in scene.objects if o.is_visible()]:
|
||||
# for ob_main in scene.objects.context:
|
||||
|
||||
free, derived = create_derived_objects(ob_main)
|
||||
|
||||
if derived == None: continue
|
||||
|
||||
for ob, ob_mat in derived:
|
||||
# for ob, ob_mat in BPyObject.getDerivedObjects(ob_main):
|
||||
objType=ob.type
|
||||
objName=ob.name
|
||||
self.matonly = 0
|
||||
if objType == "Camera":
|
||||
if objType == "CAMERA":
|
||||
# if objType == "Camera":
|
||||
self.writeViewpoint(ob, ob_mat, scene)
|
||||
elif objType in ("Mesh", "Curve", "Surf", "Text") :
|
||||
if EXPORT_APPLY_MODIFIERS or objType != 'Mesh':
|
||||
me= BPyMesh.getMeshFromObject(ob, containerMesh, EXPORT_APPLY_MODIFIERS, False, scene)
|
||||
elif objType in ("MESH", "CURVE", "SURF", "TEXT") :
|
||||
# elif objType in ("Mesh", "Curve", "Surf", "Text") :
|
||||
if EXPORT_APPLY_MODIFIERS or objType != 'MESH':
|
||||
# if EXPORT_APPLY_MODIFIERS or objType != 'Mesh':
|
||||
me = ob.create_mesh(EXPORT_APPLY_MODIFIERS, 'PREVIEW')
|
||||
# me= BPyMesh.getMeshFromObject(ob, containerMesh, EXPORT_APPLY_MODIFIERS, False, scene)
|
||||
else:
|
||||
me = ob.getData(mesh=1)
|
||||
me = ob.data
|
||||
# me = ob.getData(mesh=1)
|
||||
|
||||
self.writeIndexedFaceSet(ob, me, ob_mat, world, EXPORT_TRI = EXPORT_TRI)
|
||||
elif objType == "Lamp":
|
||||
|
||||
# free mesh created with create_mesh()
|
||||
if me != ob.data:
|
||||
bpy.data.remove_mesh(me)
|
||||
|
||||
elif objType == "LAMP":
|
||||
# elif objType == "Lamp":
|
||||
data= ob.data
|
||||
datatype=data.type
|
||||
if datatype == Lamp.Types.Lamp:
|
||||
if datatype == 'POINT':
|
||||
# if datatype == Lamp.Types.Lamp:
|
||||
self.writePointLight(ob, ob_mat, data, world)
|
||||
elif datatype == Lamp.Types.Spot:
|
||||
elif datatype == 'SPOT':
|
||||
# elif datatype == Lamp.Types.Spot:
|
||||
self.writeSpotLight(ob, ob_mat, data, world)
|
||||
elif datatype == Lamp.Types.Sun:
|
||||
elif datatype == 'SUN':
|
||||
# elif datatype == Lamp.Types.Sun:
|
||||
self.writeDirectionalLight(ob, ob_mat, data, world)
|
||||
else:
|
||||
self.writeDirectionalLight(ob, ob_mat, data, world)
|
||||
@@ -754,11 +891,14 @@ class x3d_class:
|
||||
#print "Info: Ignoring [%s], object type [%s] not handle yet" % (object.name,object.getType)
|
||||
pass
|
||||
|
||||
if free:
|
||||
free_derived_objects(ob_main)
|
||||
|
||||
self.file.write("\n</Scene>\n</X3D>")
|
||||
|
||||
if EXPORT_APPLY_MODIFIERS:
|
||||
if containerMesh:
|
||||
containerMesh.verts = None
|
||||
# if EXPORT_APPLY_MODIFIERS:
|
||||
# if containerMesh:
|
||||
# containerMesh.verts = None
|
||||
|
||||
self.cleanup()
|
||||
|
||||
@@ -771,7 +911,7 @@ class x3d_class:
|
||||
self.texNames={}
|
||||
self.matNames={}
|
||||
self.indentLevel=0
|
||||
print "Info: finished X3D export to %s\n" % self.filename
|
||||
print("Info: finished X3D export to %s\n" % self.filename)
|
||||
|
||||
def cleanStr(self, name, prefix='rsvd_'):
|
||||
"""cleanStr(name,prefix) - try to create a valid VRML DEF name from object name"""
|
||||
@@ -807,15 +947,18 @@ class x3d_class:
|
||||
faceMap={}
|
||||
nFaceIndx=0
|
||||
|
||||
if mesh.faceUV:
|
||||
for face in mesh.faces:
|
||||
if mesh.active_uv_texture:
|
||||
# if mesh.faceUV:
|
||||
for face in mesh.active_uv_texture.data:
|
||||
# for face in mesh.faces:
|
||||
sidename='';
|
||||
if face.mode & Mesh.FaceModes.TWOSIDE:
|
||||
if face.twoside:
|
||||
# if face.mode & Mesh.FaceModes.TWOSIDE:
|
||||
sidename='two'
|
||||
else:
|
||||
sidename='one'
|
||||
|
||||
if sided.has_key(sidename):
|
||||
if sidename in sided:
|
||||
sided[sidename]+=1
|
||||
else:
|
||||
sided[sidename]=1
|
||||
@@ -829,56 +972,63 @@ class x3d_class:
|
||||
imageMap[faceName]=[face.image.name,sidename,face]
|
||||
|
||||
if self.verbose > 2:
|
||||
for faceName in imageMap.iterkeys():
|
||||
for faceName in imageMap.keys():
|
||||
ifs=imageMap[faceName]
|
||||
print "Debug: faceName=%s image=%s, solid=%s facecnt=%d" % \
|
||||
(faceName, ifs[0], ifs[1], len(ifs)-2)
|
||||
print("Debug: faceName=%s image=%s, solid=%s facecnt=%d" % \
|
||||
(faceName, ifs[0], ifs[1], len(ifs)-2))
|
||||
|
||||
return len(imageMap)
|
||||
|
||||
def faceToString(self,face):
|
||||
|
||||
print "Debug: face.flag=0x%x (bitflags)" % face.flag
|
||||
print("Debug: face.flag=0x%x (bitflags)" % face.flag)
|
||||
if face.sel:
|
||||
print "Debug: face.sel=true"
|
||||
print("Debug: face.sel=true")
|
||||
|
||||
print "Debug: face.mode=0x%x (bitflags)" % face.mode
|
||||
print("Debug: face.mode=0x%x (bitflags)" % face.mode)
|
||||
if face.mode & Mesh.FaceModes.TWOSIDE:
|
||||
print "Debug: face.mode twosided"
|
||||
print("Debug: face.mode twosided")
|
||||
|
||||
print "Debug: face.transp=0x%x (enum)" % face.transp
|
||||
print("Debug: face.transp=0x%x (enum)" % face.transp)
|
||||
if face.transp == Mesh.FaceTranspModes.SOLID:
|
||||
print "Debug: face.transp.SOLID"
|
||||
print("Debug: face.transp.SOLID")
|
||||
|
||||
if face.image:
|
||||
print "Debug: face.image=%s" % face.image.name
|
||||
print "Debug: face.materialIndex=%d" % face.materialIndex
|
||||
print("Debug: face.image=%s" % face.image.name)
|
||||
print("Debug: face.materialIndex=%d" % face.materialIndex)
|
||||
|
||||
def getVertexColorByIndx(self, mesh, indx):
|
||||
c = None
|
||||
for face in mesh.faces:
|
||||
j=0
|
||||
for vertex in face.v:
|
||||
if vertex.index == indx:
|
||||
c=face.col[j]
|
||||
break
|
||||
j=j+1
|
||||
if c: break
|
||||
return c
|
||||
# XXX not used
|
||||
# def getVertexColorByIndx(self, mesh, indx):
|
||||
# c = None
|
||||
# for face in mesh.faces:
|
||||
# j=0
|
||||
# for vertex in face.v:
|
||||
# if vertex.index == indx:
|
||||
# c=face.col[j]
|
||||
# break
|
||||
# j=j+1
|
||||
# if c: break
|
||||
# return c
|
||||
|
||||
def meshToString(self,mesh):
|
||||
print "Debug: mesh.hasVertexUV=%d" % mesh.vertexColors
|
||||
print "Debug: mesh.faceUV=%d" % mesh.faceUV
|
||||
print "Debug: mesh.hasVertexColours=%d" % mesh.hasVertexColours()
|
||||
print "Debug: mesh.verts=%d" % len(mesh.verts)
|
||||
print "Debug: mesh.faces=%d" % len(mesh.faces)
|
||||
print "Debug: mesh.materials=%d" % len(mesh.materials)
|
||||
# print("Debug: mesh.hasVertexUV=%d" % mesh.vertexColors)
|
||||
print("Debug: mesh.faceUV=%d" % (len(mesh.uv_textures) > 0))
|
||||
# print("Debug: mesh.faceUV=%d" % mesh.faceUV)
|
||||
print("Debug: mesh.hasVertexColours=%d" % (len(mesh.vertex_colors) > 0))
|
||||
# print("Debug: mesh.hasVertexColours=%d" % mesh.hasVertexColours())
|
||||
print("Debug: mesh.verts=%d" % len(mesh.verts))
|
||||
print("Debug: mesh.faces=%d" % len(mesh.faces))
|
||||
print("Debug: mesh.materials=%d" % len(mesh.materials))
|
||||
|
||||
def rgbToFS(self, c):
|
||||
s="%s %s %s" % (
|
||||
round(c.r/255.0,self.cp),
|
||||
round(c.g/255.0,self.cp),
|
||||
round(c.b/255.0,self.cp))
|
||||
s="%s %s %s" % (round(c[0]/255.0,self.cp),
|
||||
round(c[1]/255.0,self.cp),
|
||||
round(c[2]/255.0,self.cp))
|
||||
|
||||
# s="%s %s %s" % (
|
||||
# round(c.r/255.0,self.cp),
|
||||
# round(c.g/255.0,self.cp),
|
||||
# round(c.b/255.0,self.cp))
|
||||
return s
|
||||
|
||||
def computeDirection(self, mtx):
|
||||
@@ -886,9 +1036,10 @@ class x3d_class:
|
||||
|
||||
ax,ay,az = (mtx*MATWORLD).toEuler()
|
||||
|
||||
ax *= DEG2RAD
|
||||
ay *= DEG2RAD
|
||||
az *= DEG2RAD
|
||||
# ax *= DEG2RAD
|
||||
# ay *= DEG2RAD
|
||||
# az *= DEG2RAD
|
||||
|
||||
# rot X
|
||||
x1=x
|
||||
y1=y*math.cos(ax)-z*math.sin(ax)
|
||||
@@ -924,7 +1075,7 @@ class x3d_class:
|
||||
self.indentLevel = self.indentLevel + inc
|
||||
|
||||
spaces=""
|
||||
for x in xrange(self.indentLevel):
|
||||
for x in range(self.indentLevel):
|
||||
spaces = spaces + "\t"
|
||||
self.file.write(spaces + s)
|
||||
|
||||
@@ -975,11 +1126,11 @@ class x3d_class:
|
||||
# Callbacks, needed before Main
|
||||
##########################################################
|
||||
|
||||
def x3d_export(filename, \
|
||||
EXPORT_APPLY_MODIFIERS= False,\
|
||||
EXPORT_TRI= False,\
|
||||
EXPORT_GZIP= False,\
|
||||
):
|
||||
def x3d_export(filename,
|
||||
context,
|
||||
EXPORT_APPLY_MODIFIERS=False,
|
||||
EXPORT_TRI=False,
|
||||
EXPORT_GZIP=False):
|
||||
|
||||
if EXPORT_GZIP:
|
||||
if not filename.lower().endswith('.x3dz'):
|
||||
@@ -989,9 +1140,13 @@ def x3d_export(filename, \
|
||||
filename = '.'.join(filename.split('.')[:-1]) + '.x3d'
|
||||
|
||||
|
||||
scene = Blender.Scene.GetCurrent()
|
||||
scene = context.scene
|
||||
# scene = Blender.Scene.GetCurrent()
|
||||
world = scene.world
|
||||
alltextures = Blender.Texture.Get()
|
||||
|
||||
# XXX these are global textures while .Get() returned only scene's?
|
||||
alltextures = bpy.data.textures
|
||||
# alltextures = Blender.Texture.Get()
|
||||
|
||||
wrlexport=x3d_class(filename)
|
||||
wrlexport.export(\
|
||||
@@ -1045,7 +1200,41 @@ def x3d_export_ui(filename):
|
||||
#########################################################
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
Blender.Window.FileSelector(x3d_export_ui,"Export X3D", Blender.Get('filename').replace('.blend', '.x3d'))
|
||||
# if __name__ == '__main__':
|
||||
# Blender.Window.FileSelector(x3d_export_ui,"Export X3D", Blender.Get('filename').replace('.blend', '.x3d'))
|
||||
|
||||
class EXPORT_OT_x3d(bpy.types.Operator):
|
||||
'''
|
||||
X3D Exporter
|
||||
'''
|
||||
__idname__ = "export.x3d"
|
||||
__label__ = 'Export X3D'
|
||||
|
||||
# List of operator properties, the attributes will be assigned
|
||||
# to the class instance from the operator settings before calling.
|
||||
|
||||
__props__ = [
|
||||
bpy.props.StringProperty(attr="path", name="File Path", description="File path used for exporting the X3D file", maxlen= 1024, default= ""),
|
||||
|
||||
bpy.props.BoolProperty(attr="apply_modifiers", name="Apply Modifiers", description="Use transformed mesh data from each object.", default=True),
|
||||
bpy.props.BoolProperty(attr="triangulate", name="Triangulate", description="Triangulate quads.", default=False),
|
||||
bpy.props.BoolProperty(attr="compress", name="Compress", description="GZip the resulting file, requires a full python install.", default=False),
|
||||
]
|
||||
|
||||
def execute(self, context):
|
||||
x3d_export(self.path, context, self.apply_modifiers, self.triangulate, self.compress)
|
||||
return ('FINISHED',)
|
||||
|
||||
def invoke(self, context, event):
|
||||
wm = context.manager
|
||||
wm.add_fileselect(self.__operator__)
|
||||
return ('RUNNING_MODAL',)
|
||||
|
||||
def poll(self, context): # Poll isnt working yet
|
||||
print("Poll")
|
||||
return context.active_object != None
|
||||
|
||||
bpy.ops.add(EXPORT_OT_x3d)
|
||||
|
||||
# NOTES
|
||||
# - blender version is hardcoded
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user