Questions about using CSG to cut meshes in half

Hello everyone, I hope everyone is doing well!

I’ve been struggling with this problem for two days haha ​​basically, I’m trying to find a way to cut horizontal planes in BabylonJS, using other vertical planes.

After many attempts, I managed to cut a plane in half using another plane, as you can see in this Playground:

However, if I try to repeat exactly the same cutting procedure using one of the meshes from the previous division, the procedure no longer works (as you can see, instead of cutting the new mesh in the middle, it creates a mesh in the bottom, although I’m replicating the exact same steps):

I’m using CSG instead of CSG2 because apparently CSG2 doesn’t work with this type of mesh.

In my production code, I’m trying to replicate the logic that works with the first cut to continue working in subsequent cuts, but without success:

let resultingMeshes = []
let currentMeshes = [squareMesh]

rMeshes.forEach((redPlaneMesh, index) => {

    currentMeshes.forEach((mesh) => {
        const cutterCSG = BABYLON.CSG.FromMesh(redPlaneMesh)

        const meshCSG = BABYLON.CSG.FromMesh(mesh)
        
        let firstSideCSG = cutterCSG.subtract(meshCSG)
        firstSideCSG = firstSideCSG.intersect(meshCSG)

        let secondSideCSG = meshCSG.subtract(cutterCSG)
        secondSideCSG = secondSideCSG.subtract(firstSideCSG)

        if (firstSideCSG) {
            const firstMesh = firstSideCSG.toMesh(`cutMesh${index}`, blackMaterial, scene)
            resultingMeshes.push(firstMesh)
        }

        if (secondSideCSG) {
            const secondMesh = secondSideCSG.toMesh(`cutMesh${index}`, blackMaterial, scene)
            secondMesh.flipFaces(true)
            resultingMeshes.push(secondMesh)
        }
    })

    // Dispose of the original meshes after cutting
    currentMeshes.forEach(mesh => mesh.dispose())
    currentMeshes = resultingMeshes
    resultingMeshes = [] // Reset for the next iteration
})

Does anyone have any tips on this?

Thank you in advance and have a great weekend everyone!

I just did a small fix to the second playground to correctly show the resulting issue:

Instead of a plane, try using a very thin box. CSG normally needs the mesh to be a volume in order to work. Furthermore, CSG2 should work with a thin box, so it is probably preferable to use it rather than CSG.

1 Like

Thank you, @Evgeni_Popov. I’ll try this :blush:

@Evgeni_Popov bro, you saved my skin, haha. This just works with a subtraction; no need to call multiple CSG methods:

The only issue I have now is that it doesn’t separate the object into multiple meshes, but I think this issue can be solved more easily (I hope :grin:).

Just in case, do you know if BabylonJS has any native way to separate parts of a mesh that “don’t touch”?

I solved this problem of separating meshes manually by using its vertices data. Thanks

1 Like