Creating a voxel chunk with a VBO How to translate the coordinates of each block and add it to the VBO chunk? I'm trying to make a voxel engine similar to minecraft as a little learning experience and a way to learn some opengl. I have created a chunk class and I want to put all of the vertices for the whole chunk into a single VBO. I was previously only putting each block into a vbo and making a call to render each block. Anyways, I am a bit confused about how I can translate the coordinates of each block in the chunk when I'm putting all vertices into one vbo. This is what I have at the moment. public void putVertices(float tx, float ty, float tz) float l length 1.0f float l height 1.0f float l width 1.0f vertexPositionData.put(new float xOffset l length tx, l height ty, zOffset l width tz, xOffset l length tx, l height ty, zOffset l width tz, xOffset l length tx, l height ty, zOffset l width tz, xOffset l length tx, l height ty, zOffset l width tz, xOffset l length tx, l height ty, zOffset l width tz, xOffset l length tx, l height ty, zOffset l width tz, xOffset l length tx, l height ty, zOffset l width tz, xOffset l length tx, l height ty, zOffset l width tz, xOffset l length tx, l height ty, zOffset l width tz, xOffset l length tx, l height ty,zOffset l width tz, xOffset l length tx, l height ty,zOffset l width tz, xOffset l length tx, l height ty, zOffset l width tz, xOffset l length tx, l height ty, zOffset l width tz, xOffset l length tx, l height ty,zOffset l width tz, xOffset l length tx, l height ty, zOffset l width tz, xOffset l length tx, l height ty, zOffset l width tz, xOffset l length tx, l height ty, zOffset l width tz, xOffset l length tx, l height ty, zOffset l width tz, xOffset l length tx, l height ty, zOffset l width tz, xOffset l length tx, l height ty,zOffset l width tz, xOffset l length tx, l height ty,zOffset l width tz, xOffset l length tx, l height ty, zOffset l width tz, xOffset l length tx, l height ty, zOffset l width tz, xOffset l length tx, l height ty, zOffset l width tz ) public void createChunk() vertexPositionData BufferUtils.createFloatBuffer((24 3) activateBlocks) Random random new Random() for (int x 0 x lt CHUNK SIZE x ) for (int y 0 y lt CHUNK SIZE y ) for (int z 0 z lt CHUNK SIZE z ) if(blocks x y z .getActive()) putVertices(x 2.0f, y 2.0f, z 2.0f) What's any easy way to translate the vertices of each block into its correct position? I was previously using glTranslatef with each call to render block but this won't work now. What I am doing now also does not work, the blocks all render in stacks on top of each other and it looks like this Thanks


i want to upload to 2gb model animation to vram with VBO technic but i am getting this error with nvidia (with amd no error) when i try to work with amd its working with amd hd6870 and ati x1550 but when i try to work with gtx 950 its giving this error. if i upload less than 2gb example 300mb then its working but i want to upload 2gb. what can i do ? sorry for bad english.


OpenGL ES 2.0 Point Sprites Size I am trying to draw point sprites in OpenGL ES 2.0, but all my points end up with a size of 1 pixel...even when I set gl PointSize to a high value in my vertex shader. How can I make my point sprites bigger?


How can I adjust the origin for 2D UI in OpenGL? As I am quite used to screen geometry, where 0,0 is at the top left corner or the screen (as it is for just about every desktop app and Web app in the world), but I find it very hard to actually implement a UI in OpenGL since it's coordinate system is vertically inverted from what I have always worked with. I'm trying to implement a GUI for a plugin for the game Rising World, and this is driving me crazy. The added restriction that I have is that I do not have access to the actual screen resolution, but can only achieve full screen width and height using relative positioning and size (from 0 to 1). Sure, I can use pixels to position shapes and controls, but I cannot say, for example place this at 50 20 pixels it is either one or the other per shape. I am Googling for things I can read about UI design with "inverted" Y coordinates (i.e. since we read from top to bottom, it is inverted to me), but I can't find anything relevant. And since I cannot use any third party GUI library but what the game is offering, I am restricted to basic shapes and positioning (i.e. doing things 100 manually). Is there a way in this context that I can author my UI in a coordinate system where the origin is the top left?


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


OpenGL What to do after running glBufferData? I am interested in understanding a bit more behind how OpenGL does its memory management and what are some good practices before I start heavily coding and back myself into a corner. The real question I have is regarding memory. I have a class called Mesh that consists of a pointer to some vertex data, a pointer to the face data, as well as the number of vertices and faces. I am familiar with one possible process that OpenGL uses to get these drawn on the screen generate a buffer for vertices and a buffer for faces, bind them as GL ARRAY BUFFER and GL ELEMENT ARRAY BUFFER, call glBufferData to move the data to the buffers, and lastly call glDrawElements to draw them. From here I can understand how I can load several Mesh objects and draw them on screen, and I have no issue there. My question then lies in where the memory is stored and what I should be doing in order to conserve memory. My assumption is that after the call to glBufferData, the data is copied to the GPU (or to some other register to later be copied to the GPU). Is it safe for me to delete the original Mesh object that was used with the buffer calls? In my head, the mesh data is retained inside the GPU so the data is not lost, and so long as I do not need to reload this data using OpenGL later then I won't miss this data at any point. Also in my head, this frees up RAM space for other uses, so my Mesh, in some sense, now totally lives in GPU memory and nowhere else, and I can do my drawing solely by making OpenGL calls to the correct buffers (so I obviously need to save the generated buffer IDs, but that part goes without saying). If someone could tell me if this is correct incorrect logic, as well as good bad game dev practice?


Android Hardware Scaler I was reading through this using hardware scaler for performance and am a little confused by it. It says all you need to do to invoke the scaler is to set it like so surfaceView new GLSurfaceView(this) surfaceView.getHolder().setFixedSize(1280, 720) They says to use a fixed size for all devices. On my Google Nexus 10 (which has a resolution of 2560 x 1600). I've used 1280 800. It then goes on to say that the system will scale it to match the device's actual resolution. So this is what I get What am I missing here? Unfortunately the above link says that examples will be added soon but as yet there is nothing.


GLSL Efficient Point inside Box Check I'm attempting to improve the performance of a shader that changes the colour of a region of the world that is inside a "zone". I am using a deferred lighting system, so the colour and world space position of each pixel on the screen are stored in two separate textures, gColor and gPosition. The zonePos uniform stores the two corners of each zone. The zoneColor uniform stores the colour of each zone. The totalZones uniform stores the amount of zones in the current game. Here is the fragment shader out vec4 FragColor in vec2 texCoords layout (binding 0) uniform sampler2D gColor layout (binding 1) uniform sampler2D gPosition uniform vec3 zonePos 10 uniform vec3 zoneColor 5 uniform int totalZones void main() vec3 FragPos texture(gPosition, texCoords).rgb vec3 Albedo texture(gColor, texCoords).rgb vec3 j vec3 k for (int i totalZones i gt 0 i ) j zonePos i 2 k zonePos i 2 1 if (FragPos.x gt j.x amp amp FragPos.x lt k.x amp amp FragPos.y gt j.y amp amp FragPos.y lt k.y amp amp FragPos.z gt j.z amp amp FragPos.z lt k.z) Albedo zoneColor i FragColor vec4(Albedo, 1.0) The changes I have made so far are Using j and k, rather than accessing zonePos 6 times in the if statement Looping down from totalZones to 0, as a comparison against 0 is faster Any suggestions are greatly appreciated.


Fog shader camera problem I have some difficulties with my vertex fragment fog shader in Unity. I have a good visual result but the problem is that the gradient is based on the camera's position, it moves as the camera moves. I don't know how to fix it. Here is the shader code. struct v2f float4 pos SV POSITION float4 grabUV TEXCOORD0 float2 uv depth TEXCOORD1 float4 interpolatedRay TEXCOORD2 float4 screenPos TEXCOORD3 v2f vert(appdata base v) v2f o o.pos mul(UNITY MATRIX MVP, v.vertex) o.uv depth v.texcoord.xy o.grabUV ComputeGrabScreenPos(o.pos) half index v.vertex.z o.screenPos ComputeScreenPos(o.pos) o.interpolatedRay mul(UNITY MATRIX MV, v.vertex) return o sampler2D GrabTexture float4 frag(v2f IN) COLOR float3 uv UNITY PROJ COORD(IN.grabUV) float dpth UNITY SAMPLE DEPTH(tex2Dproj( CameraDepthTexture, uv)) dpth LinearEyeDepth(dpth) float4 wsPos (IN.screenPos dpth IN.interpolatedRay) Here is the problem but how to fix it float fogVert max(0.0, (wsPos.y Depth) ( DepthScale 0.1f)) fogVert fogVert fogVert (exp ( fogVert)) return fogVert Thanks a lot !


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


Should I batch up debug primitives for rendering in modern OpenGL? I've recently started porting some old rendering demos I did to modern OpenGL. I had a debug drawing class in my old code which used immediate mode glBegin(), glEnd() etc. for rendering debug objects such as triangles, cubes and spheres etc. Originally I replaced the code in these functions with code to generate the VAO and VBOs (for position and colour), bind them, assign the vertex data, render, then disable and delete the VBOs and VAO. Is there anything wrong with this? I've been thinking about modifying the class so that every time it gets a draw primitive call it generates the VAO and VBOs and assigns the vertex data but doesn't actually do the rendering until after all the other rendering has been completed. Then it renders all the debug prims that have been stored at once. I'm not sure of the benefits of either way of doing this and was just wondering what people thought.


How can I rotate a quad around it's center? My code is GL11.glPushMatrix() rotate around center GL11.glTranslatef( 200 2, 200 2, 0) GL11.glRotatef(30, 0.0f, 0.0f, 1) GL11.glTranslatef(200 2, 200 2, 0) draw quad GL11.glBegin(GL11.GL QUADS) GL11.glTexCoord2f(0f,0.5f) GL11.glVertex3f(50,50,1) GL11.glTexCoord2f(0.5f,0.5f) GL11.glVertex3f(50 200,50,1) GL11.glTexCoord2f(0.5f,0f) GL11.glVertex3f(50 200,50 200,1) GL11.glTexCoord2f(0f,0f) GL11.glVertex3f(50,50 200,1) GL11.glEnd() GL11.glPopMatrix() and it's not rotating it around the center, am I doing this correctly? if not how would I?


How do I calculate a vertex's position on the CPU? I'm creating light processor and I need light position and vertex position after translating, rotating and scaling (to calculate distance between them to check if light is affecting my vertex somehow). But my question is how to properly multiply my position in Vector3 with transformation matrix to get real vertex position in the world? To calculate it in GLSL I just simply use something like this vec4 vertexInWorldPosition transformMatrix vec4(vertexPosition,1.0) But how properly do that with my vertex (Stored in Vector3) and Matrix4 in C code? Do I need to multiply each row or column by my original vertexPosition stored to Vector4? I have no idea what to do.


Tips for writing 3D Collision detection with opengl I would like to any tips articles tutorials on how to write collision detection using OpenGL and C in 3D mainly just simple box collisions etc but also if there are any advanced resources that would be great to. i also don't wont to use any external library s if possible. thanks


OpenGL calculate UV sphere vertices I am trying to implement a class Sphere in C . Therefore I want to calculate the vertices in the constructor of the class (or in a seperate function..). Although I read tons of articles about creating spheres in different ways (UV Sphere, Quad Sphere, Icosphere etc.) I did not understand how to create the vertices for my buffer object. I decided to use the UV Sphere since it is easy to map a texture on it. A "UV sphere" in this sense is one where the (quad) edges run like lines of latitude and longitude, and the texture is mapped to the sphere like an equirectangular projection. (Equirectangular Earth texture by Strebe via Wikimedia Commons, CC BY SA 3.0) But how can I calculate all the vertex positions and texture coordinates? For my vertices I use a Vertex struct struct Vertex glm vec3 position glm vec2 texture


How can I make this tile map correctly? I'm having the following problem creating this hexa tiled map. this is what I wanted EDIT Ok I've Managed to do this const float scaleX ((float)tileWidth) 10000, scaleY ((float)tileHeight ) 10000 const float hexagon r scaleY 2 const float hexagon dx hexagon r cosf(30 3.14f 180.0) const float hexagon dy hexagon r sinf(30 3.14f 180.0) const float hexagon gx 2.0 hexagon dx const float hexagon gy 2.0 hexagon dx sinf(60 3.14f 180.0) Vector2 auxPos auxPos.x 0 auxPos.y 0 float j 0 for (unsigned int y 0 y lt layer gt layerHeight y , j hexagon gx 2) auxPos.y y (hexagon gy 2 ) auxPos.x j for (unsigned int x 0 x lt layer gt layerWidth x ) auxPos.x hexagon gx 2 float angle 90 3.14f 180 auxPos.y hexagon gy 2 SetData(stack gt vData, stack gt vCounter 0, auxPos.x (( scaleX) cosf(angle) ( scaleY) sinf(angle))) SetData(stack gt vData, stack gt vCounter 1, auxPos.y (( scaleX) sinf(angle) ( scaleY) cosf(angle))) SetData(stack gt vData, stack gt vCounter 2, layer gt layerDepth) SetData(stack gt vData, stack gt vCounter 3, auxPos.x ((scaleX) cosf(angle) ( scaleY) sinf(angle))) SetData(stack gt vData, stack gt vCounter 4, auxPos.y ((scaleX) sinf(angle) ( scaleY) cosf(angle))) SetData(stack gt vData, stack gt vCounter 5, layer gt layerDepth) SetData(stack gt vData, stack gt vCounter 6, auxPos.x ((scaleX) cosf(angle) (scaleY) sinf(angle))) SetData(stack gt vData, stack gt vCounter 7, auxPos.y ((scaleX) sinf(angle) (scaleY) cosf(angle))) SetData(stack gt vData, stack gt vCounter 8, layer gt layerDepth) SetData(stack gt vData, stack gt vCounter 9, auxPos.x (( scaleX) cosf(angle) (scaleY) sinf(angle))) SetData(stack gt vData, stack gt vCounter 10, auxPos.y (( scaleX) sinf(angle) (scaleY) cosf(angle))) SetData(stack gt vData, stack gt vCounter 11, layer gt layerDepth) can't seem to make this work...


Create 2D sprites with libGdx using a shape and a texture separately I am creating a 2D game with LibGdx that will have creatures that are generated from dozens of characteristics with potentially millions of unique combinations. For each segment of each creature, I want to use two sprites so that I can mix shapes and colors and cut down on my resources. I would like one sprite to be a black and white (or grayscale) of the shape of the body part while the second sprite is just a color pattern. I think I may need to write a shader that splices the color pattern onto my shape to give me the sprite I need. I just need some guidance on how to get started. Another way of explaining this is with the example of clothing. I want to be able to draw a shirt shape, and pants shape, a socks shape, etc. and also draw different fabric patterns. Then I would mix and match the clothing with the pattern instead of drawing every possible combination. How can I accomplish this with LibGdx?


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


Passing array to uniform in glsl error Here is my attemps to pass array to uniform array struct Vector float x,y,z float threshold 2 0.5, 0.25 Vector kernel new Vector kernel size kernel size 16 fill kernel glUniform1fv(glGetUniformLocation( program, "t"), 2, threshold) glUniform3fv(glGetUniformLocation( program, "kernel"), kernel size, (const GLfloat )kernel) because Vector contains only 3 float fields this kind of casting should be ok shader uniform float t 2 uniform vec3 kernel 16 And the results are weird. Only first float or first vector are filled with proper values. For example t 0.5, 7.1830559e 042 Even when I try change only one value (name "t 1 ") it doesn't work. I checked this on AMD CodeXL. My graphics card is Radeon HD 5770 and I have the newest drivers. I'm using OpenGL 3.3 and GLSL 330. What am I doing wrong?


Practice openGL or learn a specific engine? Possible Duplicate Should I use Game Engines to learn to make 3D games? I am a university student. I want to work in the game industry. Now I am thinking about either practicing my openGL skills or learn a complete new game engine during my time in school. I will do this by developing a smartphone game. I am debating over using just openGL or using a game engine. If I learn a game engine, then if the company I want to work for does not use that game engine, then wouldn't it be a waste of time to learn that game engine now instead of solidifying my openGL skills? So, openGL or game engine? Thanks.


JME3 Fragment Shader not compiling Here is the fragment shader code (MyShaders Shader1.frag) void main() gl FragColor vec4(1.0,1.0,1.0,1.0) And the vertex shader code (MyShaders Shader1.vert) void main(void) gl Position vec4(1.0,1.0,1.0,0.0) And the .j3md material code MaterialDef Shader1 MaterialParameters Technique VertexShader GLSL100 GLSL150 MyShaders Shader1.frag FragmentShader GLSL100 GLSL150 MyShaders Shader1.vert The error stack trace is WARNING Bad compile of 1 version 110 2 define FRAGMENT SHADER 1 3 void main(void) 4 5 6 gl Position vec4(1.0,1.0,1.0,0.0) 7 8 May 01, 2018 3 35 57 PM com.jme3.app.LegacyApplication handleError SEVERE Uncaught exception thrown in Thread jME3 Main,5,main com.jme3.renderer.RendererException compile error in ShaderSource name MyShaders Shader1.vert, defines, type Fragment, language GLSL100 ERROR 0 6 Use of undeclared identifier 'gl Position' And here is the code for instantiating the material Material mat new Material(assetManager,"MyShaders Shader1.j3md") I think that the bug is somewhere in me not passing any gl Position parameters into the shader, but how do I do that? I am using JME3 and Java.


Opengl Compute Shaders support? I have a question about compute shaders. My GPU is an AMD mobility Radeon 6490 which as the AMD website says supports OpenGL 4.1. However, when I check for my compatibility version via 'glGetString(GL VERSION)' I get 4.3.12618 Compatibility Profile Context 13.250.18.0. Does that mean I should be able to use compute shaders as they are introduced in OpenGL 4.3? If I try to create a compute shader in my program GLenum type GL COMPUTE SHADER is unknown but I'm not sure if newest headers are included. My GPU also supports the 'GL ARB compute shader' extension. So is there a special way to enable this extension or should I try to somehow include newer headers? Or will I not be able to use compute shaders at all (I don't want to use OpenCL)? Thanks for answer.


Giving values to uniform in OpenGL First thing is that I know how to give values to uniforms in OpenGL. Second thing is that it is a question related to optimization and performance. The habit for changing the uniforms, we preferred is like this Consider that we have shaders having 'aValue' as uniform During initialization GLint loc glGetUniformLocation(program, "aValue") During a loop or when required to change uniform's value if (loc ! 1) glUniform1f(loc, 0.75) But what if it is like this 'program' is a global variable Can be anywhere but not after destructing 'program' void updateUniformf( const char name, float value ) glUniform1f(glGetUniformLocation(program, name), value) During a loop or when required to change uniform's value updateUniformf("aValue", 0.75) How much would such approach decreases the performance? Or would this approach even affects the performance? It will be appreciable to have some measurements or practical example rather than all theories. Of course, I need to know reasons as well. Thanks for answering this question!


How do I ensure my skybox is always in the background, with OpenGL? I created a skybox in OpenGL (through LWJGL), but the only way I found to render it behind all objects was to make it very big. This leads to ugly edges between the 6 skybox planes. Optimally, I would draw a small skybox and disable DepthTesting on all other objects, but since I want those to display in the right depth order, that isn't possible. How can I do this?


Having problems with making a button class (checkIfClick) opengl Just basing how sfml does it, I get the globalbound of the object and then check if the mouseposition is within the object. I tried do something like that but I dont know exactly how to do it with opengl. I tried changing the projection from 1 to 1 coords to the size of the application in the hope I could just get the position of the object, but when doing std cout, it still shows the position in 1 to 1 coords. So my question is quot How would I convert my mouseposition to 1 to 1 or vi versa. quot Its actually 0 to 2 and not 1 to 1 So far i have this I dont know exactly how to get the top left right with opengl I know with sfml. I would use the position and subtract the half of the width and height to get it but like I said, idk how to do that in opengl. I tried doing that but the object position i still 1 to 1 even though I passed in the glm mat4 proj glm ortho(0,width, 0, height, 1,1) I know my projection is working, because when I enter any big number, my object gets really small. FYI, just because I see these types of answers alot I'm not asking you to write me a fully functional button class. I just want a general idea on how it would be done or some article that could help me do that (or a very basic example). void contain(glm vec2 position) if (position.x gt button.left amp amp position.x lt button.right amp amp position.y gt button.top amp amp position.y lt button.bottom) std cout lt lt quot True n quot else std cout lt lt quot False n quot


Do shader program compilers optimise divide by PoT constants to bitshift operations? So just to restate that, let's say we have this float f g 2 Given the divisor is a constant, will the shader compiler auto optimise this to a bitshift operation, as some language compilers are known to do? Where would I find more info on shader program compiler implementation details? (I'm guessing there will be different answers for OpenGL amp DirectX.)


OpenGL ES 2.0 Controlling Transparency in Fragment Shader The following is the OpenGL ES 2.0 simple GLSL Fragment Shader, I use to place textures on polygons, to render 2D sprites. varying mediump vec2 TextureCoordOut uniform sampler2D Sampler void main() gl FragColor texture2D(Sampler, TextureCoordOut) gl FragColor vec4(texture2D(Sampler, TextureCoordOut).xyz, TextureCoordOut.w 0.5) The fragment shader places voxels with alpha information taken from the source 2D texutre(.png image). Apart from alpha information, I need to control overall polygon sprite transparency to achieve Fade In Fade Out effects. Could you show me, please, how to modify the above shader to control the overall transparency, besides the alpha information? Note The commented out line is used for my attempts to achieve the transparency. I wish to combine both the alpha information with the overall polygon sprite transparency. Thanks.


Why is the size of glm's vec3 struct 12 bytes? When trying to determine the size of glm vec3 (from GLM math library) by using the size of operator like so sizeof(glm vec3) I get 12 returned. When I look at the definition of a vec3 struct I see this template lt typename T, precision P defaultp gt struct tvec3 Implementation detail typedef tvec3 lt T, P gt type typedef tvec3 lt bool, P gt bool type typedef T value type ifdef GLM META PROG HELPERS static GLM RELAXED CONSTEXPR length t components 3 static GLM RELAXED CONSTEXPR precision prec P endif GLM META PROG HELPERS Data if GLM HAS ANONYMOUS UNION union struct T x, y, z struct T r, g, b struct T s, t, p ifdef GLM SWIZZLE GLM SWIZZLE3 2 MEMBERS(T, P, tvec2, x, y, z) GLM SWIZZLE3 2 MEMBERS(T, P, tvec2, r, g, b) GLM SWIZZLE3 2 MEMBERS(T, P, tvec2, s, t, p) GLM SWIZZLE3 3 MEMBERS(T, P, tvec3, x, y, z) GLM SWIZZLE3 3 MEMBERS(T, P, tvec3, r, g, b) GLM SWIZZLE3 3 MEMBERS(T, P, tvec3, s, t, p) GLM SWIZZLE3 4 MEMBERS(T, P, tvec4, x, y, z) GLM SWIZZLE3 4 MEMBERS(T, P, tvec4, r, g, b) GLM SWIZZLE3 4 MEMBERS(T, P, tvec4, s, t, p) endif GLM SWIZZLE other code...... For which I see three structs, each with three member variables of templated type T, which in GLM defaults to float type. My question is why is the sizeof() operator returning 12 bytes as the size of glm vec3 when it looks like it should be 36 bytes 3 structs, with 3 float members each 3 3 4(number of bytes in a float) 36.


Rotate a plane defined by its normal and its distance First apologies for the amount of pictures, it's a bit hard trying to explain my problem without pictures. Hope I've provided all the relevant code. If you feel you want to know about how I am doing something else, please tell me and I will include it. I've been trying to work around rotating a plane in 3D space, but I keep hitting dead ends. The following is the situation I have a physics engine where I simulate a moving sphere inside a cube. To make things simpler, I have only drawn the top and bottom plane and moved the sphere vertically. I have defined my two planes as follows CollisionPlane p new CollisionPlane(glm vec3(0.0, 1.0, 0.0), 5.0) CollisionPlane p2 new CollisionPlane(glm vec3(0.0, 1.0, 0.0), 5.0) Where the vec3 defines the normal of the plane, and the second parameter defines the distance of the plane from the normal. The reason I defined their distance as 5 is because I have scaled the the model that represents my two planes by 10 on all axis, so now the distance from the origin is 5 to top and bottom, if that makes any sense. To give you some reference, I am creating my two planes as two line loops, and I have a model which models those two line loop, like the following top plane std shared ptr lt Mesh gt f1 std make shared lt Mesh gt (GL LINE LOOP) std vector lt Vertex gt verts Vertex(glm vec3(0.5, 0.5, 0.5)), Vertex(glm vec3(0.5, 0.5, 0.5)), Vertex(glm vec3( 0.5, 0.5, 0.5)), Vertex(glm vec3( 0.5, 0.5, 0.5)) f1 gt BufferVertices(verts) bottom plane std shared ptr lt Mesh gt f2 std make shared lt Mesh gt (GL LINE LOOP) std vector lt Vertex gt verts2 Vertex(glm vec3(0.5, 0.5, 0.5)), Vertex(glm vec3(0.5, 0.5, 0.5)), Vertex(glm vec3( 0.5, 0.5, 0.5)), Vertex(glm vec3( 0.5, 0.5, 0.5)) f2 gt BufferVertices(verts2) std shared ptr lt Model gt faceModel std make shared lt Model gt (std vector lt std shared ptr lt Mesh gt gt f1, f2 ) And like I said I scale the model by 10. Now I have a sphere that moves up and down, and collides with each face, and the collision response is implemented as well. The problem I am facing is when I try to rotate my planes. It seems to work fine when I rotate around the Z axis, but when I rotate around the X axis it doesn't seem to work. The following shows the result of rotating around Z However If I try to rotate around X, the ball penetrates the bottom plane, as if the collisionplane has moved down The following is the code I've tried to rotate the normals and the planes for (int i 0 i lt m entities.size() i) glm mat3 normalMatrix glm mat3 cast(glm angleAxis(glm radians(6.0f), glm vec3(0.0, 0.0, 1.0))) CollisionPlane p (CollisionPlane )m entities i gt GetCollisionVolume() glm vec3 normalDivLength p gt GetNormal() glm length(p gt GetNormal()) glm vec3 pointOnPlane normalDivLength p gt GetDistance() glm vec3 newNormal normalMatrix normalDivLength glm vec3 newPointOnPlane newNormal (normalMatrix (pointOnPlane glm vec3(0.0)) glm vec3(0.0)) p gt SetNormal(newNormal) float newDistance newPointOnPlane.x newPointOnPlane.y newPointOnPlane.z p gt SetDistance(newDistance) I've done the same thing for rotating around X, except changed the glm vec3(0.0, 0.0, 1.0) to glm vec3(1.0, 0.0, 0.0) m entites are basically my physics entities that hold the different collision shapes (spheres planes etc). I based my code on the answer here Rotating plane with normal and distance I can't seem to figure at all why it works when I rotate around Z, but not when I rotate around X. Am I missing something crucial?


OpenGL Texture disappears I'm making a simple program with C , SDL and GLEW. So far it is going great but I ran into a weird problem. One of my four textures would not show up on screen even though it used the same code as the other three. EXAMPLE https www.dropbox.com s 4038p0yv041mhdy Sk C3 A4rmdump 202014 09 10 2021.37.48.png?dl 0 HOW IT SHOULD BE https www.dropbox.com s huhln17zjip1pjb Sk C3 A4rmdump 202014 09 10 2021.39.04.png?dl 0 But the weird thing is how I fixed it. NOT WORKING sprite 0 .init(0.0f, 0.0f, 1.0f, 1.0f, "kitten.png") sprite 1 .init( 1.0f, 1.0f, 1.0f, 1.0f, "kitten1.png") sprite 2 .init(0.0f, 1.0f, 1.0f, 1.0f, "kitten1.png") sprite 3 .init( 1.0f, 0.0f, 1.0f, 1.0f, "kitten.png") WORKING sprite 1 .init(0.0f, 0.0f, 1.0f, 1.0f, "kitten.png") Switched around the 0 and the 1 sprite 0 .init( 1.0f, 1.0f, 1.0f, 1.0f, "kitten1.png") sprite 2 .init(0.0f, 1.0f, 1.0f, 1.0f, "kitten1.png") sprite 3 .init( 1.0f, 0.0f, 1.0f, 1.0f, "kitten.png") I only changed the index when the init function was called and all of a sudden it started to work again. So my question is Why does the texture not display when I'm using index 1 but working when I'm using index 0. Nothing happened when I only changed the draw function. INIT FUNCTION void Sprite init(float x, float y, float w, float h, std string image) Loads image, initilaze the varibles and generate the Vertex Buffer Object(VBO) texture ResourceManager getTexture(image) x x y y w w h h if( vboid 0) glGenBuffers(1, amp vboid) if( eboid 0) glGenBuffers(1, amp eboid) The vertex data Vertex vertexData 4 Specify which vertices to reuse GLuint elementdata 6 0, 1, 2, 2, 3, 0 Top right corner position vertexData 0 .setPosition( x w, y h) vertexData 0 .setTexCoord(1, 0) Top left corner position vertexData 1 .setPosition( x, y h) vertexData 1 .setTexCoord(0, 0) Bottom left corner position vertexData 2 .setPosition( x, y) vertexData 2 .setTexCoord(0, 1) Bottom right corner position vertexData 3 .setPosition( x w, y) vertexData 3 .setTexCoord(1, 1) for(int i 0 i lt 4 i ) vertexData i .setColor(255, 255, 255, 255) Let's set some special color Binds the buffer, then upload data to the GPU and the last thing it does is unbind the buffer glBindBuffer(GL ARRAY BUFFER, vboid) glBufferData(GL ARRAY BUFFER, sizeof(vertexData), vertexData, GL DYNAMIC DRAW) glBindBuffer(GL ARRAY BUFFER, 0) glBindBuffer(GL ELEMENT ARRAY BUFFER, eboid) glBufferData(GL ELEMENT ARRAY BUFFER, sizeof(elementdata), elementdata, GL DYNAMIC DRAW) glBindBuffer(GL ELEMENT ARRAY BUFFER, 0)


How can i port my OpenGL game to linux? I made a game with OpenGL 4.3(core profile) and C . I used GLFW3 for window and context management. I am also using bunch of third party library which are also available for linux. What things do i need to consider if i want to port the game and how can i make it support all windows and linux?


3d Picking under reticle i'm currently trying to work out some 3d picking code that I started years ago, but then lost interested the assignment was completed (this part wasn't actually part of the assignment). I am not using the mouse coords for picking, i'm just using the position in 3d space and a ray directly out from there. A small hitch though is that I want to use a cone and not a ray. Here are the variables i'm using float iReticleSlope 95 3000 inverse reticle slope float baseReticle 1 radius of the reticle at z 0 float maxRange 3000 max range to target Quaternion orientation the cameras orientation Vector3d position the cameras position Then I loop through each object in the world Vector3d transformed object position after transformations float d, r holder variables for(i 0 i lt objects.length i ) transformed position objects i .position transform the position relative to camera orientation.multiply(transformed) orient the object relative to the camera if(transformed.z lt 0) d sqrt(transformed 0 transformed 0 transformed 1 transformed 1 ) r transformed 2 iReticleSlope objects i .radius if(d lt r amp amp transformed 2 objects i .radius lt maxRange) the object is under the reticle else the object is not under the reticle else the object is not under the reticle Now this all works fine and dandy until the window ratio doesn't match the resolution ratio. Is there any simple way to account for that


Stencil buffer mask calculation I dont understand how exactly stencil buffer works in openGL. One aspect that confuses me is why do we use a bit operator there in glStencilFunc. Some text say that is is used to achieve multiple stencil planes but I am not sure how that can be done. Can anybody please explain the whole procedure of stencil buffer calculation during the rendering cycle. Thank you.


glReadPixels with GL DEPTH COMPONENT into PBO is slow I need to read depth buffer back to cpu memory. It may be few frames old, so I use glReadPixels with a buffer bound to GL PIXEL PACK BUFFER. I use several buffers and ping pong them. Finally, I read from the PBO with glGetBufferSubData. I have tried creating the buffers with GL STATIC READ, GL DYNAMIC READ and GL STREAM READ all with same results. Unfortunately, all this is still horribly slow. class DepthBuffer private static const uint32 PboCount 2 Buffer buffer uint32 index uint32 pbo PboCount uint32 w PboCount , h PboCount public DepthBuffer() DepthBuffer() void performCopy(uint32 fbo, uint32 w, uint32 h) returns 0..1 in logarithmic depth float valuePix(uint32 x, uint32 y) pix in 0..(cw ch 1) float valueNdc(float x, float y) ndc in 1..1 DepthBuffer DepthBuffer() index(0), pbo 0, 0 , w 0, 0 , h 0, 0 glGenBuffers(PboCount, pbo) DepthBuffer DepthBuffer() glDeleteBuffers(PboCount, pbo) void DepthBuffer performCopy(uint32 fbo, uint32 paramW, uint32 paramH) copy framebuffer to pbo glBindBuffer(GL PIXEL PACK BUFFER, pbo index ) if (w index ! paramW h index ! paramH) glBufferData(GL PIXEL PACK BUFFER, paramW paramH sizeof(float), nullptr, GL STREAM READ) w index paramW h index paramH glBindFramebuffer(GL READ FRAMEBUFFER, fbo) CHECK GL FRAMEBUFFER(GL READ FRAMEBUFFER) glReadPixels(0, 0, w index , h index , GL DEPTH COMPONENT, GL FLOAT, 0) CHECK GL("read the depth (framebuffer to pbo)") copy gpu pbo to cpu buffer index (index 1) PboCount float depths nullptr uint32 reqsiz w index h index sizeof(float) if (buffer.size() lt reqsiz) buffer.allocate(reqsiz) depths (float )buffer.data() glBindBuffer(GL PIXEL PACK BUFFER, pbo index ) glGetBufferSubData(GL PIXEL PACK BUFFER, 0, w index h index sizeof(float), depths) glBindBuffer(GL PIXEL PACK BUFFER, 0) CHECK GL("read the depth (pbo to cpu)") float DepthBuffer valuePix(uint32 x, uint32 y) if (w index h index 0) return nan1() assert(x lt w index amp amp y lt h index ) return ((float )buffer.data()) x y w index float DepthBuffer valueNdc(float x, float y) assert(x gt 1 amp amp x lt 1 amp amp y gt 1 amp amp y lt 1) return valuePix((x 0.5 0.5) (w index 1), (y 0.5 0.5) (h index 1)) The glReadPixels is taking all the time (on cpu). Am I doing something wrong? I thought that reading into the PBO should be asynchronous. Thanks.


Using same buffer for vertex and index data? Is it possible to use the same buffer for both GL ARRAY BUFFER and GL ELEMENT ARRAY BUFFER? I load both vertex data and index data into a big slab of memory, so it would be easier for me to just load it all into a single buffer. So naturally, I do like this glBindBuffer(GL ARRAY BUFFER, vboId) glBufferData(GL ARRAY BUFFER, dataSize, data, usage) glBindBuffer(GL ARRAY BUFFER, 0) Is it legal to ndash during rendering ndash simply use it as both? glBindBuffer(GL ARRAY BUFFER, vboId) glBindBuffer(GL ELEMENT ARRAY BUFFER, vboId) glVertexAttribPointer(...) ... glDrawElements(mode, count, dataType, (void )indexOffset) I can't find anything in the spec saying it's ok to do so, but I can't find anything that says that I can't either. Googling doesn't turn up much either, but I might be looking in the wrong places.


Accessing struct in glut I have to write a game for a uni project using openGL glut. I am just going to use a generic example code as I'm just looking for a solution to one specific problem Using glut, I have to call a function 'glutDisplayFunc(display) ' in the main function. I am also using an IdleFunc(update). The problem is that, as described here, the 'display' function cannot pass anything. I have some structs outside my main that I wish to be initialized in the main, and be accessible by display and update. Hopefully some code will explain my problem better include lt gl glut.h gt struct Player GLfloat x GLfloat y GLfloat z int score ... function prototypes (showing how I would normally pass the struct) void InitPlayer (Player amp player) void DrawPlayer (Player amp player) void UpdatePlayer (Player amp player) void main (int argc, char argv) Player player InitPlayer(player) ... glut openGL initialisation code left out ... glutDisplayFunc (display) glutReshapeFunc (reshape) glutIdleFunc (update) glutMainLoop() void display() DrawPlayer(player) void update () UpdatePlayer(player) glutPostRedisplay () end The above code doesn't work I hope it demonstrates what I would like to do though. Access the struct 'player' in 'display' and 'update', having the same values stored globally. How would I go about ?


Underwater Shader Animation Help I found an underwater (distort) effect and I got it to work but somehow I cannot make it animate given the offset here Fragment Shader code uniform sampler2D fbo texture uniform float offset varying vec2 f texcoord void main(void) vec2 texcoord f texcoord texcoord.x sin(texcoord.y 4 2 3.14159 offset) 100 gl FragColor texture2D(fbo texture, texcoord) Original Source here


Geometric Transformations on the CPU vs GPU I've noticed that many 3d programs normally do vector matrix calculations as well as geometric transformations on the CPU. Has anyone found an advantage in moving these calculations into vertex shaders on the GPU?


glfw resizing causing image scaling I have a quad rendered that extends from the top left of the window to with width of the window that is also 64 pixels high. When I resize the window, from its initial size, the quad and text scales proportionately bigger or smaller in the same say Photoshop can scale a image. What I'm seeking on a basic level is that regardless of how I resize the window, everything drawn remains the same. From the below image, the right side is the initial size and the left side is what happens when I drag the window to be a smaller size. The red bar and text scales with it. This is how Im handling my resizing glfwSetWindowSizeCallback(pWindow, WindowSizeCallback) initialized after context void WindowSizeCallback(GLFWwindow window, int width, int height) glfwSetWindowSize(window, width, height)


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


GLSL Bokeh using Quads and Textures I'm trying to create a depth of field effect with bokeh sprites in GLSL. Specifically, what i would like to do is, for each pixel See if the pixel is out of the focal range If it is, draw a quad and apply a texture to provide a bokeh sprite. This kind of implementation is seen in the Unreal Engine and by Matt Pettineo, however, both implementations are in DX11 and I'm using OpenGL. I'm a bit stuck on the drawing a quad and applying a texture bit. Does anyone know how I can do this, or provide any relevant links as to how I can do this? Thanks


How to get independent from GLEW dll file I'm literally an absolute noob in GL. I just wrote my first GLEW piece of code yesterday include lt stdio.h gt include lt stdlib.h gt include lt GL glew.h gt include lt GL glfw.h gt int main(void) glfwInit() glfwOpenWindowHint(GLFW FSAA SAMPLES, 4) glfwOpenWindowHint(GLFW OPENGL VERSION MAJOR, 3) glfwOpenWindowHint(GLFW OPENGL VERSION MINOR, 3) glfwOpenWindowHint(GLFW OPENGL PROFILE, GLFW OPENGL CORE PROFILE) glfwOpenWindow(640, 480, 8, 8, 8, 0, 24, 0, GLFW WINDOW) glewInit() glfwSetWindowTitle("OpenGL Rules!") glfwEnable( GLFW STICKY KEYS ) do glfwSwapBuffers() while( glfwGetKey( GLFW KEY ESC ) ! GLFW PRESS amp amp glfwGetWindowParam( GLFW OPENED ) ) This compiles just fine with (using mingw on win8 x64) gcc opengl.c lglfw lglew32 lopengl32 However, in order to run the output, I have to copy the glew32.dll to the same directory from which I'm running the program. Is there a way to get independent from the dll? Like, compiling once and using without having to carry the dll around?


Why is my OpenGL 4.1 shader not working on OS X Macbook ( works on Linux )? I've recently rebuild shaders for my program and it stopped "working" ( black screen ) on OS X ( El Capitan ), but it's ok on Linux. What could be the cause? There are no shader compilation errors, and here is my shader code https github.com Marqin YuriaViewer blob master vertex.glsl Keep in mind that this software worked on El Capitan with OpenGL 4.1 before shader rewrite. Here are my glfw hints glfwWindowHint(GLFW CONTEXT VERSION MAJOR, 4) glfwWindowHint(GLFW CONTEXT VERSION MINOR, 1) glfwWindowHint(GLFW OPENGL PROFILE, GLFW OPENGL CORE PROFILE) glfwWindowHint(GLFW OPENGL FORWARD COMPAT, GL TRUE) My program also is checking for GL ARB gpu shader fp64 and it's available on my Macbook ( Macbook Air 2013 mid ). EDIT1 I've "debugged" it a little and it looks that i is always lesser than vis on OS X, that's why it's black. EDIT2 I made a simple test I've typed all uniform values in shader by hand and now it wasn't black, but I've got some gibberish on screen. Then I've changed every dvec3 and dvec2 to float versions and it showed nice fractal. So it looks like double is not working on OS X. But how can it be? It's saying that GL ARB gpu shader fp64 is available and it even doesn't complain when I request it in vertex shader. EDIT3 It works on iMac with R9 M395. So it's problem with Intel hardware ( or problem with OS X Intel driver ).


removing triangle artifacts from overlapping height maps OpenGL I have two 100x100 height maps that I am drawing using a triangle mesh. One represents the land height, and the other represents (water land) height. I currently draw both meshes on top of each other, and I make the water mesh transparent when the water level is 0. But where the land meets the water there are lots of artifacts. I believe the cause is the water mesh is the height of the land mesh so at the edges the water mesh height goes from being land mesh height to , the visible slope is actually the water mesh slope and not the land mesh slope. That said, I don't know any good way to fix it. Note water level may not be flat so replacing the water mesh with a plane wont work


lighting for landscape I've got a landscape(created in Photoshop .raw file) and a .tga texture for it. I read .raw file and read .tga file like this LoadRawFile("landscape.Raw", MapSize MapSize, amp HeightMap 0 0 ) Texture landscape if (LoadTGA( amp landscape, "landscape.tga")) glGenTextures(1, amp landscape.texID) glBindTexture(GL TEXTURE 2D, landscape.texID) glTexImage2D(GL TEXTURE 2D, 0, landscape.bpp 8, landscape.width, landscape.height, 0, landscape.type, GL UNSIGNED BYTE, landscape.imageData) glTexParameteri(GL TEXTURE 2D, GL TEXTURE MIN FILTER, GL LINEAR) glTexParameteri(GL TEXTURE 2D, GL TEXTURE MAG FILTER, GL LINEAR) if (landscape.imageData) free(landscape.imageData) else cout lt lt "Cannot load texture" lt lt endl glEnableClientState(GL VERTEX ARRAY) glVertexPointer (3, GL FLOAT, 0, VertexMap) glEnableClientState(GL TEXTURE COORD ARRAY) glTexCoordPointer(2, GL FLOAT, 0, TextureMap) for (int Row 0 Row lt MapSize 2 Row ) Indices Row Row I render landscape like this(method renderLandscape) int x, y, i, j int Index 0 for (i 0 i lt MapSize 1 i ) Index 0 for (j 0 j lt MapSize 1 j ) x j Zoom y i Zoom TextureMap Index 0 0 j TextureBit TextureMap Index 0 1 i TextureBit TextureMap Index 1 0 j TextureBit TextureMap Index 1 2 (i 1) TextureBit VertexMap Index 0 2 HeightMap j i VertexMap Index 1 2 HeightMap j i 1 VertexMap Index 0 0 x VertexMap Index 0 3 y VertexMap Index 1 0 x VertexMap Index 1 4 y Zoom Index 2 glDrawElements(GL TRIANGLE STRIP, Index, GL UNSIGNED INT, Indices) draw method glPushMatrix() glTranslatef( 20, 0, 0) glScalef(0.01, 0.01, 0.01) glRotatef(90, 1, 0, 0) landscape.RenderLandscape() glPopMatrix() So by default(without lighting) it looks like this But when I enable lighting(add this lines to my opengl init function) GLfloat light ambient 0.5, 0.5, 0.5, 1.0 GLfloat light diffuse 1.0, 1.0, 1.0, 1.0 GLfloat light specular 1.0, 1.0, 1.0, 1.0 GLfloat light position 1.0, 1.0, 1.0, 0.0 glLightfv(GL LIGHT0, GL AMBIENT, light ambient) glLightfv(GL LIGHT0, GL DIFFUSE, light diffuse) glLightfv(GL LIGHT0, GL SPECULAR, light specular) glLightfv(GL LIGHT0, GL POSITION, light position) glEnable(GL LIGHTING) glEnable(GL LIGHT0) The result landscape looks like this I don't need any special or difficult lighting. So it seems I need to calculate normales(I am new in opengl and usually create .obj models where vn precalculated). What is the best way to calculate normales in my case?


Cannot Get The Texture Showed Up Correctly glDrawElements I still have this problem almost 1 month. Tried to search on Google but did not find any solution to this. I have loaded all the data correctly but don't know why the texture came up like this. Here is my loader Header struct SVertex public float X, Y, Z struct STexture public float U, V struct SFace public int X, Y, Z class CBMap public struct SMesh SVertex Vertex SVertex Normal STexture TexCoord SFace Face SFace FaceNormal char Texture 32 int TextureID int TotalVertice int TotalNormal int TotalFace SMesh Mesh CBMap() CBMap() int TotalMesh int Load(char szFile) int Get FileHeader(FILE pFile) int Get TotalMesh(FILE pFile) int GetData(FILE pFile) CPP int CBMap Load(char szFile) FILE pFile fopen(szFile, "r") if (!pFile) return 0 int iBMap Get FileHeader(pFile) if (!iBMap) printf("BMAP file is not valid n") return 0 TotalMesh Get TotalMesh(pFile) Mesh new SMesh TotalMesh GetData(pFile) int iMesh 0 char pJunk char szHeader 32 while (!feof(pFile)) fscanf(pFile, " s", amp szHeader) if (!strncmp(szHeader, "BMAP", 4)) continue if (!strncmp(szHeader, "mesh", 4)) continue if (!strncmp(szHeader, "mtl", 3)) fscanf(pFile, " s", Mesh iMesh .Texture) Mesh iMesh .TextureID LoadTexture(Mesh iMesh .Texture) if (!strncmp(szHeader, "ve", 2)) fscanf(pFile, " d", amp pJunk) Mesh iMesh .Vertex (SVertex )malloc(sizeof (SVertex) Mesh iMesh .TotalVertice) for (int i 0 i lt Mesh iMesh .TotalVertice i) fscanf(pFile, " f f f", amp Mesh iMesh .Vertex i .X, amp Mesh iMesh .Vertex i .Y, amp Mesh iMesh .Vertex i .Z) if (!strncmp(szHeader, "uv", 2)) fscanf(pFile, " d", amp pJunk) Mesh iMesh .TexCoord (STexture )malloc(sizeof (STexture) Mesh iMesh .TotalVertice) for (int i 0 i lt Mesh iMesh .TotalVertice i) fscanf(pFile, " f f", amp Mesh iMesh .TexCoord i .U, amp Mesh iMesh .TexCoord i .V) if (!strncmp(szHeader, "vn", 2)) fscanf(pFile, " d", amp pJunk) Mesh iMesh .Normal (SVertex )malloc(sizeof (SVertex) Mesh iMesh .TotalNormal) for (int i 0 i lt Mesh iMesh .TotalNormal i) fscanf(pFile, " f f f", amp Mesh iMesh .Normal i .X, amp Mesh iMesh .Normal i .Y, amp Mesh iMesh .Normal i .Z) if (!strncmp(szHeader, "f", 1)) fscanf(pFile, " d", amp pJunk) Mesh iMesh .Face (SFace )malloc(sizeof (SFace) Mesh iMesh .TotalFace 3) Mesh iMesh .FaceNormal (SFace )malloc(sizeof (SFace) Mesh iMesh .TotalFace 3) for (int i 0 i lt Mesh iMesh .TotalFace i) fscanf(pFile, " d d d d d d", amp Mesh iMesh .Face i .X, amp Mesh iMesh .Face i .Y, amp Mesh iMesh .Face i .Z, amp Mesh iMesh .FaceNormal i .X, amp Mesh iMesh .FaceNormal i .Y, amp Mesh iMesh .FaceNormal i .Z) if (!strncmp(szHeader, "end", 3)) if (iMesh lt TotalMesh) iMesh printf("CBMap Model Loaded n") fclose(pFile) return 1 First picture is reality and second picture expectation


Z Value of clip space position is always 1.0 I render a lot of quads on the screen into z direction (20 x 2000). I want to get the depth value in a final render target. But it looks like z is always 1.0f. I checked the result with the OpenGL debugger. Any advice? Vertex shader version 410 layout(row major) uniform UView mat4 m View mat4 m Projection layout(row major) uniform UModelMatrix mat4 m ModelMatrix layout(location 0) in vec2 VertexPosition out vec3 PSVSPosition void main(void) vec4 VSPosition m View m ModelMatrix vec4(VertexPosition.xy, 0.0f, 1.0f) PSVSPosition VSPosition.xyz gl Position m Projection VSPosition Fragment shader version 410 layout(row major) uniform USettings mat4 m ProjectionMatrix layout(location 0) out vec4 PSColor in vec3 PSVSPosition void main(void) Calculate depth vec4 CSPosition m ProjectionMatrix vec4(PSVSPosition, 1.0f) CSPosition.xyz CSPosition.w PSColor vec4(vec3(CSPosition.z 0.5f 0.5f), 1.0f) Result Closer result view space position result clip space position result


How to use OpenGL blend mode functions to brighten darken a texture. Tried this code, but the texture didnot get any lighter. try texture TextureLoader.getTexture("png", Game.class.getResourceAsStream(" brick.png"), true, GL NEAREST) catch (IOException e) e.printStackTrace() GL11.glBindTexture(GL11.GL TEXTURE 2D, texture.getTextureID()) glEnable(GL BLEND) glBlendFunc(GL CONSTANT ALPHA, GL CONSTANT ALPHA) GL14.glBlendColor(1.0f, 1.0f, 1.0f, 0.5f) glColor4f(1, 1, 1, 0.5f) GL11.glBegin(GL11.GL QUADS) Start Drawing Quads Front Face GL11.glNormal3f(0.0f, 0.0f, 1.0f) Normal Pointing Towards Viewer GL11.glTexCoord2f(0.0f, 0.0f) GL11.glVertex3f( 1.0f, 1.0f, 1.0f) Point 1 (Front) GL11.glTexCoord2f(1.0f, 0.0f) GL11.glVertex3f(1.0f, 1.0f, 1.0f) Point 2 (Front) GL11.glTexCoord2f(1.0f, 1.0f) GL11.glVertex3f(1.0f, 1.0f, 1.0f) Point 3 (Front) GL11.glTexCoord2f(0.0f, 1.0f) GL11.glVertex3f( 1.0f, 1.0f, 1.0f) Point 4 (Front) glEnd()


Reset Camera view webgl I have camera rotating by dragging mouse. Im trying to add reset button that restart the scene to initial view. The rotating camera works as expected but I can't figure out how to reset it. The scene rotating in weird directions, not as expected. I have 2 vars absX, absY which hold the overall change angle value from the init mode. when reset applied mat4.rotate(getRotationCameraMat, degToRad( absX 10), 0, 1, 0 ) mat4.rotate(getRotationCameraMat, degToRad( absY 10), 1, 0, 0 ) absX 0 absY 0 apply the rotate mat4.multiply(mvMatrix, cameraRotationMat) the camera code var mouseDown false var prevMouseX null var prevMouseY null var cameraRotationMat mat4.create() mat4.identity(cameraRotationMat) function handleMouseDown(event) mouseDown true prevMouseX event.clientX prevMouseY event.clientY function handleMouseUp(event) mouseDown false var absX 0 var absY 0 function handleMouseMove(event) if (!mouseDown) return var currentX event.clientX var currentY event.clientY var deltaX currentX prevMouseX absX deltaX var newRotationMatrix mat4.create() mat4.identity(newRotationMatrix) mat4.rotate(newRotationMatrix, degToRad(deltaX 10), 0, 1, 0 ) var deltaY currentY prevMouseY absY deltaY mat4.rotate(newRotationMatrix, degToRad(deltaY 10), 1, 0, 0 ) mat4.multiply(newRotationMatrix, cameraRotationMat,cameraRotationMat) prevMouseX currentX prevMouseY currentY


understanding the basics of raytracing I have got a sphere in my world space. I don't understand how can i find my sphere using my X and Y on my screen, because i don't understand what the value Z of my ray assuming the fact that we use world coordinate system.


How do I build Assimp with MinGW? How can I build Assimp with cMake and MinGW? I tried, but I don't get a functioning library... Details of my attempt I am trying to build the Open Asset Import Library (Assimp) but I have been running into problems. The assimp documentation is really poor and expects you to know exactly what you are doing. The developers haven't been particularly helpful either. I hope someone here has successfully built assimp and can let me know where I am going wrong. I suspect that I have several problems that are contributing to my failure. I am using 64 bit Windows 8.1 pro and using MinGW version 4.8.1. The first thing I tried was downloading assimp 3.1.1 and boost 1.57. I extracted both folders and tried to use cMake to generate the makefile for MinGW. I haven't used cMake before and the assimp instructions are use cMake as you normally would, so I have no idea if I configured it right. I pointed BOOST ROOT to the boost folder I extracted from the download, set it to build static libraries and generated the makefile. I then tried running the makefile and got a number of errors. The first was IFCReaderGen.cpp.obj too many sections and was too big. After some googling, I found a workaround was to set CMAKE BUILD TYPE to release. That seemed to work and it finished the build but I only got the files assimp32.dll and libassimp.dll.a, which I thought was odd because I was expecting lib relese libassimp.a to be generated as per the details on the assimp website. Though the website might also be wrong or out of date. I linked with lassimp.dll and that allowed me to build my program. However it crashed upon start up the error that appeared immediately at start up was Program has stopped working (There was no additional info.) I guessed that this was a dll problem which was odd because I had (tried) to build the static libraries through cMake. I copied assimp32.dll into my executable folder. This time, the program wouldn't crash but the screen would be blank. I'm guessing that there was something wrong with the library I build that was causing it to link incorrectly. At this point, I deleted everything to try a fresh start. I tried to follow this article I downloaded assimp 3.1.1 and boost 1.57 and extracted them. I opened cmd, changed to the boost root directory and ran bootstrap.bat mingw I then ran b2 build dir "C Libraries boost " variant release link static address model 32 toolset gcc The result of this was 598 targets updates, 3 targets skipped, 2 targets failed. I now have a folder C Libraries boost boost bin.v2 with two folders libs and standalone, but I'm not certain what my BOOST ROOT directory is anymore. I opened cMake, selected the assimp folder I had extracted, and configured the following BOOST ROOT "C Libraries boost boost " ASSIMP BUILD STATIC LIB TRUE ASSIMP BUILD TESTS FALSE ASSIMP ENABLE BOOST WORKAROUND FALSE BUILD SHARED LIBS FALSE I then pressed configure and got the error that the boost libraries were not found. I'm only guessing what these cMake settings do, as I can't find any documentation for assimp. I'd like to build some version of assimp that I can then link to and use in a simple test program. At some point I will go back and build the shared libraries, but first I just want to get something working and understand how to do it again. Can someone see what has gone wrong?


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


OpenGl lighting casting black shadow I'm having issues with lighting that I can't figure out, namely solid black sections. Any ideas? Here's my fragment shader code version 400 core in vec2 pass textureCoords in vec3 surfaceNormal in vec3 toLightVector in vec3 toCameraVector out vec4 out Colour uniform sampler2D modelTexture uniform vec3 lightColour uniform float shineDamper uniform float reflectivity void main(void) vec3 unitNormal normalize(surfaceNormal) vec3 unitLightVector normalize(toLightVector) float nDot1 dot(unitNormal, unitLightVector) float brightness max(nDot1,0.4) vec3 diffuse brightness lightColour vec3 unitVectorToCamera normalize(toCameraVector) vec3 lightDirection unitLightVector vec3 reflectedLightDirection reflect(lightDirection,unitNormal) float specularFactor dot(reflectedLightDirection, unitVectorToCamera) specularFactor max(specularFactor,0.0) float dampedFactor pow(specularFactor,shineDamper) vec3 finalSpecular dampedFactor reflectivity lightColour vec4 textureColour texture(modelTexture,pass textureCoords) if(textureColour.a lt 0.5) discard out Colour vec4(diffuse,1.0) textureColour vec4(finalSpecular,1.0) and vertex shader code version 400 core in vec3 position in vec2 textureCoords in vec3 normal out vec2 pass textureCoords out vec3 surfaceNormal out vec3 toLightVector out vec3 toCameraVector uniform mat4 transformationMatrix uniform mat4 projectionMatrix uniform mat4 viewMatrix uniform vec3 lightPosition uniform float useFakeLighting void main(void) vec4 worldPosition transformationMatrix vec4(position,1.0) gl Position projectionMatrix viewMatrix worldPosition pass textureCoords textureCoords vec3 actualNormal normal if (useFakeLighting gt 0.5) actualNormal vec3(0.0,1.0,0.0) surfaceNormal (transformationMatrix vec4(actualNormal,0.0)).xyz toLightVector lightPosition worldPosition.xyz toCameraVector (inverse(viewMatrix) vec4(0.0,0.0,0.0,1.0)).xyz worldPosition.xyz


Render in a imGui Window How do i render my game scene into an imgui window? I want to get from this to this


Ray Tracing in One Weekend, how to add depth of field to view matrix? I'm working through the infamous Ray Tracing in One Weekend book as I implement it on a OpenGL compute shader, the only thing I have left to do is add depth of field. I have this function that generates rays from a view and projection matrix, so its slightly different from the book where he does his own camera setup, here is my function Ray Camera getRay(inout uvec4 useed) float aperture 0.1 float lens radius aperture 2 vec3 rd lens radius sampleUnitDisk(useed) vec3 rayNDC vec3( ((2.0f fragCoord.x) iResolution.x 1.0f), (1.0f (2.0f fragCoord.y) iResolution.y), 1.0f ) vec4 rayClip vec4( rayNDC.x, rayNDC.y 1, 1.0f, 1.0f ) vec4 rayCamera inverse(projection) rayClip rayCamera.z 1.0f, rayCamera.w 0.0f vec3 direction normalize((inverse(view) rayCamera).xyz) return Ray(position, direction) I am trying to add the randomized offset as described in the Defocus Blur chapter. I have gotten this far float aperture 0.1 float lens radius aperture 2 vec3 rd lens radius sampleUnitDisk(useed) But I am not sure what to do with rd next, do I simply add it to the ray's position? do I also need to add it to the ray direction? Do I alter the view matrix? Any help is appreciated.


How to use GLX from Java? I am trying to use Clojure to create an opengl window under Linux. Is there a tutorial on how to use GLX and X Window directly. I'd rather learn how to do this directly, which I already know how under Windows with win32 sdk, instead of relying on a wrapper.


Problem with bullet movement I'm trying to draw quot bullets quot in my game, but I think something is wrong with velocity computation. Sometimes the quot bullets quot are going in the right way, but sometimes they won't. The CameraFront is constructed with euler angles. Can you help? Thanks in advance So this is how I create bullets Bullet tracer makeBulletTracer(v3 cameraFront,v3 startP, v3 endP) Bullet tracer result assert((gTracersCount 1) lt MAX BULLET TRACERS) mat4 model indentity() model scale(model, v3(.5f,.5f,1.5f)) v3 up v3(0.0f,1.0f,0.0f) v3 right normalize(cross(cameraFront,up)) mat4 M rows3x3(right,up,cameraFront) model model M model translate(model, startP v3(0.0f,3.0f,0.0f)) result.model model result.velocity cameraFront gTracersCount return result This is how I draw them for (u32 tracerIndex 0 tracerIndex lt gTracersCount tracerIndex ) Bullet tracer tracer gameState gt tracers tracerIndex v3 p getTranslationPart(tracer gt model) v3 offset (p tracer gt velocity) input gt dtForFrame 0.01f tracer gt model translate(tracer gt model, offset) passUniformMatrix(opengl.shaderProgram,tracer gt model,false, quot model quot ) glDrawArrays(GL TRIANGLES, 0, 36)


Why does the lighting change the objects color? I have a code that draws a sphere. Without lighting it is white, but if I enable lighting, it's drawn in gray. I don't know why the sphere changed it's color include lt GL gl.h gt include lt GL glu.h gt include lt GL glut.h gt void init(void) GLfloat mat specular 1.0, 1.0, 1.0, 1.0 GLfloat mat shininess 50.0 GLfloat light position 1.0, 1.0, 1.0, 0.0 glClearColor (0.0, 0.0, 0.0, 0.0) glShadeModel (GL SMOOTH) glMaterialfv(GL FRONT, GL SPECULAR, mat specular) glMaterialfv(GL FRONT, GL SHININESS, mat shininess) glLightfv(GL LIGHT0, GL POSITION, light position) glEnable(GL LIGHTING) glEnable(GL LIGHT0) glEnable(GL DEPTH TEST) void display(void) glClear (GL COLOR BUFFER BIT GL DEPTH BUFFER BIT) glutSolidSphere (1.0, 20, 16) glFlush () void reshape (int w, int h) glViewport (0, 0, (GLsizei) w, (GLsizei) h) glMatrixMode (GL PROJECTION) glLoadIdentity() if (w lt h) glOrtho ( 1.5, 1.5, 1.5 (GLfloat)h (GLfloat)w, 1.5 (GLfloat)h (GLfloat)w, 10.0, 10.0) else glOrtho ( 1.5 (GLfloat)w (GLfloat)h, 1.5 (GLfloat)w (GLfloat)h, 1.5, 1.5, 10.0, 10.0) glMatrixMode(GL MODELVIEW) glLoadIdentity() int main(int argc, char argv) glutInit( amp argc, argv) glutInitDisplayMode (GLUT SINGLE GLUT RGB GLUT DEPTH) glutInitWindowSize (500, 500) glutInitWindowPosition (100, 100) glutCreateWindow (argv 0 ) init () glutDisplayFunc(display) glutReshapeFunc(reshape) glutMainLoop() return 0


glViewport() Win10 doesn't draw new parts I've been steadily working through building a basic 2D tile framework in python. I'm trying to use modern openGL so I have a simple shader and some vertex buffers and it's mostly doing what I want so far. I have a Scene with a method for centering the viewport on a Sprite def centre viewport(self, x, y) x x self.viewport width 2 y y self.viewport height 2 if x gt 0 x 0 if y lt 0 y 0 if x self.viewport width lt self.width x self.width self.viewport width if y self.viewport height gt self.height y self.height self.viewport height self.viewport x x self.viewport y y glViewport(x, y, self.viewport width, self.viewport height) self.viewport width and height are set when a scene is added to the window, so they have the same dimensions as whatever window is created. In my test game, the scene width and height are twice the window dimensions of 704x512. Everything works fine on my main mac development machine. On my work windows machine though, when the sprite moves and causes the scene to scroll, the previously hidden parts of the scene are not drawn My draw loop is very simple def draw(self) glBindBuffer(GL ARRAY BUFFER, self.sprite vertex buffer) glVertexAttribPointer(self.vertices, 3, GL FLOAT, GL FALSE, 0, None) glBindBuffer(GL ARRAY BUFFER, self.sprite texture buffer) glVertexAttribPointer(self.tex coords, 2, GL FLOAT, GL TRUE, 0, None) glDrawArrays(GL TRIANGLES, 0, self.sprite vertex count) glBindBuffer(GL ARRAY BUFFER, self.tile vertex buffer) glVertexAttribPointer(self.vertices, 3, GL FLOAT, GL FALSE, 0, None) glBindBuffer(GL ARRAY BUFFER, self.tile texture buffer) glVertexAttribPointer(self.tex coords, 2, GL FLOAT, GL TRUE, 0, None) glDrawArrays(GL TRIANGLES, 0, self.tile vertex count) and as mentioned, it works fine on my mac. Is glViewport() the appropriate way to be doing this, and why isn't it working properly on windows?


OpenGL strange rendering problem when buffers have different sizes I have encountered a very odd error in my program, "odd" in the sense that everything the API says suggests that the error should not occur. I have a bunch of 2D un indexed vertex data, and I want to render it as lines. So far, so good. Then, I wanted to make each vertex have its own (RGB) color, so I generate a color for each vertex. For simplicity, I chose red. Works fine, except now only 2 3 of the points are being rendered! The problem arises from the fact that each vertex's position data consists of only 2 numbers, whereas the color data consists of 3 numbers. So, the "position" buffer has 2 elements per vertex while the "color" one has 3 elements per vertex. I thought that using glVertexAttribPointer to tell this information to OpenGL would be enough, but turns out it's not. In fact, if I say that the color data has only 2 elements per vertex, using glVertexAttribPointer(vertexColorID2,2,GL DOUBLE,GL FALSE,0,(void )0) (as opposed to 3), it renders all the points except now I can only specify two numbers for the RGB color, so I can't get the right color. The full code of the issue is below glUseProgram(programID2) draw the graph graph data graphData() std vector lt double gt graphcolordata(graph data.size() 2 3) for (int i 0 i lt graph data.size() i 3) graphcolordata i 1 glEnableVertexAttribArray(vertexPosition modelspaceID2) glBindBuffer(GL ARRAY BUFFER, graphbuffer) glBufferData(GL ARRAY BUFFER, graph data.size() sizeof(GLdouble), amp graph data 0 , GL STREAM DRAW) glVertexAttribPointer(vertexPosition modelspaceID2,2,GL DOUBLE,GL FALSE,0,(void )0) glEnableVertexAttribArray(vertexColorID2) glBindBuffer(GL ARRAY BUFFER, colorbuffer2) glBufferData(GL ARRAY BUFFER, graphcolordata.size() sizeof(GLdouble), amp graphcolordata 0 , GL STREAM DRAW) glVertexAttribPointer(vertexColorID2,3,GL DOUBLE,GL FALSE,0,(void )0) glDrawArrays(GL LINES, 0, graph data.size() 2) glDisableVertexAttribArray(vertexPosition modelspaceID2) glDisableVertexAttribArray(vertexColorID2) Note programID2 is my basic shader program, and the following variable definitions were previously used GLuint vertexPosition modelspaceID2 glGetAttribLocation(programID2, "vertexPosition modelspace") GLuint vertexColorID2 glGetAttribLocation(programID2, "vertexColor") Edit Incredibly stupid error, figured it out immediately after posting when it had previously stumped me for half an hour. std vector lt double gt graphcolordata(graph data.size() 2 3) for (int i 0 i lt graph data.size() i 3) graphcolordata i 1 should be std vector graphcolordata(graph data.size() 2 3) for (int i 0 i lt graphcolordata.size() i 3) graphcolordata i 1 When this initialization is fixed, it works fine. I would delete this, but I do not see how.


Multiple Render Targets, Multiple Fragment Shaders I render a normal and a depth image of a scene. Then I want to reuse these two images to do further texture image processing in a second fragment shader. I use a framebuffer with 3 textures attached to it. 2 for the normal and the depth textures and one is supposed to contain the final processed image. The problem is, that I can't get the first two images to the second fragment shader to use them as texture samplers. Here is my code First I create a fbo and attach 3 textures to it. create FBO glGenFramebuffers(1, amp Framebuffer) glBindFramebuffer(GL FRAMEBUFFER, Framebuffer) glGenTextures(1, amp renderedNormalTexture) glBindTexture, glTexImage2D, glTexParameteri ... left out for clarity glFramebufferTexture2D(GL FRAMEBUFFER, GL COLOR ATTACHMENT0, GL TEXTURE 2D, renderedNormalTexture, 0) glGenTextures(1, amp renderedDepthTexture) glFramebufferTexture2D(GL FRAMEBUFFER, GL COLOR ATTACHMENT1, GL TEXTURE 2D, renderedDepthTexture, 0) glGenTextures(1, amp edgeTexture) glFramebufferTexture2D(GL FRAMEBUFFER, GL COLOR ATTACHMENT2, GL TEXTURE 2D, edgeTexture, 0) ndbuffers 0 GL COLOR ATTACHMENT0 ndbuffers 1 GL COLOR ATTACHMENT1 ndbuffers 2 GL COLOR ATTACHMENT2 glDrawBuffers(3, ndbuffers) Fragment shader 1 This is the first fragment shader which outputs 2 textures to position 0 and 1 in vec3 position worldspace in vec3 normal cameraspace in vec4 vpos to fragment uniform float zmin uniform float zmax layout(location 0) out vec3 normalcolor layout(location 1) out vec3 depthcolor void main() normalcolor normalize( normal cameraspace ) 0.5 0.5 normal out vec4 v vec4(vpos to fragment) v v.w float gray ( v.z zmin) (zmax zmin) depthcolor vec3(gray) depth out fragment shader 2 And the second fragment shader which is supposed to receive two texture samplers from position 0 and 1 and do sth. with them uniform sampler2D normalImage uniform sampler2D depthImage uniform float width uniform float height in vec2 UV layout(location 2) out vec3 color void main() vec3 irgb texture2D(normalImage, UV).rgb do sth here... color irgb And finally the rendering step Maybe I am mistaken here. I render the geometry scene (once?!) and apply two fragment shaders. glUseProgram(FragmentShader1) SetMVPUniforms() glClear(GL COLOR BUFFER BIT GL DEPTH BUFFER BIT) RenderScene() render geometry glUseProgram(FragmentShader2) GLuint nID glGetUniformLocation(FragmentShader2, "normalImage") GLuint dID glGetUniformLocation(FragmentShader2, "depthImage") glActiveTexture(GL TEXTURE0) glBindTexture(GL TEXTURE 2D, renderedNormalTexture) glProgramUniform1i(FragmentShader2, nID, 0) glActiveTexture(GL TEXTURE1) glBindTexture(GL TEXTURE 2D, renderedDepthTexture) glProgramUniform1i(FragmentShader2, dID, 1) Now what I get is either nothing or a wrong colored image.


Color Picking Troubles LWJGL OpenGL I'm attempting to check which object the user is hovering over. While everything seems to be just how I'd think it should be, I'm not able to get the correct color due to the second time I draw (without picking colors). Here is my rendering code public void render() glClear(GL COLOR BUFFER BIT GL DEPTH BUFFER BIT) glLoadIdentity() camera.applyTranslations() scene.pick() glClear(GL COLOR BUFFER BIT GL DEPTH BUFFER BIT) glLoadIdentity() camera.applyTranslations() scene.render() And here is what gets called on each block tile on "scene.pick()" public void pick() glColor3ub((byte) pickingColor.x, (byte) pickingColor.y, (byte) pickingColor.z) draw() glReadBuffer(GL FRONT) ByteBuffer buffer BufferUtils.createByteBuffer(4) glReadPixels(Mouse.getX(), Mouse.getY(), 1, 1, GL RGBA, GL UNSIGNED BYTE, buffer) int r buffer.get(0) amp 0xFF int g buffer.get(1) amp 0xFF int b buffer.get(2) amp 0xFF if(r pickingColor.x amp amp g pickingColor.y amp amp b pickingColor.z) hovered true else hovered false I believe the problem is that in the method of each tile block called by scene.pick(), it is reading the color from the regular drawing state, after that method is called somehow. I believe this because when I remove the "glReadBuffer(GL FRONT)" line from the pick method, it seems to almost fix it, but then it will also select blocks behind the one you are hovering as it is not only looking at the front. If you have any ideas of what to do, please be sure to reply! EDIT Adding scene.render(), tile.render(), and tile.draw() scene.render public void render() for(int x 0 x lt tiles.length x ) for(int z 0 z lt tiles.length z ) tiles x z .render() tile.render public void render() glColor3f(color.x, color.y, color.z) draw() if(hovered) glColor3f(1, 1, 1) glPolygonMode(GL FRONT AND BACK, GL LINE) draw() glPolygonMode(GL FRONT AND BACK, GL FILL) tile.draw public void draw() float x position.x, y position.y, z position.z Top glBegin(GL QUADS) glVertex3f(x, y size, z) glVertex3f(x size, y size, z) glVertex3f(x size, y size, z size) glVertex3f(x, y size, z size) glEnd() Left glBegin(GL QUADS) glVertex3f(x, y, z) glVertex3f(x size, y, z) glVertex3f(x size, y size, z) glVertex3f(x, y size, z) glEnd() Right glBegin(GL QUADS) glVertex3f(x size, y, z) glVertex3f(x size, y size, z) glVertex3f(x size, y size, z size) glVertex3f(x size, y, z size) glEnd() (The game is like an isometric game. That's why I only draw 3 faces.)


Picking 3D with OpenGL ES 2 I'm trying to implement picking in my framework but I don't understand how I can do this. I'm working with OpenGL ES 2. GLM mathematic library. What I have understand, picking can be made with two methods Draw scene with one color per polygon, and read pixel under mouse. Ray projection in 3D and finally calculate geometry lt ray intersection. My architecture A Geometry class with indices vertices texture coords colors data. A Scene class with a Mesh array (using a geometry). A Transformable class with Matrix computed with rotation position scale. A Camera class with methods like getViewport . What I have My ray calculation void Ray createFromEvent( const Camera amp camera ) glm mat4 model camera.getMatrix() glm mat4 projection camera.getProjectionMatrix() glm vec4 viewPort camera.getViewport() this gt origin glm unProject( glm vec3( x, y, camera.getMinDistance() ), model, projection, viewPort ) this gt direction glm unProject( glm vec3( x, y, camera.getMaxDistance() ), model, projection, viewPort ) So, my questions are How can I calculate intersection with my scene geometries? It's better to calculate if point is inside a bounding box or ray traversing a bounding box? How can I compute bounding box with Transformable matrix (rotation, scale, )? (I am on mobile so I am limited by hardware performance.) Thanks!


Orbital rotation equation I am developing a space sandbox (3D). Now I am working on an asteroid belt around a planet. I have an Asteroid class and an AsteroidBelt class that has a collection of the Asteroid instances. Each Asteroid object is placed randomly during initialization. Asteroid class Matrix4 transform double angle float x, y, z Vector3 initPosition public Asteroid(ModelObject object, Texture diffuseTex) initPosition new Vector3( MathUtils.random( Settings.RingsDepth, Settings.RingsDepth), x MathUtils.random( .5f, .5f), y MathUtils.random( Settings.RingsDepth, Settings.RingsDepth)) z public void update(Camera camera) angle Settings.RingsRotationalSpeed if(angle gt 360) angle 0 if(angle lt 0) angle 360 double angleRad angle MathUtils.degreesToRadians x (float) (Math.sin(angleRad) Settings.RingsRadius initPosition.x) y initPosition.y z (float) (Math.cos(angleRad) Settings.RingsRadius initPosition.z) transform.idt() transform.translate(x, y, z) The code above works correctly, but it doesn't allow to rotate the asteroid belt around a planet. How to modify x, y, and z to rotate the asteroid belt around a planet freely? I hope the illustration below will clarify my problem Now the asteroid belt looks like below But I need to rotate it from 90 to 90 degrees by X and Y axis Any help will be appreciated!


Terminology for the way Transformation Matrix Data is treated I recently asked a question at math stack exchange and realize a similar questions is more suited for this forum, but the original is here https math.stackexchange.com questions 1526601 terminology for transformation matrices update or rigid body transform I'm attempting to describe transformation matrix operations within Sketchup's Ruby scripts, and I need some terminology. Sketchup allows the selection of a group of "loose" drawing objects (i.e. edges and faces), and provides options to create a grouped object from them. The drawing elements inside the group have position data relative to the group's local coordinate system. The grouped objects respond to a getter "transformation" method that returns a transformation object that contains data representing the orientation, scale, and position of the group. Sketchup's "world space" supports multiple grouped objects, and typically there are numerous grouped entities in the outer level entities, as well as loose drawing objects. Each grouped object has a separate transformation that determines their position, orientation, and scaling in world space. The transformation can be altered or replaced with methods that include a) The "transform" method Applies a transformation (i.e. like a rotation) to rotate the group and b) The "transformation " setter method Replaces the existing transformation with the supplied argument. Lets say I have a grouped object called "entity1" and rotation transformation object called "rotation". To provide the same rotation effect I could perform either of the following in Sketchup's Ruby programming entity1.transform!( rotation ) OR entity1.transformation rotation entity1.transformation Only groups and components support the "transformation " setter method, while fundamental Point3d amp Vector3d object provide "transform!" kind of methods. It is obvious, at least from within Sketchup (which uses OpenGL internally), that transformation matrix internal data can be treated as either Relative A transformation performs an incremental operation (Example "entity1.transform! identity" does not have an affect on the grouped model) or Absolute The data inside a transformation is treated as absolute position, orientation, and scaling of the grouped object. (Example "entity1.transformation IDENTITY" sets the model to Sketchup's origin position, the model is de rotated to the orientation it was when first grouped, and it is descaled) Questions 1) What is the terminology for the type of transformation that is supplied to the "transform!" method? I was calling it an "affine", now want to call it an "update transformation". 2) What is the terminology for the type of transformation that is the argument to the setter "transformation "? I have been calling it a "rigid body transformation", and sometimes "absolute transform". It appears that OpenGL is calling this the "model matrix". 3) If I call it "model matrix", is more than one model matrix transform allowed in world space? A previous english stack exchange article for a word to mean "position and orientation" is at https english.stackexchange.com questions 119883 word for position and orientation The article responses recommend to use "pose matrix".


Creating a 3rd Person Flying Camera for 3D asteroids game In order to learn PyOpenGL and test out an engine I am developing, I am trying to write a 3D asteroids flying space shooter game. Currently, I am implementing the camera using a "look at" function positioned right behind the player's ship. The player is able to control the yaw and pitch with the left right and up down arrow keys respectively. The results look like this (forgive the placeholder art) And here is the code snippet in my Player class that implements that from pyorama.entity import Entity from pyorama.math3d.vec3 import Vec3 from pyorama.math3d.mat4 import Mat4 import math class Player(Entity) def init (self, model, camera) self.model model self.center self.model.mesh.compute bounding sphere().center self.model.transform self.model.transform.translate( self.center) self.camera camera self.key down status "Left" False, "Right" False, "Up" False, "Down" False super(Player, self). init () def update(self) messages super(Player, self).update() for message in messages if message.event type "key down" key message.data "key name" if key in self.key down status.keys() self.key down status key True if message.event type "key up" key message.data "key name" if key in self.key down status.keys() self.key down status key False self.model.transform self.model.transform.translate(self.center) if self.key down status "Up" self.model.transform self.model.transform.rotate x( 0.01) if self.key down status "Down" self.model.transform self.model.transform.rotate x(0.01) if self.key down status "Left" self.model.transform self.model.transform.rotate y(0.01) if self.key down status "Right" self.model.transform self.model.transform.rotate y( 0.01) self.model.transform self.model.transform.translate( self.center) self.model.transform self.model.transform.translate(Vec3(0, 0, 0.1)) right self.model.transform.data 0 3 up Vec3( self.model.transform.data 4 7 ) forward Vec3( self.model.transform.data 8 11 ) position Vec3( self.model.transform.data 12 15 ) temp self.model.transform self.model.transform self.model.transform.translate( self.center) right self.model.transform.data 0 3 up Vec3( self.model.transform.data 4 7 ) forward Vec3( self.model.transform.data 8 11 ) position Vec3( self.model.transform.data 12 15 ) self.camera.view Mat4.look at(position 20 forward, position, up) self.model.transform temp As you can see, the ship stays perfectly still behind and the world rotates around. As a result, it looks very unnatural, as if a 2D ship sprite was simply glued onto the screen! So my question is, how are third person cameras in flying games typically implemented? What would a keyboard mouse control scheme look like that controls yaw, pitch, roll, banking, acceleration deceleration, etc? Would the camera controls for the camera be separated from moving the ship? Any help would be greatly appreciated.


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


Is a Single Texture Cube Map Possible? I'm currently developing a test project to explore OpenGL 3 texturing abilities. I have a simple cube, made of 8 vertices and 36 indices. I want each of the cubes faces to have a different texture, so I devised this texture I made it obvious which sections I want visible (I hope...). In Direct3D, I once made a skybox, and I used a cubemap. However, I had to split it into 6 different textures. This is annoying and hard to manage, it would be nice to have just one texture. Is this even possible? I read somewhere that I could do this by duplicating vertices, is that a good idea? Someone else said I could do it in the shader, but that also baffles me...


Creating a glitch effect similar to Watch Dogs I'm currently working on a LibGDX game. When a user does something wrong, I would like all the graphics on the screen to jitter very similar to the glitch distort effect seen in the game Watch Dogs (See Below). My question is this can this effect be achieved in real time by writing a shader? If so are there any references online on how to do this? (I've had a quick Google but all I could find is how to achieve this effect in Photoshop After Effects). Thank you for your help. Screen jitter https www.youtube.com watch?v EYkqC9uI8Nc Text glitch effect https www.youtube.com watch?v Wj26Wp2AH U


Multiple texture coordinates per mesh? So far I've used the same texture coordinate for both the normal and diffuse textures on a mesh, yet when reading the Assimp documentation (http assimp.sourceforge.net lib html structai mesh.html details) on a Mesh, it implies that there can be more than one texture coordinate sets per mesh. My question is, in general what scenario would these be present and what is their purpose?


Rendering model with multiple tiling textures See edit How would I go about rendering a model with multiple tiling textures? I have a few ideas, but all of them have drawbacks, here are a few (by the way this is for an opengl game) Use a huge texture, but this comes at the cost of the texture being expensive Render diffrent objects for each textured object (eg one model could be bricks for a house, another could by the roof, each with their own tiled texture), but this would become very messy, very quickly. Here is an (amazing) image to help demonstrate what I'm trying to do. The repeating "R" on the red area represents perhaps a repeating brick texture, while the green one represents a roof, maybe roof shingles. To add on to that, I've added a window texture. My question is, how do most games deal with this? I can't seem to wrap my head around how I could fit this in one texture, but yet I see many other games do exactly what I want. EDIT This should give a better visual demo. I want a large mesh (not very large in the demo) using one texture atlas. (Please keep in mind not all textures in the atlas will be the same size!) Lets say this is my object, it uses each texture on the atlas, but not the same amount of repeats (brick repeats 3 times, when the smiley face repeats 9 or so times) How do most games achieve something like this? Without using some huge file with repeating textures. Example (from BOTW) I assume they didn't just repeat this texture on the atlas, considering how large that would be (and expensive).


How can I bend an object in OpenGL? Is there a way one could bend an object, like a cylinder or a plane using OpenGL? I'm an OpenGL beginner (I'm using OpenGL ES 2.0, if that matters, although I suspect, math matters most in this case, so it's somehow version independent), I understand the basics translate, rotate, matrix transformations, etc. I was wondering if there is a technique which allows you to actually change the geometry of your objects (in this case by bending them)? Any links, tutorials or other references are welcomed!


Rotation matrix from OpenGL to DirectX I have an application which uses openGL and i have to port it to DirectX. To sum up my issue How can I port rotation matrix based on a right handed coordinate system to a left handed coordinate system ? I hardly found some documentation on the internet. This is what i found on MSDN Flip the order of triangle vertices so that the system traverses them clockwise from the front. In other words, if the vertices are v0, v1, v2, pass them to Direct3D as v0, v2, v1. Use the view matrix to scale world space by 1 in the z direction. To do this, flip the sign of the 31, 32, 33, and 34 member of the D3DMATRIX structure that you use for your view matrix. This is work fine except i can not flip easily my vertices because i got an 3D model from CATIA which is not a primitive, so i can't use it. (I'm aware of row major and column major difference, it does not matter) Do you know how i can port my rotation matrix from openGL to DirectX ? Thanks a lot


Lightmap not moving properly with camera movement I ve implemented a 2d lighting system (also with support of 2d shadows). Everything was fine until today when I realised that its not working when moving the camera, as it looks like the lightmap has still some offset than the camera position (for example, if camera.x is 100, the lightmap is x 200) Little video showing the problem Video I can post any piece of code, for now Im sending you my light shader(fragment) version 440 in vec4 fragmentColor in vec2 TexCoords out vec4 color uniform float ambientStrength uniform vec2 resolution uniform sampler2D textureSampler uniform sampler2D lightMapTexture uniform bool textureON void main() Calc the ligthMap vec2 lightCoord (gl FragCoord.xy resolution) vec4 lightMap texture(lightMapTexture,lightCoord) if (textureON) vec4 textureColor texture(textureSampler, TexCoords) vec4 finalColor lightMap textureColor fragmentColor color vec4(finalColor.rgb,textureColor.a fragmentColor.a) else color fragmentColor Vertex version 440 in vec3 vertexPosition in vec4 vertexColor in vec2 vertexUV out vec4 fragmentColor out vec2 TexCoords uniform mat4 Projection uniform mat4 View uniform mat4 Model void main() gl Position Projection View Model vec4(vertexPosition.xy,0,1) fragmentColor vertexColor TexCoords vec2(vertexUV.x, 1.0 vertexUV.y) At first I thought that its a problem with resolution, but everything is good. Everything is working fine until I move the camera(or change its position from 0,0 to something else all other objects have good position, also mouse coords)


Cook Torrance model implementation black specular light I am trying to implement the Cook Torrance model, and this is how I calculate the parameter Rs float Rs(float m,float F,vec3 N, vec3 L,vec3 V, vec3 H) float result float NdotV dot(N,V) float NdotH dot(N,H) float NdotL dot(N,L) float VdotH dot(V,H) float Geom min(min(1.0, (2.0 NdotV NdotH) VdotH), (2.0 NdotL NdotH) VdotH) float Rough pow(1.0 (pow(m,2.0) pow(NdotH,4.0)), ( pow(NdotH,2.0) 1.0) ( pow(m,2.0) pow(NdotH,2.0))) float Fresnel F pow(1.0 VdotH,5.0) (1.0 F) return (Fresnel Rough Geom) (NdotV NdotL) I apply this formula Where I set m to 0.5 and F0 to 2.0. But I think it's wrong because I'm getting a black area where there should be the specular light PS With OpenGL 2.1, GLSL 1.20.


Send Geometry Data to Multiple Shaders So I am implementing a deferred rending model for my engine, and I want to be able to send all scene geometry into a single shader to calculate ambient, diffuse, normal, ect thats not the question. Once I have all of this data buffered into the GPU I can render all of that geometry from a camera perspective defined by a uniform for the cameras position in the scene. I am wondering if I can reuse this model data already in VRam in another shader translated by a light sources projection matrix to calculate the shadows on this scene geometry without needing to send the same data to the GPU again. Is there a way to tell my light shader, hey all that juicy geometry scene data you want is already in V Ram, just use this matrix transformation instead. Alternatively when I am sending the VAO to the GPU is there a way to send it to two shades in parallel, one for the deferred rending model, one for shadow casing light sources? Thanks so much!


Python Opengl Procedural Terrain Rendering I am rendering procedural terrain in Python using OpenGL. Once generated, data for each terrain tile is stored in lists. However currently I am only getting around 25fps despite rendering only around 4000 polygons (2 per terrain tile). The model x and z coordinates are stored in the position matrix contained in the terrain quad location list where as the heights are stored in the vertices of each terrain tile quad in the terrain VAO list. It seems like this low fps is due to inefficiency when render large numbers of models not polygons as when I render models with high polygon counts in addition to this my fps is minimally affected. For reference I am using VAOs, VBOs and EBOs and built upon these tutorials. Is there a way I can make the code more efficient? Before Runtime count 0 for i in range(terrain quad number) terrain VAO count glGenVertexArrays(1) glBindVertexArray(terrain VAO count ) terrain VBO count glGenBuffers(1) glBindBuffer(GL ARRAY BUFFER, terrain VBO count ) glBufferData(GL ARRAY BUFFER, terrain quad vertices count .nbytes, terrain quad vertices count , GL STATIC DRAW) terrain EBO count glGenBuffers(1) glBindBuffer(GL ELEMENT ARRAY BUFFER, terrain EBO count ) glBufferData(GL ELEMENT ARRAY BUFFER, terrain quad vertices count .nbytes, quad indices, GL STATIC DRAW) glEnableVertexAttribArray(0) glVertexAttribPointer(0, 3, GL FLOAT, GL FALSE, terrain quad vertices count .itemsize 5, ctypes.c void p(0)) glEnableVertexAttribArray(1) glVertexAttribPointer(1, 2, GL FLOAT, GL FALSE, terrain quad vertices count .itemsize 5, ctypes.c void p(12)) Runtime moo 0 for i in range (len(rendered terrain number)) model terrain quad location rendered terrain number moo glBindVertexArray(terrain VAO rendered terrain number moo ) glBindTexture(GL TEXTURE 2D, ground textures int(terrain quad sub biome int(rendered terrain number moo ) 0 0 ) 1 ) glUniformMatrix4fv(model loc, 1, GL FALSE, model) glDrawElements(GL TRIANGLES, len(quad indices), GL UNSIGNED INT, None) moo moo 1 I understand that I may need to lower the number of draw calls which may be done my merging terrain tile models, but how do I do this given I want each tile to have its own texture? Apparently Minecraft does this by merging every block in a chunk into one VBO but how is this done given every block has a different texture? Instancing would not work either. Here is a video of the program.


Eye Parallax Refraction Shader I am trying to implement the Parallax Refraction effect explained by Jorge Jimenez on this presentation http www.iryoku.com downloads Next Generation Character Rendering v6.pptx and I am facing some difficulties. Here is a screenshot of the interesting part. But this document lacks a bit of explanations especially the second part with the Physically based Refraction. Here is what I've achieved for the moment. This is the simple Parallax Refraction effect and, as you might notice in the screenshot, there is small glitch at grazing angles in the iris when the Parallax Scale value is too high. This seems to be caused by the parallax calculation but are there some tricks to avoid or minimize such issue ? I don't want to go deeper with parallax mapping for the moment, so I don't want to use Steep Parallax Mapping or Parallax Occlusion Mapping. This is the simple Parallax Refraction part. height value comes from a texture float2 offset height viewDir offset.y offset.y texcoord ParallaxScale offset Next there is the texture sampling with the texcoord value Here is the way I calculate the refraction vector according to Snell's law. float cosine dot(viewDir, worldNormal) float sine sqrt(1 cosine cosine) float sine2 ( IOR sine) float cosine2 sqrt(1 sine2 sine2) float3 x worldNormal float3 y normalize(cross(cross(viewDir, worldNormal), worldNormal)) float3 refractedW x cosine2 y sine2 This is integrated with the Physically based Refraction and it gives interesting results but I still don't know how to get rid of the high parallax scale issue which appear at grazing angles... Any idea how to get rig of that ? Thanks a lot.


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


How to toggle fullscreen with lwjgl I'm using glfw in lwjgl 3 to try to create a toggleFullscreen method. However it always gives me errors. I saw this question Toggle Fullscreen at Runtime but it didn't help because glfwOpenWindow() and glfwCloseWindow() don't exist for me. I guess lwjgl uses a differnt version of glfw? Does anyone know of a good solution for toggling fullscreen? thanks. this is my current code if it helps. public void toggleFullscreen() long newWindow fullscreen !fullscreen if(fullscreen) newWindow glfwCreateWindow(windowWidth, windowHeight, "Title", glfwGetPrimaryMonitor(), window.getWindowHandle()) glfwMakeContextCurrent( newWindow ) else newWindow glfwCreateWindow(windowWidth, windowHeight, "Title", NULL, windowHandle()) glfwMakeContextCurrent( newWindow ) glfwDestroyWindow(window.getWindowHandle()) windowHandle newWindow glfwMakeContextCurrent(windowHandle) glfwSwapInterval(1) glfwShowWindow(windowHandle) GLContext.createFromCurrent() GL11.glEnable(GL11.GL TEXTURE 2D) glClearColor(0.0f, 1.0f, 0.0f, 0.0f) GL11.glEnable(GL11.GL BLEND) GL11.glBlendFunc(GL11.GL SRC ALPHA, GL11.GL ONE MINUS SRC ALPHA) GL11.glViewport(0,0,windowWidth,windowHeight) GL11.glOrtho(0, windowWidth, windowHeight, 0, 1, 1) GL11.glMatrixMode(GL11.GL MODELVIEW) game.initInputPolling()


OpenGL Get Rotated X and Y of quad I am developing a game in 2D using LWJGL library. So far I have a rotating box. I have done basic Rectangle collision, but it doesn't work for rotated rectangles. Does OpenGL have a function that returns the vertices of rotated rectangle? Or is there another way of doing this using trigonometry? I had researched how to do this and everything I found was using some matrix that I don't understand so I am asking if there is another way of doing this. For clarification, I am trying to find out the true (rotated) X,Y of each point of the rectangle. Let's say, the first point of a rectangle (top,left) has x 10 y 10.. Width and height is 100 pixels. When I rotate the rectangle using glRotatef() the x and y stay the same. The rotation is happening inside OpenGL. I need to extract the x,y of the rectangle so I can detect collisions properly.