Exemple #1
0
def citygml2obj(filename, foldername):
 # 1. create and/or clear the folder
        if not os.path.exists(foldername):
                os.mkdir(foldername)
        else:
                shutil.rmtree(foldername)
                os.mkdir(foldername)

# 2. create and/or clear the folder
        print "Processing file:", filename
        print "Parsing the file..."
        path = os.path.dirname(os.path.realpath(__file__))
        cmd = os.path.join(path, "run.bat " + filename + " "+ foldername)
        print("cmd", cmd)
        subprocess.call(cmd, shell=True)
  
# 3. convert each polyfile into a obj
        os.chdir(foldername)
        dFiles = {}
        for f in os.listdir('.'):
            if f[-4:] == 'poly':
                i = (f.split('.poly')[0]).rfind('.')
                f1 = f[:i]
                if f1 not in dFiles:
                    dFiles[f1] = [f]
                else:
                    dFiles[f1].append(f)
        MyCov = ConvProvider()
        for polyname in dFiles:
            objfile = polyname + ".obj"
            if MyCov.convert(dFiles[polyname][0], objfile, True) == False:
                print("conversion failed")
                sys.os.exit(0)
            else:
                print("output", objfile)
# 4. combine all the obj file into a obj
        dFiles = []
        for f in os.listdir('.'):
            if f[-3:] == 'obj':
               dFiles.append(f)
        if foldername.rfind('\\') != -1:
            outputname = foldername[foldername.rfind('\\') + 1:]
        elif foldername.rfind('/') != -1:
            outputname = foldername[foldername.rfind('/'):]
        if CombineObj(dFiles, outputname + ".obj") == False:
            print("combine files failed")
            sys.os.exit(0)
        else:
            print("combined", objfile)
Exemple #2
0
def main():
	#handel the arguments and make the conversion decision
    if len(sys.argv) < 3:
        if len(sys.argv) == 2 and sys.argv[1].startswith('--') and sys.argv[1][2:] == 'help':
                #help part
                print """
    Conversion between Obj and Poly format and tessellation (only geometric part) holes in polyfiles are always tessellated
    Support Obj<->Poly and its tessellation, and Obj->Tessellated Obj and Poly->Tessellated Poly, the format is detected by the suffix
    Usage: "obj2poly FILEPATH1 FILEPATH2 bFlag" where FILE1 is converted to FILE2 and bFlag == True means tessellation of all the polygons
                """
        else:
            print "TWO FILEPATHS REQUIRED. Plz see details by obj2poly --help"
            sys.exit()

    elif len(sys.argv) in (3, 4):
        fileName1, fileExt1 = os.path.splitext(sys.argv[1])
        fileName2, fileExt2 = os.path.splitext(sys.argv[2])
        if fileExt1 in ('.obj', '.poly') and fileExt2 in ('.obj', '.poly'):
            #generic conversion
            MyCov = ConvProvider()
            if len(sys.argv) == 3 or (len(sys.argv) == 4 and (sys.argv[3] == 'False' or sys.argv[3] == 'false')):
                # standardised conversion without tessellation
                if MyCov.convert(sys.argv[1], sys.argv[2]) == False:
                    print ("Conversion failed")
                    sys.exit()
            elif len(sys.argv) == 4 and (sys.argv[3] == 'True' or sys.argv[3] == 'true'):
                 # conversion with tessellation
                 if MyCov.convert(sys.argv[1], sys.argv[2], True) == False:
                     print ("Conversion failed")
                     sys.exit()
            print ("Succeed!")
        else:
            print ("Invalid file extension or bFlag value. Support conversion between obj and poly and its tessellation. Plz see details by obj2poly --help")
    else:
        print ("TWO FILEPATHS REQUIRED. Plz see details by obj2poly --help")
        sys.exit()
Exemple #3
0
def dothework(filename):
  filename = str(filename)
# 0. define the output path
  fREPORT = 'report_' + os.path.splitext(os.path.basename(filename))[0] + '.xml'
  fREPORT_SHAPE_TMP = 'report_shape_' + os.path.splitext(os.path.basename(filename))[0]
  fREPORT_SHAPE = fREPORT_SHAPE_TMP + '.obj'
  fREPORT_SHAPEMTL =  fREPORT_SHAPE_TMP + ".mtl"
  fREPORT_SHAPE_TMP = fREPORT_SHAPE_TMP + 'tmp.obj'

# 1. convert obj to poly
  MyCov = ConvProvider()
  polyfile = filename[:-4] + ".poly"
  if MyCov.convert(filename, polyfile, False) == False:
        print("conversion failed")
        sys.os.exit(0)
  else:
        print("output", polyfile)

  val3dity = '3DValidation\\3DValidation.exe'
  invalidsolids = 0
  xmlsolids = []
  exampleerrors = []
    # check if solid or multisurface in first file
  t = open(polyfile)
  t.readline()
  if t.readline().split()[1] == '0':
      multisurface = True
  else:
      multisurface = False
  t.close()
    
    # validate with val3dity
  str1 = val3dity + " -xml " +  "".join(polyfile)
  op = subprocess.Popen(str1.split(' '), stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  R = op.poll()
  if R:
       res = op.communicate()
       raise ValueError(res[1])
  o =  op.communicate()[0]
  if o.find('ERROR') != -1:
      invalidsolids += 1
      i = o.find('<errorCode>')
      while (i != -1):
        if exampleerrors.count(o[i+11:i+14]) == 0:
          exampleerrors.append(o[i+11:i+14])
        tmp = o[i+1:].find('<errorCode>')
        if tmp == -1:
          i = -1
        else:
          i = tmp + i + 1
  else: #-- no error detected, WARNING if MultiSurface!
      if multisurface == True:
        print 'WARNING: MultiSurfce is actually a valid solid'
        s = []
        s.append("\t\t<ValidatorMessage>")
        s.append("\t\t\t<type>WARNING</type>")
        s.append("\t\t\t<explanation>MultiSurfaces form a valid Solid</explanation>")
        s.append("\t\t</ValidatorMessage>\n")
        o = "\n".join(s)
  o = '\t<Solid>\n\t\t<id>' + polyfile + '</id>\n' + o + '\t</Solid>'
  xmlsolids.append(o)

  totalxml = []
  totalxml.append('<ValidatorContext>')
  totalxml.append('\t<inputFile>' + filename + '</inputFile>')
  totalxml.append("\n".join(xmlsolids))
  totalxml.append('</ValidatorContext>')
  
  #write to the proper folder
  OutputFolder = os.path.dirname(filename)
  os.chdir(OutputFolder)

  fout = open(fREPORT, 'w')
  fout.write('\n'.join(totalxml))
  fout.close()
  print "Invalid solids: ", invalidsolids
  print "Errors present:"
  for each in exampleerrors:
    print each, dErrors[int(each)]


# 4. do not wipe the tmp folder
#  os.chdir('../')
#  shutil.rmtree('tmp')

# 5. open textmate
  # os.system("mate " + fREPORT)

#6 Modify the orignal file and add materials dErrors_colors to each error
  if invalidsolids != 0:
        print('Output Erroneous Map to ' + fREPORT_SHAPE)

  ##copy original file to current folder
  #convert poly to obj
  #polyfile = filename[:-4] + ".poly"
  if MyCov.convert(polyfile, fREPORT_SHAPE_TMP, False) == False:
        print("conversion failed")
        sys.os.exit(0)
  try:
        f_shape_tmp = file(fREPORT_SHAPE_TMP, 'r')
  except:
        print('invalid file:' + fREPORT_SHAPE_TMP)
        sys.exit()

  try:
        ReportXMLRoot = MyXML.parse(fREPORT).getroot()
  except:
        print('Failed to parser ' + fREPORT)
        sys.exit()
  try:
        f_shape = file(fREPORT_SHAPE, 'w')
  except:
        print('invalid file:' + fREPORT_SHAPE)
        sys.exit()
  try:
        f_mtl = file(fREPORT_SHAPEMTL,'w')
  except:
        print ("invalid file: " + fREPORT_SHAPEMTL)
        return

  f_shape.write('mtllib ' + fREPORT_SHAPEMTL + '\n')
  #print errid
  f_mtl.write('newmtl manifold'+ '\n')
  f_mtl.write('Ka 0.5 0.5 0.5'+'\n')
  f_mtl.write('Kd 0.5 0.5 0.5'+'\n')
  f_mtl.write('Ks 0.0 0.0 0.0'+'\n')
  ##add x3d materials in the app:appearance according to the counted errors
  errorlist = ({})
  for errid in exampleerrors:
        #print errid
        f_mtl.write('newmtl ' + str(errid) + '\n')
        curcolor = []
        for color in dErrors_colors[int(errid)].split():
            curcolor.append(str(round(float(color)/255, 3)))

        f_mtl.write('Ka '+ curcolor[0] + ' ' + curcolor[1] + ' ' + curcolor[2]+ '\n')
        f_mtl.write('Kd '+ curcolor[0] + ' ' + curcolor[1] + ' ' + curcolor[2]+ '\n')
        f_mtl.write('Ks '+ curcolor[0] + ' ' + curcolor[1] + ' ' + curcolor[2]+ '\n')
      
        #traverse all the solids in the freport
        for solid in ReportXMLRoot.findall('.//Solid'):
            #print solid.find('id').text
            for validatormessage in solid.findall('ValidatorMessage'):
                errorcode = 'null'
                try:
                    errorcode = validatormessage.find('errorCode').text
                except:
                    pass #no error
                if errid == errorcode:
                    #check wether the id of face is valid
                    reportfaceid = validatormessage.find('face').text
                    if reportfaceid == '-1':
                        #if an error is unlocatable
                        pass
                    else:
                        errorlist[int(reportfaceid)] = errid

  #add mtl to the face in the fREPORT_SHAPE
  icount = 0
  for line in f_shape_tmp:
    bTag = False
    if line.startswith('f') and line[1] == ' ':
        try:
            errid = errorlist[icount]
            f_shape.write('usemtl ' + errid + '\n')
            bTag = True
        except:
            pass
        icount = icount + 1

    f_shape.write(line)
    if bTag:
        f_shape.write('usemtl manifold\n')
    

  f_mtl.close()
  f_shape.close()
  f_shape_tmp.close()
  os.remove(fREPORT_SHAPE_TMP)
  os.remove(polyfile)
  
  print('Finished!')
Exemple #4
0
def do_the_work(inputFilePath, isSemantic, debugControl):

    #Init mid files
    if os.path.exists(MIDFILEPATH):
        os.remove(MIDFILEPATH)

    #Init datastructure
    ModelDataFuncs.Init()
    ModelData.strInputFileName, ext = os.path.splitext(inputFilePath)

    #read file
    print ("----Processing file----")
    print (inputFilePath)
    if isSemantic == True:
        if os.path.splitext(inputFilePath)[1] == '.obj':
            print('WARNING: obj format does not contain semantics')
            print('Semantics will be deduced')
            print ("Check and tessellate the file...")
            MyCov = ConvProvider()
            MyCov.convert(inputFilePath, MIDFILEPATH, True)
            #read a tesselated objfile
            if ModelDataFuncs.reader_obj(MIDFILEPATH) == False:
                raise Exception
        else:
            #poly with semantics
            try:
                if not ModelDataFuncs.reader_poly_with_semantics(inputFilePath):
                    return
            except:
                raise ImportError
    else:
        #preprocess (convert and tessellation)
        print ("Check and tessellate the file...")
        MyCov = ConvProvider()
        MyCov.convert(inputFilePath, MIDFILEPATH, True)
        #read a tesselated objfile
        if ModelDataFuncs.reader_obj(MIDFILEPATH) == False:
            raise Exception

    #invert the normal of the input model
    if ModelData.global_INVERT_NORMAL:
        ModelDataFuncs.invert_poly_normal()
    #only for debug
    #tmp = ModelData.centerVertex
    #ModelData.centerVertex = (0.0, 0.0, 0.0)
    #ModelDataFuncs.writer_obj(ModelData.strInputFileName+"_CLS.obj")
    #ModelData.centerVertex = tmp
    #
    if int(debugControl) == 1:
        #Decomposit all the triangles
        DecomposeFunc.model_decompositionEx()

        #Merge all the coplaner dictFaces
        #coplaner_face_merge()
        #ModelDataFuncs.writer_obj(ModelData.strInputFileName+"_DEC.obj")

    elif int(debugControl) == 2:
        #Constrained Tetrahedralization
        if False == TetraFunc.CDT():
            print("Constrained Delauney Tetrahedralization FAILED!")
            return

        #ModelDataFuncs.writer_obj(ModelData.strInputFileName+"_CDT.obj")

        #Heuristic carving
        CarveFunc.heuristic_tet_carving()
        #ModelDataFuncs.writer_obj(ModelData.strInputFileName+"_CARVE.obj")

        #Reconstruct the mesh from tetrahedron
        TetraFunc.extract_mesh_from_tet(isSemantic)
        #Output
        ModelDataFuncs.writer_obj(ModelData.strInputFileName+"_OUTPUT.obj")
        if isSemantic:
            ModelDataFuncs.writer_poly_with_semantics(ModelData.strInputFileName + "_OUTPUT.poly")
    elif int(debugControl) == 3:
        #only deduce the semantics
        TetraFunc.deduce_semantics_of_poly(isSemantic)
        ModelDataFuncs.writer_poly_with_semantics(ModelData.strInputFileName + "_OUTPUT.poly")

    else:
        #Decomposit all the triangles
        DecomposeFunc.model_decompositionEx()

        #Merge all the coplaner dictFaces
        #coplaner_face_merge()
        ModelDataFuncs.writer_obj(ModelData.strInputFileName +"_DEC.obj")

        #Constrained Tetrahedralization
        if False == TetraFunc.CDT():
            print("Constrained Delauney Tetrahedralization FAILED!")
            return
        ModelDataFuncs.writer_obj(ModelData.strInputFileName+"_CDT.obj")

        #Heuristic carving
        CarveFunc.heuristic_tet_carving()
        ModelDataFuncs.writer_obj(ModelData.strInputFileName+"_CARVE.obj")

        #Reconstruct the mesh from tetrahedron
        TetraFunc.extract_mesh_from_tet(isSemantic)
        #Output
        ModelDataFuncs.writer_obj(ModelData.strInputFileName + "_OUTPUT.obj")
        if isSemantic:
            ModelDataFuncs.writer_poly_with_semantics(ModelData.strInputFileName + "_OUTPUT.poly")