How can I make OpenGL textures scale without becoming blurry? I'm using OpenGL through LWJGL. I have a 16x16 textured quad rendering at 16x16. When I change it's scale amount, the quad grows, then becomes blurrier as it gets larger. How can I make it scale without becoming blurry, like in Minecraft. Here is the code inside my RenderableEntity object public void render() Color.white.bind() this.spriteSheet.bind() GL11.glBegin(GL11.GL QUADS) GL11.glTexCoord2f(0,0) GL11.glVertex2f(this.x, this.y) GL11.glTexCoord2f(1,0) GL11.glVertex2f(getDrawingWidth(), this.y) GL11.glTexCoord2f(1,1) GL11.glVertex2f(getDrawingWidth(), getDrawingHeight()) GL11.glTexCoord2f(0,1) GL11.glVertex2f(this.x, getDrawingHeight()) GL11.glEnd() And here is code from my initGL method in my game class GL11.glEnable(GL11.GL TEXTURE 2D) GL11.glClearColor(0.46f,0.46f,0.90f,1.0f) GL11.glViewport(0,0,width,height) GL11.glOrtho(0,width,height,0,1, 1) And here is the code that does the actual drawing public void start() initGL(800,600) init() while(true) GL11.glClear(GL11.GL COLOR BUFFER BIT) for(int i 0 i lt entities.size() i ) ((RenderableEntity)entities.get(i)).render() Display.update() Display.sync(100) if(Display.isCloseRequested()) Display.destroy() System.exit(0)


How can I render a font in C with OpenGL? What I tried I was testing some things in order to render text with stb truetype.h and OpenGL in C. I took as a reference the example that appears here. Basically, this example, loads a .ttf file and returns the raw information in bytes, that can be used to generate a texture in OpenGL. I adapted the example, mentioned before, into modern OpenGL, because, the example uses OpenGL deprecated functions, like glVertex2f. The only thing I get to output on screen was this kind of noise of strange colors The code I use texture t fnt texture GLuint fnt shader unsigned char ttf buffer 1 lt lt 20 unsigned char temp bitmap 512 512 stbtt bakedchar cdata 96 ASCII 32..126 is 95 glyphs define FONT VS quot version 330 core n quot quot layout(location 0) in vec3 m Position quot quot layout(location 1) in vec2 m TexCoords quot quot out vec2 TexCoords n quot quot void main() n quot quot TexCoords m TexCoords n quot quot gl Position vec4(m Position, 1.0) n quot quot n quot define FONT FS quot version 330 core n quot quot in vec2 TexCoords n quot quot uniform sampler2D Texture n quot quot void main() n quot quot gl FragColor texture(Texture, TexCoords) n quot quot n quot void font init(void) fread(ttf buffer, 1, 1 lt lt 20, fopen( quot c windows fonts times.ttf quot , quot rb quot )) stbtt BakeFontBitmap(ttf buffer, 0, 32.0, temp bitmap, 512, 512, 32, 96, cdata) no guarantee this fits! glGenTextures(1, amp fnt texture 3 ) My texture type, is an array that saves the texture on the 3rd position. glBindTexture(GL TEXTURE 2D, fnt texture 3 ) glTexImage2D(GL TEXTURE 2D, 0, GL RGBA8, 512, 512, 0, GL RGBA, GL UNSIGNED BYTE, temp bitmap) glGenerateMipmap(GL TEXTURE 2D) can free temp bitmap at this point glTexParameteri(GL TEXTURE 2D, GL TEXTURE WRAP S, GL CLAMP TO EDGE) glTexParameteri(GL TEXTURE 2D, GL TEXTURE WRAP T, GL CLAMP TO EDGE) glTexParameteri(GL TEXTURE 2D, GL TEXTURE MIN FILTER, GL LINEAR) glTexParameteri(GL TEXTURE 2D, GL TEXTURE MAG FILTER, GL LINEAR) glBindTexture(GL TEXTURE 2D, 0) fnt shader shader init(FONT VS, FONT FS) void font render(model t model) shader bind(fnt shader) texture bind(fnt texture, 0) model begin(model) model draw(model, GL TRIANGLES) The model (vao, vbo, ibo) is rendering the whole buffer, not individual glyphs model end() texture unbind() shader unbind() Can someone tell me what I'm doing wrong, and, how I'm suposed to render correctly text, with modern OpenGL, with textures and buffers, in order to read the .ttf file and create the necessary information with stb truetype.h and, then, render the text?


Should I update VAO when I update a VBO? My VAO VBO IBO work fine on iPad and other devices on Android excepted two (A Samsung galaxy S4 and a Sony Xperia S). A problem is present when I start my application on this devices, every elements move everywhere and start to blink on each frame, the problem is present on every element updated during the simulation. I have a SpriteRenderer who share a VBO, so I need to update this VBO on each frame for each sprite (change color, uvs, ). The visual glitch is not present on static element (like text). So my question his Did I have to do something with my VAO on each frame? Here is what I've got Init part bind vao gt Bind vbo gt Bind ibo unbind vao Rendering part for( sprites ) Update (Need to bind VAO here?) bind vbo (lock) update vbo data unbind vbo (unlock bind) Draw. bind vao drawElement unbind vao Thanks!


Is Windows window creation faster more efficient than GLFW window creation? Are there any benefits to using Windows window for OpenGL or Vulkan rendering, rather than using GLFW window? Is there any performance hits when using C Window creation over GLFW since it provides OpenGL and Vulkan interface?


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


Alpha Blending performance on IOS I've got few questions without responses about my game development, can you help me? Here is the questions In my game when a large object appear on the screen, the GPU go to his limits, my framerate become very slow. How can I handle that? (I'm working on mobile). ( Currently, I'm sorting object from back to front) I've read some stuff about batching (How to draw efficiently large number of objects with alpha blending?), how can I handle batching when my game need to draw my scene from back to front with alpha blending? What is faster Add a condition to test pixel transparency in fragment shader or enable Alpha blending? (I've got colors around my sprites without alpha blending or condition) Thanks!


Posible to export f curves in blender? I work with some friends on a rail shooter game in openGL. For creating our world we are using Blender. Since we want our Tank to follow a path I have started to work with creating bezier curves and exporting them. That works, but takes a lot of time. Is it possible to export the f curves you use in the graph editor to an obj file or any other file that can be used to describe the position for a specific point in time? I would be grateful if someone has an idea that could be helpful.


Texture coordinates projection I have some classic texture coordinates and as a normal behaviour they follow the mesh's transformations. I am trying to use the same texture coordinates behaviour but without being affected by the mesh rotation transformation. The results would be a sort of texture coordinates projection. I don't know if my explanations are well explained but how could I achieve such effect. Thanks a lot.


What are some good learning resources for OpenGL? I have been using the OpenGL ES on the iPhone for a while now and basically I feel pretty lost outside to the small set of commands I've seen in examples and adopted as my own. I would love to use OpenGL on other platforms and have a good understanding of it. Every time I search for a book I find this HUGE bibles that seem uninteresting and very hard for a beginner. If I had a couple of weekends to spend on learning OpenGL what would be the best way to spend my time (and money)?


Rotation and translation like in GTA 1 OpenGL Okay, so I have a figure in XZ plain. I want to move it forward backward and rotate at it's own Y axis, then move forward again in the rotation's direction, like the character in GTA 1. Code so far Init spaceship position glm vec3(0,0,0) spaceship rotation glm vec3(0,0,0) spaceship scale glm vec3(1, 1, 1) Draw glm mat4 transform glm scale lt float gt (spaceship scale) glm rotate lt float gt (spaceship rotation.x, 1, 0, 0) glm rotate lt float gt (spaceship rotation.y, 0, 1, 0) glm rotate lt float gt (spaceship rotation.z, 0, 0, 1) glm translate lt float gt (spaceship position) drawMesh(spaceship, texture, transform) Update switch (key.keysym.sym) case SDLK UP spaceship position.z 0.1 break case SDLK DOWN spaceship position.z 0.1 break case SDLK LEFT spaceship rotation.y 1 break case SDLK RIGHT spaceship rotation.y 1 break So this only moves on the Z axis, but how can I move the object on both Z and X axis where the object is facing?


Most efficient way of drawing a lot of cubes OpenGL ES I have to draw a lot of cubes in my OpenGL programme for android. All the cubes have the same size but different colors. I know that calling glDrawArrays is expensive operation so I should call it less as possible. But as I know I have to call it 6 times (one per each side) and since I have more than 500 cubes it's not efficient at all. Does anyone have the idea what to do? Btw, I am using OpenGL ES 1.0. I saw that I can use one big VBO but I don't know how to do that.


How can I calculate the bounding box of a 3D model? I am making a game in OpenGL and Blender and trying to use JBullet as the collision manager. I am using BoxShapes for collisions, which requires a javax.vecmath.Vector3f representing half of the box to create. How do I calculate the dimensions (width, depth and height) of a Blender model in game?


Android OpenGLES, getting number of fragments passed depth test Occlusion Query? Afeter reading many blogs and searching on Internet, I did not get any sloution for getting number of fragments pixels which are occludded or not occludded of the object on OpenGL ES3.0 Android version. GL SAMPLES PASSED is not present on OpenGL ES3.0. Is there any way to get these occluded or non occluded fragments on Android OpenGl ES3.0?


Does swap buffer with vsynch guarantee synchronization? I was wondering if I could assume that all buffer related GPU operations such as glDrawElements glBufferData glSubBufferData glUnmapBuffer are guaranteed to be completed after swap buffer is performed (i.e. frame is finished) assuming vsync is on. I'm confused as I've come across implementations of vertex streaming techniques such as rond robin vbo which imply that a vbo could still be in use during the next frame. What I basically want to do is stream vertices through glMapBufferRange with GL UNSYNCHRONIZED BIT, managing the correct ranges myself so that writes and reads never overlap. This would work very well if I could just assume synchronization and reset the stream range index at the end of the frame. In other words, does swap buffer with vsynch guarantee synchronization?


Rotating a swinging sword in LWJGL gives wierd results I'm making a 2d top down game in Java using LWJGL(OpenGL, essentially). I recently tried adding a swinging sword mechanism. My coordinate system is set to the bottom left FOR ALL objects. The rotation worked, but it happens with respect to the bottom left corner of the Sword Quad. I want it to rotate with the center of the bottom line as the pivot for rotation. I tried a lot of solutions from the internet like translating the object to origin(0,0 of the screen), then rotating, then translate to the point of pivot. translating object normally, then rotating, then again translating to the point you want it to pivot at. But they all yield weird results. Here's the code The Sword Class public class Sword extends GameObject private static int speed 5, deg 0 private Texture tex public Sword(float x, float y, ObjectId id) super(x, y, id) tex ImageLoader.loadTexture(null, null) protected void update(ArrayList lt GameObject gt objects) if(deg lt 360) deg 1 else deg 0 protected void render() Draw.rect(x, y, 10, 32, deg, 1, 0, 0) public Rectangle getBounds() return null The Draw.rect method public static void rect( float x, float y, float width, float height, float deg, float r, float g, float b) glDisable(GL TEXTURE 2D) glPushMatrix() glTranslatef(0, 0, 0) glRotatef(deg, 0, 0, 1) glTranslatef(x (width 2), y, 0) glColor3f(r, g, b) glBegin(GL QUADS) Specifies to the program where the drawing code begins. just to keep stuff neat. GL QUADS specifies the type of shape you're going to be drawing. glVertex2f(0, 0) Specify the vertices. 0, 0 is on BOTTOM LEFT CORNER OF SCREEN. glVertex2f(0, height) 2f specifies the number of args we're taking(2) and the type (float) glVertex2f(width, height) glVertex2f(width, 0) glEnd() glPopMatrix() glEnable(GL TEXTURE 2D) EDIT Here is an image of what "weird result" is. In the pic, I'm translating first to origin (0, 0) of the WORLD , then rotating(by 90 degrees), then translating to translating to x (width 2) , y . As you can see, the red block that represents the sword is out of the "arena", even though I've set the x, and y of the sword to near the player. The image


Does it makes sense to apply perspective projection, in a 2D game? Does it makes sense to apply perspective projection, in a 2D game? What will be the cost for doing so, and does it overweigh the benefits gained from the 3rd dimension? Perspective projection has features that could be used in 2D games. Two very beneficial characteristics that come to my mind are Using perspective projection as a substitute for parallax scrolling. Using perspective projection to perform depth order for 2D sprites On the other hand, perspective projection resizes objects with distance, including 2D sprites. That is why mip mapping has been developed. Mip mapping, however, does not always produce perfect results, as it relies on interpolation between two neighboring mip mapped frames. This might not be sufficient, for a 2D game, where developers require pixel based precision and detail.


Bullet physics with OpenGL I have got some problem implementing bullet physics into my opengl game. The thing is that it doesn't want to update my translatef value continously but only at the end. The code for bullet looks like this void CGL initPhysics( void ) broadphase new btDbvtBroadphase() collisionConfiguration new btDefaultCollisionConfiguration() dispatcher new btCollisionDispatcher(collisionConfiguration) solver new btSequentialImpulseConstraintSolver dynamicsWorld new btDiscreteDynamicsWorld(dispatcher,broadphase,solver,collisionConfiguration) dynamicsWorld gt setGravity(btVector3(0, 10,0)) ballShape new btSphereShape(1) pinShape new btCylinderShape(btVector3(1,1,1)) pinShape gt setMargin(0.04) fallMotionState new btDefaultMotionState(btTransform(btQuaternion(0,0,0,1),btVector3(0,10,0))) btScalar mass 1 btVector3 fallInertia(0,0,0) ballShape gt calculateLocalInertia(mass,fallInertia) btCollisionShape groundShape new btStaticPlaneShape(btVector3(0,1,0),1) btDefaultMotionState groundMotionState new btDefaultMotionState(btTransform(btQuaternion(0,0,0,1),btVector3(0, 1,0))) btRigidBody btRigidBodyConstructionInfo groundRigidBodyCI(0,groundMotionState,groundShape,btVector3(0,0,0)) btRigidBody groundRigidBody new btRigidBody(groundRigidBodyCI) dynamicsWorld gt addRigidBody(groundRigidBody) btRigidBody btRigidBodyConstructionInfo fallRigidBodyCI(mass,fallMotionState,ballShape,fallInertia) btRigidBody fallRigidBody new btRigidBody(fallRigidBodyCI) dynamicsWorld gt addRigidBody(fallRigidBody) for (int i 0 i lt 300 i ) dynamicsWorld gt stepSimulation(1 60.f,10) btTransform trans fallRigidBody gt getMotionState() gt getWorldTransform(trans) fallY trans.getOrigin().getY() state list.remove( STATE FALL BALL ) printf("stoped n") And the drawing function which is called at the beginning looks like this void CGL fallingBall( void ) glPushMatrix() float colBall2 4 0.0f, 0.0f, 1.0f, 1.0f glMaterialfv( GL FRONT, GL AMBIENT, colBall2) glTranslatef(0.0f,fallY,0.0f) printf("fallY f n",fallY) glutSolidSphere(1.0f,20,20) glPopMatrix() The thing is that it shows correct value in this function's printf but translation is called only at the beginning I mean I can only see the last state. Can anyone help me, please?


Fire simulation using java and opengl i'm newly working with opengl. I'm trying to create a simple program that will simulate fire. My question is what are the ways other than particle effects to simulate fire. And can fire simulation really be done without particle system effect??


Large vertex buffer vs multiple draw calls I'm just getting started with OpenGL, and I'm attempting to use it to create a 2D game. In this game, I have a hexagonal grid made up of a very large variety of differently colored hexagons. As a newbie OpenGL programmer, I see two ways of drawing this grid Using a vertex buffer with the data for a single hexagon, then using a uniform offset value and iterating on the CPU to draw the same program many times until I have a grid. Creating a singular very large pre calculated vertex buffer that draws all the hexagons in a single call. What's the most efficient method? Is there a better way of doing this?


How to use traditional pixel coordinates system in OpenGL? (with C SDL2) I find the normalized, centralized coordinate system used in OpenGL weird and annoying, is there anything I can do at all to make it work like normal pixel coordinates on everything ever except OpenGL? And yes, of course I Googled it. EDIT I'm using OpenGL 2.1


World texturing techniques in FPS game Texturing for small objects (pickups and enimies) can easily be done UV unwrapping the model, and use a texture of reasonable size to make the model look good. But how can texturing be done for the world? Covering a large building with one texture would require a huge texture (otherwise it will look blurry), and a lot of it will be repeated (brickwall textures, wallpapers ...), so that approach seems inefficient. Assigning different textures to different faces may be slow, since there cannot be a texture switch within the draw call. I am targeting OpenGL 4 or later. I prefer good looking stuff rather than extremely high framerate I aim for 30 fps, but perhaps with motion blur (which I guess requires four times that). About tiling Tiling would work, but then there are some parts of the mesh which requires some other texture. And then I need to switch texture.


Light Attenuation Formula Derivation I understand that when sampling the brightness of a given point on the surface, a certain cutoff needs to be taken into consideration. Other words, when the light is further away, the intensity decreases. I came across the following formula that is used to compute the aforementioned attenuation 1.0 (1.0 a dist b dist dist) However, I have not been able to find out why and how this formula is derived. From the formula what I can understand is that as the distance get larger, the result will become smaller but how it is derived is beyond me. If distance takes an important role in the above formula, which helps determine the intensity, could we simply ignore a and b from the formula and simply use attenuation 1.0 (1.0 dist) ? Does anyone know how the formula is derived and the importance the values a and b play within the formula? Thanks.


Batching and Z order with Alpha blending in a 3D world I'm working on a game in a 3D world with 2D sprites only (like Don't Starve game). (OpenGL ES2 with C ) Currently, I'm ordering elements back to front before drawing them without batch (so 1 element 1 drawcall). I would like to implement batching in my framework to decrease draw calls. Here is what I've got for the moment Order all elements of my scene back to front. Send order list of elements to the Renderer. Renderer look in his batch manager if a batch exist for the given element with his Material. Batch didn't exist create a new one. Batch exist for element with this Material Add sprite to the batch. Compute big mesh with all sprite for each batch (1 material type 1 batch). When all batches are ok, the batch manager compute draw commands for the renderer. Renderer process draw commands (bind shader, bind textures, bind buffers, draw element) Image with my problem here But I've got some problems because objects can be behind another objects inside another batch. How can I do something like that?


Can I leverage the fact that my scene is often static to improve OpenGL (JOGL) performance? My scene is drawn based on the location of several (often several million) vertices (kept in VBO's) and a camera. I can easily tell in my code when my scene has changed and when it hasn't. There are also some odd cases such as the window being resized, but I believe I can easily enumerate and handle those as well. Can I (in user code or through some OpenGL property) leverage this to increase the performance when the scene is static? Clearly when the scene is changing, all of the math must be done to properly calculate what should be rendered. But when the scene is static, that picture isn't changing each frame. I've tried implementing something in my code to do this, but the result is a flickering scene (and I'm not entirely sure why). Basically I check to see if anything has changed and if it hasn't I simply return from the display(GLAutoDrawable drawable) function that is invoked by the JOGL FPSAnimator. I feel like this is probably a common problem that should have a standard solution. However, I haven't been able to find anything so far.


VBO glGenBuffers() IllegalStateException i'm kinda noob in OpenGL but I have this problem I get an IllegalStateException at this code int vboVertex glGenBuffers() In detail exception Exception in thread "main" java.lang.IllegalStateException Function is not supported at org.lwjgl.BufferChecks.checkFunctionAddress(BufferChecks.java 58) at org.lwjgl.opengl.GL15.glGenBuffers(GL15.java 116) at Mesh.initVbo(Mesh.java 49) OpenGL version 2.0.5819 WinXP Release Thanks for support and sorry for the horrible english.


Cross platform GLFW build with CMake I know this is probably a popular question and can be very vague, so I'm going to be as specific as possible. I don't really know how to even form this question to be able to search Google, so I came here. I've been following the tutorials from learnopengl.com and they have been by far the best explanations I've found on modern OpenGL anywhere. After I'm done with the tutorials, I'll be making a game. I have already started working on the game engine and it works just fine on Ubuntu and Mac OS X. Building the project is done with CMake (I've found this to be the easiest). The project uses GLFW and Glad as used in the tutorial. I can post the GitHub repo if you want. Today I started trying to figure out how to get the project to run on Windows, but don't even know where to start. Hence coming here. I plan on using Visual Studio but haven't used it since college. How do I even start making the project? I've tried building GLFW on the machine and the building the project using CMake, but I get build tool errors that I don't know how to troubleshoot. Where do I begin?


Is glxinfo saying that the 980 GTX doesn't support a 32 bit depth buffer? I've been using the glxinfo command (glxinfo v) to explore the supported framebuffer configurations. There are two values relating to depth, "depth" and "depthsize." According the source, it appears that the "depth" value relates to the X config and the "depthsize" value relates to the OpenGL config. Assuming that is correct, would the lack of a "depthsize 32" entry suggest that 32 bit depth buffers aren't supported? Or is my understanding of the glxinfo output flawed?


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


Calculate normal angle in screen space I'm working on adding billboarded sprites to a game engine, but the engine allows for walking on curved terrain, like spheres. In order to look like the player is walking on the terrain, I want to start with the billboard, then rotate it around its origin (bottom centre) so that its up vector matches the screenspace normal of the terrain. Here's a diagram of the general idea The billboarding works fine passed the camera's rotation matrix to the sprite, and the poly quad's 0,0,0 is at the bottom centre of the canvas. How can I get the angle between the normal and screenspace up? I think it's a matter of projecting the normal with the MVP matrix, to get it as a 2D screenspace vector to calculate the angle from. But I'm not having much luck attempting to implement it. The sprites take their positioning from the centre of the tiles, along with the normal. I'd also like to move the sprites down in the rotated axis, so that they cover the tile they're standing on. Any other methods are welcome too.


Long loading times on large PNG file using C , OpenGL SOIL I'm currently optimising a C OpenGL game, and I've noticed something slightly odd about texture loading. I've got a number of PNG files I load as textures and use as spritesheets these are generally 512px or 1024px, with one 2048px. I use SOIL (www.lonesock.net soil.html) to load the PNGs then bind them to a custom OpenGL texture class. I've put some primitive code in to measure how long it takes to load these PNG files as textures measured in ticks. Generally speaking the load times are 512px PNG 100 150 ticks 1024px PNG 400 500 ticks 2048px PNG 1800 2000 ticks Now I recognise that not all image files are created equally, but these don't quite seem to add up with what I understand in terms of texture files. There's not much to be gained by using fewer larger textures compared to more smaller textures, and often there's no gain for that 2048px PNG compared to four 1024px. My question is, are these (relative) load times normal? Is there something I'm missing when it comes to loading textures with SOIL? Note that my question isn't 'how can I generically speed up image loading times' (I may at a later date convert these to more OpenGL friendly file formats like DDS), but more is there a pattern I should shouldn't be using to optimise this? Thanks Nathan


Initializing a blank texture in OpenGL without artifacts I'm generating a texture atlas in OpenGL, where I want to create a blank texture and copy my sprites to it. The texture is generated like this glGenTextures(1, amp texture) glBindTexture(GL TEXTURE 2D, texture) glPixelStorei(GL UNPACK ALIGNMENT, 1) glTexParameteri(GL TEXTURE 2D, GL TEXTURE MIN FILTER, GL NEAREST) glTexParameteri(GL TEXTURE 2D, GL TEXTURE MAG FILTER, GL NEAREST) glTexParameteri(GL TEXTURE 2D, GL TEXTURE WRAP S, GL CLAMP TO EDGE) glTexParameteri(GL TEXTURE 2D, GL TEXTURE WRAP T, GL CLAMP TO EDGE) glTexEnvf(GL TEXTURE ENV, GL TEXTURE ENV MODE, GL MODULATE) glTexImage2D(GL TEXTURE 2D, 0, GL RGBA, width, height, 0, GL RGBA, GL UNSIGNED BYTE, NULL) While the sprites are copied like this GLenum format if (sprite.hasAlpha) format GL RGBA else format GL RGB glTexSubImage2D( GL TEXTURE 2D, 0, sprite.x, sprite.y, sprite.width, sprite.height, format, GL UNSIGNED BYTE, sprite.data) The issue is I keep getting artifacts in the texture not covered by a sprite Here I'm supposed to only have two slugs, one sword in the stone, one light grey tile, and one dark grey tile. I tried creating a width height sizeof(GLuint) GLuint array filled with zeros and passing it to the glTexImage2D call, but that didn't seem to do anything.


Which consoles may I target with OpenGL? I'm thinking on technical design for a game game engine using OpenGL, and I wonder if there is any recent consoles (Xbox360, PS3, Wii U, Xbox one and PS4) that I could work with if I do so. I found plenty of conflicting answers through forums. The only straight answer seems that it is impossible for Xboxes because Microsoft forbid to use something else than DirectX, its own product. So, finally, does anyone know for sure which consoles can support an OpenGL based game?


Create a crosshair openGL How do I draw a white crosshair in the middle of screen in openGL, it's all well and good knowing how to render objects in 3d space, but I have literally no idea on how to draw something that sticks on the screen no matter what Would this require a shader? one that does not take into account model view projection matrix? at what point would i draw the cross? after everything to coincide with the painters algorithm? Or do I give it a z value?


Deferred shadow mapping Question What am i doing wrong in the CalcShadowFactor method? It looks like the depth check is not working correctly. Body I'm using deferred rendering in my engine and i have generated the following shadow map Which is draw by the following fragment void main() gl FragColor vec4(texture(gColorMap, TexCoord0).x) The position texture is generated like this WorldPos0 (gWorld vec4(Position, 1.0)).xyz Where gWorld is the transformation of the object being draw(translation rotation scale) Finally, in the light pass, i want to generate the shadow produced from this spotlight with the following code float CalcShadowFactor(vec3 WorldPos) vec4 ShadowCoord gLightWVP vec4(WorldPos,1) ShadowCoord ShadowCoord.w vec2 UVCoords UVCoords.x 0.5 ShadowCoord.x 0.5 UVCoords.y 0.5 ShadowCoord.y 0.5 float z 0.5 ShadowCoord.z 0.5 float Depth texture(gShadowMap, UVCoords).x if (Depth lt z 0.00001) return 0 else return 1.0 It returns a float which multiplicates the color output. I know, im just returning 0 to set the color to complete transparent, it is intensional. The variables used were gLightWVP It is the ProjectionView of the camare set at the light Projection LightCameraRotation LightCameraTranslation WorldPos It is the position got from the Position Texture vec3 WorldPos texture2D( gPositionMap, TextCoord0 ).xyz gShadowMap It is the shadow map texture sampler. This is what is displayed(notice how the spotlight looks at the first image) The engine passes are Shadow pass Render the scene for every light using a alternative camera which is placed in their position with their orientation. It generates the shadow maps for every light. Currently i just have one shadow map for that spot light. Render pass It renders all the scene using the main camera. It generates the position map, normal map, diffuse map and a specular map. Light pass It uses all the textures generated to place the illumination. Here is where the shadow map is being checked for generate the shadows. EDIT I'll also leave here the shadow map texture definition. glGenTextures(1, amp m shadowMap) glBindTexture(GL TEXTURE 2D, m shadowMap) glTexImage2D(GL TEXTURE 2D, 0, GL DEPTH COMPONENT32, WindowWidth, WindowHeight, 0, GL DEPTH COMPONENT, GL FLOAT, NULL) glTexParameteri(GL TEXTURE 2D, GL TEXTURE MIN FILTER, GL LINEAR) glTexParameteri(GL TEXTURE 2D, GL TEXTURE MAG FILTER, GL LINEAR) glTexParameteri(GL TEXTURE 2D, GL TEXTURE COMPARE MODE, GL NONE) glTexParameteri(GL TEXTURE 2D, GL TEXTURE WRAP S, GL CLAMP TO EDGE) glTexParameteri(GL TEXTURE 2D, GL TEXTURE WRAP T, GL CLAMP TO EDGE) glBindFramebuffer(GL FRAMEBUFFER, m fbo) glFramebufferTexture2D(GL FRAMEBUFFER, GL DEPTH ATTACHMENT, GL TEXTURE 2D, m shadowMap, 0)


What resources are available for Mac OS game development? Are there are any modern resources on how to develop games for Mac OS? I suppose this would include objective c, cocoa and opengl 3 . The book Beginning Mac OS X Game Development with Cocoa looks very promising but isn't out until early next year.


Cheap ways to do scaling ops in shader? I've got an extensive world terrain that uses vec3 for the vertex position attribute. That's good, because the terrain has endless gradations due to the use of floating point. But I'm thinking about how to reduce the amount of data uploaded to the GPU. For my terrain, which uses discrete grid based vertex positions in x and z, it's pretty clear that I can replace my vec3s (floats, really) with shorts, halving the per vertex position attribute cost from 12 bytes each to 6 bytes. Considering I've got little enough other vertex data, and an enormous amount of terrain data to push into the world, it's a major gain. Currently in my code, one unit in GLSL shaders is equal to 1m in the world. I like that scale. If I move over to using shorts, though, I won't be able to use the same scale, as I would then have a very blocky world where every step in height is an entire metre. So I see these potential solutions to scale the positional data correctly once it arrives at the vertex shader stage Use 10 1 scaling, i.e. 1 short unit 1 decimetre in CPU side code. Do a division by 10 in the vertex shader to scale incoming decimetre values back to metres. Arbirary (non PoT) divisions tend to be slow, however. Use (some power of two) 1 scaling (eg. 8 1), which enables the use of a bitshift (eg. val gt gt 3) to do the division... not sure how performant this is in shaders, though. Not as intuitive to read values, but possibly quite a bit faster than div by a non PoT value. Use a texture as lookup table to convert the value from decimetres to metres. I've heard that this is really fast. Or whatever solutions others can offer to achieve the same results minimal vertex data with sensible scaling.


Draw coloured transparent polygons on top of texture in modern opengl I am trying to render an image in the viewPort using symmetry create 1 and binding texture to it. static const GLfloat vertices vertexdata symmetry create, symmetry create, 0.0f, uv 0.0f, 1.0f, symmetry create, symmetry create, 0.0f, uv 1.0f, 1.0f, symmetry create, symmetry create, 0.0f, uv 1.0f, 0.0f, symmetry create, symmetry create, 0.0f, uv 0.0f, 0.0f My vertex shader looks like version 330 core layout (location 0) in vec3 aPos layout (location 1) in vec2 texCoord out vec2 TexCoord void main() gl Position vec4(aPos.x, aPos.y, aPos.z, 1.0) TexCoord texCoord And fragment shader looks like version 330 core in vec2 TexCoord out vec4 frag color uniform sampler2D myTexture void main() frag color texture(myTexture, TexCoord) I have setup my vao, vbo and indices correctly and thus I am getting the result as expected (ie A provided image on the display screen). Now I would like to draw 'n' number of transparent polygons on the image generated.For each polygon, I have thought of achieving using mouse cursor positions and clicks and render using glDrawArrays(GL TRIANGLE FAN, 0, n) . If I use the same vertex and fragment shaders my result now is black opaque polygons on top of the image. How to achieve transparency and color in the polygons. Do I need to another set of shaders(vertex and frag)?


OpenGL Water reflection seems to follow camera yaw and pitch I'm attempting to add reflective water to my procedural terrain. I've got it to a point which seems like it's reflecting however when I move the camera left right up down the reflections move with it. I believe the problem has something to do with the way I convert from world space to clip space for the projective texture mapping. Here is a gif of what is happening. http i.imgur.com PDta5Qu.gifv Vertex Shader version 400 in vec4 vPosition out vec4 clipSpace uniform mat4 model uniform mat4 view uniform mat4 projection void main () clipSpace projection view model vec4(vPosition.x, 0.0, vPosition.z, 1.0) gl Position clipSpace Fragment Shader version 400 in vec4 clipSpace out vec4 frag colour uniform sampler2D reflectionTexture void main () vec2 ndc (clipSpace.xy clipSpace.z) 2.0 0.5 vec2 reflectTexCoords vec2(ndc.x, ndc.y) vec4 reflectColour texture(reflectionTexture, reflectTexCoords) frag colour reflectColour I'm using this code to move the camera under the water's surface to get the reflection float distance 2 (m camera gt GetPosition().y m water gt GetHeight()) m camera gt m cameraPosition.y distance m camera gt m cameraPitch m camera gt m cameraPitch If this is insufficient code to diagnose the problem, I'll post more. I tried to keep it to what I thought could be the problem.


GLSL C Only first sampler array index is accessible I have the following shader, which whose fragment shader contains a sampler array of 16 elements. Fragment version 330 core in vec2 uv flat in int instanceID out vec4 color uniform sampler2D sampler 16 void main() color texture(sampler instanceID , uv) Now when I try to set the second array element using the following method void Shader setUniform(const std string amp uniform, GLuint values, size t amount) const bindProgram() GLuint loc getUniformLocation(uniform " 0 ") for(int i 0 i lt amount i ) glUniform1ui(loc i, values i ) std cout lt lt values i lt lt " " For debug std cout lt lt std endl For debug It just sets the first element of the shader. Even though I'm passing 2 values. This is the output of the cout's 5 4 5 4 5 4 5 4 ... Looking up the shader variables with GDebugger, only the first element is set. It also only draws the first (index 0) image.


Generating circular bounding volume AABB for bone animated object I have the animated bounding boxes for the individual bones of an object which comes from a pre computation of the bone's bounding boxes multiplied with the bone matrix. In this question I'm referring to the surrounding aka overall BB for the model. I get it by looping through the precomputed bounding boxes of the bones. I'm able to get an OBB but not an AABB or circular volume because I can't get into the correct "space" for the center of the volume. I thought that getting an AABB would be very easy, but since I have the min max points in bone space (?) I need to do some operation to disable rotation. All I can get is OBB ( I figure that the aabbV4 vector is in "bone space". So, I have to take the inverse of that space somehow, but since I have the combined value of each bone, I need the AABB circular volumes to follow tutorials on collision detection and not just OBB that I have now. So, each object has multiple bones which have a bounding box which animate each frame according to a bone matrix. Then, the mvpGet() function creates the MVP matrix which moves rotates scales the whole thing. I render the OBB surrounding volume of the bones like this for (auto amp i myAbj.allObj) if (i gt bb gt val b amp amp i gt anim gt val b) i gt aabbV4.clear() for (auto amp j i gt bbSkelAll) for (auto amp k i gt aiGbones) if (k.name j.name) i gt obbMVP glm transpose(k.animatedXform) j.obbMVP precomputed obbMVP AABB STEP 1 GATHER STORE glm vec4 bbSkelXformMin glm transpose(k.animatedXform) glm vec4(j.min, 1.f) glm vec4 bbSkelXformMax glm transpose(k.animatedXform) glm vec4(j.max, 1.f) i gt aabbV4.push back(bbSkelXformMin) i gt aabbV4.push back(bbSkelXformMax) break i gt mvpGet() i gt render() AABB STEP 2 MIN MAX for (auto amp i myAbj.allObj) if (i gt bb gt val b amp amp i gt anim gt val b) glm vec4 aabbMin (i gt aabbV4.empty()) ? glm vec4(0.f) i gt aabbV4 0 glm vec4 aabbMax (i gt aabbV4.empty()) ? glm vec4(0.f) i gt aabbV4 0 for (uint j 0 j lt i gt aabbV4.size() j) aabbMin glm min(i gt aabbV4 j , aabbMin) aabbMax glm max(i gt aabbV4 j , aabbMax) glm vec3 aabbSize aabbMax aabbMin glm vec3 aabbCenter .5f (aabbMin aabbMax) i gt aabbMVP glm translate(glm mat4(), aabbCenter) glm scale(glm mat4(), aabbSize) i gt aabbTgl 1 i gt mvpGet() i gt render() i gt aabbTgl 0 cout lt lt "aabbCenter " lt lt glm to string(aabbCenter) lt lt endl


Variable number of light sources I'm going to be writing a very simple renderer, mainly for learning purposes (using OpengGL). I've been wondering about how to implement support for dynamic number of light sources. Two solutions that come to my mind are Define an upper limit for each kid of light source (point, directional etc) and pass an array of lights in an uniform. Write a shader for each of the light source type, iterate over each light in the scene and invoke it's appropriate shader, giving it as input the gBuffer with positions, normals and etc. This seems inefficient for me, as we will loop n times through the fragments in the framebuffer, where n is the number of lights. Are there any more solutions?


Technique suggestion to render corroded pipes in 3D We currently have a lot of data relating to cracks corrosion deformations in metal pipes which at present, can be viewed in a crude flat 2D application which makes the metal anomalies hard to spot. What I would like to create is a virtual 3D pipe viewer that displays the pipe and then models all of the dents in it. I have limited knowledge of graphics programming from University however, what I was thinking of doing is creating a height map from the data given and then use tessellation to push pull the vertices of the pipes mesh, similar to terrain generation techniques. My Question(s) Can a tessellated square plane be wrapped around to form a pipe (and would this approach loose accuracy)? (I've only ever manipulated vertices in the y direction on a flat plane). Some of the dents are extremely small (1 5mm across deep), would my approach be accurate enough to model these anomalies? Is this tessellated terrain generation style the correct way to proceed or is there a simpler solution. Any advise is welcome


cylindrical coordinate point in origin I have a camera which has the following attributes pos (position of the camera in the scene) look(either direction in which camera will face, or target vector) up vector( y axis) I am using cylindrical coordinates system for moving camera around centre of scene. my question is 'how can I find look vector of the camera in a such a way that it will be pointing out in the origin of the scene under 45 degree?'. According to this thread there is not such a way. And you can never look directly down at the focal point, no matter how high up you go. P.S I need somehow to get look vector if it's possible. Thank you for you attention


Unable to Render to multiple rendertargets I am trying to implement a simple deferred rendering engine in openGL and i have a little problem with the GBuffer. I cant get it to render to more than one texture at a single time, which is the one attached to GL COLOR ATTACHMENT0. GBuffer initialization code glGenFramebuffers(1, amp m FBO) glBindFramebuffer(GL FRAMEBUFFER,m FBO) create Gbuffers glEnable(GL TEXTURE 2D) create diffusemap glGenTextures(1, amp m Textures GBUFFER DIFFUSE 24 ) glBindTexture(GL TEXTURE 2D,m Textures GBUFFER DIFFUSE 24 ) glTexImage2D(GL TEXTURE 2D,0,GL RGB,m Width,m Height,0,GL RGB,GL UNSIGNED BYTE,0) glTexParameteri(GL TEXTURE 2D, GL TEXTURE MIN FILTER, GL LINEAR) glTexParameteri(GL TEXTURE 2D, GL TEXTURE MAG FILTER, GL LINEAR) glFramebufferTexture2D(GL FRAMEBUFFER,GL COLOR ATTACHMENT0,GL TEXTURE 2D,m Textures GBUFFER DIFFUSE 24 ,0) if(!glIsTexture(m Textures GBUFFER DIFFUSE 24 )) return false create normalmap glGenTextures(1, amp m Textures GBUFFER NORMAL24 MATID8 ) glBindTexture(GL TEXTURE 2D,m Textures GBUFFER NORMAL24 MATID8 ) glTexImage2D(GL TEXTURE 2D,0,GL RGB32F,m Width,m Height,0,GL RGB,GL FLOAT,NULL) glTexParameteri(GL TEXTURE 2D, GL TEXTURE MIN FILTER, GL LINEAR) glTexParameteri(GL TEXTURE 2D, GL TEXTURE MAG FILTER, GL LINEAR) glFramebufferTexture2D(GL FRAMEBUFFER,GL COLOR ATTACHMENT1,GL TEXTURE 2D,m Textures GBUFFER NORMAL24 MATID8 ,0) if(!glIsTexture(m Textures GBUFFER NORMAL24 MATID8 )) return false create depthmap glGenTextures(1, amp m Textures GBUFFER DEPTH32 ) glBindTexture(GL TEXTURE 2D,m Textures GBUFFER DEPTH32 ) glTexImage2D(GL TEXTURE 2D,0,GL DEPTH24 STENCIL8,m Width,m Height,0,GL DEPTH STENCIL,GL UNSIGNED INT 24 8,0) glTexParameteri(GL TEXTURE 2D, GL TEXTURE MIN FILTER, GL LINEAR) glTexParameteri(GL TEXTURE 2D, GL TEXTURE MAG FILTER, GL LINEAR) glFramebufferTexture2D(GL FRAMEBUFFER,GL DEPTH STENCIL ATTACHMENT,GL TEXTURE 2D,m Textures GBUFFER DEPTH32 ,0) if(!glIsTexture(m Textures GBUFFER DEPTH32 )) return false GLenum drawBuffers GL COLOR ATTACHMENT0, GL COLOR ATTACHMENT1 glDrawBuffers(2,drawBuffers) GLenum status glCheckFramebufferStatus(GL FRAMEBUFFER) if(status ! GL FRAMEBUFFER COMPLETE) printf("FBO error!!, status 0x x n",status) return false glBindFramebuffer(GL FRAMEBUFFER,0) And then before i render all geometry i do this glClearColor(0.2f,0.6f,0.3f,0) glBindFramebuffer(GL DRAW FRAMEBUFFER,m FBO) GLenum drawBuffers GL COLOR ATTACHMENT0, GL COLOR ATTACHMENT1 glDrawBuffers(2,drawBuffers) glClear(GL COLOR BUFFER BIT GL DEPTH BUFFER BIT GL STENCIL BUFFER BIT) And then after i rendered all of it i blit it to the normal framebuffer RenderGeometry() glBindFramebuffer(GL FRAMEBUFFER,0) glClearColor(0.0f,0.0f,0.0f,0) glClear(GL COLOR BUFFER BIT GL DEPTH BUFFER BIT GL STENCIL BUFFER BIT) glBindFramebuffer(GL READ FRAMEBUFFER,m GBuffer gt GetHandle()) glReadBuffer(GL COLOR ATTACHMENT0) glBlitFramebuffer(0,0,1280,720, 0,0,640,370,GL COLOR BUFFER BIT,GL LINEAR) glReadBuffer(GL COLOR ATTACHMENT1) glBlitFramebuffer(0,0,1280,720, 640,370,640,370,GL COLOR BUFFER BIT,GL LINEAR) glfwSwapBuffers(m Window) And my fragment shader code is version 430 in vec2 Tex in vec3 Normal uniform sampler2D tex1 uniform bool UseTexture layout(location 0) out vec3 FragmentColor layout(location 1) out vec3 FragmentNormal void main() FragmentNormal.xyz normalize(Normal) if(UseTexture) FragmentColor texture(tex1,Tex).rgb diffuse color else FragmentColor vec3(1,1,1) And the result is It should be two rectangles drawn to the screen one containing the diffuse color and one containing the screen normals. However i am only getting one.


How can I efficiently render a tile based map with many Z levels, where the levels act like hollowed out voxels? My map setup is a little different to what you normally have with tilemaps. The map itself is a rectangular prism, with a width, height, and depth being variable. In my case, width is the x axis horizontally across the screen, height is the y axis vertically across the screen and depth is the z level, or how quot deep quot the map goes into out of the screen. In my map you could consider the rectangular prism as quot solid quot . Many most of these voxels could be considered as occluders to the voxels below them. Some voxels are hollowed out to make rooms and corridors. The map is viewed at a specific z level, from 0, the quot bottom quot of the rectangular prism, to n, the top. A quot hollowed out quot voxel, if viewed from it's level, would result in me rendering a floor texture in that tile. If there were 4 voxels above it hollowed out, then that floor texture would be rendered when the map is viewed from each of these z levels, but each z level above the quot floor quot would have a semi transparent black rect rendered on top of the tile (so it gets successively darker the further quot up quot you are). This occurs until you're on a z level above the tallest voxel that is hollowed out to make the room at which point you can't see it any longer, because this non hollowed out voxel blocks your view to the room below. The problem I have is that there are many z levels to render and most of the hollowed out sections criss cross around in the different layers to make a very complex network of little rooms and tunnels. This results in me naively rendering a floor texture, followed by several layers of semi transparent black rects, followed by a fully opaque black rect and potentially repeated for any additional overlapping rooms for every x,y tile on the screen. I'm trying to wrap my head around a way to render this more efficiently but I'm having trouble. Currently, for every render loop, I'm attempting to step through the z layers, from the current viewed z level down to 0, and finding the z level that is occluded first (or all the way to the 0 level), so that when rendering, I can skip z layers for that tile that are below this value. This isn't really giving me much of a performance increase. I'm looking for ideas on how to better perform these series of draw calls. I'm using OpenGL3.3 directly, so I'm not restricted by any library or engine constraints. Currently, I'm rendering each quot tile quot on each layer seperately and would prefer to keep it that way for simplicity.


What does glBlendFunc do when given an incorrect enumeration value? In cocos2d x, I am using particle system from plist with blend values dst 1, and src 100 which is wrong enum for gl blend. Although app logged "OpenGL error 0x0500" but it still run and showed a good blend effect. And i can not find the right pairs of dst and src to recreate that effect. So i hope someone can tell me how BlendFunc gl blend will work when it having bad src value. Base on that i hope i can recreate that effect without using wrong src value. Thanks


Region selection in OpenGL If I have a mesh of triangles and going to make a selection on it using a region (and not rectangle using Glu.gluPickMatrix(...) ), how can I implement it?


How can glass breaking effect from Smash Hit be achieved? I saw Smash Hit the other day and was amazed by the physics of the game, specially the shattered glass effect I've read other posts about this subject but I still feel that they don't share enough details to let me get started on implementing this on my own with OpenGL GLSL. Is it possible for somebody with an enhanced perception and graphics understanding to watch the gameplay and give some pointers on how this effect could be replicated? I rather not use 3rd party physics engine and do the entire thing on my own for educational purposes, so could you mention some of the physics that goes behind this as well? References to other documents and demos are highly appreciated.


Do game engines put all interpolation onto the GPU? Is it considered standard to push all the vertices and an interpolation of the next position onto the GPU? Suppose a sector is moving up every game tick at 50 units per second. You could put on the shader something like (good old parametric equation like formulas) pos.x a x1 (1 a) x0 Where you'd calculate a as a uniform and only send this value to the GPU in an uncapped fashion, like so while (true) a percentage of the way between frames in range from 0.0 to 1.0 updateGLUniform(..., a) render() Rest of stuff delay() The other way of doing it was to manually set each entity and sector every single time you loop, but then you might have to update the position of a lot of things every game cycle. Just setting one value seems way more efficient. However, I don't know if there's any downsides to this. Are there any negatives to shoving interpolation off to the GPU to save computation time in the game? Or is there something that I'm missing? What do major games do?


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?


How does re glBufferData()'ing interact with glVertexAttribPointer? I understand the basic sequence glGenBuffers() creates a quot buffer object name, quot glBindBuffer() creates the actual buffer object (as well as binding the name), glBufferData() quot creates and initializes a buffer object's data store, quot and glVertexAttribPointer() sets the format of the buffer data, as well as saving the buffer object binding as part of vertex attrib array state. The tricky thing that I'm unsure of is if the glVertexAttribPointer() stuff remains valid if the the quot buffer object data store quot (but not the buffer object itself) is blown away by a new call to glBufferData(). I'm aware that this isn't usually a good idea use glBufferSubData() when just rewriting buffers but glBufferData() seems like the only option if it needs to be resized. Plus, I'm just curious. The reference pages make it sound like it could go either way in particular (https www.khronos.org registry OpenGL Refpages gl4 html glVertexAttribPointer.xhtml) If pointer is not NULL, a non zero named buffer object must be bound to the GL ARRAY BUFFER target (see glBindBuffer), otherwise an error is generated. pointer is treated as a byte offset into the buffer object's data store. The buffer object binding (GL ARRAY BUFFER BINDING) is saved as generic vertex attribute array state (GL VERTEX ATTRIB ARRAY BUFFER BINDING) for index index. When a generic vertex attribute array is specified, size, type, normalized, stride, and pointer are saved as vertex array state, in addition to the current vertex array buffer object binding. It seems like both the byte offset and the buffer object binding could remain valid, even if the data store was replaced by something different. But I could also see it being implemented such that at the time of the call, the binding captures a specific pointer into the data store, which becomes invalidated if the data store is replaced. Neither way seems to be precluded by the wording.


GLSL shader algorithm to render a sprite map with a single draw call (on a single sprite mesh) I'm trying to render a tile map world on a single sprite mesh (instead of one sprite per tile.) This significantly reduces the array vertex bus labor for extremely large worlds In order to do this, you pass two textures to the shader the sprite sheet itself, and a texture containing tile IDs. Sprite map (I know some tiles repeat but ignore that, this could be any spritesheet) Below Entire tile world represented by a 128 x 128 texture map, where each RGB value holds actual Tile ID for that location on the map. There are more efficient ways to represent the actual tile ID. Here, for the sake of simplicity, it is stored in the R component. Putting it all together The right most square is the screen output. On the image I just repeat texture... but what should actually happen is a tile world rendered from tiles on the sprite sheet. I wrote the shader that is supposed to do this, but I'm stuck. I can render the sprite sheet itself, and even scale it on the sprite mesh, but I can't seem to get the tile IDs render at the proper location, matching the tile world data. I do think I am really close and there are just a couple of modification needed to the shader so what am I doing wrong? The following shader is what I have so far tilemap.vs version 330 core layout (location 0) in vec3 position layout (location 1) in vec3 color layout (location 2) in vec2 texCoord out vec2 TexCoord uniform sampler2D ourTexture uniform sampler2D ourTilemapDataTexture uniform mat4 Model uniform mat4 View uniform mat4 Projection void main() gl Position Projection View Model vec4(position, 1.0) TexCoord texCoord tilemap.frag version 330 core in vec2 TexCoord uniform sampler2D ourTexture uniform sampler2D ourTilemapDataTexture void main() size of the tile world (128 by 128 tiles on one sprite) float cols 128.0f float rows 128.0f float tilesPerSide 8.0f figure out which tile we re in from the 3D coordinates vec2 tile vec2(floor(TexCoord.x) cols, floor(TexCoord.y) rows) get tile s texture ID from tile ID texture map float tex texture2D(ourTilemapDataTexture, tile).r vec2 UV vec2(tex fract(TexCoord.x), fract(TexCoord.y)) color texture2D(ourTexture, UV) if (color.a 0) remove transparent areas discard PS I looked at every tutorial I could find on Google, and tried to re implement it in my shader to no effect. This is as far as I got so far. Can anyone point out what I'm doing wrong? Update 1 I was able to get position sampling to work. I painted a bit on the world map It's not perfect but definitely a step forward Adjustments made to the fragment shader float cols 128.0f float rows 128.0f float tex texture2D(ourTilemapDataTexture, TexCoord).r float tey texture2D(ourTilemapDataTexture, TexCoord).g vec2 UV vec2( (TexCoord.x (cols) (tex 32.0f)), (TexCoord.y (rows) (tey 32.0f)) ) color texture2D(ourTexture, UV) Sure it's not 100 correct but at least map indexing works now )


Lasers in 3D space game I am creating this little 3d space shooter and am somewhat unsure on how to implement the laser beams. I'm thinking about something along Star Wars and the like where mostly you shoot rather short laser beams but very many of those. Should I create a "tube" for each of the beams, render them via instancing and give them a better look just with the shader? How would you go on about this? I was rather perplexed that there was no good tutorial on this matter out there.


Simple openGL code paradox I'm trying to create the most basic application that will draw a cube using indices and textures for starters, but nothing about it makes any sense whatsoever. I ran it on my machine with an nVidia card and the display driver (latest, not that it matters) crashes (null ref), along with the program on the glDrawElements(...) command (Renderer.cpp). Fine. Then I sent it to a friend of mine who has an AMD card to try to debug it because I was unable to find the bug in the code, and the program worked (didn't crash) on his machine. That surprised me since I only did the most basic openGL stuff, no way it was vendor specific. To get to the bottom of this, I downloaded APItrace (http apitrace.github.io ) to try to see what's going on under the hood of my machine and why does my driver crash. Once I dumped the trace after I ran the program, it said that the shader program linker failed because I didn't write to gl Position (which I have). The problem is that the program links just fine in VS debugger and no error is returned there. So it just keeps getting weirder. If you want to mess with this, you can get the code (commit with issue linked) at https github.com Karlovsky120 7DaysWorldEditor commit e86b8be40c81511c4416dc5e253b90e42a5a8ec0 I don't think you'd see the bug if I just pasted the code here, there must be a mistake with the setup somewhere. I really made an effort to make this as hassle free as possible, it's just one click install clone it, build it, and you're good to go, no additional setup required. You will need to open it with VS2017 though. There's a lot of classes in the code, but all of the relevant code is in Scene.cpp and any of the classes it references. Thank you for any help you give, even if it's just a guess at what might be wrong because I'm at my wits end here.


2D graphic over 3D perspective projection To draw a 2D HUD (just a simple trianlge, for now) over 3D graphics in OpenGL I draw all 3D objects, then call glDisable(GL DEPTH TEST) before drawing 2D HUD draw 2D triangle call glEnable(GL DEPTH TEST) however it seems I am missing something and the triangle is only rendered when I set Model View Projection matrix to Identity DrawFrame() . .. Draw 3D objects . Coordinates of 2D triangle vert 0 0.0f vert 1 0.5f vert 2 0.0f TOP vert 3 0.5f vert 4 0.5f vert 5 0.0f LEFT vert 6 0.5f vert 7 0.5f vert 8 0.0f RIGHT glDisable(GL DEPTH TEST) glm mat4 guiMVP glm mat4(1.0f) glm mat4 guiMVP Ortho View glm mat4(1.0f) This does not render triangle glm mat4 guiMVP Projection View glm mat4(1.0f) This DOES render triangle at its place but in 3D world glUniformMatrix4fv(MatrixID, 1, GL FALSE, amp guiMVP 0 0 ) ... .. render2D triangle glEnable(GL DEPTH TEST) OnSurfaceChanged(int width, int height) glViewport(0, 0, width, height) aspect (float) width height Projection Matrix Projection glm perspective(45.0f, aspect, 0.1f, 10000.0f) Orthographic Matrix for 2D HUD Ortho glm ortho(0.0f, (float)width, (float)height, 0.0f) setCamera(float cameraX, float cameraY, float cameraZ, float cameraLX, float cameraLY, float cameraLZ) Camera View matrix View glm lookAt( glm vec3(cameraX, cameraY, cameraZ), Camera position glm vec3(cameraLX, cameraLY, cameraLZ), pointing at glm vec3(0, 1, 0) Angle ) here's my Vertex shader attribute vec3 in Position uniform mat4 MVP void main(void) vec4 v vec4(in Position, 1.0) gl Position MVP v This is screenshot of what I want I DO get this output by using an Identity MVP matrix for 2D graphics. I know this is an ugly hack that works for now. How to do this properly using Orthographic matrix ?


How do open world game engines allocate memory? My troubles I've been trying to create a game engine but since I am not well experienced in C I am having trouble deciding on how to load new scenes efficiently level by level or just an open world. Example Recent games are heavy, Most populat games are about 40 to 100 gigabytes but neither RAM nor GPU have that much memory at least Normal PC or Consoles. So obviously most game engines pre allocate enough memory to fit the scene and sometimes just tolerate some wasted memory but how would you decide how much is enough? Possible solution I was planning to create separate game loops, before entering the game loop I would load each level, then start the loop, thus I would be able to deallocate preceding level and then reallocate new memory for a next level. Since I am new to the world of games and memory management my solution may sound rather stupid, But I need to know how to handle such situations efficiently.


Aquire disassembly of shader code Is there a way to get the disassembly that your driver generates when compiling a shader? I noticed that you can get an accidental disassembly dump if you go over the maximum thread group size supported by the hardware in compute shaders, so naturally I figured there must be some way to do this for all shader types. Is there a reliable way to get the disassembly (perhaps specific to NVIDIA AMD Intel hardware), using tools or even just "hacks" like causing errors during compilation linking?


How to create realistic rainfall animation in modern OpenGL using shaders? I see many examples of particle system in old style OpenGL with falling raindrops. Examples of rainfall that can interact with environment lighting and look realistic are hard to find. How to create realistic rainfall animation in modern OpenGL using shaders?


OpenGL multiple mesh management I've been working on coding a new 3D engine in Java. For the moment at least I'm sticking to openGL... Currently I'm reworking how meshes get transformed and then drawn. ATM each mesh created has its own VBO and IBO along with its own draw method so if I wanted to draw multiple meshes it would look like this mesh1 MeshLoader.loadMesh("cube.obj") mesh2 MeshLoader.loadMesh("pyramid.obj") mesh1.addToBuffers() adds vertex and index data to vbo and ibo mesh2.addToBuffers() mesh1.draw() mesh2.draw() The draw method defined in class Mesh enables vertex attribute arrays, binds the bufffers, and then draws elements based on the ibo. Then I send my projection matrix (transformation and perspective) as a uniform to the vertex shader. QUESTION Games are made of many many meshes and each has to be identified so that transformation can be applied. I want to be able to apply transformations (translate, rotate, scale) directly to a given mesh, independent of the other meshes. In other words I want to move mesh1 and only mesh1 5 units to the right (on its own axis) without it affecting mesh2. How do I do all this without making a million draw calls to the gpu? Any advice appreciated.


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


Is index drawing faster than non index drawing I need to draw a lot of polygons consisting of 6 vertices's (two triangles). Without any texture coordinates, normals etc., both approaches result in 72 bytes. In the future I would definitely also need texture coordinates and normals, which would make index drawing consume less memory. Not a lot though. So my question is For VAOs with few vertex overlaps, which approach is faster? I don't care about the extra memory consumed by non index drawing, only speed. Edit To make it clear. Non index approach float 18 vertices Triangle 1 1,1,0, 1,0,0, 0,0,0, Triangle 2 1,0,0, 0,1,0, 0,0,0, Index approach float 12 vertices 1,1,0, 1,0,0, 0,0,0, 0,1,0, int 6 indices Triangle 1 0,1,2, Triangle 2 0,3,2


How to draw textured tile map in opengl I am trying to create a textured hexagonal tile map in opengl. I have the VBO and respective index buffer. Additionally I have a texture atlas for texturing individual tiles. I'm attempting to create a distinct texture for each hex without mixing the textures. I understood that one should use a pair of (U,V) texture coordinates for each vertex. Now if the tile map would not be indexed and have the overlapping vertices, I could just set the texture coordinates for each vertex and get each hex rendering the correct texture. However, with indexing the overlapping vertices are gone and I can only set single pair of texture coordinates for each vertex which results in the textures mixing inside the hexes. Is there a way to texture tiles with indexing or another alternative approach to creating hex maps with different textures?


How shader program still works even after detaching shader object? In the following process of shader creation, shader object is detached after linking program (glLinkProgram), how does the shader program still works after detaching and deleting shader objects? glCreateShader glShaderSource glCompileShader glCreateProgram glAttachShader glLinkProgram glDetachShader glDeleteShader Use shader.


Animate multiple entities I'm trying to animate multiple(3) entities using one model(IQM format). It's working but performance is really bad because I'm calling animate function for each entity in my game loop (I think problem is there). What's the best way to animate multiple entities (with different animation ofc) in OpenGL? I think I can try build one VBO entity for better performances but I don't think it's the best way to do it.


Jittery Rotational Movement with Arcball implementation I have an assignment where I need to implement arcball using Opengl ( 2.0). I have it more or less implemented but I have a some problems issues bugs and I'm not sure whats either causing them or how to solve. Arcball rotation Specically minor variance in mouse movement away from the axis I'm rotating on seems to "confuse" my program, causing artifacts (such as rotating briefly a completely different direction before resuming its current path). Code void mouse motion(int mx, int my) float angleRadians handles mouse motion events if ( arcball on amp amp (mx ! last mx my ! last my) ) if left button is pressed lArcAngle arcAngle cout lt lt " Last Angle " lt lt lArcAngle lt lt endl cur mx mx cur my my glm vec3 va get arcball vector(last mx, last my) glm vec3 vb get arcball vector(cur mx, cur my) angleRadians acos(min(1.0f, glm dot(va, vb))) arcAngle ( ( angleRadians 180 ) 3.14159265 ) cout lt lt " Angle in degrees " lt lt arcAngle lt lt endl cout lt lt " ArcAngle after Mult " lt lt arcAngle lt lt endl arcAngle lArcAngle cout lt lt " ArcAngle after accumulation " lt lt arcAngle lt lt endl axis in world coord glm cross(va, vb) last mx cur mx last my cur my glutPostRedisplay() other code for other functionality... void display() Background color glClearColor(1, 1, 1, 0) glClear(GL COLOR BUFFER BIT GL DEPTH BUFFER BIT) glClear(GL COLOR BUFFER BIT) glEnable(GL DEPTH TEST) Matrix setup glMatrixMode(GL PROJECTION) glViewport(0, 0, width, height) glLoadIdentity() gluPerspective(40, (float)width (float)height, 0.1, 1000) Matrix setup glMatrixMode(GL MODELVIEW) glLoadIdentity() glTranslatef(0, 0, 3) int myFlagCtr getFlagCtr() cout lt lt "CRX " lt lt crx lt lt " CRY " lt lt cry lt lt " CRZ " lt lt crz lt lt endl glPushMatrix() glRotatef(arcAngle, axis in world coord.x, axis in world coord.y, axis in world coord.z) glTranslatef(vec blx, vec bly, zScaling) glRotatef(arcAngle, axis in world coord.x, axis in world coord.y, axis in world coord.z) if (myFlagCtr 1) Set Wireframe glPolygonMode(GL FRONT AND BACK, GL LINE) color red glColor3f(1.0f, 0.0f, 0.0f) else if (myFlagCtr 2) glPolygonMode(GL FRONT AND BACK, GL LINE) color red glColor3f(1.0f, 0.0f, 0.0f) glEnable(GL POLYGON OFFSET LINE) glPolygonOffset( 1.0, 1.0) draw object blDrawMouseMesh() glPolygonMode(GL FRONT AND BACK, GL FILL) color red glColor3f(0.0f, 1.0f, 0.0f) else if (myFlagCtr 0 myFlagCtr 1) Bring back to Default glPolygonMode(GL FRONT AND BACK, GL FILL) glColor3f(0.53f, 0.12f, 0.47f) blDrawMouseMesh() glPopMatrix() glutSwapBuffers() As you can see between the two mouse vectors I get the angle between them, and the orthonogol vector which is the axis I am rotating around. But this only seems to work in a rather "dirty" and not particularly smooth way. Edit I now think the problem is the accumulation of degrees, when I switch axis's it remembers the angle from before, so it will "rotate" by the same amount previously plus the new angle, I'm not sure how to solve given the loading of the identity matrix causing non accumulated values to reset.


Is it a good idea to render many textures into one texture? I'm making a 2D game with OpenGL. In order to avoid changing the state machine and binding at runtime, I want to make consolidate my textures into bigger textures, for example, taking 4 128x128 textures and making 1 big 512x512. I could then just render part of the texture rather than binding a new one. Is this a good idea? Could my newly created texture get lost, or are there major faults in doing this? Thanks


Is the "impossible object" possible in computer graphics? This may be a silly question but I want to know the answer to it. I saw this thing called the "impossible object", while they're many different images of this online, it's suppost to be impossible geometry. Here is an example Now as far as logic goes, I know you don't have to obey it in games, such as a flying cow, or an impossible object. So that's out of the way, but what stands in my way is whether or not there is a way to draw this onto a 3D scene. Like is there a way to represent it as a 3D object? Thanks!


Rotate view matrix based on touch coordinates I'm working on an Android game where I need to rotate the camera around the origin based on the user dragging their finger. My view matrix has initial position of sitting on the negative z and facing origin. I have succeeded in moving the camera through rotation left or right, up or down based on the user dragging the finger, but my problem is obviously that after I drag my finger up down and rotate say 90 degrees so my intial position of z is now y and still facing origin, if I drag my finger left right I want to rotate from y to x, but what happens is it rotates around the pole y. This is to be expected as I am mapping 2D touch drag coords to 3D space, but I dont know where to start trying to do what I want. Perhaps someone can point me in the right direction, I've been googling for a while now but I don't know what I want to do is called! Edit What I was looking for is called an ArcBall, google it for lots of info on it.


How to calculate view matrix for OpenGL 3. 2D Camera Roll I'm trying to create a camera object for my 2D game engine, but I just can't seem to get the view matrix down right. Here's the code I'm currently using glm mat4 Camera GetViewMatrix() glm mat4 view glm vec3 camPos glm vec3(this gt pos, CAM Z) GLfloat xup, yup xup sin(this gt rot) yup cos(this gt rot) view glm lookAt(camPos, camPos glm vec3(0.0f, 0.0f, 1.0f), glm vec3(xup, yup, 0.0f)) return view The result I get from this is as follows Before rotation After rotation As you can see, the camera is rotating around its top left corner. The top left corner is the origin point (0,0,0) and the camera's position is (0,0). Shouldn't the lookAt function position the camera at (0,0,1) and point it at (0,0,0)? That's not what seems to be happening. I'm just trying to get the camera to roll about it's set position. Any help would be greatly appreciated! Thanks in advance!


Infinite terrain generation performance one big heightmap or several smaller heightmap? I'm generating a procedural terrain using (a home made fBm based on) Perlin noise as heightmap. To make the terrain infinite, I redraw part of it while the camera moves. There are two alternatives either have several (say 9) heightmap textures and rotate them while the camera moves or have only one heightmap (say 9 times bigger) and redraw only part of it as necessary. Note The two approaches redraw exactly the same amount of pixels each time. But in the first case, I must bind 3 small textures and entirely redraw them to redraw a line of my grid in the second case, I bind the whole bigger texture and redraw only a line inside it. Question Should I expect one to be faster than the other? Does glBindTexture has higher cost for larger texture?


Map Engine Rendering Broken So I've been making my own tile map engine in LibGDX as the one currently implemented doesn't support collision detection with scaling. So I've come up with my own Layer and Map class and a drawing function for the map. Currently this is what it produces Here's the rendering code public void draw(SpriteBatch batch) for(Layer layer layers) for(int x 0 x lt layer.getTileMap().length x ) for(int y 0 y lt layer.getTileMap() x .length y ) batch.draw(layer.getTiles() layer.getTileMap() x y , xOffset (x ((layer.getTileWidth() scale))), yOffset (y ((layer.getTileHeight() scale))), (layer.getTileWidth() scale), (layer.getTileHeight() scale)) EDIT Yes, I'm aware the map looks weird, it's just random textures thrown in from a tile sheet.


How do you fix wobbling shadow edges? I've implemented an omni directional shadow map and I've noticed a rather unwanted behaviour on the shadows. It seems like when the angle between the occluded points and the light source is really steap, then the egde of the shadow starts to wobble. It's almost looks like it's pulsating. Could it have something to do with when the light source moves further away from the occluded polygons, the pixels next to each other are further away from each other than the corresponding texels on the shadow map face that I sample from which result in some sort of magnification side effect when performing aliasing? This is just a really wild guess! Is anyone familiar with this type of behaviour and or have any solution to it? Thank you!


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


In OpenGL, how can I discover the depth range of a depth buffer? I am doing a GL multi pass rendering app for iOS. The first pass renders to a depth buffer texture. The second pass uses the values in the depth buffer to control the application of a fragment shader. I want to rescale the values in the depth buffer to something useful but before I can do that I need to know the depth value range of the depth buffer values. How do I do this?


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


Batching and Z order with Alpha blending in a 3D world I'm working on a game in a 3D world with 2D sprites only (like Don't Starve game). (OpenGL ES2 with C ) Currently, I'm ordering elements back to front before drawing them without batch (so 1 element 1 drawcall). I would like to implement batching in my framework to decrease draw calls. Here is what I've got for the moment Order all elements of my scene back to front. Send order list of elements to the Renderer. Renderer look in his batch manager if a batch exist for the given element with his Material. Batch didn't exist create a new one. Batch exist for element with this Material Add sprite to the batch. Compute big mesh with all sprite for each batch (1 material type 1 batch). When all batches are ok, the batch manager compute draw commands for the renderer. Renderer process draw commands (bind shader, bind textures, bind buffers, draw element) Image with my problem here But I've got some problems because objects can be behind another objects inside another batch. How can I do something like that?


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


How to check for cube collisions? I want a method, which takes two "ObjectBox" objects (A "ObjectBox" has .getX() .getY() .getZ() .getSizeX() .getSizeY() .getSizeZ() methods) as a parameter and return true if the two Boxes are colliding and false if they aren't. So it should be something like this public static boolean checkCollision(ObjectBox box1, ObjectBox box2) return TRUE IF COLLIDING FALSE IF NOT COLLIDING I tried figuring it out but it seemed pretty hard to me.


Migrating 2D game from immediate mode to VBOs I am in the process of migrating away from legacy OpenGL calls in my 2D LWJGL game. Previously I would render each sprite using immediate mode, which was dead easy bind the texture, add the vertices, and it's done. Now I want to use vertex arrays. Ideally I would put the vertices for ALL my entities in one big array and render it in a single draw call. The problem? Each entity type uses a different texture, and glDrawArrays uses just one texure at a time. Here are some possible solutions I came up with 1) Create a separate vertex array for each entity This is by far the easiest solution, but it somehow seems wrong to me, because it's so similar to using immediate mode. Doesn't this defeat the benefit of using vertex arrays? 2) Create a separate vertex array for each entity type In other words, all entities that have the same texture will be rendered together. This isn't ideal as it would involve a good chunk of extra work and some extra effort on the CPU to separate the entities by type, and more importantly, would affect the z ordering of the entities. For example, it would be impossible to have a Tree that appears in front of one Squirrel but behind another Squirrel. That is, unless I introduced a depth buffer, but I was trying to avoid this as it adds another level of complexity and, as I understand it, more work on the GPU (although that probably doesn't matter too much). 3) Combine all textures using a texture atlas If I was able to use a single texture for all entities, I could use a single vertex array. However, there are 2 problems with this I have not been able to find a good library for creating a texture atlas at runtime, and writing this code myself would be non trivial. I am worried that some GPUs may have a prohibitively small texture size limit. Summary Would the first solution be viable advisable? Am I being foolish for trying to avoid using the depth buffer? Am I missing something here? Is there a better solution?


My Ambient lighting is not working correctly I'm having a problem when using ambient lights in my opengl game. When I first started with my program, i had a positioned light, and the code was this GLfloat AmbientColor 1.0f,1.0f,1.0f,1.0f glLightModelfv(GL LIGHT MODEL AMBIENT,AmbientColor) POSITIONED LIGHT GLfloat LightColor0 0.9f,0.9f,0.7f,1.0f GLfloat LightPos0 0.0f,900.0f,1000.0f,1.0f glLightfv(GL LIGHT0,GL DIFFUSE,LightColor0) glLightfv(GL LIGHT0,GL POSITION,LightPos0) When doing this, I had a well lit area with no problem. Once I changed my matrix to GL MODELVIEW, I noticed that my lights were not equal on each face. I changed my code to look like this GLfloat AmbientColor 1.0f,1.0f,1.0f,1.0f glLightModelfv(GL LIGHT MODEL AMBIENT,AmbientColor) POSITIONED LIGHT GLfloat LightColor0 0.9f,0.9f,0.7f,1.0f glLightfv(GL LIGHT0,GL AMBIENT,AmbientColor) Once I used this code, only the mountains in my terrain were lit up, and anything perfectly flat was not lit at all(completely black...) So my question is How would I use my ambient light correctly? Example code would be nice, thanks.


Lag Spike When Creating Model I am creating a game using OpenGl in c . Whenever I create a new model while the game is running, such as fire a bullet, there is a huge lag spike. The function that creates the model is below. std string jsonString jsonString file gt load(type) json jf json parse(jsonString) Might be causing the lag indicesSizeTexture jf quot textureIndices quot .size() verticesSizeTexture jf quot textureVertices quot .size() indicesSizeCollision jf quot collisionIndices quot .size() verticesSizeCollision jf quot collisionVertices quot .size() verticesTexture new float verticesSizeTexture 8 verticesCollision new float verticesSizeCollision 8 verticesCollisionUpdated new float verticesSizeCollision 8 indicesTexture new int indicesSizeTexture indicesCollision new int indicesSizeCollision for (int i 0 i lt verticesSizeTexture i ) responsible for just the texture vertices verticesTexture i jf quot textureVertices quot i for (int i 0 i lt indicesSizeTexture i ) responsible for just the texture indices indicesTexture i jf quot textureIndices quot i for (int i 0 i lt verticesSizeCollision i ) responsible for just the collision vertices verticesCollision i jf quot collisionVertices quot i verticesCollisionUpdated i verticesCollision i for (int i 0 i lt indicesSizeCollision i ) responsible for just the collision indices indicesCollision i jf quot collisionIndices quot i binds id glGenBuffers(1, amp VBO) glGenVertexArrays(1, amp VAO) glGenBuffers(1, amp EBO) glGenTextures(1, amp texture) glBindVertexArray(VAO) glBindBuffer(GL ARRAY BUFFER, VBO) glBufferData(GL ARRAY BUFFER, verticesSizeTexture 8 sizeof(float), verticesTexture, GL STATIC DRAW) position attribute glVertexAttribPointer(0, 3, GL FLOAT, GL FALSE, 8 sizeof(float), (void )0) glEnableVertexAttribArray(0) texture glBindTexture(GL TEXTURE 2D, texture) glVertexAttribPointer(2, 2, GL FLOAT, GL FALSE, 8 sizeof(float), (void )(6 sizeof(float))) glEnableVertexAttribArray(2) stbi set flip vertically on load(true) unsigned char data stbi load(texturePathString.c str(), amp width, amp height, amp nrChannels, 0) glTexImage2D(GL TEXTURE 2D, 0, GL RGBA, width, height, 0, GL RGBA, GL UNSIGNED BYTE, data) glGenerateMipmap(GL TEXTURE 2D) stbi image free(data) glBindBuffer(GL ARRAY BUFFER, 0) glBindVertexArray(0) I stripped out a lot of parts that I am almost certain aren't causing the lag. There is a lot of stuff going on, but it is mostly simple mathematical operations. The only parts that I think could be causing the lag is the json section used for loading the model data. The model data is stored in a variable from file as a string. I need the json section for the data storage though. What could be causing the lag? should I find a different data storage type? What if I created a bullet offscreen on startup, then copied it whenever I needed it? The specific json library I am using is https github.com nlohmann json


how to make a fast fragment shader that converts intensity to saturation? I have a simple fragment shader that looks like this ifdef GL ES precision lowp float endif varying vec4 v fragmentColor varying vec2 v texCoord uniform vec4 u desiredColor uniform sampler2D u texture void main() gl FragColor texture2D(u texture, v texCoord) u desiredColor My goal is to take a grayscale image and apply a color to it, but maintain luminance. There was a stackoverflow post from years ago where the poster was after exactly what I want https stackoverflow.com questions 4361023 opengl es 1 1 how to change texture color without losing luminance The answers however are outdated (OpenGL ES 1.0) and also I am a little confused by them. The accepted answer says to use multi texturing, and the 2nd answer says that is "nonsense". Regardless, the code example there is incompatible with the version of OpenGL ES 2.0 that my game is using with cocos2d v2.x. Here are my original grayscale sprites With my simple shader applied and setting u desiredColor to vec4(1.0, 0.0, 0.0, 1.0), you can see it does exactly what I don't want it to do it completely tints the entire image, turning everything red, including the white. What I really want is for the darker shades of gray have the richest color, but as the sampled grayscale pixel approaches white, the colorized pixels lose saturation, where ultimately a sampled pixel of white has 0 saturation but a sampled pixel of dark gray would be 100 saturation. My desired output is My thought was that the simplest approach would be to have my shader make the output pixel color's saturation be something like (1.0 samplePixelIntensity). So, if the sample pixel's intensity was 1.0, that would mean 0 saturation in the output, if the sample pixel's intensity was 0.5, it would have 50 saturation.. if the sample pixel's intensity was 0.2, then it would have 80 saturation. However, I am not very familiar with writing shaders, so I am wondering how I might construct something like this?


OpenGL vector rotation matrix to a given point I have a sphere with a radius of .5 The sphere is centred at 0,0,0 I am now trying to place items around my sphere based on a given x,y,z on the surface of the sphere. My items have been draw created in such a way that they are positioned on the surface when translated to 0,0,0 because their centre offset has been positioned at the centre of the sphere. What I need is some help with the calculation needed to get the correct glRotate values so that my icons will show at the correct x,y,z on the surface. To help explain what I mean, here is a picture So you can see 0,0,0 at the centre, and also rotating around the same point is the blue line, This represents the rotation of my object. The green part is the visible part of my item, and so will draw on the surface of the sphere. I have everything ready to go for this, in that I can already draw my items in this manner, however I am not able to correctly calculate the rotation. With the default rotation of Identity my items will draw on the bottom of the sphere. In summary I am looking for something like this glRotate GetRotationForSurface(X,Y,Z) I hope that's clear, this is a bit tricky to explain. Thanks,


Single Array Texture, multiple wrap modes I have a array texture of which I would like some of its sub images have wrap modes of GL REPEAT and others to be GL CLAMP TO EDGE. From my research, I haven't found a clear answer. It appears Sampler Objects may be what I'm looking for, however I'm unsure as to how to go about implementing this. As current I have a sampler class which looks like this class TextureSampler public unsigned int id TextureSampler() TextureSampler(unsigned int wrapS, unsigned int wrapT, unsigned int filterMin, unsigned int filterMag) TextureSampler() void bind(unsigned int textureId) void unbind(unsigned int textureId) As you can expect the constructor simply sets all the wrap and filter parameters. I bind with this glBindSampler(textureId, id) . The textureId being that from glGenTextures() and the id from glGenSamplers(). Now when it comes to my implementation, I've created two samplers, one for repeating wrap mode and another for edge clamping. This is where things are a bit murky. I've got two samplers, one texture array... it doesn't seem possible to bind both samplers at the same time and yet how do I access both types in the fragment shader? Google has not been much help and I've read parts of the ARB sampler objects extension to see if it had useful information and it seemed to say ... Should sampler objects be made visible to the shading language. This is left for a future extension. I am using GL 4.3, so this is extension is not built in, however that quote leaves me wondering if I've approached this all wrong. What is the correct approach to this? Is this possible with a single texture array?


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


Collision Detection Tips I need collision detection for my 3D racing game but it isn't going well right now. I think I understand the concept of testing boxes and generating a response, however implementation part is a nightmare for me. OpenGL makes everything more complicated than it has to be. How can I use a shape that is constructed with glVertex ? Should I create the bounding boxes with some Vector3D class?


How do I flip upside down fonts in FTGL I just use FTGL to use it in my app. I want to use the version FTBufferFont to render font but it renders in the wrong way. The font(texture?buffer?) is flipped in the wrong axis. I want to use this kind of orthographic settings void enable2D(int w, int h) winWidth w winHeight h glViewport(0, 0, w, h) glMatrixMode(GL PROJECTION) glLoadIdentity() I don't even want to swap the 3rd and 4th param because I like to retain the top left as the origin glOrtho(0, w, h, 0, 0, 1) glMatrixMode(GL MODELVIEW) I render the font like this No pushing and popping of matrices No translation font.Render("Hello World!", 1, position, spacing, FTGL RenderMode RENDER FRONT) On the other forums, they said, just scaled it down to 1, but it wont work in mine. Example font is above the screen I can't see relevant problem like in mine in google so I decide to ask this here again. How can I invert texture's v coordinate without modifying its source code ? (assume its read only)


Geometry shader for multiple primitives How can I create a geometry shader that can handle multiple primitives? For example when creating a geometry shader for triangles, I define a layout like so layout(triangles) in layout(triangle strip, max vertices 3) out But if I use this shader then lines or points won't show up. So adding layout(triangles) in layout(triangle strip, max vertices 3) out layout(lines) in layout(line strip, max vertices 2) out The shader will compile and run, but will only render lines (or whatever the last primitive defined is). So how do I define a single geometry shader that will handle multiple types of primitives? Or is that not possible and I need to create multiple shader programs and change shader programs before drawing each type?


When should I use GL TRUE or GL FALSE values? When using GLboolean, should I just use true and false or should I use GL TRUE and GL FALSE? When should I prefer using GL TRUE and GL FALSE? or maybe I shouldn't care at all (Because both works)? Here It is said that both are actually a different type. But in some tutorial websites I've read, they use GL TRUE or GL FALSE on functions that requires GLboolean. Example glVertexAttribPointer(0, 3, GL FLOAT, GL FALSE, 3 sizeof(GLfloat), (GLvoid ) 0) Well, it works too if we substitute GL FALSE with false in the code above.


model view projection multiplication order I'm debugging a lighting problem where the camera position is effecting the diffused lighting component on my 3d model. In researching my problem I went back and am reading over all the how to documents. I found that one of my old sources (where I learned open gl 2.0) said this (summarized) When creating the modelViewProjection matrix you can't change the order or you'll get unexpected results. First take the View Matrix and post multiply it by the projection matrix to create a viewProjection matrix. Then post multiply the model matrix to get the modelViewProjection matrix. Looking at my code, all this time I haven't been doing this matrixMultiply(mView, thisItem gt objModel, mModelView) matrixMultiply(mProjection, mModelView, mModelViewProjection) As a test I tried changing it to this matrixMultiply(mView, thisItem gt objModel, mModelView) matrixMultiply(mProjection, mView, mViewProjection) matrixMultiply(mViewProjection, thisItem gt objModel, mModelViewProjection) ...but the result appears the same. EDIT To answer a question about what the matrices contain. A snapshot of the matrix values EDIT2 As a test I did the math both ways to compare the results and even with moving the camera and model around and rotating the model I'm getting the same results for the final ModelViewProjection.


How to use LWJGL Vertex Buffer Objects? I have been learning how to make a game with LWJGL for a while now by following YouTube tutorials online but I've recently been having a problem understanding Vertex Buffer Objects. I've looked at several tutorials including the one at the LWJGL Wiki, but I still don't understand how to use them. Can someone please clarify how Vertex Buffer Objects should be used? I understand the code behind it but I don't know how it should be used. I know that the VBO should only be created once and be rendered every frame loop. But my main question is, is there one Vertex Buffer Object per game or one per Object to be drawn? Also, what's the difference between VBOs and Interleaved VBOs?