AlgebraMaster

Modern C++ 创造非凡 . 改变世界

导航

-OPENGL4 Shader & WorldSpaceShader & CameraSpaceShader & Blinn -

CP13:

 

 

全部合并成头文件,实现进一步抽象简洁

一个摄像机GLFWCamera.h

一个读取材质LoadShader.h

一个FrameWindow

 

cmake_minimum_required(VERSION 3.5)

project(Triangle)

set(CMAKE_CXX_STANDARD 11)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
# OPENGL
find_package(OpenGL REQUIRED)
include_directories(${OpenGL_INCLUDE_DIRS})
link_directories(${OpenGL_LIBRARY_DIRS})
add_definitions(${OpenGL_DEFINITIONS})

if(NOT OPENGL_FOUND)
    message(ERROR " OPENGL not found!")
endif(NOT OPENGL_FOUND)

# GLEW
set(GLEW_HOME D:/plugin_dev/libs/glew-2.1.0)
include_directories(${GLEW_HOME}/include)
link_directories(${GLEW_HOME}/lib/Release/x64)

# GLFW
set(GLFW_HOME D:/plugin_dev/libs/glfw-3.3.1.bin.WIN64)
include_directories(${GLFW_HOME}/include/)
link_directories(${GLFW_HOME}/lib-vc2019)

# STB
include_directories(D:/plugin_dev/libs/stb)

# GLM
include_directories(D:/plugin_dev/libs/GLM_include)

# output excutable dir
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_SOURCE_DIR})


add_executable(Triangle main.cpp LoadShader.h GLFWCamera.h FrameWindow.h)
target_link_libraries(Triangle glew32s glfw3 opengl32)
CMakeLists
#ifndef WINDOW_H
#define WINDOW_H
#undef GLFW_DLL
#include <GLFW/glfw3.h>

#define GLEW_STATIC
#include <GL/glew.h>



class FrameWindow
{
public:
    FrameWindow(int width,int height,const char*title="OpenGL");
    virtual ~FrameWindow();
    GLFWwindow *getWindow();
private:
     GLFWwindow *window;
     int w;
     int h;
};

FrameWindow::FrameWindow(int width,int height,const char*title){
    w = width;
    h = height;
    glfwInit();
    window = glfwCreateWindow(width,height,title,NULL,NULL);
    glfwMakeContextCurrent(window);
    glewInit();

}
FrameWindow::~FrameWindow(){
    glfwDestroyWindow(window);
    glfwTerminate();
}
GLFWwindow * FrameWindow::getWindow(){
    return window;
}

#endif // WINDOW_H
FrameWindow.h
#ifndef LOADSHADER_H
#define LOADSHADER_H


#include <GL/glew.h>

#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>


using namespace std;
struct LoadShader
{
    LoadShader()=default;
    LoadShader(const char*vertPath, const char* fragPath){
        load(vertPath,fragPath);
    }

    string _readFile(const char *path){
        ifstream stream;
        stringstream ss;
        stream.exceptions(ifstream::badbit);
        try
        {
            stream.open(path);    // open file
            ss << stream.rdbuf(); // get strings from file
        } catch (ifstream::failure e)
        {
            cout << "ERROR::OPEN FILE:" << path << endl;
        }
        // close file handle
        stream.close();

        // get str() from stringstream
        string shaderCode = ss.str();
        return shaderCode;
    }

    void _loadVertexShader(const char *path){

        // read shader code
        auto handle = _readFile(path);
        const char * shaderCode = handle.c_str();
        // Vertex shader
        vertexShader = glCreateShader( GL_VERTEX_SHADER );
        glShaderSource( vertexShader, 1, &shaderCode, NULL );
        glCompileShader( vertexShader );
        GLint success;
        GLchar infoLog[512];

        glGetShaderiv( vertexShader, GL_COMPILE_STATUS, &success );
        if ( !success )
        {
            glGetShaderInfoLog( vertexShader, 512, NULL, infoLog );
            std::cout << "ERROR::SHADER::VERTEX::COMPILATION_FAILED\n" << infoLog << std::endl;
        }

    }

    void _loadFragmentShader(const char *path){
        // read shader code
        auto handle = _readFile(path);
        const char * shaderCode = handle.c_str();
        // Vertex shader
        fragmentShader = glCreateShader( GL_FRAGMENT_SHADER );
        glShaderSource( fragmentShader, 1, &shaderCode, NULL );
        glCompileShader( fragmentShader );
        GLint success;
        GLchar infoLog[512];

        glGetShaderiv( fragmentShader, GL_COMPILE_STATUS, &success ); // Get Compile status
        if ( !success )
        {
            glGetShaderInfoLog( fragmentShader, 512, NULL, infoLog );
            std::cout << "ERROR::SHADER::FRAGMENT::COMPILATION_FAILED\n" << infoLog << std::endl;
        }
    }

    void load(const char* vertShaderPath, const char* fragShaderPath){
        _loadVertexShader(vertShaderPath);
        _loadFragmentShader(fragShaderPath);


        // create shader program and check it
        GLint success;
        GLchar infoLog[512];
        shaderProgram = glCreateProgram();
        glAttachShader(shaderProgram,vertexShader);
        glAttachShader(shaderProgram,fragmentShader);
        glLinkProgram(shaderProgram );
        glGetProgramiv( shaderProgram, GL_LINK_STATUS, &success );  // Get Link Status
        if (!success)
        {
           glGetProgramInfoLog( shaderProgram, 512, NULL, infoLog );
           std::cout << "ERROR::SHADER::PROGRAM::LINKING_FAILED\n" << infoLog << std::endl;
        }
        // Delete the shaders as they're linked into our program now and no longer necessery
        glDeleteShader( vertexShader );
        glDeleteShader( fragmentShader );
    }

    void use(){
        glUseProgram(shaderProgram);
    }

    void setBool(const char *name, bool value) const
    {
        glUniform1i(glGetUniformLocation(shaderProgram, name), (int)value);
    }
    void setInt(const char *name, int value) const
    {
        glUniform1i(glGetUniformLocation(shaderProgram,name), value);
    }
    // ------------------------------------------------------------------------
    void setFloat(const char *name, float value) const
    {
        glUniform1f(glGetUniformLocation(shaderProgram, name), value);
    }
    // ------------------------------------------------------------------------
    void setVec2(const char *name, const glm::vec2 &value) const
    {
        glUniform2fv(glGetUniformLocation(shaderProgram,name), 1, &value[0]);
    }

    void setVec2(const char *name, float x, float y) const
    {
        glUniform2f(glGetUniformLocation(shaderProgram,name), x, y);
    }
    // ------------------------------------------------------------------------
    void setVec3(const char *name, const glm::vec3 &value) const
    {
        glUniform3fv(glGetUniformLocation(shaderProgram,name), 1, &value[0]);
    }
    void setVec3(const char *name, float x, float y, float z) const
    {
        glUniform3f(glGetUniformLocation(shaderProgram,name), x, y, z);
    }
    // ------------------------------------------------------------------------
    void setVec4(const char *name, const glm::vec4 &value) const
    {
        glUniform4fv(glGetUniformLocation(shaderProgram,name), 1, &value[0]);
    }
    void setVec4(const char *name, float x, float y, float z, float w)
    {
        glUniform4f(glGetUniformLocation(shaderProgram,name), x, y, z, w);
    }

    void setMat2(const char*name, const glm::mat2 &mat) const
    {
        glUniformMatrix2fv(glGetUniformLocation(shaderProgram, name), 1, GL_FALSE,glm::value_ptr(mat));
    }

    void setMat3(const char*name, const glm::mat3 &mat){
        GLuint location = glGetUniformLocation(shaderProgram, name);
        glUniformMatrix3fv(location,1, GL_FALSE, &mat[0][0]);
    }

    void setMat4(const char *name , const glm::mat4 &mat){
        GLuint location = glGetUniformLocation(shaderProgram, name);
        glUniformMatrix4fv(location,1, GL_FALSE, glm::value_ptr(mat));
    }

    GLuint shaderProgram;
    GLuint vertexShader;
    GLuint fragmentShader;
};





#endif // LOADSHADER_H
LoadShader.h
#ifndef GLFWCAMERA_H
#define GLFWCAMERA_H

#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>


class GLFWCamera{
public:
    GLFWCamera();
    ~GLFWCamera(){}
    enum CAMERA_MOVEMENT{
        FORWARD,     // Camera move to front   ->  key:W
        BACKWARD,    // Camera move to back    ->  key:S
        LEFT,        // Camera move to left    ->  key:A
        RIGHT        // Camera move to right   ->  key:D
    };

public:
    glm::vec3 pos;
    glm::vec3 front;
    glm::vec3 up;

    // Euler Angles
   float yaw;
   float pitch;


   // Camera options
   float movementSpeed;
   float mouseSensitivity;
   float fov;

   void processFov(float yoffset){
       if(fov >= 1.0f && fov <= 45.0f){
           fov -= yoffset;
       }
       if(fov <=1.0f){
           fov = 1.0f;
       }
       if(fov >= 45.0f){
           fov = 45.0f;
       }
   }

   // build the matrix for lookAt
   glm::mat4 GetViewMatrix(){
       return glm::lookAt(pos , pos + front , up);
   }

   // process -Rotate the view-
   void processMouseMove(float xoffset, float yoffset);


   // process -W S A D-
   void processKeyboardMove(float delta, CAMERA_MOVEMENT moveDir);



   void updateFront(){
       glm::vec3 tempfront;
       tempfront.x = cos(glm::radians(yaw)) * cos(glm::radians(pitch));
       tempfront.y = sin(glm::radians(pitch));
       tempfront.z = sin(glm::radians(yaw)) * cos(glm::radians(pitch));
       this->front = glm::normalize(tempfront);
   }


};

GLFWCamera::GLFWCamera(){
    pos = glm::vec3(0.0f,0.0f,3.0f);
    up = glm::vec3(0.0f,1.0f,0.0f);
    front = glm::vec3(0.0f,0.0f,-1.0f);
    yaw = -90.0f;
    pitch = 0.0f;
    fov = 45.0f;
    movementSpeed = 2.5f;
    mouseSensitivity = 0.1f;
}

void GLFWCamera::processMouseMove(float xoffset, float yoffset)
{

    xoffset *= mouseSensitivity;
    yoffset *= mouseSensitivity;

    yaw += xoffset;
    pitch += yoffset;

    // make sure that when pitch is out of bounds, screen doesn't get flipped
    if (pitch > 89.0f)
        pitch = 89.0f;
    if (pitch < -89.0f)
        pitch = -89.0f;
    this->updateFront();
}

void GLFWCamera::processKeyboardMove(float delta, CAMERA_MOVEMENT moveDir)
{
    float vel = movementSpeed * delta;
    switch (moveDir)
    {
    case FORWARD:
        {
            pos += vel * front;
            break;
        }
    case BACKWARD:
        {
            pos -= vel * front;
            break;
        }
    case LEFT:
        {
            pos -= glm::normalize(glm::cross(front, up)) * vel;
            break;
        }
    case RIGHT:
        {
            pos += glm::normalize(glm::cross(front, up)) * vel;
        }
    default:
        break;
    }
}

#endif // GLFWCAMERA_H
GLFWCamera.h
#define GLEW_STATIC
// GLEW

#include <GL/glew.h>
#include <cstdlib>
#undef GLFW_DLL
// GLFW
#include <GLFW/glfw3.h>
#include <iostream>
#include "LoadShader.h"
#include "GLFWCamera.h"
#include "FrameWindow.h"


#define STB_IMAGE_IMPLEMENTATION
#include <stb_image.h>
#include <cmath>


#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>



const unsigned int SRC_WIDTH = 1400;
const unsigned int SRC_HEIGHT = 720;


static GLuint VAO,VBO,EBO;
static LoadShader shader;
void init();
void display();
void showFPS(GLFWwindow *);


void processInput(GLFWwindow *window);
void framebuffer_size_callback(GLFWwindow* window, int width, int height); // framezize
void mouse_callback(GLFWwindow* window, double xpos, double ypos); // Maya Alt+LeftMouse
void scroll_callback(GLFWwindow *window, double xoffset, double yoffset);


// camera
static GLFWCamera *camera;


static float lastX =  float(SRC_WIDTH) / 2.0f;
static float lastY =  float(SRC_HEIGHT) / 2.0f;

static bool firstMouse = true;

// timing
static float deltaTime = 0.0f;    // time between current frame and last frame
static float lastFrame = 0.0f;



// world space positions of our cubes
static  glm::vec3 cubePositions[] = {
        glm::vec3( 0.0f,  0.0f,  0.0f),
        glm::vec3( 2.0f,  5.0f, -15.0f),
        glm::vec3(-1.5f, -2.2f, -2.5f),
        glm::vec3(-3.8f, -2.0f, -12.3f),
        glm::vec3( 2.4f, -0.4f, -3.5f),
        glm::vec3(-1.7f,  3.0f, -7.5f),
        glm::vec3( 1.3f, -2.0f, -2.5f),
        glm::vec3( 1.5f,  2.0f, -2.5f),
        glm::vec3( 1.5f,  0.2f, -1.5f),
        glm::vec3(-1.3f,  1.0f, -1.5f)
};


void init(){
    camera = new GLFWCamera;

    float vertices[] = {
        -0.5f, -0.5f, -0.5f,  0.0f, 0.0f,
         0.5f, -0.5f, -0.5f,  1.0f, 0.0f,
         0.5f,  0.5f, -0.5f,  1.0f, 1.0f,
         0.5f,  0.5f, -0.5f,  1.0f, 1.0f,
        -0.5f,  0.5f, -0.5f,  0.0f, 1.0f,
        -0.5f, -0.5f, -0.5f,  0.0f, 0.0f,

        -0.5f, -0.5f,  0.5f,  0.0f, 0.0f,
         0.5f, -0.5f,  0.5f,  1.0f, 0.0f,
         0.5f,  0.5f,  0.5f,  1.0f, 1.0f,
         0.5f,  0.5f,  0.5f,  1.0f, 1.0f,
        -0.5f,  0.5f,  0.5f,  0.0f, 1.0f,
        -0.5f, -0.5f,  0.5f,  0.0f, 0.0f,

        -0.5f,  0.5f,  0.5f,  1.0f, 0.0f,
        -0.5f,  0.5f, -0.5f,  1.0f, 1.0f,
        -0.5f, -0.5f, -0.5f,  0.0f, 1.0f,
        -0.5f, -0.5f, -0.5f,  0.0f, 1.0f,
        -0.5f, -0.5f,  0.5f,  0.0f, 0.0f,
        -0.5f,  0.5f,  0.5f,  1.0f, 0.0f,

         0.5f,  0.5f,  0.5f,  1.0f, 0.0f,
         0.5f,  0.5f, -0.5f,  1.0f, 1.0f,
         0.5f, -0.5f, -0.5f,  0.0f, 1.0f,
         0.5f, -0.5f, -0.5f,  0.0f, 1.0f,
         0.5f, -0.5f,  0.5f,  0.0f, 0.0f,
         0.5f,  0.5f,  0.5f,  1.0f, 0.0f,

        -0.5f, -0.5f, -0.5f,  0.0f, 1.0f,
         0.5f, -0.5f, -0.5f,  1.0f, 1.0f,
         0.5f, -0.5f,  0.5f,  1.0f, 0.0f,
         0.5f, -0.5f,  0.5f,  1.0f, 0.0f,
        -0.5f, -0.5f,  0.5f,  0.0f, 0.0f,
        -0.5f, -0.5f, -0.5f,  0.0f, 1.0f,

        -0.5f,  0.5f, -0.5f,  0.0f, 1.0f,
         0.5f,  0.5f, -0.5f,  1.0f, 1.0f,
         0.5f,  0.5f,  0.5f,  1.0f, 0.0f,
         0.5f,  0.5f,  0.5f,  1.0f, 0.0f,
        -0.5f,  0.5f,  0.5f,  0.0f, 0.0f,
        -0.5f,  0.5f, -0.5f,  0.0f, 1.0f
    };

    glEnable(GL_DEPTH_TEST);

    GLuint indices[6] = {
            0, 1, 3,  // FIRST TRIANGLE
            1, 2, 3   // SECOND TRIANGLE
        };
    shader.load("shader.vert","shader.frag");
    shader.use();

    glCreateVertexArrays(1, &VAO);
    glCreateBuffers(1, &VBO);
    glCreateBuffers(1, &EBO);

    glBindVertexArray(VAO);
    glBindBuffer(GL_ARRAY_BUFFER,VBO);
    //glNamedBufferStorage(VBO,sizeof(verticels), verticels, 0);
    glBufferData(GL_ARRAY_BUFFER,sizeof(vertices), vertices, GL_STATIC_DRAW);



    glCreateBuffers(1, &EBO);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO);
    glNamedBufferStorage(EBO, sizeof(indices), indices , 0);

    // VERTEX POINTS ATTRIBUTES
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 5 * sizeof(float),  (void*)0); // POS at location 0
    glEnableVertexAttribArray(0);
    glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 5 * sizeof(float), (void*)(3 * sizeof(float))); // ST at location 1
    glEnableVertexAttribArray(1);




    cout << "GEN Texture\n";
    // loading one texture
    GLuint textureID;
    glCreateTextures(GL_TEXTURE_2D,1 , &textureID);
    glBindTexture(GL_TEXTURE_2D,textureID);
    glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_T, GL_REPEAT);
    glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_S, GL_REPEAT);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

    int width, height, nrChannels;
    stbi_set_flip_vertically_on_load(true); // tell stb_image.h to flip loaded texture's on the y-axis.
    unsigned char *data = stbi_load("wendy.png", &width, &height, &nrChannels, 0);
    if (data)
    {
        glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, data);
        glGenerateMipmap(GL_TEXTURE_2D);
    }
    cout << "FREE IMAGE\n";
    stbi_image_free(data);

}

void display(){
    // per-frame time logic
            // --------------------
    float currentFrame = glfwGetTime();
    deltaTime = currentFrame - lastFrame;
    lastFrame = currentFrame;


    glClearColor(0.2f, 0.3f, 0.3f, 1.0f);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);




    glm::mat4 projection = glm::perspective(glm::radians(camera->fov),float(SRC_WIDTH) / float(SRC_HEIGHT),0.1f,  1000.0f);
    glm::mat4 view = camera->GetViewMatrix();
    // Send projection and view matrix to shader
    shader.setMat4("projection", projection);
    shader.setMat4("view", view);



    for (unsigned int i = 0; i < 10; i++)
    {
        // RULE : RST
        // FIRST WE ROTATION
        glm::mat4 tempRot = glm::mat4(1.0f);
        tempRot = glm::rotate(tempRot, float(glfwGetTime()*0.5f + float(i) ),glm::vec3(1.00f,0.0f,0.0f));
        // then translate
        glm::mat4 tempTrans = glm::mat4(1.0f);
        tempTrans = glm::translate(tempTrans,cubePositions[i]);

        // final combine one matrix
        glm::mat4 model = glm::mat4(1.0f);
        model = tempTrans * tempRot;
        // send to opengl
        shader.setMat4("model",model);
        glDrawArrays(GL_TRIANGLES,0,36);

    }


}


int main()
{
    glfwInit();
    FrameWindow FrameWindow(SRC_WIDTH,SRC_HEIGHT);
    glfwSetFramebufferSizeCallback(FrameWindow.getWindow(), framebuffer_size_callback);
    glfwSetCursorPosCallback(FrameWindow.getWindow(),mouse_callback);
    glfwSetScrollCallback(FrameWindow.getWindow(), scroll_callback);
    init();
    // RENDER--------------
    while(!glfwWindowShouldClose(FrameWindow.getWindow())){
        processInput(FrameWindow.getWindow());
        display();
        glfwSwapBuffers(FrameWindow.getWindow());
        glfwPollEvents();
    }
    delete camera;
    return 0;
}

void framebuffer_size_callback(GLFWwindow* window, int width, int height)
{
    // make sure the viewport matches the new window dimensions; note that width and
    // height will be significantly larger than specified on retina displays.
    glViewport(0, 0, width, height);
}

void processInput(GLFWwindow *window)
{
    if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS)
        glfwSetWindowShouldClose(window, true);
    if (glfwGetKey(window, GLFW_KEY_W) == GLFW_PRESS)
        camera->processKeyboardMove(deltaTime,GLFWCamera::FORWARD);
    if (glfwGetKey(window, GLFW_KEY_S) == GLFW_PRESS)
        camera->processKeyboardMove(deltaTime,GLFWCamera::BACKWARD);
    if (glfwGetKey(window, GLFW_KEY_A) == GLFW_PRESS)
        camera->processKeyboardMove(deltaTime,GLFWCamera::LEFT);
    if (glfwGetKey(window, GLFW_KEY_D) == GLFW_PRESS)
        camera->processKeyboardMove(deltaTime,GLFWCamera::RIGHT);
}

// ROTATE VIEW DIR
void mouse_callback(GLFWwindow* window, double xpos, double ypos){
    int mouse_state = glfwGetMouseButton(window,GLFW_MOUSE_BUTTON_LEFT);
    int key_state = glfwGetKey(window,GLFW_KEY_LEFT_ALT);

    if( mouse_state == GLFW_PRESS && key_state== GLFW_PRESS)
    {
        if (firstMouse){
            lastX = xpos;
            lastY = ypos;
            firstMouse = false;
        }
        float xoffset = xpos - lastX;
        float yoffset = lastY - ypos; // reversed since y-coordinates go from bottom to top
        lastX = xpos;
        lastY = ypos;
        camera->processMouseMove(xoffset,yoffset);
    }
    if (key_state == GLFW_RELEASE || mouse_state == GLFW_RELEASE){
        firstMouse = true;
    }

}

void scroll_callback(GLFWwindow *window, double xoffset, double yoffset){
    camera->processFov(yoffset);
}
main.cpp

 

CP14:

没按教程的材质写,但是套路一样,用的BLINN高光。而且规范使用物理渲染中的命名。

同样白色立方体为灯光。本案例灯光只是个傀儡,负责位置的刷新,这个位置是在C++定义传输到 其他立方体uniform上。做blinn和diffuse要用到。

 

灯光材质:

// LightShader.vert
#version 450 core
layout ( location = 0 ) in vec4 vPosition; // c++ pos
uniform mat4 model;
uniform mat4 view;
uniform mat4 projection;
void main(){
    gl_Position = projection *   view * model * vPosition;
}

//---------------------------------------------------------

// LightShader.frag
#version 450 core
out vec4 FragColor;
void main()
{
    FragColor = vec4(1.0); // set alle 4 vector values to 1.0
}

物体表面材质:

SurfaceShader.vert: 注暂时没用到Light结构体的东西,因为感觉没啥用。原文章只是简单的乘运算。

#version 450 core
// INCOMING DATA
layout ( location = 0 ) in vec4 v_position; //  pos
layout ( location = 1 ) in vec3 v_normal;   //  norm
layout ( location = 2 ) in vec2 v_texCoord; //  st

// define out data
out vec2 f_TexCoord;
// normal at world matrix, we direct from C++ calcalation
out vec3 f_Normal;  // to world matrix : mat3( transpose(inverse(model)) ) * v_normal;
out vec3 f_Pos;

// INCOMING THE MATRIX FROM CLIENT to transform the gl point position
uniform mat4 model;
uniform mat4 view;
uniform mat4 projection;


void main(){
    // Transform the world matrix to view matrix
    gl_Position = projection *   view * model * v_position;

    f_Normal = mat3(transpose(inverse(model))) * v_normal;  // f_Normal at world matrix
    f_TexCoord = v_texCoord;          // out TexCoord
    f_Pos = vec3(model *v_position);  // out fragment position
}

SurfaceShader.frag:

#version 450 core
// Final Color To export
out vec4 FragColor;

// from vert shader
in vec3 f_Normal;
in vec2 f_TexCoord;
in vec3 f_Pos; // fragment position

struct Light {
    vec3 position;
    vec3 ambient;
    vec3 diffuse;
    vec3 specular;
};

struct Material{
    float Kd;        // diffuse mult
    float kS;        // specular mult
    float shininess; // phong pow(,shine)
    sampler2D diffuse_map;
    sampler2D specular_map;
    sampler2D emission_map;
};

uniform vec3 viewPos;
uniform Material material;
uniform Light light;

void main()
{
    vec3 diffuse_tex =  texture(material.diffuse_map, f_TexCoord).rgb;
    vec3 specular_tex =  texture(material.specular_map, f_TexCoord).rgb;
    vec3 emission_tex =  texture(material.emission_map, f_TexCoord).rgb;

    vec3 L = light.ambient * diffuse_tex; // Final rediance , first is ambient light


    vec3 nn = normalize(f_Normal);
    vec3 wi = normalize(light.position - f_Pos);
    vec3 wo = normalize(viewPos - f_Pos);

    // cal the diffuse
    float ndotwi = max(dot(nn,wi),0.0f);
    vec3 diffuse_brdf = material.Kd * diffuse_tex *  light.diffuse * ndotwi;
    L += diffuse_brdf;

    // cal the blinn specular
    vec3 h = normalize(wi + wo);
    float ndoth = max(dot(nn,h),0.0f);
    float blinn_brdf = pow(ndoth,material.shininess) * material.kS ;
    L+= specular_tex * blinn_brdf;

    // add emission
    //L += emission_tex;

    FragColor = vec4(L,1.0f);
}

 

以上的材质都是在世界空间,view空间运算材质参考原作者:

 

 

 

 

 

加入一个辅助类,加载贴图,参考原作者

#ifndef LOADTEXTURE_H
#define LOADTEXTURE_H
#include <GL/glew.h>

// IMP the stb image loader
#define STB_IMAGE_IMPLEMENTATION
#include <stb_image.h>
#include <iostream>
using namespace std;


class LoadTexture
{
public:
    LoadTexture()=default;
    LoadTexture(const char *fileName);
    void load(const char *fileName);
    virtual ~LoadTexture();
    inline GLuint getTextureID(){return textureID;}
    inline GLuint getImageFormat(){return format;}
    GLuint textureID;
    GLenum format;
};

void LoadTexture::load(const char *fileName)
{
    glGenTextures(1, &textureID);
    int width, height, nrComponents;
    unsigned char *data = stbi_load(fileName, &width, &height, &nrComponents, 0);
    if (data)
    {
        if (nrComponents == 1)
            format = GL_RED;
        else if (nrComponents == 3)
            format = GL_RGB;
        else if (nrComponents == 4)
            format = GL_RGBA;

        glBindTexture(GL_TEXTURE_2D, textureID);
        glTexImage2D(GL_TEXTURE_2D, 0, format, width, height, 0, format, GL_UNSIGNED_BYTE, data);
        glGenerateMipmap(GL_TEXTURE_2D);

        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR_MIPMAP_LINEAR);

        stbi_image_free(data);
    }
    else
    {
        std::cout << "Texture failed to load at path: " << fileName << std::endl;
        stbi_image_free(data);
    }

}

LoadTexture::LoadTexture(const char *fileName){
    load(fileName);
}
LoadTexture::~LoadTexture(){}


#endif // LOADTEXTURE_H
LoadTexture.h
#define GLEW_STATIC
// GLEW

#include <GL/glew.h>
#include <cstdlib>
#undef GLFW_DLL
// GLFW
#include <GLFW/glfw3.h>
#include <iostream>
#include "LoadShader.h"
#include "LoadTexture.h"
#include "GLFWCamera.h"
#include "FrameWindow.h"

#include <cmath>


#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>



const unsigned int SRC_WIDTH = 1400;
const unsigned int SRC_HEIGHT = 720;


static GLuint cubeVAO,VBO;
static GLuint lightVAO;  //VBO stays the same; the vertices are the same for the light object which is also a 3D cube


static LoadShader SurfaceShader;
static LoadShader LightShader;

static LoadTexture DiffuseMap;
static LoadTexture SpecularMap;
static LoadTexture EmissionMap;


void init();
void display();
void showFPS(GLFWwindow *);


void processInput(GLFWwindow *window);
void framebuffer_size_callback(GLFWwindow* window, int width, int height); // framezize
void mouse_callback(GLFWwindow* window, double xpos, double ypos); // Maya Alt+LeftMouse
void scroll_callback(GLFWwindow *window, double xoffset, double yoffset);


// camera
static GLFWCamera *camera;
static float lastX =  float(SRC_WIDTH) / 2.0f;
static float lastY =  float(SRC_HEIGHT) / 2.0f;
static bool firstMouse = true;
static bool firstMiddowMouse = true;
// timing
static float deltaTime = 0.0f;    // time between current frame and last frame
static float lastFrame = 0.0f;


// light define
static glm::vec3 lightPos(1.2f, 1.0f, 2.0f);


// texture file;
static LoadTexture diffuse_map;
static LoadTexture specular_map;
static LoadTexture emission_map;

// world space positions of our cubes
static  glm::vec3 cubePositions[] = {
        glm::vec3( 0.0f,  0.0f,  0.0f),
        glm::vec3( 2.0f,  5.0f, -15.0f),
        glm::vec3(-1.5f, -2.2f, -2.5f),
        glm::vec3(-3.8f, -2.0f, -12.3f),
        glm::vec3( 2.4f, -0.4f, -3.5f),
        glm::vec3(-1.7f,  3.0f, -7.5f),
        glm::vec3( 1.3f, -2.0f, -2.5f),
        glm::vec3( 1.5f,  2.0f, -2.5f),
        glm::vec3( 1.5f,  0.2f, -1.5f),
        glm::vec3(-1.3f,  1.0f, -1.5f)
};


void init(){
    camera = new GLFWCamera;
    camera->pos.z = 5.0f;
    float vertices[] = {
        // positions          // normals           // texture coords
        -0.5f, -0.5f, -0.5f,  0.0f,  0.0f, -1.0f,  0.0f,  0.0f,
         0.5f, -0.5f, -0.5f,  0.0f,  0.0f, -1.0f,  1.0f,  0.0f,
         0.5f,  0.5f, -0.5f,  0.0f,  0.0f, -1.0f,  1.0f,  1.0f,
         0.5f,  0.5f, -0.5f,  0.0f,  0.0f, -1.0f,  1.0f,  1.0f,
        -0.5f,  0.5f, -0.5f,  0.0f,  0.0f, -1.0f,  0.0f,  1.0f,
        -0.5f, -0.5f, -0.5f,  0.0f,  0.0f, -1.0f,  0.0f,  0.0f,

        -0.5f, -0.5f,  0.5f,  0.0f,  0.0f,  1.0f,  0.0f,  0.0f,
         0.5f, -0.5f,  0.5f,  0.0f,  0.0f,  1.0f,  1.0f,  0.0f,
         0.5f,  0.5f,  0.5f,  0.0f,  0.0f,  1.0f,  1.0f,  1.0f,
         0.5f,  0.5f,  0.5f,  0.0f,  0.0f,  1.0f,  1.0f,  1.0f,
        -0.5f,  0.5f,  0.5f,  0.0f,  0.0f,  1.0f,  0.0f,  1.0f,
        -0.5f, -0.5f,  0.5f,  0.0f,  0.0f,  1.0f,  0.0f,  0.0f,

        -0.5f,  0.5f,  0.5f, -1.0f,  0.0f,  0.0f,  1.0f,  0.0f,
        -0.5f,  0.5f, -0.5f, -1.0f,  0.0f,  0.0f,  1.0f,  1.0f,
        -0.5f, -0.5f, -0.5f, -1.0f,  0.0f,  0.0f,  0.0f,  1.0f,
        -0.5f, -0.5f, -0.5f, -1.0f,  0.0f,  0.0f,  0.0f,  1.0f,
        -0.5f, -0.5f,  0.5f, -1.0f,  0.0f,  0.0f,  0.0f,  0.0f,
        -0.5f,  0.5f,  0.5f, -1.0f,  0.0f,  0.0f,  1.0f,  0.0f,

         0.5f,  0.5f,  0.5f,  1.0f,  0.0f,  0.0f,  1.0f,  0.0f,
         0.5f,  0.5f, -0.5f,  1.0f,  0.0f,  0.0f,  1.0f,  1.0f,
         0.5f, -0.5f, -0.5f,  1.0f,  0.0f,  0.0f,  0.0f,  1.0f,
         0.5f, -0.5f, -0.5f,  1.0f,  0.0f,  0.0f,  0.0f,  1.0f,
         0.5f, -0.5f,  0.5f,  1.0f,  0.0f,  0.0f,  0.0f,  0.0f,
         0.5f,  0.5f,  0.5f,  1.0f,  0.0f,  0.0f,  1.0f,  0.0f,

        -0.5f, -0.5f, -0.5f,  0.0f, -1.0f,  0.0f,  0.0f,  1.0f,
         0.5f, -0.5f, -0.5f,  0.0f, -1.0f,  0.0f,  1.0f,  1.0f,
         0.5f, -0.5f,  0.5f,  0.0f, -1.0f,  0.0f,  1.0f,  0.0f,
         0.5f, -0.5f,  0.5f,  0.0f, -1.0f,  0.0f,  1.0f,  0.0f,
        -0.5f, -0.5f,  0.5f,  0.0f, -1.0f,  0.0f,  0.0f,  0.0f,
        -0.5f, -0.5f, -0.5f,  0.0f, -1.0f,  0.0f,  0.0f,  1.0f,

        -0.5f,  0.5f, -0.5f,  0.0f,  1.0f,  0.0f,  0.0f,  1.0f,
         0.5f,  0.5f, -0.5f,  0.0f,  1.0f,  0.0f,  1.0f,  1.0f,
         0.5f,  0.5f,  0.5f,  0.0f,  1.0f,  0.0f,  1.0f,  0.0f,
         0.5f,  0.5f,  0.5f,  0.0f,  1.0f,  0.0f,  1.0f,  0.0f,
        -0.5f,  0.5f,  0.5f,  0.0f,  1.0f,  0.0f,  0.0f,  0.0f,
        -0.5f,  0.5f, -0.5f,  0.0f,  1.0f,  0.0f,  0.0f,  1.0f
    };
    // GL depth zbuffer
    glEnable(GL_DEPTH_TEST);


    SurfaceShader.load("shaders/SurfaceShader.vert","shaders/SurfaceShader.frag");
    LightShader.load("shaders/LightShader.vert", "shaders/LightShader.frag");
    // ----------------- CREATE Cube VAO VBO -----------------
    glCreateVertexArrays(1, &cubeVAO);
    glCreateBuffers(1, &VBO);
    glBindVertexArray(cubeVAO);

    glBindBuffer(GL_ARRAY_BUFFER,VBO);
    //glNamedBufferStorage(VBO,sizeof(verticels), verticels, 0);
    glBufferData(GL_ARRAY_BUFFER,sizeof(vertices), vertices, GL_STATIC_DRAW);

    // VERTEX POINTS ATTRIBUTES
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(float),  (void*)0); // POS at location 0
    glEnableVertexAttribArray(0);
    glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(float),  (void*)(3 * sizeof(float))); // NORMAL at location 1
    glEnableVertexAttribArray(1);
    glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 8 * sizeof(float),  (void*)(6 * sizeof(float))); // uv coords at location 2
    glEnableVertexAttribArray(2);
    // ----------------- CREATE Cube VAO VBO -----------------



    // ------------------ Create Light VAO VBO------------------------
    glCreateVertexArrays(1,&lightVAO);
    glBindVertexArray(lightVAO);
    // !important:we only need to bind to the VBO (to link it with glVertexAttribPointer), no need to fill it;
    // the VBO's data already contains all we need (it's already bound, but we do it again for educational purposes)
    glBindBuffer(GL_ARRAY_BUFFER,VBO);
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(float),  (void*)0); // POS at location 0
    glEnableVertexAttribArray(0);
     // ------------------ Create Light VAO VBO------------------------



    // -------------------- Texture Loading ----------------------------
    diffuse_map.load("texture/diffuse.png");
    specular_map.load("texture/specular.png");
    emission_map.load("texture/emission.jpg");
    // send texture to uniform , remeber to set GL_TEXTURE Unit in renderer
    SurfaceShader.use();
    SurfaceShader.setInt("material.diffuse_map", 0);
    SurfaceShader.setInt("material.specular_map", 1);
    SurfaceShader.setInt("material.emission_map", 2);
    // -------------------- Texture Loading ----------------------------
}

// ----------- Render Loop ----------
void display(){
    // per-frame time logic
            // --------------------
    float currentFrame = glfwGetTime();
    deltaTime = currentFrame - lastFrame;
    lastFrame = currentFrame;


    glClearColor(0.2f, 0.3f, 0.3f, 1.0f);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);


    // update light position can see how much effective on object
    lightPos.x = sin(glfwGetTime()) * 2.3f;
    //lightPos.y = sin(glfwGetTime()) * 2.3f;
    lightPos.z = cos(glfwGetTime()) * 2.3f;

    // ------------------------------------ OBJECT RENDERING SETTINGS --------------------------------------------------
    // object fragment settings
    // object surface,first active texture to renderer
    SurfaceShader.use();
    glActiveTexture(GL_TEXTURE0);
    glBindTexture(GL_TEXTURE_2D,diffuse_map.getTextureID());
    glActiveTexture(GL_TEXTURE1);
    glBindTexture(GL_TEXTURE_2D,specular_map.getTextureID());
    glActiveTexture(GL_TEXTURE2);
    glBindTexture(GL_TEXTURE_2D,emission_map.getTextureID());

    SurfaceShader.setVec3("viewPos",camera->pos);
    SurfaceShader.setFloat("material.Kd",1.0f); // diffuse strength
    SurfaceShader.setFloat("material.kS",1.0f); // diffuse strength
    SurfaceShader.setFloat("material.shininess",65.0f);   // specular pow
    SurfaceShader.setVec3("light.position", lightPos);  // send light position to fragment shader
    SurfaceShader.setVec3("light.ambient", 0.2f, 0.2f, 0.2f);
    SurfaceShader.setVec3("light.diffuse", 0.5f, 0.5f, 0.5f);
    SurfaceShader.setVec3("light.specular", 1.0f, 1.0f, 1.0f);

    // object .vert settings
    glm::mat4 projection = glm::perspective(glm::radians(camera->fov),float(SRC_WIDTH) / float(SRC_HEIGHT),0.1f,  1000.0f);
    glm::mat4 view = camera->GetViewMatrix();
    SurfaceShader.setMat4("projection", projection);
    SurfaceShader.setMat4("view", view);

    // object world transformation
    glm::mat4 model = glm::mat4(1.0f);

    for (int i=0; i<10 ;i++){
        model = glm::translate(model,cubePositions[i]);
        SurfaceShader.setMat4("model", model);
        // render the cube
        glBindVertexArray(cubeVAO);
        glDrawArrays(GL_TRIANGLES, 0, 36);
        model = glm::mat4(1.0f);
    }


    // ------------------------------------ OBJECT RENDERING SETTINGS --------------------------------------------------






    // ------------------------------------ LIGHT RENDERING SETTINGS --------------------------------------------------
    LightShader.use();
    LightShader.setMat4("projection", projection);
    LightShader.setMat4("view", view);
    model = glm::mat4(1.0f);
    model = glm::translate(model, lightPos);
    model = glm::scale(model, glm::vec3(0.2f)); // a smaller cube
    LightShader.setMat4("model", model);
    // render the cube
    glBindVertexArray(lightVAO);
    glDrawArrays(GL_TRIANGLES, 0, 36);

}


int main()
{
    glfwInit();
    FrameWindow FrameWindow(SRC_WIDTH,SRC_HEIGHT);
    glfwSetFramebufferSizeCallback(FrameWindow.getWindow(), framebuffer_size_callback);
    glfwSetCursorPosCallback(FrameWindow.getWindow(),mouse_callback);
    glfwSetScrollCallback(FrameWindow.getWindow(), scroll_callback);
    init();
    // RENDER--------------
    while(!glfwWindowShouldClose(FrameWindow.getWindow())){
        processInput(FrameWindow.getWindow());
        display();
        glfwSwapBuffers(FrameWindow.getWindow());
        glfwPollEvents();
    }
    delete camera;
    return 0;
}

void framebuffer_size_callback(GLFWwindow* window, int width, int height)
{
    // make sure the viewport matches the new window dimensions; note that width and
    // height will be significantly larger than specified on retina displays.
    glViewport(0, 0, width, height);
}

void processInput(GLFWwindow *window)
{
    if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS)
        glfwSetWindowShouldClose(window, true);
    if (glfwGetKey(window, GLFW_KEY_W) == GLFW_PRESS)
        camera->processKeyboardMove(deltaTime,GLFWCamera::FORWARD);
    if (glfwGetKey(window, GLFW_KEY_S) == GLFW_PRESS)
        camera->processKeyboardMove(deltaTime,GLFWCamera::BACKWARD);
    if (glfwGetKey(window, GLFW_KEY_A) == GLFW_PRESS)
        camera->processKeyboardMove(deltaTime,GLFWCamera::LEFT);
    if (glfwGetKey(window, GLFW_KEY_D) == GLFW_PRESS)
        camera->processKeyboardMove(deltaTime,GLFWCamera::RIGHT);
}

// ROTATE VIEW DIR
void mouse_callback(GLFWwindow* window, double xpos, double ypos){

    int middow_mouse_state = glfwGetMouseButton(window,GLFW_MOUSE_BUTTON_MIDDLE);
    int mouse_state = glfwGetMouseButton(window,GLFW_MOUSE_BUTTON_LEFT);
    int key_state = glfwGetKey(window,GLFW_KEY_LEFT_ALT);
    // set up the camera view
    if( mouse_state == GLFW_PRESS && key_state== GLFW_PRESS)
    {
        if (firstMouse){
            lastX = xpos;
            lastY = ypos;
            firstMouse = false;
        }
        float xoffset = xpos - lastX;
        float yoffset = lastY - ypos; // reversed since y-coordinates go from bottom to top
        lastX = xpos;
        lastY = ypos;
        camera->processMouseMove(xoffset,yoffset);
    }
    if (key_state == GLFW_RELEASE || mouse_state == GLFW_RELEASE){
        firstMouse = true;
    }


    // Move Camera Position
    if( middow_mouse_state == GLFW_PRESS) {

        if (firstMiddowMouse){
            lastX = xpos;
            lastY = ypos;
            firstMiddowMouse = false;
        }
        float xoffset = xpos - lastX;
        float yoffset = lastY - ypos; // reversed since y-coordinates go from bottom to top
        lastX = xpos;
        lastY = ypos;
        camera->pos.x += xoffset*0.01f;
        camera->pos.y += yoffset*0.01f;

    }
    if ( middow_mouse_state == GLFW_RELEASE){
        firstMiddowMouse = true;
    }

}

void scroll_callback(GLFWwindow *window, double xoffset, double yoffset){
    camera->processFov(yoffset);
}
main.cpp

 

CP15:

Point光源衰减:

SurfaceShader.frag

#version 450 core
// Final Color To export
out vec4 FragColor;

// from vert shader
in vec3 f_Normal;
in vec2 f_TexCoord;
in vec3 f_Pos; // fragment position

struct Light {
    vec3 position;
    vec3 ambient;
    vec3 diffuse;
    vec3 specular;
};

struct Material{
    float Kd;        // diffuse mult
    float kS;        // specular mult
    float shininess; // phong pow(,shine)
    sampler2D diffuse_map;
    sampler2D specular_map;
    sampler2D emission_map;
};

uniform vec3 viewPos;
uniform Material material;
uniform Light light;

void main()
{
    vec3 diffuse_tex =  texture(material.diffuse_map, f_TexCoord).rgb;
    vec3 specular_tex =  texture(material.specular_map, f_TexCoord).rgb;
    vec3 emission_tex =  texture(material.emission_map, f_TexCoord).rgb;

    vec3 L = light.ambient * diffuse_tex; // Final rediance , first is ambient light


    vec3 nn = normalize(f_Normal);
    vec3 wi = normalize(light.position - f_Pos);
    vec3 wo = normalize(viewPos - f_Pos);

    // cal the diffuse
    float ndotwi = max(dot(nn,wi),0.0f);
    vec3 diffuse_brdf = material.Kd * diffuse_tex *  light.diffuse * ndotwi;
    diffuse_brdf *= light.diffuse;

    // cal the blinn specular
    vec3 h = normalize(wi + wo);
    float ndoth = max(dot(nn,h),0.0f);
    float blinn_brdf = pow(ndoth,material.shininess) * material.kS ;
    vec3 specular = specular_tex * blinn_brdf;
    specular *= light.specular;
    // add emission;
    //L += emission_tex;


    // cal the distance attenuation;
    float d = distance(light.position, f_Pos);
    float attuen = 1.0f / (1.0f + 0.09f* d + 0.032f * d* d);

    diffuse_brdf *= attuen;
    specular *= attuen;
    L += diffuse_brdf;
    L += specular;

    FragColor = vec4(L,1.0f);
}

 

 

 main.cpp:修改ambient灯光的贡献为0,主要看点光源的贡献。

#define GLEW_STATIC
// GLEW

#include <GL/glew.h>
#include <cstdlib>
#undef GLFW_DLL
// GLFW
#include <GLFW/glfw3.h>
#include <iostream>
#include "LoadShader.h"
#include "LoadTexture.h"
#include "GLFWCamera.h"
#include "FrameWindow.h"

#include <cmath>


#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>



const unsigned int SRC_WIDTH = 1400;
const unsigned int SRC_HEIGHT = 720;


static GLuint cubeVAO,VBO;
static GLuint lightVAO;  //VBO stays the same; the vertices are the same for the light object which is also a 3D cube


static LoadShader SurfaceShader;
static LoadShader LightShader;

static LoadTexture DiffuseMap;
static LoadTexture SpecularMap;
static LoadTexture EmissionMap;


void init();
void display();
void showFPS(GLFWwindow *);


void processInput(GLFWwindow *window);
void framebuffer_size_callback(GLFWwindow* window, int width, int height); // framezize
void mouse_callback(GLFWwindow* window, double xpos, double ypos); // Maya Alt+LeftMouse
void scroll_callback(GLFWwindow *window, double xoffset, double yoffset);


// camera
static GLFWCamera *camera;
static float lastX =  float(SRC_WIDTH) / 2.0f;
static float lastY =  float(SRC_HEIGHT) / 2.0f;
static bool firstMouse = true;
static bool firstMiddowMouse = true;
// timing
static float deltaTime = 0.0f;    // time between current frame and last frame
static float lastFrame = 0.0f;


// light define
static glm::vec3 lightPos(1.2f, 1.0f, 2.0f);


// texture file;
static LoadTexture diffuse_map;
static LoadTexture specular_map;
static LoadTexture emission_map;

// world space positions of our cubes
static  glm::vec3 cubePositions[] = {
        glm::vec3( 0.0f,  0.0f,  0.0f),
        glm::vec3( 2.0f,  5.0f, -15.0f),
        glm::vec3(-1.5f, -2.2f, -2.5f),
        glm::vec3(-3.8f, -2.0f, -12.3f),
        glm::vec3( 2.4f, -0.4f, -3.5f),
        glm::vec3(-1.7f,  3.0f, -7.5f),
        glm::vec3( 1.3f, -2.0f, -2.5f),
        glm::vec3( 1.5f,  2.0f, -2.5f),
        glm::vec3( 1.5f,  0.2f, -1.5f),
        glm::vec3(-1.3f,  1.0f, -1.5f)
};


void init(){
    camera = new GLFWCamera;
    camera->pos.z = 5.0f;
    float vertices[] = {
        // positions          // normals           // texture coords
        -0.5f, -0.5f, -0.5f,  0.0f,  0.0f, -1.0f,  0.0f,  0.0f,
         0.5f, -0.5f, -0.5f,  0.0f,  0.0f, -1.0f,  1.0f,  0.0f,
         0.5f,  0.5f, -0.5f,  0.0f,  0.0f, -1.0f,  1.0f,  1.0f,
         0.5f,  0.5f, -0.5f,  0.0f,  0.0f, -1.0f,  1.0f,  1.0f,
        -0.5f,  0.5f, -0.5f,  0.0f,  0.0f, -1.0f,  0.0f,  1.0f,
        -0.5f, -0.5f, -0.5f,  0.0f,  0.0f, -1.0f,  0.0f,  0.0f,

        -0.5f, -0.5f,  0.5f,  0.0f,  0.0f,  1.0f,  0.0f,  0.0f,
         0.5f, -0.5f,  0.5f,  0.0f,  0.0f,  1.0f,  1.0f,  0.0f,
         0.5f,  0.5f,  0.5f,  0.0f,  0.0f,  1.0f,  1.0f,  1.0f,
         0.5f,  0.5f,  0.5f,  0.0f,  0.0f,  1.0f,  1.0f,  1.0f,
        -0.5f,  0.5f,  0.5f,  0.0f,  0.0f,  1.0f,  0.0f,  1.0f,
        -0.5f, -0.5f,  0.5f,  0.0f,  0.0f,  1.0f,  0.0f,  0.0f,

        -0.5f,  0.5f,  0.5f, -1.0f,  0.0f,  0.0f,  1.0f,  0.0f,
        -0.5f,  0.5f, -0.5f, -1.0f,  0.0f,  0.0f,  1.0f,  1.0f,
        -0.5f, -0.5f, -0.5f, -1.0f,  0.0f,  0.0f,  0.0f,  1.0f,
        -0.5f, -0.5f, -0.5f, -1.0f,  0.0f,  0.0f,  0.0f,  1.0f,
        -0.5f, -0.5f,  0.5f, -1.0f,  0.0f,  0.0f,  0.0f,  0.0f,
        -0.5f,  0.5f,  0.5f, -1.0f,  0.0f,  0.0f,  1.0f,  0.0f,

         0.5f,  0.5f,  0.5f,  1.0f,  0.0f,  0.0f,  1.0f,  0.0f,
         0.5f,  0.5f, -0.5f,  1.0f,  0.0f,  0.0f,  1.0f,  1.0f,
         0.5f, -0.5f, -0.5f,  1.0f,  0.0f,  0.0f,  0.0f,  1.0f,
         0.5f, -0.5f, -0.5f,  1.0f,  0.0f,  0.0f,  0.0f,  1.0f,
         0.5f, -0.5f,  0.5f,  1.0f,  0.0f,  0.0f,  0.0f,  0.0f,
         0.5f,  0.5f,  0.5f,  1.0f,  0.0f,  0.0f,  1.0f,  0.0f,

        -0.5f, -0.5f, -0.5f,  0.0f, -1.0f,  0.0f,  0.0f,  1.0f,
         0.5f, -0.5f, -0.5f,  0.0f, -1.0f,  0.0f,  1.0f,  1.0f,
         0.5f, -0.5f,  0.5f,  0.0f, -1.0f,  0.0f,  1.0f,  0.0f,
         0.5f, -0.5f,  0.5f,  0.0f, -1.0f,  0.0f,  1.0f,  0.0f,
        -0.5f, -0.5f,  0.5f,  0.0f, -1.0f,  0.0f,  0.0f,  0.0f,
        -0.5f, -0.5f, -0.5f,  0.0f, -1.0f,  0.0f,  0.0f,  1.0f,

        -0.5f,  0.5f, -0.5f,  0.0f,  1.0f,  0.0f,  0.0f,  1.0f,
         0.5f,  0.5f, -0.5f,  0.0f,  1.0f,  0.0f,  1.0f,  1.0f,
         0.5f,  0.5f,  0.5f,  0.0f,  1.0f,  0.0f,  1.0f,  0.0f,
         0.5f,  0.5f,  0.5f,  0.0f,  1.0f,  0.0f,  1.0f,  0.0f,
        -0.5f,  0.5f,  0.5f,  0.0f,  1.0f,  0.0f,  0.0f,  0.0f,
        -0.5f,  0.5f, -0.5f,  0.0f,  1.0f,  0.0f,  0.0f,  1.0f
    };
    // GL depth zbuffer
    glEnable(GL_DEPTH_TEST);


    SurfaceShader.load("shaders/SurfaceShader.vert","shaders/SurfaceShader.frag");
    LightShader.load("shaders/LightShader.vert", "shaders/LightShader.frag");
    // ----------------- CREATE Cube VAO VBO -----------------
    glCreateVertexArrays(1, &cubeVAO);
    glCreateBuffers(1, &VBO);
    glBindVertexArray(cubeVAO);

    glBindBuffer(GL_ARRAY_BUFFER,VBO);
    //glNamedBufferStorage(VBO,sizeof(verticels), verticels, 0);
    glBufferData(GL_ARRAY_BUFFER,sizeof(vertices), vertices, GL_STATIC_DRAW);

    // VERTEX POINTS ATTRIBUTES
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(float),  (void*)0); // POS at location 0
    glEnableVertexAttribArray(0);
    glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(float),  (void*)(3 * sizeof(float))); // NORMAL at location 1
    glEnableVertexAttribArray(1);
    glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 8 * sizeof(float),  (void*)(6 * sizeof(float))); // uv coords at location 2
    glEnableVertexAttribArray(2);
    // ----------------- CREATE Cube VAO VBO -----------------



    // ------------------ Create Light VAO VBO------------------------
    glCreateVertexArrays(1,&lightVAO);
    glBindVertexArray(lightVAO);
    // !important:we only need to bind to the VBO (to link it with glVertexAttribPointer), no need to fill it;
    // the VBO's data already contains all we need (it's already bound, but we do it again for educational purposes)
    glBindBuffer(GL_ARRAY_BUFFER,VBO);
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(float),  (void*)0); // POS at location 0
    glEnableVertexAttribArray(0);
     // ------------------ Create Light VAO VBO------------------------



    // -------------------- Texture Loading ----------------------------
    diffuse_map.load("texture/diffuse.png");
    specular_map.load("texture/specular.png");
    emission_map.load("texture/emission.jpg");
    // send texture to uniform , remeber to set GL_TEXTURE Unit in renderer
    SurfaceShader.use();
    SurfaceShader.setInt("material.diffuse_map", 0);
    SurfaceShader.setInt("material.specular_map", 1);
    SurfaceShader.setInt("material.emission_map", 2);
    // -------------------- Texture Loading ----------------------------
}

// ----------- Render Loop ----------
void display(){
    // per-frame time logic
            // --------------------
    float currentFrame = glfwGetTime();
    deltaTime = currentFrame - lastFrame;
    lastFrame = currentFrame;


    glClearColor(0.2f, 0.3f, 0.3f, 1.0f);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);


    // update light position can see how much effective on object
    lightPos.x = sin(glfwGetTime()) * 2.3f;
    //lightPos.y = sin(glfwGetTime()) * 2.3f;
    lightPos.z = cos(glfwGetTime()) * 2.3f;

    // ------------------------------------ OBJECT RENDERING SETTINGS --------------------------------------------------
    // object fragment settings
    // object surface,first active texture to renderer
    SurfaceShader.use();
    glActiveTexture(GL_TEXTURE0);
    glBindTexture(GL_TEXTURE_2D,diffuse_map.getTextureID());
    glActiveTexture(GL_TEXTURE1);
    glBindTexture(GL_TEXTURE_2D,specular_map.getTextureID());
    glActiveTexture(GL_TEXTURE2);
    glBindTexture(GL_TEXTURE_2D,emission_map.getTextureID());

    SurfaceShader.setVec3("viewPos",camera->pos);
    SurfaceShader.setFloat("material.Kd",1.0f); // diffuse strength
    SurfaceShader.setFloat("material.kS",1.0f); // diffuse strength
    SurfaceShader.setFloat("material.shininess",65.0f);   // specular pow
    SurfaceShader.setVec3("light.position", lightPos);  // send light position to fragment shader
    SurfaceShader.setVec3("light.ambient", 0.0f, 0.0f, 0.0f);
    SurfaceShader.setVec3("light.diffuse", 1.0f, 1.00f, 1.0f);
    SurfaceShader.setVec3("light.specular", 1.0f, 1.0f, 1.0f);

    // object .vert settings
    glm::mat4 projection = glm::perspective(glm::radians(camera->fov),float(SRC_WIDTH) / float(SRC_HEIGHT),0.1f,  1000.0f);
    glm::mat4 view = camera->GetViewMatrix();
    SurfaceShader.setMat4("projection", projection);
    SurfaceShader.setMat4("view", view);

    // object world transformation
    glm::mat4 model = glm::mat4(1.0f);

    for (int i=0; i<10 ;i++){
        model = glm::translate(model,cubePositions[i]);
        glm::mat4 rotMatrix = glm::mat4(1.0f);
        float angle = 20.0f * i + glfwGetTime()*50;
        rotMatrix = glm::rotate(rotMatrix, glm::radians(angle), glm::vec3(1.0f, 0.3f, 0.5f));
        model *= rotMatrix;
        SurfaceShader.setMat4("model", model);

        // render the cube
        glBindVertexArray(cubeVAO);
        glDrawArrays(GL_TRIANGLES, 0, 36);
        model = glm::mat4(1.0f);
    }


    // ------------------------------------ OBJECT RENDERING SETTINGS --------------------------------------------------






    // ------------------------------------ LIGHT RENDERING SETTINGS --------------------------------------------------
    LightShader.use();
    LightShader.setMat4("projection", projection);
    LightShader.setMat4("view", view);
    model = glm::mat4(1.0f);
    model = glm::translate(model, lightPos);
    model = glm::scale(model, glm::vec3(0.2f)); // a smaller cube
    LightShader.setMat4("model", model);
    // render the cube
    glBindVertexArray(lightVAO);
    glDrawArrays(GL_TRIANGLES, 0, 36);

}


int main()
{
    glfwInit();
    FrameWindow FrameWindow(SRC_WIDTH,SRC_HEIGHT);
    glfwSetFramebufferSizeCallback(FrameWindow.getWindow(), framebuffer_size_callback);
    glfwSetCursorPosCallback(FrameWindow.getWindow(),mouse_callback);
    glfwSetScrollCallback(FrameWindow.getWindow(), scroll_callback);
    init();
    // RENDER--------------
    while(!glfwWindowShouldClose(FrameWindow.getWindow())){
        processInput(FrameWindow.getWindow());
        display();
        glfwSwapBuffers(FrameWindow.getWindow());
        glfwPollEvents();
    }
    delete camera;
    return 0;
}

void framebuffer_size_callback(GLFWwindow* window, int width, int height)
{
    // make sure the viewport matches the new window dimensions; note that width and
    // height will be significantly larger than specified on retina displays.
    glViewport(0, 0, width, height);
}

void processInput(GLFWwindow *window)
{
    if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS)
        glfwSetWindowShouldClose(window, true);
    if (glfwGetKey(window, GLFW_KEY_W) == GLFW_PRESS)
        camera->processKeyboardMove(deltaTime,GLFWCamera::FORWARD);
    if (glfwGetKey(window, GLFW_KEY_S) == GLFW_PRESS)
        camera->processKeyboardMove(deltaTime,GLFWCamera::BACKWARD);
    if (glfwGetKey(window, GLFW_KEY_A) == GLFW_PRESS)
        camera->processKeyboardMove(deltaTime,GLFWCamera::LEFT);
    if (glfwGetKey(window, GLFW_KEY_D) == GLFW_PRESS)
        camera->processKeyboardMove(deltaTime,GLFWCamera::RIGHT);
}

// ROTATE VIEW DIR
void mouse_callback(GLFWwindow* window, double xpos, double ypos){

    int middow_mouse_state = glfwGetMouseButton(window,GLFW_MOUSE_BUTTON_MIDDLE);
    int mouse_state = glfwGetMouseButton(window,GLFW_MOUSE_BUTTON_LEFT);
    int key_state = glfwGetKey(window,GLFW_KEY_LEFT_ALT);
    // set up the camera view
    if( mouse_state == GLFW_PRESS && key_state== GLFW_PRESS)
    {
        if (firstMouse){
            lastX = xpos;
            lastY = ypos;
            firstMouse = false;
        }
        float xoffset = xpos - lastX;
        float yoffset = lastY - ypos; // reversed since y-coordinates go from bottom to top
        lastX = xpos;
        lastY = ypos;
        camera->processMouseMove(xoffset,yoffset);
    }
    if (key_state == GLFW_RELEASE || mouse_state == GLFW_RELEASE){
        firstMouse = true;
    }


    // Move Camera Position
    if( middow_mouse_state == GLFW_PRESS) {

        if (firstMiddowMouse){
            lastX = xpos;
            lastY = ypos;
            firstMiddowMouse = false;
        }
        float xoffset = xpos - lastX;
        float yoffset = lastY - ypos; // reversed since y-coordinates go from bottom to top
        lastX = xpos;
        lastY = ypos;
        camera->pos.x += xoffset*0.01f;
        camera->pos.y += yoffset*0.01f;

    }
    if ( middow_mouse_state == GLFW_RELEASE){
        firstMiddowMouse = true;
    }

}

void scroll_callback(GLFWwindow *window, double xoffset, double yoffset){
    camera->processFov(yoffset);
}
View Code

 

CP16:

聚光灯

 

#version 450 core
// Final Color To export
out vec4 FragColor;

// from vert shader
in vec3 f_Normal;
in vec2 f_TexCoord;
in vec3 f_Pos; // fragment position

// current light is spot light
struct Light {
    vec3 spotDir;
    float cutOff;       //phi
    float outerCutOff;  //gamma
    vec3 position;
    vec3 ambient;
    vec3 diffuse;
    vec3 specular;
};

struct Material{
    float Kd;        // diffuse mult
    float kS;        // specular mult
    float shininess; // phong pow(,shine)
    sampler2D diffuse_map;
    sampler2D specular_map;
    sampler2D emission_map;
};

uniform vec3 viewPos;
uniform Material material;
uniform Light light;

void main()
{
    vec3 L = vec3(0.0f);
    vec3 diffuse_tex =  texture(material.diffuse_map, f_TexCoord).rgb;
    vec3 specular_tex =  texture(material.specular_map, f_TexCoord).rgb;
    vec3 emission_tex =  texture(material.emission_map, f_TexCoord).rgb;

    vec3 ambient = light.ambient * diffuse_tex; // Final rediance , first is ambient light


    vec3 nn = normalize(f_Normal);
    vec3 wi = normalize(light.position - f_Pos);
    vec3 wo = normalize(viewPos - f_Pos);

    // cal the diffuse
    float ndotwi = max(dot(nn,wi),0.0f);
    vec3 diffuse_brdf = material.Kd * diffuse_tex *  light.diffuse * ndotwi;
    diffuse_brdf *= light.diffuse;

    // cal the blinn specular
    vec3 h = normalize(wi + wo);
    float ndoth = max(dot(nn,h),0.0f);
    float blinn_brdf = pow(ndoth,material.shininess) * material.kS ;
    vec3 specular = specular_tex * blinn_brdf;
    specular *= light.specular;

    // add emission;
    //L += emission_tex;

    // cal the distance attenuation;
    float d = distance(light.position, f_Pos);
    float attuen = 1.0f / (1.0f + 0.09f* d + 0.032f * d* d);

    // cal spotlight
    float theta = dot(normalize(-light.spotDir),wi);
    float eps = light.cutOff - light.outerCutOff;
    float intensity = clamp((theta - light.outerCutOff) / eps, 0.0f,1.0f );


    // spot light E
    diffuse_brdf *= intensity*5;
    specular *= intensity*5;

    ambient *= attuen;
    diffuse_brdf *= attuen;
    specular *= attuen;
    L += diffuse_brdf;
    L += specular;

    FragColor = vec4(L,1.0f);
}
SurfaceShader.frag

把灯光设置了一个合理的位置:

// light define
static glm::vec3 lightPos(0.0f, 4.0f,-2.0f);

 

main.cpp主要设置材质中聚光灯方向,还有cut off的量,还有外部的cutoff量

SurfaceShader.setVec3("viewPos",camera->pos);
SurfaceShader.setFloat("material.Kd",1.0f); // diffuse strength
SurfaceShader.setFloat("material.kS",1.0f); // diffuse strength
SurfaceShader.setFloat("material.shininess",65.0f);   // specular pow
SurfaceShader.setVec3("light.position", lightPos);  // send light position to fragment shader
SurfaceShader.setVec3("light.spotDir",-0.0f,-1.0f, 0.0f);
SurfaceShader.setFloat("light.cutOff", glm::cos(glm::radians(10.5f)));
SurfaceShader.setFloat("light.outerCutOff", glm::cos(glm::radians(20.5f)));
SurfaceShader.setVec3("light.ambient", 0.0f, 0.0f, 0.0f);
SurfaceShader.setVec3("light.diffuse", 1.0f, 1.00f, 1.0f);
SurfaceShader.setVec3(
"light.specular", 1.0f, 1.0f, 1.0f);

 

Assimp dump obj infos:

#include <iostream>
#include <assimp/Importer.hpp>
#include <assimp/scene.h>
#include <assimp/postprocess.h>
#include <string>
using namespace std;

void processNode(aiNode * node, const aiScene* scene);
int main(){
    Assimp::Importer import;
    string path = "model/nanosuit.obj";
    const aiScene * scene = import.ReadFile(path, aiProcess_Triangulate | aiProcess_FlipUVs);
    if(!scene || scene->mFlags & AI_SCENE_FLAGS_INCOMPLETE || !scene->mRootNode)
    {
        cout << "ERROR::ASSIMP::" << import.GetErrorString() << endl;

    }

    string directory = path.substr(0, path.find_last_of('/'));
    cout << directory << endl;

    // Get Root Node
    aiNode * node = scene->mRootNode;
    cout <<"ROOT NODE:  " <<node->mName.C_Str() << endl;

    processNode(node,scene);





    return 0;
}

void processNode(aiNode * node, const aiScene* scene){
    cout << "LOOP At Node->" << node->mName.C_Str() << endl;
    for(unsigned int i = 0; i < node->mNumMeshes; i++)
    {
        aiMesh *mesh = scene->mMeshes[node->mMeshes[i]];
        // mesh points
        cout <<"Num points:" <<mesh->mNumVertices<< endl;

        // Dump materials infos
        aiMaterial *mat = scene->mMaterials[mesh->mMaterialIndex];
        cout << "Get Mesh Name: "<<mesh->mName.C_Str()<< " <->  MaterialName: " << mat->GetName().C_Str()  << endl;
        cout << "{\n";
        for(unsigned int i = 0; i < mat->GetTextureCount(aiTextureType_DIFFUSE); i++)
        {
            aiString str;
            mat->GetTexture(aiTextureType_DIFFUSE, i, &str);
            cout << "\tdiffuseTexture: "<<str.C_Str() << endl;
        }
        for(unsigned int i = 0; i < mat->GetTextureCount(aiTextureType_NORMALS); i++)
        {
            aiString str;
            mat->GetTexture(aiTextureType_NORMALS, i, &str);
            cout << "\tNormalTexture: "<<str.C_Str() << endl;
        }
        for(unsigned int i = 0; i < mat->GetTextureCount(aiTextureType_AMBIENT); i++)
        {
            aiString str;
            mat->GetTexture(aiTextureType_AMBIENT, i, &str);
            cout << "\tAmbientTexture: "<<str.C_Str() << endl;
        }
        for(unsigned int i = 0; i < mat->GetTextureCount(aiTextureType_OPACITY); i++)
        {
            aiString str;
            mat->GetTexture(aiTextureType_OPACITY, i, &str);
            cout << "\tOpacityTexture: "<<str.C_Str() << endl;
        }
        for(unsigned int i = 0; i < mat->GetTextureCount(aiTextureType_SPECULAR); i++)
        {
            aiString str;
            mat->GetTexture(aiTextureType_SPECULAR, i, &str);
            cout << "\tSpecularTexture: "<<str.C_Str() << endl;
        }
        for(unsigned int i = 0; i < mat->GetTextureCount(aiTextureType_HEIGHT); i++)
        {
            aiString str;
            mat->GetTexture(aiTextureType_HEIGHT, i, &str);
            cout << "\tHeightTexture: "<<str.C_Str() << endl;
        }
        for(unsigned int i = 0; i < mat->GetTextureCount(aiTextureType_UNKNOWN); i++)
        {
            aiString str;
            mat->GetTexture(aiTextureType_HEIGHT, i, &str);
            cout << "\tUnkownTexture: "<<str.C_Str() << endl;
        }
        cout << "}\n";

    }

    for(unsigned int i = 0; i < node->mNumChildren; i++)
    {
        processNode(node->mChildren[i], scene);
    }
}

DUMPINFOS:

model
ROOT NODE:  nanosuit.obj
LOOP At Node->nanosuit.obj
LOOP At Node->Visor
Num points:156
Get Mesh Name: Visor <->  MaterialName: Glass
{
    diffuseTexture: glass_dif.png
    HeightTexture: glass_ddn.png
}
LOOP At Node->Legs
Num points:15222
Get Mesh Name: Legs <->  MaterialName: Leg
{
    diffuseTexture: leg_dif.png
    SpecularTexture: leg_showroom_spec.png
    HeightTexture: leg_showroom_ddn.png
}
LOOP At Node->hands
Num points:19350
Get Mesh Name: hands <->  MaterialName: Hand
{
    diffuseTexture: hand_dif.png
    SpecularTexture: hand_showroom_spec.png
    HeightTexture: hand_showroom_ddn.png
}
LOOP At Node->Lights
Num points:78
Get Mesh Name: Lights <->  MaterialName: Glass
{
    diffuseTexture: glass_dif.png
    HeightTexture: glass_ddn.png
}
LOOP At Node->Arms
Num points:6804
Get Mesh Name: Arms <->  MaterialName: Arm
{
    diffuseTexture: arm_dif.png
    SpecularTexture: arm_showroom_spec.png
    HeightTexture: arm_showroom_ddn.png
}
LOOP At Node->Helmet
Num points:7248
Get Mesh Name: Helmet <->  MaterialName: Helmet
{
    diffuseTexture: helmet_diff.png
    SpecularTexture: helmet_showroom_spec.png
    HeightTexture: helmet_showroom_ddn.png
}
LOOP At Node->Body
Num points:8316
Get Mesh Name: Body <->  MaterialName: Body
{
    diffuseTexture: body_dif.png
    SpecularTexture: body_showroom_spec.png
    HeightTexture: body_showroom_ddn.png
}

 

在废物Maya中:

 

 

 

posted on 2020-02-16 18:56  gearslogy  阅读(290)  评论(0编辑  收藏  举报