• 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
iamtakingiteasy

Shadow-casting through time acting in "reverse" before next notciable shadowmap update

1 post in this topic

Hello!

 

I have a scene of big thin parallelepiped, small cube, and a light source, all aligned on Y axis, like so:

[attachment=17447:Untitled.png]

 

 

Both objects are static and light is sliding on Y axis only.

Also, a tiny (32x32) depth texture from Light's PointOfView is being rendered off-screen and then applied to both cube and parallelepiped on on-screen rendering stage, making effect of a shadow being casted by a small cube on a big parallelepiped.

The problem i am experiencing is that when light moves away from cube, such low-res depth texture is getting updated only 6-7 times, but it's projection on surfaces updates constantly and wrongly: while shadow is supposed to shrink when lightsource moves away and grow when lightsource moves closer, it is in fact doing the reverse between updates of texture projection! In other words, between two updates of texture, it's projection on a parallelepiped grows when light moves away and shrinks when light moves closer and then "jumps" when texture updates, which is looking very wrong.

To better show the problem, i've made this video:

http://www.youtube.com/watch?v=XOraTZimmUU

(the square in right-upper corner is the depth texture, made from light's POV). As you can see, at first i am moving light out (decresing negative Y) and you can notice projection growing between "jumps" of texture updates. Then i am moving light in and you can notice projection shrinking between the same "jumps".

My question is: how to reverse this shrinking-growing behavior without increasing shadowmap texture resolution (which only make problem less noticable, but not completly solved)?

 

Shaders used to map texture on:

 

Vertex:

#version 120
struct light_t {
  vec3 spot_dir;
  vec3 position;
  mat4 MVP;
  mat4 V;
  mat4 P;
};
attribute vec4 in_position;
uniform mat4 MVP;
uniform mat4 M;
uniform mat4 V;
uniform mat4 P;
uniform light_t light;
varying vec4 shadowcoord;
void main() {
  gl_Position = MVP * in_position;
  mat4 bias = mat4(0.5, 0.0, 0.0, 0.0,
                   0.0, 0.5, 0.0, 0.0,
                   0.0, 0.0, 0.5, 0.0,
                   0.5, 0.5, 0.5, 1.0);
  shadowcoord = bias * light.MVP * in_position;
}

Fragment:

#version 120
varying vec4 shadowcoord;
uniform sampler2D shadowmap;
void main() {
  vec4 color = vec4(0.5);
  float factor = 1.0;
  float z = texture2DProj(shadowmap, shadowcoord.xyw).z;
  if (z < (shadowcoord.z-0.0005)/shadowcoord.w) factor = 0.2;
  gl_FragColor = factor * color;
}

The full self-contained source of minimal (~900 lines, meh) example (extracted from full-scale project) is here (glm math library, C++ compiler and glut is needed):

 

Compile line:





g++ -g -o example main.cpp  -lGL -lGLU -lglut -lGLEW

Source:







#include <GL/glew.h>
#include <GL/glut.h>
#include <iostream>
#include <vector>
#include <string>
#include <map>
#include <glm/glm.hpp>
#include <glm/gtc/quaternion.hpp>
#include <glm/gtc/matrix_transform.hpp>

struct VertexData {
  float xyzw[4];

  VertexData(float x, float y, float z, float w) {
    xyzw[0] = x;
    xyzw[1] = y;
    xyzw[2] = z;
    xyzw[3] = w;
  }
};

class DepthTextureObject {
  private:
    unsigned int m_id;
    int m_width;
    int m_height;

  public:
    DepthTextureObject() :
      m_id(0),
      m_width(2048),
      m_height(2048)
    {}

    void cleanup() {
      glDeleteTextures(1, &m_id);
    }

    void bind() const {
      glBindTexture(GL_TEXTURE_2D, m_id);
    }

    void unbind() const {
      glBindTexture(GL_TEXTURE_2D, 0);
    }
    unsigned int id() const {
      return m_id;
    }
    void width(int newWidth) {
      m_width = newWidth;
    }
    int width() const {
      return m_width;
    }
    void height(int newHeight) {
      m_height = newHeight;
    }
    int height() const {
      return m_height;
    }

    void generate() {
      glGenTextures(1, &m_id);
      glBindTexture(GL_TEXTURE_2D, m_id);
      glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
      glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
      glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
      glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
      glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT, m_width, m_height, 0, GL_DEPTH_COMPONENT, GL_FLOAT, 0);
    }
};

class FramebufferObject {
  private:
    unsigned int m_id;

  public:
    FramebufferObject() :
      m_id(0)
    {}
    void cleanup() {
      glDeleteFramebuffers(1, &m_id);
    }

    void generate() {
      glGenFramebuffers(1, &m_id);
    }
    void bind() const {
      glBindFramebuffer(GL_FRAMEBUFFER, m_id);
    }
    void unbind() const {
      glBindFramebuffer(GL_FRAMEBUFFER, 0);
    }
    unsigned int id() const {
      return m_id;
    }
    void attach_depth_texture(DepthTextureObject const& tex) {
      bind();
      glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, tex.id(), 0);
      if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) {
        std::cout << "Framebuffer #" << m_id << " is incomplete!";
      }
      unbind();
    }
};

class VertexbufferObject {
  private:
    std::vector<VertexData> m_vertices_data;
    std::vector<unsigned int> m_indices_data;
    unsigned int m_vert_id;
    unsigned int m_indx_id;
    
  public:
    VertexbufferObject() :
      m_vert_id(0),
      m_indx_id(0)
    {}
    void cleanup() {
      glDeleteBuffers(1, &m_vert_id);
      glDeleteBuffers(1, &m_indx_id);
    }

    void provide_vertices(std::vector<VertexData> const& data) {
      m_vertices_data.insert(m_vertices_data.end(), data.begin(), data.end());
    }

    void provide_indices(std::vector<unsigned int> const& data) {
      m_indices_data.insert(m_indices_data.end(), data.begin(), data.end());
    }

    void provide_vertices(unsigned int length, float *arr) {
      for (int i = 0; i < length/4; i++) {
        float x = arr[i*4+0];
        float y = arr[i*4+1];
        float z = arr[i*4+2];
        float w = arr[i*4+3];
        m_vertices_data.push_back(VertexData(x, y, z, w));
      }
    }

    void provide_indices(unsigned int length, unsigned int *arr) {
      for (int i = 0; i < length; i++) {
        m_indices_data.push_back(arr[i]);
      }
    }

    void generate() {
      glGenBuffers(1, &m_vert_id);
      glGenBuffers(1, &m_indx_id);

      glBindBuffer(GL_ARRAY_BUFFER, m_vert_id);
      glBufferData(GL_ARRAY_BUFFER, m_vertices_data.size() * sizeof(VertexData), m_vertices_data.data(), GL_STATIC_DRAW);
      glBindBuffer(GL_ARRAY_BUFFER, 0);

      glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_indx_id);
      glBufferData(GL_ELEMENT_ARRAY_BUFFER, m_indices_data.size() * sizeof(unsigned int), m_indices_data.data(), GL_STATIC_DRAW);
      glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
    }

    unsigned int vert_id() const {
      return m_vert_id;
    }

    unsigned int indx_id() const {
      return m_indx_id;
    }

    unsigned int indx_count() const {
      return m_indices_data.size();
    }

    void bind() const {
      glBindBuffer(GL_ARRAY_BUFFER, m_vert_id);
      glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_indx_id);
    }

    void unbind() const {
      glBindBuffer(GL_ARRAY_BUFFER, 0);
      glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
    }
};

class Object3D {
  private:
    glm::vec3 m_position;
    glm::quat m_rotation;
    glm::mat4 m_model;
    glm::mat4 m_view;
    glm::mat4 m_proj;
    glm::mat4 m_MVP;
   
    float m_aspect;
    float m_fov;
    float m_near;
    float m_far;
    float m_bottom;
    float m_top;
    float m_left;
    float m_right;

    static glm::mat4 m_rhs2lhs;
    static glm::mat4 m_lhs2rhs;

  public:
    Object3D() :
      m_aspect(1.0f),
      m_fov(60.0f),
      m_near(0.1f),
      m_far(100.0f),
      m_bottom(-10.0f),
      m_top(10.0f),
      m_left(-10.0f),
      m_right(10.0f)
    {}

    void translate(glm::vec3 scaledDirction) {
      m_position += scaledDirction;
    }
    void translate(float x, float y, float z) {
      m_position.x += x;
      m_position.y += y;
      m_position.z += z;
    }
    void rotate(glm::vec3 axis, float degrees) {
      m_rotation = glm::rotate(m_rotation, degrees, glm::normalize(axis));
    }
    glm::vec3 position() const {
      return m_position;
    }
    void position(float x, float y, float z) {
      m_position.x = x;
      m_position.y = y;
      m_position.z = z;
    }
    glm::quat rotation() const {
      return m_rotation;
    }
    void rotation(glm::quat & newRot) {
      m_rotation = newRot;
    }
    void ortho(float left, float right, float bottom, float top, float near, float far) {
      m_left = left;
      m_right = right;
      m_bottom = bottom;
      m_top = top;
      m_near = near;
      m_far = far;
    }
    void persp(float aspect, float fov, float near, float far) {
      m_aspect = aspect;
      m_fov = fov;
      m_near = near;
      m_far = far;
    }
    glm::mat4 const& rhs2lhs() const {
      return m_rhs2lhs;
    }
    glm::mat4 const& lhs2rhs() const {
      return m_lhs2rhs;
    }
    glm::mat4 calcModelMatrix() {
      glm::mat4 rot = glm::mat4_cast(m_rotation);
      m_model = glm::translate(rot, m_position);
      return m_model;
    }
    glm::mat4 calcViewMatrix() {
      glm::mat4 trans = glm::translate(glm::mat4(), m_position);
      trans *= glm::mat4_cast(m_rotation);
      m_view = rhs2lhs() * glm::inverse(trans);
      return m_view;
    }
    glm::mat4 calcProjPerspMatrix() {
      m_proj = glm::perspective(m_fov, m_aspect, m_near, m_far);
      return m_proj;
    }
    glm::mat4 calcProjOrthoMatrix() {
      m_proj = glm::ortho(m_left, m_right, m_bottom, m_top, m_near, m_far);
      return m_proj;
    }
    glm::mat4 calcMVPMatrix(glm::mat4 model) {
      m_MVP = m_proj * m_view * model;    
    }

    glm::mat4 const& model() const {
      return m_model;
    }
    glm::mat4 const& view() const {
      return m_view;
    }
    glm::mat4 const& proj() const {
      return m_proj;
    }
    glm::mat4 const& MVP() const {
      return m_MVP;
    }
};

glm::mat4 Object3D::m_rhs2lhs = glm::mat4(
    1.0f, 0.0f, 0.0f, 0.0f,
    0.0f, 0.0f,-1.0f, 0.0f,
    0.0f, 1.0f, 0.0f, 0.0f,
    0.0f, 0.0f, 0.0f, 1.0f
);
glm::mat4 Object3D::m_lhs2rhs = glm::mat4(
    1.0f, 0.0f, 0.0f, 0.0f,
    0.0f, 0.0f, 1.0f, 0.0f,
    0.0f,-1.0f, 0.0f, 0.0f,
    0.0f, 0.0f, 0.0f, 1.0f
);

class Camera : public Object3D {
  private:
    int m_width;
    int m_height;
  
  public:
    Camera() :
      m_width(800),
      m_height(600)
    {}
    void width(int newWidth) {
      m_width = newWidth;
    }
    int width() const {
      return m_width;
    }
    void height(int newHeight) {
      m_height = newHeight;
    }
    int height() const {
      return m_height;
    }
};

class Light : public Object3D {
  private:
    int m_width;
    int m_height;
    
    glm::vec3 m_spot_dir;

    DepthTextureObject m_depth_texture;
    FramebufferObject m_framebuffer;

  public:
    Light() :
      m_depth_texture(DepthTextureObject()),
      m_framebuffer(FramebufferObject())
    {}

    void generate_shadowmap() {
      m_framebuffer.generate();
      m_depth_texture.width(m_width);
      m_depth_texture.height(m_height);
      m_depth_texture.generate();
      m_framebuffer.attach_depth_texture(m_depth_texture);
    }

    DepthTextureObject const& depth_texture() const {
      return m_depth_texture;
    }

    FramebufferObject const& framebuffer() const {
      return m_framebuffer;
    }

    void width(int newWidth) {
      m_width = newWidth;
    }
    int width() const {
      return m_width;
    }
    void height(int newHeight) {
      m_height = newHeight;
    }
    int height() const {
      return m_height;
    }

    void spot_dir(float x, float y, float z) {
      m_spot_dir.x = x;
      m_spot_dir.y = y;
      m_spot_dir.z = z;
    }
    glm::vec3 const& spot_dir() const {
      return m_spot_dir;
    }
};

class ShaderObject {
  private:
    std::string m_log;
    unsigned int m_id;
    GLenum m_type;

  public:
    ShaderObject(GLenum shaderType, const char *source) {
      std::vector<char> log;
      int length;
      int actual_len;

      m_type = shaderType;
      m_id = glCreateShader(shaderType);
      glShaderSource(m_id, 1, &source, 0);
      glCompileShader(m_id);
      glGetShaderiv(m_id, GL_INFO_LOG_LENGTH, &length);
      log.resize(length);
      glGetShaderInfoLog(m_id, length, &actual_len, log.data());
      m_log.insert(m_log.end(), log.begin(), log.begin()+actual_len);
    }

    void cleanup() {
      glDeleteShader(m_id);
    }

    unsigned int id() const {
      return m_id;
    }

    std::string const& log() const {
      return m_log;
    }

    GLenum type() const {
      return m_type;
    }
};

class ShaderProgram {
  private:
    unsigned int m_id;
    std::vector<ShaderObject> m_objects;
    std::map<std::string, unsigned int> m_uniforms;
    std::string m_log;

  public:
    ShaderProgram() :
      m_id(0)
    {}
    void cleanup() {
      glDeleteProgram(m_id);
    }

    void link(std::vector<ShaderObject> const& objects) {
      m_id = glCreateProgram();
     
      std::vector<ShaderObject>::const_iterator it, end = objects.end();

      for (it = objects.begin(); it != end; it++) {
        glAttachShader(m_id, it->id());
        if (!it->log().empty()) {
          m_log += "\n";
          m_log += it->log();
        }
        m_objects.push_back(*it);
      }

      int log_length;
      int actual_len;
      std::vector<char> log_data;
      glGetProgramiv(m_id, GL_INFO_LOG_LENGTH, &log_length);
      log_data.resize(log_length);
      glGetProgramInfoLog(m_id, log_length, &actual_len, log_data.data());
      m_log.insert(m_log.end(), log_data.begin(), log_data.begin()+actual_len);
     

      if (!m_log.empty()) {
        std::cout << m_log << "\n";
      }

      glBindAttribLocation(m_id, 0, "in_position");
      glLinkProgram(m_id);
      glValidateProgram(m_id);
      
      int total_uniforms;
      int uniform_max_len;

      glGetProgramiv(m_id, GL_ACTIVE_UNIFORMS, &total_uniforms);
      glGetProgramiv(m_id, GL_ACTIVE_UNIFORM_MAX_LENGTH, &uniform_max_len);

      for (int i = 0; i < total_uniforms; i++) {
        std::vector<char> name_data;
        std::string name;
        int actual_len;
        int location;
          
        name_data.resize(uniform_max_len);
        glGetActiveUniform(m_id, i, uniform_max_len, &actual_len, 0, 0, name_data.data());
        name.insert(name.end(), name_data.begin(), name_data.begin()+actual_len);
        location = glGetUniformLocation(m_id, name.data());
        if (location > -1) {
          m_uniforms[name] = location;
        }
      }
    }

    unsigned int id() const {
      return m_id;
    }

    void bind() const {
      glUseProgram(m_id);
    }

    void unbind() const {
      glUseProgram(0);
    }

#define TRY_GET_UNIFORM(name, idx) do { \
      std::map<std::string, unsigned int>::const_iterator it; \
      it = m_uniforms.find(name); \
      if (it == m_uniforms.end()) { \
        /*std::cout << "uniform '" << name << "' wasnt found in program #" << m_id << "!\n";*/ \
        return; \
      } \
      *idx = it->second; \
    } while(0)


    void uniform(std::string name, glm::mat4 const& value) {
      unsigned int idx;
      TRY_GET_UNIFORM(name, &idx);
      glUniformMatrix4fv(idx, 1, GL_FALSE, &value[0][0]);
    }

    void uniform(std::string name, glm::mat3 const& value) {
      unsigned int idx;
      TRY_GET_UNIFORM(name, &idx);
      glUniformMatrix3fv(idx, 1, GL_FALSE, &value[0][0]);
    }
    
    void uniform(std::string name, glm::vec4 const& value) {
      unsigned int idx;
      TRY_GET_UNIFORM(name, &idx);
      glUniform4f(idx, value[0], value[1], value[2], value[3]);
    }

    void uniform(std::string name, glm::vec3 const& value) {
      unsigned int idx;
      TRY_GET_UNIFORM(name, &idx);
      glUniform3f(idx, value[0], value[1], value[2]);
    }

    void uniform(std::string name, glm::vec2 const& value) {
      unsigned int idx;
      TRY_GET_UNIFORM(name, &idx);
      glUniform2f(idx, value[0], value[1]);
    }

    void uniform(std::string name, float value) {
      unsigned int idx;
      TRY_GET_UNIFORM(name, &idx);
      glUniform1f(idx, value);
    }

    void uniform(std::string name, int value) {
      unsigned int idx;
      TRY_GET_UNIFORM(name, &idx);
      glUniform1i(idx, value);
    }

    void uniform(std::string name, bool value) {
      unsigned int idx;
      TRY_GET_UNIFORM(name, &idx);
      glUniform1i(idx, value);
    }

    void uniform(std::string name, Light const& light) {
      uniform(name + ".spot_dir", light.spot_dir());
      uniform(name + ".position", light.position());
      uniform(name + ".MVP", light.MVP());
      uniform(name + ".V", light.view());
      uniform(name + ".P", light.proj());
    }
};
class Entity : public Object3D {
  private:
    VertexbufferObject m_vbo;
    ShaderProgram m_program;
    ShaderProgram m_depth_program;

  public:
    void vbo(VertexbufferObject const& vbo) {
      m_vbo = vbo;
    }
    void program(ShaderProgram const& program) {
      m_program = program;
    }
    void depth_program(ShaderProgram const& program) {
      m_depth_program = program;
    }

    void renderGeometry(Object3D POV) {
      glCullFace(GL_FRONT);
      glm::mat4 model = calcModelMatrix();
      glm::mat4 MVP = POV.proj() * POV.view() * model;
      
      m_depth_program.bind();
      m_depth_program.uniform("MVP", MVP);
      m_vbo.bind();
      glEnableVertexAttribArray(0);
      glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, sizeof(VertexData), 0);
      glDrawElements(GL_TRIANGLES, m_vbo.indx_count(), GL_UNSIGNED_INT, 0);
      glDisableVertexAttribArray(0);
      m_vbo.unbind();
      m_depth_program.unbind();
    }

    void renderAll(Object3D const& POV, Light & light) {
      glCullFace(GL_BACK);
      glm::mat4 model = calcModelMatrix();
      glm::mat4 view = POV.view();
      glm::mat4 proj = POV.proj();
      glm::mat4 MVP = proj * view * model;

      m_program.bind();

      m_program.uniform("M", model);
      m_program.uniform("V", view);
      m_program.uniform("P", proj);
      m_program.uniform("MVP", MVP);
      
      glActiveTexture(GL_TEXTURE0);
      light.depth_texture().bind();
      m_program.uniform("shadowmap", 0);
      
      light.calcMVPMatrix(model);
      m_program.uniform("light", light);
      
      m_vbo.bind();
      glEnableVertexAttribArray(0);
      
      glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, sizeof(VertexData), 0);
      glDrawElements(GL_TRIANGLES, m_vbo.indx_count(), GL_UNSIGNED_INT, 0);

      glDisableVertexAttribArray(0);
      m_vbo.unbind();

      m_program.unbind();
    }
};

// scene
Camera camera;
Light light;
Entity cube;

// input
bool keystate[256];
float movespeed = 0.1f;
float angularspeed = 0.4f;
int dx;
int dy;
int dz;

// dimensions
int width = 800;
int height = 600;

void initGL() {
  glClearColor(0.2f, 0.2f, 0.2f, 1.0f);
  glViewport(0, 0, width, height);
  glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
  glEnable(GL_DEPTH_TEST);
  glDepthFunc(GL_LEQUAL);
  glClearDepth(1.0f);
}

void initScene() {
  camera.width(width);
  camera.height(height);
  camera.position(0.0f,-3.0f, 0.0f);
  camera.persp((float) width/height, 60.0f, 0.1f, 100.0f);

  light.width(32);
  light.height(32);
  light.spot_dir(0.0f, 1.0f, 0.0f);
  light.position(0.0f, -3.0f, 0.0f);
  light.persp(1.0f, 60.0f, 0.1f, 100.0f);
  light.generate_shadowmap();
 
  float cube_vertices[] = {
    1.0f ,1.0f,-1.0f, 1.0f,
    1.0f,-1.0f,-1.0f, 1.0f,
   -1.0f,-1.0f,-1.0f, 1.0f,
   -1.0f, 1.0f,-1.0f, 1.0f,
    1.0f, 1.0f, 1.0f, 1.0f,
    1.0f,-1.0f, 1.0f, 1.0f,
   -1.0f,-1.0f, 1.0f, 1.0f,
   -1.0f, 1.0f, 1.0f, 1.0f,
    6.0f, 9.0f,-6.0f, 1.0f,
    6.0f, 8.0f,-6.0f, 1.0f,
   -6.0f, 8.0f,-6.0f, 1.0f,
   -6.0f, 9.0f,-6.0f, 1.0f,
    6.0f, 9.0f, 6.0f, 1.0f,
    6.0f, 8.0f, 6.0f, 1.0f,
   -6.0f, 8.0f, 6.0f, 1.0f,
   -6.0f, 9.0f, 6.0f, 1.0f
  };
  unsigned int cube_indices[] = {
     0, 1, 3,
     4, 7, 6,
     0, 4, 5,
     1, 5, 2,
     2, 6, 3,
     4, 0, 3,
     8, 9,11,
    12,15,14,
     8,12,13,
     9,13,10,
    10,14,11,
    12, 8,11,
     1, 2, 3,
     5, 4, 6,
     1, 0, 5,
     5, 6, 2,
     6, 7, 3,
     7, 4, 3,
     9,10,11,
    13,12,14,
     9, 8,13,
    13,14,10,
    14,15,11,
    15,12,11
  };

  VertexbufferObject vbo;
  vbo.provide_vertices(sizeof(cube_vertices)/sizeof(float), cube_vertices);
  vbo.provide_indices(sizeof(cube_indices)/sizeof(unsigned int), cube_indices);

  vbo.generate();

  ShaderObject depth_vertex(GL_VERTEX_SHADER,
      "#version 120\n"
      "attribute vec4 in_position;\n"
      "uniform mat4 MVP;\n"
      "void main() {\n"
      "  gl_Position = MVP * in_position;\n"
      "}\n"
  );

  ShaderObject vertex(GL_VERTEX_SHADER,
      "#version 120\n"
      "struct light_t {\n"
      "  vec3 spot_dir;\n"
      "  vec3 position;\n"
      "  mat4 MVP;\n"
      "  mat4 V;\n"
      "  mat4 P;\n"
      "};\n"
      "attribute vec4 in_position;\n"
      "uniform mat4 MVP;\n"
      "uniform mat4 M;\n"
      "uniform mat4 V;\n"
      "uniform mat4 P;\n"
      "uniform light_t light;\n"
      "varying vec4 shadowcoord;\n"
      "void main() {\n"
      "  gl_Position = MVP * in_position;\n"
      "  mat4 bias = mat4(0.5, 0.0, 0.0, 0.0,\n"
      "                   0.0, 0.5, 0.0, 0.0,\n"
      "                   0.0, 0.0, 0.5, 0.0,\n"
      "                   0.5, 0.5, 0.5, 1.0);\n"
      "  shadowcoord = bias * light.MVP * in_position;\n"
      "}\n"
  );
  ShaderObject fragment(GL_FRAGMENT_SHADER,
      "#version 120\n"
      "varying vec4 shadowcoord;\n"
      "uniform sampler2D shadowmap;\n"
      "void main() {\n"
      "  vec4 color = vec4(0.5);\n"
      "  float factor = 1.0;\n"
      "  float z = texture2DProj(shadowmap, shadowcoord.xyw).z;\n"
      "  if (z < (shadowcoord.z-0.0005)/shadowcoord.w) factor = 0.2;\n"
      "  gl_FragColor = factor * color;\n"
      "}\n"
  );

  std::vector<ShaderObject> depth_objects;
  depth_objects.push_back(depth_vertex);
  ShaderProgram depth_program;
  depth_program.link(depth_objects);

  std::vector<ShaderObject> objs;
  objs.push_back(vertex);
  objs.push_back(fragment);
  ShaderProgram program;
  program.link(objs);

  cube.vbo(vbo);
  cube.program(program);
  cube.depth_program(depth_program);
}


void display(void) {
  glm::vec3 camera_movedir(0,0,0);
  if (keystate['w']) {
      camera_movedir += glm::vec3(0,1,0);
  }
  if (keystate['s']) {
      camera_movedir += glm::vec3(0,-1,0);
  }
  if (keystate['a']) {
      camera_movedir += glm::vec3(-1,0,0);
  }
  if (keystate['d']) {
      camera_movedir += glm::vec3(1,0,0);
  }
  if (keystate['[']) {
    light.translate(0,-0.05,0);
    std::cout << "Current light position: X:0 Y:" << light.position().y << " Z:0\n";
  }
  if (keystate[']']) {
    light.translate(0,0.05,0);
    std::cout << "Current light position: X:0 Y:" << light.position().y << " Z:0\n";
  }
  if (keystate['f']) {
    camera_movedir += glm::vec3(0,0,1);
  }
  if (keystate['g']) {
    camera_movedir += glm::vec3(0,0,-1);
  }

  if (keystate['q']) {
    dz = -10;
  }

  if (keystate['e']) {
    dz = 10;
  }

  if (dx != 0) {
    float px = ((float)dx / width) * 100 * angularspeed;
    camera.rotate(glm::vec3(0,0,-1), px);
  }
  if (dy != 0) {
    float py = ((float)dy / height) * 100 * angularspeed;
    camera.rotate(glm::vec3(-1,0,0), py);
  }
  if (dz != 0) {
    float pz = ((float)dz / 1000) * 100 * angularspeed;
    camera.rotate(glm::vec3(0,1,0), pz);
  }

  dx = 0;
  dy = 0;
  dz = 0;
  if (glm::length(camera_movedir) > 0.0f) {
    camera_movedir = camera.rotation() * camera_movedir;
    camera.translate(glm::normalize(camera_movedir) * movespeed);
  }

  
  light.calcProjPerspMatrix();
  light.calcViewMatrix();

  camera.calcProjPerspMatrix();
  camera.calcViewMatrix();

  light.framebuffer().bind();
  glViewport(0, 0, light.width(), light.height());
  glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
  cube.renderGeometry(light);
  light.framebuffer().unbind();

  glViewport(0, 0, width, height);
  glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
  cube.renderAll(camera, light);
 
  glActiveTexture(GL_TEXTURE0);
  glEnable(GL_TEXTURE_2D);
  light.depth_texture().bind();
  glBegin(GL_QUADS);
  glTexCoord2d(0,0); glVertex3f(0.0f, 0.0f, 0.0f);
  glTexCoord2d(1,0); glVertex3f(1.0f, 0.0f, 0.0f);
  glTexCoord2d(1,1); glVertex3f(1.0f, 1.0f, 0.0f);
  glTexCoord2d(0,1); glVertex3f(0.0f, 1.0f, 0.0f);
  glEnd();
  light.depth_texture().unbind();

  glFlush();
  glutSwapBuffers();
  glutWarpPointer(width/2, height/2);
}

void keyboardUp(unsigned char key, int x, int y) {
  keystate[key] = false;
}

void keyboardDown(unsigned char key, int x, int y) {
  keystate[key] = true;
}

void mouse(int x, int y) {
  dx += x - (width/2);
  dy += y - (height/2);
}


int main(int argc, char ** argv) {
  glutInit(&argc, argv);
  glutInitWindowSize(width, height);
  glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_DEPTH);
  glutCreateWindow("Example");
  
  glewInit();

  initGL();

  initScene();
  
  glutDisplayFunc(display);
  glutIdleFunc(display);

  glutKeyboardFunc(keyboardDown);
  glutKeyboardUpFunc(keyboardUp);
  
  glutPassiveMotionFunc(mouse);
  glutSetCursor(GLUT_CURSOR_NONE);

  glutIgnoreKeyRepeat(true);

  glutWarpPointer(width/2, height/2);

  glutMainLoop();
  return 0;
}

Edited by iamtakingiteasy
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