svn merge -r 20373:20515 https://svn.blender.org/svnroot/bf-blender/branches/blender2...
[blender.git] / release / scripts / export_obj-2.5.py
1 #!BPY
2
3 """
4 Name: 'Wavefront (.obj)...'
5 Blender: 248
6 Group: 'Export'
7 Tooltip: 'Save a Wavefront OBJ File'
8 """
9
10 __author__ = "Campbell Barton, Jiri Hnidek"
11 __url__ = ['http://wiki.blender.org/index.php/Scripts/Manual/Export/wavefront_obj', 'www.blender.org', 'blenderartists.org']
12 __version__ = "1.2"
13
14 __bpydoc__ = """\
15 This script is an exporter to OBJ file format.
16
17 Usage:
18
19 Select the objects you wish to export and run this script from "File->Export" menu.
20 Selecting the default options from the popup box will be good in most cases.
21 All objects that can be represented as a mesh (mesh, curve, metaball, surface, text3d)
22 will be exported as mesh data.
23 """
24
25
26 # --------------------------------------------------------------------------
27 # OBJ Export v1.1 by Campbell Barton (AKA Ideasman)
28 # --------------------------------------------------------------------------
29 # ***** BEGIN GPL LICENSE BLOCK *****
30 #
31 # This program is free software; you can redistribute it and/or
32 # modify it under the terms of the GNU General Public License
33 # as published by the Free Software Foundation; either version 2
34 # of the License, or (at your option) any later version.
35 #
36 # This program is distributed in the hope that it will be useful,
37 # but WITHOUT ANY WARRANTY; without even the implied warranty of
38 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
39 # GNU General Public License for more details.
40 #
41 # You should have received a copy of the GNU General Public License
42 # along with this program; if not, write to the Free Software Foundation,
43 # Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
44 #
45 # ***** END GPL LICENCE BLOCK *****
46 # --------------------------------------------------------------------------
47
48
49 import bpy
50
51 # import Blender
52 # from Blender import Mesh, Scene, Window, sys, Image, Draw
53 # import BPyMesh
54 # import BPyObject
55 # import BPySys
56 # import BPyMessages
57
58 # Returns a tuple - path,extension.
59 # 'hello.obj' >  ('hello', '.obj')
60 def splitExt(path):
61         dotidx = path.rfind('.')
62         if dotidx == -1:
63                 return path, ''
64         else:
65                 return path[:dotidx], path[dotidx:] 
66
67 def fixName(name):
68         if name == None:
69                 return 'None'
70         else:
71                 return name.replace(' ', '_')
72
73 # A Dict of Materials
74 # (material.name, image.name):matname_imagename # matname_imagename has gaps removed.
75 MTL_DICT = {} 
76
77 def write_mtl(filename):
78         
79         world = Blender.World.GetCurrent()
80         if world:
81                 worldAmb = world.getAmb()
82         else:
83                 worldAmb = (0,0,0) # Default value
84         
85         file = open(filename, "w")
86         file.write('# Blender3D MTL File: %s\n' % Blender.Get('filename').split('\\')[-1].split('/')[-1])
87         file.write('# Material Count: %i\n' % len(MTL_DICT))
88         # Write material/image combinations we have used.
89         for key, (mtl_mat_name, mat, img) in MTL_DICT.iteritems():
90                 
91                 # Get the Blender data for the material and the image.
92                 # Having an image named None will make a bug, dont do it :)
93                 
94                 file.write('newmtl %s\n' % mtl_mat_name) # Define a new material: matname_imgname
95                 
96                 if mat:
97                         file.write('Ns %.6f\n' % ((mat.getHardness()-1) * 1.9607843137254901) ) # Hardness, convert blenders 1-511 to MTL's 
98                         file.write('Ka %.6f %.6f %.6f\n' %  tuple([c*mat.amb for c in worldAmb])  ) # Ambient, uses mirror colour,
99                         file.write('Kd %.6f %.6f %.6f\n' % tuple([c*mat.ref for c in mat.rgbCol]) ) # Diffuse
100                         file.write('Ks %.6f %.6f %.6f\n' % tuple([c*mat.spec for c in mat.specCol]) ) # Specular
101                         file.write('Ni %.6f\n' % mat.IOR) # Refraction index
102                         file.write('d %.6f\n' % mat.alpha) # Alpha (obj uses 'd' for dissolve)
103                         
104                         # 0 to disable lighting, 1 for ambient & diffuse only (specular color set to black), 2 for full lighting.
105                         if mat.getMode() & Blender.Material.Modes['SHADELESS']:
106                                 file.write('illum 0\n') # ignore lighting
107                         elif mat.getSpec() == 0:
108                                 file.write('illum 1\n') # no specular.
109                         else:
110                                 file.write('illum 2\n') # light normaly 
111                 
112                 else:
113                         #write a dummy material here?
114                         file.write('Ns 0\n')
115                         file.write('Ka %.6f %.6f %.6f\n' %  tuple([c for c in worldAmb])  ) # Ambient, uses mirror colour,
116                         file.write('Kd 0.8 0.8 0.8\n')
117                         file.write('Ks 0.8 0.8 0.8\n')
118                         file.write('d 1\n') # No alpha
119                         file.write('illum 2\n') # light normaly
120                 
121                 # Write images!
122                 if img:  # We have an image on the face!
123                         file.write('map_Kd %s\n' % img.filename.split('\\')[-1].split('/')[-1]) # Diffuse mapping image                 
124                 
125                 elif mat: # No face image. if we havea material search for MTex image.
126                         for mtex in mat.getTextures():
127                                 if mtex and mtex.tex.type == Blender.Texture.Types.IMAGE:
128                                         try:
129                                                 filename = mtex.tex.image.filename.split('\\')[-1].split('/')[-1]
130                                                 file.write('map_Kd %s\n' % filename) # Diffuse mapping image
131                                                 break
132                                         except:
133                                                 # Texture has no image though its an image type, best ignore.
134                                                 pass
135                 
136                 file.write('\n\n')
137         
138         file.close()
139
140 def copy_file(source, dest):
141         file = open(source, 'rb')
142         data = file.read()
143         file.close()
144         
145         file = open(dest, 'wb')
146         file.write(data)
147         file.close()
148
149
150 def copy_images(dest_dir):
151         if dest_dir[-1] != sys.sep:
152                 dest_dir += sys.sep
153         
154         # Get unique image names
155         uniqueImages = {}
156         for matname, mat, image in MTL_DICT.itervalues(): # Only use image name
157                 # Get Texface images
158                 if image:
159                         uniqueImages[image] = image # Should use sets here. wait until Python 2.4 is default.
160                 
161                 # Get MTex images
162                 if mat:
163                         for mtex in mat.getTextures():
164                                 if mtex and mtex.tex.type == Blender.Texture.Types.IMAGE:
165                                         image_tex = mtex.tex.image
166                                         if image_tex:
167                                                 try:
168                                                         uniqueImages[image_tex] = image_tex
169                                                 except:
170                                                         pass
171         
172         # Now copy images
173         copyCount = 0
174         
175         for bImage in uniqueImages.itervalues():
176                 image_path = sys.expandpath(bImage.filename)
177                 if sys.exists(image_path):
178                         # Make a name for the target path.
179                         dest_image_path = dest_dir + image_path.split('\\')[-1].split('/')[-1]
180                         if not sys.exists(dest_image_path): # Image isnt alredy there
181                                 print '\tCopying "%s" > "%s"' % (image_path, dest_image_path)
182                                 copy_file(image_path, dest_image_path)
183                                 copyCount+=1
184         print '\tCopied %d images' % copyCount
185
186 def write(filename, objects,\
187 EXPORT_TRI=False,  EXPORT_EDGES=False,  EXPORT_NORMALS=False,  EXPORT_NORMALS_HQ=False,\
188 EXPORT_UV=True,  EXPORT_MTL=True,  EXPORT_COPY_IMAGES=False,\
189 EXPORT_APPLY_MODIFIERS=True, EXPORT_ROTX90=True, EXPORT_BLEN_OBS=True,\
190 EXPORT_GROUP_BY_OB=False,  EXPORT_GROUP_BY_MAT=False, EXPORT_KEEP_VERT_ORDER=False):
191         '''
192         Basic write function. The context and options must be alredy set
193         This can be accessed externaly
194         eg.
195         write( 'c:\\test\\foobar.obj', Blender.Object.GetSelected() ) # Using default options.
196         '''
197         
198         def veckey3d(v):
199                 return round(v.x, 6), round(v.y, 6), round(v.z, 6)
200                 
201         def veckey2d(v):
202                 return round(v.x, 6), round(v.y, 6)
203         
204         print 'OBJ Export path: "%s"' % filename
205         temp_mesh_name = '~tmp-mesh'
206
207         time1 = sys.time()
208         scn = Scene.GetCurrent()
209
210         file = open(filename, "w")
211         
212         # Write Header
213         file.write('# Blender3D v%s OBJ File: %s\n' % (Blender.Get('version'), Blender.Get('filename').split('/')[-1].split('\\')[-1] ))
214         file.write('# www.blender3d.org\n')
215
216         # Tell the obj file what material file to use.
217         if EXPORT_MTL:
218                 mtlfilename = '%s.mtl' % '.'.join(filename.split('.')[:-1])
219                 file.write('mtllib %s\n' % ( mtlfilename.split('\\')[-1].split('/')[-1] ))
220         
221         # Get the container mesh. - used for applying modifiers and non mesh objects.
222         containerMesh = meshName = tempMesh = None
223         for meshName in Blender.NMesh.GetNames():
224                 if meshName.startswith(temp_mesh_name):
225                         tempMesh = Mesh.Get(meshName)
226                         if not tempMesh.users:
227                                 containerMesh = tempMesh
228         if not containerMesh:
229                 containerMesh = Mesh.New(temp_mesh_name)
230         
231         if EXPORT_ROTX90:
232                 mat_xrot90= Blender.Mathutils.RotationMatrix(-90, 4, 'x')
233                 
234         del meshName
235         del tempMesh
236         
237         # Initialize totals, these are updated each object
238         totverts = totuvco = totno = 1
239         
240         face_vert_index = 1
241         
242         globalNormals = {}
243         
244         # Get all meshs
245         for ob_main in objects:
246                 for ob, ob_mat in BPyObject.getDerivedObjects(ob_main):
247                         # Will work for non meshes now! :)
248                         # getMeshFromObject(ob, container_mesh=None, apply_modifiers=True, vgroups=True, scn=None)
249                         me= BPyMesh.getMeshFromObject(ob, containerMesh, EXPORT_APPLY_MODIFIERS, False, scn)
250                         if not me:
251                                 continue
252                         
253                         if EXPORT_UV:
254                                 faceuv= me.faceUV
255                         else:
256                                 faceuv = False
257                         
258                         # We have a valid mesh
259                         if EXPORT_TRI and me.faces:
260                                 # Add a dummy object to it.
261                                 has_quads = False
262                                 for f in me.faces:
263                                         if len(f) == 4:
264                                                 has_quads = True
265                                                 break
266                                 
267                                 if has_quads:
268                                         oldmode = Mesh.Mode()
269                                         Mesh.Mode(Mesh.SelectModes['FACE'])
270                                         
271                                         me.sel = True
272                                         tempob = scn.objects.new(me)
273                                         me.quadToTriangle(0) # more=0 shortest length
274                                         oldmode = Mesh.Mode(oldmode)
275                                         scn.objects.unlink(tempob)
276                                         
277                                         Mesh.Mode(oldmode)
278                         
279                         # Make our own list so it can be sorted to reduce context switching
280                         faces = [ f for f in me.faces ]
281                         
282                         if EXPORT_EDGES:
283                                 edges = me.edges
284                         else:
285                                 edges = []
286                         
287                         if not (len(faces)+len(edges)+len(me.verts)): # Make sure there is somthing to write
288                                 continue # dont bother with this mesh.
289                         
290                         if EXPORT_ROTX90:
291                                 me.transform(ob_mat*mat_xrot90)
292                         else:
293                                 me.transform(ob_mat)
294                         
295                         # High Quality Normals
296                         if EXPORT_NORMALS and faces:
297                                 if EXPORT_NORMALS_HQ:
298                                         BPyMesh.meshCalcNormals(me)
299                                 else:
300                                         # transforming normals is incorrect
301                                         # when the matrix is scaled,
302                                         # better to recalculate them
303                                         me.calcNormals()
304                         
305                         # # Crash Blender
306                         #materials = me.getMaterials(1) # 1 == will return None in the list.
307                         materials = me.materials
308                         
309                         materialNames = []
310                         materialItems = materials[:]
311                         if materials:
312                                 for mat in materials:
313                                         if mat: # !=None
314                                                 materialNames.append(mat.name)
315                                         else:
316                                                 materialNames.append(None)
317                                 # Cant use LC because some materials are None.
318                                 # materialNames = map(lambda mat: mat.name, materials) # Bug Blender, dosent account for null materials, still broken.  
319                         
320                         # Possible there null materials, will mess up indicies
321                         # but at least it will export, wait until Blender gets fixed.
322                         materialNames.extend((16-len(materialNames)) * [None])
323                         materialItems.extend((16-len(materialItems)) * [None])
324                         
325                         # Sort by Material, then images
326                         # so we dont over context switch in the obj file.
327                         if EXPORT_KEEP_VERT_ORDER:
328                                 pass
329                         elif faceuv:
330                                 try:    faces.sort(key = lambda a: (a.mat, a.image, a.smooth))
331                                 except: faces.sort(lambda a,b: cmp((a.mat, a.image, a.smooth), (b.mat, b.image, b.smooth)))
332                         elif len(materials) > 1:
333                                 try:    faces.sort(key = lambda a: (a.mat, a.smooth))
334                                 except: faces.sort(lambda a,b: cmp((a.mat, a.smooth), (b.mat, b.smooth)))
335                         else:
336                                 # no materials
337                                 try:    faces.sort(key = lambda a: a.smooth)
338                                 except: faces.sort(lambda a,b: cmp(a.smooth, b.smooth))
339                         
340                         # Set the default mat to no material and no image.
341                         contextMat = (0, 0) # Can never be this, so we will label a new material teh first chance we get.
342                         contextSmooth = None # Will either be true or false,  set bad to force initialization switch.
343                         
344                         if EXPORT_BLEN_OBS or EXPORT_GROUP_BY_OB:
345                                 name1 = ob.name
346                                 name2 = ob.getData(1)
347                                 if name1 == name2:
348                                         obnamestring = fixName(name1)
349                                 else:
350                                         obnamestring = '%s_%s' % (fixName(name1), fixName(name2))
351                                 
352                                 if EXPORT_BLEN_OBS:
353                                         file.write('o %s\n' % obnamestring) # Write Object name
354                                 else: # if EXPORT_GROUP_BY_OB:
355                                         file.write('g %s\n' % obnamestring)
356                         
357                         
358                         # Vert
359                         for v in me.verts:
360                                 file.write('v %.6f %.6f %.6f\n' % tuple(v.co))
361                         
362                         # UV
363                         if faceuv:
364                                 uv_face_mapping = [[0,0,0,0] for f in faces] # a bit of a waste for tri's :/
365                                 
366                                 uv_dict = {} # could use a set() here
367                                 for f_index, f in enumerate(faces):
368                                         
369                                         for uv_index, uv in enumerate(f.uv):
370                                                 uvkey = veckey2d(uv)
371                                                 try:
372                                                         uv_face_mapping[f_index][uv_index] = uv_dict[uvkey]
373                                                 except:
374                                                         uv_face_mapping[f_index][uv_index] = uv_dict[uvkey] = len(uv_dict)
375                                                         file.write('vt %.6f %.6f\n' % tuple(uv))
376                                 
377                                 uv_unique_count = len(uv_dict)
378                                 del uv, uvkey, uv_dict, f_index, uv_index
379                                 # Only need uv_unique_count and uv_face_mapping
380                         
381                         # NORMAL, Smooth/Non smoothed.
382                         if EXPORT_NORMALS:
383                                 for f in faces:
384                                         if f.smooth:
385                                                 for v in f:
386                                                         noKey = veckey3d(v.no)
387                                                         if not globalNormals.has_key( noKey ):
388                                                                 globalNormals[noKey] = totno
389                                                                 totno +=1
390                                                                 file.write('vn %.6f %.6f %.6f\n' % noKey)
391                                         else:
392                                                 # Hard, 1 normal from the face.
393                                                 noKey = veckey3d(f.no)
394                                                 if not globalNormals.has_key( noKey ):
395                                                         globalNormals[noKey] = totno
396                                                         totno +=1
397                                                         file.write('vn %.6f %.6f %.6f\n' % noKey)
398                         
399                         if not faceuv:
400                                 f_image = None
401                         
402                         for f_index, f in enumerate(faces):
403                                 f_v= f.v
404                                 f_smooth= f.smooth
405                                 f_mat = min(f.mat, len(materialNames)-1)
406                                 if faceuv:
407                                         f_image = f.image
408                                         f_uv= f.uv
409                                 
410                                 # MAKE KEY
411                                 if faceuv and f_image: # Object is always true.
412                                         key = materialNames[f_mat],  f_image.name
413                                 else:
414                                         key = materialNames[f_mat],  None # No image, use None instead.
415                                 
416                                 # CHECK FOR CONTEXT SWITCH
417                                 if key == contextMat:
418                                         pass # Context alredy switched, dont do anythoing
419                                 else:
420                                         if key[0] == None and key[1] == None:
421                                                 # Write a null material, since we know the context has changed.
422                                                 if EXPORT_GROUP_BY_MAT:
423                                                         file.write('g %s_%s\n' % (fixName(ob.name), fixName(ob.getData(1))) ) # can be mat_image or (null)
424                                                 file.write('usemtl (null)\n') # mat, image
425                                                 
426                                         else:
427                                                 mat_data= MTL_DICT.get(key)
428                                                 if not mat_data:
429                                                         # First add to global dict so we can export to mtl
430                                                         # Then write mtl
431                                                         
432                                                         # Make a new names from the mat and image name,
433                                                         # converting any spaces to underscores with fixName.
434                                                         
435                                                         # If none image dont bother adding it to the name
436                                                         if key[1] == None:
437                                                                 mat_data = MTL_DICT[key] = ('%s'%fixName(key[0])), materialItems[f_mat], f_image
438                                                         else:
439                                                                 mat_data = MTL_DICT[key] = ('%s_%s' % (fixName(key[0]), fixName(key[1]))), materialItems[f_mat], f_image
440                                                 
441                                                 if EXPORT_GROUP_BY_MAT:
442                                                         file.write('g %s_%s_%s\n' % (fixName(ob.name), fixName(ob.getData(1)), mat_data[0]) ) # can be mat_image or (null)
443                                                 file.write('usemtl %s\n' % mat_data[0]) # can be mat_image or (null)
444                                         
445                                 contextMat = key
446                                 if f_smooth != contextSmooth:
447                                         if f_smooth: # on now off
448                                                 file.write('s 1\n')
449                                                 contextSmooth = f_smooth
450                                         else: # was off now on
451                                                 file.write('s off\n')
452                                                 contextSmooth = f_smooth
453                                 
454                                 file.write('f')
455                                 if faceuv:
456                                         if EXPORT_NORMALS:
457                                                 if f_smooth: # Smoothed, use vertex normals
458                                                         for vi, v in enumerate(f_v):
459                                                                 file.write( ' %d/%d/%d' % (\
460                                                                   v.index+totverts,\
461                                                                   totuvco + uv_face_mapping[f_index][vi],\
462                                                                   globalNormals[ veckey3d(v.no) ])) # vert, uv, normal
463                                                         
464                                                 else: # No smoothing, face normals
465                                                         no = globalNormals[ veckey3d(f.no) ]
466                                                         for vi, v in enumerate(f_v):
467                                                                 file.write( ' %d/%d/%d' % (\
468                                                                   v.index+totverts,\
469                                                                   totuvco + uv_face_mapping[f_index][vi],\
470                                                                   no)) # vert, uv, normal
471                                         
472                                         else: # No Normals
473                                                 for vi, v in enumerate(f_v):
474                                                         file.write( ' %d/%d' % (\
475                                                           v.index+totverts,\
476                                                           totuvco + uv_face_mapping[f_index][vi])) # vert, uv
477                                         
478                                         face_vert_index += len(f_v)
479                                 
480                                 else: # No UV's
481                                         if EXPORT_NORMALS:
482                                                 if f_smooth: # Smoothed, use vertex normals
483                                                         for v in f_v:
484                                                                 file.write( ' %d//%d' % (\
485                                                                   v.index+totverts,\
486                                                                   globalNormals[ veckey3d(v.no) ]))
487                                                 else: # No smoothing, face normals
488                                                         no = globalNormals[ veckey3d(f.no) ]
489                                                         for v in f_v:
490                                                                 file.write( ' %d//%d' % (\
491                                                                   v.index+totverts,\
492                                                                   no))
493                                         else: # No Normals
494                                                 for v in f_v:
495                                                         file.write( ' %d' % (\
496                                                           v.index+totverts))
497                                                 
498                                 file.write('\n')
499                         
500                         # Write edges.
501                         if EXPORT_EDGES:
502                                 LOOSE= Mesh.EdgeFlags.LOOSE
503                                 for ed in edges:
504                                         if ed.flag & LOOSE:
505                                                 file.write('f %d %d\n' % (ed.v1.index+totverts, ed.v2.index+totverts))
506                                 
507                         # Make the indicies global rather then per mesh
508                         totverts += len(me.verts)
509                         if faceuv:
510                                 totuvco += uv_unique_count
511                         me.verts= None
512         file.close()
513         
514         
515         # Now we have all our materials, save them
516         if EXPORT_MTL:
517                 write_mtl(mtlfilename)
518         if EXPORT_COPY_IMAGES:
519                 dest_dir = filename
520                 # Remove chars until we are just the path.
521                 while dest_dir and dest_dir[-1] not in '\\/':
522                         dest_dir = dest_dir[:-1]
523                 if dest_dir:
524                         copy_images(dest_dir)
525                 else:
526                         print '\tError: "%s" could not be used as a base for an image path.' % filename
527         
528         print "OBJ Export time: %.2f" % (sys.time() - time1)
529         
530
531 # converted: 0%
532 def write_ui(filename):
533         
534         if not filename.lower().endswith('.obj'):
535                 filename += '.obj'
536         
537         if not BPyMessages.Warning_SaveOver(filename):
538                 return
539         
540         global EXPORT_APPLY_MODIFIERS, EXPORT_ROTX90, EXPORT_TRI, EXPORT_EDGES,\
541                 EXPORT_NORMALS, EXPORT_NORMALS_HQ, EXPORT_UV,\
542                 EXPORT_MTL, EXPORT_SEL_ONLY, EXPORT_ALL_SCENES,\
543                 EXPORT_ANIMATION, EXPORT_COPY_IMAGES, EXPORT_BLEN_OBS,\
544                 EXPORT_GROUP_BY_OB, EXPORT_GROUP_BY_MAT, EXPORT_KEEP_VERT_ORDER
545         
546         EXPORT_APPLY_MODIFIERS = Draw.Create(0)
547         EXPORT_ROTX90 = Draw.Create(1)
548         EXPORT_TRI = Draw.Create(0)
549         EXPORT_EDGES = Draw.Create(1)
550         EXPORT_NORMALS = Draw.Create(0)
551         EXPORT_NORMALS_HQ = Draw.Create(0)
552         EXPORT_UV = Draw.Create(1)
553         EXPORT_MTL = Draw.Create(1)
554         EXPORT_SEL_ONLY = Draw.Create(1)
555         EXPORT_ALL_SCENES = Draw.Create(0)
556         EXPORT_ANIMATION = Draw.Create(0)
557         EXPORT_COPY_IMAGES = Draw.Create(0)
558         EXPORT_BLEN_OBS = Draw.Create(0)
559         EXPORT_GROUP_BY_OB = Draw.Create(0)
560         EXPORT_GROUP_BY_MAT = Draw.Create(0)
561         EXPORT_KEEP_VERT_ORDER = Draw.Create(1)
562         
563         # Old UI
564         '''
565         # removed too many options are bad!
566         
567         # Get USER Options
568         pup_block = [\
569         ('Context...'),\
570         ('Selection Only', EXPORT_SEL_ONLY, 'Only export objects in visible selection. Else export whole scene.'),\
571         ('All Scenes', EXPORT_ALL_SCENES, 'Each scene as a separate OBJ file.'),\
572         ('Animation', EXPORT_ANIMATION, 'Each frame as a numbered OBJ file.'),\
573         ('Object Prefs...'),\
574         ('Apply Modifiers', EXPORT_APPLY_MODIFIERS, 'Use transformed mesh data from each object. May break vert order for morph targets.'),\
575         ('Rotate X90', EXPORT_ROTX90 , 'Rotate on export so Blenders UP is translated into OBJs UP'),\
576         ('Keep Vert Order', EXPORT_KEEP_VERT_ORDER, 'Keep vert and face order, disables some other options.'),\
577         ('Extra Data...'),\
578         ('Edges', EXPORT_EDGES, 'Edges not connected to faces.'),\
579         ('Normals', EXPORT_NORMALS, 'Export vertex normal data (Ignored on import).'),\
580         ('High Quality Normals', EXPORT_NORMALS_HQ, 'Calculate high quality normals for rendering.'),\
581         ('UVs', EXPORT_UV, 'Export texface UV coords.'),\
582         ('Materials', EXPORT_MTL, 'Write a separate MTL file with the OBJ.'),\
583         ('Copy Images', EXPORT_COPY_IMAGES, 'Copy image files to the export directory, never overwrite.'),\
584         ('Triangulate', EXPORT_TRI, 'Triangulate quads.'),\
585         ('Grouping...'),\
586         ('Objects', EXPORT_BLEN_OBS, 'Export blender objects as "OBJ objects".'),\
587         ('Object Groups', EXPORT_GROUP_BY_OB, 'Export blender objects as "OBJ Groups".'),\
588         ('Material Groups', EXPORT_GROUP_BY_MAT, 'Group by materials.'),\
589         ]
590         
591         if not Draw.PupBlock('Export...', pup_block):
592                 return
593         '''
594         
595         # BEGIN ALTERNATIVE UI *******************
596         if True: 
597                 
598                 EVENT_NONE = 0
599                 EVENT_EXIT = 1
600                 EVENT_REDRAW = 2
601                 EVENT_EXPORT = 3
602                 
603                 GLOBALS = {}
604                 GLOBALS['EVENT'] = EVENT_REDRAW
605                 #GLOBALS['MOUSE'] = Window.GetMouseCoords()
606                 GLOBALS['MOUSE'] = [i/2 for i in Window.GetScreenSize()]
607                 
608                 def obj_ui_set_event(e,v):
609                         GLOBALS['EVENT'] = e
610                 
611                 def do_split(e,v):
612                         global EXPORT_BLEN_OBS, EXPORT_GROUP_BY_OB, EXPORT_GROUP_BY_MAT, EXPORT_APPLY_MODIFIERS, KEEP_VERT_ORDER
613                         if EXPORT_BLEN_OBS.val or EXPORT_GROUP_BY_OB.val or EXPORT_GROUP_BY_MAT.val or EXPORT_APPLY_MODIFIERS.val:
614                                 EXPORT_KEEP_VERT_ORDER.val = 0
615                         else:
616                                 EXPORT_KEEP_VERT_ORDER.val = 1
617                         
618                 def do_vertorder(e,v):
619                         global EXPORT_BLEN_OBS, EXPORT_GROUP_BY_OB, EXPORT_GROUP_BY_MAT, EXPORT_APPLY_MODIFIERS, KEEP_VERT_ORDER
620                         if EXPORT_KEEP_VERT_ORDER.val:
621                                 EXPORT_BLEN_OBS.val = EXPORT_GROUP_BY_OB.val = EXPORT_GROUP_BY_MAT.val = EXPORT_APPLY_MODIFIERS.val = 0
622                         else:
623                                 if not (EXPORT_BLEN_OBS.val or EXPORT_GROUP_BY_OB.val or EXPORT_GROUP_BY_MAT.val or EXPORT_APPLY_MODIFIERS.val):
624                                         EXPORT_KEEP_VERT_ORDER.val = 1
625                         
626                 def do_help(e,v):
627                         url = __url__[0]
628                         print 'Trying to open web browser with documentation at this address...'
629                         print '\t' + url
630                         
631                         try:
632                                 import webbrowser
633                                 webbrowser.open(url)
634                         except:
635                                 print '...could not open a browser window.'
636                 
637                 def obj_ui():
638                         ui_x, ui_y = GLOBALS['MOUSE']
639                         
640                         # Center based on overall pup size
641                         ui_x -= 165
642                         ui_y -= 110
643                         
644                         global EXPORT_APPLY_MODIFIERS, EXPORT_ROTX90, EXPORT_TRI, EXPORT_EDGES,\
645                                 EXPORT_NORMALS, EXPORT_NORMALS_HQ, EXPORT_UV,\
646                                 EXPORT_MTL, EXPORT_SEL_ONLY, EXPORT_ALL_SCENES,\
647                                 EXPORT_ANIMATION, EXPORT_COPY_IMAGES, EXPORT_BLEN_OBS,\
648                                 EXPORT_GROUP_BY_OB, EXPORT_GROUP_BY_MAT, EXPORT_KEEP_VERT_ORDER
649
650                         Draw.Label('Context...', ui_x+9, ui_y+209, 220, 20)
651                         Draw.BeginAlign()
652                         EXPORT_SEL_ONLY = Draw.Toggle('Selection Only', EVENT_NONE, ui_x+9, ui_y+189, 110, 20, EXPORT_SEL_ONLY.val, 'Only export objects in visible selection. Else export whole scene.')
653                         EXPORT_ALL_SCENES = Draw.Toggle('All Scenes', EVENT_NONE, ui_x+119, ui_y+189, 110, 20, EXPORT_ALL_SCENES.val, 'Each scene as a separate OBJ file.')
654                         EXPORT_ANIMATION = Draw.Toggle('Animation', EVENT_NONE, ui_x+229, ui_y+189, 110, 20, EXPORT_ANIMATION.val, 'Each frame as a numbered OBJ file.')
655                         Draw.EndAlign()
656                         
657                         
658                         Draw.Label('Output Options...', ui_x+9, ui_y+159, 220, 20)
659                         Draw.BeginAlign()
660                         EXPORT_APPLY_MODIFIERS = Draw.Toggle('Apply Modifiers', EVENT_REDRAW, ui_x+9, ui_y+140, 110, 20, EXPORT_APPLY_MODIFIERS.val, 'Use transformed mesh data from each object. May break vert order for morph targets.', do_split)
661                         EXPORT_ROTX90 = Draw.Toggle('Rotate X90', EVENT_NONE, ui_x+119, ui_y+140, 110, 20, EXPORT_ROTX90.val, 'Rotate on export so Blenders UP is translated into OBJs UP')
662                         EXPORT_COPY_IMAGES = Draw.Toggle('Copy Images', EVENT_NONE, ui_x+229, ui_y+140, 110, 20, EXPORT_COPY_IMAGES.val, 'Copy image files to the export directory, never overwrite.')
663                         Draw.EndAlign()
664                         
665                         
666                         Draw.Label('Export...', ui_x+9, ui_y+109, 220, 20)
667                         Draw.BeginAlign()
668                         EXPORT_EDGES = Draw.Toggle('Edges', EVENT_NONE, ui_x+9, ui_y+90, 50, 20, EXPORT_EDGES.val, 'Edges not connected to faces.')
669                         EXPORT_TRI = Draw.Toggle('Triangulate', EVENT_NONE, ui_x+59, ui_y+90, 70, 20, EXPORT_TRI.val, 'Triangulate quads.')
670                         Draw.EndAlign()
671                         Draw.BeginAlign()
672                         EXPORT_MTL = Draw.Toggle('Materials', EVENT_NONE, ui_x+139, ui_y+90, 70, 20, EXPORT_MTL.val, 'Write a separate MTL file with the OBJ.')
673                         EXPORT_UV = Draw.Toggle('UVs', EVENT_NONE, ui_x+209, ui_y+90, 31, 20, EXPORT_UV.val, 'Export texface UV coords.')
674                         Draw.EndAlign()
675                         Draw.BeginAlign()
676                         EXPORT_NORMALS = Draw.Toggle('Normals', EVENT_NONE, ui_x+250, ui_y+90, 59, 20, EXPORT_NORMALS.val, 'Export vertex normal data (Ignored on import).')
677                         EXPORT_NORMALS_HQ = Draw.Toggle('HQ', EVENT_NONE, ui_x+309, ui_y+90, 31, 20, EXPORT_NORMALS_HQ.val, 'Calculate high quality normals for rendering.')
678                         Draw.EndAlign()
679                         
680                         
681                         Draw.Label('Blender Objects as OBJ:', ui_x+9, ui_y+59, 220, 20)
682                         Draw.BeginAlign()
683                         EXPORT_BLEN_OBS = Draw.Toggle('Objects', EVENT_REDRAW, ui_x+9, ui_y+39, 60, 20, EXPORT_BLEN_OBS.val, 'Export blender objects as "OBJ objects".', do_split)
684                         EXPORT_GROUP_BY_OB = Draw.Toggle('Groups', EVENT_REDRAW, ui_x+69, ui_y+39, 60, 20, EXPORT_GROUP_BY_OB.val, 'Export blender objects as "OBJ Groups".', do_split)
685                         EXPORT_GROUP_BY_MAT = Draw.Toggle('Material Groups', EVENT_REDRAW, ui_x+129, ui_y+39, 100, 20, EXPORT_GROUP_BY_MAT.val, 'Group by materials.', do_split)
686                         Draw.EndAlign()
687                         
688                         EXPORT_KEEP_VERT_ORDER = Draw.Toggle('Keep Vert Order', EVENT_REDRAW, ui_x+239, ui_y+39, 100, 20, EXPORT_KEEP_VERT_ORDER.val, 'Keep vert and face order, disables some other options. Use for morph targets.', do_vertorder)
689                         
690                         Draw.BeginAlign()
691                         Draw.PushButton('Online Help', EVENT_REDRAW, ui_x+9, ui_y+9, 110, 20, 'Load the wiki page for this script', do_help)
692                         Draw.PushButton('Cancel', EVENT_EXIT, ui_x+119, ui_y+9, 110, 20, '', obj_ui_set_event)
693                         Draw.PushButton('Export', EVENT_EXPORT, ui_x+229, ui_y+9, 110, 20, 'Export with these settings', obj_ui_set_event)
694                         Draw.EndAlign()
695
696                 
697                 # hack so the toggle buttons redraw. this is not nice at all
698                 while GLOBALS['EVENT'] not in (EVENT_EXIT, EVENT_EXPORT):
699                         Draw.UIBlock(obj_ui, 0)
700                 
701                 if GLOBALS['EVENT'] != EVENT_EXPORT:
702                         return
703                 
704         # END ALTERNATIVE UI *********************
705         
706         
707         if EXPORT_KEEP_VERT_ORDER.val:
708                 EXPORT_BLEN_OBS.val = False
709                 EXPORT_GROUP_BY_OB.val = False
710                 EXPORT_GROUP_BY_MAT.val = False
711                 EXPORT_APPLY_MODIFIERS.val = False
712         
713         Window.EditMode(0)
714         Window.WaitCursor(1)
715         
716         EXPORT_APPLY_MODIFIERS = EXPORT_APPLY_MODIFIERS.val
717         EXPORT_ROTX90 = EXPORT_ROTX90.val
718         EXPORT_TRI = EXPORT_TRI.val
719         EXPORT_EDGES = EXPORT_EDGES.val
720         EXPORT_NORMALS = EXPORT_NORMALS.val
721         EXPORT_NORMALS_HQ = EXPORT_NORMALS_HQ.val
722         EXPORT_UV = EXPORT_UV.val
723         EXPORT_MTL = EXPORT_MTL.val
724         EXPORT_SEL_ONLY = EXPORT_SEL_ONLY.val
725         EXPORT_ALL_SCENES = EXPORT_ALL_SCENES.val
726         EXPORT_ANIMATION = EXPORT_ANIMATION.val
727         EXPORT_COPY_IMAGES = EXPORT_COPY_IMAGES.val
728         EXPORT_BLEN_OBS = EXPORT_BLEN_OBS.val
729         EXPORT_GROUP_BY_OB = EXPORT_GROUP_BY_OB.val
730         EXPORT_GROUP_BY_MAT = EXPORT_GROUP_BY_MAT.val
731         EXPORT_KEEP_VERT_ORDER = EXPORT_KEEP_VERT_ORDER.val
732         
733         
734         
735         base_name, ext = splitExt(filename)
736         context_name = [base_name, '', '', ext] # basename, scene_name, framenumber, extension
737         
738         # Use the options to export the data using write()
739         # def write(filename, objects, EXPORT_EDGES=False, EXPORT_NORMALS=False, EXPORT_MTL=True, EXPORT_COPY_IMAGES=False, EXPORT_APPLY_MODIFIERS=True):
740         orig_scene = Scene.GetCurrent()
741         if EXPORT_ALL_SCENES:
742                 export_scenes = Scene.Get()
743         else:
744                 export_scenes = [orig_scene]
745         
746         # Export all scenes.
747         for scn in export_scenes:
748                 scn.makeCurrent() # If alredy current, this is not slow.
749                 context = scn.getRenderingContext()
750                 orig_frame = Blender.Get('curframe')
751                 
752                 if EXPORT_ALL_SCENES: # Add scene name into the context_name
753                         context_name[1] = '_%s' % BPySys.cleanName(scn.name) # WARNING, its possible that this could cause a collision. we could fix if were feeling parranoied.
754                 
755                 # Export an animation?
756                 if EXPORT_ANIMATION:
757                         scene_frames = xrange(context.startFrame(), context.endFrame()+1) # up to and including the end frame.
758                 else:
759                         scene_frames = [orig_frame] # Dont export an animation.
760                 
761                 # Loop through all frames in the scene and export.
762                 for frame in scene_frames:
763                         if EXPORT_ANIMATION: # Add frame to the filename.
764                                 context_name[2] = '_%.6d' % frame
765                         
766                         Blender.Set('curframe', frame)
767                         if EXPORT_SEL_ONLY:
768                                 export_objects = scn.objects.context
769                         else:   
770                                 export_objects = scn.objects
771                         
772                         full_path= ''.join(context_name)
773                         
774                         # erm... bit of a problem here, this can overwrite files when exporting frames. not too bad.
775                         # EXPORT THE FILE.
776                         write(full_path, export_objects,\
777                         EXPORT_TRI, EXPORT_EDGES, EXPORT_NORMALS,\
778                         EXPORT_NORMALS_HQ, EXPORT_UV, EXPORT_MTL,\
779                         EXPORT_COPY_IMAGES, EXPORT_APPLY_MODIFIERS,\
780                         EXPORT_ROTX90, EXPORT_BLEN_OBS,\
781                         EXPORT_GROUP_BY_OB, EXPORT_GROUP_BY_MAT, EXPORT_KEEP_VERT_ORDER)
782                 
783                 Blender.Set('curframe', orig_frame)
784         
785         # Restore old active scene.
786         orig_scene.makeCurrent()
787         Window.WaitCursor(0)
788
789
790 if __name__ == '__main__':
791         Window.FileSelector(write_ui, 'Export Wavefront OBJ', sys.makename(ext='.obj'))