void EnvirePhysics::updatePositions( const GraphTraits::vertex_descriptor origin,
                                    const GraphTraits::vertex_descriptor target,
                                    const TransformWithCovariance& originToRoot)
{
#ifdef DEBUG  
  LOG_DEBUG("EnvirePhysics::updatePositions");
#endif


  Transform tf = control->graph->getTransform(origin, target);

  if (control->graph->containsItems<envire::core::Item<std::shared_ptr<mars::sim::SimNode>>>(target))
  {
    // Update simulation node
    using simNodeType = envire::core::Item<std::shared_ptr<mars::sim::SimNode>>;
    using IteratorSimNode = EnvireGraph::ItemIterator<simNodeType>;
    IteratorSimNode begin_sim, end_sim;
    boost::tie(begin_sim, end_sim) = control->graph->getItems<simNodeType>(target);
    double calc_ms = control->sim->getCalcMs();
    for (;begin_sim!=end_sim; begin_sim++)
    {
      const std::shared_ptr<mars::sim::SimNode> sim_node = begin_sim->getData();
      sim_node->update(calc_ms);

      TransformWithCovariance absolutTransform;
      absolutTransform.translation = sim_node->getPosition();
      absolutTransform.orientation = sim_node->getRotation();    

      tf.setTransform(originToRoot * absolutTransform); 
      control->graph->updateTransform(origin, target, tf);
    }
  }

  if (control->graph->containsItems<envire::core::Item<std::shared_ptr<mars::sim::SimJoint>>>(target))
  {
    // Update simulation Joints
    using simJointType = envire::core::Item<std::shared_ptr<mars::sim::SimJoint>>;
    using IteratorSimJoint = EnvireGraph::ItemIterator<simJointType>;
    IteratorSimJoint begin_sim, end_sim;
    boost::tie(begin_sim, end_sim) = control->graph->getItems<simJointType>(target);
    double calc_ms = control->sim->getCalcMs();
    for (;begin_sim!=end_sim; begin_sim++)
    {
      const std::shared_ptr<mars::sim::SimJoint> sim_joint = begin_sim->getData();
      sim_joint->update(calc_ms);
    }
  }

  const Transform invTf = control->graph->getTransform(target, origin);
  updateChildPositions(target, invTf.transform * originToRoot);
}
Example #2
0
// Update Context
OSVRWRAPPER_API void OSVR_Update()
{
	Context->update();

	// Initialize HMD When Context Is Ready
	if(!IsHMDInit && Context->checkStatus()) OnInitHMD();

}
Example #3
0
void update(float _dt) {

    g_time += _dt;

    for (auto& ease : m_eases) {
        if (!ease.finished()) { ease.update(_dt); }
    }

    m_inputHandler->update(_dt);

    m_view->update();

    {
        std::lock_guard<std::mutex> lock(m_tilesMutex);
        ViewState viewState {
            m_view->getMapProjection(),
            m_view->changedOnLastUpdate(),
            glm::dvec2{m_view->getPosition().x, -m_view->getPosition().y },
            m_view->getZoom()
        };

        m_tileManager->updateTileSets(viewState, m_view->getVisibleTiles());

        bool updateLabels = m_labels->needUpdate();
        auto& tiles = m_tileManager->getVisibleTiles();

        if (m_view->changedOnLastUpdate() || m_tileManager->hasTileSetChanged()) {
            for (const auto& tile : tiles) {
                tile->update(_dt, *m_view);
            }
            updateLabels = true;
        }

        if (updateLabels) {
            auto& cache = m_tileManager->getTileCache();
            m_labels->update(*m_view, _dt, m_scene->styles(), tiles, cache);
        }

        bool animated = false;
        for (const auto& style : m_scene->styles()) {
            if (style->isAnimated()) {
                animated = true;
                break;
            }
        }
        if (animated != isContinuousRendering()) {
            setContinuousRendering(animated);
        }
    }
}
Example #4
0
    void update(float _dt) {

        g_time += _dt;

        if (m_view) {

            m_view->update();

            m_tileManager->updateTileSet();

            if(m_view->changedOnLastUpdate() || m_tileManager->hasTileSetChanged() || Label::s_needUpdate) {
                Label::s_needUpdate = false;

                for (const auto& mapIDandTile : m_tileManager->getVisibleTiles()) {
                    const std::shared_ptr<MapTile>& tile = mapIDandTile.second;
                    tile->update(_dt, *m_view);
                }

                // update labels for specific style
                for (const auto& style : m_scene->getStyles()) {
                    for (const auto& mapIDandTile : m_tileManager->getVisibleTiles()) {
                        const std::shared_ptr<MapTile>& tile = mapIDandTile.second;
                        tile->updateLabels(_dt, *style, *m_view);
                    }
                }

                // manage occlusions
                m_labels->updateOcclusions();

                for (const auto& style : m_scene->getStyles()) {
                    for (const auto& mapIDandTile : m_tileManager->getVisibleTiles()) {
                        const std::shared_ptr<MapTile>& tile = mapIDandTile.second;
                        tile->pushLabelTransforms(*style, m_labels);
                    }
                }
            }

            if (Label::s_needUpdate) {
                requestRender();
            }
        }

        if(m_scene) {
            // Update lights and styles
        }
    }
Example #5
0
void display()
{
  glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

  gm->update(counter.fps());
  gm->render();

//  if(keyPressed[KEY_ID_W]==true)      gm->getCam()->moveForward();
//  if(keyPressed[KEY_ID_A]==true)      gm->getCam()->moveLeft();
//  if(keyPressed[KEY_ID_D]==true)      gm->getCam()->moveRight();
//  if(keyPressed[KEY_ID_S]==true)      gm->getCam()->moveBackward();
//  if(keyPressed[KEY_ID_SPACE]==true)  gm->getCam()->moveUp();
//  if(keyPressed[KEY_ID_C]==true)      gm->getCam()->moveDown();



  if(keyPressed[KEY_ID_RIGHT]==true)  gm->getShip()->moveRight();
  if(keyPressed[KEY_ID_LEFT]==true)   gm->getShip()->moveLeft();
  if(keyPressed[KEY_ID_UP]==true)     gm->getShip()->moveUp();
  if(keyPressed[KEY_ID_DOWN]==true)   gm->getShip()->moveDown();
  if((keyPressed[KEY_ID_SPACE]==true) && (gm->getShip()->getLife() > 0))
                      {
                                        gm->addBulletPlayer();
                                        keyPressed[KEY_ID_SPACE] = false;
                                        }
  int scores = gm->getShip()->getScores();
  std::ostringstream convert;
  convert << scores;
  std::string score;
  score = convert.str();
  ad->drawText(score.data(), score.size(),100,680);
  if (gm->getShip()->getLife() == 0){
    std::string gameover;
    std::ostringstream convert2;
    convert2 << gm->getShip()->getScores();
    std::string score2;
    score2 = convert2.str();
    gameover = "Game Over. Your score is: " + convert2.str();
    ad->drawText(gameover.data(), gameover.size(),250,400);
  }
  glutSwapBuffers();
  glutPostRedisplay();
}
Example #6
0
void display()
{
  glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

  float startFps = glutGet(GLUT_ELAPSED_TIME);
  float deltaFps = startFps - oldfps;
  oldfps = startFps;
  gm->update(1/deltaFps*1000);
  gm->render();

  /* check for errors that may occur in OpenGL */
  GLenum err = glGetError();
  if (err != GL_NO_ERROR)
	 std::cout << "OpenGL error: " << gluErrorString(err) << std::endl;
  std::cout.flush();

 


  if(keyPressed[KEY_ID_W]==true)      gm->getCam()->moveForward();
  if(keyPressed[KEY_ID_A]==true)      gm->getCam()->moveLeft();
  if(keyPressed[KEY_ID_D]==true)      gm->getCam()->moveRight();
  if(keyPressed[KEY_ID_S]==true)      gm->getCam()->moveBackward();
  if(keyPressed[KEY_ID_X]==true)      gm->getCam()->moveUp();
  if(keyPressed[KEY_ID_C]==true)      gm->getCam()->moveDown();


  if (keyPressed[KEY_ID_RIGHT] == true)  gm->getShip()->moveRight();
  if (keyPressed[KEY_ID_LEFT] == true)   gm->getShip()->moveLeft();
  if (keyPressed[KEY_ID_UP] == true)     gm->getShip()->moveUp();
  if (keyPressed[KEY_ID_DOWN] == true)   gm->getShip()->moveDown();
  if ((keyPressed[KEY_ID_SPACE] == true)&& (gm->getShip()->getLife() > 0))
  {
	  gm->addBulletPlayer();
	  keyPressed[KEY_ID_SPACE] = false;
  }  

  glutSwapBuffers();
  glutPostRedisplay();

}
Example #7
0
void Automata::computeSituationState()
{
    Logger::getStaticLogger()<<"State : computing situation"<<std::endl;
    mutex.lock();
    situation->update();
    bool wait = false;
    if(detectRobot)
    {
        Logger::getStaticLogger()<<"Robot is blocked by another robot"<<std::endl;
        wait = true;
        currentState = BlockedByRobot;
        if(beginBlocked<0)
            beginBlocked = //curTime
        if(timeSinceBlocked>thresholdTimeBlockedByRobot)
        {
            Logger::getStaticLogger()<<"Too long time since robot is blocked : obstacle is added, plan is recomputed"<<std::endl;
            wait = false;
            timeSincePreviousBlocking = //curTime
            situation->addFrontObstacleForCurrentRobot();
            actions->computeBestGoal(situation);
        }
    }
Example #8
0
void Lab::onUpdate(float dt, const InputState& currentInput, const InputState& previousInput) {
    if (currentInput.m_keyboard.m_keys[GLFW_KEY_RIGHT] || currentInput.m_keyboard.m_keys['D'])
        m_cameraOrientation += M_PI * dt;
    if (currentInput.m_keyboard.m_keys[GLFW_KEY_LEFT] || currentInput.m_keyboard.m_keys['A'])
        m_cameraOrientation -= M_PI * dt;

    glm::vec3 cameraOrientation = getCameraOrientation(m_cameraOrientation);

    if (currentInput.m_keyboard.m_keys[GLFW_KEY_UP] || currentInput.m_keyboard.m_keys['W'])
        m_cameraPosition += cameraOrientation * 10.0f * dt;
    if (currentInput.m_keyboard.m_keys[GLFW_KEY_DOWN] || currentInput.m_keyboard.m_keys['S'])
        m_cameraPosition -= cameraOrientation * 10.0f * dt;


    glm::vec3 rightOrientation = glm::cross(cameraOrientation, glm::vec3(0.0f, 1.0f, 0.0f));
    if (currentInput.m_keyboard.m_keys['E'])
        m_cameraPosition += rightOrientation * 10.0f * dt;
    if (currentInput.m_keyboard.m_keys['Q'])
        m_cameraPosition -= rightOrientation * 10.0f * dt;

    m_camera.setPosition(m_cameraPosition);
    m_camera.setFacing(cameraOrientation);
    m_camera.commit();

    // set the listener by the camera
    m_listener.m_position = m_cameraPosition;
    m_listener.m_facing = cameraOrientation;

    // rotate the box at a constant speed
    m_boxModelOrientation += M_PI * 0.1f * dt;
    m_boxModelMatrix = glm::mat4(cos(m_boxModelOrientation),  0, sin(m_boxModelOrientation), 0,
                                 0,						   1, 0,						     0,
                                 -sin(m_boxModelOrientation), 0, cos(m_boxModelOrientation), 0,
                                 0,						   0, 0,						     1);
    m_boxEntity->setModelMatrix(m_boxModelMatrix);

    // update sound source
    m_source->update();
}
Example #9
0
void update(float _dt) {

    g_time += _dt;

    m_inputHandler->update(_dt);

    m_view->update();

    {
        std::lock_guard<std::mutex> lock(m_tilesMutex);

        m_tileManager->updateTileSets();

        if (m_view->changedOnLastUpdate() || m_tileManager->hasTileSetChanged() || m_labels->needUpdate()) {

            auto& tiles = m_tileManager->getVisibleTiles();

            for (const auto& tile : tiles) {
                tile->update(_dt, *m_view);
            }

            m_labels->update(*m_view, _dt, m_scene->styles(), tiles);
        }

        bool animated = false;
        for (const auto& style : m_scene->styles()) {
            if (style->isAnimated()) {
                animated = true;
                break;
            }
        }
        if (animated != isContinuousRendering()) {
            setContinuousRendering(animated);
        }
    }
}
void HouseOfYesApp::update()
{
	mWorld.dt = getElapsedSeconds() - mWorld.time;
	mWorld.time = getElapsedSeconds();
	mCurrentCue->update(mWorld);
}
Example #11
0
void gameLoop(std::shared_ptr<World> world, std::shared_ptr<Display> display) {
  int d_x = 0;
  int d_y = 0;

  TCODConsole::setKeyboardRepeat(200, 200);
  TCODSystem::setFps(30);

  bool quit = false;

  while (!TCODConsole::isWindowClosed() && !quit) {
    TCOD_key_t key = TCODConsole::checkForKeypress();
    switch (key.c) {
      case 'k':
        d_y = -1;
        break;
      case 'j':
        d_y = 1;
        break;
      case 'h':
        d_x = -1;
        break;
      case 'l':
        d_x = 1;
        break;
      case 'y':
        d_y = -1;
        d_x = -1;
        break;
      case 'u':
        d_y = -1;
        d_x = 1;
        break;
      case 'n':
        d_y = 1;
        d_x = -1;
        break;
      case 'm':
        d_y = 1;
        d_x = 1;
        break;
      case 'g':
        world->generateMap();
        world->updateDisplayOnly();
        break;
      case 'W':
        world->WIZARD = !world->WIZARD;
        world->updateDisplayOnly();
        break;
      case 'q':
        quit=true;
        break;
      default:
        world->updateDisplayOnly();
        continue;
    }

    if ((d_x != 0) or (d_y != 0)) {
      world->events.emit<Movement>(world->player, d_x, d_y);
      d_x = 0;
      d_y = 0;
    }
    world->update();
  }
}
    void on_draw() override
    {
		glfwMakeContextCurrent(window);
        
		if (igm) igm->begin_frame();

		glEnable(GL_CULL_FACE);
		glEnable(GL_DEPTH_TEST);

		glEnable(GL_BLEND);
		glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

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

		glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
		glClearColor(1.0f, 0.1f, 0.0f, 1.0f);

		const auto proj = camera.get_projection_matrix((float) width / (float) height);
		const float4x4 view = camera.get_view_matrix();
		const float4x4 viewProj = mul(proj, view);
        
		if (ImGui::SliderInt("Sun Theta", &sunPos.x, 0, 90)) skydome.set_sun_position(sunPos.x, sunPos.y);
		if (ImGui::SliderInt("Sun Phi", &sunPos.y, 0, 360)) skydome.set_sun_position(sunPos.x, sunPos.y);

        auto draw_cubes = [&](float3 eye, float4x4 vp)
        {
            simpleShader->bind();
            
            simpleShader->uniform("u_eye", eye); 
            simpleShader->uniform("u_viewProj", vp);
            
            simpleShader->uniform("u_emissive", float3(0, 0, 0));
            simpleShader->uniform("u_diffuse", float3(0.33f, 0.33f, 0.33f));
            
            for (int i = 0; i < 2; i++)
            {
                simpleShader->uniform("u_lights[" + std::to_string(i) + "].position", lights[i].position);
                simpleShader->uniform("u_lights[" + std::to_string(i) + "].color", lights[i].color);
            }
            
            for (const auto & model : regularModels)
            {
                simpleShader->uniform("u_modelMatrix", model.get_model());
                simpleShader->uniform("u_modelMatrixIT", inv(transpose(model.get_model())));
                model.draw();
            }
            
            simpleShader->unbind();
        };

        // Render/Update cube camera
        cubeCamera->render = [&](float3 eyePosition, float4x4 viewMatrix, float4x4 projMatrix)
        {
            skydome.render(mul(projMatrix, viewMatrix), eyePosition, camera.farClip);
			draw_cubes(eyePosition, mul(projMatrix, viewMatrix));
        };

        cubeCamera->update(camera.get_eye_point()); // render from a camera positioned @ {0, 0, 0}

        glViewport(0, 0, width, height);
        skydome.render(viewProj, camera.get_eye_point(), camera.farClip);
        grid.render(proj, view);

        draw_cubes(camera.get_eye_point(), viewProj);
        
		// Glass material
        {
            glassMaterialShader->bind();
            
            glassMaterialShader->uniform("u_eye", camera.get_eye_point());
            glassMaterialShader->uniform("u_viewProj", viewProj);

			// Can set from either a pre-loaded cubemap, or one capured from the cubeCamera
            glassMaterialShader->texture("u_cubemapTex", 0, cubeCamera->get_cubemap_handle(), GL_TEXTURE_CUBE_MAP); // cubeTex.get_gl_handle()

            for (const auto & model : glassModels)
            {
                glassMaterialShader->uniform("u_modelMatrix", model.get_model());
                glassMaterialShader->uniform("u_modelMatrixIT", inv(transpose(model.get_model())));
                model.draw();
            }

            glassMaterialShader->unbind();
            glDisable(GL_BLEND);
        }

        gl_check_error(__FILE__, __LINE__);
        if (igm) igm->end_frame();
        glfwSwapBuffers(window);
        frameCount++;
    }
Example #13
0
bool update(float _dt) {

    FrameInfo::beginUpdate();

    g_time += _dt;

    bool viewComplete = true;

    for (auto& ease : m_eases) {
        if (!ease.finished()) {
            ease.update(_dt);
            viewComplete = false;
        }
    }

    size_t nTasks = 0;
    {
        std::lock_guard<std::mutex> lock(m_tasksMutex);
        nTasks = m_tasks.size();
    }
    while (nTasks-- > 0) {
        std::function<void()> task;
        {
            std::lock_guard<std::mutex> lock(m_tasksMutex);
            task = m_tasks.front();
            m_tasks.pop();
        }
        task();
    }

    m_inputHandler->update(_dt);
    m_view->update();

    for (const auto& style : m_scene->styles()) {
        style->onBeginUpdate();
    }

    {
        std::lock_guard<std::mutex> lock(m_tilesMutex);
        ViewState viewState {
            m_view->getMapProjection(),
            m_view->changedOnLastUpdate(),
            glm::dvec2{m_view->getPosition().x, -m_view->getPosition().y },
            m_view->getZoom()
        };

        m_tileManager->updateTileSets(viewState, m_view->getVisibleTiles());

        auto& tiles = m_tileManager->getVisibleTiles();

        if (m_view->changedOnLastUpdate() ||
            m_tileManager->hasTileSetChanged()) {

            for (const auto& tile : tiles) {
                tile->update(_dt, *m_view);
            }
            m_labels->updateLabelSet(*m_view, _dt, m_scene->styles(), tiles,
                                     m_tileManager->getTileCache());

        } else {
            m_labels->updateLabels(*m_view, _dt, m_scene->styles(), tiles);
        }
    }

    FrameInfo::endUpdate();

    bool viewChanged = m_view->changedOnLastUpdate();
    bool tilesChanged = m_tileManager->hasTileSetChanged();
    bool tilesLoading = m_tileManager->hasLoadingTiles();
    bool labelsNeedUpdate = m_labels->needUpdate();
    bool resourceLoading = (m_scene->m_resourceLoad > 0);
    bool nextScene = bool(m_nextScene);

    if (viewChanged || tilesChanged || tilesLoading || labelsNeedUpdate || resourceLoading || nextScene) {
        viewComplete = false;
    }

    // Request for render if labels are in fading in/out states
    if (m_labels->needUpdate()) { requestRender(); }

    return viewComplete;
}
Example #14
0
void CCLinkTestApp::update()
{
    _serialLink->update();
}
Example #15
0
	/**
	 * Update both the server and the client.
	 *
	 * @see Server::update
	 * @see Client::update
	 */
	void update() {
		server->update();
		Client::update();
	}
Example #16
0
int main(int argc, char **argv) {
    ros::init(argc, argv, "imu_3dm_gx4");
    ros::NodeHandle nh("~");

    std::string device;
    int baudrate;
    int imu_decimation, filter_decimation;
    bool enable_filter;
    bool enable_mag_update, enable_accel_update;

    //  load parameters from launch file
    nh.param<std::string>("device", device, "/dev/ttyACM0");
    nh.param<int>("baudrate", baudrate, 115200);
    nh.param<std::string>("frameId", frameId, std::string("imu"));
    nh.param<int>("imu_decimation", imu_decimation, 10);
    nh.param<int>("filter_decimation", filter_decimation, 5);
    nh.param<bool>("enable_filter", enable_filter, false);
    nh.param<bool>("enable_mag_update", enable_mag_update, false);
    nh.param<bool>("enable_accel_update", enable_accel_update, true);

    pubIMU = nh.advertise<sensor_msgs::Imu>("imu", 1);
    pubMag = nh.advertise<sensor_msgs::MagneticField>("magnetic_field", 1);
    pubPressure = nh.advertise<sensor_msgs::FluidPressure>("pressure", 1);

    if (enable_filter) {
        pubFilter = nh.advertise<imu_3dm_gx4::FilterOutput>("filter", 1);
    }

    //  new instance of the IMU
    Imu imu(device);
    try {
        imu.connect();

        ROS_INFO("Selecting baud rate %u", baudrate);
        imu.selectBaudRate(baudrate);

        ROS_INFO("Fetching device info.");
        imu.getDeviceInfo(info);
        std::map<std::string,std::string> map = info.toMap();
        for (const std::pair<std::string,std::string>& p : map) {
            ROS_INFO("%s: %s", p.first.c_str(), p.second.c_str());
        }

        ROS_INFO("Idling the device");
        imu.idle();

        //  read back data rates
        uint16_t imuBaseRate, filterBaseRate;
        imu.getIMUDataBaseRate(imuBaseRate);
        ROS_INFO("IMU data base rate: %u Hz", imuBaseRate);
        imu.getFilterDataBaseRate(filterBaseRate);
        ROS_INFO("Filter data base rate: %u Hz", filterBaseRate);

        ROS_INFO("Selecting IMU decimation rate: %u", imu_decimation);
        imu.setIMUDataRate(
            imu_decimation, Imu::IMUData::Accelerometer |
            Imu::IMUData::Gyroscope |
            Imu::IMUData::Magnetometer |
            Imu::IMUData::Barometer);

        ROS_INFO("Selecting filter decimation rate: %u", filter_decimation);
        imu.setFilterDataRate(filter_decimation, Imu::FilterData::Quaternion |
                              Imu::FilterData::Bias |
                              Imu::FilterData::AngleUnertainty |
                              Imu::FilterData::BiasUncertainty);

        ROS_INFO("Enabling IMU data stream");
        imu.enableIMUStream(true);

        if (enable_filter) {
            ROS_INFO("Enabling filter data stream");
            imu.enableFilterStream(true);

            ROS_INFO("Enabling filter measurements");
            imu.enableMeasurements(enable_accel_update, enable_mag_update);

            ROS_INFO("Enabling gyro bias estimation");
            imu.enableBiasEstimation(true);
        } else {
            ROS_INFO("Disabling filter data stream");
            imu.enableFilterStream(false);
        }
        imu.setIMUDataCallback(publish_data);
        imu.setFilterDataCallback(publish_filter);

        //  configure diagnostic updater
        if (!nh.hasParam("diagnostic_period")) {
            nh.setParam("diagnostic_period", 0.2);  //  5hz period
        }

        updater.reset(new diagnostic_updater::Updater());
        const std::string hwId = info.modelName + "-" + info.modelNumber;
        updater->setHardwareID(hwId);

        double imuRate = imuBaseRate / (1.0 * imu_decimation);
        double filterRate = filterBaseRate / (1.0 * filter_decimation);
        imuDiag = configTopicDiagnostic("imu",&imuRate);
        if (enable_filter) {
            filterDiag = configTopicDiagnostic("filter",&filterRate);
        }

        updater->add("diagnostic_info",
                     boost::bind(&updateDiagnosticInfo, _1, &imu));

        ROS_INFO("Resuming the device");
        imu.resume();

        while (ros::ok()) {
            imu.runOnce();
            updater->update();
        }
        imu.disconnect();
    }
    catch (Imu::io_error &e) {
        ROS_ERROR("IO error: %s\n", e.what());
    }
    catch (Imu::timeout_error &e) {
        ROS_ERROR("Timeout: %s\n", e.what());
    }
    catch (std::exception &e) {
        ROS_ERROR("Exception: %s\n", e.what());
    }

    return 0;
}
Example #17
0
File: main.cpp Project: mcleary/pbr
int main()
{
    GLFWwindow* window = nullptr;
    
    if(!glfwInit())
    {
        std::cerr << "Failed to initialize GLFW" << std::endl;
		return EXIT_FAILURE;
    }
    
	glfwWindowHint(GLFW_DEPTH_BITS, 32);
    glfwWindowHint(GLFW_SAMPLES, 16);

#ifdef __APPLE__    
    glfwWindowHint (GLFW_CONTEXT_VERSION_MAJOR, 3);
    glfwWindowHint (GLFW_CONTEXT_VERSION_MINOR, 3);
    glfwWindowHint (GLFW_OPENGL_FORWARD_COMPAT, 1);
    glfwWindowHint (GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
#endif
    
    std::string windowTitleBase = "Physically Based Rendering with OpenGL ";	
    
	if (s_bFullScreen)
	{
		int monitorsCount;
		GLFWmonitor** monitors = glfwGetMonitors(&monitorsCount);
		const int activeMonitorIdx = 1;

		const GLFWvidmode* mode = glfwGetVideoMode(monitors[activeMonitorIdx]);
		glfwWindowHint(GLFW_RED_BITS, mode->redBits);
		glfwWindowHint(GLFW_GREEN_BITS, mode->greenBits);
		glfwWindowHint(GLFW_BLUE_BITS, mode->blueBits);
		glfwWindowHint(GLFW_REFRESH_RATE, mode->refreshRate);

		window = glfwCreateWindow(mode->width, mode->height, windowTitleBase.data(), monitors[activeMonitorIdx], nullptr);
	}
	else
	{
		window = glfwCreateWindow(s_WindowWidth, s_WindowHeight, windowTitleBase.data(), nullptr, nullptr);
	}
    
    if (!window)
    {
        std::cerr << "Failed to open GLFW window" << std::endl;
        glfwTerminate();
        return EXIT_FAILURE;
    }
    
    // Set callback functions
    glfwSetFramebufferSizeCallback(window, reshape);
    glfwSetKeyCallback(window, key);
	glfwSetMouseButtonCallback(window, mouseButtonCallback);
	glfwSetCursorPosCallback(window, mouseMotionCallback);
	glfwSetScrollCallback(window, mouseScrollCallback);
    
    glfwMakeContextCurrent(window);
    glfwSwapInterval(s_bEnableVSync);

	glbinding::Binding::initialize(false);
    
    glfwGetFramebufferSize(window, &s_WindowWidth, &s_WindowHeight);
    reshape(window, s_WindowWidth, s_WindowHeight);

    init();
    
    auto openglVersion = glbinding::ContextInfo::version();
    windowTitleBase += std::to_string(openglVersion.majorVersion()) + "." + std::to_string(openglVersion.minorVersion());
    
    FPSTimer fpsTimer;
    Timer frameTimer;
    
    // Main loop
    while( !glfwWindowShouldClose(window) )
    {        
        draw();
        
        // Update animation
        scene->update(frameTimer.elapsedSeconds());
        
        frameTimer.start();
        
        // Swap buffers
        glfwSwapBuffers(window);
        glfwPollEvents();
        
        if(fpsTimer.update())
        {
            auto windowTitle = windowTitleBase + " - FPS: " + std::to_string(fpsTimer.getFPS());
            glfwSetWindowTitle(window, windowTitle.data());
        }
    }
    
    // Terminate GLFW
    glfwTerminate();
    
    // Exit program
    return EXIT_SUCCESS;
}
Example #18
0
setter_type property_setter(std::shared_ptr<DiscreteProperty> const &p)
{
    return [p](std::string const &v) mutable {
        return p->update(v);
    };
}