Skip to content

Instantly share code, notes, and snippets.

@selfsame
Last active February 10, 2024 17:32
Show Gist options
  • Save selfsame/9093389d008d902a83f8e7438d18086c to your computer and use it in GitHub Desktop.
Save selfsame/9093389d008d902a83f8e7438d18086c to your computer and use it in GitHub Desktop.
compute volume of three.js ConvexHull

A bit of js that computes the volume of a ConvexHull (or any mesh if you iterate the faces making tetrahedrons with the centerpoint)

import {Vector3} from 'three'
import {ConvexHull} from 'three/examples/jsm/math/ConvexHull.js'

// via https://stackoverflow.com/questions/9866452/calculate-volume-of-any-tetrahedron-given-4-points
function determinant_3x3(m){
    return (m[0][0] * (m[1][1] * m[2][2] - m[1][2] * m[2][1]) -
            m[1][0] * (m[0][1] * m[2][2] - m[0][2] * m[2][1]) +
            m[2][0] * (m[0][1] * m[1][2] - m[0][2] * m[1][1]))
}

function subtract(a, b){
    return [a.x - b.x, a.y - b.y, a.z - b.z]
}

function tetrahedron_volume(a,b,c,d){
    return Math.abs(
        determinant_3x3(
            [subtract(a, b),
             subtract(b, c),
             subtract(c, d) ])) / 6.0
}

function compute_volume(o){
    var ch = new ConvexHull()
    ch.setFromObject(o)
    let sum = 0;
    let a = o.getWorldPosition(new Vector3(0,0,0))
    for (let index = 0; index < ch.faces.length; index++) {
        const face = ch.faces[index];
        let b = face.edge.tail().point
        let c = face.edge.head().point
        let d = face.edge.next.head().point

        var V = tetrahedron_volume(a,b,c,d)
        sum += V;
    }
    return sum;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment