Jump to content
Sign in to follow this  
Visual Cortex Lab

Python Telnetlib

Recommended Posts

HI

i'm making a python script which needs (well.. I'd say "i'd like to") telnet houdini (which have 'openport 12000' from textport windows) .. everything runs fine if i run "telnet localhost 12000" from shell.... and telnetlib.Telnet("localhost", 12000) gives me no error. Netstat gives me a ESTABLISHED connection... but then i got nothing more..

write() gives me no output (hence i guess no errors)

read() gives me no output ... (tried read_until() but i then have a stucked telnet session since there's no output back from my write() commands)

any guess?

thanks in advance.

cheers.

Share this post


Link to post
Share on other sites

hm.... anyone knows how to "create shop from vop network" ... with Hscript command?

since I'm going on with my little python parser.. i now need to create Shops from the VOP i just created.. using Hscript commands.

thanks in advance for any help.

cheers

Share this post


Link to post
Share on other sites

Ok.. I should start a new thread maybe .. but I'm not that sure this will get interest.. so I'll just post here.

I *finished* (read: finished an alpha which needs tests and critiques :) the first version of my Python script I was working on during last days... task were two mainly:

- Learn python

- have a OBJ file better imported into houdini (shader reasons mostly)

so i made a python script which does the following:

- sends to you houdini opened TCP port all the commands needed to load a Obj file... creates the VOP networks and SHOP shaders from the .mtl file.. applies such shaders to the corresponding object groups (not clusters yet).. and gives you a GEO with all that inside ready to work on it.

it might sounds worthless and maybe useless... but i found a need when during latest months I had to make all my tries (hopefully *real* tasks since next week) with Effects here.. and I had to load many OBJ files from XSI.... and obviosuly i had to make all the materials from scratch, which with phong or easy shaders this is a real waste of time.

that said... here's the code of the python script... I tested it on Linux and Windows.. and it works.

NOTE: it works for XSI exported OBJ only.

#!/usr/bin/env python
"""
OBJ and MTL file parser and Houdini script exporter

This script will parse a mtl file (soon a OBJ also) and creates the 
hscript syntax and script to create shaders and then connect them to the corresponding
object primitive groups

USE:
- open a textport in your Houdini session and open port 12000
- save the houdini scene and then copy the OBJ and the MTL files in the same HIP location because I use the $HIP 
variable for easier setting of the File Sop
- open your favourite shell and launch the script with the following command:

$ python mtl_to_Houdini.py file.obj

- watch Houdini gui being populated by your OBJ and Vop shaders

TOBEDONE:
- custom Houdini port
- MTL and OBJ parsing from others packages.. since XSI exported OBJ is quiet simple and uncomplete
- more commandline options, like choose between telnet or .cmd output
- code more optizmised and more "coder" style and less "noob" style :)
- Tk or Pmw parameters and arguments GUI for easier execution

LIMITATIONS:
- textures path must not have spaces (this should be already in your daily basis rules i guess :)
- XSI exports an Mtl file which contains really basic shader parameters... so most of your rendertree will be lost.. better is to attach textures directly to diffuse notde and 
not use mixers.. for example.. also.. mtl file doesnt include bump nor ambient textures (nor all others).
- transparency is not exported so this information gets lots.
- many others....



Thanks to OdForce user who created this Wiki http://www.odforce.net/wiki/index.php/PythonToHoudini which inspired me

Note this is my first python script... so I really appreciate any feedback/bug/improvment sent to:
This script was ment to be usefull for some of my work and tests... I hope you will find any use for it as I did.

jclaude at mimgfx dor com

Cheers
"""

#temporary disabled until i'll make the GUI... well.. until I'll study Tk first :D
#from Tkinter import *
#import tkFileDialog
#import Pmw

import string,sys
import socket
import time

class FileHandle:
	def __init__(self):
  self.OBJfile = sys.argv[1]
  
  self.MTLopened = False
  self.OBJopened = False
  
	def MTLOpenFileR(self, MTLfile):
  self.MTLfile = MTLfile
  if self.MTLopened:
 	 print ".::   " + str(self.MTLfile) + " its opened... better to close it first.."
  self.MTLCloseFile(self.MTLfile)
  f = open(self.MTLfile, "r")
  print ".::   " + str(self.MTLfile)+" loaded successfully (READ mode)...."
  self.MTLopened = True
  return f
  
	def MTLOpenFileW(self, MTLfile):
  self.MTLfile = MTLfile
  if self.MTLopened:
 	 print ".::   " + str(self.MTLfile) + " its opened... better to close it first.."
  self.MTLCloseFile(self.MTLfile)
  f = open(self.MTLfile, "w")
  print ".::   " + str(self.MTLfile)+" loaded successfully (WRITE mode)...."
  self.MTLopened = True
  return f

	def MTLCloseFile(self, MTLfile):
  self.MTLfile = MTLfile
  f = file(self.MTLfile)
  f.close()
  print ".::   " + str(self.MTLfile)+" CLOSED successfully...."
  self.MTLopened = False
  
	def OBJOpenFileR(self):
  if self.OBJopened:
 	 print ".::   " + str(self.OBJfile) + " its opened... better to close it first.."
  self.OBJCloseFile()
  f = open(self.OBJfile, "r")
  print ".::   " + str(self.OBJfile)+" loaded successfully (READ mode)...."
  self.OBJopened = True
  return f
  
	def OBJOpenFileW(self):
  if self.OBJopened:
 	 print ".::   " + str(self.OBJfile) + " its opened... better to close it first.."
  self.OBJCloseFile()
  f = open(self.OBJfile, "w")
  print ".::   " + str(self.OBJfile)+" loaded successfully (WRITE mode)...."
  self.OBJopened = True
  return f

	def OBJCloseFile(self):
  f = file(self.OBJfile)
  f.close()
  print ".::   " + str(self.OBJfile)+" CLOSED successfully...."
  self.OBJopened = False
  

class MTLFileClean:
	def __init__(self, MTLfile):
  self.MTLfile = MTLfile
  
  # instance della classe FileHandle
  self.filehandle =  FileHandle()
  
	def isEmptyLine(self, line):
  #controlliamo se c'e' una riga vuota
  print ".",
  return line=='\n'
  
	def removeEmptyLine(self, lines, line):
  return lines.remove(lines[line])

	def MTLwriteFileLine(self, line, file):
  print ".",
  return file.write(line)

	def FixEmptyLines(self, __MTLfile):
  # qui creiamo l'handle per il file.. tramire 'self.filehandle.. perche' l'istanza di filehandle e' fatta da __INIT__
  f = self.filehandle.MTLOpenFileR(__MTLfile)      
  
  # qui controllo ed elimino le righe vuote....
  line = 0
  emptylines = 0
  lines = f.readlines()
  totlines = len(lines)
  origtotlines = totlines
  
  print ".::   CHECKING empty lines....."
  while line in range(totlines):
 	 if self.isEmptyLine(lines[line]):
    emptylines += 1
    totlines -= 1
    self.removeEmptyLine(lines, line)
    print ".",
    line -= 1
 	 line += 1
  print "\n"
  print ".::   CHECK finished...."

  #chiudo il file..
  self.filehandle.MTLCloseFile(__MTLfile)
  
  print ".::   Total Lines "+str(origtotlines)+" are now "+str(len(lines))+ "..... for a total of "+str(emptylines)+ " deleted\n\n"
  
  #print "\nDo you want to preview new file content before writing to file?"
  answer = "n"
#  answer = raw_input('(Y/n) ')
  if (answer == "y") | (answer == "Y"):
 	 print lines

  #print "\ndoes it looks ok? Pressing \"Y\" here will overwrite the file with fixes?"
  answer = "y"
#  answer = raw_input('(Y/n) ')
  if (answer == "y") | (answer == "Y"):
 	 if emptylines > 0:
    print ".::   Now fixing the file and writing changes...."
    f = self.filehandle.MTLOpenFileW(__MTLfile)
    line = 0

    print "writing line ",
    while line in range(len(lines)):
   	 self.MTLwriteFileLine(lines[line], f)
   	 line += 1
   	 print ".",
    if line == len(lines):
   	 print "\n"
   	 print ".::   File Fixed successfully"

  
class MTLFileParse:
	def __init__(self, MTLfile):
  self.MTLfile = MTLfile
  self.opened = False
  
	def isNewMaterial(self, line):
  import string
  return line.startswith('newmtl')

	def MTLstringParse(self, line):
  import string
  mtlstring = lines[line].split(" ")
  mtlstring = map(string.strip, mtlstring)
  return mtlstring


class OBJFileClean:
	def __init__(self):
  self.OBJfile = sys.argv[1]
  
  # instance della classe FileHandle
  self.filehandle =  FileHandle()
  
	def isEmptyLine(self, line):
  #removing empty line
  #print "_",
  return line=='\n'
  
	def isCommentLine(self, line):
  #if its a comment... let's remove it.. to have a cleaner file to dictionarize
  #print "#",
  return line.startswith('# ')
  
	def isStartDefinition (self, line):
  #if its a comment... let's remove it.. to have a cleaner file to dictionarize
  #print "#",
  return line.startswith('#begin ')
  
	def removeEmptyLine(self, lines, line):
  return lines.remove(lines[line])

	def writeFileLine(self, line, file):
  #print ".",
  return file.write(line)

	def FixEmptyLines(self):
  # qui creiamo l'handle per il file.. tramire 'self.filehandle.. perche' l'istanza di filehandle e' fatta da __INIT__
  f = self.filehandle.OBJOpenFileR()      
  
  # qui controllo ed elimino le righe vuote....
  line = 0
  emptylines = 0
  lines = f.readlines()
  totlines = len(lines)
  origtotlines = totlines
  
  print ".:: CHECKING empty lines....."
  while line in range(totlines):
 	 if self.isStartDefinition(lines[line]):
    advance = lines[line].split( " ")
    line = line + int(advance[1])
    
 	 elif self.isEmptyLine(lines[line]) | self.isCommentLine(lines[line]):
    emptylines += 1
    totlines -= 1
    self.removeEmptyLine(lines, line)
    print ".",
    line -= 1
 	 line += 1
  print "\n"
  print ".::   CHECK finished...."

  #chiudo il file..
  self.filehandle.OBJCloseFile()
  
  print ".::   Total Lines "+str(origtotlines)+" are now "+str(len(lines))+ "..... for a total of "+str(emptylines)+ " deleted\n\n"
  
  #print "\nDo you want to preview new file content before writing to file?"
  answer = "n"
#  answer = raw_input('(Y/n) ')
  if (answer == "y") | (answer == "Y"):
 	 print lines

  #print "\ndoes it looks ok? Pressing \"Y\" here will overwrite the file with fixes?"
  answer = "y"
#  answer = raw_input('(Y/n) ')
  if (answer == "y") | (answer == "Y"):
 	 if emptylines > 0:
    print ".::   Now fixing the file and writing changes...."
    f = self.filehandle.OBJOpenFileW()
    line = 0

    print ".::   writing line ",
    while line in range(len(lines)):
   	 self.writeFileLine(lines[line], f)
   	 line += 1
   	 
    if line == len(lines):
   	 print "\n"
   	 print ".::   File Fixed successfully"

  
class OBJFileParse:
	def __init__(self):
  self.OBJfile = sys.argv[1]
  self.OBJopened = False
  
	def isMTLfile(self, line):
  import string
  return line.startswith('mtllib ')

	def isNewGroup(self, line):
  import string
  return line.startswith('g ')

	def isEmptyLine(self, line):
  #removing empty line
  #print "_",
  return line=='\n'
  
	def isComment(self, line):
  #if its a comment... let's remove it.. to have a cleaner file to dictionarize
  #print "#",
  return line.startswith('# ')
  
	def isStartDefinition (self, line):
  #if its a comment... let's remove it.. to have a cleaner file to dictionarize
  #print "#",
  return line.startswith('#begin ')

	def isEndDefinition (self, line):
  #if its a comment... let's remove it.. to have a cleaner file to dictionarize
  #print "#",
  return line.startswith('#end ')

	def isMaterialAssignment (self, line):
  return line.startswith('usemtl  ')
  
	def isNewMaterial(self, line):
  import string
  return line.startswith('newmtl')

	def OBJstringParse(self, line):
  import string
  objstring = lines[line].split(" ")
  objstring = map(string.strip, objstring)
  return objstring

class HscriptOut:
	def __init__(self):
  host = "localhost"
  port = 12000
  self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  self.sock.connect((host, port))

	def HExecute(self, command):
  self.sock.send(command + '\n')
  return()

	def HRead(self):
  #Retrieve Data from Houdini until you hit the delimiter
  delimiter = '\x00'
  buffer = ""
  while delimiter not in buffer:
 	 buffer = buffer + self.sock.recv(8192)
  return(buffer[:-2]) #trim the delimiter

	def HFlush(self):
  chunk = "null"
  while len(chunk) > 1:
 	 chunk = self.sock.recv(8192)
  return()

	def HClose(self):
  #Close the connection with Houdini
  self.sock.close()
  return()

	def HoudiniExecute(self, script, verbose=0):
  num_commands = len(script)
  i = 0
  for i in range(0,num_commands):
 	 command = script[i]
 	 if command[:5] == "opset":
    time.sleep(0.7)
 	 else:
    time.sleep(0.01)
 	 self.HExecute(command)
 	 if verbose == 1:
    print str(i+1) + " > " + command
 	 i += 1
  verbose = 0

Hscript = HscriptOut()
H_SCRIPT = ""
OUTPUT_script = []

OBJ_name = sys.argv[1].split(".")
OBJ_name = map(string.strip, OBJ_name)

print "\n>::   Do you want to clean the scene and delete everything in /OBJ before proceeding?"
#answer = "y"
answer = raw_input('([Y]/n) ')
if (answer == "y") | (answer == "Y") | (answer ==""):
	#just deleting everything... dont forget this script is ment to be a OBJ.MTL file loader... :)
	OUTPUT_script.append("opcd /obj")
	OUTPUT_script.append("oprm *")
else:
	print "....then you must give a base name for the new OBJ stuffs :"
	OBJ_name[0] = raw_input('OBJ base name : ')

#creating the GEO contaning our geometry and subnetworks
OUTPUT_script.append("opcd /obj")
OUTPUT_script.append("opadd geo OBJ_" + OBJ_name[0])
OUTPUT_script.append("opcd OBJ_" + OBJ_name[0])
OUTPUT_script.append("opadd vopnet VOP_shaders")
OUTPUT_script.append("opadd shopnet SHOP_shaders")
OUTPUT_script.append("opadd file")
OUTPUT_script.append("opadd reverse")
OUTPUT_script.append("opadd facet")
OUTPUT_script.append("opwire file1 -0 reverse1")
OUTPUT_script.append("opwire reverse1 -0 facet1")
OUTPUT_script.append("opparm file1 file ($HIP/" + str(sys.argv[1]) +")")
OUTPUT_script.append("opparm facet1 postnml 1")
OUTPUT_script.append("opparm facet1 cusp 1")
OUTPUT_script.append("opset -d on facet1")
OUTPUT_script.append("opset -r on facet1")
OUTPUT_script.append("opcd /obj/OBJ_" + OBJ_name[0])

# connection and sending commands to Houdini socket port
Hscript.HoudiniExecute(OUTPUT_script)
OUTPUT_script = []

if (answer == "y") | (answer == "Y") | (answer ==""):
	print "\n\n.::   every network/nodes have been deleted"

# MTL File parsing.. and cleaning... and making the Hscript to create all nodes.. VOP and SHOP nodes.. 
############################################################
# instancing the classes
parse = OBJFileParse()
f = FileHandle()
f = f.OBJOpenFileR()
lines = f.readlines()

#checking for the mtllib declaration
line = 0
while line in range(len(lines)):
	if parse.isMTLfile(lines[line]):
  MTLfile = lines[line].split(" ")
  MTLfile = map(string.strip, MTLfile)
  MTLfile = MTLfile[1]
  MTLfile = MTLfile[-3:]
  OBJfile = sys.argv[1]
  OBJfile = OBJfile[:-3]
  
  __MTLfile = OBJfile + MTLfile	
  print "\n.::   MTL file found... : " + __MTLfile + "\n"
  f = FileHandle()
  f = f.MTLOpenFileR(__MTLfile)
  break
	else:
  line += 1

clean = MTLFileClean(__MTLfile)
parse = MTLFileParse(__MTLfile)

# running the whole EmptyLine Fix
clean.FixEmptyLines(__MTLfile)

f = FileHandle()
f = f.MTLOpenFileR(__MTLfile)
lines = f.readlines()

line = 0
mat_number = 1
__materials_list = {}
############################################################
# MTL parsing
############################################################
while line in range(len(lines)):
	if parse.isNewMaterial(lines[line]):
  
  stringa = parse.MTLstringParse(line)
  mat_name = "VEX_" + str(mat_number) + "_" + OBJ_name[0] + "_" + stringa[1] + "_"
  mat_number += 1
  print ".::   MTL material: " + stringa[1] + "\n--------> " + str(mat_name)
  
  __materials_list[stringa[1]] = str(mat_name)
  # HOUDINI COMMANDS    
  lighting_model_name = "main_shader"
  parameter_diffuse = "diffuse"
  parameter_ambient = "ambient"
  parameter_specular = "specular"
  parameter_rought = "rought"
  parameter_opacity = "opacity"
  parameter_tmap = "map"

  OUTPUT_script.append("opcd /obj/OBJ_" + OBJ_name[0] + "/VOP_shaders")
  OUTPUT_script.append("opadd surface "+mat_name)
  OUTPUT_script.append("opcd "+mat_name)
  OUTPUT_script.append("opadd lighting "+ str(lighting_model_name))
  OUTPUT_script.append("opwire "+ str(lighting_model_name) + " -0 output1")
  
  step = 1
  
  while step in range(1,len(lines)):
 	 position = line + step

 	 if position < len(lines):
    stringa = parse.MTLstringParse(position)

    # inizio a recuperare i dati del materiale
    # creo il dizionario temporaneo per i parametri dello shader
    attributes = {}
    
    if   stringa[0] == "Ka":
   	 # AMBIENT
   	 attributes["ambr"] = stringa[1]
   	 attributes["ambg"] = stringa[2]
   	 attributes["ambb"] = stringa[3]
   	 
   	 OUTPUT_script.append("opparm "+ str(lighting_model_name) + " amb ("+ attributes["ambr"] + " " + attributes["ambg"] + " " + attributes["ambb"] + ")")
   	 OUTPUT_script.append("opadd parameter "+ str(parameter_ambient))
   	 OUTPUT_script.append("opparm " + str(parameter_ambient) + " parmname ambient" )
   	 OUTPUT_script.append("opparm " + str(parameter_ambient) + " parmlabel ambient" )
   	 OUTPUT_script.append("opparm " + str(parameter_ambient) + " parmtype (color)")
   	 OUTPUT_script.append("opparm " + str(parameter_ambient) + " colordefr ("+ str(attributes["ambr"]) + ")" )
   	 OUTPUT_script.append("opparm " + str(parameter_ambient) + " colordefg ("+ str(attributes["ambg"]) + ")")
   	 OUTPUT_script.append("opparm " + str(parameter_ambient) + " colordefb ("+ str(attributes["ambb"]) + ")")
   	 OUTPUT_script.append("opwire " + str(parameter_ambient) + " -3 "+ str(lighting_model_name))
   	 
   	 step += 1
    elif stringa[0] == "Kd":
   	 # DIFFUSE
   	 attributes["diffr"] = stringa[1]
   	 attributes["diffg"] = stringa[2]
   	 attributes["diffb"] = stringa[3]
    
   	 OUTPUT_script.append("opparm "+ str(lighting_model_name) + " diff ("+ attributes["diffr"] + " " + attributes["diffg"] + " " + attributes["diffb"] + ")")
   	 OUTPUT_script.append("opadd parameter "+ str(parameter_diffuse))
   	 OUTPUT_script.append("opparm " + str(parameter_diffuse) + " parmname diffuse" )
   	 OUTPUT_script.append("opparm " + str(parameter_diffuse) + " parmlabel diffuse" )
   	 OUTPUT_script.append("opparm " + str(parameter_diffuse) + " parmtype (color)")
   	 OUTPUT_script.append("opparm " + str(parameter_diffuse) + " colordefr ("+ str(attributes["diffr"]) + ")" )
   	 OUTPUT_script.append("opparm " + str(parameter_diffuse) + " colordefg ("+ str(attributes["diffg"]) + ")")
   	 OUTPUT_script.append("opparm " + str(parameter_diffuse) + " colordefb ("+ str(attributes["diffb"]) + ")")
   	 OUTPUT_script.append("opwire " + str(parameter_diffuse) + " -4 "+ str(lighting_model_name))

   	 step += 1
    elif stringa[0] == "Ks":
   	 # SPECULAR
   	 attributes["specr"] = stringa[1]
   	 attributes["specg"] = stringa[2]
   	 attributes["specb"] = stringa[3]
    
   	 OUTPUT_script.append("opparm "+ str(lighting_model_name) + " spec ("+ attributes["specr"] + " " + attributes["specg"] + " " + attributes["specb"] + ")")
   	 OUTPUT_script.append("opadd parameter "+ str(parameter_specular))
   	 OUTPUT_script.append("opparm " + str(parameter_specular) + " parmname specular" )
   	 OUTPUT_script.append("opparm " + str(parameter_specular) + " parmlabel specular" )
   	 OUTPUT_script.append("opparm " + str(parameter_specular) + " parmtype (color)")
   	 OUTPUT_script.append("opparm " + str(parameter_specular) + " colordefr ("+ str(attributes["specr"]) + ")" )
   	 OUTPUT_script.append("opparm " + str(parameter_specular) + " colordefg ("+ str(attributes["specg"]) + ")")
   	 OUTPUT_script.append("opparm " + str(parameter_specular) + " colordefb ("+ str(attributes["specb"]) + ")")
   	 OUTPUT_script.append("opwire " + str(parameter_specular) + " -5 "+ str(lighting_model_name))

   	 step += 1
   	 #exit

    elif stringa[0] == "Ns":
   	 # SPECULAR DECAY
   	 attributes["urough"] = stringa[1]
   	 attributes["vrough"] = stringa[1]
    
   	 OUTPUT_script.append("opparm "+ str(lighting_model_name) + " urough (`1-fit(("+ attributes["urough"] + "), 1, 300, 1, 0.01)`)")
   	 OUTPUT_script.append("opparm "+ str(lighting_model_name) + " vrough (`1-fit(("+ attributes["vrough"] + "), 1, 300, 1, 0.01)`)")
   	 OUTPUT_script.append("opadd parameter "+ str(parameter_rought))
   	 OUTPUT_script.append("opparm " + str(parameter_rought) + " parmname rought" )
   	 OUTPUT_script.append("opparm " + str(parameter_rought) + " parmlabel rought" )
   	 OUTPUT_script.append("opparm " + str(parameter_rought) + " parmtype (float)")
   	 OUTPUT_script.append("opparm " + str(parameter_rought) + " floatdef (`1-fit(("+ attributes["urough"] + "), 1, 300, 1, 0.01)`)")
   	 OUTPUT_script.append("opwire " + str(parameter_rought) + " -6 "+ str(lighting_model_name))
   	 OUTPUT_script.append("opwire " + str(parameter_rought) + " -7 "+ str(lighting_model_name))

   	 step += 1
    elif stringa[0] == "Tr":          
   	 # TRANSPARENCY
   	 attributes["Of"] = 1 - float(stringa[1])

   	 OUTPUT_script.append("opadd parameter "+ str(parameter_opacity))
   	 OUTPUT_script.append("opparm " + str(parameter_opacity) + " parmname opacity" )
   	 OUTPUT_script.append("opparm " + str(parameter_opacity) + " parmlabel opacity" )
   	 OUTPUT_script.append("opparm " + str(parameter_opacity) + " parmtype (color)")
   	 OUTPUT_script.append("opparm " + str(parameter_opacity) + " colordefr ("+ str(attributes["Of"]) + ")" )
   	 OUTPUT_script.append("opparm " + str(parameter_opacity) + " colordefg ("+ str(attributes["Of"]) + ")")
   	 OUTPUT_script.append("opparm " + str(parameter_opacity) + " colordefb ("+ str(attributes["Of"]) + ")")
   	 OUTPUT_script.append("opwire " + str(parameter_opacity) + " -1 output1")
   	 
   	 step += 1
    elif stringa[0] == "illum":
   	 # SHADING TYPE
   	 if stringa[1] == "0":
      attributes["lmodel"] = "constant"
   	 elif stringa[1] == "1":
      attributes["lmodel"] = "lambert"
   	 elif stringa[1] == "2":
      attributes["lmodel"] = "phong"
   	 elif stringa[1] == "3":
      attributes["lmodel"] = "blinn"
   	 elif stringa[1] == "4":
      attributes["lmodel"] = "blinn"
   	 elif stringa[1] == "5":
      attributes["lmodel"] = "anisotropic"
   	 elif stringa[1] == "6":
      attributes["lmodel"] = "anisotropic"
   	 elif stringa[1] == "7":
      attributes["lmodel"] = "anisotropic"
   	 elif stringa[1] == "8":
      attributes["lmodel"] = "anisotropic"
   	 elif stringa[1] == "9":
      attributes["lmodel"] = "constant"   	 
   	 
   	 OUTPUT_script.append("opparm "+ str(lighting_model_name) + " lmodel ("+ attributes["lmodel"] + ")")

   	 step += 1
    elif stringa[0] == "map_Kd":
   	 # DIFFUSE TEXTURE MAP
   	 attributes["diff_tmap"] = stringa[1]
    
   	 OUTPUT_script.append("opadd texture")
   	 OUTPUT_script.append("opadd shadinglayer")
   	 OUTPUT_script.append("opadd vectofloat")
   	 OUTPUT_script.append("opadd multiply")
   	 
   	 OUTPUT_script.append("opparm texture1 map \""+ attributes["diff_tmap"] + "\"")
   	 
   	 OUTPUT_script.append("opwire shadinglayer1 -0 vectofloat1")
   	 OUTPUT_script.append("opwire -o 0 vectofloat1 -1 texture1")
   	 OUTPUT_script.append("opwire -o 1 vectofloat1 -2 texture1")
   	 
   	 OUTPUT_script.append("opwire "+ str(lighting_model_name) + " -0 multiply1")
   	 OUTPUT_script.append("opwire texture1 -1 multiply1")
   	 OUTPUT_script.append("opwire multiply1 -0 output1")
   	 
   	 OUTPUT_script.append("opadd parameter "+ str(parameter_tmap))
   	 OUTPUT_script.append("opparm " + str(parameter_tmap) + " parmname map" )
   	 OUTPUT_script.append("opparm " + str(parameter_tmap) + " parmlabel Texture Map" )
   	 OUTPUT_script.append("opparm " + str(parameter_tmap) + " parmtype (image)")
   	 OUTPUT_script.append("opparm " + str(parameter_tmap) + " imagedef (\"" + attributes["diff_tmap"] + "\")")
   	 OUTPUT_script.append("opwire " + str(parameter_tmap) + " -0 texture1")
   	 
   	 step += 1
    else:
   	 step += 1
   	 break
 	 else:
    step = len(lines)+1
  
  OUTPUT_script.append("opcd /obj/OBJ_" + OBJ_name[0] + "/SHOP_shaders")
  OUTPUT_script.append("opadd  "+mat_name)

	elif stringa[0] == "":
  line += 1
	else:
  break
	if position == 0:
  position = line
	if position > line:
  line = position


# connection and sending commands to Houdini socket port
print "\n.::   Running houdini commands to create VOP and SHOP shaders.... please wait\n"
Hscript.HoudiniExecute(OUTPUT_script)
OUTPUT_script = []

# OBJ File parsing.. and cleaning... and making the Hscript to create all SHOP connection using a SHADER node.. 
############################################################
# instancing the classes
#clean = OBJFileClean()
parse = OBJFileParse()

f = FileHandle()
f = f.OBJOpenFileR()
lines = f.readlines()

line = 0
position = 0
groups = 0
mat_number = 1

GROUP = []
############################################################
# OBL parsing
############################################################
while line in range(len(lines)):
	if parse.isNewGroup(lines[line]):
  
  stringa = parse.OBJstringParse(line)
  GROUP.append("SHADER_" + stringa[1])
  print ".::   Found points group : " + stringa[1] + "\n----------> SOP : " + GROUP[groups]
  SOP = GROUP[groups]
  SHOP = stringa[1]
  # HOUDINI COMMANDS    
  OUTPUT_script.append("opcd /obj/OBJ_" + OBJ_name[0])
  OUTPUT_script.append("opadd shop SHADER_" + stringa[1])

  if groups == 0:
 	 # HOUDINI COMMANDS    
 	 OUTPUT_script.append("opadd null OBJ_" + OBJ_name[0])
 	 OUTPUT_script.append("opwire facet1 -0 OBJ_" + OBJ_name[0])
 	 OUTPUT_script.append("opwire OBJ_" + OBJ_name[0] + " -0 " + GROUP[groups])
  else:
 	 OUTPUT_script.append("opwire "+ GROUP[groups-1] + " -0 " + GROUP[groups])

  OUTPUT_script.append("opset -d on SHADER_" + stringa[1])
  OUTPUT_script.append("opset -r on SHADER_" + stringa[1])
  Hscript.HoudiniExecute(OUTPUT_script)
  OUTPUT_script = []
  
  step = 1
  line += 1
  groups += 1

 	 
#	elif parse.isComment(lines[line]):
#  line += 1
#	elif parse.isEmptyLine(lines[line]):
#  line += 1
	elif parse.isStartDefinition(lines[line]):
  stringa = parse.OBJstringParse(line)
  #print stringa
  if stringa[2] == "faces":
 	 line += 1
 	 shader = parse.OBJstringParse(line)
 	 shadertoapply = shader[1]
 	 line += int(stringa[1])*2
 	 line += 2
 	 try:
    surface = __materials_list[shadertoapply]
 	 except KeyError:
    surface = "ERROR_NO_SHADER_FOUND"
    print ".::   some ERROR found... check your VOP and SHOP network.. ans Shader SOPs..."
 	 OUTPUT_script.append("opparm SHADER_" + SHOP + " quickgroup \"" + SHOP + "\"")
 	 OUTPUT_script.append("opparm SHADER_" + SHOP + " quicksurface \"../SHOP_shaders/" + surface + "1\"")
 	 Hscript.HoudiniExecute(OUTPUT_script)
 	 OUTPUT_script = []
  else: 	 
# 	 print ".: skipping <" + stringa[2] + "> parsing..."
 	 line += int(stringa[1])
 	 line += 2
	elif parse.isEndDefinition(lines[line]):
#  stringa = parse.OBJstringParse(line)
#  print stringa[1] + " " ,
#  print stringa[2:],
#  print " lines skipped..."
  line += 1
	else:
  line += 1
  

# MTL and OBJ File parsing.. finished.. 
Hscript.HClose()
print "\n\n\n.::   MTL parsing ends successfully"

just copy/paste the above lines to and empty .py file.. and launch it after you opened port 12000 into Houdini.

NOTE2:.. I'm using such *openport* approach just for *fun* reasons... this makes the script to be slower.... I could just make a .cmd out from this script.. i know..

this was ment to be fun and getting some knowledge...

anyway .. more script to come.. I'm willing to make Maya export as well... and then all the usefull stuffs we usually need.. camera.. lights.. and so on.

and obviosly... critiques and opinions are really welcome.

cheers.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
Sign in to follow this  

×