TheMusiKid

Blender to Maya

Feb 10th, 2013
208
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 39.74 KB | None | 0 0
  1. #!BPY
  2. """Registration info for Blender menus:
  3. Name: 'OBJ...'
  4. Blender: 232
  5. Group: 'Import'
  6. Tip: 'Import Wavefront File Format (*.obj)'
  7. """
  8.  
  9. #=========================================================================
  10. # Wavefront OBJ Importer/Exporter v1.2
  11. # This is a complete OBJ importer and exporter script
  12. # All Rights Reserved
  13.  
  14.  
  15. #Version mise a jour pour Blender 228 par jm soler
  16. #
  17.  
  18. #=========================================================================
  19. # DESCRIPTION: This script allows for full importing and exporting of
  20. #      .obj files. uv texture coordinates and normals can be exported and
  21. #      imported. .obj groups and materials can also be converted to and
  22. #      from material indexes in Blender.
  23. #
  24. # INSTALLATION:
  25. #      You need the FULL python installation to run this script. You can
  26. #      down load the latest version of PYTHON from http://www.python.org.
  27. #
  28. # INSTRUCTIONS (You definitely want to read this!):
  29. #      Once the script is loaded in Blender, hit alt-p. This will bring up
  30. #      the main interface panel. You will have a choise of exporting or
  31. #      importing an .obj module. If you are exporting you must have at least
  32. #      one mesh selected in Blender, or you will get an error.  
  33. #      You can change the export filename by entering the path and filename
  34. #      in the dialog.  If you do not enter a path, the path will default to
  35. #      your blender directory. You can change the default path in the script <==== NOTE
  36. #      itself by modifying the variable 'Filename' at the top of the script.  
  37. #
  38. #    EXPORTING:
  39. #      There are 4 different export options: Default, Groups, Material Layers,
  40. #      and Standard. "Default" will export your mesh using Material Layers if
  41. #      the mesh has material indexes. "Groups" and "Material Layers" are
  42. #      logically equivalent, but are a different .obj format. If you are
  43. #      exporting a Poser morph target, you must select "Material Layers".   <===== NOTE
  44. #      "Standard" will ignore grouping information, even if your mesh has
  45. #      material indexes.
  46. #
  47. #      There is also a choice between export using "mesh coordinates" or
  48. #      "object coordinates". "Object coordinates" are any location, rotation,
  49. #      or scaling values created outside of mesh edit. They belong to the object
  50. #      rather than the mesh. If you export using mesh coordinates (the default)
  51. #      the center of the object will always be at 0, 0, 0. Export using "mesh
  52. #      coordinates is definintely what you want to use if you are working with
  53. #      a Poser morph target. If you are exporting a group of objects, you will
  54. #      automatically be placed in "object coordinate" mode.
  55. #
  56. #    IMPORTING:
  57. #      If your OBJ model has uv mapping coordinates, and you want to use them  <===== NOTE
  58. #      in Blender, you can access them in two ways. The best way is through Blender's
  59. #      realtime UV coordinates which you enable simply by selecting the UV option in
  60. #      the material edit window. This gives you an exact version of the uv coordinates.
  61. #      An older method is to select the "stick" option in the material edit window. I
  62. #      really don't know why anyone would want to use this option since it cannot handle
  63. #      seams and texture overlap, but I left it in just in case someone could use it for
  64. #      something.
  65. #    
  66. #      If your OBJ contains groups, once it has been imported, it may still appear
  67. #      to lack any material indexes. If this happens, it can be remedied      <=== NOTE
  68. #      by going to the mesh editor window, clicking on the mesh selection button, and
  69. #      reselecting the mesh you have just imported. You will now have as many
  70. #      materials attached to your object as there are groups. You can then select
  71. #      different groups by doing a material select when you are in edit mode.
  72. #
  73. #      Finally, you might have problems with certain parts of the object not displaying
  74. #      after you go in and out of edit mode the first time. To fix this, simply go into
  75. #      edit mode again, and select the "remove doubles" option.
  76. #
  77. #
  78. # HISTORY:
  79. #   Nov 13, 2001: Initial Release
  80. #   Nov 16, 2001: Version 1.1 - no longer need to pre-define dummy materials
  81. #   Dec 13, 2001: Version 1.2 - now imports into realtime UV (the UV button in the material edit window), and
  82. #       exports realtime UV. This format is more compatible with the native .OBJ uv format. Should eliminate
  83. #       texture misalignments and seams. Simply press the UV button in the material edit window after importing.
  84. #
  85. #  GetRaw
  86. #================================
  87.  
  88.  
  89. # ===============================
  90. #   Setup our runtime constants
  91. # ===============================
  92.  
  93. DEBUG=1         #Set this to "1" to see extra messages
  94. MESHVERSION=3   # If the export file doesn't work,
  95. FILEVERSION=3   # try changing these to "2"
  96.  
  97. EVENT_PATHCHANGE=     1
  98. EVENT_IMPORT=         2
  99. EVENT_IMPORT_CONT=    3
  100. EVENT_OPTIONS=        4
  101. EVENT_EXPORT=         7
  102. EVENT_EXPORT_CHK=     5
  103. EVENT_EXPORT_CANCEL=  6
  104. EVENT_QUIT=           8
  105. EVENT_EXPORT_ERR=     9
  106. EVENT_TYPE=           10
  107. EVENT_DONE=           11
  108. EVENT_IMPORT_SELECT=  12
  109.  
  110. # ===============================
  111. # Import our libraries
  112. # ===============================
  113.  
  114. #import string
  115. #import os
  116. #import struct
  117.  
  118. try:
  119.     import nt
  120.     os=nt
  121.     os.sep='\\'
  122. except:    
  123.     import posix
  124.     os=posix
  125.     os.sep='/'
  126.  
  127. def isdir(path):
  128.     try:
  129.         st = os.stat(path)
  130.         return 1
  131.     except:
  132.         return 0
  133.    
  134. def split(pathname):
  135.          k0=pathname.split(os.sep)
  136.          directory=pathname.replace(k0[len(k0)-1],'')
  137.          Name=k0[len(k0)-1]
  138.          return directory, Name
  139.        
  140. def join(l0,l1):        
  141.      return  l0+os.sep+l1
  142.    
  143. os.isdir=isdir
  144. os.split=split
  145. os.join=join
  146.  
  147. import math
  148. import Blender
  149. #import Blender210
  150. from Blender import *
  151. from Blender import NMesh
  152. from Blender.Draw import *
  153. from Blender.BGL import *
  154. from Blender import Material
  155. from Blender import Window
  156.  
  157.  
  158.  
  159. # ===============================
  160. # Input Variables
  161. # ===============================
  162.  
  163. Filename = "G:\\tmp\\t\\t\\quip.obj"
  164.  
  165. gFilename=Create(Filename)
  166. gAlert   = 0
  167. type     = 1
  168. exporttype = 1
  169. returncode = 0
  170. operation = "Export"
  171. center = [0,0,0]
  172. rotation = [0,0,0]
  173. Transform = []
  174. multiflag = 0
  175.  
  176. #================================
  177. # def Fileselect function:
  178. #================================
  179. def ImportFunctionselet(filename):
  180.              global gFilename
  181.              global ExportOptions
  182.              global ExportType
  183.              global type
  184.              global exporttype
  185.              global operation
  186.              global gAlert
  187.              gFilename.val=filename
  188.              ImportFunction(filename, type)
  189.              operation = "Import"
  190.  
  191. #================================
  192. def ExitGUI ():
  193. #================================
  194.     Exit()
  195.  
  196. #================================
  197. def EventGUI (event):
  198. #================================
  199.       global gFilename
  200.       global ExportOptions
  201.       global ExportType
  202.       global type
  203.       global exporttype
  204.       global operation
  205.       global gAlert
  206.  
  207.       if (event==EVENT_IMPORT):
  208.          ImportFunction(gFilename.val, type)
  209.          operation = "Import"
  210.  
  211.       if (event==EVENT_IMPORT_SELECT):        
  212.          Window.FileSelector (ImportFunctionselet, 'IMPORT FILE')
  213.  
  214.  
  215.       if (event==EVENT_IMPORT_CONT):
  216.          gAlert = 0
  217.          operation = "Import"
  218.          Draw ()
  219.  
  220.       if (event==EVENT_EXPORT):
  221.          ExportFunction(gFilename.val, type)
  222.          operation = "Export"
  223.  
  224.       if (event==EVENT_EXPORT_CHK):
  225.          ExportFunctionOK(gFilename.val, type)
  226.          Draw ()
  227.       if (event==EVENT_EXPORT_CANCEL):
  228.          gAlert = 0
  229.          Draw ()
  230.       if (event==EVENT_OPTIONS):
  231.          type = ExportOptions.val
  232.          Draw ()
  233.       if (event==EVENT_TYPE):
  234.          exporttype = ExportType.val
  235.          Draw ()
  236.       if (event==EVENT_EXPORT_ERR):
  237.          gAlert = 0
  238.          Draw ()
  239.       if (event==EVENT_DONE):  
  240.          gAlert = 0
  241.          Draw ()
  242.       if (event==EVENT_QUIT):
  243.          ExitGUI()
  244.  
  245. #================================
  246. def DrawGUI():
  247. #================================
  248.       global type
  249.       global exporttype
  250.       global operation
  251.  
  252.       glClearColor (0.6,0.6,0.6,0)
  253.       glClear (GL_COLOR_BUFFER_BIT)
  254.  
  255.       global gFilename
  256.       global gAlert
  257.       global ExportOptions
  258.       global ExportType
  259.  
  260.       if (gAlert==0):
  261.          # Add in the copyright notice and title
  262.          glRasterPos2d(32, 380)
  263.          Text("Wavefront OBJ Importer/Exporter")
  264.          glRasterPos2d(32, 350)
  265.          Text("Copyright (C) Chris Lynch 2001")
  266.  
  267.          gFilename=String ("Filename: ",EVENT_PATHCHANGE,32,250,320,32,gFilename.val,255,"Full pathname and filename")
  268.          Button ("Export",EVENT_EXPORT,32,200,100,32)
  269.          Button ("Import",EVENT_IMPORT,252,200,100,32)
  270.          Button ("Select Import",EVENT_IMPORT_SELECT,355,200,100,32)
  271.          glRasterPos2d(32, 165)
  272.          Text("Select Export Options:")
  273.          options = "Export Options %t| Default %x1| Material Layers %x2| Obj Groups %x3| Standard %x4"
  274.          ExportOptions = Menu (options,EVENT_OPTIONS,200,150,150,32, type)
  275.          Button ("Done",EVENT_QUIT,142,50,100,32)
  276.          glRasterPos2d(32, 115)
  277.          Text("Export using ")
  278.          options = "Export Type %t| Mesh Coordinates %x1| Object Coordinates %x2"
  279.          ExportType = Menu (options,EVENT_TYPE,170,100,180,32, exporttype)
  280.          Button ("Done",EVENT_QUIT,142,50,100,32)
  281.  
  282.       elif (gAlert==1):
  283.          glRasterPos2i (32,250)
  284.          Text (gFilename.val+ " already exists. Save anyway?")
  285.          Button ("Save",EVENT_EXPORT_CHK,150,200,50,32)
  286.          Button ("Cancel",EVENT_EXPORT_CANCEL,250,200,50,32)
  287.          gAlert = 0
  288.       elif (gAlert==2):
  289.          glRasterPos2i (32,250)
  290.          Text (gFilename.val+ " cannot be found. Check directory and filename.")
  291.          Button ("Continue",EVENT_IMPORT_CONT,32,190,70,32)
  292.          gAlert = 0
  293.       elif gAlert == 3:
  294.          glRasterPos2i (32,250)
  295.          Text ("No objects selected to export. You must select one or more objects.")
  296.          Button ("Continue",EVENT_EXPORT_ERR,192,200,70,32)
  297.          gAlert = 0
  298.       elif gAlert == 5:
  299.          glRasterPos2i (32,250)
  300.          Text ("Invalid directory path.")
  301.          Button ("Continue",EVENT_EXPORT_ERR,192,200,70,32)
  302.          gAlert = 0
  303.       else:
  304.          glRasterPos2i (32,250)
  305.          Text (str(operation)+ " of " +str(gFilename.val)+ " done.")
  306.          Button ("Continue",EVENT_DONE,192,200,70,32)
  307.          
  308. #================================
  309. def RegisterGUI ():
  310. #================================
  311.     Register (DrawGUI,None,EventGUI)
  312.  
  313. #================================
  314. # MAIN SCRIPT
  315. #================================
  316. # Opens a file, writes data in it
  317. # and closes it up.
  318. #================================
  319. RegisterGUI()
  320.  
  321. #================================
  322. def ImportFunction (importName, type):
  323. #================================      
  324.       global gFilename
  325.       global gAlert
  326.  
  327.       try:
  328.          FILE=open (importName,"r")
  329.          
  330.          directory, Name = os.split(gFilename.val)
  331.          
  332.          
  333.          words = Name.split(".")
  334.          Name = words[0]
  335.          ObjImport(FILE, Name, gFilename.val)
  336.          FILE.close()
  337.          gAlert = 4
  338.          Draw ()
  339.       except IOError:
  340.          gAlert=2
  341.          Draw ()
  342.  
  343. #================================
  344. def ExportFunction (exportName, type):
  345. #================================      
  346.       global gFilename
  347.       global gAlert
  348.  
  349.       try:
  350.          FILE=open (exportName,"r")
  351.          FILE.close()
  352.          gAlert = 1
  353.          Draw ()
  354.       except IOError:
  355.  
  356.          directory, Name = os.split(gFilename.val)
  357.  
  358.          
  359.          if os.isdir(directory):
  360.             ExportFunctionOK(exportName, type)
  361.             Draw ()
  362.          else:
  363.             gAlert = 5
  364.             Draw ()
  365.  
  366. #================================
  367. def ExportFunctionOK (exportName, type):
  368. #================================      
  369.       global gFilename
  370.       global gAlert
  371.       global returncode
  372.  
  373.       FILE=open (exportName,"w")
  374.  
  375.       directory, Name = os.split(gFilename.val)
  376.      
  377.       words = Name.split(".")
  378.       Name = words[0]
  379.       ObjExport(FILE, Name, type)
  380.       if returncode > 0:
  381.          gAlert = 3
  382.       else:
  383.          gAlert = 4
  384.       FILE.flush()
  385.       FILE.close()
  386.  
  387. #=========================
  388. def ObjImport(file, Name, filename):
  389. #=========================  
  390.     vcount     = 0
  391.     vncount    = 0
  392.     vtcount    = 0
  393.     fcount     = 0
  394.     gcount     = 0
  395.     setcount   = 0
  396.     groupflag  = 0
  397.     objectflag = 0
  398.     mtlflag    = 0
  399.     baseindex  = 0
  400.     basevtcount = 0
  401.     basevncount = 0
  402.     matindex   = 0
  403.  
  404.     pointList    = []
  405.     uvList       = []
  406.     normalList   = []
  407.     faceList     = []
  408.     materialList = []
  409.     imagelist    = []
  410.    
  411.     uv = []
  412.     lines = file.readlines()
  413.     linenumber = 1
  414.  
  415.     for line in lines:
  416.         words = line.split()
  417.         if words and words[0] == "#":
  418.             pass # ignore comments
  419.         elif words and words[0] == "v":
  420.             vcount = vcount + 1
  421.             x = float(words[1])
  422.             y = float(words[2])
  423.             z = float(words[3])
  424.             pointList.append([x, y, z])
  425.  
  426.         elif words and words[0] == "vt":
  427.             vtcount = vtcount + 1
  428.             u = float(words[1])
  429.             v = float(words[2])
  430.             uvList.append([u, v])
  431.  
  432.         elif words and words[0] == "vn":
  433.             vncount = vncount + 1
  434.             i = float(words[1])
  435.             j = float(words[2])
  436.             k = float(words[3])
  437.             normalList.append([i, j, k])
  438.  
  439.         elif words and words[0] == "f":
  440.             fcount = fcount + 1
  441.             vi = [] # vertex  indices
  442.             ti = [] # texture indices
  443.             ni = [] # normal  indices
  444.             words = words[1:]
  445.             lcount = len(words)
  446.             for index in (xrange(lcount)):
  447.                if words[index].find( "/") == -1:
  448.                      vindex = int(words[index])
  449.                      if vindex < 0: vindex = baseindex + vindex + 1  
  450.                      vi.append(vindex)
  451.                else:
  452.                    vtn = words[index].split( "/")
  453.                    vindex = int(vtn[0])
  454.                    if vindex < 0: vindex = baseindex + vindex + 1
  455.                    vi.append(vindex)
  456.            
  457.                    if len(vtn) > 1 and vtn[1]:
  458.                       tindex = int(vtn[1])
  459.                       if tindex < 0: tindex = basevtcount +tindex + 1
  460.                       ti.append(tindex)
  461.  
  462.                    if len(vtn) > 2 and vtn[2]:
  463.                       nindex = int(vtn[2])
  464.                       if nindex < 0: nindex = basevncount +nindex + 1
  465.                       ni.append(nindex)
  466.             faceList.append([vi, ti, ni, matindex])
  467.  
  468.         elif words and words[0] == "o":
  469.             ObjectName = words[1]
  470.             objectflag = 1
  471.             #print "Name is %s" % ObjectName
  472.  
  473.         elif words and words[0] == "g":
  474.             groupflag = 1
  475.             index = len(words)
  476.             if objectflag == 0:
  477.                objectflag = 1
  478.                if index > 1:
  479.                   ObjectName = words[1].join("_")
  480.                   GroupName = words[1].join("_")
  481.                else:
  482.                   ObjectName = "Default"
  483.                   GroupName = "Default"
  484.                #print "Object name is %s" % ObjectName
  485.                #print "Group name is %s" % GroupName
  486.             else:
  487.                if index > 1:
  488.                   GroupName = join(words[1],"_")
  489.                else:
  490.                   GroupName = "Default"
  491.                #print "Group name is %s" % GroupName
  492.                  
  493.             if mtlflag == 0:
  494.                matindex = AddMeshMaterial(GroupName,materialList, matindex)
  495.             gcount = gcount + 1
  496.                
  497.             if fcount > 0:
  498.                baseindex = vcount
  499.                basevncount = vncount
  500.                basevtcount = vtcount
  501.  
  502.         elif words and words[0] == "mtllib":
  503.             # try to export materials
  504.             directory, dummy = os.split(filename)
  505.             filename = os.join(directory, words[1])
  506.             print  "try to import : ",filename
  507.             try:
  508.                 file = open(filename, "r")
  509.             except:
  510.                 print "no material file %s" % filename
  511.             else:
  512.                 mtlflag = 0
  513.                 file = open(filename, "r")
  514.                 line = file.readline()
  515.                 mtlflag = 1
  516.                 while line:
  517.                     words = line.split()
  518.                     if words and words[0] == "newmtl":
  519.                       name = words[1]
  520.                       line = file.readline()  # Ns ?
  521.                       words = line.split()
  522.                       while words[0] not in ["Ka","Kd","Ks","map_Kd"]:
  523.                           line = file.readline()
  524.                           words = line.split()
  525.                              
  526.                       if words[0] == "Ka":
  527.                         Ka = [float(words[1]),
  528.                               float(words[2]),
  529.                               float(words[3])]
  530.                         line = file.readline()  # Kd
  531.                         words = line.split()
  532.                        
  533.                       if words[0] == "Kd":
  534.                         Kd = [float(words[1]),
  535.                               float(words[2]),
  536.                               float(words[3])]
  537.                         line = file.readline()  # Ks
  538.                         words = line.split()
  539.                          
  540.                       if words[0] == "Ks":
  541.                         Ks = [float(words[1]),
  542.                               float(words[2]),
  543.                               float(words[3])]
  544.                          
  545.                       if words[0] == "map_Kd":
  546.                         Kmap= words[1]
  547.                         img=os.join(directory, Kmap)
  548.                         im=Blender.Image.Load(img)
  549.                         words = line.split()
  550.                          
  551.                       matindex = AddGlobalMaterial(name, matindex)                            
  552.                       matlist = Material.Get()
  553.                        
  554.                       if len(matlist) > 0:
  555.                          if name!='defaultMat':
  556.                              material = matlist[matindex]
  557.                              material.R = Kd[0]
  558.                              material.G = Kd[1]
  559.                              material.B = Kd[2]
  560.                              try:
  561.                                   material.specCol[0] = Ks[0]
  562.                                   material.specCol[1] = Ks[1]
  563.                                   material.specCol[2] = Ks[2]
  564.                              except:
  565.                                   pass
  566.                              try:
  567.                                   alpha = 1 - ((Ka[0]+Ka[1]+Ka[2])/3)
  568.                              except:
  569.                                   pass
  570.                              try:
  571.                                   material.alpha = alpha
  572.                              except:
  573.                                   pass
  574.  
  575.                              try:
  576.                                  
  577.                                  img=os.join(directory, Kmap)
  578.                                  im=Blender.Image.Load(img)
  579.                                  imagelist.append(im)
  580.                              
  581.                                  t=Blender.Texture.New(Kmap)
  582.                                  t.setType('Image')
  583.                                  t.setImage(im)
  584.                              
  585.                                  material.setTexture(0,t)
  586.                                  material.getTextures()[0].texco=16
  587.                              except:
  588.                                   pass
  589.                                
  590.                          else:
  591.                              material = matlist[matindex]
  592.                              
  593.                              material.R = 0.8
  594.                              material.G = 0.8
  595.                              material.B = 0.8
  596.                              material.specCol[0] = 0.5
  597.                              material.specCol[1] = 0.5
  598.                              material.specCol[2] = 0.5
  599.                              
  600.                              img=os.join(directory, Kmap)
  601.                              im=Blender.Image.Load(img)
  602.                              imagelist.append(im)
  603.                              
  604.                              t=Blender.Texture.New(Kmap)
  605.                              t.setType('Image')
  606.                              t.setImage(im)
  607.                              
  608.                              material.setTexture(0,t)
  609.                              material.getTextures()[0].texco=16
  610.                        
  611.                       else:
  612.                          mtlflag = 0
  613.                              
  614.                     line = file.readline()
  615.                          
  616.                        
  617.                 file.close()
  618.                  
  619.         elif words and words[0] == "usemtl":
  620.             if mtlflag == 1:
  621.                name = words[1]
  622.                matindex = AddMeshMaterial(name, materialList, matindex)
  623.         elif words:  
  624.             print "%s: %s" % (linenumber, words)
  625.         linenumber = linenumber + 1
  626.     file.close()
  627.  
  628.     # import in Blender
  629.  
  630.     print "import into Blender ..."
  631.     mesh   = NMesh.GetRaw ()
  632.  
  633.     i = 0
  634.     while i < vcount:
  635.       x, y, z = pointList[i]
  636.       vert=NMesh.Vert(x, y, z)
  637.       mesh.verts.append(vert)
  638.       i=i+1
  639.  
  640.     if vtcount > 0:
  641.        #mesh.hasFaceUV() = 1
  642.        print ("Object has uv coordinates")
  643.  
  644.     if len(materialList) > 0:
  645.        for m in materialList:
  646.           try:
  647.             M=Material.Get(m)
  648.             mesh.materials.append(M)
  649.           except:
  650.             pass
  651.  
  652.     total = len(faceList)
  653.     i = 0
  654.  
  655.     for f in faceList:
  656.         if i%1000 == 0:
  657.           print ("Progress = "+ str(i)+"/"+ str(total))
  658.  
  659.         i = i + 1
  660.         vi, ti, ni, matindex = f
  661.         face=NMesh.Face()
  662.         if len(materialList) > 0:
  663.            face.mat = matindex
  664.  
  665.         limit = len(vi)
  666.         setcount = setcount + len(vi)
  667.         c = 0    
  668.    
  669.         while c < limit:
  670.           m = vi[c]-1
  671.           if vtcount > 0 and len(ti) > c:
  672.              n = ti[c]-1
  673.           if vncount > 0 and len(ni) > c:
  674.              p = ni[c]-1
  675.  
  676.           if vtcount > 0:
  677.              try:
  678.                   u, v = uvList[n]
  679.              except:
  680.                   pass
  681.  
  682.              """
  683.        #  multiply uv coordinates by 2 and add 1. Apparently blender uses uv range of 1 to 3 (not 0 to 1).
  684.             mesh.verts[m].uvco[0] = (u*2)+1
  685.             mesh.verts[m].uvco[1] = (v*2)+1
  686.            """
  687.  
  688.           if vncount > 0:
  689.              if p > len(normalList):
  690.                 print("normal len = " +str(len(normalList))+ " vector len = " +str(len(pointList)))
  691.                 print("p = " +str(p))
  692.              x, y, z = normalList[p]  
  693.              mesh.verts[m].no[0] = x
  694.              mesh.verts[m].no[1] = y
  695.              mesh.verts[m].no[2] = z
  696.           c = c+1  
  697.      
  698.         if len(vi) < 5:
  699.           for index in vi:
  700.             face.v.append (mesh.verts[index-1])
  701.  
  702.           if vtcount > 0:  
  703.             for index in ti:
  704.                u, v = uvList[index-1]
  705.                face.uv.append((u,v))
  706.                
  707.             if len(imagelist)>0:
  708.                 face.image=imagelist[0]
  709.                 #print
  710.                
  711.           if vcount>0:
  712.              face.smooth=1
  713.  
  714.           mesh.faces.append(face)
  715.  
  716.     print "all other (general) polygons ..."
  717.     for f in faceList:
  718.         vi, ti, ni, matindex = f
  719.         if len(vi) > 4:
  720.             # export the polygon as edges
  721.             print ("Odd face, vertices = "+ str(len(vi)))
  722.             for i in range(len(vi)-2):
  723.                face = NMesh.Face()
  724.                if len(materialList) > 0:
  725.                   face.mat = matindex
  726.                face.v.append(mesh.verts[vi[0]-1])
  727.                face.v.append(mesh.verts[vi[i+1]-1])
  728.                face.v.append(mesh.verts[vi[i+2]-1])
  729.  
  730.                if vtcount > 0:
  731.                   if len(ti) > i+2:
  732.                      u, v = uvList[ti[0]-1]
  733.                      face.uv.append((u,v))
  734.                      u, v = uvList[ti[i+1]-1]
  735.                      face.uv.append((u,v))
  736.                      u, v = uvList[ti[i+2]-1]
  737.                      face.uv.append((u,v))
  738.  
  739.                mesh.faces.append(face)
  740.      
  741.     NMesh.PutRaw(mesh, Name,1)
  742.  
  743.     print ("Total number of vertices is "+ str(vcount))
  744.     print ("Total number of faces is "+ str(len(faceList)))
  745.     print ("Total number of sets is "+ str(setcount))
  746.  
  747.  
  748.     print("Finished importing " +str(Name)+ ".obj")
  749.  
  750. #=========================================
  751. def AddMeshMaterial(name, materialList, matindex):
  752. #=========================================
  753.    
  754.    index = 0
  755.    found = 0
  756.    limit = len(materialList)
  757.  
  758.    while index < limit:
  759.      if materialList[index] == name:
  760.         matindex = index
  761.         found = 1
  762.         index = limit
  763.      index = index + 1
  764.    
  765.    if found == 0:      
  766.       materialList.append(name)
  767.       matindex = len(materialList)-1
  768.        
  769.    return matindex
  770.  
  771. #=========================================
  772. def AddGlobalMaterial (name, matindex):
  773. #=========================================
  774.    
  775.    index = 0
  776.    found = 0
  777.    matindex  = 0
  778.    MatList = Material.Get()
  779.    limit = len(MatList)
  780.  
  781.    while index < limit:
  782.      if MatList[index].name == name:
  783.         matindex = index
  784.         found = 1
  785.         index = limit
  786.      index = index + 1
  787.  
  788.    if found == 0:
  789.       material = Material.New(name)
  790.       matindex = index
  791.    
  792.    return matindex
  793.  
  794. #================================
  795. def ObjExport(FILE, Name, type):
  796. #================================
  797.   global returncode
  798.   global vertexcount
  799.   global uvcount
  800.   global Transform
  801.   global multiflag
  802.   global exporttype
  803.  
  804.   vertexcount = 0
  805.   uvcount = 0
  806.   returncode = 0
  807.   print("Writing %s..." % Name)
  808.   FILE.write("# Wavefront OBJ (1.0) exported by lynx's OBJ import/export script\n\n")
  809.  
  810.   Objects = Object.GetSelected()
  811.   if Objects == []:
  812.      print("You have not selected an object!")
  813.      returncode = 4
  814.   else:
  815.      for object in Objects:
  816.         MtlList = []
  817.         if len(Objects) > 1 or exporttype > 1:
  818.            Transform = CreateMatrix(object, Transform)
  819.            multiflag = 1
  820.            
  821.         mesh = NMesh.GetRawFromObject(object.name)
  822.         ObjName = mesh.name
  823.         has_uvco = mesh.hasVertexUV()
  824.  
  825.         FILE.write("# Meshname:\t%s\n" % ObjName)
  826.  
  827.         faces = mesh.faces
  828.         materials = mesh.materials
  829.         Vertices = mesh.verts
  830.         GlobalMaterials = Material.Get()
  831.  
  832.         if len(materials) > 1 and len(GlobalMaterials) > 0 and type < 4:
  833.            CreateMtlFile(Name, materials, MtlList)
  834.  
  835.         # Total Vertices and faces; comment if not useful
  836.         FILE.write("# Total number of Faces:\t%s\n" % len(faces))
  837.         FILE.write("# Total number of Vertices:\t%s\n" % len(Vertices))
  838.  
  839.         FILE.write("\n")
  840.  
  841.         # print first image map for uvcoords to use
  842.         # to be updated when we get access to other textures
  843.         if mesh.hasFaceUV(): FILE.write("# UV Texture:\t%s\n\n" % mesh.hasFaceUV())
  844.  
  845.         if len(materials) > 1 and len(GlobalMaterials) > 0 and type < 3:
  846.            UseLayers(faces, Vertices, MtlList, has_uvco, FILE, ObjName, Name)
  847.         elif len(materials) > 1 and len(GlobalMaterials) > 0 and type == 3:
  848.            UseMtl(faces, Vertices, MtlList, has_uvco, FILE, ObjName, Name)
  849.         else:
  850.            Standard(faces, Vertices, has_uvco, FILE, ObjName)
  851.  
  852. #================================================
  853. def CreateMtlFile (name, MeshMaterials, MtlList):
  854. #================================================
  855.       global gFilename
  856.  
  857.     # try to export materials
  858.       directory, mtlname = os.split(gFilename.val)
  859.       mtlname = name + ".mtl"
  860.       filename = os.join(directory, mtlname)
  861.       file = open(filename, "w")
  862.  
  863.       file.write("# Materials for %s.\n" % (name + ".obj"))
  864.       file.write("# Created by Blender.\n")
  865.       file.write("# These files must be in the same directory for the materials to be read correctly.\n\n")
  866.  
  867.       MatList = Material.Get()
  868.       print str(MeshMaterials)
  869.  
  870.       MtlNList=[]
  871.       for m in  MatList:
  872.          MtlNList.append(m.name)
  873.  
  874.       counter = 1
  875.       found = 0  
  876.  
  877.       for material in MeshMaterials:
  878.          for mtl in MtlList:
  879.             if material == mtl:
  880.                 found = 1
  881.  
  882.          MtlList.append(material)
  883.  
  884.          if found == 0:
  885.             file.write("newmtl %s \n" % material.name)
  886.             index = 0
  887.             print material, MatList
  888.             while index < len(MatList):
  889.                if material.name == MatList[index].name:
  890.                   mtl = MatList[index]
  891.                   index = len(MatList)
  892.                   found = 1
  893.                index = index + 1
  894.  
  895.             if found == 1:
  896.                alpha = mtl.getAlpha()
  897.                file.write("       Ka %s %s %s \n" % (round(1-alpha,5), round(1-alpha,5), round(1-alpha,5)))
  898.                file.write("       Kd %s %s %s \n" % (round(mtl.R,5), round(mtl.G,5), round(mtl.B,5)))
  899.                file.write("       Ks %s %s %s \n" % (round(mtl.specCol[0],5), round(mtl.specCol[1],5), round(mtl.specCol[2],5)))
  900.                file.write("       illum 1\n")
  901.                
  902.             else:
  903.                file.write("       Ka %s %s %s \n" % (0, 0, 0))
  904.                file.write("       Kd %s %s %s \n" % (1, 1, 1))
  905.                file.write("       Ks %s %s %s \n" % (1, 1, 1))
  906.                file.write("       illum 1\n")
  907.  
  908.          found = 0
  909.  
  910.       file.flush()
  911.       file.close()
  912.  
  913. #===========================================================
  914. def Standard(faces, Vertices, has_uvco, FILE, ObjName):
  915. #===========================================================
  916.        global vertexcount
  917.        global uvcount
  918.        global multiflag
  919.  
  920.        uvPtrs = []
  921.        uvList = []
  922.  
  923.        FILE.write("o %s\n\n" % (ObjName))
  924.        FILE.write("g %s\n\n" % (ObjName))
  925.  
  926.        for v in Vertices:
  927.           vert = v.co
  928.           if multiflag  == 1:
  929.              vert = Alter(vert, Transform)
  930.           x, y, z = vert
  931.                
  932.           FILE.write("v %s %s %s\n" % (x, y, z))
  933.  
  934.        uv_flag = 0
  935.        for face in faces:
  936.          for uv in face.uv:
  937.             found = 0
  938.             index = len(uvList)
  939.             limit = 0
  940.             if len(uvList)-200 > 0:
  941.                limit = len(uvList)-200
  942.             while index > limit and found == 0:
  943.                uv_value = uvList[index-1]
  944.                if uv[0] == uv_value[0] and uv[1] == uv_value[1]:
  945.                   uvPtrs.append(index+uvcount)
  946.                   found = 1
  947.                index = index - 1
  948.             if found == 0:
  949.                uvList.append(uv)
  950.                index = len(uvList)
  951.                uvPtrs.append(index+uvcount)
  952.                u, v = uv
  953.                FILE.write("vt %s %s\n" % (u, v))
  954.                uv_flag = 1
  955.  
  956.        if has_uvco and uv_flag == 0:
  957.          for v in Vertices:
  958.             u, v, z = v.uvco
  959.             u = (u-1)/2
  960.             v = (v-1)/2
  961.             FILE.write("vt %s %s\n" % (u, v))
  962.  
  963.        for v in Vertices:
  964.           x, y, z = v.no
  965.           FILE.write("vn %s %s %s\n" % (x, y, z))
  966.  
  967.        p = 0
  968.        uvindex = 0
  969.        total = len(faces)
  970.  
  971.        for face in faces:
  972.           p = p+1
  973.           if (p%1000) == 0:
  974.               print ("Progress = "+ str(p)+ " of "+ str(total) +" faces")
  975.  
  976.           FILE.write("f ")
  977.           for index in range(len(face.v)):
  978.              v = face.v[index].index + vertexcount
  979.              if len(face.uv) > 0:
  980.                 FILE.write("%s/%s/%s " % (v+1, uvPtrs[uvindex], v+1))
  981.                 uvindex = uvindex+1
  982.              elif has_uvco:
  983.                 FILE.write("%s/%s/%s " % (v+1, v+1, v+1))
  984.              else:                    
  985.                 FILE.write("%s//%s " % (v+1, v+1))
  986.           FILE.write("\n")
  987.  
  988.        vertexcount = vertexcount + len(Vertices)
  989.        uvcount = uvcount + len(uvList)
  990.  
  991.        print("Export of " +str(ObjName)+ ".obj finished.\n")
  992.  
  993. #=====================================================================
  994. def UseLayers(faces, Vertices, MtlList, has_uvco, FILE, ObjName, Name):
  995. #=====================================================================
  996.        global vertexcount
  997.        global uvcount
  998.        global multiflag
  999.  
  1000.        uvPtrs = []
  1001.        uvList = []
  1002.  
  1003.        FILE.write("mtllib %s\n\n" % (Name + ".mtl"))
  1004.        FILE.write("g %s\n\n" % (ObjName))
  1005.  
  1006.        for v in Vertices:
  1007.           vert = v.co
  1008.           if multiflag  == 1:
  1009.              vert = Alter(vert, Transform)  
  1010.           x, y, z = vert
  1011.           FILE.write("v %s %s %s\n" % (x, y, z))
  1012.  
  1013.        uv_flag = 0
  1014.        for m in range(len(MtlList)):
  1015.           for face in faces:
  1016.               if face.mat == m:
  1017.                  for uv in face.uv:
  1018.                     found = 0
  1019.                     index = len(uvList)
  1020.                     limit = 0
  1021.                     if len(uvList)-200 > 0:
  1022.                        limit = len(uvList)-200
  1023.                     while index > limit and found == 0:
  1024.                        uv_value = uvList[index-1]
  1025.                        if uv[0] == uv_value[0] and uv[1] == uv_value[1]:
  1026.                           uvPtrs.append(index+uvcount)
  1027.                           found = 1
  1028.                        index = index - 1
  1029.                     if found == 0:
  1030.                        uvList.append(uv)
  1031.                        index = len(uvList)
  1032.                        uvPtrs.append(index+uvcount)
  1033.                        u, v = uv
  1034.                        FILE.write("vt %s %s\n" % (u, v))
  1035.                        uv_flag = 1
  1036.  
  1037.        if has_uvco and uv_flag == 0:
  1038.          for v in Vertices:
  1039.             u, v, z = v.uvco
  1040.             u = (u-1)/2
  1041.             v = (v-1)/2
  1042.             FILE.write("vt %s %s\n" % (u, v))
  1043.  
  1044.        for v in Vertices:
  1045.           x, y, z = v.no
  1046.           FILE.write("vn %s %s %s\n" % (x, y, z))
  1047.  
  1048.        total = len(faces)
  1049.        p = 0
  1050.        uvindex = 0
  1051.        for m in range(len(MtlList)):        
  1052.           FILE.write("usemtl %s\n" % (MtlList[m].name))
  1053.           for face in faces:
  1054.               if face.mat == m:
  1055.                 p = p+1
  1056.                 if (p%1000) == 0:
  1057.                    print ("Progress = "+ str(p)+ " of "+ str(total) +" faces")
  1058.  
  1059.                 FILE.write("f ")
  1060.                 for index in range(len(face.v)):
  1061.                    v = face.v[index].index + vertexcount
  1062.                    if len(face.uv) > 0:
  1063.                       FILE.write("%s/%s/%s " % (v+1, uvPtrs[uvindex], v+1))
  1064.                       uvindex = uvindex+1
  1065.                    elif has_uvco:
  1066.                       FILE.write("%s/%s/%s " % (v+1, v+1, v+1))
  1067.                    else:
  1068.                       FILE.write("%s//%s " % (v+1, v+1))
  1069.                 FILE.write("\n")
  1070.  
  1071.        vertexcount = vertexcount + len(Vertices)
  1072.        print("Export of " +str(ObjName)+ ".obj using material layers finished.\n")
  1073.  
  1074. #==================================================================
  1075. def UseMtl(faces, Vertices, MtlList, has_uvco, FILE, ObjName, Name):
  1076. #==================================================================
  1077.        global vertexcount
  1078.        global multiflag
  1079.  
  1080.        FILE.write("mtllib %s\n\n" % (Name + ".mtl"))
  1081.        FILE.write("o %s\n\n" % (ObjName))
  1082.        
  1083.        index = 0
  1084.        VertexList = []
  1085.        for vertex in Vertices:
  1086.           VertexList.append(-1)
  1087.           index = index + 1
  1088.        print("number of vertices is " +str(len(VertexList)))
  1089.  
  1090.        Totalindex = 0
  1091.        ix = 0
  1092.        NewVertexList = []
  1093.        NewVertexCo = []
  1094.        for m in range(len(MtlList)):
  1095.            # Group name is the name of the mesh
  1096.            if MtlList[m]:
  1097.               FILE.write("g %s\n" % (MtlList[m].name+str(m+1)))
  1098.            else:
  1099.               FILE.write("g %s\n" % ("Null"+str(m+1)))
  1100.            FILE.write("s off\n\n")
  1101.          
  1102.            FILE.write("usemtl %s\n\n" % (MtlList[m].name))
  1103.  
  1104.            for face in faces:
  1105.               if face.mat == m:
  1106.                  for vertex in face.v:
  1107.                     v = vertex.index
  1108.                     if VertexList[v] < 0:
  1109.                        VertexList[v] = Totalindex
  1110.                        NewVertexList.append(v)
  1111.                        Totalindex = Totalindex + 1
  1112.  
  1113.            for v_old in NewVertexList:
  1114.               vert = Vertices[v_old].co
  1115.               if multiflag  == 1:
  1116.                 vert = Alter(vert, Transform)
  1117.               x, y, z = vert
  1118.               FILE.write("v %s %s %s\n" % (x, y, z))
  1119.               NewVertexCo.append([x,y,z])
  1120.  
  1121.            if has_uvco:
  1122.               for v_old in NewVertexList:
  1123.                  u, v, z = Vertices[v_old].uvco
  1124.                  u = (u-1)/2
  1125.                  v = (v-1)/2              
  1126.                  FILE.write("vt %s %s\n" % (u, v))
  1127.  
  1128.            for v_old in NewVertexList:
  1129.               x, y, z = Vertices[v_old].no
  1130.               FILE.write("vn %s %s %s\n" % (x, y, z))
  1131.  
  1132.            for face in faces:
  1133.              if face.mat == m:
  1134.                 FILE.write("f ")
  1135.                 for index in range(len(face.v)):
  1136.                    v = face.v[index].index
  1137.                    v_new = VertexList[v]
  1138.                    if has_uvco:
  1139.                       FILE.write("%s/%s/%s " % (v_new+1, v_new+1, v_new+1))
  1140.                    else:
  1141.                       FILE.write("%s//%s " % (v_new+1, v_new+1))
  1142.                 FILE.write("\n")
  1143.  
  1144.            FILE.write("\n")
  1145.  
  1146.            NewVertexList = []
  1147.            print("Group " +str(m+1)+ " of " +str(len(MtlList))+ " finished.")
  1148.  
  1149.        print("Export of " +str(ObjName)+ ".obj using groups finished.\n")
  1150.  
  1151. #========================================
  1152. def CreateMatrix(object, Transform):
  1153. #========================================
  1154.    Mx = []
  1155.    My = []
  1156.    Mz = []
  1157.    T1 = []
  1158.    Transform = []
  1159.  
  1160.    angle = object.RotX
  1161.    Mx.append([1, 0, 0])
  1162.    y = math.cos(angle)
  1163.    z = -math.sin(angle)
  1164.    Mx.append([0, y, z])
  1165.    y = math.sin(angle)
  1166.    z = math.cos(angle)
  1167.    Mx.append([0, y, z])
  1168.  
  1169.    angle = object.RotY
  1170.    x = math.cos(angle)
  1171.    z = math.sin(angle)
  1172.    My.append([x, 0, z])
  1173.    My.append([0, 1, 0])
  1174.    x = -math.sin(angle)
  1175.    z = math.cos(angle)
  1176.    My.append([x, 0, z])
  1177.  
  1178.    angle = object.RotZ
  1179.    x = math.cos(angle)
  1180.    y = -math.sin(angle)
  1181.    Mz.append([x, y, 0])
  1182.    x = math.sin(angle)
  1183.    y = math.cos(angle)
  1184.    Mz.append([x, y, 0])
  1185.    Mz.append([0, 0, 1])
  1186.  
  1187.    m0 = Mx[0]
  1188.    m1 = Mx[1]
  1189.    m2 = Mx[2]
  1190.    for row in My:
  1191.       x, y, z = row
  1192.       nx = x*m0[0] + y*m1[0] + z*m2[0]
  1193.       ny = x*m0[1] + y*m1[1] + z*m2[1]
  1194.       nz = x*m0[2] + y*m1[2] + z*m2[2]
  1195.       T1.append([nx, ny, nz])
  1196.  
  1197.    m0 = T1[0]
  1198.    m1 = T1[1]
  1199.    m2 = T1[2]
  1200.    for row in Mz:
  1201.      x, y, z = row
  1202.      nx = x*m0[0] + y*m1[0] + z*m2[0]
  1203.      ny = x*m0[1] + y*m1[1] + z*m2[1]
  1204.      nz = x*m0[2] + y*m1[2] + z*m2[2]
  1205.      Transform.append([nx, ny, nz])
  1206.  
  1207.    Transform.append([object.SizeX, object.SizeY, object.SizeZ])
  1208.    Transform.append([object.LocX, object.LocY, object.LocZ])
  1209.  
  1210.    return Transform
  1211.  
  1212. #======================================
  1213. def Alter(vect, Transform):
  1214. #======================================
  1215.    v2 = []
  1216.    nv = []
  1217.  
  1218.    x, y, z = vect
  1219.    sx, sy, sz = Transform[3]
  1220.    lx, ly, lz = Transform[4]
  1221.  
  1222.    v2.append(x*sx)
  1223.    v2.append(y*sy)
  1224.    v2.append(z*sz)
  1225.  
  1226.    for index in range(len(vect)):
  1227.       t = Transform[index]
  1228.       nv.append(v2[0]*t[0] + v2[1]*t[1] +v2[2]*t[2])
  1229.  
  1230.    nv[0] = nv[0]+lx
  1231.    nv[1] = nv[1]+ly
  1232.    nv[2] = nv[2]+lz
  1233.  
  1234.    return nv
Advertisement
Add Comment
Please, Sign In to add comment