Transform Three.js Mesh to Mesh object Mesh(vertices, indices)

Hey there,

how can I transform a Three.js Mesh (.geometry = BufferGeometry so positions and vertices) to a Mesh that takes vertices and indices as an input (for this Mesh I have some functions ready to use).
Just by transforming the positions to vertices?
I tried a lot but I am afraid that I’m messing something up with the indices.
Maybe also because I may not have understand this concept completely, even though I read a lot about it.

That’s what I did:

export function convertThreeMeshToMeshObject(mesh: THREE.Mesh) {
    const positions = mesh.geometry.attributes.position.array;
    const vertices: Point3d[] = [];
    for (let i = 0; i < positions.length; i += 3) {
        vertices.push(new Point3d(positions[i], positions[i + 1], positions[i + 2]));
    }

    let indices: number[]= [];
    if (mesh.geometry.index) {
        indices = Array.from(mesh.geometry.index.array);
    }
    
    return new Mesh(vertices, indices);
}

If someone could help me out that would be great

Here is an updated version of your convertThreeMeshToMeshObject function that should work with Three.js THREE.BufferGeometry :

export function convertThreeMeshToMeshObject(mesh: THREE.Mesh) {
    const positions = mesh.geometry.attributes.position.array;
    const vertices: Point3d[] = [];
    for (let i = 0; i < positions.length; i += 3) {
        vertices.push(new Point3d(positions[i], positions[i + 1], positions[i + 2]));
    }

    let indices: number[]= [];
    if (mesh.geometry.index) {
        indices = Array.from(mesh.geometry.index.array);
    } else if(mesh.geometry.attributes.index){
        indices = Array.from(mesh.geometry.attributes.index.array);
    }
    else if(mesh.geometry.index === null){
        for(let i = 0; i< vertices.length;i++){
            indices.push(i);
        }
    }
    return new Mesh(vertices, indices);
}

In this version, I’ve added a check for the index attribute of the THREE.BufferGeometry which is used when the BufferGeometry was created with index. I’ve also added a check for case when the index property is null, In this case, I’m creating indices by iterating over the number of vertices.

You should also check if the custom mesh object you are creating can handle the indices format correctly.

Also, it’s good to log the indices and vertices after converting them to make sure that they are in the correct format and also to check if the indices are referencing the correct vertices and if the indices are in the correct order.


Generated with ChatGPT . Maybe this help…

1 Like