OpenGL question about glColorPointer So, I'm just starting out with LWJGL, and my current task is to render two colored cubes on the screen. I can render them, however, I'm looking for some advice on the most efficient way to specify the colors. Currently, I'm doing this specify vertices and colors vertexData.put(new float 0.5f, 0.5f, 0, 0.5f, 0.5f, 0, 0.5f, 0.5f, 0, 0.5f, 0.5f, 0, 1st cube vertices 1.0f, 2.5f, 0, 0, 2.5f, 0, 1.0f, 1.5f, 0, 0, 1.5f, 0 ) 2nd cube vertices colorData.put(new float 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1, colors for 1st cube 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1 ) colors for 2nd In the render loop glVertexPointer(vertexBufSize, GL FLOAT, 0, 0L) glColorPointer(colorBufSize, GL FLOAT, 0, 0L) ... glDrawArrays(GL TRIANGLE STRIP, 0, 4) 1st cube glDrawArrays(GL TRIANGLE STRIP, 4, 4) 2nd cube This works, but I can't help but think that since I'm specifying the exact same color values for both cubes, I'm wasting memory. I was hoping to just have one set of vertex colors that could be applied to each cube that gets drawn. Can it be done? If so, what is the best way to do it? Thanks


How do you create a fractal cube map? I want to create a map similar to how Mincraft and other related games do. I just haven't the faintest clue on how to do so. Can anyone point me to a decent tutorial or give me a decent run through? I program in java and use openGL.


opengl flickering of fragments even with disabled depth test I'm trying to render a quad with a coloured border. I'm using texture coordinates to detect whether the fragment should be considered part of border or not. If it is part of border, then render it with green colour or else with black colour. Here are my vertices normals tex coordinates. float vertices posistions normals texture coords 0.5f, 0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.5f, 0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 0.5f, 0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, 0.5f, 0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, 0.5f, 0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.5f, 0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, Here's my fragment shader version 330 core in vec3 frag pos in vec3 frag nor in vec2 frag tex out vec4 frag color void main() vec2 origin vec2(0.01, 0.01) float width 1.0 origin.x 2.0 float height 1.0 origin.y 2.0 if( (frag tex.x gt origin.x amp amp frag tex.x lt origin.x width) amp amp (frag tex.y gt origin.y amp amp frag tex.y lt origin.y height) ) frag color vec4(0.0) else frag color vec4(0.0, 1.0, 0.0, 0.0) And this is how I'm rendering glDisable(GL DEPTH TEST) glBindVertexArray(vao) glDrawArrays(GL TRIANGLES, 0, 6) In right, I'm drawing the same quad with another pass through fragment shader in wireframe mode. As you can see the left quad is flickering while moving the camera. Any ideas how to fix this.


Why are my texture coordinates always (0,0) in this shader? What I'm trying to do is add my depth buffers values to my scene, ie. I'm trying to make objects closer to the camera darker and objects further away lighter. Which should be easy just render the depth buffer to a texture, and then render the scene, multiplying each pixels colour by the colour value at the same coordinates in my depth buffer texture... Yet I don't know how to use coordinates for textures. Or more like it's just failing. What's happening is that the vertex shader is only using the (0,0) coordinate of my texture, so the entire scene changes colour depending on what's there. What I'm doing is this (the critical stuff from my render function) glActiveTexture(GL TEXTURE0) glBindTexture(GL TEXTURE 2D, depthTextureId) Binds the texture box.render() Sets the viewing matrix and renders a test VBO I guess that's the right way to bind a texture? Anyhoo, here's the vertex shader's important stuff out vec4 ShadowCoord void main() gl Position PMatrix (VMatrix MMatrix) gl Vertex Projection view and model matrices ShadowCoord gl MultiTexCoord0 something I kept seeing in examples, was hoping it would work. It seems gl MultiTexCoord0 is the problem? Maybe? The frag shader sets the colour using this function vec4(texture2D(ShadowMap, ShadowCoord.st).x vec3(Color), 1.0) Where the ShadowMap is the sampler2D for the texture, and Color is the vertex's color... So what am I missing? How come the coordinates are not changing from 0,0?


NiftyGUI Text isn't rendering I am trying to create a gui with nifty on top of lwjgl. I've already had some problems during the Nifty setup, however now Nifty is set up and running correctly but for text rendering. Here is my xml file lt ?xml version "1.0" encoding "UTF 8"? gt lt ! To change this license header, choose License Headers in Project Properties. To change this template file, choose Tools Templates and open the template in the editor. gt lt nifty xmlns "http nifty gui.sourceforge.net nifty 1.4.xsd" xmlns xsi "http www.w3.org 2001 XMLSchema instance" xsi schemaLocation "http niftygui. sourceforge.net nifty 1.4.xsd http nifty gui.sourceforge.net nifty 1.4.xsd" gt lt screen id "start" gt lt layer childLayout "center" gt lt panel id "panel" height "25 " width "35 " align "center" valign "center" backgroundColor " f60f" childLayout "center" visibleToMouse "true" gt lt text id "text" font "aurulent sans 16.fnt" color " ffff" text "Hello World!" gt lt panel gt lt layer gt lt screen gt lt nifty gt and here the respective java class package niftylwjgl import de.lessvoid.nifty.Nifty import de.lessvoid.nifty.nulldevice.NullSoundDevice import de.lessvoid.nifty.renderer.lwjgl.input.LwjglInputSystem import de.lessvoid.nifty.renderer.lwjgl.render.LwjglRenderDevice import de.lessvoid.nifty.tools.TimeProvider import org.lwjgl.LWJGLException import org.lwjgl.input.Keyboard import org.lwjgl.opengl.Display import org.lwjgl.opengl.GL11 public class NiftyLwjgl private static Nifty nifty private static boolean close private static LwjglInputSystem inSys public static void main(String args) throws LWJGLException, Exception init() initNifty() while (!close) update() preRender() render() postRender() destroy() private static void init() throws LWJGLException Display.setDisplayMode(Display.getDesktopDisplayMode()) Display.setFullscreen(true) Display.create() GL11.glOrtho(0, 1920, 0, 1080, 1, 1) private static void initNifty() throws Exception inSys new LwjglInputSystem() inSys.startup() nifty new Nifty(new LwjglRenderDevice(), new NullSoundDevice(), inSys, new TimeProvider()) nifty.fromXml("xml main.xml", "start") nifty.loadStyleFile("nifty default styles.xml") nifty.loadControlFile("nifty default controls.xml") private static void preRender() GL11.glClear(GL11.GL COLOR BUFFER BIT GL11.GL DEPTH BUFFER BIT GL11.GL STENCIL BUFFER BIT) GL11.glMatrixMode(GL11.GL PROJECTION) GL11.glLoadIdentity() GL11.glMatrixMode(GL11.GL MODELVIEW) GL11.glEnable(GL11.GL TEXTURE 2D) private static void postRender() GL11.glDisable(GL11.GL TEXTURE 2D) private static void update() if (Display.isCloseRequested() Keyboard.isKeyDown(Keyboard.KEY ESCAPE) nifty.update()) close true private static void render() nifty.render(false) Display.update() private static void destroy() inSys.shutdown() Display.destroy() Here is a screenshot of the application running I somehow feel like I'm missing something incredible simple but important, like an glXXXXX call. Any help suggestions are appreciated.


Cascade(Waterfalls) particles animation openframeworks, alternatives Has anyone tried to create a waterfall particles animation using openframeworks? Is it possible? Is it good? If not, can you recommend any other frameworks for easier creation of cascade animation? Thanks a LOT!


Gamma Space and Linear Space with Shader I am using Unity and I can choose between two color space mode in the settings Gamma or Linear Space. I am trying to build a Custom Lighting Surface shader but I am facing some problems with those Color Space. Because the render is not the same depending of the Color Space. If I render the lightDir, Normal or viewDir I can see that they are different depending of the Color Space I use. I made some test and the result I have in Linear Space is great but how can I obtain the same result in Gamma Space ? Are there some transformations ? On what component should I apply those transformations ? Thank you very much !


Can I use glTranslate and glRotate when my GLSL Version over ( version 120)? I was using "GLSL Version 120". But now i am trying to do one tutorial and it is using "gl ClipDistance 0 " inside of vertex shader. And "GLSL Version 120" doesn't support "gl ClipDistance 0 ". Now i need to change GLSL Version with over 120 for example 330 . I also have to change "gl ModelViewProjectionMatrix" inside vertex shader. But my question is i need to change glTranslate,glRotate,glLoadIdentity etc ?


I get GL INVALID VALUE after calling glTexSubImage2D I am trying to figure out why my texture allocation does not work. Here is the code glTexStorage2D(GL TEXTURE 2D, 2, GL RGBA8, 2048, 2048) glTexSubImage2D(GL TEXTURE 2D, 0, 0, 0, 2048, 2048, GL RGB, GL UNSIGNED SHORT 5 6 5 REV, amp BitMap 0 ) glTexSubImage2D returns GL INVALID VALUE but the maximum texture allowed is 16384x16384 on my card. The source of the image is 16bit (Red 5, Green 6, Blue 5).


How should I structure VBOs for my 2d world data? My game is played on a fixed size hex based arena, where each hex can be of a different type, and possibly contain some creatures items anything on it. When I started out, I got the advice to have a VBO per entity, which I took quite literally and ended up creating a VBO per hex per frame, which got real slow. This lead me to restructure the data in a way that I pre calculate all of the VBO data for the "background" hex grid just once, and just repeatedly draw it. The problem is that now I can't simply rely on changing the model and having everything be updated, as the whole "map" is pre calculated. Following this I created a separate VBO which is filled just with "dynamic" objects that change on each frame, and first render the static background, and then the dynamic part that changes. But this leads me to a question. What if I need to change the background at runtime? For example, what if a "wall" gets torn down every once in a while, and I need to update the world data? Currently I can think of only a few options Change the VBO in place during the frame. This would only work if the change is small enough to not lag the frame. Keep a separate VBO that just has the "changes" and is drawn over the original one. I don't really like this approach, as it doesn't really feel flexible. Build a new VBO in a separate thread and atomically swap them once done. While this would allow me to do a larger update without sacrificing framerate, it could also introduce a weird kind of latency, when the user would still see the old thing for a few frames until the new VBO is calculated. Ideally I'd just change my "model" and re build the whole VBO from it, but that's about as slow as it gets, so I'm not really sure if I should even keep thinking this way? How do larger and more complicated games handle updating geometry on the fly? Is everything just pre calculated animations that simply get swapped around?


Problem using glm lookAt and glm perspective I'm trying to change the code from the 22th tutorial at http ogldev.atspace.co.uk , using the GLM library, but the result seems wrong. The problem is shown in the below picture While it should be This program displays a model onto the screen. The model is loaded using a library and I ensure that all of its vertices, normals, and texuture coordinates are loaded correctly. The problem seems to be at creating the Projection model view matrix. I searched for the use of GLM and use the below code to calcualate that matrix glm vec3 Pos(3.0f, 7.0f, 10.0f) glm vec3 Target(0.0f, 0.2f, 1.0f) glm vec3 Up(0.0, 1.0f, 0.0f) glm mat4 viewMat glm lookAt(Pos, Target, Up) glm mat4 perMat glm perspective(60.0f, (float)WINDOW WIDTH WINDOW HEIGHT, 1.0f, 100.0f) glm mat4 modelMat glm scale(glm mat4(1.0f),glm vec3(0.1f, 0.1f, 0.1f)) modelMat glm rotate(modelMat, m scale, glm vec3(0.0f, 1.0f, 0.0f)) modelMat glm translate(modelMat, glm vec3(0.0f, 0.0f, 10.0f)) FINAL MATRIX glm mat4 PVMMat perMat viewMat modelMat After that, I supplied the matrix to the shader like this glUniformMatrix4fv(m WVPLocation, 1, GL TRUE, amp PVMMat 0 0 ) Finally, in the shader, I calculate the gl Position as below vertex shader void main() gl Position gWVP vec4(Position, 1.0) TexCoord0 TexCoord Normal0 (gWorld vec4(Normal, 0.0)).xyz WorldPos0 (gWorld vec4(Position, 1.0)).xyz " Fragment shader void main() FragColor texture2D(gSampler, TexCoord0.xy) " I tried my best for a few days and I can't see any error in the way I use glm lookAt and gml perspective. This is exactly as in the manual on the GLM website. Could you suggest some reason for the problems I'm seeing, or some way for me to further investigate the error? Thanks so much. I hope to see your answer.


Having trouble running OpenGL on MSVC I'm using the OpenGL Programming Guide, 8th Edition with MSVC 2013 but I can't get the triangles.cpp file to run. These are the errors popping up http puu.sh jAokn c07420cf46.png


Displacement Mapping opengl es I need to do an application similar to this Morfo. And I posted a question here where the answer states the solution is "Displacement Mapping" . And I googled this to do it in opengles. I couldnt get how to start and implement this in opengles. Can someone give me some starter on this?


Camera Rolling when Implementing Pitch and Yaw I am implementing a camera in opengl for an android game and am having problems getting the pitch yaw roll of the camera correct. I have read many tutorials on quaternions and have implemented a basic camera based on this link. Everything works well except for when I pitch and yaw I get unwanted roll. I have read things that say I need to apply the pitch yaw rotation together to prevent this, and other things that said not to track individual changes to angles, but I'm not sure what they mean or how to extend this implementation to mine. I am new to this type of math so any help would be appreciated. My goal is to have a camera that can rotate similar to how a space ship would rotate I want the camera to be able to rotate 360 degrees in all directions and turn upside down which is why I was rotating the upVector too. Any suggestions on what I can do to not have the camera roll when rotating around the y and y axes? Thanks! Here is the code that translates user input into two angles, and rotates the lookVector, upVector, and rightVector of the camera. My problem is the camera is also rolling when I just pitch and yaw. Java Camera uses a position vector, lookAt vector, and upVector eventually calls Matrix.setLookAtM() Camera c mRenderer.theCamera PVector is a class that implements a 3 dimensional vector float thetaX getTouchChange(...) set by the user touching the screen float thetaY getTouchChange(...) set by the user touching the screen I keep 3 vectors in the camera class, one points up, one points right, and the 3rd is the point I am looking at Pitch rotate the up and look around right get up and look vectors PVector lookVector PVector.sub(c.getLookAtPoint(), c.getLocation()) PVector otherVector c.getUpDirection() get axis PVector rAxis c.getRightDirection() rAxis.normalize() rotate look PVector rotated Quaternion.rotateVector(lookVector, rAxis, thetaY) Add back camera location to convert vector to actual look points rotated.add(mRenderer.theCamera.getLocation()) c.setLookAtPoint(rotated) rotate up rotated Quaternion.rotateVector(otherVector, rAxis, thetaY) rotated.normalize() c.setUpDirection(rotated) Yaw rotate the look and right around up get up and look vectors lookVector PVector.sub(c.getLookAtPoint(), c.getLocation()) otherVector c.getRightDirection() get axis rAxis c.getUpDirection() rAxis.normalize() rotate look rotated Quaternion.rotateVector(lookVector, rAxis, thetaX) Add back camera location to convert vector to actual look points rotated.add(mRenderer.theCamera.getLocation()) c.setLookAtPoint(rotated) rotate right rotated Quaternion.rotateVector(otherVector, rAxis, thetaX) rotated.normalize() c.setRightDirection(rotated) In my rendering code I update the camera orientation by calling the following called in onSurfaceChanged Matrix.frustumM(m3DProjectionMatrix, 0, screenRatio, screenRatio, 1, 1, 1, 70) called in onDrawFrame Matrix.setLookAtM(m3DViewMatrix, 0, theCamera.getLocation().x, theCamera.getLocation().y, theCamera.getLocation().z, theCamera.getLookAtPoint().x, theCamera.getLookAtPoint().y, theCamera.getLookAtPoint().z, theCamera.getUpDirection().x, theCamera.getUpDirection().y, theCamera.getUpDirection().z) Matrix.multiplyMM(m3DMVPMatrix, 0, m3DProjectionMatrix, 0, m3DViewMatrix, 0) m3DMVPMatrix is eventually passed to the shader along with the shape data


Should all primitives be GL TRIANGLES in order to create large, unified batches? Optimizing modern OpenGL relies on aggressive batching, which is done by calls like glMultiDrawElementsIndirect. Although glMultiDrawElementsIndirect can render a large number of different meshes, it makes the assumption that all these meshes are made of the same primitives (eg. GL TRIANGLES, GL TRIANGLE STRIP, GL POINTS). In order to most efficiently batch rendering, is it wise to force everything to be GL TRIANGLES (while ignoring possible optimizations with GL TRIANGLE STRIP or GL TRIANGLE FAN) in order to make it possible to group more meshes together? This though comes from reading the Approaching Zero Driver Overhead slides, which suggests to draw everything (or, presumably, as much as possible) in a single glMultiDrawElementsIndirect call.


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


Texture coordinate discontinuity with mipmaps creates seams I just started learning openGL and I am getting this artifact when texturing a sphere with mipmaps. Basically when the fragment samples the edge of my texture, it detects the discontinuity (say from 1 to 0) and picks the smallest mipmap, which creates this ugly seam ugly seam http cdn.imghack.se images 6bbe0ad0173cac003cd5dddc94bd43c7.png So I tried to manually override the gradients using textureGrad fragVert is the original vertex from the vertex shader vec2 ll vec2((atan(fragVert.y, fragVert.x) 3.1415926 1.0) 0.5, (asin(fragVert.z) 3.1415926 0.5)) vec2 ll2 ll if (ll.x lt 0.01 ll.x gt 0.99) ll2.x .5 vec4 surfaceColor textureGrad(material.tex, ll, dFdx(ll2), dFdy(ll2)) Now I get two seams instead of one. How can I get rid of them? And why does the code above generate 2 seams? 2 eams http cdn.imghack.se images 44a38ef13cc2cdd801967c9223fdd2d3.png You can't tell from the two images but the 2 seams are on either side of the original seam.


How to clear a buffer to 1.0 instead of 0.0 in OpenGL? Using glClear() you can set the buffer specified by the parameter to 0.0. This is useful say if you want pixels not covered by models to be black. Because vec3(0.0, 0.0, 0.0) results in black. But for the depth buffer, clearing means to set it to the maximum value 1.0 since you don't want pixels not covered by models to have the depth 0.0 which is the camera's position but to have the depth 1.0 which means as far away as possible. So how can I clear the depth buffer to 1.0 or come over this issue in another way?


How to change the color of an invalid texture? In openGL, when I don't bind a texture, or I bind a texture that was loaded incorrectly, any calls to texture2D texelFetch in the shader will return vec4(0, 0, 0, 1), is there a way to change this to return vec4(1, 1, 1, 1) instead? Initially I looked for a way to test if the sampler2D was valid, and when I couldn't find that I tried using glColor4f, but that doesn't seem to work either although that could be the amdgpu driver, it seems to have some trouble with the old pipeline calls generally. Is there someway to change what this default return color is?


Coordinate transformation in voxel ray tracing? I am implementing voxelization. I can't understand the coordinate transformation through shader. I have read some papers and code, the first step in the geometry shader is project the triangle along its dominant axis. What's the difference between this method and using projection matrix? In usual ways, we transform data from local space,world space, view space, then to projection space. Does project the triangle means we transform from view space to projection space ? What should we get after these process, in the end of pixel shader?


How to use FrameBuffer objects (OpenGL) I want to draw a 2D scene and after the scene i want to draw some light effects. When i draw some light, i create a FBO, draw in it and when finished with drawing, i want to create a texture where i draw the content of the FBO. My current code Init Create Texture glActiveTexture(GL TEXTURE0) glGenTextures(1, out texfbo) glBindTexture(GL TEXTURE 2D, texfbo) glTexImage2D(GL TEXTURE 2D, 0, GL RGBA, screenWidth, screenHeight, 0, GL RGBA, GL UNSIGNED BYTE, null) glBindTexture(GL TEXTURE 2D, 0) Create Renderbuffer glGenRenderbuffers(1, out rb) glBindRenderbuffer(GL RENDERBUFFER, rb) glRenderbufferStorage(GL RENDERBUFFER, GL DEPTH COMPONENT16, screenWidth, screenHeight) glBindRenderbuffer(GL RENDERBUFFER, 0) Create Framebuffer glGenFramebuffers(1, out fbo) glBindFramebuffer(GL FRAMEBUFFER, fbo) glFramebufferTexture2D(GL FRAMEBUFFER, GL COLOR ATTACHMENT0, GL TEXTURE 2D, texfbo, 0) glFramebufferRenderbuffer(GL FRAMEBUFFER, GL DEPTH ATTACHMENT, GL RENDERBUFFER, rb) glBindFramebuffer(GL FRAMEBUFFER, 0) Loop glBindFramebuffer(GL FRAMEBUFFER, fbo) Draw Scene glBindFramebuffer(GL FRAMEBUFFER, 0) glBindTexture(GL TEXTURE 2D, texfbo) Draw Rectangle with texture from Framebuffer The Scene is not drawn on the screen, i think that means it's drawn in the right buffer. But i can't get someting on the screen. What is wrong?


OpenGL What steps to take to correctly set up an Uniform Block Array I have managed to get uniform blocks to work, but I seem to make something wrong when trying to setup an array of uniform blocks. Assume this glsl layout(std140, binding 1) uniform LightingBlock vec4 ambient vec4 diffuse vec4 specular vec3 factors float shininess lighting 3 What's the exact procedure to bind this? What I am doing (and what works for a single block, not an array) GenBuffer... BindBuffer... BindBufferRange(UNIFORM BUFFER, 1, buffer id, 0, size in bytes) index GetProgramResourceIndex(program id, UNIFORM BLOCK, "LightingBlock") UniformBlockBinding(program id, index, 1) I read that I should replace the LightningBlock with lighting 0 , 1 etc, but this only returns invalid indices. So my current attempt looks like this GenBuffer... BindBuffer... binding 1 for(int i 0 i lt 3 i) BindBufferRange(UNIFORM BUFFER, binding i, buffer id, 0, size in bytes) index GetProgramResourceIndex(program id, UNIFORM BLOCK, "lighting " str(i) " ") UniformBlockBinding(program id, index, binding i) What am I doing wrong? How to do this correctly?


How to get PS3 Xbox 360 experience without having access to Dev kits? I am a budding game programmer trying to get into the industry programming for PS3, Xbox 360. The main problem I see is the need to demonstrate my skills to a potential employer, but without access to Dev kits for the PS3 or Xbox 360, doing this directly is impossible. My question is, what is the best alternative way to show console developers my skills? C programming in DirectX for Windows seems close to showing Xbox 360 programming skills, and C programming in OpenGL seems relatively close to showing PS3 programming skills. Unfortunately, it seems from web research as if both Xbox 360 and PS3 actually have their own propietary libraries, therefore seeming to make this not a 100 fruitful endeavor. This approach seems closest, but also most time consuming. Plus you're not actually making anything run on the console. On the other hand, programming in XNA has the benefit that your games are actually on the console, though I get the impression that this is looked upon as not "the real deal" since it is just a wrapper around DirectX and uses C instead of C . Does anyone have knowledge or experience from inside the industry so as to know what kind of game demos would be most useful to show to a potential employer? C in DirectX, OpenGL, XNA, Unreal Engine, Unity3d, Flash, etc etc etc? There are only so many hours in the day, and I'd love to know how to direct my efforts. My gut feeling is that DirectX would be the best choice, as it seems closer to what is used on the Xbox 360, but if having a good demo in another language engine is just as good, it would obviously be less time consuming to go another route. Thanks in advance for your help and advice!


How do I represent blended tiles in a mesh vertex array? I recently started making a Terraria clone using the L VE library, which is based in OpenGL. In Terraria, for each tile, there is a large texture with all possible combinations for merging with neighbouring tiles. They usually only support tiles of the same type, and sometimes other materials, like dirt. As a result, they only need a single vertex array. In Starbound, it seems to be simpler. A tutorial I found notes the use of basic 8x8 blocks, with a few edges drawn if the block is next to a block of a different type. I want to implement a similar mechanic, but I encountered a serious issue. A single vertex array does not allow z ordering, which I would need. My first idea was to use one vertex array for each type of block, but that would eat a lot of memory. My second idea was to use the fact that OpenGL vertex array draws primitives in order. I could use some complicated data structure to represent tiles, so I would always know where to place their vertices in the array. However, that would either require moving lots of vertices or lots of memory. What is the best way to implement this?


Point Light shows black box rect (PointLight not working) libgdx 3D I am creating a 3d scene currently a box and rect, and trying to enable lighting. When i create a PointLight and add it to Environment everything turns to black color? all i want to do is create a 3d scene and enable point light, like a sun or rays coming from a point and shading the objects. Code environment new Environment() environment.add(new PointLight().set(1f, 1f, 1f, 0, 0, 20f, 100f)) modelBatch new ModelBatch() .. square new ModelBuilder().createBox(300,300,300,new Material(ColorAttribute.createDiffuse(Color.GREEN)), VertexAttributes.Usage.Position VertexAttributes.Usage.Normal) squareinst new ModelInstance(square) squareinst.transform.setTranslation( 500,0,0) sprites.get(0).setRotationY(sprites.get(0).getRotationY() 1f) sprites.get(1).setRotationY(sprites.get(1).getRotationY() 1f) squareinst.transform.rotate(1,0,0,1) modelBatch.begin(camera) for(Sprite3D sp sprites) has 3d rect models sp.draw(modelBatch,environment) modelBatch.render(squareinst,environment) modelBatch.end() PointLight turning everything black Without using environment or lights as per my investigation, here if pointlight is not working then everything should be black as currently, because the environment needs light, it works fine with Directional light (only the backface of rect is black even after rotations, i don't know why) libgdx version 1.6.1 android studio i checked it on both android device and desktop please i really need to get this PointLight working, i don't know if it will take a custom shader, if so please guide me to some links because i am not experienced in shaders. I also read about PointLight not working on some device or not working in opengl 2.0 enabled, but i am not sure.


How can I obtain a triangle ID during rasterization? I want to know the triangle ID of each rendered pixel is coming from. Is there a way to do this in OpenGL?


Sprite framework binding multiple textures In an attempt to batch render as many quads (sprites) as possible, I'm instance rendering a single unit sized quad and passing in a buffer of per instance data that includes width height, texture coordinates, color, texture Id, etc. Offline, I have a tool that constructs texture atlases based on any particular sprite animation, so the output is flexible in terms of texture atlas width height, which sprites reference which texture atlas, and so on. The end result is that I may have many texture atlases, and sprites which reference any one of those atlases for their current frame. I need a robust solution that'll allow me to draw these sprites in any order while reducing texture binding as much as possible. After some research there are two options combine multiple 2D textures into a 2D array texture (up to GL MAX ARRAY TEXTURE LAYERS EXT) bind multiple textures in array of samplers (up to MAX TEXTURE IMAGE UNITS) The first solution I believe requires all textures to be the same height width. The second solution seems to have a limitation that requires a constant index to access the array of samplers in the fragment shader. I think I want to go with the second solution, but I'm worried I won't be able to properly write a fragment shader if I have to use a constant index, as I'd be getting the index via per instance data input. Are my above suspicions correct? Is there a known work a round for the second solution? Or is there a better way to do this than what I presented.


How can I render a simple lattice in LibGDX? I have searched all over, but I can't find what I think will be a simple answer. I am using Opengl ES 2.0, and LibGDX. I simply want to use GL LINES primitives to create a lattice structure. I have used shapeRenderer with the following code in create() shapeRenderer new ShapeRenderer() shapeRenderer.setProjectionMatrix(cam.combined) in render() shapeRenderer.setProjectionMatrix(cam.combined) shapeRenderer.begin(ShapeType.Line) shapeRenderer.setColor(0, 1, 0, 1) for (float i 10 i lt 10 i ) for (float j 10 j lt 10 j ) shapeRenderer.line(i, j, 10, i, j, 10) shapeRenderer.line( 10, i, j, 10, i, j) shapeRenderer.line(j, 10, i, j, 10, i) shapeRenderer.end() The problem is, this is not a model instance, thus doesn't seem to use the RendererContext (GL DEPTH TEST, etc.). When I render the lattice this way, it either shows up entirely behind my models, or entirely in front of them (depending on the order I render them in the render method). Is there a way to build a model which is simply a set of lines to be rendered with Opengl primitive GL LINES? Any pointers would be greatly appreciated.


What's the difference between bloom and emission? In my engine, I've implemented bloom but I also want to implement emission because some models that I have come with an emission map. It sounded to me like something adjacent to bloom but I guess it's different since other engines differentiate the two like here Unity Emission https docs.unity3d.com Manual StandardShaderMaterialParameterEmission.html Unity Bloom https docs.unity3d.com Manual PostProcessing Bloom.html and also because it seems like it's something that is done in the material shader and not in any post processing. What is the difference (i.e not a part of post processing) and how could I go about writing emission into my standard material shader (I'm using a deferred rendering technique)? UPDATE Alright, I've seen that emission is just something that you add on top of the fragment after you've sampled the emission map. How then, would someone get that light appear to be glowing off the surface like in Unreal and Unity and also seemingly lighting other surfaces? Is that then to do with global illumination (I currently have a baked G.I solution for static scenes)?


Using GLFW and GLUT together I'm new to OpenGL Lets say I create an OpenGL window using glfw and I need the UI feature from glut (such as popup menu). Is it possible to use glfw and glut in one program? Thank you


Comparing meshes and reducing duplication of data I'm writing a class that reads an obj file, indexes each mesh and creates a VAO and GameObject of the appropriate type. I've stumbled on a design issue. Objects of the same name (Tree A001, Tree A002) are currently skipped over, and their min and max extents are used to calculate their centre, and therefore where to position the a copy of that mesh. Not only does this mean I've read in the mesh twice, just to ignore all the data as soon as I've got the min and max, but in my case I have 230 trees. It works but takes 12 15 seconds to read in the file itself, and I've not been able to gleam the rotation or scale of said object. I understand that comparing the min and max extents of the duplicate mesh to the original could let me get the scale, but as soon as the mesh is rotated in the scene file then it breaks. I'd like to do something more efficient than this however, and I'm stuck on what do to. What is the done thing in professional games, that allows multiple objects to be placed in a 3d modelling software, and their individual position rotation and scale to be kept? I've experimented with using single triangles to represent the position and scale etc but it makes designing the scene much harder as you can't see what you're placing. Thanks for any advice


OpenGL Transformations I'm not sure if I correctly understand 3D transformations in OpenGL. Let's assume I'm using the typical matrix stack. It seems like you move the world X units over, drop in a bag of verts (a mesh) and move the world back by popping the matrix off the stack, then you repeat the process to place another model? Say I wanted to place a model at (10, 0, 0) and another at (0, 10, 0). I think I would... PUSH move(10,0,0) DRAW model A POP PUSH move(0,10,0) DRAW model B POP Some questions come to mind, like for example what does loading an identity matrix do in the stack? Am I right to assume that these operations in effect move the world around, then you draw the mesh at 0,0,0 in world space when you've moved the world to your liking? Or is it the other way around, does GL "apply" the matrix stack to your mesh as you draw it? Thanks, Cody


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


Irrlicht engine game wont compile on linux. Undefined refrences(opengl and xfree) I'm trying to port over my game I'm developing to Linux. But when i compile i get a lot of undefined references to mostly functions that look like they belong to OpenGL. Most are titled gl... But one of them is called XFree. I compiled it with this command g main.cpp L.. .. .. LIB irrlicht 1.8.3 lib Linux lIrrlicht I.. .. .. LIB irrlicht 1.8.3 include one of the errors home owner LIB irrlicht 1.8.3 source Irrlicht COpenGLDriver.cpp 3746 undefined reference to glVertex3f


How to only render fragments with Z from 0 to 1 in OpenGL? I have been using OpenGL for a year now, but I just recently found out that OpenGL only clips vertices when the absolute value of the x,y or z coordinate is less than the absolute value of w coordinate. Previously I had assumed that the z coordinate would have to be 0 lt z lt w to be rendered. Is there any way to clip vertices with z less than 0, without a performance hit? I am using OpenGL 4.4


Bullet Physics implementing custom MotionState class I'm trying to make my engine's camera a kinematic rigid body that can collide into other rigid bodies. I've overridden the btMotionState class and implemented setKinematicPos which updates the motion state's tranform. I use the overridden class when creating my kinematic body, but the collision detection fails. I'm doing this for fun trying to add collision detection and physics to Sean O' Neil's Procedural Universe I referred to the bullet wiki on MotionStates for my CPhysicsMotionState class. If it helps I can add the code for the Planetary rigid bodies, but I didn't want to clutter the post. Here is my motion state class class CPhysicsMotionState public btMotionState protected This is the transform with position and rotation of the camera CSRTTransform m srtTransform btTransform m btPos1 public CPhysicsMotionState(const btTransform amp initialpos, CSRTTransform srtTransform) m srtTransform srtTransform m btPos1 initialpos virtual CPhysicsMotionState() TODO Auto generated destructor stub virtual void getWorldTransform(btTransform amp worldTrans) const worldTrans m btPos1 void setKinematicPos(btQuaternion amp rot, btVector3 amp pos) m btPos1.setRotation(rot) m btPos1.setOrigin(pos) virtual void setWorldTransform(const btTransform amp worldTrans) btQuaternion rot worldTrans.getRotation() btVector3 pos worldTrans.getOrigin() m srtTransform gt m qRotate CQuaternion(rot.x(), rot.y(), rot.z(), rot.w()) m srtTransform gt SetPosition(CVector(pos.x(), pos.y(), pos.z())) m btPos1 worldTrans I add a rigid body for the camera Create rigid body for camera btCollisionShape cameraShape new btSphereShape(btScalar(5.0f)) btTransform startTransform startTransform.setIdentity() forgot to add this line CVector vCamera m srtCamera.GetPosition() startTransform.setOrigin(btVector3(vCamera.x, vCamera.y, vCamera.z)) m msCamera new CPhysicsMotionState(startTransform, amp m srtCamera) btScalar tMass(80.7f) bool isDynamic (tMass ! 0.f) btVector3 localInertia(0,0,0) if (isDynamic) cameraShape gt calculateLocalInertia(tMass,localInertia) btRigidBody btRigidBodyConstructionInfo rbInfo(tMass, m msCamera, cameraShape, localInertia) m rigidBody new btRigidBody(rbInfo) m rigidBody gt setCollisionFlags(m rigidBody gt getCollisionFlags() btCollisionObject CF KINEMATIC OBJECT) m rigidBody gt setActivationState(DISABLE DEACTIVATION) This is the code in Update() that runs each frame CSRTTransform srtCamera CCameraTask GetPtr() gt GetCamera() Quaternion qRotate srtCamera.m qRotate btQuaternion rot btQuaternion(qRotate.x, qRotate.y, qRotate.z, qRotate.w) CVector vCamera CCameraTask GetPtr() gt GetPosition() btVector3 pos btVector3(vCamera.x, vCamera.y, vCamera.z) CPhysicsMotionState cameraMotionState CCameraTask GetPtr() gt GetMotionState() cameraMotionState gt setKinematicPos(rot, pos)


How to create more vertexes from within a shader in OpenGL? when rendering voxels in octrees, the only information necessary is the current octree level, position and colour texture. But one has to send eight vertices to the rendering pipeline in order to render a complete cube and still needs colour texture. Is there a better way? Since geometry shaders wont be wide spread for quite some time the "emit vertex" method in the geometry pass wont suffice (or am i wrong? i don't think mesa currently supports geometry shaders). Also, afaik, backface culling is done before the geometry pass, so that would lead to additional overhead. My current idea is to send 'dummy vertices' and have the actual drawing data in between but that really shouldn't be the solution. kind regards


When would you use an octree in a voxel Engine? I've been reading about Octrees, and I understand how they work (or at least I think I do). However, I can't figure out why you would use octrees instead of a simple multidimensional array. In my project, I use chunks in my world. Every chunk is made up of 16x16x16 voxels. If I need to access a voxel, I just use the notation myChunk x y z . If I need to check neighboring voxels, I can use the same notation. I've already implemented frustum culling, face merging, and hidden surface determination. With these optimizations and this simple multidimensional array, I can render about 500 chunks at 80 fps. So, in which situation would I use octrees in this kind of Voxel Engine? Or is it useless? I can see the purpose of octrees if I would implement LOD into my voxel engine (which I'm not planning to do). Is my lack of experience in Game Development blinding me on something?


"Highlighting" Faces Edges Corners How would I "highlight" faces edges corners? I would prefer an explanation OpenGL if possible. Here's an example


My model is drawn wrong in 3d I'm learning OpenGL and now after I made everything I needed, I started with 3D, my first problem is that my mesh doesn't draw like I intended... Here's my rectangle (uses GL TRIANGLES) std vector lt GLfloat gt Vpos 0.5, 0.5, 0.0, 0.5, 0.5, 0.0, 0.5, 0.5, 0.0 0.5, 0.5, 0.0 0.5, 0.5, 0.0, 0.5, 0.5, 0.0 comms are the 3d version And here I draw my array glDrawArrays(GL TRIANGLES, 0, verNum 2) it is binded with vertex array, I use shaders And my fragment shader is version 330 in vec2 passTextureCoords out vec4 outColor uniform sampler2D ourTexture void main() outColor vec4(0.0, 1.0, 0.5, 1.0) texture(ourTexture, passTextureCoords) I don't have a texture so I use a lightgreen for debug proposes Also my vertex shader version 330 layout (location 0) in vec3 inVertPos layout (location 1) in vec2 inTexCoords out vec2 passTextureCoords void main() gl Position vec4(inVertPos.x, inVertPos.y, inVertPos.z, 1.0) passTextureCoords inTexCoords Thanks for help by now, I pretty sure that I missed something small but important.


Everything turning black when pitching down Just a quick questions about something that's occurring in my world. Every time I pitch my camera downward, everything starts turning black, and if I pitch upward, everything sort of intensifies. I'm multiplying my normals by the normal matrix in the shader, and I'm multiplying my lights direction by the model view matrix. If I leave the normal and light dir in world space everything ends up fine. I thought putting them both in view space would not cause those weird things to happen?


LWJGL loading textures of various types I googled around a bit and nobody seems to have asked this question. I have images in multiple color formats (all of them are PNGs). Most of them are ARGB but my bitmap fonts are gray scale, and I would like them to stay that way. All I want to do is find out what format BufferedImage uses to store my pixel data and then use that information with glTexImage2D. Java, in all its wisdom, seems to be determined to hide that information from me at all costs... I also need to know how BufferedImage aligns its pixel data in both of these formats (glTexImage2D cares). Could someone please tell me how to Determine the pixel format of my BufferedImage. If it is ARGB32, I'm going to have to reorder the bytes and use GL RGBA. If it's grayscale, I will be using GL INTENSITY. Extract the actual bytes from the image. I have seen a few examples on the web that use BufferedImage.getRaster().getDataBuffer(). This is nonsensical. Why are there different types of buffers like DataBufferInt? Because of Java's strong typing, I need DataBufferByte. If this is the only way, could somebody give me specific directions to use the different type of buffers with glTexImage2D? Figure out how the aforementioned image data is aligned. I will use this information with glPixelStorei. In addition, I come from C and C programming. In C this was 100 lines of simple libPNG and GL calls. Should I expect more trouble like this in the future?


Custom Model Format Loading I've been working on a small engine for educational purposes. I understand that going production with "raw" model files like .obj is wrong mostly because of parsing and loading time. Thus, I want to create a program which parses these raw files and formats it in a new way, let's say using protobuf. My questions Are there any best practices, or any example lib I can take a look at? What should I do with attached texture files? Seperate files? How can I support multiple types of models and or attributes in the models like materials, uv mapping, etc...


How to remove seams from a tile map in 3D? I am using my OpenGL custom engine to render a tilemap made with Tiled, using a well spread tileset from the web. There is nothing fancy going on. I load the TMX file from Tiled and generate vertex arrays and index arrays to render the tilemap. I am rendering this tilemap as a wall in my 3D world, meaning that I move around with a fly camera in my 3D world and at Z 0 there is a plane showing me my tiles. Everything is working correctly but I get ugly seems between the tiles. I've tried orthographic and perspective cameras and with either I found particular sets of parameters for the projection and view matrices where the artifacts did not show, but otherwise they are there 99 of the time in multiple patterns, depending on the zoom and camera parameters like field of view. Here's a screenshot of the artifact being shown http i.imgur.com HNV1g4M.png Here's the tileset I am using (which Tiled also uses and renders correctly) http i.imgur.com SjjHK4q.png My tileset has no mipmaps and is set to GL NEAREST and GL CLAMP TO EDGE values. I've looked around many articles in the internet and nothing helped. I tried uv correction so the uv fall at half of the texel, rather than the end of the texel to prevent interpolating with the neighbour value(which is transparency). I tried debugging with my geometry and I verified that with no texture and a random color in each tile, I don't seem to see any seams. All vertices have integer coordinates, i.e, the first tile is a quad from (0,0) to (1,1) and so on. Tried adding a little offset both to the UV and to the vertices to see if the gaps cease to exist. Disabled multisampling too. Nothing fixed it so far. Thanks.


Migrating from OpenGL to XNA (MonoGame)? I just started working in MonoGame with 3D code. I've used OpenGL before in the past, and I've also built engines with 2D Sprites SpriteBatch's in MonoGame. However, I'm getting extremely stumped with going from GL to XNA, likely due to the fact that I believe XNA is no longer a "state" machine like GL is. I've looked thru the tutorials by RB Whitaker and Riemers but most of the stuff they have written covers models, etc. I've already migrated some of my code to build procedural meshes into a VertexBuffer. I'd like to test it now, but I'm getting very confused as to how to setup the World, View, Projection matrices, etc. Are there any good tutorials that either show how to move from GL to XNA or optionally any good tutorials that assume you're not using Models, etc? I'm looking to write something fairly low level when it comes to primitives.


2D Sprite batching in OpenGL How to send transformation data to GPU OpenGL newbie here. So I'm trying to implement sprite batching to draw 100 sprites per draw call. I've created a VBO that contains texture coordinates, vertex coordinates, color data (for tinting), and a mat4 matrix for transforms. So far, so good, right? Well, everything is working but the transform portion of my VBO. My theory is that I could push a mat4 with all of the rotation, scaling, flipping, and world location data applied to it, so that it gets multiplied in with viewports (see glsl code below). version 130 Vertex position attribute in vec2 vertexPos Texture coordinate attribute in vec2 texCoordIn out vec2 texCoord Vertex color in vec4 textureColorIn out vec4 textureColor Matrix transformations for the sprite in mat4 transformation void main() Process texCoord texCoord texCoordIn Process texture color textureColor textureColorIn Process vertex gl Position gl ProjectionMatrix gl ModelViewMatrix vec4( vertexPos.x, vertexPos.y, 0.0, 1.0 ) transformation So here's my question, if you were to send transform data to the GPU, how would you do it? Sending a mat4 over the wire per vertex seems like overkill.


rotating 3D object around the center I have object moving from A to B on x axis and there is no translation of object apart from it. Now, while moving, i want to rotate it around y axis and the motion should change accordingly, i mean if i rotate it right when moving from x to x axis, it should move towards near plane. I have variable in gltranslatef which is modified in the loop after that i have glscalef to scale whole object which is made of hierarchical structure. Now i tried following code to achieve the expected result but its not working properly glTranslatef(move, 0, 0) If I comment these 3 lines, it does not affect the output glTranslatef( move, 0, 0) glRotatef(rotate,0,1,0) glTranslatef(move, 0, 0) glScalef(0.2, 0.2, 1.0)


Qt 5 QOpenGLWidget not updating the screen I'm creating a level editor for my game using Qt for gui and i'm in really early stages. Right now i'm trying to dynamically add objects ( entities ) on screen when i click a button. So far the objects are pushed into a stack but i can't see them on screen. When my widget inherits QGLWidget the screen is updated immediately and i can see the objects being drawn but since QGLWidget is deprecated i use QOpenGLWidget. Strangely this class does not auto update the screen. I have also connected update() to a timer and set the interval to 0 to update the screen in real time. connect( amp timer, SIGNAL(timeout()), this, SLOT(update())) timer.setInterval(0) timer.start() Am i missing something ?


Is glEnable obsolete unneeded in OpenGL ES 2? In an iOS app I am writing I am now culling all the GL 1 crap from my GL 2 code. Can I safely remove glEnable?


3D collision detection on non flat surface I am developing a game which needs an accurate collision detection algorithm, when an object travels down a slope which isn't flat. To be more precise I need to simulate a skier who travels down a ramp. My first idea was to create simple bounding box around the skies and the ramp. Then place the skier in mid air and start calculating gravity. When the two bounding boxes intersect collision detected (this is how I did it in 2D). But the problem is that the skies are flat and the slope isn't. So there is a chance that the ski will stick into the jump (due to curved surface of the jump) or even worse the skier will go under the jump (I don't want the skies to "sink" into the jump as well) . What would be the best way of solving this? What I could think of is when collision is detected, rotate the skies until the front and the back end of the skies are colliding with the surface. Is this idea any good? Did any face this kind of problem? Would be better to morph the skies according to the slope (but this would probably be an overhead I can't afford)? P.S. if I didn't explain enough, write a comment and make a sketch.


What is GL MAX COMBINED TEXTURE IMAGE UNITS? I am a beginner in OpenGL. I am learning about textures in OpenGL. What I don't understand is how to determine how many texture units are in the GPU. I heard someone said that you can see how many texture units by writing the following code. int total units glGetIntegerv(GL MAX COMBINED TEXTURE IMAGE UNITS, amp total units) std cout lt lt total units lt lt ' n' the result is 192 Is there 192 texture units in my GPU? In documentation, it says GL MAX COMBINED TEXTURE IMAGE UNITS params returns one value, the maximum supported texture image units that can be used to access texture maps from the vertex shader and the fragment processor combined. If both the vertex shader and the fragment processing stage access the same texture image unit, then that counts as using two texture image units against this limit. The value must be at least 48. See glActiveTexture. So I wanted to know how many texture units can be used to access texture maps from the vertex and fragment shaders. So I wrote and run the following code. int vertex units, fragment units glGetIntegerv(GL MAX VERTEX TEXTURE IMAGE UNITS, amp vertex units) std cout lt lt vertex units lt lt quot n quot the result is 32 glGetInteferv(GL MAX TEXTURE IMAGE UNITS, amp fragment units) std cout lt lt fragment units lt lt quot n quot the result is also 32 So 32 32 64. But why does GL MAX COMBINED TEXTURE IMAGE UNITS shows me the result of 192? I think I am missing something. What do I need to calculate to get 192? And also, in OpenGL, why are there only GL TEXTURE0 to GL TEXTURE31 macros? I think these macros are for each shaders. Am I right?


GLSL shader compilation When i'm compiling a shader does it have to be complete? Can i use glCompileShader on a shader without a main() function? The OpenGL reference documentation has a nice writeup on program linking errors, but i can't find one for shader linking, so i have to ask here. I want to have the ability to have each part of a shader in a different file. So f.e. i'll have a material calculating function and i'll have a "main" shader with the main function that'll only reference the material calculating function. Right now i have my shaderes as arrays of strings that they can read from a file, then i put together an array of string pointeres and compile that into a single shader (vertex, fragment, geometry). But if i could compile each invidividual shaders (parts of vertex shaders, instead of the whole vertex shader put together in an array of strings) and put them together when i'm linking the program, that would make the code much clearer and i could move the shader compilation code from the program managing code to the shader object itself (the one that load the string from file and exposes it).


Testing spheres without extracting planes I am currently a bit stuck. On OpenGL I am attempting to do view frustum culling, so far I managed to do it by using a PCM. Where center is the world position of the mesh. bool shouldRenderMesh(mat4 VP, vec3 center, float radius) vec4 transformedCentre VP vec4(center, 1) vec3 PCN vec3( transformedCentre.x transformedCentre.z, transformedCentre.y transformedCentre.z, transformedCentre.z transformedCentre.z ) if( abs(PCN.x) gt 1 abs(PCN.y) gt 1 abs(PCN.y) gt 1 ) return false return true The problem is, while the approach works, items will disappear too soon, as the testing is based on the centre point of the mesh, rather than the bounding box. Is it possible to test a sphere or box without extracting planes? Thanks


Is OpenGL appropriate for 2D games? I have been teaching myself the OpenGL library for a while now, and want to start making a game. However, for an easier introduction, I want to start with something 2D, such as a top down Pokemon style game. Is this a good plan, or is OpenGL made specifically for 3D?


transformation before the perspective divide but after projecting perspectively My problem is that I would like to confine a scene render to a (possibly rotated) rectangle without using glViewport(). I don't want to use it to save, if possible, some cycles that would otherwise be spent on state switching. Also, there is the tantalizing possibility of rotating the scene render, which is not possible with glViewport... Is it possible to confine a scene render to this (possible rotated) rectangle in this way?


How to not render what is behind object? I am working on a 3d project using openGL. I am looking for a way to optimize my renderings. Is there a way to tell if an object is behind another object and thus not visible to not waste time rendering it ? I am already working on a frustrum culling implementation to not display what is not visible because out of the viewing frustrum, but I didn't find a way to know if an object in located behind another object. Can any of you help me about this, please ?


GLSL shader time uniform freezed? I have a simple fragment shader to simulate "falling water". I'm using Ogre3D and opengles2, this is my code version 130 uniform sampler2D valveTex uniform sampler2D noiseTex uniform float time uniform vec3 sprayColor varying vec2 uv varying float rand void main() gl FragColor.w texture2D(valveTex, uv).w float noiseW texture2D(noiseTex, uv vec2(rand, time)).x gl FragColor.w noiseW noiseW gl FragColor.xyz sprayColor The shader works well and I see the animation happening, but after some time running the animation stops like if the variable time stopped updating, and the water stream looks still. What can be causing this? Edit1 variable time is derived from Ogre's time 0 1.


Texture object and texture unit in GL As I understand texture usage consist of two parts How to store this discrete data about texture internally. How much dimensions, channels, etc. How to fetch sample filter The question relative to OpenGL are q1 What parameters are stored in texture object (glGenTexture) and what parameters are store in texture unit (glActiveTexture) ? q2 Does glTexParameter perform setup per texture object or per texture unit?


How do I render a PNG image with OpenGL? I have an image (100 200 px) painted with Paint.NET and saved as a .png with 32 bit color depth. How can I render it using OpenGL 1.1 (with the LWJGL binding) or higher inside the display? I tried creating a ByteBuffer, then loading the pixel color values inside that buffer, but I'm missing the OpenGL settings that need to be enabled. Some help?


OpenGL ES 2.0 Moving Camera in Orthogonal (2D) Projection I have quite large 2D game scene. The scene is much larger than the screen of the LCD. Therefore, I have to move the camera (view) in desired directions, to display particular parts of the scene. What is the correct way of moving viewport over the scene, in Orthogonal (2D) projection, please? There are two solutions coming to my mind Using GluLookAt(), which is designed to move camera moslty in Perspective Projection, but it could work well for 2D as well. However, not all of the GluLookAt() parameters would be utilized in Ortho configuration. Using opposite View Translate transformation. This would mean, if I need to move my 2D camera 10 units to the right(positive x axis), I would apply opposite Translate transformation to every scene vertex (negative x axis). This way, I would create illusion, the camera moves to the right. These are the solutions coming from my mind. However, because, i am self taught, is there any correct and recommended way of moving camera over the 2D scene, please?


OpenGL Understanding the relationship between Model, View and World Matrix I am having a bit of trouble understanding how these matrixes work and how to set them up in relation to one another to get a proper system running. In my understanding the Model Matrix is the matrix of a object, for example a cube or a sphere, there will be many of these in the application game. The World Matrix is the matrix which defines the origin of the 3D world. the starting point. And the View Matrix is the "camera" everything gets translated with this to make sure you have the illusion of an actual camera when in fact everything is moving instead of this matrix? I am a bit lost here. So I was hoping someone here could help me understand this properly. Does every modelMatrix get translated multiplied with the world matrix and the worldMatrix then with the viewMatrix? Or does every modelMatrix get translated multiplied with the viewMatrix and then that with the worldMatrix? How do all these matrixes relate and how do you set up a world with multiple objects and a "camera"? EDIT Thanks a lot for the feedback already. I did some googling aswel and I think I do understand it a bit better now, however would it be possible to get some pseudo code advice? projectionMatrix Matrix makePerspective(45, width, height, 0.1, 1000.0, projectionMatrix) modelMatrix Matrix identity(modelMatrix) translate(modelMatrix, 0.0, 0.0, 10.0 ) move back 10 on z axis viewMatrix Matrix identity(viewMatrix) do some translation based on input with viewMatrix Do I multiply or translate the viewMatrix with the modelMatrix or the other way around? and what then? I currently have a draw method up in such a way that it only needs 2 matrixes for arguments to draw. Here is my draw method draw(matrix1 matrix2) bindBuffer(ARRAY BUFFER, cubeVertexPositionBuffer) vertexAttribPointer(shaderProgram.getShaderProgram().vertexPositionAttribute, cubeVertexPositionBuffer.itemSize, FLOAT, false, 0, 0) bindBuffer(ARRAY BUFFER, cubeVertexColorBuffer) vertexAttribPointer(shaderProgram.getShaderProgram().vertexColorAttribute, cubeVertexColorBuffer.itemSize, FLOAT, false, 0, 0) bindBuffer(ELEMENT ARRAY BUFFER, cubeVertexIndexBuffer) setMatrixUniforms(shaderProgram, matrix1, matrix2) drawElements(TRIANGLES, cubeVertexIndexBuffer.numItems, UNSIGNED SHORT, 0) What are those matrixes suppose to be? Thanks a lot in advance again guys.


Libgdx Transparent color over texture I am attempting to tint a texture a color but I want the texture to show under the tint. For example, I have a picture of a person but I want to tint them a light green and not change the transparency of the actual person itself. So far I have attempted to use the SpriteBatch method setColor which takes rgba values. When I set the alpha value to .5 it will render the tinting and the texture with that alpha value. Is there any way to separate the alpha values of the tint and the texture? I know I could draw another texture on top of it but I don't want to have two draw passes for the one texture because it will be inefficient. If there's anyway to do it in raw OpenGL that'd be great too.


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


How do I change a sprite's color? In my rhythm game, I have a note object which can be of a different color depending on the note chart. I could use a sprite sheet with all the different color variations I use, but I would prefer to parametrize this. (Each note sprite is made of different shades of a hue. For example a red note has only red, light red and dark red.) How can I colourise a sprite anew? I'm working with OpenGL, but any algorithm or math explanation will do. )


How forward rendering done using OpenGL? Recently I come across the term forward rendering. I'm kind of curious how this could be done in OpenGL. I have done a lot of search on this, majority of the result I get are on theory but not code implementation. May I know is there any code implementation on OpenGL for this rendering technique?


Aggregation of value in GLSL loop results in 0 I'm banging my head against a wall trying to understand why this code is giving me some reasonable results with some visible colors on parts of the screen... version 130 in vec2 vTex must match name in vertex shader flat in int iLayer must match name in fragment shader out vec4 fragColor first out variable is automatically written to the screen uniform sampler2DArray tex uniform sampler2DArray norm define MAX LIGHTS 4 struct Light vec3 position vec4 color vec3 falloff vec3 aim float aperture float aperturehardness uniform Light lights MAX LIGHTS void main() vec4 DiffuseColor texture(tex, vec3(vTex.x, vTex.y, iLayer)) if (DiffuseColor.a 0) discard vec3 NormalMap texture(norm, vec3(vTex.x, vTex.y, iLayer)).rgb NormalMap.g 1.0 NormalMap.g vec3 FinalColor vec3(0,0,0) for (int i 0 i lt MAX LIGHTS i ) vec3 LightDir vec3((lights i .position.xy gl FragCoord.xy) vec2(320.0, 200.0).xy, lights i .position.z) float D length(LightDir) vec3 N normalize(NormalMap 2.0 1.0) vec3 L normalize(LightDir) vec3 Diffuse (lights i .color.rgb lights i .color.a) max(dot(N, L), 0.0) vec3 sd normalize(vec3(gl FragCoord.xy, 1.0) lights i .position) float Attenuation smoothstep(lights i .aperture lights i .aperturehardness, lights i .aperture, dot(sd,lights i .aim)) (lights i .falloff.x (lights i .falloff.y D) (lights i .falloff.z D D) ) vec3 Intensity Diffuse Attenuation FinalColor max(FinalColor, DiffuseColor.rgb Intensity) fragColor vec4(FinalColor, DiffuseColor.a) ... but when I change FinalColor max(FinalColor, DiffuseColor.rgb Intensity) to FinalColor clamp(FinalColor DiffuseColor.rgb Intensity, vec3(0,0,0), vec3(1,1,1)) everything goes black. Is there something I don't understand about aggregation of variables in loops in GLSL, or about the operator operating on vectors? By my logic, the changed code should return more brightness than the original code because the changed code would be adding all the values whereas the old code would just be taking the highest one.


OpenGL texture releasing If I call glDeleteTextures, will it release memory immediately? And what is the performance? I know that glGenTexture is quite cheap, because it only alocated id, but I have nor found anything about deleting.


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.


What does the keyword "interface" mean in GLSL? interface vs out vec3 get color() struct vs out impl vs out vec3 get color() return vec3(1,0,0) Where is this behavior defined? None of the specifications uses the keyword interface. It is generally reserved in version 460. I myself accidentally, at Visual Studio, discovered that this keyword is recognized, thought about it and remembered the Nvidia language C for graphics. It has the ability to create interfaces. I tried it and it worked! This code does not crash with compilation errors. It compiles fine. To check, instead of the diffuse color, I used the method vs out impl get color(), and the objects were painted red. Where to see the specification of this functionality? On the Internet, a bunch of words interface and GLSL leads to articles on interface blocks, which is not the same.


Why, after calling SetVideoMode as in the following, does nothing appear on my screen? I am trying to create an application that will need to use double buffering (for purpose of vsync). I am using SDL.NET. From what I understood, in order to have double buffering, I have to SetVideoMode with the opengl paremeter set to true. Here's the code I'm using Video.Initialize() Video.GLSetAttribute(OpenGLAttr.DoubleBuffer, 1) Video.GLSetAttribute(OpenGLAttr.SwapControl, 1) Video.GLSetAttribute(OpenGLAttr.RedSize, 8) Video.GLSetAttribute(OpenGLAttr.GreenSize, 8) Video.GLSetAttribute(OpenGLAttr.BlueSize, 8) Video.GLSetAttribute(OpenGLAttr.DepthSize, 16) Video.SetVideoMode(VideoInfo.ScreenWidth, VideoInfo.ScreenHeight, false, true, true, true) If 4th parameter (bool opengl) is false, it works a new fullscreen window is created and displayed (but I assume the OpenGLAttr's set above are meaningless in this case). If 4th parameter is true, nothing happens. A new window gets created (at least, it appears in the list of open windows) but I cannot alt tab into it and nothing appears on the screen. What am I doing wrong?


Best strategy to track object hierarchy using groups and obj files I am making a 3D game in OpenGL from scratch. In this game I have a ship with stuff inside it. How can I attach the stuff to the ship in the CAD program and maintain that hierarchy in my own game? For example say I have a fire extinguisher in my ship that mounts on the wall. There are two approaches both with problems. Solution 1 Save fire extinguisher and ship as separate obj files. Problem How can I place the fire extinguisher in the proper place inside my ship in my game? With hundreds of objects manually placing them is completely infeasible. I want to arrange stuff in my CAD and load it into the game and be done. Solution 2 Save fire extinguisher as its own group inside the ship obj file. Problem Now I can't reuse the fire extinguisher in other ships. The obj files for game assets will balloon out of control in size with new instances of reused sub objects. Is there some way I can specify the position of an external object? A 3d point in my ship obj file representing the origin of another obj model?


Rendering perspective independent polygons in perspective view I am creating an editor where I have "grabhandles" that can be dragged to transform a primitive object. My problem is that I can't find the correct solution to show these grabhandles in a perspective view. They need to have the correct position AND same size independent of where they are,how far away they are on the perspective viewport and independent of what the viewport dimensions are. In orthographic mode I do not have this problem as I create the handle polygons by multiplying it with a zoom factor.


How to create a MessageBox in OpenGL using C I have a game that needs results displayed upon exit with a messagebox. I have the following code that works but I need to add an integer variable to the text. This works MessageBox(NULL, L"Description nline2", L"Info", MB OK MB ICONEXCLAMATION) But I need to say "Description " num I tried to pass a string but it won't compile MessageBox(NULL, L(string), L"Info", MB OK MB ICONEXCLAMATION)


Why does scissor test happen after fragment shading? In OpenGL why is scissor test performed after shading. Wouldn't be more efficient to do the discarding before shading? Reference pipeline overview, the scissor test is inside the Fragment Processing stage.


Why does my depth test fail on Nvidia cards? I sent a test version of my in development game to some friends, and they found out that the Depth Test in OpenGL does not work on Nvidia cards. I'm using LWJGL. I use my own matrices and send them to the shader, and at the start of evey game loop I use glClear(GL COLOR BUFFER BIT GL DEPTH BUFFER BIT ) clear the display On an Nvidia card, you can see mountains through other mountains and stuff. On my Radeon HD 6650M it works perfectly fine. Any ideas? I don't have anything special in the shaders just some basic lighting calculations. I dont touch the gl FragDepth. Here's a screenshot (with placeholder textures) I use these calculations for the Projection Matrix public Matrix4f getProjectionMatrix() Setup projection matrix Matrix4f projectionMatrix new Matrix4f() float fieldOfView 40.0f float aspectRatio (float)Display.getWidth() (float)Display.getHeight() float near plane 0.1f float far plane 1000f float y scale coTangent((float) Math.toRadians(fieldOfView 2f)) float x scale y scale aspectRatio float frustum length far plane near plane projectionMatrix.m00 x scale projectionMatrix.m11 y scale projectionMatrix.m22 ((far plane near plane) frustum length) projectionMatrix.m23 1 projectionMatrix.m32 ((2 near plane far plane) frustum length) projectionMatrix.m33 0 return projectionMatrix


Are there any good techniques for reducing or smoothing stutter after a longer frame? I've been using SDL2 with OpenGL to play around with some very basic game engine development. I'm running everything on a newer laptop with Linux and Intel integrated graphics. Regardless of whether I have VSync on or off, occasionally a call to SDL GL SwapWindow (glxSwapBuffers under the hood) will take 22 33ms which causes a noticeable stutter in any moving sprites. These long frames happen even if the game loop contains nothing but a call to glClear followed by SDL GL SwapWindow, so I'm assuming this is just due to everything running on a relatively underpowered system (and I don't see the long frames or stutter on my desktop with dedicated graphics). I would have given up here and left it at the laptop not being cut out for OpenGL, but when I look at some indie games running on the same laptop, I'm unable to notice any of these stutter effects leading me to believe there may be a way to eliminate them (or that I'm doing something wrong). A few of the indie games were built with Monogame and at least one is also using SDL2 and OpenGL. I used apitrace to look at the OpenGL calls being made by these games and nothing looks very different from what I'm doing. I then spun up a very basic Monogame project on my own machine, but still experienced the long frames and sprite stutter. I've tried different variations of fixed and variable game loops timesteps as well as deltatime averaging to try to smooth over longer frames, but I still have a noticeable stutter. Is there anything else I can do to eliminate the stutter or the long frames?


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.


Texture Mapping to procedurally generated geometry How can I calculate texture coordinates of such geometry? The angle shown in the image (89.90 degree) may vary, therefore the geometry figure is changing and is not always such uniform.(maybe like geometry in the bottom of image) and red dots are generated procedurally depends on degree of smoothness given.


SFML Segmentation Fault when using VBOs? I'm trying to follow along with the gltut tutorials and for some reason when I call GLDrawArrays my program segmentation faults. I've been looking at the state of my application with the Mac OpenGL Profiler and Googling and I can't seem to figure out why it isn't working. I may have missed setting some OpenGL state somewhere. My code is here, it segfaults on line 32. If I don't call glEnableClientState(GL VERTEX ARRAY) and the respective glDisableClientState(GL VERTEX ARRAY) it compiles and runs, but I get no rendering, which is what I would expect given my limited OpenGL knowledge.


Per fragment lighting with OpenGL 4.x tessellated model I'm experienced with OpenGL 3 . I'm dabbling with tessellation shaders and have now got to a point where I have a nicely tessellated teapot plane demo (quick look here) As can be seen from the screenshots, the lighting is broken (though admittedly doesn't look too bad in the image) I've tried to add a normal map to the equation but it still doesn't come out right, I can calculate the normals, tangents and binormals per triangle in the geometry shader but still looks wrong. I think the question would be How do I add per fragment lighting to a tessellated model? The teapot is 32 16 point patches, the plane is one single 16 point patch. The shaders are here, but they are a complete mess, so I don't blame anyone who cant make sense of them. But peruse at your leisure if you like. Also, if this question is more suited to be somewhere else i.e. Stack Overflow or the Programming stack please let me know.


How to convert screen to world coordinates while using gluLookAt gluPerspective or similar matrix transforms? I am just starting an adventure in looking under the hood of graphics for a game project I've been working on for a while, and I could use some guidance. I am using Python Kivy (though that is not part of the concern), and am trying to use projection and modelview matrices to perform screen to world coordinate conversion. I am using something similar to gluLookAt and gluPerspective matrix transforms for those. The issue I'm running into, is that the coordinates I get out of multiplying the mv and p matrices together and inverting them, then multiplying by NDC screen coords, the resulting coordinates are only either a fraction of a pixel away from the world position look at is currently centered on, or a max of a few pixels that point. I know I'm missing something, and I would love if someone could help me understand. I wrote a standalone example gist, and made a short youtube video showing what problem I'm having. https youtu.be UxbWQO9e0NE https gist.github.com spinningD20 951e49cb836f08c434a0e9ab0e90c766 The code in question, is the screen to world method in the gist, when using the camera look at perspective method to create the MVP, which I will list here p Matrix() p.perspective(90., 16 9, 1, 1000) self.canvas 'projection mat' p self.canvas 'modelview mat' Matrix().look at(w x, w y 30, self.camera scale 350, w x, w y, 0, 0, 1, 0) That is for creating the matrices, and... def screen to world(self, x, y) proj self.canvas 'projection mat' model self.canvas 'modelview mat' get the inverse of the current matrices, MVP m Matrix().multiply(proj).multiply(model) inverse m.inverse() w, h self.size normalize pos in window norm x x w 2.0 1.0 norm y y h 2.0 1.0 p inverse.transform point(norm x, norm y, 0) print('convert from screen to world', x, y, p) return p 2 Was originally written to convert coordinates when using the previous projection matrix built using translate and creating a clip space (also included in the example). While the implementation appears to be specific to Kivy, it is just a modelview matrix and projection matrix being used, and their Matrix.transform point method used above is the same as multiplying a vec against the matrix in question. It can also include what appears to be the W part of a vec4, which I have also experimented with, with no apparent change. Here is a screenshot of the standalone example, painting where I have moved the mouse on the screen (red) and where the resulting world coordinate ends up being (green). The goal is for the converted coordinates in the world to fall directly under the red.


How to render models using a personalized projection matrix? I'm creating a game with a great sprite demand. Out team is considering automatizing the sprite generation using 3D models. The problem is we have a very particular ortographic projection We have already set up a good projection matrix. The problem is none of the 3D renderer of nowadays have an option for using custom matrixes. How is this kind of problem dealt with?


GLSL Fragment Shader compiles fine on certain computers I got this piece of code in a fragment shader if (color.a lt 0.01f) discard It runs fine on an older graphic card but can't even compile on my newer (maybe not new, but..) GTX 770. I got the most recent drivers and everything. The versions is correct. OpenGL 4.4. The shader compiles like normal if I remove the discard statement. I've been searching around and I'm finding nothing about this. Does the discard just not work on certain graphic cards or what?


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


how to move a 2d shape in opengl 4.6 (glfw) Class Button So from my understanding in order to move a 2d shape you need manipulate the vertices and then update???? If i do need to update the buffer how i would go by doing that? float xpos 150 Cords relative to the window application so let say the window size 480 by 260 float ypos 60 Where would I plug in position in the vertices array? float vertices .5f, .5f,0, .5f, .5f,0, .5f,.5f,0, .5f,.5f,0 shader.setup( quot Resources Shaders shape.vertex quot , quot Resources Shaders shape.frag quot ) glGenVertexArrays(1, amp VAO) glGenBuffers(1, amp VBO) bind the Vertex Array Object first, then bind and set vertex buffer(s), and then configure vertex attributes(s). glBindVertexArray(VAO) glBindBuffer(GL ARRAY BUFFER, VBO) glBufferData(GL ARRAY BUFFER, sizeof(vertices), vertices, GL DYNAMIC DRAW) glVertexAttribPointer(0, 3, GL FLOAT, GL FALSE, 3 sizeof(float), (void )0) glEnableVertexAttribArray(0) note that this is allowed, the call to glVertexAttribPointer registered VBO as the vertex attribute's bound vertex buffer object so afterwards we can safely unbind glBindBuffer(GL ARRAY BUFFER, 0) You can unbind the VAO afterwards so other VAO calls won't accidentally modify this VAO, but this rarely happens. Modifying other VAOs requires a call to glBindVertexArray anyways so we generally don't unbind VAOs (nor VBOs) when it's not directly necessary. glBindVertexArray(0)


Directional light shader not behaving as expected I coded my first glsl shader which manage diffuse and specular effects of a directional light. This is the fragment shader. version 120 matrix uniform mat4 model matrix directional light position in world coordinates uniform vec3 light position uniform vec3 eye send to fragment shader varying vec4 color varying vec4 normal varying vec4 vertex void main() float light diffuse intensity float light specular intensity float light mod vec3 world normal vec3 world vertex vec3 world reflec vec3 vertex to light vec3 vertex to eye world normal (model matrix normal).xyz world vertex (model matrix vertex).xyz vertex to light light position world vertex vector from vertex to light vertex to eye eye world vertex vector from vertex to eye world reflec 2 dot(vertex to light, normalize(world normal.xyz)) normalize(world normal) vertex to light reflection of vertex to light light diffuse intensity dot(normalize(vertex to light), normalize(world normal.xyz)) computing angle between light and normal light specular intensity dot(normalize(vertex to eye), normalize(world reflec)) computing angle between eye and reflection if (light diffuse intensity gt 0) light mod light diffuse intensity light specular intensity pow(light specular intensity, 8.0) else light specular intensity 0 gl FragColor vec4(mix(color.rgb light diffuse intensity, vec3(1.0,1.0,1.0), light specular intensity), 1.0) As you can see from the screenshot below, in the first screen, where I look at the sphere from the direction of the light, the border of the sphere is white because of the specular effect. However if the shader were correct it should not look like that. It should be white only in the middle of the sphere. In the second screen, I look at both the sphere and the source of the directional light (the yellow sun) and everything looks just fine. I cannot find the error in my shader, could someone help please? Thank you very much!


how to use a mask texture? A texture pack for a sponza model contains mask textures (black and white). I guess that I should read only a red channel from that texture, right ? I use deferred rendering and for shading calculations I use additive blending. A result is first save in a texture (for some post process operations), so doesn't go directly to the default framebuffer. How to use a mask texture ?


LWJGL GL QUADS texture artifact I managed to get working LWJGL in Java, and I loaded a test image (tv test card), but I keep getting weird artifacts outside the image. Code glBegin(GL QUADS) glTexCoord2f(0, 0) glVertex2i(10, 10) glTexCoord2f(1, 0) glVertex2i(500, 10) glTexCoord2f(1, 1) glVertex2i(500, 500) glTexCoord2f(0, 1) glVertex2i(10, 500) glEnd() What could be the cause?


How can I render text using the new(ish) JOGL GPU curve rendering classes? I'm fairly new to OpenGL JOGL, working through various tutorials and books and making steady progress. Text, however, is an area where I'm stuck. I figured out one way using BufferedImage and Graphics2D to draw strings and then swizzle the pixels and copy to an OpenGL texture, but the quality is low, it is resolution dependent, and it's not efficient. I found this http forum.jogamp.org GPU based Resolution Independent Curve Rendering td2764277.html. Unfortunately while there are some demos in the GitHub repo I can't quite get my head around them. The code I've tried to use is below In the init() method InputStream fontFile getClass().getResourceAsStream("media futura.ttf") try font FontFactory.get(fontFile, true) catch (IOException e) System.err.println("Couldn't open font!") e.printStackTrace() RenderState renderState RenderState.createRenderState(SVertex.factory()) renderState.setColorStatic(1, 1, 1, 1) renderState.setHintMask(RenderState.BITHINT GLOBAL DEPTH TEST ENABLED) renderer RegionRenderer.create(renderState, RegionRenderer.defaultBlendEnable, RegionRenderer.defaultBlendDisable) renderer.init(gl, Region.VBAA RENDERING BIT) util new TextRegionUtil(Region.VBAA RENDERING BIT) In the display() method PMVMatrix pmv renderer.getMatrix() pmv.glMatrixMode(GLMatrixFunc.GL MODELVIEW) pmv.glLoadIdentity() pmv.glTranslatef(0, 0, 300) float pixelSize font.getPixelSize(32, 96) util.drawString3D(gl, renderer, font, pixelSize, "Test", null, samples) I've searched and searched for a tutorial on this stuff or a simple, commented code example explaining how it works but to no avail. If anyone can help me I'd be extremely grateful!


What is the fastest way of drawing simple, textured geomtries and keeping the depth test? I'm looking for a fast way to draw simple 3D geometries that will consist of up to 10 vertices. Each of them will have a texture (though varying between geometries). I also want to store the fragment depth for depth testing. There will be no lighting and only very simple transformations (this actually is for isometric game). So far what I did was trying to achieve top performance using OpenGL for drawing simple quads (what the problem actually boils down to). For my machine (from around 2008), I had the following results Using immediate mode 4800 quads took 120ms Using vertex arrays and VBOs this took around 40 ms What I see as a problem is the bottleneck of glDraw calls. I want to somehow get below 4 5 ms , as there will be really a lot of objects on the screen. Any ideas about how could (or perhaps couldn't) achieve that?


How do I pick tiles from an isometric map with slopes? I'm looking for a way to convert mouse screen coordinates to isometric map coordinates, with the addition that the world has slopes and cliffs, and I have to be able to tell which quadrant of the tile is being pointed at by the mouse. The textures are handled by OpenGL, so I can't (easily) pick directly based on the tile sprite. I've found several similar solutions, (e.g. Isometric Tiles Math, XNA Resources amp Mouse Maps for Isometric Height Maps with the latter looking most promising) but none of them seem to quite fit my requirements. My tiles look like this What algorithm or technique could I use here?


GLSL variables as main function params vs on their own line? I am learning OpenGL and GLSL. I was taught that the in out variables should be formatted like this in vec3 something out vec3 somethingElse int main() etc... However, I ran across code like this online (ShaderToy) int main(in vec3 something, out vec3 somethingElse) Is there a difference? Is there any difference?


Does SDL2 completely encapsulates Direct3D and OpenGL? I'm starting to study game development but the concepts of how the SDL2 lib works are still a bit blurry to me. I get that both Direct3D and OpenGL are two sides of the same coin. They both are used to draw vectors in the screen and are used as a graphics hardware abstraction layer. From what I read about the SDL2 lib it seems to be a multi purpose library that encapsulates some functionalities as user input, threading, networking, window creation, and so on and also quot graphics hardware via OpenGL and Direct3D quot . Now the questions The SDL2 webpage states that it provides access to quot graphics hardware via OpenGL and Direct3D quot . What exactly that means? If I'm making a 3D game do I need to decide beforehand which graphics API I want to use (Direct3D or OpenGL) and use it alongside with the SDL2? If not, does SDL2 completely encapsulates the graphics API so I could easily deploy my game targeting Direct3D or OpenGL without adapting too much code for each one? In the case SDL2 does not completely abstract the graphics API, what texts and terms should I search to learn how to implement such an abstraction layer using SDL2? I want to be able to easily build for Direct3D and OpenGL. Thanks very much!


In a shader, why does substituting a variable with the expression producing it cause different behaviour? I have this correctly working OpenGL shader producing Perlin noise float left lerp(fade(v), downleft, topleft) float right lerp(fade(v), downright, topright) float result lerp(fade(u), left, right) Then I tried plugging the definitions of right and left into result float result lerp(fade(u), lerp(fade(v), downleft, topleft), lerp(fade(v), downright, topright)) Surprisingly, this behaves completely differently, giving visible edges in my Perlin noise. Below are both results My whole 30 line shader is here. What is the difference between those?


How can I unit test rendering output? I've been embracing Test Driven Development (TDD) recently and it's had wonderful impacts on my development output and the resiliency of my codebase. I would like to extend this approach to some of the rendering work that I do in OpenGL, but I've been unable to find any good approaches to this. I'll start with a concrete example so we know what kinds of things I want to test lets say I want to create a unit cube that rotates about some axis, and that I want to ensure that, for some number of frames, each frame is rendered correctly. How can I create an automated test case for this? Preferably, I'd even be able to write a test case before writing any code to render the cube (per usual TDD practices.) Among many other things, I'd want to make sure that the cube's size, location, and orientation are correct in each rendered frame. I may even want to make sure that the lighting equations in my shaders are correct in each frame. The only remotely useful approach to this that I've come across involves comparing rendered output to a reference output, which generally precludes TDD practice, and is very cumbersome. I could go on about other desired requirements, but I'm afraid the ones I've listed already are out of reach.


Calculating vertex normals (vn) causes ugly lines C openGL Im trying to procedurally generate planets for a project I'm working on. By adding noise to each vertex, I'm able to generate elevation, but without having updated vertice normals for my shader. It originally looked something like the picture below. When I tried to recalculate the vertex normals, I got some ugly sharp lines, most likely as a result from the way I was parsing the model. this is the code Im using to recalculate the normals for (auto amp x normals)x vec3(0) zero normals vec3 facenormal buffer indices is the faces triangles indexed, in pairs of 3. for (size t i 0 i lt indices.size() ) facenormal cross( (shape indices i 1 shape indices i ), (shape indices i 2 shape indices i ) ) normals indices i facenormal normals indices i facenormal normals indices i facenormal for (auto amp x normals)x normalize(x) normalize adjacent faces Basically I add up the adjacent faces to the vertices they belong to, then normalize the value they have. Then, based on suggestions, I took a look at the parsing and made sure it doesnt share vertices in the indexing. This seems to remove the lines, but im still stuck flat shading? But according to this, it should be accurate. So I'm still not fixing the problem. What is the correct formula to do the vertex calculation, if its not what I'm already doing. Like user Kolenda suggests, I was not modifying values at the base mesh level. but rather, doing them after loading the indexed copies. So, what I end up with is a combination of flat shading faces "shading" ghost vertice normals. Iterating over the faces on a mesh level, with the same formula, solves the problem.


Are there alternatives to multiple buffering? I'm learning about game programming. So far, my sources lead me to believe that multiple buffering is the best technique for redrawing in OpenGL. Are there other redrawing techniques? What are their advantages disadvantages? I'm not sure about terminology yet, but googling as best as I can hasn't yielded much result yet. Does anyone have any experience with redrawing techniques besides multiple buffering?


Texture loading Everything at once OR un loading the needed assets? Good evening. We've been developing quite a huge game for android on the basis of AndEngine. So we have a lot of assets to load, especially textures. At the moment everything (sound, textures etc) for every screen (menu, shop, etc etc) is loaded when the app starts (while showing a progress bar). This way the user only has to wait once about 16 seconds at the start of the game. We think that this is a pretty pleasant solution from the users perspective but might it be bad in terms of battery usage memory usage or any other reasons? What arguments speak for a solution where we unload all the screen specific assets of the active screen and load the assets needed for the next screen? Thank you for your opinion!


Unintended stuttering when moving camera I am using opengl and GLFW to make a rendering engine. Things work per se, but there is some weird flickering happening when I move the camera. Due the nature of the problem I need to link a youtube video https www.youtube.com watch?v XhFrXadnWbs amp feature youtu.be If you pay attention you will see the stuttering happening as I move the camera. I beleive this problem occurs due to how I have implemented my camera movement, which is GLFW key callback define CAM SPEED 0.2f void static key callback(GLFWwindow window, int key, int scancode, int action, int mods) if(key GLFW KEY W) c.translateForward(CAM SPEED) if(key GLFW KEY S) c.translateForward( CAM SPEED) if(key GLFW KEY A) c.translateSideways( CAM SPEED) if(key GLFW KEY D) c.translateSideways(CAM SPEED) Camera code void inline translateForward(float speed) glm vec3 hForward forward hForward.y 0 hForward normalize(hForward) position hForward speed void inline translateSideways(float speed) position side speed


searching for "university kind" free online course about OPENGL I know there are a lot of free university courses, but I'm trying to find one about OpenGL. Do you know where can I find one, online?


3D model rendered in halftone I am writing a 3D renderer that would render 3D models as if they had been drawn in halftone. Feature wise I need nothing fancy no colors, just pure 3D geometry and basic lighting like here Image credit https blenderartists.org forum showthread.php?438820 Suzanne Sketch Notes I have written a basic 3D renderer in the past, however, I am really inexperienced when it comes to shaders (again, I do know basics) and I have absolutely no idea where to start with this. The example image has been created in Blender, but I am writing my custom renderer. This is not a duplicate of "How can I make a shader effect that looks like a lightly shaded pencil drawing?", as my input is a 3D model, whereas the OP in the linked question used an image.


OpenGL ES draw pre rendered background onto depth buffer I want to create a scene with 2D pre rendered background and 3D models for characters (like those classic Final fantasy games). For the background, I have 2 textures one to be displayed, with colors, details... one to be used as depth buffer (depth value presented as grayscale value maybe) I want to write a shader program to help me discard all the pixels(frags) which have the depth smaller than current depth. But then, do the background and the models have to use the same shader? What value to compare with the depth value? Is this approach even possible?


Palette reduction to pre defined palette I'm writing a bunch of GLSL effects for fun, but I can't wrap my head around this. Basically, I want to reduce a texture's palette into a pre defined set of colors. For example, a post processing shader would take the FBO result texture and a 1D 2D texture that would contain the reduced palette (say, 64 colors), and the output would then be sampled based on these. Something like this in its core sampler2D source sampler2D palette vec4 source texture2D(...) Source texture to sample vec4 palette texture2D(...) Palette vec3 result color from the source converted to the closest value available in palette Any ideas how to do this? And to be more precise, I don't mean palette swapping the source texture is full colored result, and this shader would ultimately be a post processing shader, reducing the amount of colors to the ones that are predefined in the palette texture.