[PYTHON] Extrude with Fusion360 API

background

It seems that the "Fusion 360 Extrusion Competition" (details in another blog article ()) will start this year as well. Rumors have flowed. Fusion 360 has a macro-like function called a script. If you use this guy, you will definitely win! ?? That's why I tried it.

Preparation

How to create a new script or edit an existing script Please refer to the following article. He has translated the official help into Japanese.

Create scripts and add-ins for Fusion 360

"Edit" the sample script that is included from the beginning (be careful not to overwrite it!) You can also check the contents. Also (although it's painful to have only English) on the official help script page There were various samples, so it was very helpful. The links below are the ones that perform various extrusions.

Extrude Feature API Sample API Sample

Script content

Draw a circle with a sketch and extrude it, then draw a different circle on it and extrude it, and repeat. Data on the pitch height (= height of each extrusion) to be stacked, the position and diameter of the circle If you load it as a CSV file, it will be pushed out automatically.

I managed to get it to work by combining various samples. Below, I will explain the code with a little break. It should work if you connect everything in order, but please correct it as needed.

import adsk.core, adsk.fusion, traceback, math, io

def run(context):
    ui = None
    try:
        app = adsk.core.Application.get()
        ui  = app.userInterface
        # Get all components in the active design.
        product = app.activeProduct
        design = adsk.fusion.Design.cast(product)
        # Get the root component of the active design
        rootComp = design.rootComponent
        # Get extrude features
        extrudes = rootComp.features.extrudeFeatures

        title = 'Import csv file'
        if not design:
            ui.messageBox('No active Fusion design', title)
            return
        
        dlg = ui.createFileDialog()
        dlg.title = 'Open CSV File'
        dlg.filter = 'Comma Separated Values (*.csv);;All Files (*.*)'
        if dlg.showOpen() != adsk.core.DialogResults.DialogOK :
            return
        filename = dlg.filename

Up to this point, the screen for selecting the initial settings and CSV file has been executed. It is almost the same as the sample script.

        # Set 1st-sketch plane
        sketches = rootComp.sketches   
        sketch = sketches.add(rootComp.xZConstructionPlane)
        
        cnt = 0
        # Read the csv file.
        with io.open(filename, 'r', encoding='utf-8-sig') as f:
            line = f.readline()
            data = []
            while line:
                pntStrArr = line.split(',')
                for pntStr in pntStrArr:
                    try:
                        data.append(float(pntStr))
                    except:
                        break
                # csv file line 1 is pitch of extrude
                if cnt == 0:
                    distance = adsk.core.ValueInput.createByReal(data[0]/10)

Set to draw a sketch on the XZ plane and extrude it in the Y direction. Read the CSV file line by line. Set the pitch height (= each extrusion height) to be stacked, which is the data of the first line.

                # csv file after line 2 are sketch of extrude
                elif cnt == 1:
                    sketchCircles = sketch.sketchCurves.sketchCircles
                    centerPoint = adsk.core.Point3D.create(data[0]/10, data[1]/10, 0)
                    circle = sketchCircles.addByCenterRadius(centerPoint, data[2]/10)
                    prof = sketch.profiles.item(0)
                    extrude = extrudes.addSimple(prof, distance, adsk.fusion.FeatureOperations.NewBodyFeatureOperation)
                else:
                    sketch = sketches.addWithoutEdges(extrude.endFaces.item(0) )
                    sketchCircles = sketch.sketchCurves.sketchCircles
                    centerPoint = adsk.core.Point3D.create(data[0]/10, data[1]/10, 0)
                    circle = sketchCircles.addByCenterRadius(centerPoint, data[2]/10)
                    prof = sketch.profiles.item(0)
                    extrude = extrudes.addSimple(prof, distance, adsk.fusion.FeatureOperations.JoinFeatureOperation)
                
                line = f.readline()
                data.clear()
                cnt += 1

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

Read the center positions X, Y and diameter of the circle, which are the data from the second line of the CSV file. Draw on a sketch and extrude at the set pitch. In the first stage, draw a sketch on the XY plane and extrude with a new body. From the second stage onward, draw a sketch on the plane of the body and extrude by combining. Repeat until the end of the CSV file.

Finally

If there is a "record" button like an Excel macro, API analysis will also progress. There is not much information in Japanese, and there are many things that I do not understand. It may be a messy code, but please forgive me.

Besides the perfect circle, I could draw an ellipse (Sketch Ellipses). I don't know how to draw a square by combining straight lines.

I really wanted to start by choosing an arbitrary plane instead of the XY plane. I didn't understand this either, so I would appreciate it if you could let me know.

In addition to the articles introduced in the article, I also referred to the following Qiita article. It was serialized in a series and was easy to understand because it was explained carefully. Thanks!

Let's run Fusion 360 with Python Part 1 Create a new script

By the way, this time, in the 2020 extrusion competition, it was clearly stated that "scripts etc. cannot be used". Please note that it will be a foul if you use it (laugh)

Recommended Posts

Extrude with Fusion360 API
Image download with Flickr API
Use Trello API with python
Create an API with Django
Use Twitter API with Python
API with Flask + uWSGI + Nginx
Web API with Python + Falcon
Play RocketChat with API / Python
Support yourself with Twitter API
Call the API with python3.
Use subsonic API with python3
Successful update_with_media with twitter API
Qiita API Oauth with Django
Get ranking with Rakuten API
Operate Nutanix with REST API Part 2
Create Awaitable with Python / C API
[AWS] Create API with API Gateway + Lambda
Persist Flask API server with forever
Quine Post with Qiita API (Python)
[python] Read information with Redmine API
Detect video objects with Video Intelligence API
Multi-input / multi-output model with Functional API
Create API using hug with mod_wsgi
GraphQL API with graphene_django in Django
Introducing Google Map API with rails
Hit ISE's ERS API with PowerShell
Collecting information from Twitter with Python (Twitter API)
Access the Docker Remote API with Requests
Streaming speech recognition with Google Cloud Speech API
Retrieving food data with Amazon API (Python)
Delete all unnecessary Gmail emails with API
What you can do with API vol.1
Build a Fast API environment with docker-compose
Try using Dropbox API v2 with Go
Send data to DRF API with Vue.js
Post from another account with Twitter API
Transcription of images with GCP's Vision API
[Python] Quickly create an API with Flask
Get holidays with the Google Calendar API
Serverless face recognition API made with Python
Create Page / Todo Block with Notion API
[Python] Get Python package information with PyPI API
Extract sudden buzzwords with twitter streaming API
Play with puns using the COTOHA API
Make API of switchbot thermo-hygrometer with Node-RED
Easy REST API with API Gateway / Lambda / DynamoDB
Get coincheck virtual currency information with API ♪
Transcribe WAV files with Cloud Speech API
Automatic follow-back using streaming api with Tweepy