OpenGL 2D transformations without keeping aspect - opengl

I need to have a 2D layer in my OpenGL application.I have implemented it first using a typical ortho projection like this:
Mat4 ortho =Glm.ortho(0,viewWidth , 0 ,viewHeight);
The 2d worked fine except the fact that when running in different screen sizes the 2d shapes are scaled relatively to a new aspect.That is not what I want (opposite to what usually people need). I need the 2d shapes to get stretched or squeezed according to the new screen size.
I tried not to use the ortho matrix but just an identity.This one works but in such a case I have to use numbers in range 0 -1 to manipulate the objects in the visible frustum area.And I need to use numbers in regular (not normalized ) ranges.So it is sort of forcing me to get back to ortho projection which is problematic because of what already said.
So the question is how do I transform 2d object without perspective staying in the world coordinates system.
UPDATE:
The best example is 2D layers in Adobe AfterEffects. If one changes composition dimension ,2d layers don't get scaled according to new dimensions.That is what I am after.

It's tricky to know how to answer this, because to some degree your requirements are mutually exclusive. You don't want normalised coordinates, you want to use screen coordinates. But by definition, screen coordinates are defined in pixels, and pixels are usually square... So I think you need some form of normalised coordinates, albeit maybe uniformly scaled.
Perhaps what you want is to fix the ratio for width and height in your ortho. That would allow you to address the screen in some kind of pseudo-pixel unit, where one axis is "real" pixels, but the other can be stretched. So instead of height, pass 3/4 of the width for a 4:3 display, or 9/16ths on a 16:9, etc. This will be in units of pixels if the display is the "right" dimension, but will stretch in one dimension only if it's not.
You may need to switch which dimension is "real" pixels depending on the ratio being less or greater than your "optimal" ratio, but it's tricky to know what you're really shooting for here.

Related

Why is the OpenGL projection matrix needlessly complicated?

The following image shows the main values used in calculating the perspective projection matrix in OpenGL. They are labelled "HALFFOV", "RIGHT", "LEFT", "NEAR" AND "NEAR x 2":
Now, as you'll see in the following picture, to figure out the x value after projection supposedly it does 2 x NEAR divided by RIGHT - LEFT. The fact is that 2 x NEAR divided by RIGHT - LEFT is the same as simply doing NEAR / RIGHT. In both cases you're simply doubling, doubling the NEAR, and doubling the RIGHT, so the fraction is the same.
Also, in the 3rd column there are operations where there should be zeroes, for example: RIGHT + LEFT divided by RIGHT - LEFT always ends up being 0 / RIGHT - LEFT, which is always zero.
When the GLM math library makes a perspective projection matrix for me those two that always end up zero are always zero.
Why is it that the matrix is written like this? Are there certain cases for which my assumptions are wrong?
Why is it that the matrix is written like this?
Because a symmetrical, view centered projection is just one of many possibilities. Sometimes you want to skew and/or shift the planes for certain effects or rendering techniques.
Are there certain cases for which my assumptions are wrong?
For example plane parallel shifting the view frustum is required for tiled rendering (not to be confused with a tiled rasterizer) where the image to be rendered is split up into a grid of tiles, each one rendered individually and then merged later. This is needed if the desired output images resolution exceeds the maximum viewport/renderbuffer size limits of the used OpenGL implementation.
Other cases are if you want to simulate tilt-shift photography.
And last but not least a shifted projection matrix is required for stereoscopic rendering targeting a fixed position screen display device, that's viewed using 3D glasses.
(Rendering for headmounted displays requires a slightly different projection setup).

Circular grid of uniform density

How can I generate a circular grid, made of tiles with uniform area/whose vertices are uniformly distributed?
I'll need to apply the Laplacian operator to the grid at each frame of my program.
Applying the Laplacian was easy with a rectangular grid made of rectangular tiles whose locations were specified in cartesian coordinates, since for a tile at (i,j), I knew the positions of its neighboring tiles to be (i-1,j), (i,j-1), (i+1,j), and (i,j+1).
While I'd like to use polar coordinates, I'm not sure whether querying a tile's neighborhood would be as easy.
I'm working in OpenGl, and could either render triangles or points. Triangles seem more efficient (and have the nice effect of filling the area between their vertices), but seem more amenable to cartesian coordinates. Perhaps I could render points and then polar coordinates would work fine?
The other concern is the density of tiles. I want waves traveling on the surface of this mesh to have the same resolution whether they're at the center or not.
So the two main concerns are: generating the mesh in a way that allows for easy querying of a tiles' neighborhood, and in a way that preserves a uniform density distribution of tiles.
I think you're asking for something impossible.
However, this is a technique for remapping a regular square 2D grid into a circle shape with a relatively low amount of warping. It might suffice for your problem.
You might want to have a look at this paper, it has been written to sample spheres but you might be able to adapt it for a circle.
An option can be to use a polar grid with a constant angular step but varying radial steps, so that all cells have the same area, i.e. (R+dR)²-R²=Cst, giving dR as a function of R.
You may want to reduce the anisotropy (some cells becoming very elongated) by changing the number of cells every now and then (f.i. by doubling). This will introduce singularities in the mesh, i.e. cells with five vertices instead of four.
See the figures in https://mathematica.stackexchange.com/questions/78806/ndsolve-and-fem-support-for-non-conformal-meshes-of-a-disk-with-kernel-crash

OpenGL - Render a sphere with fixed pixel radius

I am currently using glutsolidsphere() to render a sphere. Of course, after scaling, the sphere appears to be an ellipsoid.
So is there any way to render a sphere with fixed pixel radius ? I just want to draw a sphere in a certain place (x,y,z) with a certain radius in pixels (eg, r = 10 pixels) and make it sure that its shape will not be affected by modeling transformation.
Transformation such as Rotation, Translation, and Scaling should not affect the way a sphere looks. Remember to scale correctly on all 3 axis by the same value. Or you can just multiply vertices by a constant scalar and that should scale the sphere without distorting it. If you still see distortion, it might be because of your camera (high FOV tends to distort near the edges) or a wrong aspect-ratio (re-sizing an openGL window does not preserve aspect-ratio).
When you scale, you can scale in x, y, and z. If you scale with the same value in each dimension, it will stay a sphere.
If you want to apply a scaling that always gives the same size of the sphere, as measured in pixels, then you have to make a scaling based on the viewport size definition. These are the arguments you gave to glViewport().
For example, when scaling 'x', use factor k/width (where width is taken from glViewport). Choose constant 'k' as you want, depending on the size of the sphere.
It is possible to use glGet() to request the data that was sent with glViewport(), but reading data from OpenGL should be avoided. In worst case, it will wait for the pipeline to flush. A better idea is to remember what was used for glViewport().
You do realize that glut is old and no longer recommended? And that glutsolidsphere is based on deprecated fixed function pipeline OpenGL?

labels in an opengl map application

Short Version
How can I draw short text labels in an OpenGL mapping application without having to manually recompute coordinates as the user zooms in and out?
Long Version
I have an OpenGL-based mapping application where I need to be able to draw data sets with up to about 250k points. Each point can have a short text label, usally about 4 or 5 characters long.
Currently, I do this using a single textue containing all the characters. For each point, I define a quad for each character in its label. So a point with the label "Fred" would have four quads associated with it, and each quad uses texture coordinates into that single texture to draw its corresponding character.
When I draw the map, I draw the map points themselves in map coordinates (e.g., longitude/latitude). Then I compute the position of each point in screen coordinates and update the four corner points for each of that point's label quads, again in screen coordinates. (For instance, if I determine the point is drawn at screen point 100, 150, I could set the quad for the first character in the point's label to be the rectangle starting with left-top point of 105, 155 and having a width of 6 pixels and a height of 12 pixels, as appropriate for the particular character. Then the second character might start at 120, 155, and so on.) Then once all these label character quads are positioned correctly, I draw them using an orthogonal screen projection.
The problem is that the process of updating all of those character quad coordinates is slow, taking about half a second for a particular test data set with 150k points (meaning that, since each label is about four characters long, there are about 150k * [ 4 characters per point] * [ 4 coordinate pairs per character] coordinate pairs that need to be set on each update.
If the map application didn't involve zooming, I would not need to recompute all these coordinates on each refresh. I could just compute the label coordinates once and then simply shift my viewing rectangle to show the right area. But with zooming, I can't see how to make it work without doing coordniate computation, because otherwise the characters will grow huge as you zoom in and tiny as you zoom out.
What I want (and what I understand OpenGL doesn't provide) is a way to tell OpenGL that a quad should be drawn in a fixed screen-coordinate rectangle, but that the top-left position of that rectangle should be a fixed distance from a given point in map coordinate space. So I want both a primitive hierarchy (a given map point is that parent of its label character quads) and the ability to mix two different coordinate systems within this hierarchy.
I'm trying to understand whether there is some magic transformation matrix I can set that will do all this form me, but I can't see how to do it.
The other alternative I've considered is using a shader on each point to handle computing the label character quad coordinates for that point. I haven't worked with shaders before, and I'm just trying to understand (a) if it's possible to use shaders to do this, and (b) whether computing all those points in shader code actually buys me anything over computing them myself. (By the way, I have confirmed that the big bottleneck is computing the quad coordinates, not in uploading the updated coordinates to the GPU. The latter takes a bit of time, but it's the computation, the sheer number of coordinates being updated, that takes up the bulk of that half second.)
(Of course, the other other alternative is to be smarter about which labels need to be drawn in a given view in the first place. But for now I'd like to concentrate on the solution assuming all labels need to be drawn.)
So the basic problem ("because otherwise the characters will grow huge as you zoom in and tiny as you zoom out") is that you are doing calculations in map coordinates rather than screen coordinates? And if you did it in screen coords, this would require more computations? Obviously, any rendering needs to translate from map coordinates to screen coordinates. The problem seems to be that you are translating from map to screen too late. Therefore, rather than doing a single map-to-screen for each point, and then working in screen coords, you are working mostly in map coords, and then translating per-character to screen coords at the very end. And the slow part is that you are working in screen coords, then having to manually translate back to map coords just to tell OpenGL the map coords, and it will convert those back to screen coords! Is that a fair assessment of your problem?
The solution therefore is to push that transformation earlier in your pipeline. However, I can see why it is tricky, because at first glance, OpenGL seems want to do everything in "world coordinates" (for you, map coords), but not in screen coords.
Firstly, I am wondering why you are doing separate coordinate calculations for each character. What font rendering system are you using? Something like FreeType will automatically generate a bitmap image of an entire string, and doesn't require you to work per-character [edit: this isn't quite true; see comments]. You definitely shouldn't need to calculate the map coordinate (or even screen coordinate) for every character. Calculate the screen coordinate for the top-left corner of the label, and have your font rendering system produce the bitmap of the entire label in one go. That should speed things up about fourfold (since you assume 4 characters per label).
Now as for working in screen coords, it may be helpful to learn a bit about shaders. The more you learn about OpenGL, the more you learn that really it isn't a 3D rendering engine at all. It's just a 2D graphics library with some very fast matrix primitives built-in. OpenGL actually works, at the lowest level, in screen coordinates (not pixel coordinates -- it works in normalized screen space, I think from memory from -1 to 1 in both the X and Y axis). The only reason it "feels" like you're working in world coordinates is because of these matrices you have set up.
So I think the reason why you are working in map coords all the way until the end is because it's easiest: OpenGL naturally does the map-to-screen transform for you (using the matrices). You have to change that, because you want to work in screen coords yourself, and therefore you need to make the transformation a long time before OpenGL gets its hands on your data. So when you go to draw a label, you should manually apply the map-to-screen transformation matrix on each point, as follows:
You have a particular point (which needs a label drawn) in map coords.
Apply the map-to-screen matrix to convert the point to screen coords. This probably means multiplying the point by the MODELVIEW and PROJECTION matrices, using the same algorithm that OpenGL does when it's rendering a vertex. So you could either glGet the GL_MODELVIEW_MATRIX and GL_PROJECTION_MATRIX to extract OpenGL's current matrices, or you could manually keep around a copy of the matrix yourself.
Now you have the map label in screen coords, compute the position of the label's text. This is simply adding 5 pixels in the X and Y axis, as you said above. However, remember that you aren't in pixel space, but normalised screen space, so you are working in percentages (add 0.05 units, would add 5% of the screen space, for example). It's probably better not to think in pixels, because then your application will scale to match the resolution. But if you really want to think in pixels, you will have to calculate the pixels-to-units based on the resolution.
Use glPushMatrix to save the current matrix, then glLoadIdentity to set the current matrix to the identity -- tell OpenGL not to transform your vertices. (I think you will have to do this for both the PROJECTION and MODELVIEW matrices.)
Draw your label, in screen coordinates.
So you don't really need to write a shader. You could certainly do this in a shader, and it would certainly make step 2 faster (no need to write your own software matrix multiply code; multiplying matrices on the GPU is extremely fast). But that would be a later optimisation, and a lot of work. I think the above steps will help you work in screen coordinates and avoid having to waste a lot of time just to give OpenGL map coordinates.
Side comment on:
"""
generate a bitmap image of an entire string, and doesn't require you to work per-character
...
Calculate the screen coordinate for the top-left corner of the label, and have your font rendering system produce the bitmap of the entire label in one go. That should speed things up about fourfold (since you assume 4 characters per label).
"""
Freetype or no, you could certainly compute a bitmap image for each label, rather than each character, but that would require one of:
storing thousands of different textures, one for each label
It seems like a bad idea to store that many textures, but maybe it's not.
or
rendering each label, for each point, at each screen update.
this would certainly be too slow.
Just to follow up on the resolution:
I didn't really solve this problem, but I ended up being smarter about when I draw labels in the first place. I was able to quickly determine whether I was about to draw too many characters (i.e., so many characters that on a typical screen with a typical density of points the labels would be too close together to read in a useful way) and then I simply don't label at all. With drawing up to about 5000 characters at a time there isn't a noticeable slowdown recomputing the character coordinates as described above.

Fast plane rotation algorithm?

I am working on an application that detects the most prominent rectangle in an image, then seeks to rotate it so that the bottom left of the rectangle rests at the origin, similar to how IUPR's OSCAR system works. However, once the most prominent rectangle is detected, I am unsure how to take into account the depth component or z-axis, as the rectangle won't always be "head-on". Any examples to further my understanding would be greatly appreciated. Seen below is an example from IUPR's OSCAR system.
alt text http://quito.informatik.uni-kl.de/oscar/oscar.php?serverimage=img_0324.jpg&montage=use
You don't actually need to deal with the 3D information in this case, it's just a mappping function, from one set of coordinates to another.
Look at affine transformations, they're capable of correcting simple skew and perspective effects. You should be able to find code somewhere that will calculate a transform from the 4 points at the corners of your rectangle.
Almost forgot - if "fast" is really important, you could simplify the system to only use simple shear transformations in combination, though that'll have a bad impact on image quality for highly-tilted subjects.
Actually, I think you can get away with something much simpler than Mark's approach.
Once you have the 2D coordinates on the skewed image, re-purpose those coordinates as texture coordinates.
In a renderer, draw a simple rectangle where each corner's vertices are texture mapped to the vertices found on the skewed 2D image (normalized and otherwise transformed to your rendering system's texture coordinate plane).
Now you can rely on hardware (using OpenGL or similar) to do the correction for you, or you can write your own texture mapper:
The aspect ratio will need to be guessed at since we are disposing of the actual 3D info. However, you can get away with just taking the max width and max height of your skewed rectangle.
Perspective Texture Mapping by Chris Hecker