Lesson 1: The basic scripts and Add-in

Steps to Create Your First Add-in

1. Launch Fusion, find utilities and click at the drop menu of ADD-INS button. You can find Scripts and Add-ins menu item.
Add-ins menu

2. Click at it, in the new window, we can create two types of add-ins: Scripts and Add-ins. There isn’t much different between them technically. The script will run at once and disposed after running, while the Add-ins could be kept running with Fusion and be unloaded later. Let’s focus on the script first, we’ll upgrade it to an Add-in later.
Scripts and add-in dialog.

3. Click at the + button. Click at the Create new script or add-in. A new dialog will pop up. You can choose the type of new created item, update the name of it and add some meta info. Let’s create a script here, choose the language you would like to continue with.
New script or add-in dialog

4. After creating it, you can also change the name of the scripts. Click Edit to view newly created script.
Edit in code editor

5. Fusion will launch the editor for the selected script. For Python scripts, it will be VSCode. C++ will be Visual Studio or Xcode based on your platform.

Python/VSCode
Python script in VSCode

C++/Visual Studio
CPP code in Visual Studio

If you are using Visual Studio later than Visual Studio 2012, it will ask you to upgrade the project. Please update it to your version of Visual Studio.

C++/Xcode
CPP code in Xcode

1. Launch Fusion, find utilities and click at the drop menu of ADD-INS button. You can find Design Automation for Fusion menu item.
Add-ins menu

2. Click at it, it will open a dialog. It is very straight forward. We can create a script with Create script button and edit it with Edit Script. You can use the drop down list to choose the script to edit.

3. Let’s create a script and click at edit script to view it in the VSCode.
TypeScript code in VSCode

Explain the code


"""This file acts as the main module for this script."""

import traceback
import adsk.core
import adsk.fusion

# import adsk.cam        
# Initialize the global variables for the Application and UserInterface objects.
app = adsk.core.Application.get()
ui  = app.userInterface        

def run(_context: str):
"""This function is called by Fusion when the script is run."""
        
    try:
        # Your code goes here.
        ui.messageBox(f'"{app.activeDocument.name}" is the active Document.')
    except:  #pylint:disable=bare-except
        # Write the error message to the TEXT COMMANDS window.
        app.log(f'Failed:\n{traceback.format_exc()}') 
        

First, we’ll get instance of running Fusion with adsk.core.Application.get().

Then, we’ll get instance of user interface of current Fusion with app.userInterface.

When a script is running, Fusion will call the run method. We’ll put our scripts in it. In the basic script, it will be displaying the name of current active document. The name is acquired with app.activeDocument.name, and it will be shown with a dialog box using ui.messageBox.

There could be exception when running a code, so the default script has a try-catch block to capture any exceptions. It uses app.log to display the error message. You can find these logs in the Text Commands window (File>View>Show Text Commands or Ctrl+Alt+C).


#include <Core/CoreAll.h>
#include <Fusion/FusionAll.h>
#include <Cam/CamAll.h>

using namespace adsk::core;
using namespace adsk::fusion;
using namespace adsk::cam;

Ptr<Application> app;
Ptr<UserInterface> ui;

extern "C" XI_EXPORT bool run(const char* context)
{
    app = Application::get();
    if (!app)
    return false;

        ui = app->userInterface();
        if (!ui)
            return false;

        ui->messageBox("Hello script");

        return true;
}

#ifdef XI_WIN

#include <windows.h>

BOOL APIENTRY DllMain(HMODULE hmodule, DWORD reason, LPVOID reserved)
{
    switch (reason)
    {
    case DLL_PROCESS_ATTACH:
    case DLL_THREAD_ATTACH:
    case DLL_THREAD_DETACH:
    case DLL_PROCESS_DETACH:
    break;
}
return TRUE;
}

#endif // XI_WIN
        

When using C++, all the Fusion objects are warped with Ptr<T>;So, we could find that the Application and UI are wrapped as Ptr<Application> and Ptr<UserInterface>.

First, we’ll notice that the run function is exported in C calling convention. There is also a XI_EXPORT macro in the definition. It is mainly for multiplatform.

In the plugin entry, we’ll get the application object with Application::get().

Then, we’ll get instance of user interface of current Fusion with app->userInterface().

When a script is running, Fusion will call the run method. We’ll put our scripts in it. In the basic script, it will be displaying a message box with Hello script message.

The last part for windows. You can add some behaviors for different events.


/**
 * Hello Fusion
 * Design Automation for Fusion's 'Hello World' sample
 * @returns {object} The parameters passed with the script.
 */
import { adsk } from "@adsk/fas";

function run() {

// Log a message
adsk.log("Hello Fusion");

// Get the Fusion API's application object
const app = adsk.core.Application.get();
if (!app) throw Error("No asdk.core.Application.");

// Log some information
adsk.log(new Date().toString());
adsk.log("UserName: " + app.userName);
adsk.log("User: " + app.currentUser.displayName);
adsk.log("UserID: " + app.userId);
adsk.log("Version: " + app.version);

// Read the parameters passed with the script
const parameters = JSON.parse(adsk.parameters);

// Hand them back as a result
adsk.result = JSON.stringify(parameters);
}

run();
        

Unlike Python and CPP, TypeScript will run the top level codes. This sample code defines a run method and calls it later.

First, we’ll get application object with adsk.core.Application.get()!.All of the Fusion objects are returned as nullable, we’ll need to unpack it before using it.

Then it will log some user infos with app.log.

Because the typescript API is designed for the cloud, the parameters are serialized json objects. We could get the parameters with JSON.parse(adsk.parameters)

Now, we have a brief view of the default scripts created with Fusion. Before we are going to write a simple script, we’ll look at the Fusion API document first. It will be very helpful to understand how to use documents when reading this tutorial.


Comments

Leave a Reply

Discover more from Autodesk Developer Blog

Subscribe now to keep reading and get access to the full archive.

Continue reading