_id
int64 0
49
| text
stringlengths 71
4.19k
|
---|---|
1 | How can I avoid the precision loss when recentering objects on open terrain? For a better context this question is related to this one What 39 s the largest quot relative quot level I can make using float? When the player is moving too far away from the center, all the scene and objects are moved in the opposite direction, in order to bring the center closer to the player and avoid float precision issues. Recentering all objects makes me doubt a little, since it might still accumulate error since it's an addition. I also don't think I can tell a physics engine to just teleport all its object without causing weird behavior. |
1 | Do glColorMask and glDrawBuffer accomplish the same thing? I'm doing a shadowmap pass (only storing depth values) so I set glDrawBuffer(GL NONE) to disable color writing for the moment. Yet, I see some tutorials also do glColorMask(GL FALSE, GL FALSE, GL FALSE, GL FALSE). Is this really necessary, given glDrawBuffer(GL NONE)? Don't they accomplish the same thing? |
1 | Why are all OpenGL function calls prefixed with "q" in the Doom 3 source code? Why is every OpenGL call prefixed with a "q" in the Doom 3 source code? Are they custom functions or a different library, and if so, why use that over OpenGL? Any Google search comes up with the Qt OpenGL module, which I assume has nothing to do with it. |
1 | For deferred rendering and SSAO, what coordinate system are the normals actually in? So, I'm following the very helpful LearnOpenGL online tutorials, and I'm working on implementing SSAO. I don't have a deferred rendering pipeline, but I need to collect normals during my depth pass so that I can sample them for the SSAO effect. I'm following this tutorial https learnopengl.com Advanced Lighting SSAO, and referencing this one when needed https learnopengl.com Advanced Lighting Deferred Shading. However, neither of these tutorials really explain what's going on with the normals. What is the normalMatrix being used in the shader? mat3 normalMatrix transpose(inverse(mat3(view model))) Normal normalMatrix (invertedNormals ? aNormal aNormal) I'm not worried about the invertexNormals conditional, that's probably just something weird the author added for handling different conventions, but what the heck is going on with that normalMatrix? Why would we invert the view model matrix? If we're starting with aNormal in object space (whether it's coming directly from a vertex buffer or from a normal map TBN calculation), I can't for the life of me figure out what coordinate system that resulting normal is going to end up in! So, long story short, what coordinate frame should my normals be in if I'm to use them for SSAO? World space? View Space? Clip space? None of the above? If it's some weird coordinate system, can somebody help me get there? I'm probably more confused than I should be. |
1 | My model is drawn wrong in 3d I'm learning OpenGL and now after I made everything I needed, I started with 3D, my first problem is that my mesh doesn't draw like I intended... Here's my rectangle (uses GL TRIANGLES) std vector lt GLfloat gt Vpos 0.5, 0.5, 0.0, 0.5, 0.5, 0.0, 0.5, 0.5, 0.0 0.5, 0.5, 0.0 0.5, 0.5, 0.0, 0.5, 0.5, 0.0 comms are the 3d version And here I draw my array glDrawArrays(GL TRIANGLES, 0, verNum 2) it is binded with vertex array, I use shaders And my fragment shader is version 330 in vec2 passTextureCoords out vec4 outColor uniform sampler2D ourTexture void main() outColor vec4(0.0, 1.0, 0.5, 1.0) texture(ourTexture, passTextureCoords) I don't have a texture so I use a lightgreen for debug proposes Also my vertex shader version 330 layout (location 0) in vec3 inVertPos layout (location 1) in vec2 inTexCoords out vec2 passTextureCoords void main() gl Position vec4(inVertPos.x, inVertPos.y, inVertPos.z, 1.0) passTextureCoords inTexCoords Thanks for help by now, I pretty sure that I missed something small but important. |
1 | How can I render "two sided" clouds like in Minecraft? The clouds in Minecraft are semi transparent and are rendered on both sides. If you fly into the cloud you can see inside of the cloud. If I render clouds the inside faces would be visible on the outside. How can I prevent that? Z Ordering the faces and render near to far with depth test on? There must be a better, easier way. Could the accum or stencil buffers be used somehow? UPDATE I think the crucial point everyone is forgetting is that these clouds and semi transparent and "blended" into the scene as each face is rendered. If two faces are rendered on top of each other the "white" texture will double up which is undesired. The faces also seem to have slight lighting variations which would rule out using a stencil. UPDATE2 Just another note. Each cloud is 12x12x4 blocks (roughly). Larger clouds are just a group of the base clouds stuck together. Here's showing clouds from above. They are translucent and the chunks below can be seen. And here's the view from inside them. |
1 | First encounter with dynamic lighting I have a game idea with lots of pretty lights (literally) in mind that I would really love to implement, but I have essentially zero experience with shadow mapping, deferred rendering, the lot of it. I've done some research into 2D shadow casting, and I think I might try a method similar to this, but I haven't a fathom how to create a virtual rectangular manipulation of a polar image (from the point light's perspective on the map). My question How can I create a virtual rectangular manipulation of a polar image whose process is quick enough that it can be run twice per frame every time a light moves in game? I'd like to be able to handle at least 4 dynamic lights on screen at any time, but I'll take what I can get. I've started to learn OpenGL, so hopefully this isn't too high above my skill level. |
1 | Perspective Matrix doesn't work OpenGL 4 I tried to implement my own perspective matrix and it doesn't work. I don't understand why. With just with my view matrix (without Perspective Matrix) I can see my mesh. Here my view matrix Vec3f position(0.0,0.0, 5.0) Vec3f target(0.0,0.0,0.0) Mat4f Camera LookAt(Vec3f target, Vec3f position) ce dont j'ai besoin pour calculer les parametre de ma camera... Vec3f up world Vec3f(0.0,1.0,0.0) Vec3f forward (position target).normalize() Vec3f right up world.cross(forward).normalize() Vec3f up forward.cross(right).normalize() Mat3f R R.setCol(2,forward) R.setCol(0,right) R.setCol(1,up) R.transpose() Mat4f R4(R) Vec3f mp position 1.0f Mat4f P4 P4.setCol(3,mp) LookAt R4 P4 return LookAt And my Perspective Matrix Mat4f Camera perspective(float fovy, float aspect, float zNear, float zFar) float theta fovy 0.5f (180.f M PI) float range zFar zNear float invtan 1.f tanf(theta) Mat4f projMat(invtan aspect, 0.0f, 0.0f, 0.0f, 0.0f, invtan, 0.0f, 0.0f, 0.0f, 0.0f, (zFar zNear) range, 2 zNear zFar range, 0.0f, 0.0f, 1.0f, 0.0f) perspectiveCam projMat std cout lt lt perspectiveCam lt lt std endl return perspectiveCam Mat4f perspective(float fovy M PI 2, float aspect (1280.f 720.f) 1.f, float zNear 0.1f, float zFar 100.f) My shader is very simple so it can't be the problem.. version 410 core layout(location 0) in vec3 V position layout(location 1) in vec3 V color layout(location 2) in vec3 V normal uniform mat4 view matrix uniform mat4 proj matrix out vec3 color void main() color V color gl Position proj matrix view matrix vec4(V position, 1.) when I initialise perspectiveCam with the unit matrix 4x4 it displays my triangle.. but when I implement perspectiveCam like in the function it does not display my triangle Here my Set col function template lt typename TYPE gt void Mat4 lt TYPE gt setCol(int i, Vec4 lt TYPE gt amp vec4) for (size t k 0 k lt 4 k ) setElement(k,i, vec4.getElement(k)) void setElement(int i,int j, TYPE var) element i 4 j var TYPE getElement(int i, int j) const return element i 4 j |
1 | how to do partial updates in OpenGL? It is general wisdom that you redraw the entire viewport on each frame. I would like to use partial updates what are the various ways can do that, and what are their pros, cons and relative performance? (Using textures, FBOs, the accumulator buffer, any kind of scissors that can affect swapbuffers etc?) A scenario a scene with a fair few thousand visible trees although the textures are mipmapped and they are drawn via VBOs roughly front to back with so on, its still a lot of polys. Would streaming a single screen sized texture be better than throwing them at the screen every frame? You'd have to redraw and recapture them only on camera movement or as often as your wind model updates or whatever, which need not be every frame. |
1 | Does one need normals for a strictly 2d Game? I'm starting to learn OpenGL by creating a pure 2D game. I have to decide on the format of the Vertices. Do I need a normal component? Or is this for a 2d component not needed? My gut feeling says I won't need it since everything is flat. But perhaps I need it for some shader or other thing I don't see yet. |
1 | C OpenGL SDL2 VBO Depth problem Transparency I got a problem with my VBO. When having textures. The far blocks overlay the near ones. I tried editing the alpha, depth buffer, the VBO byte allocation. Nothing works for me... The FAR plane is overlapping the NEAR plane. Alpha glEnable(GL BLEND) glBlendFunc(GL SRC ALPHA, GL ONE MINUS SRC ALPHA) glEnable(GL DEPTH TEST) glDepthFunc(GL LEQUAL) glEnable(GL CULL FACE) glDisable(GL MULTISAMPLE) glDepthMask(GL TRUE) |
1 | OpenGL App not setting cursor position appropriately I have written a small application using OpenGL, and have implemented some rudimentary camera controls. Unfortunately, I cannot get the application to set my cursor position correctly. The cursor is never set to where I tell it to go, so my application just reacts to where the cursor is on my entire screen. I first attempted to use GLFW, and when I saw that I couldn't set the cursor appropriately, I decided to try SFML. Neither one works. I'm on an Arch Linux install with a Gnome desktop. I've been trying to figure this out for a few days now to no avail. The relevant code is as follows sf Vector2i cursor pos sf Mouse getPosition( window) sf Mouse setPosition(sf Vector2i(1280 2, 720 2), window) This gets called every frame inside a function that messes with some matrices. I also set the cursor position at initialization. Any hints or advice would be greatly appreciated. |
1 | OpenGL Disable Anti Alias I can't find anything on how to hint to the driver to disable any antialias. I'm using a very minimal passthrough setup yet I notice my driver is still doing what looks like MSAA. I want to disable this, or at least give a strong hint to disable it, so to save performance. As I will be doing deferred rendering with my own SSAA. |
1 | physics model simulation I am building a game for which I want to simulate certain rigid body dynamics.Could someone suggest me some engines which work on Ubuntu.Also as I have dont have much time to implement it,so it would be helpful if it is a easy one to work with. I have some across one namely ODE.Am looking for others which would help me simulate collisions and angular movements. |
1 | Are buffers in OpenGL associated with GLSL programs? I have two different shader programs in my OpenGL code. 1 renders simple font using freetype 2 simple shader which draw primitive shapes. I sent both of them some data using buffers, I understood that they are stored on server side, but are they associated with different programs? or any program can use any buffer data by just using gBindBuffer() ? |
1 | How can I use ARB debug output with SDL on Windows? I'm trying to port a small GL program that I've been working on from Linux to Windows. I have the following window SDL CreateWindow(...) SDL GL SetAttribute(SDL GL CONTEXT FLAGS, SDL GL CONTEXT DEBUG FLAG) glContext SDL GL CreateContext(window ) glewInit() if (GLEW ARB debug output) glDebugMessageCallbackARB( amp DebugCallback, nullptr) I was surprised to find out that GLEW ARB debug output evaluates to false. Could it be that ARB debug output not supported on Windows, with the latest drivers for my video card (an older Radeon HD540v)? Am I doing anything wrong? I thought this extension was rather old, and it would probably be supported everywhere by now. Update I added my SDL initialization code, as I needed to pass SDL GL CONTEXT DEBUG FLAG. Unfortunately, ARB debug output is still not supported. Update After initializing the context with the debug flag through SDL, I manually queried the available extensions (bypassing GLEW) and ARB debug output is not available! Again, could this not be supported on my implementation? |
1 | 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. |
1 | I want to render some surfaces in GLSL with normal maps, and some without I have normal mapping working in my game, but I want to only use normal mapping for some surfaces, and not others. Right now, as far as I can tell, my shader is applying an incorrect normal of (0, 0, 0) in tangent space to my non normal mapped surfaces, since no textures are bound to the sampler. Is there a suitable way of detecting that nothing is bound to a sampler in GLSL and then using a flat normal instead? I've also found old posts around the web recommending the following Using a dummy 1x1 texture with the color (128, 128, 255) this will lose Phong interpolation. Switching shader programs for normal mapped and non normal mapped surfaces I get the feeling that I'd end up duplicating a lot of code this way, especially when I start implementing specular maps, parallax displacement maps, etc. Are either of these still recommended or is there a new feature to query the sampler that I could make use of? Should I be doing it one way over another for performance reasons? Here is my fragment shader version 330 core in vec2 UV in vec3 tangentSpaceLightDir out vec4 outColor uniform sampler2D diffuseMap, normalMap void main (void) vec4 texel texture(diffuseMap, UV) vec4 ntexel texture(normalMap, UV) I want to use vertex normal here, if nothing is bound. vec3 N normalize(ntexel.xyz 2.0 1.0) vec3 L normalize(tangentSpaceLightDir) float lambertTerm dot(N, L) vec4 finalColor vec4(0.0) if (lambertTerm gt 0.0) finalColor vec4(lambertTerm, 1.0) outColor finalColor texel |
1 | Process of writing to the depth texture In openGL, let's say I output one single point from the vertex shader with this value gl Position vec4(2.0,3.0,5.0,7.0) what exact math operations happen to "z" after leaving the vertex shader? what will be the end value of that depth texel? |
1 | Providing texture coordinates and using indexed drawing at the same time Please consider the following vertex structure struct vertex vec3 posL, normalL Using this vertex layout, we can provide the vertex data in an interleaved way, i.e. (posL,normalL),(posL',normalL'),... This works pretty fine in combination with indexed drawing via glDrawElements(). However, if we add texture coordinates to our vertex structure, i.e. consider struct vertex vec3 posL, normalL vec2 tex things get more complicated. Since one and the same vertex (meaning it's position) may participate in a variety of different faces with varying texture coordinates, I wondered how one would provide such vertex data to the vertex buffer. One solution would be to quit storing the data interleaved and provide it a linear way, i.e. (posL,posL',...),(normalL,normalL',...),(tex,tex',...) where each tuple has the same length. Doing so, we would hold related things together (i.e. the k th element of each tuple forms exactly one input the vertex shader sees). But we would push much more data to the pipeline than necessary. So, what's the "ideal" solution to this problem? If one suggests to use different buffers, how does the vertex shader know, that texture coordinate tex at position i in Buffer 2 corresponds to the tuple (posL,normalL) at position j in Buffer 1? |
1 | OpenGL first person camera orientation issues I have a "camera" in my opengl program that I recently finished. However, I've noticed that whenever I rotate and then move again, the x, y, and z angles change. For example, when I press the "w" key, I move forward along the "z" axis. If I then rotate the camera 90 degrees, when I push the "W" key, I will actually be moving right, seemingly along the "x" axis. It makes sense why this happens, I'm just wondering why its happening. Here's the rotation function private void camera() glRotatef(xrot, 1.0f, 0.0f, 0.0f) glRotatef(yrot, 0.0f, 1.0f, 0.0f) The keyboard function if (Keyboard.isKeyDown(Keyboard.KEY D)) xpos 0.035 delta if (Keyboard.isKeyDown(Keyboard.KEY A)) xpos 0.035 delta if (Keyboard.isKeyDown(Keyboard.KEY W)) zpos 0.03f delta if (Keyboard.isKeyDown(Keyboard.KEY S)) zpos 0.035 delta if (Keyboard.isKeyDown(Keyboard.KEY UP)) xrot 0.035 if (xrot gt 360) xrot 360 if (Keyboard.isKeyDown(Keyboard.KEY DOWN)) xrot 0.035 if (xrot gt 360) xrot 360 if (Keyboard.isKeyDown(Keyboard.KEY RIGHT)) yrot 0.035 if (xrot gt 360) xrot 360 if (Keyboard.isKeyDown(Keyboard.KEY LEFT)) yrot 0.035 if (xrot gt 360) xrot 360 And my translate function glTranslated(xpos, ypos, zpos 30) any ideas on how to solve this? I would be very grateful |
1 | Getting the number of fragments which passed the depth test In "modern" environments, the "NV Occlusion Query" extension provides a method to get the number of fragments which passed the depth test. However, on the iPad iPhone using OpenGL ES, the extension is not available. What is the most performant approach to implement a similar behaviour in the fragment shader? Some of my ideas Render the object completely in white, then count all the colors together using a two pass shader where first a vertical line is rendered and for each fragment the shader computes the sum over the whole row. Then, a single vertex is rendered whose fragment sums all the partial sums of the first pass. Doesn't seem to be very efficient. Render the object completely in white over a black background. Downsample recursively, abusing the hardware linear interpolation between textures until being at a reasonably small resolution. This leads to fragments which have a greyscale level depending on the number of white pixels where in their corresponding region. Is this even accurate enough? Use mipmaps and simply read the pixel on the 1x1 level. Again the question of accuracy and if it is even possible using non power of two textures. The problem wit these approaches is, that the pipeline gets stalled which results in major performance issues. Therefore, I'm looking for a more performant way to accomplish my goal. Using the EXT OCCLUSION QUERY BOOLEAN extension Apple introduced EXT OCCLUSION QUERY BOOLEAN in iOS 5.0 for iPad 2. "4.1.6 Occlusion Queries Occlusion queries use query objects to track the number of fragments or samples that pass the depth test. An occlusion query can be started and finished by calling BeginQueryEXT and EndQueryEXT, respectively, with a target of ANY SAMPLES PASSED EXT or ANY SAMPLES PASSED CONSERVATIVE EXT. When an occlusion query is started with the target ANY SAMPLES PASSED EXT, the samples boolean state maintained by the GL is set to FALSE. While that occlusion query is active, the samples boolean state is set to TRUE if any fragment or sample passes the depth test. When the occlusion query finishes, the samples boolean state of FALSE or TRUE is written to the corresponding query object as the query result value, and the query result for that object is marked as available. If the target of the query is ANY SAMPLES PASSED CONSERVATIVE EXT, an implementation may choose to use a less precise version of the test which can additionally set the samples boolean state to TRUE in some other implementation dependent cases." The first sentence hints on a behavior which is exactly what I'm looking for getting the number of pixels which passed the depth test in an asynchronous manner without much performance loss. However, the rest of the document describes only how to get boolean results. Is it possible to exploit this extension to get the pixel count? Does the hardware support it so that there may be hidden API to get access to the pixel count? Other extensions which could be exploitable would be debugging features like the number of times the fragment shader was invoked (PSInvocations in DirectX not sure if something simila is available in OpenGL ES). However, this would also result in a pipeline stall. |
1 | What happen if I try to run OpenGL 4.4 code on an unsupported graphic card? I'm learning OpenGL because I'd like to build my own engine. I'd like to know what happens if I try to run OpenGL 4.4 code (the latest version at the moment of writing) on an unsupported graphic card ? (I mean for example a graphic card that support up to 4.1 OpenGL). Does it fails even to start ? or, it start but fails to render ? Thank you very much. |
1 | Is FreeGLUT still a good choice? I recently decided to utilize the C library called FreeGLUT to have a window be managed from my program, where I can draw things via OpenGL. But at the same time I saw some people telling that it is an old library, not that much reliable and so on... Should I keep using that or move to another one? |
1 | How do I convert from Cartesian to spherical coordinates? This seems like a fairly basic and common problem. Is there a builtin way to achieve it or do I have to write the algorithm on my own? If I do, how should it work? |
1 | Is linear filtering possible on depth textures in OpenGL? I'm working on shadow maps in OpenGL (using C ). First, I've created a framebuffer and attached a depth texture as follows Generate the framebuffer. var framebuffer 0u glGenFramebuffers(1, amp framebuffer) glBindFramebuffer(GL FRAMEBUFFER, framebuffer) Generate the depth texture. var shadowMap 0u glGenTextures(1, amp shadowMap) glBindTexture(GL TEXTURE 2D, shadowMap) glTexImage2D(GL TEXTURE 2D, 0, GL DEPTH COMPONENT24, 1024, 1024, 0, GL DEPTH COMPONENT, GL FLOAT, null) glTexParameteri(GL TEXTURE 2D, GL TEXTURE WRAP S, GL REPEAT) glTexParameteri(GL TEXTURE 2D, GL TEXTURE WRAP T, GL REPEAT) glTexParameteri(GL TEXTURE 2D, GL TEXTURE MIN FILTER, GL NEAREST) glTexParameteri(GL TEXTURE 2D, GL TEXTURE MAG FILTER, GL NEAREST) glFramebufferTexture2D(GL FRAMEBUFFER, GL DEPTH ATTACHMENT, GL TEXTURE 2D, shadowMap, 0) Set the read and draw buffers. glDrawBuffer(GL NONE) glReadBuffer(GL NONE) Later (after rendering to the shadow map and preparing the main scene), I sample from the shadow map in a GLSL fragment shader as follows float shadow texture(shadowMap, shadowCoords.xy).r Where vec3 shadowCoords is the coordinates of the fragment from the perspective of the global directional light source (the one used to create the shadow map). The result is shown below. As expected, shadow edges are jagged due to using GL NEAREST filtering. To improve smoothness, I tried replaced the shadow map's filtering with GL LINEAR, but the results haven't changed. I understand there are other avenues I could take (like Percentage Closer Filtering), but I'd like to answer this question first, if only for my sanity. I've also noticed that other texture parameters (like GL CLAMP TO EDGE rather than GL REPEAT for wrapping) don't function for the shadow map, which hints that this may be a limitation of depth textures in general. To reiterate Is linear filtering possible using depth textures in OpenGL? |
1 | Textures "don't work" when I don't specify any texture parameters. Is this a driver bug or intended behavior? Whenever I try to use textures, I have to at least specify the sample filtering parameters (GL TEXTURE MAG FILTER, GL TEXTURE MIN FILTER) for textures to work at all. If I don't, sampling the textures in a shader will usually just return a value of 0 for all texels in the texture, even though glReadPixels return the correct values, and rendering to the textures actually works. Debugging tools like Nsight and gDebugger confirm this. I tested this on two NVIDIA GPUs (GTX 970, GT 555m) with the latest driver versions (347.09), and the behavior is the same. However, I can't find any reference to this in docs like this or this I assumed that not specifying these parameters just made them take on their default values. So is this actually intended standard behavior (probably meaning "undefined behavior") or can I assume this is a driver bug? |
1 | draw fog of war using shaders I am making a RTS game, and I'd like some advice on how to best render fog of wars, given what I'm already doing. You can imagine this game as being a classic RTS like Age of Empires 2, where the fog of war will basically be handled by a 2D array telling if a given "tile" is explored or not. The specific things to consider here are 1) I'm only doing a few draw calls to draw the whole screen, using shaders, and I'm not drawing "tile by tile" in a 2D loop 2) The whole map is much bigger than the screen, and the screen can move every frame or so In that case, how could I draw the fog of war ? I have no issue maintaining on the CPU side a 2D array giving the fog of war for each tile, but what would be the best way to actually display it dynamically ? thanks! |
1 | Engine and level of detail for maze labyrinth dungeon scene? My question is similar to these Algorithm for generating a 2d maze To scene graph or not to scene graph? I.e. in this case should I use jME3 or some other engine (I heard Unreal offers a free engine) for a 3D dungeon game and when I build up the dungeon, should I use an algorithm for a new dungeon every time or should I use a static scene? I've code to build a small wall that adds it to my scene which is mostly programmaticly achieved with less 3D modelling and more algorithmic solutions This loop builds a wall out of individual bricks. public void initWall() float startpt brickLength 4 float height 0 for (int j 0 j lt 15 j ) for (int i 0 i lt 6 i ) Vector3f vt new Vector3f(i brickLength 2 startpt, brickHeight height, 10) makeBrick(vt) startpt startpt height 2 brickHeight This method creates one individual physical brick. public void makeBrick(Vector3f loc) Create a brick geometry and attach to scene graph. Geometry brick geo new Geometry("brick", box) brick geo.setMaterial(wall mat) rootNode.attachChild(brick geo) Position the brick geometry brick geo.setLocalTranslation(loc) Make brick physical with a mass gt 0.0f. brick phy new RigidBodyControl(2f) Add physical brick to physics space. brick geo.addControl(brick phy) bulletAppState.getPhysicsSpace().add(brick phy) |
1 | OpenGL poor performace with instanced drawing I'm just started learning OpenGL and this is my first project besides tutorials. I'm trying to load a huge enginering model The data is structured in a way that I thought I could use instancing for very good performance, because many items are simple primitives (cylinder, torus, cones, etc) with different transformation matrices. So I structured my data this way Primitive 1 VAO VBO gt vertices VBO gt indices Instance 1.1 VBO gt object color VBO gt transformation matrix Instance 1.2 VBO gt object color VBO gt transformation matrix Instance 1.n VBO gt object color VBO gt transformation matrix Primitive n VAO VBO gt vertices VBO gt indices Instance n.1 VBO gt object color VBO gt transformation matrix Instance n.n VBO gt object color VBO gt transformation matrix The model has 50k unique primitives and 120k instances, so in general each primitive has 2 instances. But in practice, some have 10 and some have only 1. I end up with 50k VAOs and then call dlDrawElementsInstanced for each VAO. The model is being draw at only 3 fps. I gues it's because of the number of glDraw calls (50k for the triangles and 50k for the outlines). The shaders are very simple, not even lightning is being applied. To be sure of that I changed the way I organize the buffers I put everything in a single buffer, but to do that I had to pass the color and transformations matrices as vertex attributes to each vertex. I know this isn't right but I had to test if the problem was the number of glDraw calls. I couldn't even load the model this way because the buffers get way to big and I get out of memory. So I tested this theory on a smaller model that was taking 50ms to render in the instanced way. With a single VAO for everything and only a single glDrawElements call the model is taking less than 1ms to render. I know that putting everything in a single VAO and passing the trasnformations for every vertex is not the correct way of doing this. Now I also know that instancing isn't the tool for this due the very few intances for each mesh. So the question is, what would be the correct way to setup the buffers to minimize the number of glDraw calls? I think that it would be perfect to store all in a single VAO (so I could call glDrawElements a single time) but use something like the glVertexAttribDivisor used in instancing to inform the shaders when to use the next shaders. But not exactly because I had to manually inform when to use the next matrix, in way like glPrimitiveRestartIndex works. I'm using OpenGL 3.3 |
1 | How to implement OpenGL triple buffering of buffer objects to avoid stalls? I'm trying to implement the triple buffering described here. The intent is to gain higher frame rate by avoiding waiting for glBufferSubData() to finish. My understanding is that this is how to implement triple buffer make 3 buffers with glGenBuffers() Current frame bind to buffer3 draw last frame bind to buffer1 glBufferSubData for all the vertices, keep track of their texture vertex count,blend function, etc Next frame bind to buffer 1 draw last frame (bind texture, blend func, glDrawArrays) and so on There doesn't seem to be any performance gain between this and doing glBufferSubData() and then immediately calling glDrawArrays(). Am I missing something or misunderstand how triple buffer should work? Also is there a way to know when glDrawArrays() stalls due to glBufferSubData() still not being finished? |
1 | LibGDX Shader files in assets Access is Denied I stored the glsl files in android gt assets gt shaders directory, but when I run the app, an error is displayed Error Gradle Execution failed for task ' android mergeDebugAssets'. Error java.io.FileNotFoundException ...android assets shaders (Access is denied) But the problem goes away if I put those files in assets root folder. Can I not store shader files in asset subdirectories? Using Gdx v1.9.3. EDIT The issue is not there when running on Desktop, but only on Android. Didn't check others. UPDATE Apparently the issue got resolved today. I didn't make any changes but it's working now! |
1 | Simplifying Camera Strafing I have a camera that follows the position and direction of the player. These are updated using spin and velocity. The velocity is updated like so auto velocity get velocity() velocity get acceleration().x get right() velocity get acceleration().y get up() velocity get acceleration().z get forward() set velocity(velocity) ... where acceleration is relative to the object, not the world. This is the first time I have used OpenGL and I am not sure if this is the best solution, but it does what I want. I was wondering if there is a better way to do this using OpenGL Mathematics (GLM). Additionally, this method works like a rocket, which is good for what I am trying to do, but if I want something more like a human, I have to change it to auto velocity get velocity() auto const y velocity.y get acceleration().y velocity get acceleration().x get right() velocity get acceleration().z get forward() velocity.y y set velocity(velocity) ... to prevent the player from being able to fly by looking up. Is there a way of simplifying this case, too? Acceleration is defined as switch (dir) case left return glm vec3( 1, 0, 0) case right return glm vec3( 1, 0, 0) case front return glm vec3( 0, 0, 1) case back return glm vec3( 0, 0, 1) case up return glm vec3( 0, 1, 0) case down return glm vec3( 0, 1, 0) default assert(false) |
1 | How to reduce image size without pixelation? I see lots of games with smooth edges characters and high res images, however when I try to reduce images to say 64x64 for my character I just get a pixelated mess. even if I start with a 64x64 canvas I get pixelated edges. Should I be scaling with OpenGL? or is there some technique perhaps with photoshop or pixen that I am unaware of? |
1 | JWJGL Multi threading to separate update and render Introduction I am currently designing a game in Java using the LWJGL 3.0, with Gradle. I have quite an advanced knowledge on multi threading, and I am aware how GLFW does doesn't implement multi threading from this guide. Currently, I have one class Updater with a loop for updating, and another class Renderer for rendering, each extending Runnable with their own loops and time calculations. Below is a diagram showing the structure of the classes and update and render methods. I have also set up a lock system, using the Java Lock class (again below). My Problem Despite setting each thread as the current context before each loop executes its window call, and setting the current context to null at the end, I still get the error Exception in thread "RENDERER" java.lang.IllegalStateException GLFW error 0x10008 WGL Failed to make context current The requested resource is in use. Any idea as to why? Been at this for a few hours now. Loop class private void threadLoop() try lock.lock() locked true loop() TPS catch (InterruptedException e) e.printStackTrace() finally lock.unlock() locked false Override public void run() init() long lastTime System.nanoTime() double ns SECOND (MAX TPS 2) double delta 0 long timer System.currentTimeMillis() while (running) long now System.nanoTime() delta (now lastTime) ns lastTime now while(delta gt 1) threadLoop() TPS delta if(System.currentTimeMillis() timer gt 1000) finalTPS TPS timer 1000 TPS 0 stop() Thread Manager public void update() if (window null) return window.setThread() window.update() window.nullThread() public void render() if (window null) return window.setThread() window.render() window.nullThread() Renderer Override protected void loop() if (state ! null) state.render() threadManager.intermediateCode() threadManager.render() Updater Override protected void loop() if (state ! null) state.update() threadManager.intermediateCode() threadManager.update() Window public void setThread() glfwMakeContextCurrent(getID()) public void nullThread() glfwMakeContextCurrent(NULL) public void render() glClear(GL COLOR BUFFER BIT GL DEPTH BUFFER BIT) glClearColor(0.0f, 0.3f, 0.8f, 0.0f) glfwSwapBuffers(ID) System.out.println("Rendered window") public void update() glfwPollEvents() System.out.println("Updated window") |
1 | Linear filter problem with diagonal lines on adjecent tiles I am quite new at using OpenGL GLSL. Basically, the project I am working on is my first 'real' experience with it. I do not know whether this is relevant, but I use libgdx for my project. Currently, I am trying to use the GL LINEAR filters to draw tile of my (tile) map (before I was using GL NEAREST without problems). My map contains diagonal roads (just simple lines in this example). A partial overview example of my map (using the nearest filter without corrections) With the GL NEAREST filter, initially I added a 1 pixel border, so the tiles were slightly overlapping and the diagonal roads were draw without the small gaps at the edges of the tiles. This does not work with the GL LINEAR filter, because I suppose that the overlapping parts are drawn twice, resulting in a darker 'blob' I tried to get rid of the blobs, by making the horizontal lines shorter, but there is always an irregularity, either a blob or an 'decrease of line width' (as seen in the diagonal part of the line). So I removed the 1 pixel additional border and have this as a result Now I am trying to fill in the 'gaps' by drawing the two triangular fillers like this but I can't get it completely right (this is the best I managed to get) I suppose it is virtually impossible to get this perfectly right by 'manually' drawing these triangles. Also, when looking at the third image, the lines at the 'edges' (that need to be filled) are very sharp. I suppose this is problematic..? So, my question is how does one solve this problem? Do I need to prepare modify my textures for this? Can I use a shader to fill the gaps automatically? Is manually filling the gaps with the triangles the way to go? Or is there some entirely different technique to have smooth diagonal lines that span multiple tiles? |
1 | Geometry shader questions? I had some questions on geometry shaders. Do directx geometry shaders offer anything over the opengl ones? What advantages does the official geometry shader implementation on opengl 3.2 have over the plug in for 2.0? Is the official one faster? What are the oldest cards which support opengl 3.2 and the geometry shaders on there? What are the oldest cards which support opengl 2.0 and the geometry shader plugin? |
1 | OpenGL Black rectangle in rendering texture I create textures (for example, I just fill the texture color), and render their. But, for some reason, to the upper edge added black rectangle. Screenshot var Textures array of GLuint procedure LoadTexture(const TextureID Byte var Texture GLuint) var w, h Cardinal Data PByteArray begin if TextureID 0 then begin w 512 h 512 end else begin w 128 h 64 end GetMem(Data, w h 3) if TextureID 0 then FillChar(Data , w h 3, 204) else FillChar(Data , w h 3, 102) glBindTexture(GL TEXTURE 2D, Texture) glTexParameteri(GL TEXTURE 2D, GL TEXTURE MAG FILTER, GL NEAREST) glTexParameteri(GL TEXTURE 2D, GL TEXTURE MIN FILTER, GL LINEAR) glTexImage2D(GL TEXTURE 2D, 0, GL RGB8, w, h, 0, GL RGB, GL UNSIGNED BYTE, Data) FreeMem(Data, w h 3) Data nil end procedure glInit begin glEnable(GL TEXTURE 2D) SetLength(Textures, 2) glGenTextures(1, Textures 0 ) LoadTexture(0, Textures 0 ) glGenTextures(1, Textures 1 ) LoadTexture(1, Textures 1 ) glClearColor(1, 1, 1, 0) glShadeModel(GL SMOOTH) glClearDepth(1) glDisable(GL DEPTH TEST) glHint(GL PERSPECTIVE CORRECTION HINT, GL NICEST) glViewport(0, 0, 800, 600) glMatrixMode(GL PROJECTION) glLoadIdentity glOrtho(0, 800, 600, 0, 0, 1) glMatrixMode(GL MODELVIEW) glLoadIdentity end procedure glDraw begin glClearColor(1, 1, 1, 0) glClear(GL COLOR BUFFER BIT or GL DEPTH BUFFER BIT) glBindTexture(GL TEXTURE 2D, Textures 0 ) glBegin(GL QUADS) glTexCoord2f(0, 0) glVertex2f(0, 0) glTexCoord2f(1, 0) glVertex2f(512, 0) glTexCoord2f(1, 1) glVertex2f(512, 512) glTexCoord2f(0, 1) glVertex2f(0, 512) glEnd glBindTexture(GL TEXTURE 2D, Textures 1 ) glBegin(GL QUADS) glTexCoord2f(0, 0) glVertex2f(128, 64) glTexCoord2f(1, 0) glVertex2f(256, 64) glTexCoord2f(1, 1) glVertex2f(256, 128) glTexCoord2f(0, 1) glVertex2f(128, 128) glEnd end |
1 | Wireframe shader sometimes won't render parts depending on camera rotation I'm trying to make a stylized wireframe shader for a game using this method, but it seems to be conflicting with my character controller. Here's some images to better show what's going on https imgur.com a f48F3lN Basically, as I look around, some lines will disappear and reappear. It might have something to do with culling but the face is still visible, so theoretically shouldn't all the vertices still be rendered? It would also help if you knew of a better method for doing this as well. If it helps, I'm using OpenGL with c , and my shader code is functionally the same as what I linked to. |
1 | How can I efficiently render lots of 2D quads? I have lots of 2D quads. I write their local vertex position info to a buffer (accompanied with a world transform matrix) which gets sent to the render thread. I then pass the world transform matrix as a uniform into the vertex shader which applies itself to each vertex and works fine. I however have to make a call to glDrawElements() for each quad I want to render because each one has a different world transform. What is the most efficient way for me to render all of these quads? Should I do what I'm already doing, or should I calculate the world position for each vertex on the CPU before I write them to the buffer, so I can attempt to batch more quads into a single glDrawElements() call? Or is there another approach? |
1 | Qt opengl glTexImage2D in a widget I was doing an OpenGL display, where I render in an opengl context (GLUT). But now I would like to integrate it into a big project that does not use the Qt OpenGL API at all (QGLWidget, QOpenGLWidget, ). So I would have to display on QWidget for example using the function glTexImage2D () because it can take a Qimage input ((GLvoid ) Qimage.bits ()) |
1 | How to use modern OpenGL for 2D games? I've found a plethora of "modern" OpenGL (3.0 ) tutorials for 3D, but I have found next to nothing when looking for information on how to use it for 2D game development. How can I get started using OpenGL for 2D gamedev? Specifically, I'm interested in getting answers to the following topics How should I set up my various matrices for orthographic projection? Are shaders as heavily used in 2D applications as in 3D ones? If so, what is their purpose in the 2D setting? How should I handle the massive number of textures obviously required for a 2D game? I apologize for the relatively broad question, but I've spent a long time searching and I've found very little useful information that applies to modern OpenGL. |
1 | OpenGL picking performance ray casting vs. color picking I am curious of how the performance of color picking compares to ray casting. I am looking at the scenario when the mouse is clicked which means only then the scene is rendered in a backbuffer for color picking or ray cating has to be applied. Note I have found this question which unfortunatly does not give any indication. |
1 | What is actually drawn when glDrawArrays and glDrawElements are called? In my journey out of immediate mode I've come across a snag that I haven't been able to find a decent answer for in any tutorial or API, namely Which data structures are actually invoked when I make a call to a glDraw function in OpenGL3.3 ? For example, if I want to draw two 3D models and I've put their vertex data in two different VBO's, does invoking glDrawArrays draw everything set under the current VAO? Or does it only draw the currently bound VBO sampling from the currently bound texture? I basically understand VAO's and VBO's conceptually but its down to implementation that I'm running into problems, it's a big jump to go from the "stability" of immediate mode to the a synchronicity of modern OpenGL. |
1 | rotating 3D object around the center I have object moving from A to B on x axis and there is no translation of object apart from it. Now, while moving, i want to rotate it around y axis and the motion should change accordingly, i mean if i rotate it right when moving from x to x axis, it should move towards near plane. I have variable in gltranslatef which is modified in the loop after that i have glscalef to scale whole object which is made of hierarchical structure. Now i tried following code to achieve the expected result but its not working properly glTranslatef(move, 0, 0) If I comment these 3 lines, it does not affect the output glTranslatef( move, 0, 0) glRotatef(rotate,0,1,0) glTranslatef(move, 0, 0) glScalef(0.2, 0.2, 1.0) |
1 | Skybox texture artifact on edge I have strange problem with drawing skybox texture on Mac. On iPhone everything is going fine. I have tried to change near and far planes value with no success. It is a skybox of six textures, and for every texture I set this 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) What could be the problem? Screenshot EDIT I have tried to set background color to red, to ensure if it is bleeding through the texture I have also tried to change coords of the texture to this float err corr 0.5 TEXTURE SIZE GLfloat vertices 24 1.0f err corr, 1.0f err corr, 1.0f err corr, 1.0f err corr, 1.0f err corr, 1.0f err corr, 1.0f err corr, 1.0f err corr, 1.0f err corr, 1.0f err corr, 1.0f err corr, 1.0f err corr, 1.0f err corr, 1.0f err corr, 1.0f err corr, 1.0f err corr, 1.0f err corr, 1.0f err corr, 1.0f err corr, 1.0f err corr, 1.0f err corr, 1.0f err corr, 1.0f err corr, 1.0f err corr, And the box is drawn in this order GLubyte indices 14 0, 1, 2, 3, 7, 1, 5, 4, 7, 6, 2, 4, 0, 1 SOLUTION The solution is to set GL CLAMP TO EDGE for the cubemap itself! glTexParameteri(GL TEXTURE CUBE MAP, GL TEXTURE WRAP S, GL CLAMP TO EDGE) glTexParameteri(GL TEXTURE CUBE MAP, GL TEXTURE WRAP T, GL CLAMP TO EDGE) |
1 | How can I make a transparent hole with shaperenderer using stencil masking in libgdx? I'm making a 2d game, where I need a resizeable, moveable rectangle outline. I'm trying to use stencil masking to do it by cutting a hole in a solid rectangle, and I thought this would help How can I add a transparent overlay to a UI in libGDX? But all I get is a solid box. Here's my code Gdx.gl.glClear(GL STENCIL BUFFER BIT) Gdx.gl.glColorMask(false, false, false, false) Gdx.gl.glDepthMask(false) Gdx.gl.glEnable(GL20.GL STENCIL TEST) Gdx.gl.glStencilFunc(GL20.GL ALWAYS, 0x1, 0xffffffff) Gdx.gl.glStencilOp(GL REPLACE, GL REPLACE, GL REPLACE) shapeRenderer.begin(ShapeRenderer.ShapeType.Filled) shapeRenderer.box(cubby.xpos 5 , cubby.ypos 5, 0, cubby.size 10, cubby.size 10, 0) shapeRenderer.end() shapeRenderer.begin(ShapeRenderer.ShapeType.Filled) Gdx.gl.glColorMask(true, true, true, true) Gdx.gl.glDepthMask(true) Gdx.gl.glStencilFunc(GL NOTEQUAL, 0x1, 0xffffffff) Gdx.gl.glStencilOp(GL KEEP, GL KEEP, GL KEEP) shapeRenderer.box(cubby.xpos, cubby.ypos,0,cubby.size, cubby.size, 0) shapeRenderer.end() Gdx.gl.glDisable(GL20.GL STENCIL TEST) |
1 | 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. |
1 | glRotatef rotation never applied to 3d cube I have a floating cube that I want to rotate around the Y axis. The cube renders fine, the proper size, the proper coordinate, the proper texture faces, etc. However, the rotation is never applied. My update logic calculates a new rotation value, between 0 and 360. Set the coordinates, rotate Y axis GL11.glTranslatef(x,y,z) GL11.glRotatef(rotation, 0, 1f, 0) Each cube face rendered, etc... GL11.glColor3f( ... GL11.glTexCoord2f( .. GL11.glVertex3f .. No matter what combination I've tried, the cube never changes it's rotation. Update Per a comment, I was using glBegin outside the glRotatef and the comment advised that I use glPush Pop GL11.glPushMatrix() GL11.glTranslatef(x,adjY,z) GL11.glRotatef(rotation, 0f, 1f, 0) GL11.glPopMatrix() GL11.glBegin(GL11.GL QUADS) block.renderVertex(x,adjY,z,1,null,0.1f) GL11.glEnd() |
1 | Using depth texture for depth testing I was wondering if it is possible to render my scene onto a depth texture then using that texture for depth testing in another pass. I have an idea to that in shaders, but is that possible hardware side? |
1 | Synchronization between several glDispatchCompute with same SSBOs Let's say I have one compute shader A which writes to an SSBO, and then a second compute shader B which reads from the same SSBO. Do I need to do anything special to ensure that A has finished executing before B starts? |
1 | How do I implement a quaternion based camera? UPDATE The error here was a pretty simple one. I have missed a radian to degrees conversion. No need to read the whole thing if you have some other problem. I looked at several tutorials about this and when I thought I understood I tried to implement a quaternion based camera. The problem is it doesn't work correctly, after rotating for approx. 10 degrees it jumps back to 10 degrees. I have no idea what's wrong. I'm using openTK and it already has a quaternion class. I'm a noob at opengl, I'm doing this just for fun, and don't really understand quaternions, so probably I'm doing something stupid here. Here is some code (Actually almost all the code except the methods that load and draw a vbo (it is taken from an OpenTK sample that demonstrates vbo s)) I load a cube into a vbo and initialize the quaternion for the camera protected override void OnLoad(EventArgs e) base.OnLoad(e) cameraPos new Vector3(0, 0, 7) cameraRot Quaternion.FromAxisAngle(new Vector3(0,0, 1), 0) GL.ClearColor(System.Drawing.Color.MidnightBlue) GL.Enable(EnableCap.DepthTest) vbo LoadVBO(CubeVertices, CubeElements) I load a perspective projection here. This is loaded at the beginning and every time I resize the window. protected override void OnResize(EventArgs e) base.OnResize(e) GL.Viewport(0, 0, Width, Height) float aspect ratio Width (float)Height Matrix4 perpective Matrix4.CreatePerspectiveFieldOfView(MathHelper.PiOver4, aspect ratio, 1, 64) GL.MatrixMode(MatrixMode.Projection) GL.LoadMatrix(ref perpective) Here I get the last rotation value and create a new quaternion that represents only the last rotation and multiply it with the camera quaternion. After this I transform this into axis angle so that opengl can use it. (This is how I understood it from several online quaternion tutorials) protected override void OnRenderFrame(FrameEventArgs e) base.OnRenderFrame(e) GL.Clear(ClearBufferMask.ColorBufferBit ClearBufferMask.DepthBufferBit) double speed 1 double rx 0, ry 0 if (Keyboard Key.A ) ry speed e.Time if (Keyboard Key.D ) ry speed e.Time if (Keyboard Key.W ) rx speed e.Time if (Keyboard Key.S ) rx speed e.Time Quaternion tmpQuat Quaternion.FromAxisAngle(new Vector3(0,1,0), (float)ry) cameraRot tmpQuat cameraRot cameraRot.Normalize() GL.MatrixMode(MatrixMode.Modelview) GL.LoadIdentity() Vector3 axis float angle cameraRot.ToAxisAngle(out axis, out angle) THIS IS WHAT I DID WRONG I NEED TO CONVERT FROM RADIANS TO DEGREES BEFORE GL.Rotate(angle, axis) AFTER GL.Rotate(angle (float)180.0 (float)Math.PI, axis) GL.Translate( cameraPos) Draw(vbo) SwapBuffers() Here are 2 images to explain better I rotate a while and from this it jumps into this Any help is appreciated. Update1 I add these to a streamwriter that writes into a file sw.WriteLine("camerarot X 0 Y 1 Z 2 W 3 L 4 ", cameraRot.X, cameraRot.Y, cameraRot.Z, cameraRot.W, cameraRot.Length) sw.WriteLine("ry 0 ", ry) The log is available here http www.pasteall.org 26133 text. At line 770 the cube jumps from right to left, when camerarot.Y changes signs. I don't know if this is normal. Update2 Here is the complete project. |
1 | Looking for specific "textured quad" openGL tutorial in c I'm new to openGL and I've been googling around for the old and simple textured quad tutorial in openGL but I haven't been able to find one that suits my needs. OpenGL3.X compatible OpenGL ES 2.0 compatible AND Only uses core openGL library (no GLUT, GLEW...) I'm creating the window and the openGL context with SDL2. I only need the most basic stuff to draw quads. I'm not interested in any of the new OpenGL features, just in compatibility and cross platformness (Windows, OSX, Linux, Android and iOS). |
1 | What are the alternatives to OpenGL arrays for deferred rendering? I'm trying to build a deferred rendering technique in an OpenGL engine, but I can't figure how I could get more than the limit of 32 lights. I use an array in my shader, feed light properties into this array then loop through it and compute lightning, but I can't get more than 32 items into my array. What is a better alternative to this? |
1 | 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? |
1 | Quaternion rotation around center, undefined behavior Here's my code vec4 qx, qy, qz mat4 mx, my, mz rotating using quaternions glm quat(qx, to radians(a gt rx), 1.0f, 0.0f, 0.0f) glm quat(qy, to radians(a gt ry), 0.0f, 1.0f, 0.0f) glm quat(qz, to radians(a gt rz), 0.0f, 0.0f, 1.0f) turning the quaternions into matrices glm quat mat4(qx, mx) glm quat mat4(qy, my) glm quat mat4(qz, mz) mat4 trans 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 mat4 rot 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 mat4 final combining the rotations into one. glm mat4 mulN((mat4 ) amp mx, amp my, amp mz , 3, rot) translating the trans matrix. glm translate(trans, (vec3) a gt x, a gt y, a gt z ) finally combining the translation with the rotation into one. glm mat4 mul(trans, rot, final) My desired behavior is that the object rotates around its center, but here is what happens instead So , it seems that my object is rotating around some weird other undefined point. I have no idea why this happens. Any ideas? Thank you. |
1 | Combine textures with coordinates Is it possible to add one texture to another texture, at specific coordinates? Like if I want to add a small texture(16x16) to big texture (1368 x 768) with coordinates ( 100, 100) so the small texture goes to specific coordinates (100, 100 ). |
1 | 3D Studio MAX dxf model to OpenGL and DirectX Main Question I saw this Loading and Animating MD5 Models with OpenGL an old post explaining .md5mesh .md5anim files. Is there any similar alternate mechanisms? Additional Questions 1.) Is there an open source tool or a Plug in for 3ds max to convert a .DXF file to such files which can be used in 3D OpenGL DirectX game programming. 2.) If I am developing a game in this approach how to make these model files encrypted and make big single file which contains all this file, so that the user cannot crack hack it? 3.) If I am providing an update via an online gaming server, then how to I update this models and keep it encrypted again? |
1 | How to calculate normal from normal map in world space? (OpenGL) I'm trying to do normal mapping in a deferred renderer and I'm stuck on how to implement normal maps. I have a bool that passes whether or not to use a normal mapped value and thus, whether to calculate the TBN matrix. My vertex code for the geometry pass looks as follows version 410 core layout (location 0) in vec3 aPos layout (location 1) in vec3 aNormal layout (location 2) in vec2 aTexCoords layout (location 3) in vec3 aTangent Optional Texture coordinates layout (location 4) in vec3 aBitangent Optional Texture coordinates out vec3 FragPos out vec2 TexCoords out vec3 Normal out mat3 TBN uniform mat4 model uniform mat4 view uniform mat4 projection uniform bool hasNormalMap void main() vec4 worldPos model vec4(aPos, 1.0) FragPos worldPos.xyz TexCoords aTexCoords Normal transpose(inverse(mat3(model))) aNormal if(hasNormalMap) vec3 T normalize(vec3(model vec4(aTangent, 0.0))) vec3 N normalize(vec3(model vec4(aNormal, 0.0))) re orthogonalize T with respect to N T normalize(T dot(T, N) N) then retrieve perpendicular vector B with the cross product of T and N vec3 B cross(N, T) mat3 TBN mat3(T, B, N) gl Position projection view worldPos Here is where I am confused In my calculation, I multiplied T and N by the model matrix which should have moved it into world space. Now transposing (T,B,N) should move me back into model space (I think, I'm not sure). In the fragment shader how do I use the TBN to calculate the normal in world space? If there are better approaches, they are welcome. Thank you. Update I removed the transposing of the TBN as there's no reason to transform into tangent space if we want to pass it in world space. Now that we have the TBN matrix in the fragment shader, how do we apply it so that the normal is the correct value for lighting? Currently I've done version 410 core layout (location 0) out vec3 gPosition layout (location 1) out vec3 gNormal layout (location 2) out vec4 gAlbedoSpec in vec2 TexCoords in vec3 FragPos in vec3 Normal in mat3 TBN struct Material sampler2D diffuseMap sampler2D specularMap sampler2D normalMap float shininess uniform Material material uniform bool hasNormalMap void main() store the fragment position vector in the first gbuffer texture gPosition FragPos also store the per fragment normals into the gbuffer gNormal normalize(Normal) if(hasNormalMap) gNormal texture(material.normalMap, TexCoords).rgb TBN gNormal normalize(gNormal) and the diffuse per fragment color gAlbedoSpec.rgb texture(material.diffuseMap, TexCoords).rgb store specular intensity in gAlbedoSpec's alpha component gAlbedoSpec.a texture(material.specularMap, TexCoords).r but that doesn't feel right. I imagine that I would transform the sampled value from the normal map by the TBN matrix to get it in world space. Am I missing something? |
1 | OpenGL lighting with dynamic geometry I'm currently thinking hard about how to implement lighting in my game. The geometry is quite dynamic (fixed 3D grid with custom geometry in each cell) and needs some light to get more depth and in general look nicer. A scene in my game always contains sunlight and local light sources like lamps (point lights). One can move underground, so sunlight must be able to illuminate as far as it can get. Here's a render of a typical situation The lamp is positioned behind the wall to the top, and in the hollow cube there's a hole in the back, so that light can shine through. (I don't want soft shadows, this is just for illustration) While spending the whole day searching through Google, I stumbled on some keywords like deferred rendering, forward rendering, ambient occlusion, screen space ambient occlusion etc. Some articles tutorials even refer to "normal shading", but to be honest I don't really have an idea to even do simple shading. OpenGL of course has a fixed lighting pipeline with 8 possible light sources. However they just illuminate all vertices without checking for occluding geometry. I'd be very thankful if someone could give me some pointers into the right direction. I don't need complete solutions or similar, just good sources with information understandable for someone with nearly no lighting experience (preferably with OpenGL). |
1 | 2D pixels change size when scrolling I'm working on a 2D side scroller, OpenGL, pixel art. And I'm having trouble getting the pixels to remain square when scrolling the camera. By that I mean, when scrolling the camera at low speed when you have tile pixels being draw at 2x2 scale, you can see some pixels become 3x2 in size rather than 2x2. I've tried different ways of calculating the size of the orthographic projection in order to get the pixels sized correctly, and while they do usually appear correct when stationary, they always wobble while scrolling. Here is my latest attempt at calculating window size for the orthographic projection define TILE SIZE 32 Each tile is 32x32 define TILE MIN HEIGHT 10 Adjust pixel size to fit at east 10 tiles vertically in the window float windowRatio (float)window gt width (float)window gt height int pixelSize window gt height TILE SIZE TILE MIN HEIGHT float tileHeight (float)window gt height (pixelSize TILE SIZE) gameState gt windowTileWidth tileHeight windowRatio TILE SIZE gameState gt windowTileHeight tileHeight TILE SIZE window gt orthoProjection matrix44 createOrthographic2D( gameState gt windowTileWidth, gameState gt windowTileHeight ) So far, I've tried all of these in an attempt to eliminate the wobble Calculate orthographic projection as above, to fix at least 10 tiles vertically, adjusting projection size to fit window ratio. Calculate orthographic projection to exactly fit a 20x10 tile scene, scaling pixels to fit window. Render the scene to a 1 1 scale framebuffer, then blit that buffer to the window to scale it up to desired pixel size. Disable offsetting of texture coordinates (I draw tiles from a texture atlas, and so offset the coordinates by 0.001 inside each quad to eliminate bleed from surrounding textures). None of these have eliminated the wobbling. Sometimes it is extremely subtle, but still present when examining the movement closely. What is the correct way to draw a 2D image to the scree with perfect square pixel accuracy, at a given pixel size? |
1 | Can't use SFML sprite drawing and OpenGL rendering at the same time I'm using some SFML built in functions to draw sprites and text as an overlay on top of some OpenGL rending in an SFML RenderWindow. The opengl rendering appears fine until I add the code to draw the sprites or text. The sprite or text drawing causes the OpenGL stuff to disappear. The follow code show what I'm trying to do sf RenderWindow window(sf VideoMode(viewport.width,viewport.height,32), "SFML Window") glMatrixMode(GL PROJECTION) glLoadIdentity() glOrtho(0,viewport.width,0,viewport.height,0,1) while (window.pollEvent(Event)) event handling... begin drawing glClear(GL COLOR BUFFER BIT GL DEPTH BUFFER BIT) glBegin(GL TRIANGLES) glColor3f(col.x,col.y,col.z) for(int i 0 i lt 3 i ) glVertex2f(pos.x verts i .x,pos.y verts i .y) glEnd() adding this line causes all the previous opengl triangles not to appear window.draw("Sometext") window.display() |
1 | How to only render fragments with Z from 0 to 1 in OpenGL? I have been using OpenGL for a year now, but I just recently found out that OpenGL only clips vertices when the absolute value of the x,y or z coordinate is less than the absolute value of w coordinate. Previously I had assumed that the z coordinate would have to be 0 lt z lt w to be rendered. Is there any way to clip vertices with z less than 0, without a performance hit? I am using OpenGL 4.4 |
1 | How to create a 2D overlay over a 3D game? (LWJGL OpenGL) GameDev! I would like to create a 2D overlay over a 3D world, using LWJGL (Java version of OpenGL), to show information to the player, for example, a chat box, health bar, selected cannonball type, etc. Currently the code I have is this (Taken from several sources on the internet) glClear(GL COLOR BUFFER BIT GL DEPTH BUFFER BIT) glEnable(GL BLEND) GL11.glMatrixMode(GL11.GL PROJECTION) GL11.glLoadIdentity() glOrtho(0.0f, Display.getWidth(), Display.getHeight(), 0.0f, 0.0f, 1.0f) GL11.glMatrixMode(GL11.GL MODELVIEW) GL11.glLoadIdentity() glDisable(GL DEPTH TEST) glDisable(GL CULL FACE) glDisable(GL TEXTURE 2D) glDisable(GL LIGHTING) glDisable(GL DEPTH TEST) glDisable(GL CULL FACE) glDisable(GL BLEND) glDisable(GL TEXTURE 2D) glDisable(GL LIGHTING) glBegin(GL QUADS) glColor3f(1, 1, 1) glVertex2f(0, 0) glVertex2f(1, 1) glVertex2f(1, 0) glVertex2f(0, 1) glEnd() GL11.glMatrixMode(GL11.GL MODELVIEW) GL11.glLoadIdentity() glPopMatrix() glEnable(GL DEPTH TEST) glEnable(GL CULL FACE) glEnable(GL BLEND) glEnable(GL TEXTURE 2D) glEnable(GL LIGHTING) glEnable(GL DEPTH TEST) glEnable(GL CULL FACE) glEnable(GL TEXTURE 2D) glEnable(GL LIGHTING) glDisable(GL BLEND) GL11.glMatrixMode(GL11.GL PROJECTION) GL11.glLoadIdentity() Reset The Projection Matrix GLU.gluPerspective(45.0f, ((float) Display.getWidth() (float) Display.getHeight()), 0.1f, 5000.0f) Calculate The Aspect Ratio Of The Window GL11.glMatrixMode(GL11.GL MODELVIEW) glLoadIdentity() However this does not show a 2D scene at all! I would appreciate it if anybody could help me. Thanks! |
1 | C Freetype advance X problem I'm currently working on a font rendering system for my OpenGL based engine. I sure got something to work, but the only thing I still have problems with, is the horizontal advance! This is what it spits out, obviously not correct. If I understood correct from the documentation and some other threads, this is the procedure to draw a string set current drawing position to (0, 0) draw first character move drawing position in the x for advance.x draw second character move drawing position in the x for next face glyph advance.x ... repeat Is that correct? If not, what am I doing wrong? I think its worth to say that I render every character as a texture! |
1 | Why doesn't the y Axis work with SuperBible frame reference or GluLookAt I'm currently trying to understand how to use the GLFrame Class in the superbible book, and acording to the 4th edition of the book, the camera matrix derived from the Frame of reference class should work the same as GluLookAt When I add these lines cameraFrame.SetForwardVector( 0.5f, 0.0f, 0.5f) cameraFrame.Normalize() The camera looks in the correct direction, yaw at 45 Degrees (Am I doing that right!) However when I add this cameraFrame.SetForwardVector(0.0f, 0.5f, 0.5f) The camera just looks as if it was set to (0.0f, 0.0f, 1.0f) Why is this! It's been driving me mad for three days. Maybe I'm not passing in the vectors correctly, but I'm not sure how to pass in x,y 360 degrees for the look at (forward) location vector. Do the vectors have to be normalized before passing them in? Eventually I hope to do full mouse look (FPS style) , but for now just understanding why I can't make the camera simply pitch up would be a good start. Thansk! Here is the code in situ. Called to draw scene void RenderScene(void) Color values static GLfloat vFloorColor 0.0f, 1.0f, 0.0f, 1.0f static GLfloat vTorusColor 1.0f, 0.0f, 0.0f, 1.0f static GLfloat vSphereColor 0.0f, 0.0f, 1.0f, 1.0f Time Based animation static CStopWatch rotTimer float yRot rotTimer.GetElapsedSeconds() 60.0f Clear the color and depth buffers glClear(GL COLOR BUFFER BIT GL DEPTH BUFFER BIT) Save the current modelview matrix (the identity matrix) modelViewMatrix.PushMatrix() M3DMatrix44f mCamera My Code cameraFrame.SetForwardVector( 0.5f, 0.5f, 0.5f) cameraFrame.Normalize() End of my code cameraFrame.GetCameraMatrix(mCamera) modelViewMatrix.PushMatrix(mCamera) Transform the light position into eye coordinates M3DVector4f vLightPos 0.0f, 10.0f, 5.0f, 1.0f M3DVector4f vLightEyePos m3dTransformVector4(vLightEyePos, vLightPos, mCamera) Draw the ground shaderManager.UseStockShader(GLT SHADER FLAT, transformPipeline.GetModelViewProjectionMatrix(), vFloorColor) floorBatch.Draw() for(int i 0 i lt NUM SPHERES i ) modelViewMatrix.PushMatrix() modelViewMatrix.MultMatrix(spheres i ) shaderManager.UseStockShader(GLT SHADER POINT LIGHT DIFF, transformPipeline.GetModelViewMatrix(), transformPipeline.GetProjectionMatrix(), vLightEyePos, vSphereColor) sphereBatch.Draw() modelViewMatrix.PopMatrix() Draw the spinning Torus modelViewMatrix.Translate(0.0f, 0.0f, 2.5f) Save the Translation modelViewMatrix.PushMatrix() Apply a rotation and draw the torus modelViewMatrix.Rotate(yRot, 0.0f, 1.0f, 0.0f) shaderManager.UseStockShader(GLT SHADER POINT LIGHT DIFF, transformPipeline.GetModelViewMatrix(), transformPipeline.GetProjectionMatrix(), vLightEyePos, vTorusColor) torusBatch.Draw() modelViewMatrix.PopMatrix() "Erase" the Rotation from before Apply another rotation, followed by a translation, then draw the sphere modelViewMatrix.Rotate(yRot 2.0f, 0.0f, 1.0f, 0.0f) modelViewMatrix.Translate(0.8f, 0.0f, 0.0f) shaderManager.UseStockShader(GLT SHADER POINT LIGHT DIFF, transformPipeline.GetModelViewMatrix(), transformPipeline.GetProjectionMatrix(), vLightEyePos, vSphereColor) sphereBatch.Draw() Restore the previous modleview matrix (the identity matrix) modelViewMatrix.PopMatrix() modelViewMatrix.PopMatrix() Do the buffer Swap glutSwapBuffers() Tell GLUT to do it again glutPostRedisplay() |
1 | Using full resolution of depth buffer for 2D rendering I'm working on a front to back renderer for a 2D engine using an orthographic projection. I want to use the depth buffer to avoid overdraw. I have a 16 bit depth buffer, a camera at Z 100 looking at Z 0, zNear is 1, and zFar is 1000. Each sprite rendered sets its Z co ordinates to increasingly distant values, allowing depth test to skip rendering anything which is underneath. However I'm aware the way Z positions end up with Z buffer values is non linear. I want to make use of the full resolution of the 16 bit depth buffer, i.e. allowing 65536 unique values. So for every sprite rendered, I want to increment the Z position to the next position to correlate to the next unique depth buffer value. In other words I want to turn an incrementing index (0, 1, 2, 3...) of the sprite being drawn in to the appropriate Z position for each sprite to have a unique depth buffer value. I'm not sure of the maths behind this. What is the calculation to do this? Note I'm working in WebGL (basically OpenGL ES 2), and I need to support a wide range of hardware, so while extensions like gl FragDepth might make this easier, I can't use it for compatibility reasons. |
1 | What is the difference between OpenGL, SDL, DirectX, GLFW, GLUE? I have not work with graphics yet but I'd like to know its concepts at some high level overview. I was told that OpenGL and DirectX are somehow programmed into my graphics card, and I can use GLFW, SDL etc. to get access to those and manipulate them, by creating kind of different graphics objects. Analogy OpenGL programming language SDL framework Please, correct me politely. |
1 | Changing player color without multiple player bitmaps Possible Duplicate How to colorize certain parts of a model like RTS games have those team colors? Ok, so here is my current situation. I have a player model, fully UV mapped, and textured. At first I made multiple bitmaps for the character representing multiple colors for each team in the game. (red, blue, green, yellow, etc) Well, as my player count build up, space lowers. So I needed to make a new method of keeping the game effecient, clean, and fast. So I thought of the idea of having a color mask (alpha map covering the areas to be colored). I am using OpenGL, and I just have NO idea on where to begin! So I ask you, are there any libraries? methods? anything that could help me do this? |
1 | Would it perform faster to split calculation between vertex and fragment shaders? Assuming the total amount of computation would be the same (at least as far as my code goes), would there be any performance increase in splitting the calculation and using separate vertex and fragment shaders vs. doing all the calculations in just a fragment shader? In my use case, I would not be using vertex shaders as they are typically intended (so, not processing actual vertices). I just thought if the GPU hardware is set up such that the pipeline is expected to be used, would it be better to take advantage of that, or would it be just as fast to put it all in a fragment shader. Conceptually, it would be simpler to just use the fragment shader. Note, that I do need a lot of data going to the fragment shader that is updated every frame (eg. texture buffer object). |
1 | GLSL, all in one or many shader programs? I am doing some 3D demos using OpenGL and I noticed that GLSL is somewhat "limited" (or is it just me?). Anyway I have many different types of materials. Some materials have ambient and diffuse color, some materials have ambient occlusion map, some have specular map and bump map etc. Is it better to support everything in one vertex fragment shader pair or is it better to create many vertex fragment shaders and select them based on currently selected material? What is the usual shader strategy in OpenGL or D3D? |
1 | Bind render result to texture id I want to save the result screen of the rendering and then apply another shader on that result, the typical way is to read the screen using glReadPixels and then buffer that image to gpu and then apply my effect, so is there a way to bind the screen result to a texture id directory in gpu, instead of retrieving it back to CPU and then buffer it to GPU ? |
1 | How would I setup fog to follow a players coordinates? I'm wondering if its possible to setup a fog to a player's coordinates (where there is fog around the player to make it more third person) the main reason I ask this is because I have my player more towards the top right corner of the screen Here's some code that can give you a guide on what im doing glEnable(GL FOG) GLfloat FogColor 0.8,0.8,0.8,1.0 glFogfv(GL FOG COLOR,FogColor) glFogi(GL FOG MODE,GL LINEAR) glFogf(GL FOG START,30) glFogf(GL FOG END,) glHint(GL FOG HINT,GL NICEST) and I want the fog to follow a player with a position as said in posX,posY,posZ If anyone can turn this into some example code that would be very helpful, thanks If this is not possible then how would I setup the fog to be around a certain position of the camera, like show on the top right corner of the camera instead of the center? Here's a picture of the game screen so you can see what im talking about |
1 | Speed of procedural geometries I'm evaluating solutions for creating a VR videogame that should run on cellphones. The assets will be streamed from our servers and that could be a problem on limited capabilities devices. Since the geometries are not going to be too complex (mostly boxes and wardrobes) I was thinking about procedurally generating them. Is generating geometries procedurally usually faster or slower than just streaming a bunch of vertex data? |
1 | How to properly delete unwanted models I am implementing bullets into my game, and each bullet has a lifetime. Whenever the bullet has existed for a set amount of time or collides with an object, the bullet should be deleted. I implemented the timer properly and whenever the bullet reaches the end of its life, it gets deleted. The problem occurs whenever I shoot another bullet. This instantly causes a crash with the code Exception thrown at 0x044765D7 (nvoglv32.dll) in gravityGame.exe 0xC0000005 Access violation reading location 0x00000000. After some research, I've found that this usually means that I am trying to render something that is a nullptr. My thinking is that I am not deleting the previous bullet properly and this affects the new one. A single bullet object is created on startup, and every new bullet is copied using the following line of code std shared ptr lt Bullet gt bullet std make shared lt Bullet gt ( std dynamic pointer cast lt Bullet gt (modelsLoaded.at(i))) The reason for the dynamic pointer cast is because it is in a vector of its base class that it inherits from. Whenever the bullet needs to get deleted, it is erased from the bullets vector using bullets.erase(bullets.begin() index) and the object it is pointing to should go out of scope, there is nothing else pointing to it. I feel like somehow having that object getting deleted has an adverse effect on the other bullets in the vector, but I do not know how. A new object is created and all the data from the original bullet gets copied over. How could deleting a copy of an object mess with the other copied objects? The functions to create, and render the models are below. Generate Model Function 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) color attribute glVertexAttribPointer(1, 3, GL FLOAT, GL FALSE, 8 sizeof(float), (void )(3 sizeof(float))) glEnableVertexAttribArray(1) glBindBuffer(GL ELEMENT ARRAY BUFFER, EBO) glBufferData(GL ELEMENT ARRAY BUFFER, indicesSizeTexture 4, indicesTexture, GL STATIC DRAW) texture glBindTexture(GL TEXTURE 2D, texture) glVertexAttribPointer(2, 2, GL FLOAT, GL FALSE, 8 sizeof(float), (void )(6 sizeof(float))) glEnableVertexAttribArray(2) glBindBuffer(GL ARRAY BUFFER, 0) glBindVertexArray(0) Rendering Function unsigned int transformLoc glGetUniformLocation(shader gt ID, quot location quot ) glUniformMatrix4fv(transformLoc, 1, GL FALSE, glm value ptr(trans)) glBindTexture(GL TEXTURE 2D, texture) glBindVertexArray(VAO) glDrawElements(GL TRIANGLES, indicesSizeTexture, GL UNSIGNED INT, 0) glBindVertexArray(0) Destructor glDeleteVertexArrays(1, amp VAO) glDeleteBuffers(1, amp VBO) glDeleteBuffers(1, amp EBO) Update After removing the contents of the destructor, the problem goes away. However, I would like to have some sort of destructor to allow for the proper freeing of memory. |
1 | Create a white background for the texture and then blend using GLSL I have a transparent png texture and I'd like to create a white background and then blend this on top of that. Is this possible using just GLSL? I can't multiply, add or mix colors because I don't want to overlay the color white. I want it to be in the background of the texture. I can achieve what I want by creating 2 objects with the exact same dimensions and position, set the color of the object behind to white and the object in the front to the transparent texture. But this seems less than ideal to me. Any suggestions will be much appreciated! |
1 | Local shape color blending I am trying to implement this in Unity 4 Pro. But I am stuck in the blending part. I don't understand how you could blend multiples textures colors using multiples volumes on an object. How could you access those volumes in the shader and check for "collision"? It's seems to be very similar to vertex pixel lighting. But maybe I am wrong. Here is the simple effect I am trying to create. |
1 | Converting normalized device coordinates to world space coordinates flipping my sprites I'm trying to convert my game's camera system to use world space coordinates rather than OpenGL's default normalized device coordinates, however in doing so my sprites are being rendered improperly as you will see in the image below. Using GLM as my math library I have created a 4x4 orthographic matrix with the following code m orthoMatrix glm ortho(0.0f, (float) m screenWidth, (float) m screenHeight, 0.0f) I am then performing some translations (and scaling if by chance that is messing with anything) with the following code (m cameraMatrix is a 4x4 matrix) vec3 translation( m position.x, m position.y, 0.0f) m cameraMatrix glm translate(m orthoMatrix, translation) vec3 scale(m scale, m scale, 0.0f) m cameraMatrix glm scale(mat4(1.0f), scale) m cameraMatrix m scale is a float currently with my testing at value 1.0f. m position is a vec2 where in the image, the sprite on the right has values (0, 0) and the sprite on the left as values (screen width 2, 20). The issue, as you will notice, is that the sprites are rendered upside down, and I can't seem to fix it without getting rid of my translation math and going back to normalized coordinates. |
1 | Beginner question about vertex arrays in OpenGL Is there a special order in which vertices are entered into a vertex array? Currently I'm drawing single textures like this glBindTexture(GL TEXTURE 2D, texName) glVertexPointer(2, GL FLOAT, 0, vertices) glTexCoordPointer(2, GL FLOAT, 0, coordinates) glDrawArrays(GL TRIANGLE STRIP, 0, 4) where vertices has four "xy pairs". This is working fine. As a test I doubled the sizes of the vertices and coordinates arrays and changed the last line above to glDrawArrays(GL TRIANGLE STRIP, 0, 8) since vertices now contains eight "xy pairs". I do see two textures (the second is intentionally offset from the first). However the textures are now distorted. I've tried passing GL TRIANGLES to glDrawArrays instead of GL TRIANGLE STRIP but this doesn't work either. I'm so new to OpenGL that I thought it's best to just ask here ) Cheers! |
1 | Rotate an image and get back to its original position opengles glkit I need to rotate an image in opengles GLkit and get it back to its original position in GLkit. rotation 5 modelViewMatrix GLKMatrix4Rotate( modelViewMatrix, GLKMathDegreesToRadians(5), 1, 0, 0) modelViewMatrix GLKMatrix4Rotate( modelViewMatrix, GLKMathDegreesToRadians(rotation), 1,0,0) I need to move it in x axis for certain amount and getting back to its original position from where it started. How should i do it? |
1 | Optimizing texture fetches with higher mip levels Let's say I have some shader program in DirectX or OpenGL rendering a full screen quad. And in a pixel fragment shader I sample some huge textures at random texture coordinates. That is one same texture coordinate for all texture samplings in one shader invocation, but it is various among different shader invocations. These fetch operations produce performance drop, I even think that due to the size of the textures the GPU texture cache is not big enough and is used not efficiently. Now I have a theoretical question can I optimize the performance by using some low resolution like 32x32 mask textures, which are built by mipmapping the large textures, and if a value in a mask texture at given texture coordinate at some higher mip level is not appropriate, then I don't need to perform texture fetches at full size level 0? Something like this in HLSL (GLSL code is pretty similar, but there is no branch attribute) float2 tc calculateTexCoordinates() bool performHeavyComputations testValue(largeMipmappedTexture.SampleLevel(sampler, tc, 5)) float result 0 branch if (performHeavyComputations) result largeMipmappedTexture.SampleLevel(sampler, tc, 0) About 50 of texels at mip level 5 will not pass the test. And so a lot of shader invocations should not sample the full size textures. But I am introducing branching in the code. May this branching hurt the performance even worse than sampling the full size texture even if that is not needed? Different GPUs may behave differently, some may not even support branching, will they perform two fetches instead of one? I can test this code on some machines, but my question is theoretical. And can you suggest another optimizations, if this won't work properly ? |
1 | glVertexAttribPointer stride ambiguity As a hobbyist junior game programmer, I have done multiple small OpenGL projects just to have fun with 3D. I've tested VBOs in C and in Java and I found something or rather understood Java tutorials differently than the C ones. When using the glVertexAttribPointer function in Java, it is told that the parameter stride (second from the end) is the size of an entire vertex. void glVertexAttribPointer( GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, const GLvoid pointer) Considering the following my interpretation of the Java OpenGL tutorial, this is what should be done (as example) in C glVertexAttribPointer(vertexLoc, 3, GL FLOAT, GL FALSE, sizeof(MyVertex), BUFFER OFFSET(0)) glVertexAttribPointer(normalLoc, 3, GL FLOAT, GL FALSE, sizeof(MyVertex), BUFFER OFFSET(sizeof(float) 3)) glVertexAttribPointer(texCoord0Loc, 2, GL FLOAT, GL FALSE, sizeof(MyVertex), BUFFER OFFSET(sizeof(float) 6)) struct MyVertex float x, y, z float nx, ny, nz float s0, t0 Now I'm really confused because this works in my Java code. However, in my old C code, I was something like this glVertexAttribPointer(vertexLoc, 3, GL FLOAT, GL FALSE, sizeof(MyVertex) sizeof(aPosition), BUFFER OFFSET(0)) glVertexAttribPointer(normalLoc, 3, GL FLOAT, GL FALSE, sizeof(MyVertex) sizeof(aNormal), BUFFER OFFSET(sizeof(float) 3)) glVertexAttribPointer(texCoord0Loc, 2, GL FLOAT, GL FALSE, sizeof(MyVertex) sizeof(aTextCoord), BUFFER OFFSET(sizeof(float) 6)) My question is should the stride parameter be the size of an entire vertex in bytes or should it be the number of bytes separating another vertex attribute of the same type, i.e. the size between two normals, positions, texture coordinates, ect? |
1 | Time to render each frame is proportional to the amount of models in the scene This question is deliberately written in a "High Level" manor to avoid screeds and screeds of code snippets, hopefully I can get my point across, I am using C and OpenGL. I have a game engine, and in the engine I have my "game loop" that is called every frame, one of the things in this game loop is my call to Render(), before a call to SwapBuffers(), nothing new there. Essentially my engine draws the scene using a scene graph, that is I have GameObject's and each object has a GameComponent. So when the Render() is called in the "game loop" I get the root GameObject and render its GameComponent and then move onto the next GameObject and render its GameComponent, etc. until all GameObject's and each of their GameComponent's are drawn using glDrawElements(...). One of the GameComponent's a GameObject can have is a MeshRenderer, that is a Mesh paired with a Texture. In my scene I want to add loads of tree models, therefore I create for example 50 GameObject's that each have a MeshRenderer component (a tree) that will eventually in the game loop described above be drawn. The issue with this is that the time it takes to render a frame is directly proportional to the number of tree models I have (O(N) I think is how you word it). For example with 100 trees the render time is 23ms, with 200 trees it is 46ms, with 400 trees it is 90ms so on and so forth. This is terrible, I need at least 1000 trees in my "game world" and even at around 400 my game is "laggy". Because the time to draw a frame is proportional to the number of tees I know that each frame it is re drawing each mesh essentially (every frame drawing 100 trees, and then 200 and so on, and the time to draw scales with it) My question is this How can I store the mesh data so that I don't need to draw them from scratch every frame, I can just draw them once, and then re use that data for the next frame, but don't re draw it all? is there a way to firstly use glDrawElements(...), then store that mesh data(all the vertices etc.) and then every frame after call something like for example glDrawExcistingElements() instead of glDrawElements(...). Ultimately meaning that for consecutive frame draws the time is the exact same wether I have 1 tree or 1000 trees because the system is simply saying "here is the scene I already drew", instead of "lets draw it all again from scratch". |
1 | OpenGL How can I make the edges of this textured circle smoother? I'm building a game and I've applied a certain texture (RAW file) to a circle (GL POLYGON) in OpenGL. It loads correctly, with the right size and all, but the edges seem a bit jagged and I would prefer them smooth (without any evidence of a polygon being underneath). GLuint loadTex(int wrap) GLuint texture int width, height BYTE data FILE file file fopen( "tex.raw", "rb" ) if (file NULL) std cerr lt lt "O ficheiro da textura n o foi encontrado" lt lt std endl return 0 width 128 height 128 data (BYTE )malloc( width height 3 ) Aloca o do buffer fread( data, width height 3, 1, file ) Ler dados da textura fclose( file ) glGenTextures( 1, amp texture ) Nome da textura glBindTexture( GL TEXTURE 2D, texture ) Selec o da textura actual glTexEnvf( GL TEXTURE ENV, GL TEXTURE ENV MODE, GL MODULATE ) glTexParameterf( GL TEXTURE 2D, GL TEXTURE MIN FILTER, GL LINEAR MIPMAP NEAREST ) Par metros da Textura glTexParameterf( GL TEXTURE 2D, GL TEXTURE MAG FILTER, GL LINEAR ) glTexParameterf( GL TEXTURE 2D, GL TEXTURE WRAP S, wrap ? GL REPEAT GL CLAMP ) glTexParameterf( GL TEXTURE 2D, GL TEXTURE WRAP T, wrap ? GL REPEAT GL CLAMP ) gluBuild2DMipmaps( GL TEXTURE 2D, 3, width, height, GL RGB, GL UNSIGNED BYTE, data ) free(data) return texture void drawCircle(float cx, float cy, float r, float aspectRatio) GLuint t loadTex(1) float angle, radian, x, y, tx, ty, xcos, ysin glEnable(GL TEXTURE 2D) glBindTexture(GL TEXTURE 2D, t) glBegin(GL POLYGON) for (angle 0.0 angle lt 360.0 angle 2.0) radian angle (M PI 180.0f) xcos (float)cos(radian) ysin (float)sin(radian) x xcos r cx y ysin r aspectRatio cy tx xcos 0.5 0.5 ty ysin 0.5 0.5 glTexCoord2f(tx, ty) glVertex2f(x, y) glEnd() glDisable(GL TEXTURE 2D) Is this a problem from my texture file? Or is it from my code? I apply Line Smoothing before drawing anything (and it is being applied correctly in my lines I believe) |
1 | C OpenGL SDL2 VBO Depth problem Transparency I got a problem with my VBO. When having textures. The far blocks overlay the near ones. I tried editing the alpha, depth buffer, the VBO byte allocation. Nothing works for me... The FAR plane is overlapping the NEAR plane. Alpha glEnable(GL BLEND) glBlendFunc(GL SRC ALPHA, GL ONE MINUS SRC ALPHA) glEnable(GL DEPTH TEST) glDepthFunc(GL LEQUAL) glEnable(GL CULL FACE) glDisable(GL MULTISAMPLE) glDepthMask(GL TRUE) |
1 | SDL 2.0 OpenGL not drawing anything except background My 'hello triangle' compiles well, no errors, but doesn't drawing anything. Here's my code main.cpp include "src App.h" int main( int argc, char args ) App app(600, 400, false) app.Run() return 0 App.h ifndef APP H define APP H include lt SDL.h gt class App public explicit App(size t win width, size t win height, bool fullscreen mode) m window width(win width), m window height(win height), m fullscreen(fullscreen mode) void Run() private void Draw() void Update(double dt) void Resize(size t width, size t height) void ProcessEvents() private size t m window width size t m window height bool m fullscreen bool is done SDL Window m window SDL GLContext m glcontext endif APP H App.cpp include ".. App.h" include lt SDL opengl.h gt include lt cassert gt void App Run() SDL Init(SDL INIT VIDEO) m window SDL CreateWindow("Okno gry", SDL WINDOWPOS CENTERED, SDL WINDOWPOS CENTERED, m window width, m window height, SDL WINDOW OPENGL (m fullscreen?SDL WINDOW FULLSCREEN SDL WINDOW RESIZABLE)) m glcontext SDL GL CreateContext(m window) Resize(m window width, m window height) SDL GL SetAttribute(SDL GL DOUBLEBUFFER, 1) SDL GL SetAttribute(SDL GL CONTEXT PROFILE MASK, SDL GL CONTEXT PROFILE COMPATIBILITY) glClearColor(0, 0, 1, 0) glEnable(GL DEPTH TEST) glDepthFunc(GL EQUAL) is done false size t last ticks SDL GetTicks() while(!is done) ProcessEvents() size t ticks SDL GetTicks() double delta time (ticks last ticks) 1000 last ticks ticks if (delta time gt 0 ) Update(delta time) Draw() SDL Quit() void App Draw() glClear(GL COLOR BUFFER BIT GL DEPTH BUFFER BIT) glLoadIdentity() glBegin(GL TRIANGLES) glColor3f(1, 1, 0) glVertex2f(1, 1) glVertex2f(0, 1) glVertex2f(0, 0) glEnd() SDL GL SwapWindow(m window) void App ProcessEvents() if (is done) return SDL Event event while (SDL PollEvent( amp event)) if (event.type SDL WINDOWEVENT amp amp event.window.event SDL WINDOWEVENT SIZE CHANGED) Resize(event.window.data1, event.window.data2) else if (event.type SDL QUIT) is done true break void App Resize(size t width, size t height) m window width width m window height height glViewport(0, 0, static cast lt int gt (width), static cast lt int gt (height)) glMatrixMode(GL PROJECTION) glLoadIdentity() glOrtho(0, 1, 0, 1, 1, 10) glMatrixMode(GL MODELVIEW) glLoadIdentity() void App Update(double dt) printf(" d", dt) Can anyone help? I don't know why it's not running. |
1 | Texture coordinate discontinuity with mipmaps creates seams I just started learning openGL and I am getting this artifact when texturing a sphere with mipmaps. Basically when the fragment samples the edge of my texture, it detects the discontinuity (say from 1 to 0) and picks the smallest mipmap, which creates this ugly seam ugly seam http cdn.imghack.se images 6bbe0ad0173cac003cd5dddc94bd43c7.png So I tried to manually override the gradients using textureGrad fragVert is the original vertex from the vertex shader vec2 ll vec2((atan(fragVert.y, fragVert.x) 3.1415926 1.0) 0.5, (asin(fragVert.z) 3.1415926 0.5)) vec2 ll2 ll if (ll.x lt 0.01 ll.x gt 0.99) ll2.x .5 vec4 surfaceColor textureGrad(material.tex, ll, dFdx(ll2), dFdy(ll2)) Now I get two seams instead of one. How can I get rid of them? And why does the code above generate 2 seams? 2 eams http cdn.imghack.se images 44a38ef13cc2cdd801967c9223fdd2d3.png You can't tell from the two images but the 2 seams are on either side of the original seam. |
1 | Which code is faster to convert 1 to 0 and 1 to 1? I'm writing a shader for rendering the sides of triangles with different colors. I have a value mediump float back dot(V, N) which is positive if the normal faces away from the camera and negative if towards the camera. To correctly select which diffuse color to shade a particular fragment, I need something like this lowp vec4 color max(0.0, sign( back)) frontdiffuse max(0.0, sign(back)) back diffuse It's more or less an "unrolled conditional"... Which code produces faster instructions? x 0.5 0.5, or max(0.0, x) ? The former may be better mathematically behaved than the latter, but maybe min max clamping is super efficient in hardware |
1 | How do I render using VBOs? I'm trying to render a hemisphere in OpenGL, the problem that the hemisphere isn't rendered at all, only part of it. I initialize it, then at each frame I draw it using the following code. I'm trying to use a VBO for drawing it. void Jellyfish Init HemiSphere(const float radius, const int segments ) m iSegements segments m fVerts new float (segments 1) 2 3 m fNormals new float (segments 1) 2 3 m fTexCoords new float (segments 1) 2 2 for( int j 0 j lt segments 2 j ) float theta1 j 2 3.14159f segments ( 3.14159f ) float theta2 (j 1) 2 3.14159f segments ( 3.14159f ) for( int i 0 i lt segments i ) Vec3f e, p float theta3 i 2 3.14159f segments e.x math lt float gt cos( theta1 ) math lt float gt cos( theta3 ) e.y math lt float gt sin( theta1 ) e.z math lt float gt cos( theta1 ) math lt float gt sin( theta3 ) p e radius m fNormals i 3 2 0 e.x m fNormals i 3 2 1 e.y m fNormals i 3 2 2 e.z m fTexCoords i 2 2 0 0.999f i (float)segments m fTexCoords i 2 2 1 0.999f 2 j (float)segments m fVerts i 3 2 0 p.x m fVerts i 3 2 1 p.y m fVerts i 3 2 2 p.z e.x math lt float gt cos( theta2 ) math lt float gt cos( theta3 ) e.y math lt float gt sin( theta2 ) e.z math lt float gt cos( theta2 ) math lt float gt sin( theta3 ) p e radius m fNormals i 3 2 3 e.x m fNormals i 3 2 4 e.y m fNormals i 3 2 5 e.z m fTexCoords i 2 2 2 0.999f i (float)segments m fTexCoords i 2 2 3 0.999f 2 ( j 1 ) (float)segments m fVerts i 3 2 3 p.x m fVerts i 3 2 4 p.y m fVerts i 3 2 5 p.z glGenBuffers(3, amp SVboId 0 ) Vertex glBindBuffer(GL ARRAY BUFFER,SVboId 0 ) glBufferData(GL ARRAY BUFFER,sizeof( m fVerts) (m iSegements 1) 2 3, m fVerts,GL DYNAMIC DRAW) Normals glBindBuffer(GL ARRAY BUFFER,SVboId 1 ) glBufferData(GL ARRAY BUFFER,sizeof( m fNormals) (m iSegements 1) 2 3, m fNormals,GL DYNAMIC DRAW) void Jellyfish drawHemiSphere( ) glEnableClientState( GL VERTEX ARRAY ) glVertexPointer( 3, GL FLOAT, sizeof( m fVerts) (m iSegements 1) 2 3, m fVerts ) glEnableClientState( GL VERTEX ARRAY ) glBindBuffer(GL ARRAY BUFFER,SVboId 0 ) glVertexPointer( 3, GL FLOAT, 0, 0 ) glEnableClientState( GL NORMAL ARRAY ) glBindBuffer(GL NORMAL ARRAY,SVboId 1 ) glNormalPointer( GL FLOAT, 0,0 ) glEnableClientState( GL TEXTURE COORD ARRAY ) glTexCoordPointer( 2, GL FLOAT, sizeof( m fTexCoords) (m iSegements 1) 2 3, m fTexCoords ) glEnableClientState( GL NORMAL ARRAY ) glNormalPointer( GL FLOAT, sizeof( m fNormals) (m iSegements 1) 2 2, m fNormals ) for( int j 0 j lt m iSegements 2 j ) for( int i 0 i lt m iSegements i ) glDrawArrays( GL TRIANGLES, 0, (m iSegements 1) 2 ) glDisableClientState( GL VERTEX ARRAY ) glDisableClientState( GL TEXTURE COORD ARRAY ) glDisableClientState( GL NORMAL ARRAY ) |
1 | Skeletal Animation with UV seams I have a UV mapped model that I am about to animate and load into my game. Like most unwrapped models, I have several UV seams. In order to render the model correctly, I split each vertex along the seam into two vertices whose positions and normals are the same but whose UV coordinates differ. I do the same thing when I have more than one normal associated with a vertex. This works fine for static models, but now I'm getting into the realm of animation. Technically since the two seam vertices occupy the same position in space they should use the same joint weights and joint IDs. Right now the simple way to do this is to just give them the same joint weights and joint IDs and then skin them separately. But to me this seems very wasteful because there are so many vertices along seams and so there will be many duplicate computations. It gets even worse since I need to render the animated model into the shadow map too. Does anyone have any thoughts about improving this process? I've considered using something involving OpenGL transform feedback to save the results of the transformed vertices. This would at least help with computing transformed positions once and using the same results in the main render pass and shadow pass, but I still can't think of an elegant way to handle the duplicate computation along UV seams. |
1 | OpenGL Interpole keyframes of animated 3d object inside vertex shader Lets say I have N vertex buffers that hold the N key frames of an animated 3d object, that was created by an application like blender. To smoothly interpolate these frames, I would like to bind two buffers to render the object with a vertex shader like this in vec4 inPos0 in vec4 inPos1 in vec3 inNormal0 in vec3 inNormal1 ... other attributes... uniform float time void main() vec4 currentPos mix(inPos0,inPos1,time) ... other calculations ... To do this, the two buffers must be bound simultaneously, so I'd need to call glVertexAttribPointer every time, that a new keyframe should be used. This way buffer I can be bound to inPos0 and buffer I 1 to inPos1. My question Is this a good way to interpolate key frames? Or is there any builtin function to handle this scenario? |
1 | Blending for multiple lighting passes I am attempting to perform shadow mapping with deferred shading, using the following code for (auto light m ShadowDirs) render shadow map shadowDirPass(m ShadowBuffer, light) glEnable(GL BLEND) glBlendFunc(GL ONE, GL ONE) activate shader for non shadow casting lights m ShadowDirLightShader.activate() m FrameBuffer.LightingPass(m ShadowDirLightShader) m ShadowDirLightShader.setUniform(("WSCamPos"), m ActiveCamera gt getPosition()) m ShadowDirLightShader.setDirLight(("dirLight"), static cast lt DirLightData amp gt (light gt getLightData())) m ShadowDirLightShader.setUniform(("ShadowTransform"), m ShadowDirMatrix) bind depth map m ShadowDirLightShader.bindTexture(("shadowMap"),5, m ShadowBuffer.getDepthTexture()) render renderQuad() glDisable(GL BLEND) shadowDirPass(m ShadowBuffer, light) Simply renders the geometry to the shadow map. m FrameBuffer.LightingPass(m ShadowDirLightShader) Just binds the Gbuffer textures. I have two directional lights in the scene, one with red colour (1,0,0), and one with blue colour (0,0,1) One would think that the scene would be coloured purple, but no. Every time I render (for each) light, the image in the target framebuffer is overwritten completely, instead of blended together. To illustrate this, see the following images Above is the scene with a single red light. Above is the same scene, with a single blue light, but from a different direction. (See shadows). When I enable both lights, the result is as if the first light was never used, though by stepping through the code, I can confirm that it is definitely going through a render cycle. I'm pretty sure than I've messed up the blending somehow, but I could use some guidance. |
1 | rendering rolling hills I want to render very pretty smooth undulating hills. There are objects snuggled between these hills, so I can't really use naive bump mapping. I am currently rendering using a very detailed mesh that I generate myself. Its a lot of very small triangles. Are there other approaches? What is the current viability of displacement mapping, for example? I would like to run on mainstream hardware, including integrated graphics, and possibly even one day across to tablets and such. |
1 | How to detect GLSL warnings? After compiling a shader with glCompileShader, I can call glGetShaderiv with GL COMPILE STATUS to check if the shader compiled successfully. I can also call glGetShaderInfoLog to get information about possible errors, warnings or other info. The information log returned by this function is unspecified. In a tool where users can write their own shaders, I would like to print all errors and warnings from the compilation, but nothing if no warnings or errors were found. The problem is that the GL COMPILE STATUS returns only false if the compilation failed and true otherwise. If no problems were found, some drivers return empty info log from glGetShaderInfoLog, but some drivers can return something else such as "No errors.", which I do not want to print to the user. How is this problem generally solved? |
1 | OpenGl indices array I have a class terrain which create a grid of Quads. I do it like this for(int z 0 z lt length z ) for(int x 0 x lt width x ) vertices.push back(vec3((float)x 250, 0.f, (float)z 250)) for(int z 0 z lt ( length 1) z) for(int x 0 x lt ( width 1) x) int index z width x Vertex vertices Vertex(vertices.at(index),vec3(0, 0, 0)), Vertex(vertices.at(index 1),vec3(0, 0, 0)), Vertex(vertices.at(index width),vec3(0, 0, 0)), Vertex(vertices.at(index 1 width),vec3(0,0,0)) unsigned short indices index,index 1,index width,index 1,index width,index width 1 Quad quad( vertices, 4, indices, 6) squares.push back(quad) i The vertices and the logic are correct, but the indices aren't, for some reason. here is the output for this code But when I change this indices to this unsigned short indices 0,1,2,1,2,3 It works great The problem is I don't understand why this line unsigned short indices index,index 1,index width,index 1,index width,index width 1 doesn't work. And if it worked, my grid would consume a lot less ressources. If someone could explain me why it doesn't work, It would be great, thanks you. In case you need to know how I draw a Quad, here is the code class Quad public Quad(Vertex vertices, int n, unsigned short indices, unsigned short numIndices) for(int i 0 i lt numIndices i ) indices.push back( indices i ) for(int i 0 i lt n i ) vec3 v vec3( vertices i .position, lengthPower) position.push back(v) glGenVertexArrays(1, amp mVertexArray) glBindVertexArray(mVertexArray) glGenBuffers(1, amp mPositionBuffer) glBindBuffer(GL ARRAY BUFFER, mPositionBuffer) glBufferData(GL ARRAY BUFFER, sizeof(vec3) position.size(), position.data(), GL STATIC DRAW) glGenBuffers(1, amp mIndicesBuffer) glBindBuffer(GL ELEMENT ARRAY BUFFER, mIndicesBuffer) glBufferData(GL ELEMENT ARRAY BUFFER, sizeof(unsigned short) indices.size(), indices.data(), GL STATIC DRAW) void draw() glEnableVertexAttribArray(0) glBindBuffer(GL ARRAY BUFFER, mPositionBuffer) glVertexAttribPointer(0, 4, GL FLOAT, GL FALSE, 0, 0) glBindBuffer(GL ELEMENT ARRAY BUFFER, mIndicesBuffer) glDrawElements(GL TRIANGLES, indices.size(), GL UNSIGNED SHORT, 0) glDisableVertexAttribArray(0) Quad() private std vector lt unsigned short gt indices std vector lt vec3 gt position GLuint mVertexArray GLuint mPositionBuffer GLuint mIndicesBuffer I'm using, OpenGL, glm, glfw etc. |
1 | Generating geometry when using VBO Currently I am working on a project in which I generate geometry based on the players movement. A glorified very long trail, composed of quads. I am doing this by storing a STD Vector, and removing the oldest verticies once enough exist, and then calling glDrawArrays. I am interested in switching to a shader based model, usually examples I see the VBO is generated at start and then that's basically it. What is the best route to go about creating geometry in real time, using shader VBO approach |
1 | Why are some of my normals facing away from the camera? I'm trying to use WebGL to render some simple models, and I'm running into issues where pixels near the edge of my model are passing normals to my fragment shader that point away from the camera. This is of course messing with my attempts to use physically based shading, because BRDFs are only defined in the hemisphere around the normal vector. These normals aren't just slightly pointing away from the screen if that was the case, I would chalk it up to floating point error and clamp to acceptable values. But some of my pixels have v dot n values of 0.5 or less. This happens on pretty much any mesh I try to render. I have verified that my vertex normals point away from the mesh. I have backface culling turned on. This happens with both perspective and orthographic projections. I have tested in both Firefox and Chrome. Everything else about my render looks fine. My vertex shader looks like this precision mediump float uniform mat4 M uniform mat4 V uniform mat4 P attribute vec3 vertexPos model attribute vec3 vertexNormal model varying vec3 pos world varying vec3 normal world void main() gl Position P V M vec4(vertexPos model, 1.0) pos world (M vec4(vertexPos model, 1.0)).xyz We can use M here instead of its inverse transpose because it does not scale the model. normal world mat3(M) vertexNormal model And my fragment shader looks like this precision mediump float uniform vec3 cameraPos world varying vec3 pos world varying vec3 normal world void main() vec3 n normalize(normal world) vec3 v normalize(cameraPos world pos world) float vAngleCos dot(n, v) This will highlight pixels whose view vectors are outside of the hemisphere around n. gl FragColor vec4(vec3(clamp( vAngleCos, 0.0, 1.0)), 1.0) Rendering with the fragment shader above gives me results like this Apologies if I'm missing something obvious! |
1 | Fastest way to draw quads in OpenGL ES? I am using OpenGL ES 2.0 I have a bunch a quads to be drawn, would love to be able to have to pass only 4 vertices per quad as if I were using GL QUADS, but basically I just want to know the best way of drawing a bunch of separate quads. So far what I've found I could do GL TRIANGLES(6 vertices per quad) Degenerate GL TRIANGLE STRIP(6 vertices per quad) Possibilities I've found GL TRIANGLE STRIPS with a special index value that resets quad strip(this would mean 5 indexes per quad, but I don't think this is possible is OpenGL ES 2.0) |
1 | Panorama from cube map without geometry Is it possible to achieve effect equivalent to looking on the cube textured from cube map from its center, but without creation of its faces (6 quads or 12 triangles)? Say, one needed a skybox, but without the "box". There is no anything except skybox and there is no need to calculate depth of something all the points of that skybox are always visible. |
1 | How do I render using VBOs? I'm trying to render a hemisphere in OpenGL, the problem that the hemisphere isn't rendered at all, only part of it. I initialize it, then at each frame I draw it using the following code. I'm trying to use a VBO for drawing it. void Jellyfish Init HemiSphere(const float radius, const int segments ) m iSegements segments m fVerts new float (segments 1) 2 3 m fNormals new float (segments 1) 2 3 m fTexCoords new float (segments 1) 2 2 for( int j 0 j lt segments 2 j ) float theta1 j 2 3.14159f segments ( 3.14159f ) float theta2 (j 1) 2 3.14159f segments ( 3.14159f ) for( int i 0 i lt segments i ) Vec3f e, p float theta3 i 2 3.14159f segments e.x math lt float gt cos( theta1 ) math lt float gt cos( theta3 ) e.y math lt float gt sin( theta1 ) e.z math lt float gt cos( theta1 ) math lt float gt sin( theta3 ) p e radius m fNormals i 3 2 0 e.x m fNormals i 3 2 1 e.y m fNormals i 3 2 2 e.z m fTexCoords i 2 2 0 0.999f i (float)segments m fTexCoords i 2 2 1 0.999f 2 j (float)segments m fVerts i 3 2 0 p.x m fVerts i 3 2 1 p.y m fVerts i 3 2 2 p.z e.x math lt float gt cos( theta2 ) math lt float gt cos( theta3 ) e.y math lt float gt sin( theta2 ) e.z math lt float gt cos( theta2 ) math lt float gt sin( theta3 ) p e radius m fNormals i 3 2 3 e.x m fNormals i 3 2 4 e.y m fNormals i 3 2 5 e.z m fTexCoords i 2 2 2 0.999f i (float)segments m fTexCoords i 2 2 3 0.999f 2 ( j 1 ) (float)segments m fVerts i 3 2 3 p.x m fVerts i 3 2 4 p.y m fVerts i 3 2 5 p.z glGenBuffers(3, amp SVboId 0 ) Vertex glBindBuffer(GL ARRAY BUFFER,SVboId 0 ) glBufferData(GL ARRAY BUFFER,sizeof( m fVerts) (m iSegements 1) 2 3, m fVerts,GL DYNAMIC DRAW) Normals glBindBuffer(GL ARRAY BUFFER,SVboId 1 ) glBufferData(GL ARRAY BUFFER,sizeof( m fNormals) (m iSegements 1) 2 3, m fNormals,GL DYNAMIC DRAW) void Jellyfish drawHemiSphere( ) glEnableClientState( GL VERTEX ARRAY ) glVertexPointer( 3, GL FLOAT, sizeof( m fVerts) (m iSegements 1) 2 3, m fVerts ) glEnableClientState( GL VERTEX ARRAY ) glBindBuffer(GL ARRAY BUFFER,SVboId 0 ) glVertexPointer( 3, GL FLOAT, 0, 0 ) glEnableClientState( GL NORMAL ARRAY ) glBindBuffer(GL NORMAL ARRAY,SVboId 1 ) glNormalPointer( GL FLOAT, 0,0 ) glEnableClientState( GL TEXTURE COORD ARRAY ) glTexCoordPointer( 2, GL FLOAT, sizeof( m fTexCoords) (m iSegements 1) 2 3, m fTexCoords ) glEnableClientState( GL NORMAL ARRAY ) glNormalPointer( GL FLOAT, sizeof( m fNormals) (m iSegements 1) 2 2, m fNormals ) for( int j 0 j lt m iSegements 2 j ) for( int i 0 i lt m iSegements i ) glDrawArrays( GL TRIANGLES, 0, (m iSegements 1) 2 ) glDisableClientState( GL VERTEX ARRAY ) glDisableClientState( GL TEXTURE COORD ARRAY ) glDisableClientState( GL NORMAL ARRAY ) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.