OpenGL screen layout - c++

I have some questions about the screen set up. Originally when I would draw a triangle the x vector 1 would be all the way to the right and -1 would be all the way to the left. Now I have adjusted it to account for the different aspect ratio of the window. My new question how do I make the numbers which are used to render a 2d tri go along with the pixel values. If my window is 480 pixels wide and 320 tall I want to have to enter this to span the screen with a tri
glBegin(GL_TRIANGLES);
glVertex2f(240, 320);
glVertex2f(480, 0);
glVertex2f(0, 0);
glEnd();
but instead it currently looks like this
glBegin(GL_TRIANGLES);
glVertex2f(0, 1);
glVertex2f(1, -1);
glVertex2f(-1, -1);
glEnd();
Any ideas?

You need to use functions glViewport and glOrtho with correct values. Basically glViewport sets the part of your window capable of rendering 3D-Graphics using OpenGL. glOrtho establishes coordinate system within that part of a window using OpenGL's coordinates.
So for your task you need to know exact width and height of your window. If you are saying they are 480 and 320 respectively then you need to call
glViewport(0, 0, 480, 320)
// or: glViewport ( 0,0,w,h)
somewhere, maybe in your SizeChanging-handler(if you are using WINAPI it is WM_SIZE message)
Next, when establishing OpenGL's scene you need to specify OpenGL's coordinates. For orthographic projection they will be the same as dimensions of a window so
glOrtho(-240, 240, -160, 160, -100, 100)
// or: glOrtho ( -w/2, w/2, -h/2, h/2, -100, 100 );
is siutable for your purppose. Not that here I'm using depth of 200 (z goes from -100 to 100).
Next on your rendering routine you may draw your triangle

Since the second piece of code is working for you, I assume your transformation matrices are all identity or you have a shader that bypasses them. Also your viewport is spanning the whole window.
In general if your viewport starts at (x0,y0) and has WxH size, the normalized coordinates (x,y) you feed to glVertex2f will be transformed to (vx,vy) as follows:
vx = x0 + (x * .5f + .5f) * W
vy = y0 + (y * .5f + .5f) * H
If you want to use pixel coordinates you can use the function
void vertex2(int x, int y)
{
float vx = (float(x) + .5f) / 480.f;
float vy = (float(y) + .5f) / 320.f;
glVertex3f(vx, vy, -1.f);
}
The -1 z value is the closest depth to the viewer. It's negative because the z is assumed to be reflected after the transformation (which is identity in your case).
The addition of .5f is because the rasterizer considers a pixel as a 1x1 quad and evaluates the coverage of your triangle in the middle of this quad.

Related

OpenGL when switch fron 2D to 3D

Here's what I want to achieve, I have a flag called switch_2D_3D in the code below, and when it's true I switch to 2D mode, otherwise 3D.
void reshape(GLsizei width, GLsizei height)
{
if (switch_2D_3D)
{
// GLsizei for non-negative integer
// Compute aspect ratio of the new window
if (height == 0)
height = 1; // To prevent divide by 0
GLfloat aspect = (GLfloat)width / (GLfloat)height;
// Reset transformations
glLoadIdentity();
// Set the aspect ratio of the clipping area to match the viewport
glMatrixMode(GL_PROJECTION); // To operate on the Projection matrix
// Set the viewport to cover the new window
glViewport(0, 0, width, height);
if (width >= height)
{
// aspect >= 1, set the height from -1 to 1, with larger width
gluOrtho2D(-1.0 * aspect, 1.0 * aspect, -1.0, 1.0);
}
else
{
// aspect < 1, set the width to -1 to 1, with larger height
gluOrtho2D(-1.0, 1.0, -1.0 / aspect, 1.0 / aspect);
}
winWidth = width;
winHeight = height;
} // 2D mode
else
{
// Prevent a divide by zero, when window is too short
// (you cant make a window of zero width).
if (height == 0)
height = 1;
float ratio = width * 1.0 / height;
// Use the Projection Matrix
glMatrixMode(GL_PROJECTION);
// Reset Matrix
glLoadIdentity();
// Set the viewport to be the entire window
glViewport(0, 0, width, height);
// Set the correct perspective.
gluPerspective(45.0f, ratio, 0.1f, 100.0f);
// Get Back to the Modelview
glMatrixMode(GL_MODELVIEW);
winWidth = width;
winHeight = height;
}// 3D mode
}
Everything works perfectly when drawing only in 2d mode, but when I change the flag to switch to the 3d mode, here comes the problem
Every time I resize the window, the things I draw in the 3d scene(for example a cube) would be come smallerand smaller, eventually disappeared, why is this happening
And if I switch back to 2D mode, everything in 2d mode still works fine, the problem is with the 3d mode
Also, if I start the program with the flag set to false, I would see a cube and it still gets smaller as I resize the window each time
Why is this happening?
You should look at your glLoadIdentity() / glMatrixMode() interactions.
Right now, you have two different behaviors:
In 2D: you're resetting your matrix for whatever is active when you enter the function, presumably GL_MODELVIEW, which causes the gluOrtho2D calls to "stack up".
In 3D: you're always resetting the projection matrix, which seems more correct.
Try swapping the order of the glLoadIdentity and glMatrixMode calls in your first path (2D) only.
It's a wise idea to always explicitly set the matrix you want to modify before actually modifying it.

Keeping the geometry intact on screen size change

I have made some shapes like this :
// Triangle
glBegin(GL_TRIANGLES);
glVertex3f(0.0,0.0,0);
glVertex3f(1.0,0.0,0);
glVertex3f(0.5,1.0,0);
glEnd();
// Cube using GLUT
glColor3f(0.0,0.0,1.0);
glutSolidCube(.5);
// Circle
glPointSize(2);
glColor3f(1.0,0.0,1.0);
glBegin(GL_POINTS);
float radius = .75;
for( float theta = 0 ; theta < 360 ; theta+=.01 )
glVertex3f( radius * cos(theta), radius * sin(theta), 0 );
glEnd();
Initially I keep my window size as 500x500 and the output is as shown :
However, if I change the width and height (not in proportion) of my widget, the shapes get distorted (Circle looks oval, Equilateral triangle looks isosceles) :
This is the widget update code :
void DrawingSurface::resizeGL(int width, int height)
{
// Update the drawable area in case the widget area changes
glViewport(0, 0, (GLint)width, (GLint)height);
}
I understand that I can keep the viewport itself with same width and height, but then lot of space will get wasted on sides.
Q. Any solution for this ?
Q. How do game developers handle this in general, designing OpenGL game for different resolutions ?
P.S. : I do understand that this isn't modern OpenGL and also there are better ways of making a circle.
They solve it by using the projection matrix, both the perspective matrix and ortho projection traditionally have a way of getting the aspect ratio (width/height) and use that to adjust the result on screen.

How to tell the size of font in pixels when rendered with openGL

I'm working on the editor for Bitfighter, where we use the default OpenGL stroked font. We generally render the text with a linewidth of 2, but this makes smaller fonts less readable. What I'd like to do is detect when the fontsize will fall below some threshold, and drop the linewidth to 1. The problem is, after all the transforms and such are applied, I don't know how to tell how tall (in pixels) a font of size <fontsize> will be rendered.
This is the actual inner rendering function:
if(---something--- < thresholdSizeInPixels)
glLineWidth(1);
float scalefactor = fontsize / 120;
glPushMatrix();
glTranslatef(x, y + (fix ? 0 : size), 0);
glRotatef(angle * radiansToDegreesConversion, 0, 0, 1);
glScalef(scaleFactor, -scaleFactor, 1);
for(S32 i = 0; string[i]; i++)
OpenglUtils::drawCharacter(string[i]);
glPopMatrix();
Just before calling this, I want to check the height of the font, then drop the linewidth if necessary. What goes in the ---something--- spot?
Bitfighter is a pure old-school 2D game, so there are no fancy 3D transforms going on. All code is in C++.
My solution was to combine the first part Christian Rau's solution with a fragment of the second. Basically, I can get the current scaling factor with this:
static float modelview[16];
glGetFloatv(GL_MODELVIEW_MATRIX, modelview); // Fills modelview[]
float scalefact = modelview[0];
Then, I multiply scalefact by the fontsize in pixels, and multiply that by the ratio of windowHeight / canvasHeight to get the height in pixels that my text will be rendered.
That is...
textheight = scalefact * fontsize * widndowHeight / canvasHeight
And I liked also the idea of scaling the line thickness rather than stepping from 2 to 1 when a threshold is crossed. It all works very nicely now.
where we use the default OpenGL stroked font
OpenGL doesn't do fonts. There is no default OpenGL stroked font.
Maybe you are referring to GLUT and its glutStrokeCharacter function. Then please take note that GLUT is not part of OpenGL. It's an independent library, focused on providing a simplicistic framework for small OpenGL demos and tutorials.
To answer your question: GLUT Stroke Fonts are defined in terms of vertices, so the usual transformations apply. Since usually all transformations are linear, you can simply transform the vector (0, base_height, 0) through modelview and projection finally doing the perspective divide (gluProject does all this for you – GLU is not part OpenGL, too), the resulting vector is what you're looking for; take the vector length for scaling the width.
This should be determinable rather easily. The font's size in pixels just depends on the modelview transformation (actually only the scaling part), the projection transformation (which is a simple orthographic projection, I suppose) and the viewport settings, and of course on the size of an individual character of the font in untransformed form (what goes into the glVertex calls).
So you just take the font's basic size (lets consider the height only and call it height) and first do the modelview transformation (assuming the scaling shown in the code is the only one):
height *= scaleFactor;
Next we do the projection transformation:
height /= (top-bottom);
with top and bottom being the values you used when specifying the orthographic transformation (e.g. using glOrtho). And last but not least we do the viewport transformation:
height *= viewportHeight;
with viewportHeight being, you guessed it, the height of the viewport specified in the glViewport call. The resulting height should be the height of your font in pixels. You can use this to somehow scale the line width (without an if), as the line width parameter is in floats anyway, let OpenGL do the discretization.
If your transformation pipeline is more complicated, you could use a more general approach using the complete transformation matrices, perhaps with the help of gluProject to transform an object-space point to a screen-space point:
double x0, x1, y0, y1, z;
double modelview[16], projection[16];
int viewport[4];
glGetDoublev(GL_MODELVIEW_MATRIX, modelview);
glGetDoublev(GL_PROJECTION_MATRIX, projection);
glGetIntegerv(GL_VIEWPORT, viewport);
gluProject(0.0, 0.0, 0.0, modelview, projection, viewport, &x0, &y0, &z);
gluProject(fontWidth, fontHeight, 0.0, modelview, projection, viewport, &x1, &y1, &z);
x1 -= x0;
y1 -= y0;
fontScreenSize = sqrt(x1*x1 + y1*y1);
Here I took the diagonal of the character and not only the height, to better ignore rotations and we used the origin as reference value to ignore translations.
You might also find the answers to this question interesting, which give some more insight into OpenGL's transformation pipeline.

Cord system and units?

How do I change default cord system and units in OpenGL?
Right now it's using the default, meaning it goes from -1.0 (left) to 1.0 (right) with 0 being the origin (same with Y, -1.0 being top, 1.0 being bottom).
Optimally I would 1) want to change units to roughly same number of pixels. For example, on an 800x600 display have it go from -400 to 400 (on x) and -300 to 300 (on y). Seems like it would be easier to work with than -1.0 to 1.0
2) Bonus points: how do I change the x/y? One game engine had I seen had it go from 0 to maxWidth and 0 to maxHeight.
That is, 0,0 was top left and 800,600 was bottom right. (0, 600 would be left bottom and 800,0 would be top right)
I think these both have to do with the viewpoint command, but don't know if I fully understand it.
First answering your last point: There is no "viewpo i nt" commant. There is glViewport which defines the mapping from so called clip space [-1,1]×[-1,1]×[-1,1] into window/screen space — important: glViewport doesn't set some clipping, so if your viewport only covers some smaller, middle part of your window, things that exceed the viewport in rendering may/will cause artifacts outside the viewport. Scissor testing (enabled and set with *glEnable(GL_SCISSOR_TEST)* and glScissor) does this kind of clipping, which also works within the viewport (nice for implementing selection rubber bands!).
Now to cover your first question: OpenGL's coordinate system is whatever you want it to be; in OpenGL-3.1 and OpenGL-4 there's no default coordinate system at all! In OpenGL-2 and below there are a number of so called transformation matrices, most importantly modelview and projection.
You can think projection to be some kind of a camera's lens (although it works entirely differently). What is does is, it transforms the world (or modelview) space into the aforementioned clip space. It is this projection matrix, that allows you map any affine coordinate system into clip space. OpenGL before version 3 provides you helper functions glFrustum and glOrtho for the most oftenly used projections: Perspective and Ortho.
Let's construct some projection ourself (it's an ortho, but I'd like to show how things work on the math side). Say you'd like to map x in [0; 200], y in [0; 100] to [-1; 1] (left to right), [-1,1] (top to bottom), and leave z as it is. Then
x_clip = -1 + x*(1-(-1))*(200-0) = -1 + x*2/200
y_clip = 1 + y*(-1 1 )*(100-0) = 1 + x*(-2)/100
z_clip = z
This translates into the following matrix:
2/200 0 0 -1
0 -2/100 0 1
0 0 1 0
0 0 0 1
You could now put this into the projection matrix using glLoadMatrix.
The modelview matrix is used for moving stuff around in the world space. It's also used to define the viewpoint: OpenGL has no camera. Instead we just move the whole world in an opposite way to how we'd moved a camera within the world to the desired viewpoint (this time …point, not …port!)
glOrtho():
#include <GL/glut.h>
unsigned int win_w = 0;
unsigned int win_h = 0;
void display(void)
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0, win_w, win_h, 0, -1, 1);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glColor3ub(255,0,0);
glPushMatrix();
glScalef(50,50,50);
glBegin(GL_QUADS);
glVertex2f(0,0);
glVertex2f(1,0);
glVertex2f(1,1);
glVertex2f(0,1);
glEnd();
glPopMatrix();
glFlush();
glutSwapBuffers();
}
void reshape(int w, int h)
{
win_w = w;
win_h = h;
glViewport(0, 0, w, h);
}
int main(int argc, char **argv)
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_RGBA | GLUT_DEPTH | GLUT_DOUBLE);
glutInitWindowSize(800,600);
glutCreateWindow("Ortho);
glutDisplayFunc(display);
glutReshapeFunc(reshape);
glutMainLoop();
return 0;
}

how to draw a spiral using opengl

I want to know how to draw a spiral.
I wrote this code:
void RenderScene(void)
{
glClear(GL_COLOR_BUFFER_BIT);
GLfloat x,y,z = -50,angle;
glBegin(GL_POINTS);
for(angle = 0; angle < 360; angle += 1)
{
x = 50 * cos(angle);
y = 50 * sin(angle);
glVertex3f(x,y,z);
z+=1;
}
glEnd();
glutSwapBuffers();
}
If I don't include the z terms I get a perfect circle but when I include z, then I get 3 dots that's it. What might have happened?
I set the viewport using glviewport(0,0,w,h)
To include z should i do anything to set viewport in z direction?
You see points because you are drawing points with glBegin(GL_POINTS).
Try replacing it by glBegin(GL_LINE_STRIP).
NOTE: when you saw the circle you also drew only points, but drawn close enough to appear as a connected circle.
Also, you may have not setup the depth buffer to accept values in the range z = [-50, 310] that you use. These arguments should be provided as zNear and zFar clipping planes in your gluPerspective, glOrtho() or glFrustum() call.
NOTE: this would explain why with z value you only see a few points: the other points are clipped because they are outside the z-buffer range.
UPDATE AFTER YOU HAVE SHOWN YOUR CODE:
glOrtho(-100*aspectratio,100*aspectratio,-100,100,1,-1); would only allow z-values in the [-1, 1] range, which is why only the three points with z = -1, z = 0 and z = 1 will be drawn (thus 3 points).
Finally, you're probably viewing the spiral from the top, looking directly in the direction of the rotation axis. If you are not using a perspective projection (but an isometric one), the spiral will still show up as a circle. You might want to change your view with gluLookAt().
EXAMPLE OF SETTING UP PERSPECTIVE
The following code is taken from the excellent OpenGL tutorials by NeHe:
glViewport(0, 0, width, height);
glMatrixMode(GL_PROJECTION); // Select The Projection Matrix
glLoadIdentity(); // Reset The Projection Matrix
// Calculate The Aspect Ratio Of The Window
gluPerspective(45.0f,(GLfloat)width/(GLfloat)height,0.1f,100.0f);
glMatrixMode(GL_MODELVIEW); // Select The Modelview Matrix
glLoadIdentity(); // Reset The Modelview Matrix
Then, in your draw loop would look something like this:
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Clear The Screen And The Depth Buffer
glLoadIdentity();
glTranslatef(-1.5f,0.0f,-6.0f); // Move Left 1.5 Units And Into The Screen 6.0
glBegin(GL_TRIANGLES); // Drawing Using Triangles
glVertex3f( 0.0f, 1.0f, 0.0f); // Top
glVertex3f(-1.0f,-1.0f, 0.0f); // Bottom Left
glVertex3f( 1.0f,-1.0f, 0.0f); // Bottom Right
glEnd();
Of course, you should alter this example code your needs.
catchmeifyoutry provides a perfectly capable method, but will not draw a spatially accurate 3D spiral, as any render call using a GL_LINE primitive type will rasterize to fixed pixel width. This means that as you change your perspective / view, the lines will not change width. In order to accomplish this, use a geometry shader in combination with GL_LINE_STRIP_ADJACENCY to create 3D geometry that can be rasterized like any other 3D geometry. (This does require that you use the post fixed-function pipeline however)
I recommended you to try catchmeifyoutry's method first as it will be much simpler. If you are not satisfied, try the method I described. You can use the following post as guidance:
http://prideout.net/blog/?tag=opengl-tron
Here is my Spiral function in C. The points are saved into a list which can be easily drawn by OpenGL (e.g. connect adjacent points in list with GL_LINES).
cx,cy ... spiral centre x and y coordinates
r ... max spiral radius
num_segments ... number of segments the spiral will have
SOME_LIST* UniformSpiralPoints(float cx, float cy, float r, int num_segments)
{
SOME_LIST *sl = newSomeList();
int i;
for(i = 0; i < num_segments; i++)
{
float theta = 2.0f * 3.1415926f * i / num_segments; //the current angle
float x = (r/num_segments)*i * cosf(theta); //the x component
float y = (r/num_segments)*i * sinf(theta); //the y component
//add (x + cx, y + cy) to list sl
}
return sl;
}
An example image with r = 1, num_segments = 1024:
P.S. There is difference in using cos(double) and cosf(float).
You use a float variable for a double function cos.