Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.cadcamfun.xyz/llms.txt

Use this file to discover all available pages before exploring further.

CAD API

The CAD API provides a comprehensive set of functions for creating, modifying, and managing 3D models within the application. This API gives you direct access to the core CAD functionality, allowing you to programmatically work with geometric models and design features.

Overview

The CAD API is centered around several key concepts:
  • Models: The top-level container for a 3D design
  • Features: Discrete operations that define the geometry (e.g., extrusions, holes)
  • Sketches: 2D profiles that can be used to create 3D features
  • Parameters: Dimensional and relational values that control the model
  • Operations: Actions that modify or transform the model

Key Components

The CAD API is organized into several modules:
  • Model Management: Create, load, save, and manage models
  • Feature Operations: Add, modify, and delete model features
  • Sketch Tools: Create and edit 2D sketches
  • Geometric Operations: Perform operations like boolean operations, fillets, etc.
  • Parameter Management: Access and modify model parameters
  • Transformation Operations: Apply transformations to models and features
  • Query Tools: Analyze and extract information from models

Basic Usage

Creating a New Model

import { cadApi } from '@/lib/api/cad-api';

async function createNewModel(name: string, projectId: string) {
  try {
    const model = await cadApi.createModel({
      name,
      type: '3d',
      projectId,
      units: 'mm',
      description: 'Created via CAD API'
    });
    
    return model;
  } catch (error) {
    console.error('Error creating model:', error);
    throw error;
  }
}

Adding Primitive Shapes

import { cadApi } from '@/lib/api/cad-api';

async function addPrimitives(modelId: string) {
  try {
    // Add a box
    const box = await cadApi.addPrimitive(modelId, {
      type: 'box',
      width: 100,
      height: 50,
      depth: 30,
      position: [0, 0, 0],
      orientation: [0, 0, 0, 1] // Quaternion (identity)
    });
    
    // Add a cylinder
    const cylinder = await cadApi.addPrimitive(modelId, {
      type: 'cylinder',
      radius: 25,
      height: 80,
      position: [150, 0, 0],
      orientation: [0, 0, 0, 1]
    });
    
    // Add a sphere
    const sphere = await cadApi.addPrimitive(modelId, {
      type: 'sphere',
      radius: 40,
      position: [0, 100, 0],
      orientation: [0, 0, 0, 1]
    });
    
    return { box, cylinder, sphere };
  } catch (error) {
    console.error('Error adding primitives:', error);
    throw error;
  }
}

Creating a Sketch

import { cadApi } from '@/lib/api/cad-api';

async function createSketch(modelId: string) {
  try {
    // Create a new sketch on the XY plane
    const sketch = await cadApi.createSketch(modelId, {
      plane: 'XY',
      origin: [0, 0, 0]
    });
    
    // Add a rectangle to the sketch
    await cadApi.addSketchEntity(sketch.id, {
      type: 'rectangle',
      x: -50,
      y: -25,
      width: 100,
      height: 50
    });
    
    // Add a circle to the sketch
    await cadApi.addSketchEntity(sketch.id, {
      type: 'circle',
      x: 0,
      y: 0,
      radius: 30
    });
    
    return sketch;
  } catch (error) {
    console.error('Error creating sketch:', error);
    throw error;
  }
}

Creating an Extrusion

import { cadApi } from '@/lib/api/cad-api';

async function createExtrusion(modelId: string, sketchId: string) {
  try {
    const extrusion = await cadApi.addFeature(modelId, {
      type: 'extrusion',
      sketchId,
      distance: 50,
      direction: 'normal', // or 'reverse' or 'both'
      operation: 'new', // or 'add', 'subtract', 'intersect'
    });
    
    return extrusion;
  } catch (error) {
    console.error('Error creating extrusion:', error);
    throw error;
  }
}

Adding a Fillet

import { cadApi } from '@/lib/api/cad-api';

async function addFillet(modelId: string, edgeIds: string[]) {
  try {
    const fillet = await cadApi.addFeature(modelId, {
      type: 'fillet',
      edges: edgeIds,
      radius: 5,
    });
    
    return fillet;
  } catch (error) {
    console.error('Error adding fillet:', error);
    throw error;
  }
}

Advanced Features

Working with Parameters

import { cadApi } from '@/lib/api/cad-api';

async function workWithParameters(modelId: string) {
  try {
    // Get all parameters
    const parameters = await cadApi.getParameters(modelId);
    
    // Create a new parameter
    const newParam = await cadApi.createParameter(modelId, {
      name: 'box_width',
      value: 100,
      type: 'number',
      unit: 'mm',
      description: 'Width of the main box'
    });
    
    // Update an existing parameter
    await cadApi.updateParameter(modelId, newParam.id, {
      value: 150,
    });
    
    // Create a parameter with an expression
    const expressionParam = await cadApi.createParameter(modelId, {
      name: 'box_height',
      expression: 'box_width / 2',
      type: 'number',
      unit: 'mm',
      description: 'Height of the main box, calculated as half the width'
    });
    
    return { parameters, newParam, expressionParam };
  } catch (error) {
    console.error('Error working with parameters:', error);
    throw error;
  }
}

Boolean Operations

import { cadApi } from '@/lib/api/cad-api';

async function performBooleanOperation(modelId: string, targetBodyId: string, toolBodyId: string) {
  try {
    const result = await cadApi.booleanOperation(modelId, {
      type: 'subtract', // 'unite', 'subtract', 'intersect'
      targetBody: targetBodyId,
      toolBody: toolBodyId,
      keepTool: false // Whether to keep the tool body after the operation
    });
    
    return result;
  } catch (error) {
    console.error('Error performing boolean operation:', error);
    throw error;
  }
}

Pattern Features

import { cadApi } from '@/lib/api/cad-api';

async function createLinearPattern(modelId: string, featureId: string) {
  try {
    const pattern = await cadApi.addFeature(modelId, {
      type: 'linearPattern',
      featureId,
      direction: [1, 0, 0],
      distance: 50,
      count: 5
    });
    
    return pattern;
  } catch (error) {
    console.error('Error creating linear pattern:', error);
    throw error;
  }
}

async function createCircularPattern(modelId: string, featureId: string) {
  try {
    const pattern = await cadApi.addFeature(modelId, {
      type: 'circularPattern',
      featureId,
      axis: [0, 0, 1], // Z-axis
      angleTotal: 360, // Full circle
      count: 8, // 8 copies
      center: [0, 0, 0]
    });
    
    return pattern;
  } catch (error) {
    console.error('Error creating circular pattern:', error);
    throw error;
  }
}

Measuring and Analysis

import { cadApi } from '@/lib/api/cad-api';

async function analyzeModel(modelId: string) {
  try {
    // Get model volume
    const volume = await cadApi.calculateVolume(modelId);
    
    // Get model surface area
    const surfaceArea = await cadApi.calculateSurfaceArea(modelId);
    
    // Measure distance between two points
    const distance = await cadApi.measureDistance(modelId, {
      from: { type: 'point', coordinates: [0, 0, 0] },
      to: { type: 'point', coordinates: [100, 100, 100] }
    });
    
    // Get center of mass
    const centerOfMass = await cadApi.calculateCenterOfMass(modelId);
    
    return {
      volume,
      surfaceArea,
      distance,
      centerOfMass
    };
  } catch (error) {
    console.error('Error analyzing model:', error);
    throw error;
  }
}

Feature History and Timeline

import { cadApi } from '@/lib/api/cad-api';

async function workWithFeatureHistory(modelId: string) {
  try {
    // Get feature history
    const history = await cadApi.getFeatureHistory(modelId);
    
    // Rollback to a specific feature
    await cadApi.rollbackToFeature(modelId, history[2].id);
    
    // Resume from rollback
    await cadApi.resumeFromFeature(modelId);
    
    // Suppress a feature (temporarily disable it)
    await cadApi.suppressFeature(modelId, history[3].id);
    
    // Unsuppress a feature
    await cadApi.unsuppressFeature(modelId, history[3].id);
    
    return history;
  } catch (error) {
    console.error('Error working with feature history:', error);
    throw error;
  }
}

Sketch Constraints

import { cadApi } from '@/lib/api/cad-api';

async function addSketchConstraints(modelId: string, sketchId: string) {
  try {
    // Add a dimensional constraint
    const dimensionConstraint = await cadApi.addSketchConstraint(sketchId, {
      type: 'dimension',
      entityId: 'entity_id_1', // ID of sketch entity to constrain
      value: 100,
      parameterName: 'width' // Optional, to create a named parameter
    });
    
    // Add a geometric constraint
    const horizontalConstraint = await cadApi.addSketchConstraint(sketchId, {
      type: 'horizontal',
      entityId: 'entity_id_2'
    });
    
    // Add a relational constraint
    const parallelConstraint = await cadApi.addSketchConstraint(sketchId, {
      type: 'parallel',
      entityId1: 'entity_id_1',
      entityId2: 'entity_id_3'
    });
    
    return { dimensionConstraint, horizontalConstraint, parallelConstraint };
  } catch (error) {
    console.error('Error adding sketch constraints:', error);
    throw error;
  }
}

Model Import and Export

Importing Models

import { cadApi } from '@/lib/api/cad-api';

async function importModel(projectId: string, fileData: File) {
  try {
    const formData = new FormData();
    formData.append('file', fileData);
    
    const importedModel = await cadApi.importModel({
      projectId,
      data: formData,
      options: {
        format: 'auto', // Auto-detect format
        units: 'mm',
        name: fileData.name.split('.')[0], // Use filename as model name
        createNewModel: true
      }
    });
    
    return importedModel;
  } catch (error) {
    console.error('Error importing model:', error);
    throw error;
  }
}

Exporting Models

import { cadApi } from '@/lib/api/cad-api';

async function exportModel(modelId: string, format: string) {
  try {
    const exportedFile = await cadApi.exportModel(modelId, {
      format, // 'stl', 'obj', 'step', 'iges', 'fbx', etc.
      quality: 'high',
      includeMetadata: true,
      binary: true // For formats that support binary export
    });
    
    return exportedFile;
  } catch (error) {
    console.error('Error exporting model:', error);
    throw error;
  }
}

Working with Assemblies

Creating an Assembly

import { cadApi } from '@/lib/api/cad-api';

async function createAssembly(projectId: string, name: string) {
  try {
    const assembly = await cadApi.createAssembly({
      name,
      projectId,
      description: 'Created via CAD API'
    });
    
    return assembly;
  } catch (error) {
    console.error('Error creating assembly:', error);
    throw error;
  }
}

Adding Components to an Assembly

import { cadApi } from '@/lib/api/cad-api';

async function addComponentToAssembly(assemblyId: string, modelId: string) {
  try {
    const component = await cadApi.addComponent(assemblyId, {
      modelId,
      position: [0, 0, 0],
      orientation: [0, 0, 0, 1], // Quaternion (identity)
      name: 'Component 1'
    });
    
    return component;
  } catch (error) {
    console.error('Error adding component to assembly:', error);
    throw error;
  }
}

Creating Assembly Constraints

import { cadApi } from '@/lib/api/cad-api';

async function addAssemblyConstraint(assemblyId: string, component1Id: string, component2Id: string) {
  try {
    // Add a mate constraint (align faces)
    const mateConstraint = await cadApi.addAssemblyConstraint(assemblyId, {
      type: 'mate',
      component1: component1Id,
      component2: component2Id,
      face1: 'face_id_1',
      face2: 'face_id_2',
      offset: 0
    });
    
    // Add an axial alignment constraint
    const axialConstraint = await cadApi.addAssemblyConstraint(assemblyId, {
      type: 'axial',
      component1: component1Id,
      component2: component2Id,
      axis1: 'axis_id_1',
      axis2: 'axis_id_2'
    });
    
    return { mateConstraint, axialConstraint };
  } catch (error) {
    console.error('Error adding assembly constraint:', error);
    throw error;
  }
}

Error Handling

The CAD API uses a consistent error handling mechanism with specific error codes:
try {
  const model = await cadApi.createModel({
    name: 'Test Model',
    type: '3d',
    projectId: 'project_id'
  });
} catch (error) {
  if (error.code === 'INVALID_PARAMETERS') {
    console.error('Invalid parameters:', error.details);
    // Handle validation errors
  } else if (error.code === 'MODEL_CREATION_FAILED') {
    console.error('Failed to create model:', error.message);
    // Handle model creation failure
  } else if (error.code === 'GEOMETRY_ERROR') {
    console.error('Geometry error:', error.message);
    // Handle geometry-related errors
  } else {
    console.error('Unknown error:', error);
    // Handle other errors
  }
}

Common Error Codes

Error CodeDescription
INVALID_PARAMETERSInvalid input parameters or constraints
MODEL_NOT_FOUNDModel with the specified ID not found
FEATURE_NOT_FOUNDFeature with the specified ID not found
SKETCH_NOT_FOUNDSketch with the specified ID not found
GEOMETRY_ERRORError in geometric calculation or operation
BOOLEAN_OPERATION_FAILEDFailed to perform boolean operation
SKETCH_CONSTRAINT_ERRORError adding or evaluating sketch constraint
IMPORT_ERRORError importing model from file
EXPORT_ERRORError exporting model to file
MODEL_CREATION_FAILEDFailed to create a new model
FEATURE_CREATION_FAILEDFailed to create or add a feature
PERMISSION_DENIEDNot authorized to perform the operation

Events

The CAD system triggers several events that you can subscribe to:
import { events } from '@/lib/utils/events';

// Listen for model events
events.subscribe('model.created', (data) => {
  console.log('Model created:', data.modelId);
});

events.subscribe('model.changed', (data) => {
  console.log('Model changed:', data.modelId, 'Feature:', data.featureId);
});

// Listen for feature events
events.subscribe('feature.added', (data) => {
  console.log('Feature added:', data.featureId, 'to model:', data.modelId);
});

events.subscribe('feature.modified', (data) => {
  console.log('Feature modified:', data.featureId);
});

// Listen for sketch events
events.subscribe('sketch.created', (data) => {
  console.log('Sketch created:', data.sketchId);
});

events.subscribe('sketch.modified', (data) => {
  console.log('Sketch modified:', data.sketchId);
});

Performance Considerations

When working with complex models, consider these performance optimization tips:
  1. Batch Operations: Use batch methods for adding multiple features or entities
  2. Feature Suppression: Suppress complex features temporarily during editing
  3. Level of Detail: Use appropriate level of detail for visualization
  4. Efficient Queries: Be specific in topology queries to minimize processing
  5. Model Simplification: Use simplified versions for assembly operations
Example of batch operations:
import { cadApi } from '@/lib/api/cad-api';

async function addMultipleFeaturesInBatch(modelId: string) {
  try {
    const features = await cadApi.addFeaturesBatch(modelId, [
      {
        type: 'box',
        width: 100,
        height: 50,
        depth: 30,
        position: [0, 0, 0]
      },
      {
        type: 'cylinder',
        radius: 25,
        height: 80,
        position: [150, 0, 0]
      },
      {
        type: 'fillet',
        edges: ['edge_id_1', 'edge_id_2'],
        radius: 5
      }
    ]);
    
    return features;
  } catch (error) {
    console.error('Error adding features in batch:', error);
    throw error;
  }
}

Best Practices

Model Organization

  • Use Features Logically: Build models in a logical sequence
  • Parametrize Important Dimensions: Use named parameters for values that might change
  • Use Reference Geometry: Create reference planes, axes, and points for complex models
  • Name Important Features: Give meaningful names to key features
  • Group Related Features: Use feature folders to organize complex models

Efficient Modeling

  • Start Simple: Begin with basic shapes and add detail incrementally
  • Use Symmetry: Mirror features when appropriate to reduce modeling effort
  • Reuse Components: Create and reuse common components
  • Suppress Unnecessary Features: Hide or suppress features not currently needed
  • Use Patterns: Leverage patterns for repetitive features

Robust Sketches

  • Properly Constrain Sketches: Fully constrain sketches to prevent unexpected changes
  • Use Construction Geometry: Create reference lines and points as needed
  • Keep Sketches Simple: Break complex geometry into multiple sketches
  • Use Sketch Blocks: Group and reuse common sketch elements

Examples

Creating a Simple Part

import { cadApi } from '@/lib/api/cad-api';

async function createSimplePart(projectId: string) {
  try {
    // Create a new model
    const model = await cadApi.createModel({
      name: 'Simple Part',
      type: '3d',
      projectId,
      units: 'mm'
    });
    
    // Create a sketch on the XY plane
    const sketch = await cadApi.createSketch(model.id, {
      plane: 'XY',
      origin: [0, 0, 0]
    });
    
    // Add a rectangle to the sketch
    await cadApi.addSketchEntity(sketch.id, {
      type: 'rectangle',
      x: -50,
      y: -25,
      width: 100,
      height: 50
    });
    
    // Extrude the sketch
    const baseExtrusion = await cadApi.addFeature(model.id, {
      type: 'extrusion',
      sketchId: sketch.id,
      distance: 20,
      direction: 'normal'
    });
    
    // Create a second sketch on the top face
    const topFace = await cadApi.getTopology(model.id, {
      type: 'face',
      position: [0, 0, 20], // Approximate position
      tolerance: 0.1
    });
    
    const topSketch = await cadApi.createSketch(model.id, {
      plane: 'custom',
      planeType: 'face',
      faceId: topFace[0].id
    });
    
    // Add a circle to the top sketch
    await cadApi.addSketchEntity(topSketch.id, {
      type: 'circle',
      x: 0,
      y: 0,
      radius: 15
    });
    
    // Create a hole using the sketch
    const hole = await cadApi.addFeature(model.id, {
      type: 'extrusion',
      sketchId: topSketch.id,
      distance: 20,
      direction: 'normal',
      operation: 'subtract' // Cut operation
    });
    
    // Add fillets to the base edges
    const edges = await cadApi.getTopology(model.id, {
      type: 'edge',
      position: [0, 0, 0], // Base area
      tolerance: 5
    });
    
    const fillet = await cadApi.addFeature(model.id, {
      type: 'fillet',
      edges: edges.slice(0, 4).map(e => e.id), // First 4 edges
      radius: 5
    });
    
    return {
      model,
      features: {
        baseExtrusion,
        hole,
        fillet
      }
    };
  } catch (error) {
    console.error('Error creating simple part:', error);
    throw error;
  }
}

Creating a Simple Assembly

import { cadApi } from '@/lib/api/cad-api';

async function createSimpleAssembly(projectId: string) {
  try {
    // Create base plate model
    const basePlate = await cadApi.createModel({
      name: 'Base Plate',
      type: '3d',
      projectId,
      units: 'mm'
    });
    
    // Add a box for the base plate
    await cadApi.addPrimitive(basePlate.id, {
      type: 'box',
      width: 200,
      height: 10,
      depth: 100,
      position: [0, 0, 0]
    });
    
    // Create bracket model
    const bracket = await cadApi.createModel({
      name: 'Bracket',
      type: '3d',
      projectId,
      units: 'mm'
    });
    
    // Add features to bracket...
    
    // Create an assembly
    const assembly = await cadApi.createAssembly({
      name: 'Simple Assembly',
      projectId,
      description: 'A simple assembly with a base plate and brackets'
    });
    
    // Add base plate to assembly
    const basePlateComponent = await cadApi.addComponent(assembly.id, {
      modelId: basePlate.id,
      position: [0, 0, 0],
      orientation: [0, 0, 0, 1]
    });
    
    // Add first bracket
    const bracket1 = await cadApi.addComponent(assembly.id, {
      modelId: bracket.id,
      position: [50, 10, 25],
      orientation: [0, 0, 0, 1]
    });
    
    // Add second bracket
    const bracket2 = await cadApi.addComponent(assembly.id, {
      modelId: bracket.id,
      position: [-50, 10, 25],
      orientation: [0, 0, 0, 1]
    });
    
    // Add constraints between components
    
    return {
      assembly,
      components: {
        basePlate: basePlateComponent,
        bracket1,
        bracket2
      }
    };
  } catch (error) {
    console.error('Error creating simple assembly:', error);
    throw error;
  }
}

API Reference

cadApi

MethodDescription
createModel()Create a new CAD model
getModel()Get a model by ID
updateModel()Update model properties
deleteModel()Delete a model
addPrimitive()Add a primitive shape to a model
addFeature()Add a feature to a model
updateFeature()Update an existing feature
deleteFeature()Delete a feature
createSketch()Create a new sketch
addSketchEntity()Add an entity to a sketch
addSketchConstraint()Add a constraint to a sketch
getParameters()Get all parameters for a model
createParameter()Create a new parameter
updateParameter()Update an existing parameter
booleanOperation()Perform a boolean operation
getTopology()Query model topology
importModel()Import a model from a file
exportModel()Export a model to a file
createAssembly()Create a new assembly
addComponent()Add a component to an assembly
addAssemblyConstraint()Add a constraint to an assembly
For complete API reference including all parameters and return types, see the CAD API Reference.