How can I place a GLTF model behind a stencil mask in three.js?

I’m using a stencil mask in Three.js to create a portal effect. It works correctly on meshes when I can control the material. However, when I load a gltf model with the model’s material I cannot get it to hide outside the stencil mask.

See this example screenshot here with the desired effect with a cube mesh

Screenshot of GLTF model unable to hide outside the stencil mask

   material.stencilWrite = true;
   material.stencilFunc =  THREE.EqualStencilFunc;
   material.stencilRef =  1;
   material.stencilFuncMask =  0xFF;
   material.stencilFail =  THREE.KeepStencilOp;
   material.stencilZFail =  THREE.KeepStencilOp;
   material.stencilZPass =  THREE.ReplaceStencilOp;
type or paste code here

Here is a codepen with both the mesh and the gltf model: https://codepen.io/jattfield/pen/GRMzRjw

Thanks for any guidance.

This may be a little late, but for other people with the same issue you need to explicitly set the renderOrder on the gltf scene:

    gltf.scene.renderOrder = 2;

For whatever reason it seems like when you add a scene to a group, the scene’s original renderOrder (0 in this case) is not overwritten by the group you add it to. Not sure if this is intended or a bug on three.js’s part.

Thanks, yes. I came to the same conclusion eventually. renderOrder is now my go-to when I experience any rendering issues in a scene.

1 Like