fekt-scara/scripts/generate_3mf_files.py

65 lines
2.3 KiB
Python
Executable file

#!/usr/bin/freecadcmd
import os
import FreeCAD # type: ignore
import Mesh # type: ignore
# Define the project root directory
project_root = os.path.abspath(
os.path.join(os.path.dirname(os.path.realpath(__file__)), os.pardir)
)
# Define the directories for CAD files and 3MF export files
printed_cad_dir = os.path.join(project_root, "cad", "printed")
printed_3mf_dir = os.path.join(project_root, "3mf")
# List to keep track of files that failed to export
failed_files = []
# Traverse the printed CAD directory and its subdirectories
for root, dirs, files in os.walk(printed_cad_dir):
for file in files:
if file.endswith(".FCStd"):
# Absolute path of the CAD file
file_path = os.path.join(root, file)
# Abslute path for the exported 3MF file
output_path = os.path.join(
printed_3mf_dir, os.path.relpath(file_path, printed_cad_dir)
).replace(".FCStd", ".3mf")
# Create the output directory if it doesn't already exist
os.makedirs(os.path.dirname(output_path), exist_ok=True)
FreeCAD.Console.PrintMessage(f"\nExporting {file_path}\n")
# Open the FreeCAD document and recompute it
doc = FreeCAD.openDocument(file_path)
FreeCAD.setActiveDocument(doc.Name)
FreeCAD.ActiveDocument.recompute()
# Get the body object from the document
body = doc.getObject("Body")
if body is None:
FreeCAD.Console.PrintError(f"No 'Body' found in {file}\n")
FreeCAD.closeDocument(doc.Name)
failed_files.append(file_path)
continue
# Try to export the body to a 3MF file
try:
Mesh.export([body], output_path)
except Exception as e:
FreeCAD.Console.PrintError(f"Error exporting {file}: {e}\n")
failed_files.append(file_path)
# Close the FreeCAD document
FreeCAD.closeDocument(doc.Name)
# Print the result of the export and the files that failed
if failed_files:
FreeCAD.Console.PrintError("\nThe following files failed to export:\n")
for file in failed_files:
FreeCAD.Console.PrintError(f" - {file}\n")
else:
FreeCAD.Console.PrintMessage("\nAll files have been exported successfully.\n")