Make masked objects intersect?

Here’s the Three.js masking example: three.js examples

But as you can see, the two objects never intersect because they are two scenes layered on each other.

How would you make the objects intersect as if they are in a single scene?

Possible methods:

  • one way is to not use post-processing-based masking, and instead project the images onto two meshes using a SpotLight texture and making sure the SpotLight is positioned at the scene’s camera with the same camera frustum (this is an easy approach, f.e. I’m using to project another scene’s texture to make a “portal” world-in-world effect)
  • another way might be to render the two masked objects into the same scene (somehow?) including the depth buffer so they intersect normally as they would in the first point?

Is the second method possible?

1 Like

Set renderer.autoClear=false when rendering the second scene, and it should depth test against what is already in the depth buffer.
This will only work if you don’t have other things in the first scene wiping out the depth buffer during its rendering, (like full screen quad passes/post processing that doesn’t use depthWrite=false ).

2 Likes

i would try to avoid postpro for masking. it seems to me stencil is easier and less intrusive. all you need is the same stencilRef, you can use it multiple times: https://codesandbox.io/p/sandbox/inverted-stencil-buffer-7n2yru

mask

        colorWrite,
        depthWrite,
        stencilWrite: true,
        stencilRef: id,
        stencilFunc: THREE.AlwaysStencilFunc,
        stencilFail: THREE.ReplaceStencilOp,
        stencilZFail: THREE.ReplaceStencilOp,
        stencilZPass: THREE.ReplaceStencilOp,

masked content

    stencilWrite: true,
    stencilRef: id,
    stencilFunc: inverse ? THREE.NotEqualStencilFunc : THREE.EqualStencilFunc,
    stencilFail: THREE.KeepStencilOp,
    stencilZFail: THREE.KeepStencilOp,
    stencilZPass: THREE.KeepStencilOp,

can you give a threejs example?