Community
Fusion API and Scripts
Got a new add-in to share? Need something specialized to be scripted? Ask questions or share what you’ve discovered with the community.
cancel
Showing results for 
Show  only  | Search instead for 
Did you mean: 

Insert STL and Convert to B-REP using Python Script

5 REPLIES 5
SOLVED
Reply
Message 1 of 6
sounakc9
855 Views, 5 Replies

Insert STL and Convert to B-REP using Python Script

Hi everyone, 


I'm trying to automate importing a batch of stl files into fusion 360 and converting them to B-REP (the button under mesh --> modify --> convert mesh) using python. Is there any documentation on this? 

 

Thank you!

 

Best,

Sounak 

5 REPLIES 5
Message 2 of 6
kandennti
in reply to: sounakc9

Hi @sounakc9 .

 

I converted the OBJ file to BRepBody here. I think it can be used in STL with a few modifications.

https://forums.autodesk.com/t5/fusion-360-api-and-scripts/insert-obj-file/m-p/9640466#M10730


However, if the number of faces in one body is more than 10,000, a warning dialog appears, and if the number of faces is more than 50,000, it cannot be processed. This is the same even if you use the GUI.
To avoid this problem, here is a sample of how to split a body until the number of faces in a body is less than 10000, and then convert it.
However, it is all written in Japanese.

https://kantoku.hatenablog.com/entry/2021/04/27/171136 

Message 3 of 6
sounakc9
in reply to: kandennti

Hi kandennti , 

Thank you for the python script examples. I've modified the first script to import an STL file. However, I noticed that file explorer pops up, and I still need to manually click on the file I want to work with. Is there any way to automate this part by adding a file path? I've included the modified code below. I mainly changed lines 15, 49, and 80. 

Thank you!

Best,

Sounak

# Fusion360API Python script  by kantoku
# Mesh2BRep sample
# Changed to Import STL 
import adsk.core, adsk.fusion, traceback

_app = adsk.core.Application.cast(None)
_ui = adsk.core.UserInterface.cast(None)

def run(context):
    try:
        global _app, _ui
        _app = adsk.core.Application.get()
        _ui = _app.userInterface

        # select files
        paths = selectFiles('select STL file')
        if not paths: return

        # new doc
        _app.documents.add(adsk.core.DocumentTypes.FusionDesignDocumentType)
        des  :adsk.fusion.Design = _app.activeProduct
        des.designType = adsk.fusion.DesignTypes.ParametricDesignType
        root :adsk.fusion.Component = des.rootComponent

        # baseFeature
        baseFeatures = root.features.baseFeatures
        baseFeature = baseFeatures.add()

        baseFeature.startEdit()
        
        # import obj files
        meshs = importMesh(paths ,root.meshBodies, baseFeature)

        # Mesh2BRep
        #execMesh2BRep(meshs)

        #baseFeature.finishEdit()

        # finish
        _ui.messageBox('Done')

    except:
        if _ui:
            _ui.messageBox('Failed:\n{}'.format(traceback.format_exc()))

def execMesh2BRep(
    meshBodies):

    # select meshBody
    for mesh in meshBodies:
        _ui.activeSelections.add(mesh)

    # show Mesh2BRep Command dialog
    _app.executeTextCommand(u'Commands.Start Mesh2BRepCommand')

    # push OK button
    _app.executeTextCommand(u'NuCommands.CommitCmd')


def importMesh(
    paths :list,
    meshBodies :adsk.fusion.MeshBodies,
    baseFeature :adsk.fusion.BaseFeature) -> list:

    unitCm = adsk.fusion.MeshUnits.CentimeterMeshUnit
    bodies = []

    for path in paths:
        meshLst = meshBodies.add(path, unitCm, baseFeature)
        [bodies.append(mesh) for mesh in meshLst]

    return bodies


def selectFiles(
    msg :str):

    fileDlg = _ui.createFileDialog()
    fileDlg.isMultiSelectEnabled = True
    fileDlg.title = msg
    fileDlg.filter = '*.stl'
    
    dlgResult = fileDlg.showOpen()
    if dlgResult == adsk.core.DialogResults.DialogOK:
        return fileDlg.filenames

 

Message 4 of 6
kandennti
in reply to: sounakc9

@sounakc9 .

 

The CommandID of the mesh transformation has been changed and is now fixed.

Enter the path of the desired STL file in the "paths" variable to avoid specifying the file in the dialog.

# Fusion360API Python script
import adsk.core
import adsk.fusion
import traceback

_app = adsk.core.Application.cast(None)
_ui = adsk.core.UserInterface.cast(None)

def run(context):
    try:
        global _app, _ui
        _app = adsk.core.Application.get()
        _ui = _app.userInterface

        # import stl files list
        paths = [
            r'C:\temp\hoge.stl',
            r'C:\temp\piyo.stl',
        ]

        # new doc
        _app.documents.add(adsk.core.DocumentTypes.FusionDesignDocumentType)
        des  :adsk.fusion.Design = _app.activeProduct
        des.designType = adsk.fusion.DesignTypes.ParametricDesignType
        root :adsk.fusion.Component = des.rootComponent

        # baseFeature
        baseFeatures = root.features.baseFeatures
        baseFeature = baseFeatures.add()

        baseFeature.startEdit()
        
        # import obj files
        meshs = importMesh(paths ,root.meshBodies, baseFeature)

        # Mesh2BRep
        execMesh2BRep(meshs)

        baseFeature.finishEdit()

        # finish
        _ui.messageBox('Done')

    except:
        if _ui:
            _ui.messageBox('Failed:\n{}'.format(traceback.format_exc()))

def execMesh2BRep(
    meshBodies):

    # select meshBody
    for mesh in meshBodies:
        _ui.activeSelections.add(mesh)

        # show ParaMeshConvertCommand Command dialog
        _app.executeTextCommand(u'Commands.Start ParaMeshConvertCommand')

        # push OK button
        _app.executeTextCommand(u'NuCommands.CommitCmd')


def importMesh(
    paths :list,
    meshBodies :adsk.fusion.MeshBodies,
    baseFeature :adsk.fusion.BaseFeature) -> list:

    unitCm = adsk.fusion.MeshUnits.CentimeterMeshUnit
    bodies = []

    for path in paths:
        meshLst = meshBodies.add(path, unitCm, baseFeature)
        [bodies.append(mesh) for mesh in meshLst]

    return bodies
Message 5 of 6
sounakc9
in reply to: sounakc9

Hi kandennti,

 

Thank you for the help! Here's the new code implementing the ParaMeshConvertCommand.

import adsk.core, adsk.fusion, adsk.cam, traceback
import os 
def run(context):
    ui = None
    try:
        app = adsk.core.Application.get()
        ui  = app.userInterface
        test_name = '1test_file'
        #Find project by name
        # Get the root folder of the project
        for data_file in app.activeDocument.dataFile.parentFolder.dataFiles:
            #if data_file.fileExtension == 'stl':                    
            if test_name == data_file.name:
                msg = str(data_file.name)
                ui.messageBox(msg)
                app.documents.open(data_file)
                des :adsk.fusion.Design = app.activeProduct
                root :adsk.fusion.Component = des.rootComponent
                sels :adsk.core.Selections = ui.activeSelections
                sels.clear()
                cmDefs = ui.commandDefinitions
                
                for mesh in root.meshBodies:
                    msg = str(mesh.name)
                    ui.messageBox(msg)
                    sels.add(mesh)
                    # show ParaMeshConvertCommand Command dialog
                    app.executeTextCommand(u'Commands.Start ParaMeshConvertCommand')
                    # push OK button
                    app.executeTextCommand(u'NuCommands.CommitCmd')
                    #cmDef = cmDefs.itemById("ParaMeshConvertCommand")
                    #cmDef.controlDefinition.isEnabled
                    #cmDef.execute()
                msg = 'brep conversion complete'
                ui.messageBox(msg)

    except:
        if ui:
            ui.messageBox('Failed:\n{}'.format(traceback.format_exc()))


    

 

I looked at your other examples on how to select meshes.  Before, I saw your most recent reply, I was actually trying to use the commandDefinitions to execute the ParaMeshConvert command. If you comment out the text commands and uncomment the commandDefinition lines,  I got to the point where I just needed to press the enter key. Just out of curiosity, would you know how I can use keyboard events?

 

Again, thank you for the help!

 

Best,

Sounak 

 

Message 6 of 6
arndt.grossmann
in reply to: sounakc9

This used to work until recently. Any ideas why it doesn't anymore?

 

Can't find what you're looking for? Ask the community or share your knowledge.

Post to forums  

Autodesk DevCon in Munich May 28-29th


Autodesk Design & Make Report