Anonymous
Anonymous

Reputation: 4757

OpenGL: Using colour gradients for given line segments

I know that I can get a colour gradient representation on a line like this:

glBegin (GL_LINES);

glColor3f  (1, 0, 0);
glVertex2f (v0_x, v0_y);
glColor3f  (0, 0, 1);
glVertex2f (v1_x, v1_y);

glEnd ();

Result:

enter image description here

Question:

Is it possible to extend this for more points? Example: I have two further points v2 and v3. All points are connected (v0v1,v1v2,v2v3). Is there any way to get a colour gradient (red to blue) while drawing these lines so that v0 would be coloured red and v3 would be coloured blue?

Upvotes: 0

Views: 1983

Answers (1)

keltar
keltar

Reputation: 18409

You need to calculate colours for this points with linear interpolation.

If distance between all your vertices is the same:

static void lerp3(float *o, const float *a, const float *b, float t) {
    float it = 1.0f - t;
    o[0] = it*a[0]+t*b[0];
    o[1] = it*a[1]+t*b[1];
    o[2] = it*a[2]+t*b[2];
}

/* ... */

float v0_colour[3] = {1.0f, 0.0f, 0.0f};
float v1_colour[3], v2_colour[3];
float v3_colour[3] = {0.0f, 0.0f, 1.0f};

float t1 = 1.0f / 3;
float t2 = 1.0f / 3 + t1;

lerp3(v1_colour, v0_colour, v3_colour, t1);
lerp3(v2_colour, v0_colour, v3_colour, t2);

Then just use v1_colour and v2_colour to colour your extra vertices. If distance is varying, recalculate t1 and t2 accordingly - e.g. by dividing sum vector lengths of this points.

Upvotes: 2

Related Questions