Aspect ratio of drawn quad messed up after rotating When I draw a quad that is rotating the aspect ratio of the quad gets messed up and the size changes. Gif of what is happening I am confident it has something to do with the way I calculate the size because that is relative to the width and height of the screen, I just don't know why the aspect ratio would change since the aspect ratio of the screen doesn't change. Code of transformationMatrix creation Matrix4f matrix Maths.createTransformationMatrix( new Vector2f( gui.getPosition().getX() Display.getWidth() 2 1 gui.getSize().getX() Display.getWidth(), gui.getPosition().getY() Display.getHeight() 2 1 gui.getSize().getY() Display.getHeight() ), gui.getRotation() ,new Vector2f( gui.getSize().getX() Display.getWidth(), gui.getSize().getY() Display.getHeight() ) ) shader.loadTransformation(matrix) The x size, y size, x position and y position are in pixels, if you put in 1600 pixels for x position and the screen is 1600 pixels wide it will fill the whole screen. The calculation that is done here will translate those sizes to a value that the shaders will display on the screen. I had tried calculating the sizes in a different way gui.getSize().getX() (float) (Display.getWidth() Math.abs(Math.cos((Math.toRadians(gui.getRotation())))) Display.getHeight() Math.abs(Math.sin((Math.toRadians(gui.getRotation()))))), but this does not work at all, my thought process was that if it is sideways it should use Display.getHeight to calculate the x size and if it is vertical it should use Display.getWidth. This does work for 0, 90, 180 and 270 degrees rotation, but in between it gets smaller and weird. Of course I've also done this for the x position but then cos and sin switched around. video of this method And this is the createTransformationMatrix method public static Matrix4f createTransformationMatrix(Vector2f translation, float rotation, Vector2f scale) Matrix4f matrix new Matrix4f() matrix.setIdentity() Matrix4f.translate(translation, matrix, matrix) Matrix4f.rotate((float) Math.toRadians(rotation), new Vector3f(0, 0, 1), matrix, matrix) Matrix4f.scale(new Vector3f(scale.x, scale.y, 1f), matrix, matrix) return matrix


Is there a way to get what pixel is being processed within the fragment shader? In OpenGL, a fragment shader goes through each pixel, right? So is it possible (within the shader itself) to get what pixel it is processing and color each specific pixel?


How can I find the location of OpenGL object after rotation? I have a rotating object, a cube, which I rotate in OpenGL as follows gl.glPushMatrix() gl.glTranslatef(400.0f, 300.0f, 1300.0f) gl.glRotatef(m x, 4.0f, 0.0f, 0.0f) gl.glRotatef(m y, 0.0f, 4.0f, 0.0f) gl.glRotatef(m z, 0.0f, 0.0f, 42.0f) gl.glCallList( shapeNumber) cube 2 gl.glPopMatrix() (m x, m y, and m z are the change in the rotation each frame.) I want to detect a collision between the camera and that rotating object, and to do that I need to get the coordinates of the rotated object in real time. How can I accomplish that?


Converting 3D coordinates to 2D and back? I'm wondering if there is a simple way to convert 3D coordinates to 2D coordinates. Also, if it's possible, to convert in the reverse direction. I'm using OpenGL(GLUT) in my C project. I am also using SFML for the 2D information (sprites text etc.) I found out that I can use gluProject(), but I have no idea how to use this. I'm asking for a simple example of using gluProject() or another example to convert 3D coordinates (such as from the player) to 2D coordinates. If I can't get the simple process I'm confident that I can figure out the rest.


How can I place a ProgressBar in Android using Cocos 2d? I want to place a horizontal progress bar in my Android application and I want to change its progress color. I used the following code, but the progress bar is not being displayed. CCProgressTimer progressBar CCProgressTimer.progress("progressbar.png") progressBar.setType(kCCProgressTimerTypeHorizontalBarLR) progressBar.setScale(5) progressBar.setAnchorPoint(CGPoint.ccp(0, 0)) progressBar.setPosition(CGPoint.ccp(0,0)) addChild(progressBar)


does glBindAttribLocation silently ignore names not found in a shader? Does glBindAttribLocation silently ignore names that are not found? For example, in a shader Some vertex shader in vec3 position in vec3 normal ... And in some set up code While setting up shader GLuint program glCreateProgram() glBindAttribLocation(program, 0, "position") glBindAttribLocation(program, 1, "normal") glBindAttribLocation(program, 2, "color") What about this one? glLinkProgram(program)


Replace glTranslatef and glRotatef with matrixes I'm not an opengl expert, and, as a novice, I prefer to practice a little bit with the old opengl just to be sure to understand correctly the basic concept of computer graphics before deal with shaders and modern opengl (3.x). I don't want to start a flame with this so I'll go through my question. I just know that what I'm using is deprecated. What I wanto to render is this and I'm drawing it using this piece of code draw grid drawGrid(10, 1) draw a teapot glPushMatrix() glTranslatef(modelPosition 0 , modelPosition 1 , modelPosition 2 ) glRotatef(modelAngle 0 , 1, 0, 0) glRotatef(modelAngle 1 , 0, 1, 0) glRotatef(modelAngle 2 , 0, 0, 1) drawAxis(4) drawTeapot() glPopMatrix() Now, I'd like to replace the last glTranslatef and glRotatef with matrixes, and I'm doing in this way Matrix4 matrixModel matrixModel.identity() matrixModel.translate(modelPosition 0 , modelPosition 1 , modelPosition 2 ) matrixModel.rotateX(modelAngle 0 ) matrixModel.rotateY(modelAngle 1 ) matrixModel.rotateZ(modelAngle 2 ) glLoadMatrixf( matrixModel.getTranspose()) And I don't see anymore the teapot. So I thought that this matrixModel is not complete because it is only the model matrix and I need a modelview so I have to multiply it with the projection matrix but.. this is what I get where am I wrong?


What is a VAO in Opengl? i've just started out with Opengl, and i've got to know what Vertex Buffer Objects are, but i really don't understand what VAOs are. Can someone help me?


How can I draw the depth value in GLSL? I want to draw the depth buffer in the fragment shader, I do this Vertex shader varying vec4 position gl Position gl ModelViewProjectionMatrix gl Vertex position gl ModelViewProjectionMatrix gl Vertex Fragment shader float depth ((position .z position .w) 1.0) 0.5 gl FragColor vec4(depth, depth, depth, 1.0) But all I print is white, what am I doing wrong?


Restoring projection matrix I am learning to use FBOs and one of the things that I need to do when rendering something onto user defined FBO, I have to setup the projection, modelview and viewport for it. Once I am done rendering to the FBO, I need to restore these matrices. I found glPushAttrib(GL VIEWPORT BIT) glPopAttrib() to restore the viewport to its old state. Is there a way to restore the projection and modelview matrix to whatever it was earlier ? Tech C OpenGL Thanks!


How to scale to fit OGL viewport to GLFW window? Say my window is 1280x720. I want to render my stuff to lower resolution and then stretch it to window. I've tried this glViewport(0, 0, 1280 2, 720 2) When I call glViewport and pass lesser width and height than window, I get all my OpenGL rendering in left bottom 1 4 of window. I need to scale it (linear filtering preferably) back to window size so I would get a pixelated effect. I wonder if there is such possibility within glad glfw API.


How to render portals in OpenGL? I am making RPG in OpenGl and I need to make some portals. How should I render it if I want to see through the portal on the other side?


GL INVALID OPERATION in glGenerateMipmap(incomplete cube map) I'm trying to learn OpenGL and i'm using SOIL to load images. I have the following piece of code GLuint texID 0 bool loadCubeMap(const char baseFileName) glActiveTexture(GL TEXTURE0) glGenTextures(1, amp texID) glBindTexture(GL TEXTURE CUBE MAP, texID) const char suffixes "posx", "negx", "posy", "negy", "posz", "negz" GLuint targets GL TEXTURE CUBE MAP POSITIVE X, GL TEXTURE CUBE MAP NEGATIVE X, GL TEXTURE CUBE MAP POSITIVE Y, GL TEXTURE CUBE MAP NEGATIVE Y, GL TEXTURE CUBE MAP POSITIVE Z, GL TEXTURE CUBE MAP NEGATIVE Z for (int i 0 i lt 6 i ) int width, height std string fileName std string(baseFileName) " " suffixes i ".png" std cout lt lt "Loading " lt lt fileName lt lt std endl unsigned char image SOIL load image(fileName.c str(), amp width, amp height, 0, SOIL LOAD RGB) if (!image) std cerr lt lt FUNCTION lt lt " cannot load image " lt lt fileName lt lt " (" lt lt SOIL last result() lt lt ")" lt lt std endl return false glTexImage2D(GL TEXTURE 2D, 0, GL RGB, width, height, 0, GL RGB, GL UNSIGNED BYTE, image) SOIL free image data(image) glTexParameteri(GL TEXTURE CUBE MAP, GL TEXTURE MAG FILTER, GL LINEAR) glTexParameteri(GL TEXTURE CUBE MAP, GL TEXTURE MIN FILTER, GL LINEAR MIPMAP LINEAR) glTexParameteri(GL TEXTURE CUBE MAP, GL TEXTURE WRAP S, GL CLAMP TO EDGE) glTexParameteri(GL TEXTURE CUBE MAP, GL TEXTURE WRAP T, GL CLAMP TO EDGE) glTexParameteri(GL TEXTURE CUBE MAP, GL TEXTURE WRAP R, GL CLAMP TO EDGE) glGenerateMipmap(GL TEXTURE CUBE MAP) glBindTexture(GL TEXTURE CUBE MAP, 0) return true When i call this, the images load successfully, but then i get an error in console OGL DEBUG message lt 1 gt 'API' reported 'Error' with 'High' severity GL INVALID OPERATION in glGenerateMipmap(incomplete cube map) BACKTRACE and no cubemap is displaying at all. Do you see any mistake in this code?


OpenGL fovx question To boil my question down to the simplest form, I fear I am oversimplifying how mat4 perspective works. I am using mat4.perspective(45, 2, 0.1, 1000.0) (the binding is WebGL fwiw). With a fovy of 45, and an aspect ratio of 2, I expect to have a fovx of 90. Thus, if I position my camera at (0, 0, 50), looking towards the origin, I expect to see a cube positioned at (50, 0, 0) (45 degrees) right at the very periphery of my screen, half on, half off,. Instead, a cube at (50, 0, 0) is totally off screen, and my actually periphery occurs at about (41.1, 0, 0). What am I missing here? Thanks, nick


How do I create good looking plasma explosion effects? Is this just a billboard quad with a bloom shader?


Most efficient way to draw large number of the same objects, but with different transforms I'd like to draw a large number (multiple thousands) of simple meshes (each maybe... a maximum of 50 triangles, but even that is a very large upper bound), all of which are exactly the same. As a simple brute force way, right now I'm just doing thousands of draw calls, where I just change the transformation matrices that the shaders need and then draw the same objects again. Of course this is hideously slow, since (I'm guessing) there are too many draw calls for the driver and my PC to handle efficiently. What can I do to make it faster?


Efficient Rendering for multiple light sources I'm building a 3D rendering engine using C and OpenGL. Right now, I've added support for multiple light sources in my GLSL shaders, but I've hit a bit of a bump for my rendering methods. I'm worried about my engines performance if it has to render a lot of objects for a lot of light sources. The straight forward approach would be something like this for every object to be rendered closestLights for every light in the scene if (light closer than all lights in closestLights) swap furthest light from closestLights with current light loadLightSourcesToShader(closestLights) renderObject(object) However, I'm afraid the performance of this rendering loop will degrade quickly since when either the amount of lights or the amount of objects increases, the amount of calculations will rise even quicker. 1) Is there any way to circumvent this? 2) How is this implemented in 'real' engines? 3) How can I find the closest K lightsources to an object efficiently? I've heard about kd trees and octrees, but I feel like building a tree everytime I render is probably worse than what I'm thinking about doing right now. 4) I could keep an octree and a kd tree for every object (which keeps track of all other objects), which when using (smart) pointers, could be quite efficient in terms of time (but not space?). Is this a good approach? I know the saying 'Premature optimization is the root of all evil', but I'm pretty sure this WILL become a problem when a game program reaches a certain complexity size.


How many OpenGL programs should I use to render multiple objects? My scene has multiple objects in it. (Let's say 3 cubes, 1 cylinder, 8 spheres.) I assume I should create a vertex shader for each. How many programs should I have? Alternatives One program per object One program for all cubes and another for all spheres (assuming they use the same shaders) One large program for everything What is the correct approach?


What advantages does multisampling have over supersampling? I never really fully understood this, or found an article which explained all the steps in a friendly way. I'll start with what I do know already (which I hope do not contain misconceptions). I'm pretty sure allocating a multi sampled frame buffer requires as many times the memory (of a regular buffer) as the number of samples (N). This makes sense because each pixel may be sampled up to N times. During rasterization, the GPU generates a fragment for the MS frame buffer by testing if each sample is inside of the geometry being drawn. This is what provides edge anti aliasing. Each sample produces a fragment. I'm unsure about what occurs when all samples of a pixel are inside the geometry. How many fragments are generated? Is this configurable? What if I want to sample the "inside" pixels 4 times, and the edge pixels 16 times? This would require a 16x MS frame buffer. Are there other differences? It seems like if the fragment shader is run once on each sample then we are left with something not much different from basic supersampling with the exception of jittered sample locations. Actually, I'm also a bit unsure about what a frogment really is. It seems like a fragment shader gets (can get) executed more than once per pixel in a multi sampled scene, however this doesn't seem to necessarily mean that a fragment is more related to the sample than the pixel. Is a fragment best thought of as a sample, a pixel, or something else?


Can you sync screen update on vertical retrace with OpenGL? In OpenGL, is there a way to ensure I get exactly, no more nor less, 60 (or whatever rate my monitor is set for) frames per second? Of course given that the new frame can be calculated in less than 1 60 second. I was thinking Windows more than Linux or Mac OSX, even though it is interesting to keep an eye on portability.


Understanding how OpenGL blending works I am attempting to understand how OpenGL (ES) blending works. I am finding it difficult to understand the documentation and how the results of glBlendFunc and glBlendEquation effect the final pixel that is written. Do the source and destination out of glBlendFunc get added together with GL FUNC ADD by default? This seems wrong because "basic" blending of GL ONE, GL ONE would output 2,2,2,2 then (Source giving 1,1,1,1 and dest giving 1,1,1,1). I have written the following pseudo code, what have I got wrong? struct colour float r, g, b, a colour blend factor( GLenum factor, colour source, colour destination, colour blend colour ) colour colour factor float i min( source.a, 1 destination.a ) From http www.khronos.org opengles sdk docs man xhtml glBlendFunc.xml switch( factor ) case GL ZERO colour factor 0, 0, 0, 0 break case GL ONE colour factor 1, 1, 1, 1 break case GL SRC COLOR colour factor source break case GL ONE MINUS SRC COLOR colour factor 1 source.r, 1 source.g, 1 source.b, 1 source.a break ... return colour factor colour blend( colour amp source, colour destination, GLenum source factor, from glBlendFunc GLenum destination factor, from glBlendFunc colour blend colour, from glBlendColor GLenum blend equation from glBlendEquation ) colour source colour blend factor( source factor, source, destination, blend colour ) colour destination colour blend factor( destination factor, source, destination, blend colour ) colour output From http www.khronos.org opengles sdk docs man xhtml glBlendEquation.xml switch( blend equation ) case GL FUNC ADD output add( mul( source, source colour ), mul( destination, destination colour ) ) case GL FUNC SUBTRACT output sub( mul( source, source colour ), mul( destination, destination colour ) ) case GL FUNC REVERSE SUBTRACT output sub( mul( destination, destination colour ), mul( source, source colour ) ) return output void do pixel() colour final colour Blending if( enable blending ) final colour blend( current colour output, framebuffer pixel , ... ) else final colour current colour output Thanks!


How to achieve cavalier projection using OpenGL fixed pipeline? I want to make a quick demo program showing a cube, or a user loaded model, rotating in screen rendered with one of three projections perspective, isometric and cavalier. Using the fixed pipeline, how can I build a projection matrix for cavalier projection? I think I can start with the orthographic projection matrix and then tweak the values, by eye, until I get the z of the vertices go to the right and up as farther the z is. I want the lines parallel to the z axis rendered as vertical lines 45 degrees rotated to the right.


Positioning a texture inside a 3D object with GLSL I have a 3D object in my scene and a texture that is the same size of the screen (a render to texture). Is there a way to make the object act like a "mask" for the texture(using glsl), so the texture is aligned with the screen 2D space but only shows what is "inside" the mask object? What I'm trying to achieve here is this I have a 3D scene made of cubic tiles, some of these tiles are going to be water and I want to distort whatever is behind them. My idea was to pass the render to texture and then distort it to make a refraction effect. Is this going to work? Am I even suposed to do refraction like this?


Help in understanding atmospheric scattering shading I have a made a planet and wanted to make an atmosphere around it. So I was referring to this site Click to visit site I don't understand this As with the lookup table proposed in Nishita et al. 1993, we can get the optical depth for the ray to the sun from any sample point in the atmosphere. All we need is the height of the sample point (x) and the angle from vertical to the sun (y), and we look up (x, y) in the table. This eliminates the need to calculate one of the out scattering integrals. In addition, the optical depth for the ray to the camera can be figured out in the same way, right? Well, almost. It works the same way when the camera is in space, but not when the camera is in the atmosphere. That's because the sample rays used in the lookup table go from some point at height x all the way to the top of the atmosphere. They don't stop at some point in the middle of the atmosphere, as they would need to when the camera is inside the atmosphere. Fortunately, the solution to this is very simple. First we do a lookup from sample point P to the camera to get the optical depth of the ray passing through the camera to the top of the atmosphere. Then we do a second lookup for the same ray, but starting at the camera instead of starting at P. This will give us the optical depth for the part of the ray that we don't want, and we can subtract it from the result of the first lookup. Examine the rays starting from the ground vertex (B 1) in Figure 16 3 for a graphical representation of this. First Question isn't optical depth dependent on how you see that is, on the viewing angle? If yes, the table just gives me the optical depth of the rays going from land to the top of the atmosphere in a straight line. How to find the optical depth in the case where the ray pierces the atmosphere and goes through it to the camera? Second Question What is the vertical angle it is talking about...like, is it the same as the angle with the z axis as we use in polar coordinates? (I am having a very hard time understanding this angle) Third Question The article talks about scattering of the rays going to the sun..shouldn't it be the other way around? like coming from the sun to a point? Any explanation on the article or on my questions will help a lot. Thanks in advance!


Why am I having these weird framerate issues with OpenGL on Windows? I'm using OpenGL on windows (have been for a while now), and I've come across a strange issue. Once every so often, the rate at which frames are presented on the screen drops to roughly 10 fps. However, my framerate counter stays at the usual framerate (2000fps in the menu, 300fps in game). My framerate counter is based on the time between draw calls, so the graphics card is definitly rendering 2000 frames a second. What is the problem? How can I fix it? EDIT I forgot to mention, this only happens when running in windowed mode.


What should the Z coordinate be after transformed by the projection matrix? I'm working on an OpenGL 1.x implementation for the Sega Dreamcast. Because the Dreamcast didn't have any hardware T amp L the entire vertex transformation pipeline has to be done in software. What also has to be done in software is clipping to the near Z plane as failure to clip results in the polygon being dropped entirely from rendering by the hardware. I'm having some trouble getting the transform clip perspective divide process working correctly and basically I can sum up the problem as follows I transform polygon vertices by the modelview and projection matrices I clip each polygon against the W 0.000001 plane This results in new vertices on the near plane with a W of 0.000001, but a Z which is twice the near plane distance At perspective divide vertex.z vertex.w results in an extreme value because we're dividing a Z value (e.g. 0.2) by 0.000001 Something seems very wrong here. The projection matrix is being generated in the same way as described in the glFrustum docs. So my question is, if I have a coordinate on the near plane, should its Z value be zero after transform by the projection matrix or should it be the near z distance, or something else? After clipping polygons to the W 0.000001 plane, should the generated Z coordinates be 0.000001? Update Here is the projection matrix as calculated by gluPerspective(45.0f, 640.0f 480.0f, 0.44f, 100.0f) 1.810660 0.000000 0.000000 0.000000 0.000000 2.414213 0.000000 0.000000 0.000000 0.000000 1.008839 0.883889 0.000000 0.000000 1.000000 0.000000 Does this look correct? It's the value in the right hand column I'm not sure about...


Anti Aliasing in OpenGL C I'm trying to make anti aliasing work inside of OpenGL, here's what I've tried glEnable(GL POINT SMOOTH) glHint(GL POINT SMOOTH HINT, GL NICEST) glEnable(GL LINE SMOOTH) glHint(GL LINE SMOOTH HINT, GL NICEST) glEnable(GL POLYGON SMOOTH) glHint(GL POLYGON SMOOTH HINT, GL NICEST) glEnable(GL BLEND) glBlendFunc(GL SRC ALPHA, GL ONE MINUS SRC ALPHA) But so far none of these have worked. I have gotten antialiasing to work by enabling it on the control panel for my video card (Catalyst Control Center in my case), but I would like to get it working inside my program instead. This is what the rendering looks like with 4x antialiasing enabled via the video card control panel And this is what it looks like when I do it with my program How do I get antialiasing to work?


Ara matrices calculated on the GPU or on the CPU? Would built in matrix functions be faster than my custom ones? If I add a math library (for example containing a Matrix class) and use it in my program drawing with OpenGL, will my be work slower than if I used standard OpenGL functions for matrix calculations? Does the same hold true for DirectX?


Texturing a PyOpenGL 3D Cube with PySDL2 So, I've just started learning OpenGL with PySDL2, and I've created a class that will create a cube to the window that I've created with PySDL2. What I'd like to do now, is to figure out a way to texture the cube. I don't believe that the actual texturing part is the problem, but actually loading the image. I've tried to do this with PySDL's image loader, but this causes an error from the OpenGL texture creator. Here is my code to load an texture and bind it to OpenGL def LoadTexture(self, filename) """Loads a texture for the cube""" surface SDL LoadBMP(filename) Checks if the loading succeeded if surface Translate the LP SDL Surface pointer got from SDL LoadBMP() to a real SDL Surface texture surface surface.contents texture format GL.GL RGBA GL TEXTURE ID GL.glGenTextures(1) GL.glBindTexture(GL.GL TEXTURE 2D, GL TEXTURE ID) GL.glPixelStorei(GL.GL UNPACK ALIGNMENT, 1) GL.glTexImage2D(GL.GL TEXTURE 2D, 0, 3, texture surface.w, texture surface.h, 0, texture format, GL.GL UNSIGNED BYTE, texture surface) return GL TEXTURE ID return None And the error that gives looks like this TypeError ("No array type handler for type lt class 'sdl2.surface.SDL Surface' gt (value lt sdl2.surface.SDL Surface object at 0x030762B0 gt ) registered", lt OpenGL.GL.images.ImageInputConverter object at 0x02EC49F0 gt ) I'm using Python 3 so using something like PIL won't work for me. Any ideas how to get the texture loaded, preferably with PySDL2?


What does glMultiDraw do? I'm having trouble understanding exactly what glMultiDraw does, and when it should be used. Is it to be used if I have one VBO with multiple objects in it or do I use it with many VBO's? It would be great if someone could give a real example of how to use this is a VAO VBO as all the stuff I've found on google just explain what the function does rather that how to use it practically.


Random lines away from images in java2d opengl game Working on a java game that uses some pngs images for icons textures. A few images ( fewer than 5, out of dozens ) are showing some odd parallel "artifact" lines. They move with the image, are certainly not in the PNG itself. I can't figure out what's causing it. Using slick2d, lwjgl. I've tried slcik2d and opengl methods of clamping textures but that didn't help. This black line is showing off the right hand side of an icon (maybe 50 of the actual image width away). It should not be there.


OpenGL pitching problem I've been trying to implement several camera movements for my application. So far yawing, rolling, strafing, walking has been working properly, but I can't get my pitching to work properly. If I continue pitching upwards, it doesn't rotate back 360 degree, and instead gets stuck looking at the top of the screen. Here's my code for Camera class class Camera float m 16 Vector dirForward, dirUp, dirRight void loadCameraDirections() glGetFloatv(GL MODELVIEW MATRIX, m) dirForward Vector(m 2 , m 6 , m 10 ).unitVector() dirUp Vector(m 1 , m 5 , m 9 ).unitVector() dirRight Vector(m 0 , m 4 , m 8 ).unitVector() public Vector position Vector lookAt Vector up Camera() position Vector(300, 0, 100) lookAt Vector(0, 0, 100) up Vector(0, 0, 1) void rotatePitch(double rotationAngle) glPushMatrix() glRotatef(rotationAngle, dirRight.x, dirRight.y, dirRight.z) loadCameraDirections() glPopMatrix() lookAt position.repositionBy(dirForward.reverseVector()) cam I call the gluLookAt funtion by gluLookAt(cam.position.x, cam.position.y, cam.position.z, cam.lookAt.x, cam.lookAt.y, cam.lookAt.z, cam.up.x, cam.up.y, cam.up.z)


Animation of moving circle by square's outer surface I want to make this animation in OpenGL, here I attached a simple gif how I want it to looks like Main problem is that I can not figure out how to move by corner circle should smoothly move by corner, not to just jump to another side's begin position. import Blender from Blender import Draw,BGL from Blender.BGL import from math import sin,cos import time squareLength, squareX, squareY, circleRadius 200, 200, 200, 20 movingX, movingY 0, 0 def event(evt, val) if evt Draw.ESCKEY Draw.Exit() def gui() global movingX, movingY glClearColor(0.17, 0.24, 0.31, 1.0) glClear(BGL.GL COLOR BUFFER BIT) glLineWidth(1) glColor3f(0.74, 0.76, 0.78) glBegin(GL QUADS) glVertex2i(squareX, squareY) glVertex2i(squareX, squareY squareLength) glVertex2i(squareX squareLength, squareY squareLength) glVertex2i(squareX squareLength, squareY) glEnd() glColor3f(0.58, 0.65, 0.65) glPushMatrix() if movingX circleRadius if movingY lt squareLength movingY 1 else movingX 0 movingY squareLength circleRadius else if movingY squareLength circleRadius if movingX lt squareLength movingX 1 else movingX squareLength circleRadius movingY squareLength else if movingY lt 0 if movingX gt 0 movingX 1 else movingX circleRadius movingY 0 else if movingY gt 0 movingY 1 else movingX squareLength movingY circleRadius glTranslatef(movingX, movingY, 0) glBegin(GL LINE LOOP) for i in xrange(0, 360, 1) glVertex2f(squareX sin(i) circleRadius, squareY cos(i) circleRadius) glEnd() glPopMatrix() Draw.Redraw(1) Draw.Register(gui, event, None) Can you please say me, how can I optimize this code to make circle moving by corners? Just start learning computer graphics and think up such exercises for training, so I will really appreciate for any help.


GLSL sampler2D fallback to constant color? So I have the following situation I'm sharing a blinn shader accross many meshes. Some meshes have specular amp normal maps, others do not. I'd like to, without making the shader code too complicated, be able to specify a constant color instead of a texture, for the normal or specular maps. This is for example if a given mesh doesn't need one of those maps. The way I imagine it, I would just pass a flat "grey" as the specular map, for instance, and the shader could just act as if a texture was passed in. Is this possible? Ideally, I don't want to have an extra uniform for each mesh specifying whether or not the texture should be used. Another alternative would be to actually create a grey texture on the fly, if this is the better way, please advise on the simplest way to do this.


Any GL transformation not working Today I was trying to make a test camera, with a new method(I usually use gluLookAt) So I got a problem, void GameDraw() glPushMatrix() glMatrixMode(GL PROJECTION) glLoadIdentity() gluPerspective(90, WIDTH HEIGHT, 0.001, 10000.0) pitch 1 glRotatef(pitch, 1.0, 0.0, 0.0) glRotatef(yaw, 0.0, 1.0, 0.0) glMatrixMode(GL MODELVIEW) glLoadIdentity() s gt bind() test gt drawMesh() glPopMatrix() And my draw function is glDrawElements(GL TRIANGLES, indices, GL UNSIGNED INT, nullptr) if it isn't working with glDrawElements is there any alternative to use? Edit Disabling shader it works fine, but how I can use this with Shader Please don't use glm examples, because I don't like to use it, I feel more comfortable by using the my math


What is a fast way to darken the vertices I'm rendering? To make a lighting system for a voxel game, I need to specify a darkness value per vertex. I'm using GL COLOR MATERIAL and specifying a color per vertex, like this glEnable(GL COLOR MATERIAL) glBegin(GL QUADS) glColor3f(0.6f, 0.6f, 0.6f) glTexCoord2f(...) glVertex3f(...) glColor3f(0.3f, 0.3f, 0.3f) glTexCoord2f(...) glVertex3f(...) glColor3f(0.7f, 0.7f, 0.7f) glTexCoord2f(...) glVertex3f(...) glColor3f(0.9f, 0.9f, 0.9f) glTexCoord2f(...) glVertex3f(...) glEnd() This is working, but with many quads it is very slow.. I'm using display lists too. Any good ideas in how to make vertices darker?


client side array in the OpenGL 3.3. core It is possible the topic (not using VBO)? in the OpenGL 3.0 compatible profile I can to draw this way GLint position index attrib location get("VertexPosition") gl EnableVertexAttribArray(position index) gl VertexAttribPointer(position index, 3, gl FLOAT, false, 0, pos Data) gl DrawArrays(gl TRIANGLES, 0, count of vertices) Bat in the OpenGL 3.3 core profile it displays a blank screen. It is right?


Basic 2D Lighting Optimization Issue in Fragment Shader with OpenGL (GLSL) I'm using a fragment shader to implement 2D lighting (code further below). Even though I am satisfied with the visuals of the light i noticed that it has a quite big GPU usage, and when trying to add about 40 light sources the usage is close to 100 (GTX 1050). I have a uniform array of structs that contain data about each light source and for loop that goes through all of them. At first I thought I was pushing too much data to the GPU so I combined the RGB values of the light color in a single 32 bit integer and the two strengths of the light in a single 32 bit integer as well. Then I tried simplifying the formulas I used (using a composed, by composed I'm not referring to the operation, function from multiple linear functions) but it seemed that just made the matters worse. I think it's worth noting the difference between LightStrength and VisualStrength values that I used in the code, the LightStrength is the strength of the light that lights up the medium around it and the VisualStrength is the strength of the colored hue around the light. And there is also a dark hue variable that is used to make the scene darker as of in the different times of the day. The code of the fragment shader version 450 core in vec2 texCoord0 uniform vec3 CameraPosition uniform mat4 Projection uniform float DarkHue uniform sampler2D u Texture uniform vec2 u resolution struct LightSource vec2 Position int LightColor int ArgumentValue uniform LightSource LightSources 300 uniform int LightSourceCount float GetLightfactor(float x,float Streght) return min(1 (x (Streght 100.0) 1),1) void main() gl FragColor texture2D(u Texture,texCoord0) vec3 LightSum vec3(0) vec4 PCameraPosition vec4(CameraPosition,0) Projection vec2 NormalizedPosition gl FragCoord.xy 2 u resolution 1 float LightFactor,VisualFactor,LightStreght,VisualStreght for (int i 0 i lt LightSourceCount i) vec4 Pos vec4(LightSources i .Position,0,0) Projection PCameraPosition vec2 coord (NormalizedPosition Pos.xy) u resolution LightFactor 0.0 VisualFactor 0.0 LightStreght LightSources i .ArgumentValue amp 0xffff VisualStreght (LightSources i .ArgumentValue gt gt 16) amp 0xffff float lng length(coord) LightFactor GetLightfactor(lng,LightStreght) VisualFactor GetLightfactor(lng,VisualStreght) LightSum mix(LightSum,vec3(1),gl FragColor.rgb LightFactor (1 DarkHue)) vec3(((LightSources i .LightColor gt gt 16) amp 0xff) 255.0,((LightSources i .LightColor gt gt 8) amp 0xff) 255.0,(LightSources i .LightColor amp 0xff) 255.0) VisualFactor gl FragColor.rgb DarkHue gl FragColor.rgb LightSum The code of the c function that adds a light source. (Yes when setting uniforms caching is used) static void AddLightSource(Vec2 Position, uint8 t R, uint8 t B, uint8 t G, uint16 t LightStrenght,uint16 t VisualStrenght) std string access quot LightSources quot std to string(ActiveLightSources) quot quot int Value (VisualStrenght lt lt 16) LightStrenght int Color (R lt lt 16) (G lt lt 8) B Vec3 Translated VertexArrayManager TranslateValue shader gt setUniform2f(access quot .Position quot , glm vec2(Position.x Translated.x,Position.y Translated.y)) shader gt setUniform1i(access quot .LightColor quot , Color) shader gt setUniform1i(access quot .ArgumentValue quot , Value) ActiveLightSources shader gt setUniform1i( quot LightSourceCount quot , ActiveLightSources)


3D sphere generation I have found a 3D sphere in a closed source game engine that I really like the look of and would like to have something similar in my own 3D engine. This is how the sphere looks like when it is created in the game engine, at program game start At program start, a function named CreateSphere is called and the user has the option to choose a 3D position and a radius of the sphere. That's all I know about the function since the engine is closed source. Anyone have any idea of how this sphere might be generated programmatically? I have checked other posts sites discussing spheres but none of them has the look of the sphere in the image. Edit removed some unnecessary information to get to the point of what I need help with.


Graphical mesh lags behind collision shape in BulletPhysics debug drawing In Bullet Physics when I debug draw physics world the graphical mesh lags behind the collsion shape. m DynamicsWorld gt stepSimulation(1 60.0f, 10) btTransform trans, trans2 trans2 m RigidBodies.at("CubeMesh") gt m Body gt getWorldTransform() m RigidBodies.at("CubeMesh") gt m Body gt getMotionState() gt getWorldTransform(trans) using m RigidBodies.at("CubeMesh") gt m Body gt getMotionState() gt getWorldTransform(trans) causes the graphical mesh to lag behind the collision shape in DebugDraw call Checking with debugger shows that the lag error keeps on increasing glm mat4 M trans.getOpenGLMatrix(glm value ptr(M)) m RigidBodies.at("CubeMesh") gt GetGraphicalObject() gt Model M if (m DebugDraw) m DynamicsWorld gt debugDrawWorld() If I use the OpenGL matrix from trans2 then debug drawing is perferct. But with trans the graphical mesh lags behind the collision shape in debug draw. I am using btDefaultMotionState when setting the CubeMesh rigid body. btTransform tr tr.setIdentity() tr.setOrigin(btVector3(0.0f, 90.0f, 0.0f)) cubeMesh gt m PhysicsBody gt m MotionState new btDefaultMotionState(tr) Can anyone explain reason for this lag?


Should I distribute shaders in a compiled form or in plain text? Having an application that uses shaders that have been wrote in GLSL, what is the best strategy for the distribution in the real world and for the desktop and mobile? I'm aiming to distribute this in a binary form or as plain serialized text, i would like a good suggestion on this.


Why is the size of glm's vec3 struct 12 bytes? When trying to determine the size of glm vec3 (from GLM math library) by using the size of operator like so sizeof(glm vec3) I get 12 returned. When I look at the definition of a vec3 struct I see this template lt typename T, precision P defaultp gt struct tvec3 Implementation detail typedef tvec3 lt T, P gt type typedef tvec3 lt bool, P gt bool type typedef T value type ifdef GLM META PROG HELPERS static GLM RELAXED CONSTEXPR length t components 3 static GLM RELAXED CONSTEXPR precision prec P endif GLM META PROG HELPERS Data if GLM HAS ANONYMOUS UNION union struct T x, y, z struct T r, g, b struct T s, t, p ifdef GLM SWIZZLE GLM SWIZZLE3 2 MEMBERS(T, P, tvec2, x, y, z) GLM SWIZZLE3 2 MEMBERS(T, P, tvec2, r, g, b) GLM SWIZZLE3 2 MEMBERS(T, P, tvec2, s, t, p) GLM SWIZZLE3 3 MEMBERS(T, P, tvec3, x, y, z) GLM SWIZZLE3 3 MEMBERS(T, P, tvec3, r, g, b) GLM SWIZZLE3 3 MEMBERS(T, P, tvec3, s, t, p) GLM SWIZZLE3 4 MEMBERS(T, P, tvec4, x, y, z) GLM SWIZZLE3 4 MEMBERS(T, P, tvec4, r, g, b) GLM SWIZZLE3 4 MEMBERS(T, P, tvec4, s, t, p) endif GLM SWIZZLE other code...... For which I see three structs, each with three member variables of templated type T, which in GLM defaults to float type. My question is why is the sizeof() operator returning 12 bytes as the size of glm vec3 when it looks like it should be 36 bytes 3 structs, with 3 float members each 3 3 4(number of bytes in a float) 36.


Vertex data split into separate buffers or one one structure? Is it better to have all vertex data in one structure like this class MyVertex int x,y,z int u,v int normalx, normaly, normalz Or to have each component (location, normal, texture coordinates) in separate arrays buffers? To me it always seemed logical to keep the data grouped together in one structure because they'd always be the same for each instance of a shared vertex and that seems to be true for things like character models (ex the normal should be an average of adjacent normals for smooth lighting). One instance where this doesn't seem to work is other kinds of meshes like say a cube where the texture coordinates for each may be the same but that causes them to be different where the vertices are shared. Are they normally kept separate? Won't this make them less space efficient if there needs to be an instance of texture coordinates and normals for each vertex (they won't be indexed)? Can OpenGL even handle this mixing of indexed (for location) vs non indexed buffers in the same VBO?


LibGDX 2D Silhouette recently I decided to implement in my game the drawing of a silhouette of the player when he is behind objects (the top layer of the map). Found a similar question here, but it doesn't matter to me to understand anything. Can someone please explain how it all works? I will be very grateful to you! Specifically, I'm interested in the issue of creating the Vertex and Fragments of the shaders? And why is only one shader passed to two setSheader methods. Code that I do not understand Rendering the upper map layer Simple quot if (gl FragColor.a 0.0) discard quot fragment shader renderer.getBatch().setShader(shader) Rendering the silhouettes quot gl FragColor vec4(0.0, 1.0, 1.0, 0.2) texture2D(u texture, v texCoord0).a quot batch.setShader(shader) EDITS I tried adding this code and this is what I got Java code above render the normal player texture outside the shader code mapRenderer.render(lowerLayer) player.update(mapMgr, game.batch, delta, world) mapRenderer.render(upperLayer) Gdx.gl20.glClear(GL20.GL STENCIL BUFFER BIT) Gdx.gl20.glEnable(GL20.GL STENCIL TEST) Gdx.gl20.glStencilFunc(GL20.GL ALWAYS, 0x1, 0xFF) Gdx.gl20.glStencilOp(GL20.GL REPLACE, GL20.GL REPLACE, GL20.GL REPLACE) mapRenderer.getBatch().setShader(shader) mapRenderer.render(upperLayer) mapRenderer.getBatch().setShader(null) Gdx.gl20.glStencilFunc(GL20.GL LEQUAL, 0x1, 0xFF) Gdx.gl20.glStencilOp(GL20.GL KEEP, GL20.GL KEEP, GL20.GL KEEP) game.batch.setShader(shader) player.update(mapMgr, game.batch, delta, world) game.batch.setShader(null) Gdx.gl20.glDisable(GL20.GL STENCIL TEST) Fragment GLSL code varying vec4 v color varying vec2 v texCoords uniform sampler2D u texture void main() vec4 c vec4(.5, .5, .5, texture2D(u texture, v texCoords).a) if (c.a 0.0) discard gl FragColor c It didn't work out that way. In addition to the fact that the color of the top layer changes, the player is also completely painted, regardless of whether he is under the top layer or not. I think the problem is in some of this This part of the code does not work. Because even if you remove it, nothing changes. Gdx.gl20.glClear(GL20.GL STENCIL BUFFER BIT) Gdx.gl20.glEnable(GL20.GL STENCIL TEST) Gdx.gl20.glStencilFunc(GL20.GL ALWAYS, 0x1, 0xFF) Gdx.gl20.glStencilOp(GL20.GL REPLACE, GL20.GL REPLACE, GL20.GL REPLACE) Gdx.gl20.glStencilFunc(GL20.GL LEQUAL, 0x1, 0xFF) Gdx.gl20.glStencilOp(GL20.GL KEEP, GL20.GL KEEP, GL20.GL KEEP) Gdx.gl20.glDisable(GL20.GL STENCIL TEST) Fragment shader is not written correctly I spent all day solving this problem. Nothing works. I hope someone will figure it out! Thanks.


does glBindAttribLocation silently ignore names not found in a shader? Does glBindAttribLocation silently ignore names that are not found? For example, in a shader Some vertex shader in vec3 position in vec3 normal ... And in some set up code While setting up shader GLuint program glCreateProgram() glBindAttribLocation(program, 0, "position") glBindAttribLocation(program, 1, "normal") glBindAttribLocation(program, 2, "color") What about this one? glLinkProgram(program)


LWJGL Lighting advice fix Problem The spotlight I've set up with OpenGL won't light up anything behind it, no matter what values I set for GL SPOT DIRECTION float LightDir new float 0,0, 1,0 float LightPos new float 0,0,15f,1 Initialization code for lighting glEnable(GL LIGHTING) glEnable(GL LIGHT0) glLightModel(GL LIGHT MODEL AMBIENT,asFlippedFloatBuffer(new float 0.1f, 0.1f, 0.1f, 1f )) glLight(GL LIGHT0,GL DIFFUSE,asFlippedFloatBuffer(new float 0.5f, 0.5f, 0.5f, 1f )) glLight(GL LIGHT0, GL POSITION, asFlippedFloatBuffer(new float 0, 0, 0, 1 )) glLightf(GL LIGHT0,GL SPOT CUTOFF,60.0f) glLightf(GL LIGHT0,GL SPOT EXPONENT,2.0f) glEnable(GL COLOR MATERIAL) glColorMaterial(GL FRONT AND BACK, GL AMBIENT AND DIFFUSE) glShadeModel(GL SMOOTH) Lighting code ran every loop glLight(GL LIGHT0,GL SPOT DIRECTION,asFlippedFloatBuffer(LightDir)) glLight(GL LIGHT0,GL POSITION,asFlippedFloatBuffer(LightPos)) The Following shows To try and change the direction I hit a key that does LightDir 1 The angle of the light goes up as expected, but seems to stop turning once it's pointed straight up. Which looks like Which is the problem, it wont turn around. Iv'e tried every possible value for LightDir in all it's values, but I cannot get it to illuminate the back pf the tube. I've even tried to transform to light around the scene with glRotate and glTranslate. The light is supposed to function as a flashlight. Is this something that would be potentially solved with Shaders? Thanks in advance! EDIT Anytime LightDir 2 goes above 0 the light goes dark.


glScalef game math issue I can't get my head wrapped around this issue. The issue is my latest code is making the camera zoom in and out really quickly. My approach is built on http www.zdnet.com blog burnette how to use multi touch in android 2 part 6 implementing the pinch zoom gesture 1847?tag content siu container The opengl scale will be getting the variable scale. gl.glScalef(scale, scale, 1) the distance is obtained by between two fingers, old distance (initial touch points), and new distance (dragging touch points). The zooming in and out works well. However, it would reset glScalef each time the user start using pinch zoom. scale newDistance oldDistance I tried calculating by additive ratio. The oldtscale handles the previous distance, if it is same, then it doesn't need to add up anything to scale. The zooming is really quick, I moved the fingers closer by mere 1 cm to 5 cm, zoom goes down or up fast. I think additive ratio is a bad solution. I think it might be incomplete solution. I'm trying to figure out what's wrong with it. additive ratio tscale (newDistance oldDistance) 1 if(oldtscale tscale) oldtscale tscale tscale 0 else oldtscale tscale adding up the additive ratio and scale tscale scale tscale checking tscale for limiting the maximum minimum scale if(tscale gt 2) tscale 2 else if(tscale lt 1) tscale 1 supply scale scale tscale


How stencil buffer and glFrontFace help making a shadow? I'm trying to understand the tutorial 27th in Nehe website. This is about how to cast a shadow of an object using stencil buffer in OpenGL. The idea here is checking the directions of all the faces of the object with the direction of light, and the result will define whether or not this face make a shadow. In the case of making a shadow, we will draw "shadow" into the stencil buffer as the following code. First Pass. Increase Stencil Value In The Shadow glFrontFace( GL CCW ) glStencilOp( GL KEEP, GL KEEP, GL INCR ) doShadowPass( object, lightPosition ) Second Pass. Decrease Stencil Value In The Shadow glFrontFace( GL CW ) glStencilOp( GL KEEP, GL KEEP, GL DECR ) doShadowPass( object, lightPosition ) My question here is why "glFrontFace" function in the second pass help remove shadow between objects in the scene? I Hope to see your answer. Thanks so much! P S this is the explanation in the tutorial, but I don't get it "They are rendered in two passes as you can see, one incrementing the stencil buffer with the front faces (casting the shadow), the second decrementing the stencil buffer with the backfaces ("turning off" the shadow between the object and any other surfaces)."


How can I compute the orbit of one body around another? I'm attempting to have a planet (with a known mass and radius) orbit it's sun (also with a known mass and radius). It doesn't have to be 100 realistic, but it should be possible that the sun have more than one planet orbit it at a time. What equations should I use to accomplish this?


Understanding normal mapping I am trying to understand the basics of normal mapping using this tutorial http ogldev.atspace.co.uk www tutorial26 tutorial26.html What I don't get there is the following equation E1 ( U1 U0 ) T ( V1 V0 ) B How do they came to this equation? This it out of nowhere for me. What is E1? The tutorial say that E1 is one edge of the triangle. But I don't get it, in the equation E1 seems to be a real number, not a vector ( which an edge is supposed to be right? he have a x and y component ).


Making a weapon stay with a first person camera I was looking all over the internet for any information on how to get a gun to stay with a camera as done in FPS games. I am using OpenGL and GLSL to carry this out. I knew a way of how to do this in earlier OpenGL versions, but I could never figure it out in the newer versions. The type of camera that I am trying to get is something similar to this With the view matrix and everything else, I should be able to figure out the movement of the hand and the shooting. Here is some of the code that I have so far Copyright(c) 2019 Ryan Hall All Rights Reserved I do not permit any of this code to be used elsewhere by anyone else except me for commercial purposes. The gun has two defining variables one that actually creates the gun and another that moves it around in object space weaponOfChoice glm translate(weaponOfChoice, glm vec3(camera.GetPosition().x 0.15, camera.GetPosition().y 0.15, camera.GetPosition().z 0.3)) weaponOfChoice glm rotate(gun, angle, glm vec3(0.0f, 1.0f, 0.0f)) weaponOfChoice glm scale(gun, glm vec3(0.005f, 0.005f, 0.005f)) glUniformMatrix4fv(glGetUniformLocation(shader.Program, "gun"), 1, GL FALSE, glm value ptr(weaponOfChoice)) I have spent quite some time working on how to fix the code so that it will render the gun correctly and have not been able to find any great sources online that will help solve my problem. How could I do this? Do I need an identity matrix as used by me in older versions of OpenGL? If so, how do I create a mimicking function of glLoadIdentity() that will help me with this problem? Thanks, rjhwinner03


Split up a screen into regions My task I want to split up a screen into 3 regions for buffs bar (with picked items), score info and a game map. It doesn't matter are regions intersect with each other or not. For example I have a screen with width 1 height 1 and the origin of coordinates (0 0) is the left bottom point. I have 3 functions draw items, draw info, draw map. If I use it without any matrix transformations, it draws fullscreen, because it's vertex coordinates are from 0 0 to 1 1. (pseudo code) drawItems() drawInfo() drawMap() And after that I see only map onto info onto items. My goal I have some matrixes for transformation vertexes with 0 0 1 1 coordinates to strict regions. There is only one thing, what I need to do set matrix before drawing. So my call of drawItems function is like (pseudo code) adjustViewMatrixes andSomethingElse(items.position of the region there it should be drawn, items.sizes of region to draw) setItemsMatrix() drawItems() the same function with vertex coordinates 0 0 gt 1 1, but it draws in other coordinates, because I have just set the matrix for region I know only some people will understand me, so there is a picture with regions which I need to make. Every region has 0 0 1 1 inner coordinates.


What does glMultiDraw do? I'm having trouble understanding exactly what glMultiDraw does, and when it should be used. Is it to be used if I have one VBO with multiple objects in it or do I use it with many VBO's? It would be great if someone could give a real example of how to use this is a VAO VBO as all the stuff I've found on google just explain what the function does rather that how to use it practically.


Can I use the HD Graphics 3000's quad list primitive type via D3D? I was studying some technical documentation on the Intel HD Graphics 3000 GPU, which I'm using as a lower end reference for my 2D game engine. I noticed the hardware supports a nice "Quad List" topology, where every 4 vertices in a vert buffer are interpreted as an independent quad. My engine draws nothing but sprite quads, so that would be a nice optimization in my case, to eliminate the need for copying caching processing an accompanying index buffer with 12 bytes per quad of trivial triangle edge definitions (I'm using indexed TriangleList primitives at the moment). From what I can tell though, DirectX 9 doesn't expose quad list, and after some cursory peeking around in DX10 11 (which I don't plan to support at this point) it seems they don't expose this feature either. Does anyone know if there's a way to use Quad Lists in DirectX? I'd be curious about OpenGL also, if anyone has experience on that side.


What technique should I use to create models and animation sequences in OpenGL code? I'm getting into game development using OpenGL (and the LWJGL library) and I want to create models for characters, NPC's etc. in the code, as well as animation sequences (for example the way the models are done in Minecraft). What is the process to go about doing something like this? Is there a particular feature set that is used or common methods of doing this? I'm basically looking for pointers as to what to search for when trying to find examples of how this is done.


What advantage do OpenGL, SFML and SDL have over software rendering? I started watching the Handmade Hero stream, where Casey Muratori creates a game engine without using frameworks or such. Yesterday I got to the part where he showed how an image is drawn onto the screen. As far as I understood it he just allocated some memory as big as the size of the screen he wants to draw to. And then he created a bitmap which he passed to the buffer memory he allocated and drew it to the screen using a os specific function. This seems quite straight forward. I used GameMaker, changed to Love2D, worked a little bit with Sprite Kit but I was always wondering what was really happening beneath this sometimes confusing layers. Given that, why even bother using graphics libraries (OpenGL, SFML, SDL, ) when all you have to do is simply allocate some buffer, pass a bitmap and draw it to the screen? If you then want to draw distinct things to you screen you just write them to your bitmap which then gets passed into the buffer. I'm quite new to programming, but this seems quite simple to me. Please correct me if I'm wrong.


How to read rendered textures back without killing performance I have an application where I need to render some OpenGL based dlls, read the rendered textures back, and send them to another directx based application that will render them in directx. Right now, I am rendering them using FBOs, reading them back, and then sending the data across the network. However, the "reading them back" step is killing the performance. My basic loop is as follows while(true) ... render 5 to 10 textures ... foreach( texture in renderedTextures ) bind texture glGetTexImage( data ) push data onto a queue to send asyncronously Commenting out the glGetTextImage call causes performance to improve drastically. What techniques can I use to read the data back faster?


Draw multiple times same object but translated and rotated I want to draw lots of spheres in different locations and orientations with Opengl4 and JOGL. As the vertexes and colours are the same for all of them, I have just one array for vertexes and another for colours. For the positions and orientations, I have another big matrix where I have all data for all spheres. In principle, drawing one with glDrawArrays is not a problem but for severals, I have read that I should use glDrawArraysInstanced instead. My problem is that I am a bit confused about how to apply each transformation for my particles. How should I introduce this array into the shader? Should I send the matrix model after doing the transformations in the cpu or should I send the positions and orientations and transform them inside the shader? How do I connect the data to the shader? How should the shader look like?


Updating texture memory via shader? What the title says.Is it possible to update a texture via a glsl shader ? Something like Read vec4 Pixel texture2D(TextureID,gl TexCoord TextureIndex .st) Write to texture memory ? vec4 NewPixel Pixel vec4(0.0,0.0,0.0,AlphaPatch) ?? How to write back to texture memory ?? texture2D(TextureID,gl TexCoord TextureIndex .st) NewPixel ??


OpenGL Drawing multiple meshes at once using VBOs and IBOs I have been learning OpenGL 2.1 but using shaders, VBOs, IBOs, etc. I have gotten a rendering engine that can load and draw meshes, materials, forward lighting (no shadows yet), SceneNodes, and NodeComponents. There are no optimizations yet (for obvious reasons) such as occlusion culling, only Face culling at the moment. A mesh (simplified) class looks like this struct Mesh GLuint vbo GLuint ibo GLuint size void draw(Program shaderProgram) const glEnableVertexAttribArray(shaderProgram gt attrib("vertPos")) glEnableVertexAttribArray(shaderProgram gt attrib("vertTexCoord")) ... glBindBuffer(GL ARRAY BUFFER, vbo) glVertexAttribPointer(shaderProgram gt attrib("vertPos"), 3, GL FLOAT, false, sizeof(Vertex), (const GLvoid )(0 sizeof(float))) ... glBindBuffer(GL ELEMENT ARRAY BUFFER, ibo) glDrawElements(GL TRIANGLES, size, GL UNSIGNED INT, 0) glBindBuffer(GL ARRAY BUFFER, 0) glBindBuffer(GL ELEMENT ARRAY BUFFER, 0) glDisableVertexAttribArray(shaderProgram gt attrib("vertPos")) ... When I have been drawing multiple objects with the same mesh (or multiple meshes), I notice a frame drop compared to a single mesh with the same number of triangles. Stanford Models were used. (1 Face Triangle) Model Num Models Total Faces With Lighting Without Lighting ms frame ms frame 0 (control) 0 0.47 0.41 bunny 1 69630 1.2 0.64 bunny 14 974820 12.4 3.50 buddha 1 1087474 7.87 2.89 buddha 10 10874740 71.4 23.8 I does look like that time frame is O(n). However, drawing one vbo with 12 more faces, the frame time is decreased by 37 . So my questions are Is drawing multiple VBOs actually worse than drawing one big one? How would I combine these VBOs and IBOs into one big one if this is true?


Separate shader programs or branch in shader? I have a bunch of point lights and directional lights. Instead of checking the light type in the fragment shader and then branch for either point light calculation or directional light calculation, is it more efficient to use two separate programs, one for point lights and one for directional lights? (Using deferred shading in OpenGL 3.3)


Managing many draw calls for dynamic objects We are developing a game (cross platform) using Irrlicht. The game has many (around 200 500) dynamic objects flying around during the game. Most of these objects are static mesh and build from 20 50 unique Meshes. We created seperate scenenodes for each object and referring its mesh instance. But the output was very much unexpected. Menu screen (150 tris Just to show you the full speed rendering performance of 2 test computers) a) NVidia Quadro FX 3800 with 1GB 1600 FPS DirectX and 2600 FPS on OpenGL b) Mac Mini with Geforce 9400M 256mb 260 FPS in OpenGL Now inside the game in a test level (160 dynamic objects counting around 10K tris) a) NVidia Quadro FX 3800 with 1GB 45 FPS DirectX and 50 FPS on OpenGL b) Mac Mini with Geforce 9400M 256mb 45 FPS in OpenGL Obviously we don't have the option of mesh batch rendering as most of the objects are dynamic. And the one big static terrain is already in single mesh buffer. To add more information, we use one 2048 png for texture for most of the dynamic objects. And our collision detection hardly and other calculations hardly make any impact on FPS. So we understood its the draw calls we make that eats up all FPS. Is there a way we can optimize the rendering, or are we missing something?


What's the best way of drawing a glowing 3d line using LWJGL? Sort of like a strip light effect not actually a light source, but just a polygon with glowing edges. Can this be done easily? Right now I'm contemplating drawing a line more than once with varying alpha width values to achieve this, but I think that'll cause weird glowing points at the vertices, which is far from ideal.


OpenGL Framebuffer Object issue I am struggling with implementing a proper Framebuffer Object . glCheckFramebufferStatus is returning me GL FRAMEBUFFER INCOMPLETE ATTACHMENT (36054). What am i missing? GLuint fbo, rboColor, rboDepth Color renderbuffer. glGenRenderbuffers(1, amp rboColor) glBindRenderbuffer(GL RENDERBUFFER,rboColor) Set storage for currently bound renderbuffer. glRenderbufferStorage(GL RENDERBUFFER, GL BGRA, w, h) Depth renderbuffer glGenRenderbuffers(1, amp rboDepth) glBindRenderbuffer(GL RENDERBUFFER,rboDepth) glRenderbufferStorage(GL RENDERBUFFER, GL DEPTH COMPONENT24, w, h) Framebuffer glGenFramebuffers(1, amp fbo) glBindFramebuffer(GL FRAMEBUFFER,fbo) glFramebufferRenderbuffer(GL DRAW FRAMEBUFFER, GL COLOR ATTACHMENT0, GL RENDERBUFFER, rboColor) Set renderbuffers for currently bound framebuffer glFramebufferRenderbuffer(GL DRAW FRAMEBUFFER, GL DEPTH ATTACHMENT,GL RENDERBUFFER,rboDepth) Set to write to the framebuffer. glBindFramebuffer(GL FRAMEBUFFER,fbo) Tell glReadPixels where to read from. glReadBuffer(GL COLOR ATTACHMENT0) GLenum e glCheckFramebufferStatus(GL DRAW FRAMEBUFFER) glCheckFramebufferStatus check the completeness status of a framebuffer if (e ! GL FRAMEBUFFER COMPLETE) printf(" nThere is a problem with the FBO.")


Modern OpenGL Sprite Drawing Not Rendering I'm trying to render sprites based of this tutorial, in LWJGL. Here's what I have so far, with descriptions of what class I use Transformable2D is a class that holds transform matrices meant for 2D rendering, and Drawable is just an interface that has a draw() function. Texture is a container for loading and creating Textures, and its bind function just sets the active texture to it's ID and binds itself to the passed unit parameter. SpriteTechnique is a container for a shader program, and I will paste the shaders here too, although they are the same as from the tutorial. I make the shader and vao static, because every Sprite uses the same vao and shader. Finally, I pass a View to the draw() function, which holds the necessary info to make an orthogonal matrix based off the transforms of the object. This matrix is correct, as I also use it for text rendering, where it works as expected. All of the classes described above work completely I am 100 sure the problem is not within the backing classes. Here are the GL settings I set in my backend, too glFrontFace(GL CW) glCullFace(GL BACK) glEnable(GL CULL FACE) glEnable(GL DEPTH TEST) So, onto the actual class public class Sprite extends Transformable2D implements Drawable private Texture texture private Vector3f color private static SpriteTechnique tech new SpriteTechnique() private static boolean isRendererInitialized private static int vao public Sprite(Texture texture) this.texture texture color new Vector3f() public static boolean initRenderer() if (isRendererInitialized) return true if (!tech.init()) return false float vertices Pos Tex 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f, 0.0f FloatBuffer vertexBuf BufferUtils.createFloatBuffer(vertices.length) vertexBuf.put(vertices) vertexBuf.flip() vao glGenVertexArrays() glBindVertexArray(vao) int vbo glGenBuffers() glBindBuffer(GL ARRAY BUFFER, vbo) glBufferData(GL ARRAY BUFFER, vertexBuf, GL STATIC DRAW) glEnableVertexAttribArray(0) glVertexAttribPointer(0, 4, GL FLOAT, false, 16, 0) glBindBuffer(GL ARRAY BUFFER, 0) glBindVertexArray(0) isRendererInitialized true return true Override public void draw(View v, RenderStates states) if (!isRendererInitialized) System.err.println("Sprite renderer must be initialized before drawing sprites!") return tech.enable() tech.setTextureUnit(COLOR TEXTURE UNIT INDEX) tech.setColor(color) tech.setProjection(getOrthoTrans(v).getMatrix()) texture.bind(COLOR TEXTURE UNIT) glBindVertexArray(vao) glDrawArrays(GL TRIANGLES, 0, 6) glBindVertexArray(0) Here are my shaders Sprite.vs version 330 core layout (location 0) in vec4 vertex lt vec2 position, vec2 texCoords gt out vec2 TexCoords uniform mat4 gProjection void main() TexCoords vertex.zw gl Position gProjection vec4(vertex.xy, 0.0, 1.0) Sprite.fs version 330 core in vec2 TexCoords out vec4 color uniform sampler2D gSpriteTexture uniform vec3 gSpriteColor void main() color vec4(gSpriteColor, 1.0) texture(gSpriteTexture, TexCoords) When I try to render a Sprite, however, nothing appears on the screen. Not even a black quad. I've tried to scale the quad, but to no avail. What am I doing wrong here?


Gldraw call asynchronous or not When i call gldrawarrays with a large set of data will the function return only after drawing all the vertices or will it happen asynchronously b w cpu and gpu? Also how does vsync work. Aren't they related?


GLSL Shader compiles, but source is empty I'm trying to compile a GLSL shader, to which I use the following code. Initialization SDL Window boringInitStuff() SDL Init(SDL INIT VIDEO) SDL GL SetAttribute( SDL GL CONTEXT MAJOR VERSION, 3 ) SDL GL SetAttribute( SDL GL CONTEXT MINOR VERSION, 1 ) SDL GL SetAttribute( SDL GL CONTEXT PROFILE MASK, SDL GL CONTEXT PROFILE CORE ) Uint32 windowFlags SDL WINDOW OPENGL SDL Window sdlWindow SDL CreateWindow("Boooring", SDL WINDOWPOS UNDEFINED, SDL WINDOWPOS UNDEFINED, 400, 400, windowFlags) SDL GL CreateContext(sdlWindow) glewExperimental GL TRUE glewInit() return sdlWindow File parser void readFile(std string path, std string amp data) std ifstream f(path.c str(), std ios binary) data.assign((std istreambuf iterator lt char gt (f)), (std istreambuf iterator lt char gt ())) Main int main(int argv, char args) SDL Window sdlWindow boringInitStuff() std string buffer readFile(". compile test.vert", buffer) const char cBuffer buffer.c str() GLuint shaderID glCreateShader(GL VERTEX SHADER) glShaderSource(shaderID, 1, amp cBuffer, nullptr) glCompileShader(shaderID) while(!SDL QuitRequested()) SDL GL SwapWindow(sdlWindow) return 0 But when I try to inspect the source code in gDEBugger, the source code is gone. Linking of course doesn't work aswell. The weird thing is, that the compilation error checking works. EDIT When I copy amp paste the main part into another opengl project, it works.


Is making an acceptable 3D engine possible using only SDL functions? I've been watching Javidx9's 3D engine series and I decided to start making it with SDL because it was something I had heard of and seemed simple enough. I'm not going to implement too complex graphical features anyway. So I start writing code, and I'm drawing my triangles with SDL DrawLine(), and I'm filling my triangles with SDL DrawLine, and I go to load up the Utah Teapot and the frames are stuttering quite a bit. I'm pretty sure I already know the answer to this question but I want to be sure Is it unrealistic to try to create a 3D engine without using raw OpenGL funcions? It would make sense that the frames are so bad because SDL would have to work through something like OpenGL so I'm just calling an abstracted DrawLine function that's just making the computer do extra stuff and slowing it down. By the way, I do know that SDL has OpenGL, but I (naively?) figured it would just be easier to go without it.


Loading models with opengl I'm developing a video game using OpenGL as graphic API and C programming language, and I'm creating all models with blender. One question I have is how you deal with models (vertices), I mean, once you have created a model and want to load them with OpenGL you use hard coded or a software module to load them on runtime?.


OpenGL Objects wont draw at certain angles while using lighting(shaders) I was following this tutorial (http www.lighthouse3d.com tutorials glsl 12 tutorial point light per pixel ) but when the camera is at a certain angle, if I had alpha test and blend enabled the cube i have in the scene wouldn't draw, otherwise they would be black(if alpha and blend was disabled) Any thoughts on what's going on? here is some relevant code glClearColor(0.6, 0.6, 0.6, 1) glMatrixMode(GL PROJECTION) glLoadIdentity() gluPerspective(80, (float)window.getSize().x (float)window.getSize().y, 0.01f, 1000.0) glMatrixMode(GL MODELVIEW) glEnable(GL TEXTURE 2D) glEnable(GL DEPTH TEST) glEnable(GL CULL FACE) glCullFace(GL BACK) glEnable(GL BLEND) glBlendFunc(GL SRC ALPHA, GL ONE MINUS SRC ALPHA) glEnable(GL ALPHA TEST) glAlphaFunc(GL GREATER, 0.1f) glEnable(GL COLOR MATERIAL) glShadeModel(GL SMOOTH) glEnable(GL LIGHTING) glEnable(GL LIGHT0) glEnable(GL AUTO NORMAL) glEnable(GL NORMALIZE) ..... void Lighting(Camera cam, sf Vector3f Pos) GLfloat amb 0.2, 0.2, 0.2, 1 glLightModelfv(GL LIGHT MODEL AMBIENT, amb) GLfloat diff 1, 1, 1, 1 GLfloat pos Pos.x, Pos.y, Pos.z, 1 glLightfv(GL LIGHT0, GL DIFFUSE, diff) glLightfv(GL LIGHT0, GL POSITION, pos) .... glLoadIdentity() glClear(GL COLOR BUFFER BIT GL DEPTH BUFFER BIT) cam.up(delta, window) Lighting(cam, Pos) sf Shader bind( amp shader) cube.draw() cube1.draw() window.display() sf Shader bind(NULL) draw function for cubes glPushMatrix() glTranslatef(pos.x, pos.y, pos.z) glBegin(GL QUADS) glColor3f(color.r 255, color.g 255, color.b 255) glVertex3f(0, 0, 0) glVertex3f(width, 0, 0) glVertex3f(width, height, 0) glVertex3f(0, height, 0) glVertex3f(width, 0, 0) glVertex3f(width, 0, length) glVertex3f(width, height, length) glVertex3f(width, height, 0) glVertex3f(0, 0, length) glVertex3f(0, 0, 0) glVertex3f(0, height, 0) glVertex3f(0, height, length) glVertex3f(width, 0, length) glVertex3f(0, 0, length) glVertex3f(0, height, length) glVertex3f(width, height, length) glVertex3f(width, 0, 0) glVertex3f(0, 0, 0) glVertex3f(0, 0, length) glVertex3f(width, 0, length) glVertex3f(0, height, 0) glVertex3f(width, height, 0) glVertex3f(width, height, length) glVertex3f(0, height, length) glEnd() glPopMatrix()


OpenGL additive vertex color mode Surely OpenGL has a way to set the vertex color mode. By default it is multiplication. When I have an existing texture on a quad to represent a player in my game, I want to add color to it. As of now, doing so only multiplies the color with the texels on the quad. So if I have a color that represents bright light say (128,128,128) what I want is additive behavior take the color in the texel and add the channels together. I have not found anything to do this automatically in OpenGL without the use of shaders or including a second draw step on one sprite with a different blend mode to simulate this.


GLSL sampler2D fallback to constant color? So I have the following situation I'm sharing a blinn shader accross many meshes. Some meshes have specular amp normal maps, others do not. I'd like to, without making the shader code too complicated, be able to specify a constant color instead of a texture, for the normal or specular maps. This is for example if a given mesh doesn't need one of those maps. The way I imagine it, I would just pass a flat "grey" as the specular map, for instance, and the shader could just act as if a texture was passed in. Is this possible? Ideally, I don't want to have an extra uniform for each mesh specifying whether or not the texture should be used. Another alternative would be to actually create a grey texture on the fly, if this is the better way, please advise on the simplest way to do this.


Tangent on generated sphere I have difficulties understanding the tangent bitangent concept for normal mapping, or rather the calculations of them. I draw a sphere which is generated with the code in the OpenGL redbook http www.glprogramming.com red chapter05.html. I use cube mapping to texture the sphere. Now, pretty much everything in the web links to http www.terathon.com code tangent.html. But in that algorithm, they use the texture coords u and v, which I don't have like this because my texture mapping is 3D... Any pointers to how I can compute the tangents and bitangents with this setup? Also, aren't the tangents just vectors orthogonal to the normal of a point on the sphere? To me it seems there could be an easier way.. Edit As far as I understand I need those values to be able to "apply" the normal from the normal map to the point on the sphere. (I'm not sure what the correct mathematical terminologies are here). In other words, to deviate the normals of any point on the sphere based on the normal map. I calculated the normals as point on surface center of sphere (which, in modelspace, when the center is (0,0,0), is just point on surface)


Texture artifacts depending on texture size I get some strange artifacting with textures depending on their size. I run OpenGL 3.3 with an GTX 580 so it should definitely support non power of two textures. I've narrowed down the problem specifically to the texture's size, I've tried checking if transparency had anything to do with it, color channels etc. As you can see, the 512x512 and 300x300 textures look just fine but the 437x437 is all distorted. What could be the cause of this and how can it be fixed? I could of course just stick to power of two textures which seem to work fine but since this is an personal educational project I really want to understand what's going on.


Animation of moving circle by square's outer surface I want to make this animation in OpenGL, here I attached a simple gif how I want it to looks like Main problem is that I can not figure out how to move by corner circle should smoothly move by corner, not to just jump to another side's begin position. import Blender from Blender import Draw,BGL from Blender.BGL import from math import sin,cos import time squareLength, squareX, squareY, circleRadius 200, 200, 200, 20 movingX, movingY 0, 0 def event(evt, val) if evt Draw.ESCKEY Draw.Exit() def gui() global movingX, movingY glClearColor(0.17, 0.24, 0.31, 1.0) glClear(BGL.GL COLOR BUFFER BIT) glLineWidth(1) glColor3f(0.74, 0.76, 0.78) glBegin(GL QUADS) glVertex2i(squareX, squareY) glVertex2i(squareX, squareY squareLength) glVertex2i(squareX squareLength, squareY squareLength) glVertex2i(squareX squareLength, squareY) glEnd() glColor3f(0.58, 0.65, 0.65) glPushMatrix() if movingX circleRadius if movingY lt squareLength movingY 1 else movingX 0 movingY squareLength circleRadius else if movingY squareLength circleRadius if movingX lt squareLength movingX 1 else movingX squareLength circleRadius movingY squareLength else if movingY lt 0 if movingX gt 0 movingX 1 else movingX circleRadius movingY 0 else if movingY gt 0 movingY 1 else movingX squareLength movingY circleRadius glTranslatef(movingX, movingY, 0) glBegin(GL LINE LOOP) for i in xrange(0, 360, 1) glVertex2f(squareX sin(i) circleRadius, squareY cos(i) circleRadius) glEnd() glPopMatrix() Draw.Redraw(1) Draw.Register(gui, event, None) Can you please say me, how can I optimize this code to make circle moving by corners? Just start learning computer graphics and think up such exercises for training, so I will really appreciate for any help.


Where to store OpenGL object id s When working with OpenGL, you often recieve integer id s to keep track of OpenGL objects. For example, representing a simple mesh, you may have a number of references to objects like so GLuint arrayBuffer GLuint elementArrayBuffer GLuint texture Having many meshes, the id s add up quickly. Therefore my problem is, where it is most logical and efficient to store them? Alternative 1 My first thaught was to hand out the id s to corresponding game entities. Something along the lines class Entity public GLuint arrayBuffer GLuint elementArrayBuffer GLuint texture Other methods... Then having a render class Create the buffers and textures and pass id s to entity. renderer.init(entity) Render with corresponding buffer texture id s stored in entity renderer.render(projection, view, entity) Where it then is easy enough, in the implementation of the render method, just picking id s and render with them. Some disadvantages is that this is a leaky abstraction, where OpenGL concepts are "leaked" to game entities. Which does not feel quite right. An advantage might be that the method supposedly is efficient. You do not have to find id s, you know them for each rendering pass. Alternative 2 Another alternative would be to store the id s internally in the renderer. For example, an internal data struct struct RenderData GLuint arrayBuffer GLuint elementArrayBuffer GLuint texture Then having an unordered map with references to each entity and corresponding RenderData std unordered map lt unsigned int, RenderData gt render data Then in the rendering method, the correct render data is fetched from the map only by a unique id that is stored in each entity. Advantages of this approach, is that it is less "leaky", where only the entity id is passed to the renderer, to know what data to use. Disadvantages may be slightly less efficiency, because of lookups in the unordered map? I would greatly appreciate inputs on this, what approach to prefer, or if there are any other approaches out there?


Why is OpenGL provided with latest GeForce drivers so extremely slow? I'm writting a code in OpenGL and using two computers an old and a new one. On the old computer (which I use for debugging creating implementation for the old GL) I have GeForce 5500 FX. Before windows reinstall on it, I had NVIDIA drivers with OpenGL 1.5. And everything worked perfectly. Games made quite good FPS, even with dozens or hundreds sprites. However, after XP reinstall, I installed the drivers provided with my video card but it seems there's no OpenGL at all (mysterious 'GDI Generic' renderer). So I tried to download the newest NVidia drivers. After their installation I saw there's OpenGL 2.3 but when I runned my app it worked with extremely low FPS (about 0.25, I mean I had to wait four seconds for any app reaction) with only one sprite. And as I loaded smaller images, the FPS relatively increased, but on the new computer it's always (no matter how big and how many sprites) speed, so it must be the perfomance problem. Without any sprites, it seemed it worked normal, but game without graphics doesn't make any sense. That's why I downloaded the oldest drivers for NVIDIA GeForce 5500 FX I found on the Nvidia site. But they're still providing OpenGL 2.0 (2.1 exactly). The problem's the same. I also tried to change all the properties of OpenGL to increase performance but it didn't help too. So what can I do? I'd like to find drivers with OpenGL 1.5 but it seems they're not on the NVIDIA site and most people say it's the best to download they from there.


How to render a texture partly transparent? Good Morning StackOverflow, I'm having a bit of a problem right now as I can't seem to find a way to render part of a texture transparently with openGL. Here is my setting I have a quad, representing a wall, covered with this texture (converted to PNG for uploading purposes). Obviously, I want the wall to be opaque, except for the panes of glass. There is another plane behind the wall which is supposed to show a landscape. I want to see the landscape from behind the window. Each texture is a TGA with alpha channel. The "landscape" is rendered first, then the wall. I thought it would be sufficient to achieve this effect but apparently it's not the case. The part of the window supposed to be transparent is black and the landscape only appears when I move past the wall. I tried to fiddle with GLBlendFunc() after having enabled it but it doesn't seem to do the trick. Am i forgetting an important step ? Thank you )


Storing and using UV and Normal Data with OpenGL I'm having trouble mapping UV coordinates to vertices in OpenGL. I'm binding my buffers and enabling all of my attrib arrays perfectly well and things are rendering but what I'm stuck on is how to map UV and Normal data. You can't just store UV and Normal data with the Vertex data, because obviously you'll be re using vertices, but not necessarily with the same Normal or UV. For clarity this is the general flow of what I'm doing at the moment I bind my shader program. I bind my vertex array buffer with GL.BindBuffer I Bind my element buffer with GL.BindBuffer I use GL.Uniform (1, 2, 3 or 4) to bind values to my uniform variables I enable all of my vertex buffer attributes with GL.EnableVertexAttribArrau and then encode their layout using GL.VertexAttribPointer I draw using GL.DrawElements I disable all of my vertex attrib arrays again I'm totally stuck on how to encode UV and Normal data to my vertex attributes. Do I need to use a second buffer? If so how does OpenGL know to use a different set of indices to find them? I'm totally lost and any help would be greatly appreciated.


How to use continious collision detection in a dynamic AABB tree I am currently writing a game in c using openGL, and I am currently using a kinetic sweep and prune algorithm for the broad phase and then using GJK Raycast GJK amp EPA for the narrow phase. However I have realized that kinetic sweep and prune may not be the best choice because there are many objects in the scene that are just static and cause a lot of swapping when an object moves. So basically I would like to implement a dynamic AABB tree for the broad phase knowing there will be only a few objects requiring continuous collision detection (but these objects are essential). However for these fast moving objects what is the best way to detect a possible collision with other objects in the broad phase? I am thinking about using an AABB that contains the object trajectory from one frame to another, is this a good idea? Or will this a lot of overhead due to many false positives? Also I haven't read to much about dynamic AABB trees but I think I understand the idea, the idea is for each object that moved check if it's AABB if overlapping with the tree node, if it is do the same check with it's children and do so until we are at the leaves of the tree. All help is greatly appreciated


Pixel perfect clickable picture in OpenGL C So I have a picture(for easier understanding of problem like this http www.lib.utexas.edu maps europe europe 95.jpg). My goal is to click on any of the countries and get what country I clicked. The picture is full of colors, not just simple lets say Germany is purple. Also if I hover above a country I could also do things, like highlight it, write some text in a bar, etc. What solutions popped in my mind Draw every slice into a mesh, and ray trace the click. (making lots of meshes is a lot of time) Draw a single quad with texture, make a pixelmap, and get the coordinates clicked, then look up in the table.(I have to make a map for every resolution) Is there any better way of doing this? Or are there any algorithms for it?


OpenGL Updating VAO array buffer range I am trying to stream data to a buffer which I have bound to a VAO vertex buffer binding point that I want to access through vertex attributes in the shader. Usually I stream to buffers which I have bound as GL UNIFORM BUFFERs and I do it like this create an immutable data storage glNamedBufferStorage(uboID, capacity, data, GL MAP WRITE BIT GL MAP PERSISTENT BIT GL MAP COHERENT BIT) map entire storage forever mappedPtr glMapNamedBufferRange(uboID, 0, capacity, GL MAP WRITE BIT GL MAP PERSISTENT BIT GL MAP COHERENT BIT) bind buffer to target(GL UNIFORM BUFFER) binding point glBindBufferBase(GL UNIFORM BUFFER, uboBinding, uboID) bind shader interface block to target binding point glUniformBlockBinding(shaderProgramID, blockIndex, uboBinding) Now the uniform block can be accessed in the shader program and i can stream to it like so copy data to mapped pointer at stream offset memcpy(mappedPtr uploadOffset, amp uploadData 0 , uploadSize) This is the important part tell the shader which range of the buffer to use glBindBufferRange(GL UNIFORM BUFFER, uboBinding, uboID, uploadOffset, uploadSize) increment offset uploadOffset uploadSize If I bind a buffer to a VAO and access its data as vertex attributes in the shader, I don t know how to give the shader the range in which the updated data can be found. I can give an offset when binding a buffer to a VAO when calling glVertexArrayVertexBuffer, but it has a few more parameters and does not seem like the right thing to call every frame. I have not gotten it to work with it, too. Is there something like glBindBufferRange for vertex buffers bound to VAOs?


Keeping ratio the same across devices on fixed screen game My game is an Android game using OpenGL ES 2.0 (But this question could apply to any platform). I have read many questions on here regarding ratio management, and also read many tutorials outside of this site, but I'm still really confused as to how to manage this. My game is a Fixed screen 2d platformer. By fixed screen, I mean the player sees the whole screen at once and the screen doesn't scroll. All action takes place on this one screen (kind of like Bubble Bobble). Therefore scrolling is not possible as we need to see the whole play area. On my development device, I've written everything to look perfect, like so What I've currently done is when the game is run on other devices, I resize my GLViewport so that I maintain ratio like so Obviously, this has it's own problem namely, it wastes screen real estate. Now, I would accept this reluctantly, if I couldn't find a better solution, however, Google's documentation states that it's not allowed (of sorts) see App uses the whole screen in both orientations and does not letterbox to account for orientation changes. So, finally, I just stretched it out to fit the screen like so This takes the whole screen, but frankly looks a little naff as everything is stretched. Am I out of options? I see some similar games on the Play Store (ie, fixed screen) and they seem to look identical on different screens (and nothing is stretched) and there doesn't appear to be any extra space, but I have absolutely no idea how they achieve this. Would love to hear from someone who has dealt with this problem themselves or has any ideas on how best to proceed.


Libgdx, TiledMap, and tearing My TiledMap tears when the window is specific sizes, resized, or the camera moves. The tileset is padded by 2px and have tried as high as 10px. Each tile is 70x70. Here are the pack.json settings, paddingX 2, paddingY 2, bleed true, edgePadding true, duplicatePadding true, maxWidth 4096, maxHeight 4096, filterMin Nearest, filterMag Nearest, ignoreBlankImages true, wrapX ClampToEdge, wrapY ClampToEdge, grid true, fast false Here is the code. Parameters params new Parameters() params.textureMinFilter TextureFilter.Nearest params.textureMagFilter TextureFilter.Nearest TileMap map new TmxMapLoader().load(file.getAbsolutePath(),params) So what am I doing wrong? If nothing, does that mean libgdx absolutely cannot handle TileMaps of any sort?


How do I calculate specular contribution in physically based rendering? I'm trying to implement physically based rendering, in a small game engine built for academic and learning purposes. I cannot understand the right way to calculate specular and diffuse contribution, based on the materials metallic and roughness values. We don't use any third party libraries or engines for rendering everything is hand written in OpenGL 3.3. Right now, I ues this Calculate contribution based on metallicity vec3 diffuseColor baseColor baseColor metallic vec3 specularColor mix(vec3(0.00), baseColor, metallic) I'm under the impression that the specular has to be dependant on the roughness, somehow. I was thinking to change it to this vec3 specularColor mix(vec3(0.00), baseColor, roughness) Again, I'm not sure. What is the right way to do it? Is there even a right way, or should I just use the 'trial and error' method until I get a satisfying result? Here is the full glsl code Calculates specular intensity according to the Cook Torrance model float CalcCookTorSpec(vec3 normal, vec3 lightDir, vec3 viewDir, float roughness, float F0) Calculate intermediary values vec3 halfVector normalize(lightDir viewDir) float NdotL max(dot(normal, lightDir), 0.0) float NdotH max(dot(normal, halfVector), 0.0) Note the following line could also be NdotL, which is the same value float NdotV max(dot(normal, viewDir), 0.0) float VdotH max(dot(viewDir, halfVector), 0.0) float specular 0.0 if(NdotL gt 0.0) float G GeometricalAttenuation(NdotH, NdotV, VdotH, NdotL) float D BeckmannDistribution(roughness, NdotH) float F Fresnel(F0, VdotH) specular (D F G) (NdotV NdotL 4) return specular vec3 CalcLight(vec3 lightColor, vec3 normal, vec3 lightDir, vec3 viewDir, Material material, float shadowFactor) Helper variables vec3 baseColor material.diffuse vec3 specColor material.specular vec3 emissive material.emissive float roughness material.roughness float fresnel material.fresnel float metallic material.metallic Calculate contribution based on metallicity vec3 diffuseColor baseColor baseColor metallic vec3 specularColor mix(vec3(0.00), baseColor, metallic) Lambertian reflectance float Kd DiffuseLambert(normal, lightDir) Specular shading (Cook Torrance model) float Ks CalcCookTorSpec(normal, lightDir, viewDir, roughness, fresnel) Combine results vec3 diffuse diffuseColor Kd vec3 specular specularColor Ks vec3 result lightColor (emissive diffuse specular) return result (1.0 shadowFactor)


What does "GL CLAMP TO EDGE should be used in NPOT textures" mean? I have two sRGB PNG images I am using for textures. One is 64x64, and works fine. The other is 64x47, and when I attempt to use it I get an error reason 'GL CLAMP TO EDGE should be used in NPOT textures' What does this mean, and how do I address it?


OpenGL gradient banding on Samsung Galaxy S2 Android phone I've got a live wallpaper out on the market which uses OpenGL to render some basic shapes and a flat plane. The simple lighting creates a gradient effect across the plane, which looks fine on most devices. The Samsung Galaxy S2 series seems to have some trouble rendering the gradient, though, as you can see in this screen shot The color banding looks awful, especially compared to this screen shot from an Incredible I'm using a 565 EGL config in both cases, so I believe this is just a display issue with the GS2 devices. Can anyone confirm this suspicion? Is there any solution to the banding?


Advanced copying between textures in OpenGL I have many RGBA textures in my project. I often copy a part of one texture into another texture using copyTexSubImage2D . I am probably able to copy just a specific channel by setting mask (colorMask). I would like to multiply (and store) the alpha of one texture by an alpha of another texture. Is it possible to do it somehow without creating and calling shaders? I am working with WebGL 1.0 (OpenGL ES 2.0).


OpenGL model not rendering properly I have been playing with OpenGL for a while and I came into the wall that I don't know how to pass. I am trying to render a model of an object based on a .obj file. In that file I have position coordinates, uv coordinates and indices of a positions and uv coordinates (faces). I am trying to render the model like so Get all the positions from the files Get all the uv coordinates from the file Get all the faces. Generate array of vertices with all the positions and uv coordinates in order defined by indices. Index the vertices 0,1,2,... Draw the indexed vertices. I got blocked when I tried just to render the model without the texture. I have been shown a monstrosity instead of what I am trying to achieve. When I have been drawing the model in the other way (get all the vertices and index them in the order they should be drawn) everything is fine but in this way I cannot texture the model the way I wanted. I am adding the code below Reading from the file std vector lt float gt verts container for vertices std vector lt unsigned int gt inds container for indexes of vertices std vector lt unsigned int gt texinds container for indexes of textures std vector lt float gt texs container for textures bool LoadFromFile(const std string amp path) std ifstream f(path) if (!f.is open()) return false while (!f.eof()) char line 128 f.getline(line, 128) std strstream s s lt lt line char junk char junk1 char junk2 char junk3 if ((line 0 'v') amp amp (line 1 't')) float Textu 2 s gt gt junk gt gt junk1 gt gt Textu 0 gt gt Textu 1 ingoring the first 2 characters (vt) before data texs.push back( Textu 0 ) texs.push back( Textu 1 ) if (line 0 'f') unsigned int Index 6 s gt gt junk gt gt Index 0 gt gt junk1 gt gt Index 1 gt gt Index 2 gt gt junk2 gt gt Index 3 gt gt Index 4 gt gt junk3 gt gt Index 5 ingoring f and every between indexes inds.push back( Index 0 1 ) texinds.push back( Index 1 1 ) inds.push back( Index 2 1 ) texinds.push back( Index 3 1 ) inds.push back( Index 4 1 ) texinds.push back( Index 5 1 ) if ((line 0 'v') amp amp (line 1 ' ')) float Vertex 3 s gt gt junk gt gt Vertex 0 gt gt Vertex 1 gt gt Vertex 2 verts.push back( Vertex 0 ) verts.push back( Vertex 1 ) verts.push back( Vertex 2 ) Creating array of vertices and idexing them float Vertices 89868 for (int i 0 i lt inds.size() i ) Vertices i verts inds i Creating array with the vertices in order defined in the index vector unsigned int indices 89868 for (int i 0 i lt inds.size() i ) indices i i I understand maybe I have made a stupid mistake somewhere but I am literally incapable of finding it.


Setting up OpenGL camera with off center perspective I'm using OpenGL ES (in iOS) and am struggling with setting up a viewport with an off center distance point. Consider a game where you have a character in the left hand side of the screen, and some controls alpha'd over the left hand side. The "main" part of the screen is on the right, but you still want to show whats in the view on the left. However when the character moves "forward" you want the character to appear to be going "straight", or "up" on the device, and not heading on an angle to the point that is geographically at the mid x position in the screen. Here's the jist of how i set my viewport up where it is centered in the middle setup the camera glMatrixMode(GL PROJECTION) glLoadIdentity() const GLfloat zNear 0.1 const GLfloat zFar 1000.0 const GLfloat fieldOfView 90.0 can definitely adjust this to see more less of the scene GLfloat size zNear tanf(DEGREES TO RADIANS(fieldOfView) 2.0) CGRect rect rect.origin CGPointMake(0.0, 0.0) rect.size CGSizeMake(backingWidth, backingHeight) glFrustumf( size, size, size (rect.size.width rect.size.height), size (rect.size.width rect.size.height), zNear, zFar) glMatrixMode(GL MODELVIEW) rotate the whole scene by the tilt to face down on the dude const float tilt 0.3f const float yscale 0.8f const float zscale 4.0f glTranslatef(0.0, yscale, zscale) const int rotationMinDegree 0 const int rotationMaxDegree 180 glRotatef(tilt (rotationMaxDegree rotationMinDegree) 2, 1.0f, 0.0f, 0.0f) glTranslatef(0, yscale, zscale) static float b 25 0 static float c 0 rotate by to face in the direction of the dude float a RADIANS TO DEGREES( atan2f( gCamera.orientation.x, gCamera.orientation.z)) glRotatef(a, 0.0, 1.0, 0.0) and move to where it is glTranslatef( gCamera.pos.x, gCamera.pos.y, gCamera.pos.z) draw the rest of the scene ... I've tried a variety of things to make it appear as though "the dude" is off to the right do a translate after the frustum to the x direction do a rotation after the frustum about the up y axis move the camera with a biased lean to the left of the dude Nothing i do seems to produce good results, the dude will either look like he's stuck on an angle, or the whole scene will appear tilted. I'm no OpenGL expert, so i'm hoping someone can suggest some ideas or tricks on how to "off center" these model views in OpenGL. Thanks!


When trying to render a texture in opengl after including the stb image.h file in the project i get a linker error Initially i gave the path of the stb image.h amp stb image.c file location C C include directories as adding the header file directly to the project was not working.


Do I need Texture Units when NOT using shaders? Does calling glActiveTexture() even make sense when not using shaders? I only have to switch the textures before drawing a buffer with glBindTexture(), right?


using heightmap to simulate 3d in an isometric 2d game I saw a video of an 2.5d engine that used heightmaps to do zbuffering. Is this hard to do? I have more or less no idea of Opengl(lwjgl) and that stuff. I could imagine, that you compare each pixel and its depthmap to the depthmap of the already drawn background to determine if it gets drawn or not. Are there any tutorials on how to do this, is this a common problem? It would already be awesome if somebody knows the names of the Opengl commands so that i can go through some general tutorials on that. greets! Great 2.5d engine with the needed effect, pls go to the last 30 seconds Edit, just realised, that my question wasn't quite clear expressed How can i tell Opengl to compare the existing depthbuffer with an grayscale texure, to determine if a pixel should get drawn or not?


Taking fixed direction on hemisphere and project to normal (openGL) I am trying to perform sampling using hemisphere around a surface normal. I want to experiment with fixed directions (and maybe jitter slightly between frames). So I have those directions vec3 sampleDirections 6 vec3(0.0f, 1.0f, 0.0f), vec3(0.0f, 0.5f, 0.866025f), vec3(0.823639f, 0.5f, 0.267617f), vec3(0.509037f, 0.5f, 0.700629f), vec3( 0.509037f, 0.5f, 0.700629), vec3( 0.823639f, 0.5f, 0.267617f) now I want the first direction to be projected on the normal and the others accordingly. I tried these 2 codes, both failing. This is what I used for random sampling (it doesn't seem to work well, the samples seem to be biased towards a certain direction) and I just used one of the fixed directions instead of s (here is the code of the random sample, when i used it with the fixed direction i didn't use theta and phi). vec3 CosWeightedRandomHemisphereDirection( vec3 n, float rand1, float rand2 ) float theta acos(sqrt(1.0f rand1)) float phi 6.283185f rand2 vec3 s vec3(sin(theta) cos(phi), sin(theta) sin(phi), cos(theta)) vec3 v normalize(cross(n,vec3(0.0072, 1.0, 0.0034))) vec3 u cross(v, n) u s.x u v s.y v vec3 w s.z n vec3 direction u v w return normalize(direction) EDIT This is the new code vec3 FixedHemisphereDirection( vec3 n, vec3 sampleDir) vec3 x vec3 z if(abs(n.x) lt abs(n.y)) if(abs(n.x) lt abs(n.z)) x vec3(1.0f,0.0f,0.0f) else x vec3(0.0f,0.0f,1.0f) else if(abs(n.y) lt abs(n.z)) x vec3(0.0f,1.0f,0.0f) else x vec3(0.0f,0.0f,1.0f) z normalize(cross(x,n)) x cross(n,z) mat3 M mat3( x.x, n.x, z.x, x.y, n.y, z.y, x.z, n.z, z.z) return M sampleDir So if my n (0,0,1) and my sampleDir (0,1,0) shouldn't the M sampleDir be (0,0,1)? Cause that is what I was expecting.