Advertisement
ezak

Codea export script - io_export_mdl.py

May 9th, 2012
179
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 7.04 KB | None | 0 0
  1. bl_info = {
  2.     "name": "Export Model",
  3.     "description": "Export model",
  4.     "author": "Xavier de Boysson",
  5.     "version": (1, 1),
  6.     "blender": (2, 6, 3),
  7.     "location": "File > Export",
  8.     "warning": "",
  9.     "wiki_url": "",
  10.     "tracker_url": "",
  11.     "category": "Import-Export"}
  12.  
  13.  
  14.  
  15. import bpy
  16. import re
  17. from bpy.props import *
  18. import mathutils, math, struct
  19. import os
  20. from os import remove
  21. import time
  22. import shutil
  23.  
  24.  
  25. def writeString(file, string):
  26.     file.write(bytes(string, 'UTF-8'))
  27.  
  28. def do_export(context, props, filepath):
  29.     texture_list = []
  30.    
  31.     mat_x90 = mathutils.Matrix.Rotation(-math.pi/2, 4, 'X')
  32.     ob = context.selectable_objects
  33.     file = open(filepath, 'wb')
  34.     tab = '    '
  35.     indices = []
  36.    
  37.     me = bpy.context.object.data
  38.     for poly in me.polygons:
  39.         for loop_index in poly.loop_indices:
  40.             indices.append(me.loops[loop_index].vertex_index)
  41.    
  42.     i=0
  43.    
  44.    
  45.     for objs in ob:
  46.         if (objs.type == 'MESH'):
  47.             text = objs.active_material.active_texture
  48.            
  49.             #   Make sure that all listed textures are unique
  50.             newTexture = True
  51.             if (len(texture_list) == 0):
  52.                 texture_list.append(text.name)
  53.                 newTexture = False
  54.             else:
  55.                 for n in range(0, len(texture_list)):
  56.                     if (texture_list[n] == text.name):
  57.                         newTexture = False;
  58.             #   Texture Names
  59.             if newTexture:
  60.                 texture_list.append(text.name)
  61.             i+=1
  62.  
  63.     #   Header
  64.     writeString(file, '-- <------------------Scene info Start------------------>\r\n')
  65.     writeString(file, '-- Number of Objects: %i\r\n' % i)
  66.     writeString(file, '-- Number of Textures: %i\r\n' % len(texture_list))
  67.     writeString(file, '-- Textures: ')
  68.     for n in range(0, len(texture_list)):
  69.         writeString(file, '%s ' % texture_list[n])
  70.     writeString(file, '\r\n')
  71.     writeString(file, '-- <-------------------Scene info End------------------->\r\n\r\n')
  72.    
  73.    
  74.     writeString(file, '\r\n')
  75.     writeString(file, 'Scene = class()\r\n')
  76.     writeString(file, '\r\n')
  77.     writeString(file, 'function Scene:init()\r\n')
  78.    
  79.     for objs in ob:
  80.         if (objs.type == 'MESH'):
  81.             basename = objs.name.capitalize()
  82.             basename = re.sub(r'[^\w]', '', basename)
  83.             writeString(file, '%sself.mdl%s = %s()\r\n' % (tab, basename, basename))
  84.     writeString(file, 'end\r\n')
  85.     writeString(file, '\r\n')
  86.     writeString(file, 'function Scene:draw()\r\n')
  87.     for objs in ob:
  88.         if (objs.type == 'MESH'):
  89.             basename = objs.name.capitalize()
  90.             basename = re.sub(r'[^\w]', '', basename)
  91.             writeString(file, '%sself.mdl%s:draw()\r\n' % (tab, basename))
  92.     writeString(file, 'end\r\n')
  93.     writeString(file, '\r\n')
  94.    
  95.     n = 0
  96.     for objs in ob:
  97.        
  98.         nbVertices = 0
  99.         if (objs.type == 'MESH'):
  100.             n = n+1
  101.             mesh = objs.to_mesh(context.scene, props.apply_modifiers, 'PREVIEW')
  102.             if props.world_space:
  103.                 mesh.transform(objs.matrix_world)
  104.             if props.rot_x90:
  105.                 mesh.transform(mat_x90)        
  106.  
  107.             basename = objs.name.capitalize()
  108.             basename = re.sub(r'[^\w]', '', basename)
  109.             text = objs.active_material.active_texture
  110.  
  111.  
  112.             for face in mesh.tessfaces:
  113.                 for index in face.vertices:
  114.                     nbVertices+=1
  115.  
  116.             toto = mesh.getDrawType()
  117.             writeString(file, '-- Position %i \r\n' % toto)
  118.            
  119.             writeString(file, '-- *** Object %i ***\r\n' % n)
  120.            
  121.            
  122.             writeString(file, '-- *** Object %i ***\r\n' % n)
  123.             #   Object Name
  124.             writeString(file, '-- name: %s\r\n' % basename)
  125.             #   Number of vertices
  126.             writeString(file, '-- vertices: %i\r\n' % nbVertices)
  127.             #   Texture Name
  128.             writeString(file, '-- Texture name: %s\r\n' % text.name)
  129.             #   Texture Alpha
  130.             writeString(file, '-- texture alpha: %f\r\n\r\n' % objs.active_material.alpha)
  131.  
  132.             writeString(file, '%s = class()\r\n' % basename)
  133.             writeString(file, '\r\n')
  134.             writeString(file, 'function %s:init()\r\n' % basename)
  135.             writeString(file, '%sself.model = mesh()\r\n' % tab)
  136.             writeString(file, '%sself.model.texture = "Scene:%s"\r\n' % (tab, text.name))
  137.  
  138.         #   Vertices
  139.             writeString(file, '-- Vertices\r\n')
  140.             writeString(file, '%sself.model.vertices = {\r\n' % tab)
  141.             i = 1
  142.             for nb in range(0, len(indices)):
  143.                 index = indices[nb]
  144.                 vert = mesh.vertices[index]
  145.                 writeString(file, '%s%svec3(%f, %f, %f),\r\n' % (tab, tab, vert.co.x, vert.co.y, vert.co.z))
  146.                 #writeString(file, '\tvn: %f, %f, %f\r\n' % (vert.normal.x, vert.normal.y, vert.normal.z))
  147.                 i+=1
  148.             writeString(file, '%s}\r\n' % tab)
  149.             writeString(file, '\r\n')
  150.            
  151.         #   Texture Coordinates
  152.             writeString(file, '-- Texture Coordinates\r\n')
  153.             writeString(file, '%sself.model.texCoords = {\r\n' % tab)
  154.             if len(mesh.uv_textures) > 0:
  155.                 uv_layer = mesh.tessface_uv_textures.active
  156.                 for face in mesh.tessfaces:
  157.                     faceUV = uv_layer.data[face.index]
  158.                     i=0
  159.                     for index in face.vertices:
  160.                         writeString(file, '%s%svec2(%f, %f),\r\n' % ( tab, tab, faceUV.uv[i][0], faceUV.uv[i][1] ))
  161.                         i+=1
  162.             writeString(file, '%s}\r\n' % tab)
  163.             writeString(file, '\r\n')
  164.             writeString(file, '%sself.model:setColors(255,255,255,255)\r\n' % tab)
  165.            
  166.            
  167.             writeString(file, 'end\r\n')
  168.            
  169.             writeString(file, '\r\n')
  170.             writeString(file, 'function %s:draw()\r\n' % basename)
  171.             writeString(file, '%sself.model:draw()\r\n' % tab)
  172.             writeString(file, 'end\r\n')
  173.  
  174.             writeString(file, '\r\n')
  175.  
  176.  
  177.  
  178.  
  179.  
  180.     file.flush()
  181.     file.close()
  182.  
  183.     return True
  184.  
  185.  
  186. ###### EXPORT OPERATOR #######
  187. class Export_mdl(bpy.types.Operator):
  188.     '''Exports the active Object as mdl file.'''
  189.     bl_idname = "export_object.mdl"
  190.     bl_label = "Export to map file"
  191.     filepath = StringProperty(subtype='FILE_PATH')
  192.    
  193.     apply_modifiers = BoolProperty(name="Apply Modifiers",
  194.                             description="Applies the Modifiers",
  195.                             default=True)
  196.  
  197.     rot_x90 = BoolProperty(name="Convert to Y-up",
  198.                             description="Rotate 90 degrees around X to convert to y-up",
  199.                             default=True)
  200.    
  201.     world_space = BoolProperty(name="Export into Worldspace",
  202.                             description="Transform the Vertexcoordinates into Worldspace",
  203.                             default=True)
  204.  
  205.    
  206.     @classmethod
  207.     def poll(cls, context):
  208.         return context.active_object.type in ['MESH', 'CURVE', 'SURFACE', 'FONT']
  209.  
  210.     def execute(self, context):
  211.         start_time = time.time()
  212.         print('\r\n_____START_____')
  213.        
  214.         Filepath = bpy.path.ensure_ext(self.filepath, ".lua")
  215.         exported = do_export(context, self.properties, Filepath)
  216.        
  217.         if exported:
  218.             print('finished export in %s seconds' %((time.time() - start_time)))
  219.            
  220.         return {'FINISHED'}
  221.  
  222.     def invoke(self, context, event):
  223.         wm = context.window_manager
  224.  
  225.         if True:
  226.             # File selector
  227.             wm.fileselect_add(self) # will run self.execute()
  228.             return {'RUNNING_MODAL'}
  229.         elif True:
  230.             # search the enum
  231.             wm.invoke_search_popup(self)
  232.             return {'RUNNING_MODAL'}
  233.         elif False:
  234.             # Redo popup
  235.             return wm.invoke_props_popup(self, event) #
  236.         elif False:
  237.             return self.execute(context)
  238.  
  239.  
  240. ### REGISTER ###
  241.  
  242. def menu_func(self, context):
  243.     self.layout.operator(Export_mdl.bl_idname, text="Export Model")
  244.  
  245. def register():
  246.     bpy.utils.register_module(__name__)
  247.  
  248.     bpy.types.INFO_MT_file_export.append(menu_func)
  249.  
  250. def unregister():
  251.     bpy.utils.unregister_module(__name__)
  252.  
  253.     bpy.types.INFO_MT_file_export.remove(menu_func)
  254.  
  255. if __name__ == "__main__":
  256.     register()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement