Face data to DXF

Need help, or want to share a macro? Post here!
Forum rules
Be nice to others! Respect the FreeCAD code of conduct!
Post Reply
HalpPlease
Posts: 9
Joined: Tue Mar 14, 2023 10:26 am

Face data to DXF

Post by HalpPlease »

Thanks in advance,

Is it possible to make a DXF from face data with python code throught the FreeCAD API ?

I cant really find something.

Ill just dump my code as an example, Im filtering out duplicate child solids, then i search for the face object with the highest Area.
Most of the time this should be the basic plane of type Plane.

Would be great if i could also get a complete face with the bends.

Code: Select all

import sys
import FreeCAD
import Part
import Import
import json
import decimal

class Test:
    def __init__(self, shape,ShapeType, valid, area, volume, length, num_faces):
        self.shape = shape
        self.ShapeType = ShapeType
        self.valid = valid
        self.area = area
        self.volume = volume
        self.length = length
        self.num_faces = num_faces
        self.face_data = []

        for face in self.shape.Faces:

            #print(dir(face.Placement.Base))
            face_dict = {
                "valid": face.isValid(),
                 # "WhatBeInIt": dir(face),
                "area": face.Area,
                "volume":face.Volume,
                # "isSame": face.isSame(),
                # "center_of_mass": face.CenterOfMass,
                # "normal": face.normalAt(0.5, 0.5),
                #  "isClosed": face.isClosed, An error occurred: Object of type 'builtin_function_or_method' is not JSON serializable
                #  "hashCode": face.hashCode, An error occurred: Object of type 'builtin_function_or_method' is not JSON serializable
                "lengte": face.Length,
                'X': face.Placement.Base.x,
                "Y": face.Placement.Base.y,
                "Z": face.Placement.Base.z,
                "faces": len(face.Faces),
                "num_wires": len(face.Wires),
                "num_edges": len(face.Edges),
            }
            self.face_data.append(face_dict)
        

try:
    data = Part.Shape()
    # data.read("./assets/test/Weldment02-Staander_Midden.stp")
    data.read("./assets/test/TestDubbel.stp")
    # Read in the STP file and extract the desired lines of text
    # with open("./assets/test/Weldment02-Staander_Midden.stp", "r") as f:
    with open("./assets/test/TestDubbel.stp", "r") as f:
        stp_text = f.readlines()

    # Loop through each line in stp_text

    product_lines = []
    found_occurrence = False
    occurrence_lines = []
    for line in stp_text:
        if "=NEXT_ASSEMBLY_USAGE_OCCURRENCE('" in line:
            found_occurrence = True
            occurrence_lines.append(line)
        elif found_occurrence:
            occurrence_lines.append(line)
            if ";" in line:
                found_occurrence = False
                product_lines.append("".join(occurrence_lines))
                occurrence_lines = []

    ShapeType = data.ShapeType
    valid = data.isValid()
    area = data.Area
    volume = data.Volume
    length = data.Length
    #  faces = data.Faces
    num_faces = len(data.Faces)
    num_solids = len(data.Solids)

    # Create a Test object with the extracted data

    # print(dir(faceCollection), 'what be in it')
    test = Test(data,ShapeType, valid, area, volume, length, num_faces)
   
   
    # Create a list of dictionaries to hold the data for each object
    object_list = []

    # Append the data for the first object
    object_dict = {
        "stuknaam": product_lines[-1],
        "valid": test.valid,
        "opp": round(test.area,2),
        "volume": round(test.volume,2),
        "lengte": round(test.length,2),
        "aantalFaces": test.num_faces,
        "subparts": num_solids,
        "face_data": test.face_data,
    }
    object_list.append(object_dict)

    # Initialize the object list
    properties_list = []

    for i, solid in enumerate(data.Solids):
        properties = (round(solid.Area, 2), round(solid.Volume, 2), round(solid.Length, 2), len(solid.Faces), len(solid.Edges))
        if properties not in properties_list:

            face_collection = []
            face_shapes = []
            for face in solid.Faces:
                area = face.Area
                # get the underlying surface of the face
                surface = face.Surface
                # Het effectieve shape eruit halen voor json.
                surface_type = type(surface).__name__

                # get the type of the surface
                # surface_type = surface.__class__.__name__
                face_shapes.append(surface_type)
                face_collection.append(area)

            max_area = max(face_collection)
            max_index = face_collection.index(max_area)
            count = face_collection.count(max_area)
            derp = face_shapes[max_index]

            properties_dict = {
                'count': 1,
                'valid': solid.isValid(),
                'opp': solid.Area,
                'volume': solid.Volume,
                'length': solid.Length,
                'num_faces': len(solid.Faces),
                'num_edges': len(solid.Edges),
                'faceShape': derp ,
                'highestFaceArea': max_area,
                'highestFaceAreaCount': count
            }
            properties_list.append(properties)
            properties_dict['properties'] = properties
            properties_dict['sub_objects'] = []
            properties_dict['sub_objects'].append(i)

            object_list.append(properties_dict)

        else:
            index = properties_list.index(properties)
            properties_dict = object_list[index+1]
            properties_dict['count'] += 1
            properties_dict['sub_objects'].append(i)

    print(json.dumps(object_list))        #print(json.dumps(solids))


except Exception as e:
    print("An error occurred:", e)
    sys.exit(1)
Post Reply