Why am I experiencing weird texture warping? I'm using cubemaps to render a skybox, in my game. Thinking this would be a simple task, I threw some stuff together using the tutorials I found online, particularly this one. Taking all of this together, I then adjusted the program to compensate for my particularly junky Linux laptop, by converting the GLSL to 120. However, this turned sour when I discovered that the texture I was loading, which is just a straight black line meant to test this very issue, is being horribly bent by my program. A short clip of my problem is shown on Youtube, here. In desperation, I asked this question on gamedev.net, without much success. My Shader code looks like this Vertex Shader version 120 attribute vec3 verPos uniform mat4 MVP uniform vec3 camPos varying vec3 texCoord void main() vec4 vertexPosition vec4(verPos, 1.0) texCoord verPos gl Position MVP vertexPosition Fragment Shader version 120 varying vec3 texCoord uniform samplerCube CubeMap void main() gl FragColor textureCube(CubeMap, texCoord) Rendering Code To avoid being spammy, I'll just assume that I loaded the images correctly, and not show off that particular mess. I'm using IMAGE Load from SDL2 to handle the texture loading, and I made the cube map clamp to edge and such. void SkyBox Draw() if(!loadedCheck) return glUseProgram(myProgID) glDisable(GL DEPTH TEST) glDepthFunc(GL LEQUAL) glm mat4 perspect glm perspective(45.0f, float(640) float(480), 0.1f, 3000.0f) vector3f playerPos player.myNPC.myEnt.myObject.getPosition() float playerAngY player.myNPC.myEnt.myObject.myAngle.y camPos glm vec3( 15.0f float(cos( playerAngY 1.62)), 0, 15.0f float(sin( playerAngY 1.62))) Convert my vector3f class to glm vec3 glm vec3 playerGLM glm vec3(playerPos.x, playerPos.y, playerPos.z) float playerAngX player.myNPC.myEnt.myObject.myAngle.x camPos is the position of the camera relative to the player's position glm mat4 view glm lookAt(camPos playerGLM, playerGLM, glm vec3(0,1,0)) view glm mat4(glm mat3(view)) To get rid of the translation matrix view 3 0 0 view 3 1 0 view 3 2 0 comb is equivalent to an MVP matrix glm mat4 comb perspect view GLuint matrixID glGetUniformLocation(myProgID, "MVP") glUniformMatrix4fv(matrixID, 1, GL FALSE, glm value ptr(comb)) GLuint camID glGetUniformLocation(myProgID, "camPos") GLuint sampler glGetUniformLocation(myProgID, "CubeMap") float camP 3 camPos.x, camPos.y, camPos.z glUniform3fv(camID, 3, camP) glActiveTexture(GL TEXTURE0 0) glBindTexture(GL TEXTURE CUBE MAP, myTexture) glBindBuffer(GL ARRAY BUFFER, vertexBuffer) glEnableVertexAttribArray(verAttrib) glVertexAttribPointer( verAttrib, 3, GL FLOAT, GL FALSE, 0, (void )0 ) glDrawArrays(GL TRIANGLES, 0, 36) glDepthFunc(GL LESS) glEnable(GL DEPTH TEST) All in all, I feel like this should be working. Why am I experiencing weird texture warping?


Moving a camera without rolling (tumble not arcball rotation) I'm trying to move my camera around using mouse keyboard. I'm looking for specific camera behaviour however, and I cant figure out how to get it right. What I've found, is that to get a maya tumble style camera, I need to multiply my xrotation in world space then my yrotation. Reversing the order it looks like this view cam move wasd in cam space, this works correctly yrot before world to camera space view xrot after model to world space This means my xrot(world) doesn't interfere with my yrot(eye), which avoids unwanted roll induced by regular cam space x rotation. My problem however, is that I want the xrotation to happen around a point (as if done in eye space) but without creating unwanted roll. I do not know how to get that result. According to my sources It should be as easy as translating inversely before xrotating, then translating back after, but its just not working. Perhaps someone knows how I can get my cam to spin (yaw) around a point, without causing the unwanted roll? SOLUTION Keeping track of pitch yaw (mouse move.xy) seperately, as well as the camera location, and making sure to multiply the yaw before the pitch. Pitching will create unwanted roll, but yawing wont create unwanted pitch, so its a matter of which you do first here. To move the camera in eye space, I do this make a mat3 rotation matrix and multiply it with current movement if (keys 'A' keys 'D' keys 'W' keys 'S' ) camlocation rotated then moved (glm normalize(vec3(keys 'A' keys 'D' , 0, keys 'W' keys 'S' )) move speed) mat3(glm rotate(mat4(1.0f), pitch, vec3(1, 0, 0))) mat3(glm rotate(mat4(1.0f), yaw, vec3(0, 1, 0))) which will be a value to add in world space Then under camera update, or where I build the view matrix, I do this view glm rotate(mat4(1.0f), pitch, vec3(1, 0, 0)) pitch radian float glm rotate(mat4(1.0f), yaw, vec3(0, 1, 0)) yaw also in radian glm translate(mat4(1.0f), camlocation) Just remember that in OpenGL GLM the matrix transformations are reverse order, due to how OpenGL does column row matrix computations. (Compared to directx it saves a transpose operation in the shader (apparently)) Making sure to yaw before pitching, and both after translating (reversed on paper) avoids the unwanted roll, wich yields the desired tumble maya effect!


Sorting a vector using array version of quick sort I'm coding a simple rendering engine using OpengGL and I wrote a class that manages a particle system. The class creates the particles and pushes them into a vector to be used by a renderer to draw them on screen. I need to order the particles from the farthest to the nearest to the camera (in order to solve problems with alpha blending and depth, having disabled depth testing for transparency), so I tried with the following code void ParticleRenderer render() prepare renderer ..... update particle state (position,ecc..) and remove it if necessary update returns a bool indicating if particle is still alive while (it ! mParticles.end()) if (!( it) gt update()) delete it it mParticles.erase(it) if (it mParticles.end()) break else continue it if (mParticles.size() gt 0) sortParticles( amp mParticles 0 , 0, mParticles.size() 1) for (Particle particle mParticles) ..... render particle ..... std cout lt lt getCameraDistance(particle) lt lt std endl std cout lt lt " " lt lt std endl mShader.unuse() glDisable(GL BLEND) void ParticleRenderer sortParticles(Particle particles, int low, int high) if (low gt high) return Particle temp particles low while (true) while (compareParticles(temp, particles high ) gt 0 amp amp low lt high) high if (low high) break else particles low particles high while (compareParticles(temp, particles low ) lt 0 amp amp low lt high) low if (low high) break else particles high particles low particles high temp int middle high sortParticles(particles, low, middle 1) sortParticles(particles, middle 1, high) double ParticleRenderer compareParticles(Particle particle1, Particle particle2) return getCameraDistance(particle1) getCameraDistance(particle2) double ParticleRenderer getCameraDistance(Particle particle) glm vec3 distance mCamera.getPosition() particle gt getPosition() return glm length(distance) but what I get on the console are all unsorted particles (the cout statement) and of course I have problems when the particles are rendered on screen. Am I missing something? I know I could use std sort and the STL algorithms, but since I'm learning I would like to know what I am doing wrong.


Heightmap terrain picking I've implemented an OpenGL based terrain unsing a tesselation shader for dividing each 'terrain cell' into the desired tiles. The heightmap is uploaded to the GPU and applied on the shader. When it comes to picking, I don't really know what to do. Testing triangles on intersection with the pick ray is not possible because only the GPU 'knows' the mesh. Is render to texture with an unique color the way to go? Or holding an additional mesh in RAM, only for picking collision?


C OpenGL loading models fast I'm looking for a faster solution that will allow me to load objects faster with OpenGL and currently when trying to load, parse and pass the data on my main thread it takes a while... Would multi threading be a reasonable solution to this and if so, how would I go about it? Would I make a second thread with the same context and save the data once it has loaded or... Would I create a second thread to load and parse the data, then pass it back to the first thread to save to the GPU? This is the limit of my knowledge of this subject at the minute, if anyone has any better solutions please drop me a comment.


How to draw the simplest grid map OpenGL 1.0 I want to draw a simple black amp white grid map, like that I have been searching for a way to generate tile, a tile map and tho and I want to draw this map and thats all. I mean that I want to draw it only once so it should be easy. I use OpenGL 1.0. How can I draw that and how should I draw should I draw an Image and place it like a map, should I draw a tile and multiple it ?


Difference and interaction between Viewport and Camera I'm very very confused about some very basic concepts in game grafical developing. The interaction between the individual components (camera, viewport, window sizes, gameworld sizes, ...) when rendering graphical things are still confusing me. As far as I understand A camera "filming" viewing something as long it is between the near and the far clipping plane Camera has a Width and Height which defines the area of what will get "viewed"... ? The viewport can connect to an camera the viewport is the area which will get shown withing the window the cameras view will get projected onto the viewport so if the camera has a size of 1024x768 and the viewport ist only 300x400, the 1024 pixels will get upset on 300 "real" pixels As you may have have recognized Im very unsure about this. Maybe you can help me with that. I want to run the test app down bellow in a way, that the picture will not get stretched. Also Im wondering what "game coordinates" are in that context. For Demo Cases and learning I've just created a piece of src package com.mygdx.game import ... public class MyGdxGame extends ApplicationAdapter public PerspectiveCamera cam public Model model public ModelBatch modelBatch public ModelInstance instance private FitViewport viewport Override public void create() modelBatch new ModelBatch() creating a camera gets width and height from the window so it will "fit" best in the current window cam new PerspectiveCamera(67, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()) cam.position.set(10f, 10f, 10f) cam.lookAt(0, 0, 0) cam.near 1f cam.far 300f cam.update() creating viewport width n height r not really necessary since it gets new values within the rezise() method correct? viewport new FitViewport(1920, 1080, cam) ModelBuilder modelBuilder new ModelBuilder() model modelBuilder.createBox(5f, 5f, 5f, new Material(ColorAttribute.createDiffuse(Color.GREEN)), Usage.Position Usage.Normal) instance new ModelInstance(model) Override public void render() Gdx.gl.glViewport(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()) Gdx.gl.glClear(GL20.GL COLOR BUFFER BIT GL20.GL DEPTH BUFFER BIT) what is happening here? cam.update() modelBatch.begin(cam) modelBatch.render(instance) modelBatch.end() Override public void dispose() model.dispose() Override public void resize(int w, int h) putting new values into the viewport and updating it will "resize" the camera ... ? float aspectRatio (float) w (float) h viewport.update((int) (h aspectRatio), h) viewport.update(1920, 1080) viewport.update(w, h)


How to reduce image size without pixelation? I see lots of games with smooth edges characters and high res images, however when I try to reduce images to say 64x64 for my character I just get a pixelated mess. even if I start with a 64x64 canvas I get pixelated edges. Should I be scaling with OpenGL? or is there some technique perhaps with photoshop or pixen that I am unaware of?


GLSL shader without a vertex array Ok so I have a idea for a neat GPU driven curve renderer, and I realised that the vertex shader can be hardwired to generate points of the curve segment (to be rendered as a line strip) without sending any vertex positions gl Position could be set completely procedurally. That said I'd still need to specify a "t" value per point via vertex attributes. Is it possible to specify attributes (ie via glVertexAttribPointer) without specifying vertices? Or does the GL need "space" in the buffers for vertices even if they aren't initialized.


How does GL INT 2 10 10 10 REV work for color data? Can anybody tell me how exactly to use GL INT 2 10 10 10 REV as type parameter in glVertexAttribPointer()? I am trying to pass color values using this type. What is the significance of "REV" suffix in this type? Does it require any special treatment in the shaders?


Detect Sprites, they are in Shape or Not which random draw in Cocos2d I have searched a lot on the web and found some helpful links but none solve my question. Link 1 Link 2 I have written some code, to draw lines with Touch methods, but I still have questions. Here is what I need help understanding. 1 Line has been cleared after draw complete (this might go in ccTouchesEnded method UIPangesture state End.) I am not sure how to draw custom shapes with UIPanGesture or Touch methods. 2 Is there any difference between capturing the whole game scenario for collision as like scheduleUpdate method and how do I find out if objects are colliding (these are randomly moving sprites and they have random shapes)? 3 How to Check whether a User drawn shape is closed or open (a convex shape or not)? 4 How to check random moving sprites inside drawn shape or outside? Here I have some code, but I am not sure whether it's useful or not. This code is in init method linePoints NSMutableArray alloc init create a simple rendertexture node and clear it with the color white rtx CCRenderTexture renderTextureWithWidth winSize.width height winSize.height rtx.position CGPointMake(winSize.width 2, winSize.height 2) self addChild rtx z 6 tag 101 brush CCSprite spriteWithFile "Line1.png" retain brush.scale 5.0f Draw line by touch move method. (void) ccTouchesMoved (NSSet )touchess withEvent (UIEvent )event UITouch touchMyMinge touchess anyObject CGPoint start self convertTouchToNodeSpace touchMyMinge CGPoint end touchMyMinge previousLocationInView touchMyMinge.view end CCDirector sharedDirector convertToGL end end self convertToNodeSpace end NSValue value NSValue valueWithCGPoint start linePoints addObject value rtx begin float distance ccpDistance(start, end) for (int i 0 i lt distance i ) float difx end.x start.x float dify end.y start.y float delta (float)i distance brush setPosition ccp(start.x (difx delta), start.y (dify delta)) brush visit rtx end I have attached two screen shots for more clarification. Please help me about on my technical query.


What's wrong with this camera implementation? I'm using WebGL and glMatrix and I implemented a camera. When a move backward, no problem. But when I move to the side and particularly forward, the camera becomes all glitchy. I implemented almost exactly the same camera before in C and it worked perfectly. I put the whole code on jsFiddle (with glMatrix because it's not in the list and I didn't find a url, sry). https jsfiddle.net ydx0Lr1v 14 Click and move the mouse to move around. Also, the more I decrease the speed of the camera movement, the more it works well. I put a high speed to dramatize the effect. I know I should make the speed of the camera depend on the time between each frame, but I haven't implemented an fps counter yet. Thanks! Edit Hum, that's strange. In jsFiddle the camera seems to work better when moving forward.


interpolating frames in a vertex shader My models are stored as a set of meshes, each with a vertex list and normal list per key frame, and indices for GL TRIANGLES which is shared for all frames. Each frame I lerp between two adjacent key frames to generate the vertices for that frame on the CPU and then draw it. How can I move this into a GLSL vertex shader? Can a shader interpolate between two sets of vertices, and how can I store those vertices on the GPU?


LibGDX Max number of textures? I've been developing a game targeted at android. I know not to think about program optimization until the project is finished, but I have to wonder how many textures most phones can handle safely without melting or murdering battery. I've seen that the max SIZE of a texture should be 1024 or 2048 pixels squared (I've been combining sprite sheets into 1024x1024 atlas's) but I can't help but wonder if there is a limit to how many of these I can use at runtime. I understand it should depend on the GPU but what spec determines it?


Directional shadow mapping view projection matrices I've got shadow mapping with directional lights working, but I believe I am constructing the view projection matrices wrong. Here's how I build them Mat4 viewMatrix LookAt(lighting.mCameraPosition (directionalLight.mLightDirection Z FAR 2.0f), directionalLight.mLightDirection, Vec3(0.0f, 1.0f, 0.0f)) Mat4 lightVP CreateOrthographicMatrix( Z FAR, Z FAR, Z FAR, Z FAR, Z NEAR, Z FAR) viewMatrix The problem is the shadows become skewed and change depending on the camera position, which is bad. What is the proper way of doing this? EDIT 1) No, that is what I'm not sure about currently as you said it is the camera position and thus the shadows moves around when I move the camera, which is bad what should be the actual position, since directional lights have no position? 2) Also using Z FAR DOES make it pixelated which is my second problem but must not the boundaries be Z FAR in all directions, otherwise objects in the view range may not cast shadows?


Is there an efficient, available online, algorithm for converting a matrix of squares into a triangle strip? Imagine having a 4x4 square, with 16 smaller squares inside of it, with associated data on what the squares should look like (ie., opacity, colour, etc...). Is there an existing, efficient, algorithm, for converting this set of squares into an open gl compatible triangle strip?


Rendering text with SDL2 and OpenGL I've been trying to have text rendering in my OpenGL scene using SDL2. The tutorial I came across is this one Rendering text I followed the same code, and I get text rendering fine. However the issue I'm having is that there is obviously a "conflict" between the OpenGL rendering and the SDL Renderer used in the code. When I run my scene the text displays but everything else keeps flickering. The following gif shows the issue Any idea on how to overcome this while still just using SDL2 and OpenGL, not another library or anything. Thanks


Playing movies with OpenGL in Java I am trying to play a movie file into an OpenGL texture in a Java application. I am using JOGL and have a basic OpenGL scene, but I have no idea how to play a movie into a texture. The only thing I could find was this http paulo.ragonha.me blog 2008 08 java movie playback jogl fobs4jmf.html It is quite old and uses JOGL 1.1 and Fobs4JMF, which is no longer maintained. I managed to get it to build in eclipse but it wasn't able to read my movie clip. I could probably convert the movie clip to an older codec to see if that works, but I would rather have a modern solution. I am a professional game developer, so the OpenGL part is no problem, but I am new to Java (coming from a C background). Is there any modern library that wraps this functionality in an easy to use package?


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?


How to handle wildly varying rendering hardware getting baseline I've recently started with mobile programming (cross platform, also with desktop) and am encountering wildly differing hardware performance, in particular with OpenGL and the GPU. I know I'll basically have to adjust my rendering code but I'm uncertain of how to detect performance and what reasonable default settings are. I notice that certain shader functions are basically free in a desktop implemenation but can be unusable in a mobile device. The problem is I have no way of knowing what features will cause what performance issues on all the devices. So my first issue is that even if I allow configuring options I'm uncertain of which options I have to make configurable. I'm wondering also wheher one just writes one very configurable pipeline, or whether I should have 2 distinct options (high low). I'm also unsure of where to set the default. If I set to the poorest performer the graphics will be so minimal that any user with a modern device would dismiss the game. If I set them even at some moderate point, the low end devices will basically become a slide show. I was thinking perhaps that I just run some benchmarks when the user first installs and randomly guess what works, but I've not see a game do this before.


OpenGL HUD is flickering when rotating the camera I draw game HUD after drawing 3D scene. When I move the camera quickly, HUD starts flickering. I noticed that it happens only if the distance between the camera and an object its looking at changes after camera's position transformation.It does not happen if there is no mesh in front of the camera. I use separate shader program for HUD rendering. Have tried to enable disable depth test, blending already. Using VBOs to draw stuff. Render code def render() glClear(GL COLOR BUFFER BIT GL DEPTH BUFFER BIT) glEnable(GL DEPTH TEST) glDepthFunc(GL LESS) glEnable(GL CULL FACE) Shader.setCurrentShader(Shader.SHADER VOXEL) Shader.currentShader().enable() set3DMatrices() updateShaderVOXEL() val world WorldRegistry.getWorldByID(0) world.renderWorld() Shader.currentShader().disable() Shader.setCurrentShader(Shader.SHADER SIMPLE) Shader.currentShader().enable() set3DMatrices() ManagerRegistry.renderManagerSceneBoundingBox.render() ManagerRegistry.renderManagerSceneRectangle.render() ManagerRegistry.renderManagerSceneLine.render() Shader.currentShader().disable() glDepthMask(false) glDisable(GL DEPTH TEST) glDisable(GL CULL FACE) Shader.setCurrentShader(Shader.SHADER HUD) Shader.currentShader().enable() set2DMatrices() GL13.glActiveTexture(GL13.GL TEXTURE0) Texture unit 0 GL11.glBindTexture(GL11.GL TEXTURE 2D, Texture.getTexture("screen cursor default.png")) HUDRenderRegistry.HUDRender.render() Shader.currentShader().disable() glDepthMask(true) glfwSwapBuffers(window) EDIT I made a video(captured on the phone, so the quality is bad, sorry) and the rectangle in it is actually fully red, not yellow. https youtu.be HhHEfrgsfiU


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?


Generating geometry when using VBO Currently I am working on a project in which I generate geometry based on the players movement. A glorified very long trail, composed of quads. I am doing this by storing a STD Vector, and removing the oldest verticies once enough exist, and then calling glDrawArrays. I am interested in switching to a shader based model, usually examples I see the VBO is generated at start and then that's basically it. What is the best route to go about creating geometry in real time, using shader VBO approach


How to draw a mini map OpenGL OpenGL ES? I'm trying to draw a mini map. Succeeded to put current screen to smaller screen (mini map) via FBO. But I do not know how to make the mini screen brighter when hover. You can imagine that, the real screen is very large, and you have a mini screen in the left bottom (like StarCraft), and when you hover on it, it's brighter than others. I'm trying to use multiple attachment in FBO but it doesn't work. In fact that I don't know how does multiple attachment work, how is it used for?. My way, draw map with attachment 0 first, draw a hovering rectangle with attachment 1. Bind then draw all of the attachment textures in legal sequence (NOT WORKED). I mean, the first draws a mini "large screen". The second draws a brighter rectangle when hover. Can anyone lead me how to do this or give me any suggestion? Thank you very much!


With what projection matrix should I render a portal to a texture? I'm using OpenGL. I have problem with my engine's portal implementation. To create the first portal I do create a virtual camera with the position of the second portal and the correct orientation render whole scene from virtual camera to the texture using FBO render the first portal using the texture created before. The problem The virtual camera is rendering to the texture with the main projection view, so when I use this texture to render the first portal, everything is rescaled. The virtual camera should only render some part of the view to prevent scaling. The problem could perhaps be solved by changing the virtual camera's projection matrix, but I don't know how to calculate such a matrix. Here's how it looks This picture shows one portal (the texture is a little bit deformed on bottom and top, but that's not important now) and some other objects. The second portal is behind the camera, and the camera is in the middle between the two portals. We can clearly see that the portal texture is rescaled down to the portal size. As I said before, I think the virtual camera should have another projection matrix, but how do I calculate it? Or is there a better way?


How to implement translation, scale, rotation gizmos for manipulating 3D object's transforms? I am in the process of developing a basic 3D editor. It uses OpenGL for rendering a 3D world. Right now my scene is just a few boxes of different sizes and I am at the stage where I want to be able to select each box and then move scale rotate it to achieve any transform I want. How can I solve the problem of implementing both the rendering of these tool's gizmos(or handles, or how people usually call them), and also picking them on each axis to perform the change in the transform with my mouse? For clarity My research so far suggested the cleanest approach is to have an axis aligned bounding box per arrow in the gizmo and another one per square (the ones that move the object in a plane rather than a single axis) and then cast a ray from the mouse position and see what it collides with. But this is still a bit too abstract for me, I would appreciate further guidance in how this algorithm would go (pseudocode is more than enough)


GLSL Sphere from Vertex I am working on a particle simulation where we have a lot of spheres which can have different radii. Using this tutorial http mmmovania.blogspot.de 2011 01 point sprites as spheres in opengl33.html (see also code below) I was able to create a sphere from a point, but they all have the size from glPointSize(). Is it possible to extend this with a radius? version 330 out vec4 vFragColor uniform vec3 Color uniform vec3 lightDir void main(void) calculate normal from texture coordinates vec3 N N.xy gl PointCoord 2.0 vec2(1.0) float mag dot(N.xy, N.xy) if (mag gt 1.0) discard kill pixels outside circle N.z sqrt(1.0 mag) calculate lighting float diffuse max(0.0, dot(lightDir, N)) vFragColor vec4(Color,1) diffuse Maybe of interest I am using version 120 for my shaders. Or, is there a better way to do this? So, combining the two answers I now have void Draw setGeometry(float geometry, float velocity, float radius, GLuint size) this gt size size glGenBuffers(1, amp vertexData) glBindBuffer(GL ARRAY BUFFER, vertexData) glBufferData(GL ARRAY BUFFER, size 3 sizeof(float), geometry, GL STATIC DRAW) glBindBuffer(GL ARRAY BUFFER, 0) glGenBuffers(1, amp velocityData) glBindBuffer(GL ARRAY BUFFER, velocityData) glBufferData(GL ARRAY BUFFER, size 3 sizeof(float), velocity, GL STATIC DRAW) glBindBuffer(GL ARRAY BUFFER, 0) glGenBuffers(1, amp radiusData) glBindBuffer(GL ARRAY BUFFER, radiusData) glBufferData(GL ARRAY BUFFER, size sizeof(float), radius, GL STATIC DRAW) glBindBuffer(GL ARRAY BUFFER, 0) And the drawing method void Draw paint(GLenum mode) glBindBuffer(GL ARRAY BUFFER, vertexData) glEnableVertexAttribArray(0) glVertexAttribPointer(0, 3, GL FLOAT, GL FALSE, 0, 0) glEnableVertexAttribArray(1) glVertexAttribPointer(1, 3, GL FLOAT, GL FALSE, 0, 0) glEnableVertexAttribArray(2) glVertexAttribPointer(2, 1, GL FLOAT, GL FALSE, 0, 0) glDrawArrays(mode, 0, size 3 sizeof(float)) glDisableVertexAttribArray(0) And the Vertex Shader version 130 attribute vec3 position attribute vec3 velocity attribute float size uniform mat4 MVP uniform mat4 MV void main() gl PointSize size gl Position MVP vec4(position, 1.0) The problem is that when gl PointSize 15 is set, they are drawn well. When I make it equal with size, then it looks like this http picpaste.com Big particles daIBnJCG.png Works better now. Particles still getting bigger as they move along.


Texture being rendered to main frame buffer? I'm using Ogre 1.10.12 (openglES2 as render system) to create a manual texture like this rtt texture Ogre TextureManager getSingleton().createManual("RttTex", Ogre ResourceGroupManager DEFAULT RESOURCE GROUP NAME, Ogre TEX TYPE 2D, m size.width(), m size.height(), 0, Ogre PF A1R5G5B5, Ogre TU RENDERTARGET) m renderTexture static cast lt Ogre GLES2FBORenderTexture gt (rtt texture gt getBuffer() gt getRenderTarget()) m renderTexture gt addViewport(m camera) m renderTexture gt getViewport(0) gt setClearEveryFrame(true) m renderTexture gt getViewport(0) gt setBackgroundColour(Ogre ColourValue Red) m renderTexture gt getViewport(0) gt setOverlaysEnabled(false) then, I bind the texture to the FBO and retrieve the FBO's ID like Ogre GLES2FrameBufferObject ogreFbo 0 m renderTexture gt getCustomAttribute("FBO", amp ogreFbo) Ogre GLES2FBOManager manager ogreFbo gt getManager() manager gt bind(m renderTexture) GLint id glGetIntegerv(GL FRAMEBUFFER BINDING, amp id) My concern is that id is 0 so I cannot render this texture outside my display, it's getting visible which I don't want it to be. Shouldn't be ogre creating an unused frame buffer object when creating a manual texture with the TU RENDERTARGET parameter?


Why would I want to set a minimal OpenGL version before creating the context? Typical GLFW applications have these lines after glfwInit() glfwWindowHint(GLFW CONTEXT VERSION MAJOR, 3) glfwWindowHint(GLFW CONTEXT VERSION MINOR, 3) glfwWindowHint(GLFW OPENGL PROFILE, GLFW OPENGL CORE PROFILE) glfwWindowHint(GLFW OPENGL FORWARD COMPAT, GL TRUE) And similarly glfwMakeContextCurrent(window) I get that glfwMakeContextCurrent is needed before sending calls to the OpenGL API, but the doc says You can require a minimum OpenGL version by setting the GLFW CONTEXT VERSION MAJOR and GLFW CONTEXT VERSION MINOR hints before creation But why would I want that? Why would I cut options for OpenGL versions? I did not understand that, if I am interpreting it correctly in the first place


OpenGL Applications Bring computer to halt Whenever I run any application that utilizes the OpenGL interface, my entire computer comes to a halt, but it doesn't do this when it utilizes the DirectX interface. I run both Linux (Ubuntu 15.10) and Windows 10 so this isn't exactly caused by the operating system. I'm running the latest drivers from NVidia and both OS's are completely up to date. This is happening on a Dell Precision M6300 laptop (Core 2 Dou 2.5ghz, NVidia Quadro FX 1600M, 4gb ram) and although it's a bit old it should be completely capable of rendering a blank OpenGL window using GLFW, however it slows down my entire computer (every application starts freezing to where it becomes unusable until the application is closed). This happens in games like Left4Dead, Half life 2, etc., but also in my own OpenGL programs. The same programs and games do not have the same effect on my desktop (although much better hardware, a blank OpenGL window shouldn't matter). Any help would be greatly appreciated, thank you. Also my apologies if I left out any vital information or made a confusing question. Just ask me to clarify or add something and I shall. Added the code for the blank OpenGL window in question include lt stdio.h gt include lt stdlib.h gt include lt GL glew.h gt include lt GLFW glfw3.h gt include lt glm glm.hpp gt using namespace glm int main(int argc, char argv ) if ( !glfwInit() ) fprintf(stderr, "Failed to initialize GLFW n") return 1 glfwWindowHint(GLFW SAMPLES, 4) 4x AA glfwWindowHint(GLFW CONTEXT VERSION MAJOR, 3) GL 3.3 glfwWindowHint(GLFW CONTEXT VERSION MINOR, 3) glfwWindowHint(GLFW OPENGL FORWARD COMPAT, GL TRUE) glfwWindowHint(GLFW OPENGL PROFILE, GLFW OPENGL CORE PROFILE) GLFWwindow window window glfwCreateWindow(1024, 768, "OpenGL Tutorial", NULL, NULL) if (window NULL) fprintf(stderr, "Failed to create OpenGL Window.") return 1 glfwMakeContextCurrent(window) glewExperimental true if (glewInit() ! GLEW OK) fprintf(stderr, "Failed to initiate the glew context!") return 1 glfwSetInputMode(window, GLFW STICKY KEYS, GL TRUE) do glfwSwapBuffers(window) glfwPollEvents() while (glfwGetKey(window, GLFW KEY ESCAPE ) ! GLFW PRESS amp amp glfwWindowShouldClose(window) 0)


glTranslate, how exactly does it work? I have some trouble understanding how does glTranslate work. At first I thought it would just simply add values to axis to do the transformation. However then I have created two objects that would load bitmaps, one has matrix set to GL TEXTURE public class Background float vertices new float 0f, 1f, 0.0f, 4f, 1f, 0.0f, 0f, 1f, 0.0f, 4f, 1f, 0.0f .... private float backgroundScrolled 0 public void scrollBackground(GL10 gl) gl.glLoadIdentity() gl.glMatrixMode(GL10.GL MODELVIEW) gl.glTranslatef(0f, 0f, 0f) gl.glPushMatrix() gl.glLoadIdentity() gl.glMatrixMode(GL10.GL TEXTURE) gl.glTranslatef(backgroundScrolled, 0.0f, 0.0f) gl.glPushMatrix() this.draw(gl) gl.glPopMatrix() backgroundScrolled 0.01f gl.glLoadIdentity() and another to GL MODELVIEW public class Box float vertices new float 0.5f, 0f, 0.0f, 1f, 0f, 0.0f, 0.5f, 0.5f, 0.0f, 1f, 0.5f, 0.0f .... private float boxScrolled 0 public void scrollBackground(GL10 gl) gl.glMatrixMode(GL10.GL MODELVIEW) gl.glLoadIdentity() gl.glTranslatef(0f, 0f, 0f) gl.glPushMatrix() gl.glMatrixMode(GL10.GL MODELVIEW) gl.glLoadIdentity() gl.glTranslatef(boxScrolled, 0.0f, 0.0f) gl.glPushMatrix() this.draw(gl) gl.glPopMatrix() boxScrolled 0.01f gl.glLoadIdentity() Now they are both drawn in Renderer.OnDraw. However background moves exactly 5 times faster. If I multiply boxScrolled by 5 they will be in sinc and will move together. If I modify backgrounds vertices to be float vertices new float 1f, 1f, 0.0f, 0f, 1f, 0.0f, 1f, 1f, 0.0f, 0f, 1f, 0.0f It will also be in sinc with the box. So, what is going under glTranslate?


I can't seem to figure out what's causing this bug with the "layout" keyword in GLSL I have a GL shader file whose first few lines currently look like this version 120 layout (location 0) in vec3 position layout (location 1) in vec2 vertexUV When I try to compile this shader when running the program, it returns this error 0 2(1) error syntax error, unexpected NEW IDENTIFIER From what I know, this means that the word layout is giving it trouble. What am I doing wrong? Do I need to provide more information?


Why should i set glClearColor and setProjectionMatrix in render method many time in LibGDX? import com.badlogic.gdx.Game import com.badlogic.gdx.graphics.OrthographicCamera import com.badlogic.gdx.graphics.g2d.SpriteBatch public class MyGame extends Game public OrthographicCamera camera public SpriteBatch batch .. Override public void create() .. batch new SpriteBatch() Gdx.gl.glClearColor(0, 0, 0, 1) batch.setProjectionMatrix(camera.combined) Override public void render(float delta) Gdx.gl.glClear(GL20.GL COLOR BUFFER BIT) .. In LibGDX Doc Gdx.gl.glClearColor(0, 0, 0, 1) and batch.setProjectionMatrix(camera.combined) is setting in render() method at a time. I use this definitions in create() method at once, and it is running perfect. So why should i use this definitions in render() method? is't it a performance loss?


OBJ file, face materials and drawing them with OpenGL I'm implementing a model class which loads OBJ and MTL files, and ran into an issue or question with face materials. Consider the following example It's a cube with 5 sides Gray and 1 side Green. mtllib Materials.mtl o Cube v 1.000000 1.000000 1.000000 v 1.000000 1.000000 1.000000 v 1.000000 1.000000 1.000000 v 1.000000 1.000000 1.000000 v 1.000000 1.000000 1.000000 v 1.000000 1.000000 1.000000 v 1.000000 1.000000 1.000000 v 1.000000 1.000000 1.000000 usemtl Green f 7 8 4 3 usemtl Gray f 5 8 2 1 f 6 7 3 2 f 8 5 1 4 f 1 2 3 4 f 8 7 6 5 The OBJ file obviously shares same vertices for adjacent faces even if the faces get different materials. When drawing such a cube with OpenGL however, I would need to duplicate the vertices of the adjacent faces with different materials, since every vertex specifies the color it has and I have two different colors for the same vertices here, depending on the face and the different material it has. If I wouldn't do that, the adjacent faces would smooth over to the different materials. First Did I get this correctly or am I missing an OpenGL "feature" here which lets me "specify" the color of a whole triangle face rather than a single vertex? Second If not, is there an easier way to keep track of the faces materials and duplicating the adjacent vertices if they get different materials? What would be the easiest way to implement different materials on one object?


Adjusting view matrix when glViewPort resizing I have an issue when my window resizes. I have a simple MVP shader like this gl Position projection view model vec4(in Position, 1.0) to render a map in my game scene. The map is extremely simple that it simply offers a lane's vertex. And what I need to do is drawing it inside the window. So I set up my MVP matrix individually, the "view" and "model" matrix remains the same because all I want to do is drawing a static map. "perspective" is the only matrix need to change since I want to have a zoom feature that I can zoom in out by changing fovy. "perspective" is updated by calling glm perspective(glm radians(fovy), (float)width height, near, far) and my view matrix is calculated by glm lookAt(camera pos, camera pos camera front, camera up) However, when I resize the viewport, I find everything changed. I mean by default, the resolution gonna drop when my window goes larger if I didn't do anything(like updating the glViewPort()). But the behavior I wanna achieve is like "I could see more part of the map when I made my window size larger". Therefore I believe that I should keep my viewport resolution same (glViewPort(0, 0, screen width, screen height)). And updating perspective matrix by changing the ratio when new window's width and height comes in. Then the final step is to update the camera's position to update view matrix. However I stuck here for a while coz I don't know how to adjust it. I believe this is a common issue but I cannot even find a source talking about it. Do I think it the wrong way? Do I need to change Camera's position to update my view matrix to achieve the resize behavior? Platform Ubuntu 16.04, OpenGL3.3 , C 14


Making a camera in a 2D game (glOrtho) I'm trying to make a camera that follows my character and it seems I've managed. However, I don't know how to limit that my camera don't follow me when my character reachs the boundaries of the windows (it's ugly see black spaces beyond my tile map x x). So, this is my code public class Camera public void update(Vector2f spritePos) Vector2f pos new Vector2f(spritePos.getX() 368, spritePos.getY() 268) if((pos.getX() 368 gt 368) amp amp (pos.getY() 268 gt 268)) glMatrixMode(GL PROJECTION) glLoadIdentity() glOrtho(pos.getX(), pos.getX() Display.getDisplayMode().getWidth(), pos.getY() Display.getDisplayMode().getHeight(), pos.getY(), 1, 1) glMatrixMode(GL MODELVIEW) I substract 368 to the X position, because I want to place my character at the center of my camera. Same with 268. This is a bad way to archieve this, because my camera "jumps" roughly to the position of my character . Thank you very much.


Opengl create tunnel TRIANGLES and texture coords on a 3d path I have a path, lets say a bezier, or a circle. I d like to make a continously 3d cylinder (tunnel) on it (R 0.5f) How can I calculate tha TRIangles (TRIANGLE STRIP) coordinate, and the texture coords right?


OpenGL ES 2.0 Controlling Transparency in Fragment Shader The following is the OpenGL ES 2.0 simple GLSL Fragment Shader, I use to place textures on polygons, to render 2D sprites. varying mediump vec2 TextureCoordOut uniform sampler2D Sampler void main() gl FragColor texture2D(Sampler, TextureCoordOut) gl FragColor vec4(texture2D(Sampler, TextureCoordOut).xyz, TextureCoordOut.w 0.5) The fragment shader places voxels with alpha information taken from the source 2D texutre(.png image). Apart from alpha information, I need to control overall polygon sprite transparency to achieve Fade In Fade Out effects. Could you show me, please, how to modify the above shader to control the overall transparency, besides the alpha information? Note The commented out line is used for my attempts to achieve the transparency. I wish to combine both the alpha information with the overall polygon sprite transparency. Thanks.


Are interleaved vertex data formats better than non interleaved formats? I have been reading up on data formatting for 3D objects so that I can render my meshes as fast as possible in OpenGL. I am quite new to OpenGL so bear with me. The format for interleaving your meshes goes something like position, normal, texture1, texture2 this I understand Most formats for 3D meshes, however, don't use this structure. From my understanding the interleaved format is fast for execution but isn't necessarily the best in terms of size, since you never really have as many unique normals as you do vertices, since (if you are using hard shading) all normals for a face would be the same. A hard shaded basic cube for example has 8 unique vertices and 6 unique normals. So my question is, is it worth it to set up an interleaved format like this despite the fact that if you had 3 separate buffers you would use MUCH less data? Also (remember I'm new) is it somehow possible to do pack your vertex information like all positions, all normals, all tex1, all tex2 so all of one type in a sequence and have different sets of indices for each type? Or is that just dumb?


Lightmap not moving properly with camera movement I ve implemented a 2d lighting system (also with support of 2d shadows). Everything was fine until today when I realised that its not working when moving the camera, as it looks like the lightmap has still some offset than the camera position (for example, if camera.x is 100, the lightmap is x 200) Little video showing the problem Video I can post any piece of code, for now Im sending you my light shader(fragment) version 440 in vec4 fragmentColor in vec2 TexCoords out vec4 color uniform float ambientStrength uniform vec2 resolution uniform sampler2D textureSampler uniform sampler2D lightMapTexture uniform bool textureON void main() Calc the ligthMap vec2 lightCoord (gl FragCoord.xy resolution) vec4 lightMap texture(lightMapTexture,lightCoord) if (textureON) vec4 textureColor texture(textureSampler, TexCoords) vec4 finalColor lightMap textureColor fragmentColor color vec4(finalColor.rgb,textureColor.a fragmentColor.a) else color fragmentColor Vertex version 440 in vec3 vertexPosition in vec4 vertexColor in vec2 vertexUV out vec4 fragmentColor out vec2 TexCoords uniform mat4 Projection uniform mat4 View uniform mat4 Model void main() gl Position Projection View Model vec4(vertexPosition.xy,0,1) fragmentColor vertexColor TexCoords vec2(vertexUV.x, 1.0 vertexUV.y) At first I thought that its a problem with resolution, but everything is good. Everything is working fine until I move the camera(or change its position from 0,0 to something else all other objects have good position, also mouse coords)


Why does this geometry shader slow down my program so much? I have an OpenGL program, and I'm rendering a terrain mesh. I displace the vertices in the vertex buffer and don't really color them in the fragment shader yet. I'm adding a geometry shader one part at a time. Before I added the geometry shader, when I was just programming the fragment and vertex shading steps of the pipeline, I was getting framerates of about 30 . Enough that I couldn't notice any choppiness. After adding the geometry shader, I get around 5 frames per second. Why? This is the entirety of the geometry shader version 420 layout (triangles) in layout (triangle strip, max vertices 3) out void main() for (int i 0 i lt gl in.length() i ) gl Position gl in i .gl Position EmitVertex() EndPrimitive() Isn't this exactly what OpenGL was doing without the geometry shader?


HDR Tone Mapping choosing parameters I implement HDR in my graphics engine (deferred rendering) based on this document link I save a luminance in a texture (RGBA16F) this way const float delta 1e 6 vec3 color texture(texture0, texCoord).xyz float luminance dot(color, vec3(0.2125, 0.7154, 0.0721)) float logLuminance log(delta luminance) fragColor vec4(logLuminance, logLuminance, 0.0, 0.0) first channel stores max luminance during a minification process Then I can calculate an average luminance and find a max luminance. The delta 1e 6. Is that a good choice ? Can I calculate "a" (equation 2) dynamically to achieve better results ?


How is terrain editing implemented like a sculpt tool? Some creativity sandbox games have a terrain editing feature. When thinking of a terrain, I'm thinking of a grid of vertices. The elevation of each vertex is then determined by a heightmap (image). And the user can edit this elevations, so you get mountains and valleys. Most times terrain editing is 'just' changing the height component of the positions of vertices in an existing grid of a fixed amount of vertices. Now I see some games that make it possible to do the following This seems way more complex than just a grid and a heightmap. I have thought a lot about this, but what is the best most common approach to implement this? I think it's difficult to find a good data structure for the vertices. I'm pretty sure, during editing, vertices are also created and added into the terrain, which also seems complex. All attempts to create indices seems a hell of a job to me. (Think of rendering this in triangle strips)


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?


Accessing struct in glut I have to write a game for a uni project using openGL glut. I am just going to use a generic example code as I'm just looking for a solution to one specific problem Using glut, I have to call a function 'glutDisplayFunc(display) ' in the main function. I am also using an IdleFunc(update). The problem is that, as described here, the 'display' function cannot pass anything. I have some structs outside my main that I wish to be initialized in the main, and be accessible by display and update. Hopefully some code will explain my problem better include lt gl glut.h gt struct Player GLfloat x GLfloat y GLfloat z int score ... function prototypes (showing how I would normally pass the struct) void InitPlayer (Player amp player) void DrawPlayer (Player amp player) void UpdatePlayer (Player amp player) void main (int argc, char argv) Player player InitPlayer(player) ... glut openGL initialisation code left out ... glutDisplayFunc (display) glutReshapeFunc (reshape) glutIdleFunc (update) glutMainLoop() void display() DrawPlayer(player) void update () UpdatePlayer(player) glutPostRedisplay () end The above code doesn't work I hope it demonstrates what I would like to do though. Access the struct 'player' in 'display' and 'update', having the same values stored globally. How would I go about ?


Combining rotation,scaling around a pivot with translation into a matrix In short I need to combine rotation (in the form of a quaternion), scaling around a pivot point along with translation into a transformation matrix. The long I am trying to implement a proprietary model format. This format includes animations. Part of that animation involves generating a matrix which combines rotation (in the form of a quaternion) and scaling around a pivot point, with translation into a transformation matrix. I am using OpenGL and the OpenGL math library (GLM) Someone else has already implemented parts of the proprietary model format using DirectX. The part in question was implemented in directX like this D3DXMatrixTransformation( amp BaseMatrix, amp ModelBaseData gt PivotPoint, NULL, amp ScalingVector, amp ModelBaseData gt PivotPoint, reinterpret cast lt D3DXQUATERNION gt ( amp RotationVector), amp TranslationVector) I found the WINE implementation of this function and attempted to duplicate it like this mat4 m1, m2, m3, m4, m5, m6, m7, p1, p2, p3, p4, p5 m5 glm translate(0,0,0) m7 glm translate(pivot translationVector) m1 glm translate( pivot) m3 glm scale(scalingVector) m6 glm mat4 cast(rotationQuaternion) Convert quaternion to a matrix m2 amp m4 are identity p1 m1 m2 p2 p1 m3 Apply scaling first p3 p2 m4 p4 p3 m5 p5 p4 p5 p4 m6 mat4 result p5 m7 (I realize glm translate(0,0,0) is the identity matrix) Unfortunately neither the scaling nor the rotation seems to work correctly like this. So I took another approach based off of this ordering of translation, rotation and scaling. mat4 result glm scale(scalingVector) glm translate(pivot) glm mat4 cast(rotationQuaternion) glm translate(translationVector) However the scaling does not appear to be around the pivot point and I'm not entirely sure about the rotation. Does anyone have any tips on how to accomplish this?


Additive blending problems I'm trying to get the blend of two images to work without luck. I have a render target on which I have an object, then I want to render again the same object in same position but with different light condition. My goal is to add the result of this two render so I tried to do something like glEnable(GL BLEND) glBlendFunc (GL ONE , GL ONE) .... glClear( GL COLOR BUFFER BIT GL DEPTH BUFFER BIT) render on render target A change light condition do not clear now render on render target A again with new light condition glDisable(GL BLEND) display render target A I am surely missing something because not only just the first image shows, but the object is transparent. I am extremely sorry if the question is stupid but I'm very new to such things. Thank you. edit Following the answer of Sam Johnston I've edited my code but, although I solved the transparency, the results are not added (to make sure of this I render one with a completely red light and one with a green light) together, but I get just the first render as result glEnable(GL BLEND) glBlendFunc (GL ONE , GL ZERO) glClear( GL COLOR BUFFER BIT GL DEPTH BUFFER BIT) render on render target A change light condition glBlendFunc (GL ONE , GL ONE) do not clear now render on render target A again with new light condition glDisable(GL BLEND) display render target A Have I misunderstood the answer? Juan


Indirect indexing (uv coords read from texture) In the vertex shader, I need to make a texture fetch, where the texture coordinate itself is read from some other texture. vec2 uv texture(someTexture,coords).xy vec4 val texture(otherTexture,uv).xyzw As far as I know, the second sample has undefined results, because the value of uv is outside of uniform flow control. Is there any way to efficiently (i.e., not copy back the contents of the texture and upload it as a uniform to the shader or something) do what I want to do?


openGL textures in bitmap mode For reasons detailed here I need to texture a quad using a bitmap (as in, 1 bit per pixel, not an 8 bit pixmap). Right now I have a bitmap stored in an on device buffer, and am mounting it like so glBindBuffer(GL PIXEL UNPACK BUFFER, BFR.G (T 1) 2 ) glTexImage2D(GL TEXTURE 2D, 0, GL RGB, W, H, 0, GL COLOR INDEX, GL BITMAP, 0) The OpenGL spec has this to say about glTexImage2D "If type is GL BITMAP, the data is considered as a string of unsigned bytes (and format must be GL COLOR INDEX). Each data byte is treated as eight 1 bit elements..." Judging by the spec, each bit in my buffer should correspond to a single pixel. However, the following experiments show that, for whatever reason, it doesn't work as advertised 1) When I build my texture, I write to the buffer in 32 bit chunks. From the wording of the spec, it is reasonable to assume that writing 0x00000001 for each value would result in a texture with 1 px wide vertical bars with 31 wide spaces between them. However, it appears blank. 2) Next, I write with 0x000000FF. By my apparently flawed understanding of the bitmap mode, I would expect that this should produce 8 wide bars with 24 wide spaces between them. Instead, it produces a white 1 px wide bar. 3) 0x55555555 1010101010101010101010101010101, therefore writing this value ought to create 1 wide vertical stripes with 1 pixel spacing. However, it creates a solid gray color. 4) Using my original 8 bit pixmap in GL BITMAP mode produces the correct animation. I have reached the conclusion that, even in GL BITMAP mode, the texturer is still interpreting 8 bits as 1 element, despite what the spec seems to suggest. The fact that I can generate a gray color (while I was expecting that I was working in two tone), as well as the fact that my original 8 bit pixmap generates the correct picture, support this conclusion. Questions 1) Am I missing some kind of prerequisite call (perhaps for setting a stride length or pack alignment or something) that will signal to the texturer to treat each byte as 8 elements, as it suggests in the spec? 2) Or does it simply not work because modern hardware does not support it? (I have read that GL BITMAP mode was deprecated in 3.3, I am however forcing a 3.0 context.) 3) Am I better off unpacking the bitmap into a pixmap using a shader? This is a far more roundabout solution than I was hoping for but I suppose there is no such thing as a free lunch.


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!


Render Queue Sorting, HOW? Recently I'm trying to implement a render queue sorting system, i.e., ordering my renderable objects in an array in such a way that the overhead of OpenGL state changes are minumum. After some googling, the most ideal one (to me) is to generate an integer key value for each renderable object, and the sorting is based on that value. Once done sorting, objects that have similar rendering states (same shader, texture, distance, etc.) will be close to each other, so we can just loop through the object array and submit the draw calls for rendering. Here's a detailed explanation Order your graphics draw calls around! My problem is, how do I loop through the renderable object's array to submit their draw calls for actual rendering? Do I need to keep track of the current OpenGL states manually? What have come to my mind is (for each renderable object) if(objects i .getShader() ! m currentShader) m currentShader objects i .getShader() m currentShader.bind() if(objects i .getTexture() ! m currentTexture) m currentTexture objects i .getTexture() m currentTexture.bind() ... and so on object i .getMesh().draw() Seems not so performance friendly to me, but I can't find any further explanation on how to submit the actual draw calls form the object's array either on the article I've provided or other sites I can find. Perhaps there's something I have missed?


Why doesn't glBindVertexArray work in this case? From my understanding of what glBindVertexArray does and how it works, the following code should work fine First init glGenVertexArraysOES(1, amp vertexArray) glBindVertexArrayOES( vertexArray) glGenBuffers(1, amp buffer) glBindBuffer(GL ARRAY BUFFER, buffer) glBufferData(GL ARRAY BUFFER, kMaxDrawingVerticesCount sizeof(GLKVector3), NULL, GL DYNAMIC DRAW) glGenBuffers(1, amp indexBuffer) glBindBuffer(GL ELEMENT ARRAY BUFFER, indexBuffer) glBufferData(GL ELEMENT ARRAY BUFFER, kMaxDrawingVerticesCount 1.5 sizeof(GLuint), NULL, GL DYNAMIC DRAW) glEnableVertexAttribArray(GLKVertexAttribPosition) glVertexAttribPointer(GLKVertexAttribPosition, 3, GL FLOAT, GL FALSE, sizeof(GLKVector3), BUFFER OFFSET(0)) glBindVertexArrayOES(0) And later add new geometry glBindVertexArrayOES( vertexArray) glBufferSubData(GL ARRAY BUFFER, 0, (GLintptr) data.vertices.length, data.vertices.bytes) glBufferSubData(GL ELEMENT ARRAY BUFFER, 0, (GLintptr) data.indices.length, data.indices.bytes) glBindVertexArrayOES(0) However, it doesn't work (there is screen output, but it looks like the buffers were changed between each other). Binding the vertex array is not enough for the vertex indices buffer to get bound? Because, if I do this glBindVertexArrayOES( vertexArray) glBindBuffer(GL ARRAY BUFFER, buffer) lt note this line glBindBuffer(GL ELEMENT ARRAY BUFFER, indexBuffer) lt note this line glBufferSubData(GL ARRAY BUFFER, 0, (GLintptr) data.vertices.length, data.vertices.bytes) glBufferSubData(GL ELEMENT ARRAY BUFFER, 0, (GLintptr) data.indices.length, data.indices.bytes) glBindVertexArrayOES(0) Everything works looks as expected. I find it strange, since the vertex array should have taken care of the buffer binding. Otherwise, what's the purpose to have a vertex array if you still have to bind all the buffers?


Should the modelview and projection matrices be calculated in the shader or on the CPU? At minimum I would have a camera with rotation and world position projections parameters such as angle of view and perspective vs. orthographic and meshes with scale, angle, and world position. When rendering a mesh I am wondering if I should calculate the final transformation matrix on the CPU and pass it to my shader, or if I should calculate the transformation matrix inside my shader.


Why am I not getting an sRGB default framebuffer? I'm trying to make my OpenGL Haskell program gamma correct by making appropriate use of sRGB framebuffers and textures, but I'm running into issues making the default framebuffer sRGB. Consider the following Haskell program, compiled for 32 bit Windows using GHC and linked against 32 bit freeglut import Foreign.Marshal.Alloc(alloca) import Foreign.Ptr(Ptr) import Foreign.Storable(Storable, peek) import Graphics.Rendering.OpenGL.Raw import qualified Graphics.UI.GLUT as GLUT import Graphics.UI.GLUT(( )) main IO () main do ( progName, args) lt GLUT.getArgsAndInitialize GLUT.initialDisplayMode GLUT.SRGBMode window lt GLUT.createWindow "sRGB Test" To prove that I actually have freeglut working correctly. This will fail at runtime under classic GLUT. GLUT.closeCallback Just (return ()) glEnable gl FRAMEBUFFER SRGB colorEncoding lt allocaOut glGetFramebufferAttachmentParameteriv gl FRAMEBUFFER gl FRONT LEFT gl FRAMEBUFFER ATTACHMENT COLOR ENCODING print colorEncoding allocaOut Storable a gt (Ptr a gt IO b) gt IO a allocaOut f alloca ptr gt do f ptr peek ptr On my desktop (Windows 8 64 bit with a GeForce GTX 760 graphics card) this program outputs 9729, a.k.a. gl LINEAR, indicating that the default framebuffer is using linear color space, even though I explicitly requested an sRGB window. This is reflected in the rendering results of the actual program I'm trying to write everything looks washed out because my linear color values aren't being converted to sRGB before being written to the framebuffer. On the other hand, on my laptop (Windows 7 64 bit with an Intel graphics chip), the program prints 0 (huh?) and I get an sRGB default framebuffer by default whether I request one or not! And on both machines, if I manually create a non default framebuffer bound to an sRGB texture, the program correctly prints 35904, a.k.a. gl SRGB. Why am I getting different results on different hardware? Am I doing something wrong? How can I get an sRGB framebuffer consistently on all hardware and target OSes?


Java LWJGL How can I click to interact with objects? I want to be able to click on a monster to walk to him and start attacking him. The part that doesnt make sense to me is the conversion between the mouse position, and the actual terrain position. There are camera angles to worry about, heights, seperate terrains, how is this done???? I am using Java LWJGL and rendering with OpenGL 4.4


Noisy edges, smoothing out edges between faces via fragment shader I have a generated terrain, with hexagonal geometry, as per screenshot below I then generate biomes, but as you can see the borders between them are really ugly and straight. To hide that hexagonal origin, I would need to smooth out the borders between biomes. This is how it looks now in wireframe with real tringular faces What I'm aiming for is something more like this Each vertex has attibute that holds the biome type, I can also add special attributes to the vertices on the edge between two biomes, but I just don't seem to be able to figure out how to pull this off in shader code, obviously noise is involved here, but how do I make it continous across multiple faces and entire border of multiple biomes? I'm rendering with WebGL using THREE.js


What does the identity matrix really do? I understand that multiplying by the identity matrix is like multiplying by 1. Why would you multiply a matrix that will only contain the same result? Also, I'm experimenting with some OpenGL code and found some very interesting things. Like for example When you use setIdentity(), the image rotates slower Matrix.setIdentityM(mProjectionMatrix, 0) Matrix.rotateM(mProjectionMatrix, 0, angleInDegrees, 0.0f, 0.0f, 1.0f) But if you try to remove the setIdentity(), the image will rotate so fast... first it will rotate clockwise so fast, and then it will become slower until it stops and then it will begin to rotate counter clockwise, and then will stop again, then rotate clockwise. I really don't understand how the identity matrix affects them despite multiplying by 1. Can someone explain to me what's going on? Here is the tutorial I am following.


Rectangular area light illuminance colour banding I'm currently working on an implementation of rectangular area lights but I am having some issues with the illuminance calculation, which gives me serious colour banding across the entire lit area. I'm using the paper published by DICE, "Moving Frostbite to Physically Based Rendering" (http www.frostbite.com 2014 11 moving frostbite to pbr ) as my base for implementation (Listing 12). This is the relevant code used Solid angle of the rectangle define M PI 3.14159265358979323846 float RectangleSolidAngle(vec3 worldPos, vec3 p0, vec3 p1, vec3 p2, vec3 p3) vec3 v0 p0 worldPos vec3 v1 p1 worldPos vec3 v2 p2 worldPos vec3 v3 p3 worldPos vec3 n0 normalize(cross(v0, v1)) vec3 n1 normalize(cross(v1, v2)) vec3 n2 normalize(cross(v2, v3)) vec3 n3 normalize(cross(v3, v0)) float g0 acos(dot( n0, n1)) float g1 acos(dot( n1, n2)) float g2 acos(dot( n2, n3)) float g3 acos(dot( n3, n0)) return g0 g1 g2 g3 2.0f M PI Illuminance calculation float RectangleIlluminance(vec3 worldPos, vec3 worldNormal, AreaLightData lightSource) float result 0.0f if (dot((worldPos lightSource.position), lightSource.normal) gt 0.0f) float hWidth lightSource.halfWidth float hHeight lightSource.halfHeight vec3 p0 lightSource.position lightSource.right hWidth lightSource.up hHeight vec3 p1 lightSource.position lightSource.right hWidth lightSource.up hHeight vec3 p2 lightSource.position lightSource.right hWidth lightSource.up hHeight vec3 p3 lightSource.position lightSource.right hWidth lightSource.up hHeight float solidAngle RectangleSolidAngle(worldPos, p0, p1, p2, p3) float illuminance solidAngle 0.2f ( Saturate(dot(normalize(p0 worldPos), worldNormal)) Saturate(dot(normalize(p1 worldPos), worldNormal)) Saturate(dot(normalize(p2 worldPos), worldNormal)) Saturate(dot(normalize(p3 worldPos), worldNormal)) Saturate(dot(normalize(lightSource.position worldPos), worldNormal))) result illuminance return result The paper mentions some level of banding but it should not be on the level which I am currently getting, which can be seen in motion in this video https youtu.be gmkOOxIYc9s . These images show the illuminance without shadows or anything. From what I can gather from the paper, the code is correct. The current solution is deferred, reconstructing position using the depth stencil texture and sampling normals from a RGBA32F texture (trying to eliminate precision issues). A directional light also seems to produce some level of banding, although not as visible as with the area light, which can be seen in the following images. So maybe it's still just a precision issue? The code for handling my depth and position reconstruction looks like this uniform sampler2D gDepthStencil vec4 ReconstructWSPosition(float z, vec2 uv f) vec4 sPos vec4(uv f 2.0f 1.0f, z, 1.0f) sPos gInvProjView sPos return vec4((sPos.xyz sPos.w ), sPos.w) void main() ivec2 pixel ivec2(gl GlobalInvocationID.xy) float depth texelFetch(gDepthStencil, pixel, 0).r 2.0f 1.0f vec4 wPosition ReconstructWSPosition(depth, uv) Which to me looks correct, but I might be missing something. Any other ideas or suggestions? Maybe a matter of tonemapping HDR problems?


OpenGL Fragment Shader simulate LCD slow response time I have a very simple OpenGL view rendering 2 triangles with a single texture applied. The minimum setup for rendering a 2d game. What i do is redraw the texture for every frame and easily get 60fps. I would like to add an effect simulating LCD slow response by outputting pixels that are the average between the current and the previous frame. The pseudo code of fragment shader would look like this varying vec2 v TexCoordinate uniform sampler2D u Texture void main() gl FragColor (texture2D(u Texture, v TexCoordinate) PIXEL PREVIOUS FRAME) 2 PIXEL PREVIOUS FRAME gl FragColor Well, i think shaders can't keep a persistent variable like PIXEL PREVIOUS FRAME, then i really don't know how to tackle this problem. Any suggestion?


VBO rendering crashed with glDrawArrays I'm playing around in LWJGL3 and I'm experiencing an issue regarding glDrawArrays. At glDrawArrays the JVM crashes. I'm using modern OpenGL and therefore I have my own shaders and matrix calculations. The pipeline I've programmed is quite complex so pasting all the code here isn't of any use. Vertex shader version 330 core uniform mat4 projectionMatrix uniform mat4 viewMatrix uniform mat4 modelMatrix layout (location 0) in vec3 in position void main() gl Position (projectionMatrix viewMatrix modelMatrix) vec4(in position, 1.0f) Fragment shader version 330 core void main() gl FragColor vec4(1.0f, 0.0, 1.0f, 1.0f) I'm trying to draw 1 point to the screen using a VBO. Creation of the VBO float vboData new float 0.0f, 0.0f, 0.0f FloatBuffer buffer BufferUtils.createFloatBuffer(vboData) vbo id glGenBuffers() glBindBuffer(GL ARRAY BUFFER, vbo id) glBufferData(GL ARRAY BUFFER, buffer, GL STATIC DRAW) glBindBuffer(GL ARRAY BUFFER, 0) And the rendering of the point using glDrawArrays glClear(GL COLOR BUFFER BIT GL DEPTH BUFFER BIT) testShader.bind() pipeline.applyMatrices(testShader) glBindBuffer(GL ARRAY BUFFER, vbo id) glVertexAttribPointer(0, 3, GL FLOAT, false, 12, 0) glDrawArrays(GL POINTS, 0, 1) glBindBuffer(GL ARRAY BUFFER, 0) pipeline.setCameraPosition(new Vector3f(0.0f, 0.0f, 0.0f), new Vector3f(0.0f, 0.0f, 0.0f)) testShader.unbind() GLFWUtils.swapBuffers() Using GLIntercept I managed to get a log of every OpenGL call made glClearColor(1.000000,0.000000,1.000000,1.000000) glPointSize(10.000000) glGenBuffers(1,000000001E0F6FC0) glBindBuffer(GL ARRAY BUFFER,1) glBufferData(GL ARRAY BUFFER,12,0000000025EB8D90,GL STATIC DRAW) glBindBuffer(GL ARRAY BUFFER,0) glCreateProgram() 1 glCreateShader(GL VERTEX SHADER) 2 glCreateShader(GL FRAGMENT SHADER) 3 glShaderSource(2,1,000000001E0F6FC0,000000001E0F6FC8) glShaderSource(3,1,000000001E0F6FC0,000000001E0F6FC8) glCompileShader(2) glCompileShader(3) glGetShaderiv(2,GL COMPILE STATUS,000000001E0F6FC0) glGetShaderiv(3,GL COMPILE STATUS,000000001E0F6FC0) glAttachShader(1,2) glAttachShader(1,3) glLinkProgram(1) glEnableVertexAttribArray(0) glClear(GL DEPTH BUFFER BIT GL COLOR BUFFER BIT) glUseProgram(1) glGetUniformLocation(1,"projectionMatrix") 1 glUniformMatrix4fv(1,1,false, 0.671312, 0.000000, 0.000000, 0.000000, 0.000000, 0.895083, 0.000000, 0.000000, 0.000000, 0.000000, 1.000020, 1.000000, 0.000000, 0.000000, 0.020000, 0.000000 ) glGetUniformLocation(1,"viewMatrix") 2 glUniformMatrix4fv(2,1,false, 1.000000,0.000000,0.000000,0.000000,0.000000,1.000000,0.000000,0.000000,0.000000,0.000000,1.000000,0.000000,0.000000,0.000000,0.000000,1.000000 ) glGetUniformLocation(1,"modelMatrix") 0 glUniformMatrix4fv(0,1,false, 1.000000,0.000000,0.000000,0.000000,0.000000,1.000000,0.000000,0.000000,0.000000,0.000000,1.000000,0.000000,0.000000,0.000000,0.000000,1.000000 ) glBindBuffer(GL ARRAY BUFFER,0) glVertexAttribPointer(0,3,GL FLOAT,false,12,0000000000000000) glDrawArrays(GL POINTS,0,1) I've carefully tested a few things The shaders compile and link fine The matrices calculated look correct (you can double check inside the GLIntercept log) The VBO is correctly created and filled with the correct data The attribute pointer ( layout 1) is enabled The matrices are correctly sent to the shader (this happens at pipeline.applyMatrices) What am I missing? Interesting debug finding I'm running this on nVidia. On a Intel graphics CPU it runs, but nothing shows on the screen!


Voxel engine artifacts There are white little dots between blocks at random places, mainly at very near blocks. They disappear when I move the mouse and change the view direction. I use Vertex Arrays with glVertexAttributePointer to send the data directly to the shader. The shader only adds some fake light based on the face direction and draws the pixels. What could be the reason for the small white artifacts? Chunk render code public void renderChunk() glPushMatrix() glTranslatef(pos.x world.chunkSize.x, 0.0f, pos.z world.chunkSize.z) glBindBuffer(GL ARRAY BUFFER, vao id) glVertexAttribPointer(world.game.positionAtt, 3, GL FLOAT, false, 32, 0) glVertexAttribPointer(world.game.normalAtt, 3, GL FLOAT, false, 32, 12) glVertexAttribPointer(world.game.texCoordAtt, 2, GL FLOAT, false, 32, 24) glDrawArrays(GL TRIANGLES, 0, arraySize 8) glBindBuffer(GL ARRAY BUFFER, 0) glPopMatrix() Vertex Shader attribute vec3 in position attribute vec3 in normal attribute vec3 in texcoord varying vec2 texture coordinate varying vec3 normal void main() gl Position gl ModelViewProjectionMatrix vec4(in position, 1.0) normal in normal texture coordinate in texcoord Fragment Shader varying vec2 texture coordinate varying vec3 normal uniform sampler2D texture void main() float add if (normal.x 1.0 normal.z 1.0) add 0.65 else if (normal.y ! 1.0) add 0.8 else add 1.0 gl FragColor texture2D(texture, texture coordinate) add Enlarge the image by click it to notice the artifacts.


Why do we move the world instead of the camera? I heard that in an OpenGL game what we do to let the player move is not to move the camera but to move the whole world around. For example here is an extract of this tutorial OpenGL View matrix In real life you're used to moving the camera to alter the view of a certain scene, in OpenGL it's the other way around. The camera in OpenGL cannot move and is defined to be located at (0,0,0) facing the negative Z direction. That means that instead of moving and rotating the camera, the world is moved and rotated around the camera to construct the appropriate view. Why do we do that?


Peer to peer first person shooter I've been developing a first person shooter massive multiplayer online roleplaying game for my small business, and was wondering if it would be feasible to use peer to peer technology to communicate between players, without the use of an intermediary server (as our company does not have enough funds for a high speed connection to run a game server on). How would such Peer to peer technology be best implemented in such a game? Here's a few of the options I've been considering a) Divide the game into segments, and have each segment be played on a separate P2P "mesh" (currently named XRevolution) b) Have one mesh for all portions of the game, and place all of the players on a single grid c) Some other P2P solution I've already used option A (considering only one area of the game is done) on a small scale (4 computers), but am wondering how well that would scale when thousands of computers would potentially be bound to the same mesh. Here's a list of possible concerns with P2P technology During penetration testing, it was identified that a client could spoof packets to lie about the state of the game to other peers, allowing people to cheat. This is identified as "medium" risk, as it could be prevented to a certain extent through various security routines that would be integrated within the game (such as encryption, movement prediction, double checking state with other peers, AI, etc.) Lag was originally a problem on slower networks, but now movement prediction and other techniques are used to reduce the effect of lag, and disconnect peers whose lag is too high. However, a problem which remains is the amount of time it would take on a larger scale network to find peers (other players), and establish connections. Due to the amount of time it would take to connect to so many peers, solution A would seem optimal to solve this particular problem A problem with solution A, would be in game chat between meshes (as no two peers in different meshes can communicate with each other, except for the purpose of relaying), however, this problem could be potentially solved by using something in between solutions A and B (such as creating a separate mesh for inter mesh communication, which would be specific to each player or something) What's the best way to do something like this? Solution A, or B, something in between the two, or an entirely different solution altogether. Due to our budget, using a server to facilitate communication between players is completely out of the question, so it would be nice to use a P2P solution, otherwise the project would have to be abandoned.


How can i draw a curve in modern Opengl? OpenGl is capable of rendering points, lines, triangles and quads but what if i want to draw a bezier curve? I read online you should use something called GL STRIP, but the solutions were using either legacy Opengl, or they were not explaining well the process. The question is How can i render bezier curves in Modern Opengl? I'm using C .


Do Java and Actionscript use OpenGL? As far as I know there are only 3 base graphics libraries on Windows, the GDI, OpenGL and DirectX, is that correct, so that means that Java, Actionscript and all language use one of these 3 libraries if they are to display graphics, or maybe Java has it's own graphics library API?


How to animate a model in WebGL? I created a human model in Blender, exported the vertices and indices into a JSON file and render the model in a browser using WebGL. Now I created a walk and jump animation in Blender and would like to do the same with WebGL. I saw examples that use a list of vertices for every frame of the animation. Is this the way to go? Do I need to export the vertices for every frame for every animation?


OpenGL sluggish performance in extracting texture from GPU I'm currently working on an algorithm which creates a texture within a render buffer. The operations are pretty complex, but for the GPU this is a simple task, done very quickly. The problem is that, after creating the texture, i would like to save it. This requires to extract it from GPU memory. For this operation, i'm using glGetTexImage(). It works, but the performance is sluggish. No, i mean even slower than that. For example, an 8MB texture (uncompressed) requires 3 seconds (yes, seconds) to be extracted. That's mind puzzling. I'm almost wondering if my graphic card is connected by a serial link... Anyway, i've looked around, and found some people complaining about the same, but no working solution so far. The most promising advise was to "extract data in the native format of the GPU". Which i've tried and tried, but failed so far. Edit by moving the call to glGetTexImage() in a different place, the speed has been a bit improved for the most dramatic samples looking again at the 8MB texture, it knows requires 500ms, instead of 3sec. It's better, but still much too slow. Smaller texture sizes were not affected by the change (typical timing remained into the 60 80ms range). Using glFinish() didn't help either. Note that, if i call glFinish() (without glGetTexImage), i'm getting a fixed 16ms result, whatever the texture size or complexity. It really looks like the timing for a frame at 60fps. The timing is measured for the full rendering saving sequence. The call to glGetTexImage() alone does not really matter. That being said, it is this call which changes the performance. And yes, of course, as stated at the beginning, the texture is "created into the GPU", hence the need to save it. Edit 2 I've also tried to use glReadPixels(), instead of glGetTexImage(). But it's worse unfortunately. Approximately twice slower. Edit 3 Here is the code. Note that it uses a "framework" that i've not developed. So some of the function calls here are not OpenGL standard. But they are nonetheless quite self expressive. glDisable(GL BLEND) Simple construction, for test the resulting texture is output into render buffer renderbufx1.bind() clear(0,0,0,0) simpleDiffShader.bind() simpleDiffShader.setTexture("TextureRef",img.tex,0) simpleDiffShader.setTexture("TextureDown",renderbufx2.getTexture(),1) img.tex gt drawPart( 1, 1,2,2,0,0,1,1) simpleDiffShader.unbind() renderbufx1.unbind() Not really useful, but just in case, the result is copied into another render buffer. renderbufx1 is going to be displayed, and i want to avoid any access conflict savebufx1.bind() clear(0,0,0,0) renderbufx1.getTexture() gt bind() renderbufx1.getTexture() gt drawPart( 1, 1,2,2,0,0,1,1) renderbufx1.getTexture() gt unbind() savebufx1.unbind() savebufx1.getTexture() gt bind() glGetTexImage(GL TEXTURE 2D, 0, GL RGBA, GL BYTE, t.data) lt This is the line savebufx1.getTexture() gt unbind() glEnable (GL BLEND) renderbufx1.getTexture() gt bind() renderbufx1.getTexture() gt drawPart(tex2x, 1,w,h,texSpan,texSpan,fact,fact) renderbufx1.getTexture() gt unbind() Timing measured encompasses all this (and a few other things, which do not really contribute to the total). Edit 4 (on course for the most edited question of the week) The native texture format of the GPU is supposed to be retrieved through the function glGetTexLevelParameter. More precisely, i've used this line of code glGetTexLevelParameteriv ( GL TEXTURE 2D, 0, GL TEXTURE INTERNAL FORMAT, amp iTexFormat) The result of the function (within iTexFormat) is 32856. 32856, decimal, is 0x8058, and within gl.h there is define GL RGBA8 0x8058


Apply portion of texture atlas I'm trying to write a shader that only maps a portion of a large texture to my sprite and I'm getting a strange behaviour with my current code. This is what I have right now Texture atlas example (256x256px) EDIT I've changed both shaders and I get the following output right now (first image), but I need to zoom the texture so I only render the highlighted portion of the second image, how should I modify the shaders to achieve that? These are my current shaders Vertex uniform mat4 uMVPMatrix attribute vec4 aPosition attribute vec2 aTextureCoord varying vec2 vTextureCoord varying vec2 vTextureCoordOffset void main() offset and texSize will be defined as attributes later. They're defined here for test purposes only vec2 offset vec2(128.0, 64.0) vec2 texSize vec2(256.0, 256.0) float u offset.x texSize.x float v offset.y texSize.y vTextureCoordOffset vec2(u, v) vTextureCoord aTextureCoord gl Position uMVPMatrix aPosition Fragment precision mediump float uniform sampler2D sTexture varying vec2 vTextureCoord varying vec2 vTextureCoordOffset void main() gl FragColor texture2D(sTexture, fract(vTextureCoord) vTextureCoordOffset) SOLVED I solved it changing the fragment shader to gl FragColor texture2D(sTexture, fract(vTextureCoord) vZoom vTextureCoordOffset) vZoom is calculated in the vertex shader vZoom subTextureSize texSize


Difference in glDrawArrays and glDrawElements While refreshing my mind on OpenGL ES, I came across glDrawArrays and glDrawElements. I understand how they are used and sort of understand why they are different. What I do not seem to understand is that, I fail to see how glDrawElements can save draw calls (saving draw calls is a description that is mentioned by most of the books I have read, hence my mentioning of it here). Imagine a simple scenario in which I tried to draw a square using 2 triangles. I would need to have a set of 6 vertices using glDrawArrays while using glDrawElements, I would need only 4 in addition to an index array that has 6 elements. Given the above, here is what I do not understand how could glDrawElements save draw calls, if it still needs to use the index array (6 indices, in case of a square) to index into my vertex array that had 4 elements (6 times)? Other words, does it mean glDrawElements would still need to have a total of 6 draw calls just like glDrawArrays? how would using glDrawElements save space, if one would still need to have 2 arrays, namely, one for the vertices and one for the indices? In the case of drawing a square from 2 triangles, for simplicity, how many draw calls does glDrawElements (4 items in vertex array and 6 items in index array) and glDrawArrays (6 items only in vertex array) need, individually? Thanks.


Heightmap Physics Optimization Improvement I'm working on implementing the physics surrounding a player walking on a heightmap. A heightmap is a grid of points which are evenly spaced on the x and z axes, with varying heights. The physical representation of my player (what is exposed to my physics engine manager) is simply a point mass where his feet are, rather than complicating the problem by treating him as a sphere or a box. This image should help further explain heightmaps and show how triangles are generated from the points. This picture would be looking straight down on a heightmap, and each intersection would be a vertex that has some height. Feel free to move this over to math, physics, or stack overflow, but I'm pretty sure this is where it belongs as it is a programming question related to games. Here's my current algorithm Calculate the player's velocity from input gravity previous velocity etc Move the player's position (nextPos prevPos velocity timeSinceLastFrame) Figure out which triangle (all graphics is done in triangles!) of my heightmap the player's new position is vertically aligned with Use the three vertices of that triangle to calculate the equation for the plane which that triangle lies in Plug in the player's x and z coordinates into the plane's equation to get the y coordinate for the player's position on that plane Set the y coordinate of the player's position to this (if newPos.y lt y) This is all fine and dandy, but I'm wondering if there's anything that I can optimize. For example, my first thought is to store the plane's equation with the triangle's vertex information. This way all I have to do is plug in the x and z values to the equation to get the y. However, this would require adding 4 floats to every vertex of the heightmap which is a little ridiculous memory wise. Also, my heightmaps are dynamic (meaning the heights will change at runtime), which would mean changing the plane equations every time a vertex's height changes. Is there a faster way to calculate that point than digging up the plane's equation and then plugging in x and z? Should I store the plane equations and update them on vertex height change or should I just regenerate the plane equations for every triangle every time the player moves on that triangle? Is there a better way to do heightmap physics that maintains this simplicity? (this seems very simple to me as far as physics engines go)


How to draw a 3D capsule? I want to draw a 3D capsule defined by a segment (two points start end) and a radius Image source Orionist on Wikimedia Commons I already have a sphere leaning on this answer https stackoverflow.com a 31326534 1902536. I understand that I can expand the Parametric Equation to an ellipse one but I'm not sure how to do it with the segment (that may have rotation). what is the best way to draw model a capsule?


Importing Models from Maya to OpenGL I am looking for ways to import models to my game project. I am using Maya as modelling software, and GLUT for windowing of my game. I found this great parser, it imports all the textures and normal vectors, but it is compatible with .obj files of 3dsMAX. I tried to use it with Maya obj's, and it turned out that Maya's obj files are a bit different from former one, thus it cannot parse them. If you know any way to convert Maya obj files to 3dsMax obj files, that would be acceptable as well as a new parser for Maya obj files.


Deforming a lip mesh to match face tracking points I'm creating a lipstick filter. I have a basic mesh for the lip shape ( 140 vertices ) which I am able to render on screen. I need the mesh since I have my own lighting system, and hence need the normal info. Plus I don't want to create a model at runtime since if I load an obj file I have the flexibility of rendering high quality meshes. The problem that I am now facing is that when a user is going to use it, their face will be moving around in the video frame, and I will be getting the lips' positions accordingly. Hence at each frame the mesh will be rendered differently ( in one frame he might be smiling, the other he might be frowning etc), in different places in the screen. How can I set the OpenGL vertices to match the positions of the tracked feature points, and interpolate the rest? I have only 20 ish detection landmark points for each of the upper and lower lip.


Lwjgl or opengl double pixels I'm working in java with LWJGL and trying to double all my pixels. I'm trying to draw in an area of 800x450 and then stretch all the frame image to the complete 1600x900 pixels without them getting blured. I can't figure out how to do that in java, everything I find is in c ... A hint would be great! Thanks a lot. EDIT I've tried drawing to a texture created in opengl by setting it to the framebuffer, but I can't find a way to use glGenTextures() in java... so this is not working... also I though about using a shader but I would not be able to draw only in the smaller region...


OpenGL get the outline of multiple overlapping objects I just had an idea for my on going game made with opengl in c I'd like to have a big outline (5 6 pixel) on multiple overlapping object when the player win something. I thought the best way is to use stencil buffer but it's few hours that I' trying to do some off screen render of the stencil buffer and I can't achieve any kind of result so probab. there are some other techniques! This is what I want to get Any ideas?


Knowing the size of a framebuffer when rendering transformed meshes to a texture I have a couple of 2D meshes that make a hierarchical animated model. I want to do some post processing on it, so I decided to render this model to a texture, so that I could do the post processing with a fragment shader while rendering it as a textured quad. But I don't suppose that it would be very smart to have the render texture's size as large as the entire screen for every layer that I'd like to compose it would be nicer if I could use a smaller render texture, just big enough to fit every element of my hierarchical model, right? But how am I supposed to know the size of the render target before I actually render it? Is there any way to figure out the bounding rectangle of a transformed mesh? (Keep in mind that the model is hierarchical, so there might be multiple meshes translated rotated scaled to their proper positions during rendering to make the final result.) I mean, sure, I could transform all the vertices of my meshes myself to get their world space screen space coordinates and then take their minima maxima in both directions to get the size of the image required. But isn't that what vertex shaders were supposed to to so that I wouldn't have to calculate that myself on the CPU? (I mean, if I have to transform everything myself anyway, what's the point of having a vertex shader in the first place? q ) It would be nice if I could just pass those meshes through the vertex shader first somehow without rasterizing it yet, just to let the vertex shader transform those vertices for me, then get their min max extents and create a render texture of that particular size, and only after that let the fragment shader rasterize those vertices into that texture. Is such thing possible to do though? If it isn't, then what would be a better way to do that? Is rendering the entire screen for each composition layer my only option?


How to spin a 2D quad in place using only matrices? In short, I have a textured 2D quad (a sprite). I would like to rotate spin it about the z axis (coming out of the screen) using nothing but matrices. If I do the following to a transform with scale in it already, the object spins, but also follows a circular path around the origin. As a test, if I first undo the scale, then this works fine (the object spins in place). But I'm not normally keeping scale, orientation and translation separate and then computing the matrix every frame in this case. I'm mutating the matrix all the time. So this isn't workable. Can this be done without first undoing the scale? self is the current transformation matrix (4x4) pivot is the "center" of the quad's AABB (recomputed immediately before this) eulerAngles is a vec3 containing 0.0, 0.0, z angle translate to the origin translate(self, pivot) rotate rotate(self, eulerAngles) go back translate(self, pivot) (I'm using OpenGL, but that probably doesn't matter much here) There are other related articles, but I didn't get to a solution. I'm linking for reference Combining rotation,scaling around a pivot with translation into a matrix How can I rotate about an arbitrary point in 3D (instead of the origin)?


How to detect GLSL warnings? After compiling a shader with glCompileShader, I can call glGetShaderiv with GL COMPILE STATUS to check if the shader compiled successfully. I can also call glGetShaderInfoLog to get information about possible errors, warnings or other info. The information log returned by this function is unspecified. In a tool where users can write their own shaders, I would like to print all errors and warnings from the compilation, but nothing if no warnings or errors were found. The problem is that the GL COMPILE STATUS returns only false if the compilation failed and true otherwise. If no problems were found, some drivers return empty info log from glGetShaderInfoLog, but some drivers can return something else such as "No errors.", which I do not want to print to the user. How is this problem generally solved?


Why is my model rotating opposite direction around the Y axis? I have a simple scenario. I have a simple scene, and in it I'm drawing a grid and a model, with some axis for orientation. I noticed when I rotate the model about it's local Y axis, if I rotate the model clockwise, the vertices end up rendering as if they've been rotated counterclockwise. I can see this by rendering the model's local forward vector. Here's a picture of what I mean. Initially, the world forward, local forward, and model all face the same direction. However, after I begin rotating the object clockwise, I notice the "world forward vector" is rotating clockwise, but my model rotates counterclockwise? When I export the model from Blender3D I use the coordinate system "Forward Z" and "UP Y Up", which matches the RHS coordinate system I'm using in opengl. When I "rotate the object", I mean I multiply the object's rotation matrix like so float constexpr angle 1.0f glm vec3 const axis glm vec3 0.0, 1.0, 0.0 object.rotation glm angleAxis(glm radians(angle), axis) object.rotation Here's my vertex shader, I'm just multiplying the vertices by the MVP matrix. vertex shader in vec4 a position in vec4 a color out vec4 v color uniform mat4 u mvpmatrix void main() gl Position u mvpmatrix a position v color a color The rotation object.rotation 's initial value is the quaternion identity. Here's how I calculate the MVP matrix uniform value glm mat4 const tmatrix glm translate(glm mat4 , this gt translation) glm mat4 const rmatrix glm toMat4(this gt rotation) glm mat4 const smatrix glm scale(glm mat4 , this gt scale) glm mat4 const model matrix tmatrix rmatrix smatrix camera xyz are world coords for the camera target xyz is world coords of the object glm vec3 const UP glm vec3 0.0f, 1.0f, 0.0f glm mat4 const view glm lookAt(camera xyz, target xyz, UP) glm mat4 const projection glm perspective(fov, aspect ratio, near, far) glm mat4 const mvp matrix projection view model matrix Other relavent calculations glm vec3 eye forward() const return forward glm vec3 eye up() const return up glm vec3 eye backward() const return eye forward() glm vec3 eye left() const return eye right() glm vec3 eye right() const return glm normalize(glm cross(eye forward(), eye up())) glm vec3 eye down() const return eye up() glm vec3 world forward() const return forward orientation() glm vec3 world up() const return up orientation() glm vec3 world backward() const return world forward() glm vec3 world left() const return world right() glm vec3 world right() const return glm normalize(glm cross(world forward(), world up())) glm vec3 world down() const return world up() From what I can tell, it seems like I'm doing everything right. Can someone explain it to me? I also have a video showing this in more detail. This is important, because I move the object "forward" based on it's forward vector, so when I rotate the object and move it "forward" it's not moving in the direction it is facing. edit Am I calculating the "local forward" correctly with this calculation? double edit I just noticed I labeled the "World" and "Object space" vectors backwards. The green arrow is the World forward vector (0, 0, 1) and the light blue is the object's local forward vector. forward is initialized with Z (0.0, 0.0, 1.0) glm vec3 world forward() const return forward orientation() glm quat const amp orientation() const return object.rotation


Correct way to calculate Perspective Matrix I have seen at least 3 different ways to calculate the perspective matrix and I'm confused as to which one I should be using and what the differences are? OpenGL says to do it this way f cotangent(fov 0.5) f aspect, 0, 0, 0 0, f, 0, 0 0, 0, (far near) (near far), (2 far near) (near far) 0, 0, 1, 0 glm does it this way range tan(fov 0.5) near left range aspect right range aspect bottom range top range (2 near) (right left), 0, 0, 0 0, (2 near) (top bottom), 0, 0 0, 0, (far near) (far near), 1 0, 0, (2 far near) (far near), 0


(GLSL) Lighting code outputting a black quad So, ive been transitioning to modern opengl recently and it's going rather well. But alas, something must go wrong. As the titel says, all I'm getting is a completely black quad. (Ive double checked my C code and I'm pretty sure it has nothing to do with that.) version 330 core Vertex shader layout(location 0) in vec3 vertexPosition modelspace layout(location 1) in vec3 vertexColor layout(location 2) in vec2 vertexUV layout(location 3) in vec3 vertexNormal out vec3 vertNorm out vec3 fragmentColor out vec3 vertPos out vec2 UV uniform mat4 MVP void main() gl Position MVP vec4(vertexPosition modelspace,1.0f) UV vertexUV fragmentColor vertexColor vertPos vertexPosition modelspace vertNorm vertexNormal Fragment shader version 330 core in vec3 Normal in vec3 fragmentColor in vec3 vertPos in vec2 UV out vec3 color uniform sampler2D textureSampler uniform mat4 Model void main() vec3 lightPos vec3(0, 0, 0) mat3 normalMatrix transpose(inverse(mat3(Model))) vec3 normal normalize(normalMatrix Normal) vec3 fragPosition vec3(Model vec4(vertPos, 1)) vec3 surfaceToLight lightPos fragPosition float brightness dot(normal, surfaceToLight) (length(surfaceToLight) length(normal)) brightness clamp(brightness, 0, 1) color vec3(brightness 1 (texture(textureSampler, UV).rgb fragmentColor)) But if you require my c code, say so and ill edit.