Set parameters from a csv file and export to STEP

Description

Reads data from a .csv file and sets user parameters in the model and then exports the model to STEP. When setting parameters be aware that this sample is setting user parameters. It's also possible to set model parameters but that's not demonstrated here. Also when accessing parameters, it is case sensitive so the names you use in your program much exactly match the names in the model.

Code Samples

import adsk.core, adsk.fusion, traceback

def run(context):
    ui = None
    try:
        app = adsk.core.Application.get()
        ui  = app.userInterface
        
        design = app.activeProduct
        # Read the csv file.
        cnt = 0
        file = open('C://Temp//values.csv')
        for line in file:
            # Get the values from the csv file.
            pieces = line.split(',')
            
            length = pieces[0]
            width = pieces[1]
            height = pieces[2]
            
            # Set the parameters.
            lengthParam = design.userParameters.itemByName('Length')
            lengthParam.expression = length
            
            widthParam = design.userParameters.itemByName('Width')
            widthParam.expression = width

            heightParam = design.userParameters.itemByName('Height')
            heightParam.expression = height
            
            #Export the STEP file.
            exportMgr = design.exportManager
            stepOptions = exportMgr.createSTEPExportOptions('C:\\Temp\\test_​box' + str(cnt) + '.stp')
            cnt += 1
            res = exportMgr.execute(stepOptions)
        
        ui.messageBox('Finished')
    except:
        if ui:
            ui.messageBox('Failed:\n{}'.format(traceback.format_exc()))
#include <Core/Application/Application.h>
#include <Core/UserInterface/UserInterface.h>
#include <Fusion/Fusion/UserParameters.h>
#include <Fusion/Fusion/UserParameter.h>
#include <Fusion/Fusion/STEPExportOptions.h>
#include <Fusion/Fusion/ExportManager.h>
// startTest
#include <Core/Application/Document.h>
#include <Core/Application/Documents.h>
#include <Core/Geometry/Point3D.h>
#include <Core/UserInterface/UserInterface.h>
#include <Core/Application/ValueInput.h>
#include <Fusion/Features/Features.h>
#include <Fusion/Features/Feature.h>
#include <Fusion/Features/ExtrudeFeatures.h>
#include <Fusion/Features/ExtrudeFeature.h>
#include <Fusion/Features/ExtrudeFeatureInput.h>
#include <Fusion/Components/Component.h>
#include <Fusion/Construction/ConstructionPlane.h>
#include <Fusion/Fusion/Design.h>
#include <Fusion/Sketch/Sketch.h>
#include <Fusion/Sketch/SketchCircle.h>
#include <Fusion/Sketch/SketchCircles.h>
#include <Fusion/Sketch/SketchCurves.h>
#include <Fusion/Sketch/Sketches.h>
#include <Fusion/Sketch/SketchPoint.h>
#include <Fusion/Sketch/Profiles.h>
#include <Fusion/Sketch/Profile.h>
#include "../../../TestUtils.h"
// endTest

#include <fstream>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>

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

Ptr<UserInterface> ui;

typedef std::vector<std::vector<std::string>> DataSet;

void loadCSVFile(const std::string& csvFilePath, DataSet& dataSet)
{
    std::ifstream infile(csvFilePath);

    while (infile)
    {
        std::string s;
        if (!getline(infile, s))
            break;

        std::istringstream ss(s);
        std::vector<std::string> record;

        while (ss)
        {
            std::string s;
            if (!getline(ss, s, ','))
                break;
            record.push_back(s);
        }

        dataSet.push_back(record);
    }
}

std::string getTempPath()
{
    std::string strTempPath;
#ifdef XI_WIN
    char chPath[MAX_PATH];
    if (::GetTempPathA(MAX_PATH, chPath))
        strTempPath = chPath;
#else  // Mac
    NSString* tempDir = NSTemporaryDirectory();
    if (tempDir == nil)
        tempDir = @"/tmp";
    strTempPath = [tempDir UTF8String];
#endif // XI_WIN
    return strTempPath;
}

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

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

    // startTest
    Ptr<Documents> docs = app->documents();
    if (!docs)
        return false;

    // Create a document.
    Ptr<Document> doc = docs->add(DocumentTypes::FusionDesignDocumentType);
    if (!doc)
        return false;

    Ptr<Design> design = app->activeProduct();
    if (!design)
        return false;

    // Get the root component of the active design
    Ptr<Component> rootComp = design->rootComponent();
    if (!rootComp)
        return false;

    // Create sketch
    Ptr<Sketches> sketches = rootComp->sketches();
    if (!sketches)
        return false;

    Ptr<Sketch> sketch = sketches->add(rootComp->xYConstructionPlane());
    if (!sketch)
        return false;

    Ptr<SketchCurves> curves = sketch->sketchCurves();
    if (!curves)
        return false;

    // Draw some circles.
    Ptr<SketchCircles> sketchCircles = curves->sketchCircles();
    if (!sketchCircles)
        return false;

    Ptr<SketchCircle> sketchCircle = sketchCircles->addByCenterRadius(Point3D::create(0, 0, 0), 3.0);
    if (!sketchCircle)
        return false;

    // Get the profile defined by the circle.
    Ptr<Profiles> profiles = sketch->profiles();
    if (!profiles)
        return false;
    Ptr<Profile> profile = profiles->item(0);
    if (!profile)
        return false;

    // Create an extrusion input
    Ptr<Features> feats = rootComp->features();
    if (!feats)
        return false;
    Ptr<ExtrudeFeatures> extrudeFeats = feats->extrudeFeatures();
    if (!extrudeFeats)
        return false;
    Ptr<ExtrudeFeatureInput> extrudeFeatInput =
        extrudeFeats->createInput(profile, FeatureOperations::NewBodyFeatureOperation);
    if (!extrudeFeatInput)
        return false;

    // Define that the extent is a distance extent of 5 cm.
    Ptr<ValueInput> distance = ValueInput::createByReal(5);
    if (!distance)
        return false;
    extrudeFeatInput->setDistanceExtent(false, distance);

    // Create the extrusion.
    Ptr<ExtrudeFeature> extrudeFeat = extrudeFeats->add(extrudeFeatInput);
    if (!extrudeFeat)
        return false;
    // endTest

    // Read the csv file.
    int cnt = 0;

    // startSample
    // DataSet dataSet;
    // loadCSVFile("C:\\Temp\\values.csv", dataSet);
    // endSample

    // startTest
    std::vector<std::string> data0;
    data0.push_back("2");
    data0.push_back("3");
    data0.push_back("4");
    std::vector<std::string> data1;
    data1.push_back("3");
    data1.push_back("6");
    data1.push_back("9");
    DataSet dataSet;
    dataSet.push_back(data0);
    dataSet.push_back(data1);
    // endTest
    for (auto data : dataSet)
    {
        // Get the values from the csv file.
        std::string length = data.at(0);
        std::string width = data.at(1);
        std::string height = data.at(2);

        // Set the parameters.
        Ptr<UserParameters> userParams = design->userParameters();
        if (!userParams)
            return false;
        Ptr<UserParameter> lengthParam = userParams->itemByName("Length");
        // startTest
        if (!lengthParam)
        {
            lengthParam = userParams->add("Length", ValueInput::createByReal(0.0), "cm", "Length");
        }
        // endTest
        if (!lengthParam)
            return false;
        lengthParam->expression(length);

        Ptr<UserParameter> widthParam = userParams->itemByName("Width");
        // startTest
        if (!widthParam)
        {
            widthParam = userParams->add("Width", ValueInput::createByReal(0.0), "cm", "Width");
        }
        // endTest
        if (!widthParam)
            return false;
        widthParam->expression(width);

        Ptr<UserParameter> heightParam = userParams->itemByName("Height");
        // startTest
        if (!heightParam)
        {
            heightParam = userParams->add("Height", ValueInput::createByReal(0.0), "cm", "Height");
        }
        // endTest
        if (!heightParam)
            return false;
        heightParam->expression(height);

        // Export the STEP file.
        Ptr<ExportManager> exportMgr = design->exportManager();
        if (!exportMgr)
            return false;
        // startSample
        // std::string filename = "C:\\Temp\\test_box" + std::to_string(cnt) + ".stp";
        // Ptr<STEPExportOptions> stepOptions = exportMgr->createSTEPExportOptions(filename);
        // endSample
        // startTest
        std::string tempPath = getTempPath();
        std::string filename = tempPath + "//test_box" + std::to_string(cnt) + ".stp";
        Ptr<STEPExportOptions> stepOptions = exportMgr->createSTEPExportOptions(filename);
        // endTest
        if (!stepOptions)
            return false;

        ++cnt;
        exportMgr->execute(stepOptions);
    }

    // startTest
    if (doc)
        doc->close(false);
    // endTest

    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