opengl z index changing does not zoom in I am making a simple opengl application where I have a cube and I want to move forward to it with the glTranslate3d function, where I change the z index. One would expect the object to get bigger because of the view but it does not My code glClearColor(0, 0, 0, 1) glClearDepth(1.0) glEnable(GL DEPTH TEST) glDepthFunc(GL LEQUAL) glViewport(0, 0, width, height) glMatrixMode(GL PROJECTION) glOrtho(30, width, 0, height, 100, 100) glMatrixMode(GL MODELVIEW) I have tried many things also I have been told that gluPerspective is out dated and should not be used.... EDIT it works when I rotate the object you can see how 3d it is p


What are the possible techniques to optimize the lighting pass in a deferred shading renderer? I am toying around with "modern" OpenGL (this is my first attempt, I am new to this) and I have been developping my own deferred shading renderer as an exercise. I am using an FBO with the following attachments DS Depth Stencil (GL DEPTH32F STENCIL8) RT0 Position (GL RGB16F) RT1 Normal (GL RGB16F) RT2 Albedo (GL RGB16F) RT3 Postprocessing buffer 0 RT4 Postprocessing buffer 1 Depth RT0, 1, 2 are filled first in one single geometry pass. Then for each light source (point lights only for now, spheres are used as light volumes) Stencil pass to limit light calculation to where it actually has an effect Light pass light contribution is accumulated in RT3 From this point on, I am only rendering a quad the size of the screen and fragment shaders are used to compute the next image. Albedo (RT2) and Light (RT3) are blended into RT4 I now have my lit image. I can enable more postprocessng shaders (FXAA, Depth of field, ...), in which case RT3 and RT4 are used for ping ponging. The thing is, even with no postprocessing, not that many lights (around 10) and a very simple scene (roughly 5k vertices), my frame rate drops like significantly as soon as I increase resolution or add more lights. It looks like my light pass is responsible for most of this but how can I track down what exactly is slowing everything down? Are there any tricks to optimize it? Is there anything I am missing? Thanks! Light Fragment Shader for reference uniform sampler2D position uniform sampler2D normal uniform float screenw uniform float screenh uniform vec3 light pos uniform vec3 camera pos uniform vec4 diffuse uniform vec4 ambient uniform vec4 specular uniform float outer radius uniform float inner radius float specular hardness 100.0 vec4 calc point light(vec3 p, vec3 n) vec3 light dir light pos p float d to light length(light dir) light dir normalize(light dir) vec3 eye dir normalize(camera pos p) vec3 half vec normalize(light dir eye dir) float attenuation (outer radius d to light) (outer radius inner radius) attenuation max(min(attenuation, 1.0), 0.0) vec3 c ambient.rgb ambient.a c diffuse.rgb max(dot(n, light dir), 0.0) diffuse.a c specular.rgb pow(max(dot(n, half vec), 0), specular hardness) specular.a return vec4(clamp(c, 0.0, 1.0) attenuation, 1.0) void main(void) vec2 texcoord gl FragCoord.xy vec2(screenw, screenh) vec3 p texture2D(position, texcoord).xyz vec3 n texture2D(normal, texcoord).xyz gl FragColor calc point light(p, n)


OpenGL Fragment Shader Interpolation Vs Inverse Calculation I have found openGL fragment shader tutorials on the web, some that use use inverse calculations to revert the fragment coordinate back to the world space and others that interpolate the position. With that said... Is there a difference between interpolated world space position and the actual world space position calculated using inverse matrices and the fragment window space coordinates? Does anyone know of any resources that would help me understand the mathematical differences between these two things, if they are different? If they aren't different, then why would anyone use inverse matrices instead of interpolating, which seems less expensive? I wrote a shader to test 1, but I cannot tell if rounding errors are to blame for the differences or not. Thanks!


Rendering artifacts at a large scale I'm a new to OpenGL or graphics in general. Trying to write a game with realistic scale. I had a perfectly fine rendering of earth at a small scale, but when I try to scale it up to 1 1 I get this artifact. Any ideas what this could be? I suspect it's because I am using floats, but I would rather avoid using doubles in the shader for performance reasons.


How can I get my meshes to work with Bullet Physics? The problem is that I'm trying to use my meshes with Bullet Physics for the collision part of my game. When I attempted doing this method with my GLM(model loading library by nate robins) model, I get a segmentation fault in the debug, so I figured that it doesnt like the coordinate variables of the model. If i use blender to export my model as a collision file, what type of file should I use? I have heard of a .bullet exporter, but i dont know hot to integrate this python script into my Blender 2.5 program.


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?


Rendering a black and white image in OpenGL 1.1 Is there is any way that I can simple disable the color in OpenGL 1.1? Or can I "grey out" textures in LWJGL?


LWJGL Determining whether or not a polygon is on screen Not sure whether this is an LWJGL or math question. I want to check whether a shape is on screen, so that I don't have to render it if it isn't. First of all, is there any simple way to do this that I am overlooking? Like some method or something that I haven't found? I'm going to assume there isn't. I tried using my trigonometry skills, but it is hard to do this because of how glRotate also distorts the image a little for perspective and realism. Or, is there any way to easily determine if a ray starting from the camera, and going outward in a straight line intersects a shape? (I can probably do it with my math skillz, but is there an easier way?) By the way, I can easily determine the angle at which the camera is facing around the x and y axis. EDIT Or, possibly, I could get the angles of a vector from the camera to the object, and compare those angles to my camera angles. But I have a feeling that the distorts from glRotate and glTranslate would be an issue. I'll try it though.


OpenGL Positional 2D Texture Masking I have a simple 2D java game engine running using LWJGL. I have my own vertex and fragment shaders, and I'm able to render quads with textures. I want to be able to mask one quad using the texture from another quad. Example I have two quads with two different textures mapped to them. Quad A has a red circle texture. Quad B has a blue square texture. I want to use Quad A's red circle texture as a mask such that Quad B will only be visible if it is within Quad A's red circle texture. Here's an image showing what I want to do The problem is that I am always seeing the 'full overlap' no matter the position of the quads. I can never get that partial masking that I'm looking for. My shader logic is close to this version 150 core uniform sampler2D texture uniform sampler2D maskTexture in vec2 pass TextureCoord in vec2 pass MaskTextureCoord out vec4 out Color void main(void) other logic here to determine out Color if(pass MaskTextureCoord.x ! 1 amp amp pass MaskTextureCoord.y ! 1) if we have valid mask texture coordinates, we are masking vec4 maskColor texture(maskTexture, pass MaskTextureCoord) get the rgba values of the mask texture if(maskColor.a 0) if mask texture has no alpha, discard discard Do I need to pass location data of the masking quad into the shader? If so, how do I do that? EDIT ilmale's method using the stencil buffer worked for me! All I needed to add was a uniform boolean value to tell the shader if I was drawing a mask or not. Here's the relevant shader code if(isMask) if this is a mask, discard where texture alpha is 0 if(texColor.a 0) discard else out Color vec4(0, 0, 0, 0) make the rest transparent, so we don't see the mask texture


Only one triangle drawn I am trying to render a quad with gl render mode GL TRIANGLES with using element array buffer. Here is some code to explain process. Only the first 3 elements of indices array are drawn as expected. But following indices doesn't drawn at all. Mesh Creation glm vec3 vertices glm vec3( 1, 1, 0), glm vec3( 1, 1, 0), glm vec3(1, 1, 0), glm vec3(1, 1, 0) glm vec2 textures glm vec2(1, 0), glm vec2(0, 0), glm vec2(0, 1), glm vec2(1, 1) unsigned int indices 0, 1, 3, 3, 1, 2 Mesh mesh new Mesh(vertices, sizeof(vertices) sizeof(glm vec3), textures, sizeof(textures) sizeof(glm vec2), indices, sizeof(indices) sizeof(unsigned int), texture) Mesh Class Mesh Mesh(...) InitMesh(...) void Mesh InitMesh(vec3 vertices, unsigned int numVertices, vec2 textureCoords, unsigned int numTextureCoords, unsigned int indices, unsigned int numIndices) this gt numIndices numIndices Generate VAO and bind glGenVertexArrays(1, amp vaoID) glBindVertexArray(vaoID) Generate VBOs glGenBuffers(3, vboIDs) Bind Position Buffer, Buffer Position Data glBindBuffer(GL ARRAY BUFFER, vboIDs 0 ) glBufferData(GL ARRAY BUFFER, numVertices sizeof(vec3), vertices, GL STATIC DRAW) glEnableVertexAttribArray(0) glVertexAttribPointer(0, 3, GL FLOAT, GL FALSE, 0, 0) Buffer TextureCoord Data glBindBuffer(GL ARRAY BUFFER, vboIDs 1 ) glBufferData(GL ARRAY BUFFER, numTextureCoords sizeof(vec2), textureCoords, GL STATIC DRAW) glEnableVertexAttribArray(1) glVertexAttribPointer(1, 2, GL FLOAT, GL FALSE, 0, 0) Buffer Indices Data glBindBuffer(GL ELEMENT ARRAY BUFFER, vboIDs 2 ) glBufferData(GL ELEMENT ARRAY BUFFER, numIndices sizeof(unsigned int), indices, GL STATIC DRAW) Unbind VAO glBindVertexArray(0) void Mesh Draw() glBindVertexArray(vaoID) glEnableVertexAttribArray(0) glEnableVertexAttribArray(1) glDrawElements(GL TRIANGLES, numIndices, GL UNSIGNED INT, 0) glDisableVertexAttribArray(1) glDisableVertexAttribArray(0) glBindVertexArray(0)


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


How can I clip my sprite as it passes through a portal in a 2D scenario, using OpenGL? This is a very simple question, but after a brief search and reading through the "similar questions" I could not yet find an answer. I'm creating a 2D game using OpenGL and came across a problem Let's say I wanted to create portals. An Entity can move into a portal A and come out of the corresponding portal B. Transforming the coordinates and velocity of the entity is easy, but this would create "hard" texture teleportation. Which means while half of the entity is in the A portal, it won't be rendered on the corresponding B side. How would I create a smooth transition? My first Idea was I define "exit" and "entry" zones containing the transformation function (Matrix). Now when an Entity enteres the exit zone the entity is also drawn at the entry zone using the transformation matrix relative the the entry exit zones. But drawing it twice would still give me the difficulty, that I need to clip the entity on the portals "backside". (The entity shall vanish behind portal A when entering). So my second thought was, that there should be a solution using (vertex?) shader? But how would such a shader look like? (Example code would be nice, but not neccessary. I'd rather want to have a "what the shader would do" answer). Would I define Uniforms (exit and entry zones) which the shader would clip transform ("move") the vertexes from? How does a typical solution for this clipping look like? Or where could I read some information about these kind of problems? I only found some to 3D versions, where the view of portal B should be rendered in portal A. But this does not solve the object moving through it problem...I think In my opinion changing the draw order, or rendering something above the backside of the portals is not the right way to go, since this could create strange behavior in certain situations. (Portal B is just behind portal A for example. One of both would be overdrawn I think.)


How to free the GPU from a long task? I'm developing an application that uses the GPU. Some tasks might be rather long (like a fragment shader with a loop). I have the impression that I can make the entire OS visually freeze by asking the GPU to perform a job that doesn't end. Of course, I'm not doing this on purpose, but when that accidentally happens, I have to force power off my machine and this is very difficult to debug. Some questions Is this behaviour normal? Or could this be a bug in the hardware or driver? Is there a technique to recover from this without force stopping my machine? Since the OS is still functioning (only not rendering), I could try to ssh into my machine and kill the process. Would that free the GPU from its job? Update I tried to ssh into my machine and sudo kill 9 pid , but didn't work. I would like to know if there is an OS independent answer for this. If there isn't, my setup is macOS, with OpenGL (running on Intel HD Graphics 3000).


OpenGL Maximal amount of debug string reached I was trying to check my current openGL code in gDEBugger, everything works fine. But, I get these messages Debug String gt gt gt gt gt gt gt gt gt 1 Debug String gt gt gt gt gt gt gt gt gt 2 Debug String gt gt gt gt gt gt gt gt gt 3 ... Debug String gt gt gt gt gt gt gt gt gt 497 Debug String Maximal amount of debug string reached (500 strings). Additional debug strings will be ignored What are these messages, everything in my code runs fine. But its troubling to see these debug strings.


OpenGL 4D textures with bilinear interpolation I want to use and interpolated 4D texture in OpenGL, i.e. a texture that is accessed with a texture coordinate vector (s, t, p, q) and interpolated linearly in every texture coordinate. The extension GL SGIS texture4D does exactly this. However, it is unsupported on literally every GPU I have access to. If the was a GL TEXTURE 3D ARRAY, I guess I could sample the appropriate 2 layers of a 3D array texture with the (s, t, p) coordinates and then manually interpolate in the q coordinate. However, there are only "ordinary" GL TEXTURE 2D ARRAY texture arrays. A possible solution is to treat the texture array as 2D array of 2D texture, sample the appropriate 4 layers with (s, t) and then manually interpolate in p and q. This method is somewhat constrained by GL MAX ARRAY TEXTURE LAYERS . I am also afraid of the relatively large number of 2D texture fetches required to fetch a single 4D texture value. Is there a simpler way of achieving 4D interpolated textures?


Model gets distorted when rotating the camera I'm currently developing my own 3d graphics engine and I'm having a hard time figuring out why my 3D models gets distorted when rotating the camera around. This is my projection matrix. I'm following the OpenGL's Model. def get projection mat(aspect ratio, camera) fov camera.fov z near camera.z near z far camera.z far top math.tan(fov 0.5) z near bottom top right top aspect ratio left right projection mat np.identity(4, dtype float) projection mat 0, 0 2 z near (right left) projection mat 0, 2 (right left) (right left) projection mat 1, 1 2 z near (top bottom) projection mat 1, 2 (top bottom) (top bottom) projection mat 2, 2 (z far z near) (z far z near) projection mat 2, 3 2 z far z near (z far z near) projection mat 3, 2 1 projection mat 3, 3 0 return projection mat This is my view matrix def camera matrix(self) camera matrix np.identity(4, dtype float) camera matrix 3, 0 self.left camera matrix 3, 1 self.up camera matrix 3, 2 self.forward camera matrix 3, 3 self.pos return camera matrix This is how I get the ViewProjection matrix projection mat get projection mat(self.aspect ratio, self.camera) view mat self.camera.camera matrix() view mat np.linalg.inv(view mat) self.view projection mat np.dot(projection mat, view mat) And, finally, this is the ViewProjectionModel matrix view projection model mat np.dot(model.transform mat.T, self.view projection mat) This is the method that I use to rotate the camera def rotate(self, yaw, pitch, degress True) rotation mat y helper.rotate matrix y(yaw, degrees) rotation mat x helper.rotate matrix x(pitch, degrees) rotation mat np.dot(rotation mat y, rotation mat x) self.forward np.dot(np.insert(self.forward, 3, 1), rotation mat) self.forward helper.normalized((self.forward self.forward 3 ) 3 ) self.up np.dot(np.insert(self.up, 3, 1), rotation mat) self.up helper.normalized((self.up self.up 3 ) 3 ) self.left np.dot(np.insert(self.left, 3, 1), rotation mat) self.left helper.normalized((self.left self.left 3 ) 3 ) A video demo, showing the problem To summarize, the order of multiplication is ProjectionMat X ViewMat x ModelMat x ModelFaces. If it isn't clear by now, I'm using Python for this project. Any help would be greatly appreciated. With best regards, Jo o Pedro EDIT Like this? directions, r np.linalg.qr(np.array( self.forward, self.up, self.left )) self.forward directions 0 self.up directions 1 self.left directions 2


How can I improve the performance of this rendering code? I've created a practice application for rendering triangles squares cubes using VBOs. This is mainly so I can get it right before upgrading a 3D block world game I've written that currently is using display lists to cache block rendering. I have a 3D cube rendering with an interleaved VBO and I recreated a basic chunk block system that does the following Loads chunks in a 10x10 area Each chunk creates its own float buffer and adds 16x16x16 cube vertices, colors, texture coordinates. Each chunk then is rendered via its own VBO. The VBO rendering code, called per chunk, looks like this interleavedBuffer.flip() glGenBuffersARB(ib) int vHandle ib.get(0) glEnableClientState(GL VERTEX ARRAY) glEnableClientState(GL COLOR ARRAY) glEnableClientState(GL TEXTURE COORD ARRAY) glBindBufferARB(GL ARRAY BUFFER ARB, vHandle) glBufferDataARB(GL ARRAY BUFFER ARB, interleavedBuffer, GL STATIC DRAW ARB) glVertexPointer(3, GL FLOAT, 32, 0) glColorPointer(3, GL FLOAT, 32, 12) glTexCoordPointer(3, GL FLOAT, 32, 24) glDrawArrays(GL QUADS, 0, vertexCount) glBindBufferARB(GL ARRAY BUFFER ARB, 0) glDisableClientState(GL COLOR ARRAY) glDisableClientState(GL VERTEX ARRAY) glDisableClientState(GL TEXTURE COORD ARRAY) ib.put(0, vHandle) glDeleteBuffersARB(ib) clear() This method renders everything perfectly, however it suffers from performance problems. A few chunks of 16x5x16 are fine, 60 fps. Increasing them to 16 3 and loading 10x10 chunks, the performance drops to 8fps. I'm preparing to use VBOs on a game that loads at most 20x20 chunks of 16x128x16 dimensions so I need resolve this performance issue. What are my choices? I have yet to look into interfaced indexed VBOs. I've heard those are good choices when rendering many of the same thing? My game currently uses display lists to cache chunk rendering, and I only refresh that cache when a block change is made that requires it. Is there something similar I can do with VBOs? For reference, my code for the chunk loading and chunk rendering can be perused.


Loading PNG textures for use in Android OpenGL ES1 I'm very new to Android and OpenGL coding (I have previously used ogre3d). I am trying to find an efficient way to load PNG textures. It is currently taking around 8 secs to load 3 512x512 textures on a fairly fast phone (Motorola Defy) There seems to be a problem with the texture being upside down (I used a Matrix to flip it below). Secondly, the order of the colour channels are incompatible, therefore each pixel needs changed. This (I believe) is the cause of the slowness, is there a way to make the BitmapFactory load it in a channel order that is compatible with opengl? Is there a better approach here? Here is the code Will load a texture out of a drawable resource file, and return an OpenGL texture ID private int loadTexture(GL10 gl, Context context, int resource, boolean loadMipMaps) We need to flip the textures vertically Matrix flip new Matrix() flip.postScale(1f, 1f) This will tell the BitmapFactory to not scale based on the device's pixel density BitmapFactory.Options opts new BitmapFactory.Options() opts.inScaled false Load up, and flip the texture Bitmap temp BitmapFactory.decodeResource(context.getResources(), resource, opts) Bitmap bmp Bitmap.createBitmap(temp, 0, 0, temp.getWidth(), temp.getHeight(), flip, true) temp.recycle() int id loadTextureFromBmp(gl,bmp, true) bmp.recycle() return id protected static int loadTextureFromBmp(GL10 gl, Bitmap bmp, boolean reverseRGB) ByteBuffer bb ByteBuffer.allocateDirect(bmp.getHeight() bmp.getWidth() 4) bb.order(ByteOrder.nativeOrder()) IntBuffer ib bb.asIntBuffer() for (int y bmp.getHeight() 1 y gt 1 y ) for (int x 0 x lt bmp.getWidth() x ) if (reverseRGB) int px bmp.getPixel(x,y) int alpha (px amp 0xFF000000) gt gt 24 int red (px amp 0xFF0000) gt gt 16 int green (px amp 0xFF00) gt gt 8 int blue (px amp 0xFF) ib.put((alpha lt lt 24) (blue lt lt 16) (green lt lt 8) (red)) ib.put(Integer.reverseBytes(bmp.getPixel(x, y))) else ib.put(bmp.getPixel(x,y)) ib.position(0) bb.position(0) int tmp tex new int 1 gl.glGenTextures(1, tmp tex, 0) int tex tmp tex 0 gl.glBindTexture(GL10.GL TEXTURE 2D, tex) gl.glTexImage2D(GL10.GL TEXTURE 2D, 0, GL10.GL RGBA, bmp.getWidth(), bmp.getHeight(), 0, GL10.GL RGBA, GL10.GL UNSIGNED BYTE, bb) gl.glTexParameterf(GL10.GL TEXTURE 2D, GL10.GL TEXTURE MIN FILTER, GL10.GL LINEAR) gl.glTexParameterf(GL10.GL TEXTURE 2D, GL10.GL TEXTURE MAG FILTER, GL10.GL LINEAR) return tex


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


what happens with missing vertices in geometry shader I am relatively new to GLSL shader programming, and the documentation I found is unfortunately often inscrutable. I am having trouble understanding a few things with how geometry shaders fit into the pipeline. I am trying to implement silhouette detection by detecting boundary triangles in a geometry shader. A triangle is a boundary triangle if it is front facing and an adjacent triangle is back facing. The idea then is to emit additional camera facing triangles to outline them. For this purpose, I am looking at GL TRIANGLE ADJACENCY shaders, since they seem to fit the bill. Let's assume for the moment that I have already got the data loaded properly into the buffer. For clarity I plan on doing skinning and the Model View transform in the vertex shader, but to hold off on the perspective projection until I decide what to do in the geometry shader (this seems reasonable, but maybe I am wrong). Here is where the uncertainties start to come in. First of all, am I expected to manually perform backface culling at some shader stage? Second, if a triangle has incomplete adjacency information(only 2 out of three triangles for example), how is this conveyed to the shader? Does it just have a length less than 6 vertices? Third, what does the pass through shader (the one that does nothing special) have to perform? Do I emit every vertex in the input list, or just 3 from the first triangle? And again, am I supposed to allowed to cull backfaces? And last, if I decide to emit additional geometry, is there anyway to distinguish that from the (passed through) input geometry from the point of view of the fragment shader? I'd like to be able to texture map them separately if it is possible. If I am on the wrong path on any of this, of course feel free to let me know. In case it is important, I am using OpenGL 3.3. Based on my understanding and Nathan's answer, I could start with a passthrough shader that looks something like this layout(triangle adjacency) in layout(triangle strip, max vertices 14) out flat out float is border void main() gl Position gl in 0 .gl Position is border 0.0 EmitVertex() gl Position gl in 2 .gl Position is border 0.0 EmitVertex() gl Position gl in 4 .gl Position is border 0.0 EmitVertex() EndPrimitive() And then when if I add triangle strips for outlines, I will set is border 1.0 for each of those vertices.


Difference between Spherical Harmonics and Spherical Harmonics Lighting What is the difference between Spherical Harmonics and Spherical Harmonics Lighting in OpenGL?


OpenGL 4.4 LWJGL How can i render text to the screen I have been told that you need to create a texture atlas for the font, and individually assign each character to a texture and add them up to create the string you want to produce. This seems a little more difficult than it should be. Is there another way? If not there must be documentation or a library someone wrote to do this. Can someone help me out?


Beginning on animations I am clueless with regards to animations. I have a simple rendering engine that renders models, sprites, skyboxes and whatnot but everything is simply static with no animations whatsoever. With my engine written in C and OpenGL I will have to learn how to implement animations accordingly but any OpenGL book or tutorial I look for doesn't explain animations. It's probably one of those topics which being so complex requires its own book or something. Does anyone know any great resources to explain how I can programme animations? I'm not interested in learning how to design them, rather just the technical side of it, you know bones and all. I would also welcome tips as to the general concept of modern animations in OpenGL. If it also means much, I use assimp as my model loader. Suffice it to say, how does a programmer animate a model to 'run' or 'jump'?


How do I fix this access violation when I exit my custom OpenGL game engine? I'm writing an game engine, where the engine is written in a project and exports a .dll file. In another project, in the same solution as the engine, there is a sandbox project which uses the engine. However, there is a bug. I run the sandbox project in debug mode with the engine dll. When I spam my mouse and keyboard for a few seconds, and close the program via the exit button, the program crashes with an error Exception thrown at 0x00000043 in phantom sandbox.exe 0xC0000005 Access violation executing location 0x00000043.If there is a handler for this exception, the program may be safely continued. I found the source of the bug. Since I'm currently writing the engine for OpenGL, I have to initialize GLEW, and I need to create a HGLRC. If I don't initialize this HGLRC, everything works. This is not the ideal solution, since I need to use OpenGL for my engine. I went forth without exporting the .dll from the engine, making the engine an application, instead. I made a main.cpp, and wrote it to use the engine, enabling OpenGL rendering. I tried to recreate the bug, but everything works! I thought it might OpenGL, but then now I'm thinking it might be my engine. How do I fix this? Here is my code, where it errors int const main result invoke main() telemetry main return trigger(nullptr) if(! scrt is managed app()) exit(main result)l if(!has actor) lt this is the line being sent to the call stack cexit() scrt unititialize crt(true, false) return main result except ( seh filter exe(GetExceptionCode(), GetExceptionInformation())) int const main result GetExceptionCode() if(! scrt is managed app()) exit(main result) Here is the call stack


Problems with Rotation Matrices on Certain Axes Here is what my rotation matrix looks like public Matrix4f initRotation(float x, float y, float z) Matrix4f rx new Matrix4f() Matrix4f ry new Matrix4f() Matrix4f rz new Matrix4f() x (float)Math.toRadians(x) y (float)Math.toRadians(y) z (float)Math.toRadians(z) rz.m 0 0 (float)Math.cos(z) rz.m 0 1 (float)Math.sin(z) rz.m 0 2 0 rz.m 0 3 0 rz.m 1 0 (float)Math.sin(z) rz.m 1 1 (float)Math.cos(z) rz.m 1 2 0 rz.m 1 3 0 rz.m 2 0 0 rz.m 2 1 0 rz.m 2 2 1 rz.m 2 3 0 rz.m 3 0 0 rz.m 3 1 0 rz.m 3 2 0 rz.m 3 3 1 rx.m 0 0 1 rx.m 0 1 0 rx.m 0 2 0 rx.m 0 3 0 rx.m 1 0 0 rx.m 1 1 (float)Math.cos(x) rx.m 1 2 (float)Math.sin(x) rx.m 1 3 0 rx.m 2 0 0 rx.m 2 1 (float)Math.sin(x) rx.m 2 2 (float)Math.cos(x) rx.m 2 3 0 rx.m 3 0 0 rx.m 3 1 0 rx.m 3 2 0 rx.m 3 3 1 ry.m 0 0 (float)Math.cos(y) ry.m 0 1 0 ry.m 0 2 (float)Math.sin(y) ry.m 0 3 0 ry.m 1 0 0 ry.m 1 1 1 ry.m 1 2 0 ry.m 1 3 0 ry.m 2 0 (float)Math.sin(y) ry.m 2 1 0 ry.m 2 2 (float)Math.cos(y) ry.m 2 3 0 ry.m 3 0 0 ry.m 3 1 0 ry.m 3 2 0 ry.m 3 3 1 m rz.mult(ry.mult(rx)).getM() return this And here is how I've been implementing it for tests (using default orthographic perspective) public class Renderer private WorldMesh mesh private Mesh mesh private Matrix4f transform private Shader shader public Renderer() Setup Meshes mesh new WorldMesh() mesh ResLoader.loadMesh("pyramid.obj") mesh.addToBuffers( mesh) setup Shader shader new Shader() shader.addVertexShader(ResLoader.loadShader("basicVertex.vs")) shader.addFragmentShader(ResLoader.loadShader("basicFragment.fs")) shader.compileShader() shader.addUniform("transformation") temporary transformation matrix Matrix4f tran new Matrix4f().initTranslation(0, 0, 0) Matrix4f rot new Matrix4f().initRotation(0, 0, 0) problem is definitely with the rotation matrix Matrix4f scale new Matrix4f().initScale(1, 1, 1) transform tran.mult(rot.mult(scale)) public void update() public void render() RenderUtils.clearScreen() shader.setUniform("transformation", transform) shader.bind() mesh.draw(true) and finally here is my vertex shader version 330 layout (location 0) in vec3 position uniform mat4 transformation void main() gl Position transformation vec4(position, 1.0) The problem is that setting a rotation on any other axis other than Z (for some reason z axis rotation is working fine) does not function properly. An X axis rotation seems to be doing both an x and y rotation at the same time, causing a weird stretching affect. A Y axis rotation causes the mesh to completely disappear. The funny thing is that I've used this code over and over again and some projects don't give me a problem. The order of multiplication seems in order, and I made sure that OpenGL knows to transpose the matrix I give it when setting the uniform. Any ideas as to what could be causing the x and y axis rotations to completely fail?


how to calculate smooth normals for 10,000,000 vertices? I am trying to calculate smooth normals with angle weight for a huge mesh with 10 million vertices. Currently, i am using map dictionary to store the traingles connected to a vertex. That is, for each vertex, I loop through the entire mesh to find triangles connected to a single vertex and store them in a map for that vertex. I am doing this for 10 million triangles. So, i iterate 10 million x 10 million times to calculate normals for the whole mesh. It takes around 8 seconds to create the map itself. I also have to animate this mesh dynamically calculating the normals for 10 instances. Is there a possibility to move these computations to shaders?


Why does GLM only have a translate function that returns a 4x4 matrix, and not a 3x3 matrix? I'm working on a 2D game engine project, and I want to implement matrices for my transformations. I'm going to use the GLM library. Since my game is only 2D, I figured I only need a 3x3 matrix to combine the translation, rotation and scale operations. However, glm translation is only overloaded to return a 4x4 matrix, and never a 3x3. I thought a translation could be performed by using a 3x3 matrix why does GLM only have a translate function that returns a 4x4 matrix, and not a 3x3 matrix?


Can you specify which VBO EBO to use with glDrawElements? I'm creating a voxel like game. I'm not sure if I am using VBO EBO's correctly. I am creating a new VBO amp EBO for every chunk. This is done once, but chunks call a render function in every block inside, and the block calls glDrawElements (Is there a more efficient way?). How can I specify which VBO amp EBO each is supposed to use? Is this possible? Thank you!


Opengl shader questions I'm currently building a shader that takes a 2D texture sampler and uses UV coordinates to map it. This works fine for all textured objects. However, I'm having a bit of a problem as I'm trying to render a Mesh with no texture and the shader objects just keeps sampling based on the parameters of the last object I rendered. What is a good way to make sure whenever no texture is available it will just treat it as a white texture or something? One thing I've thought of was creating and binding a white 1x1 texture but that seems overkill. Related question I've been wondering about this and I've yet to find an answer Is it best to make a multi purpose shader or constantly change the shader program for different objects in the same render update? For instance, should I have just created a shader for non textured objects?


Multithreaded Game Loop I'm trying to implement a multithreaded game loop. I already did that but had to use a few locks for that, which ruined the performance. After researching a bit I came up with this idea Instead of splitting the engines subsystems into different threads (e.g. physics, animation), all subsystems run on all threads. So when we got four CPUs, four threads are created, with each thread having one loop for all subsystems. So the single core game loop is copied on all four threads. These game loops are controlled by one other loop, which sends messages (or 'jobs', 'tasks') to one of these threads (depending on their usage) according to user input or scripts. This could be done with a double buffered command buffer. Only the rendering loop is alone in a thread for maximum rendering performance. Now I'm thinking of the best way to communicate with the rendering loop. The best idea I could come up with is to again use a command buffer and swap it when the rendering loop is complete. That way the rendering loop doesn't have to wait for any of the loops and can go on rendering. If the game loop hasn't finished when the rendering loop swapped the buffer, all commands after that will be executed in the next frame of the rendering loop. To make sure that all objects will be drawn even if the game loop hasn't finished, the rendering loop holds all objects that will be drawn and draws them until it gets the command to stop drawing them. My goal is to make the engine scalable to cpu numbers and make it to use all cores. Is this a way to do that? What is the best approach to this and how are modern engines handling this?


How can I add 3D animation to my Pygame window? I've developed a quiz game using Pygame but now I'm being asked to implement a 3D animation element (a game show host) to the game. I used Pygame as I was told it would be an easy enough language to learn and make something simple, however I see now that it seems very limited in terms of 3D animation. I've seen OpenGL being used with Pygame and what I need is for my game to run exactly as it is, but with the 3D element (game show host) added on the corner of the window for example. How can I use OpenGL in Pygame in order to do this?


Generating 3D like effect I'm making a 2D sidescroller game and want to give the blocks a 3D like effect. This way it looks like the player is walking on 3D blocks while walking on a 2D plane (thus having only x,y coordinates). I have already written the code to generate the terrain in 2D, but the 3D effect is now baked in. It looks like this At this moment the 3D effect is baked into the blocks, but I want to try to generate it. Is there a common way to achieve this 3D like effect while still staying 2D? Do I have to convert from 2D to 3D or is it also possible to do this with calculations shaders? EDIT The reason I want the top texture of the block separate of the block is because when the camera would go up, the top should get bigger as the camera sees more of the top of the block and the other way around when the camera goes down.


Maximum tile and texture size for tiled maps I'm currently making a game using libGDX and Tiled. Everything was running fine until I changed the tile size from 96x96 to 300x300. Most layers are still displayed correctly but the tiles of a single layer are just black. I guess that there may be a problem with the large tiles (as there are some tiles together in one tileset bitmap the texure is 2100x2100 large). Are there any upper limits for tiles and or tilesets regarding the bitmap and texture size? GL MAX TEXTURE SIZE returns 3379 on this machine.


How to do directional per fragment lighting in world space? I am attempting to create a GLSL shader for simple, per fragment directional light. So far, after following many tutorials, I have continually ran into the issue my light is specified in world coordinates, however, the shader treats the light's position as being in eye space, thus, the light direction changes when I move the camera. My question is, how to I transform a directional light position such as (50, 50, 50, 0) into eye space, or, would doing things this way be the incorrect approach to the problem?


RGB to xyY color space conversion and luminance The luminance calculated by following GLSL functions (fragment shaders tonemap) has different value float GetLuminance (vec3 rgb) return (0.2126 rgb.x) (0.7152 rgb.y) (0.0722 rgb.z) vec3 RGB2xyY (vec3 rgb) const mat3 RGB2XYZ mat3(0.4124, 0.3576, 0.1805, 0.2126, 0.7152, 0.0722, 0.0193, 0.1192, 0.9505) vec3 XYZ RGB2XYZ rgb return vec3(XYZ.x (XYZ.x XYZ.y XYZ.z), XYZ.y (XYZ.x XYZ.y XYZ.z), XYZ.y) I used a glm library to calculate an example result. For glm vec3(2.0f, 3.0f, 8.0f) GetLuminance returns 3.1484. RGB2xyY returns glm vec3 which z component is equal 3.8144. What is wrong ?


Invalid GLSL on some machines I'm writing a game engine using OpenGL 4.3 using gcc 5, mainly to teach myself graphics programming. Initial development was on my Surface Pro 3 using mingw w64 and worked like a charm. I've decided to move to my desktop, which is running two GTX 670s, and both Windows and Arch Linux. I've made sure that I have the latest NVIDIA drivers installed on both operating systems, but am having issues with my vertex and fragment shaders. All I know is that neither system compiles the shaders, but the OpenGL Reference Compiler simply issues a warning saying that OpenGL 4.3 might not be fully implemented. I've also tried downgrading all the way to OpenGL 4.0, but this doesn't seem to fix the issue. Below are the shaders that I'm currently trying out. Hoping someone more experienced than I can lend a hand? shader.vert version 430 layout (location 0) in vec3 vertex position layout (location 1) in vec2 vt uniform mat4 cam view, cam proj, sprite matrix out vec2 texture coordinates void main() texture coordinates vt gl Position cam proj cam view sprite matrix vec4(vertex position, 1.0) shader.frag version 430 in vec2 texture coordinates layout (binding 0) uniform sampler2D tex out vec4 frag colour void main() vec4 texel texture(tex, texture coordinates) frag colour texel Thanks in advance )


World position reconstruction from depth fails when viewport size does not match window size I'm facing very strange issue. My code for world pos reconstruction works correctly when the viewport size is equal to window size (or framebuffer size in other words). Below is the part for reconstruction to view space, later I multiply the result by inversed view matrix vec3 posFromDepth(in vec2 Tex, in float depth) vec3 pos vec3(Tex, depth) 2.0 1.0 clip space position float z projection 3 2 (pos.z projection 2 2 ) float x pos.x halfTanFovX z float y pos.y halfTanFovY z return vec3(x, y, z) When I change the viewport light and shadow calculations seems to be incorrect. The shadows for example instead of being "glued" to the object, floats a little bit along with camera movement. When I switched my deferred renderer to use world pos stored in G buffer then everything was calculated right. Is there some transformation of texture coordinates which I'm missing? I tried pass fullscreen quad coords in vertex attributes and compute using below formula gl FragCoord.xy texelSize but the results were the same. I'm searching for the issue more than week and slowly running out of ideas what could be wrong. Maybe you'll come up with something useful.


GL EXT draw instanced vs VBO's I'm having trouble understanding the benefit of the newer GL EXT draw instanced over traditional VBO's. Don't both keep geometry cached on the gpu for faster redrawing? VBO's seem much more flexible.


Efficient way of loading wavefront models in openGL game In my game, a RTS game, the units are all wavefront obj. all their animation frames are each seperate wavefront obj file. ie. without any skeletal animation fully rigid models. So when many units are loaded before a game starts, it takes too much time. for example, if 20 types of units are loaded, they take approximately 700 800MB in memory, take atleast 3 minutes to load. Can it be done in an efficient way somehow? Solutions I have already used As obj parsing take too much time. I have stored each obj as memory dump and load that dump. This helped a lot atleast reduced to 3min from 10min, for above example. Further Possible solution I tried I tried loading the anination frames on runtime, when they are accesessed. But this is making the game slow at some crucial time. Like when fighting, all units' fighting frames are loaded together. thus making the game slow. loading the units in different threads. Makes no improvement


How to calculate normal from normal map in world space? (OpenGL) I'm trying to do normal mapping in a deferred renderer and I'm stuck on how to implement normal maps. I have a bool that passes whether or not to use a normal mapped value and thus, whether to calculate the TBN matrix. My vertex code for the geometry pass looks as follows version 410 core layout (location 0) in vec3 aPos layout (location 1) in vec3 aNormal layout (location 2) in vec2 aTexCoords layout (location 3) in vec3 aTangent Optional Texture coordinates layout (location 4) in vec3 aBitangent Optional Texture coordinates out vec3 FragPos out vec2 TexCoords out vec3 Normal out mat3 TBN uniform mat4 model uniform mat4 view uniform mat4 projection uniform bool hasNormalMap void main() vec4 worldPos model vec4(aPos, 1.0) FragPos worldPos.xyz TexCoords aTexCoords Normal transpose(inverse(mat3(model))) aNormal if(hasNormalMap) vec3 T normalize(vec3(model vec4(aTangent, 0.0))) vec3 N normalize(vec3(model vec4(aNormal, 0.0))) re orthogonalize T with respect to N T normalize(T dot(T, N) N) then retrieve perpendicular vector B with the cross product of T and N vec3 B cross(N, T) mat3 TBN mat3(T, B, N) gl Position projection view worldPos Here is where I am confused In my calculation, I multiplied T and N by the model matrix which should have moved it into world space. Now transposing (T,B,N) should move me back into model space (I think, I'm not sure). In the fragment shader how do I use the TBN to calculate the normal in world space? If there are better approaches, they are welcome. Thank you. Update I removed the transposing of the TBN as there's no reason to transform into tangent space if we want to pass it in world space. Now that we have the TBN matrix in the fragment shader, how do we apply it so that the normal is the correct value for lighting? Currently I've done version 410 core layout (location 0) out vec3 gPosition layout (location 1) out vec3 gNormal layout (location 2) out vec4 gAlbedoSpec in vec2 TexCoords in vec3 FragPos in vec3 Normal in mat3 TBN struct Material sampler2D diffuseMap sampler2D specularMap sampler2D normalMap float shininess uniform Material material uniform bool hasNormalMap void main() store the fragment position vector in the first gbuffer texture gPosition FragPos also store the per fragment normals into the gbuffer gNormal normalize(Normal) if(hasNormalMap) gNormal texture(material.normalMap, TexCoords).rgb TBN gNormal normalize(gNormal) and the diffuse per fragment color gAlbedoSpec.rgb texture(material.diffuseMap, TexCoords).rgb store specular intensity in gAlbedoSpec's alpha component gAlbedoSpec.a texture(material.specularMap, TexCoords).r but that doesn't feel right. I imagine that I would transform the sampled value from the normal map by the TBN matrix to get it in world space. Am I missing something?


OpenGL specification error? Follow up for my previous question, whose answer lead to another question As the OpenGL specification documentation states, in glDrawElements(GLenum mode, GLsizei count, GLenum type, const GLvoid indices), indices "Specifies a pointer to the location where the indices are stored." So why does calling gl glDrawElements(gl GL TRIANGLES, IndexBuffer.size(), gl GL UNSIGNED INT, (void )(0)) work, but calling gl glDrawElements(gl GL TRIANGLES, IndexBuffer.size(), gl GL UNSIGNED INT, amp (IndexBuffer.at(0))) doesn't ?


glUniformMatrix4fv OpenTK equivalent Very simple and quick question which surprisingly I couldn't find an answer to over the internet what is the equivalent of glUniformMatrixfv for opentk? I've browsed all the 7 overloads of GL.UniformMatrix4 and none of them seems correct to me and or I have found any example usage for. E.g. if I have a Matrix4 matrices variable (properly initialized etc..) that I want to map on a mat4 matrices 2 in glsl, which GL.UniformMatrix4 overload should I use? P.S. Using OpenTK.Next NuGet package version 1.1.1616.8959


Trapping mouse inside window in OpenGL with GLUT? I perfectly understand that GLUT is limited and the following problem can't probably be solved with OpenGL GLUT, but since I don't know exactly if it can or not, I better just ask. Maybe I'm doing something wrong or forgetting something important. Or probably not and GLUT doesn't get better than this. My problem is that I can't trap the mouse inside the window. Well, actually, I can, the code below does just that. I trap the mouse inside the window and I can use the mouse freely to rotate the world. The problem? If I move the mouse too fast I can get way from window prison. Is there a way around this with OpenGL GLUT or the only option is another library or make some calls to the Windows API directly? Enough words, here's my current code void processPassiveMouseMotion(int x, int y) static int centerX glutGet(GLUT WINDOW WIDTH) 2 static int centerY glutGet(GLUT WINDOW HEIGHT) 2 CameraAngle.x 1.0f (y centerY) CameraAngle.y 1.0f (x centerX) if(CameraAngle.x ! 0.0f CameraAngle.y ! 0.0f) SceneCamera.Rotate(CameraAngle) glutPostRedisplay() glutWarpPointer(centerX, centerY) glutPassiveMotionFunc(processPassiveMouseMotion)


draw fog of war using shaders I am making a RTS game, and I'd like some advice on how to best render fog of wars, given what I'm already doing. You can imagine this game as being a classic RTS like Age of Empires 2, where the fog of war will basically be handled by a 2D array telling if a given "tile" is explored or not. The specific things to consider here are 1) I'm only doing a few draw calls to draw the whole screen, using shaders, and I'm not drawing "tile by tile" in a 2D loop 2) The whole map is much bigger than the screen, and the screen can move every frame or so In that case, how could I draw the fog of war ? I have no issue maintaining on the CPU side a 2D array giving the fog of war for each tile, but what would be the best way to actually display it dynamically ? thanks!


Creating a frustum for culling in world space glm matrices I need to do frustum culling where the bounding boxes are in world space to determine which entities get to be updated drawn. I was trying to use the classic projection view matrix plane extraction method but it doesn't seem to work with perspective matrices created by GLM. Is this method appropriate for world space culling? It seems like it would be (takes the eye position into account and the projection matrix shapes the frustum). I've only looked at the near far planes extract so far and they're wrong for a frustum sitting at the origin (Both have a c component that's negative which means near and far are facing the same direction). Also, since the d components can't match the near far clipping values with this method is it wrong for world space culling?


FBO picking in Oculus Rift applications I am writing an Oculus Rift application, I am rendering a very high poly mesh that I wish to be able to perform picking on using the Oculus Touch. Ideally, I want to be able to get the "triangle" id and other information attached to it. Currently, I am using an OBB Tree and ray casting to perform picking on the CPU, It works perfectly, the problem is that even with OBB tree the picking process is slow. I thought I'd perform picking on the GPU by rendering the view (from the point of view of the Oculus Touch) to an FBO using a custom shader that outputs "triangle information" to the buffer and then use glReadPixels to read the central pixel data. The problem I am facing is that the Oculus does distortion to my on screen scene but there is no way to apply it to the off screen buffer, so there is significant difference between the on screen buffer and the off screen buffer. My question is, Is ray casting the only feasible way to do picking in Oculus Apps or is there a way to perform the faster FBO picking even when the view distorted?


2D pixels change size when scrolling I'm working on a 2D side scroller, OpenGL, pixel art. And I'm having trouble getting the pixels to remain square when scrolling the camera. By that I mean, when scrolling the camera at low speed when you have tile pixels being draw at 2x2 scale, you can see some pixels become 3x2 in size rather than 2x2. I've tried different ways of calculating the size of the orthographic projection in order to get the pixels sized correctly, and while they do usually appear correct when stationary, they always wobble while scrolling. Here is my latest attempt at calculating window size for the orthographic projection define TILE SIZE 32 Each tile is 32x32 define TILE MIN HEIGHT 10 Adjust pixel size to fit at east 10 tiles vertically in the window float windowRatio (float)window gt width (float)window gt height int pixelSize window gt height TILE SIZE TILE MIN HEIGHT float tileHeight (float)window gt height (pixelSize TILE SIZE) gameState gt windowTileWidth tileHeight windowRatio TILE SIZE gameState gt windowTileHeight tileHeight TILE SIZE window gt orthoProjection matrix44 createOrthographic2D( gameState gt windowTileWidth, gameState gt windowTileHeight ) So far, I've tried all of these in an attempt to eliminate the wobble Calculate orthographic projection as above, to fix at least 10 tiles vertically, adjusting projection size to fit window ratio. Calculate orthographic projection to exactly fit a 20x10 tile scene, scaling pixels to fit window. Render the scene to a 1 1 scale framebuffer, then blit that buffer to the window to scale it up to desired pixel size. Disable offsetting of texture coordinates (I draw tiles from a texture atlas, and so offset the coordinates by 0.001 inside each quad to eliminate bleed from surrounding textures). None of these have eliminated the wobbling. Sometimes it is extremely subtle, but still present when examining the movement closely. What is the correct way to draw a 2D image to the scree with perfect square pixel accuracy, at a given pixel size?


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


Deferred shading how to combine multiple lights? I'm starting out with GLSL and I've implemented simple deferred shading that outputs G buffer with positions, normals and albedo. I've also written a simple point light shader. Now I draw a sphere for the point light and output goes into a lighting buffer. The problem is, how do I combine the results of lighting buffer when drawing multiple lights? E.g. when I'm drawing the second light to the lightbuffer using the point light shader, how do I add first light to the second light in the lighting buffer. I mean, you can't read from and write to the same output buffer?


Should I continue studying OpenGL or just switch to DirectX to give me a better chance of landing a job in the game industry? I've been learning graphics programming for some time now using OpenGL and Linux. I'm pretty familiar with most of the concepts, but I would really like to further my knowledge and eventually pursue a career in game development, especially game engine development. So far it seems to me that the majority of game studios make games for Windows using DirectX. Edit I know that the OpenGL vs DirectX question has been asked here before, but I haven't found an answer in the perspective I want. Edit 2 After reading all the responses comments I've decided to continue diving deeper into graphics with OpenGL GLSL, but I'll try to play around with DX as well, just to have a basic understanding of the API. I'd like to thank everyone for the answers and insight you've given me.


Game Maker Shader CGA how to swap the palette I created a shader that get the actual color of the surface and render it to the closer of a cga palette I have to change it to swap the palette in 4 colors but I don't know how secondary, I have to render it dynamic (maybe using an uniform variable) because it have to change in base of the palette please help me, thanks CGA Shader varying vec2 v vTexcoord xy varying vec4 v vColour rgba define 0.0 define o (1. 3.) define b (2. 3.) define B 1.0 define check(r,g,b) color vec4(r,g,b,0.) dist distance(sample,color) if (dist lt bestDistance) bestDistance dist bestColor color void main(out vec4 v vColour, in vec2 v vTexcoord) float dist float bestDistance 1000. vec4 color vec4 bestColor vec2 pixel vec2(320,200) floor( v vTexcoord.xy iResolution.xy vec2(320,200)) vec4 sample texture2D(iChannel0, pixel vec2(320,200)) sample (texture2D(iChannel1, pixel iChannelResolution 1 .xy) 0.5) 0.5 pallete 0 check( , , ) check(o,B,o) check(B,o,o) check(B,B,o) vec4 color1 bestColor bestDistance 1000. pallete 1 check( , , ) check(o,B,B) check(B,o,B) check(B,B,B) vec4 color2 bestColor float t (clamp(sin(iGlobalTime) 4., 1.,1.) 1.) 2. v vColour mix(color2, color1, t) gl FragColor v vColour texture2D( gm BaseTexture, v vTexcoord )


Triple buffering causes input lag? Consider some time in between two vsyncs. Suppose the first display buffer is being used to display the current image, and suppose the game was really fast and computed and rendered the next image to the second display buffer and the next one after that to the third display buffer. That is the rendering to the second and third display buffer happens so fast that it occurs before the next vsync. Suppose input from the user comes in now. What you would like is for the results of the input to show up on the next vsync or (probably more typical) the vsync after that. However, with the third display buffer already rendered the input can only effect the image after that. Meaning the input will only take effect at best 3 vsyncs later. I wish i had an image to show the exact timings of what I mean.


Camera scrolling and game boundaries I am making a platformer game in JBox2D and LWJGL that has a scrolling camera, but I have hit a wall with the boundaries of the camera. Essentially what I have right now is a Box2D world that is being draw on the screen, a viewport being moved by gluLookAt and several boundaries specified by Box2D edges that also help keep the player from moving out of bounds. It looks a bit like this What I'd like to do is "push" the camera when ever it comes in contact with the edge, but otherwise be centered on the player. I've tried a couple of methods for this, such as finding the min and max width and height, and simply doing an easy box hit test, and moving the screen accordingly, but that has it's limitations, such as if the world is not in a rectangular shape e.g. Another method I've tried is doing something where I raytrace from one vertex to another of each edge, and if it comes into contact with the screen, I "push" the screen out of the way, but that hasn't quite worked either Fixture fixture boundary.getFixtureList() Vec2 point null boolean hit false fixtureLoop for(int i 0 i lt boundary.m fixtureCount i ) EdgeShape edge (EdgeShape)fixture.getShape() Vec2 origin new Vec2(edge.m vertex1.x Main.OPENGL SCALE, edge.m vertex1.y Main.OPENGL SCALE) Vec2 direction new Vec2(edge.m vertex2.x Main.OPENGL SCALE, edge.m vertex2.y Main.OPENGL SCALE).sub(origin) for(float t 0 t lt 1.0f t 0.001f) Raytrace loop point origin.add(direction.mul(t)) See if point is within screen bounds if(point.x gt screenX Main.WIDTH 2 amp amp point.x lt screenX Main.WIDTH 2 amp amp point.y gt screenY Main.HEIGHT 2 amp amp point.y lt screenY Main.HEIGHT 2) hit true If hit, find closest vertex if(hit) float shortestDistance Float.MAX VALUE Vec2 vertex new Vec2() for(int v 0 v lt screenVertices.length v ) float distance point.sub(screenVertices i ).length() if(distance lt shortestDistance) shortestDistance distance vertex screenVertices v Vec2 displacement point.add(vertex.sub(new Vec2(screenX, screenY))) screenX displacement.x screenY displacement.y break fixtureLoop fixture fixture.getNext() What I have here is my attempt that I have played around with WAAAY too much. Essentially what I'm trying to do is detect if and edges are hitting the screen, find the point where they hit, find the closest screen vertex, subtract them to find the displacement between them, and apply it to the screen so that they're no longer in contact (The screenVertices array is essentially 4 vertices that look like Vec2(screenX WIDTH 2, screenY HEIGHT 2), etc) I was wondering if anyone could help me out, I'm not sure if I'm having logic problems, code problems, or both. Absolutely any help would be appreciated, thanks!


How to use default framebuffer's depth stencil when rendering to a texture? Is it possible to use the default framebuffer depth buffer when rendering to a texture (instead of using a depth texture)? The Idea is to continue to render part of the scene normally but on a separate texture so I can later apply a post processing effect without having to incur the cost of having another stencil depth buffer. Ho can I do that?


How to organize a fallback system for older GPUs in OpenGL? I don't want to make this question too broad or opinion based, but I really need some help about good practices. The scenario I created a particle engine with functions which require at least OpenGL 4.3. But some GPUs don't support this version, so I want to try to implement a fallback system for it. But it's not only the particle system. There are many features in 3D engines that can't be simply replaced by a different function name. Some features need different logic behind them and it can go quite complex. What are the best practices to manage fallback rendering in OpenGL?


What's better drawing every interval that the window updates, or drawing when necessary and updating when drawing? So what's better? In case the title is a bit confusing I mean 1) Drawing every window update interval. For example, for a 60FPS window, every 17 milliseconds. For example window.setFramerateLimit(60) Update every 17 milliseconds for 60FPS while(window.isOpen()) window.display() Or 2) Drawing when you need to (for example, when a sprite moves) and displaying it straight after. For example void func(sf RenderWindow amp window) window.draw(sf Sprite()) Whatever you're drawing window.display() Or is there a much better way?


1D vs 2D vs 3D texture performance I'm working on a 3D game with large blocky untextured, but individually colored, voxels (similar to CubeWorld). For rendering, right now I naively convert online all visible faces ahead of time to triangles with the color information stored in the vertex attributes. The screenshot below is an example of what I'm currently doing. There's a lot of room to improve here and I want to switch to a system that uses fewer vertices and stores color information in a texture. What I'd like to do is combine adjacent triangles with the same normals and simplify the mesh so I'm left with a fraction of the vertices. My big hangup is color information. It's easy to add UVs, but the correct choice for texturing isn't obvious. I'm trying to figure out the relative performance of these options Use a 1D texture. This is compact but I'm concerned that large 1D textures won't play nicely with texture mapping units optimized for 2D textures. Use a 2D texture. Simple, but it'll end up with gaps. Use a 3D texture with the full set of voxels. Does anyone have insight as to the relative performance of these options? No mipmapping or other filtering is needed here, so all three options should be viable. For reference I'm making this in C using OpenGL on Windows. My target GPU architectures are GTX 780 Ti and higher or AMD equivalent.


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


Texturing in OpenGL, Should texture coordinates be assigned to vertices in the shader? I attempting to texture 3D models (a cube for example) using ibo s, with OpenGL in Java. Currently, my textures are distorted. I believe this is because only a single texture coordinate is being assigned to each vertex, as the meshes are loaded from wave front (.obj) files. As each vertex should correspond to multiple texture coordinates, should I be assigning texture coordinates to vertices as the data is loaded from file or would it be better to assign texture coordinates to vertices in the shader? I would appreciate example code.


My generated texture is flipped I'm learning OpenGL and I don't understand why my texture is flipped if I give as UVs the "matching" vec2 of the mesh's vertex (vec3). Example vert 256 256 uv 0 0 vert 256 256 uv 1 1 I've had to try a different order for the UVs to be able to get the correct result... Can someone explain why is that so? Thanks. Screenshots http imgur.com a 49ZVp This are the snippets of code I use Create texture GLuint texDebugId RGBA Texture R G B A unsigned char texDebugBuf 255, 0, 0, 255, 0, 255, 0, 255, 0, 0, 255, 255, 0, 0, 0, 0, glEnable(GL TEXTURE 2D) glGenTextures(1, amp texDebugId) glBindTexture(GL TEXTURE 2D, texDebugId) glTexParameteri(GL TEXTURE 2D, GL TEXTURE MIN FILTER, GL NEAREST) glTexParameteri(GL TEXTURE 2D, GL TEXTURE MAG FILTER, GL NEAREST) glTexImage2D(GL TEXTURE 2D, 0, GL RGBA, 2, 2, 0, GL RGBA, GL UNSIGNED BYTE, texDebugBuf) glBindTexture(GL TEXTURE 2D, 0) glDisable(GL TEXTURE 2D) Prepare VBOs static const GLfloat verts 256.0f, 256.0f, 0.0f, 256.0f, 256.0f, 0.0f, 256.0f, 256.0f, 0.0f, 256.0f, 256.0f, 0.0f FLIPPED (but why?) static const GLfloat uvs 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, OK static const GLfloat uvs 0.0f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, Upload vertices glBindBuffer(GL ARRAY BUFFER, vbo id) glBufferData(GL ARRAY BUFFER, sizeof(verts), verts, GL STATIC DRAW) glBindBuffer(GL ARRAY BUFFER, 0) Upload UVs glBindBuffer(GL ARRAY BUFFER, vbo tex id) glBufferData(GL ARRAY BUFFER, sizeof(uvs), uvs, GL STATIC DRAW) glBindBuffer(GL ARRAY BUFFER, 0) Render glBindTexture(GL TEXTURE 2D, texId) glEnableVertexAttribArray((GLuint) pd.vertex a) glEnableVertexAttribArray((GLuint) pd.uv a) Vertices glBindBuffer(GL ARRAY BUFFER, vbo id) glVertexAttribPointer( (GLuint) pd.vertex a, attribute id 3, size GL FLOAT, type GL FALSE, normalized? 0, stride (void )0 array buffer offset ) UVs glBindBuffer(GL ARRAY BUFFER, vbo tex id) glVertexAttribPointer( (GLuint) pd.uv a, attribute id 2, size GL FLOAT, type GL FALSE, normalized? 0, stride (void )0 array buffer offset ) glDrawArrays(GL TRIANGLE STRIP, 0, 4) glBindBuffer(GL ARRAY BUFFER, 0) glDisableVertexAttribArray((GLuint) pd.uv a) glDisableVertexAttribArray((GLuint) pd.vertex a) glBindTexture(GL TEXTURE 2D, 0) Note proj matrix proj glm ortho( 320, 320, 240, 240, 1.0f, 100.0f) 640x480 with 0,0 at center camera matrix cam target glm vec3() cam up glm vec3(0.0, 1.0f, 0.0f) cam pos glm vec3(0.0f, 0.0f, 5.0f) camera glm lookAt(cam pos, cam target, cam up) MVP matrix glm mat4 mvp proj camera


Is there any performance benefit to sharing shaders between programs? OpenGL allows you to share the same shader between multiple programs. Aside from saving small amounts of memory and a shader handle, are there any GPU side performance benefits to doing this?


How to render tile maps in modern opengl? I'm trying to use SDL2 and Modern OpenGL to make a 2D rpg. The problem is, I have no idea how to render a tile map. I'm using the Tiled map editor to create maps. I have a vague idea of how to parse the maps using this (https github.com andrewrk tmxparser) tmx parser. I try to parse the maps using said parser, but then I run into the problem of how to actually get the tile maps to appear on screen, when using a spritebatch class. How would I go about rendering these maps using modern OpenGL?


What is the better approach to redraw a static background scene for game? Take for an example I have the background scene of a game which should remain static for an interval.Then for every time redrawing the scene,is it better for me to store the color buffer for every pixel on the viewport and redrawing using the stored color buffer or to applying a texture to the whole background or to draw the triangular,quad meshes?


What is the correct way to draw layered Sprites in modern OpenGL? So what do I mean by layered sprites? Layered Sprites are Sprites that consist of multiple layers, e.g. you have sprite sheets for the basic Body, the Head, Clothes, Weapons, etc. Well now I wanted to know how you would draw this in the most efficient way right now the idea is to use vertex buffer objects (VBOs), but I heard that it is expensive to change the textures in a VBO... So what would be the correct way to draw them? My idea right now would be to draw the Map tiles first (with a texture atlas), then I would draw all the basic bodys, then the heads, then clothes, and then the weapons. Would that be the best way or is there a more efficient way? I also thought of using vertex arrays instead of VBOs, but as far as I know they are deprecated...


3D models on 2D tilemap perspective when scrolling I am creating a small top down game, where the player traverses a 2D tilemap, with an illusion of depth provided by 3D models for things like buildings or trees. Having gotten to the point where I can render models and a basic terrain as a background, I've gotten stuck on the task of joining both together in a way as to seem not too unnatural. I think an image description of my problem would be best suited for this. For the sake of explanation, the model I am rendering is a transparent cube. In this position, where the camera has a head on view, everything looks generally normal. Now, if I shift the model a bit to the right, the following gets displayed Not horrible by any means, but it does look a tad bit awkward the road remains straight while the building seems to be jutting out from the path. The building itself has been panned, but the ground has remained static. Additionally, this has proven rather nausea inducing during testing, due to the awkward mixing of angles. The only possible solution that came to me (and hence why I am asking here) would be to render each tile as a model as well. I think that creating a flat rectangle the size of the viewable screen and texturing it with the visible tiles could possible work that way, since it is a model, it can be rotated and shrunk based on visibility, like the model. However, I am (very) new to OpenGL, and I fail to see how I could implement this. I know that I can draw a textured rectangle with one, solid texture. I don't know how to draw multiple, smaller textures across a face of the rectangle is it even possible? Then, considering that I wish to have other things like cliffs, I wondered if cliff tiles could be rendered as being slanted. My map format has a height map, so the slant could be determined by the direction in which the nearest tile with a smaller height resides. I fear I'm being rather clumsy at explaining this, which is why, using my most Picasso esque skills I have put together the next image Essentially, though the map itself is made up of 2D tiles, by changing the angle they are being rendered at I reckon it would be possible to simulate a 3D effect the player camera (smiley in the image) would not be able to see the leftmost side (yellow) if they are positioned towards the right. Regardless, this is all hypothetical and I have no idea where to even begin. Is it possible to render the background as essentially a model in 3D space? If so, how would this be done via one large cuboid, or multiple smaller ones? Lastly, would slanting textures based on neighbor height work? More importantly, is there a better way to achieve my goals than what I have proposed? For all it matters, I am writing this game in Java, utilizing the LWJGL OpenGL wrapper.


Should unbind buffers? I'm making some tests with OpenGL ES 2 and got some questions, my current program is like that Init gt create index buffer gt fill index buffer glBufferData gt create vertex buffer gt fill vertex buffer glBufferData Draw 1. Apply vertex buffer gt Bind VAO gt bind vertex buffer enable attributs (glVertexPointer, ) gt unbind vertex buffer gt Unbind VAO gt Bind VAO 3. Apply index buffer 4. Draw The problem The given code crash, after some researches, I've understood why I need to unbind my index buffer in init part (after "fill index buffer glBufferData") or unbind it before the first "Bind VAO" My questions are Can I put my index buffer in VAO (VAO stock index buffer?)? Did I have to unbind buffers after each update (glBufferData)? In my application I've got some buffers who are updated on each frame (Exemple Particles) so I've got an OpenGL stack like that gt bind buffer 1 gt update buffer 1 gt close buffer 1 gt bind buffer 1 gt draw First 3 lines update the Vertex buffer, the two last draw object, that should be something like that gt bind buffer 1 gt update buffer 1 gt draw Thanks


Convertion from 3D to 2D openGL Few days ago , we learned about Homogeneous Matrices in OpenGL class. From what I have understood , using these matrices we can convert 3D objects to 2D. However , I am facing some difficulties answering a simple question like "Which of those matrices answering to the definition of converting from 3D to 2D (Homogeneous)" A B C D I'm not asking you to do my homework, I know the answer it's D and C and this is all I need for this section. I just want to understand why? how it works? why A,B not and C,D yes. Thank you.


OpenGL are strips fans faster for rendering or just data bandwidth When we send data for drawing we can mark it as TRIANGLE STRIP or TRIANGLE FAN to reduce the number of vertices we have to specify. Now, does this actually improve the rendering speed on the graphics card, or does it merely reduce the amount of data that has to be sent to the card? I'm using a very simple model. To construct it correctly I need multiple calls to glDrawArrays using TRIANGLE STRIP. If I switch to using just GL TRIANGLES I could have just one call to glDrawArrays. Is this type of apporach useful, or is the overhead of an the call to glDrawArrays low enouhg that it won't make a difference. I will profile, but since I have only one card I don't know if my result will be indicative of the general case. (NOTE I need to be ES2 compliant, so some of my options are limited).


Trying to implement Camera I'm trying to implement a Camera class in order to walk and look on the world as follow ifndef CAMERA H define CAMERA H include lt glm glm.hpp gt class Camera public Camera() Camera() void Update(const glm vec2 amp newXY) if by 0.0 it means, it will use the const Class speed to scale it void MoveForward(const float by 0.0f) void MoveBackword(const float by 0.0f) void MoveLef(const float by 0.0f) void MoveRight(const float by 0.0f) void MoveUp(const float by 0.0f) void MoveDown(const float by 0.0f) void Speed(const float speed 0.0f) glm vec3 amp GetCurrentPosition() glm vec3 amp GetCurrentDirection() glm mat4 GetWorldToView() const private glm vec3 position, viewDirection, strafeDir glm vec2 oldYX float speed const glm vec3 up endif include "Camera.h" include lt glm gtx transform.hpp gt Camera Camera() up(0.0f, 1.0f, 0.0), viewDirection(0.0f, 0.0f, 1.0f), speed(0.1f) Camera Camera() void Camera Update(const glm vec2 amp newXY) glm vec2 delta newXY oldYX auto length glm length(delta) if (glm length(delta) lt 50.f) strafeDir glm cross(viewDirection, up) glm mat4 rotation glm rotate( delta.x speed, up) glm rotate( delta.y speed, strafeDir) viewDirection glm mat3(rotation) viewDirection oldYX newXY void Camera Speed(const float speed) this gt speed speed void Camera MoveForward(const float by) float s by 0.0f ? speed by position s viewDirection void Camera MoveBackword(const float by) float s by 0.0f ? speed by position s viewDirection void Camera MoveLef(const float by ) float s by 0.0f ? speed by position s strafeDir void Camera MoveRight(const float by ) float s by 0.0f ? speed by position s strafeDir void Camera MoveUp(const float by ) float s by 0.0f ? speed by position s up void Camera MoveDown(const float by ) float s by 0.0f ? speed by position s up glm vec3 amp Camera GetCurrentPosition() return position glm vec3 amp Camera GetCurrentDirection() return viewDirection glm mat4 Camera GetWorldToView() const return glm lookAt(position, position viewDirection, up) and I update and render as follow void Game OnUpdate() glLoadIdentity() glClear(GL COLOR BUFFER BIT GL DEPTH BUFFER BIT) glUniformMatrix4fv(program gt GetUniformLocation("modelToViewWorld"), 1, GL FALSE, amp cam.GetWorldToView() 0 0 ) void Game OnRender() model gt Draw() Which the Vertix shader is version 410 layout (location 0) in vec3 inVertex layout (location 1) in vec2 inTexture layout (location 2) in vec3 inNormal uniform mat4 modelToViewWorld void main() gl Position vec4(mat3(modelToViewWorld) inVertex, 1) But in result the model itslef is moving rotating instead of moving the camera around the model. What am I doing wrong here?


How do i writing timing function for lightning flash in C ? I need to write a horror scene with lightning flash. Unfortunately I am new to both C and OpenGL and I am looking for efficient way to mimic lightning timing in C OpenGL? I don't need graphical implementation, just algorithmic implementation. as such, the function should return a float representing lighting intensity and the delay of lightning flash should be random (5 seconds followed by 10 seconds then 3 seconds.. etc) I hope I made everything clear!


How can I change the value of a matrix uniform in an OpenGL vertex shader? I'm new at OpenGL. I have a uniform transform matrix in a vertex shader file. I want to modify the matrix by individually assigning each values in the matrix. How can I do that in C ? I learned that we have to get location variable by using glGetUniformLocation but I am not sure how to access and modify index n with it with glUniform.


Casting a Matrix4 class to float glUniformMatrix4fv(glGetUniformLocation(program, "projMatrix"), 1, false, (float ) amp projMatrix) projMatrix is a an object of type Matrix4 where the first variable declared is a float array. Does (float ) amp projMatrix therefore somehow retrieve this array? What does the casting appear to be doing?


Geometry Shader crashing I keep getting some strange errors in my Geometry shader and when I search for the cause of the errors, it returns nothing substantial. Here is the code. Shader version 450 core layout(triangles) in layout(points, max vertices 3)out void main(void) int i for (i 0 i lt gl in.length() i ) gl Position gl in i .gl Position EmitVertex() Log. 0(4) error C3008 unknown layout specifier 'max vertices 3' 0(4) error C3008 unknown layout specifier 'points' 0(10) error C3004 function "void EmitVertex() " not supported in this profile I'm using OpenGL 4.5 (My pc supports it before anyone asks p) and and glfw 3.2 EDIT Here is the steps I'm using to load up my shader. Creating a shader instance shader new StaticShader("VertexShader.shader", "TesselationControl.shader", "TessilationEvaluation.shader", "Geometry.shader", "FragmentShader.shader") StaticShader Constructor ShaderProgram ShaderProgram(const char vertex file path, const char tesselation controll shader path, const char tesselation evaluation shader path, const char geometry shader path, const char fragment file path) vertexShaderID loadShader(vertex file path, GL VERTEX SHADER) tessControllShaderID loadShader(tesselation controll shader path, GL TESS CONTROL SHADER) tessEvaluationShaderID loadShader(tesselation evaluation shader path, GL TESS EVALUATION SHADER) geometryShaderID loadShader(geometry shader path, GL GEOMETRY SHADER) fragmentShaderID loadShader(fragment file path, GL FRAGMENT SHADER) Status("ShaderProgram", "Initilizing shader program") programID glCreateProgram() glAttachShader(programID, vertexShaderID) glAttachShader(programID, tessControllShaderID) glAttachShader(programID, tessEvaluationShaderID) glAttachShader(programID, geometryShaderID) glAttachShader(programID, fragmentShaderID) bindAttributes() glLinkProgram(programID) GLint isLinked 0 glGetProgramiv(programID, GL LINK STATUS, (int ) amp isLinked) if (isLinked GL FALSE) GLint maxLength 0 glGetProgramiv(programID, GL INFO LOG LENGTH, amp maxLength) if (maxLength gt 1) GLchar infoLog (GLchar )malloc(maxLength) glGetProgramInfoLog(programID, maxLength, amp maxLength, amp infoLog 0 ) std cout lt lt infoLog StatusError() exit(0) StatusOkay() Clean Up glDetachShader(programID, vertexShaderID) glDetachShader(programID, tessControllShaderID) glDetachShader(programID, tessEvaluationShaderID) glDetachShader(programID, geometryShaderID) glDetachShader(programID, fragmentShaderID) glDeleteShader(vertexShaderID) glDeleteShader(tessControllShaderID) glDeleteShader(tessEvaluationShaderID) glDeleteShader(geometryShaderID) glDeleteShader(fragmentShaderID) Load shader function GLuint ShaderProgram loadShader(const char file path, int type) GLuint shaderID glCreateShader(type) std string shaderCode FileManager readFile(file path) char const sourcePointer shaderCode.c str() Status("ShaderObject", "Compiling Shader " std string(file path)) glShaderSource(shaderID, 1, amp sourcePointer, NULL) glCompileShader(shaderID) GLint isCompiled 0 glGetShaderiv(shaderID, GL COMPILE STATUS, amp isCompiled) if (isCompiled GL FALSE) GLint maxLength 0 glGetShaderiv(shaderID, GL INFO LOG LENGTH, amp maxLength) if (maxLength gt 1) GLchar infoLog (GLchar )malloc(maxLength) glGetShaderInfoLog(shaderID, maxLength, amp maxLength, amp infoLog 0 ) std cout lt lt infoLog StatusError() exit(0) StatusOkay() return shaderID


JOGL hardware based shadow mapping computing the texture matrix I am implementing hardware shadow mapping as described here. I've rendered the scene successfully from the light POV, and loaded the depth buffer of the scene into a texture. This texture has correctly been loaded I check this by rendering a small thumbnail, as you can see in the screenshot below, upper left corner. The depth of the scene appears to be correct objects further away are darker, and that are closer to the light are lighter. However, I run into trouble while rendering the scene from the camera's point of view using the depth texture the texture on the polygons in the scene is rendered in a weird, nondeterministic fashion, as shown in the screenshot. I believe I am making an error while computing the texture transformation matrix, but I am unsure where exactly. Since I have no matrix utilities in JOGL other then the gl Load Mult Matrix procedures, I multiply the matrices using them, like this void calcTextureMatrix() glPushMatrix() glLoadIdentity() glLoadMatrixf(biasmatrix, 0) glMultMatrixf(lightprojmatrix, 0) glMultMatrixf(lightviewmatrix, 0) glGetFloatv(GL MODELVIEW MATRIX, shadowtexmatrix, 0) glPopMatrix() I obtained these matrices by using the glOrtho and gluLookAt procedures glLoadIdentity() val wdt width 45 val hgt height 45 glOrtho(wdt, wdt, hgt, hgt, 45.0, 45.0) glGetFloatv(GL MODELVIEW MATRIX, lightprojmatrix, 0) glLoadIdentity() glu.gluLookAt( xlook lightpos. 1, ylook lightpos. 2, lightpos. 3, xlook, ylook, 0.0f, 0.f, 0.f, 1.0f) glGetFloatv(GL MODELVIEW MATRIX, lightviewmatrix, 0) My bias matrix is float biasmatrix new float 16 0.5f, 0.f, 0.f, 0.f, 0.f, 0.5f, 0.f, 0.f, 0.f, 0.f, 0.5f, 0.f, 0.5f, 0.5f, 0.5f, 1.f After applying the camera projection and view matrices, I do glTexGeni(GL S, GL TEXTURE GEN MODE, GL EYE LINEAR) glTexGenfv(GL S, GL EYE PLANE, shadowtexmatrix, 0) glEnable(GL TEXTURE GEN S) for each component. Does anybody know why the texture is not being rendered correctly? Thank you.


Change flag if mousepress while on loop I have this program that starts a loop when the key is pressed The problem is that when i start the loop, i want to be able to stop it halfway with my mousepress. The problem is that it doesn't register my mousepress until my loop is done. How do I stop it halfway if the mouse was pressed in my loop? I tried a flag, if(mousePressed) but the flag doesnt change until the loop is done


Create YUV texture for GL TEXTURE EXTERNAL OES format 0 down vote favorite I need to create a yuv texture for GL TEXTURE EXTERNAL OES format. source https github.com crossle MediaPlayerSurface blob master src me crossle demo surfacetexture VideoSurfaceView.java I am doing all processing on YUV, so it would save clock cycles, if I can generate a yuv texture as output of texture2D. To get 'y' value, I need to take dotproduct of each texel with vec3 of (0.3,0.59,0.11) Since, for my purpose I need to take 3x3 pixel block's 'y' value and take a convolution of them, this results in performance impact. So it would save clock cycles, if I can generate a yuv texture as output of texture2D.


How to emulate PSX's graphics with OpenGL? I want to know what options (or shaders) to set so that my OpenGL game looks like Playstation 1 game. I know it probably can not be achieved 100 because PSX used television and television renders differently that monitor. Thanks. )


Rotation along normal vector I have a triangle in the 3D world. I have the positions for the three points the normal vectors for the three points (all the same, because vertices are not shared) This triangle faces to a direction, so it has a XYZ rotation (but I dont know the rotation itself). If I put a cube into the same scene, how I can achieve the same rotation for the cube? So if the triangle "looks" upwards, the cube should do the same. If it has a 10f x rotation, how can I get what is the x?


(While using a cube map) box like textures appearing around my scene whenever I move the camera I've been learning about cube map and I implemented one into my program. It seemed to work well until I started moving the camera around the scene and zooming out. As you can see in the attached gif, there seems to be a problem with the cube map since this weird behavior is occurring https gyazo.com 70ad4ce027d1e032bc19258e28def66f Main program unsigned int cubemapTexture texo.loadCubeMap(faces) glDepthFunc(GL EQUAL) bg.bind() skyBox.use() glm mat4 projection glm perspective(glm radians(fov), (float)scr width (float)scr height, 0.1f, 100.0f) glm mat4 view camera.GetViewMatrix() skyBox.setUniformMat4("projection", projection) skyBox.setUniformMat4("view", view) glActiveTexture(GL TEXTURE20) glBindTexture(GL TEXTURE CUBE MAP, cubemapTexture) GLCall(glDrawArrays(GL TRIANGLES, 0, 36)) loadCubeMap unsigned int Textures loadCubeMap(std vector lt std string gt faces) unsigned int textureID glGenTextures(1, amp textureID) glBindTexture(GL TEXTURE CUBE MAP, textureID) stbi set flip vertically on load(false) int width, height, nrChannels for (unsigned int i 0 i lt faces.size() i ) unsigned char data stbi load(faces i .c str(), amp width, amp height, amp nrChannels, 0) if (data) glTexImage2D(GL TEXTURE CUBE MAP POSITIVE X i, 0, GL RGB, width, height, 0, GL RGB, GL UNSIGNED BYTE, data ) stbi image free(data) else std cout lt lt "Cubemap tex failed to load at path " lt lt faces i lt lt std endl stbi image free(data) glTexParameteri(GL TEXTURE CUBE MAP, GL TEXTURE MIN FILTER, GL LINEAR) glTexParameteri(GL TEXTURE CUBE MAP, GL TEXTURE MAG FILTER, GL LINEAR) glTexParameteri(GL TEXTURE CUBE MAP, GL TEXTURE WRAP S, GL CLAMP TO EDGE) glTexParameteri(GL TEXTURE CUBE MAP, GL TEXTURE WRAP T, GL CLAMP TO EDGE) glTexParameteri(GL TEXTURE CUBE MAP, GL TEXTURE WRAP R, GL CLAMP TO EDGE) return textureID Vertex Shader version 330 core layout (location 0) in vec3 aPos out vec3 TexCoords uniform mat4 view uniform mat4 projection void main() vec4 pos projection view vec4(aPos, 1.0) TexCoords aPos Setting z value to w (1.0) so that the cube map is always in the background gl Position pos.xyww Fragment shader version 330 core out vec4 FragColor in vec3 TexCoords uniform samplerCube skybox void main() FragColor texture(skybox, TexCoords) The problem probably originates from one of these snippets, but if you have any other ideas I can provide more info.


Drawing multiple objects from one Vertex Buffer Object in OpenGL OpenTK I am trying to experimenting drawing method using VBO in OpenGL. Many people normally use 1 vbo to store one object data array. I was trying to do something quite opposite which is storing multiple object data into 1 vbo then drawing it. There is story behind why i want to do this. I want to group many of objects as a single object sometime. However my code doesn't do the justice. Following is my pseudo code Data int vBO new int 1 vertex buffer objects triangleVertices new float 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, first triangle lineloop, positions in the middle of the screen. 3.0f, 1.0f, 0.0f, 2.0f, 1.0f, 0.0f, 4.0f, 1.0f, 0.0f, second triangle lineloop, positions on the left side of the first triangle. 3.0f, 1.0f, 0.0f, 4.0f, 1.0f, 0.0f, 2.0f, 1.0f, 0.0f third triangle lineloop, positions on the right side of the first triangle. Setting Up void init() GL.GenBuffers(1, vBO) GL.BindBuffer(BufferTarget.ArrayBuffer, vBO 0 ) GL.BufferData(BufferTarget.ArrayBuffer, new IntPtr(sizeof(float) triangleVertices.Length), triangleVertices, BufferUsageHint.StaticDraw) GL.VertexPointer(3, VertexPointerType.Float, 0, 0) GL.EnableClientState(Array.VertexArray) Drawing void display() GL.Clear(ClearBufferMask.ColorBufferBit) GL.Clear(ClearBufferMask.DepthBufferBit) setting up camera and projection. float eyes 0.0f, 0.0f, 10.0f float target 0.0f, 0.0f, 0.0f Matrix4 projection Matrix4.CreatePerspectiveFieldOfView(0.785398163f, 4.0f 3.0f, 0.1f, 100f) 45 degree 0.785398163 rads Matrix4 view Matrix4.LookAt(eyes 0 , eyes 1 , eyes 2 , target 0 , target 1 , target 2 , 0, 1, 0) Matrix4 model Matrix4.Identity Matrix4 MV view model GL.MatrixMode(MatrixMode.Projection) GL.LoadIdentity() GL.LoadMatrix(ref projection) GL.MatrixMode(MatrixMode.Modelview) GL.LoadIdentity() GL.LoadMatrix(ref MV) GL.Viewport(0, 0, glControlWindow.Width, glControlWindow.Height) GL.Enable(EnableCap.DepthTest) Enable correct Z Drawings GL.DepthFunc(DepthFunction.Less) Enable correct Z Drawings GL.MatrixMode(MatrixMode.Modelview) Draw drawTriangleLineLoops() Finally... GraphicsContext.CurrentContext.VSync true Caps frame rate as to not over run GPU glControlWindow.SwapBuffers() Takes from the 'GL' and puts into control void drawTriangleLineLoops() GL.BindBuffer(BufferTarget.ArrayBuffer, vBO 0 ) GL.VertexPointer(3, VertexPointerType.Float, 0, 0) GL.EnableClientState(ArrayCap.VertexArray) GL.DrawArrays(BeginMode.LineLoop, 0, 3) drawing first triangle lineloop, first vertex starts at index 0. GL.DrawArrays(BeginMode.LineLoop, 9, 3) drawing second triangle lineloop, first vertex starts at index 9. GL.DrawArrays(BeginMode.LineLoop, 18, 3) drawing third triangle lineloop, first vertex starts at index 18. GL.DisableClientState(ArrayCap.VertexArray) I expect 3 different triangles to be drawn, but only one was drawn. I don't know what went wrong.


OpenGL Array Texture generates black texture I am creating a game using OpenGL that has many textured cubes. I am trying to use an Array Texture to load multiple textures from one file. I tried to setup my texture atlas however, all that renders is a black texture. I'm not sure what exactly I am doing wrong. Here is the texture loading code Load image stbi set flip vertically on load(true) unsigned char data stbi load(path, amp width, amp height, amp nrChannels, 0) Generate texture object glActiveTexture(GL TEXTURE0) glGenTextures(1, amp textureId) glBindTexture(GL TEXTURE 2D ARRAY, textureId) Actually load texture if (data) glTexImage3D(GL TEXTURE 2D ARRAY, 0, GL RGBA, width, height, 0, 0, GL RGB, GL UNSIGNED BYTE, data) glGenerateMipmap(GL TEXTURE 2D ARRAY) else std cout lt lt "Failed to load " lt lt path lt lt " texture" lt lt std endl set texture filtering parameters glTexParameteri(GL TEXTURE 2D ARRAY, GL TEXTURE MIN FILTER, GL NEAREST) glTexParameteri(GL TEXTURE 2D ARRAY, GL TEXTURE MAG FILTER, GL NEAREST) Free memory stbi image free(data) Here is my fragment shader version 330 core out vec4 FragColor in vec2 TexCoord uniform sampler2DArray my sampler void main() FragColor texture(my sampler, vec3(0, 0, 1)) vec4(1.0f) Here is my texture file Does anyone know how I can solve my issue?


How can I draw curves above a mesh surface? I am making an animation of a deformed sphere that represents some aspects of the wave function in a hydrogen atom. I am starting with an octahedron that i push through a tessellation shader. The tessellation evaluation shader then first deforms the octahedron into something more sphere like and then applies the deformation stuff. Now, to further improve the visual impression of the deformation, I would like to place lines on top of the sphere and also deform those, to achieve something resembling level curves. What would be a good way to achieve this? Generating circles on the cpu side and then sending them to GL and having them deformed separately seems rather odd, but I cannot figure out another way. If I want to achieve this in one shader run I am also limited to drawing triangles (patches) and making these appear as lines also seems rather unwieldy.