three.js

[Code Reading] Clipping Object in Three.js

Example

I have been learning of Three.js, and I would like to put forth my code with a great idea someday. Therefore I have started to read and understand by Thee.js Examples. Through this challenge, I would make progress for a creative coder.

First of all, I picked up the following example.

Sample image
three.js
Edit description

In this example, the originating object is cropped by invisible planes in surrounding. Besides, the cut mouth is coloured with specific colour material, magenta. They call this technic that applying materials to the cut face a stencil because the behaviour is similar to seal the content on the object. Once you remove the invisible plane, you will see the logic in visual.

Clipping

The most highlighted code in the example is to enable localClippingEnable that is the property of WebGLRenderer . If not enabled, all of the configuration for stencil crop is to no avail in the end.

The next important point is to pass invisible planes into the material of the object so that the planes can mask the cutting faces. You can make the mask with the following couple of codes that is shorthanded from example code.

Create planes:

planes = [
 new THREE.Plane(new THREE.Vector3(- 1, 0, 0), 0),
 new THREE.Plane(new THREE.Vector3(0, - 1, 0), 0),
 new THREE.Plane(new THREE.Vector3(0, 0, - 1), 0)
];

var geometry = new THREE.TorusKnotBufferGeometry(0.4, 0.15, 220, 60);
object = new THREE.Group();
scene.add(object);

// Set up clip plane rendering
planeObjects = [];
var planeGeom = new THREE.PlaneBufferGeometry(4, 4);

for (var i = 0; i < 3; i++) {
 var poGroup = new THREE.Group();
 var plane = planes[i];
 var stencilGroup = createPlaneStencilGroup(geometry, plane, i + 1);
 
 // plane is clipped by the other clipping planes
 var planeMat =
 new THREE.MeshStandardMaterial({
  color: 0xE91E63,
  metalness: 0.1,
  roughness: 0.75,
  clippingPlanes: planes.filter(p => p !== plane),
  stencilWrite: true,
  stencilRef: 0,
  stencilFunc: THREE.NotEqualStencilFunc,
  stencilFail: THREE.ReplaceStencilOp,
  stencilZFail: THREE.ReplaceStencilOp,
  stencilZPass: THREE.ReplaceStencilOp,
 });
 var po = new THREE.Mesh(planeGeom, planeMat);
 po.onAfterRender = function (renderer) {
  renderer.clearStencil();
 };
 po.renderOrder = i + 1.1;
 object.add(stencilGroup);
 poGroup.add(po);
 planeObjects.push(po);
 scene.add(poGroup);
}

Apply material with invisible planes

var material = new THREE.MeshStandardMaterial({
 // ...
 clippingPlanes: planes,
 clipShadows: true,
 // ...
});
// add the color
var clippedColorFront = new THREE.Mesh(geometry, material);
object.add(clippedColorFront);