# OpenGL matrix/coordinates?

This topic is 1242 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

To preface, I am using OpenTK and C#. However, I don't think that deters the issue from being something simple to how I am calling OpenGL methods. I don't understand some of the setup stuff, it's mostly pieced together code from other examples until I found something that worked somewhat.

Here is my routine for setting up OpenGL:

public bool Initialize(IntPtr Handle, Size ScreenSize)
{
//stuff to set in case of GDI
handle = Handle;
screensize = ScreenSize;
bmp = new System.Drawing.Bitmap (screensize.Width, screensize.Height);

//setup the initial scales
if ((screensize.Width != 1000) && (screensize.Height != 600))
{
scalewidth = 1000 / screensize.Width;
scaleheight = 600 / screensize.Height;
}

if (OpenTK.Configuration.RunningOnAndroid)
{
//
return true;
}
else
{
//video card name
glRenderer = GL.GetString (StringName.Renderer);
//what version of OpenGL do we have?
glVersionStr = GL.GetString (StringName.Version);
if (glVersionStr.Length < 3)
return false;

glVersion = new Version (int.Parse (GLVersionStr [0].ToString ()), int.Parse (GLVersionStr [2].ToString ()));
//glVersion = new Version (int.Parse (glVersionStr [0].ToString()), int.Parse (glVersionStr [2]).ToString());
// Set viewport
if (GLFunctions.Viewport (glVersion))
GL.Viewport (0, 0, screensize.Width, screensize.Height);
else
return false; //can't use a viewport, default to GDI

//we now have successfull OpenGL window/context we can use
// Set rendering options
GL.MatrixMode (MatrixMode.Projection);

GL.Enable (EnableCap.LineSmooth);
GL.Enable (EnableCap.PointSmooth);

GL.Hint (HintTarget.LineSmoothHint, HintMode.Nicest);
GL.Hint (HintTarget.PointSmoothHint, HintMode.Nicest);
GL.Hint (HintTarget.PolygonSmoothHint, HintMode.Nicest);
GL.Hint (HintTarget.PerspectiveCorrectionHint, HintMode.Nicest);

// 3D options
GL.CullFace(CullFaceMode.Front);
GL.Enable(EnableCap.Multisample);
GL.Enable(EnableCap.CullFace);

// Enable blending
GL.Enable(EnableCap.Blend);
GL.BlendFunc(BlendingFactorSrc.SrcAlpha, BlendingFactorDest.OneMinusSrcAlpha);

//without the next two lines we can't see anything
ProjectionSet(Vector3d.Zero);
ModelView_Set(Vector3d.Zero, Vector3d.Zero, Vector3d.Zero, 0, true);

return true;
}
}

private void ProjectionSet(Vector3d renderLocation)
{
// Create a perspective frustrum
Matrix4d projection = Matrix4d.CreatePerspectiveFieldOfView(MathHelper.DegreesToRadians(45), 1000.0 / 600.0, 1.0, 2000.0);

if (renderLocation != Vector3d.Zero)
{
// Move zero point for rendering to upper left corner
projection *= Matrix4d.CreateTranslation(-1, 1, 0);

// Translate rendering point to the specified location
projection *= Matrix4d.CreateTranslation(_3D_ProjectionSpace_NormalizeVector(new Vector3d(renderLocation.X, renderLocation.Y, 0)));
}

GL.MatrixMode(MatrixMode.Projection);
}

public void ModelView_Set(Vector3d cameraLocation, Vector3d cameraRotation, Vector3d cameraOffset, double zoom, bool activateMatrix)
{
// Rotate world to get the correct axes in 3D (X going right, Y going down)

// Rotate camera

// Offset camera
modelview *= Matrix4d.CreateTranslation(cameraOffset);

// Zoom
if (zoom != 0)
modelview *= Matrix4d.Scale(zoom);

// Set camera with fixed zoom to make the 1000x600 frame match the 1000x600 pixels
modelview *= Matrix4d.LookAt(new Vector3d(-cameraLocation.X, -cameraLocation.Y, cameraLocation.Z + (-724)), Vector3d.UnitZ, Vector3d.UnitY);

if (activateMatrix)
ModelView_Activate();
}

/// <summary>
/// Activates the model view
/// </summary>
public void ModelView_Activate()
{
GL.MatrixMode(MatrixMode.Modelview);
}

Now, I create a bitmap with the text to be drawn to the screen. Then I create a texture and bind it OpenGL. I then go to display that texture which semi works:

private void DrawImage(Image image, int X, int Y, int Z, int Width, int Height)
{

GL.Enable(EnableCap.Texture2D);
if (image.GenerateTexture)
{
{
GL.Disable (EnableCap.Texture2D);
return;
}
}

// Save current matrix
//GL.PushMatrix();

//forget the values I passed and use hardcoded for testing
GL.Color4(1F, 1F, 1F, 1F);
GL.BindTexture (TextureTarget.Texture2D, image.Texture);
GL.TexCoord2(0.0f, 0.0f);
GL.Vertex3(0, 0, 0); //TOP-LEFT
GL.TexCoord2(1.0f, 0.0f);
GL.Vertex3(1000, 0, 0); //TOP-RIGHT
GL.TexCoord2(1.0f, 1.0f);
GL.Vertex3(1000, 300, 0); //BOTTOM-RIGHT
GL.TexCoord2(0.0f, 1.0f);
GL.Vertex3(0, 300, 0); //BOTTOM-LEFT
GL.End();

// Restore matrix
//GL.PopMatrix();

}

As you can see, the GL.Vertex3 calls are outside the range of -1 to 1. For some reason this is how I can display the texture. However it shows up in the bottom right quadrant of the screen. Changing the Vertex3's x axis to anything negative (thinking -1 would be left of screen/view) completely hides the texture. Subtle trials like -0.1 don't change the location either.

This should be at Top left, 1000 wide, 300 down. I can't seem to figure this out...

[attachment=23844:opengl.png]

##### Share on other sites

I don't understand some of the setup stuff, it's mostly pieced together code from other examples until I found something that worked somewhat.

Stop here, delete your project, look for tutorials and start over again. This time concentrate on understanding the stuff you are using and why it does/doesn't works this way.

It is the most safe and eventually quickest way to get into something new. Building your project on something which magically works sometimes, without knowing why it works at all .. will often end at the point , where you can't figure out a show-stopper (a bug, which ruins your whole project).

My first really big project ended this way, it was a pretty cool learning experience, still it hurts a lot if you consider the progress made .

##### Share on other sites

I went ahead and stripped everything down. I then followed some examples and tutorials and have some triangles rendering to the screen.

I am calling this to Initialize OpenGL:

GL.Viewport (0, 0, screensize.Width, screensize.Height);
GL.Enable(EnableCap.DepthTest);
GL.Enable(EnableCap.Texture2D);

Matrix4 modelview = Matrix4.LookAt(Vector3.Zero, Vector3.UnitZ, Vector3.UnitY);
GL.MatrixMode(MatrixMode.Modelview);
GL.LoadMatrix(ref modelview);

I am then testing this by drawing a large triangle, then a small one

//large
GL.Color4 (System.Drawing.Color.Yellow);
GL.Begin(PrimitiveType.Triangles);
GL.Vertex3(-1.0f, -1.0f, 4.0f);
GL.Vertex3(1.0f, -1.0f, 4.0f);
GL.Vertex3(0.0f, 1.0f, 4.0f);
GL.End();

//small
GL.Color4 (System.Drawing.Color.Blue);
GL.Begin(PrimitiveType.Triangles);
GL.Vertex3(0.5f, -0.5f, 4.0f); //bottom left
GL.Vertex3(0.0f, 1.0f, 4.0f); //top
GL.Vertex3(-0.5f, -0.5f, 4.0f); //bottom right
GL.End();

but only the large one is drawn (the small should be drawn on top of the large). If I move the "small" triangle code above the large, I see both triangles. Is the rendering/drawing order reversed for OpenGL or is it something I did wrong?

EDIT: Turns out I was a little hasty with my clicking. This is because of the

GL.Enable(EnableCap.DepthTest);
I thought depth testing was needed in order to use the z-axis for when I need 3d? Edited by detlion1643

##### Share on other sites

OpenGL is always 3d....... there is always depth your triangles have a depth of 4.0.

##### Share on other sites

I was merely talking about why the first triangle in code wasn't drawn first, then the second in code drawn on top of the first. Both use the same depth of 4.0.

In fact, it seems like the initial -1 -> 1 coordinate system isn't working how I thought it would. Here is code that I trialed and errored to get right:

//negative y = down
//negative x = right
//negative z = closer to camera, less than 1 is invisible
//the following x, y, and z coordinates fill the screen on the initial screensize
GL.Vertex3( -1.38f, -0.828f, 2.0f);    // bottom right
GL.Color3 (System.Drawing.Color.Green);
GL.Vertex3( 1.38f, -0.828f, 2.0f);    // bottom left
GL.Color3 (System.Drawing.Color.Red);
GL.Vertex3( 1.38f, 0.828, 2.0f);    // top left
GL.Color3 (System.Drawing.Color.DarkOrange);
GL.Vertex3( -1.38f, 0.828f, 2.0f);    // top right
GL.End ();
I know the depth is 2.0f, but even at 1.0f using -1, 1 for x/y values fill more than the screen (as 0.8 values fill more than the screen, 0.5 fill less than the screen).

Here is my resize code:

GL.Viewport(Left, Top, Width, Height);
//Matrix4 projection = Matrix4.CreatePerspectiveFieldOfView((float)Math.PI / 4, Width / (float)Height, 0.5f, 64.0f);
Matrix4d projection = Matrix4d.CreatePerspectiveFieldOfView(MathHelper.DegreesToRadians(45), Width / (float)Height, 1.0, 1000.0);
GL.MatrixMode(MatrixMode.Projection);
GL.LoadMatrix(ref projection);

Should I  be concerned about my starting point. I am going to have to calculate pixel coordinates based on a 1000x600 initial screensize in order to render my controls. For example, a control placed X=0, Y=0, W=500, H=300 would be calculated based on the above starting point. So the left side would be at 1.38f, the right side at 0, the top at 0.828 and the bottom at 0.

Doesn't this sound overly complex?

##### Share on other sites

I skipped over your initial problem. If you are trying to render 2D with openGL  You dont want persepctive (which implies a 3D world) you want orthographic.

Matrix4.____Ortho____
Should be a function something like that. Depth will still matter but you can work in 2D. Ortho(0,screenwidth, 0, screenheight)  <-- allows you to call glVertex3f() with 2d pixel coordinates + some z-depth.

With Ortho there is no perspective division to warp stuff away from the camera. The z value doesnt effect perspective, the input x,y  will be the output x,y

• 10
• 12
• 10
• 10
• 11
• ### Similar Content

• Good Evening,
I want to make a 2D game which involves displaying some debug information. Especially for collision, enemy sights and so on ...
First of I was thinking about all those shapes which I need will need for debugging purposes: circles, rectangles, lines, polygons.
I am really stucked right now because of the fundamental question:
Where do I store my vertices positions for each line (object)? Currently I am not using a model matrix because I am using orthographic projection and set the final position within the VBO. That means that if I add a new line I would have to expand the "points" array and re-upload (recall glBufferData) it every time. The other method would be to use a model matrix and a fixed vbo for a line but it would be also messy to exactly create a line from (0,0) to (100,20) calculating the rotation and scale to make it fit.
If I proceed with option 1 "updating the array each frame" I was thinking of having 4 draw calls every frame for the lines vao, polygons vao and so on.
In addition to that I am planning to use some sort of ECS based architecture. So the other question would be:
Should I treat those debug objects as entities/components?
For me it would make sense to treat them as entities but that's creates a new issue with the previous array approach because it would have for example a transform and render component. A special render component for debug objects (no texture etc) ... For me the transform component is also just a matrix but how would I then define a line?
Treating them as components would'nt be a good idea in my eyes because then I would always need an entity. Well entity is just an id !? So maybe its a component?
Regards,
LifeArtist
• By QQemka
Hello. I am coding a small thingy in my spare time. All i want to achieve is to load a heightmap (as the lowest possible walking terrain), some static meshes (elements of the environment) and a dynamic character (meaning i can move, collide with heightmap/static meshes and hold a varying item in a hand ). Got a bunch of questions, or rather problems i can't find solution to myself. Nearly all are deal with graphics/gpu, not the coding part. My c++ is on high enough level.
Let's go:
Heightmap - i obviously want it to be textured, size is hardcoded to 256x256 squares. I can't have one huge texture stretched over entire terrain cause every pixel would be enormous. Thats why i decided to use 2 specified textures. First will be a tileset consisting of 16 square tiles (u v range from 0 to 0.25 for first tile and so on) and second a 256x256 buffer with 0-15 value representing index of the tile from tileset for every heigtmap square. Problem is, how do i blend the edges nicely and make some computationally cheap changes so its not obvious there are only 16 tiles? Is it possible to generate such terrain with some existing program?
Collisions - i want to use bounding sphere and aabb. But should i store them for a model or entity instance? Meaning i have 20 same trees spawned using the same tree model, but every entity got its own transformation (position, scale etc). Storing collision component per instance grats faster access + is precalculated and transformed (takes additional memory, but who cares?), so i stick with this, right? What should i do if object is dynamically rotated? The aabb is no longer aligned and calculating per vertex min/max everytime object rotates/scales is pretty expensive, right?
Drawing aabb - problem similar to above (storing aabb data per instance or model). This time in my opinion per model is enough since every instance also does not have own vertex buffer but uses the shared one (so 20 trees share reference to one tree model). So rendering aabb is about taking the model's aabb, transforming with instance matrix and voila. What about aabb vertex buffer (this is more of a cosmetic question, just curious, bumped onto it in time of writing this). Is it better to make it as 8 points and index buffer (12 lines), or only 2 vertices with min/max x/y/z and having the shaders dynamically generate 6 other vertices and draw the box? Or maybe there should be just ONE 1x1x1 cube box template moved/scaled per entity?
What if one model got a diffuse texture and a normal map, and other has only diffuse? Should i pass some bool flag to shader with that info, or just assume that my game supports only diffuse maps without fancy stuff?
There were several more but i forgot/solved them at time of writing
• By RenanRR
Hi All,
I'm reading the tutorials from learnOpengl site (nice site) and I'm having a question on the camera (https://learnopengl.com/Getting-started/Camera).
I always saw the camera being manipulated with the lookat, but in tutorial I saw the camera being changed through the MVP arrays, which do not seem to be camera, but rather the scene that changes:
#version 330 core layout (location = 0) in vec3 aPos; layout (location = 1) in vec2 aTexCoord; out vec2 TexCoord; uniform mat4 model; uniform mat4 view; uniform mat4 projection; void main() { gl_Position = projection * view * model * vec4(aPos, 1.0f); TexCoord = vec2(aTexCoord.x, aTexCoord.y); } then, the matrix manipulated:
..... glm::mat4 projection = glm::perspective(glm::radians(fov), (float)SCR_WIDTH / (float)SCR_HEIGHT, 0.1f, 100.0f); ourShader.setMat4("projection", projection); .... glm::mat4 view = glm::lookAt(cameraPos, cameraPos + cameraFront, cameraUp); ourShader.setMat4("view", view); .... model = glm::rotate(model, glm::radians(angle), glm::vec3(1.0f, 0.3f, 0.5f)); ourShader.setMat4("model", model);
So, some doubts:
- Why use it like that?
- Is it okay to manipulate the camera that way?
-in this way, are not the vertex's positions that changes instead of the camera?
- I need to pass MVP to all shaders of object in my scenes ?

What it seems, is that the camera stands still and the scenery that changes...
it's right?

Thank you

• Sampling a floating point texture where the alpha channel holds 4-bytes of packed data into the float. I don't know how to cast the raw memory to treat it as an integer so I can perform bit-shifting operations.

int rgbValue = int(textureSample.w);//4 bytes of data packed as color
// algorithm might not be correct and endianness might need switching.
vec3 extractedData = vec3(  rgbValue & 0xFF000000,  (rgbValue << 8) & 0xFF000000, (rgbValue << 16) & 0xFF000000);
extractedData /= 255.0f;

• While writing a simple renderer using OpenGL, I faced an issue with the glGetUniformLocation function. For some reason, the location is coming to be -1.
Anyone has any idea .. what should I do?