<commit_before>/* redis_async_test.cc
   Wolfgang Sourdeau, 11 December 2012
   Copyright (c) 2012 Datacratic.  All rights reserved.

   Test commands supported by our Redis class
*/

#define BOOST_TEST_MAIN
#define BOOST_TEST_DYN_LINK

#include <unordered_map>

#include <boost/test/unit_test.hpp>

#include "soa/service/redis.h"
#include "soa/service/testing/redis_temporary_server.h"

using namespace std;
using namespace Redis;

BOOST_AUTO_TEST_CASE( test_redis_commands )
{
    RedisTemporaryServer redis;
    AsyncConnection connection(redis);

    /* MSET is supported */
    Command mset(MSET);
    mset.addArg("testkey1"); mset.addArg(1234);
    mset.addArg("testkey2"); mset.addArg(9876);
    mset.addArg("testkey3"); mset.addArg("textvalue");

    Result result = connection.exec(mset);
    BOOST_CHECK_EQUAL(result.ok(), true);

    /* MGET is supported and that all slots requested must be returned in the
       form of an array, including empty ones, without errors */
    Command mget(MGET);
    mget.addArg("testkey1");
    mget.addArg("testkey3");
    mget.addArg("poil");

    result = connection.exec(mget);
    BOOST_CHECK_EQUAL(result.ok(), true);
    Reply reply = result.reply();
    BOOST_CHECK_EQUAL(reply.type(), ARRAY);

    Reply subreply = reply[0]; /* testkey1 */
    BOOST_CHECK_EQUAL(subreply.type(), STRING);
    BOOST_CHECK_EQUAL(subreply.asString(), "1234");
    /* FIXME: expected behaviour:
    BOOST_CHECK_EQUAL(subreply.type(), INTEGER);
    BOOST_CHECK_EQUAL(subreply.asInt(), 1234);
    */

    subreply = reply[1]; /* testkey3 */
    BOOST_CHECK_EQUAL(subreply.type(), STRING);
    BOOST_CHECK_EQUAL(string(subreply), "textvalue");

    subreply = reply[2]; /* poil */
    BOOST_CHECK_EQUAL(subreply.type(), NIL);

    /* SADD is supported and each slot is used once per key, even when
       specified multiple times */
    Command sadd(SADD);
    sadd.addArg("my-new-set");
    sadd.addArg("testkey1");
    sadd.addArg("testkey2");
    sadd.addArg("testkey2");

    result = connection.exec(sadd);
    BOOST_CHECK_EQUAL(result.ok(), true);

    /* SMEMBERS is supported and does return the values registered above */
    Command smembers(SMEMBERS);
    smembers.addArg("my-new-set");

    result = connection.exec(smembers);
    BOOST_CHECK_EQUAL(result.ok(), true);
    reply = result.reply();
    BOOST_CHECK_EQUAL(reply.type(), ARRAY);
    BOOST_CHECK_EQUAL(reply.length(), 2); /* testkey1, testkey2 */

    /* members are not specifically returned in order */
    unordered_map<string, bool> keyMap;
    subreply = reply[0];
    BOOST_CHECK_EQUAL(subreply.type(), STRING);
    keyMap[subreply.asString()] = true;
    subreply = reply[1];
    BOOST_CHECK_EQUAL(subreply.type(), STRING);
    keyMap[subreply.asString()] = true;

    BOOST_CHECK_EQUAL(keyMap["testkey1"], true);
    BOOST_CHECK_EQUAL(keyMap["testkey2"], true);
}
<commit_msg>added unit testing for SMOVE, EXISTS and SISMEMBER commands<commit_after>/* redis_async_test.cc
   Wolfgang Sourdeau, 11 December 2012
   Copyright (c) 2012 Datacratic.  All rights reserved.

   Test commands supported by our Redis class
*/

#define BOOST_TEST_MAIN
#define BOOST_TEST_DYN_LINK

#include <unordered_map>

#include <boost/test/unit_test.hpp>

#include "soa/service/redis.h"
#include "soa/service/testing/redis_temporary_server.h"

using namespace std;
using namespace Redis;

BOOST_AUTO_TEST_CASE( test_redis_commands )
{
    RedisTemporaryServer redis;
    AsyncConnection connection(redis);

    /* MSET is supported */
    Command mset(MSET);
    mset.addArg("testkey1"); mset.addArg(1234);
    mset.addArg("testkey2"); mset.addArg(9876);
    mset.addArg("testkey3"); mset.addArg("textvalue");

    Result result = connection.exec(mset);
    BOOST_CHECK_EQUAL(result.ok(), true);

    /* MGET is supported and that all slots requested must be returned in the
       form of an array, including empty ones, without errors */
    Command mget(MGET);
    mget.addArg("testkey1");
    mget.addArg("testkey3");
    mget.addArg("poil");

    result = connection.exec(mget);
    BOOST_CHECK_EQUAL(result.ok(), true);
    Reply reply = result.reply();
    BOOST_CHECK_EQUAL(reply.type(), ARRAY);

    Reply subreply = reply[0]; /* testkey1 */
    BOOST_CHECK_EQUAL(subreply.type(), STRING);
    BOOST_CHECK_EQUAL(subreply.asString(), "1234");
    /* FIXME: expected behaviour:
    BOOST_CHECK_EQUAL(subreply.type(), INTEGER);
    BOOST_CHECK_EQUAL(subreply.asInt(), 1234);
    */

    subreply = reply[1]; /* testkey3 */
    BOOST_CHECK_EQUAL(subreply.type(), STRING);
    BOOST_CHECK_EQUAL(string(subreply), "textvalue");

    subreply = reply[2]; /* poil */
    BOOST_CHECK_EQUAL(subreply.type(), NIL);

    /* SADD is supported and each slot is used once per key, even when
       specified multiple times */
    Command sadd(SADD);
    sadd.addArg("my-new-set");
    sadd.addArg("testkey1");
    sadd.addArg("testkey2");
    sadd.addArg("testkey2");

    result = connection.exec(sadd);
    BOOST_CHECK_EQUAL(result.ok(), true);

    /* SMEMBERS is supported and does return the values registered above */
    Command smembers(SMEMBERS);
    smembers.addArg("my-new-set");

    result = connection.exec(smembers);
    BOOST_CHECK_EQUAL(result.ok(), true);
    reply = result.reply();
    BOOST_CHECK_EQUAL(reply.type(), ARRAY);
    BOOST_CHECK_EQUAL(reply.length(), 2); /* testkey1, testkey2 */

    /* members are not specifically returned in order */
    unordered_map<string, bool> keyMap;
    subreply = reply[0];
    BOOST_CHECK_EQUAL(subreply.type(), STRING);
    keyMap[subreply.asString()] = true;
    subreply = reply[1];
    BOOST_CHECK_EQUAL(subreply.type(), STRING);
    keyMap[subreply.asString()] = true;

    BOOST_CHECK_EQUAL(keyMap["testkey1"], true);
    BOOST_CHECK_EQUAL(keyMap["testkey2"], true);

    /* SMOVE is supported, it moves a key from one set to another*/
    Command smove(SMOVE);
    smove.addArg("my-new-set");
    smove.addArg("my-destination-set");
    smove.addArg("testkey2");

    result = connection.exec(smove);
    BOOST_CHECK_EQUAL(result.ok(), true);

    /* verify that the key was properly moved */
    Command smembersNewSet(SMEMBERS);
    smembersNewSet.addArg("my-new-set");
    Command smembersDestSet(SMEMBERS);
    smembersDestSet.addArg("my-destination-set");

    result = connection.exec(smembersNewSet);
    BOOST_CHECK_EQUAL(result.ok(), true);
    reply = result.reply();
    BOOST_CHECK_EQUAL(reply.type(), ARRAY);
    BOOST_CHECK_EQUAL(reply.length(), 1);
    BOOST_CHECK_EQUAL(reply[0].type(), STRING);
    BOOST_CHECK_EQUAL(reply[0].asString(), "testkey1");

    result = connection.exec(smembersDestSet);
    BOOST_CHECK_EQUAL(result.ok(), true);
    reply = result.reply();
    BOOST_CHECK_EQUAL(reply.type(), ARRAY);
    BOOST_CHECK_EQUAL(reply.length(), 1);
    BOOST_CHECK_EQUAL(reply[0].type(), STRING);
    BOOST_CHECK_EQUAL(reply[0].asString(), "testkey2");

    /* check a SMOVE failure */
    result = connection.exec(smove);
    BOOST_CHECK_EQUAL(result.ok(), true);
    BOOST_CHECK_EQUAL(result.reply().type(), INTEGER);
    BOOST_CHECK_EQUAL(result.reply().asInt(), 0);

    /* SISMEMBER is supported, it checks for the membership of a
     * key to a set */
    Command sIsMemberTrue(SISMEMBER);
    sIsMemberTrue.addArg("my-new-set");
    sIsMemberTrue.addArg("testkey1");

    result = connection.exec(sIsMemberTrue);
    BOOST_CHECK_EQUAL(result.ok(), true);
    BOOST_CHECK_EQUAL(result.reply().type(), INTEGER);
    BOOST_CHECK_EQUAL(result.reply().asInt(), 1);

    Command sIsMemberFalse(SISMEMBER);
    sIsMemberFalse.addArg("my-new-set");
    sIsMemberFalse.addArg("testkey2");

    result = connection.exec(sIsMemberFalse);
    BOOST_CHECK_EQUAL(result.ok(), true);
    BOOST_CHECK_EQUAL(result.reply().type(), INTEGER);
    BOOST_CHECK_EQUAL(result.reply().asInt(), 0);

    /* EXISTS is supported it checks for the existance of a key */
    Command existsTrue(EXISTS);
    existsTrue.addArg("testkey2");

    result = connection.exec(existsTrue);
    BOOST_CHECK_EQUAL(result.ok(), true);
    BOOST_CHECK_EQUAL(result.reply().type(), INTEGER);
    BOOST_CHECK_EQUAL(result.reply().asInt(), 1);

    Command existsFalse(EXISTS);
    existsFalse.addArg("testkey4");

    result = connection.exec(existsFalse);
    BOOST_CHECK_EQUAL(result.ok(), true);
    BOOST_CHECK_EQUAL(result.reply().type(), INTEGER);
    BOOST_CHECK_EQUAL(result.reply().asInt(), 0);
}
<|endoftext|>


<commit_before>#include <GuiBase/Viewer/TrackballCameraManipulator.hpp>

#include <Core/Math/Math.hpp>
#include <Core/Utils/Log.hpp>
#include <Engine/Renderer/Camera/Camera.hpp>
#include <Engine/Renderer/Light/Light.hpp>
#include <GuiBase/Utils/Keyboard.hpp>

#include <GuiBase/Utils/KeyMappingManager.hpp>

#include <QApplication>
#include <QMessageBox>
#include <algorithm>
#include <iostream>

namespace Ra {
namespace Gui {
using Core::Math::Pi;

#define KMA_VALUE( XX ) \
    Gui::KeyMappingManager::KeyMappingAction Gui::TrackballCameraManipulator::XX;
KeyMappingCamera;
#undef KMA_VALUE

void Gui::TrackballCameraManipulator::configureKeyMapping_impl() {

    m_keyMappingContext = Gui::KeyMappingManager::getInstance()->getContext( "CameraContext" );
    if ( m_keyMappingContext.isInvalid() )
    {
        LOG( Ra::Core::Utils::logINFO )
            << "CameraContext not defined (maybe the configuration file do not contains it)";
        LOG( Ra::Core::Utils::logERROR ) << "CameraContext all keymapping invalide !";
        return;
    }

#define KMA_VALUE( XX ) \
    XX = Gui::KeyMappingManager::getInstance()->getActionIndex( m_keyMappingContext, #XX );
    KeyMappingCamera
#undef KMA_VALUE
}

Gui::TrackballCameraManipulator::TrackballCameraManipulator( uint width, uint height ) :
    CameraManipulator( width, height ),
    m_rotateAround( true ),
    m_cameraRotateMode( false ),
    m_cameraPanMode( false ),
    m_cameraZoomMode( false ) {
    resetCamera();
}

Gui::TrackballCameraManipulator::TrackballCameraManipulator( const CameraManipulator& other ) :
    CameraManipulator( other ),
    m_rotateAround( true ),
    m_cameraRotateMode( false ),
    m_cameraPanMode( false ),
    m_cameraZoomMode( false ) {
    m_distFromCenter = ( m_target - m_camera->getPosition() ).norm();
    updatePhiTheta();
}

Gui::TrackballCameraManipulator::~TrackballCameraManipulator() = default;

void Gui::TrackballCameraManipulator::resetCamera() {
    m_camera->setFrame( Core::Transform::Identity() );
    m_camera->setPosition( Core::Vector3( 0_ra, 0_ra, 2_ra ) );
    m_target = Core::Vector3::Zero();
    m_camera->setDirection( Core::Vector3( 0_ra, 0_ra, -1_ra ) );
    m_distFromCenter = 2.0_ra;
    updatePhiTheta();

    if ( m_light != nullptr )
    {
        m_light->setPosition( m_camera->getPosition() );
        m_light->setDirection( m_camera->getDirection() );
    }

    emit cameraChanged( m_camera->getPosition(), m_target );
}

void Gui::TrackballCameraManipulator::setTrackballRadius( Scalar rad ) {
    m_distFromCenter = rad;
    m_target         = m_camera->getPosition() + m_distFromCenter * m_camera->getDirection();
    updatePhiTheta();
}

Scalar Gui::TrackballCameraManipulator::getTrackballRadius() const {
    return m_distFromCenter;
}

void Gui::TrackballCameraManipulator::setTrackballCenter( const Core::Vector3& c ) {
    m_target         = c;
    m_distFromCenter = ( c - m_camera->getPosition() ).norm();
    updatePhiTheta();
}

const Core::Vector3& Gui::TrackballCameraManipulator::getTrackballCenter() const {
    return m_target;
}

bool Gui::TrackballCameraManipulator::handleMousePressEvent( QMouseEvent* event,
                                                             const Qt::MouseButtons& buttons,
                                                             const Qt::KeyboardModifiers& modifiers,
                                                             int key ) {
    bool handled = false;
    m_lastMouseX = event->pos().x();
    m_lastMouseY = event->pos().y();

    auto action = KeyMappingManager::getInstance()->getAction(
        m_keyMappingContext, buttons, modifiers, key, false );

    if ( action == TRACKBALLCAMERA_ROTATE )
    {
        m_cameraRotateMode = true;
        handled            = true;
    }
    if ( action == TRACKBALLCAMERA_PAN )
    {
        m_cameraPanMode = true;
        handled         = true;
    }
    if ( action == TRACKBALLCAMERA_ZOOM )
    {
        m_cameraZoomMode = true;
        handled          = true;
    }

    return handled;
}

bool Gui::TrackballCameraManipulator::handleMouseMoveEvent( QMouseEvent* event,
                                                            const Qt::MouseButtons& buttons,
                                                            const Qt::KeyboardModifiers& modifiers,
                                                            int /*key*/ ) {

    // auto action = KeyMappingManager::getInstance()->getAction( context, buttons, modifiers, key
    // );

    Scalar dx = ( event->pos().x() - m_lastMouseX ) / m_camera->getWidth();
    Scalar dy = ( event->pos().y() - m_lastMouseY ) / m_camera->getHeight();

    if ( event->modifiers().testFlag( Qt::AltModifier ) ) { m_quickCameraModifier = 10.0_ra; }
    else
    { m_quickCameraModifier = 2.0_ra; }

    if ( m_cameraRotateMode ) { handleCameraRotate( dx, dy ); }

    if ( m_cameraPanMode ) { handleCameraPan( dx, dy ); }

    if ( m_cameraZoomMode ) { handleCameraZoom( dx, dy ); }

    m_lastMouseX = event->pos().x();
    m_lastMouseY = event->pos().y();

    if ( m_light != nullptr )
    {
        m_light->setPosition( m_camera->getPosition() );
        m_light->setDirection( m_camera->getDirection() );
    }

    emit cameraChanged( m_camera->getPosition(), m_target );

    return m_cameraRotateMode || m_cameraPanMode || m_cameraZoomMode;
}

bool Gui::TrackballCameraManipulator::handleMouseReleaseEvent( QMouseEvent* /*event*/ ) {
    m_cameraRotateMode    = false;
    m_cameraPanMode       = false;
    m_cameraZoomMode      = false;
    m_quickCameraModifier = 1.0_ra;

    return true;
}

bool Gui::TrackballCameraManipulator::handleWheelEvent( QWheelEvent* event ) {

    handleCameraZoom( ( event->angleDelta().y() * 0.01_ra + event->angleDelta().x() * 0.01_ra ) *
                      m_wheelSpeedModifier );

    if ( m_light != nullptr )
    {
        m_light->setPosition( m_camera->getPosition() );
        m_light->setDirection( m_camera->getDirection() );
    }

    emit cameraPositionChanged( m_camera->getPosition() );

    return true;
}

void Gui::TrackballCameraManipulator::toggleRotateAround() {
    m_rotateAround = !m_rotateAround;
}

bool Gui::TrackballCameraManipulator::handleKeyPressEvent(
    QKeyEvent* /*event*/,
    const KeyMappingManager::KeyMappingAction& action ) {

    if ( action == TRACKBALLCAMERA_ROTATE_AROUND )
    {
        m_rotateAround = !m_rotateAround;
        return true;
    }

    return false;
}

bool Gui::TrackballCameraManipulator::handleKeyReleaseEvent( QKeyEvent* /*e*/ ) {
    return false;
}

void Gui::TrackballCameraManipulator::setCamera( Engine::Camera* camera ) {
    if ( !camera ) return;
    camera->resize( m_camera->getWidth(), m_camera->getHeight() );
    m_camera         = camera;
    m_target         = m_camera->getPosition() + 2 * m_camera->getDirection().normalized();
    m_distFromCenter = 2.0_ra;
    updatePhiTheta();
    m_camera->show( false );

    if ( m_light != nullptr )
    {
        m_light->setPosition( m_camera->getPosition() );
        m_light->setDirection( m_camera->getDirection() );
    }
}

void Gui::TrackballCameraManipulator::setCameraPosition( const Core::Vector3& position ) {
    if ( position == m_target )
    {
        QMessageBox::warning( nullptr, "Error", "Position cannot be set to target point" );
        return;
    }
    m_camera->setPosition( position );
    /*
    m_camera->setDirection( (m_target - position).normalized() );
    m_distFromCenter = (m_target - position).norm();
    updatePhiTheta();
    */
    m_target = position + m_distFromCenter * m_camera->getDirection().normalized();

    if ( m_light != nullptr )
    {
        m_light->setPosition( m_camera->getPosition() );
        m_light->setDirection( m_camera->getDirection() );
    }

    emit cameraPositionChanged( m_camera->getPosition() );
}

void Gui::TrackballCameraManipulator::setCameraTarget( const Core::Vector3& target ) {
    if ( m_camera->getPosition() == m_target )
    {
        QMessageBox::warning( nullptr, "Error", "Target cannot be set to current camera position" );
        return;
    }

    m_target = target;
    m_camera->setDirection( ( target - m_camera->getPosition() ).normalized() );
    m_distFromCenter = ( target - m_camera->getPosition() ).norm();
    updatePhiTheta();

    if ( m_light != nullptr ) { m_light->setDirection( m_camera->getDirection() ); }

    emit cameraTargetChanged( m_target );
}

void Gui::TrackballCameraManipulator::fitScene( const Core::Aabb& aabb ) {
    resetCamera();

    Scalar f = m_camera->getFOV();
    Scalar a = m_camera->getAspect();

    const Scalar r = ( aabb.max() - aabb.min() ).norm() / 2_ra;
    const Scalar x = r / std::sin( f / 2_ra );
    const Scalar y = r / std::sin( f * a / 2_ra );
    Scalar d       = std::max( std::max( x, y ), 0.001_ra );

    m_camera->setPosition(
        Core::Vector3( aabb.center().x(), aabb.center().y(), aabb.center().z() + d ) );
    m_camera->setDirection( Core::Vector3( 0_ra, 0_ra, -1_ra ) );
    m_target         = aabb.center();
    m_distFromCenter = d;

    updatePhiTheta();

    Scalar zfar = std::max( d + ( aabb.max().z() - aabb.min().z() ) * 2_ra, m_camera->getZFar() );
    m_camera->setZFar( zfar );

    if ( m_light != nullptr )
    {
        m_light->setPosition( m_camera->getPosition() );
        m_light->setDirection( m_camera->getDirection() );
    }

    emit cameraChanged( m_camera->getPosition(), m_target );
}

void Gui::TrackballCameraManipulator::handleCameraRotate( Scalar dx, Scalar dy ) {
    Scalar dphi = dx * m_cameraSensitivity * m_quickCameraModifier;
    Scalar y    = -dy * m_cameraSensitivity * m_quickCameraModifier;

    Scalar phi   = std::fmod( m_phi + dphi, 2_ra * Pi );          // Keep phi between 0 and 2pi
    Scalar theta = std::fmod( m_theta + y + Pi, 2_ra * Pi ) - Pi; // Keep theta between -pi and pi

    Scalar dtheta = theta - m_theta;

    Core::Vector3 P =
        m_target + m_distFromCenter * Core::Vector3( -std::cos( phi ) * std::sin( theta ),
                                                     std::cos( theta ),
                                                     -std::sin( phi ) * std::sin( theta ) );

    Core::Vector3 t( P - m_camera->getPosition() );

    // Translate the camera given this translation
    Core::Transform T( Core::Transform::Identity() );
    T.translation() = t;

    // Rotate the camera so that it points to the center
    Core::Transform R1( Core::Transform::Identity() );
    Core::Transform R2( Core::Transform::Identity() );

    Core::Vector3 U = Core::Vector3( 0_ra, 1_ra, 0_ra );
    Core::Vector3 R = -m_camera->getRightVector().normalized();

    R1 = Core::AngleAxis( -dphi, U );
    R2 = Core::AngleAxis( -dtheta, R );

    m_camera->applyTransform( T * R1 * R2 );
    m_phi   = phi;
    m_theta = theta;
}

void Gui::TrackballCameraManipulator::handleCameraPan( Scalar dx, Scalar dy ) {
    Scalar x = dx * m_cameraSensitivity * m_quickCameraModifier * m_distFromCenter * 0.1_ra;
    Scalar y = dy * m_cameraSensitivity * m_quickCameraModifier * m_distFromCenter * 0.1_ra;
    // Move camera and trackball center, keep the distance to the center
    Core::Vector3 R = -m_camera->getRightVector();
    Core::Vector3 U = m_camera->getUpVector();

    Core::Transform T( Core::Transform::Identity() );
    Core::Vector3 t = x * R + y * U;
    T.translate( t );

    m_camera->applyTransform( T );
    m_target += t;
}

void Gui::TrackballCameraManipulator::handleCameraZoom( Scalar dx, Scalar dy ) {
    handleCameraZoom( Ra::Core::Math::sign( dx ) * ( std::abs( dx ) + std::abs( dy ) ) );
}

void Gui::TrackballCameraManipulator::handleCameraZoom( Scalar z ) {
    // tested this way of zooming, not convinced it's better
#if 0
    Scalar zoom = m_camera->getZoomFactor() - z * m_cameraSensitivity * m_quickCameraModifier;
    Scalar epsIn = 0.001;
    Scalar epsOut = 3.1;
    m_camera->setZoomFactor( std::clamp( zoom, epsIn, epsOut ) );
#else
    Scalar y    = m_distFromCenter * z * m_cameraSensitivity * m_quickCameraModifier;
    Scalar dist = ( m_target - m_camera->getPosition() ).norm();
    if ( dist < ( m_camera->getZNear() + y ) ) { y = dist - m_camera->getZNear(); }

    Core::Transform T( Core::Transform::Identity() );
    Core::Vector3 t = y * m_camera->getDirection();
    T.translate( t );

    m_camera->applyTransform( T );
    m_distFromCenter = ( m_target - m_camera->getPosition() ).norm();

    emit cameraPositionChanged( m_camera->getPosition() );
#endif
}

void Gui::TrackballCameraManipulator::updatePhiTheta() {
    using Core::Math::areApproxEqual;
    const auto R = m_camera->getDirection().normalized();

    m_theta = std::acos( R.y() );
    m_phi   = ( areApproxEqual( R.z(), 0_ra ) && areApproxEqual( R.x(), 0_ra ) )
                ? 0_ra
                : std::atan2( R.z(), R.x() );
    // Keep phi between 0 and 2pi
    // Keep theta between -pi and pi
    if ( m_phi < 0_ra )
    {
        m_theta = -m_theta + Pi;
        m_phi += 2_ra * Pi;
    }

    CORE_ASSERT( std::isfinite( m_theta ) && std::isfinite( m_phi ), "Error in trackball camera" );
}

bool Gui::TrackballCameraManipulator::checkIntegrity( const std::string& mess ) const {
    Core::Vector3 c = m_camera->getPosition() + m_distFromCenter * m_camera->getDirection();
    Scalar d        = ( m_target - c ).norm();
    if ( d > 0.001_ra )
    {
        LOG( Ra::Core::Utils::logWARNING )
            << "TrackballCameraManipulator Integrity problem : " << mess;
        LOG( Ra::Core::Utils::logWARNING ) << "\t Position " << m_camera->getPosition().transpose();
        LOG( Ra::Core::Utils::logWARNING )
            << "\t Direction " << m_camera->getDirection().transpose();
        LOG( Ra::Core::Utils::logWARNING ) << "\t Target " << m_target.transpose();
        LOG( Ra::Core::Utils::logWARNING ) << "\t Center " << c.transpose();
        LOG( Ra::Core::Utils::logWARNING ) << "\t Distance " << d;
    }
    return d < 0.001_ra;
}

} // namespace Gui
} // namespace Ra
<commit_msg>Fix trackball when setting camera direction along Y axis ;<commit_after>#include <GuiBase/Viewer/TrackballCameraManipulator.hpp>

#include <Core/Math/Math.hpp>
#include <Core/Utils/Log.hpp>
#include <Engine/Renderer/Camera/Camera.hpp>
#include <Engine/Renderer/Light/Light.hpp>
#include <GuiBase/Utils/Keyboard.hpp>

#include <GuiBase/Utils/KeyMappingManager.hpp>

#include <QApplication>
#include <QMessageBox>
#include <algorithm>
#include <iostream>

namespace Ra {
namespace Gui {
using Core::Math::Pi;

#define KMA_VALUE( XX ) \
    Gui::KeyMappingManager::KeyMappingAction Gui::TrackballCameraManipulator::XX;
KeyMappingCamera;
#undef KMA_VALUE

void Gui::TrackballCameraManipulator::configureKeyMapping_impl() {

    m_keyMappingContext = Gui::KeyMappingManager::getInstance()->getContext( "CameraContext" );
    if ( m_keyMappingContext.isInvalid() )
    {
        LOG( Ra::Core::Utils::logINFO )
            << "CameraContext not defined (maybe the configuration file do not contains it)";
        LOG( Ra::Core::Utils::logERROR ) << "CameraContext all keymapping invalide !";
        return;
    }

#define KMA_VALUE( XX ) \
    XX = Gui::KeyMappingManager::getInstance()->getActionIndex( m_keyMappingContext, #XX );
    KeyMappingCamera
#undef KMA_VALUE
}

Gui::TrackballCameraManipulator::TrackballCameraManipulator( uint width, uint height ) :
    CameraManipulator( width, height ),
    m_rotateAround( true ),
    m_cameraRotateMode( false ),
    m_cameraPanMode( false ),
    m_cameraZoomMode( false ) {
    resetCamera();
}

Gui::TrackballCameraManipulator::TrackballCameraManipulator( const CameraManipulator& other ) :
    CameraManipulator( other ),
    m_rotateAround( true ),
    m_cameraRotateMode( false ),
    m_cameraPanMode( false ),
    m_cameraZoomMode( false ) {
    m_distFromCenter = ( m_target - m_camera->getPosition() ).norm();
    updatePhiTheta();
}

Gui::TrackballCameraManipulator::~TrackballCameraManipulator() = default;

void Gui::TrackballCameraManipulator::resetCamera() {
    m_camera->setFrame( Core::Transform::Identity() );
    m_camera->setPosition( Core::Vector3( 0_ra, 0_ra, 2_ra ) );
    m_target = Core::Vector3::Zero();
    m_camera->setDirection( Core::Vector3( 0_ra, 0_ra, -1_ra ) );
    m_distFromCenter = 2.0_ra;
    updatePhiTheta();

    if ( m_light != nullptr )
    {
        m_light->setPosition( m_camera->getPosition() );
        m_light->setDirection( m_camera->getDirection() );
    }

    emit cameraChanged( m_camera->getPosition(), m_target );
}

void Gui::TrackballCameraManipulator::setTrackballRadius( Scalar rad ) {
    m_distFromCenter = rad;
    m_target         = m_camera->getPosition() + m_distFromCenter * m_camera->getDirection();
    updatePhiTheta();
}

Scalar Gui::TrackballCameraManipulator::getTrackballRadius() const {
    return m_distFromCenter;
}

void Gui::TrackballCameraManipulator::setTrackballCenter( const Core::Vector3& c ) {
    m_target         = c;
    m_distFromCenter = ( c - m_camera->getPosition() ).norm();
    updatePhiTheta();
}

const Core::Vector3& Gui::TrackballCameraManipulator::getTrackballCenter() const {
    return m_target;
}

bool Gui::TrackballCameraManipulator::handleMousePressEvent( QMouseEvent* event,
                                                             const Qt::MouseButtons& buttons,
                                                             const Qt::KeyboardModifiers& modifiers,
                                                             int key ) {
    bool handled = false;
    m_lastMouseX = event->pos().x();
    m_lastMouseY = event->pos().y();

    auto action = KeyMappingManager::getInstance()->getAction(
        m_keyMappingContext, buttons, modifiers, key, false );

    if ( action == TRACKBALLCAMERA_ROTATE )
    {
        m_cameraRotateMode = true;
        handled            = true;
    }
    if ( action == TRACKBALLCAMERA_PAN )
    {
        m_cameraPanMode = true;
        handled         = true;
    }
    if ( action == TRACKBALLCAMERA_ZOOM )
    {
        m_cameraZoomMode = true;
        handled          = true;
    }

    return handled;
}

bool Gui::TrackballCameraManipulator::handleMouseMoveEvent( QMouseEvent* event,
                                                            const Qt::MouseButtons& buttons,
                                                            const Qt::KeyboardModifiers& modifiers,
                                                            int /*key*/ ) {

    // auto action = KeyMappingManager::getInstance()->getAction( context, buttons, modifiers, key
    // );

    Scalar dx = ( event->pos().x() - m_lastMouseX ) / m_camera->getWidth();
    Scalar dy = ( event->pos().y() - m_lastMouseY ) / m_camera->getHeight();

    if ( event->modifiers().testFlag( Qt::AltModifier ) ) { m_quickCameraModifier = 10.0_ra; }
    else
    { m_quickCameraModifier = 2.0_ra; }

    if ( m_cameraRotateMode ) { handleCameraRotate( dx, dy ); }

    if ( m_cameraPanMode ) { handleCameraPan( dx, dy ); }

    if ( m_cameraZoomMode ) { handleCameraZoom( dx, dy ); }

    m_lastMouseX = event->pos().x();
    m_lastMouseY = event->pos().y();

    if ( m_light != nullptr )
    {
        m_light->setPosition( m_camera->getPosition() );
        m_light->setDirection( m_camera->getDirection() );
    }

    emit cameraChanged( m_camera->getPosition(), m_target );

    return m_cameraRotateMode || m_cameraPanMode || m_cameraZoomMode;
}

bool Gui::TrackballCameraManipulator::handleMouseReleaseEvent( QMouseEvent* /*event*/ ) {
    m_cameraRotateMode    = false;
    m_cameraPanMode       = false;
    m_cameraZoomMode      = false;
    m_quickCameraModifier = 1.0_ra;

    return true;
}

bool Gui::TrackballCameraManipulator::handleWheelEvent( QWheelEvent* event ) {

    handleCameraZoom( ( event->angleDelta().y() * 0.01_ra + event->angleDelta().x() * 0.01_ra ) *
                      m_wheelSpeedModifier );

    if ( m_light != nullptr )
    {
        m_light->setPosition( m_camera->getPosition() );
        m_light->setDirection( m_camera->getDirection() );
    }

    emit cameraPositionChanged( m_camera->getPosition() );

    return true;
}

void Gui::TrackballCameraManipulator::toggleRotateAround() {
    m_rotateAround = !m_rotateAround;
}

bool Gui::TrackballCameraManipulator::handleKeyPressEvent(
    QKeyEvent* /*event*/,
    const KeyMappingManager::KeyMappingAction& action ) {

    if ( action == TRACKBALLCAMERA_ROTATE_AROUND )
    {
        m_rotateAround = !m_rotateAround;
        return true;
    }

    return false;
}

bool Gui::TrackballCameraManipulator::handleKeyReleaseEvent( QKeyEvent* /*e*/ ) {
    return false;
}

void Gui::TrackballCameraManipulator::setCamera( Engine::Camera* camera ) {
    if ( !camera ) return;
    camera->resize( m_camera->getWidth(), m_camera->getHeight() );
    m_camera         = camera;
    m_target         = m_camera->getPosition() + 2 * m_camera->getDirection().normalized();
    m_distFromCenter = 2.0_ra;
    updatePhiTheta();
    m_camera->show( false );

    if ( m_light != nullptr )
    {
        m_light->setPosition( m_camera->getPosition() );
        m_light->setDirection( m_camera->getDirection() );
    }
}

void Gui::TrackballCameraManipulator::setCameraPosition( const Core::Vector3& position ) {
    if ( position == m_target )
    {
        QMessageBox::warning( nullptr, "Error", "Position cannot be set to target point" );
        return;
    }
    m_camera->setPosition( position );
    /*
    m_camera->setDirection( (m_target - position).normalized() );
    m_distFromCenter = (m_target - position).norm();
    updatePhiTheta();
    */
    m_target = position + m_distFromCenter * m_camera->getDirection().normalized();

    if ( m_light != nullptr )
    {
        m_light->setPosition( m_camera->getPosition() );
        m_light->setDirection( m_camera->getDirection() );
    }

    emit cameraPositionChanged( m_camera->getPosition() );
}

void Gui::TrackballCameraManipulator::setCameraTarget( const Core::Vector3& target ) {
    if ( m_camera->getPosition() == m_target )
    {
        QMessageBox::warning( nullptr, "Error", "Target cannot be set to current camera position" );
        return;
    }

    m_target = target;
    m_camera->setDirection( ( target - m_camera->getPosition() ).normalized() );
    m_distFromCenter = ( target - m_camera->getPosition() ).norm();
    updatePhiTheta();

    if ( m_light != nullptr ) { m_light->setDirection( m_camera->getDirection() ); }

    emit cameraTargetChanged( m_target );
}

void Gui::TrackballCameraManipulator::fitScene( const Core::Aabb& aabb ) {
    resetCamera();

    Scalar f = m_camera->getFOV();
    Scalar a = m_camera->getAspect();

    const Scalar r = ( aabb.max() - aabb.min() ).norm() / 2_ra;
    const Scalar x = r / std::sin( f / 2_ra );
    const Scalar y = r / std::sin( f * a / 2_ra );
    Scalar d       = std::max( std::max( x, y ), 0.001_ra );

    m_camera->setPosition(
        Core::Vector3( aabb.center().x(), aabb.center().y(), aabb.center().z() + d ) );
    m_camera->setDirection( Core::Vector3( 0_ra, 0_ra, -1_ra ) );
    m_target         = aabb.center();
    m_distFromCenter = d;

    updatePhiTheta();

    Scalar zfar = std::max( d + ( aabb.max().z() - aabb.min().z() ) * 2_ra, m_camera->getZFar() );
    m_camera->setZFar( zfar );

    if ( m_light != nullptr )
    {
        m_light->setPosition( m_camera->getPosition() );
        m_light->setDirection( m_camera->getDirection() );
    }

    emit cameraChanged( m_camera->getPosition(), m_target );
}

void Gui::TrackballCameraManipulator::handleCameraRotate( Scalar dx, Scalar dy ) {
    Scalar dphi = dx * m_cameraSensitivity * m_quickCameraModifier;
    Scalar y    = -dy * m_cameraSensitivity * m_quickCameraModifier;

    Scalar phi   = std::fmod( m_phi + dphi, 2_ra * Pi );          // Keep phi between 0 and 2pi
    Scalar theta = std::fmod( m_theta + y + Pi, 2_ra * Pi ) - Pi; // Keep theta between -pi and pi

    Scalar dtheta = theta - m_theta;

    Core::Vector3 P =
        m_target + m_distFromCenter * Core::Vector3( -std::cos( phi ) * std::sin( theta ),
                                                     std::cos( theta ),
                                                     -std::sin( phi ) * std::sin( theta ) );

    Core::Vector3 t( P - m_camera->getPosition() );

    // Translate the camera given this translation
    Core::Transform T( Core::Transform::Identity() );
    T.translation() = t;

    // Rotate the camera so that it points to the center
    Core::Transform R1( Core::Transform::Identity() );
    Core::Transform R2( Core::Transform::Identity() );

    Core::Vector3 U = Core::Vector3( 0_ra, 1_ra, 0_ra );
    Core::Vector3 R = -m_camera->getRightVector().normalized();

    R1 = Core::AngleAxis( -dphi, U );
    R2 = Core::AngleAxis( -dtheta, R );

    m_camera->applyTransform( T * R1 * R2 );
    m_phi   = phi;
    m_theta = theta;
}

void Gui::TrackballCameraManipulator::handleCameraPan( Scalar dx, Scalar dy ) {
    Scalar x = dx * m_cameraSensitivity * m_quickCameraModifier * m_distFromCenter * 0.1_ra;
    Scalar y = dy * m_cameraSensitivity * m_quickCameraModifier * m_distFromCenter * 0.1_ra;
    // Move camera and trackball center, keep the distance to the center
    Core::Vector3 R = -m_camera->getRightVector();
    Core::Vector3 U = m_camera->getUpVector();

    Core::Transform T( Core::Transform::Identity() );
    Core::Vector3 t = x * R + y * U;
    T.translate( t );

    m_camera->applyTransform( T );
    m_target += t;
}

void Gui::TrackballCameraManipulator::handleCameraZoom( Scalar dx, Scalar dy ) {
    handleCameraZoom( Ra::Core::Math::sign( dx ) * ( std::abs( dx ) + std::abs( dy ) ) );
}

void Gui::TrackballCameraManipulator::handleCameraZoom( Scalar z ) {
    // tested this way of zooming, not convinced it's better
#if 0
    Scalar zoom = m_camera->getZoomFactor() - z * m_cameraSensitivity * m_quickCameraModifier;
    Scalar epsIn = 0.001;
    Scalar epsOut = 3.1;
    m_camera->setZoomFactor( std::clamp( zoom, epsIn, epsOut ) );
#else
    Scalar y    = m_distFromCenter * z * m_cameraSensitivity * m_quickCameraModifier;
    Scalar dist = ( m_target - m_camera->getPosition() ).norm();
    if ( dist < ( m_camera->getZNear() + y ) ) { y = dist - m_camera->getZNear(); }

    Core::Transform T( Core::Transform::Identity() );
    Core::Vector3 t = y * m_camera->getDirection();
    T.translate( t );

    m_camera->applyTransform( T );
    m_distFromCenter = ( m_target - m_camera->getPosition() ).norm();

    emit cameraPositionChanged( m_camera->getPosition() );
#endif
}

void Gui::TrackballCameraManipulator::updatePhiTheta() {
    using Core::Math::areApproxEqual;
    const auto R = m_camera->getDirection().normalized();

    m_theta = std::acos( -R.y() );

    m_phi = ( areApproxEqual( R.z(), 0_ra ) && areApproxEqual( R.x(), 0_ra ) )
                ? std::acos( m_camera->getRightVector().dot( Ra::Core::Vector3::UnitZ() ) ) + Pi
                : std::atan2( R.z(), R.x() );

    // Keep phi between 0 and 2pi
    // Keep theta between -pi and pi
    if ( m_phi < 0_ra )
    {
        m_theta = -m_theta + Pi;
        m_phi += 2_ra * Pi;
    }

    CORE_ASSERT( std::isfinite( m_theta ) && std::isfinite( m_phi ), "Error in trackball camera" );
}

bool Gui::TrackballCameraManipulator::checkIntegrity( const std::string& mess ) const {
    Core::Vector3 c = m_camera->getPosition() + m_distFromCenter * m_camera->getDirection();
    Scalar d        = ( m_target - c ).norm();
    if ( d > 0.001_ra )
    {
        LOG( Ra::Core::Utils::logWARNING )
            << "TrackballCameraManipulator Integrity problem : " << mess;
        LOG( Ra::Core::Utils::logWARNING ) << "\t Position " << m_camera->getPosition().transpose();
        LOG( Ra::Core::Utils::logWARNING )
            << "\t Direction " << m_camera->getDirection().transpose();
        LOG( Ra::Core::Utils::logWARNING ) << "\t Target " << m_target.transpose();
        LOG( Ra::Core::Utils::logWARNING ) << "\t Center " << c.transpose();
        LOG( Ra::Core::Utils::logWARNING ) << "\t Distance " << d;
    }
    return d < 0.001_ra;
}

} // namespace Gui
} // namespace Ra
<|endoftext|>


<commit_before>// @(#)root/alien:$Name:  $:$Id: TAlienJDL.cxx,v 1.4 2007/03/19 16:55:55 rdm Exp $
// Author: Jan Fiete Grosse-Oetringhaus   28/9/2004

/*************************************************************************
 * Copyright (C) 1995-2004, Rene Brun and Fons Rademakers.               *
 * All rights reserved.                                                  *
 *                                                                       *
 * For the licensing terms see $ROOTSYS/LICENSE.                         *
 * For the list of contributors see $ROOTSYS/README/CREDITS.             *
 *************************************************************************/

//////////////////////////////////////////////////////////////////////////
//                                                                      //
// TAlienJDL                                                            //
//                                                                      //
// Class which creates JDL files for the alien middleware               //
//                                                                      //
//////////////////////////////////////////////////////////////////////////

#include "TAlienJDL.h"
#include "TGrid.h"
#include "TGridJob.h"
#include "Riostream.h"

ClassImp(TAlienJDL)

//______________________________________________________________________________
void TAlienJDL::SetExecutable(const char* value)
{
   // Sets the executable.

   if (value)
      SetValue("Executable", AddQuotes(value));
}

//______________________________________________________________________________
void TAlienJDL::SetArguments(const char* value)
{
   // Sets the arguments.

   if (value)
      SetValue("Arguments", AddQuotes(value));
}

//______________________________________________________________________________
void TAlienJDL::SetEMail(const char* value)
{
   // Sets eMail address.

   if (value)
      SetValue("EMail", AddQuotes(value));
}

//______________________________________________________________________________
void TAlienJDL::SetOutputDirectory(const char* value)
{
   // Sets OutputDirectory

   if (value)
      SetValue("OutputDirectory", AddQuotes(value));
}

//______________________________________________________________________________
void TAlienJDL:: SetPrice(UInt_t price)
{
   // Sets OutputDirectory.

   TString pricestring= (Int_t)price;

   SetValue("Price", pricestring.Data());
}

//______________________________________________________________________________
void TAlienJDL:: SetTTL(UInt_t ttl)
{
   // Sets OutputDirectory.

   TString ttlstring= (Int_t)ttl;

   SetValue("TTL", ttlstring.Data());
}

//______________________________________________________________________________
void TAlienJDL::SetJobTag(const char* value)
{
   // Sets Job Tag

   if (value)
      SetValue("JobTag", AddQuotes(value));
}

//______________________________________________________________________________
void TAlienJDL::SetInputDataListFormat(const char* value)
{
   // Sets InputDataListFormat - can be "xml-single" or "xml-multi"

   if (value)
      SetValue("InputDataListFormat", AddQuotes(value));
}

//______________________________________________________________________________
void TAlienJDL::SetInputDataList(const char* value)
{
   // Sets InputDataList name

   if (value)
      SetValue("InputDataList", AddQuotes(value));
}

//______________________________________________________________________________
void TAlienJDL::SetSplitMode(const char* value, UInt_t maxnumberofinputfiles, UInt_t maxinputfilesize)
{
   // Sets the split mode.

   if ( (TString(value) == "se" ) || (TString(value) == "SE") || (TString(value == "Se"))) {
      SetValue("Split", AddQuotes(value));
      if (maxnumberofinputfiles) {
         TString val = (Int_t)maxnumberofinputfiles;
         SetValue("SplitMaxInputFileNumber", AddQuotes(val.Data()));
      }
      if (maxinputfilesize) {
         TString val = (Int_t)maxinputfilesize;
         SetValue("SplitMaxInputFileSize", AddQuotes(val.Data()));
      }
   } else {
      if (value)
         SetValue("Split",AddQuotes(value));
   }
}

//______________________________________________________________________________
void TAlienJDL::SetSplitArguments(const char* splitarguments)
{
   // Sets the split.

   if (splitarguments)
      SetValue("SplitArguments", AddQuotes(splitarguments));
}

//______________________________________________________________________________
void TAlienJDL::SetValidationCommand(const char* value)
{
   // Sets the validation command.

   SetValue("ValidationCommand", AddQuotes(value));
}

//______________________________________________________________________________
void TAlienJDL::AddToRequirements(const char* value)
{
   // Adds a requirement.

   if (value)
      AddToSet("Requirements", value);
}

//______________________________________________________________________________
void TAlienJDL::AddToInputSandbox(const char* value)
{
   // Adds a file to the input sandbox.

   if (value)
      AddToSet("InputFile", value);
}

//______________________________________________________________________________
void TAlienJDL::AddToOutputSandbox(const char* value)
{
   // Adds a file to the output sandbox.

   if (value)
      AddToSet("OutputFile", value);
}

//______________________________________________________________________________
void TAlienJDL::AddToInputData(const char* value)
{
   // Adds a file to the input data.

   if (value)
      AddToSet("InputData", value);
}

//______________________________________________________________________________
void TAlienJDL::AddToInputDataCollection(const char* value)
{
   // Adds a file to the input data collection.

   if (value)
      AddToSet("InputDataCollection", value);
}

//______________________________________________________________________________
void TAlienJDL::AddToPackages(const char* name,const char* version, const char* type)
{
   // Adds a package name to the package section

   if (name) {
      TString packagename = type;
      packagename += "@";
      packagename += name;
      packagename += "::";
      packagename += version;

      AddToSet("Packages", packagename.Data());
   }
}

//______________________________________________________________________________
void TAlienJDL::AddToOutputArchive(const char* value)
{
   // Adds an output archive definition

   if (value)
      AddToSet("OutputArchive", value);
}

//______________________________________________________________________________
Bool_t TAlienJDL::SubmitTest()
{
   // Tests the submission of a simple job.

   Info("SubmitTest", "submitting test job /bin/date");

   if (!gGrid) {
      Error("SubmitTest", "you must have a proper GRID environment initialized");
      return kFALSE;
   }

   Clear();
   SetExecutable("/bin/date");
   SetArguments("-R");
   TGridJob* job = gGrid->Submit(Generate());
   printf("Sending:\n%s\n",Generate().Data());
   if (job == 0) {
      Error("SubmitTest", "submitting failed");
      return kFALSE;
   }

   return kTRUE;
}
<commit_msg>From Andreas: several small bug fixes.<commit_after>// @(#)root/alien:$Name: v5-15-04 $:$Id: TAlienJDL.cxx,v 1.5 2007/03/20 08:02:11 brun Exp $
// Author: Jan Fiete Grosse-Oetringhaus   28/9/2004

/*************************************************************************
 * Copyright (C) 1995-2004, Rene Brun and Fons Rademakers.               *
 * All rights reserved.                                                  *
 *                                                                       *
 * For the licensing terms see $ROOTSYS/LICENSE.                         *
 * For the list of contributors see $ROOTSYS/README/CREDITS.             *
 *************************************************************************/

//////////////////////////////////////////////////////////////////////////
//                                                                      //
// TAlienJDL                                                            //
//                                                                      //
// Class which creates JDL files for the alien middleware               //
//                                                                      //
//////////////////////////////////////////////////////////////////////////

#include "TAlienJDL.h"
#include "TGrid.h"
#include "TGridJob.h"
#include "Riostream.h"

ClassImp(TAlienJDL)

//______________________________________________________________________________
void TAlienJDL::SetExecutable(const char* value)
{
   // Sets the executable.

   if (value)
      SetValue("Executable", AddQuotes(value));
}

//______________________________________________________________________________
void TAlienJDL::SetArguments(const char* value)
{
   // Sets the arguments.

   if (value)
      SetValue("Arguments", AddQuotes(value));
}

//______________________________________________________________________________
void TAlienJDL::SetEMail(const char* value)
{
   // Sets eMail address.

   if (value)
      SetValue("EMail", AddQuotes(value));
}

//______________________________________________________________________________
void TAlienJDL::SetOutputDirectory(const char* value)
{
   // Sets OutputDirectory

   if (value)
      SetValue("OutputDirectory", AddQuotes(value));
}

//______________________________________________________________________________
void TAlienJDL:: SetPrice(UInt_t price)
{
   // Sets OutputDirectory.

   TString pricestring= (Int_t)price;

   SetValue("Price", pricestring.Data());
}

//______________________________________________________________________________
void TAlienJDL:: SetTTL(UInt_t ttl)
{
   TString ttlstring;
   ttlstring+= ttl;

   SetValue("TTL", ttlstring.Data());
}

//______________________________________________________________________________
void TAlienJDL::SetJobTag(const char* value)
{
   // Sets Job Tag

   if (value)
      SetValue("JobTag", AddQuotes(value));
}

//______________________________________________________________________________
void TAlienJDL::SetInputDataListFormat(const char* value)
{
   // Sets InputDataListFormat - can be "xml-single" or "xml-multi"

   if (value)
      SetValue("InputDataListFormat", AddQuotes(value));
}

//______________________________________________________________________________
void TAlienJDL::SetInputDataList(const char* value)
{
   // Sets InputDataList name

   if (value)
      SetValue("InputDataList", AddQuotes(value));
}

//______________________________________________________________________________
void TAlienJDL::SetSplitMode(const char* value, UInt_t maxnumberofinputfiles, UInt_t maxinputfilesize)
{
   // Sets the split mode.

   if (value && !strcasecmp(value, "SE")) {

      SetValue("Split", AddQuotes(value));
      if (maxnumberofinputfiles) {
         TString val;
         val += maxnumberofinputfiles;
         SetValue("SplitMaxInputFileNumber", AddQuotes(val.Data()));
      }
      if (maxinputfilesize) {
         TString val;
         val += maxinputfilesize;
         SetValue("SplitMaxInputFileSize", AddQuotes(val.Data()));
      }
   } else {
      if (value)
         SetValue("Split",AddQuotes(value));
   }
}

//______________________________________________________________________________
void TAlienJDL::SetSplitArguments(const char* splitarguments)
{
   // Sets the split.

   if (splitarguments)
      SetValue("SplitArguments", AddQuotes(splitarguments));
}

//______________________________________________________________________________
void TAlienJDL::SetValidationCommand(const char* value)
{
   // Sets the validation command.

   SetValue("ValidationCommand", AddQuotes(value));
}

//______________________________________________________________________________
void TAlienJDL::AddToRequirements(const char* value)
{
   // Adds a requirement.

   if (value)
      AddToSet("Requirements", value);
}

//______________________________________________________________________________
void TAlienJDL::AddToInputSandbox(const char* value)
{
   // Adds a file to the input sandbox.

   if (value)
      AddToSet("InputFile", value);
}

//______________________________________________________________________________
void TAlienJDL::AddToOutputSandbox(const char* value)
{
   // Adds a file to the output sandbox.

   if (value)
      AddToSet("OutputFile", value);
}

//______________________________________________________________________________
void TAlienJDL::AddToInputData(const char* value)
{
   // Adds a file to the input data.

   if (value)
      AddToSet("InputData", value);
}

//______________________________________________________________________________
void TAlienJDL::AddToInputDataCollection(const char* value)
{
   // Adds a file to the input data collection.

   if (value)
      AddToSet("InputDataCollection", value);
}

//______________________________________________________________________________
void TAlienJDL::AddToPackages(const char* name,const char* version, const char* type)
{
   // Adds a package name to the package section

   if (name) {
      TString packagename = type;
      packagename += "@";
      packagename += name;
      packagename += "::";
      packagename += version;

      AddToSet("Packages", packagename.Data());
   }
}

//______________________________________________________________________________
void TAlienJDL::AddToOutputArchive(const char* value)
{
   // Adds an output archive definition

   if (value)
      AddToSet("OutputArchive", value);
}

//______________________________________________________________________________
Bool_t TAlienJDL::SubmitTest()
{
   // Tests the submission of a simple job.

   Info("SubmitTest", "submitting test job /bin/date");

   if (!gGrid) {
      Error("SubmitTest", "you must have a proper GRID environment initialized");
      return kFALSE;
   }

   Clear();
   SetExecutable("/bin/date");
   SetArguments("-R");
   TGridJob* job = gGrid->Submit(Generate());
   printf("Sending:\n%s\n",Generate().Data());
   if (job == 0) {
      Error("SubmitTest", "submitting failed");
      return kFALSE;
   }

   return kTRUE;
}
<|endoftext|>


<commit_before>#include "CBasefunction.h"
#include <iostream>
int main(int argc, char *argv[]) {
//    int redemarrage = atoi(argv[7]);
//    int position = atoi(argv[6]);
//    GUI_ARINC_partition("Partition2", position, redemarrage);
//    int nbarg = argc;
//    char **argument = new char*[argc];
//    int i = 0;
//    for (i = 0; i <= nbarg; i++) {
//        argument[i] = argv[i];
//    }
//    COMMUNICATION_VECTOR myCvector;
//    myCvector = init_communication(nbarg, argument, NULL);
//    Type_Message rMessage;
//    int portID;
//    int sock;
//    vector_get(&(myCvector.vqueuing_port), 0, &portID);
//    vector_get(&(myCvector.vqueuing_socket), 0, &sock);
//    //    CQueuing Qservice;
//
//    int ifmessage = 0;
//
//    for (;;) {
//        std::cout << "debur boucle for, vqueuing_socket[0] : " << sock << std::endl;
//
//        ifmessage = RECEIVE_QUEUING_MESSAGE(sock, &rMessage);
//        if (ifmessage > 0) {
//            //            Qservice.Display_Message();
//            std::cout << "			" << std::endl;
//            std::cout << "Display message : " << rMessage.m_message << std::endl;
//            std::cout << "length " << rMessage.m_length << std::endl;
//            std::cout << "total length " << sizeof (rMessage) << std::endl;
//            std::cout << "receive :" << rMessage.m_message << std::endl;
//            std::cout << "			" << std::endl;
//        }
//
//    }
    return 0;
}

<commit_msg>Use case Queueing working : Partition1 sending messages to Partition2<commit_after>#include "CBasefunction.h"
#include <iostream>
int main(int argc, char *argv[]) {
    int redemarrage = atoi(argv[7]);
    int position = atoi(argv[6]);
    GUI_ARINC_partition("Partition2", position, redemarrage);
    int nbarg = argc;
    char **argument = new char*[argc];
    int i = 0;
    for (i = 0; i <= nbarg; i++) {
        argument[i] = argv[i];
    }
    COMMUNICATION_VECTOR myCvector;
    myCvector = init_communication(nbarg, argument, NULL);
    Type_Message rMessage;
    int portID;
    int sock;
    vector_get(&(myCvector.vqueuing_port), 0, &portID);
    vector_get(&(myCvector.vqueuing_socket), 0, &sock);
    //    CQueuing Qservice;

    int ifmessage = 0;

    for (;;) {
        std::cout << "debur boucle for, vqueuing_socket[0] : " << sock << std::endl;

        ifmessage = RECEIVE_QUEUING_MESSAGE(sock, &rMessage);
        if (ifmessage > 0) {
            //            Qservice.Display_Message();
            std::cout << "			" << std::endl;
            std::cout << "Display message : " << rMessage.m_message << std::endl;
            std::cout << "length " << rMessage.m_length << std::endl;
            std::cout << "total length " << sizeof (rMessage) << std::endl;
            std::cout << "receive :" << rMessage.m_message << std::endl;
            std::cout << "			" << std::endl;
        }

    }
    return 0;
}

<|endoftext|>


<commit_before>// Copyright (c) 2013, Facebook, Inc.  All rights reserved.
// This source code is licensed under the BSD-style license found in the
// LICENSE file in the root directory of this source tree. An additional grant
// of patent rights can be found in the PATENTS file in the same directory.
#include <cstdio>
#include <string>
#include <vector>

#include "rocksdb/db.h"
#include "rocksdb/slice.h"
#include "rocksdb/options.h"

using namespace rocksdb;

std::string kDBPath = "/tmp/rocksdb_column_families_example";

int main() {
  // open DB
  Options options;
  options.create_if_missing = true;
  DB* db;
  Status s = DB::Open(options, kDBPath, &db);
  assert(s.ok());

  // create column family
  ColumnFamilyHandle* cf;
  s = db->CreateColumnFamily(ColumnFamilyOptions(), "new_cf", &cf);
  assert(s.ok());

  // close DB
  delete cf;
  delete db;

  // open DB with two column families
  std::vector<ColumnFamilyDescriptor> column_families;
  // have to open default column familiy
  column_families.push_back(ColumnFamilyDescriptor(
      kDefaultColumnFamilyName, ColumnFamilyOptions()));
  // open the new one, too
  column_families.push_back(ColumnFamilyDescriptor(
      "new_cf", ColumnFamilyOptions()));
  std::vector<ColumnFamilyHandle*> handles;
  s = DB::Open(DBOptions(), kDBPath, column_families, &handles, &db);
  assert(s.ok());

  // put and get from non-default column family
  s = db->Put(WriteOptions(), handles[1], Slice("key"), Slice("value"));
  assert(s.ok());
  std::string value;
  s = db->Get(ReadOptions(), handles[1], Slice("key"), &value);
  assert(s.ok());

  // atomic write
  WriteBatch batch;
  batch.Put(handles[0], Slice("key2"), Slice("value2"));
  batch.Put(handles[1], Slice("key3"), Slice("value3"));
  batch.Delete(handles[0], Slice("key"));
  s = db->Write(WriteOptions(), &batch);
  assert(s.ok());

  // drop column family
  s = db->DropColumnFamily(handles[1]);
  assert(s.ok());

  // close db
  for (auto handle : handles) {
    delete handle;
  }
  delete db;

  return 0;
}
<commit_msg>fix really trivial typo<commit_after>// Copyright (c) 2013, Facebook, Inc.  All rights reserved.
// This source code is licensed under the BSD-style license found in the
// LICENSE file in the root directory of this source tree. An additional grant
// of patent rights can be found in the PATENTS file in the same directory.
#include <cstdio>
#include <string>
#include <vector>

#include "rocksdb/db.h"
#include "rocksdb/slice.h"
#include "rocksdb/options.h"

using namespace rocksdb;

std::string kDBPath = "/tmp/rocksdb_column_families_example";

int main() {
  // open DB
  Options options;
  options.create_if_missing = true;
  DB* db;
  Status s = DB::Open(options, kDBPath, &db);
  assert(s.ok());

  // create column family
  ColumnFamilyHandle* cf;
  s = db->CreateColumnFamily(ColumnFamilyOptions(), "new_cf", &cf);
  assert(s.ok());

  // close DB
  delete cf;
  delete db;

  // open DB with two column families
  std::vector<ColumnFamilyDescriptor> column_families;
  // have to open default column family
  column_families.push_back(ColumnFamilyDescriptor(
      kDefaultColumnFamilyName, ColumnFamilyOptions()));
  // open the new one, too
  column_families.push_back(ColumnFamilyDescriptor(
      "new_cf", ColumnFamilyOptions()));
  std::vector<ColumnFamilyHandle*> handles;
  s = DB::Open(DBOptions(), kDBPath, column_families, &handles, &db);
  assert(s.ok());

  // put and get from non-default column family
  s = db->Put(WriteOptions(), handles[1], Slice("key"), Slice("value"));
  assert(s.ok());
  std::string value;
  s = db->Get(ReadOptions(), handles[1], Slice("key"), &value);
  assert(s.ok());

  // atomic write
  WriteBatch batch;
  batch.Put(handles[0], Slice("key2"), Slice("value2"));
  batch.Put(handles[1], Slice("key3"), Slice("value3"));
  batch.Delete(handles[0], Slice("key"));
  s = db->Write(WriteOptions(), &batch);
  assert(s.ok());

  // drop column family
  s = db->DropColumnFamily(handles[1]);
  assert(s.ok());

  // close db
  for (auto handle : handles) {
    delete handle;
  }
  delete db;

  return 0;
}
<|endoftext|>


<commit_before>#include "MoveController.h"
#include "GameController.h"

#include "fakeit.hpp"

using namespace fakeit;
using cocos2d::Vec2;
using cocos2d::TMXTiledMap;
using cocos2d::TMXLayer;
using cocos2d::TMXObjectGroup;
using cocos2d::Size;
using cocos2d::Sprite;
using cocos2d::ValueVector;
using cocos2d::ValueMap;
using cocos2d::Value;

class MoveControllerStub: public tsg::move::MoveController {
 public:
  virtual Vec2 getPlayerSpawn() const;
  virtual Vec2 getPlayerPosition() const;
  virtual void initSprite(Vec2) override;
  virtual void onMapLoad(TMXTiledMap *) override;
  virtual void onInit() override;
};

class MapControllerStub: public tsg::map::MapController {
  virtual void loadMapFromFile(const std::string &) { }
 public:
  MapControllerStub() : MapController(nullptr) { }
};

class TMXTiledMapStub: public TMXTiledMap {
 public:
  virtual TMXLayer *getLayer(const std::string &layerName) const;
  virtual TMXObjectGroup *getObjectGroup(const std::string &groupName) const;
  virtual const Size &getTileSize() const;
};

class TMXLayerStub: public cocos2d::TMXLayer {
 private:
  std::map<Vec2, Sprite *> tiles;
 public:
  virtual Sprite *getTileAt(const Vec2&);
  virtual void setTileAt(const Vec2, Sprite *);
};

//=============================8<==================================

void MoveControllerStub::initSprite(Vec2) { /*stubbed*/}
void MoveControllerStub::onMapLoad(TMXTiledMap *map) { tsg::move::MoveController::onMapLoad(map); }
void MoveControllerStub::onInit() { tsg::move::MoveController::onInit(); }
Vec2 MoveControllerStub::getPlayerSpawn() const { return playerSpawn; }
Vec2 MoveControllerStub::getPlayerPosition() const { return playerPosition; }

TMXLayer *TMXTiledMapStub::getLayer(const std::string &) const { return nullptr; }
TMXObjectGroup *TMXTiledMapStub::getObjectGroup(const std::string &) const { return nullptr; }
const Size &TMXTiledMapStub::getTileSize() const { return Size::ZERO; }

Sprite *TMXLayerStub::getTileAt(const Vec2 &v) { return tiles[v]; }
void TMXLayerStub::setTileAt(const Vec2 v, Sprite *sprite) { tiles[v] = sprite; }

//================================8<=======================================

TMXObjectGroup mkObjectGroup(Vec2 p) {
  TMXObjectGroup group;
  ValueVector v;
  ValueMap vp;
  vp["name"] = "spawn1";
  vp["x"] = Value(p.x);
  vp["y"] = Value(p.y);
  v.push_back(Value(vp));
  group.setObjects(v);
  return group;
}

TEST_CASE("That player spawns well in spawn point and map is scrolled to spawn point correctly",
          "[MoveController]") {
  TMXLayerStub layerStub;
  Mock<TMXTiledMapStub> mapMock;
  Sprite zeroPointSpriteStub;
  Sprite spawnSpriteStub;
  Mock<MapControllerStub> mapControllerMock;
  MoveControllerStub moveControllerStub;
  std::string spawnLayer = "spawn point";
  auto gameController = tsg::game::GameController::getInstance();
  auto zeroPointGrid = Vec2(0, 0);
  auto zeroPointWorld = Vec2(1000.0f, 1000.0f);
  auto spawnPointGrid = Vec2(4, 29);
  auto spawnPointWorld = Vec2(100, 100);
  auto tileSize = Size(64, 32);
  auto group = mkObjectGroup(Vec2(100, 100));

  gameController->injectControllers(&moveControllerStub, &mapControllerMock.get(), nullptr, nullptr);
  zeroPointSpriteStub.setPosition(zeroPointWorld);
  spawnSpriteStub.setPosition(spawnPointWorld);
  layerStub.setTileAt(zeroPointGrid, &zeroPointSpriteStub);
  layerStub.setTileAt(spawnPointGrid, &spawnSpriteStub);

  When(ConstOverloadedMethod(mapMock, getLayer, TMXLayer *(
           const std::string &)).Using("water")).AlwaysReturn(&layerStub);
  When(Method(mapMock, getObjectGroup).Using(spawnLayer)).AlwaysReturn(&group);
  When(Method(mapMock, getTileSize)).AlwaysReturn(tileSize);
//  When(Method(layerMock, getTileAt).Using(zeroPointGrid)).AlwaysReturn(&zeroPointSpriteStub);
//  When(Method(layerMock, getTileAt).Using(spawnPointGrid)).AlwaysReturn(&spawnSpriteStub);
  When(OverloadedMethod(mapControllerMock, lookAt, void(Vec2))).Return();
//  moveControllerStub.onMapLoad(&mapMock.get());
//  REQUIRE(moveControllerStub.getPlayerSpawn() == spawnPointWorld);
//  REQUIRE(moveControllerStub.getPlayerPosition() == moveControllerStub.getPlayerSpawn());
//  Verify(OverloadedMethod(mapControllerMock, lookAt, void(Vec2)).Using(spawnPointWorld)).Once();
}
<commit_msg>trying to add broken code<commit_after>#include "MoveController.h"
#include "GameController.h"

#include "fakeit.hpp"

using namespace fakeit;
using cocos2d::Vec2;
using cocos2d::TMXTiledMap;
using cocos2d::TMXLayer;
using cocos2d::TMXObjectGroup;
using cocos2d::Size;
using cocos2d::Sprite;
using cocos2d::ValueVector;
using cocos2d::ValueMap;
using cocos2d::Value;

class MoveControllerStub: public tsg::move::MoveController {
 public:
  virtual Vec2 getPlayerSpawn() const;
  virtual Vec2 getPlayerPosition() const;
  virtual void initSprite(Vec2) override;
  virtual void onMapLoad(TMXTiledMap *) override;
  virtual void onInit() override;
};

class MapControllerStub: public tsg::map::MapController {
  virtual void loadMapFromFile(const std::string &) { }
 public:
  MapControllerStub() : MapController(nullptr) { }
};

class TMXTiledMapStub: public TMXTiledMap {
 public:
  virtual TMXLayer *getLayer(const std::string &layerName) const;
  virtual TMXObjectGroup *getObjectGroup(const std::string &groupName) const;
  virtual const Size &getTileSize() const;
};

class TMXLayerStub: public cocos2d::TMXLayer {
 private:
  std::map<Vec2, Sprite *> tiles;
 public:
  virtual Sprite *getTileAt(const Vec2&);
  virtual void setTileAt(const Vec2, Sprite *);
};

//=============================8<==================================

void MoveControllerStub::initSprite(Vec2) { /*stubbed*/}
void MoveControllerStub::onMapLoad(TMXTiledMap *map) { tsg::move::MoveController::onMapLoad(map); }
void MoveControllerStub::onInit() { tsg::move::MoveController::onInit(); }
Vec2 MoveControllerStub::getPlayerSpawn() const { return playerSpawn; }
Vec2 MoveControllerStub::getPlayerPosition() const { return playerPosition; }

TMXLayer *TMXTiledMapStub::getLayer(const std::string &) const { return nullptr; }
TMXObjectGroup *TMXTiledMapStub::getObjectGroup(const std::string &) const { return nullptr; }
const Size &TMXTiledMapStub::getTileSize() const { return Size::ZERO; }

Sprite *TMXLayerStub::getTileAt(const Vec2 &v) { return tiles[v]; }
void TMXLayerStub::setTileAt(const Vec2 v, Sprite *sprite) { tiles[v] = sprite; }

//================================8<=======================================

TMXObjectGroup mkObjectGroup(Vec2 p) {
  TMXObjectGroup group;
  ValueVector v;
  ValueMap vp;
  vp["name"] = "spawn1";
  vp["x"] = Value(p.x);
  vp["y"] = Value(p.y);
  v.push_back(Value(vp));
  group.setObjects(v);
  return group;
}

TEST_CASE("That player spawns well in spawn point and map is scrolled to spawn point correctly",
          "[MoveController]") {
  TMXLayerStub layerStub;
  Mock<TMXTiledMapStub> mapMock;
  Sprite zeroPointSpriteStub;
  Sprite spawnSpriteStub;
  Mock<MapControllerStub> mapControllerMock;
  MoveControllerStub moveControllerStub;
  std::string spawnLayer = "spawn point";
  auto gameController = tsg::game::GameController::getInstance();
  auto zeroPointGrid = Vec2(0, 0);
  auto zeroPointWorld = Vec2(1000.0f, 1000.0f);
  auto spawnPointGrid = Vec2(4, 29);
  auto spawnPointWorld = Vec2(100, 100);
  auto tileSize = Size(64, 32);
  auto group = mkObjectGroup(Vec2(100, 100));

  gameController->injectControllers(&moveControllerStub, &mapControllerMock.get(), nullptr, nullptr);
  zeroPointSpriteStub.setPosition(zeroPointWorld);
  spawnSpriteStub.setPosition(spawnPointWorld);
  layerStub.setTileAt(zeroPointGrid, &zeroPointSpriteStub);
  layerStub.setTileAt(spawnPointGrid, &spawnSpriteStub);

  When(ConstOverloadedMethod(mapMock, getLayer, TMXLayer *(
           const std::string &)).Using("water")).AlwaysReturn(&layerStub);
  When(Method(mapMock, getObjectGroup).Using(spawnLayer)).AlwaysReturn(&group);
  When(Method(mapMock, getTileSize)).AlwaysReturn(tileSize);
//  When(Method(layerMock, getTileAt).Using(zeroPointGrid)).AlwaysReturn(&zeroPointSpriteStub);
//  When(Method(layerMock, getTileAt).Using(spawnPointGrid)).AlwaysReturn(&spawnSpriteStub);
  When(OverloadedMethod(mapControllerMock, lookAt, void(Vec2))).Return();
  moveControllerStub.onMapLoad(&mapMock.get());
  REQUIRE(moveControllerStub.getPlayerSpawn() == spawnPointWorld);
  REQUIRE(moveControllerStub.getPlayerPosition() == moveControllerStub.getPlayerSpawn());
  Verify(OverloadedMethod(mapControllerMock, lookAt, void(Vec2)).Using(spawnPointWorld)).Once();
}
<|endoftext|>


<commit_before>/*
 * git_repository_access.cpp
 *
 *  Created on: Aug 12, 2010
 *      Author: Mark Christensen
 */

#include "git_repository_access.h"

using namespace std;

const string TEMP_FILE = ".gitlog.tmp";
// ISO 8601 timestamp
//const string GIT_COMMAND = "git whatchanged --pretty=format:%ci --reverse --raw --encoding=UTF-8";
// Unix timestamp
const string GIT_COMMAND = "git whatchanged --pretty=format:%ct --reverse --raw --encoding=UTF-8";

// -------------------------------------------------------------------------
// API :: GitRepositoryAccess::GitRepositoryAccess
// PURPOSE :: instantiation of GitRepositoryAccess
//         :: specifically, with a local root of project info
// PARAMETERS :: std::string repositoryRoot
// RETURN :: None
// -------------------------------------------------------------------------
GitRepositoryAccess::GitRepositoryAccess(string repositoryRoot)
{
	this->root = repositoryRoot;

	// add git repo type of local files
	this->repoType = 1;

}

void GitRepositoryAccess::parseTimeBlock(SurrogateTreeNode* tree, long time, std::string *buffer)
{
	//DiscursiveDebugPrint("git,repository access","Parsing block for time %ld\n BLOCK IS: \n\n%s\n\n",time,buffer->c_str());

	// loop over each line and search for created files
	// created files are denoted by an '... A' tag sequence
	// create an istringstream to parse the suboutput for added files
	std::istringstream localGitBlockSS(*buffer);

	// individual filename line storage
	std::string fileNameLine;

	// individual filename storage
	std::string fileNameString;

	// ..a identifier location storage
	// as it will be used in search, init to -1
	int aLocation = -1;

	// loop over the detailed commit and find new filenames
	while (getline (localGitBlockSS, fileNameLine))
	{
		// test for new commit blocks, update revision number
		if(fileNameLine.find(":") != 0)
		{
			if(revTarget > 0)
			{
				localRevs++;
			}
			else
			{
				localRevs++;
				globalRevs++;
			}
		}

		//M,A,R,C,U = GIT ADD/MODIFY statuses
		//D = delete status
		int gitStatus = 0;
		aLocation = fileNameLine.find("... M");
		if (aLocation <= 0)
		{
			aLocation = fileNameLine.find("... A");
			gitStatus = 1;
		}
		if (aLocation <= 0)
		{
			aLocation = fileNameLine.find("... R");
			gitStatus = 1;
		}
		if (aLocation <= 0)
		{
			aLocation = fileNameLine.find("... C");
			gitStatus = 1;
		}
		if (aLocation <= 0)
		{
			aLocation = fileNameLine.find("... U");
			gitStatus = 1;
		}
		if (aLocation <= 0)
		{
			aLocation = fileNameLine.find("... D");
			gitStatus = 2;
		}
		if(aLocation > 0)
		{
			// locate the filename in git string
			fileNameString = fileNameLine.substr(aLocation+6,fileNameLine.size()-aLocation+6);

			// increase the number of global inserts by one
			if((insertTarget > 0) && (localInserts < insertTarget))
			{
					localInserts++;
					if(gitStatus == 1)
					{
						InsertByPathName(tree,fileNameString,time,1);
					}
					else
					{
						RemoveByPathName(tree,fileNameString);
					}
			}
			if((revTarget > 0) && (localRevs < revTarget))
			{
				if(gitStatus == 1)
				{
					InsertByPathName(tree,fileNameString,time,1);
				}
				else
				{
					RemoveByPathName(tree,fileNameString);
				}
			}
			if((insertTarget == 0) && (revTarget == 0))
			{
				globalInserts++;
				if(gitStatus == 1)
				{
					InsertByPathName(tree,fileNameString,time,1);
				}
				else
				{
					RemoveByPathName(tree,fileNameString);
				}
			}
		}

	}

}

SurrogateTreeNode* GitRepositoryAccess::generateTreeFromLog(std::string *buffer)
{
	// Blank ptree
	SurrogateTreeNode* result = new SurrogateTreeNode();
	result->set(TreeNodeKey::NAME, TreeNodeKey::ROOT);
	DiscursiveDebugPrint("git","LOG: %s\n",buffer);

	// store most recent file time
	long fileTime = 0;

	// For each time block, parse files and add to ptree
	char c;
	string str;
	for(int i=0;i<(int)buffer->size();i++)
	{
		c = buffer->at(i);
		if(c != '\n')
		{
			str += c;
		}
		else
		{
			// file time strings are 10 in length
			if(str.length() == 10)
			{
				fileTime = atol(str.c_str());
			}
			parseTimeBlock(result,fileTime,&str);
			str.clear();
		}
	}

	return result;
}

int GitRepositoryAccess::generateLog()
{
	// only generate the log in the first pass
	if(logGenerated == 0)
	{
		// create a string for holding the svn log
		repoLog.reserve(10024);  // reserve 10k for fast allocation

		// create a string for holding the svn command
		std::string localGitCommand = "cd " + this->root + "; " + GIT_COMMAND;

		// create a file pointer handle to our command output
		FILE *fp = popen(localGitCommand.c_str(), "r" );

		// loop over all the file handle and put into string
		while (true)
		{
		  int c = std::fgetc( fp );
		  if (c == EOF) break;
		  repoLog.push_back( (char)c );
		}
		std::fclose( fp );

		// show the log (debug)
		DiscursiveDebugPrint("git,repository access",repoLog.c_str());

		// don't re-generate logs if not necessary
		logGenerated = 1;
	}
    // figure out a meaningful return code
    return 1;
}

SurrogateTreeNode* GitRepositoryAccess::retrieve()
{
	SurrogateTreeNode* result = NULL;

	if(this->repoType == 1)
	{
		std::string localGitFile;
		// If we generated a log file
		if(this->generateLog())
		{
			// Create the tree from log
			result = this->generateTreeFromLog(&repoLog);
			DiscursiveDebugPrint("git,repository access","Generated tree with name '%s'\n", result->data[TreeNodeKey::NAME].c_str());
		}
	}

	return result;
}

<commit_msg>updated actual working now<commit_after>/*
 * git_repository_access.cpp
 *
 *  Created on: Aug 12, 2010
 *      Author: Mark Christensen
 */

#include "git_repository_access.h"

using namespace std;

const string TEMP_FILE = ".gitlog.tmp";
// ISO 8601 timestamp
//const string GIT_COMMAND = "git whatchanged --pretty=format:%ci --reverse --raw --encoding=UTF-8";
// Unix timestamp
const string GIT_COMMAND = "git whatchanged --pretty=format:%ct --reverse --raw --encoding=UTF-8";

// -------------------------------------------------------------------------
// API :: GitRepositoryAccess::GitRepositoryAccess
// PURPOSE :: instantiation of GitRepositoryAccess
//         :: specifically, with a local root of project info
// PARAMETERS :: std::string repositoryRoot
// RETURN :: None
// -------------------------------------------------------------------------
GitRepositoryAccess::GitRepositoryAccess(string repositoryRoot)
{
	this->root = repositoryRoot;

	// add git repo type of local files
	this->repoType = 1;

}

void GitRepositoryAccess::parseTimeBlock(SurrogateTreeNode* tree, long time, std::string *buffer)
{
	//DiscursiveDebugPrint("git,repository access","Parsing block for time %ld\n BLOCK IS: \n\n%s\n\n",time,buffer->c_str());

	// loop over each line and search for created files
	// created files are denoted by an '... A' tag sequence
	// create an istringstream to parse the suboutput for added files
	std::istringstream localGitBlockSS(*buffer);

	// individual filename line storage
	std::string fileNameLine;

	// individual filename storage
	std::string fileNameString;

	// ..a identifier location storage
	// as it will be used in search, init to -1
	int aLocation = -1;

	// loop over the detailed commit and find new filenames
	while (getline (localGitBlockSS, fileNameLine))
	{
		// test for new commit blocks, update revision number
		if(fileNameLine.find(":") != 0)
		{
			if(revTarget > 0)
			{
				localRevs++;
			}
			else
			{
				localRevs++;
				globalRevs++;
			}
		}

		//M,A,R,C,U = GIT ADD/MODIFY statuses
		//D = delete status
		int gitStatus = 0;
		aLocation = fileNameLine.find("... M");
		if (aLocation <= 0)
		{
			aLocation = fileNameLine.find("... A");
			gitStatus = 1;
		}
		if (aLocation <= 0)
		{
			aLocation = fileNameLine.find("... R");
			gitStatus = 1;
		}
		if (aLocation <= 0)
		{
			aLocation = fileNameLine.find("... C");
			gitStatus = 1;
		}
		if (aLocation <= 0)
		{
			aLocation = fileNameLine.find("... U");
			gitStatus = 1;
		}
		if (aLocation <= 0)
		{
			aLocation = fileNameLine.find("... D");
			gitStatus = 2;
		}
		if(aLocation > 0)
		{
			// locate the filename in git string
			fileNameString = fileNameLine.substr(aLocation+6,fileNameLine.size()-aLocation+6);

			// increase the number of global inserts by one
			if((insertTarget > 0) && (localInserts < insertTarget))
			{
					localInserts++;
					if(gitStatus == 1)
					{
						InsertByPathName(tree,fileNameString,time,1);
					}
					else if(gitStatus == 2)
					{
						RemoveByPathName(tree,fileNameString);
					}
			}
			if((revTarget > 0) && (localRevs < revTarget))
			{
				if(gitStatus == 1)
				{
					InsertByPathName(tree,fileNameString,time,1);
				}
				else if(gitStatus == 2)
				{
					RemoveByPathName(tree,fileNameString);
				}
			}
			if((insertTarget == 0) && (revTarget == 0))
			{
				globalInserts++;
				if(gitStatus == 1)
				{
					InsertByPathName(tree,fileNameString,time,1);
				}
				else if(gitStatus == 2)
				{
					RemoveByPathName(tree,fileNameString);
				}
			}
		}

	}

}

SurrogateTreeNode* GitRepositoryAccess::generateTreeFromLog(std::string *buffer)
{
	// Blank ptree
	SurrogateTreeNode* result = new SurrogateTreeNode();
	result->set(TreeNodeKey::NAME, TreeNodeKey::ROOT);
	DiscursiveDebugPrint("git","LOG: %s\n",buffer);

	// store most recent file time
	long fileTime = 0;

	// For each time block, parse files and add to ptree
	char c;
	string str;
	for(int i=0;i<(int)buffer->size();i++)
	{
		c = buffer->at(i);
		if(c != '\n')
		{
			str += c;
		}
		else
		{
			// file time strings are 10 in length
			if(str.length() == 10)
			{
				fileTime = atol(str.c_str());
			}
			parseTimeBlock(result,fileTime,&str);
			str.clear();
		}
	}

	return result;
}

int GitRepositoryAccess::generateLog()
{
	// only generate the log in the first pass
	if(logGenerated == 0)
	{
		// create a string for holding the svn log
		repoLog.reserve(10024);  // reserve 10k for fast allocation

		// create a string for holding the svn command
		std::string localGitCommand = "cd " + this->root + "; " + GIT_COMMAND;

		// create a file pointer handle to our command output
		FILE *fp = popen(localGitCommand.c_str(), "r" );

		// loop over all the file handle and put into string
		while (true)
		{
		  int c = std::fgetc( fp );
		  if (c == EOF) break;
		  repoLog.push_back( (char)c );
		}
		std::fclose( fp );

		// show the log (debug)
		DiscursiveDebugPrint("git,repository access",repoLog.c_str());

		// don't re-generate logs if not necessary
		logGenerated = 1;
	}
    // figure out a meaningful return code
    return 1;
}

SurrogateTreeNode* GitRepositoryAccess::retrieve()
{
	SurrogateTreeNode* result = NULL;

	if(this->repoType == 1)
	{
		std::string localGitFile;
		// If we generated a log file
		if(this->generateLog())
		{
			// Create the tree from log
			result = this->generateTreeFromLog(&repoLog);
			DiscursiveDebugPrint("git,repository access","Generated tree with name '%s'\n", result->data[TreeNodeKey::NAME].c_str());
		}
	}

	return result;
}

<|endoftext|>


<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "gpu/command_buffer/service/context_group.h"

#include <string>

#include "base/string_util.h"
#include "gpu/command_buffer/common/id_allocator.h"
#include "gpu/command_buffer/service/buffer_manager.h"
#include "gpu/command_buffer/service/framebuffer_manager.h"
#include "gpu/command_buffer/service/gles2_cmd_decoder.h"
#include "gpu/command_buffer/service/program_manager.h"
#include "gpu/command_buffer/service/renderbuffer_manager.h"
#include "gpu/command_buffer/service/shader_manager.h"
#include "gpu/command_buffer/service/texture_manager.h"
#include "ui/gfx/gl/gl_implementation.h"

namespace gpu {
namespace gles2 {

ContextGroup::ContextGroup(bool bind_generates_resource)
    : num_contexts_(0),
      bind_generates_resource_(bind_generates_resource),
      max_vertex_attribs_(0u),
      max_texture_units_(0u),
      max_texture_image_units_(0u),
      max_vertex_texture_image_units_(0u),
      max_fragment_uniform_vectors_(0u),
      max_varying_vectors_(0u),
      max_vertex_uniform_vectors_(0u),
      feature_info_(new FeatureInfo()) {
  id_namespaces_[id_namespaces::kBuffers].reset(new IdAllocator);
  id_namespaces_[id_namespaces::kFramebuffers].reset(new IdAllocator);
  id_namespaces_[id_namespaces::kProgramsAndShaders].reset(
      new NonReusedIdAllocator);
  id_namespaces_[id_namespaces::kRenderbuffers].reset(new IdAllocator);
  id_namespaces_[id_namespaces::kTextures].reset(new IdAllocator);
  id_namespaces_[id_namespaces::kQueries].reset(new IdAllocator);
}

ContextGroup::~ContextGroup() {
  CHECK(num_contexts_ == 0);
}

static void GetIntegerv(GLenum pname, uint32* var) {
  GLint value = 0;
  glGetIntegerv(pname, &value);
  *var = value;
}

bool ContextGroup::Initialize(const DisallowedFeatures& disallowed_features,
                              const char* allowed_features) {
  if (num_contexts_ > 0) {
    ++num_contexts_;
    return true;
  }

  if (!feature_info_->Initialize(disallowed_features, allowed_features)) {
    LOG(ERROR) << "ContextGroup::Initialize failed because FeatureInfo "
               << "initialization failed.";
    return false;
  }

  GLint max_renderbuffer_size = 0;
  glGetIntegerv(GL_MAX_RENDERBUFFER_SIZE, &max_renderbuffer_size);
  GLint max_samples = 0;
  if (feature_info_->feature_flags().chromium_framebuffer_multisample) {
    glGetIntegerv(GL_MAX_SAMPLES, &max_samples);
  }

  buffer_manager_.reset(new BufferManager());
  framebuffer_manager_.reset(new FramebufferManager());
  renderbuffer_manager_.reset(new RenderbufferManager(
      max_renderbuffer_size, max_samples));
  shader_manager_.reset(new ShaderManager());
  program_manager_.reset(new ProgramManager());

  // Lookup GL things we need to know.
  GetIntegerv(GL_MAX_VERTEX_ATTRIBS, &max_vertex_attribs_);
  const GLuint kGLES2RequiredMinimumVertexAttribs = 8u;
  if (max_vertex_attribs_ < kGLES2RequiredMinimumVertexAttribs) {
    LOG(ERROR) << "ContextGroup::Initialize failed because too few "
               << "vertex attributes supported.";
    return false;
  }

  GetIntegerv(GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS, &max_texture_units_);
  const GLuint kGLES2RequiredMinimumTextureUnits = 8u;
  if (max_texture_units_ < kGLES2RequiredMinimumTextureUnits) {
    LOG(ERROR) << "ContextGroup::Initialize failed because too few "
               << "texture units supported.";
    return false;
  }

  GLint max_texture_size = 0;
  GLint max_cube_map_texture_size = 0;
  glGetIntegerv(GL_MAX_TEXTURE_SIZE, &max_texture_size);
  glGetIntegerv(GL_MAX_CUBE_MAP_TEXTURE_SIZE, &max_cube_map_texture_size);

  // Limit Intel on Mac to 512.
  // TODO(gman): Update this code to check for a specific version of
  // the drivers above which we no longer need this fix.
#if defined(OS_MACOSX)
  const char* vendor_str = reinterpret_cast<const char*>(
      glGetString(GL_VENDOR));
  if (vendor_str) {
    std::string lc_str(::StringToLowerASCII(std::string(vendor_str)));
    bool intel_on_mac = strstr(lc_str.c_str(), "intel");
    if (intel_on_mac) {
      max_cube_map_texture_size = std::min(
        static_cast<GLint>(512), max_cube_map_texture_size);
    }
  }
#endif

  texture_manager_.reset(new TextureManager(feature_info_.get(),
                                            max_texture_size,
                                            max_cube_map_texture_size));

  GetIntegerv(GL_MAX_TEXTURE_IMAGE_UNITS, &max_texture_image_units_);
  GetIntegerv(
      GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS, &max_vertex_texture_image_units_);

  if (gfx::GetGLImplementation() == gfx::kGLImplementationEGLGLES2) {
    GetIntegerv(GL_MAX_FRAGMENT_UNIFORM_VECTORS,
        &max_fragment_uniform_vectors_);
    GetIntegerv(GL_MAX_VARYING_VECTORS, &max_varying_vectors_);
    GetIntegerv(GL_MAX_VERTEX_UNIFORM_VECTORS, &max_vertex_uniform_vectors_);
  } else {
    GetIntegerv(
        GL_MAX_FRAGMENT_UNIFORM_COMPONENTS, &max_fragment_uniform_vectors_);
    max_fragment_uniform_vectors_ /= 4;
    GetIntegerv(GL_MAX_VARYING_FLOATS, &max_varying_vectors_);
    max_varying_vectors_ /= 4;
    GetIntegerv(GL_MAX_VERTEX_UNIFORM_COMPONENTS, &max_vertex_uniform_vectors_);
    max_vertex_uniform_vectors_ /= 4;
  }

  if (!texture_manager_->Initialize()) {
    LOG(ERROR) << "Context::Group::Initialize failed because texture manager "
               << "failed to initialize.";
    return false;
  }

  ++num_contexts_;
  return true;
}

void ContextGroup::Destroy(bool have_context) {
  DCHECK(num_contexts_ > 0);
  if (--num_contexts_ > 0)
    return;

  if (buffer_manager_ != NULL) {
    buffer_manager_->Destroy(have_context);
    buffer_manager_.reset();
  }

  if (framebuffer_manager_ != NULL) {
    framebuffer_manager_->Destroy(have_context);
    framebuffer_manager_.reset();
  }

  if (renderbuffer_manager_ != NULL) {
    renderbuffer_manager_->Destroy(have_context);
    renderbuffer_manager_.reset();
  }

  if (texture_manager_ != NULL) {
    texture_manager_->Destroy(have_context);
    texture_manager_.reset();
  }

  if (program_manager_ != NULL) {
    program_manager_->Destroy(have_context);
    program_manager_.reset();
  }

  if (shader_manager_ != NULL) {
    shader_manager_->Destroy(have_context);
    shader_manager_.reset();
  }
}

IdAllocatorInterface* ContextGroup::GetIdAllocator(unsigned namespace_id) {
  if (namespace_id >= arraysize(id_namespaces_))
    return NULL;

  return id_namespaces_[namespace_id].get();
}

}  // namespace gles2
}  // namespace gpu

<commit_msg>Limit max texture size to 4096x4096 on intel mac<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "gpu/command_buffer/service/context_group.h"

#include <string>

#include "base/string_util.h"
#include "gpu/command_buffer/common/id_allocator.h"
#include "gpu/command_buffer/service/buffer_manager.h"
#include "gpu/command_buffer/service/framebuffer_manager.h"
#include "gpu/command_buffer/service/gles2_cmd_decoder.h"
#include "gpu/command_buffer/service/program_manager.h"
#include "gpu/command_buffer/service/renderbuffer_manager.h"
#include "gpu/command_buffer/service/shader_manager.h"
#include "gpu/command_buffer/service/texture_manager.h"
#include "ui/gfx/gl/gl_implementation.h"

namespace gpu {
namespace gles2 {

ContextGroup::ContextGroup(bool bind_generates_resource)
    : num_contexts_(0),
      bind_generates_resource_(bind_generates_resource),
      max_vertex_attribs_(0u),
      max_texture_units_(0u),
      max_texture_image_units_(0u),
      max_vertex_texture_image_units_(0u),
      max_fragment_uniform_vectors_(0u),
      max_varying_vectors_(0u),
      max_vertex_uniform_vectors_(0u),
      feature_info_(new FeatureInfo()) {
  id_namespaces_[id_namespaces::kBuffers].reset(new IdAllocator);
  id_namespaces_[id_namespaces::kFramebuffers].reset(new IdAllocator);
  id_namespaces_[id_namespaces::kProgramsAndShaders].reset(
      new NonReusedIdAllocator);
  id_namespaces_[id_namespaces::kRenderbuffers].reset(new IdAllocator);
  id_namespaces_[id_namespaces::kTextures].reset(new IdAllocator);
  id_namespaces_[id_namespaces::kQueries].reset(new IdAllocator);
}

ContextGroup::~ContextGroup() {
  CHECK(num_contexts_ == 0);
}

static void GetIntegerv(GLenum pname, uint32* var) {
  GLint value = 0;
  glGetIntegerv(pname, &value);
  *var = value;
}

bool ContextGroup::Initialize(const DisallowedFeatures& disallowed_features,
                              const char* allowed_features) {
  if (num_contexts_ > 0) {
    ++num_contexts_;
    return true;
  }

  if (!feature_info_->Initialize(disallowed_features, allowed_features)) {
    LOG(ERROR) << "ContextGroup::Initialize failed because FeatureInfo "
               << "initialization failed.";
    return false;
  }

  GLint max_renderbuffer_size = 0;
  glGetIntegerv(GL_MAX_RENDERBUFFER_SIZE, &max_renderbuffer_size);
  GLint max_samples = 0;
  if (feature_info_->feature_flags().chromium_framebuffer_multisample) {
    glGetIntegerv(GL_MAX_SAMPLES, &max_samples);
  }

  buffer_manager_.reset(new BufferManager());
  framebuffer_manager_.reset(new FramebufferManager());
  renderbuffer_manager_.reset(new RenderbufferManager(
      max_renderbuffer_size, max_samples));
  shader_manager_.reset(new ShaderManager());
  program_manager_.reset(new ProgramManager());

  // Lookup GL things we need to know.
  GetIntegerv(GL_MAX_VERTEX_ATTRIBS, &max_vertex_attribs_);
  const GLuint kGLES2RequiredMinimumVertexAttribs = 8u;
  if (max_vertex_attribs_ < kGLES2RequiredMinimumVertexAttribs) {
    LOG(ERROR) << "ContextGroup::Initialize failed because too few "
               << "vertex attributes supported.";
    return false;
  }

  GetIntegerv(GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS, &max_texture_units_);
  const GLuint kGLES2RequiredMinimumTextureUnits = 8u;
  if (max_texture_units_ < kGLES2RequiredMinimumTextureUnits) {
    LOG(ERROR) << "ContextGroup::Initialize failed because too few "
               << "texture units supported.";
    return false;
  }

  GLint max_texture_size = 0;
  GLint max_cube_map_texture_size = 0;
  glGetIntegerv(GL_MAX_TEXTURE_SIZE, &max_texture_size);
  glGetIntegerv(GL_MAX_CUBE_MAP_TEXTURE_SIZE, &max_cube_map_texture_size);

  // Limit Intel on Mac to 512.
  // TODO(gman): Update this code to check for a specific version of
  // the drivers above which we no longer need this fix.
#if defined(OS_MACOSX)
  const char* vendor_str = reinterpret_cast<const char*>(
      glGetString(GL_VENDOR));
  if (vendor_str) {
    std::string lc_str(::StringToLowerASCII(std::string(vendor_str)));
    bool intel_on_mac = strstr(lc_str.c_str(), "intel");
    if (intel_on_mac) {
      max_texture_size = std::min(
        static_cast<GLint>(4096), max_texture_size);
      max_cube_map_texture_size = std::min(
        static_cast<GLint>(512), max_cube_map_texture_size);
    }
  }
#endif

  texture_manager_.reset(new TextureManager(feature_info_.get(),
                                            max_texture_size,
                                            max_cube_map_texture_size));

  GetIntegerv(GL_MAX_TEXTURE_IMAGE_UNITS, &max_texture_image_units_);
  GetIntegerv(
      GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS, &max_vertex_texture_image_units_);

  if (gfx::GetGLImplementation() == gfx::kGLImplementationEGLGLES2) {
    GetIntegerv(GL_MAX_FRAGMENT_UNIFORM_VECTORS,
        &max_fragment_uniform_vectors_);
    GetIntegerv(GL_MAX_VARYING_VECTORS, &max_varying_vectors_);
    GetIntegerv(GL_MAX_VERTEX_UNIFORM_VECTORS, &max_vertex_uniform_vectors_);
  } else {
    GetIntegerv(
        GL_MAX_FRAGMENT_UNIFORM_COMPONENTS, &max_fragment_uniform_vectors_);
    max_fragment_uniform_vectors_ /= 4;
    GetIntegerv(GL_MAX_VARYING_FLOATS, &max_varying_vectors_);
    max_varying_vectors_ /= 4;
    GetIntegerv(GL_MAX_VERTEX_UNIFORM_COMPONENTS, &max_vertex_uniform_vectors_);
    max_vertex_uniform_vectors_ /= 4;
  }

  if (!texture_manager_->Initialize()) {
    LOG(ERROR) << "Context::Group::Initialize failed because texture manager "
               << "failed to initialize.";
    return false;
  }

  ++num_contexts_;
  return true;
}

void ContextGroup::Destroy(bool have_context) {
  DCHECK(num_contexts_ > 0);
  if (--num_contexts_ > 0)
    return;

  if (buffer_manager_ != NULL) {
    buffer_manager_->Destroy(have_context);
    buffer_manager_.reset();
  }

  if (framebuffer_manager_ != NULL) {
    framebuffer_manager_->Destroy(have_context);
    framebuffer_manager_.reset();
  }

  if (renderbuffer_manager_ != NULL) {
    renderbuffer_manager_->Destroy(have_context);
    renderbuffer_manager_.reset();
  }

  if (texture_manager_ != NULL) {
    texture_manager_->Destroy(have_context);
    texture_manager_.reset();
  }

  if (program_manager_ != NULL) {
    program_manager_->Destroy(have_context);
    program_manager_.reset();
  }

  if (shader_manager_ != NULL) {
    shader_manager_->Destroy(have_context);
    shader_manager_.reset();
  }
}

IdAllocatorInterface* ContextGroup::GetIdAllocator(unsigned namespace_id) {
  if (namespace_id >= arraysize(id_namespaces_))
    return NULL;

  return id_namespaces_[namespace_id].get();
}

}  // namespace gles2
}  // namespace gpu

<|endoftext|>


<commit_before><commit_msg>Rename: cmt_io to cmt_mgr<commit_after><|endoftext|>