'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

    // Stencil rules to make material hide 
   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;

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

Thanks for any guidance.



Solution 1:[1]

I figured it out!

Example of the model hiding correctly behind the stencil: https://codepen.io/jattfield/pen/jOaEZmJ

Model hiding correctly behind the stencil

skinnedMesh.material.stencilFunc = THREE.EqualStencilFunc;
skinnedMesh.material.stencilFuncMask =  0xFF;
skinnedMesh.material.stencilZPass =  THREE.ReplaceStencilOp;
skinnedMesh.material.stencilZPass =  THREE.ReplaceStencilOp;
skinnedMesh.material.needsUpdate = true;
insideGroup.add(gltf.scene);
gltf.scene.renderOrder = 3; // This was the KEY !!!!

The gltf.scene HAS to be rendered after the stencil mask. I had used a renderOrder on the "insideGroup" I was placing it in, but it seems this was not enough. Interestingly, when I attempt to place models with multiple meshes, each mesh also has to be given a specific renderOrder.

I can find very little documentation on this kind of stuff. I have what I need working, but if there is anybody out there also working with models and stencil masks I'd love to see it. Thanks.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Tyler2P