예제 #1
0
	void Display::Create(const std::string& title, int width, int height)
	{
		s_title = title;
		s_width = width;
		s_height = height;

		glfwSetErrorCallback(error_callback);

		if (!glfwInit())
		{
			std::cerr << "GLFW failed to initialize!" << std::endl;
			Destroy();
			exit(1);
		}

		glfwDefaultWindowHints();
		glfwWindowHint(GLFW_VISIBLE, GL_FALSE);
		glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);

		s_pWindow = glfwCreateWindow(width, height, title.c_str(), NULL, NULL);

		const GLFWvidmode* vidmode = glfwGetVideoMode(glfwGetPrimaryMonitor());
		glfwSetWindowPos(s_pWindow, (vidmode->width - width) / 2, (vidmode->height - height) / 2);

		glfwMakeContextCurrent(s_pWindow);

		if (glewInit() != GLEW_OK)
		{
			std::cerr << "GLEW failed to initialize!" << std::endl;
			exit(1);
		}

		glfwShowWindow(s_pWindow);
	}
OpenGLDepthPacketProcessor::OpenGLDepthPacketProcessor(void *parent_opengl_context_ptr, bool debug)
{
  GLFWwindow* parent_window = (GLFWwindow *)parent_opengl_context_ptr;

  // init glfw - if already initialized nothing happens
  if (glfwInit() == GL_FALSE)
  {
      LOG_ERROR << "Failed to initialize GLFW.";
      exit(-1);
  }
  
  // setup context
  glfwDefaultWindowHints();
  glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
  glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
  #ifdef __APPLE__
    glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
  #endif
  glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
  glfwWindowHint(GLFW_VISIBLE, debug ? GL_TRUE : GL_FALSE);

  GLFWwindow* window = glfwCreateWindow(1024, 848, "OpenGLDepthPacketProcessor", 0, parent_window);

  if (window == NULL)
  {
      LOG_ERROR << "Failed to create opengl window.";
      exit(-1);
  }

  impl_ = new OpenGLDepthPacketProcessorImpl(window, debug);
  impl_->initialize();
}
예제 #3
0
파일: gravity.c 프로젝트: vcored/Gravity
int main() {
    glfwSetErrorCallback(error_callback);

    if (!glfwInit())
        return -1;

    glfwDefaultWindowHints();
    glfwWindowHint(GLFW_VISIBLE, GLFW_FALSE);
    glfwWindowHint(GLFW_RESIZABLE, GLFW_FALSE);

    window = glfwCreateWindow(WIDTH, HEIGHT, "", NULL, NULL);
    if (!window) {
        glfwTerminate();
        return -1;
    }

    glfwSetKeyCallback(window, key_callback);
    glfwSetMouseButtonCallback(window, mouse_callback);

    const GLFWvidmode* vidmode = glfwGetVideoMode(glfwGetPrimaryMonitor());
    glfwSetWindowPos(window, (vidmode->width - WIDTH) / 2, (vidmode->height - HEIGHT) / 2);

    glfwMakeContextCurrent(window);

    glfwSwapInterval(1);
    glfwShowWindow(window);

    loop();

    glfwDestroyWindow(window);
    glfwTerminate();

    return 0;
}
예제 #4
0
int main() {

    glfwInit();

    glfwDefaultWindowHints();
    glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 1);

    GLFWwindow *window = glfwCreateWindow(800, 600, "nanovg Demo", nullptr, nullptr);

    NVGcontext *vg = nvgCreateGL3(NVG_ANTIALIAS | NVG_STENCIL_STROKES | NVG_DEBUG);

    while (!glfwWindowShouldClose(window)) {

        glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT|GL_STENCIL_BUFFER_BIT);

        nvgBeginFrame(vg, 800, 600, 1);

        nvgBeginPath(vg);
        nvgRoundedRect(vg, 12, 12, 800-12*2, 600-12*2, 4);
        nvgFillColor(vg, nvgRGBA(255, 255, 255, 192));
        nvgFill(vg);

        nvgEndFrame(vg);

        glfwSwapBuffers(window);
        glfwPollEvents();
    }

    glfwDestroyWindow(window);
    glfwTerminate();
    return 0;
}
예제 #5
0
파일: init.c 프로젝트: deltaluca/glfw
GLFWAPI int glfwInit(void)
{
    if (_glfwInitialized)
        return GL_TRUE;

    memset(&_glfw, 0, sizeof(_glfw));

    if (!_glfwPlatformInit())
    {
        _glfwPlatformTerminate();
        return GL_FALSE;
    }

    _glfw.monitors = _glfwPlatformGetMonitors(&_glfw.monitorCount);
    if (_glfw.monitors == NULL)
    {
        _glfwErrorCallback(GLFW_PLATFORM_ERROR, "No monitors found", _glfwErrorCallback_data);
        _glfwPlatformTerminate();
        return GL_FALSE;
    }

    _glfwInitialized = GL_TRUE;

    // Not all window hints have zero as their default value
    glfwDefaultWindowHints();

    return GL_TRUE;
}
예제 #6
0
int main(int /*argc*/, char* /*argv*/[])
{
    if (!glfwInit())
        return 1;

    glfwSetErrorCallback(errorfun);

    glfwDefaultWindowHints();
    glfwWindowHint(GLFW_VISIBLE, false);

#ifdef __APPLE__
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2);
    glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, true);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
#endif

    GLFWwindow * window = glfwCreateWindow(320, 240, "", nullptr, nullptr);

    if (!window)
    {
        glfwTerminate();
        return -1;
    }

    glfwMakeContextCurrent(window);

    compare();

    glfwTerminate();
    return 0;
}
예제 #7
0
bool Indigo::run(const char* name, void (*fn)(void*), void* param)
{
	// Create render comms pipe
	PIPE_RACK::instance().m_render_pipe =  OOBase::allocate_shared<Indigo::Pipe,OOBase::ThreadLocalAllocator>("render");
	if (!PIPE_RACK::instance().m_render_pipe)
		LOG_ERROR_RETURN(("Failed to allocate render pipe: %s",OOBase::system_error_text()),false);

	render_init(PIPE_RACK::instance().m_render_pipe.get());

	// Not sure if we need to set this first...
	glfwSetErrorCallback(&on_glfw_error);

	if (!glfwInit())
		LOG_ERROR_RETURN(("glfwInit failed"),false);

	// Set defaults
	glfwDefaultWindowHints();

	bool ret = false;
	OOBase::SharedPtr<OOBase::Thread> thread;
	PIPE_RACK::instance().m_logic_pipe = Indigo::start_thread(name,thread);
	if (PIPE_RACK::instance().m_logic_pipe)
	{
		ret = PIPE_RACK::instance().m_logic_pipe->call(OOBase::make_delegate<OOBase::ThreadLocalAllocator>(fn),param);
		if (ret)
			thread->join();
	}

	glfwTerminate();

	return ret;
}
예제 #8
0
파일: init.c 프로젝트: 2php/glfw
GLFWAPI int glfwInit(void)
{
    if (_glfwInitialized)
        return GLFW_TRUE;

    memset(&_glfw, 0, sizeof(_glfw));

    if (!_glfwPlatformInit())
    {
        _glfwPlatformTerminate();
        return GLFW_FALSE;
    }

    _glfwInitVulkan();

    _glfw.monitors = _glfwPlatformGetMonitors(&_glfw.monitorCount);
    _glfwInitialized = GLFW_TRUE;

    _glfw.timerOffset = _glfwPlatformGetTimerValue();

    // Not all window hints have zero as their default value
    glfwDefaultWindowHints();

    return GLFW_TRUE;
}
예제 #9
0
JNIEXPORT void JNICALL Java_com_badlogic_jglfw_Glfw_glfwDefaultWindowHints(JNIEnv* env, jclass clazz) {


//@line:692

		glfwDefaultWindowHints();
	

}
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
    if (nrhs != 0)
    {
        mexErrMsgIdAndTxt("glfw:usage", "Usage: glfwDefaultWindowHints()");
        return;
    }

    glfwDefaultWindowHints();
}
예제 #11
0
	// this should only be called from the main thread
	create_window_args::operator Window * () {
		gecom::log("Window").information(0) << "Creating window... [title=" << m_title << "]";
		if (m_hints[GLFW_OPENGL_DEBUG_CONTEXT]) {
			log("Window").information(0) << "Requesting debug GL context";
		}
		init_glfw();
		glfwDefaultWindowHints();
		//GLenum gl_err = glGetError();
		//gecom::log("Window") % 0 << "GLerror: " << gl_err;
		for (auto me : m_hints) {
			glfwWindowHint(me.first, me.second);
		}
		GLFWwindow *handle = glfwCreateWindow(m_size.w, m_size.h, m_title.c_str(), m_monitor, m_share ? m_share->handle() : nullptr);
		glfwDefaultWindowHints();
		if (!handle) {
			gecom::log("Window").error() << "GLFW window creation failed";
			throw window_error("GLFW window creation failed");
		}
		gecom::log("Window").information(0) << "Window created";
		return new Window(handle, m_share);
	}
예제 #12
0
파일: lua-glfw.c 프로젝트: ifzz/lua-nanovg
static int Lhint(lua_State *L) {
    int type = lua_type(L, 1);
    if (type == LUA_TNUMBER)
        return set_hint(L, lua_tointeger(L, 1));
    else if (type == LUA_TSTRING) {
        size_t len;
        const char *s = luaL_checklstring(L, 1, &len);
        if (liteq(s, "reset")) {
            glfwDefaultWindowHints();
            return 0;
        }
        return set_hint(L, find_hintcode(L, s, len));
    }
    return lbind_typeerror(L, 1, "hint name (string/number)");
}
예제 #13
0
int main() {
  if(!glfwInit()) {
    std::cerr << "Failed to initialize GLFW" << std::endl;
    return -1;
  }

  glfwDefaultWindowHints();

  GLFWwindow* window = glfwCreateWindow(300, 300, "Red Triangle", nullptr, nullptr);
  if(window == nullptr) {
    std::cerr << "Failed to open GLFW window" << std::endl;
    glfwTerminate();
    return -1;
  }

  glfwMakeContextCurrent(window);
  glfwSwapInterval(1);
  glfwShowWindow(window);

  glEnable(GL_DOUBLEBUFFER);
  glEnable(GL_DEPTH_TEST);
  glDepthFunc(GL_LESS);

  glClearColor(0, 0, 0, 1);

  glm::mat4 m = glm::perspective(45.0f, 4.0f / 3.0f, 1.0f, 100.0f);
  glMatrixMode(GL_PROJECTION);
  glLoadMatrixf(glm::value_ptr(m));

  while(glfwWindowShouldClose(window) == GL_FALSE) {
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    glColor4f(1, 0, 0, 1);
    glBegin(GL_TRIANGLES);
    glVertex3f( 0,  0.5, -5);
    glVertex3f( 0.5, -0.5, -5);
    glVertex3f(-0.5, -0.5, -5);
    glEnd();

    glfwSwapBuffers(window);
    glfwPollEvents();
  }

  glfwDestroyWindow(window);
  glfwTerminate();
  return 0;
}
예제 #14
0
Viewer::Viewer() : shader_folder("src/shader/")
{
    // init glfw - if already initialized nothing happens
    int init = glfwInit();

    // setup context
    glfwDefaultWindowHints();
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
#ifdef __APPLE__
    glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
#endif
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
    //glfwWindowHint(GLFW_VISIBLE, debug ? GL_TRUE : GL_FALSE);

    window = glfwCreateWindow(1280, 800, "Viewer", 0, NULL);
}
예제 #15
0
int main(void)
{
  glfwSetErrorCallback(error_callback);

  // Initialize GLFW library
  if (!glfwInit())
    return -1;

  glfwDefaultWindowHints();
  glfwWindowHint(GLFW_CLIENT_API, GLFW_OPENGL_ES_API);
  glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 2);
  glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 0);

  // Create and open a window
  window = glfwCreateWindow(WINDOW_WIDTH,
                            WINDOW_HEIGHT,
                            "Shader Demo",
                            NULL,
                            NULL);

  if (!window)
  {
    glfwTerminate();
    printf("glfwCreateWindow Error\n");
    exit(1); 
  }

  glfwMakeContextCurrent(window);

  Init();

  // Repeat
  while (!glfwWindowShouldClose(window)) {


	Draw();
    glfwSwapBuffers(window);
    glfwPollEvents();
  }

  glfwDestroyWindow(window);
  glfwTerminate();
  exit(EXIT_SUCCESS);
}
예제 #16
0
GLFWAPI int glfwInit(void)
{
    if (_glfwInitialized)
        return GL_TRUE;

    memset(&_glfwLibrary, 0, sizeof(_glfwLibrary));

    if (!_glfwPlatformInit())
    {
        _glfwPlatformTerminate();
        return GL_FALSE;
    }

    _glfwInitialized = GL_TRUE;

    // Not all window hints have zero as their default value
    glfwDefaultWindowHints();

    return GL_TRUE;
}
예제 #17
0
파일: Window.cpp 프로젝트: dcobban/Marbles
// --------------------------------------------------------------------------------------------------------------------
window::builder::builder(/*allocator*/)
: _win(nullptr)
, _name("Marbles")
, _width(1280)
, _height(720)
, _fullscreen(false)
, _validation(false)
{
    _pre.reserve(8);
    _pre.push_back(async(launch::deferred, [this]() -> int
    {
        glfwDefaultWindowHints();
        if (glfwVulkanSupported())
        {
            glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API); // use vulkan
        }
        return 0;
    }));

    _post.reserve(8);
    _post.push_back(async(launch::deferred, [this]() -> int
    {
        GLFWwindow* glfwWin = this->_win->_internal->_window;
        glfwSetWindowUserPointer(glfwWin, this->_win);
        glfwSetWindowPosCallback(glfwWin, [](GLFWwindow* glfwWin, int x, int y)
        {
            window* win = reinterpret_cast<window*>(glfwGetWindowUserPointer(glfwWin));
            win->onReposition(win, x, y);
        });
        glfwSetWindowCloseCallback(glfwWin, [](GLFWwindow* glfwWin)
        {
            window* win = reinterpret_cast<window*>(glfwGetWindowUserPointer(glfwWin)); 
            win->onClose(win);
        });
        

        return 0;
    }));
}
예제 #18
0
TEST(Regression_185, GLbooleanReturnValueCall)  // GL calls fail if function returns GLboolean
{
    if (!glfwInit())
    {
        SUCCEED();
        return;
    }

    glfwDefaultWindowHints();
    glfwWindowHint(GLFW_VISIBLE, false);

#ifdef SYSTEM_DARWIN
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2);
    glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, true);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
#endif

    GLFWwindow * window = glfwCreateWindow(320, 240, "", nullptr, nullptr);
    ASSERT_NE(nullptr, window);

    glfwMakeContextCurrent(window);

    glbinding::Binding::initialize();

    ASSERT_EQ(gl::GL_NO_ERROR, gl::glGetError());

    // "Death Test": resolve a basic OpenGL of return type GLboolean (with underlying type char)
    // note: this might work on some OpenGL drivers without expected failure (try NVIDIA for expected failure on windows x64)
    ASSERT_NO_THROW(gl::glIsProgram(0));    

    ASSERT_EQ(gl::GL_NO_ERROR, gl::glGetError());

    glfwMakeContextCurrent(nullptr);
    glfwTerminate();

    SUCCEED();
}
예제 #19
0
파일: engine.cpp 프로젝트: bradparks/Plum
    Engine::Impl::Impl()
    {
        if(!glfwInit())
        {
            quit("Failed to initialize glfw.");
        }
        glfwSetTime(0.0);

        bool core = true;
        const char* vertexShaderSource[2] = {VertexCoreHeader, VertexShader};
        const char* fragmentShaderSource[2] = {FragmentCoreHeader, FragmentShader};

        glfwDefaultWindowHints();
        glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
        glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2);
        glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
        glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); 
        glfwWindowHint(GLFW_VISIBLE, GL_FALSE);
        root = glfwCreateWindow(1, 1, "", nullptr, nullptr);
        if(!root)
        {
            fprintf(stderr, "* Failed to create a OpenGL 3.2 context, falling back on 2.1...\n\n");

            glfwDefaultWindowHints();
            glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 2);
            glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 1);
            glfwWindowHint(GLFW_VISIBLE, GL_FALSE);
            root = glfwCreateWindow(1, 1, "", nullptr, nullptr);

            vertexShaderSource[0] = VertexCompatHeader;
            fragmentShaderSource[0] = FragmentCompatHeader;
            core = false;

            if(!root)
            {
                quit("Failed to initialize graphics context.");
            }
        }

        glfwMakeContextCurrent(root);
        glewInit();

        vertexShader = glCreateShader(GL_VERTEX_SHADER);
        glShaderSource(vertexShader, 2, vertexShaderSource, nullptr);
        glCompileShader(vertexShader);
        {
            GLint status;
            glGetShaderiv(vertexShader, GL_COMPILE_STATUS, &status);
            if(!status)
            {
                glGetShaderiv(vertexShader, GL_INFO_LOG_LENGTH, &status);
                std::vector<char> error(status);
                glGetShaderInfoLog(vertexShader, error.size(), nullptr, error.data());
                quit(std::string("Error found in vertex shader:\r\n") + error.data());
            }
        }

        fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);
        glShaderSource(fragmentShader, 2, fragmentShaderSource, nullptr);
        glCompileShader(fragmentShader);
        {
            GLint status;
            glGetShaderiv(fragmentShader, GL_COMPILE_STATUS, &status);
            if(!status)
            {
                glGetShaderiv(fragmentShader, GL_INFO_LOG_LENGTH, &status);
                std::vector<char> error(status);
                glGetShaderInfoLog(fragmentShader, error.size(), nullptr, error.data());
                quit(std::string("Error found in fragment shader:\r\n") + error.data());
            }
        }

        program = glCreateProgram();
        glAttachShader(program, vertexShader);
        glAttachShader(program, fragmentShader);
        if(core)
        {
            glBindFragDataLocation(fragmentShader, 0, "outColor");
        }
        glLinkProgram(program);
        {
            GLint status;
            glGetProgramiv(program, GL_LINK_STATUS, &status);
            if(!status)
            {
                glGetProgramiv(program, GL_INFO_LOG_LENGTH, &status);
                std::vector<char> error(status);
                glGetProgramInfoLog(program, error.size(), nullptr, error.data());
                quit(std::string("Error found during shader linking:\r\n") + error.data());
            }
        }
        glUseProgram(program);

        projectionUniform = glGetUniformLocation(program, "projection");
        originUniform = glGetUniformLocation(program, "origin");
        pivotUniform = glGetUniformLocation(program, "pivot");
        scaleUniform = glGetUniformLocation(program, "scale");
        angleUniform = glGetUniformLocation(program, "angle");
        colorUniform = glGetUniformLocation(program, "color");
        hasImageUniform = glGetUniformLocation(program, "hasImage");
        xyAttribute = glGetAttribLocation(program, "xy");
        uvAttribute = glGetAttribLocation(program, "uv");
    }
예제 #20
0
파일: Window.cpp 프로젝트: bryongloden/kit
void kit::Window::restoreGLFWHints()
{
  glfwDefaultWindowHints();
}
예제 #21
0
파일: hints.cpp 프로젝트: Genericson/sre
 /** Applies the defult hints.
  *  \note The function is equivalent to calling glfwDefaultWindowHints(); */
 void DefaultHints::apply() const
 {
     glfwDefaultWindowHints();
 }
int main() {
  if(glfwInit() == GL_FALSE) {
    std::cerr << "Failed to initialize GLFW" << std::endl;
    return -1;
  }
  defer(std::cout << "Calling glfwTerminate()" << std::endl; glfwTerminate());

  glfwDefaultWindowHints();

  glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
  glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
  glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
  glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);

  GLFWwindow* window = glfwCreateWindow(800, 600, "Rotating cube", nullptr, nullptr);
  if(window == nullptr) {
    std::cerr << "Failed to open GLFW window" << std::endl;
    return -1;
  }
  defer(std::cout << "Calling glfwDestroyWindow()" << std::endl; glfwDestroyWindow(window));

  glfwMakeContextCurrent(window);

  if(glxwInit()) {
    std::cerr << "Failed to init GLXW" << std::endl;
    return -1;
  }

  glfwSwapInterval(1);

  glfwSetWindowSizeCallback(window, windowSizeCallback);

  glfwShowWindow(window);

  bool errorFlag = false;
  std::vector<GLuint> shaders;

  GLuint vertexShaderId = loadShader("shaders/vertexShader.glsl", GL_VERTEX_SHADER, &errorFlag);
  if(errorFlag) {
    std::cerr << "Failed to load vertex shader (invalid working directory?)" << std::endl;
    return -1;
  }

  shaders.push_back(vertexShaderId);

  GLuint fragmentShaderId = loadShader("shaders/fragmentShader.glsl", GL_FRAGMENT_SHADER, &errorFlag);
  if(errorFlag) {
    std::cerr << "Failed to load fragment shader (invalid working directory?)" << std::endl;
    return -1;
  }
  shaders.push_back(fragmentShaderId);

  GLuint programId = prepareProgram(shaders, &errorFlag);
  if(errorFlag) {
    std::cerr << "Failed to prepare program" << std::endl;
    return -1;
  }
  defer(glDeleteProgram(programId));

  glDeleteShader(vertexShaderId);
  glDeleteShader(fragmentShaderId);

  GLuint vertexVBO;
  glGenBuffers(1, &vertexVBO);
  defer(glDeleteBuffers(1, &vertexVBO));

  glBindBuffer(GL_ARRAY_BUFFER, vertexVBO);
  glBufferData(GL_ARRAY_BUFFER, sizeof(globVertexBufferData), globVertexBufferData, GL_STATIC_DRAW);

  GLuint colorVBO;
  glGenBuffers(1, &colorVBO);
  defer(glDeleteBuffers(1, &colorVBO));

  glBindBuffer(GL_ARRAY_BUFFER, colorVBO);
  glBufferData(GL_ARRAY_BUFFER, sizeof(globColorBufferData), globColorBufferData, GL_STATIC_DRAW);

  GLuint vao;
  glGenVertexArrays(1, &vao);
  defer(glDeleteVertexArrays(1, &vao));

  glBindVertexArray(vao);

  glBindBuffer(GL_ARRAY_BUFFER, vertexVBO);
  glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, nullptr);
  glBindBuffer(GL_ARRAY_BUFFER, 0); // unbind VBO

  glBindBuffer(GL_ARRAY_BUFFER, colorVBO);
  glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 0, nullptr);
  glBindBuffer(GL_ARRAY_BUFFER, 0); // unbind VBO

  glBindVertexArray(0); // unbind VAO

  glm::mat4 projection = glm::perspective(80.0f, 4.0f / 3.0f, 0.3f, 100.0f);

  GLint matrixId = glGetUniformLocation(programId, "MVP");

  auto startTime = std::chrono::high_resolution_clock::now();
  auto prevTime = startTime;

  // hide cursor
  glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);

  Camera camera(window, glm::vec3(0, 0, 5), 3.14f /* toward -Z */, 0.0f /* look at the horizon */);

  glEnable(GL_DOUBLEBUFFER);
  glEnable(GL_DEPTH_TEST);
  glEnable(GL_CULL_FACE);
  glDepthFunc(GL_LESS);

  glClearColor(0, 0, 0, 1);

  while(glfwWindowShouldClose(window) == GL_FALSE) {
    if(glfwGetKey(window, GLFW_KEY_Q) == GLFW_PRESS) break;

    if(glfwGetKey(window, GLFW_KEY_Z) == GLFW_PRESS) {
      glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
    }

    if(glfwGetKey(window, GLFW_KEY_X) == GLFW_PRESS) {
      glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
    }

    auto currentTime = std::chrono::high_resolution_clock::now();
    float startDeltaTimeMs = std::chrono::duration_cast<std::chrono::milliseconds>(currentTime - startTime).count();
    float prevDeltaTimeMs = std::chrono::duration_cast<std::chrono::milliseconds>(currentTime - prevTime).count();
    prevTime = currentTime;

    float rotationTimeMs = 3000.0f;
    float currentRotation = startDeltaTimeMs / rotationTimeMs;
    float angle = 360.0f*(currentRotation - (long)currentRotation);

    glm::mat4 view;
    camera.getViewMatrix(prevDeltaTimeMs, &view);

    glm::mat4 model = glm::rotate(angle, 0.0f, 1.0f, 0.0f);
    glm::mat4 mvp = projection * view * model; // matrix multiplication is the other way around
    glUniformMatrix4fv(matrixId, 1, GL_FALSE, &mvp[0][0]);

    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    glUseProgram(programId);

    glBindVertexArray(vao);
    glEnableVertexAttribArray(0); // could be done once before while loop ... ->
    glEnableVertexAttribArray(1);
    glDrawArrays(GL_TRIANGLES, 0, 3*12);
    glDisableVertexAttribArray(1); // -> ... in this cast remove these two lines
    glDisableVertexAttribArray(0);
    
    glfwSwapBuffers(window);
    glfwPollEvents();
  }

  return 0;
}
예제 #23
0
void Viewer::initialize()
{
    // setup context
    glfwDefaultWindowHints();
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
#ifdef __APPLE__
    glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
#endif
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
    //glfwWindowHint(GLFW_VISIBLE, debug ? GL_TRUE : GL_FALSE);

    window = glfwCreateWindow(1280, 800, "Viewer", 0, NULL);
    glfwMakeContextCurrent(window);
    OpenGLBindings *b = new OpenGLBindings();
    flextInit(window, b);
    gl(b);

    std::string vertexshadersrc = ""
        "#version 330\n"
                                                
        "in vec2 Position;"
        "in vec2 TexCoord;"
                    
        "out VertexData{"
        "vec2 TexCoord;" 
        "} VertexOut;"  
                    
        "void main(void)"
        "{"
        "    gl_Position = vec4(Position, 0.0, 1.0);"
        "    VertexOut.TexCoord = TexCoord;"
        "}";
    std::string grayfragmentshader = ""
        "#version 330\n"
        
        "uniform sampler2DRect Data;"
        
        "vec4 tempColor;"
        "in VertexData{"
        "    vec2 TexCoord;"
        "} FragmentIn;"
        
        "layout(location = 0) out vec4 Color;"
        
        "void main(void)"
        "{"
            "ivec2 uv = ivec2(FragmentIn.TexCoord.x, FragmentIn.TexCoord.y);"
            "tempColor = texelFetch(Data, uv);"
            "Color = vec4(tempColor.x/4500, tempColor.x/4500, tempColor.x/4500, 1);"
        "}";
    std::string fragmentshader = ""
        "#version 330\n"
        
        "uniform sampler2DRect Data;"
        
        "in VertexData{"
        "    vec2 TexCoord;"
        "} FragmentIn;"
       
        "layout(location = 0) out vec4 Color;"
        
        "void main(void)"
        "{"
        "    ivec2 uv = ivec2(FragmentIn.TexCoord.x, FragmentIn.TexCoord.y);"

        "    Color = texelFetch(Data, uv);"
        "}";

    renderShader.setVertexShader(vertexshadersrc);
    renderShader.setFragmentShader(fragmentshader);
    renderShader.build();

    renderGrayShader.setVertexShader(vertexshadersrc);
    renderGrayShader.setFragmentShader(grayfragmentshader);
    renderGrayShader.build();


    glfwSetWindowUserPointer(window, this);
    glfwSetKeyCallback(window, Viewer::key_callbackstatic);

    shouldStop = false;
}
예제 #24
0
int main(int /*argc*/, char ** /*argv*/)
{
    if (!glfwInit())
    {
        return 1;
    }

    glfwSetErrorCallback(errorCallback);

    glfwDefaultWindowHints();

    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2);
    glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, true);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);

    GLFWwindow * window = glfwCreateWindow(canvasWidth, canvasHeight, "", nullptr, nullptr);
    if (!window)
    {
        glfwTerminate();
        return 2;
    }

    glfwSetWindowSizeCallback(window, resizeCallback);
    glfwSetKeyCallback(window, keyCallback);

    std::cout << "Screen Aligned Quad vs. Triangle(s)" << std::endl << std::endl;

    std::cout << "Key Binding: " << std::endl
        << "  [F5] reload shaders" << std::endl
        << "  [r]  reset record and benchmark and record anew" << std::endl
        << "  [v]  switch draw mode and associated vertex array" << std::endl
        << "  [T]  increment replay speed (by magnitude)" << std::endl
        << "  [t]  decrement replay speed (by magnitude)" << std::endl
        << std::endl;

    glfwMakeContextCurrent(window);

    glbinding::Binding::initialize(false);

    example.resize(canvasWidth, canvasHeight);
    example.initialize();

    while (!glfwWindowShouldClose(window)) // main loop
    {
        glfwPollEvents();

        example.render();

        glfwSwapBuffers(window);
    }

    example.cleanup();

    glfwMakeContextCurrent(nullptr);

    glfwDestroyWindow(window);

    glfwTerminate();

    return 0;
}
예제 #25
0
int main() {
    if(glfwInit() == GL_FALSE) {
        std::cerr << "Failed to initialize GLFW" << std::endl;
        return -1;
    }
    defer(glfwTerminate());

    glfwDefaultWindowHints();

    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
    glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
    glfwWindowHint(GLFW_SAMPLES, 4);

    GLFWwindow* window = glfwCreateWindow(800, 600, "Lighting", nullptr, nullptr);
    if(window == nullptr) {
        std::cerr << "Failed to open GLFW window" << std::endl;
        return -1;
    }
    defer(glfwDestroyWindow(window));

    glfwMakeContextCurrent(window);

    if(glxwInit()) {
        std::cerr << "Failed to init GLXW" << std::endl;
        return -1;
    }

    glfwSwapInterval(1);
    glfwSetWindowSizeCallback(window, windowSizeCallback);
    glfwShowWindow(window);

    bool errorFlag = false;
    std::vector<GLuint> shaders;

    GLuint vertexShaderId = loadShader("shaders/vertexShader.glsl", GL_VERTEX_SHADER, &errorFlag);
    if(errorFlag) {
        std::cerr << "Failed to load vertex shader (invalid working directory?)" << std::endl;
        return -1;
    }

    shaders.push_back(vertexShaderId);

    GLuint fragmentShaderId = loadShader("shaders/fragmentShader.glsl", GL_FRAGMENT_SHADER, &errorFlag);
    if(errorFlag) {
        std::cerr << "Failed to load fragment shader (invalid working directory?)" << std::endl;
        return -1;
    }
    shaders.push_back(fragmentShaderId);

    GLuint programId = prepareProgram(shaders, &errorFlag);
    if(errorFlag) {
        std::cerr << "Failed to prepare program" << std::endl;
        return -1;
    }
    defer(glDeleteProgram(programId));

    glDeleteShader(vertexShaderId);
    glDeleteShader(fragmentShaderId);

    // === prepare textures ===
    GLuint textureArray[6];
    int texturesNum = sizeof(textureArray)/sizeof(textureArray[0]);
    glGenTextures(texturesNum, textureArray);
    defer(glDeleteTextures(texturesNum, textureArray));

    GLuint grassTexture = textureArray[0];
    GLuint skyboxTexture = textureArray[1];
    GLuint towerTexture = textureArray[2];
    GLuint garkGreenTexture = textureArray[3];
    GLuint redTexture = textureArray[4];
    GLuint blueTexture = textureArray[5];

    if(!loadDDSTexture("textures/grass.dds", grassTexture)) return -1;

    if(!loadDDSTexture("textures/skybox.dds", skyboxTexture)) return -1;
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);

    if(!loadDDSTexture("textures/tower.dds", towerTexture)) return -1;

    loadOneColorTexture(0.05f, 0.5f, 0.1f, garkGreenTexture);
    loadOneColorTexture(1.0f, 0.0f, 0.0f, redTexture);
    loadOneColorTexture(0.0f, 0.0f, 1.0f, blueTexture);

    // === prepare VAOs ===
    GLuint vaoArray[5];
    int vaosNum = sizeof(vaoArray)/sizeof(vaoArray[0]);
    glGenVertexArrays(vaosNum, vaoArray);
    defer(glDeleteVertexArrays(vaosNum, vaoArray));

    GLuint grassVAO = vaoArray[0];
    GLuint skyboxVAO = vaoArray[1];
    GLuint towerVAO = vaoArray[2];
    GLuint torusVAO = vaoArray[3];
    GLuint sphereVAO = vaoArray[4];

    // === prepare VBOs ===
    GLuint vboArray[10];
    int vbosNum = sizeof(vboArray)/sizeof(vboArray[0]);
    glGenBuffers(vbosNum, vboArray);
    defer(glDeleteBuffers(vbosNum, vboArray));

    GLuint grassVBO = vboArray[0];
    GLuint grassIndicesVBO = vboArray[1];
    GLuint skyboxVBO = vboArray[2];
    GLuint skyboxIndicesVBO = vboArray[3];
    GLuint towerVBO = vboArray[4];
    GLuint towerIndicesVBO = vboArray[5];
    GLuint torusVBO = vboArray[6];
    GLuint torusIndicesVBO = vboArray[7];
    GLuint sphereVBO = vboArray[8];
    GLuint sphereIndicesVBO = vboArray[9];
    // === load models ===

    GLsizei grassIndicesNumber, skyboxIndicesNumber, towerIndicesNumber, torusIndicesNumber, sphereIndicesNumber;
    GLenum grassIndexType, skyboxIndexType, towerIndexType, torusIndexType, sphereIndexType;
    if(!modelLoad("models/grass.emd", grassVAO, grassVBO, grassIndicesVBO, &grassIndicesNumber, &grassIndexType)) return -1;
    if(!modelLoad("models/skybox.emd", skyboxVAO, skyboxVBO, skyboxIndicesVBO, &skyboxIndicesNumber, &skyboxIndexType)) return -1;
    if(!modelLoad("models/tower.emd", towerVAO, towerVBO, towerIndicesVBO, &towerIndicesNumber, &towerIndexType)) return -1;
    if(!modelLoad("models/torus.emd", torusVAO, torusVBO, torusIndicesVBO, &torusIndicesNumber, &torusIndexType)) return -1;
    if(!modelLoad("models/sphere.emd", sphereVAO, sphereVBO, sphereIndicesVBO, &sphereIndicesNumber, &sphereIndexType)) return -1;

    glm::mat4 projection = glm::perspective(70.0f, 4.0f / 3.0f, 0.3f, 250.0f);

    GLint uniformMVP = getUniformLocation(programId, "MVP");
    GLint uniformM = getUniformLocation(programId, "M");
    GLint uniformTextureSample = getUniformLocation(programId, "textureSampler");
    GLint uniformCameraPos = getUniformLocation(programId, "cameraPos");

    GLint uniformMaterialSpecularFactor = getUniformLocation(programId, "materialSpecularFactor");
    GLint uniformMaterialSpecularIntensity = getUniformLocation(programId, "materialSpecularIntensity");
    GLint uniformMaterialEmission = getUniformLocation(programId, "materialEmission");

    auto startTime = std::chrono::high_resolution_clock::now();
    auto prevTime = startTime;

    Camera camera(window, glm::vec3(0, 0, 5), 3.14f /* toward -Z */, 0.0f /* look at the horizon */);

    glEnable(GL_DOUBLEBUFFER);
    glEnable(GL_CULL_FACE);
    glEnable(GL_MULTISAMPLE);
    glEnable(GL_DEPTH_TEST);
    glDepthFunc(GL_LESS);
    glClearColor(0, 0, 0, 1);

    glUseProgram(programId);

    glUniform1i(uniformTextureSample, 0);

    bool directionalLightEnabled = true;
    bool pointLightEnabled = true;
    bool spotLightEnabled = true;
    bool wireframesModeEnabled = false;
    float lastKeyPressCheck = 0.0;
    const float keyPressCheckIntervalMs = 250.0f;

    setupLights(programId, directionalLightEnabled, pointLightEnabled, spotLightEnabled);

    while(glfwWindowShouldClose(window) == GL_FALSE) {
        if(glfwGetKey(window, GLFW_KEY_Q) == GLFW_PRESS) break;

        auto currentTime = std::chrono::high_resolution_clock::now();
        float startDeltaTimeMs = std::chrono::duration_cast<std::chrono::milliseconds>(currentTime - startTime).count();
        float prevDeltaTimeMs = std::chrono::duration_cast<std::chrono::milliseconds>(currentTime - prevTime).count();
        prevTime = currentTime;

        float rotationTimeMs = 100000.0f;
        float currentRotation = startDeltaTimeMs / rotationTimeMs;
        float islandAngle = 360.0f*(currentRotation - (long)currentRotation);

        if(startDeltaTimeMs - lastKeyPressCheck > keyPressCheckIntervalMs) {
            if(glfwGetKey(window, GLFW_KEY_X) == GLFW_PRESS) {
                lastKeyPressCheck = startDeltaTimeMs;
                wireframesModeEnabled = !wireframesModeEnabled;
                if(wireframesModeEnabled) glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
                else glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
            }
            if(glfwGetKey(window, GLFW_KEY_M) == GLFW_PRESS) {
                lastKeyPressCheck = startDeltaTimeMs;
                bool enabled = camera.getMouseInterception();
                camera.setMouseInterception(!enabled);
            }
            if(glfwGetKey(window, GLFW_KEY_1) == GLFW_PRESS) {
                lastKeyPressCheck = startDeltaTimeMs;
                directionalLightEnabled = !directionalLightEnabled;
                setupLights(programId, directionalLightEnabled, pointLightEnabled, spotLightEnabled);
            }
            if(glfwGetKey(window, GLFW_KEY_2) == GLFW_PRESS) {
                lastKeyPressCheck = startDeltaTimeMs;
                pointLightEnabled = !pointLightEnabled;
                setupLights(programId, directionalLightEnabled, pointLightEnabled, spotLightEnabled);
            }
            if(glfwGetKey(window, GLFW_KEY_3) == GLFW_PRESS) {
                lastKeyPressCheck = startDeltaTimeMs;
                spotLightEnabled = !spotLightEnabled;
                setupLights(programId, directionalLightEnabled, pointLightEnabled, spotLightEnabled);
            }
        }

        glm::vec3 cameraPos;
        camera.getPosition(&cameraPos);

        glUniform3f(uniformCameraPos, cameraPos.x, cameraPos.y, cameraPos.z);

        glm::mat4 view;
        camera.getViewMatrix(prevDeltaTimeMs, &view);
        glm::mat4 vp = projection * view;

        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

        // TODO implement ModelLoader and Model classes
        // tower

        glm::mat4 towerM = glm::rotate(islandAngle, 0.0f, 1.0f, 0.0f) * glm::translate(-1.5f, -1.0f, -1.5f);
        glm::mat4 towerMVP = vp * towerM;

        glBindTexture(GL_TEXTURE_2D, towerTexture);
        glBindVertexArray(towerVAO);
        glUniformMatrix4fv(uniformMVP, 1, GL_FALSE, &towerMVP[0][0]);
        glUniformMatrix4fv(uniformM, 1, GL_FALSE, &towerM[0][0]);
        glUniform1f(uniformMaterialSpecularFactor, 1.0f);
        glUniform1f(uniformMaterialSpecularIntensity, 0.0f);
        glUniform3f(uniformMaterialEmission, 0.0f, 0.0f, 0.0f);
        glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, towerIndicesVBO);
        glDrawElements(GL_TRIANGLES, towerIndicesNumber, towerIndexType, nullptr);

        // torus

        glm::mat4 torusM = glm::translate(0.0f, 1.0f, 0.0f) * glm::rotate((60.0f - 3.0f*islandAngle), 0.0f, 0.5f, 0.0f);
        glm::mat4 torusMVP = vp * torusM;

        glBindTexture(GL_TEXTURE_2D, garkGreenTexture);
        glBindVertexArray(torusVAO);
        glUniformMatrix4fv(uniformMVP, 1, GL_FALSE, &torusMVP[0][0]);
        glUniformMatrix4fv(uniformM, 1, GL_FALSE, &torusM[0][0]);
        glUniform1f(uniformMaterialSpecularFactor, 1.0f);
        glUniform1f(uniformMaterialSpecularIntensity, 1.0f);
        glUniform3f(uniformMaterialEmission, 0.0f, 0.0f, 0.0f);
        glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, torusIndicesVBO);
        glDrawElements(GL_TRIANGLES, torusIndicesNumber, torusIndexType, nullptr);

        // grass

        glm::mat4 grassM = glm::rotate(islandAngle, 0.0f, 1.0f, 0.0f) * glm::translate(0.0f, -1.0f, 0.0f);
        glm::mat4 grassMVP = vp * grassM;

        glBindTexture(GL_TEXTURE_2D, grassTexture);
        glBindVertexArray(grassVAO);
        glUniformMatrix4fv(uniformMVP, 1, GL_FALSE, &grassMVP[0][0]);
        glUniformMatrix4fv(uniformM, 1, GL_FALSE, &grassM[0][0]);
        glUniform1f(uniformMaterialSpecularFactor, 32.0f);
        glUniform1f(uniformMaterialSpecularIntensity, 2.0f);
        glUniform3f(uniformMaterialEmission, 0.0f, 0.0f, 0.0f);
        glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, grassIndicesVBO);
        glDrawElements(GL_TRIANGLES, grassIndicesNumber, grassIndexType, nullptr);

        // skybox

        glm::mat4 skyboxM = glm::translate(cameraPos) * glm::scale(100.0f,100.0f,100.0f);
        glm::mat4 skyboxMVP = vp * skyboxM;

        glBindTexture(GL_TEXTURE_2D, skyboxTexture);
        glBindVertexArray(skyboxVAO);
        glUniformMatrix4fv(uniformMVP, 1, GL_FALSE, &skyboxMVP[0][0]);
        glUniformMatrix4fv(uniformM, 1, GL_FALSE, &skyboxM[0][0]);
        glUniform1f(uniformMaterialSpecularFactor, 1.0f);
        glUniform1f(uniformMaterialSpecularIntensity, 0.0f);
        glUniform3f(uniformMaterialEmission, 0.0f, 0.0f, 0.0f);
        glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, skyboxIndicesVBO);
        glDrawElements(GL_TRIANGLES, skyboxIndicesNumber, skyboxIndexType, nullptr);

        // point light source
        if(pointLightEnabled) {
            glm::mat4 pointLightM = glm::translate(pointLightPos);
            glm::mat4 pointLightMVP = vp * pointLightM;

            glBindTexture(GL_TEXTURE_2D, redTexture);
            glBindVertexArray(sphereVAO);
            glUniformMatrix4fv(uniformMVP, 1, GL_FALSE, &pointLightMVP[0][0]);
            glUniformMatrix4fv(uniformM, 1, GL_FALSE, &pointLightM[0][0]);
            glUniform1f(uniformMaterialSpecularFactor, 1.0f);
            glUniform1f(uniformMaterialSpecularIntensity, 1.0f);
            glUniform3f(uniformMaterialEmission, 0.5f, 0.5f, 0.5f);
            glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, sphereIndicesVBO);
            glDrawElements(GL_TRIANGLES, sphereIndicesNumber, sphereIndexType, nullptr);
        }

        // spot light source
        if(spotLightEnabled) {
            glm::mat4 spotLightM = glm::translate(spotLightPos);
            glm::mat4 spotLightMVP = vp * spotLightM;

            glBindTexture(GL_TEXTURE_2D, blueTexture);
            glBindVertexArray(sphereVAO);
            glUniformMatrix4fv(uniformMVP, 1, GL_FALSE, &spotLightMVP[0][0]);
            glUniformMatrix4fv(uniformM, 1, GL_FALSE, &spotLightM[0][0]);
            glUniform1f(uniformMaterialSpecularFactor, 1.0f);
            glUniform1f(uniformMaterialSpecularIntensity, 1.0f);
            glUniform3f(uniformMaterialEmission, 0.5f, 0.5f, 0.5f);
            glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, sphereIndicesVBO);
            glDrawElements(GL_TRIANGLES, sphereIndicesNumber, sphereIndexType, nullptr);
        }

        glfwSwapBuffers(window);
        glfwPollEvents();
    }

    return 0;
}
예제 #26
0
int GameWindow::Run(uint32_t frameRate) {
	std::cout << "Running application!" << std::endl;

    //====================================================================INIT of SDL and GLFW
	if (SDL_Init(SDL_INIT_TIMER) < 0) {
		std::cerr << "SDL failed to Init! Aborting!" << std::endl;
		return -1;
	}
	glfwSetErrorCallback(error_callback);
    if(!glfwInit()) {
        std::cerr << "GLFW failed to init! Aborting!" << std::endl;
        exit(EXIT_FAILURE);
    }
    //====================================================================GLFW render window window creation
	glfwDefaultWindowHints();
    glfwWindowHint(GLFW_VISIBLE, GL_FALSE);
    glfwWindowHint(GLFW_RESIZABLE, GL_TRUE);
    glfwWindowHint(GLFW_SAMPLES, m_samples);
    m_renderWindow = glfwCreateWindow(m_width, m_height, m_title, NULL, NULL);
    if (!m_renderWindow) {
		std::cerr << "GLFW window creation failed!" << std::endl;
		glfwTerminate();
		exit(EXIT_FAILURE);
	}
    const GLFWvidmode* vidmode = glfwGetVideoMode(glfwGetPrimaryMonitor()); //Center the renderWindow on the screen
    glfwSetWindowPos(m_renderWindow, (vidmode->width-m_width)/2, (vidmode->height-m_height)/2);
    //=====================================Render window callbacks
    glfwSetWindowSizeCallback(m_renderWindow, window_resize_callback);
    glfwSetKeyCallback(m_renderWindow, window_keyevent_callback);
    //=====================================Thread window
    m_threadWindow = glfwCreateWindow(80, 60, "ThreadWindow", NULL, m_renderWindow);
    if (!m_threadWindow) {
		std::cerr << "GLFW thread window creation failed!" << std::endl;
		glfwDestroyWindow(m_renderWindow);
		glfwTerminate();
		exit(EXIT_FAILURE);
	}
    //====================================================================INIT of GLEW
    glfwMakeContextCurrent(m_renderWindow);

    glewExperimental=true;
    GLenum err = glewInit();
	if(err!=GLEW_OK) {
		std::cerr << "Failed to initialize GLEW!" << glewGetErrorString(err) << std::endl;
		glfwDestroyWindow(m_threadWindow);
		glfwDestroyWindow(m_renderWindow);
		glfwTerminate();
		exit(EXIT_FAILURE);
	}

    //====================================================================GAME INIT and LOOP
	m_game->Init();
	m_game->OnResize(m_width, m_height);
    SDL_Thread* loaderThread = SDL_CreateThread(loadThread, "SmithGame_Loader_thread", NULL);//Making thread
    glfwShowWindow(m_renderWindow);
    uint32_t startMs = SDL_GetTicks();
    uint32_t framesAgo = 0;
    float msPerFrame = 1000.f/frameRate;
	while (!glfwWindowShouldClose(m_renderWindow)) {
        glfwMakeContextCurrent(m_renderWindow);
        UpdateDeltaTime();
		m_game->NextFrame();
		glfwSwapBuffers(m_renderWindow);
		glfwPollEvents();


        framesAgo++;
        uint32_t wantedTime = startMs+((uint32_t)(framesAgo*msPerFrame));
        uint32_t currentTime = SDL_GetTicks();
        if(wantedTime>currentTime)
            SDL_Delay(wantedTime-currentTime);
        if(framesAgo>=frameRate) {
            framesAgo=0;
            startMs+=1000;
        }
	}
	//====================================================================TELL and wait for the loading thread to stop,
    glfwSetWindowShouldClose(m_threadWindow, GL_TRUE);
    int threadReturnValue;
    SDL_WaitThread(loaderThread, &threadReturnValue);
    //====================================================================DESTROY everytning
    m_game->Destroy();
	glfwDestroyWindow(m_threadWindow);
	glfwDestroyWindow(m_renderWindow);
    glfwTerminate();
	SDL_Quit();
    std::cout << "Program end" << std::endl;
	return 0;
}
예제 #27
0
			static void creationHintsDefault(Session&) noexcept
				{return glfwDefaultWindowHints();}
예제 #28
0
파일: main.cpp 프로젝트: levj220/deepspace
int main(void)
{
	GLFWwindow * window;

	/* Initialize the library */
	if (!glfwInit())
	{
		return -1;
	}

	glfwWindowHint(GLFW_STENCIL_BITS, 1);
	glfwDefaultWindowHints();
	const GLFWvidmode *mode;
	GLFWmonitor *monitor = glfwGetPrimaryMonitor();
	mode = glfwGetVideoMode(monitor);

	/* Create a windowed mode window and its OpenGL context */
	window = glfwCreateWindow(mode->width, mode->height, "DeepSpace", NULL,
	NULL);
	if (!window)
	{
		glfwTerminate();
		return -1;
	}

	/* Make the window's context current */
	glfwMakeContextCurrent(window);
	glfwSetWindowSizeCallback(window, &resize);
	glfwSetKeyCallback(window, onKeyPress);

	/* Initialize glew*/
	if (!glewLoad())
	{
		getchar();
		return -1;
	}

	int l = 0;
	glGetIntegerv(GL_ACCUM_ALPHA_BITS, &l);
	printf("Depth: %d\n", l);

	//Set up our OpenGL world*/
	initialize(window);

	double oldTime = glfwGetTime();
	fpsTimer = glfwGetTime();

	/* Loop until the user closes the window */
	while (!glfwWindowShouldClose(window))
	{
		// calculate time elapsed
		double currentTime = glfwGetTime();
		update(currentTime - oldTime);
		oldTime = currentTime;
		/* Render here */
		draw();

		/* Swap front and back buffers */
		glfwSwapBuffers(window);

		/* Poll for and process events */
		glfwPollEvents();
	}

	destroy();
	glfwTerminate();
	return 0;
}
예제 #29
0
int main() {
    if(glfwInit() == GL_FALSE) {
        std::cerr << "Failed to initialize GLFW" << std::endl;
        return -1;
    }
    defer(glfwTerminate());

    glfwDefaultWindowHints();

    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
    glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
    glfwWindowHint(GLFW_SAMPLES, 4);

    GLFWwindow* window = glfwCreateWindow(800, 600, "Models", nullptr, nullptr);
    if(window == nullptr) {
        std::cerr << "Failed to open GLFW window" << std::endl;
        return -1;
    }
    defer(glfwDestroyWindow(window));

    glfwMakeContextCurrent(window);

    if(glxwInit()) {
        std::cerr << "Failed to init GLXW" << std::endl;
        return -1;
    }

    glfwSwapInterval(1);
    glfwSetWindowSizeCallback(window, windowSizeCallback);
    glfwShowWindow(window);

    bool errorFlag = false;
    std::vector<GLuint> shaders;

    GLuint vertexShaderId = loadShader("shaders/vertexShader.glsl", GL_VERTEX_SHADER, &errorFlag);
    if(errorFlag) {
        std::cerr << "Failed to load vertex shader (invalid working directory?)" << std::endl;
        return -1;
    }

    shaders.push_back(vertexShaderId);

    GLuint fragmentShaderId = loadShader("shaders/fragmentShader.glsl", GL_FRAGMENT_SHADER, &errorFlag);
    if(errorFlag) {
        std::cerr << "Failed to load fragment shader (invalid working directory?)" << std::endl;
        return -1;
    }
    shaders.push_back(fragmentShaderId);

    GLuint programId = prepareProgram(shaders, &errorFlag);
    if(errorFlag) {
        std::cerr << "Failed to prepare program" << std::endl;
        return -1;
    }
    defer(glDeleteProgram(programId));

    glDeleteShader(vertexShaderId);
    glDeleteShader(fragmentShaderId);

    // === prepare textures ===
    GLuint textureArray[3];
    int texturesNum = sizeof(textureArray)/sizeof(textureArray[0]);
    glGenTextures(texturesNum, textureArray);
    defer(glDeleteTextures(texturesNum, textureArray));

    GLuint grassTexture = textureArray[0];
    GLuint skyboxTexture = textureArray[1];
    GLuint towerTexture = textureArray[2];

    if(!loadDDSTexture("textures/grass.dds", grassTexture)) return -1;

    if(!loadDDSTexture("textures/skybox.dds", skyboxTexture)) return -1;
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);

    if(!loadDDSTexture("textures/tower.dds", towerTexture)) return -1;

    // === prepare VAOs ===
    GLuint vaoArray[3];
    int vaosNum = sizeof(vaoArray)/sizeof(vaoArray[0]);
    glGenVertexArrays(vaosNum, vaoArray);
    defer(glDeleteVertexArrays(vaosNum, vaoArray));

    GLuint grassVAO = vaoArray[0];
    GLuint skyboxVAO = vaoArray[1];
    GLuint towerVAO = vaoArray[2];

    // === prepare VBOs ===
    GLuint vboArray[6];
    int vbosNum = sizeof(vboArray)/sizeof(vboArray[0]);
    glGenBuffers(vbosNum, vboArray);
    defer(glDeleteBuffers(vbosNum, vboArray));

    GLuint grassVBO = vboArray[0];
    GLuint skyboxVBO = vboArray[1];
    GLuint towerVBO = vboArray[2];
    GLuint grassIndicesVBO = vboArray[3];
    GLuint skyboxIndicesVBO = vboArray[4];
    GLuint towerIndicesVBO = vboArray[5];

    // === load models ===

    GLsizei grassIndicesNumber, skyboxIndicesNumber, towerIndicesNumber;
    GLenum grassIndexType, skyboxIndexType, towerIndexType;
    if(!modelLoad("models/grass.emd", grassVAO, grassVBO, grassIndicesVBO, &grassIndicesNumber, &grassIndexType)) return -1;
    if(!modelLoad("models/skybox.emd", skyboxVAO, skyboxVBO, skyboxIndicesVBO, &skyboxIndicesNumber, &skyboxIndexType)) return -1;
    if(!modelLoad("models/tower.emd", towerVAO, towerVBO, towerIndicesVBO, &towerIndicesNumber, &towerIndexType)) return -1;

    glm::mat4 projection = glm::perspective(70.0f, 4.0f / 3.0f, 0.3f, 250.0f);

    GLint matrixId = glGetUniformLocation(programId, "MVP");
    GLint samplerId = glGetUniformLocation(programId, "textureSampler");

    auto startTime = std::chrono::high_resolution_clock::now();
    auto prevTime = startTime;

    glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED); // hide cursor

    Camera camera(window, glm::vec3(0, 0, 5), 3.14f /* toward -Z */, 0.0f /* look at the horizon */);

    glEnable(GL_DOUBLEBUFFER);
    glEnable(GL_CULL_FACE);
    glEnable(GL_MULTISAMPLE);
    glEnable(GL_DEPTH_TEST);
    glDepthFunc(GL_LESS);

    glClearColor(0, 0, 0, 1);

    glUniform1i(samplerId, 0);

    while(glfwWindowShouldClose(window) == GL_FALSE) {
        if(glfwGetKey(window, GLFW_KEY_Q) == GLFW_PRESS) break;

        if(glfwGetKey(window, GLFW_KEY_Z) == GLFW_PRESS) {
            glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
        }

        if(glfwGetKey(window, GLFW_KEY_X) == GLFW_PRESS) {
            glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
        }

        auto currentTime = std::chrono::high_resolution_clock::now();
        float startDeltaTimeMs = std::chrono::duration_cast<std::chrono::milliseconds>(currentTime - startTime).count();
        float prevDeltaTimeMs = std::chrono::duration_cast<std::chrono::milliseconds>(currentTime - prevTime).count();
        prevTime = currentTime;

        float rotationTimeMs = 100000.0f;
        float currentRotation = startDeltaTimeMs / rotationTimeMs;
        float islandAngle = 360.0f*(currentRotation - (long)currentRotation);

        glm::mat4 view;
        camera.getViewMatrix(prevDeltaTimeMs, &view);
        glm::mat4 vp = projection * view;

        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

        glUseProgram(programId);

        glm::mat4 towerMVP = vp * glm::rotate(islandAngle, 0.0f, 1.0f, 0.0f) * glm::translate(-1.5f, -1.0f, -1.5f);

        glBindTexture(GL_TEXTURE_2D, towerTexture);
        glBindVertexArray(towerVAO);
        glUniformMatrix4fv(matrixId, 1, GL_FALSE, &towerMVP[0][0]);
        glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, towerIndicesVBO);
        glDrawElements(GL_TRIANGLES, towerIndicesNumber, towerIndexType, nullptr);

        glm::mat4 grassMVP = vp * glm::rotate(islandAngle, 0.0f, 1.0f, 0.0f) * glm::translate(0.0f, -1.0f, 0.0f);

        glBindTexture(GL_TEXTURE_2D, grassTexture);
        glBindVertexArray(grassVAO);
        glUniformMatrix4fv(matrixId, 1, GL_FALSE, &grassMVP[0][0]);
        glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, grassIndicesVBO);
        glDrawElements(GL_TRIANGLES, grassIndicesNumber, grassIndexType, nullptr);

        glm::vec3 cameraPos;
        camera.getPosition(&cameraPos);
        glm::mat4 skyboxMatrix = glm::translate(cameraPos) * glm::scale(100.0f,100.0f,100.0f);
        glm::mat4 skyboxMVP = vp * skyboxMatrix;

        // TODO: implement modelDraw procedure (or maybe Model object?)
        glBindTexture(GL_TEXTURE_2D, skyboxTexture);
        glBindVertexArray(skyboxVAO);
        glUniformMatrix4fv(matrixId, 1, GL_FALSE, &skyboxMVP[0][0]);
        glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, skyboxIndicesVBO);
        glDrawElements(GL_TRIANGLES, skyboxIndicesNumber, skyboxIndexType, nullptr);

        glfwSwapBuffers(window);
        glfwPollEvents();
    }

    return 0;
}
예제 #30
0
int main()
{
    GLFWwindow *window;
    char *userptr = "userptr";

    glfwSetErrorCallback(errorcb);
    assert(glfwInit() == GL_TRUE);
    assert(!strcmp(glfwGetVersionString(), "3.2.1 JS WebGL Emscripten"));
    assert(glfwGetCurrentContext() == NULL);

    {
        int major, minor, rev;
        glfwGetVersion(&major, &minor, &rev);
        assert(major == 3);
        assert(minor == 2);
        assert(rev == 1);
    }

    {
        int count, x, y, w, h;
        GLFWmonitor **monitors = glfwGetMonitors(&count);
        assert(count == 1);
        for (int i = 0; i < count; ++i) {
            assert(monitors[i] != NULL);
        }

        assert(glfwGetPrimaryMonitor() != NULL);
        glfwGetMonitorPos(monitors[0], &x, &y);
        glfwGetMonitorPhysicalSize(monitors[0], &w, &h);
        assert(glfwGetMonitorName(monitors[0]) != NULL);
        glfwSetMonitorCallback(monitcb);

        // XXX: not implemented
        // assert(glfwGetVideoModes(monitors[0], &count) != NULL);
        // assert(glfwGetVideoMode(monitors[0]) != NULL);
        // glfwSetGamma(monitors[0], 1.0f);
        // assert(glfwGetGammaRamp(monitors[0]) != NULL);
        // glfwSetGammaRamp(monitors[0], ramp);
    }

    {
        int x, y, w, h;
        glfwDefaultWindowHints();
        glfwWindowHint(GLFW_CLIENT_API, GLFW_OPENGL_ES_API);

        window = glfwCreateWindow(640, 480, "glfw3.c", NULL, NULL);
        assert(window != NULL);

        glfwSetWindowPosCallback(window, wposicb);
        glfwSetWindowSizeCallback(window, wsizecb);
        glfwSetWindowCloseCallback(window, wcloscb);
        glfwSetWindowRefreshCallback(window, wrfrscb);
        glfwSetWindowFocusCallback(window, wfocucb);
        glfwSetWindowIconifyCallback(window, wiconcb);
        glfwSetFramebufferSizeCallback(window, wfsizcb);

        assert(glfwWindowShouldClose(window) == 0);
        glfwSetWindowShouldClose(window, 1);
        assert(glfwWindowShouldClose(window) == 1);

        glfwSetWindowTitle(window, "test");
        glfwSetWindowTitle(window, "glfw3.c");

        // XXX: not implemented
        // glfwSetWindowPos(window, 1, 1);

        glfwGetWindowPos(window, &x, &y); // stub
        glfwGetWindowSize(window, &w, &h);
        assert(w == 640 && h == 480);

        glfwSetWindowSize(window, 1, 1);
        glfwGetWindowSize(window, &w, &h);
        assert(w == 1 && h == 1);

        glfwSetWindowSize(window, 640, 480);
        glfwGetFramebufferSize(window, &w, &h);

        // XXX: not implemented
        // glfwIconifyWindow(window);
        // glfwRestoreWindow(window);
        // glfwShowWindow(window);
        // glfwHideWindow(window);

        assert(glfwGetWindowMonitor(window) == NULL);
        glfwDestroyWindow(window);

        window = glfwCreateWindow(640, 480, "glfw3.c", glfwGetPrimaryMonitor(), NULL);
        assert(window != NULL);
        assert(glfwGetWindowMonitor(window) == glfwGetPrimaryMonitor());
        glfwDestroyWindow(window);

        window = glfwCreateWindow(640, 480, "glfw3.c", NULL, NULL);
        assert(window != NULL);

        assert(glfwGetWindowAttrib(window, GLFW_CLIENT_API) == GLFW_OPENGL_ES_API);

        assert(glfwGetWindowUserPointer(window) == NULL);
        glfwSetWindowUserPointer(window, userptr);
        assert(glfwGetWindowUserPointer(window) == userptr);
    }

    {
        double x, y;

        glfwSetKeyCallback(window, wkeypcb);
        glfwSetCharCallback(window, wcharcb);
        glfwSetMouseButtonCallback(window, wmbutcb);
        glfwSetCursorPosCallback(window, wcurpcb);
        glfwSetCursorEnterCallback(window, wcurecb);
        glfwSetScrollCallback(window, wscrocb);

        // XXX: stub, events come immediatly
        // glfwPollEvents();
        // glfwWaitEvents();

        assert(glfwGetInputMode(window, GLFW_CURSOR) == GLFW_CURSOR_NORMAL);

        // XXX: not implemented
        // glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_HIDDEN);

        glfwGetKey(window, GLFW_KEY_A);
        glfwGetMouseButton(window, 0);
        glfwGetCursorPos(window, &x, &y);

        // XXX: not implemented
        // glfwSetCursorPos(window, 0, 0);
    }

    {
        // XXX: not implemented
        // glfwJoystickPresent(joy);
        // glfwGetJoystickAxes(joy, &count);
        // glfwGetJoystickButtons(joy, &count);
        // glfwGetJoystickName(joy);
    }

    {
        // XXX: not implemented
        // glfwSetClipboardString(window, "string");
        // glfwGetClipboardString(window);
    }

    {
        glfwGetTime();
        glfwSetTime(0);
    }

    {
        glfwMakeContextCurrent(window); // stub
        assert(glfwGetCurrentContext() == window);
        glfwSwapBuffers(window); // stub
        glfwSwapInterval(0); // stub
    }

    {
        assert(glfwExtensionSupported("nonexistant") == 0);
        assert(glfwGetProcAddress("nonexistant") == NULL);
    }

    glfwTerminate();

#ifdef REPORT_RESULT
    REPORT_RESULT(1);
#endif
    return 0;
}