Clip parts of mesh inside a box

Hello,
I want the parts inside a box clipped for every mesh.

Before clip:

After clip:

Can I implement it by the 6 clipPlanes? or any other solution?

Thanks

Yup I think clip planes will work fine

1 Like

Using the standard clip planes won’t work because one plane clips off an entire half of the space: for example, in your example, the leftmost plane will remove everything on the right, so most of the excavator arm will be removed too.

You’ll need to use a custom fragment shader that will check all 6 planes and discard the fragment if the point lies within the interior formed by the 6 planes.

Note, however, that you won’t get exactly what you’ve pictured. Meshes aren’t volumetric, so when they’re clipped by a plane, you’ll see an empty space, like this:

image

1 Like

@Evgeni_Popov , thanks for your reply, you got the two points I need to solve.

And I still need someone to help me:
1、I’m poor at shader, can anyone give a guide how to implement such a custom fragment shader, as standard clipplanes won’t work here.
2、Anyone has idea to generate a special plane, so meshes look not empty after clipped? Just like the picture I post.

  1. First read through Shader Docs:

Afterwards for example create ShaderMaterial for the mesh. Then find and set clipping box shader code like code parts in here:

  1. In the vertex shader find out if vertex world position is “inside” and/or behind one of the 6 planes. If true, then set prefered gl_FragColor.
1 Like

For 2/, you can try to fake it by disabling backface culling, and if the current pixel of the fragment shader is from a back face, use a fixed color.

You can reuse most of the existing shader code for the clip planes, but you must disable what the fragment shader is doing and replace it by your own one (see line 1 in the PG below).

Here’s one way to do it with a material plugin:

@Evgeni_Popov , thanks for your fanstanstic idea, it is really close to what I need.

But I have one more question:
After replacing the clip fragment to my own, If I want to resume to the original, how can I do?

I have a PG here, the “switch” doesn’t work.
https://playground.babylonjs.com/#A8FURG#2

You can’t really do it by changing the code in the include shader store because our cache mechanism won’t see the change and won’t recompile the effect.

You can do it with the material plugin from my PG:

Of course, when switching, you won’t see anything because the 6 clip planes are still in effect, and this time each plane removes half of the space!