home *** CD-ROM | disk | FTP | other *** search
/ Windows News 2005 November / WNnov2005.iso / Windows / Equipement / Blender / blender-2.37a-windows.exe / $_5_ / .blender / scripts / bpymodules / eps2obj.py < prev    next >
Text File  |  2005-06-13  |  15KB  |  446 lines

  1. #----------------------------------------------
  2. # (c) jm soler juillet 2004-juin 2005 , released under Blender Artistic Licence 
  3. #    for the Blender 2.34-2.37 Python Scripts Bundle.
  4. #----------------------------------------------
  5. # Page officielle :
  6. #   http://jmsoler.free.fr/didacticiel/blender/tutor/cpl_import_eps.htm
  7. # Communiquer les problemes et erreurs sur:
  8. #   http://www.zoo-logique.org/3D.Blender/newsportal/thread.php?group=3D.Blender
  9. #----------------------------------------------
  10. DEVELOPPEMENT   =   0
  11. SHARP_IMPORT    =   0
  12. SCALE           =   1.0
  13. scale           =   1
  14.  
  15. import sys
  16. #oldpath=sys.path
  17.  
  18. import Blender
  19. from Blender import Draw
  20. BLversion=Blender.Get('version')
  21.  
  22. try:
  23.     import nt
  24.     os=nt
  25.     os.sep='\\'
  26.  
  27. except:    
  28.     import posix
  29.     os=posix
  30.     os.sep='/'
  31.     
  32. def isdir(path):
  33.     try:
  34.         st = os.stat(path)
  35.         return 1 
  36.     except:
  37.         return 0
  38.     
  39. def split(pathname):
  40.          if pathname.find(os.sep)!=-1:
  41.              k0=pathname.split(os.sep)
  42.          else:
  43.             if os.sep=='/':
  44.                 k0=pathname.split('\\')
  45.             else:
  46.                 k0=pathname.split('/') 
  47.  
  48.          directory=pathname.replace(k0[len(k0)-1],'')
  49.          Name=k0[len(k0)-1]
  50.          return directory, Name
  51.         
  52. def join(l0,l1):        
  53.      return  l0+os.sep+l1
  54.     
  55. os.isdir=isdir
  56. os.split=split
  57. os.join=join
  58.  
  59. def filtreFICHIER(nom):
  60.      f=open(nom,'rU')
  61.      t=f.readlines()
  62.      f.close()
  63.      if len(t)==1 and t[0].find('\r'):
  64.               t=t[0].split('\r')
  65.      if len(t)>1 and t[0].find('PS-Adobe-3.0')==-1 and t[0].find('EPSF')==-1: 
  66.           return t   
  67.      else:
  68.          name = "OK?%t| Not a valid file or an empty file or... %x1| not a pure PS-Adobe-2.0 file %x2 "  
  69.          result = Blender.Draw.PupMenu(name)
  70.          return 'false'
  71.         
  72. #===============================
  73. # Data
  74. #===============================
  75. #===============================
  76. # Blender Curve Data
  77. #===============================
  78. objBEZIER=0
  79. objSURFACE=5
  80. typBEZIER3D=1  #3D
  81. typBEZIER2D=9  #2D
  82.  
  83. class Bez:
  84.       def __init__(self):
  85.            self.co=[]
  86.            self.ha=[0,0]
  87.            
  88. class ITEM:
  89.       def __init__(self):
  90.                self.type        =  typBEZIER3D,    
  91.                self.pntsUV      =  [0,0]              
  92.                self.resolUV     =  [32,0]            
  93.                self.orderUV     =  [0,0]             
  94.                self.flagUV      =  [0,0]              
  95.                self.Origine     =  [0.0,0.0]
  96.                self.beziers_knot = []
  97.  
  98. class COURBE:
  99.       def __init__(self):
  100.               self.magic_number='3DG3'              
  101.               self.type            =  objBEZIER        
  102.               self.number_of_items =  0              
  103.               self.ext1_ext2       =  [0,0]             
  104.               self.matrix          =  """0.0 0.0 1.0 0.0
  105. 0.0 1.0 0.0 0.0
  106. 0.0 0.0 1.0 0.0
  107. 0.0 0.0 0.0 1.0 """ #- right-handed object matrix. Used to determine position, rotation and size
  108.               self.ITEM            = {}
  109.  
  110. courbes=COURBE()
  111. PATTERN={}
  112. BOUNDINGBOX={'rec':[],'coef':1.0}
  113. npat=0
  114. #=====================================================================
  115. #======== name of the curve in teh courbes dictionnary ===============
  116. #=====================================================================
  117. n0=0
  118.  
  119. #=====================================================================
  120. #====================== current Point ================================
  121. #=====================================================================
  122. CP=[0.0,0.0] #currentPoint
  123.  
  124. # modifs 12/06/2005       
  125. #=====================================================================
  126. #====================== current transform ============================
  127. #=====================================================================
  128. class transform:
  129.       def __init__(self,matrix=[1,0,01],x=0.0,y=0.0):
  130.           self.matrix=matrix[:]
  131.           self.xy=[x,y]          
  132.  
  133. GSTACK          =   []
  134. stack=transform()
  135. GSTACK.append(stack)
  136.  
  137. GSCALE          =   [1.0,1.0]
  138. GTRANSLATE       =   [0.0,0.0]
  139.  
  140. def G_move(l,a):
  141.     global GSCALE, GTRANSLATE, GSTACK
  142.     #print GSCALE, GTRANSLATE, GSTACK
  143.     return str((float(l)+GTRANSLATE[a]+GSTACK[-1].xy[a])*GSCALE[a])
  144. # modifs 12/06/2005
  145.  
  146. #=====================================================================
  147. #===== to compare last position to the original move to displacement =
  148. #=====  needed for cyclic efinition  =================================
  149. #=====================================================================
  150. def test_egalitedespositions(f1,f2):
  151.     if f1[0]==f2[0] and f1[1]==f2[1]:
  152.        return Blender.TRUE
  153.     else:
  154.        return Blender.FALSE
  155.  
  156.  
  157. def Open_GEOfile(dir,nom):
  158.     global SCALE,BOUNDINGBOX, scale
  159.     if BLversion>=233:
  160.        Blender.Load(dir+nom+'OOO.obj', 1)
  161.        BO=Blender.Object.Get()
  162.  
  163.        BO[-1].RotY=3.1416
  164.        BO[-1].RotZ=3.1416
  165.        BO[-1].RotX=3.1416/2.0
  166.        if scale==1:
  167.           BO[-1].LocY+=BOUNDINGBOX['rec'][3]
  168.        else:
  169.          BO[-1].LocY+=BOUNDINGBOX['rec'][3]/SCALE
  170.  
  171.        BO[-1].makeDisplayList() 
  172.        Blender.Window.RedrawAll()
  173.     else:
  174.        print "Not yet implemented"
  175.  
  176. def create_GEOtext(courbes):
  177.     global SCALE, B, BOUNDINGBOX,scale
  178.     r=BOUNDINGBOX['rec']
  179.  
  180.     if scale==1:
  181.        SCALE=1.0
  182.     elif scale==2:
  183.        SCALE=r[2]-r[0]
  184.     elif scale==3:
  185.        SCALE=r[3]-r[1]
  186.  
  187.     t=[]
  188.     t.append(courbes.magic_number+'\n')
  189.     t.append(str(courbes.type)+'\n')
  190.     t.append(str(courbes.number_of_items)+'\n')
  191.     t.append(str(courbes.ext1_ext2[0])+' '+str(courbes.ext1_ext2[1])+'\n')
  192.     t.append(courbes.matrix+'\n')
  193.     
  194.     for k in courbes.ITEM.keys():
  195.         t.append("%s\n"%courbes.ITEM[k].type)
  196.         t.append("%s %s \n"%(courbes.ITEM[k].pntsUV[0],courbes.ITEM[k].pntsUV[1]))
  197.         t.append("%s %s \n"%(courbes.ITEM[k].resolUV[0],courbes.ITEM[k].resolUV[1]))
  198.         t.append("%s %s \n"%(courbes.ITEM[k].orderUV[0],courbes.ITEM[k].orderUV[1]))
  199.         t.append("%s %s \n"%(courbes.ITEM[k].flagUV[0],courbes.ITEM[k].flagUV[1]))
  200.  
  201.         flag =courbes.ITEM[k].flagUV[0]
  202.  
  203.         for k2 in range(flag,len(courbes.ITEM[k].beziers_knot)):
  204.            k1 =courbes.ITEM[k].beziers_knot[k2]
  205.            t.append("%4f 0.0 %4f \n"%(float(k1.co[0])/SCALE,float(k1.co[1])/SCALE))
  206.            t.append("%4f 0.0 %4f \n"%(float(k1.co[2])/SCALE,float(k1.co[3])/SCALE))
  207.            t.append("%4f 0.0 %4f \n"%(float(k1.co[4])/SCALE,float(k1.co[5])/SCALE))
  208.            t.append(str(k1.ha[0])+' '+str(k1.ha[1])+'\n')
  209.     return t
  210.  
  211. def save_GEOfile(dir,nom,t):
  212.      f=open(dir+nom+'OOO.obj','w')
  213.      f.writelines(t)
  214.      f.close()
  215.  
  216.      #name = "REMINDER : %t | Do not forget to rename your blender file NOW ! %x1"
  217.      #result = Blender.Draw.PupMenu(name)
  218.  
  219.  
  220. #=====================================================================
  221. #=====      EPS format   :  DEBUT             =========================
  222. #=====================================================================
  223. def mouvement_vers(l,n0,CP):
  224.     if n0 in courbes.ITEM.keys():
  225.        #if  test_egalitedespositions(courbes.ITEM[n0].Origine,CP):
  226.        #   courbes.ITEM[n0].flagUV[0]=1 
  227.        n0+=1
  228.        CP=[l[-3].replace('d',''),l[-2]]        
  229.     else:
  230.        CP=[l[-3].replace('d',''),l[-2]] 
  231.     #i=
  232.     courbes.ITEM[n0]=ITEM() 
  233.     courbes.ITEM[n0].Origine=[l[-3].replace('d',''),l[-2]] 
  234.     
  235.     B=Bez()
  236.     B.co=[G_move(CP[0],0),
  237.           G_move(CP[1],1),
  238.           G_move(CP[0],0),
  239.           G_move(CP[1],1),
  240.           G_move(CP[0],0),
  241.           G_move(CP[1],1)]
  242.     
  243.     B.ha=[0,0]    
  244.     courbes.ITEM[n0].beziers_knot.append(B)       
  245.  
  246.     return  courbes,n0,CP     
  247.  
  248. def rmouvement_vers(l,n0,CP):
  249.     if n0 in courbes.ITEM.keys():
  250.        #if  test_egalitedespositions(courbes.ITEM[n0].Origine,CP):
  251.        #   courbes.ITEM[n0].flagUV[0]=1 
  252.        n0+=1
  253.        CP=["%4f"%(float(l[-3])+float(CP[0])),"%4f"%(float(l[-2])+float(CP[1]))] 
  254.     else:
  255.        CP=["%4f"%(float(l[-3])+float(CP[0])),"%4f"%(float(l[-2])+float(CP[1]))] 
  256.     #i=
  257.     courbes.ITEM[n0]=ITEM() 
  258.     courbes.ITEM[n0].Origine=[l[-3].replace('d',''),l[-2]] 
  259.     
  260.     B=Bez()
  261.     B.co=[CP[0],CP[1],CP[0],CP[1],CP[0],CP[1]]
  262.     B.ha=[0,0]    
  263.     courbes.ITEM[n0].beziers_knot.append(B)       
  264.     return  courbes,n0,CP     
  265.        
  266. def courbe_vers_c(l, l2, n0,CP): #c,C
  267.     """
  268.     B=Bez()
  269.     B.co=[l[0],l[1],l[2],l[3],l[4],l[5]]
  270.     B.ha=[0,0]
  271.  
  272.     courbes.ITEM[n0].beziers_knot.append(B)
  273.     """
  274.     B=Bez()
  275.     B.co=[G_move(l[2],0),
  276.           G_move(l[3],1),
  277.           G_move(l[4],0),
  278.           G_move(l[5],1),
  279.           G_move(l[0],0),
  280.           G_move(l[1],1)]
  281.     if len(courbes.ITEM[n0].beziers_knot)==1:
  282.        CP=[l[0],l[1]]
  283.        courbes.ITEM[n0].Origine=[l[0],l[1]]
  284.     if l[-1]=='C':  
  285.         B.ha=[2,2]
  286.     else:
  287.         B.ha=[0,0]
  288.     courbes.ITEM[n0].beziers_knot.append(B)
  289.     if len(l2)>1 and l2[-1] in Actions.keys():
  290.        B.co[-2]=G_move(l2[0],0)
  291.        B.co[-1]=G_move(l2[1],1)
  292.     else:
  293.        B.co[-2]=G_move(CP[0],0)
  294.        B.co[-1]=G_move(CP[1],1)
  295.     return  courbes,n0,CP
  296.       
  297. def ligne_tracee_l(l,n0,CP):
  298.     B=Bez()
  299.     B.co=[G_move(l[0],0),
  300.           G_move(l[1],1),
  301.           G_move(l[0],0),
  302.           G_move(l[1],1),
  303.           G_move(l[0],0),
  304.           G_move(l[1],1)]
  305.     B.ha=[0,0]
  306.     courbes.ITEM[n0].beziers_knot.append(B)    
  307.     CP=[l[0],l[1]]
  308.     return  courbes,n0,CP    
  309.  
  310. def rligne_tracee_l(l,n0,CP):
  311.     B=Bez()
  312.     B.co=["%4f"%(float(l[0])+float(CP[0])),
  313.           "%4f"%(float(l[1])+float(CP[1])),
  314.           "%4f"%(float(l[0])+float(CP[0])),
  315.           "%4f"%(float(l[1])+float(CP[1])),
  316.           "%4f"%(float(l[0])+float(CP[0])),
  317.           "%4f"%(float(l[1])+float(CP[1]))]   
  318.     B.ha=[0,0]
  319.     courbes.ITEM[n0].beziers_knot.append(B)    
  320.     CP=[l[0],l[1]]
  321.     return  courbes,n0,CP    
  322.      
  323. Actions=   {     "curveto" : courbe_vers_c,
  324.                  "curveto" : courbe_vers_c,
  325.                  "moveto" : mouvement_vers,
  326.                  "rmoveto" : mouvement_vers,
  327.                  "lineto" : ligne_tracee_l,
  328.                  "rlineto" : rligne_tracee_l
  329. }
  330.      
  331. TAGcourbe=Actions.keys()
  332.  
  333. """                 
  334. def pik_pattern(t,l):
  335.     global npat, PATTERN, BOUNDINGBOX
  336.     while t[l].find('%%EndSetup')!=0:   
  337.           if t[l].find('%%BoundingBox:')!=-1:
  338.              l0=t[l].split()
  339.              BOUNDINGBOX['rec']=[float(l0[-4]),float(l0[-3]),float(l0[-2]),float(l0[-1])]
  340.              r=BOUNDINGBOX['rec']
  341.              BOUNDINGBOX['coef']=(r[3]-r[1])/(r[2]-r[0])
  342.           print l,
  343.           if  t[l].find('BeginPatternLayer')!=-1:
  344.                npat+=1
  345.                PATTERN[npat]=[]
  346.                while t[l].find('EndPatternLayer')==-1:
  347.                      print t[l] 
  348.                      PATTERN[npat].append(l) 
  349.                      l+=1   
  350.           if l+1<len(t):
  351.              l=l+1
  352.           else:
  353.              return 1,l
  354.     return 1,l
  355. """
  356.              
  357. def scan_FILE(nom):
  358.   global CP, courbes, SCALE, scale, GSTACK, GSCALE, GTRANSLATE
  359.   dir,name=split(nom)
  360.   name=name.split('.')
  361.   n0=0
  362.   result=0
  363.   t=filtreFICHIER(nom)
  364.   #print t
  365.   if t!='false' and (nom.upper().find('.EPS')!=-1 or nom.upper().find('.PS')!=-1 ):
  366.      if not SHARP_IMPORT:
  367.          warning = "Select Size : %t| As is %x1 | Scale on Height %x2| Scale on Width %x3" 
  368.          scale = Blender.Draw.PupMenu(warning)
  369.      npat=0
  370.      l=0
  371.      do=0
  372.      while l <len(t)-1 :
  373.        if t[l].find('%%BoundingBox:')!=-1:
  374.              l0=t[l].split()
  375.              BOUNDINGBOX['rec']=[float(l0[-4]),float(l0[-3]),float(l0[-2]),float(l0[-1])]
  376.              r=BOUNDINGBOX['rec']
  377.              BOUNDINGBOX['coef']=(r[3]-r[1])/(r[2]-r[0])
  378.        """
  379.        if not do:
  380.           do,l=pik_pattern(t,l)
  381.        """
  382.        #print 'len(t)',len(t)        
  383.        t[l].replace('\n','') 
  384.        if t[l][0]!='%':
  385.             l0=t[l].split()
  386.             if l0!=[] and l0[-1] in TAGcourbe:
  387.                 if l0[-1] in ['curveto']:
  388.                    l2=t[l+1].split()
  389.                    courbes,n0,CP=Actions[l0[-1]](l0,l2,n0,CP)
  390.                 else: 
  391.                    courbes,n0,CP=Actions[l0[-1]](l0,n0,CP)
  392.             # modifs 10/06/2005       
  393.             elif l0!=[] and l0[-1] in ['scale']:
  394.                 GSCALE=[float(l0[-3]),float(l0[-2])]
  395.             elif l0!=[] and l0[-1] in ['translate']:
  396.                 GTRANSLATE=[float(l0[-3]),float(l0[-2])]
  397.             elif l0!=[] and l0[-1] in ['concat'] and l0[0] in ['gsave']:
  398.                 l0[1]=l0[1].replace('[','')
  399.                 l0[-2]=l0[-2].replace(']','')
  400.                 stack=transform([float(l0[1]),float(l0[2]),float(l0[3]),float(l0[4])],float(l0[5]),float(l0[6]))
  401.                 GSTACK.append(stack)
  402.                 #print GSTACK
  403.             elif l0!=[] and l0[-1] in ['concat'] and l0[0] in ['grestore']:
  404.                 del GSTACK[-1]              
  405.             # modifs 12/06/2005 : end    
  406.                 
  407.                 
  408.        l=l+1#; print l                    
  409.      t=[]
  410.      
  411.   if  t!='false':
  412.       courbes.number_of_items=len(courbes.ITEM.keys())
  413.  
  414.       for k in courbes.ITEM.keys():
  415.          courbes.ITEM[k].pntsUV[0] =len(courbes.ITEM[k].beziers_knot)
  416.  
  417.          if  test_egalitedespositions(courbes.ITEM[k].Origine,
  418.                                       [courbes.ITEM[k].beziers_knot[-1].co[-2],
  419.                                        courbes.ITEM[k].beziers_knot[-1].co[-1]]):
  420.               courbes.ITEM[k].flagUV[0]=1 
  421.               courbes.ITEM[k].pntsUV[0] -=1
  422.  
  423.       if courbes.number_of_items>0:
  424.          if len(PATTERN.keys() )>0:
  425.             #print len(PATTERN.keys() )
  426.             pass
  427.          t=create_GEOtext(courbes)
  428.          save_GEOfile(dir,name[0],t)
  429.          Open_GEOfile(dir,name[0])
  430.       else:
  431.           pass
  432.  
  433.     
  434. #=====================================================================
  435. #====================== EPS format mouvements =========================
  436. #=====================================================================
  437. #=========================================================          
  438. # une sorte de contournement qui permet d'utiliser la fonction
  439. # et de documenter les variables Window.FileSelector
  440. #=========================================================
  441. def fonctionSELECT(nom):
  442.     scan_FILE(nom)
  443.  
  444. if DEVELOPPEMENT==1 : Blender.Window.FileSelector (fonctionSELECT, 'SELECT .EPS/.PS FILE')
  445. #sys.path=oldpath       
  446.