Skip to content
Snippets Groups Projects
parsers.py 1.89 KiB
Newer Older
def parseOBJfiles(filePath:str,ratio:float = 1,cornered:bool = False)->dict:
    """
    Parse an OBJ file and return a dict with the vertices and faces
    
    :param filePath: Path to the OBJ file
    :param ratio: Ratio to apply to the vertices
    :param cornered: If True, the vertices will be cornered
    :return: A dict with the vertices and faces
    """
    with open(filePath, 'r') as f:
        x, y, z = [], [], []
        triangles = []
        data = f.readlines()
        for line in data :
            if line.startswith('f'):
                # Face indices start at 1, not 0
                triangles.append([int(line.split()[1])-1, int(line.split()[2])-1, int(line.split()[3])-1])
            elif line.startswith('v'):
                x.append(float(line.split()[1]) * ratio)
                y.append(float(line.split()[2]) * ratio)
                z.append(float(line.split()[3]) * ratio)
        if cornered:
            xmin = min(x)
            for i in range(len(x)):
                x[i] -= xmin
            ymin = min(y)
            for i in range(len(y)):
                y[i] -= ymin
            zmin = min(z)
            for i in range(len(z)):
                z[i] -= zmin
        return {'x':x, 'y':y, 'z':z, 'faces':triangles, "verticies": zip(x,y,z)}
    
def parseXYZfiles(filePath: str, delimiter: str = ' ') -> dict:
    """
    Parses an xyz file and returns a dict containing the coordinates.

    :param file: The xyz file to be parsed.
    :param delimiter: The delimiter used in the xyz file.
    :return: A dictionary containing the  coordinates.
    """
    x , y , z = [], [], []
    with open(filePath, 'r') as f:
        data = f.readlines()
        x = [float(line.split(delimiter)[0]) for line in data]
        y = [float(line.split(delimiter)[1]) for line in data]
        z = [float(line.split(delimiter)[2]) for line in data]
    return {'x':x, 'y':y, 'z':z, "verticies": zip(x,y,z)}