Skip to content

Light OCCT + Three.js Integration Examples

This section demonstrates the powerful combination of Light OCCT for CAD operations and Three.js for 3D rendering. The workflow is: Create CAD geometry with Light OCCT → Generate mesh → Extract triangles → Render with Three.js.

Complete Workflow Implementation

The following code examples demonstrate the complete workflow:

  1. 🏗️ CAD Creation: Light OCCT WebAssembly creates precise CAD primitives (boxes, spheres, cylinders, etc.)
  2. ⚙️ Mesh Generation: Light OCCT's incremental mesher tessellates shapes into triangles
  3. 🔍 Triangle Extraction: Mesh data is extracted as vertices, indices, and normals
  4. 🎨 Three.js Rendering: Extracted triangles are rendered as Three.js BufferGeometry

Core Workflow Implementation

1. CAD Primitive Creation (Light OCCT)

javascript
// Load Light OCCT WebAssembly
const LightOcct = await loadWasmModule()

// Create CAD primitives using Light OCCT
const origin = LightOcct.CreatePoint(0, 0, 0)
const box = LightOcct.LPrim.CreateBox(origin, 5, 3, 2)
const sphere = LightOcct.LPrim.CreateSphere(origin, 2.5)

// Validate shapes
console.log('Box valid:', box.IsValid())
console.log('Sphere valid:', sphere.IsValid())

2. Mesh Generation (Light OCCT)

javascript
// Create incremental mesher
const mesher = LightOcct.LMesher.CreateIncMesh()

// Configure mesh parameters
const params = {
  LinearDeflection: 0.1,      // Controls triangle size
  AngularDeflection: 0.2,     // Controls curve smoothness  
  InParallel: true,           // Use parallel processing
  ControlSurfaceDeflection: true
}

// Generate mesh
const meshResult = mesher.GenerateMesh(box, params)
console.log('Triangles:', meshResult.Statistics.TotalTriangles)
console.log('Vertices:', meshResult.Statistics.TotalNodes)

3. Triangle Extraction (Light OCCT → Three.js Bridge)

javascript
// Extract triangulation data from Light OCCT shape
function extractTriangles(shape) {
  const triangulation = shape.GetTriangulation()
  
  // Extract vertices as Float32Array for Three.js
  const vertices = new Float32Array(triangulation.GetNbNodes() * 3)
  for (let i = 0; i < triangulation.GetNbNodes(); i++) {
    const node = triangulation.GetNode(i + 1) // 1-based indexing
    vertices[i * 3] = node.x
    vertices[i * 3 + 1] = node.y  
    vertices[i * 3 + 2] = node.z
  }
  
  // Extract triangle indices as Uint32Array
  const indices = new Uint32Array(triangulation.GetNbTriangles() * 3)
  for (let i = 0; i < triangulation.GetNbTriangles(); i++) {
    const triangle = triangulation.GetTriangle(i + 1)
    indices[i * 3] = triangle.n1 - 1     // Convert to 0-based
    indices[i * 3 + 1] = triangle.n2 - 1
    indices[i * 3 + 2] = triangle.n3 - 1
  }
  
  return { vertices, indices }
}

4. Three.js Rendering

javascript
// Create Three.js scene
const scene = new THREE.Scene()
const camera = new THREE.PerspectiveCamera(75, width/height, 0.1, 1000)
const renderer = new THREE.WebGLRenderer()

// Convert Light OCCT mesh data to Three.js BufferGeometry
function createThreeJSMesh(meshData) {
  const geometry = new THREE.BufferGeometry()
  
  // Set vertex positions from Light OCCT
  geometry.setAttribute('position', 
    new THREE.Float32BufferAttribute(meshData.vertices, 3))
  
  // Set triangle indices from Light OCCT  
  geometry.setIndex(
    new THREE.Uint32BufferAttribute(meshData.indices, 1))
  
  // Compute normals for lighting
  geometry.computeVertexNormals()
  
  // Create material and mesh
  const material = new THREE.MeshPhongMaterial({ 
    color: 0x888888,
    side: THREE.DoubleSide 
  })
  
  return new THREE.Mesh(geometry, material)
}

// Add Light OCCT mesh to Three.js scene
const triangleData = extractTriangles(box)
const threeMesh = createThreeJSMesh(triangleData)
scene.add(threeMesh)

Advanced Features

Real-time Mesh Parameter Adjustment

javascript
// Update mesh quality in real-time
function updateMeshQuality(shape, linearDeflection) {
  // Re-mesh with new parameters
  const newParams = { ...params, LinearDeflection: linearDeflection }
  const newMeshResult = mesher.GenerateMesh(shape, newParams)
  
  // Extract new triangle data
  const newTriangleData = extractTriangles(shape)
  
  // Update Three.js geometry
  const geometry = threeMesh.geometry
  geometry.setAttribute('position', 
    new THREE.Float32BufferAttribute(newTriangleData.vertices, 3))
  geometry.setIndex(
    new THREE.Uint32BufferAttribute(newTriangleData.indices, 1))
  geometry.computeVertexNormals()
  
  // Force Three.js to update
  geometry.attributes.position.needsUpdate = true
  geometry.computeBoundingSphere()
}

Export Capabilities

javascript
// Export Three.js scene to JSON
function exportThreeJSScene() {
  const sceneData = scene.toJSON()
  const blob = new Blob([JSON.stringify(sceneData)], { type: 'application/json' })
  const url = URL.createObjectURL(blob)
  
  const a = document.createElement('a')
  a.href = url
  a.download = 'light_occt_scene.json'
  a.click()
}

// Export mesh as OBJ format
function exportOBJ() {
  let objData = ''
  
  scene.traverse((object) => {
    if (object instanceof THREE.Mesh) {
      const geometry = object.geometry
      const vertices = geometry.attributes.position.array
      
      // Write vertices
      for (let i = 0; i < vertices.length; i += 3) {
        objData += `v ${vertices[i]} ${vertices[i+1]} ${vertices[i+2]}\n`
      }
      
      // Write faces
      const indices = geometry.index.array
      for (let i = 0; i < indices.length; i += 3) {
        objData += `f ${indices[i]+1} ${indices[i+1]+1} ${indices[i+2]+1}\n`
      }
    }
  })
  
  const blob = new Blob([objData], { type: 'text/plain' })
  const url = URL.createObjectURL(blob)
  
  const a = document.createElement('a')
  a.href = url
  a.download = 'light_occt_mesh.obj'
  a.click()
}

Key Benefits

Best of Both Worlds

  • Light OCCT: Precise CAD operations, robust meshing, industry-standard geometry kernel
  • Three.js: Modern WebGL rendering, rich ecosystem, excellent performance

Complete Workflow Control

  • Full control over mesh quality and parameters
  • Real-time mesh updates and parameter adjustment
  • Triangle-level access to geometry data

Web-First Architecture

  • Runs entirely in the browser via WebAssembly
  • No server-side dependencies for CAD operations
  • Direct integration with modern web applications

Export Flexibility

  • Three.js JSON for web applications
  • OBJ/STL for 3D printing and CAD tools
  • Direct access to triangle data for custom formats

Architecture Overview

┌─────────────────┐    ┌──────────────────┐    ┌────────────────┐
│   Light OCCT    │    │   Triangle       │    │   Three.js     │
│   WebAssembly   │    │   Extraction     │    │   Rendering    │
│                 │    │                  │    │                │
│ • CAD Primitives│───▶│ • Vertices       │───▶│ • BufferGeometry│
│ • Mesh Generation│   │ • Indices        │    │ • Materials     │
│ • Quality Control│   │ • Normals        │    │ • Lighting      │
│ • Validation    │    │ • UV Coordinates │    │ • Interaction   │
└─────────────────┘    └──────────────────┘    └────────────────┘

This architecture provides the precision of industrial CAD software with the performance and flexibility of modern web graphics.

Released under the LGPL-2.1 License