alpha, blend equation, blending, cpp, Fragment Shader, Microsoft Visual Studio, Oculus Rift, Oculus SDK for Windows, OpenGL, semi-transparent textures, sorted transparent objects, transparency, virtual reality, VR
A seagull. Bang!
‘It happened to a seagull?’
Peters lifted some crisps from the packet. Munching, language inaudible apart from the word Yes.
He wiped the salt from his greasy fat lips. ‘Sometimes it’s bees. A fly, perhaps. But, yes, a big white feathery bird hit the bathroom window.’
Let us consider the case using an Oculus Rift virtual reality headset. I cranked open my C++ Microsoft Visual Studio application – incorporating OpenGL graphics library and the Oculus SDK for Windows – and began to render some windows.
The Learn OpenGL article Blending will guide us through the requirements.
If I open the window PNG file in GIMP, I can hold down the Shift key when using the color picker tool to determine each pixel’s alpha value:
A bit of inspection tells me that the glass in the window is 75% transparent.
Next, when rendering the windows to my VR headset, I switch on OpenGL blending:
glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
We are blending our semi-transparent glass with the objects behind it. The alpha value of 0.25 means each pixel colour consists of 25% glass and 75% of the objects behind it.
But we have one further consideration. If we want to render multiple windows to our virtual world without sorting them from furthest to nearest us, the following disaster can strike:
That’s pants! The window in front is not showing the window immediately behind it.
So let’s sort our transparent windows for rendering (after rendering all the opaque objects of our virtual world):
Phew! That’s better. Each transparent window correctly shows all the objects behind it, including other transparent windows.
‘There was only one bathroom window,’ Peters said, munching a pasty.
‘Yes, one bathroom window. But I wish to demonstrate how the poor bird came a cropper on transparency. You see-‘ I stopped speaking. Then I said, ‘Did you say there was only one bathroom window?’
‘Yeah,’ Peters confirmed, flakes of pastry falling from his plump lips. ‘It’s completely smashed. Glass everywhere.’
I wrung my hair. ‘Oh, my bathroom window!’ I cried.
Peters was unconcerned. ‘Don’t worry about it. It’s better this way. Feels like you are shitting in the woods.’
His words, as ever, were of little comfort to me.
Here’s a video of the transparent windows rearranged into a nice bit of balcony fencing (and some grass with discarded fragments):