Demonstrates using materials and appearance using the API.
To use the sample, create a new Python or C++ script and copy and paste this code, replacing the default code. The sample also used an external appearance library which you can get here. Copy that to any location on your computer and edit the path in the script. When running the script, have a design open that contains a body in the root component.
import adsk.core, adsk.fusion, traceback
def run(context):
ui = None
try:
app = adsk.core.Application.get()
ui = app.userInterface
# Load a local material library. You'll need to edit the path to the libary.
materialLibs = app.materialLibraries
matLib = materialLibs.load('C:/Temp//APISampleMaterialLibrary2.adsklib')
# Get the first appearance from the library.
appear = matLib.appearances.item(0)
# Copy the appearance into the design.
des = adsk.fusion.Design.cast(app.activeProduct)
appear = des.appearances.addByCopy(appear, f'{appear.name}_Copied')
# Apply the appearance to the first body in the design.
root = des.rootComponent
body = root.bRepBodies.item(0)
body.appearance = appear
# Unload the library.
if matLib.isNative == False:
matLib.unload()
except:
if ui:
ui.messageBox('Failed:\n{}'.format(traceback.format_exc()))
#include <Core/CoreAll.h>
#include <Fusion/FusionAll.h>
using namespace adsk::core;
using namespace adsk::fusion;
Ptr<Application> app;
Ptr<UserInterface> ui;
extern "C" XI_EXPORT bool run(const char* context)
{
app = Application::get();
if (!app)
return false;
Ptr<Product> product = app->activeProduct();
if (!product)
return false;
Ptr<Design> design = product;
if (!design)
return false;
// Load a local material library. You'll need to edit the path to the library.
Ptr<MaterialLibraries> matLibs = app->materialLibraries();
if (!matLibs)
return false;
Ptr<MaterialLibrary> matLib = matLibs->load("C:/Temp/APISampleMaterialLibrary2.adsklib");
// Get the first appearance from the library.
Ptr<Appearance> existingAppear = matLib->appearances()->item(0);
if (!existingAppear)
return false;
// Copy the appearance into the design.
Ptr<Appearance> appear = design->appearances()->addByCopy(existingAppear, existingAppear->name() + "_Copied");
// Get the first body in the root component of the design.
Ptr<Component> rootComp = design->rootComponent();
if (!rootComp)
return false;
Ptr<BRepBody> body = rootComp->bRepBodies()->item(0);
if (!body)
return false;
// Apply the appearance to the body.
body->appearance(appear);
if (matLib->isNative() == false)
{
matLib->unload();
}
return true;
}
/** * Material API Sample * Demonstrates using materials and appearance using the API. To use the sample, create a new Python or C++ script and copy and paste this code, replacing the default code. The sample also used an external appearance lib... */ import { adsk } from '@adsk/fusion'; function getDataFile(app: adsk.core.Application, hubId: string, fileURN: string): adsk.core.DataFile { if (hubId) { // Possible hubId formats: base64 encoded string, or business:<id>, // or personal:<id> (deprecated) const hub = app.data.dataHubs.itemById(hubId) || app.data.dataHubs.itemById(`a.${adsk.btoa(`business:${hubId}`, true)}`) || app.data.dataHubs.itemById(`a.${adsk.btoa(`personal:${hubId}`, true)}`); if (!hub) { adsk.log(`Hub with id ${hubId} not found.`) throw "Hub not found" } adsk.log(`Setting hub: ${hub.name}.`); app.data.activeHub = hub; adsk.log(`Hub has been set`) } const file = app.data.findFileById(fileURN); if (!file) { adsk.log(`File not found ${fileURN}.`) throw "File not found" } return file } function wait(ms: number) { const start = new Date().getTime(); while (new Date().getTime() - start < ms) adsk.doEvents(); } function download(hubId: string, fileURN: string, path: string) { const app = adsk.core.Application.get() const file = getDataFile(app, hubId, fileURN); adsk.log("downloading file") let future = file.dataObject adsk.log("download started") while (future.state == adsk.core.FutureStates.ProcessingFutureState) { adsk.log(".") wait(1000) } if (future.state != adsk.core.FutureStates.FinishedFutureState) { adsk.log("Download Failed") throw "Download Failed"; } let dataObect = future.dataObject adsk.log("Saving file to \"" + path + "\"") dataObect.saveToFile(path) adsk.log("Download successfull") } function createBody(rootComp: adsk.fusion.Component) { // Create a sketch const sketches = rootComp.sketches const sketch = sketches.add(rootComp.yZConstructionPlane) // Get sketch lines const sketchLines = sketch.sketchCurves.sketchLines // Create sketch rectangle const startPoint = adsk.core.Point3D.create(0, 0, 0) const endPoint = adsk.core.Point3D.create(5.0, 5.0, 0) sketchLines.addTwoPointRectangle(startPoint, endPoint) // Get the profile const prof = sketch.profiles.item(0) // Create an extrusion input const extrudes = rootComp.features.extrudeFeatures const extInput = extrudes.createInput(prof, adsk.fusion.FeatureOperations.NewBodyFeatureOperation) // Define that the extent is a distance extent of 5 cm const distance = adsk.core.ValueInput.createByReal(5.0) // Set the distance extent const distanceExtentDef = adsk.fusion.DistanceExtentDefinition.create(distance) extInput.setOneSideExtent(distanceExtentDef, adsk.fusion.ExtentDirections.PositiveExtentDirection) // Set the extrude type to be solid extInput.isSolid = true // Create the extrusion const ext = extrudes.add(extInput) // Get the body with the extrude const brepBody = ext.bodies.item(0) return brepBody } function run() { // Get the parameters passed to the script const scriptParameters = JSON.parse(adsk.parameters); if (!scriptParameters) throw "Invalid parameters provided."; const app = adsk.core.Application.get(); if (!app) throw "No adsk.core.Application."; // Create a document. const doc = app.documents.add(adsk.core.DocumentTypes.FusionDesignDocumentType) const design = app.activeProduct as adsk.fusion.Design // Get the root component of the active design. const rootComp = design.rootComponent const fileName = scriptParameters.fileName; // Download library file from Hub if (scriptParameters.libraryURN) { download(scriptParameters.hubId, scriptParameters.libraryURN, fileName) } const content: string = adsk.readFileSync(fileName) adsk.log("Library content: " + content) const materialLibs = app.materialLibraries const matLib = materialLibs.load(fileName) adsk.log("Material library loaded: " + matLib.name) // Get the first appearance from the library. let appear = matLib.appearances.item(0) // Copy the appearance into the design. appear = design.appearances.addByCopy(appear, `${appear.name}_Copied`) // Apply the appearance to the first body in the design. const body = createBody(rootComp) body.appearance = appear // Unload the library. if (matLib.isNative === false) { matLib.unload() } } run();