louisdeb
louisdeb

Reputation: 439

How can I blend two colours to a mix of them in OpenGL?

I'm rendering both a blue and a red line (in the context of an anaglyph). When the red line and blue line overlap I want a purple color to be rendered instead of the line in front.

I am using OpenGL. Some of the code I have tried so far is this:

glBlendFunc(GL_ONE, GL_DST_ALPHA);

This causes the overlap to render white, and the line appears as follows:

I thought maybe using an RGB scale factor on top of this blend would be the right thing to do.

So I tried using the glBlendFuncSeparate which takes parameters:

  1. Source Factor RGB
  2. Destination Factor RGB
  3. Source Factor Alpha
  4. Destination Factor Alpha

I could not find parameters which made this work for me.

I also attempted using glBlendEquation with an additive equation, but didn't notice any success in that method.

How do I produce a function which successfully blends the two lines into a purple color?

Edit:

I've noticed that glBlendFunc(GL_ONE, GL_DST_ALPHA) does perform some blending to produce intermediate colors (the actual lines are just nonsensical here, it was just to display some blending). enter image description here

Upvotes: 0

Views: 3094

Answers (2)

datenwolf
datenwolf

Reputation: 162164

I'm rendering both a blue and a red line (in the context of an anaglyph)

Not the answer you expect, but the answer you need: The usual approach to render anaglyph images in OpenGL is not to use blending. Blending is hard enough to get right, you don't want to mess things up further with the anaglyph part.

There are two commonly used methods:

  • Rendering each view into a FBO attached texture and combining them in a postprocessing step.

  • using glColorMask to select the active color channels for each rendering step.

I think for now you're good with the color mask method: Do it as following:

display:
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
    glViewport(…)

    # prepare left view
    setup_left_view_projection()
    glColorMask(1,0,0, 1); # red is commonly used for the left eye

    draw_scene()

    glClear(GL_DEPTH_BUFFER_BIT) # clear the depth buffer (and just the depth buffer!)

    # prepare right view
    setup_right_view_projection()
    glColorMask(0,1,1, 1); # cyan is commonly used for the right eye

    draw_scene()

Upvotes: 2

Zac
Zac

Reputation: 4695

The typical blend function is glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);; note that the final color changes according to the draw order.

Blend functions are not so obvious, so a graphical representation sometimes is better; check out for example this site.

Upvotes: 1

Related Questions