# Professional Mesh Comparison Algorithms - Research Report

**Date:** 2026-02-14
**Purpose:** Replace vertex-to-vertex spatial hash comparison with tessellation-invariant algorithms

## Executive Summary

Professional CAD comparison tools (CATIA V5, SolidWorks, Metro/MeshLab) use **point-to-triangle distance** and **Hausdorff distance** algorithms that are invariant to tessellation differences. These algorithms compare the underlying surfaces rather than individual vertices, solving the problem where identical surfaces with different triangulation report false differences.

---

## 1. Point-to-Triangle Distance Algorithm

### 1.1 Core Concept

Instead of comparing vertices to vertices, compute the distance from each point to the **nearest triangle surface** (not just the nearest vertex). This solves tessellation variance because the triangle surface represents the actual geometry.

### 1.2 Algorithm Details

**Source:** [Distance Between Point and Triangle in 3D - Geometric Tools](https://www.geometrictools.com/Documentation/DistancePoint3Triangle3.pdf)

**Key Insight:** The distance from point P to triangle T is computed by:

1. **Project the point onto the triangle's plane**
2. **Check if the projection falls inside the triangle**
   - If inside: Distance = distance to plane
   - If outside: Distance = distance to nearest edge/vertex

**Mathematical Formulation:**

```
Triangle T(s, t) = B + s*E0 + t*E1
where:
  B = base vertex
  E0, E1 = edge vectors
  s, t = barycentric coordinates (0 ≤ s, t ≤ 1, s+t ≤ 1)

Minimize: Q(s,t) = ||P - T(s,t)||²
```

**Regions to Handle:**
- **Region 0:** Projection inside triangle (orthogonal distance to plane)
- **Regions 1-3:** Projection outside, nearest to an edge
- **Regions 4-6:** Projection outside, nearest to a vertex

### 1.3 Optimized Implementation

**Key Performance Features:**
- **At most ONE division** operation (deferred until needed)
- **No square roots** in the inner loop (work with squared distances)
- **Minimal branching** (use lookup table for region classification)

**Sources:**
- [3D Distance from a Point to a Triangle - ResearchGate](https://www.researchgate.net/publication/243787422_3D_Distance_from_a_Point_to_a_Triangle)
- [Closest Point to Triangle - 3DCollisions](https://gdbooks.gitbooks.io/3dcollisions/content/Chapter4/closest_point_to_triangle.html)
- [Distance to Triangle - Inigo Quilez](https://iquilezles.org/articles/triangledistance/)

### 1.4 Barycentric Coordinate Approach

**Alternative Method:** Use barycentric coordinates to determine if point is inside/outside

```
α = Area(PBC) / Area(ABC)
β = Area(PAC) / Area(ABC)
γ = Area(PAB) / Area(ABC)

If α < 0 or β < 0 or γ < 0: Point is outside triangle
```

**Efficiency:** Single matrix inversion, no square roots, GPU-friendly

**Sources:**
- [Ray-Tracing: Rendering a Triangle - Scratchapixel](https://www.scratchapixel.com/lessons/3d-basic-rendering/ray-tracing-rendering-a-triangle/barycentric-coordinates.html)
- [Computing Barycentric Coordinates of Projected Point](https://vccimaging.org/Publications/Heidrich2005CBP/Heidrich2005CBP.pdf)

### 1.5 Computational Complexity

- **Single point-to-triangle:** O(1) - constant time
- **Point-to-mesh (naive):** O(n) where n = triangle count
- **With spatial acceleration:** O(log n) average case

---

## 2. Hausdorff Distance

### 2.1 Definition

**Hausdorff distance** measures the "maximum of minimum distances" between two sets:

```
H(A, B) = max(h(A, B), h(B, A))

where:
  h(A, B) = max(min(d(a, b))) for all a ∈ A, b ∈ B
           (one-sided Hausdorff)
```

**Intuitive Meaning:** "How far is the farthest point on mesh A from the nearest point on mesh B?"

### 2.2 Why It Solves Tessellation Variance

Hausdorff distance measures **surface-to-surface** proximity, not vertex-to-vertex. If two meshes represent the same surface:
- Even with different vertex counts
- Even with different triangulation patterns
- The Hausdorff distance will be near zero

### 2.3 Exact vs Approximate Computation

**Exact Hausdorff (Slow but Accurate):**
- Computes exact maximum distance between all triangle pairs
- Uses branch-and-bound to prune search space
- Guarantees correctness

**Approximate Hausdorff (Fast):**
- Sample points uniformly on mesh A
- For each sample, find nearest point on mesh B
- Take maximum distance as approximation

**Source:** [Fast and Accurate Hausdorff Distance Calculation - ResearchGate](https://www.researchgate.net/publication/221546565_Fast_and_Accurate_Hausdorff_Distance_Calculation_between_Meshes)

### 2.4 Metro Algorithm (MeshLab)

**Metro** is the seminal tool for mesh comparison using Hausdorff distance.

**Algorithm:**
1. **Sample mesh A** uniformly or randomly
2. **For each sample point:**
   - Find nearest triangle on mesh B
   - Compute point-to-triangle distance
3. **Compute statistics:**
   - Maximum distance (worst-case error)
   - Mean distance (average error)
   - RMS distance (root-mean-square error)

**Sampling Strategies:**
- **Uniform sampling:** Subdivision-based, ensures coverage
- **Monte Carlo sampling:** Random, faster but may miss features
- **Adaptive sampling:** Subdivide triangles in high-error regions

**Implementation in MeshLab:**
- Filter → Sampling → Hausdorff Distance
- Assigns quality value to each vertex (distance to target mesh)
- Visualizes error as color map

**Sources:**
- [Metro Algorithm - MeshLab GitHub](https://github.com/areslp/meshlab/blob/master/vcglib/apps/metro/metro.cpp)
- [Metro Mesh Comparison - SourceForge Discussion](https://sourceforge.net/p/meshlab/discussion/499533/thread/401d6a83/)
- [Robust Hausdorff Distance - SGI 2021](https://summergeometry.org/sgi2021/robust-computation-of-the-hausdorff-distance-between-triangle-meshes/)

### 2.5 Fast Hausdorff Computation

**Branch-and-Bound Method:**

```
For each triangle T_a in mesh A:
  1. Compute upper bound: max distance from T_a vertices to mesh B
  2. Compute lower bound: min possible distance from T_a to mesh B

  If upper_bound > current_best:
    Subdivide T_a recursively
  Else:
    Prune this branch
```

**Adaptive Subsampling:**
- Only subdivide triangles that might contain the maximum distance
- Dramatically reduces computation for high-accuracy results

**Source:** [Fast Hausdorff Distance Calculation - Guthe et al.](https://cg.cs.uni-bonn.de/backend/v1/files/publications/guthe-2005-fast.pdf)

### 2.6 One-Sided vs Two-Sided Hausdorff

**One-Sided h(A, B):**
- Measures how far mesh A is from mesh B
- Asymmetric: h(A, B) ≠ h(B, A)
- Faster to compute

**Two-Sided H(A, B):**
- H(A, B) = max(h(A, B), h(B, A))
- Symmetric, more robust
- Twice the computation

**Use Case:** For CAD comparison, compute both directions to detect additions AND deletions.

---

## 3. Spatial Indexing for Triangle Queries

### 3.1 Why Spatial Indexing?

**Problem:** Finding the nearest triangle to a point is O(n) naive complexity.

**Solution:** Use spatial data structures to achieve O(log n) average case.

### 3.2 Bounding Volume Hierarchy (BVH)

**Concept:** Tree structure where:
- Leaf nodes contain individual triangles
- Internal nodes contain bounding volumes (AABB, OBB, sphere)
- Recursively group nearby triangles

**Traversal:**
```
function findNearest(point, node):
  if node is leaf:
    return distance to triangle

  dist_left = distance to left child's bounding box
  dist_right = distance to right child's bounding box

  if dist_left < dist_right:
    explore left first, prune right if dist_left < dist_right
  else:
    explore right first, prune left if dist_right < dist_left
```

**Advantages:**
- Fast construction (O(n log n))
- Fast queries (O(log n) average)
- Memory efficient
- Better than octree for dynamic scenes

**Sources:**
- [Bounding Volume Hierarchy - Wikipedia](https://en.wikipedia.org/wiki/Bounding_volume_hierarchy)
- [BVH Star - NVIDIA Research](https://meistdan.github.io/publications/bvh_star/paper.pdf)

### 3.3 Octree for Triangle Indexing

**Concept:** Recursively subdivide space into 8 octants

**Properties:**
- **Pros:** Simple to implement, good for uniform distributions
- **Cons:** Poor for non-uniform distributions, wastes memory on empty cells

**Comparison to BVH:**
- BVH is generally preferred for triangle meshes
- Octree is better for point clouds or volumetric data

**Source:** [OLBVH: Octree Linear BVH](https://www.researchgate.net/publication/342718520_OLBVH_octree_linear_bounding_volume_hierarchy_for_volumetric_meshes)

### 3.4 Uniform Voxel Grid

**Concept:** Divide space into fixed-size voxels, hash triangles to voxels

**Advantages:**
- O(1) lookup
- Very fast for uniform distributions
- Easy to parallelize

**Disadvantages:**
- Poor for sparse/non-uniform meshes
- Memory intensive
- Requires tuning voxel size

**Use Case:** When mesh density is relatively uniform and performance is critical.

**Source:** [Fast Point to Mesh Distance - CMU](http://biorobotics.ri.cmu.edu/papers/paperUploads/Point_To_Mesh_Distance_IROS_v6_Geordan.pdf)

---

## 4. Three.js Integration: three-mesh-bvh

### 4.1 Library Overview

**three-mesh-bvh** is a production-ready BVH implementation for Three.js that provides exactly what we need.

**GitHub:** [gkjohnson/three-mesh-bvh](https://github.com/gkjohnson/three-mesh-bvh)
**NPM:** [three-mesh-bvh](https://www.npmjs.com/package/three-mesh-bvh)

### 4.2 Key Features

**Distance Queries:**
```typescript
import { MeshBVH } from 'three-mesh-bvh';

// Build BVH
const geometry = mesh.geometry;
geometry.boundsTree = new MeshBVH(geometry);

// Closest point to a point
const point = new THREE.Vector3(x, y, z);
const target = new THREE.Vector3();
const result = geometry.boundsTree.closestPointToPoint(
  point,      // query point
  target,     // output: closest point on mesh
  0,          // minThreshold (early exit)
  Infinity    // maxThreshold (ignore distant triangles)
);

// result.distance = distance to mesh
// target = closest point coordinates
```

**Mesh-to-Mesh Distance:**
```typescript
const target1 = new THREE.Vector3();
const target2 = new THREE.Vector3();

const result = bvhA.closestPointToGeometry(
  meshB,
  meshBMatrix,
  target1,  // closest point on mesh A
  target2,  // closest point on mesh B
  minThreshold,
  maxThreshold
);
```

### 4.3 Advanced Features

**Shader-Based Distance Queries:**
- GPU SDF generation
- Distance field computation in shaders
- Real-time distance queries

**Triangle Queries:**
```typescript
// Get detailed triangle information
const hitInfo = getTriangleHitPointInfo(
  geometry,
  result.faceIndex,
  target
);

// Returns:
// - UV coordinates
// - Triangle normal
// - Barycentric coordinates
// - Material index
```

**Source:** [three-mesh-bvh Distance Example](https://gkjohnson.github.io/three-mesh-bvh/example/bundle/distancecast.html)

### 4.4 Performance Characteristics

**Construction:**
- O(n log n) time
- Can be done in a worker thread

**Query:**
- O(log n) average case
- Near O(1) for spatially coherent queries
- Supports early exit with thresholds

**Memory:**
- ~2x geometry size (BVH structure)
- Can share BVH between multiple meshes

---

## 5. Implementation Strategy for FikoYT

### 5.1 Recommended Approach

**Hybrid Algorithm:**

```
1. Build BVH for both meshes (use three-mesh-bvh)

2. Sample points from mesh A:
   - Uniform sampling on triangle surfaces
   - Density proportional to triangle area
   - Use ~10,000-100,000 samples for accuracy

3. For each sample point:
   - Query BVH of mesh B for nearest triangle
   - Compute exact point-to-triangle distance
   - Track maximum, mean, RMS distances

4. Repeat in reverse (mesh B to mesh A) for two-sided Hausdorff

5. Report results:
   - Maximum distance (H_max)
   - Mean distance (H_mean)
   - RMS distance (H_rms)
   - Distance histogram
   - Color-coded visualization
```

### 5.2 Integration with Existing Code

**Leverage Existing Infrastructure:**
- Your `FikoRaycastBVH.ts` already uses `three-mesh-bvh`
- Your `FikoWasmBridge.ts` can accelerate point-to-triangle computation
- Your `FikoGPUSelection.ts` can perform shader-based distance queries

**Proposed New File:**
```
src/service/fikoyt-ui/src/lib/fiko-three-js/IFikoThreeJS/
  FikoMeshComparison.ts
```

### 5.3 Pseudocode

```typescript
class FikoMeshComparison {

  // Main comparison function
  compareMeshes(
    meshA: THREE.Mesh,
    meshB: THREE.Mesh,
    sampleCount: number = 10000
  ): ComparisonResult {

    // 1. Build BVH if not exists
    const bvhA = this.ensureBVH(meshA.geometry);
    const bvhB = this.ensureBVH(meshB.geometry);

    // 2. Sample points from mesh A
    const samplesA = this.sampleMeshSurface(meshA, sampleCount);

    // 3. Compute one-sided Hausdorff A → B
    const distancesAtoB = this.computeDistances(
      samplesA,
      bvhB,
      meshB.matrixWorld
    );

    // 4. Sample points from mesh B
    const samplesB = this.sampleMeshSurface(meshB, sampleCount);

    // 5. Compute one-sided Hausdorff B → A
    const distancesBtoA = this.computeDistances(
      samplesB,
      bvhA,
      meshA.matrixWorld
    );

    // 6. Compute statistics
    return {
      hausdorffMax: Math.max(
        Math.max(...distancesAtoB),
        Math.max(...distancesBtoA)
      ),
      hausdorffMean: (
        this.mean(distancesAtoB) + this.mean(distancesBtoA)
      ) / 2,
      hausdorffRMS: Math.sqrt(
        (this.rms(distancesAtoB)² + this.rms(distancesBtoA)²) / 2
      ),
      colorMap: this.generateColorMap(distancesAtoB)
    };
  }

  // Sample points uniformly on mesh surface
  sampleMeshSurface(
    mesh: THREE.Mesh,
    count: number
  ): THREE.Vector3[] {
    const sampler = new MeshSurfaceSampler(mesh)
      .setWeightAttribute('area')
      .build();

    const samples: THREE.Vector3[] = [];
    const temp = new THREE.Vector3();

    for (let i = 0; i < count; i++) {
      sampler.sample(temp);
      samples.push(temp.clone());
    }

    return samples;
  }

  // Compute distances from samples to mesh
  computeDistances(
    samples: THREE.Vector3[],
    bvh: MeshBVH,
    transform: THREE.Matrix4
  ): number[] {
    const target = new THREE.Vector3();
    const distances: number[] = [];

    for (const point of samples) {
      const result = bvh.closestPointToPoint(
        point,
        target,
        0,
        Infinity
      );

      distances.push(result.distance);
    }

    return distances;
  }

  // Optional: Use WASM for acceleration
  computeDistancesWASM(
    samples: Float32Array,  // [x,y,z, x,y,z, ...]
    triangles: Float32Array // [v0x,v0y,v0z, v1x,v1y,v1z, v2x,v2y,v2z, ...]
  ): Float32Array {
    // Call WASM function for batch processing
    return this.wasmModule.batchPointToTriangleDistance(
      samples,
      triangles
    );
  }
}
```

### 5.4 WASM Acceleration Opportunity

**Add to `fikoyt-wasm/src/lib.rs`:**

```rust
#[wasm_bindgen]
pub fn batch_point_to_triangle_distance(
    points: &[f32],       // length = 3 * num_points
    triangles: &[f32],    // length = 9 * num_triangles
) -> Vec<f32> {
    let num_points = points.len() / 3;
    let num_triangles = triangles.len() / 9;
    let mut distances = vec![f32::MAX; num_points];

    for i in 0..num_points {
        let point = Vec3::new(
            points[i * 3],
            points[i * 3 + 1],
            points[i * 3 + 2]
        );

        let mut min_dist = f32::MAX;

        for j in 0..num_triangles {
            let v0 = Vec3::new(
                triangles[j * 9],
                triangles[j * 9 + 1],
                triangles[j * 9 + 2]
            );
            let v1 = Vec3::new(
                triangles[j * 9 + 3],
                triangles[j * 9 + 4],
                triangles[j * 9 + 5]
            );
            let v2 = Vec3::new(
                triangles[j * 9 + 6],
                triangles[j * 9 + 7],
                triangles[j * 9 + 8]
            );

            let dist = point_to_triangle_distance(point, v0, v1, v2);
            min_dist = min_dist.min(dist);
        }

        distances[i] = min_dist;
    }

    distances
}

fn point_to_triangle_distance(
    p: Vec3,
    v0: Vec3,
    v1: Vec3,
    v2: Vec3
) -> f32 {
    // Optimized implementation from Geometric Tools
    // (See section 1.2 above for algorithm)

    let e0 = v1 - v0;
    let e1 = v2 - v0;
    let diff = v0 - p;

    let a = e0.dot(e0);
    let b = e0.dot(e1);
    let c = e1.dot(e1);
    let d = e0.dot(diff);
    let e = e1.dot(diff);

    let det = a * c - b * b;
    let s = b * e - c * d;
    let t = b * d - a * e;

    // Classify region and compute distance
    // (6 regions, see Geometric Tools paper)

    if s + t <= det {
        if s < 0.0 {
            if t < 0.0 {
                // Region 4
                // ...
            } else {
                // Region 3
                // ...
            }
        } else if t < 0.0 {
            // Region 5
            // ...
        } else {
            // Region 0 (inside triangle)
            let inv_det = 1.0 / det;
            let s = s * inv_det;
            let t = t * inv_det;

            let closest = v0 + e0 * s + e1 * t;
            return (p - closest).length();
        }
    } else {
        // Regions 1, 2, 6
        // ...
    }

    // Return computed distance
    // (Full implementation omitted for brevity)
}
```

---

## 6. CAD Industry Best Practices

### 6.1 CATIA V5 Comparison

**Approach:** Superposition-based comparison
- Align meshes using ICP or manual alignment
- Compute signed distance field
- Visualize differences with color mapping

**Source:** [3D CAD Model Comparison Tools](https://www.capvidia.com/blog/how-to-compare-3d-cad-models)

### 6.2 SolidWorks Compare Geometry

**Features:**
- **Signature-based matching:** Match faces by geometric signature
- **Volume comparison:** Detect added/removed material
- **Face comparison:** Detect modified faces
- **History matching:** Compare feature trees (when available)

**Tessellation Independence:** Uses B-Rep (boundary representation) when possible, falls back to tessellated comparison

**Source:** [SolidWorks Compare Geometry Tool](https://www.cati.com/blog/solidworks-free-tools-utilities-compare-geometry/)

### 6.3 PTC Creo Compare

**Method:** Exact geometry comparison at B-Rep level
- Compare NURBS surfaces directly
- Fall back to tessellated comparison when B-Rep unavailable

### 6.4 3DViewStation and 3DComparator

**Advanced Features:**
- Compare exact geometries (B-Rep) or tessellated meshes
- Generate new geometries representing differences
- Signed distance visualization
- Cross-section comparison

**Source:** [3DViewStation CAD Comparison](https://www.cadinterop.com/en/your-needs/analyze-cad-models/the-simplest-and-the-fastest-solution-to-compare-cad-model.html)

### 6.5 Key Takeaway

**Professional tools use a hierarchy:**
1. **Best:** B-Rep comparison (exact geometry)
2. **Good:** Hausdorff distance with high sampling density
3. **Fast:** Approximate Hausdorff with adaptive sampling
4. **Fallback:** Vertex-to-vertex (your current method)

**For FikoYT:** Since you're working with tessellated meshes (not B-Rep), implement approach #2 or #3.

---

## 7. Complexity Analysis

### 7.1 Vertex-to-Vertex (Current Method)

**Algorithm:** Spatial hash of vertices, find nearest neighbor

```
Construction: O(n) where n = vertex count
Query: O(1) average, O(n) worst case
Total: O(n + m) for n vertices in A, m vertices in B
```

**Problems:**
- Misses surface geometry between vertices
- Fails when tessellation differs
- No geometric meaning to distances

### 7.2 Point-to-Triangle with BVH (Recommended)

**Algorithm:** Sample mesh A, query nearest triangle on mesh B

```
BVH Construction: O(n log n) where n = triangle count
Sampling: O(s) where s = sample count
Query per sample: O(log n)
Total: O(n log n + s log n)
```

**Typical Values:**
- n = 100,000 triangles
- s = 10,000 samples
- Construction: ~100ms (one-time, cacheable)
- Queries: ~10ms per mesh
- **Total: ~120ms for full comparison**

**Benefits:**
- Geometrically accurate
- Tessellation-invariant
- Tunable accuracy (adjust sample count)

### 7.3 GPU-Accelerated SDF (Advanced)

**Algorithm:** Compute signed distance field on GPU

```
SDF Generation: O(r³ / p) where r = resolution, p = parallelism
Query: O(1) per point (texture lookup)
Total: O(r³ / p + s)
```

**Typical Values:**
- r = 256 (256³ voxel grid)
- p = ~1000 GPU threads
- Generation: ~50ms
- Queries: ~1ms per mesh
- **Total: ~100ms for full comparison**

**Benefits:**
- Fastest query time
- Reusable for multiple comparisons
- Supports advanced visualizations

---

## 8. Recommended Implementation Roadmap

### Phase 1: Basic Implementation (2-3 days)

**Goal:** Replace spatial hash with point-to-triangle BVH

1. Install `three-mesh-bvh` (already in your project)
2. Create `FikoMeshComparison.ts` service
3. Implement basic comparison:
   - Use `MeshSurfaceSampler` for sampling
   - Use `closestPointToPoint` for queries
   - Compute one-sided Hausdorff distance
4. Add visualization (color-coded distance map)
5. Test with simple meshes

**Expected Results:**
- Detects surface differences correctly
- ~100-200ms comparison time for typical models
- Visually intuitive color mapping

### Phase 2: Optimization (1-2 days)

**Goal:** Improve performance and accuracy

1. Implement two-sided Hausdorff (symmetric comparison)
2. Add adaptive sampling (more samples in high-curvature areas)
3. Optimize BVH usage (cache, reuse, worker threads)
4. Add statistics (max, mean, RMS, histogram)
5. Tune sample count for accuracy vs speed

**Expected Results:**
- <100ms comparison time
- Accurate to <0.1mm for typical CAD parts
- Comprehensive statistics

### Phase 3: WASM Acceleration (2-3 days)

**Goal:** 10-50x speedup for large meshes

1. Implement `batch_point_to_triangle_distance` in Rust
2. Update `FikoWasmBridge.ts` with new bindings
3. Benchmark WASM vs pure JS
4. Add fallback when WASM unavailable
5. Optimize memory transfers (use SharedArrayBuffer)

**Expected Results:**
- 10-50x faster distance computation
- Maintains accuracy
- Graceful fallback to JS

### Phase 4: Advanced Features (Optional, 3-5 days)

**Goal:** Professional-grade comparison tools

1. GPU SDF generation (`three-mesh-bvh` shader examples)
2. Signed distance (inside vs outside)
3. Cross-section comparison
4. Volume difference computation
5. Export comparison reports (PDF, JSON)
6. Animation/interpolation between models

**Expected Results:**
- Near-instant comparisons (<10ms)
- Advanced visualizations
- Production-ready tool

---

## 9. Testing Strategy

### 9.1 Test Cases

**Case 1: Same Surface, Different Tessellation**
- Create sphere with 100 triangles
- Create sphere with 1000 triangles
- **Expected:** Hausdorff distance ≈ 0

**Case 2: Similar but Not Identical**
- Sphere radius 10.0
- Sphere radius 10.1
- **Expected:** Hausdorff distance ≈ 0.1

**Case 3: Partial Overlap**
- Box 10×10×10
- Box 10×10×11 (1mm longer)
- **Expected:** Hausdorff distance ≈ 1.0

**Case 4: No Overlap**
- Box at origin
- Box at (100, 0, 0)
- **Expected:** Hausdorff distance ≈ 100

### 9.2 Validation

**Ground Truth:**
- Compare results to MeshLab's Metro tool
- Use CloudCompare for verification
- Analytical test cases (geometric primitives)

**Performance Benchmarks:**
- Small mesh (1k triangles): <10ms
- Medium mesh (100k triangles): <100ms
- Large mesh (1M triangles): <1s

---

## 10. References and Resources

### Academic Papers

1. [Distance Between Point and Triangle in 3D - Geometric Tools](https://www.geometrictools.com/Documentation/DistancePoint3Triangle3.pdf)
2. [Fast and Accurate Hausdorff Distance Calculation - Guthe et al.](https://cg.cs.uni-bonn.de/backend/v1/files/publications/guthe-2005-fast.pdf)
3. [Exact Computation of Hausdorff Distance - KIT](https://publikationen.bibliothek.kit.edu/1000027274/5536623)
4. [Robust Hausdorff Distance Computation - SGI 2021](https://summergeometry.org/sgi2021/robust-computation-of-the-hausdorff-distance-between-triangle-meshes/)

### Implementation Resources

5. [three-mesh-bvh GitHub Repository](https://github.com/gkjohnson/three-mesh-bvh)
6. [three-mesh-bvh Distance Example](https://gkjohnson.github.io/three-mesh-bvh/example/bundle/distancecast.html)
7. [Metro Algorithm - MeshLab](https://github.com/areslp/meshlab/blob/master/vcglib/apps/metro/metro.cpp)
8. [Distance Queries - Open3D Documentation](https://www.open3d.org/docs/latest/tutorial/geometry/distance_queries.html)

### Geometry Algorithms

9. [Closest Point to Triangle - 3DCollisions](https://gdbooks.gitbooks.io/3dcollisions/content/Chapter4/closest_point_to_triangle.html)
10. [Distance to Triangle - Inigo Quilez](https://iquilezles.org/articles/triangledistance/)
11. [Barycentric Coordinates - Scratchapixel](https://www.scratchapixel.com/lessons/3d-basic-rendering/ray-tracing-rendering-a-triangle/barycentric-coordinates.html)

### CAD Industry Tools

12. [SolidWorks Compare Geometry](https://www.cati.com/blog/solidworks-free-tools-utilities-compare-geometry/)
13. [3DViewStation CAD Comparison](https://www.cadinterop.com/en/your-needs/analyze-cad-models/the-simplest-and-the-fastest-solution-to-compare-cad-model.html)
14. [Comparing 3D CAD Models - ResearchGate](https://www.researchgate.net/publication/261648305_Comparing_3D_CAD_Models_Uses_Methods_Tools_and_Perspectives)

### Spatial Data Structures

15. [Bounding Volume Hierarchy - Wikipedia](https://en.wikipedia.org/wiki/Bounding_volume_hierarchy)
16. [BVH Star - NVIDIA Research](https://meistdan.github.io/publications/bvh_star/paper.pdf)
17. [Fast Point to Mesh Distance - CMU](http://biorobotics.ri.cmu.edu/papers/paperUploads/Point_To_Mesh_Distance_IROS_v6_Geordan.pdf)

### Additional Tools

18. [MeshLab Official Site](https://www.meshlab.net/)
19. [Mesh to SDF Library](https://github.com/marian42/mesh_to_sdf)
20. [P2M: Point to Mesh Distance Solver - arXiv](https://arxiv.org/abs/2308.16084)

---

## 11. Conclusion

**Key Findings:**

1. **Point-to-triangle distance** solves tessellation variance by measuring to the surface, not vertices
2. **Hausdorff distance** is the industry standard for mesh comparison
3. **BVH spatial indexing** makes queries fast (O(log n))
4. **three-mesh-bvh** provides all needed functionality for Three.js
5. **WASM acceleration** can provide 10-50x speedup for large meshes

**Recommended Solution:**

Replace your spatial hash vertex-to-vertex comparison with:
- **Metro-style algorithm:** Sample → BVH query → Hausdorff statistics
- **Use three-mesh-bvh:** Already in your project, production-ready
- **Accelerate with WASM:** Leverage your existing Rust infrastructure
- **Visualize results:** Color-coded distance mapping

**Implementation Complexity:**
- **Basic version:** 2-3 days
- **Optimized version:** 3-5 days
- **With WASM:** 5-8 days total

**Expected Results:**
- ✅ Tessellation-invariant comparison
- ✅ <100ms comparison time
- ✅ Accurate to <0.1mm
- ✅ Professional-grade visualization
- ✅ Matches MeshLab/Metro accuracy

---

**Document Version:** 1.0
**Author:** Research conducted by Claude (Anthropic)
**Date:** 2026-02-14
