How to put OpenGL in a state for drawing blended, colored, nontextured polys? Using OpenGL1.1 (sadly) I'm trying to draw a cube, which is colored and alpha blended. It is instead showing up as opaque black. Even without including alpha in the color it still shows up as opaque black so I don't believe blending is the problem. Override public void doRender(Entity entity, double d0, double d1, double d2, float f, float f1) assert(entity instanceof EntityExplosion) EntityExplosion explosion (EntityExplosion) entity glPushMatrix() glPushAttrib(GL BLEND) glPushAttrib(GL COLOR MATERIAL) glDepthMask(false) glColorMaterial (GL FRONT AND BACK, GL AMBIENT AND DIFFUSE) TODO fix glEnable(GL COLOR MATERIAL) i dunno if this even does anything glBlendFunc(GL SRC ALPHA, GL ONE MINUS SRC ALPHA) glColor3b((byte)0, (byte)255, (byte)255) TODO fix glTranslated(d0, d1, d2) trans whole thing for(NukeParticle p explosion.particles) glPushMatrix() glTranslated(p.x, p.y, p.z) glCallList(callCube) glPopMatrix() glPopAttrib() glPopAttrib() glPopMatrix() This is being done during a Minecraft Entity Renderer, meaning that the current state of GL is for drawing shaded, textured polys. What attribs or whatever do I change so that I can draw the way I want to?


nvidia SSAO visible errors I am trying to add ssao effect to a visualization application but there are errors in resulting image. I am using code from https github.com nvpro samples gl ssao . Errors occur in rapidly changing lighting near the edges of screen. Only change to code was to remove basic shading and passing only white from scene.frag shader so the error could be seen more pronounced. I also added obj input to import sponza scene but the error is visible with the included sample scene as well if camera is moved close to object. As is this implementation only enables viewing objects in relative distance. Moving closer to objects brings up this errors. What causes this error and is there fix.


Taking cube from camera space to clip space, error in my math? watching Ken Joy's Computer Graphics lectures on youtube. One thing I'm confused about is after he gets the cube from the camera space to clip space, from my calculations the cube doesn't look like that. I expected the cube to look like that pink parallelogram in my picture, if we assume the Z of the front face of the cube to be 4 3 and the back face to be 2 then the Ws come out to be 4 3 and 2 respectively. So can someone explain how after multiplying by the viewing matrix, the cube comes out to look like how Ken has it. Ken's view matrix After view matrix has been applied What I think the side of the cube should look like(the pink parallelogram) after view matrix has been applied my reasoning is, after the perspective divide by W, the blue and green vectors should get truncated to create that pink parallelogram. So I'm struggling to understand this. Thanks in advance.


Assimp renders a partial amount of vertices I'm building a 3D game, and i'm trying to load some assets with the nice Assimp library. The model should look like the one in the first picture, but instead, it takes the form of some kind of avant garde sculpture, as the second picture shows. At least i'm proud that i get to see something, but hey, i can do better. It's not a problem with shaders (it simply isn't, i pass no normals and no textures, just the vertex coordinate, since i set a static colour). Here is my code MODEL LOADING (only vertex coordinates) void Mesh open(const std string file) Assimp Importer importer const aiScene scene importer.ReadFile(file, aiProcess Triangulate) if(!scene) throw STREAM("Could open mesh '" lt lt file lt lt "'!") std vector lt float gt g vp count 0 for(uint m i 0 m i lt scene gt mNumMeshes m i ) const aiMesh mesh scene gt mMeshes 0 g vp.reserve(3 mesh gt mNumVertices) count mesh gt mNumVertices for(uint v i 0 v i lt mesh gt mNumVertices v i ) if(mesh gt HasPositions()) const aiVector3D vp amp (mesh gt mVertices v i ) g vp.push back(vp gt x) g vp.push back(vp gt y) g vp.push back(vp gt z) glGenBuffers(1, amp vbo) glBindBuffer(GL ARRAY BUFFER, vbo) glBufferData(GL ARRAY BUFFER, count 3 sizeof(float), amp g vp 0 , GL STATIC DRAW) glEnableVertexAttribArray(0) glVertexAttribPointer(0, 3, GL FLOAT, GL FALSE, 0, (GLubyte )NULL) SCENE RENDERING void renderScene() glClear(GL COLOR BUFFER BIT GL DEPTH BUFFER BIT) program.use() program.setUniform("transformMat", modelMat) glBindBuffer(GL ARRAY BUFFER, m.vbo) glDrawArrays(GL TRIANGLES, 0, m.count) SDL GL SwapWindow(window gt mWin) Depth testing is enabled, and i'm using OpenGL 4.0 with v400 shaders too. The error will possibly be stupid, but i can't find it, and my head is all boiling at this very moment. Thanks for your help!


OpenGL Quad is being separated like a two triangles after blending I wanted to add transparency for my UI elements, so I enabled blending by adding glEnable(GL BLEND) glBlendFunc(GL SRC ALPHA, GL ONE MINUS SRC ALPHA) before renderer and glDisable(GL BLEND) after renderer. So I tried to render simple rectangle (with glDrawArrays() because I'm using GLSL shaders). Before I enabled blending my rectangle (1 quad) looked like this And now, after blending it looks like this (Like a two triangles) Do I need some extra settings for my blending or what? Edit I noticed that if I remove anti aliasing code glHint(GL LINE SMOOTH HINT, GL NICEST) glHint(GL POINT SMOOTH HINT, GL NICEST) glHint(GL POLYGON SMOOTH HINT, GL NICEST) glHint(GL PERSPECTIVE CORRECTION HINT, GL NICEST) glEnable(GL LINE SMOOTH) glEnable(GL POINT SMOOTH) glEnable(GL POLYGON SMOOTH) Problem will disappear, but I want to keep anti aliasing in my game. Any ideas?


How many textures can usually I bind at once? I'm developing a game engine, and it's only going to work on modern (Shader model 4 ) hardware. I figure that, by the time I'm done with it, that won't be such an unreasonable requirement. My question is how many textures can I bind at once on a modern graphics card? 16 would be sufficient. Can I expect most modern graphics cards to support that number of textures? My GTX 460 appears to support 32, but I have no idea if that's representative of most modern video cards.


Random lines drawn on screen while all vertexes are correct I'm writing a 2D program in which a monocycle follows a Catmull Rom spline. My problem is when I write the circle, the drawing goes crazy. There is one line on the screenshot (which seems to be 3 when watching it), that rotates with the circle and blinks around it. It doesn't happen always, comes randomly, sometimes it's fine then it will start this after a few seconds. I have no clue what could cause it. My calculations are correct, there aren't fauly or nans inf s in the array, and if I put printf right before buffering the vbo, the lines don't appear, so I can't even debug it. And sometimes there's a small blinking in the green part too. Here's some part of my code. Creating the curve void Create() Curve glGenVertexArrays(1, amp vaoCurve) glBindVertexArray(vaoCurve) glGenBuffers(1, amp vboCurve) Generate 1 vertex buffer object glBindBuffer(GL ARRAY BUFFER, vboCurve) Enable the vertex attribute arrays glEnableVertexAttribArray(0) attribute array 0 Map attribute array 0 to the vertex data of the interleaved vbo glVertexAttribPointer(0, 2, GL FLOAT, GL FALSE, 2 sizeof(float), NULL) attribute array, components attribute, component type, normalize?, stride, offset void Create() glGenVertexArrays(1, amp vaoCyclist) glBindVertexArray(vaoCyclist) Curve glGenBuffers(1, amp vboCyclist) Generate 1 vertex buffer object glBindBuffer(GL ARRAY BUFFER, vboCyclist) glGenBuffers(1, amp vboHuman) Generate 1 vertex buffer object Enable the vertex attribute arrays glEnableVertexAttribArray(0) attribute array 0 Map attribute array 0 to the vertex data of the interleaved vbo glVertexAttribPointer(0, 2, GL FLOAT, GL FALSE, 2 sizeof(float), NULL) attribute array, components attribute, component type, normalize?, stride, offset Calculating humanData.clear() circleData.clear() for (int i 0 i lt 180 i ) cordX cosf((float)M PI i 2 180.0f) cordY sinf((float)M PI i 2 180.0f) if (i 0) circleData.push back(cordX) circleData.push back(cordY) else if (i 179) circleData.push back(cosf((float)M PI i 2 180.0f)) circleData.push back(sinf((float)M PI i 2 180.0f)) circleData.push back(cosf((float)M PI i 2 180.0f)) circleData.push back(sinf((float)M PI i 2 180.0f)) circleData.push back(cosf((float)M PI 0 2 180.0f)) circleData.push back(sinf((float)M PI 0 2 180.0f)) else circleData.push back(cordX) circleData.push back(cordY) circleData.push back(cordX) circleData.push back(cordY) Draw mat4 MVPTransform MrotateTranslate() camera.V() camera.P() MVPTransform.SetUniform(gpuProgram.getId(), "MVP") int colorLocation glGetUniformLocation(gpuProgram.getId(), "color") for (int i 0 i lt circleData.size() 1 i ) printf(" f n", circleData i ) glBindVertexArray(vaoCyclist) glBindBuffer(GL ARRAY BUFFER, vboCyclist) glBufferData(GL ARRAY BUFFER, circleData.size() sizeof(float), amp circleData 0 , GL DYNAMIC DRAW) if (colorLocation gt 0) glUniform4f(colorLocation, 0.72f, 0.16f, 0.0f, 1.0f) glDrawArrays(GL LINES, 0, circleData.size()) Cyclist attributes class Cyclist private unsigned int vaoCyclist, vboCyclist unsigned int vboHuman float r 1 float v 0 vec2 wTranslate vec2( 10.0f, 0.0f) vec2 position vec2(0, 0) float sina, fi 0, ds float cordX, cordY vector lt float gt circleData vector lt float gt humanData float dir 1.0f


Optimizing black and white matrix block drawing Disclaimer I am uncertain if this is the best place to post this question, so please advise me of how I can best find the answer if I am doing something wrong. I am asking this question because I am trying to optimize a drawing function of a PC game I am programming. Preface There is a matrix of blocks, that can be either on (black) or off (white). There will be different colors, but for the sake of simplicity I am presenting the problem to you as black and white only, so please imagine this matrix forming some random pattern like a QR code which would be a good example. Problem Instead of drawing each black block individually, I want to determine how to draw all black blocks using as minimum calls to my draw black rectangle function as possible. Question Is there any existing process that I can refer to so as to make my drawing process as efficient as possible, or how would I logically go about tackling this conundrum? Edit Tried to produce some example code for us to play with std vector lt std vector lt bool gt gt matrix int width 100 int height 100 matrix.resize(height) for(int h 0 h lt height h ) matrix h .resize(width) for(int w 0 w lt width w ) matrix h w random 1 0 void draw() .. draw matrix using a minimum amount of calls to draw rectangle void draw rectangle(int x, int y, int width, int height) .. draws a set of black blocks


How do I implement GPU based dynamic geometry LOD in OpenGL? I'm trying to implement LOD to boost my game's performance. I found a very nice tutorial. The basic concept that I think I understand is Get the distance from the camera to the object, check for the right LOD level and then render the object with the "right amount of instances". How do I implement that? The provided example code is a mystery to me... Some questions Is this a good method to implement LOD? Can someone please explain me detailed, how I have to implement it, with the queries and so on... I'm rendering all of my objects with GL11.glDrawElements(GL11.GL TRIANGLES, model.getRawModel().getVertexCount(), GL11.GL UNSIGNED INT, 0) The example code uses GL POINTS. Can I implement it also with GL TRIANGLES?


issue with Compute Shader macbeth chart I'm trying to generate a macbeth chart using the compute shader, but there seems to be an issue with the output image. here is the glsl code version 430 core layout (local size x 32, local size y 32) in layout (rgba32f, binding 0) uniform image2D data uniform int factor 2 const float colorMatchingFunc 3 72 const float spectralData 24 36 void spectrumToXYZ(uint colorIndex, out vec3 XYZ) const mat3 XYZ TO RGB const float gamma 1 void main(void) uvec2 dim gl NumWorkGroups.xy factor uvec2 ij gl WorkGroupID.xy factor uint i ij.x dim.x ij.y vec3 xyz spectrumToXYZ(i, xyz) vec3 rgb max(vec3(0), XYZ TO RGB xyz) rgb pow(rgb, vec3(1 gamma)) imageStore(data, ivec2(gl GlobalInvocationID.xy), vec4(rgb, 1)) and here is the c setup static int factor 4 static int patchSize 32 int width 192 factor int height 128 factor glActiveTexture(TEXTURE( id)) glBindTexture(GL TEXTURE 2D, buffer) glTexStorage2D(GL TEXTURE 2D, 1, GL RGBA32F, width, height) glTexParameteri(GL TEXTURE 2D, GL TEXTURE WRAP S, GL CLAMP TO EDGE) glTexParameteri(GL TEXTURE 2D, GL TEXTURE WRAP T, GL CLAMP TO EDGE) glDispatchCompute( width (patchSize), height (patchSize), 1) This setup and glsl code makes sure I get a 6 4 macbeth chart. I'm assuming regardless of which invocation workgroup I end up in I should always generate the correct color for the patch I'm currently on. but I seem to have som aliasing especially on the bottom row and its very noticable all rows on lower resolutions. Low resolution image


OpenGL cubemap binding I'm experimenting a strange behaviour of textures inside my shaders. Basically I need and bind two cubemap textures inside my shader but only one gets actually bound. I've tried swapping the two textures keeping the samplers untouched and the texture that previouly I could see now I don't see it anymore, so I think the problem is related to the samplers inside my shader. This is how I bind my two cubemaps to the shader int firstTextureLocation glGetUniformLocation(programID, "ConvolutionSrc") returns 5 int secondTextureLocation glGetUniformLocation(programID, "LastResult") returns 9 glActiveTexture(GL TEXTURE0) glBindTexture(GL TEXTURE CUBE MAP, firstTextureID) glUniform1i(firstTextureLocation, 0) glActiveTexture(GL TEXTURE1) glBindTexture(GL TEXTURE CUBE MAP, secondTextureID) glUniform1i(secondTextureLocation, 1) And this is a portion of my shader (the parts where the cubemaps are used) uniform samplerCube ConvolutionSrc uniform samplerCube LastResult ... vec3 Sample(vec3 R) ... vec3 hdrPixel rescaleHDR(textureLod(ConvolutionSrc, L, lod).rgb) ... void main() ... vec3 lastResult textureLod(LastResult, R, ConvolutionMip).rgb sampledColor.rgb mix(lastResult.xyz, importanceSampled.xyz, 1.0f (ConvolutionSamplesOffset)) ... Basically only the texture at uniform location 5 of my shader gets bound.


GLSL 330 Core Bug? Uniform variable will not set to value if it is named a certain way In the code below I have a uniform variable named "vw matrix" used in the calculation for gl Position. When I run my program, a rectangle gets printed to the screen. version 330 core layout (location 0) in vec4 position uniform mat4 pr matrix uniform mat4 vw matrix mat4(1.0) Rectangle! uniform mat4 m1 matrix mat4(1.0) No rectangle! uniform mat4 mmmmm mat4(1.0) No rectangle! uniform mat4 test mat4(1.0) Rectangle! uniform mat4 aaa mat4(1.0) No rectangle! void main() gl Position pr matrix position vw matrix If instead I put "m1 matrix" in the gl Position line instead of "vw matrix". The rectangle no longer appears. I'm not getting any GLSL compile errors. void main() gl Position pr matrix position m1 matrix There are no calls to glUniformMatrix4fv changing the value "m1 matrix". It has the same value as "vw matrix" so for some reason it must not be initializing. I did some experimenting, it won't set a uniform variable if it starts with a certain letter and "m" is one of those letters. Anything that starts with a "v" or "t" works fine. I can't make this up! Is there anything I should double check post or is this just a rather bizarre bug? The full code is available at https github.com nduplessis11 Freeze I'm running on Linux Mint 17.1 and my GL VERSION is "OpenGL 4.4 13374 Compatibility Profile Context 15.20.2013". My video driver is AMD's fglrx version 15.200 UPDATE Ok, I found a bug in my main program in a function that retrieves the location of a uniform. GLint Shader getUniformLocation(const GLchar name) This is a very slow operation, optimize later. glGetUniformLocation(m ShaderID, name) return 0 This was causing 0 to be passed as the location for glSetUniform calls. I'm not sure how, but fixing this function stopped the unpredictable behavior when initializing uniform variables from within the shader program. I'm still going to take Trevor's advice and set them from within my main program.


How can I make terrain texturing look detailed both close up and far away? I attempting to make my game have very detailed textures, and in general look pretty. However, I'm having some issues with that. Let's take a look at a rock texture close up Picture. As you can see, this looks perfectly adequate for a 3D game up close. However, I'm struggling to get this working at a distance Picture At a distance, the texturing looks obviously uniform, and looks very tiled and very bland. Picture How can I solve this issue to make my textures look more detailed at all distances? I obviously have mipmapping enabled, but I don't understand why the texture looks so badly detailed and what I can do to improve it.


Problem with 2d rotation in OpenGL I have a function to perform sprite rotation void Sprite rotateSprite(float angle) Making an array of vertices 6 for 2 triangles Vector2 lt gamePos gt halfDims( rect.w 2, rect.h 2) Vector2 lt gamePos gt bl( halfDims.x, halfDims.y) Vector2 lt gamePos gt tl( halfDims.x,halfDims.y) Vector2 lt gamePos gt br(halfDims.x, halfDims.y) Vector2 lt gamePos gt tr(halfDims.x,halfDims.y) bl rotatePoint(bl,angle) halfDims br rotatePoint(br,angle) halfDims tl rotatePoint(tl,angle) halfDims tr rotatePoint(tr,angle) halfDims 1st triangle Top right dataPointer.vertices 0 .setPosition( rect.x tr.x, rect.y tr.y) Top left dataPointer.vertices 1 .setPosition( rect.x tl.x, rect.y tl.y) Bottom left dataPointer.vertices 2 .setPosition( rect.x bl.x, rect.y bl.y) 2nd triangle Bottom left dataPointer.vertices 3 .setPosition( rect.x bl.x, rect.y bl.y) Bottom right dataPointer.vertices 4 .setPosition( rect.x br.x, rect.y br.y) Top right dataPointer.vertices 5 .setPosition( rect.x tr.x, rect.y tr.y) Vector2 lt gamePos gt Sprite rotatePoint(Vector2 lt gamePos gt pos, float amp angle) Vector2 lt gamePos gt newv newv.x pos.x cos(angle) pos.y sin(angle) newv.y pos.y cos(angle) pos.x sin(angle) return newv And the result is Am i doing something wrong ? It happens also when i put small angle (even if i put here angle 1 ) Thanks for help.


SDL, SFML, OpenGL, or just move to Java I recently started a new project, and I'm wondering if I should change the technology now before it's too late. I'm using SDL with C , I have around 6 classes, and the game is going alright, but I got to this point where I have to rotate my sprite to make it point to the coordinates of the mouse. It's a 2D topdown game, so if I pre cached the images, I'd have to load 360 images, which is bad for memory. If I used SDL glx, I could do the rotation real time, but I heard it'd drop my frame rate very drastically, and I don't want my game to be slow. I also read I could use OpenGL, which is faster at these things. The problem is, how much would I have to change my code if I moved to OpenGL with SDL. So, I considered moving to a completely different language Java which is much simpler, and would allow me to focus on the game and handle networking much more easily than with C . I am very confused, and would like to hear your opinion thank you!


Best approach to render text in OpenGL 4.5 I have tried to implement text rendering in OpenGL from several tutorials and guides but I am unable to implement any of them successfully. The latest one I have attempted is Here but it seems to be incompatible with GL 4.5. My end goal is to implement the ability to load TTF files into OpenGL and render them. If someone could give me a hand with a sample code snippet of how to implement this myself, or even to reconfigure the free type library, that would be appreciated!


Transformed Vertices have wrong Z Axis For quite some time I've been working on my open 3D game engine, to learn how this stuff works. You can see the full codebase relating to my problem here on GitHub. I'm using an OpenGL 3.3 Core Profile Context on Mac OS X 10.10.3 and a GeForce GTX 760, if this matters. Everything seems to work fine when submitting my vertices and MVP matrix to the Pipeline. But at two different points I try to transform vertices on my CPU, which leads to problems. To simplify rendering the debug bounding boxes in a single frame, I transform the vertices by their MVP matrix and later submit them all to OpenGL with an identity matrix as transformation matrix for (auto amp c corner) glm vec4 t VP glm vec4(c, 1.0f) vertices.emplace back(glm vec3(t) t.w) ... Shader drawGL(vertices, colorsLine, indicesLine, glm mat4(1.0f), gl GL LINES) Most of the time, this seems to work fine. But when some vertices of a bounding box lie behind the camera, they will be "mirrored" and extend into empty space, as you can see in this screenshot Something similar happens with my portal based rendering approach, as described in Portals and Mirrors Simple, Fast Evaluation of Potentially Visible Sets. Basically, I'm looking for a visible portal, and then for more portals that are visible through the already found portal. The relevant code for (int c 0 c lt 4 c ) glm vec3 port portal.getVertex(c) glm vec4 result VP glm vec4(port, 1.0f) glm vec3 vert glm vec3(result) result.w ... This basically works as expected, as you can see in the following screenshot However, as before, there is a problem with vertices behind the camera. I would expect the transformed vertices Z axis to be in the range 0 1 and vertices behind the camera should be outside of that range. What I'm really seeing, however, is that the Z part is always 1, as you can see in this screenshot (the first line is the world vector, the second is the vector multiplied with the matrix, the third is the multiplied vector divided by w) To give you the full picture, this is how I create my projection matrix projection glm perspective(45.0f, size.x size.y, 0.1f, 75000.0f) And my view matrix is created using the quaternion of my camera glm mat4 translate glm translate(glm mat4(1.0f), pos) glm mat4 rotate glm toMat4(quaternion) view glm inverse(translate rotate) According to every description I've read of the OpenGL transformation pipeline, I've done everything to have my world coordinates now in clipping space. But, looking at the Z axis, this seems to be false. I'm sure I'm missing something obvious with my math here. Please help me out ) Best Regards, Thomas PS English is not my native language, please excuse any mistakes.


Questions related to rendering to texture and rendering to buffer (OpenGL) I am experimenting with off screen rendering. I understand there is two solutions to this rendering to texture (you attach a texture to one of the FBO's attachment point which can be a color, depth, etc.) use a render buffer. Question 1 I first experimented with using render buffers. I have a FBO and 2 RBOs, one for color (attached to COLOR0) and one for depth (attached to DEPTH). When I want to visualise the content of what I rendered to the render buffer, I use the glBlitFramebuffer function to copy the content from the FBO to the Window frame buffer (index 0). glBindFramebuffer(GL READ FRAMEBUFFER, fboId) glBindFramebuffer(GL DRAW FRAMEBUFFER, 0) glBlitFramebuffer(0, 0, width, height, 0, 0, width, height, GL COLOR BUFFER BIT, GL LINEAR) First I would like to know if this the best way? (of passing the image from the a render buffer back to the window buffer). Question 2 My second question. The method I described above works but I can only see the "color" buffer of the FBO, not the depth buffer (I would also like to visualise the depth buffer). So I was wondering how if this was possible using this approach? I tried to use the index of the depth render buffer in place of the fboIdx in glBindFramebuffer but it didn't change anything. Can I make it work without using render to texture approach? Question 3 My end goal is to render two images using an off screen approach and blend them together. The result of the mix between the two rendered images is what I want to display to the screen. To keep things fast, I understand this can be done in hardware. What's the best way for doing this? Can it be done using the render buffer approach or do I need to go the render to texture approach (aka render to two textures and then blend these textures using a fragment shader when I do my final pass in which I render a quad stretched over the surface of the screen?


Mapping rectangular texture on trapezoid like shape I have a problem with rendering rectangular textures on non rectangular surfaces. While googling, I found a thread with person having a pretty similar problem http www.gamedev.net topic 419296 skewedsheared texture mapping in opengl But in my case, I cannot be sure about surface's exact properties. It's not regular trapezoid, it can be slightly bent. Which means, that I cannot just calculate correct texture matrix, or at least I don't know how. I've tried to render triangle fan like shape, but it just changed the characteristics of final distortion.


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


Am I allowed to make my Minecraft clone open source? I'm developing in my spare time a game like Minecraft. In fact, it isn't "like Minecraft", because I'm trying to make it a close as possible copy of it (meant as exercise for myself at the age of 16 and simply because of it is fun to me). Of course, I'm not copying the code using the Minecraft Coder Pack (MCP). I started the game from scratch in Java using OpenGL. So, my question is am I allowed to put my source code online on a public source code versioning host like GitHub, Google Code, et cetera (which makes my code open source, because I don't want to pay to use a private host)? Of course, I don't want to sell the game, because the game is from Notch. A detail which might be important is that I'm using a custom texture pack (so, not the one that is shipped with the real Minecraft). If it is allowed, are there any rules? I took a look to this page, but it seems that he doesn't say anything about this http www.minecraft.net terms Edit There is the game called Terasology (started under the name Blockmania) from Begla. That is a nice project, but it is not meant to be as close as possible to Minecraft. That project is open source.


How to get rid of half pixel artifacts? I've been having a bit of trouble using OpenGL to make 2D games. I am using a traditional ortho perspective with just some sprites being rendered and moved around. It all works perfectly but there is a little graphical artifact that I would like to get rid of. As the sprites move, their edges jitter a little bit I assume this happens as the position of the sprite goes from a half pixel coordinate to a nicely rounded up coordinate, and then back again, causing the artifact to intermittently show up. I also had the exact same problem with text rendering (textured quads technique), when it was sitting at half pixel coordinates, where it would get blurry and ugly, while at strict integer positions it would show immaculate. I could force my sprites to integer positions before rendering, which would probably fix the artifact, but at the same time ruin the movement smoothness. So, does anyone know what is the state of the art solution for this problem? How to handle sprite positioning without artifacts?


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.


A good way to build a game loop in OpenGL I'm currently beginning to learn OpenGL at school, and I've started making a simple game the other day (on my own, not for school). I'm using freeglut, and am building it in C, so for my game loop I had really just been using a function I made passed to glutIdleFunc to update all the drawing and physics in one pass. This was fine for simple animations that I didn't care too much about the frame rate, but since the game is mostly physics based, I really want to (need to) tie down how fast it's updating. So my first attempt was to have my function I pass to glutIdleFunc (myIdle()) to keep track of how much time has passed since the previous call to it, and update the physics (and currently graphics) every so many milliseconds. I used timeGetTime() to do this (by using lt windows.h gt ). And this got me to thinking, is using the idle function really a good way of going about the game loop? My question is, what is a better way to implement the game loop in OpenGL? Should I avoid using the idle function?


What is Vulkan and how does it differ from OpenGL? Khronos Group (the standards body behind OpenGL) has just announced Vulkan Vulkan is the new generation, open standard API for high efficiency access to graphics and compute on modern GPUs. This ground up design, previously referred to as the Next Generation OpenGL Initiative, provides applications direct control over GPU acceleration for maximized performance and predictability. Their page is quite marketese jargon heavy, as is the press release In simple terms, what does Vulkan mean to game developers? (Gabe Newell is quoted as being strongly in favour, without further explanation.) What exactly is Vulkan's relationship to OpenGL? Its previous name "glNext" (short for "Next Generation OpenGL Initiative") makes it sound like a replacement. Update The Vulkan 1.0 spec was released on 16 02 2016.


D3D OpenGL Question about shaders in larger projects I'm a game dev student and last semester we had a '3D programming' course, in which we did some basic stuff such as rendering a textured quad spinning around in the "scene". We used quite basic vertex , geometry , and fragment shaders to do this. My question is, how are shaders "managed" in a larger projects? For example, I might have a sphere in the scene that uses a shader to generate some effect on it, some VS or FS to generate water ripples or waves on a water 'model', etc. How would all these different shaders be combined in the same project? Do we just create new shader programs for the different shaders(as you can do in OpenGL)? Do you use some kind of condition statement in the shader and use only one program? Some other approach? I've heard you really want to minimize API calls, especially for realtime apps (Multiple shader programs would need at least 2 calls to set the shader programs, EVERY frame.) I'm really confused about this part, and our next course involves making a small game so this will be quite important I'd imagine. (also im personally very paranoid when it comes to performance I want to do things right from the start when possible) Sorry if the question is poorly formulated, hope it makes some sense. ' An example would be great, HLSL D3D or GLSL OpenGL doesnt matter, I've fiddled with both.


How expensive is OpenGL Texture Binding I'm currently working on a renderer for Tiled's .tmx maps. Among one of the features there is that layers and tilesets are independent, so that a layer can use any tile set on any tile. It's not so much of a problem, though, as my Image type is basically data Image Image imageTexture TextureObject , imageMinTex2 TexCoord2 , imageMaxTex2 TexCoord2 deriving (Show, Eq) Drawing an image is therefore Bind texture Render Quad using min max texture coords A quite simple implementation. However, if every Tile is an Image, in my implementation, then this would mean that on every tile, a texture is bound. Often times it will be the same, and quite often just a few tiles have entirely different texture. So how expensive is a texture binding in OpenGL? Do I have to sort the Tiles by texture or will the OpenGL drivers do that for me?


OpenGL Shadow Mapping from directional light I have read this tutorial http www.opengl tutorial.org intermediate tutorials tutorial 16 shadow mapping I wonder, is this the current best technique for generating shadows in an arbitrary 3D scene? Is it the way current modern games implements directional light shadows or are they using some other better way of calculating shadows on the fly? What I mean is if you know your geometry so good that you know exactly every impact a shadow can have on an objects colors, it must be better to use that information instead of rendering a Shadow map? For example, if we have a 3D grid world with all perfect cubes at perfect offset (think minecraft) and the directional light if exactly 45 degree in all dimensions, that leave us with a situation where a cube closer to the light will also cast shadow on the entire cubes at position offset 1, 1, 1 from that cube, and so on. The shadows always go diagonal and put other equally sized cubes sides in 1 of three states all shadow, all light or 50 in shadow. If we know our geometry so good, then using that information must be much faster than rendering shadow maps right? Even when most of such calculation is done on the CPU instead of the GPU.


Translate operation is rotating? cube 1. 0. 0. 6. 0. 1. 0. 0. 0. 0. 1. 0. 0. 0. 0. 1. view 1. 0. 0. 0. 0. 1. 0. 0. 0. 0. 1. 0. 0. 0. 0. 1. final 1. 0. 0. 6. 0. 1. 0. 0. 0. 0. 1. 0. 0. 0. 0. 1. Hello! I have a cube and I'm trying to move it around. The above are the calculated matricies for the cube, viewport, and the combined matrix after multiplication. The result is this I'm not sure why it's being warped like this instead of scooting over a bit. Any idea?


Effect of vertex winding on normals and shading I have implemented a Phong and Gourand shader for a triangle mesh that is being imported from an STL file. It appears to be working fairly allright but some triangles seem to be what I can only describe as upside down due to lack of better wording. This effect is visible in both shading models albeit a bit smoother in Phong. Here is an example On something basic like a cube the rendering is perfect. I am no expert but from what I have read, I am lead to suspect that perhaps the winding of the vertices in the mesh might be causing normals that are somewhat incorrect. Could this be possible and if so, how does one correct for that? The effect of interpolating the normals by either division or by area weight does not really make too much of a difference. I can also confirm that the normals that I am calculating are basically the same as those that come with the STL as calculated by FreeCAD. The manually calculated normals are slightly better though because they are area weighed. They are calculated as follows glm vec3 e1 vecs 1 vecs 0 glm vec3 e2 vecs 2 vecs 0 faceNorms i glm cross(e1, e2) with "vecs" being the 3 points of my vertices. I then sum up all these area weighed normals for each face that uses a normal and finally normalize that. PS. FreeCAD renders the mesh in a "flat" fashion and I guess thereby avoids this issue but unfortunately rendering "flat" with GLES 2.0 is a bit of a performance waste from what I have read.


Android Opengl Alternate values for gl FragColor I'm writing an Android application that utilizes opengl to perform some changes to the camera output. I've written my code in such a way that I finally figured out what is causing the performance issue. extension GL OES EGL image external require precision mediump float uniform samplerExternalOES sTexture uniform vec4 vColor const int MAX COLORS 6 uniform float vHues MAX COLORS uniform float vOffsets MAX COLORS varying vec2 v CamTexCoordinate float rgb2hue(vec4 c) vec4 K vec4(0.0, 1.0 3.0, 2.0 3.0, 1.0) vec4 p mix(vec4(c.bg, K.wz), vec4(c.gb, K.xy), step(c.b, c.g)) vec4 q mix(vec4(p.xyw, c.r), vec4(c.r, p.yzx), step(p.x, c.r)) float d q.x min(q.w, q.y) float e 1.0e 10 return abs(q.z (q.w q.y) (6.0 d e)) bool isInRange(float a1,float a2, float vOffset) if(a2 lt 0.0) return false else if(abs(a1 a2) lt vOffset) return true else if( a1 gt a2) return (1.0 a1 a2) lt vOffset else return (1.0 a1 a2) lt vOffset vec4 getGrey(vec4 c) float grey (c.r c.g c.b) 3.0 return vec4(grey, grey, grey, c.a) void main() vec4 c texture2D(sTexture, v CamTexCoordinate) bool hasColor vHues 0 gt 0.0 float hue rgb2hue(c) vec4 test getGrey(c) for(int i 0 i lt MAX COLORS i ) if(isInRange(hue, vHues i , vOffsets i )) If I uncomment this line the performance gets terrible test c gl FragColor test There is a significant hit to performance (a lot of frames are skipped) when I uncomment the line above. I basically want to use the original color sometimes and a different color depending on some condition. It works but is there a more efficient way to do this? Also, why does this perform so poorly?


How can I improve the performance of texture switching without resorting to atlasing? I'd like to use texture images that are not a sprite sheet or other form of texture atlas, mainly because I'll be consistently adding and swapping textures while I figure out the direction my game takes. In Java, I'm using slick2d's TextureLoader to load a texture, and then I bind it with an unique id. However, when not using a spritesheet I have many more images to bind, which causes a potential performance problem. I've noticed that calling glBindTexture for every block I'm drawing is bad, it drops my FPS to 1. I'm already rendering blocks with glCallList so I've found a middle ground. I bind a single block texture and then render all blocks of that type in the chunk, and repeat for each unique block type. However, that's still less than preferable. Is there a better way to efficiently use multiple textures without an atlas or sprite sheet?


Get world position in Vertex shader I'm wondering how I can get the final position of a vertex. I use glTranslate in my render code, and I'm not getting the world coordinates correct. My world is devided in chunks and my position get's screwed up. I have tried multiplying the position with the 3 built in matrices, but no success.


GraphicsAdapter.Adapters on openGL won t return secondary monitor I have been searching for this everywhere and never found the answer. I am developing a feature to allow the user to select which monitor to run the game. I have two monitors, primary and secondary. I tried to use "GraphicsAdapter.Adapters" but it always retrieves only 1 monitor (the one I am running the Visual Studio which is the default one). Is this a bug? How can I retrieve all the monitors available? Thanks MONOGAME 3.6 OPENGL (cross platform) Visual Studio 2015 Windows 10 Pro 64bits


How to fix model matrices colliding in vertex shader? I am new to OpenGL programming and I'm writing some basic code to display a few objects onto a screen. I have a pyramid shape that I'm displaying, as well as a box shape that I am displaying. The pyramid shape is a class (C ), and each pyramid object creates it's own VBO (storing the points colours). The same thing goes for the box. The problem I'm having is that I have two shapes, and the shapes use the same vertex shader. Since I apply a model matrix for each object in the shader, the model matrix gets set for one object, but then when the other object goes to display itself it overwrites the model matrix for the previous object with it's own. So only one object has the correct model matrix after they are all done their display method. I am also using hierarchical transformations to attach objects to each other. I have the root object storing the view projection matrices, and the children of the hierarchy tree storing their individual model transformations. When a child wants to display itself, it walks up the tree to compute all the transformations it needs to do to itself. The problem also applies here, since the last child to be displayed will be the one whose model matrix is applied in the vertex shader. I can't seem to figure out how to differentiate in the shader which MVP matrix to apply to which vertex. I think I'm missing something very basic here but I can't seem to figure it out... Any help would make my life a lot easier! Edit Is it possible that the shader is overwriting the MVP matrix in between glDrawArrays() glDrawElements() calls?


Smooth matrix rotation I have a coded a simple example for a matrix rotation. The example rotates a sphere around its center. The problem is that the rotation is not running perfectly smooth and I'm wondering why. Here is a minimal code sample float totalMs 0.0f int animationDuration 5000 void update(float deltaMs) totalMs deltaMs float degrees (totalMs animationDuration) animationDuration 360.0f glm mat4 rotation glm rotate(glm mat4(), radians(degrees), rotationAxis) multiply modelViewMatrix by rotation matrix and use the resulting matrix in shader to transform points I'm programming in C , using GLM Library for Maths, SDL2 for rendering context and OpenGL for the rendering. Any hints what could cause the rendering to not look totally smooth? Edit Ok I found out that the time needed for SDL GL SwapWindow() at the end of my gameLoop varies between lt 1ms and 30ms. What could be causing this?


OpenglGL Render two scenes with one draw call I need to draw a normal vector scene and default scene. I could achieve this my having two programs with different fragment shader to produce the following images. It will require me to draw twice. somethinglike useProgram(normal vector rendering program) render bunny() useProgram(just default scene program) render bunny() However when I am rendering the default scene, I am already passing normal vector information to achieve the lighting. So it got me curious, can I produce two different scenes with one program(a program that has two color buffer attaches) and one draw call somehow? I think if such is possible then I am saving lots of computer resource by not having to draw multiple times for different images.


Am I allowed to make my Minecraft clone open source? I'm developing in my spare time a game like Minecraft. In fact, it isn't "like Minecraft", because I'm trying to make it a close as possible copy of it (meant as exercise for myself at the age of 16 and simply because of it is fun to me). Of course, I'm not copying the code using the Minecraft Coder Pack (MCP). I started the game from scratch in Java using OpenGL. So, my question is am I allowed to put my source code online on a public source code versioning host like GitHub, Google Code, et cetera (which makes my code open source, because I don't want to pay to use a private host)? Of course, I don't want to sell the game, because the game is from Notch. A detail which might be important is that I'm using a custom texture pack (so, not the one that is shipped with the real Minecraft). If it is allowed, are there any rules? I took a look to this page, but it seems that he doesn't say anything about this http www.minecraft.net terms Edit There is the game called Terasology (started under the name Blockmania) from Begla. That is a nice project, but it is not meant to be as close as possible to Minecraft. That project is open source.


Is it possible to run GLFW eventhough my graphic card(Nvidia) supports Direct3d API? I have Nvidia 820M GPU installed in my windows 7 machine. In nvidia control panel it is showing it supports Direct3d API version 11. Am I able to run OpenGL applications(using GLUT,GLFW) on my machine with this configuration? see the below screenshot for configuration details.


Using compressed(ETC1) textures in LibGDX I use standard android tool for compressing PNG texture and archiving it with gzip android sdks tools etc1tool texture.png encodeNoHeader gzip texture.pkm Then I try to load it FileHandle file ... ETC1.ETC1Data data new ETC1.ETC1Data(file) ETC1TextureData td new ETC1TextureData(data, false) Texture texture new Texture(td) But I get an java.nio.BufferOverflowException inside ETC1Data (FileHandle pkmFile) constructor in new DataInputStream(new BufferedInputStream(new GZIPInputStream(pkmFile.read()))) int fileSize in.readInt() compressedData BufferUtils.newUnsafeByteBuffer(fileSize) int readBytes 0 while ((readBytes in.read(buffer)) ! 1) compressedData.put(buffer, 0, readBytes) Exception occurs here compressedData.position(0) compressedData.limit(compressedData.capacity()) How to fix it? Thanks. ps if it's important unarchived pkm file size is 33KB


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


How can I set up a pixel perfect camera using OpenGL and orthographic projection? I am creating a 2D game using OpenGL and orthographic projection. For sprites, I use textured quads (actually two triangles). I want the pixel art textures for the sprites to be displayed in a multiple of the original size to avoid blurry textures. How can I set up a pixel perfect camera using OpenGL and orthographic projection? After doing so, how do I size the qauds?


How do I apply 2 rotations about different points to a single primitive using OpenGL I'm working on a 2D top down shooter game that has a rotation feature like Realm Of The Mad God such that if you press e the camera rotates around the character in a clockwise direction and q rotates the camera around the character in a counterclockwise direction. I have this working with my floors and walls by translating to the character, doing the screen rotation, and drawing everything with the character as the origin. The problem arises when I shoot projectiles which need to both rotate around the character and rotate around themselves (shooting uses the mouse cursor so I can shoot at any angle). For example, if the screen is not rotated and I'm shooting rectangular projectiles, I want them to face in the direction I'm shooting (rotation around themselves). However if I only do this rotation, when I then rotate the screen the projectiles will always shoot at the same position because my cursor position does not change. Therefore I need to also either rotate the projectiles around the character or rotate the mouse cursor position to get the correct position (which would then totally screw up all of the collision detection). Likewise if I only do the screen rotation on projectiles, the rectangles will always be facing the same way and they would only look correct if I were shooting straight up or straight down. So my question is, how can I perform 2 rotations on a primitive around 2 different points? The only way I can think of is to translate to the character and do the screen rotation, then somehow calculate the translation required to move back to the middle of the projectile (seeing as how my axes are now rotated) and do its rotation. Or am I thinking about this in the wrong way and there is a different solution to accomplishing this effect?


Rotate heading relative to agent's local space I'm having a little trouble translating a point in my game's world space to an object's local space. I have a cannon in my game with a normalized heading vector that's always supposed to point in the direction of a target. The target is set by an incoming screen touch event. My problem is that the coordinates I get from the incoming touch events are relative to the game world's axis centered at the world's origin, not relative to the cannon's position like I need. The angle I calculate to rotate the heading is relative to the world's X axis, not the cannon's local X axis, this means I can never rotate the heading by anything outside of 0 lt x lt 90. I hope my crude drawing conveys what I mean. In the picture below, A is the cannon's position (with the blue heading vector), and B is the target's location (set by an event). The green line represents the angle the game is giving me, and the angle between red line and the heading is what I need to find (the little curved blue arrow). Here's the code I use to calculate the heading float xDistance target.x position.x float yDistance target.y position.y float angleToTurn (float) Math.atan2(yDistance, xDistance) vec2RotateAroundOrigin(heading, angleToTurn) Thanks in advance. Any help is greatly appreciated.


How to remove fragment from VAO? I have the OpenGL VAO object ( 40K) to draw the 3D scene glBindVertexArray(VAO) glDrawElements(GL TRIANGLES, 4, GL UNSIGNED BYTE, nullptr) glBindVertexArray(0) To add some data I can use glMapBuffer GLuint buffer glGenBuffers(1, amp buffer) glBindBuffer(GL ARRAY BUFFER, buffer) glBufferData(GL ARRAY BUFFER, (2 steps) sizeof(float), NULL, GL STATIC DRAW) float data (float ) glMapBuffer(GL ARRAY BUFFER, GL WRITE ONLY) myFuncAddingData(data, 2.4f, 40.0f, 19.0f ) glUnmapBuffer(GL ARRAY BUFFER) Can I to remove (hide mask) some verteces (3 from 40K) directly from the located in the grafical memory VAO without full complete replacement all of the 40K?


vec4 for vec3 multiplication while calculating the specular value I'm following this tutorial to calculate the specular color of a vertex. I use OpenGL 2.1 with GLSL version 120. This is the formula that I apply spec (R eye) s Ls Lm With L direction vector light vertex N vector normal eye direction vector vertex eye R 2N (L N) L Now the problem is that following this way I need to multiply a vec3 for a vec4. This is what I tried to do vec4 L normalize(gl LightSource 0 .position gl Position) vec3 N normalize (gl NormalMatrix gl Normal) vec4 eye normalize( gl Position) vec4 R 2.0 N (L N) L Syntax error N is a vec3 vec4 spec (R eye) gl LightSource 0 .specular I wouldn't get a vec3 result when calculating the specular value, this value I would be ignoring the alpha value. How do I go around this?


Cannot Draw a triangle without VAO on MacOS So I was watching Cherno's Video on Vertex attributes and he was successful in drawing a triangle without a VAO, but in tutorials from learnopengl.com they specifically say they we need a VAO to draw VBO and I tested it and it works fine. Here is my snippet glGenVertexArrays(1, amp VAO) glBindVertexArray(VAO) glGenBuffers(1, amp VBO) glBindBuffer(GL ARRAY BUFFER, VBO) glBufferData(GL ARRAY BUFFER, sizeof(triangleVertices), triangleVertices, GL STATIC DRAW) glVertexAttribPointer(0, 3, GL FLOAT, GL FALSE, 3 sizeof(GLfloat), (GLvoid )0) glEnableVertexAttribArray(0) Game Loop Loop until the user closes the window while (!glfwWindowShouldClose(window)) Poll for and process events glfwPollEvents() Render here glClearColor(0.2f, 0.3f, 0.3f, 1.0f) RGBA glClear(GL COLOR BUFFER BIT) glUseProgram(shaderProgram) glBindVertexArray(VAO) we did not unbind it so it's still binded to the assigned VAO glDrawArrays(GL TRIANGLES, 0, 3) Swap front and back buffers glfwSwapBuffers(window) This only works if I uncomment the VAO which is understandable, what I can't get my head around is how did Cherno got it working without a VAO and just using a VBO? Is it a MacOS specific thing?


Working towards going 3D I am a beginner intermediate C Java programmer and my long term goal is to be a game programmer. I have decided to start off with 2D and work my way towards 3D. I would like to use SDL to start off with, but I am wondering if it is maybe not such a great idea. Given the fact that I am working towards 3D, would it be advisable to use SDL or jump into OpenGL without the Z axis?


Why do I have to switch T(v) texture coordinates while importing OpenGL to Direct3D? I am importing my code from OpenGL to Direct3D. My D3DTS PROJECTION uses D3DXMatrixPerspectiveFovRH, and my D3DTS VIEW uses D3DXMatrixLookAtRH to set a view equal to OpenGL's view. My question is why do I have to switch all of my 1.0000 Tex(v) texture coordinates to "minus value" in D3D to get equal texture mapping as in OpenGL. OpenGL T(u) T(v) 1.0000, 1.0000, 0.0000, 1.0000, 1.0000, 0.0000, 1.0000, 0.0000, 0.0000, 1.0000, 0.0000, 0.0000, 0.0000, 1.0000, 0.0000, 0.0000, 1.0000, 1.0000, 1.0000, 1.0000, 0.0000, 0.0000, 1.0000, 0.0000, ... Direct3D T(u) T(v) D3DXVECTOR2( 1.0000f, 1.0000f) D3DXVECTOR2( 0.0000f, 1.0000f) D3DXVECTOR2( 1.0000f, 0.0000f) D3DXVECTOR2( 1.0000f, 0.0000f) D3DXVECTOR2( 0.0000f, 1.0000f) D3DXVECTOR2( 0.0000f, 0.0000f) D3DXVECTOR2( 0.0000f, 1.0000f) D3DXVECTOR2( 0.0000f, 0.0000f) D3DXVECTOR2( 1.0000f, 1.0000f) D3DXVECTOR2( 1.0000f, 1.0000f) D3DXVECTOR2( 0.0000f, 0.0000f) D3DXVECTOR2( 1.0000f, 0.0000f) ... Is it because Direct3D's origin (0.0) of texture coordinates lies in different place than in OpenGL?


Storing rendering data for voxel game 1 VAO and VBO or 1 for every chunk I have a minecraft style voxel game with placing and digging blocks. it runs at 400 fps on my computer but when I added semi transparent water it started running at 40 fps. so a time per frame increase of 0.0175s or 8 times what is used to be. What I am currently doing is having a VAO and VBO for each chunk and every time a chunk is changed or loaded it finds all of the non occluded blocks and puts their positions into another buffer in the chunk. then I use instancing to render the whole chunk in one draw call so every frame I am doing 300 draw calls. Once I added the water(using order independent transparency http www.openglsuperbible.com 2013 08 20 is order independent transparency really necessary ) I was individually calling gldrawelements() for every visible water block so around 9000 if half the visible area is ocean. I know using instancing with these blocks would help but then I have 2 VAOs for every chunk and 600 draw calls of buffers with only a couple hundred blocks in them. would there be a better way to organize these things.


OpenGL only rendering 4 tris of cube? I'm on Win10, OpenGL 4.5 I wrote some code that takes mesh data from an OBJ file and puts it into a vertex buffer. I used this code to import a cube OBJ and render it in OpenGL. For some reason, although the importer output shows that all tris (broken down into vert components) were put into the buffer, the actual rendered cube only has 4 tris showing. What could be happening here? Here is my relevant code Before the main loop Import mesh data OBJ amp cube ImportOBJ( quot meshes cube.obj quot ) Bind mesh data GLuint vertexArrID glGenVertexArrays(1, amp vertexArrID) glBindVertexArray(vertexArrID) GLuint vertexBufferID glGenBuffers(1, amp vertexBufferID) glBindBuffer(GL ARRAY BUFFER, vertexBufferID) glBufferData(GL ARRAY BUFFER, cube.vertBufferSize, cube.vertBuffer, GL STATIC DRAW) Inside the main loop Draw cube glDrawArrays(GL TRIANGLES, 0, cube.vertCount) glDisableVertexAttribArray(0) Here is what it looks like and here is the importer output broken down like face index vert index (x, y, z) 0 0 ( 0.5, 0.5, 0.5) 0 1 (0.5, 0.5, 0.5) 0 2 (0.5, 0.5, 0.5) 1 3 (0.5, 0.5, 0.5) 1 4 ( 0.5, 0.5, 0.5) 1 5 (0.5, 0.5, 0.5) 2 6 ( 0.5, 0.5, 0.5) 2 7 ( 0.5, 0.5, 0.5) 2 8 ( 0.5, 0.5, 0.5) 3 9 (0.5, 0.5, 0.5) 3 10 ( 0.5, 0.5, 0.5) 3 11 ( 0.5, 0.5, 0.5) 4 12 (0.5, 0.5, 0.5) 4 13 (0.5, 0.5, 0.5) 4 14 (0.5, 0.5, 0.5) 5 15 ( 0.5, 0.5, 0.5) 5 16 (0.5, 0.5, 0.5) 5 17 ( 0.5, 0.5, 0.5) 6 18 ( 0.5, 0.5, 0.5) 6 19 ( 0.5, 0.5, 0.5) 6 20 (0.5, 0.5, 0.5) 7 21 (0.5, 0.5, 0.5) 7 22 ( 0.5, 0.5, 0.5) 7 23 ( 0.5, 0.5, 0.5) 8 24 ( 0.5, 0.5, 0.5) 8 25 ( 0.5, 0.5, 0.5) 8 26 ( 0.5, 0.5, 0.5) 9 27 (0.5, 0.5, 0.5) 9 28 (0.5, 0.5, 0.5) 9 29 ( 0.5, 0.5, 0.5) 10 30 (0.5, 0.5, 0.5) 10 31 (0.5, 0.5, 0.5) 10 32 (0.5, 0.5, 0.5) 11 33 ( 0.5, 0.5, 0.5) 11 34 (0.5, 0.5, 0.5) 11 35 (0.5, 0.5, 0.5)


Improve opengl drawing with less calls as possible I'm looking to render rectangle primitives as performant as possible, here's what I did so far int main() Window window("OpenGL", 800, 600) Shader shader(". file.shader") float vertices 8 glGenVertices(vertices, 200, 150, 400, 300) return coords for a square const GLshort indices 6 0, 1, 2, 2, 3, 0 GLuint vao, vbo, ebo glGenVertexArrays(1, amp vao) glBindVertexArray(vao) glGenBuffers(1, amp vbo) glBindBuffer(GL ARRAY BUFFER, vbo) glBufferData(GL ARRAY BUFFER, sizeof(vertices), vertices, GL STATIC DRAW) glEnableVertexAttribArray(0) glVertexAttribPointer(0, 2, GL FLOAT, GL FALSE, 0, 0) glGenBuffers(1, amp ebo) glBindBuffer(GL ELEMENT ARRAY BUFFER, ebo) glBufferData(GL ELEMENT ARRAY BUFFER, sizeof(indices), indices, GL STATIC DRAW) while(window.isOpen()) window.clear() shader.use() glDrawElements(GL TRIANGLES, 6, GL UNSIGNED SHORT, NULL) shader.setUniforms(..) glDrawElements(GL TRIANGLES, 6, GL UNSIGNED SHORT, NULL) window.update() glDeleteBuffers(1, amp vbo) glDeleteBuffers(1, amp ebo) glDeleteVertexArrays(1, amp vao) return 0 So far what I'm doing to fix my problem and seems to work Created vao, vbo and ebo to make a basic indexed rectangle. Made a function that will returns vertices coordinates based position and sizes(x, y, w, h) Create one single shader and set uniforms like position offsets, sizes and eventualy colors textures after every draw call to be able to render shapes in different places ( that makes the coordinates function useless) I'm pretty sure that's not the way to do it, but can't find something else, so this is what I'm thinking. Heard that switching shaders is expensive, but I'll require shapes that won't share the same shader.. Also heard that setting uniforms is slower than switching shaders, so probalby switching shaders will be better here, need to profile the code to see. Currently drawing one by one with glDrawElements seems hardcoded and inefficient to me, need something like a vao that could store multiple rectangular like indexedvbo all preloaded before drawing and when it goes to drawing, draw all the data with one call. Not sure if I can load shaders between drawing, some of them will require changing while drawing like a hover or click effect, maybe there's better practices here too. At the end, if you've been through this issue or having some tips docs source codes to read, it'll be excellent, thanks! BIG NOTE Mostly looking for 2d support, no 3d needed in case this could make it harder.


How to obtain touch events from a GL Viewport, not the whole screen? Background I'm implementing viewport resizing in order for my game to maintain the same display ratio on all devices. However, I've found an issue with getting touch events. Basically, if my viewport, for example, uses the whole of the physical screen's width and height then there is no issue. However, if it is resized say in the vertical, then my touch events are thrown off, because touch events are registered from the top of the physical screen. Hence if I put a sprite at say position 50 in the Y direction then it put's the sprite 50 pixels down from the top of the viewport, not the top of the actual screen. Do I have to manage this myself by adding my viewport's offset to my touch events or is there a way to tell Android to register 0, as the top of the viewport as opposed to the actual screen. Here is a graphic to illistrate what I mean, any help would be appreciated


Modern opengl for direct3d programmers I don't think this is quite the same questions as this one but if you disagree feel free to close this ) With SteamOS being announced yesterday I can see that it's entirely possible that opengl will get a big boost in usage in the near future. Now I already know direct3d11 quite well but I think maybe it's time to learn opengl too. Are there any good resource for learning modern opengl that are aimed at programmers who already know direct3d11 pretty well. So don't need any education on the concepts and math, just on how to use the API and any important differences?


Front Face Culling with Shadowmapping To avoid shadow acne I usualy use front face culling which works great. But for my current implementation the mesh is a quite complex terrain (depending on the lod level) and than the shading (dot product of the normals face with the negative light direction) is not always correct as some normals are actually facing the light. But still there is no information in the shadowmap to shadow these fragments in the shadowmap because of the front face culling ( like it is not exact enough). What I end up with, is that there are some bright spots in the shadowed area. I am not really sure why this does not work, because that would mean, that the front face culling is also culling some back faces, if the mesh has a very high level of detail, right? In the Image with Front Face Culling (top picture) you can see these bright lines in the shadowed area where as without FF Culling (bottom image) the shadowed area is completely black. My current workaround is, that I check the highest LOD level that is currently displaying and than according to that switch back an forth between ff culling and bias. I use OpenGL The front face culling glEnable(GL CULL FACE) glCullFace(GL FRONT) The shading in the fragment shader float shading max(dot(normal, lightDir), 0.0)


Soft Body rendering from OBJ model As part of my master thesis I have to do an softbody simulation. I 'm using Bullet Physics engine. I'm trying to render softbody, create from Meshes, with Shaders in OpenGL but the object doesnt seem to be rendered (it doesnt appear in the window). I'm not sure if the problem is because of the way I created the sobtbody or the way I render it. Thank you in advance. I'm using this function for creating a softBody from my OBJ Liver model btScalar verti new btScalar 3 (Liver.getMeshes() 0 .vertices.size()) for (int i 0 i lt Liver.getMeshes() 0 .vertices.size() i ) verti 3 i Liver.getMeshes() 0 .vertices i .Position.x verti 3 i 1 Liver.getMeshes() 0 .vertices i .Position.y verti 3 i 2 Liver.getMeshes() 0 .vertices i .Position.z int indi new int Liver.getMeshes() 0 .indices.size() for (int i 0 i lt Liver.getMeshes() 0 .indices.size() i ) indi i Liver.getMeshes() 0 .indices i btSoftBody LiverSBody btSoftBodyHelpers CreateFromTriMesh(softBodyWorldInfo, verti, amp indi 0 , int(Liver.getMeshes() 0 .indices.size()) 3) LiverSBody gt m cfg.kVC 0.5 btSoftBody Material pSpMat LiverSBody gt appendMaterial() LiverSBody gt m materials 0 gt m kLST 0.5 pSpMat gt m kLST 1.0 LiverSBody gt setPose(false, true) btTransform trans trans.setIdentity() trans.setOrigin(btVector3(0,0,0)) LiverSBody gt transform(trans) LiverSBody gt generateBendingConstraints(2, pSpMat) LiverSBody gt m cfg.piterations 2 LiverSBody gt m cfg.kDF 1.0 LiverSBody gt m cfg.kSRHR CL 1 LiverSBody gt m cfg.kSR SPLT CL 0 LiverSBody gt setTotalMass(10, true) LiverSBody gt scale(btVector3(0.02, 0.02, 0.02)) LiverSBody gt getCollisionShape() gt setMargin(0.1) float Friction 0.9 float Restitution 0.5 LiverSBody gt setFriction(Friction) LiverSBody gt setRestitution(Restitution) m pSoftBodyWorld gt addSoftBody(LiverSBody) I'm using this class for loading and visualizing model https learnopengl.com code viewer gh.php?code includes learnopengl model.h I need to extract from the softBody some data (Position, normal, texCoords, tangent and bitangent) to fill the vertex buffer objects but i don't know where to find most of it... I know that the position and the normals are in the softbody nodes but i can't find the other information needed (texCoords, ..). btSoftbody.h struct Node Feature btVector3 m x Position btVector3 m q Previous step position btVector3 m v Velocity btVector3 m f Force accumulator btVector3 m n Normal btScalar m im 1 mass btScalar m area Area btDbvtNode m leaf Leaf data int m battach 1 Attached


Why does my terrain texture fail to load? (OpenGL) I'm currently using a vertex shader and a fragment shader for loading my texture onto the terrain I made. Here is my vertex shader version 330 core layout (location 0) in vec3 aPos layout (location 1) in vec3 aNormal uniform mat4 model uniform mat4 view uniform mat4 projection float scale 0.5 out vec2 TexX out vec2 TexY out vec2 TexZ out vec3 blend weights void main() vec3 blend weights abs(aNormal.xyz) blend weights (blend weights 0.2) 0.7 blend weights max(blend weights, 0) blend weights (blend weights.x blend weights.y blend weights.z) TexX aPos.yz scale TexY aPos.zx scale TexZ aPos.xy scale gl Position projection view model vec4(aPos, 1.0) And here is my fragment shader. version 330 core out vec4 FragColor uniform sampler2D terrainTexture in vec2 TexX in vec2 TexY in vec2 TexZ in vec3 blend weights void main() FragColor texture(terrainTexture, TexX) blend weights.x texture(terrainTexture, TexY) blend weights.y texture(terrainTexture, TexZ) blend weights.z I was trying to implement 3D texture planar projections, based on section 1.5 of this link https developer.nvidia.com gpugems GPUGems3 gpugems3 ch01.html If I just try to implement the texture in a very simple way, it works (which looks terribly stretched on the mountanous terrains, of course). But if I implement it this way, the texture does not load. What could be the possible reason? Just in case anyone is wondering, the following is my VAO, VBO, EBO configuration VAO, VBO configuration unsigned int VAO, VBO, EBO glGenVertexArrays(1, amp VAO) glGenBuffers(1, amp VBO) glGenBuffers(1, amp EBO) glBindVertexArray(VAO) glBindBuffer(GL ARRAY BUFFER, VBO) glBufferData(GL ARRAY BUFFER, positions.size() sizeof(glm vec3) normals.size() sizeof(glm vec3) , NULL, GL STATIC DRAW) glBufferSubData(GL ARRAY BUFFER, 0, positions.size() sizeof(glm vec3), amp positions 0 ) glBufferSubData(GL ARRAY BUFFER, positions.size() sizeof(glm vec3), normals.size() sizeof(glm vec3), amp normals 0 ) glBindBuffer(GL ELEMENT ARRAY BUFFER, EBO) glBufferData(GL ELEMENT ARRAY BUFFER, indices.size() sizeof(int), amp indices 0 , GL STATIC DRAW) glEnableVertexAttribArray(0) glVertexAttribPointer(0, 3, GL FLOAT, GL FALSE, 3 sizeof(float), 0) glEnableVertexAttribArray(1) glVertexAttribPointer(1, 3, GL FLOAT, GL FALSE, 3 sizeof(float), (void )(positions.size() sizeof(glm vec3))) This is my draw function Inside the render loop void drawScene(Shader amp shader, unsigned int VAO, unsigned int numIndices, unsigned int texture1) draw the scene with the parameter data. glm mat4 model model glm translate(model, glm vec3( (int)(gridXNum) 2, 0.0f, (int)(gridZNum) 2)) glm mat4 view camera.GetViewMatrix() glm mat4 projection glm perspective(glm radians(camera.Zoom), (float)SCR WIDTH (float)SCR HEIGHT, 0.1f, 100.0f) shader.use() shader.setMat4("model", model) shader.setMat4("view", view) shader.setMat4("projection", projection) shader.setFloat("TERRAIN WIDTH",gridXNum) glActiveTexture(GL TEXTURE0) glBindTexture(GL TEXTURE 2D, texture1) glBindVertexArray(VAO) glDrawElements(GL TRIANGLE STRIP, numIndices, GL UNSIGNED INT, 0) glBindVertexArray(0) However, I really don't think this is the problem because as I said, if I change the shader codes into a really basic one, the texture successfully loads. There is definitely something wrong with my shader program. Any help would be appreciated. Thanks in advance!


Nvidia RTX ray tracing OpenGL extension I can't seem to find any OpenGL headers for the RTX ray tracing extension, seems like they only want you to use Vulkan and optix with RTX


i need suggestion animation technique for 3d? firstly you need to now i am beginner ) i am using opengl and for display vertex buffer object(vbo). i made 2000 frames animation model with blender and i export with (.obj) files and i upload all these 2000 obj files to my opengl project. But upload process is taking too much time. like 7 8min and this method use too much vram around 2 3gb. Despite all this i'm glad draw performance because when i draw 100 animation(same model) at the same time my pc using 1 2 cpu and 70 80gpu. Now i want to learn is there another method of good draw performance and low system consumption ? (i want to draw 100 and much more animation model at the same time)


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


For voxel rendering, what is more efficient pre made VBO or a geometry shader? Given a fairly static voxel array, what is more efficient using the CPU to pre generate a VBO to render the voxel faces (ignoring more advanced forms of rendering like marching cubes for now) or using a geometry shader on the GPU to generate the faces on the fly? I'm not that worried about updating changing voxels but of course that is a benefit of the GPU version since you don't have to rebuild the VBOs. Also, the GS approach feels a bit more modern ) On the other hand, I haven't looked at the details on how a GS actually works with the rasterization pipeline in modern GPUs. Does it output the vertices into a sort of stream cache or is the vertices written to the normal GPU memory in between? If it's the latter, then on the fly generating could reduce the available bandwidth and processing power from the rest of the GPU tasks I guess and then it would be more beneficial to do it on the CPU..


How to correctly setup latest LWJGL libraries to Eclipse? A year ago, I understood how to setup an LWJGL project in Eclipse IDE. Now LWJGL has a lot of changes including a different file structure. I downloaded the latest release, LWJGL 3.1.0 Build 40 from the official site. There's also a page explaining how to get started, but it does not help me to set it up in Eclipse. When I extract the downloaded .zip file, I only get .jar files (and .txt licences). I see nowadays there are no .dll natives for a specific operating system. Instead of that, I see jars like lwjgl glfw natives windows.jar. I expect these are now the files that were previously .dll files. Can someone explain to me how to set it all up correctly?


Having issue's with a confusing access violation? C , OpenGL 3.3 , SDL 2.0 Hello this code seems so well done and yet I'm getting this weird access violation error when I use anything but 0 in glShaderSources 2nd argument glShaderSource( fragshader, 0, fragfilebuff, NULL ) If I use lenofstr or any other number then 0 it calls up an error like this I have no idea for the life of me why this is happpening I've updated my drivers , I've even tried messing around with glewInit() too see if it's something to do with that but no luck what so ever. This nvidia dll has some problem with my code and I don't know why?... void LoadShaders(const char fragshaderfn, const char vertshaderfn) FILE fragfile const GLchar fragfilebuff 256 0 fopen s( amp fragfile, fragshaderfn, "r") fread(fragfilebuff, sizeof(char), sizeof(char) 256, fragfile) printf(fragfilebuff) GLsizei lenofstr strlen(fragfilebuff) printf("this is the length gt d", lenofstr) GLuint fragshader glCreateShader(GL FRAGMENT SHADER) glShaderSource(fragshader, 0, fragfilebuff, NULL) glCompileShader(fragshader) Here's the complete source include lt SDL.h gt include lt GL glew.h gt include lt SDL opengl.h gt include lt stdio.h gt include lt conio.h gt define SCREEN HEIGHT 480 define SCREEN WIDTH 640 SDL Renderer mainrenderer SDL Window mainwindow SDL Event event bool running true void LoadShaders(const char fragshaderfn, const char vertshaderfn) FILE fragfile const GLchar fragfilebuff 256 0 fopen s( amp fragfile, fragshaderfn, "r") fread(fragfilebuff, sizeof(char), sizeof(char) 256, fragfile) printf(fragfilebuff) GLsizei lenofstr strlen(fragfilebuff) printf("this is the length gt d", lenofstr) GLuint fragshader glCreateShader(GL FRAGMENT SHADER) glShaderSource(fragshader, lenofstr, fragfilebuff, NULL) glCompileShader(fragshader) int main(int argc , char argv) SDL Init(SDL INIT EVERYTHING) mainwindow SDL CreateWindow( "C OpenGL Engine", 300, 300, 640, 480, SDL WINDOW SHOWN SDL WINDOW OPENGL ) SDL GLContext maincontext SDL GL CreateContext(mainwindow) SDL GL MakeCurrent(mainwindow, maincontext) glewExperimental GL TRUE GLenum err glewInit() if (GLEW OK ! err) Problem glewInit failed, something is seriously wrong. fprintf(stderr, "Error s n", glewGetErrorString(err)) fprintf(stdout, "Status Using GLEW s n", glewGetString(GLEW VERSION)) if (SDL GL SetSwapInterval(1) lt 0) printf("Warning Unable to set VSync! SDL Error s n", SDL GetError()) LoadShaders("ffile.frag", "") glClearColor(0.0, 0.0, 0.0, 1.0) while (running true) while (SDL PollEvent( amp event)) switch (event.type) case SDL QUIT SDL GL DeleteContext(maincontext) SDL Quit() return 0 break glClear(GL COLOR BUFFER BIT GL DEPTH BUFFER BIT ) SDL GL SwapWindow(mainwindow) SDL GL DeleteContext(maincontext) SDL DestroyWindow(mainwindow) SDL Quit() return 0 All help would be appreciated I am using C , SDL 2.0 and OpenGL 3.3 , MSVC 2015 , Win10 64bit


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.


glDrawElements vs glDrawArrays for polygons that do not reuse vertices Is it better to use glDrawElements or glDrawArrays when not reusing vertices? There must be some difference, otherwise people would always use glDrawElements? I suppose the question could be reworded as the following Does glDrawElements function the same as glDrawArrays if it is passed a blank indices table?


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


Frustum culling only working at certain angles So how I'm doing this is a little sketchy but I plan on changing it to either AABBs or spheres once I get it working. So the problem I'm having right now is that the frustum culling I've implemented is only working at certain angles and is not even close to accurate, personally I believe that the problem is at a calculation level. I am fairly new to 3D game development so I just whipped up this class fairly quickly based on some thread I read. My ViewFrustum class can be found here https www.dropbox.com s 3b97bgcwoyh2oq8 ViewFrustum.java?dl 0 So all I'm doing outside this class is calling the update method from my renderer class and I have an ungodly amount of if statements checking if an entity's xyz is within the min and max xyz of the frustum (This is temporary). So my main question is, am I calculating the frustum right or did I make any mistakes? Values (when game starts, rotation matrix is a identity matrix) centerNear 134.49167, 7.3502045, 271.4365 centerFar 134.49167, 7.3502045, 1170.7365 points 0 7 0 2607.2214 1714.3507 621.8992 1.0 1 2338.238 1714.3507 621.8992 1.0 2 2607.2214 899.70605 1573.3379 1.0 3 2338.238 899.70605 1573.3379 1.0 4 136.4149 100.760254 252.18294 1.0 5 132.56844 100.760254 252.18294 1.0 6 136.4149 98.727104 252.92294 1.0 7 132.56844 98.727104 252.92294 1.0


JOGL KeyListener not functioning properly I have been having a problem with the JOGL KeyListener where if I hold down a key, it would register the key as pressed for around 1 second, then it would start quickly switching back and forth between pressed and unpressed. However, if I hold more than one key at once, sometimes the key listener "forgets" about one of the keys and keeps it held down (like it should) while releasing the other one (when it shouldn't). Here is the relevant code in the class import com.jogamp.newt.event.KeyEvent import com.jogamp.newt.event.KeyListener import java.util.HashSet import java.util.Set public class KeyInput implements KeyListener private static Set lt Short gt key new HashSet lt Short gt () public void keyPressed(KeyEvent keyEvent) key.add(keyEvent.getKeyCode()) System.out.println("added " keyEvent.getKeyChar()) public void keyReleased(KeyEvent keyEvent) key.remove(keyEvent.getKeyCode()) System.out.println("removed " keyEvent.getKeyChar()) public static boolean getKey(short k) return key.contains(k) I tried using other methods of storing the keys to no avail. How should I fix it so that it properly registers and remembers held down keys? I tried a different program with Swing and it worked fine. It has the exact same code as shown here.


Quaternion Rotation after performing previous rotations Have Quaternion Q which is rotated on the X axis 90 degrees. Q is now (0.707106, 0.707106, 0, 0) . I want to rotate Q another 90 degrees by a different pivot P so i will calculate Q P Q 1 , save the x,y,z coordinates in res(x,y,z) and then res res P . This should give me the offset between the new coordinates and the old ones, however in my case i get a big translation on the Y axis. Example 1 Here i do both rotations around the same pivot, compared to first center then pivot. Example 2 i do both rotations around the same point C( 0.5,0.5,0.5) if it matters, for the second rotation i first rotate the pivot with the current rotation to get actual coordinates of the pivot. I do all calculations in object space where the object center is at 0,0,0 EDIT CODE Before i start a rotation i calculate where the pivot should be at the current rotation like this, it only happens when there are no active rotations, i choose to rotate by vertices 3 state.currentPivot state.rotation vertices 3 this is the part of the update function that gets executed during rotations for (auto amp rotationRule v rotationRules) if (deltaTime gt rotationRule.startTime amp amp deltaTime lt rotationRule.endTime) state.rotation glm rotate(state.rotation, glm radians(rotationRule.degrees), rotationRule.axis) state.rotateAroundPivotWithQuat() TranslationMatrix glm translate(glm mat4(1.0f), state.rotatedPosition()) ModelMatrix TranslationMatrix glm mat4 cast(state.rotation) ScaleMatrix glm vec3 ObjectState rotatedPosition() return position rotationOffSet void ObjectState rotateAroundPivotWithQuat() glm vec3 negp currentPivot glm vec3 res rotation negp rotationOffSet res currentPivot When a rotation is over i add position rotationOffSet, happens at the end of it, and make it equal to (0,0,0) again. in the gifs, the first value of rotationOffSet has the high offset on y axis, as i checked in debugger.


OpenGL Colour Issues I am using a single VBO to store vertices in the follow format v1X, v1Y, v1Z, v1R, v1G, v1B, v2A, v2X, ... Vertex positioning is fine, shapes show up where expected, however instead of using the colour provided, all shapes show up red. The code given below simply draws two triangles to form one square ground shape. Buffer data preparation method public void prepare(float data) glBindBuffer(GL ARRAY BUFFER, vboID) FloatBuffer dataBuffer RenderUtils.fArrayToBuffer(data) if(dataLength ! data.length) glBufferData(GL ARRAY BUFFER, dataBuffer, GL STATIC DRAW) dataLength data.length else glBufferSubData(GL ARRAY BUFFER, 0, dataBuffer) glVertexAttribPointer(0, 3, GL FLOAT, false, 7 4, 0) glVertexAttribPointer(3, 4, GL FLOAT, false, 7 4, 3 4) Render code floorObj.prepare(new float 5, 0, 5, 1, 0, 0, 1, 5, 0, 5, 0, 1, 0, 1, 5, 0, 5, 0, 0, 1, 1, 5, 0, 5, 1, 0, 0, 1, 5, 0, 5, 0, 1, 0, 1, 5, 0, 5, 0, 0, 1, 1, ) glDrawArrays(GL TRIANGLES, 0, 6) Vertex shader version 330 core in vec3 position in vec4 i color out vec4 color uniform mat4 transform void main() gl Position transform vec4(position, 1) color i color Fragment shader version 330 core in vec4 color out vec4 f color void main() f color color As previously stated, vertex positions work fine, however colour does not. Just ask if any other code would be useful to determine the problem. Thanks, Jasper


What is the best way of storing transformations for an object and then applying them with OpenGL? First some background info... I have been working on a platformer game, which I draw with OpenGL. The platforms are cubes and the player is a cube. The platforms and the player (both cubes) are given a position, from which the vertices should be drawn. However, the first cube is at position 0, 0, 0 and I would like the player to be on top of this cube. The size of the cubes and player is 0.5, 0.5, 0.5 initially. However, I didn't manage to get the player on 0, 1, 0 (cubes are drawn from their center point I remembered), because the scaling didn't seem to work, which led me to believe the method I'm using to store the translations and scaling is inherently bad. I am currently storing the translations and scaling in a matrix, which is part of the object. The object also holds the vertices and the VBO. Let's call it class Cube, which thus holds glm mat4 m transform. I expose m transform and pass it with glUniformMatrix4fv(shader.GetUniformLocation("model"), 1, GL FALSE, glm value ptr(m transform)) And at some point I call glDrawArrays(GL TRIANGLES, 0, 36) to draw the platform player cube. So to alter the position of such a cube, I would alter m transform. Such as m transform glm translate(m transform, vec) where glm vec3 vec is the desired translation to apply. However, the issues arise when u wish to scale a cube as well, so if we scale with vec3(0, 2, 0), the translations will be twice as large. And I'm unsure where to go from here. I've read that having different matrices for translation, rotation and scaling is the way to go, which I will try, however, I would like to know what the best practices are surrounding this subject. Any suggestions are much appreciated!


Most efficient way of brighten and darken sprites with OpenGL 2.0 So I have been shading (brighten darken adding color) my sprites by using glTexEnvf with GL MODULATE and GL ADD and a vertex color. I only had to rebind the batch every time I needed to change from modulate to add and vice versa. it was not perfect but worked well enough. However libGDX 1.0 dropped support for OpenGL1.1 and the only way I see is to use shaders. I want to stay up to date and therefore want to update. I am new to shaders but I found some code that works to brighten a sprite. However as far as I understood I need to rebind the batch every time I want another value for my brightness batch binding on every sprite I render. That is not very performant. Is there a way to change values between the bindings? (I don't think it's possible because shaders get compiled afaik). Or do you have another idea how to archive this effect with openGL2.0 (like I did before)? Or is rebinding every sprite the most efficient way with OpenGL2.0?


glsl directional light specular seems to be relative to origin not camera I've been using the LearnOpenGL tutorials to calculate directional light. The diffuse works perfectly fine but the specular seems only work properly when the camera is near the origin and the specular is applied the same to all objects. When I look at the second to last object i expect the specular to be the same as the object around the origin but instead it seems reacts to the origin and not the camera. My guess is it's something to do with converting something to model space instead of camera space but as i'm new to glsl i'm lost as to where to look first. Vertex shader version 330 core layout (location 0) in vec3 vertexPosition layout (location 1) in vec2 vertexUV layout (location 2) in vec3 vertexNormal out vec3 VectorWorldPosition out vec2 UV out vec3 Normal cameraspace uniform mat4 MVP uniform mat4 V uniform mat4 M void main() gl Position MVP vec4(vertexPosition, 1.0f) VectorWorldPosition (M vec4(vertexPosition, 1.0f)).xyz Normal cameraspace vertexNormal (M V vec4(vertexNormal, 1.0f)).xyz UV vertexUV Fragment Shader version 330 core in vec3 vertexWorldPosition in vec2 UV in vec3 Normal cameraspace out vec4 color struct DirectionalLight vec3 position vec3 ambient vec3 diffuse vec3 specular struct Material sampler2D diffuse sampler2D specular float shininess uniform DirectionalLight dirLight uniform Material material uniform vec3 viewPos vec3 CalcDirectionalLight(DirectionalLight light, vec3 normal, vec3 viewDir) void main() vec3 output vec3(0.0f) vec3 norm normalize(Normal cameraspace) vec3 viewDir normalize(viewPos vertexWorldPosition) output CalcDirectionalLight(dirLight, norm, viewDir) color vec4(output, 1.0f) vec3 CalcDirectionalLight(DirectionalLight light, vec3 normal, vec3 viewDir) vec3 lightDirection normalize(light.position) float diff clamp(dot(normal, lightDirection), 0.0, 1.0) vec3 reflectDir reflect( lightDirection, normal) float spec pow(max(dot(viewDir, reflectDir), 0.0), material.shininess) vec3 ambient light.ambient vec3(texture(material.diffuse, UV)) vec3 diffuse light.diffuse diff vec3(texture(material.diffuse, UV)) vec3 specular light.specular spec vec3(texture(material.specular, UV)) return (ambient diffuse specular) I'm using light position here when the tutorial asks to use direction. My thinking is that relative to the origin, position will be equal to direction. This works fine for diffuse so it should it work for specular.


Modifying GLFW callbacks I'm currently using Imgui for the GUI part of my OpenGL C engine with the GLFW binding. The problem is though that this binding has encapsulated the input callbacks in a global .cpp file which makes it impossible to access for other classes. Now I could always use the regular routine to handle input without the callbacks like if(glfwGetKey(m window, GLFW KEY A) GLFW PRESS) ... but yet this won't give me the one to one mapping like the key callback provides as the conditional code is processed more than once. I have tried using static booleans without success to see if I could overcome the problem by setting the boolean to true when the key is pressed in the callback and then handling the outcome elsewhere. I also know that you can override callbacks with different ones but that would not make any sence in this case. Does anyone know how to solve this problem?


Is GL DEPTH COMPONENT32 deprecated in OpenGL 4.5? I'm in the process of migrating our object oriented OpenGL wrapper from 3.3 core to 4.5 core. Some OpenGL implementations are notoriously permissive on what inputs they'll accept which can make tracking down bugs difficult. Wherever possible the inputs to our wrapper are validated with asserts to keep them in line with the spec. While setting up the asserts for glTextureStorage3D I've noticed that according to this page on the Khronos website it only accepts the following sized depth types GL DEPTH COMPONENT32F, GL DEPTH COMPONENT24, GL DEPTH COMPONENT16, GL DEPTH32F STENCIL8 or GL DEPTH24 STENCIL8. Non floating point 32bit depth types seem to be missing from that list which leads me to believe they're no longer supported (or at least actively discouraged). There's also this answer to another question which states that GL DEPTH COMPONENT32 is probably overkill, and as of 4.5, isn't a required format for OpenGL implementations to support (though 16 and 24 bit ones are). I have tried to find some reference to this in the 4.5 core spec but turned up nothing. Is GL DEPTH COMPONENT32 a deprecated size type? If so, why?


OpenGL Insanely Slow I'm learning C , and I'm writing my first OpenGL program. Unfortunately, it seems to be defaulting to Software Rendering (CPU uses bounces, GPU uses stays at 1 ). I'm using SDL as the Windowing system. I've got no idea why, but when there is significant scaling, the program grinds to a halt. My PC should be able to handle it I'm using an 8800GTX. My texture is 1024x1024, 32 bit RGBA and loaded with DevIL, and glGetString(GL VENDOR) is returning "NVidia Corporation". Any ideas? I'm sorry to be dumping all the code, but I've got absolutely no idea at all what is doing it. I'm very new to OpenGL. pragma once include "SDL.h" include "SDL opengl.h"7 include "IL il.h" include "IL ilut.h" include lt math.h gt const int SCREEN WIDTH 1024 const int SCREEN HEIGHT 768 const int SCREEN BPP 32 const int FPS 60 const int XSIZE 1024 const int YSIZE 768 int main( int argc, char argv ) bool quit false SDL Init(SDL INIT EVERYTHING) SDL GL SetAttribute(SDL GL DOUBLEBUFFER, 1) SDL GL SetAttribute(SDL GL RED SIZE, 8) SDL GL SetAttribute(SDL GL GREEN SIZE, 8) SDL GL SetAttribute(SDL GL BLUE SIZE, 8) SDL GL SetAttribute(SDL GL ALPHA SIZE, 8) SDL SetVideoMode(SCREEN WIDTH, SCREEN HEIGHT, SCREEN BPP, SDL HWSURFACE SDL OPENGL) glEnable(GL TEXTURE 2D) const GLubyte Vendor glGetString(GL VENDOR) glClearColor(0.0f, 0.0f, 0.0f, 1.0f) Clear the background of our window to red glMatrixMode (GL PROJECTION) glLoadIdentity () glOrtho(0, XSIZE, YSIZE, 0, 0, 1) glMatrixMode (GL MODELVIEW) glDisable(GL DEPTH TEST) GLuint image ilInit() ilutRenderer(ILUT OPENGL) ILuint texid ILboolean success ilGenImages(1, amp texid) ilBindImage(texid) success ilLoadImage("Textures.png") if (success) success ilConvertImage(IL RGBA, IL UNSIGNED BYTE) if (!success) SDL Quit() return 1 glGenTextures(1, amp image) glBindTexture(GL TEXTURE 2D, image) glTexParameteri(GL TEXTURE 2D, GL TEXTURE WRAP S, GL REPEAT) glTexParameteri(GL TEXTURE 2D, GL TEXTURE WRAP T, GL REPEAT) glTexParameteri(GL TEXTURE 2D, GL TEXTURE MAG FILTER, GL NEAREST) glTexParameteri(GL TEXTURE 2D, GL TEXTURE MIN FILTER, GL NEAREST) glTexImage2D(GL TEXTURE 2D, 0, ilGetInteger(IL IMAGE BPP), ilGetInteger(IL IMAGE WIDTH), ilGetInteger(IL IMAGE HEIGHT), 0, ilGetInteger(IL IMAGE FORMAT), GL UNSIGNED BYTE, ilGetData()) ilDeleteImages(1, amp texid) else SDL Quit() return 2 SDL Event event float x 0.0f while (!quit) while ( SDL PollEvent( amp event) ) switch (event.type) case SDL QUIT quit true break glClear(GL COLOR BUFFER BIT) glLoadIdentity() glTranslatef(200.0f, 200.0f, 0.0f) glRotatef(x,0.0f,0.0f, 1.0f) glScalef(1.0f x, 1.0f x, 1.0f x) glBegin(GL QUADS) glTexCoord2f(0.0f, 0.0f) glVertex2f( 100, 100) glTexCoord2f(0.0f, 0.119140f) glVertex2f( 100, 100) glTexCoord2f(0.091797f, 0.119140f) glVertex2f(100, 100) glTexCoord2f(0.091797f, 0.0f) glVertex2f(100, 100) glEnd() x 0.1f SDL GL SwapBuffers() glFlush return 0 Edit (24 04 2011 9.22 PM AEST) When run on an ancient card, on an ancient computer, it maintains 60FPS.


C Help with Separating Axis Theorem I am trying to detect collision between two triangles using Separating Axis Theorem however I am unaware what is wrong with my code. The CollisionHelper isTriangleIntersectingTriangle is called every frame and passes in the vertices of both triangles. It never returns true, however. I've been stuck on this for days now. Any help is appreciated. glm vec3 CalcSurfaceNormal(glm vec3 tri1, glm vec3 tri2, glm vec3 tri3) Subtracts each coordinate respectively glm vec3 u tri2 tri1 glm vec3 v tri3 tri1 glm vec3 nrmcross glm cross(u, v) nrmcross glm normalize(nrmcross) return nrmcross bool SATTriangleCheck(glm vec3 axis, glm vec3 tri1vert1, glm vec3 tri1vert2, glm vec3 tri1vert3, glm vec3 tri2vert1, glm vec3 tri2vert2, glm vec3 tri2vert3) int t1v1 glm dot(axis, tri1vert1) int t1v2 glm dot(axis, tri1vert2) int t1v3 glm dot(axis, tri1vert3) int t2v1 glm dot(axis, tri2vert1) int t2v2 glm dot(axis, tri2vert2) int t2v3 glm dot(axis, tri2vert3) int t1min glm min(t1v1, glm min(t1v2, t1v3)) int t1max glm max(t1v1, glm max(t1v2, t1v3)) int t2min glm min(t2v1, glm min(t2v2, t2v3)) int t2max glm max(t2v1, glm max(t2v2, t2v3)) if ((t1min lt t2max amp amp t1min gt t2min) (t1max lt t2max amp amp t1max gt t2min)) return true if ((t2min lt t1max amp amp t2min gt t1min) (t2max lt t1max amp amp t2max gt t1min)) return true return false bool CollisionHelper isTriangleIntersectingTriangle(glm vec3 tri1, glm vec3 tri2, glm vec3 tri3, glm vec3 otherTri1, glm vec3 otherTri2, glm vec3 otherTri3) Triangle surface normals, 2 axes to test glm vec3 tri1FaceNrml CalcSurfaceNormal(tri1, tri2, tri3) glm vec3 tri2FaceNrml CalcSurfaceNormal(otherTri1, otherTri2, otherTri3) glm vec3 tri1Edge1 tri2 tri1 glm vec3 tri1Edge2 tri3 tri1 glm vec3 tri1Edge3 tri3 tri2 glm vec3 tri2Edge1 otherTri2 otherTri1 glm vec3 tri2Edge2 otherTri3 otherTri1 glm vec3 tri2Edge3 otherTri3 otherTri2 axes TODO may need to (un)normalize the cross products glm vec3 axis1 tri1FaceNrml glm vec3 axis2 tri2FaceNrml glm vec3 axis3 glm normalize(glm cross(tri1Edge1, tri2Edge1)) glm vec3 axis4 glm normalize(glm cross(tri1Edge1, tri2Edge2)) glm vec3 axis5 glm normalize(glm cross(tri1Edge1, tri2Edge3)) glm vec3 axis6 glm normalize(glm cross(tri1Edge2, tri2Edge1)) glm vec3 axis7 glm normalize(glm cross(tri1Edge2, tri2Edge2)) glm vec3 axis8 glm normalize(glm cross(tri1Edge2, tri2Edge3)) glm vec3 axis9 glm normalize(glm cross(tri1Edge3, tri2Edge1)) glm vec3 axis10 glm normalize(glm cross(tri1Edge3, tri2Edge2)) glm vec3 axis11 glm normalize(glm cross(tri1Edge3, tri2Edge3)) Perform SAT if (SATTriangleCheck(axis1, tri1, tri2, tri3, otherTri1, otherTri2, otherTri3)) return true if (SATTriangleCheck(axis2, tri1, tri2, tri3, otherTri1, otherTri2, otherTri3)) return true if (SATTriangleCheck(axis3, tri1, tri2, tri3, otherTri1, otherTri2, otherTri3)) return true if (SATTriangleCheck(axis4, tri1, tri2, tri3, otherTri1, otherTri2, otherTri3)) return true if (SATTriangleCheck(axis5, tri1, tri2, tri3, otherTri1, otherTri2, otherTri3)) return true if (SATTriangleCheck(axis6, tri1, tri2, tri3, otherTri1, otherTri2, otherTri3)) return true if (SATTriangleCheck(axis7, tri1, tri2, tri3, otherTri1, otherTri2, otherTri3)) return true if (SATTriangleCheck(axis8, tri1, tri2, tri3, otherTri1, otherTri2, otherTri3)) return true if (SATTriangleCheck(axis9, tri1, tri2, tri3, otherTri1, otherTri2, otherTri3)) return true if (SATTriangleCheck(axis10, tri1, tri2, tri3, otherTri1, otherTri2, otherTri3)) return true if (SATTriangleCheck(axis11, tri1, tri2, tri3, otherTri1, otherTri2, otherTri3)) return true return false