`graphics.setStencilPattern` equivalent in C API?

,

Hello!

I'm porting some code from Lua to C and I'd like to be able to set a stencil pattern for drawing. A single sprite's render code uses several stencils, so I can't set a single stencil for the sprite using pd->sprite->setStencilPattern.

Has anyone found a method of setting the global drawing stencil pattern using the C API?

Thanks so much!

I think I get what you're saying. It sounds like we need a pd->graphics->setStencilPattern() like pd->sprite has. Here's a helper function that makes an image from a pattern so that you can create images for your patterns then use setStencilImage() instead:

LCDBitmap* makePatternImage(LCDPattern* pattern)
{
    LCDBitmap* image = pd->graphics->newBitmap(32, 8, kColorBlack);
    pd->graphics->pushContext(image);
    pd->graphics->fillRect(0, 0, 32, 8, (LCDColor)pattern);
    pd->graphics->popContext();
    return image;
}

Testing this I discovered that the LCDOpaquePattern macro in pd_api_gfx.h doesn't work right, gives an array initialized from non-constant array expression error. :frowning: I swear I tested that.. Maybe it was in a different context where this isn't a problem. But it looks like it works fine if you remove the type cast. Those extra 0xffs are for the mask part of the pattern, and since they default to zero in an assignment like this you get a fully transparent pattern if you leave them out.

#define MakePattern(r0,r1,r2,r3,r4,r5,r6,r7) {(r0),(r1),(r2),(r3),(r4),(r5),(r6),(r7),0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff}
	LCDPattern pattern = MakePattern(0x55, 0xaa, 0x55, 0xaa, 0x55, 0xaa, 0x55, 0xaa);
	stencil = makePatternImage(&pattern);

ah! For some reason you have to declare the pattern static for it to work with the macro. I've been writing C code for decades and I still run across stuff like this that I just don't get..

static LCDPattern pattern = LCDOpaquePattern(0x55, 0xaa, 0x55, 0xaa, 0x55, 0xaa, 0x55, 0xaa);
stencil = makePatternImage(&pattern);

Thanks so much Dave, that's exactly what I was hoping for. That helps a lot!

It doesn't look like there's a way to clear the stencil pattern—should I just set the stencil image to an all-white image to effectively clear the stencil, or will there be a performance hit from that?

Setting the stencil image to NULL clears it (and yes, setting it to an all-white image would add some unnecessary overhead). I'll file a note to add that to the docs.