I need to get a slightly 3D representation of a two-dimensional layer of plant cells in OpenGL 2.1 (actually Compatibility profile). It's looking pretty good so far with no transformations:
What you see in the center is a small 3D cube I drew for comparison purposes. It uses the same transformation matrix as all other models. Every cell consists of an extruded plateau (lighter parts) and sloped walls (the shadowy bits). There's a diffuse white light source pointed at the cell from somewhere about the eye.
Now comes the part where I'm stuck. Scaling and translations work just fine, but I can't get 3D rotations of the cell to work. The cube, defined around (0, 0, 0) rotates exactly as expected but the cells show a strange behaviour I haven't managed to explain.
Here's the same model slightly rotated.
First of all, the shadows are different (as expected I'd say). The light source doesn't move. I've tried moving it but it didn't really change much, so that's another problem altogether. What's especially peculiar to me is the way the cells get cut off. The lower left corner has missing pieces. One could say we're looking under that part of the cell, but then the other part of that cell doesn't look quite like expected. Or is the lighting just bad?
I'm looking for a rotation of this only slightly 3D model that would look more pleasing to the user. Would I go about changing the lighting? Mind you there is no way I can use Glu so there's no gluLookAt to instead view my camera around. Would there be another way around though? Creative answers are encouraged. In short, I need a way for a user to navigate around this slightly 3D model, knowing it's mostly 2D, that feels intuitive.
Some more images for context. The application supports rotation by dragging around the screen with the mouse so playing around is easy.
Rotated 90 degrees about the y axis (OK)
Ever so slightly rotated
Transformations:
glLoadIdentity();
glScalef(m_preferences->m_mesh_magnification, m_preferences->m_mesh_magnification, 1.0);
glRotatef(m_totalRotation.x() / 5., 0, 1, 0); // user rotation
glRotatef(m_totalRotation.y() / 5., -1, 0, 0); // user rotation
Body of resizeGL(w, h), responsible for the projection view:
glViewport(0, 0, (GLsizei) w, (GLsizei) h);
glMatrixMode (GL_PROJECTION);
glLoadIdentity();
glOrtho(-((GLdouble) w) / 2, ((GLdouble) w) / 2, ((GLdouble) h) / 2, -((GLdouble) h) / 2, -1.0, 1.0);
//glFrustum(...) if we want a realistic projection
glMatrixMode (GL_MODELVIEW);
Basically I make y point down and have (0, 0) in the middle. The y direction I believe mimicks Qt's default, while the origin's location was a project decision.
EDIT: final result after rotating
glOrtho(-((GLdouble) w) / 2, ((GLdouble) w) / 2, ((GLdouble) h) / 2, -((GLdouble) h) / 2, -1.0, 1.0);
The -1.0, 1.0 are your near and far clipping planes. Anything in front of the near plane or behind the far plane will not be drawn. You'll need to increase those values -- but not much more than you need to, because you'll lose Z-buffer precision.
Related
I have the following problem, when I zoom in on the image. I have not been able to solve it. I am currently developing in Qt with c ++. I have a question about orthogonal projection and perspective projection. I need to zoom without traversing the image. I tried to make the glViewport bigger, but it does not work for me. The xmin, xmax... are the maximum and minimum values for each axis.
void MeshViewer::resizeGL(int width, int height)
{
int side = qMin(width, height);
if ( height == 0 )
height = 1;
glViewport(((GLint)(width - side)/2.0), (GLint)((height -side)/2.0), (GLint)side, (GLint)side);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glOrtho(xmin, xmax, ymin, ymax, zmin, zmax);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}
glViewport specifies the mapping of normalized device coordinates to window coordinates (pixels).
If you want that the entire geometry which is inside the clip space, is mapped to the window, then it has to be:
glViewport(0, 0, width, height)
What the window displays is a frustum, defined by six planes. Normally, these planes are parallel, as in a cube. Anything that lies outside the frustum is not displayed.
"Zoom" may be interpreted, in a generic way, as "see bigger, nearer, more detail".
There are several ways of achieve the zoom effect:
Scale the objects. This works, the flaw is that objects (or parts of them) may lie before the near plane or behind the far plane of the frustum.
Move the camera towards the object. Same matter with near/far planes. Also, take care of moving through the model, you can set a "barrier" (perhaps a box) to prevent the camera moving too deep.
For an orthogonal projection, set left/right/top/bottom planes nearer to the object. This makes the frustum smaller, thus it's normal that some objects get clipped.
For a perspective projection you can do the same trick as with orthogonal. This trick is just to reduce the FOV (field of view) angle. If objects are too far, the perspective effect may be less obvious.
I'm working on interactive scenes for a computer graphics course. I've set up a program which will generate color cubes, and let me rotate them with the keyboard. However they're getting cut open by the near clip plane of my camera:
I've tried to use gluPerspective, but the OpenGL documentation doesn't give any examples of its use. I found it being used in an example program online, and semi-replicated their code:
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective( 65, 1, 0.01, 100 );
glMatrixMode(GL_MODELVIEW);
Any thoughts?
UPDATE:
As suggested in the comments below, I tried using glFrustum instead, with the following code:
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glFrustum( -0.5, 0.5, -0.5, 0.5, 0.1, 100 );
glMatrixMode(GL_MODELVIEW);
Again, there was no difference. Am I not pushing the resulting matrices correctly or something?
Perhaps you need to move your objects a little farther from the Camera. Right now it seems that they are closer than 0.0.
Considering your update "I moved the cubes one whole unit away from the camera, and now as they rotate they get clipped by both the near and the far clip planes" your cubes may be too large for your clipping depth (100 - 0.1). Move cubes away from the camera by 50 and set your clipping planes to 0.1 .. 1000 to make sure everything fits.
If the problem remains we might need to look at your matrices code.
Original Question/Code
I am fine tuning the rendering for a 3D object and attempting to implement a camera following the object using gluLookAt because the object's center y position constantly increases once it reaches it's maximum height. Below is the section of code where I setup the ModelView and Projection matrices:
float diam = std::max(_framesize, _maxNumRows);
float centerX = _framesize / 2.0f;
float centerY = _maxNumRows / 2.0f + _cameraOffset;
float centerZ = 0.0f;
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glFrustum(centerX - diam,
centerX + diam,
centerY - diam,
centerY + diam,
diam,
40 * diam);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
gluLookAt(0., 0., 2. * diam, centerX, centerY, centerZ, 0, 1.0, 0.0);
Currently the object displays very far away and appears to move further back into the screen (-z) and down (-y) until it eventually disappears.
What am I doing wrong? How can I get my surface to appear in the center of the screen, taking up the full view, and the camera moving with the object as it is updated?
Updated Code and Current Issue
This is my current code, which is now putting the object dead center and filling up my window.
float diam = std::max(_framesize, _maxNumRows);
float centerX = _framesize / 2.0f;
float centerY = _maxNumRows / 2.0f + _cameraOffset;
float centerZ = 0.0f;
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(centerX - diam,
centerX,
centerY - diam,
centerY,
1.0,
1.0 + 4 * diam);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
gluLookAt(centerX, _cameraOffset, diam, centerX, centerY, centerZ, 0, 1.0, 0.0);
I still have one problem when the object being viewed starts moving it does not stay perfectly centered. It appears to almost jitter up by a pixel and then down by 2 pixels when it updates. Eventually the object leaves the current view. How can I solve this jitter?
Your problem is with the understanding what the projection does. In your case glFrustum. I think the best way to explain glFrustum is by a picture (I just drew -- by hand). You start of a space called Eye Space. It's the space your vertices are in after they have been transformed by the modelview matrix. This space needs to be transformed to a space called Normalized Device Coordinates space. This happens in a two fold process:
The Eye Space is transformed to Clip Space by the projection (matrix)
The perspective divide {X,Y,Z} = {x,y,z}/w is applied, taking it into Normalized Device Coordinate space.
The visible effect of this is that of kind of a "lens" of OpenGL. In the below picture you can see a green highlighted area (technically it's a 3 volume) in eye space that, is the NDC space backprojected into it. In the upper case the effect of a symmetric frustum, i.e. left = -right, top = -bottom is shown. In the bottom picture an asymmetric frustum, i.e. left ≠ -right, top ≠ -bottom is shown.
Take note, that applying such an asymmetry (by your center offset) will not turn, i.e. rotate your frustum, but skew it. The "camera" however will stay at the origin, still pointing down the -Z axis. Of course the center of image projection will shift, but that's not what you want in your case.
Skewing the frustum like that has applications. Most importantly it's the correct method to implement the different views of left and right eye an a stereoscopic rendering setup.
The answer by Nicol Bolas pretty much tells what you're doing wrong so I'll skip that. You are looking for an solution rather than telling you what is wrong, so let's step right into it.
This is code I use for projection matrix:
glViewport(0, 0, mySize.x, mySize.y);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(fovy, (float)mySize.x/(float)mySize.y, nearPlane, farPlane);
Some words to describe it:
glViewport sets the size and position of display place for openGL inside window. Dunno why, I alsways include this for projection update. If you use it like me, where mySize is 2D vector specifying window dimensions, openGL render region will ocuppy whole window. You should be familiar with 2 next calls and finaly that gluPerspective. First parameter is your "field of view on Y axis". It specifies the angle in degrees how much you will see and I never used anything else than 45. It can be used for zooming though, but I prefer to leave that to camera operating. Second parameter is aspect. It handles that if you render square and your window sizes aren't in 1:1 ratio, it will be still square. Third is near clipping plane, geometry closer than this to camera won't get rendered, same with farPlane but on contrary it sets maximum distance in what geometry gets rendered.
This is code for modelview matrix
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
gluLookAt( camera.GetEye().x,camera.GetEye().y,camera.GetEye().z,
camera.GetLookAt().x,camera.GetLookAt().y,camera.GetLookAt().z,
camera.GetUp().x,camera.GetUp().y,camera.GetUp().z);
And again something you should know: Again, you can use first 2 calls so we skip to gluLookAt. I have camera class that handles all the movement, rotations, things like that. Eye, LookAt and Up are 3D vectors and these 3 are really everything that camera is specified by. Eye is the position of camera, where in space it is. LookAt is the position of object you're looking at or better the point in 3D space at which you're looking because it can be really anywhere not just center object. And if you are worried about what's Up vector, it's really simple. It's vector perpedicular to vector(LookAt-Eye), but becuase there's infinite number of such vectors, you must specify one. If your camera is at (0,0,0) and you are looking at (0,0,-1) and you want to be standing on your legs, up vector will be (0,1,0). If you'd like to stand on your head instead, use (0,-1,0). If you don't get the idea, just write in comment.
As you don't have any camera class, you need to store these 3 vectors separately by yourself. I believe you have something like center of 3D object you're moving. Set that position as LookAt after every update. Also in initialization stage(when you're making the 3D object) choose position of camera and up vector. After every update to object position, update the camera position the same way. If you move your object 1 point up at Y axis, do the same to camera position. The up vectors remains constant if you don't want to rotate camera. And after every such update, call gluLookAt with updated vectors.
For updated post:
I don't really get what's happening without bigger frame of reference (but I don't want to know it anyway). There are few things I get curious about. If center is 3D vector that stores your object position, why are you setting the center of this object to be in right top corner of your window? If it's center, you should have those +diam also in 2nd and 4th parameter of glOrtho, and if things get bad by doing this, you are using wrong names for variables or doing something somewhere before this wrong. You're setting the LookAt position right in your updated post, but I don't find why you are using those parameters for Eye. You should have something more like: centerX, centerY, centerZ-diam as first 3 parameters in gluLookAt. That gives you the camera on the same X and Y position as your object, but you will be looking on it along Z axis from distance diam
The perspective projection matrix generated by glFrustum defines a camera space (the space of vertices that it takes as input) with the camera at the origin. You are trying to create a perspective matrix with a camera that is not at the origin. glFrustum can't do that, so the way you're attempting to do it simply will not work.
There are ways to generate a perspective matrix where the camera is not at the origin. But there's really no point in doing that.
The way a moving camera is generally handled is by simply adding a transform from the world space to the camera space of the perspective projection. This just rotates and translates the world to be relative to the camera. That's the job of gluLookAt. But your parameters to that are wrong too.
The first three values are the world space location of the camera. The next three should be the world-space location that the camera should look at (the position of your object).
I've got some 2D geometry. I want to take some bounding rect around my geometry, and then render a smaller version of it somewhere else on the plane. Here's more or less the code I have to do scaling and translation:
// source and dest are arbitrary rectangles.
float scaleX = dest.width / source.width;
float scaleY = dest.height / source.height;
float translateX = dest.x - source.x;
float translateY = dest.y - source.y;
glScalef(scaleX, scaleY, 0.0);
glTranslatef(translateX, translateY, 0.0);
// Draw geometry in question with its normal verts.
This works exactly as expected for a given dimension when the dest origin is 0. But if the origin for, say, x, is nonzero, the result is still scaled correctly but looks like (?) it's translated to something near zero on that axis anyways-- turns out it's not exactly the same as if dest.x were zero.
Can someone point out something obvious I'm missing?
Thanks!
FINAL UPDATE Per Bahbar's and Marcus's answers below, I did some more experimentation and solved this. Adam Bowen's comment was the tip off. I was missing two critical facts:
I needed to be scaling around the center of the geometry I cared about.
I needed to apply the transforms in the opposite order of the intuition (for me).
The first is kind of obvious in retrospect. But for the latter, for other good programmers/bad mathematicians like me: Turns out my intuition was operating in what the Red Book calls a "Grand, Fixed Coordinate System", in which there is an absolute plane, and your geometry moves around on that plane using transforms. This is OK, but given the nature of the math behind stacking multiple transforms into one matrix, it's the opposite of how things really work (see answers below or Red Book for more). Basically, the transforms are "applied" in "reverse order" to how they appear in code. Here's the final working solution:
// source and dest are arbitrary rectangles.
float scaleX = dest.width / source.width;
float scaleY = dest.height / source.height;
Point sourceCenter = centerPointOfRect(source);
Point destCenter = centerPointOfRect(dest);
glTranslatef(destCenter.x, destCenter.y, 0.0);
glScalef(scaleX, scaleY, 0.0);
glTranslatef(sourceCenter.x * -1.0, sourceCenter.y * -1.0, 0.0);
// Draw geometry in question with its normal verts.
In OpenGL, matrices you specify are multiplied to the right of the existing matrix, and the vertex is on the far right of the expression.
Thus, the last operation you specify are in the coordinate system of the geometry itself.
(The first is usually the view transform, i.e. inverse of your camera's to-world transform.)
Bahbar makes a good point that you need to consider the center point for scaling. (or the pivot point for rotations.) Usually you translate there, rotate/scale, then translate back. (or in general, apply basis transform, the operation, then the inverse). This is called Change of Basis, which you might want to read up on.
Anyway, to get some intuition about how it works, try with some simple values (zero, etc) then alter them slightly (perhaps an animation) and see what happens with the output. Then it's much easier to see what your transforms are actually doing to your geometry.
Update
That the order is "reversed" w.r.t. intuition is rather common among beginner OpenGL-coders. I've been tutoring a computer graphics course and many react in a similar manner. It becomes easier to think about how OpenGL does it if you consider the use of pushmatrix/popmatrix while rendering a tree (scene-graph) of transforms and geometries. Then the current order-of-things becomes rather natural, and the opposite would make it rather difficult to get anything useful done.
Scale, just like Rotate, operates from the origin. so if you scale by half an object that spans the segment [10:20] (on axis X, e.g.), you get [5:10]. The object therefore was scaled, and moved closer to the origin. Exactly what you observed.
This is why you apply Scale first in general (because objects tend to be defined around 0).
So if you want to scale an object around point Center, you can translate the object from Center to the origin, scale there, and translate back.
Side note, if you translate first, and then scale, then your scale is applied to the previous translation, which is why you probably had issues with this method.
I haven't played with OpenGL ES, just a bit with OpenGL.
It sounds like you want to transform from a different position as opposed to the origin, not sure, but can you try to do the transforms and draws that bit within glPushMatrix() and glPopMatrix() ?
e.g.
// source and dest are arbitrary rectangles.
float scaleX = dest.width / source.width;
float scaleY = dest.height / source.height;
float translateX = dest.x - source.x;
float translateY = dest.y - source.y;
glPushMatrix();
glScalef(scaleX, scaleY, 0.0);
glTranslatef(translateX, translateY, 0.0);
// Draw geometry in question with its normal verts.
//as if it were drawn from 0,0
glPopMatrix();
Here's a simple Processing sketch I wrote to illustrate the point:
import processing.opengl.*;
import javax.media.opengl.*;
void setup() {
size(500, 400, OPENGL);
}
void draw() {
background(255);
PGraphicsOpenGL pgl = (PGraphicsOpenGL) g;
GL gl = pgl.beginGL();
gl.glPushMatrix();
//transform the 'pivot'
gl.glTranslatef(100,100,0);
gl.glScalef(10,10,10);
//draw something from the 'pivot'
gl.glColor3f(0, 0.77, 0);
drawTriangle(gl);
gl.glPopMatrix();
//matrix poped, we're back to orginin(0,0,0), continue as normal
gl.glColor3f(0.77, 0, 0);
drawTriangle(gl);
pgl.endGL();
}
void drawTriangle(GL gl){
gl.glBegin(GL.GL_TRIANGLES);
gl.glVertex2i(10, 0);
gl.glVertex2i(0, 20);
gl.glVertex2i(20, 20);
gl.glEnd();
}
Here is an image of the sketch running, the same green triangle is drawn, with translation and scale applied, then the red one, outsie the push/pop 'block', so it is not affected by the transform:
HTH,
George
I have the following OpenGL code in the display function:
glLoadIdentity();
gluLookAt(eyex, eyey, eyez, atx, aty, atz, upx, upy, upz);
// called as: gluLookAt(20, 5, 5, -20, 5, 5, 0, 1, 0);
axis();
glutWireCube (1.);
glFlush ();
axis() draws lines from (0,0,0) to (10,0,0), (0,10,0) and (0,10,0), plus a line from (1,0,0) to (1,3,0).
My reshape function contains the following:
glViewport (0, 0, (GLsizei) w, (GLsizei) h);
glMatrixMode (GL_PROJECTION);
glLoadIdentity ();
gluPerspective(45.0, (GLsizei) w / (GLsizei) h, 1.0, 100.0);
glMatrixMode (GL_MODELVIEW);
This image shows the result of running the program with 1. as the argument to glutWireCube:
As you can see, the cube isn't centered around (0,0,0) as the documentation says it should be:
The cube is centered at the modeling
coordinates origin (...) (source)
If I run the program with 5. as the argument, the cube is displaced even further:
Why is that, and how do I place the cubes around (0,0,0)?
FURTHER INFORMATION
It doesn't matter if I switch the order of axis() and glutWireCube. Surrounding axis() with glPushMatrix() and glPopMatrix() doesn't fix it either.
SOLUTION
I modified gluPerspective to start looking further away from the camera, and now the Z-buffering works properly, so it is clear that the cubes are placed around the origin.
Are you sure axis does not mess with the view matrix ?
What happens if you call it after the drawing of the cube ?
Edit to add:
Actually... Looking at the picture closer, it looks like it might be centered at the origin.
The center of the cube seems to align exactly with the intersection of the 3 axes. The only thing that looks suspicious is that the red line does not write over the white edge. do you have Z-buffering properly set up ?
It might be right, I think it's hard to determine due to the perspective ... But I guess it isn't from staring a bit more at it.
To quickly rule out that axis() isn't modifying the model view matrix, surround the call with matrix push/pops:
glPushMatrix();
axis();
glPopMatrix();
Things to investigate/check:
Is this the entire window? It seems odd that the view is down in one corner.
Does it help if you add an increasing rotation before the rendering? That can make it easier to determine the perspective, by giving more clues.
You can also try moving the "camera" around, by changing the arguments to gluLookAt() dynamically.