API Scenario

Animation

import import_api
import utility_api
import fabric_api
import pattern_api
import export_api
import ApiTypes

# ----------------------------------------------------------
# Initialize a new project session
# ----------------------------------------------------------
utility_api.NewProject()

# ----------------------------------------------------------
# 1) Import the garment (ZPRJ) file
# ----------------------------------------------------------
# NOTE:
# - Update the file path below according to your local directory structure.
# - The example path assumes macOS. Use the full absolute path on your system.
#   Example (Windows): "C:/Users/Public/Documents/CLO/Projects/Animation/cat.zprj"
#   Example (macOS):   "/Users/username/Documents/Animation/cat.zprj"
# ----------------------------------------------------------
import_api.ImportFile("/Users/alex/Documents/Animation/cat.zprj")  # <-- modify this path as needed

# ----------------------------------------------------------
# 2) Define animation
# ----------------------------------------------------------
START_FRAME = 0        # Animation start frame index
END_FRAME = 209        # Animation end frame index

# ----------------------------------------------------------
# 3) Configure animation settings
# ----------------------------------------------------------
# - Sets the animation frame range
# - Enables animation recording mode
# ----------------------------------------------------------
utility_api.SetStartAnimationFrame(START_FRAME)
utility_api.SetEndAnimationFrame(END_FRAME)
utility_api.SetAnimationRecording(True)

# ----------------------------------------------------------
# (Next steps)
# - Run simulation if needed
# - Export Alembic, turntable, or rendered animation output
# - Save final project or results
# ----------------------------------------------------------
_images/catanimation.gif



Simulation

import utility_api
import ApiTypes

print("API Test Scenario - Simulation")

# Create a new empty project
utility_api.NewProject()

# Set local asset paths (adjust these to match your environment)
AssetFolderPath = "/Users/alex/Documents/md/Assets/Avatar/Avatar/"
GarmentFolderPath = "/Users/alex/Documents/md/Assets/Garment/"

# Initialize import/export options
op = ApiTypes.ImportExportOption()

# Import Avatar (.avt)
avatarFilePath = AssetFolderPath + "Female_V2/FV2_Mia.avt"
import_api.ImportAvatar(avatarFilePath, op)

# Import Garment (.zpac)
garmentFilePath = GarmentFolderPath + "Tshirt.zpac"
import_api.ImportZpac(garmentFilePath, op)

# Run simulation for 100 frames
utility_api.Simulate(100)
_images/simulation.gif



Pattern

import pattern_api
import math

# SCALE FACTOR
scale = 3.0

# SPACING between shapes
spacing = 100.0

# --- SQUARE (0,0) to (300,300)
square_points = [
    (0.0, 0.0, 0),
    (0.0, 100.0 * scale, 0),
    (100.0 * scale, 100.0 * scale, 0),
    (100.0 * scale, 0.0, 0)
]
pattern_api.CreatePatternWithPoints(square_points)

# --- TRIANGLE placed 100 units to the right of square
triangle_offset_x = 100.0 * scale + spacing
triangle_points = [
    (triangle_offset_x, 0.0, 0),
    (triangle_offset_x + 50.0 * scale, 100.0 * scale, 0),
    (triangle_offset_x + 100.0 * scale, 0.0, 0)
]
pattern_api.CreatePatternWithPoints(triangle_points)

# --- CIRCLE approximation with 16 segments, 3x size, placed 100 units to the right of triangle
circle_offset_x = triangle_offset_x + 100.0 * scale + spacing
circle_center_x = circle_offset_x + 50.0 * scale
circle_center_y = 50.0 * scale
radius = 50.0 * scale
segments = 16

circle_points = []
for i in range(segments):
    angle = 2 * math.pi * i / segments
    x = circle_center_x + radius * math.cos(angle)
    y = circle_center_y + radius * math.sin(angle)
    circle_points.append((x, y, 0))

pattern_api.CreatePatternWithPoints(circle_points)
automatic



Substance

import import_api
import utility_api
import fabric_api

print("API Test Scenario - Substance")
folderPath = '/Users/vishal.panchal/Documents/Test/'  # <-- modify this path as needed

# Import Cloth File(zpac)
zpacfilePath = folderPath + '/Female_T-Shirt.zpac'
import_api.ImportFile(zpacfilePath)

# Import Substance
lastFabricIndex = fabric_api.GetFabricCount(True) - 1
sbsarFilePath = folderPath + "/denim_fabric.sbsar"
fabric_api.ImportSubstanceFileAsFaceType(lastFabricIndex, sbsarFilePath, "Front") # FaceType: Front, Back, Side
automatic



Avatar & Camera Tour

Level: Easy

Load an avatar into a fresh project, change the 3D background and walk the camera through the preset view points.

import time
import import_api
import utility_api
import export_api
import ApiTypes

print("API Test Scenario - Avatar & Camera Tour")

# NOTE: update this path to your local Marvelous Designer asset folder.
ASSET_ROOT = "/Users/alex/Documents/md/Assets/"

# Print the Marvelous Designer API version
print("MD API version %d.%d.%d" % (utility_api.GetMajorVersion(),
                                   utility_api.GetMinorVersion(),
                                   utility_api.GetPatchVersion()))

# Start from an empty project
utility_api.NewProject()

# Import an avatar
op = ApiTypes.ImportExportOption()
import_api.ImportAvatar(ASSET_ROOT + "Avatar/Female/FV2.1_Mia.avt", op)
print("Avatars in scene:", export_api.GetAvatarNameList())

# Soft blue-grey 3D background (RGB, 0 - 255)
utility_api.SetFormat3DBackground(196, 206, 222)

# Camera view points: 0 bottom, 1 3/4 right, 2 front, 3 3/4 left,
# 4 right, 5 top, 6 left, 7 focus zoom, 8 back, 9 zoom extents all
for viewPoint in [2, 1, 4, 8, 6, 3, 2]:
    utility_api.SetCamViewPoint(viewPoint)
    utility_api.Refresh3DWindow()
    time.sleep(0.8)   # pause so each view is visible
Avatar & Camera Tour



Fabric Assignment

Level: Easy

Import an avatar and a garment, add three fabrics from the library and assign them to the patterns in turn.

import time
import import_api
import utility_api
import fabric_api
import pattern_api
import ApiTypes

print("API Test Scenario - Fabric Assignment")

# NOTE: update this path to your local Marvelous Designer asset folder.
ASSET_ROOT = "/Users/alex/Documents/md/Assets/"

utility_api.NewProject()
op = ApiTypes.ImportExportOption()
import_api.ImportAvatar(ASSET_ROOT + "Avatar/Female/FV2.1_Mia.avt", op)
import_api.ImportZpac(ASSET_ROOT + "Garment/FV2_French Sleeve Mini Dress.zpac", op)

# Add three fabrics to the Object Browser
fabricFiles = ["V2_Woven_Plaid_1.zfab", "V2_Woven_Denim_1.zfab", "V2_Woven_Satin_1.zfab"]
fabricIndices = []
for fileName in fabricFiles:
    index = fabric_api.AddFabric(ASSET_ROOT + "Fabric/" + fileName)
    fabric_api.SetFabricName(index, fileName.replace("V2_Woven_", "").replace("_1.zfab", ""))
    fabricIndices.append(index)

# Assign the fabrics to the patterns in turn
for patternIndex in range(pattern_api.GetPatternCount()):
    fabricIndex = fabricIndices[patternIndex % len(fabricIndices)]
    fabric_api.AssignFabricToPattern(fabricIndex, patternIndex, 1)
    print("%-20s -> %s" % (pattern_api.GetPatternPieceName(patternIndex),
                           fabric_api.GetFabricName(fabricIndex)))

# Drape briefly, then look at the front and the back
utility_api.Simulate(30)
for viewPoint in [2, 8, 1]:   # front, back, 3/4 right
    utility_api.SetCamViewPoint(viewPoint)
    utility_api.Refresh3DWindow()
    time.sleep(1.0)
Fabric Assignment



Snapshot & Turntable Images

Level: Easy

Dress an avatar, then save a thumbnail and eight turntable images.

import os
import import_api
import utility_api
import export_api
import ApiTypes

print("API Test Scenario - Snapshot & Turntable")

# NOTE: update these paths for your machine.
ASSET_ROOT = "/Users/alex/Documents/md/Assets/"
OUTPUT_DIR = "/Users/alex/Documents/md/API_Output/"
os.makedirs(OUTPUT_DIR, exist_ok=True)

utility_api.NewProject()
op = ApiTypes.ImportExportOption()
import_api.ImportAvatar(ASSET_ROOT + "Avatar/Female/FV2.1_Mia.avt", op)
import_api.ImportZpac(ASSET_ROOT + "Garment/FV2_French Sleeve Mini Dress.zpac", op)
utility_api.Simulate(60)

# Front view thumbnail
utility_api.SetCamViewPoint(2)
thumbnail = export_api.ExportThumbnail3D(OUTPUT_DIR + "dress_thumbnail.png")
print("Thumbnail:", thumbnail)

# Eight turntable images, 512 x 512, numbered from 0
images = export_api.ExportTurntableImages(OUTPUT_DIR + "dress_turntable.png", 8, 512, 512, 0)
for path in images:
    print("Turntable:", path)
Snapshot & Turntable Images



Fabric Color Palette

Level: Medium

Give every pattern its own fabric and drive the PBR material (base color, roughness, metalness) from a color palette.

import time
import import_api
import utility_api
import fabric_api
import pattern_api
import ApiTypes

print("API Test Scenario - Fabric Color Palette")

# NOTE: update this path to your local Marvelous Designer asset folder.
ASSET_ROOT = "/Users/alex/Documents/md/Assets/"

FRONT = 0  # material face: 0 Front, 1 Back, 2 Side

# (name, (r, g, b), reflection roughness, metalness)
PALETTE = [
    ("Coral",    (0.98, 0.45, 0.40), 0.6, 0.0),
    ("Teal",     (0.10, 0.60, 0.60), 0.4, 0.0),
    ("Mustard",  (0.90, 0.70, 0.15), 0.5, 0.0),
    ("Navy",     (0.12, 0.18, 0.40), 0.7, 0.0),
    ("Gold",     (0.85, 0.65, 0.25), 0.2, 0.8),
]

utility_api.NewProject()
op = ApiTypes.ImportExportOption()
import_api.ImportAvatar(ASSET_ROOT + "Avatar/Female/FV2.1_Mia.avt", op)
import_api.ImportZpac(ASSET_ROOT + "Garment/FV2_French Sleeve Mini Dress.zpac", op)
utility_api.Simulate(40)

# Create one fabric per palette entry. The default fabric has no base
# texture, so the base color is shown as-is (a texture would tint it).
fabricIndices = []
for name, (r, g, b), roughness, metalness in PALETTE:
    index = fabric_api.AddFabric(ASSET_ROOT + "Fabric/(Default for Simulation).zfab")
    fabric_api.SetFabricName(index, name)
    fabric_api.SetFabricPBRMaterialBaseColor(index, FRONT, r, g, b, 1.0)
    fabric_api.SetReflectionRoughness(index, FRONT, roughness)
    fabric_api.SetMetalness(index, FRONT, metalness)
    fabricIndices.append(index)

# Assign palette fabrics to patterns, cycling through the palette
for patternIndex in range(pattern_api.GetPatternCount()):
    fabricIndex = fabricIndices[patternIndex % len(fabricIndices)]
    fabric_api.AssignFabricToPattern(fabricIndex, patternIndex, 1)

# Textured surface rendering, then look around the garment
utility_api.Set3DGarmentRenderingStyle(0)
for viewPoint in [2, 1, 8, 3, 2]:   # front, 3/4 right, back, 3/4 left, front
    utility_api.SetCamViewPoint(viewPoint)
    utility_api.Refresh3DWindow()
    time.sleep(0.8)
for index in fabricIndices:
    print(fabric_api.GetFabricName(index), fabric_api.GetFabricPBRMaterialBaseColor(index, FRONT))
Fabric Color Palette



Pattern Grid Layout

Level: Medium

Build regular polygons from points, name them, lay them out on a grid in the 2D window and set grain line and particle distance per pattern.

import math
import pattern_api
import utility_api

print("API Test Scenario - Pattern Grid Layout")

utility_api.NewProject()

RADIUS = 250.0     # mm
SPACING = 650.0    # mm between grid cells
COLUMNS = 3

def regular_polygon(sides, radius, star=False):
    """Return (x, y, vertexType) points of a regular polygon or star."""
    points = []
    count = sides * 2 if star else sides
    for i in range(count):
        angle = 2 * math.pi * i / count - math.pi / 2
        r = radius * (0.45 if star and i % 2 else 1.0)
        points.append((r * math.cos(angle), r * math.sin(angle), 0))  # 0 = straight point
    return points

SHAPES = [
    ("Triangle", 3, False), ("Square", 4, False), ("Pentagon", 5, False),
    ("Hexagon", 6, False), ("Octagon", 8, False), ("Star", 5, True),
]

for i, (name, sides, star) in enumerate(SHAPES):
    patternIndex = pattern_api.CreatePatternWithPoints(regular_polygon(sides, RADIUS, star))
    pattern_api.SetPatternPieceName(patternIndex, name)

    # Place on a grid centered on the 2D origin: column/row from the creation order
    column, row = i % COLUMNS, i // COLUMNS
    pattern_api.SetPatternPiecePos(patternIndex, (column - 1) * SPACING, (row - 0.5) * SPACING)

    # Rotate the grain line 15 degrees per shape, finer mesh for stars
    pattern_api.SetPatternPieceGrainDirection(patternIndex, 15.0 * i)
    pattern_api.SetParticleDistanceOfPattern(patternIndex, 5.0 if star else 10.0)

# Report what was built
for patternIndex in range(pattern_api.GetPatternCount()):
    print("%-9s area=%9.1f mm2  pos=%s" % (
        pattern_api.GetPatternPieceName(patternIndex),
        pattern_api.GetPatternPieceArea(patternIndex),
        [round(v, 1) for v in pattern_api.GetPatternPiecePos(patternIndex)]))
Pattern Grid Layout



Simulation Physics

Level: Medium

Compare how the same garment drapes under different simulation settings: low gravity, then normal gravity with high air damping.

import time
import import_api
import utility_api
import ApiTypes

print("API Test Scenario - Simulation Physics")

# NOTE: update this path to your local Marvelous Designer asset folder.
ASSET_ROOT = "/Users/alex/Documents/md/Assets/"

utility_api.NewProject()
op = ApiTypes.ImportExportOption()
import_api.ImportAvatar(ASSET_ROOT + "Avatar/Female/FV2.1_Mia.avt", op)
import_api.ImportZpac(ASSET_ROOT + "Garment/FV2_French Sleeve Mini Dress.zpac", op)
utility_api.SetCamViewPoint(1)

# Quality preset: 0 Normal, 1 Animation, 2 Fitting, 3 FAST(GPU); mode 0 CPU, 1 GPU
utility_api.SetSimulationQuality(0, 0)

def run(label, gravity, airDamping, steps):
    utility_api.SetSimulationGravity(gravity)        # mm/s^2, default -9800
    utility_api.SetSimulationAirDamping(airDamping)  # default 1.0
    utility_api.Simulate(steps)
    utility_api.Refresh3DWindow()
    print("%-16s gravity=%8.1f damping=%.1f steps=%d" % (label, gravity, airDamping, steps))
    time.sleep(1.0)

# 1) Moon-like gravity: the dress floats and settles slowly
run("Low gravity", -1600.0, 1.0, 60)

# 2) Reset to the loaded shape, then drape with normal gravity
utility_api.ResetClothArrangement()
run("Normal gravity", -9800.0, 1.0, 60)

# 3) Heavy air damping: motion is strongly slowed down
utility_api.ResetClothArrangement()
run("High air damping", -9800.0, 20.0, 60)

# Restore defaults
utility_api.SetSimulationGravity(-9800.0)
utility_api.SetSimulationAirDamping(1.0)
Simulation Physics



Schematic Render

Level: Medium

Switch the 3D window to schematic (technical drawing) mode, style the lines and cloth color, save a thumbnail, then switch back.

import os
import time
import import_api
import utility_api
import export_api
import ApiTypes

print("API Test Scenario - Schematic Render")

# NOTE: update these paths for your machine.
ASSET_ROOT = "/Users/alex/Documents/md/Assets/"
OUTPUT_DIR = "/Users/alex/Documents/md/API_Output/"
os.makedirs(OUTPUT_DIR, exist_ok=True)

utility_api.NewProject()
op = ApiTypes.ImportExportOption()
import_api.ImportAvatar(ASSET_ROOT + "Avatar/Female/FV2.1_Mia.avt", op)
import_api.ImportZpac(ASSET_ROOT + "Garment/FV2_French Sleeve Mini Dress.zpac", op)
utility_api.Simulate(60)
utility_api.SetCamViewPoint(2)

# Hide the avatar so only the garment is drawn
utility_api.SetShowHideAvatar(False)

# Schematic style
utility_api.SetSchematicRender(True)
utility_api.SetSchematicClothRenderType(False)      # False: solid color, True: texture
utility_api.SetSchematicClothColor(255, 255, 255)   # white cloth
utility_api.SetShowSchematicSilhouetteLine(True)
utility_api.SetSchematicSilhouetteLineWidth(4)
utility_api.SetShowSchematicSeamLine(True)
utility_api.SetSchematicSeamLineWidth(2)
utility_api.SetShowSchematicInternalLine(True)
utility_api.SetSchematicInternalLineWidth(1)
utility_api.SetShowSchematicTopstitchLine(True)
utility_api.Refresh3DWindow()

print("Schematic:", export_api.ExportThumbnail3D(OUTPUT_DIR + "dress_schematic.png"))

time.sleep(2.0)  # keep the schematic view on screen for a moment

# Back to the normal view
utility_api.SetSchematicRender(False)
utility_api.SetShowHideAvatar(True)
Schematic Render



Fabric Variation Batch

Level: High

Render the same garment in several fabrics: swap the fabric on every pattern, re-drape, and save one image per variation with a progress bar.

import os
import import_api
import utility_api
import fabric_api
import pattern_api
import export_api
import ApiTypes

print("API Test Scenario - Fabric Variation Batch")

# NOTE: update these paths for your machine.
ASSET_ROOT = "/Users/alex/Documents/md/Assets/"
OUTPUT_DIR = "/Users/alex/Documents/md/API_Output/"

VARIATIONS = [
    "V2_Woven_Denim_1.zfab",
    "V2_Woven_Corduroy_1.zfab",
    "V2_Woven_Satin_1.zfab",
    "V2_Woven_Tweed_1.zfab",
    "V2_Cut_Sew_Knit_Velvet_1.zfab",
]
SIMULATION_STEPS = 40

outputFolder = os.path.join(OUTPUT_DIR, "fabric_variations")
os.makedirs(outputFolder, exist_ok=True)

utility_api.NewProject()
op = ApiTypes.ImportExportOption()
import_api.ImportAvatar(ASSET_ROOT + "Avatar/Female/FV2.1_Mia.avt", op)
import_api.ImportZpac(ASSET_ROOT + "Garment/FV2_French Sleeve Mini Dress.zpac", op)
utility_api.SetCamViewPoint(1)  # 3/4 right

# One working fabric, assigned to every pattern once
workFabric = fabric_api.AddFabric(ASSET_ROOT + "Fabric/" + VARIATIONS[0])
for patternIndex in range(pattern_api.GetPatternCount()):
    fabric_api.AssignFabricToPattern(workFabric, patternIndex, 1)

results = []
utility_api.CreateProgressBar()
try:
    for i, fileName in enumerate(VARIATIONS):
        label = os.path.splitext(fileName)[0]
        utility_api.SetProgress("Variation %d/%d: %s" % (i + 1, len(VARIATIONS), label),
                                int(100 * i / len(VARIATIONS)))

        # Replace the fabric in place: all patterns pick up the new material
        if not fabric_api.ReplaceFabric(workFabric, ASSET_ROOT + "Fabric/" + fileName):
            print("Skipped (cannot load):", fileName)
            continue
        fabric_api.SetFabricName(workFabric, label)

        # Re-drape from the loaded arrangement so every variation is comparable
        utility_api.ResetClothArrangement()
        utility_api.Simulate(SIMULATION_STEPS)

        imagePath = export_api.ExportThumbnail3D(os.path.join(outputFolder, label + ".png"))
        results.append((label, imagePath))
    utility_api.SetProgress("Done", 100)
finally:
    utility_api.DeleteProgressBar(True)

for label, imagePath in results:
    print("%-32s %s" % (label, imagePath))
print("%d / %d variations saved to %s" % (len(results), len(VARIATIONS), outputFolder))
Fabric Variation Batch



Game-Ready Export

Level: High

Prepare a draped garment for a game engine: set a coarser mesh, pack the UVs, bake a unified texture and export OBJ and FBX with explicit options.

import os
import import_api
import utility_api
import fabric_api
import pattern_api
import export_api
import ApiTypes

print("API Test Scenario - Game-Ready Export")

# NOTE: update these paths for your machine.
ASSET_ROOT = "/Users/alex/Documents/md/Assets/"
OUTPUT_DIR = "/Users/alex/Documents/md/API_Output/"

PARTICLE_DISTANCE = 15.0   # mm, larger = fewer polygons
TEXTURE_SIZE = 2048

outputFolder = os.path.join(OUTPUT_DIR, "game_ready")
os.makedirs(outputFolder, exist_ok=True)

utility_api.NewProject()
op = ApiTypes.ImportExportOption()
import_api.ImportAvatar(ASSET_ROOT + "Avatar/Female/FV2.1_Mia.avt", op)
import_api.ImportZpac(ASSET_ROOT + "Garment/FV2_French Sleeve Mini Dress.zpac", op)

# 1) Plaid fabric (so the baked texture shows the UV layout) and a coarser
#    mesh on every pattern, then drape
plaid = fabric_api.AddFabric(ASSET_ROOT + "Fabric/V2_Woven_Plaid_1.zfab")
for patternIndex in range(pattern_api.GetPatternCount()):
    fabric_api.AssignFabricToPattern(plaid, patternIndex, 1)
    pattern_api.SetParticleDistanceOfPattern(patternIndex, PARTICLE_DISTANCE)
utility_api.Simulate(60)
utility_api.Set3DGarmentRenderingStyle(4)   # show the mesh
utility_api.SetCamViewPoint(1)

# 2) Pack all UV islands into the 0-1 tile: all patterns, rescale to fit,
#    advanced search, padding 0.005 (0.001 = 1 unit in the UV tile),
#    fidelity 2, allow 0 / 90 degree rotations
utility_api.UVPacking(True, False, True, 0.005, 2, [0, 90])

# 3) Export options shared by the OBJ and FBX exports
exportOption = ApiTypes.ImportExportOption()
exportOption.bExportGarment = True
exportOption.bExportAvatar = False
exportOption.bSingleObject = True
exportOption.bThin = False                  # keep thickness
exportOption.bClothUnifiedUVCoordinates = True   # use the packed UV editor layout
exportOption.unifiedTextureSize = TEXTURE_SIZE
exportOption.bUnifiedDiffuseMap = True
exportOption.bUnifiedNormalMap = True
exportOption.scale = 0.1                    # mm -> cm
exportOption.bSaveInZip = False

# 4) Bake the unified texture for all patterns
baked = utility_api.BakeUVTexture(os.path.join(outputFolder, "dress_baked.png"), exportOption, True)
print("Baked textures:", baked)

# 5) Export
for path in export_api.ExportOBJ(os.path.join(outputFolder, "dress.obj"), exportOption):
    print("OBJ:", path)
for path in export_api.ExportFBX(os.path.join(outputFolder, "dress.fbx"), exportOption):
    print("FBX:", path)

utility_api.Set3DGarmentRenderingStyle(0)
Game-Ready Export



Garment Inspection Report

Level: High

Inspect every pattern of a garment, write a CSV and JSON report, highlight the largest pattern in 3D and save the project next to the reports.

import csv
import json
import os
import import_api
import utility_api
import fabric_api
import pattern_api
import export_api
import ApiTypes

print("API Test Scenario - Garment Inspection Report")

# NOTE: update these paths for your machine.
ASSET_ROOT = "/Users/alex/Documents/md/Assets/"
OUTPUT_DIR = "/Users/alex/Documents/md/API_Output/"

outputFolder = os.path.join(OUTPUT_DIR, "inspection")
os.makedirs(outputFolder, exist_ok=True)

utility_api.NewProject()
op = ApiTypes.ImportExportOption()
import_api.ImportAvatar(ASSET_ROOT + "Avatar/Female/FV2.1_Mia.avt", op)
import_api.ImportZpac(ASSET_ROOT + "Garment/FV2_French Sleeve Mini Dress.zpac", op)
utility_api.Simulate(40)

# 1) Collect pattern data
rows = []
for patternIndex in range(pattern_api.GetPatternCount()):
    fabricIndex = pattern_api.GetPatternPieceFabricIndex(patternIndex)
    box = pattern_api.GetBoundingBoxOfPattern(patternIndex)
    rows.append({
        "index": patternIndex,
        "name": pattern_api.GetPatternPieceName(patternIndex),
        "area_mm2": round(pattern_api.GetPatternPieceArea(patternIndex), 1),
        "width_mm": round(float(box.get("Width", 0)), 1),
        "height_mm": round(float(box.get("Height", 0)), 1),
        "fabric": fabric_api.GetFabricName(fabricIndex),
        "particle_distance_mm": pattern_api.GetParticleDistanceOfPattern(patternIndex),
        "layer": pattern_api.GetPatternLayer(patternIndex),
    })

# 2) Write the reports
csvPath = os.path.join(outputFolder, "pattern_report.csv")
with open(csvPath, "w", newline="") as f:
    writer = csv.DictWriter(f, fieldnames=list(rows[0].keys()))
    writer.writeheader()
    writer.writerows(rows)

summary = {
    "project": utility_api.GetProjectName(),
    "pattern_count": len(rows),
    "total_area_mm2": round(sum(r["area_mm2"] for r in rows), 1),
    "fabrics": sorted(set(r["fabric"] for r in rows)),
    "patterns": rows,
}
jsonPath = os.path.join(outputFolder, "pattern_report.json")
with open(jsonPath, "w") as f:
    json.dump(summary, f, indent=2)

# 3) Highlight the largest pattern with a red fabric
largest = max(rows, key=lambda r: r["area_mm2"])
highlight = fabric_api.AddFabric(ASSET_ROOT + "Fabric/V2_Woven_Plain_1.zfab")
fabric_api.SetFabricName(highlight, "Largest pattern")
fabric_api.SetFabricPBRMaterialBaseColor(highlight, 0, 0.9, 0.1, 0.1, 1.0)
fabric_api.AssignFabricToPattern(highlight, largest["index"], 1)
utility_api.SetCamViewPoint(2)

# 4) Save the project (with a thumbnail) next to the reports
zprjPath = export_api.ExportZPrj(os.path.join(outputFolder, "inspected_dress.zprj"), True)

print("%-28s %10s %8s %8s  %s" % ("Pattern", "Area mm2", "W", "H", "Fabric"))
for r in rows:
    print("%-28s %10.1f %8.1f %8.1f  %s" % (r["name"], r["area_mm2"], r["width_mm"], r["height_mm"], r["fabric"]))
print("Largest pattern: %s (%.1f mm2)" % (largest["name"], largest["area_mm2"]))
print("Reports:", csvPath, jsonPath)
print("Project:", zprjPath)
Garment Inspection Report



Scenarios with API Options

These scenarios focus on option objects from the ApiTypes module: each one creates the option object, sets its fields with a comment on what every field does, passes it to the API call and prints the result, so you can see what each option changes. All fields are listed in ApiTypes.


Import Options

Level: Medium

Options used: ImportZPRJOption, ImportExportOption

Control what an import brings in and where it goes. ImportZPRJOption loads only the garment or only the avatar of a project, appends a second copy next to the first, and ImportExportOption turns an OBJ into an avatar placed beside them.

import os
import import_api
import utility_api
import export_api
import pattern_api
import ApiTypes

print("API Test Scenario - Import Options")

# NOTE: update these paths for your machine.
ASSET_ROOT = "/Users/alex/Documents/md/Assets/"
OUTPUT_DIR = "/Users/alex/Documents/md/API_Output/"

work = os.path.join(OUTPUT_DIR, "import_options")
os.makedirs(work, exist_ok=True)


def report(step):
    print("%-38s patterns=%2d  avatars=%d" % (step, pattern_api.GetPatternCount(), export_api.GetAvatarCount()))


# ----------------------------------------------------------------------------
# 0) Prepare the inputs: a project file and an avatar OBJ
# ----------------------------------------------------------------------------
utility_api.NewProject()
import_api.ImportAvatar(ASSET_ROOT + "Avatar/Female/FV2.1_Mia.avt", ApiTypes.ImportExportOption())
import_api.ImportZpac(ASSET_ROOT + "Garment/FV2_French Sleeve Mini Dress.zpac", ApiTypes.ImportExportOption())
utility_api.Simulate(40)
projectPath = export_api.ExportZPrj(os.path.join(work, "dress.zprj"), False)

avatarOnly = ApiTypes.ImportExportOption()
avatarOnly.bExportGarment = False    # leave the dress out of the OBJ
avatarOnly.bExportAvatar = True      # the avatar mesh only
avatarOnly.bSingleObject = True      # one mesh instead of one object per avatar part
avatarOnly.scale = 1.0               # keep millimetres (MD's unit) in the file
avatarObj = export_api.ExportOBJ(os.path.join(work, "avatar.obj"), avatarOnly)[0]

# ----------------------------------------------------------------------------
# 1) ImportZPRJOption: open only the garment of the project
# ----------------------------------------------------------------------------
utility_api.NewProject()
garmentOnly = ApiTypes.ImportZPRJOption()
garmentOnly.bAppend = False          # replace the current project (the default)
garmentOnly.bLoadGarment = True      # patterns, fabrics, sewing
garmentOnly.bLoadAvatar = False      # skip the avatar stored in the file
import_api.ImportZprj(projectPath, garmentOnly)
report("1) garment only")

# ----------------------------------------------------------------------------
# 2) Add only the avatar from the same file
# ----------------------------------------------------------------------------
avatarAppend = ApiTypes.ImportZPRJOption()
avatarAppend.bAppend = True          # add to the open project instead of replacing it
avatarAppend.bLoadGarment = False
avatarAppend.bLoadAvatar = True
import_api.ImportZprj(projectPath, avatarAppend)
report("2) + avatar from the same file")

# ----------------------------------------------------------------------------
# 3) Add a second copy of the garment, moved 900 mm to the right
# ----------------------------------------------------------------------------
secondCopy = ApiTypes.ImportZPRJOption()
secondCopy.bAppend = True
secondCopy.bLoadGarment = True
secondCopy.bLoadAvatar = False
secondCopy.translationValueX = 900.0     # mm: shifts the 2D patterns and the 3D garment
import_api.ImportZprj(projectPath, secondCopy)
report("3) + second garment, X +900 mm")

# ----------------------------------------------------------------------------
# 4) ImportExportOption: the OBJ becomes an avatar for the second garment
# ----------------------------------------------------------------------------
objAsAvatar = ApiTypes.ImportExportOption()
objAsAvatar.ImportObjectType = 0         # 0 = Avatar, 1 = Trim, 2 = Garment
objAsAvatar.bAdd = True                  # add to the scene, keep what is already there
objAsAvatar.scale = 1.0                  # the file is in millimetres
objAsAvatar.bAutoTranslate = False       # keep the file's position, then move it:
objAsAvatar.translationValueX = 900.0    # under the second garment
import_api.ImportOBJ(avatarObj, objAsAvatar)
report("4) + OBJ as avatar, X +900 mm")

utility_api.Simulate(30)
utility_api.SetCamViewPoint(9)           # zoom extents: both avatars in view
Import Options



Export Options

Level: High

Options used: ImportExportOption, ExportUSDOption

Export one draped garment with different ImportExportOption settings (single object or one object per pattern, thick or thin, scale, up axis) plus USD with ExportUSDOption and Alembic, then compare the files: vertex count, object count and size along each axis.

import os
import re
import import_api
import utility_api
import export_api
import ApiTypes

print("API Test Scenario - Export Options")

# NOTE: update these paths for your machine.
ASSET_ROOT = "/Users/alex/Documents/md/Assets/"
OUTPUT_DIR = "/Users/alex/Documents/md/API_Output/"

out = os.path.join(OUTPUT_DIR, "export_options")
os.makedirs(out, exist_ok=True)

utility_api.NewProject()
import_api.ImportAvatar(ASSET_ROOT + "Avatar/Female/FV2.1_Mia.avt", ApiTypes.ImportExportOption())
import_api.ImportZpac(ASSET_ROOT + "Garment/FV2_French Sleeve Mini Dress.zpac", ApiTypes.ImportExportOption())
utility_api.Simulate(60)
utility_api.SetCamViewPoint(1)   # 3/4 right
utility_api.SetCamViewPoint(9)   # then zoom to fit the garment


def options(**fields):
    """An ImportExportOption with the given fields set; everything else keeps its default."""
    option = ApiTypes.ImportExportOption()
    for name, value in fields.items():
        setattr(option, name, value)
    return option


def obj_stats(path):
    """(vertices, objects, size x, size y, size z) of an OBJ file."""
    count, objects, low, high = 0, 0, [float("inf")] * 3, [float("-inf")] * 3
    with open(path) as f:
        for line in f:
            if line.startswith("v "):
                count += 1
                xyz = [float(v) for v in line.split()[1:4]]
                low = [min(a, b) for a, b in zip(low, xyz)]
                high = [max(a, b) for a, b in zip(high, xyz)]
            elif line.startswith(("o ", "g ")):
                objects += 1
    return (count, objects) + tuple(h - l for l, h in zip(low, high))


# Garment only, one mesh, single-layer (thin) surface, millimetres, Y up: the reference
reference = options(bExportGarment=True, bExportAvatar=False, bSingleObject=True, bThin=True, scale=1.0)

variants = [
    ("reference (mm, thin, one mesh)", reference),
    # bSingleObject=False: one object per pattern; bThin=False: both cloth surfaces and the
    # edges between them; scale=0.1: millimetres -> centimetres
    ("per pattern, thick, cm", options(bExportGarment=True, bExportAvatar=False, bSingleObject=False,
                                       bThin=False, scale=0.1)),
    # metres with Z up: axisX/Y/Z pick the source axis for each output axis (0=X, 1=Y, 2=Z),
    # bInvertZ flips the new Z so the garment stays upright and faces the same way
    ("Z up, metres", options(bExportGarment=True, bExportAvatar=False, bSingleObject=True, bThin=True,
                             scale=0.001, axisX=0, axisY=2, axisZ=1, bInvertZ=True)),
]

print("%-32s %8s %8s %10s %10s %10s" % ("OBJ variant", "vertices", "objects", "size X", "size Y", "size Z"))
for label, option in variants:
    path = export_api.ExportOBJ(os.path.join(out, label.split(" (")[0].replace(", ", "_").replace(" ", "_") + ".obj"), option)[0]
    print("%-32s %8d %8d %10.3f %10.3f %10.3f" % ((label,) + obj_stats(path)))

# FBX: garment and avatar together, one object per pattern, centimetres
fbx = export_api.ExportFBX(os.path.join(out, "garment_and_avatar.fbx"),
                           options(bExportGarment=True, bExportAvatar=True, bSingleObject=False, scale=0.1))
print("FBX:", fbx[0])

# USD: ExportUSDOption names the stage layout, ImportExportOption picks what goes in
usd = ApiTypes.ExportUSDOption()
usd.m_upAxis = 1                    # 1 = Y up
usd.m_metersPerUnit = 0.01          # stage unit: centimetres
usd.m_bAssignAvatar = True
usd.m_avatarPrimPath = "/Avatar"    # where the avatar meshes live in the stage
usd.m_bAssignGarment = True
usd.m_garmentPrimPath = "/Dress"    # where the garment meshes live
usd.m_bExportSimulationData = False
usdFiles = export_api.ExportUSD(os.path.join(out, "scene.usda"),
                                options(bExportGarment=True, bExportAvatar=True), usd)
with open(usdFiles[0]) as f:
    stage = f.read()
scopes = sorted(set(re.findall(r'def Scope "(\w+)"', stage)))
print("USD:", usdFiles[0])
print("     upAxis Y: %s, metersPerUnit 0.01: %s, top-level prims: %s"
      % ('upAxis = "Y"' in stage, "metersPerUnit = 0.01" in stage, scopes))

# Alembic: garment only, centimetres
abc = export_api.ExportAlembic(os.path.join(out, "garment.abc"),
                               options(bExportGarment=True, bExportAvatar=False, bSingleObject=True, scale=0.1))
print("Alembic:", abc[0])
Export Options



Wind & Animation Video Options

Level: Medium

Options used: WindControllerOptions, VideoExportOption

Read the wind controller with WindControllerOptions, turn it into a strong, gusty side wind, record the dress moving in it and save the animation with VideoExportOption.

import os
import import_api
import utility_api
import export_api
import ApiTypes

print("API Test Scenario - Wind & Animation Video Options")

# NOTE: update these paths for your machine.
ASSET_ROOT = "/Users/alex/Documents/md/Assets/"
OUTPUT_DIR = "/Users/alex/Documents/md/API_Output/"

os.makedirs(OUTPUT_DIR, exist_ok=True)

utility_api.NewProject()
import_api.ImportAvatar(ASSET_ROOT + "Avatar/Female/FV2.1_Mia.avt", ApiTypes.ImportExportOption())
import_api.ImportZpac(ASSET_ROOT + "Garment/FV2_French Sleeve Mini Dress.zpac", ApiTypes.ImportExportOption())
utility_api.Simulate(40)
utility_api.SetCamViewPoint(1)   # 3/4 right
utility_api.SetCamViewPoint(9)   # then zoom to fit the garment


def show(label, w):
    print("%-8s active=%s type=%d strength=%.0f decay=%.0f frequency=%.1f turbulence=%.0f "
          "position=(%.0f, %.0f, %.0f) rotation=(%.0f, %.0f, %.0f)"
          % (label, w.bWindActive, w.windType, w.strength, w.decay, w.frequency, w.turbulence,
             w.x, w.y, w.z, w.rotationX, w.rotationY, w.rotationZ))


# Every project has one wind controller (index 0); it starts inactive
wind = utility_api.GetWindControllerSettings(0)
show("before", wind)

wind.bWindActive = True
wind.windType = 1          # 0 = Spherical (blows outwards from a point), any other value = Planar
wind.strength = 4000.0     # force of the wind
wind.decay = 0.0           # 0-100: how fast the force fades with distance (0 = no fade)
wind.frequency = 2.0       # 0-100000: gusts per second (0 = constant)
wind.turbulence = 60.0     # 0-100: random variation of direction and force
wind.x, wind.y, wind.z = -900.0, 1000.0, 0.0           # mm: left of the avatar, at hip height
wind.rotationX, wind.rotationY, wind.rotationZ = 0.0, 90.0, 0.0   # degrees: blow towards +X
utility_api.SetWindControllerSettings(0, wind)
show("after", utility_api.GetWindControllerSettings(0))

# Record 90 frames of the simulation in the wind (frames are recorded at the animation frame rate)
utility_api.RunAnimationRecording(0, 90)

video = ApiTypes.VideoExportOption()
video.width = 720                # pixels
video.height = 960
video.fps = 2                    # an index, not frames per second: 0 = 24, 1 = 25, 2 = 30, 3 = 60
                                 # (-1 = the animation's own frame rate)
video.startFrame = 0             # -1 = from the first recorded frame
video.endFrame = 90              # -1 = to the last recorded frame
path = export_api.ExportAnimationVideo(os.path.join(OUTPUT_DIR, "dress_in_wind.mp4"), video)
print("Video:", path)

# Calm again for the next script
wind.bWindActive = False
utility_api.SetWindControllerSettings(0, wind)
Wind & Animation Video Options



Material Property Options

Level: High

Options used: ObjectBrowserContextOptions, MaterialPropertyOptions, MaterialContextOptions, PropertyEditorContextOptions, TransformOptions

Edit a fabric’s material through option objects: ObjectBrowserContextOptions finds the fabric, MaterialPropertyOptions reads and writes its front face (color, normal map, reflection) in one call, and PropertyEditorContextOptions + TransformOptions rotate and scale its texture.

import json
import import_api
import utility_api
import fabric_api
import pattern_api
import ApiTypes

print("API Test Scenario - Material Property Options")

# NOTE: update this path to your local Marvelous Designer asset folder.
ASSET_ROOT = "/Users/alex/Documents/md/Assets/"

utility_api.NewProject()
import_api.ImportAvatar(ASSET_ROOT + "Avatar/Female/FV2.1_Mia.avt", ApiTypes.ImportExportOption())
import_api.ImportZpac(ASSET_ROOT + "Garment/FV2_French Sleeve Mini Dress.zpac", ApiTypes.ImportExportOption())
utility_api.Simulate(40)
utility_api.SetCamViewPoint(2)   # front
utility_api.SetCamViewPoint(9)   # then zoom to fit the garment

# A plaid fabric on every pattern
plaid = fabric_api.AddFabric(ASSET_ROOT + "Fabric/V2_Woven_Plaid_1.zfab")
for patternIndex in range(pattern_api.GetPatternCount()):
    fabric_api.AssignFabricToPattern(plaid, patternIndex, 1)

# ----------------------------------------------------------------------------
# 1) ObjectBrowserContextOptions: which Object Browser list the index refers to
# ----------------------------------------------------------------------------
browser = ApiTypes.ObjectBrowserContextOptions()
browser.type = ApiTypes.ObjectBrowserType.OB_TYPE_FABRIC   # the Fabric list
browser.targetPrint = False           # the fabric itself, not its print / AOP
browser.bIncludeUnusedObjects = True  # also list fabrics no pattern uses
items = json.loads(utility_api.GetObjectBrowserItems(browser))["ObjectNameList"]
index = items.index(fabric_api.GetFabricName(plaid))       # index within that list
print("Fabric list:", items, "-> plaid at", index)

# ----------------------------------------------------------------------------
# 2) MaterialPropertyOptions: read and write a whole material face in one call
# ----------------------------------------------------------------------------
request = ApiTypes.MaterialPropertyOptions()
request.contextOptions.targetComponent = ApiTypes.MaterialTargetComponent.COMPONENT_FRONT  # Front tab

material = utility_api.GetMaterialProperties(0, index, browser, request)   # the first argument is always 0 in Marvelous Designer
front = material.front
print("before: type=%s mapping=%s color=%s normal=%d reflection=%d maps=%s"
      % (front.type, front.texture_mapping, front.base_color.color_hex_or_name,
         front.normal_map.intensity, front.reflection.reflection_intensity, front.GetPresentMaps()))

front.base_color.color_hex_or_name = "#C9D8F0"   # tint the plaid light blue
front.normal_map.intensity = 80                  # 0-100: stronger weave relief
front.reflection.reflection_intensity = 25       # 0-100: a little sheen
print(utility_api.SetMaterialProperties(0, index, browser, request, material))

front = utility_api.GetMaterialProperties(0, index, browser, request).front
print("after:  type=%s mapping=%s color=%s normal=%d reflection=%d"
      % (front.type, front.texture_mapping, front.base_color.color_hex_or_name,
         front.normal_map.intensity, front.reflection.reflection_intensity))

# ----------------------------------------------------------------------------
# 3) PropertyEditorContextOptions + TransformOptions: transform the texture
# ----------------------------------------------------------------------------
editor = ApiTypes.PropertyEditorContextOptions()
editor.materialSide = 0                                         # 0 = Front, 1 = Back, 2 = Side
editor.mapType = ApiTypes.TextureMapTarget.TEXTURE_MAP_BASE_COLOR

transform = utility_api.GetMaterialTextureTransformations(0, index, browser, editor)
print("texture before: angle=%.0f width=%.1f mm (%.0f%%) height=%.1f mm"
      % (transform.angle, transform.widthMm, transform.widthPercent, transform.heightMm))
transform.angle = 45.0              # degrees: a bias-cut plaid
transform.widthMm = 0.0             # 0 = use the percentages below instead of millimetres
transform.heightMm = 0.0
transform.widthPercent = 250.0      # bigger checks
transform.heightPercent = 250.0
transform.aspectRatioFixed = True
utility_api.SetMaterialTextureTransformations(0, index, browser, editor, transform)

transform = utility_api.GetMaterialTextureTransformations(0, index, browser, editor)
print("texture after:  angle=%.0f width=%.1f mm (%.0f%%) height=%.1f mm"
      % (transform.angle, transform.widthMm, transform.widthPercent, transform.heightMm))
utility_api.Refresh3DWindow()
Material Property Options



Pattern Snapshot Options

Level: Medium

Options used: PatternSnapShotSizeOption, PatternSnapShotLineOption, PatternSnapShotImageOption, PatternSnapShotInformationOption

Configure the 2D pattern snapshot with its four option types (paper size, lines, textures, labels) and export it before and after, so the two images show what each option changes.

import os
import import_api
import utility_api
import export_api
import fabric_api
import pattern_api
import ApiTypes

print("API Test Scenario - Pattern Snapshot Options")

# NOTE: update these paths for your machine.
ASSET_ROOT = "/Users/alex/Documents/md/Assets/"
OUTPUT_DIR = "/Users/alex/Documents/md/API_Output/"

out = os.path.join(OUTPUT_DIR, "pattern_snapshot")
os.makedirs(out, exist_ok=True)

utility_api.NewProject()
import_api.ImportZpac(ASSET_ROOT + "Garment/FV2_French Sleeve Mini Dress.zpac", ApiTypes.ImportExportOption())
plaid = fabric_api.AddFabric(ASSET_ROOT + "Fabric/V2_Woven_Plaid_1.zfab")
for patternIndex in range(pattern_api.GetPatternCount()):
    fabric_api.AssignFabricToPattern(plaid, patternIndex, 1)

WINDOW = 0     # 0 = the 2D Pattern window, 1 = the Print Layout window

print("default:", export_api.ExportSnapshot2D(os.path.join(out, "default.png"), WINDOW)[0])

# Paper: A4 landscape at 150 dpi
size = utility_api.GetPatternSnapShotSizeOption(WINDOW)
size.m_paperPreset = 0        # 0 = A4, 1 = A3, 2 = B5, 3 = B4, 4 = Letter, 5 = Legal, 6 = Tabloid, 7 = 24" roll
size.m_orientation = 1        # 0 = portrait, 1 = landscape
size.m_resolution = 150       # dots per inch
utility_api.SetPatternSnapShotSizeOption(size, WINDOW)

# Lines: red outlines, show internal lines and notches
lines = utility_api.GetPatternSnapShotLineOption(WINDOW)
lines.ShowPatternOutline = True
lines.PatternOutlineColor.R, lines.PatternOutlineColor.G, lines.PatternOutlineColor.B = 200, 30, 30
lines.ShowInternalLine = True
lines.ShowNotch = True
utility_api.SetPatternSnapShotLineOption(lines, WINDOW)

# Textures: show the fabric at 60 % opacity
image = utility_api.GetPatternSnapShotImageOption(WINDOW)
image.ShowFabricTexture = True
image.FabricTextureOpacity = 60.0
utility_api.SetPatternSnapShotImageOption(image, WINDOW)

# Labels: pattern names, line lengths and grain lines
info = utility_api.GetPatternSnapShotInformationOption(WINDOW)
info.ShowPatternName = True
info.ShowLineLength = True
info.ShowGrainLine = True
utility_api.SetPatternSnapShotInformationOption(info, WINDOW)

print("styled: ", export_api.ExportSnapshot2D(os.path.join(out, "styled.png"), WINDOW)[0])
size = utility_api.GetPatternSnapShotSizeOption(WINDOW)
print("paper now %.0f x %.0f mm at %d dpi" % (size.m_width, size.m_height, size.m_resolution))
Pattern Snapshot Options



Button Pair Options

Level: Medium

Options used: ButtonPairPlacementOption

Build a two-piece placket, then place matching buttons and buttonholes along its edges. ButtonPairPlacementOption sets the start corner, the buttonhole size and its rotation; the same option object drives both explicit positions and even distribution.

import json
import pattern_api
import utility_api
import ApiTypes

print("API Test Scenario - Button Pair Options")

utility_api.NewProject()

# Two placket strips, 120 x 600 mm. Lines of a rectangle follow its points:
# 0 = left edge, 1 = top edge, 2 = right edge, 3 = bottom edge
W, H = 120.0, 600.0
left = pattern_api.CreatePatternWithPoints([(0.0, 0.0, 0), (0.0, H, 0), (W, H, 0), (W, 0.0, 0)])
right = pattern_api.CreatePatternWithPoints([(300.0, 0.0, 0), (300.0, H, 0), (300.0 + W, H, 0), (300.0 + W, 0.0, 0)])
pattern_api.SetPatternPieceName(left, "Button placket")
pattern_api.SetPatternPieceName(right, "Buttonhole placket")
# The two pieces must belong to one sewn garment: sew their bottom edges
pattern_api.AddSeamlinePairGroup(left, 3, right, 3, True, True)


def report(label, result):
    r = json.loads(result)
    print("%-22s %s (%s) created=%s skipped=%s" % (label, r["status"], r["reason"], r.get("createdCount"), r.get("skippedCount")))
    for p in r.get("placements", []):
        print("    at %5.0f mm  button #%d  buttonhole #%d" % (p["distanceAlongEdge"], p["button"]["buttonIndex"], p["buttonhole"]["buttonholeIndex"]))


option = ApiTypes.ButtonPairPlacementOption()
option.edgeOrigin = ApiTypes.ButtonPairEdgeOrigin.BUTTON_PAIR_EDGE_ORIGIN_TOP  # measure from the top corner
option.buttonHeadStyleIndex = -1     # -1 = the current button style
option.buttonholeStyleIndex = -1     # -1 = the current buttonhole style
option.buttonholeWidth = 22.0        # mm (0 = the style's size)
option.buttonholeHeight = 3.0        # mm
option.buttonholeAngleDegree = 90.0  # vertical buttonholes, as on a shirt front
option.buttonAngleDegree = 0.0

# Explicit positions: buttons on the right edge of the button placket, buttonholes on the left
# edge of the other piece, 20 mm in from each edge
report("explicit positions",
       pattern_api.PlaceButtonPairsOnEdge(left, 2, right, 0, 20.0, [60.0, 180.0], option))

# Even spacing for the lower part, now measured from the bottom corner: 5 pairs from 40 mm
# (start margin) up to 280 mm, leaving 320 mm (end margin) for the explicit pairs above.
# A pair that would land on an existing one is reported as "skipped", never duplicated.
option.edgeOrigin = ApiTypes.ButtonPairEdgeOrigin.BUTTON_PAIR_EDGE_ORIGIN_BOTTOM
report("evenly distributed",
       pattern_api.DistributeButtonPairsOnEdge(left, 2, right, 0, 20.0, 5, 40.0, 320.0, option))
utility_api.Refresh3DWindow()
Button Pair Options