'How i can generate normals in GLSL to apply a lighting to cube?

My cubes looks like: enter image description here

But I want this

enter image description here

I can achive this result if I specify normals in VAO and send it, but i draw the cubes with EBO

auto context = QOpenGLContext::currentContext();
    auto functions = context->functions();
    auto additionalFunctions = context->extraFunctions();
    //float side = diagonal/qSqrt(3);
    unsigned int VBO;
    QVector3D vertices[] = {
 
        QVector3D(-0.5f,0.5f,-0.5f),
        QVector3D(-0.5f,0.5f,0.5f),
        QVector3D(0.5f,0.5f,-0.5f),
        QVector3D(0.5f,0.5f,0.5f),
         
        QVector3D(-0.5f,-0.5f,-0.5f),
        QVector3D(-0.5f,-0.5f,0.5f),
        QVector3D(0.5f,-0.5f,-0.5f), 
        QVector3D(0.5f,-0.5f,0.5f),    
 
    };
    
    unsigned int indices[] = {
        0,1,2,
        1,2,3,
 
        4,5,6,
        5,6,7,
        
        0,1,5,
        0,4,5,
        
        2,3,7,
        2,6,7,
    
        0,2,6,
        0,4,6,
       
        1,5,7,
        1,3,7
    };
  

   functions->glGenBuffers(1, &EBO);
   functions->glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO);
   functions->glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), 
                           indices, GL_STATIC_DRAW);
   functions->glGenBuffers(1, &VBO);
   additionalFunctions->glGenVertexArrays(1, &VAO);
   additionalFunctions->glBindVertexArray(VAO);
   functions->glBindBuffer(GL_ARRAY_BUFFER, VBO);
   functions->glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), 
                           vertices, GL_STATIC_DRAW);
   functions->glEnableVertexAttribArray(0);
   functions->glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(QVector3D), 
                                    nullptr);

vertex shader


#version 130
in vec3 aPos;
uniform mat4 model;
uniform mat4 view;
uniform mat4 projection;

void main()
{
    gl_Position = projection * view * model * vec4(aPos, 1.0);
}

fragment shader

#version 130
out vec4 FragColor;
uniform vec3 objectColor;
uniform vec3 lightColor;
void main()
{
    
    float ambientStrength = 0.1;
    vec3 ambient = ambientStrength * lightColor;
    vec3 result = ambient * objectColor;
    FragColor = vec4(lightColor * objectColor, 1.0);
}

So, my question is, is it possible to draw cube with EBO with this 8 verteces and specify this material only with shaders and how i can do it without calculating normals manually in CPU?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source