Esempio n. 1
0
result_t app_init(const char* name, const struct init_params* params)
{
    ASSERT(g_app == NULL);
    if (g_app != NULL)  {
        err_print(__FILE__, __LINE__, "application already initialized");
        return RET_FAIL;
    }

    /* create application */
    log_print(LOG_TEXT, "init OpenGL app ...");

    struct app_gl* app = (struct app_gl*)ALLOC(sizeof(struct app_gl), 0);
    ASSERT(app);
    memset(app, 0x00, sizeof(struct app_gl));
    g_app = app;

    input_zero();

    str_safecpy(app->name, sizeof(app->name), name);

    uint width = params->gfx.width;
    uint height = params->gfx.height;
    if (width == 0)
        width = DEFAULT_WIDTH;
    if (height == 0)
        height = DEFAULT_HEIGHT;

    /* initialize glfw */
    if (!glfwInit())    {
        err_print(__FILE__, __LINE__, "gl-app init failed: could not init glfw");
        return RET_FAIL;
    }

    /* create main window */
    int major, minor;
    glfwSetErrorCallback(glfw_error_callback);
    glfwDefaultWindowHints();
    glfwWindowHint(GLFW_VISIBLE, GL_FALSE);

    /* construct GL version for context creation */
    app_convert_gfxver(params->gfx.hwver, &major, &minor);
    if (major != INT32_MAX && minor != INT32_MAX)   {
        // glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
        glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
        glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, major);
        glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, minor);
    }
    if (BIT_CHECK(params->gfx.flags, GFX_FLAG_DEBUG))
        glfwWindowHint(GLFW_OPENGL_DEBUG_CONTEXT, GL_TRUE);

    log_print(LOG_INFO, "  init OpenGL context and window ...");

    GLFWmonitor* mon = BIT_CHECK(params->gfx.flags, GFX_FLAG_FULLSCREEN) ? 
        glfwGetPrimaryMonitor() : NULL;

    GLFWwindow* wnd = glfwCreateWindow((int)width, (int)height, name, mon, NULL);
    if (wnd == NULL) {
        err_print(__FILE__, __LINE__, "create window/context failed");
        return RET_FAIL;
    }
    app->wnd = wnd;

    /* callbacks */
    glfwSetFramebufferSizeCallback(wnd, glfw_window_resize);
    glfwSetWindowCloseCallback(wnd, glfw_window_close);
    glfwSetWindowFocusCallback(wnd, glfw_window_focus);
    glfwSetCharCallback(wnd, glfw_window_char);
    glfwSetKeyCallback(wnd, glfw_window_keypress);
    glfwSetMouseButtonCallback(wnd, glfw_window_mousebtn);
    glfwSetCursorPosCallback(wnd, glfw_window_mousepos);

    glfwMakeContextCurrent(wnd);
    glfwSwapInterval(BIT_CHECK(params->gfx.flags, GFX_FLAG_VSYNC) ? 1 : 0);

    str_safecpy(app->name, sizeof(app->name), name);
    g_app->wnd = wnd;
    app->width = width;
    app->height = height;
    app->always_active = TRUE;
    app->refresh_rate = params->gfx.refresh_rate;

    /* initialize input system */
    input_init();

    app->init = TRUE;
    return RET_OK;
}
Esempio n. 2
0
GLFWView::GLFWView(bool fullscreen_, bool benchmark_)
    : fullscreen(fullscreen_), benchmark(benchmark_) {
    glfwSetErrorCallback(glfwError);

    std::srand(std::time(0));

    if (!glfwInit()) {
        mbgl::Log::Error(mbgl::Event::OpenGL, "failed to initialize glfw");
        exit(1);
    }

    GLFWmonitor *monitor = nullptr;
    if (fullscreen) {
        monitor = glfwGetPrimaryMonitor();
        auto videoMode = glfwGetVideoMode(monitor);
        width = videoMode->width;
        height = videoMode->height;
    }

#ifdef DEBUG
    glfwWindowHint(GLFW_OPENGL_DEBUG_CONTEXT, GL_TRUE);
#endif

#ifdef GL_ES_VERSION_2_0
    glfwWindowHint(GLFW_CLIENT_API, GLFW_OPENGL_ES_API);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 2);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 0);
#endif

    glfwWindowHint(GLFW_RED_BITS, 8);
    glfwWindowHint(GLFW_GREEN_BITS, 8);
    glfwWindowHint(GLFW_BLUE_BITS, 8);
    glfwWindowHint(GLFW_ALPHA_BITS, 8);
    glfwWindowHint(GLFW_STENCIL_BITS, 8);
    glfwWindowHint(GLFW_DEPTH_BITS, 16);

    window = glfwCreateWindow(width, height, "Mapbox GL", monitor, NULL);
    if (!window) {
        glfwTerminate();
        mbgl::Log::Error(mbgl::Event::OpenGL, "failed to initialize window");
        exit(1);
    }

    glfwSetWindowUserPointer(window, this);
    glfwMakeContextCurrent(window);
    if (benchmark) {
        // Disables vsync on platforms that support it.
        glfwSwapInterval(0);
    } else {
        glfwSwapInterval(1);
    }


    glfwSetCursorPosCallback(window, onMouseMove);
    glfwSetMouseButtonCallback(window, onMouseClick);
    glfwSetWindowSizeCallback(window, onWindowResize);
    glfwSetFramebufferSizeCallback(window, onFramebufferResize);
    glfwSetScrollCallback(window, onScroll);
    glfwSetKeyCallback(window, onKey);

    mbgl::gl::InitializeExtensions(glfwGetProcAddress);

    glfwGetWindowSize(window, &width, &height);
    glfwGetFramebufferSize(window, &fbWidth, &fbHeight);
    pixelRatio = static_cast<float>(fbWidth) / width;

    glfwMakeContextCurrent(nullptr);

    printf("\n");
    printf("================================================================================\n");
    printf("\n");
    printf("- Press `S` to cycle through bundled styles\n");
    printf("- Press `X` to reset the transform\n");
    printf("- Press `N` to reset north\n");
    printf("- Press `R` to toggle any available `night` style class\n");
    printf("- Press `Z` to cycle through north orientations\n");
    printf("- Prezz `X` to cycle through the viewport modes\n");
    printf("- Press `A` to cycle through Mapbox offices in the world + dateline monument\n");
    printf("\n");
    printf("- Press `1` through `6` to add increasing numbers of point annotations for testing\n");
    printf("- Press `7` through `0` to add increasing numbers of shape annotations for testing\n");
    printf("\n");
    printf("- Press `Q` to remove annotations\n");
    printf("- Press `P` to add a random custom runtime imagery annotation\n");
    printf("- Press `W` to pop the last-added annotation off\n");
    printf("\n");
    printf("- `Control` + mouse drag to rotate\n");
    printf("- `Shift` + mouse drag to tilt\n");
    printf("\n");
    printf("- Press `Tab` to cycle through the map debug options\n");
    printf("- Press `Esc` to quit\n");
    printf("\n");
    printf("================================================================================\n");
    printf("\n");
}
Esempio n. 3
0
int main(int argc, const char * argv[]) {
    
    // Initialize glfw
    if (!glfwInit()){
        std::cerr << "Failed to initialize glfw" << std::endl;
        exit(EXIT_FAILURE);
    }
    
    // Set the error callback for glfw
    glfwSetErrorCallback(error_callback);
    
    // Set window settings
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2);
    glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
    
    glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);
    
    GLFWwindow *window = glfwCreateWindow(800,600, "OpenGL Renderer", NULL, NULL);
    
    if (!window) {
        std::cerr << "Could not create glfw window!" << std::endl;
        glfwTerminate();
        exit(EXIT_FAILURE);
    }
    glfwMakeContextCurrent(window);
    glfwSwapInterval(1);
    
    glfwSetKeyCallback(window, key_callback);
    glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);
    
    int width, height;
    glfwGetFramebufferSize(window, &width, &height);
    glViewport(0, 0, width, height);
    float ratio = width / (float) height;
    
    Camera cam(glm::vec3(0,0,-2));
    cam.setProjMatrix(ratio);
    
    DefaultMaterial m(glm::vec3(.2f,.2f,.9f));
    
    MeshObject cube;
    cube.setMaterial(&m);
    
    SceneNode cubeNode(&cube);
    cubeNode.setTransform(glm::scale(glm::mat4(), glm::vec3(2)));
    
    double lastFrameTime = glfwGetTime();
    double xpos, ypos;
    
    while (!glfwWindowShouldClose(window)) {
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
        
        double currentFrameTime = glfwGetTime();
        
        double delta = currentFrameTime - lastFrameTime;
        
        lastFrameTime = currentFrameTime;
        
        cam.translate(glm::vec3(delta * camXSpeed, delta * camYSpeed, delta * camZSpeed));
        
        glfwGetCursorPos(window, &xpos, &ypos);
        
        // Cursor rotation is currently broken.
        //cam.rotateFromCursor(2*xpos/width - 1, 2*ypos/height - 1);
        
        cubeNode.render(window, cam.getViewMatrix(), cam.getProjMatrix());
        
        glfwSwapBuffers(window);
        glfwPollEvents();
    }
    
    glfwDestroyWindow(window);
    glfwTerminate();
    return 0;
}
Esempio n. 4
0
int main(int argc, char** argv)
{
#if defined(_WIN32)
	// Enable memory-leak reports
	_CrtSetDbgFlag(_CRTDBG_LEAK_CHECK_DF | _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG));
#endif

    g_camera.m_width = 1024;
    g_camera.m_height = 640;
    
	if (glfwInit() == 0)
	{
		fprintf(stderr, "Failed to initialize GLFW\n");
		return -1;
	}

	char title[64];
	sprintf(title, "Box2D Testbed Version %d.%d.%d", b2_version.major, b2_version.minor, b2_version.revision);

#if defined(__APPLE__)
	// Not sure why, but these settings cause glewInit below to crash.
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 0);
    glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
#endif

    mainWindow = glfwCreateWindow(g_camera.m_width, g_camera.m_height, title, NULL, NULL);
	if (mainWindow == NULL)
	{
		fprintf(stderr, "Failed to open GLFW mainWindow.\n");
		glfwTerminate();
		return -1;
	}

	glfwMakeContextCurrent(mainWindow);
	printf("OpenGL %s, GLSL %s\n", glGetString(GL_VERSION), glGetString(GL_SHADING_LANGUAGE_VERSION));

	glfwSetScrollCallback(mainWindow, sScrollCallback);
	glfwSetWindowSizeCallback(mainWindow, sResizeWindow);
	glfwSetKeyCallback(mainWindow, sKeyCallback);
	glfwSetMouseButtonCallback(mainWindow, sMouseButton);
	glfwSetCursorPosCallback(mainWindow, sMouseMotion);
	glfwSetScrollCallback(mainWindow, sScrollCallback);

#if defined(__APPLE__) == FALSE
	//glewExperimental = GL_TRUE;
    GLenum err = glewInit();
	if (GLEW_OK != err)
	{
		fprintf(stderr, "Error: %s\n", glewGetErrorString(err));
		exit(EXIT_FAILURE);
	}
#endif
    
	g_debugDraw.Create();

	sCreateUI();

	testCount = 0;
	while (g_testEntries[testCount].createFcn != NULL)
	{
		++testCount;
	}

	testIndex = b2Clamp(testIndex, 0, testCount - 1);
	testSelection = testIndex;

	entry = g_testEntries + testIndex;
	test = entry->createFcn();

	// Control the frame rate. One draw per monitor refresh.
	glfwSwapInterval(1);

    double time1 = glfwGetTime();
    double frameTime = 0.0;
   
    glClearColor(0.3f, 0.3f, 0.3f, 1.f);
	
 	while (!glfwWindowShouldClose(mainWindow))
	{
 		glfwGetWindowSize(mainWindow, &g_camera.m_width, &g_camera.m_height);
		glViewport(0, 0, g_camera.m_width, g_camera.m_height);

		glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

		unsigned char mousebutton = 0;
		int mscroll = ui.scroll;
		ui.scroll = 0;

		double xd, yd;
		glfwGetCursorPos(mainWindow, &xd, &yd);
		int mousex = int(xd);
		int mousey = int(yd);

		mousey = g_camera.m_height - mousey;
		int leftButton = glfwGetMouseButton(mainWindow, GLFW_MOUSE_BUTTON_LEFT);
		if (leftButton == GLFW_PRESS)
			mousebutton |= IMGUI_MBUT_LEFT;

		imguiBeginFrame(mousex, mousey, mousebutton, mscroll);

		sSimulate();
		sInterface();
        
        // Measure speed
        double time2 = glfwGetTime();
        double alpha = 0.9f;
        frameTime = alpha * frameTime + (1.0 - alpha) * (time2 - time1);
        time1 = time2;

        char buffer[32];
        snprintf(buffer, 32, "%.1f ms", 1000.0 * frameTime);
        AddGfxCmdText(5, 5, TEXT_ALIGN_LEFT, buffer, WHITE);
        
		glEnable(GL_BLEND);
		glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
		glDisable(GL_DEPTH_TEST);
		RenderGLFlush(g_camera.m_width, g_camera.m_height);

		glfwSwapBuffers(mainWindow);

		glfwPollEvents();
	}

	g_debugDraw.Destroy();
	RenderGLDestroy();
	glfwTerminate();

	return 0;
}
Esempio n. 5
0
int main(int argc, char* argv[])
{
  app_argc = argc;
  app_argv = argv;
  int     width, height, running, frames, x, y;
  double  t, t1;
  char    titlestr[ 200 ];

  // Initialise GLFW
  glfwInit();

  bool start_fullscreen = false;
  int x_res = 1280;
  int y_res = 720;
  bool manual_resolution_set = false;
  for (int i = 1; i < argc; i++)
  {
    vsx_string arg1 = argv[i];
    if (arg1 == "--help" || arg1 == "/?" || arg1 == "-help" || arg1 == "-?")
    {
      printf(
             "Usage:\n"
          "  vsxu_player [path_to_vsx_file]\n"
          "\n"
          "Flags: \n"
          "  -pl        Preload all visuals on start \n"
          "  -dr        Disable randomizer     \n"
          "  -p [x,y]   Set window position x,y \n"
          "  -s [x,y]   Set window size x,y \n\n\n"
            );
      exit(0);
    } else
    if (arg1 == "-f") {
      start_fullscreen = true;
    } else
    if (arg1 == "-pl") {
      option_preload_all = true;
    } else
    if (arg1 == "-dr") {
      disable_randomizer = true;
    } else
    if (arg1 == "-no") {
      no_overlay = true;
    } else
    if (arg1 == "-s")
    {
      if (i+1 < argc)
      {
        i++;
        vsx_string arg2 = argv[i];
        vsx_avector<vsx_string> parts;
        vsx_string deli = ",";
        explode(arg2, deli, parts);
        if (parts.size() == 2)
        {
          x_res = vsx_string_helper::s2i(parts[0]);
          y_res = vsx_string_helper::s2i(parts[1]);
          manual_resolution_set = true;
        } else
        {
          deli = "x";
          explode(arg2, deli, parts);
          if ( parts.size() == 2 )
          {
            x_res = vsx_string_helper::s2i(parts[0]);
            y_res = vsx_string_helper::s2i(parts[1]);
            manual_resolution_set = true;
          }
        }
      }
    }
  }
  if (start_fullscreen && !manual_resolution_set)
  {
    // try to get the resolution from the desktop for fullscreen
    GLFWvidmode video_mode;
    glfwGetDesktopMode(&video_mode);
    x_res = video_mode.Height;
    y_res = video_mode.Width;
  }
  
  // Open OpenGL window
  glfwOpenWindowHint(GLFW_FSAA_SAMPLES, 4);
  if( !glfwOpenWindow( x_res, y_res, 0,0,0,0,16,0, start_fullscreen?GLFW_FULLSCREEN:GLFW_WINDOW ) ) // GLFW_FULLSCREEN
  {
    printf("Error! Could not create an OpenGL context. Please check your GPU drivers...\n");
    glfwTerminate();
    return 0;
  }
  if (start_fullscreen) glfwEnable( GLFW_MOUSE_CURSOR );
  app_init(0);

  glfwEnable(GLFW_AUTO_POLL_EVENTS);

  for (int i = 1; i < argc; i++) {
    vsx_string arg1 = argv[i];
    if (arg1 == "-p") {
      if (i+1 < argc)
      {
        i++;
        vsx_string arg2 = argv[i];
        vsx_avector<vsx_string> parts;
        vsx_string deli = ",";
        explode(arg2, deli, parts);
        glfwSetWindowPos( vsx_string_helper::s2i(parts[0]), vsx_string_helper::s2i(parts[1]) );
      }
    }
  }

  glfwSetKeyCallback(&key_event);
  glfwSetMouseButtonCallback(&mouse_button_event);
  glfwSetMousePosCallback(&mouse_pos_event);
  glfwSetCharCallback(&key_char_event);
  glfwSetMouseWheelCallback(&mouse_wheel);
  // set window size callback function
  glfwSetWindowSizeCallback(window_size);

  // Enable sticky keys
  glfwEnable( GLFW_STICKY_KEYS );
  glfwSwapInterval(1);

  // Main loop
  running = GL_TRUE;
  frames = 0;

  #if PLATFORM_FAMILY == PLATFORM_FAMILY_UNIX
    sprintf( titlestr, "Vovoid VSXu Player %s [GNU/Linux %d-bit]", vsxu_ver, PLATFORM_BITS);
  #endif
  #if PLATFORM_FAMILY == PLATFORM_FAMILY_WINDOWS
    sprintf( titlestr, "Vovoid VSXu Player %s [Windows %d-bit]", vsxu_ver, PLATFORM_BITS);
  #endif
  glfwSetWindowTitle( titlestr );


  while( running )
  {
    if (mouse_pos_type)
    {
      if (mouse_pos_type == 1) app_mouse_move(last_x,last_y);
      else app_mouse_move_passive(last_x,last_y);
      mouse_pos_type = 0;
    }

    app_pre_draw();

    // Get time and mouse position
    t = glfwGetTime();
    glfwGetMousePos( &x, &y );
    float delta = t-t1;
    t1 = t;
    if (key_pressed != -1)
    {
          //printf("%f\n", delta);
      key_time += delta;
      if (key_time > 0.3f)
      {
        key_repeat_time += delta;
        if (key_repeat_time > initial_key_delay)
        {
          key_repeat_time = 0.0f;
          if (key_character != -1)
            app_char(key_character);
          app_key_down((long)key_pressed);
          initial_key_delay *= 0.99f;
              //printf("repeating key: %d\n", key_character);
        }
      }
    }
    frames ++;

    // Get window size (may be different than the requested size)
    glfwGetWindowSize( &width, &height );
    height = height > 0 ? height : 1;

    // Set viewport
    vsx_gl_state::get_instance()->viewport_set( 0, 0, width, height );

    // Clear color buffer
    glClearColor( 0.0f, 0.0f, 0.0f, 0.0f );
    glClear( GL_COLOR_BUFFER_BIT );
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();

    app_draw(0);

    glfwSwapBuffers();

    // Check if the ESC key was pressed or the window was closed
    running = /*!glfwGetKey( GLFW_KEY_ESC ) &&*/
    glfwGetWindowParam( GLFW_OPENED );
  }

  // Close OpenGL window and terminate GLFW
  glfwTerminate();

  return 0;
}
void main()
{
	glfwInit();

	// Create a window
	window = glfwCreateWindow(800, 800, "Decoupling Intersecting Objects (Circle - 2D)", nullptr, nullptr);
	glfwMakeContextCurrent(window);
	glfwSwapInterval(0);

	// Initializes most things needed before the main loop
	init();


	//Generate the circle mesh
	float circleScale = 0.15f;
	int numVertices = 72;
	struct Vertex circleVerts[72];
	float stepSize = 2.0f * 3.14159 / (numVertices/3.0f);
	int vertexNumber = 0;
	for (int i = 0; i < numVertices; i++)
	{
		circleVerts[i].x = cosf(vertexNumber * stepSize);
		circleVerts[i].y = sinf(vertexNumber * stepSize);
		circleVerts[i].z = 0.0f;
		circleVerts[i].r = 1.0f;
		circleVerts[i].g = 1.0f;
		circleVerts[i].b = 0.0f;
		circleVerts[i].a = 1.0;
		++i;
		++vertexNumber;
		circleVerts[i].x = cosf(vertexNumber * stepSize);
		circleVerts[i].y = sinf(vertexNumber * stepSize);
		circleVerts[i].z = 0.0f;
		circleVerts[i].r = 1.0f;
		circleVerts[i].g = 1.0f;
		circleVerts[i].b = 0.0f;
		circleVerts[i].a = 1.0f;
		++i;
		circleVerts[i].x = 0.0f;
		circleVerts[i].y = 0.0f;
		circleVerts[i].z = 0.0f;
		circleVerts[i].r = 1.0f;
		circleVerts[i].g = 1.0f;
		circleVerts[i].b = 0.0f;
		circleVerts[i].a = 1.0f;
	}

	//circle1 creation
	circle1 = new struct Mesh(numVertices, circleVerts, GL_TRIANGLES);
	//Alter mesh for circle2
	for (int i = 0; i < numVertices; i++)
	{
		circleVerts[i].g = 0.0f;
		circleVerts[i].b = 1.0f;
	}
	//Circle2 creation
	circle2 = new struct Mesh(numVertices, circleVerts, GL_TRIANGLES);


	//Scale the circles
	circle1->scale = glm::scale(circle1->scale, glm::vec3(circleScale));
	circle2->scale = glm::scale(circle2->scale, glm::vec3(circleScale));

	//Generate the circles colliders
	circle1Collider = new Circle(glm::vec3(-0.75f, 0.0f, 0.2f), circleScale);
	circle2Collider = new Circle(glm::vec3(0.75f, 0.0f, 0.2f), circleScale);

	selectedCollider = circle1Collider;


	//Position circles
	circle1->translation = glm::translate(circle1->translation, circle1Collider->center);
	circle2->translation = glm::translate(circle2->translation, circle2Collider->center);

	//Print controls
	std::cout << "Controls:\nUse WASD to move the selected circle around the XY plane.\n";
	std::cout << "Press spacebar to swap the selected circle.\n";

	// Enter the main loop.
	while (!glfwWindowShouldClose(window))
	{
		//Check time will update the programs clock and determine if & how many times the physics must be updated
		checkTime();

		// Call the render function.
		renderScene();

		// Swaps the back buffer to the front buffer
		// Remember, you're rendering to the back buffer, then once rendering is complete, you're moving the back buffer to the front so it can be displayed.
		glfwSwapBuffers(window);

		// Checks to see if any events are pending and then processes them.
		glfwPollEvents();
	}

	// After the program is over, cleanup your data!
	glDeleteShader(vertex_shader);
	glDeleteShader(fragment_shader);
	glDeleteProgram(program);
	// Note: If at any point you stop using a "program" or shaders, you should free the data up then and there.

	delete circle1;
	delete circle2;
	delete circle1Collider;
	delete circle2Collider;

	// Frees up GLFW memory
	glfwTerminate();
}
Esempio n. 7
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;
}
Esempio n. 8
0
int main(int argc, char* argv[])
{
    if (argc >= 2) {
        g_maxdepth = atoi(argv[1]);
        g_maxdepth = (g_maxdepth == 0 ? 50 : g_maxdepth);

        if (g_maxdepth >= 5) {
            g_rrdepth = g_maxdepth * 6 / 10;
        }
    }
    if (argc >= 3) {
        g_samplenum = atoi(argv[2]);
        g_samplenum = (g_samplenum == 0 ? 10 : g_samplenum);
    }

    timer::init();

    ::glfwSetErrorCallback(errorCallback);

    auto result = ::glfwInit();
    if (!result) {
        assert(false);
        return 1;
    }

    ::glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 2);
    ::glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 0);

    auto window = ::glfwCreateWindow(
        WIDTH,
        HEIGHT,
        TITLE,
        NULL, NULL);

    if (!window) {
        ::glfwTerminate();
        assert(false);
        return 1;
    }

#if 0
    ::glfwSetWindowCloseCallback(
        window,
        closeCallback);

    ::glfwSetKeyCallback(
        window,
        keyCallback);

    ::glfwSetMouseButtonCallback(
        window,
        mouseCallback);

    ::glfwSetCursorPosCallback(
        window,
        motionCallback);

    ::glfwSetScrollCallback(
        window,
        wheelCallback);
#endif

    glfwMakeContextCurrent(window);
    glfwSwapInterval(1);

    SetCurrentDirectoryFromExe();

    // TODO
    Rand::Init(0);

    auto world = cornell_box();

    vec3 lookfrom(278, 278, -800);
    vec3 lookat(278, 278, 0);

    float dist_to_focus = 10.0;
    float aperture = 0.1;

    camera cam(
        lookfrom, 
        lookat, 
        vec3(0, 1, 0), 
        40,                     // vfov
        float(nx) / float(ny),  // aspect
        aperture, 
        dist_to_focus);

    Init();

#ifdef USE_OPENMP
    omp_set_num_threads(thread_num);
#endif

    while (!glfwWindowShouldClose(window)) {
        display(world, cam);

        ::glfwSwapBuffers(window);
        ::glfwPollEvents();
    }

    ::glfwDestroyWindow(window);
    ::glfwTerminate();

    return 1;
}
void Application::run(int swapInterval) {
    const double POLL_INTERVAL_SEC = 0.5f;

    context->makeCurrent();
    if (!init(rootRegion)) {
        throw std::runtime_error("Error occurred in application init()");
    }
    rootRegion.add(getContext()->getGlassPane());
    if (showDebugIcon) {
        GlyphRegionPtr debug = MakeGlyphRegion(
                                   createAwesomeGlyph(0xf188, FontStyle::Outline, 20),
                                   CoordPercent(1.0f, 1.0f), CoordPX(20, 20), RGBA(0, 0, 0, 0),
                                   RGBA(64, 64, 64, 128), RGBA(192, 192, 192, 128), UnitPX(0));

        debug->setOrigin(Origin::BottomRight);
        debug->onMouseDown =
        [this,debug](AlloyContext* context,const InputEvent& e) {
            if(e.button==GLFW_MOUSE_BUTTON_LEFT) {
                context->toggleDebug();
                debug->foregroundColor=context->isDebugEnabled()?MakeColor(255,64,64,255):MakeColor(64,64,64,128);
                context->setMouseFocusObject(nullptr);
                return true;
            }
            return false;
        };
        rootRegion.add(debug);
    }

    //First pack triggers computation of aspect ratios  for components.
    rootRegion.pack(context.get());
    context->getGlassPane()->setVisible(false);
    context->requestPack();
    glfwSwapInterval(swapInterval);
    glfwSetTime(0);
    uint64_t frameCounter = 0;
    std::chrono::steady_clock::time_point endTime;
    std::chrono::steady_clock::time_point lastFpsTime =
        std::chrono::steady_clock::now();
    if (!forceClose) {
        glfwShowWindow(context->window);
    } else {
        context->executeDeferredTasks();
        context->dirtyUI = true;
        context->dirtyLayout = true;
        draw();
        context->dirtyUI = true;
        context->dirtyLayout = true;
        context->update(rootRegion);
    }
    do {
        //Events could have modified layout! Pack before draw to make sure things are correctly positioned.
        if (context->dirtyLayout) {
            context->dirtyLayout = false;
            context->dirtyCursorLocator = true;
            rootRegion.pack();
        }
        draw();
        context->update(rootRegion);
        double elapsed =
            std::chrono::duration<double>(endTime - lastFpsTime).count();
        frameCounter++;
        if (elapsed > POLL_INTERVAL_SEC) {
            frameRate = (float) (frameCounter / elapsed);
            lastFpsTime = endTime;
            frameCounter = 0;
        }
        glfwSwapBuffers(context->window);
        glfwPollEvents();
        for (std::exception_ptr e : caughtExceptions) {
            std::rethrow_exception(e);
        }
        if (glfwWindowShouldClose(context->offscreenWindow)) {
            context->setOffScreenVisible(false);
        }
    } while (!glfwWindowShouldClose(context->window) && !forceClose);
}
Esempio n. 10
0
// ------------------------------------------------------------------- main ---
int main( int argc, char **argv )
{
    GLFWwindow* window;
    char* screenshot_path = NULL;

    if (argc > 1)
    {
        if (argc == 3 && 0 == strcmp( "--screenshot", argv[1] ))
            screenshot_path = argv[2];
        else
        {
            fprintf( stderr, "Unknown or incomplete parameters given\n" );
            exit( EXIT_FAILURE );
        }
    }

    glfwSetErrorCallback( error_callback );

    if (!glfwInit( ))
    {
        exit( EXIT_FAILURE );
    }

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

    window = glfwCreateWindow( 400, 400, argv[0], NULL, NULL );

    if (!window)
    {
        glfwTerminate( );
        exit( EXIT_FAILURE );
    }

    glfwMakeContextCurrent( window );
    glfwSwapInterval( 1 );

    glfwSetFramebufferSizeCallback( window, reshape );
    glfwSetWindowRefreshCallback( window, display );
    glfwSetKeyCallback( window, keyboard );

#ifndef __APPLE__
    glewExperimental = GL_TRUE;
    GLenum err = glewInit();
    if (GLEW_OK != err)
    {
        /* Problem: glewInit failed, something is seriously wrong. */
        fprintf( stderr, "Error: %s\n", glewGetErrorString(err) );
        exit( EXIT_FAILURE );
    }
    fprintf( stderr, "Using GLEW %s\n", glewGetString(GLEW_VERSION) );
#endif

    init();

    glfwShowWindow( window );
    {
        int pixWidth, pixHeight;
        glfwGetFramebufferSize( window, &pixWidth, &pixHeight );
        reshape( window, pixWidth, pixHeight );
    }

    glfwSetTime(1.0);

    while (!glfwWindowShouldClose( window ))
    {
        display( window );
        glfwPollEvents( );

        if (screenshot_path)
        {
            screenshot( window, screenshot_path );
            glfwSetWindowShouldClose( window, 1 );
        }
    }

    glfwDestroyWindow( window );
    glfwTerminate( );

    return EXIT_SUCCESS;
}
Esempio n. 11
0
int main(void) {
    srand(time(NULL));

    //Create init object
    Init init = Init();

    //Initialize glfw
    init.glfw(4, 1);
    //Open a window
    GLFWwindow *window = init.window(400, 400);

    //Print window info
    init.printWindowInfo(window);

    //Make opened window current context
    glfwMakeContextCurrent(window);

    init.glew();

    int width, height;
    glfwGetFramebufferSize(window, &width, &height);
    glViewport(0, 0, width, height);

    glEnable(GL_CULL_FACE);


    // Nvidia cards require a vertex array to cooperate.
    GLuint VertexArrayID;
    glGenVertexArrays(1, &VertexArrayID);
    glBindVertexArray(VertexArrayID);

    //Set up the initial state.
    unsigned int w = 32, h = 32, d = 32;
    State *prevState = new State(w, h, d);

    VelocityGrid *velocities = new VelocityGrid(w, h, d);
    prevState->setVelocityGrid(velocities);

    // init level set
    LevelSet *ls = factory::levelSet::ball(w, h, d);
    prevState->setLevelSet(ls);

    delete ls;

    // init simulator
    Simulator sim(*prevState, 0.1f);
    //    BubbleMaxExporter bubbleExporter;
    
    // Dark black background
    glClearColor(0.0f, 0.0f, 0.0f, 0.0f);

    //Load in shaders
    static ShaderProgram colorCubeProg("../vertShader.vert", "../colorCube.frag");
    static ShaderProgram rayCasterProg("../vertShader.vert", "../rayCaster.frag");
    static ShaderProgram bubbleProg("../bubbleVertShader.vert", "../bubbleFragShader.frag");

    static const GLfloat vertexBufferData[] = {
            -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
    };

    static const GLuint triangleBufferData[] = {
            // xy plane (z = -1)
            0, 1, 3,
            3, 2, 0,
            // xz plane (y = -1)
            0, 5, 1,
            0, 4, 5,
            // yz plane (x = -1)
            0, 2, 4,
            2, 6, 4,
            // xy plane (z = 1)
            4, 7, 5,
            4, 6, 7,
            // xz plane (y = 1)
            2, 7, 6,
            2, 3, 7,
            // yz plane (x = 1)
            1, 5, 3,
            3, 5, 7
    };

    std::vector<GLfloat> g_bubble_buffer_data;

    //Create vertex buffer
    GLuint vertexbuffer;
    glGenBuffers(1, &vertexbuffer);
    glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer);
    glBufferData(GL_ARRAY_BUFFER, sizeof(vertexBufferData), vertexBufferData, GL_STATIC_DRAW);



    GLuint triangleBuffer;
    glGenBuffers(1, &triangleBuffer);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, triangleBuffer);
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(triangleBufferData), triangleBufferData, GL_STATIC_DRAW);

    // Create bubble buffer
    GLuint bubbleBuffer;
    glGenBuffers(1, &bubbleBuffer);

    // Create framebuffer
    FBO *framebuffer = new FBO(width, height);

    GLuint volumeTextureId;
    glGenTextures(1, &volumeTextureId);
    glBindTexture(GL_TEXTURE_3D, volumeTextureId);

    //Object which encapsulates a texture + The destruction of a texture.
    Texture3D tex3D(w, h, d);
    double lastTime = glfwGetTime();
    int nbFrames = 0;

    float deltaT = 0.1; //First time step

    glfwSwapInterval(1);
    int i = 0;
    do {


        framebuffer->activate();

        // common for both render passes.
        sim.step(deltaT);

        // deltaT = sim.getDeltaT();

        glm::mat4 matrix = glm::mat4(1.0f);
        matrix = glm::translate(matrix, glm::vec3(0.0f, 0.0f, 2.0f));
        matrix = glm::rotate(matrix, -3.1415926535f / 4.0f, glm::vec3(1.0f, 0.0f, 0.0f));
        matrix = glm::rotate(matrix, 0.1415926535f / 4.0f * (float) glfwGetTime(), glm::vec3(0.0f, 1.0f, 0.0f));

        // Render back face of the cube.
        colorCubeProg();
        glCullFace(GL_FRONT);

        {
            GLuint tLocation = glGetUniformLocation(colorCubeProg, "time");
            glUniform1f(tLocation, glfwGetTime());

            GLuint mvLocation = glGetUniformLocation(colorCubeProg, "mvMatrix");
            glUniformMatrix4fv(mvLocation, 1, false, glm::value_ptr(matrix));
        }

        glClear(GL_COLOR_BUFFER_BIT);
        glEnableVertexAttribArray(0);

        glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer);
        glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, triangleBuffer);
    //Triangle coordinates
    glVertexAttribPointer(
            0,                  // Location 0
            3,                  // size
            GL_FLOAT,           // type
            GL_FALSE,           // normalized?
            0,                  // stride
            (void *) 0            // array buffer offset
    );

        glDrawElements(GL_TRIANGLES, 12 * 3, GL_UNSIGNED_INT, 0);
        glDisableVertexAttribArray(0);

        // Do the ray casting.
        glBindFramebuffer(GL_FRAMEBUFFER, 0); // bind the screen
        glCullFace(GL_BACK);
        rayCasterProg();

        {
            GLuint tLocation = glGetUniformLocation(rayCasterProg, "time");
            glUniform1f(tLocation, glfwGetTime());

            GLuint mvLocation = glGetUniformLocation(rayCasterProg, "mvMatrix");
            glUniformMatrix4fv(mvLocation, 1, false, glm::value_ptr(matrix));

            GLuint windowSizeLocation = glGetUniformLocation(rayCasterProg, "windowSize");
            glUniform2f(windowSizeLocation, width, height);
        }

        glClear(GL_COLOR_BUFFER_BIT);

        glActiveTexture(GL_TEXTURE0);
        glBindTexture(GL_TEXTURE_2D, *(framebuffer->getTexture()));

        GLuint textureLocation = glGetUniformLocation(rayCasterProg, "backfaceTexture");
        glUniform1i(textureLocation, 0);

        State *currentState = sim.getCurrentState();

        std::vector<glm::vec3> vertexList;
        std::vector<std::vector<int> > faceIndices;
        // copy desired quantities to texture
        for (unsigned int k = 0; k < d; ++k) {
            for (unsigned int j = 0; j < h; ++j) {
                for (unsigned int i = 0; i < w; ++i) {

                    // velocity
                    //tex3D.set(i,j,k,0, 0.5 + 0.5*currentState.getVelocityGrid()->u->get(i,j,k));
                    //tex3D.set(i,j,1, 0.5 + 0.5*currentState.getVelocityGrid()->v->get(i,j));
                    //tex3D.set(i,j,2, 0.5 + currentState.getCellTypeGrid()->get(i, j));
                    //tex3D.set(i,j,2, 0.5);
                    //tex3D.set(i,j,3, 1.0f);

                    // divergence
                    //tex3D.set(i,j,0, fabs(sim.getDivergenceGrid()->get(i,j)));
                    //tex3D.set(i,j,1, fabs(sim.getDivergenceGrid()->get(i,j)));
                    //tex3D.set(i,j,2, fabs(sim.getDivergenceGrid()->get(i,j)));
                    //tex3D.set(i,j,3, 1.0f);

                    // type
                    // tex3D.set(i,j,k, 0, currentState.getCellTypeGrid()->get(i,j, k) == CellType::FLUID ? 1.0 : 0.0);
                    // tex3D.set(i,j,k, 1, currentState.getCellTypeGrid()->get(i,j, k) == CellType::FLUID ? 1.0 : 0.0);
                    // tex3D.set(i,j,k, 2, currentState.getCellTypeGrid()->get(i,j, k) == CellType::SOLID ? 1.0 : 0.0);
                    // tex3D.set(i,j,k, 3, 1.0f);

                    if(currentState->getSignedDistanceGrid()->isValid(i+1,j,k) &&
                        currentState->getSignedDistanceGrid()->isValid(i,j+1,k) &&
                        currentState->getSignedDistanceGrid()->isValid(i+1,j+1,k) &&
                        currentState->getSignedDistanceGrid()->isValid(i,j,k+1) &&
                        currentState->getSignedDistanceGrid()->isValid(i+1,j,k+1) &&
                        currentState->getSignedDistanceGrid()->isValid(i,j+1,k+1) &&
                        currentState->getSignedDistanceGrid()->isValid(i+1,j+1,k+1)){

                        marchingCubes::GRIDCELL gridcell;
                        gridcell.p[0] = glm::vec3(i,j,k);
                        gridcell.p[1] = glm::vec3(i,j+1,k);
                        gridcell.p[2] = glm::vec3(i+1,j+1,k);
                        gridcell.p[3] = glm::vec3(i+1,j,k);
                        gridcell.p[4] = glm::vec3(i,j,k+1);
                        gridcell.p[5] = glm::vec3(i,j+1,k+1);
                        gridcell.p[6] = glm::vec3(i+1,j+1,k+1);
                        gridcell.p[7] = glm::vec3(i+1,j,k+1);

                        gridcell.val[0] = currentState->getSignedDistanceGrid()->get(i, j, k);
                        gridcell.val[1] = currentState->getSignedDistanceGrid()->get(i, j+1, k);
                        gridcell.val[2] = currentState->getSignedDistanceGrid()->get(i+1, j+1, k);
                        gridcell.val[3] = currentState->getSignedDistanceGrid()->get(i+1, j, k);
                        gridcell.val[4] = currentState->getSignedDistanceGrid()->get(i, j, k+1);
                        gridcell.val[5] = currentState->getSignedDistanceGrid()->get(i, j+1, k+1);
                        gridcell.val[6] = currentState->getSignedDistanceGrid()->get(i+1, j+1, k+1);
                        gridcell.val[7] = currentState->getSignedDistanceGrid()->get(i+1, j, k+1);

                        //std::cout << gridcell.val[0] << std::endl;

                        marchingCubes::TRIANGLE *triangles = new marchingCubes::TRIANGLE[5];
                        int numTriangles = marchingCubes::PolygoniseCube(gridcell, 0.0, triangles);
                        for(int i = 0; i < numTriangles; i++){
                            int startIndex = vertexList.size()+1;
                            for(int j = 0; j < 3; j++){
                                //std::cout << triangles[i].p[j].x << " " << triangles[i].p[j].y << " " << triangles[i].p[j].z << std::endl;
                            }
                            vertexList.push_back(triangles[i].p[0]);
                            vertexList.push_back(triangles[i].p[1]);
                            vertexList.push_back(triangles[i].p[2]);

                            std::vector<int> indices = {
                                    startIndex,
                                    startIndex+1,
                                    startIndex+2
                            };

                            faceIndices.push_back(indices);
                        }

                        delete[] triangles;
                    }
                    //signed dist
                    float dist = currentState->getSignedDistanceGrid()->get(i, j, k);
                    float solid = currentState->getCellTypeGrid()->get(i, j, k) == CellType::SOLID ? 1.0f : 0.0f;
                    dist = (glm::clamp(dist + solid, -1.0f, 1.0f) + 1) / 2;

                    tex3D.set(i, j, k, 0, solid);
                    tex3D.set(i, j, k, 1, 0.0f); // not used
                    tex3D.set(i, j, k, 2, dist);
                    tex3D.set(i, j, k, 3, 1.0f);
                    //closest point
                    // tex3D.set(i,j,0, currentState.getClosestPointGrid()->get(i,j).x / 70.0);
                    // tex3D.set(i,j,1, currentState.getClosestPointGrid()->get(i,j).y / 70.0);
                    // tex3D.set(i,j,2, 0.0f);
                    // tex3D.set(i,j,3, 1.0f);
                }
            }
        }

        printObjToFile("exported_" + std::to_string(i) + ".obj", vertexList, faceIndices);
        std::ofstream fileStream("exportedState_" + std::to_string(i) + ".pf", std::ios::binary);
        currentState->write(fileStream);
        fileStream.close();


        // activate and upload texture to gpu
        tex3D(GL_TEXTURE1);
        GLuint volumeTextureLocation = glGetUniformLocation(rayCasterProg, "volumeTexture");
        glUniform1i(volumeTextureLocation, 1);

        glEnableVertexAttribArray(0);
        glDrawElements(GL_TRIANGLES, 12 * 3, GL_UNSIGNED_INT, 0);
        glDisableVertexAttribArray(0);

        FBO::deactivate();

        

        ////////////////// Start drawing bubbles //////////////////////
        
        // Draw bubbles
        const std::vector<Bubble> bubbles = currentState->getBubbles();
        g_bubble_buffer_data.clear();
        std::cout << "frame=" << i << ", nBubbles=" << bubbles.size() << std::endl;
        for (int i = 0; i < bubbles.size(); i++) {
          Bubble b = bubbles.at(i);

          //          std::cout << "bubble pos " << b.position.x << ", " << b.position.y << std::endl << b.radius << std::endl;
            
          g_bubble_buffer_data.push_back(b.position.x / (float)w * 2.0 - 1.0);
          g_bubble_buffer_data.push_back(b.position.y / (float)h * 2.0 - 1.0);
          g_bubble_buffer_data.push_back(b.position.z / (float)d * 2.0 - 1.0);
          g_bubble_buffer_data.push_back(b.radius);
        }

           
        glBindBuffer(GL_ARRAY_BUFFER, bubbleBuffer);    
        glBufferData(GL_ARRAY_BUFFER, sizeof(float) * g_bubble_buffer_data.size(), &g_bubble_buffer_data[0], GL_DYNAMIC_DRAW);
        
                
        
        bubbleProg();
        glEnable(GL_PROGRAM_POINT_SIZE);

        {
            GLuint tLocation = glGetUniformLocation(colorCubeProg, "time");
            glUniform1f(tLocation, glfwGetTime());

            GLuint mvLocation = glGetUniformLocation(colorCubeProg, "mvMatrix");
            glUniformMatrix4fv(mvLocation, 1, false, glm::value_ptr(matrix));
        }

        //        glEnable (GL_BLEND);
        //        glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
                
        glPointSize(4.0);
        
        if (g_bubble_buffer_data.size() > 0) {
          glEnable(GL_PROGRAM_POINT_SIZE);
          glEnableVertexAttribArray(0);
          glVertexAttribPointer(
                                0,                  //Location 0
                                4,                  // size
                                GL_FLOAT,           // type
                                GL_FALSE,           // normalized?
                                0,                  // stride
                                (void*)0            // array buffer offset
                                );
          
          glDrawArrays(GL_POINTS, 0, 4 * g_bubble_buffer_data.size()); // 3 indices starting at 0 -> 1 triangle
          glDisableVertexAttribArray(0);
        }
        ////////////////// End drawing bubbles //////////////////////
        




        glfwPollEvents();
        glfwSwapBuffers(window);
        double currentTime = glfwGetTime();
        nbFrames++;
        if (currentTime - lastTime >= 1.0) { // If last prinf() was more than 1 sec ago
            // printf and reset timer
            std::string title = std::to_string(1000.0 / double(nbFrames)) + "ms/frame        " + std::to_string(deltaT) + "  dt";
            glfwSetWindowTitle(window, title.c_str());
            nbFrames = 0;
            lastTime += 1.0;
        }
        i++;
        
        //        bubbleExporter.update(i, sim.getBubbleTracker());
        //        bubbleExporter.exportSnapshot(i, "bubbles_" + std::to_string(i) + ".mx");

        /*        if (i > 600) {
          bubbleExporter.exportBubbles("bubbles.mx");
          break;
          }*/
    } // Check if the ESC key was pressed or the window was closed
    while (!glfwWindowShouldClose(window));

    std::cout << "Cleaning up!" << std::endl;
    // Close OpenGL window and terminate GLFW
    glfwDestroyWindow(window);
    glfwTerminate();
    glDeleteBuffers(1, &vertexbuffer);

    glDeleteVertexArrays(1, &VertexArrayID);
    exit(EXIT_SUCCESS);
}
Esempio n. 12
0
	void init()
	{
#ifdef GRAPHICS
		if (!glfwInit()) {
			LOG("Failed to init GLFW.");
			exit(-1);
		}

		initGraph(&fps_graph, GRAPH_RENDER_FPS, "Frame Time");
		initGraph(&cpu_graph, GRAPH_RENDER_MS, "CPU Time");
		initGraph(&gpu_graph, GRAPH_RENDER_MS, "GPU Time");

		glfwSetErrorCallback([](int error, const char* desc) {LOG("GLFW error %d: %s\n", error, desc); });
		glfwWindowHint(GLFW_OPENGL_DEBUG_CONTEXT, 1);
		int height = glfwGetVideoMode(glfwGetPrimaryMonitor())->height*0.6, width = height*double(world::width) / double(world::height);
		window = glfwCreateWindow(width, height, "PedestrianSimulator", NULL, NULL); if (!window) {
			glfwTerminate();
			exit(-1);
		}
		glfwSetKeyCallback(window, [](GLFWwindow* window, int key, int scancode, int action, int mods)
		{
			NVG_NOTUSED(scancode);
			NVG_NOTUSED(mods);
			if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS)
				glfwSetWindowShouldClose(window, GL_TRUE);
		});

		glfwSetMouseButtonCallback(window, [](GLFWwindow* wind, int button, int action, int mods){
			static vec_t start_pos;
			vecd_t pos;
			glfwGetCursorPos(wind, &pos.x, &pos.y);
			vec_t world_pos = screen2world({ pos.x, pos.y });
			if (action == GLFW_RELEASE)
			{
				
				if (button == GLFW_MOUSE_BUTTON_1)
				{
					world::add_objective({ world_pos, 0 });
				}
				else if (button == GLFW_MOUSE_BUTTON_2)
				{
					world::add_objective({ world_pos, 1 });
				}
				else if (button==GLFW_MOUSE_BUTTON_3)
					 LOG("click at screen (%.2lf, %.2lf), world (%.2f, %.2f)", pos.x, pos.y, world_pos.x, world_pos.y);
			}
			else if (action == GLFW_PRESS)
			{
				if (button == GLFW_MOUSE_BUTTON_2)
				{
					start_pos = world_pos;
				}
			}
		});

		glfwMakeContextCurrent(window);
		glewExperimental = GL_TRUE;
		if (glewInit() != GLEW_OK) {
			LOG("Could not init glew.\n");
			exit(-1);
		}
		glGetError();
		vg = nvgCreateGL3(512, 512, NVG_ANTIALIAS | NVG_STENCIL_STROKES);
		if (vg == NULL) {
			LOG("Could not init nanovg.\n");
			exit(-1);
		}

		nvgCreateFont(vg, "sans", "roboto.ttf");

		glfwSwapInterval(0);
		initGPUTimer(&gpu_timer);
		glfwSetTime(0);
		prev_time = glfwGetTime();
#endif
	}
Esempio n. 13
0
int main( void )
{
    int width, height, x;
    double t;

    // Initialise GLFW
    if( !glfwInit() )
    {
        fprintf( stderr, "Failed to initialize GLFW\n" );
        exit( EXIT_FAILURE );
    }

    // Open a window and create its OpenGL context
    if( !glfwOpenWindow( 640, 480, 0,0,0,0, 0,0, GLFW_WINDOW ) )
    {
        fprintf( stderr, "Failed to open GLFW window\n" );

        glfwTerminate();
        exit( EXIT_FAILURE );
    }

    glfwSetWindowTitle( "Spinning Triangle" );

    // Ensure we can capture the escape key being pressed below
    glfwEnable( GLFW_STICKY_KEYS );

    // Enable vertical sync (on cards that support it)
    glfwSwapInterval( 1 );

    do
    {
        t = glfwGetTime();
        glfwGetMousePos( &x, NULL );

        // Get window size (may be different than the requested size)
        glfwGetWindowSize( &width, &height );

        // Special case: avoid division by zero below
        height = height > 0 ? height : 1;

        glViewport( 0, 0, width, height );

        // Clear color buffer to black
        glClearColor( 0.0f, 0.0f, 0.0f, 0.0f );
        glClear( GL_COLOR_BUFFER_BIT );

        // Select and setup the projection matrix
        glMatrixMode( GL_PROJECTION );
        glLoadIdentity();
        gluPerspective( 65.0f, (GLfloat)width/(GLfloat)height, 1.0f, 100.0f );

        // Select and setup the modelview matrix
        glMatrixMode( GL_MODELVIEW );
        glLoadIdentity();
        gluLookAt( 0.0f, 1.0f, 0.0f,    // Eye-position
                   0.0f, 20.0f, 0.0f,   // View-point
                   0.0f, 0.0f, 1.0f );  // Up-vector

        // Draw a rotating colorful triangle
        glTranslatef( 0.0f, 14.0f, 0.0f );
        glRotatef( 0.3f*(GLfloat)x + (GLfloat)t*100.0f, 0.0f, 0.0f, 1.0f );
        glBegin( GL_TRIANGLES );
          glColor3f( 1.0f, 0.0f, 0.0f );
          glVertex3f( -5.0f, 0.0f, -4.0f );
          glColor3f( 0.0f, 1.0f, 0.0f );
          glVertex3f( 5.0f, 0.0f, -4.0f );
          glColor3f( 0.0f, 0.0f, 1.0f );
          glVertex3f( 0.0f, 0.0f, 6.0f );
        glEnd();

        // Swap buffers
        glfwSwapBuffers();

    } // Check if the ESC key was pressed or the window was closed
    while( glfwGetKey( GLFW_KEY_ESC ) != GLFW_PRESS &&
           glfwGetWindowParam( GLFW_OPENED ) );

    // Close OpenGL window and terminate GLFW
    glfwTerminate();

    exit( EXIT_SUCCESS );
}
Esempio n. 14
0
void Renderer::ensureVSync(bool enableVSync){
	if (vSyncEnabled != enableVSync){
		vSyncEnabled = enableVSync;
		glfwSwapInterval(enableVSync ? 1 : 0);
	}
}
Esempio n. 15
0
int main(int argc, char* argv[])
{
	glfwSetErrorCallback(error_callback);
	if (!glfwInit()) return 1;
	glfwWindowHint(GLFW_RED_BITS, 8);
	glfwWindowHint(GLFW_GREEN_BITS, 8);
	glfwWindowHint(GLFW_BLUE_BITS, 8);
	glfwWindowHint(GLFW_ALPHA_BITS, 8);
	glfwWindowHint(GLFW_DEPTH_BITS, 32);
	glfwWindowHint(GLFW_STENCIL_BITS, GLFW_DONT_CARE);
	glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
	glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2);
	glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
	glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
	glfwWindowHint(GLFW_OPENGL_DEBUG_CONTEXT, GL_TRUE);
	glfwWindowHint(GLFW_SAMPLES, 4);
	GLFWwindow *window = glfwCreateWindow(1024, 768, "Lightmapping Example", NULL, NULL);
	if (!window) return 1;
	glfwMakeContextCurrent(window);
	gladLoadGLLoader((GLADloadproc)glfwGetProcAddress);
	glfwSwapInterval(1);

	scene_t scene = {0};
	if (!initScene(&scene))
	{
		fprintf(stderr, "Could not initialize scene.\n");
		return 1;
	}

	printf("Ambient Occlusion Baking Example.\n");
	printf("Use your mouse and the W, A, S, D, E, Q keys to navigate.\n");
	printf("Press SPACE to start baking one light bounce!\n");
	printf("This will take a few seconds and bake a lightmap illuminated by:\n");
	printf("1. The mesh itself (initially black)\n");
	printf("2. A white sky (1.0f, 1.0f, 1.0f)\n");

	while (!glfwWindowShouldClose(window))
	{
		glfwPollEvents();
		if (glfwGetKey(window, GLFW_KEY_SPACE) == GLFW_PRESS)
			bake(&scene);

		int w, h;
		glfwGetFramebufferSize(window, &w, &h);
		glViewport(0, 0, w, h);

		// camera for glfw window
		float view[16], projection[16];
		fpsCameraViewMatrix(window, view);
		perspectiveMatrix(projection, 45.0f, (float)w / (float)h, 0.01f, 100.0f);
		
		// draw to screen with a blueish sky
		glClearColor(0.6f, 0.8f, 1.0f, 1.0f);
		glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
		drawScene(&scene, view, projection);

		glfwSwapBuffers(window);
	}

	destroyScene(&scene);
	glfwDestroyWindow(window);
	glfwTerminate();
	return 0;
}
Esempio n. 16
0
void boot_init(int* argc, char** argv) {

  int error;

  fail_if(glfwInit() == false);

  // OpenGL version 3
  glfwOpenWindowHint(GLFW_OPENGL_VERSION_MAJOR, 3);
  glfwOpenWindowHint(GLFW_OPENGL_VERSION_MINOR, 0);

  // No window resize
  glfwOpenWindowHint(GLFW_WINDOW_NO_RESIZE, true);
  // 400% gameboy scale, 5 bit rgb with 1 bit alpha, 8 bit z buffer
  fail_if(glfwOpenWindow(160 * 4, 144 * 4, 5, 5, 5, 1, 8, 0, GLFW_WINDOW) == false);

  glfwSetWindowTitle("");

  glfwEnable(GLFW_AUTO_POLL_EVENTS); // Automatically poll input on swap
  glfwSwapInterval(1); // 0: vsync off, 1: vsync on 

  printf("Renderer: %s\n", glGetString(GL_RENDERER));
  printf("GL Version: %s\n", glGetString(GL_VERSION));
  printf("Using GLSL: %s\n", glGetString(GL_SHADING_LANGUAGE_VERSION));

  error = glewInit();

  if (error != GLEW_OK) {
    fprintf(stderr, "GLEW error: %s\n", glewGetErrorString(error));
  }

  printf("GL Extension Wrangler: %s\n", glewGetString(GLEW_VERSION));

  // Load audio
  fail_if(alutInit(argc, argv) == false);

  glClearColor(206.0/255.0, 230.0/255.0, 165.0/255.0, 1.0f);
  glEnable(GL_SCISSOR_TEST); // For geom culling
  
  // transparency
  glEnable(GL_BLEND);
  glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

  // z-buffer
  glEnable(GL_DEPTH_TEST);
  glDepthFunc(GL_LEQUAL);

  // Set up perspective
  glOrtho(0, 160, 144, 0, -1.0, 1.0);
  glDepthRange(-1.0f, 1.0f);
  glViewport(0, 0, 160 * 4, 144 * 4);

  // This is where Ill put the logo thing
  unsigned logo = bitmap_load("bmp/logo.bmp");
  unsigned logo_vbo;
  float t0, t1, dt;
  float logo_x = 16, logo_y = -80;
  float logo_v[] = {
    0,     0, 0, 1.0 - 0,
    0,   128, 0, 1.0 - 1,
    128, 128, 1, 1.0 - 1,
    128,   0, 1, 1.0 - 0,
  };

  glGenBuffers(1, &logo_vbo);
  glBindBuffer(GL_ARRAY_BUFFER, logo_vbo);
  glBufferData(GL_ARRAY_BUFFER, sizeof(logo_v)*sizeof(float), logo_v, GL_STATIC_DRAW);
 
  Pipeline* logo_program = pipeline_new(
    shader_new(SHADER_VERTEX, "shader/logo.vert"),
    shader_new(SHADER_FRAGMENT, "shader/logo.frag"));

  pipeline_attribute(logo_program, "coord", 0);
  pipeline_attribute(logo_program, "st", 1);
  pipeline_uniform(logo_program, "pos", 0);
  pipeline_uniform(logo_program, "tex", 1);

  glUseProgram(logo_program->id);

  // Bind the logo to texture 0
  glActiveTexture(GL_TEXTURE0);
  glBindTexture(GL_TEXTURE_2D, logo);
  glUniform1i(logo_program->uniform[1], 0);

  // Bind logo vbo
  glBindBuffer(GL_ARRAY_BUFFER, logo_vbo);
  glEnableVertexAttribArray(logo_program->attribute[0]);
  glVertexAttribPointer(logo_program->attribute[0], 2, GL_FLOAT, false, 4*sizeof(float), (void*)0);
  glEnableVertexAttribArray(logo_program->attribute[1]);
  glVertexAttribPointer(logo_program->attribute[1], 2, GL_FLOAT, false, 4*sizeof(float), (void*)(2 * sizeof(float)));

  // load sound
  unsigned sound_source;
  alGenSources(1, &sound_source);
  Sound* ding = sound_load("sound/ding.ogg");

  alSourcei(sound_source, AL_BUFFER, ding->buffer);
  
  glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT);
  glfwSwapBuffers();

  sleep(1);

  t0 = glfwGetTime();
  while (logo_y < 8) {
    t1 = glfwGetTime();
    dt = t1 - t0;
    t0 = t1;

    logo_y += 50 * dt;

    glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT);

    glUniform2f(logo_program->uniform[0], roundf(logo_x), roundf(logo_y));

    // Render logo
    glDrawArrays(GL_TRIANGLE_FAN, 0, 4);

    glfwSwapBuffers();
  }

  alSourcePlay(sound_source);

  glDisableVertexAttribArray(logo_program->attribute[0]);
  glDisableVertexAttribArray(logo_program->attribute[1]);

  sleep(1);
}
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;
}
Esempio n. 18
0
int main(int argc, char* argv[]) {
	//#ifdef __MINGW32__
	//	WORD versionWanted = MAKEWORD(1, 1);
	//	WSADATA wsaData;
	//	WSAStartup(versionWanted, &wsaData);
	//#endif

	char ncwd[strlen(argv[0]) + 1];
	memcpy(ncwd, argv[0], strlen(argv[0]) + 1);
	char* ecwd =
#ifdef __MINGW32__
			strrchr(ncwd, '\\');
#else
			strrchr(ncwd, '/');
#endif
	if (ecwd != NULL) {
		ecwd++;
		ecwd[0] = 0;
		chdir(ncwd);
	}
	printf("Loading... [FROM=%s]\n", ncwd);
	main_preinit();
	width = 800;
	height = 600;
	if (!glfwInit()) return -1;
	glfwWindowHint(GLFW_DOUBLEBUFFER, 1);
	glfwWindowHint(GLFW_SAMPLES, 4); // antialiasing
	//glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_COMPAT_PROFILE);
	//glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
	//glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2);
	glfwSetErrorCallback(__error_callback);
	window = glfwCreateWindow(800, 600, windowTitle, NULL, NULL);
	if (!window) {
		glfwTerminate();
		return -1;
	}
	glfwMakeContextCurrent (window);
	glewExperimental = GL_TRUE;
	GLenum err = glewInit();
	if (err != GLEW_OK) {
		printf("GLEW Init error: %s\n", glewGetErrorString(err));
		glfwTerminate();
		return -1;
	}
	if (!glewIsSupported("GL_VERSION_3_0") || !glewIsSupported("GL_ARB_vertex_program")) {
		printf("OpenGL version 3.0+ or GL_ARB_vertex_program not satisfied.\n");
		glfwTerminate();
		return -1;
	}
	printf("OpenGL Version: %s\n", glGetString(GL_VERSION));
	glfwSetInputMode(window, GLFW_STICKY_KEYS, 1);
	main_init();
	__gui_load();
	guistate_set(0);
	clock_gettime(CLOCK_MONOTONIC, &__main_ts);
	__main_lt = (double) __main_ts.tv_sec * 1000. + (double) __main_ts.tv_nsec / 1000000.;
	__main_lf = __main_lt;
	glfwSetKeyCallback(window, __gui_keyboardCallback);
	glfwSetCharCallback(window, __gui_textCallback);
	glfwSetCursorPosCallback(window, __gui_mouseMotionCallback);
	glfwSetMouseButtonCallback(window, __gui_mouseCallback);
	glfwSetScrollCallback(window, __gui_scrollCallback);
	printf("Loaded.\n");
	while (!glfwWindowShouldClose(window)) {
		displayCallback();
		glfwSwapBuffers(window);
		glfwSwapInterval(1);
		glfwPollEvents();
	}
	glfwTerminate();
	return 0;
}
Esempio n. 19
0
void Application::EnableVSync(bool a_bEnabled)
{
	m_bVSyncEnabled = a_bEnabled;
	glfwSwapInterval( (m_bVSyncEnabled)?0:1 );

}
Esempio n. 20
0
int main(int argc, char *argv[])
{
    GLFWwindow* window;
    glfwSetErrorCallback(error_callback);
    glfwInit();
    window = glfwCreateWindow(640, 480, "Simple example", NULL, NULL);
    glfwMakeContextCurrent(window);

    glewExperimental = GL_TRUE;
    glewInit();

    //glfwWindowHint(GLFW_SAMPLES, 0);    // 0x antialiasing
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);  // 设置OPENGL版本3.3
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
    glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);

    glfwSwapInterval(1);
    glfwSetKeyCallback(window, key_callback);
    glfwSetCursorPosCallback(window, cursorpos_callback);
    glfwSetMouseButtonCallback(window, mousebutton_callback);


    glClearColor(0,0,0,1);      // 清理屏幕为黑色
    glEnable(GL_CULL_FACE);     // 启用面剔除
    glCullFace(GL_BACK);

    glEnable(GL_DEPTH_TEST);    // 启用深度测试

    glEnable(GL_LIGHT0);        // 启用灯光0
    glEnable(GL_NORMALIZE);     // 启用法线
    glEnable(GL_COLOR_MATERIAL);// 启用材质模式
    glEnable(GL_LIGHTING);      // 打开灯光

    glEnable(GL_TEXTURE_2D);
    glEnable(GL_BLEND);
    glEnable(GL_ALPHA_TEST);
    glAlphaFunc(GL_GREATER ,0.9);//0.5可以换成任何在0~1之间的数
    glShadeModel(GL_SMOOTH);

    // 设置灯光的颜色
    const GLfloat light_ambient[]  = { 0.0f, 0.0f, 0.0f, 1.0f };
    const GLfloat light_diffuse[]  = { 1.0f, 1.0f, 1.0f, 1.0f };
    const GLfloat light_specular[] = { 1.0f, 1.0f, 1.0f, 1.0f };
    const GLfloat light_position[] = { 0.0f, 3.0f, -5.0f, 0.0f };
    glLightfv(GL_LIGHT0, GL_AMBIENT,  light_ambient);  // 设置环境光颜色
    glLightfv(GL_LIGHT0, GL_DIFFUSE,  light_diffuse);  // 设置漫反射的颜色
    glLightfv(GL_LIGHT0, GL_SPECULAR, light_specular);  // 设置镜面反射的颜色
    //glLightfv(GL_LIGHT0, GL_POSITION, light_position);  // 设置灯的位置

    // 设置材质的颜色
    const GLfloat mat_ambient[]    = { 0.7f, 0.7f, 0.7f, 1.0f };
    const GLfloat mat_diffuse[]    = { 0.8f, 0.8f, 0.8f, 1.0f };
    const GLfloat mat_specular[]   = { 1.0f, 1.0f, 1.0f, 1.0f };
    const GLfloat high_shininess[] = { 100.0f };
    glMaterialfv(GL_FRONT, GL_AMBIENT,   mat_ambient);   // 设置环境光颜色
    glMaterialfv(GL_FRONT, GL_DIFFUSE,   mat_diffuse);   // 设置漫反射的颜色
    glMaterialfv(GL_FRONT, GL_SPECULAR,  mat_specular);  // 设置镜面反射的颜色
    glMaterialfv(GL_FRONT, GL_SHININESS, high_shininess);// 镜面指数 该值越小,表示材质越粗糙,点光源发射的光线照射到上面,也可以产生较大的亮点

    obj_data_t* t = obj_create();
    obj_read("Data/panel.obj","Data/panel.mtl",t);
    obj_render_t* rt = obj_create_render(t);
    obj_render_dump(rt);

    float rx = -90.0f;
    float ry = 0.0f;

    while (!glfwWindowShouldClose(window))
    {
        int width, height;
        glfwGetFramebufferSize(window, &width, &height);
        float ratio = (float) width / (float) height;
        glViewport(0, 0, width, height);                // 把图像按照指定宽,高显示到屏幕上
        glMatrixMode(GL_PROJECTION);                    // 选择透视矩阵
        glLoadIdentity();                               // 重置矩阵
        glFrustum(-ratio, ratio, -1.0, 1.0, 2.0, 100.0);// 设置透视矩阵
        glMatrixMode(GL_MODELVIEW);                     // 选择模型矩阵
        glLoadIdentity();

        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // 清理颜色和深度缓存
        //glTranslatef(0.0f ,0.0f, -3.0f);
        gluLookAt(0.0f,0.0f,-3.0f, 0.0f,0.0f,1.0f, 0.0f,1.0f,0.0);
        glLightfv(GL_LIGHT0, GL_POSITION, light_position);

        glRotatef(rx + g_roll_y, 1.0f, 0.0f, 0.0f);
        glRotatef(ry + g_roll_x, 0.0f, 1.0f, 0.0f);

        //======================================================================
        obj_render(rt);
        //======================================================================
        glfwSwapBuffers(window);
        glfwPollEvents();
    }

    obj_destory_data(t);
    obj_destory_render(rt);


    glfwDestroyWindow(window);
    glfwTerminate();
    return EXIT_SUCCESS;
}
void main()
{
	glfwInit();

	// Create a window
	window = glfwCreateWindow(800, 800, "Calculating the Moment of Inertia Tensor (Rectangular Plane)", nullptr, nullptr);
	glfwMakeContextCurrent(window);
	glfwSwapInterval(0);

	// Initializes most things needed before the main loop
	init();

	//Generate the Plane1 mesh
	struct Vertex planeVerts[6];
	float arr1[] = { 1.0f, 1.0f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f };
	planeVerts[0] = *((Vertex*)arr1);
	float arr2[] =  { 1.0f, -1.0f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f };
	planeVerts[1] =  *((Vertex*)arr2);
	float arr3[] = { -1.0f, -1.0f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f };
	planeVerts[2] = *((Vertex*)arr3);
	float arr4[] = { -1.0f, -1.0f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f };
	planeVerts[3] = *((Vertex*)arr4);
	float arr5[] = { -1.0f, 1.0f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f };
	planeVerts[4] = *((Vertex*)arr5);
	float arr6[] ={ 1.0f, 1.0f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f };
	planeVerts[5] = *((Vertex*)arr6);

	rect = new struct Mesh(6, planeVerts, GL_TRIANGLES);

	//Scale the rectangle
	glm::vec3 scale(0.3f, 0.1f, 1.0f);
	rect->scale = glm::scale(glm::mat4(1.0f), scale);

	mass = 10.0f;
	inertiaTensor = CalculateInertiaTensorOfMyRectangle(2.0f * scale.x,2.0f * scale.y, mass);

	//Print controls
	std::cout << "Controls:\nClick and drag to rotate the rectangle and calculate the new moment of inertia.\n";

	//Print moment of inertia
	std::cout << std::fixed;
	std::cout.precision(4);

	std::cout << "Inertia Tensor:\n[\t" << inertiaTensor[0][0] << "\t" << inertiaTensor[0][1] << "\t" << inertiaTensor[0][2] << "\t]\n[\t" <<
		inertiaTensor[1][0] << "\t" << inertiaTensor[1][1] << "\t" << inertiaTensor[1][2] << "\t]\n[\t" <<
		inertiaTensor[2][0] << "\t" << inertiaTensor[2][1] << "\t" << inertiaTensor[2][2] << "\t]";
	// Enter the main loop.
	while (!glfwWindowShouldClose(window))
	{
		//Check time will update the programs clock and determine if & how many times the physics must be updated
		checkTime();

		// Call the render function.
		renderScene();

		// Swaps the back buffer to the front buffer
		// Remember, you're rendering to the back buffer, then once rendering is complete, you're moving the back buffer to the front so it can be displayed.
		glfwSwapBuffers(window);

		// Checks to see if any events are pending and then processes them.
		glfwPollEvents();
	}

	// Frees up GLFW memory
	glfwTerminate();
}
Esempio n. 22
0
int main(int argc, char **argv) {
    srand(time(NULL));
    rand();
    if (argc == 2 || argc == 3) {
        char *hostname = argv[1];
        int port = DEFAULT_PORT;
        if (argc == 3) {
            port = atoi(argv[2]);
        }
        db_disable();
        client_enable();
        client_connect(hostname, port);
        client_start();
    }
    if (!glfwInit()) {
        return -1;
    }
    create_window();
    if (!window) {
        glfwTerminate();
        return -1;
    }
    glfwMakeContextCurrent(window);
    glfwSwapInterval(VSYNC);
    glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);
    glfwSetKeyCallback(window, on_key);
    glfwSetMouseButtonCallback(window, on_mouse_button);
    glfwSetScrollCallback(window, on_scroll);

    #ifndef __APPLE__
        if (glewInit() != GLEW_OK) {
            return -1;
        }
    #endif

    if (db_init()) {
        return -1;
    }

    glEnable(GL_CULL_FACE);
    glEnable(GL_DEPTH_TEST);
    glEnable(GL_LINE_SMOOTH);
    glLogicOp(GL_INVERT);
    glClearColor(0.53, 0.81, 0.92, 1.00);

    GLuint texture;
    glGenTextures(1, &texture);
    glActiveTexture(GL_TEXTURE0);
    glBindTexture(GL_TEXTURE_2D, texture);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
    load_png_texture("texture.png");

    GLuint block_program = load_program(
        "shaders/block_vertex.glsl", "shaders/block_fragment.glsl");
    GLuint matrix_loc = glGetUniformLocation(block_program, "matrix");
    GLuint camera_loc = glGetUniformLocation(block_program, "camera");
    GLuint sampler_loc = glGetUniformLocation(block_program, "sampler");
    GLuint timer_loc = glGetUniformLocation(block_program, "timer");
    GLuint position_loc = glGetAttribLocation(block_program, "position");
    GLuint normal_loc = glGetAttribLocation(block_program, "normal");
    GLuint uv_loc = glGetAttribLocation(block_program, "uv");

    GLuint line_program = load_program(
        "shaders/line_vertex.glsl", "shaders/line_fragment.glsl");
    GLuint line_matrix_loc = glGetUniformLocation(line_program, "matrix");
    GLuint line_position_loc = glGetAttribLocation(line_program, "position");

    GLuint item_position_buffer = 0;
    GLuint item_normal_buffer = 0;
    GLuint item_uv_buffer = 0;
    int previous_block_type = 0;

    Chunk chunks[MAX_CHUNKS];
    int chunk_count = 0;

    Player players[MAX_PLAYERS];
    int player_count = 0;

    FPS fps = {0, 0};
    float matrix[16];
    float x = (rand_double() - 0.5) * 10000;
    float z = (rand_double() - 0.5) * 10000;
    float y = 0;
    float dy = 0;
    float rx = 0;
    float ry = 0;
    double px = 0;
    double py = 0;

    int loaded = db_load_state(&x, &y, &z, &rx, &ry);
    ensure_chunks(chunks, &chunk_count, x, y, z, 1);
    if (!loaded) {
        y = highest_block(chunks, chunk_count, x, z) + 2;
    }

    glfwGetCursorPos(window, &px, &py);
    double previous = glfwGetTime();
    while (!glfwWindowShouldClose(window)) {
        int width, height;
        glfwGetFramebufferSize(window, &width, &height);
        glViewport(0, 0, width, height);

        update_fps(&fps, SHOW_FPS);
        double now = glfwGetTime();
        double dt = MIN(now - previous, 0.2);
        previous = now;

        if (exclusive && (px || py)) {
            double mx, my;
            glfwGetCursorPos(window, &mx, &my);
            float m = 0.0025;
            rx += (mx - px) * m;
            ry -= (my - py) * m;
            if (rx < 0) {
                rx += RADIANS(360);
            }
            if (rx >= RADIANS(360)){
                rx -= RADIANS(360);
            }
            ry = MAX(ry, -RADIANS(90));
            ry = MIN(ry, RADIANS(90));
            px = mx;
            py = my;
        }
        else {
            glfwGetCursorPos(window, &px, &py);
        }

        int szlast = sz;
        int sxlast = sx;
        sz = 0;
        sx = 0;
        ortho = glfwGetKey(window, 'F');
        fov = glfwGetKey(window, GLFW_KEY_LEFT_SHIFT) ? 15.0 : 65.0;
        if (glfwGetKey(window, 'Q')) break;
        if (glfwGetKey(window, 'W')) sz--; 
        if (glfwGetKey(window, 'S')) sz++;
        if (glfwGetKey(window, 'A')) sx--;
        if (glfwGetKey(window, 'D')) sx++;
	if (sx != 0 || sz !=0 && flying == 0){
            acc = walking_speed > acc && acc > 0 ? acc + (acc - (acc / 3))  : walking_speed; }
        else{
            if(sx == 0 && sz == 0 && flying == 0){
                if(acc > 1 && acc > 0){
                    acc = acc - (acc / 1.45);
                    if(szlast != 0){sz = szlast; };
                    if(sxlast != 0){sx = sxlast; };}		
                else{
                    acc = .8;
                }

                }
            }
       
        float m = dt * 1.0;
        if (glfwGetKey(window, GLFW_KEY_LEFT)) rx -= m;
        if (glfwGetKey(window, GLFW_KEY_RIGHT)) rx += m;
        if (glfwGetKey(window, GLFW_KEY_UP)) ry += m;
        if (glfwGetKey(window, GLFW_KEY_DOWN)) ry -= m;
        float vx, vy, vz;
        get_motion_vector(flying, sz, sx, rx, ry, &vx, &vy, &vz);
        if (glfwGetKey(window, GLFW_KEY_SPACE)) {
            if (flying) {
                vy = 1;
            }
            else if (dy == 0) {
                dy = 8;
            }
        }
        if (glfwGetKey(window, 'Z')) {
            vx = -1; vy = 0; vz = 0;
        }
        if (glfwGetKey(window, 'X')) {
            vx = 1; vy = 0; vz = 0;
        }
        if (glfwGetKey(window, 'C')) {
            vx = 0; vy = -1; vz = 0;
        }
        if (glfwGetKey(window, 'V')) {
            vx = 0; vy = 1; vz = 0;
        }
        if (glfwGetKey(window, 'B')) {
            vx = 0; vy = 0; vz = -1;
        }
        if (glfwGetKey(window, 'N')) {
            vx = 0; vy = 0; vz = 1;
        }
        float speed = flying ? 20 : acc;
        int step = 8;
        float ut = dt / step;
        vx = vx * ut * speed;
        vy = vy * ut * speed;
        vz = vz * ut * speed;
        for (int i = 0; i < step; i++) {
            if (flying) {
                dy = 0;
            }
            else {
                dy -= ut * 25;
                dy = MAX(dy, -250);
            }
            x += vx;
            y += vy + dy * ut;
            z += vz;
            if (collide(chunks, chunk_count, 2, &x, &y, &z)) {
                dy = 0;
            }
        }
        if (y < 0) {
            y = highest_block(chunks, chunk_count, x, z) + 2;
        }

        if (left_click) {
            left_click = 0;
            int hx, hy, hz;
            int hw = hit_test(chunks, chunk_count, 0, x, y, z, rx, ry,
                &hx, &hy, &hz);
            if (hy > 0 && is_destructable(hw)) {
                set_block(chunks, chunk_count, hx, hy, hz, 0, 1);
                int above = get_block(chunks, chunk_count, hx, hy + 1, hz);
                if (is_plant(above)) {
                    set_block(chunks, chunk_count, hx, hy + 1, hz, 0, 1);
                }
            }
        }

        if (right_click) {
            right_click = 0;
            int hx, hy, hz;
            int hw = hit_test(chunks, chunk_count, 1, x, y, z, rx, ry,
                &hx, &hy, &hz);
            if (is_obstacle(hw)) {
                if (!player_intersects_block(2, x, y, z, hx, hy, hz)) {
                    set_block(chunks, chunk_count, hx, hy, hz, block_type, 1);
                }
            }
        }

        if (middle_click) {
            middle_click = 0;
            int hx, hy, hz;
            int hw = hit_test(chunks, chunk_count, 0, x, y, z, rx, ry,
                &hx, &hy, &hz);
            if (is_selectable(hw)) {
                block_type = hw;
            }
        }

        if (teleport) {
            teleport = 0;
            if (player_count) {
                int index = rand_int(player_count);
                Player *player = players + index;
                x = player->x; y = player->y; z = player->z;
                rx = player->rx; ry = player->ry;
                ensure_chunks(chunks, &chunk_count, x, y, z, 1);
            }
        }

        client_position(x, y, z, rx, ry);
        char buffer[RECV_BUFFER_SIZE];
        while (client_recv(buffer, RECV_BUFFER_SIZE)) {
            float ux, uy, uz, urx, ury;
            if (sscanf(buffer, "U,%*d,%f,%f,%f,%f,%f",
                &ux, &uy, &uz, &urx, &ury) == 5)
            {
                x = ux; y = uy; z = uz; rx = urx; ry = ury;
                ensure_chunks(chunks, &chunk_count, x, y, z, 1);
                y = highest_block(chunks, chunk_count, x, z) + 2;
            }
            int bx, by, bz, bw;
            if (sscanf(buffer, "B,%*d,%*d,%d,%d,%d,%d",
                &bx, &by, &bz, &bw) == 4)
            {
                set_block(chunks, chunk_count, bx, by, bz, bw, 0);
                if (player_intersects_block(2, x, y, z, bx, by, bz)) {
                    y = highest_block(chunks, chunk_count, x, z) + 2;
                }
            }
            int pid;
            float px, py, pz, prx, pry;
            if (sscanf(buffer, "P,%d,%f,%f,%f,%f,%f",
                &pid, &px, &py, &pz, &prx, &pry) == 6)
            {
                Player *player = find_player(players, player_count, pid);
                if (!player && player_count < MAX_PLAYERS) {
                    player = players + player_count;
                    player_count++;
                    player->id = pid;
                    player->position_buffer = 0;
                    player->normal_buffer = 0;
                    player->uv_buffer = 0;
                    printf("%d other players are online\n", player_count);
                }
                if (player) {
                    update_player(player, px, py, pz, prx, pry);
                }
            }
            if (sscanf(buffer, "D,%d", &pid) == 1) {
                delete_player(players, &player_count, pid);
                printf("%d other players are online\n", player_count);
            }
        }

        int p = chunked(x);
        int q = chunked(z);
        ensure_chunks(chunks, &chunk_count, x, y, z, 0);

        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

        set_matrix_3d(matrix, width, height, x, y, z, rx, ry, fov, ortho);

        // render chunks
        glUseProgram(block_program);
        glUniformMatrix4fv(matrix_loc, 1, GL_FALSE, matrix);
        glUniform3f(camera_loc, x, y, z);
        glUniform1i(sampler_loc, 0);
        glUniform1f(timer_loc, glfwGetTime());
        for (int i = 0; i < chunk_count; i++) {
            Chunk *chunk = chunks + i;
            if (chunk_distance(chunk, p, q) > RENDER_CHUNK_RADIUS) {
                continue;
            }
            if (y < 100 && !chunk_visible(chunk, matrix)) {
                continue;
            }
            draw_chunk(chunk, position_loc, normal_loc, uv_loc);
        }

        // render players
        for (int i = 0; i < player_count; i++) {
            Player *player = players + i;
            draw_player(player, position_loc, normal_loc, uv_loc);
        }

        // render focused block wireframe
        int hx, hy, hz;
        int hw = hit_test(
            chunks, chunk_count, 0, x, y, z, rx, ry, &hx, &hy, &hz);
        if (is_obstacle(hw)) {
            glUseProgram(line_program);
            glLineWidth(1);
            glEnable(GL_COLOR_LOGIC_OP);
            glUniformMatrix4fv(line_matrix_loc, 1, GL_FALSE, matrix);
            GLuint wireframe_buffer = gen_wireframe_buffer(hx, hy, hz, 0.51);
            draw_lines(wireframe_buffer, line_position_loc, 3, 48);
            glDeleteBuffers(1, &wireframe_buffer);
            glDisable(GL_COLOR_LOGIC_OP);
        }

        set_matrix_2d(matrix, width, height);

        // render crosshairs
        glUseProgram(line_program);
        glLineWidth(4);
        glEnable(GL_COLOR_LOGIC_OP);
        glUniformMatrix4fv(line_matrix_loc, 1, GL_FALSE, matrix);
        GLuint crosshair_buffer = gen_crosshair_buffer(width, height);
        draw_lines(crosshair_buffer, line_position_loc, 2, 4);
        glDeleteBuffers(1, &crosshair_buffer);
        glDisable(GL_COLOR_LOGIC_OP);

        // render selected item
        set_matrix_item(matrix, width, height);
        if (block_type != previous_block_type) {
            previous_block_type = block_type;
            gen_item_buffers(
                &item_position_buffer, &item_normal_buffer, &item_uv_buffer,
                block_type);
        }
        glUseProgram(block_program);
        glUniformMatrix4fv(matrix_loc, 1, GL_FALSE, matrix);
        glUniform3f(camera_loc, 0, 0, 5);
        glUniform1i(sampler_loc, 0);
        glUniform1f(timer_loc, glfwGetTime());
        glDisable(GL_DEPTH_TEST);
        draw_cube(
            item_position_buffer, item_normal_buffer, item_uv_buffer,
            position_loc, normal_loc, uv_loc);
        glEnable(GL_DEPTH_TEST);

        glfwSwapBuffers(window);
        glfwPollEvents();
    }
    client_stop();
    db_save_state(x, y, z, rx, ry);
    db_close();
    glfwTerminate();
    return 0;
}
Esempio n. 23
0
int main(void)
{
    GLFWwindow* window;

    // Initialise GLFW
    if (!glfwInit())
    {
        fprintf(stderr, "Failed to initialize GLFW\n");
        exit(EXIT_FAILURE);
    }

    // Open OpenGL window
    window = glfwCreateWindow(500, 500, "Split view demo", NULL, NULL);
    if (!window)
    {
        fprintf(stderr, "Failed to open GLFW window\n");

        glfwTerminate();
        exit(EXIT_FAILURE);
    }

    // Set callback functions
    glfwSetWindowSizeCallback(window, windowSizeFun);
    glfwSetWindowRefreshCallback(window, windowRefreshFun);
    glfwSetCursorPosCallback(window, cursorPosFun);
    glfwSetMouseButtonCallback(window, mouseButtonFun);
    glfwSetKeyCallback(window, key_callback);

    // Enable vsync
    glfwMakeContextCurrent(window);
    glfwSwapInterval(1);

    glfwGetWindowSize(window, &width, &height);
    windowSizeFun(window, width, height);

    // Main loop
    for (;;)
    {
        // Only redraw if we need to
        if (do_redraw)
        {
            // Draw all views
            drawAllViews();

            // Swap buffers
            glfwSwapBuffers(window);

            do_redraw = 0;
        }

        // Wait for new events
        glfwWaitEvents();

        // Check if the window should be closed
        if (glfwWindowShouldClose(window))
            break;
    }

    // Close OpenGL window and terminate GLFW
    glfwTerminate();

    exit(EXIT_SUCCESS);
}
Esempio n. 24
0
int Game::Initialize(){
    
    LOG(info) << "Jarg initialization start";
    glfwSetErrorCallback([](int a,const char* description){LOG(error) << description;});

    int glfwErrorCode = glfwInit();
    if (!glfwErrorCode)
    {
        LOG(error) << "glfwInit error " << glfwErrorCode;
        return glfwErrorCode;
    }

    glfwWindowHint(GLFW_SAMPLES, 4);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, Game::MAJOR_GL);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, Game::MINOR_GL);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);

    monitor = nullptr;
    if(fullscreen)
    {
        monitor = glfwGetPrimaryMonitor();
    }

    window = glfwCreateWindow(width, height, title.c_str(), monitor, nullptr);
    if (!window)
    {
        glfwTerminate();
        LOG(fatal) << "Ошибка создания окна GLFW.";
        return false;
    }
    glfwMakeContextCurrent(window);
    //glfwSetWindowTitle(window, AutoVersion::GetTitle().c_str());

    glfwSwapInterval(0);

    if (glewInit() != GLEW_OK) 
    {
        LOG(fatal) << "GLEW не инициализирован.";
        return false;
    }

    GameObject go;
    go.seed = 123;
    for (int i =0; i<100; i++)
    {
        GenerateStar(&go);
    }

    int glVersion[2] = {-1, -1};
    glGetIntegerv(GL_MAJOR_VERSION, &glVersion[0]); 
    glGetIntegerv(GL_MINOR_VERSION, &glVersion[1]); 

    LOG(info) << "Renderer: " << glGetString(GL_RENDERER);
    LOG(info) << "Vendor: " <<  glGetString(GL_VENDOR);
    LOG(info) << "Version: " <<  glGetString(GL_VERSION);
    LOG(info) << "GLSL version: " <<  glGetString(GL_SHADING_LANGUAGE_VERSION);
    LOG(info) << "using OpenGL: " << std::to_string(glVersion[0]) << "." << std::to_string(glVersion[1]);
    LOG(info) << "glfw: " << glfwGetVersionString();

    Keyboard::Initialize();
    glfwSetKeyCallback(window, [](GLFWwindow *win, int key, int scancode, int action, int mods){Keyboard::SetKey(key, scancode, action, mods);});

    Mouse::Initialize(window);
    Mouse::SetWindowSize(width, height);
    //	Mouse::SetFixedPosState(true);
    glfwSetCursorPosCallback(window, [](GLFWwindow *window, double xpos, double ypos){Mouse::SetCursorPos(xpos, ypos);});
    glfwSetCursorEnterCallback(window, [](GLFWwindow *window, int entered){Mouse::CursorClientArea(entered);});	
    glfwSetWindowFocusCallback(window, [](GLFWwindow *window, int focused){Mouse::WindowFocus(focused);});
    glfwSetMouseButtonCallback(window, [](GLFWwindow *window, int a, int b, int c){Mouse::SetButton(a, b, c);});
    glfwSetWindowSizeCallback(window, [](GLFWwindow *window, int a, int b){Game::Resize(a, b); Mouse::SetWindowSize(a, b);});
    glfwSetScrollCallback(window, [](GLFWwindow *window, double a, double b){Mouse::Scroll(b);});
    wire = 1;
    spd = 1;

    //////////////////////////////////////////////////////////////////////////
    LinesShader = std::shared_ptr<BasicJargShader>(new BasicJargShader());
    LinesShader->loadShaderFromSource(GL_VERTEX_SHADER, "Shaders/colored.glsl");
    LinesShader->loadShaderFromSource(GL_FRAGMENT_SHADER, "Shaders/colored.glsl");
    LinesShader->Link();
    mvpLine = LinesShader->locateVars("MVP");

    TextureShader = std::shared_ptr<BasicJargShader>(new BasicJargShader());
    TextureShader->loadShaderFromSource(GL_VERTEX_SHADER, "Shaders/textured.glsl");
    TextureShader->loadShaderFromSource(GL_FRAGMENT_SHADER, "Shaders/textured.glsl");
    TextureShader->Link();
    mvpTex = TextureShader->locateVars("MVP");

    FXAAShader = std::shared_ptr<BasicJargShader>(new BasicJargShader());
    FXAAShader->loadShaderFromSource(GL_VERTEX_SHADER, "Shaders/fxaa.glsl");
    FXAAShader->loadShaderFromSource(GL_FRAGMENT_SHADER, "Shaders/fxaa.glsl");
    FXAAShader->Link();

    BasicShader = std::shared_ptr<BasicJargShader>(new BasicJargShader());
    BasicShader->loadShaderFromSource(GL_VERTEX_SHADER, "Shaders/minnaert.glsl");
    BasicShader->loadShaderFromSource(GL_FRAGMENT_SHADER, "Shaders/minnaert.glsl");
    BasicShader->loadShaderFromSource(GL_TESS_CONTROL_SHADER, "Shaders/minnaert.glsl");
    BasicShader->loadShaderFromSource(GL_TESS_EVALUATION_SHADER, "Shaders/minnaert.glsl");
    BasicShader->Link();
    BasicShader->UpdateUniforms();
    BasicShader->locateVars("transform.viewProjection"); //var0
    BasicShader->locateVars("transform.model"); //var1
    BasicShader->locateVars("transform.normal"); //var2
    BasicShader->locateVars("material.texture");

    testtex = std::shared_ptr<Texture>(new Texture());
    testtex->Empty(vec2(256,256));

    uptex = std::shared_ptr<Texture>(new Texture());
    uptex->Load("up.png");

    //////////////////////////////////////////////////////////////////////////

    light.position = vec4(5.0f, 12.0f, 3.0f, 1.0f);
    light.ambient = vec4(0.2f, 0.2f, 0.2f, 1.0f);
    light.diffuse = vec4(1.0f, 1.0f, 1.0f, 1.0f);
    light.specular = vec4(1.0f, 1.0f, 1.0f, 1.0f);
    light.attenuation = vec3(0.000f, 0.0f, 0.00000f);

    batched = std::unique_ptr<Batched>(new Batched());
    batched->Initialize(TextureShader.get(), LinesShader.get());

    font = std::unique_ptr<Font>(new Font());
    font->Initialize();
    //actually not load json
    if(!font->Create("font.json")){
        LOG(error) << "failed to load\process font.json";
    }

    WindowsDesigner();

    camera = std::unique_ptr<Camera>(new Camera());
    camera->SetViewport(0, 0, width, height);
    camera->SetPosition(vec3(2,2,2));
    camera->SetLookAt(vec3(0));
    gt = std::unique_ptr<GameTimer>(new GameTimer);

    Generation gen;

    rs = new QuadTreePlane();
    rs->Init(BasicShader, *camera);

    auto tex = std::shared_ptr<Texture>(new Texture());
    tex->Load("normal.png");

    icos = std::unique_ptr<Mesh>(new Mesh(Cube::getMesh()));
    icos->Bind();
    icos->shader = BasicShader;
    icos->material = std::shared_ptr<Material>(new Material());
    icos->material->texture = tex;

    //test.LoadBinary("untitled.m");
    test.Bind();
    for (int i = 0; i<test.meshes.size(); i++)
    {
        test.meshes[i]->shader = BasicShader;
    }

    return true;
}
Esempio n. 25
0
void main()
{
	glfwInit();

	// Create a window
	window = glfwCreateWindow(800, 800, "Sphere - Triangle (3D Dynamic Collision Detection)", nullptr, nullptr);
	glfwMakeContextCurrent(window);
	glfwSwapInterval(0);

	// Initializes most things needed before the main loop
	init();


	//Generate the sphere mesh
	float scale = 0.1f;
	
	GenerateSphereMesh(1.0f, 40);

	//Generate the triangle mesh
	struct Vertex triVerts[3] = 
	{
		{-1.0f, -1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f},
		{1.0f, -1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f},
		{0.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f}
	};

	//triangle creation
	triangle = new struct Mesh(3, triVerts, GL_TRIANGLES);


	//Scale the shapes
	sphere->scale = glm::scale(sphere->scale, glm::vec3(scale));
	triangle->scale = glm::scale(triangle->scale, glm::vec3(scale));


	//Generate the rigidbodies
	sphereBody = new struct RigidBody(
		glm::vec3(-1.0f, 0.0f, 0.0f),		//Start on left side of screen
		glm::vec3(1.0f, 0.0f, 0.0f),		//constant right velocity
		glm::vec3(0.0f, 0.0f, 0.0f)			//Zero acceleration
		);

	triangleBody = new struct RigidBody(
		glm::vec3(0.75f, 0.0f, 0.0f),		//Start on right side
		glm::vec3(-0.5f, 0.0f, 0.0f),		//Constant left velocity
		glm::vec3(0.0f, 0.0f, 0.0f)			//Zero acceleration
		);

	//Position shapes
	sphere->translation = glm::translate(sphere->translation, sphereBody->position);
	triangle->translation = glm::translate(triangle->translation, triangleBody->position);

	//Generate the colliders
	sphereCollider = new Sphere(sphereBody->position, scale);
	triangleCollider = new Triangle(triangleBody->position, 
		scale * glm::vec3(triVerts[0].x, triVerts[0].y, triVerts[0].z), scale * glm::vec3(triVerts[1].x, triVerts[1].y, triVerts[1].z), scale * glm::vec3(triVerts[2].x, triVerts[2].y, triVerts[2].z));

	//Print controls
	std::cout << "Controls:\nPress and hold spacebar to disable continuous collision detection.\nWhen two shapes collide, continue the simulation by toggling continuous collision detection off.\n";

	// Enter the main loop.
	while (!glfwWindowShouldClose(window))
	{
		//Check time will update the programs clock and determine if & how many times the physics must be updated
		checkTime();

		// Call the render function.
		renderScene();

		// Swaps the back buffer to the front buffer
		// Remember, you're rendering to the back buffer, then once rendering is complete, you're moving the back buffer to the front so it can be displayed.
		glfwSwapBuffers(window);

		// Checks to see if any events are pending and then processes them.
		glfwPollEvents();
	}

	// After the program is over, cleanup your data!
	glDeleteShader(vertex_shader);
	glDeleteShader(fragment_shader);
	glDeleteProgram(program);
	// Note: If at any point you stop using a "program" or shaders, you should free the data up then and there.

	delete sphere;
	delete triangle;
	delete sphereBody;
	delete triangleBody;
	delete sphereCollider;
	delete triangleCollider;

	// Frees up GLFW memory
	glfwTerminate();
}
Esempio n. 26
0
int main(int argc, char *argv[])
{
  // UI-related variables
  int running = 0;
  int mousebtn1, lastmousebtn1;
  int mousex, mousey, lastmousex, lastmousey;
  float posx, posy, zoom, rotx, rotz;

  // Shader-related variables
  GLuint textureID;
  int texw = 0;
  int texh = 0;
  GLhandleARB programObj;
  
  // Initialise GLFW
  glfwInit();
  
  // Open OpenGL window
  if( !glfwOpenWindow( 512, 512, 0,0,0,0, 0,0, GLFW_WINDOW ) )
    {
      glfwTerminate();
      return 0;
    }

  // Init user interface (mouse drag for pan/zoom/tilt/rotation)
  posx = 0.0f;
  posy = 0.0f;
  zoom = 1.0f;
  rotx = 0.0f;
  rotz = 0.0f;
  glfwGetMousePos(&mousex, &mousey); // Requires an open window
  lastmousex = mousex;
  lastmousey = mousey;
  mousebtn1 = lastmousebtn1 = GLFW_RELEASE;
  
  // Load OpenGL extensions (requires an open window)
  loadExtensions();
  
  // Load textures  
  glEnable(GL_TEXTURE_2D);
  glGenTextures( 1, &textureID );
  loadDistTexture(PATH "disttex.tga", textureID, &texw, &texh);
  
  // Create, load and compile the shader programs
  programObj = createShader(PATH "vertex.glsl", PATH "fragment1.glsl");
  
  // Disable vertical sync (on cards that support
  // it, and if current driver settings so permit)
  glfwSwapInterval( 1 );
  
  // Main loop
  running = GL_TRUE;
  while( running )
    {
      showFPS(texw, texh, zoom);
      
      // Set the uniform shader variables
      setUniformVariables(programObj, 0, (float)texw, (float)texh);

      renderScene(programObj, posx, posy, zoom, rotx, rotz);
      
      glfwSwapBuffers();
      
      // Handle mouse pan (button 1 drag), zoom (shift-btn 1 drag up/down),
      // tilt (ctrl-btn 1 drag up/down) and rotation (ctrl-btn 1 drag left/right)
      lastmousebtn1 = mousebtn1;
      mousebtn1 = glfwGetMouseButton(GLFW_MOUSE_BUTTON_1);
      lastmousex = mousex;
      lastmousey = mousey;
      glfwGetMousePos(&mousex, &mousey);
      
      if((mousebtn1 == GLFW_PRESS) && (lastmousebtn1 == GLFW_PRESS)) {
        if(glfwGetKey(GLFW_KEY_LSHIFT)) {
          zoom *= pow(1.01, (lastmousey - mousey));
	      if(zoom < 0.26f) zoom = 0.26f; // Do not go beyond 180 degrees FOV
        }
        else if (glfwGetKey(GLFW_KEY_LCTRL)) {
          rotz -= (lastmousex - mousex) * 0.5;
          rotx += (lastmousey - mousey) * 0.5;
      	  if(rotx > 89.5f) rotx = 89.5f;
          if(rotx < 0.0f) rotx = 0.0f;
        }
        else {
      	  posx += (lastmousex - mousex) / zoom;
	      posy += (lastmousey - mousey) / zoom;
        }
      }

      if(glfwGetKey('1')) {
        programObj = createShader(PATH "vertex.glsl", PATH "fragment1.glsl");
      }
      if(glfwGetKey('2')) {
        programObj = createShader(PATH "vertex.glsl", PATH "fragment2.glsl");
      }
      if(glfwGetKey('3')) {
        programObj = createShader(PATH "vertex.glsl", PATH "fragment3.glsl");
      }
      if(glfwGetKey('4')) {
        programObj = createShader(PATH "vertex.glsl", PATH "fragment4.glsl");
      }

      // Check if the ESC key is pressed or the window has been closed
      running = !glfwGetKey( GLFW_KEY_ESC ) &&
	glfwGetWindowParam( GLFW_OPENED );
    }
  
  // Close the window (if still open) and terminate GLFW
  glfwTerminate();
  
  return 0;
}
Esempio n. 27
0
///
/// \brief main
/// \return
///
int
main( void )
{

  std::cout << "Running graphics program" << std::endl;


  GLFWwindow *window;

  if ( !glfwInit( ) )
  {

    std::cerr << "GLFW initialization failed" << std::endl;
    return -1; // failure

  }

  glfwSetErrorCallback( error_callback );
  
  int WIDTH  = 640;
  int HEIGHT = 480;


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

  window = glfwCreateWindow( WIDTH, HEIGHT, "Windows Test", 0, 0 );

  if ( !window )
  {

    glfwTerminate( );
    return -1; // failure

  }

  glfwMakeContextCurrent( window );
  glfwSwapInterval( 1 );
  glfwSetKeyCallback( window, key_callback );


  if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress))
  {
	  std::cout << "Failed to initialize OpenGL context" << std::endl;
	  return -1;
  }

  // Define the viewport dimensions and clear color
  glViewport(0, 0, WIDTH, HEIGHT);
  glClearColor(1.f, 0.5f, 0.1f, 1.f);



  std::cout << "Entering main loop" << std::endl;


  while ( !glfwWindowShouldClose( window ) )
  {
	
	glClear(GL_COLOR_BUFFER_BIT);

    glfwSwapBuffers( window );
    glfwPollEvents( );

  }


  glfwTerminate( );


  std::cout << "Exiting program..." << std::endl;

} // main
Esempio n. 28
0
int main(int argc, char* argv[])
{
    GLFWwindow* window;
    double t, dt_total, t_old;
    int width, height;

    glfwSetErrorCallback(error_callback);

    if (!glfwInit())
        exit(EXIT_FAILURE);

    window = glfwCreateWindow(640, 480, "Wave Simulation", NULL, NULL);
    if (!window)
    {
        glfwTerminate();
        exit(EXIT_FAILURE);
    }

    glfwSetKeyCallback(window, key_callback);
    glfwSetFramebufferSizeCallback(window, framebuffer_size_callback);
    glfwSetMouseButtonCallback(window, mouse_button_callback);
    glfwSetCursorPosCallback(window, cursor_position_callback);
    glfwSetScrollCallback(window, scroll_callback);

    glfwMakeContextCurrent(window);
    gladLoadGLLoader((GLADloadproc) glfwGetProcAddress);
    glfwSwapInterval(1);

    glfwGetFramebufferSize(window, &width, &height);
    framebuffer_size_callback(window, width, height);

    // Initialize OpenGL
    init_opengl();

    // Initialize simulation
    init_vertices();
    init_grid();
    adjust_grid();

    // Initialize timer
    t_old = glfwGetTime() - 0.01;

    while (!glfwWindowShouldClose(window))
    {
        t = glfwGetTime();
        dt_total = t - t_old;
        t_old = t;

        // Safety - iterate if dt_total is too large
        while (dt_total > 0.f)
        {
            // Select iteration time step
            dt = dt_total > MAX_DELTA_T ? MAX_DELTA_T : dt_total;
            dt_total -= dt;

            // Calculate wave propagation
            calc_grid();
        }

        // Compute height of each vertex
        adjust_grid();

        // Draw wave grid to OpenGL display
        draw_scene(window);

        glfwPollEvents();
    }

    exit(EXIT_SUCCESS);
}
Esempio n. 29
0
int main(int argc, char **argv )
{
    bool headless_mode=false;
    for(int i=0;;i++) {
        if(!argv[i])break;
        if(strcmp(argv[i], "--headless") == 0 ) headless_mode = true;
    }

    print("program start");

#ifdef __APPLE__    
    setlocale( LC_ALL, "ja_JP");
#endif
#ifdef WIN32    
    setlocale( LC_ALL, "jpn");
#endif    
    
    // glfw
    if( !glfwInit() ) {
        print("can't init glfw");
        return 1;
    }

    GLFWwindow *window;
    glfwSetErrorCallback( glfw_error_cb );
    window =  glfwCreateWindow( SCRW, SCRH, "min2d", NULL, NULL );
    if(window == NULL ) {
        print("can't open glfw window");
        glfwTerminate();
        return 1;
    }
    glfwMakeContextCurrent(window);    
    glfwSetWindowCloseCallback( window, winclose_callback );
    glfwSetInputMode( window, GLFW_STICKY_KEYS, GL_TRUE );
    glfwSwapInterval(0); // set 1 to use vsync. Use 0 for fast screen capturing and headless
    glfwSetKeyCallback( window, kbdCallback );
#ifdef WIN32
	glewInit();
#endif
    glClearColor(0.2,0.2,0.2,1);

    SoundSystem *ss = new SoundSystem();
    Sound *bgm = ss->newSound( "assets/gymno1short.wav" );
    bgm->play();

    g_keyboard = new Keyboard();
    
    MoyaiClient *moyai_client = new MoyaiClient(window,SCRW,SCRH);
    
    if( headless_mode ) {
        Moyai::globalInitNetwork();
        RemoteHead *rh = new RemoteHead();
        int port = 22222;
        if( rh->startServer(port) == false ) {
            print("headless server: can't start server. port:%d", 22222 );
            exit(1);
        } else {
            print("Start headless server port:%d",port);
        }
        rh->enableSpriteStream();
        rh->enableReprecation(REPRECATOR_SERVER_PORT);
        moyai_client->setRemoteHead(rh);
        rh->setTargetMoyaiClient(moyai_client);
        ss->setRemoteHead(rh);
        rh->setTargetSoundSystem(ss);
        rh->setOnKeyboardCallback(onRemoteKeyboardCallback);
    }

    
    Viewport *viewport = new Viewport();
    int retina = 1;
#if defined(__APPLE__)
    retina = 2;
#endif    
    viewport->setSize(SCRW*retina,SCRH*retina); // set actual framebuffer size to output
    viewport->setScale2D(SCRW,SCRH); // set scale used by props that will be rendered

    float zoom_rate = 1.0f;
    Vec2 center(0,0);
    Camera *camera = new Camera();
    camera->setLoc(0,0);

    Layer *l = new Layer();
    moyai_client->insertLayer(l);
    l->setViewport(viewport);
    l->setCamera(camera);

    Texture *t = new Texture();
    t->load( "./assets/base.png" );
    
    TileDeck *deck = new TileDeck();
    deck->setTexture(t);
    deck->setSize(32,32,8,8);

    Prop2D *p=NULL, *pp=NULL;
    Grid *g=NULL;
    CharGrid *cg=NULL;
    

    // normal single
    p = new Prop2D();
    p->setDeck(deck);
    p->setIndex(1);
    p->setScl(64,64);
    p->setLoc(0,0);
    l->insertProp(p);
#if 0
    // with prim
    pp = new Prop2D();
    pp->setScl(1.0f);
    pp->setLoc(100,0);
    pp->addRect( Vec2(0,0), Vec2(-100,-100), Color(0,0,1,0.5) );
    pp->addLine( Vec2(0,0), Vec2(100,100), Color(1,0,0,1) );
    pp->addLine( Vec2(0,0), Vec2(100,-100), Color(0,1,0,1), 5 );
    l->insertProp(pp);
   

    // grid
    g = new Grid(4,4);
    for(int x=0;x<4;x++) {
        for(int y=0;y<4;y++) {
            //        g->set(x,y,80+((x+y)%10));
            g->set(x,y,((x+y)%3));
        }
    }
    g->setXFlip(0,0,true); 
    g->setYFlip(0,1,true);
    g->setUVRot(0,2,true);

    Prop2D *gp = new Prop2D();
    gp->setDeck(deck);
    gp->addGrid(g);
    gp->setScl(32)    ;
    gp->setLoc(50,0);
    gp->setRot(20);
    gp->setIndex(0);
    l->insertProp(gp);

    // uvrot 
    Prop2D *rotp = new Prop2D();
    rotp->setDeck(deck);
    rotp->setScl(32);
    rotp->setLoc(-300,-100);
    rotp->setUVRot(true);
    rotp->setIndex(0);
    l->insertProp(rotp);

    // chargrid
    Texture *ft = new Texture();
    ft->load("./assets/font_only.png");
    TileDeck *fdeck =new TileDeck();
    fdeck->setTexture(ft);
    fdeck->setSize(32,32,8,8);
    cg = new CharGrid(8,8);
    cg->ascii_offset = -32;
    cg->setDeck(fdeck);
    cg->printf(0,0,Color(1,1,1,1), "WHITE" );
    cg->printf(1,1,Color(1,0,0,1), "RED" );
    cg->printf(2,2,Color(0,1,0,1), "GREEN" );
    cg->printf(3,3,Color(0,0,1,1), "BLUE" );
    Prop2D *cgp = new Prop2D();
    cgp->addGrid(cg);
    cgp->setScl(16);
    cgp->setLoc(50,-100);
    l->insertProp(cgp);

    // children
    Prop2D *chp = new Prop2D();
    chp->setLoc(-200,-200);
    chp->setDeck(deck);
    chp->setScl(48);
    chp->setIndex(0);
    for(int i=0;i<8;i++) {
        Prop2D *p = new Prop2D();
        p->setDeck(deck);
        p->setLoc( chp->loc + Vec2( (i+1)*30,0 ) );
        p->setIndex(0);
        p->setScl( 36-i*3 );
        chp->addChild(p);
    }
    
    Prop2D *dynchp = new Prop2D();
    dynchp->setLoc( chp->loc + Vec2(0,-30) );
    dynchp->setIndex(0);
    dynchp->setScl(32);
    dynchp->setDeck(deck);
    chp->addChild(dynchp);
    l->insertProp(chp);
#endif    

#if 0
    // text
    wchar_t charcodes[] = L" !\"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~あいうえお";
    
    Font *font = new Font();
    font->loadFromTTF("./assets/cinecaption227.ttf", charcodes, 24 );
    TextBox *tbs[20];
    for(int i=0;i<20;i++) {
        tbs[i] = new TextBox();
        tbs[i]->setFont(font);
        tbs[i]->setString("A");
        tbs[i]->setScl(1+(float)i/10.0f);
        tbs[i]->setLoc(i*10-250,0);
        l->insertProp(tbs[i]);
    }
    TextBox *movtb = new TextBox();
    movtb->setFont(font);
    movtb->setString("ABCabc\n01234あいうえお");
    movtb->setScl(3);
    movtb->setLoc(0,-150);
    l->insertProp(movtb);

    // multiple viewport and layer
    Viewport *vp2 = new Viewport(); // testing multiple viewport scaling
    vp2->setSize(SCRW*retina,SCRH*retina); 
    vp2->setScale2D(SCRW*2,SCRH*2); 
    Camera *cam2 = new Camera();
    Layer *l2 = new Layer();
    l2->setViewport(vp2);
    l2->setCamera(cam2);
    Prop2D *p2 = new Prop2D();
    p2->setDeck(deck);
    p2->setScl(48,48);
    p2->setIndex(0);
    p2->setLoc(200,-200);
    l2->insertProp(p2);
    moyai_client->insertLayer(l2);

#endif
    
    // main loop

    while( !glfwWindowShouldClose(window) ){
        static int frame_counter = 0;
        static int loop_counter = 0;

        static double last_t = now();
        
        double t = now();
        double dt = t -last_t;
        last_t = t;

        double loop_start_at = t;
                
        frame_counter ++;
        loop_counter++;
        
        Vec2 at(::sin(t)*100,0);
        if(p){
            p->setLoc(at);
            if( loop_counter%21==0 )  p->setIndex( irange(0,3));
            static float rot=0;
            rot+=0.05;
            p->setRot(rot);
            p->setScl( 40 + ::sin(t/2) * 30 );
            if(pp) {
                pp->setRot(rot/2.0f);
            }

            if( loop_counter % 50 == 0 ) {
                float alpha = range(0.2, 1.0f);
                Color col(range(0,1),range(0,1),range(0,1),alpha);
                p->setColor(col);
            }
            if( loop_counter % 120 == 0 ) {
                switch(irange(0,3)) {
                case 0: p->setXFlip( irange(0,2)); break;
                case 1: p->setYFlip( irange(0,2)); break;
                case 2: p->setUVRot( irange(0,2)); break;
                }
            }            
        }

        int cnt = moyai_client->poll(dt);        

        if(g) {
            g->set( irange(0,4), irange(0,4), irange(0,3) );
            g->setColor( irange(0,4), irange(0,4), Color( range(0,1), range(0,1), range(0,1), range(0,1) ) );
        }
#if 0
        float tbr = 4 + ::sin(t)*3;
        movtb->setScl(tbr);

        Format fmt("%d", loop_counter);
        tbs[19]->setString(fmt.buf);
#endif
        
        // fps disp
        static double last_print_at = 0;
        if(last_print_at == 0){
            last_print_at = t;
        } else if( last_print_at < t-1 ){
        fprintf(stderr,"FPS:%d prop:%d drawcall:%d\n", frame_counter, cnt, moyai_client->last_draw_call_count  );
            frame_counter = 0;
            last_print_at = t;
        }

        moyai_client->render();
        //        print("drawcnt:%d", moyai_client->last_draw_call_count );
        if( g_keyboard->getKey( 'Q') ) {
            print("Q pressed");
            exit(0);
            break;
        }
        if( g_keyboard->getKey( 'L' ) ) {
            zoom_rate += 0.2;
            if( zoom_rate > 8 ) zoom_rate = 8;
        }
        if( g_keyboard->getKey( 'K' ) ) {
            zoom_rate -= 0.1;
            if( zoom_rate < 0.1 ) zoom_rate = 0.1;
        }
        viewport->setScale2D(SCRW * zoom_rate,SCRH * zoom_rate); 

        float scrollspeed = 10;
        if( g_keyboard->getKey( 'W' ) ) {
            center.y -= scrollspeed;
        }
        if( g_keyboard->getKey( 'S' ) ) {
            center.y += scrollspeed;
        }
        if( g_keyboard->getKey( 'A' ) ) {
            center.x += scrollspeed;
        }
        if( g_keyboard->getKey( 'D' ) ) {
            center.x -= scrollspeed;
        }
        camera->setLoc(center);

        
        if( g_keyboard->getKey( '1' ) ) {
            for(int i=0;i<50;i++) {
                Prop *p = new Particle(deck);
                l->insertProp(p);
            }
        }
        if( g_keyboard->getKey( '2' ) ) {
            if(cg) cg->printf(0,4, Color(1,1,1,1), Format( "CNT:%d", loop_counter).buf);
        }
#if 0        
        if( loop_counter % 25 == 0 ) {
            if( dynchp ) {
                bool res = chp->clearChild(dynchp);
                assert(res);
                delete dynchp;
                dynchp = NULL;
            } else {
                dynchp = new Prop2D();
                dynchp->setLoc( chp->loc + Vec2(0,-30) );
                dynchp->setIndex(0);
                dynchp->setScl(32);
                dynchp->setDeck(deck);
                chp->addChild(dynchp);
            }            
        }
#endif        
        glfwPollEvents();

        double loop_end_at = now();
        double loop_time = loop_end_at - loop_start_at;
        double ideal_frame_time = 1.0f / 60.0f;
        if(loop_time < ideal_frame_time ) {
            double to_sleep_sec = ideal_frame_time - loop_time;
            int to_sleep_msec = (int) (to_sleep_sec*1000);
            if( to_sleep_msec > 0 ) sleepMilliSec(to_sleep_msec);
        }
    }
    glfwTerminate();

    print("program finished");
    

    return 0;
}
Esempio n. 30
0
int main(int argc, char* argv[])
{
    glfwSetErrorCallback(error_callback);
    if (!glfwInit())
    {
        return -1;
    }
    
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2);
    glfwWindowHint(GLFW_RED_BITS, 8);
    glfwWindowHint(GLFW_GREEN_BITS, 8);
    glfwWindowHint(GLFW_BLUE_BITS, 8);
    glfwWindowHint(GLFW_ALPHA_BITS, 8);
    glfwWindowHint(GLFW_DEPTH_BITS, 24);
    glfwWindowHint(GLFW_STENCIL_BITS, 0);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
    //glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
    glfwWindowHint(GLFW_OPENGL_DEBUG_CONTEXT, GL_TRUE);
    GLFWwindow* window = glfwCreateWindow(SCREEN_WIDTH, SCREEN_HEIGHT, APP_NAME, NULL, NULL);
    if (!window)
    {
        glfwTerminate();
        return -1;
    }
    
    glfwMakeContextCurrent(window);
    glfwSetKeyCallback(window, key_callback);
    glfwSwapInterval(1);
    
#if _WIN32
    glewExperimental = GL_TRUE;
    auto glewErr = glewInit();
    if (glewErr != GLEW_OK)
    {
        puts((const char*)glewGetErrorString(glewErr));
        return 1;
    }
    // glewInit() occurs glGetError() == GL_INVALID_ENUM
    GLint glErr;
    while((glErr = glGetError()) != GL_NO_ERROR)
    {
    }
#endif
    
    DrawContext cont;
    memset(&cont, 0, sizeof cont);
    
    init(cont);
    
    while (!glfwWindowShouldClose(window))
    {
        paint(cont);
        glfwSwapBuffers(window);
        glfwPollEvents();
    }
    
    glfwDestroyWindow(window);
    glfwTerminate();
    return 0;
}