• Announcements

    • khawk

      Download the Game Design and Indie Game Marketing Freebook   07/19/17

      GameDev.net and CRC Press have teamed up to bring a free ebook of content curated from top titles published by CRC Press. The freebook, Practices of Game Design & Indie Game Marketing, includes chapters from The Art of Game Design: A Book of Lenses, A Practical Guide to Indie Game Marketing, and An Architectural Approach to Level Design. The GameDev.net FreeBook is relevant to game designers, developers, and those interested in learning more about the challenges in game development. We know game development can be a tough discipline and business, so we picked several chapters from CRC Press titles that we thought would be of interest to you, the GameDev.net audience, in your journey to design, develop, and market your next game. The free ebook is available through CRC Press by clicking here. The Curated Books The Art of Game Design: A Book of Lenses, Second Edition, by Jesse Schell Presents 100+ sets of questions, or different lenses, for viewing a game’s design, encompassing diverse fields such as psychology, architecture, music, film, software engineering, theme park design, mathematics, anthropology, and more. Written by one of the world's top game designers, this book describes the deepest and most fundamental principles of game design, demonstrating how tactics used in board, card, and athletic games also work in video games. It provides practical instruction on creating world-class games that will be played again and again. View it here. A Practical Guide to Indie Game Marketing, by Joel Dreskin Marketing is an essential but too frequently overlooked or minimized component of the release plan for indie games. A Practical Guide to Indie Game Marketing provides you with the tools needed to build visibility and sell your indie games. With special focus on those developers with small budgets and limited staff and resources, this book is packed with tangible recommendations and techniques that you can put to use immediately. As a seasoned professional of the indie game arena, author Joel Dreskin gives you insight into practical, real-world experiences of marketing numerous successful games and also provides stories of the failures. View it here. An Architectural Approach to Level Design This is one of the first books to integrate architectural and spatial design theory with the field of level design. The book presents architectural techniques and theories for level designers to use in their own work. It connects architecture and level design in different ways that address the practical elements of how designers construct space and the experiential elements of how and why humans interact with this space. Throughout the text, readers learn skills for spatial layout, evoking emotion through gamespaces, and creating better levels through architectural theory. View it here. Learn more and download the ebook by clicking here. Did you know? GameDev.net and CRC Press also recently teamed up to bring GDNet+ Members up to a 20% discount on all CRC Press books. Learn more about this and other benefits here.
Sign in to follow this  
Followers 0
synthetix

OpenGL
OpenGL ES 2.0: How to specify normals when using an index?

18 posts in this topic

I have an OpenGL ES 2.0-based app I'm working on, and am having trouble with lighting. I would like to send both vertices and normals to the vertex shader, but I don't know of a way to do this. I can send the vertices to the shader and it renders the model properly using my index specified with GL_ELEMENT_ARRAY_BUFFER, but the lighting isn't rendered properly without the normals.

Here's the code I'm working with:

[CODE]
glEnableVertexAttribArray(0); //vertices
glEnableVertexAttribArray(1); //normals
glBindAttribLocation(prog, 0, "v_position"); //bind this var to 0
glBindAttribLocation(prog, 1, "v_normal"); //bind this var to 1

//generate buffers
GLuint vbuf_id[2],ibuf_id[2];
glGenBuffers(2, vbuf_id); //vertex buffers
glGenBuffers(2, ibuf_id); //index buffers

//create and bind buffer for vertices
glBindBuffer(GL_ARRAY_BUFFER, vbuf_id[0]); //vertex buffer
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, (void*)0);
glBindBuffer(GL_ARRAY_BUFFER,0); //unbind

//create and bind another buffer for normals
glBindBuffer(GL_ARRAY_BUFFER, vbuf_id[1]); //normal buffer
glBufferData(GL_ARRAY_BUFFER, sizeof(normals), normals, GL_STATIC_DRAW);
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 0, (void*)0);
glBindBuffer(GL_ARRAY_BUFFER,0); //unbind

//create IBO (index buffer)
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibuf_id[0]);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(index), index, GL_STATIC_DRAW);
[/CODE]

Which works great for vertices, using the supplied index. However, since the index only references the vertices, how do I include the normals? I have a list of normals from a COLLADA file, but I can't seem to get the vertex shader to process them correctly. I also had to remove the normals entries from the index because OpenGL wouldn't work if I included them. Apparently, the GL_ELEMENT_ARRAY_BUFFER wants packed entries for vertices ONLY.

What am I doing wrong? I'm happy to supply any additional information that may help.
1

Share this post


Link to post
Share on other sites
[quote name='Brother Bob' timestamp='1339631913' post='4948985']
You are incorrect that the index only reference the vertices. An index references [i]all[/i] enabled attributes. Since you are using generic attributes, there is no notation of vertex or normal, or anything for the matter, as far as OpenGL is concerned anyway since the attribute could be anything.
[/quote]
Ah, got it. Thanks for clearing that up.

[quote]
So, do you have exactly one normal for every position in the corresponding attribute array? If not, the normal array is not correct since you have normals without corresponding position, or vice versa.
[/quote]
I should have an equal number of vertices and normals, per the COLLADA file. I made sure it was exported properly and the model in question works fine on an OpenGL (non-ES) 2.0 implementation. I am just trying to get everything working on ES 2.0 for use on phones.

I can build either one or two arrays. One with vertices and normals interleaved, or two separate arrays that each correspond to a distinct attribute variable. Assuming I have two GL_ARRAY_BUFFERS, each attached to its own attribute variable in the vertex shader, how does OpenGL know which index values correspond to each array/attribute?

FYI, my index is from the COLLADA file, and looks like this (where V is a vertex position, and N is a normal):

VNVNVNVNVN...etc Edited by Synthetix
1

Share this post


Link to post
Share on other sites
[quote name='Synthetix' timestamp='1339633016' post='4948991']
I can build either one or two arrays. One with vertices and normals interleaved, or two separate arrays that each correspond to a distinct attribute variable. Assuming I have two GL_ARRAY_BUFFERS, each attached to its own attribute variable in the vertex shader, how does OpenGL know which index values correspond to each array/attribute?

FYI, my index is from the COLLADA file, and looks like this (where V is a vertex position, and N is a normal):

VNVNVNVNVN...etc
[/quote]
As I said in the first quote that you acknowledged; an index references [i]all[/i] enabled attribute arrays. You can only have one index array, and each index in that array will reference all enabled attributes to construct one vertex. Thus, if you have the index array [1, 4, 5], then you have three vertices; first vertex is constructed from the second position and the second normal; the second vertex is constructed from the fifth position and the fifth normal; and the third vertex is constructed from the sixth position and the sixth normal.

Each index references all enabled attributes to construct a single vertex, and the array of indices are reference in sequence to construct a sequence of vertices.

edit: And note it is irrelevant whether you have an interleaved array or two separate arrays. An array (in this context) is defined by the glVertexAttribPointer. Whether you make the two calls (one for positions and one for normals) to the same or different buffer objects, or with packed or strided arrays, is irrelevant. Two pointers; two arrays. Edited by Brother Bob
2

Share this post


Link to post
Share on other sites
[quote name='Brother Bob' timestamp='1339634584' post='4948997']
As I said in the first quote that you acknowledged; an index references [i]all[/i] enabled attribute arrays. You can only have one index array, and each index in that array will reference all enabled attributes to construct one vertex. Thus, if you have the index array [1, 4, 5], then you have three vertices; first vertex is constructed from the second position and the second normal; the second vertex is constructed from the fifth position and the fifth normal; and the third vertex is constructed from the sixth position and the sixth normal.
[/quote]
Okay. I understand. This explains why the model renders properly when I remove the normal entries from the index, because as I mentioned a COLLADA file contains an interleaved index of both vertices and normals: VNVNVNVNVNVN

So my predicament is I have two arrays, one for vertices and one for normals, but I am allowed only one index. The COLLADA file's index interleaves the indices for both in an integer array. I don't think there is any relation between the two indices.

Should I just not use the index at all and assemble the data manually?

Any ideas?
1

Share this post


Link to post
Share on other sites
So basically you have two index arrays; one for positions and one for normals? That is not how OpenGL works with arrays as it expects a single index array for all attributes. You have to rearrange the arrays, and possible duplicate certain attributes, so that the two index arrays are identical. The easiest way is to just flatten the arrays and don't use indices at all.

For example, iterate over the list of triangles and assemble a secondary array for the positions and the normals by reading the indices and the corresponding attributes from the file. What you end up with is a linear list of vertices that corresponds to the final order of the vertices if you reference the indices from the file.
2

Share this post


Link to post
Share on other sites
[quote name='Brother Bob' timestamp='1339637563' post='4949007']
So basically you have two index arrays; one for positions and one for normals? That is not how OpenGL works with arrays as it expects a single index array for all attributes. You have to rearrange the arrays, and possible duplicate certain attributes, so that the two index arrays are identical. The easiest way is to just flatten the arrays and don't use indices at all.

For example, iterate over the list of triangles and assemble a secondary array for the positions and the normals by reading the indices and the corresponding attributes from the file. What you end up with is a linear list of vertices that corresponds to the final order of the vertices if you reference the indices from the file.
[/quote]
Yeah, I think you're right. I'm going to try what you suggested and see if I can get it to work. I'll report back once I'm finished!
0

Share this post


Link to post
Share on other sites
[quote name='Brother Bob' timestamp='1339637563' post='4949007']
So basically you have two index arrays; one for positions and one for normals? That is not how OpenGL works with arrays as it expects a single index array for all attributes. [/quote]
Having only one vertex buffer is good for performance, but specifying multiple vertex buffers is perfectly legitimate.

Bind vertex buffer 0.
Enable attributes and set attribute pointers.

Bind vertex buffer 1.
Enable attributes and set attribute pointers.


Modify your shader so that it returns the color of the normals (stop doing lighting calculations) and check the result.
If it is all black, post your shader.


L. Spiro
1

Share this post


Link to post
Share on other sites
Okay, here's what's happening now. I've removed the index buffer altogether, and am now just using glDrawArrays(). The way I accomplished this was by building a list of vertices using the COLLADA file's index myself, then passing the result to glBufferData(). It works if I don't use the normals. Here's what the output looks like if I use the values of the vertices as normals in the shader:
[attachment=9471:no-norms.png]
Obviously, the vertices are being read correctly. However, here's what I get when I add the normas:
[attachment=9472:with-norms.png]
What gives? I suspect this is a problem with my shader(s). Hopefully this "globe" shape will be a tell-tale sign of something I've done wrong.

Here are the shaders I'm using:

[CODE]
//vertex shader

attribute vec3 v_position;
attribute vec3 v_normal;
varying float lightIntensity;

uniform mat4 model;
//uniform mat4 view;
uniform mat4 proj;

void main(void)
{
vec4 newPosition = proj * model * vec4(v_position,1.0);
gl_Position = newPosition;

//specify direction of light
vec3 light_dir = vec3(0.9,0.8,-3.0);

//if I use this, it looks like a messed up sphere
vec4 newNormal = proj * model * vec4(v_normal,0.0);

//if I use this, I can make out the shape of the model,
//but the lighting over the model is wrong.
//vec4 newNormal = proj * model * vec4(v_position,0.0);

lightIntensity = max(0.0, dot(newNormal.xyz, light_dir));
}
[/CODE]


[CODE]
//fragment shader

varying float lightIntensity;
void main(void)
{
vec4 yellow = vec4(1.0, 1.0, 0.0, 1.0);
gl_FragColor = vec4((yellow * lightIntensity * 0.2).rgb, 1.0);
}
[/CODE]
1

Share this post


Link to post
Share on other sites
Are you using the normal data as position data? The geometry looks like a sphere, and normals are equivalent to points on a sphere.
1

Share this post


Link to post
Share on other sites
[quote name='larspensjo' timestamp='1339697178' post='4949222']
Please show the new code, including the calls to glVertexAttribPointer().
[/quote]

Here's the new code:

[CODE]
//grab locations of attribute vars
glEnableVertexAttribArray(0); //vertices
glBindAttribLocation(prog, 0, "v_position"); //bind this var to 0
glEnableVertexAttribArray(1); //normals
glBindAttribLocation(prog, 1, "v_normal"); //bind this var to 1

//generate buffers
GLuint vbuf_id[2];
glGenBuffers(2, vbuf_id); //vertex buffers

//create and bind buffer for vertices
glBindBuffer(GL_ARRAY_BUFFER, vbuf_id[0]); //vertex buffer
glBufferData(GL_ARRAY_BUFFER, (model->size*sizeof(float))*3, (void*)modeldata, GL_STATIC_DRAW);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, (void*)0);
glBindBuffer(GL_ARRAY_BUFFER,0); //unbind

//create and bind buffer for normals
glBindBuffer(GL_ARRAY_BUFFER, vbuf_id[1]); //normal buffer
glBufferData(GL_ARRAY_BUFFER, (model->size*sizeof(float))*3, (void*)normaldata, GL_STATIC_DRAW);
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 0, (void*)0);
glBindBuffer(GL_ARRAY_BUFFER,0); //unbind
[/CODE]

And then I draw with this:

[CODE]
glDrawArrays(GL_TRIANGLES,0,(model->size*sizeof(float)));
[/CODE]
0

Share this post


Link to post
Share on other sites
Looks very fishy when you're multiplying the size of a float by the size of the model in order to determine how many vertices to draw. It is necessary to multiply in glBufferData because there the size is the number of bytes, but in glDrawArrays it is the number of vertices.
0

Share this post


Link to post
Share on other sites
I figured it out! The problem was the normals needed to precede the vertices when specifying the attribute arrays. So, order matters.

Here are the updated portions of the code:

[CODE]
//grab locations of attribute vars
//array of normals must come before vertices!
glEnableVertexAttribArray(0); //normals
glBindAttribLocation(prog, 0, "v_normals");
glEnableVertexAttribArray(1); //vertices
glBindAttribLocation(prog, 1, "v_position");
[/CODE]

And also here:

[CODE]
//normals
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, (void*)0);
//vertices
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 0, (void*)0);
[/CODE]
0

Share this post


Link to post
Share on other sites
Are you using a Vertex Array Object? It may be that the code works anyway, but it is mandatory from OpenGL 3.

The VAO isn't a data buffer, it is a number of states that are saved and then easily restored when it is time to draw.
0

Share this post


Link to post
Share on other sites
You also need to normalize [background=rgb(248, 248, 248)]newNormal[/background].


L. Spiro Edited by L. Spiro
0

Share this post


Link to post
Share on other sites
[quote name='Synthetix' timestamp='1339741288' post='4949454']
I figured it out! The problem was the normals needed to precede the vertices when specifying the attribute arrays. So, order matters.
[/quote]

I just thought I'd post an update to this. The order the attribute variables wasn't actually the problem. The problem was with the vertex shader. I didn't realize this until running it on a device with a PowerVR SGX 530 GPU (the previous GPU was an Nvidia one).

The problem was that gl_Position was being written too early in the shader. It should be the [i]last thing written in the shader.[/i] Although some drivers may work when gl_Position is written in the middle of the vertex shader, others may fail. This behavior seems to be driver-specific.

Here is an updated version that works with every device I've tried:

[CODE]
//vertex shader

attribute vec3 v_position;
attribute vec3 v_normal;
varying float lightIntensity;

uniform mat4 model;
//uniform mat4 view;
uniform mat4 proj;

void main()
{
//specify direction of light
vec3 light_dir = vec3(0.9,0.8,-3.0);

vec4 newNormal = proj * model * vec4(v_normal,0.0);

lightIntensity = max(0.0, dot(newNormal.xyz, light_dir));

//gl_Position must come LAST!
vec4 newPosition = proj * model * vec4(v_position,1.0);
gl_Position = newPosition;
}
[/CODE]
0

Share this post


Link to post
Share on other sites
[quote name='Synthetix' timestamp='1340867001' post='4953573']
The problem was that gl_Position was being written too early in the shader. It should be the last thing written in the shader. Although some drivers may work when gl_Position is written in the middle of the vertex shader, others may fail. This behavior seems to be driver-specific.
[/quote]

Are you sure about that? I have many shaders where gl_Position is not the last thing. Why does it have to be last?
0

Share this post


Link to post
Share on other sites
[quote name='larspensjo' timestamp='1340883327' post='4953628']
Are you sure about that? I have many shaders where gl_Position is not the last thing. Why does it have to be last?
[/quote]

Yep, I just verified this. This is with a device running a PowerVR SGX 530 GPU. Now I can't say for sure or not whether other things in the code have any influence over this. I just know that if I write anything after gl_Position, the data for the vertices and normals gets swapped (i.e. OpenGL thinks vertex data is normal data and vice versa). That's without changing anything else, just literally moving up/down two lines of code and recompiling.

I indeed [i]did not[/i] have to put gl_Position last when the vetex shader was running on an Nvidia chip. It didn't seem to care.

I also changed my code from using separate buffers to a single OpenGL buffer to hold both vertices and normals, but that didn't seem to affect this issue. Edited by Synthetix
0

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now
Sign in to follow this  
Followers 0

  • Similar Content

    • By Solid_Spy
      Hello, I have been working on SH Irradiance map rendering, and I have been using a GLSL pixel shader to render SH irradiance to 2D irradiance maps for my static objects. I already have it working with 9 3D textures so far for the first 9 SH functions.
      In my GLSL shader, I have to send in 9 SH Coefficient 3D Texures that use RGBA8 as a pixel format. RGB being used for the coefficients for red, green, and blue, and the A for checking if the voxel is in use (for the 3D texture solidification shader to prevent bleeding).
      My problem is, I want to knock this number of textures down to something like 4 or 5. Getting even lower would be a godsend. This is because I eventually plan on adding more SH Coefficient 3D Textures for other parts of the game map (such as inside rooms, as opposed to the outside), to circumvent irradiance probe bleeding between rooms separated by walls. I don't want to reach the 32 texture limit too soon. Also, I figure that it would be a LOT faster.
      Is there a way I could, say, store 2 sets of SH Coefficients for 2 SH functions inside a texture with RGBA16 pixels? If so, how would I extract them from inside GLSL? Let me know if you have any suggestions ^^.
    • By DaniDesu
      #include "MyEngine.h" int main() { MyEngine myEngine; myEngine.run(); return 0; } MyEngine.h
      #pragma once #include "MyWindow.h" #include "MyShaders.h" #include "MyShapes.h" class MyEngine { private: GLFWwindow * myWindowHandle; MyWindow * myWindow; public: MyEngine(); ~MyEngine(); void run(); }; MyEngine.cpp
      #include "MyEngine.h" MyEngine::MyEngine() { MyWindow myWindow(800, 600, "My Game Engine"); this->myWindow = &myWindow; myWindow.createWindow(); this->myWindowHandle = myWindow.getWindowHandle(); // Load all OpenGL function pointers for use gladLoadGLLoader((GLADloadproc)glfwGetProcAddress); } MyEngine::~MyEngine() { this->myWindow->destroyWindow(); } void MyEngine::run() { MyShaders myShaders("VertexShader.glsl", "FragmentShader.glsl"); MyShapes myShapes; GLuint vertexArrayObjectHandle; float coordinates[] = { 0.5f, 0.5f, 0.0f, 0.5f, -0.5f, 0.0f, -0.5f, 0.5f, 0.0f }; vertexArrayObjectHandle = myShapes.drawTriangle(coordinates); while (!glfwWindowShouldClose(this->myWindowHandle)) { glClearColor(0.5f, 0.5f, 0.5f, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Draw something glUseProgram(myShaders.getShaderProgram()); glBindVertexArray(vertexArrayObjectHandle); glDrawArrays(GL_TRIANGLES, 0, 3); glfwSwapBuffers(this->myWindowHandle); glfwPollEvents(); } } MyShaders.h
      #pragma once #include <glad\glad.h> #include <GLFW\glfw3.h> #include "MyFileHandler.h" class MyShaders { private: const char * vertexShaderFileName; const char * fragmentShaderFileName; const char * vertexShaderCode; const char * fragmentShaderCode; GLuint vertexShaderHandle; GLuint fragmentShaderHandle; GLuint shaderProgram; void compileShaders(); public: MyShaders(const char * vertexShaderFileName, const char * fragmentShaderFileName); ~MyShaders(); GLuint getShaderProgram(); const char * getVertexShaderCode(); const char * getFragmentShaderCode(); }; MyShaders.cpp
      #include "MyShaders.h" MyShaders::MyShaders(const char * vertexShaderFileName, const char * fragmentShaderFileName) { this->vertexShaderFileName = vertexShaderFileName; this->fragmentShaderFileName = fragmentShaderFileName; // Load shaders from files MyFileHandler myVertexShaderFileHandler(this->vertexShaderFileName); this->vertexShaderCode = myVertexShaderFileHandler.readFile(); MyFileHandler myFragmentShaderFileHandler(this->fragmentShaderFileName); this->fragmentShaderCode = myFragmentShaderFileHandler.readFile(); // Compile shaders this->compileShaders(); } MyShaders::~MyShaders() { } void MyShaders::compileShaders() { this->vertexShaderHandle = glCreateShader(GL_VERTEX_SHADER); this->fragmentShaderHandle = glCreateShader(GL_FRAGMENT_SHADER); glShaderSource(this->vertexShaderHandle, 1, &(this->vertexShaderCode), NULL); glShaderSource(this->fragmentShaderHandle, 1, &(this->fragmentShaderCode), NULL); glCompileShader(this->vertexShaderHandle); glCompileShader(this->fragmentShaderHandle); this->shaderProgram = glCreateProgram(); glAttachShader(this->shaderProgram, this->vertexShaderHandle); glAttachShader(this->shaderProgram, this->fragmentShaderHandle); glLinkProgram(this->shaderProgram); return; } GLuint MyShaders::getShaderProgram() { return this->shaderProgram; } const char * MyShaders::getVertexShaderCode() { return this->vertexShaderCode; } const char * MyShaders::getFragmentShaderCode() { return this->fragmentShaderCode; } MyWindow.h
      #pragma once #include <glad\glad.h> #include <GLFW\glfw3.h> class MyWindow { private: GLFWwindow * windowHandle; int windowWidth; int windowHeight; const char * windowTitle; public: MyWindow(int windowWidth, int windowHeight, const char * windowTitle); ~MyWindow(); GLFWwindow * getWindowHandle(); void createWindow(); void MyWindow::destroyWindow(); }; MyWindow.cpp
      #include "MyWindow.h" MyWindow::MyWindow(int windowWidth, int windowHeight, const char * windowTitle) { this->windowHandle = NULL; this->windowWidth = windowWidth; this->windowWidth = windowWidth; this->windowHeight = windowHeight; this->windowTitle = windowTitle; glfwInit(); } MyWindow::~MyWindow() { } GLFWwindow * MyWindow::getWindowHandle() { return this->windowHandle; } void MyWindow::createWindow() { // Use OpenGL 3.3 and GLSL 3.3 glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); // Limit backwards compatibility glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); // Prevent resizing window glfwWindowHint(GLFW_RESIZABLE, GL_FALSE); // Create window this->windowHandle = glfwCreateWindow(this->windowWidth, this->windowHeight, this->windowTitle, NULL, NULL); glfwMakeContextCurrent(this->windowHandle); } void MyWindow::destroyWindow() { glfwTerminate(); } MyShapes.h
      #pragma once #include <glad\glad.h> #include <GLFW\glfw3.h> class MyShapes { public: MyShapes(); ~MyShapes(); GLuint & drawTriangle(float coordinates[]); }; MyShapes.cpp
      #include "MyShapes.h" MyShapes::MyShapes() { } MyShapes::~MyShapes() { } GLuint & MyShapes::drawTriangle(float coordinates[]) { GLuint vertexBufferObject{}; GLuint vertexArrayObject{}; // Create a VAO glGenVertexArrays(1, &vertexArrayObject); glBindVertexArray(vertexArrayObject); // Send vertices to the GPU glGenBuffers(1, &vertexBufferObject); glBindBuffer(GL_ARRAY_BUFFER, vertexBufferObject); glBufferData(GL_ARRAY_BUFFER, sizeof(coordinates), coordinates, GL_STATIC_DRAW); // Dertermine the interpretation of the array buffer glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3*sizeof(float), (void *)0); glEnableVertexAttribArray(0); // Unbind the buffers glBindBuffer(GL_ARRAY_BUFFER, 0); glBindVertexArray(0); return vertexArrayObject; } MyFileHandler.h
      #pragma once #include <cstdio> #include <cstdlib> class MyFileHandler { private: const char * fileName; unsigned long fileSize; void setFileSize(); public: MyFileHandler(const char * fileName); ~MyFileHandler(); unsigned long getFileSize(); const char * readFile(); }; MyFileHandler.cpp
      #include "MyFileHandler.h" MyFileHandler::MyFileHandler(const char * fileName) { this->fileName = fileName; this->setFileSize(); } MyFileHandler::~MyFileHandler() { } void MyFileHandler::setFileSize() { FILE * fileHandle = NULL; fopen_s(&fileHandle, this->fileName, "rb"); fseek(fileHandle, 0L, SEEK_END); this->fileSize = ftell(fileHandle); rewind(fileHandle); fclose(fileHandle); return; } unsigned long MyFileHandler::getFileSize() { return (this->fileSize); } const char * MyFileHandler::readFile() { char * buffer = (char *)malloc((this->fileSize)+1); FILE * fileHandle = NULL; fopen_s(&fileHandle, this->fileName, "rb"); fread(buffer, this->fileSize, sizeof(char), fileHandle); fclose(fileHandle); buffer[this->fileSize] = '\0'; return buffer; } VertexShader.glsl
      #version 330 core layout (location = 0) vec3 VertexPositions; void main() { gl_Position = vec4(VertexPositions, 1.0f); } FragmentShader.glsl
      #version 330 core out vec4 FragmentColor; void main() { FragmentColor = vec4(1.0f, 0.0f, 0.0f, 1.0f); } I am attempting to create a simple engine/graphics utility using some object-oriented paradigms. My first goal is to get some output from my engine, namely, a simple red triangle.
      For this goal, the MyShapes class will be responsible for defining shapes such as triangles, polygons etc. Currently, there is only a drawTriangle() method implemented, because I first wanted to see whether it works or not before attempting to code other shape drawing methods.
      The constructor of the MyEngine class creates a GLFW window (GLAD is also initialized here to load all OpenGL functionality), and the myEngine.run() method in Main.cpp is responsible for firing up the engine. In this run() method, the shaders get loaded from files via the help of my FileHandler class. The vertices for the triangle are processed by the myShapes.drawTriangle() method where a vertex array object, a vertex buffer object and vertrex attributes are set for this purpose.
      The while loop in the run() method should be outputting me the desired red triangle, but all I get is a grey window area. Why?
      Note: The shaders are compiling and linking without any errors.
      (Note: I am aware that this code is not using any good software engineering practices (e.g. exceptions, error handling). I am planning to implement them later, once I get the hang of OpenGL.)

       
    • By KarimIO
      EDIT: I thought this was restricted to Attribute-Created GL contexts, but it isn't, so I rewrote the post.
      Hey guys, whenever I call SwapBuffers(hDC), I get a crash, and I get a "Too many posts were made to a semaphore." from Windows as I call SwapBuffers. What could be the cause of this?
      Update: No crash occurs if I don't draw, just clear and swap.
      static PIXELFORMATDESCRIPTOR pfd = // pfd Tells Windows How We Want Things To Be { sizeof(PIXELFORMATDESCRIPTOR), // Size Of This Pixel Format Descriptor 1, // Version Number PFD_DRAW_TO_WINDOW | // Format Must Support Window PFD_SUPPORT_OPENGL | // Format Must Support OpenGL PFD_DOUBLEBUFFER, // Must Support Double Buffering PFD_TYPE_RGBA, // Request An RGBA Format 32, // Select Our Color Depth 0, 0, 0, 0, 0, 0, // Color Bits Ignored 0, // No Alpha Buffer 0, // Shift Bit Ignored 0, // No Accumulation Buffer 0, 0, 0, 0, // Accumulation Bits Ignored 24, // 24Bit Z-Buffer (Depth Buffer) 0, // No Stencil Buffer 0, // No Auxiliary Buffer PFD_MAIN_PLANE, // Main Drawing Layer 0, // Reserved 0, 0, 0 // Layer Masks Ignored }; if (!(hDC = GetDC(windowHandle))) return false; unsigned int PixelFormat; if (!(PixelFormat = ChoosePixelFormat(hDC, &pfd))) return false; if (!SetPixelFormat(hDC, PixelFormat, &pfd)) return false; hRC = wglCreateContext(hDC); if (!hRC) { std::cout << "wglCreateContext Failed!\n"; return false; } if (wglMakeCurrent(hDC, hRC) == NULL) { std::cout << "Make Context Current Second Failed!\n"; return false; } ... // OGL Buffer Initialization glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT); glBindVertexArray(vao); glUseProgram(myprogram); glDrawElements(GL_TRIANGLES, indexCount, GL_UNSIGNED_SHORT, (void *)indexStart); SwapBuffers(GetDC(window_handle));  
    • By Tchom
      Hey devs!
       
      I've been working on a OpenGL ES 2.0 android engine and I have begun implementing some simple (point) lighting. I had something fairly simple working, so I tried to get fancy and added color-tinting light. And it works great... with only one or two lights. Any more than that, the application drops about 15 frames per light added (my ideal is at least 4 or 5). I know implementing lighting is expensive, I just didn't think it was that expensive. I'm fairly new to the world of OpenGL and GLSL, so there is a good chance I've written some crappy shader code. If anyone had any feedback or tips on how I can optimize this code, please let me know.
       
      Vertex Shader
      uniform mat4 u_MVPMatrix; uniform mat4 u_MVMatrix; attribute vec4 a_Position; attribute vec3 a_Normal; attribute vec2 a_TexCoordinate; varying vec3 v_Position; varying vec3 v_Normal; varying vec2 v_TexCoordinate; void main() { v_Position = vec3(u_MVMatrix * a_Position); v_TexCoordinate = a_TexCoordinate; v_Normal = vec3(u_MVMatrix * vec4(a_Normal, 0.0)); gl_Position = u_MVPMatrix * a_Position; } Fragment Shader
      precision mediump float; uniform vec4 u_LightPos["+numLights+"]; uniform vec4 u_LightColours["+numLights+"]; uniform float u_LightPower["+numLights+"]; uniform sampler2D u_Texture; varying vec3 v_Position; varying vec3 v_Normal; varying vec2 v_TexCoordinate; void main() { gl_FragColor = (texture2D(u_Texture, v_TexCoordinate)); float diffuse = 0.0; vec4 colourSum = vec4(1.0); for (int i = 0; i < "+numLights+"; i++) { vec3 toPointLight = vec3(u_LightPos[i]); float distance = length(toPointLight - v_Position); vec3 lightVector = normalize(toPointLight - v_Position); float diffuseDiff = 0.0; // The diffuse difference contributed from current light diffuseDiff = max(dot(v_Normal, lightVector), 0.0); diffuseDiff = diffuseDiff * (1.0 / (1.0 + ((1.0-u_LightPower[i])* distance * distance))); //Determine attenuatio diffuse += diffuseDiff; gl_FragColor.rgb *= vec3(1.0) / ((vec3(1.0) + ((vec3(1.0) - vec3(u_LightColours[i]))*diffuseDiff))); //The expensive part } diffuse += 0.1; //Add ambient light gl_FragColor.rgb *= diffuse; } Am I making any rookie mistakes? Or am I just being unrealistic about what I can do? Thanks in advance
    • By yahiko00
      Hi,
      Not sure to post at the right place, if not, please forgive me...
      For a game project I am working on, I would like to implement a 2D starfield as a background.
      I do not want to deal with static tiles, since I plan to slowly animate the starfield. So, I am trying to figure out how to generate a random starfield for the entire map.
      I feel that using a uniform distribution for the stars will not do the trick. Instead I would like something similar to the screenshot below, taken from the game Star Wars: Empire At War (all credits to Lucasfilm, Disney, and so on...).

      Is there someone who could have an idea of a distribution which could result in such a starfield?
      Any insight would be appreciated
  • Popular Now