I don’t think I am quite understanding how stencils work… I have been trying to get it to work, but to no avail.
I created a new monogame app, and have 2 test images. One is the stencil (a green circle), and the other is the image (a red square).
What I hope to end up with is a red circle. However, I always seem to be ending up with a red square… or just a green circle if I tweak the stencil parameters. I can never seem to get a red circle.
I am rendering both the stencil and the image to a rendertarget and then drawing the resulting texture to the screen.
Here is my stencil code:
spriteBatch = new SpriteBatch(GraphicsDevice);
Texture2D stencil = Content.Load<Texture2D>("stencil"); Texture2D image = Content.Load<Texture2D>("image");
var renderTarget = new RenderTarget2D(GraphicsDevice, 320, 320, false, GraphicsDevice.PresentationParameters.BackBufferFormat, DepthFormat.Depth24Stencil8);
GraphicsDevice.SetRenderTarget(renderTarget);
var s1 = new DepthStencilState() { StencilEnable = true, StencilFunction = CompareFunction.Greater, StencilPass = StencilOperation.Replace, ReferenceStencil = 1, DepthBufferEnable = false, };
GraphicsDevice.Clear(ClearOptions.Target | ClearOptions.DepthBuffer | ClearOptions.Stencil, Color.Transparent, 0, 0);
spriteBatch.Begin(SpriteSortMode.Deferred, null, null, s1); spriteBatch.Draw(stencil, new Vector2(0, 0), Color.White); spriteBatch.End();
var s2 = new DepthStencilState() { StencilEnable = true, StencilFunction = CompareFunction.Equal, StencilPass = StencilOperation.Keep, ReferenceStencil = 1, DepthBufferEnable = false, };
spriteBatch.Begin(SpriteSortMode.Deferred, null, null, s2); spriteBatch.Draw(image, new Vector2(0, 0), Color.White); spriteBatch.End();
GraphicsDevice.SetRenderTarget(null);
stenciledImage = renderTarget;
I am also uploading the 2 images I am using (the green circle is the stencil, and the red square is the “image” that I want stenciled)…
Can someone point me in the right direction to get this working?
Thanks!