BaseEntity::~BaseEntity()
{
    try
    {
        if ( _p_transformNode.valid() )
        {
            size_t parents = _p_transformNode->getParents().size();
            if ( parents == 0 )
            {
                log_warning << "the transformation node of entity '" << getInstanceName() << "' has no parent!" << std::endl;
            }
            else
            {
                for ( size_t p = 0; p < parents; p++ )
                {
                    _p_transformNode->getParent( p )->removeChild( _p_transformNode.get() );
                }
            }
        }
    }
    catch( ... )
    {
        log_error << "exception occured in destructor of '" << getInstanceName() << "'" << std::endl;
    }

    // remove all attributes
    _p_attributeManager->removeAllAttributes();
    delete _p_attributeManager;
}
RTC::ReturnCode_t HrpsysSeqStateROSBridge::onInitialize() {
    // initialize
    ROS_INFO_STREAM("[HrpsysSeqStateROSBridge] @Initilize name : " << getInstanceName());

    // impl
    HrpsysSeqStateROSBridgeImpl::onInitialize();

    if ( body == NULL ) {
        return RTC::RTC_ERROR;
    }
    ROS_INFO_STREAM("[HrpsysSeqStateROSBridge] Loaded " << body->name());
    body->calcForwardKinematics();

    tm.tick();

    rootlink_name = std::string((*(bodyinfo->links()))[0].segments[0].name);
    interpolationp = false;

    ROS_INFO_STREAM("[HrpsysSeqStateROSBridge] @Initilize name : " << getInstanceName() << " done");

    fsensor_pub.resize(m_rsforceIn.size());
    for (unsigned int i=0; i<m_rsforceIn.size(); i++) {
        fsensor_pub[i] = nh.advertise<geometry_msgs::WrenchStamped>(m_rsforceName[i], 10);
    }
    zmp_pub = nh.advertise<geometry_msgs::PointStamped>("/zmp", 10);

    return RTC::RTC_OK;
}
void HrpsysSeqStateROSBridge::onJointTrajectory(trajectory_msgs::JointTrajectory trajectory) {
    m_mutex.lock();

    ROS_INFO_STREAM("[" << getInstanceName() << "] @onJointTrajectoryAction ");
    //std::cerr << goal->trajectory.joint_names.size() << std::endl;

    OpenHRP::dSequenceSequence angles;
    OpenHRP::dSequence duration;

    angles.length(trajectory.points.size()) ;
    duration.length(trajectory.points.size()) ;

    std::vector<std::string> joint_names = trajectory.joint_names;

    for (unsigned int i=0; i < trajectory.points.size(); i++) {
        angles[i].length(body->joints().size());

        trajectory_msgs::JointTrajectoryPoint point = trajectory.points[i];
        for (unsigned int j=0; j < trajectory.joint_names.size(); j++ ) {
            body->link(joint_names[j])->q = point.positions[j];
        }

        body->calcForwardKinematics();

        int j = 0;
        std::vector<hrp::Link*>::const_iterator it = body->joints().begin();
        while ( it != body->joints().end() ) {
            hrp::Link* l = ((hrp::Link*)*it);
            angles[i][j] = l->q;
            ++it;
            ++j;
        }

        ROS_INFO_STREAM("[" << getInstanceName() << "] @onJointTrajectoryAction : time_from_start " << trajectory.points[i].time_from_start.toSec());
        if ( i > 0 ) {
            duration[i] =  trajectory.points[i].time_from_start.toSec() - trajectory.points[i-1].time_from_start.toSec();
        } else { // if i == 0
            if ( trajectory.points.size()== 1 ) {
                duration[i] = trajectory.points[i].time_from_start.toSec();
            } else { // 0.2 is magic number writtein in roseus/euslisp/robot-interface.l
                duration[i] = trajectory.points[i].time_from_start.toSec() - 0.2;
            }
        }
    }

    m_mutex.unlock();

    if ( duration.length() == 1 ) {
        m_service0->setJointAngles(angles[0], duration[0]);
    } else {
        OpenHRP::dSequenceSequence rpy, zmp;
        m_service0->playPattern(angles, rpy, zmp, duration);
    }

    interpolationp = true;
}
Beispiel #4
0
std::string Light::getInstanceBlock() {
    std::string block = "";
    const std::string& typeName = getTypeName();
    if (m_dynamic) {
        //  If is dynamic, define the uniform and copy it to the global instance of the light struct
        block += "uniform " + typeName + " " + getUniformName() + ";\n";
        block += typeName + " " + getInstanceName() + ";\n";
    } else {
        //  If is not dynamic define the global instance of the light struct and fill the variables
        block += typeName + " " + getInstanceName() + getInstanceAssignBlock() +";\n";
    }
    return block;
}
EnPlayer::~EnPlayer()
{
    log_debug << "destroying player entity '"  << getInstanceName() << "', time: " << yaf3d::getTimeStamp() << std::endl;
    
    if ( _p_playerImpl )
        delete _p_playerImpl;
}
Beispiel #6
0
    bool IoWebhook::save(Image & image, JSON & data)
    {
        // ---------------------------------------
        // Attach additional fields to JSON object
        
        JSON dataCopy;
        JSON::AllocatorType& allocator = dataCopy.GetAllocator();
        dataCopy.CopyFrom(data, allocator);
        
        JSONValue instanceName;
        instanceName.SetString(getInstanceName().c_str(), allocator);
        dataCopy.AddMember("instanceName", instanceName, allocator);
        
        // -----------------------------
        // Convert JSON object to string
        
        rapidjson::StringBuffer buffer;
        rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);
        dataCopy.Accept(writer);
        
        // -------------------
        // Send a post to URL

        BINFO << "IoWebhook: post to webhook " + (std::string) getUrl();
        RestClient::response r = RestClient::post(getUrl(), "application/json", buffer.GetString());
        
        if(r.code == 200)
        {
            return true;
        }
        
        return false;
    }
bool ParameterReflection::addEvent(std::string const& name, std::string const& expression)
{
    if (hasParameter(name))
    {
        CONTROLIT_ERROR << "Parameter " << name << " already exists in " << getInstanceName();
        return false;
    }

    Event event;
    event.name = name;
    event.condition.SetExpr(expression);
    event.condition.SetVarFactory(VariableFactory<ParameterReflection>, this);
    event.condition.DefineNameChars("0123456789_."
                         "abcdefghijklmnopqrstuvwxyz"
                         "ABCDEFGHIJKLMNOPQRSTUVWXYZ");
    event.enabled = true;
    events.push_back(event);

    // Record event as a new parameter
    addParameter(name, new double(0.0));

    PRINT_INFO("Added event '" << name << "', expression '" << expression << "'");

    return true;
}
RTC::ReturnCode_t TransformROSBridge::onInitialize()
{
    // Registration: InPort/OutPort/Service
    // <rtc-template block="registration">
    // Set InPort buffers
    addInPort("TformIn", m_TformIn);

    // Set OutPort buffer

    // Set service provider to Ports

    // Set service consumers to Ports

    // Set CORBA Service Ports

    // </rtc-template>

    // <rtc-template block="bind_config">
    // Bind variables and configuration variable

    // </rtc-template>
    odom_pub = nh.advertise<nav_msgs::Odometry>("odom", 10);

    if(ros::param::has("~rate")) {
        double rate;
        ros::param::get("~rate", rate);
        if(rate != 0) {
            pub_cycle_ = 1/rate;
        }
    }
    if(ros::param::has("~initial_relative")) {
        ros::param::get("~initial_relative", initial_relative_);
    }
    if(ros::param::has("~publish_odom")) {
        ros::param::get("~publish_odom", publish_odom_);
    }
    if(ros::param::has("~publish_tf")) {
        ros::param::get("~publish_tf", publish_tf_);
    }
    if(ros::param::has("~invert_tf")) {
        ros::param::get("~invert_tf", invert_tf_);
    }
    if(ros::param::has("~tf_frame")) {
        ros::param::get("~tf_frame", tf_frame_);
    }
    if(ros::param::has("~tf_parent_frame")) {
        ros::param::get("~tf_parent_frame", tf_parent_frame_);
    }

    init_trans_.setOrigin(tf::Vector3(0, 0, 0));
    init_trans_.setRotation(tf::Quaternion(0, 0, 0, 1));
    prev_trans_.setOrigin(tf::Vector3(0, 0, 0));
    prev_trans_.setRotation(tf::Quaternion(0, 0, 0, 1));

    // initialize
    ROS_INFO_STREAM("[TransformROSBridge] @Initilize name : " << getInstanceName());

    return RTC::RTC_OK;
}
RTC::ReturnCode_t HrpsysJointTrajectoryBridge::onInitialize()
{
  m_SequencePlayerServicePort.registerConsumer("service0", "SequencePlayerService", m_service0);

  addPort(m_SequencePlayerServicePort);

  RTC::Properties& prop = getProperties();

  body = hrp::BodyPtr(new hrp::Body());

  RTC::Manager& rtcManager = RTC::Manager::instance();
  std::string nameServer = rtcManager.getConfig()["corba.nameservers"];
  int comPos = nameServer.find(",");
  if (comPos < 0)
  {
    comPos = nameServer.length();
  }
  nameServer = nameServer.substr(0, comPos);
  RTC::CorbaNaming naming(rtcManager.getORB(), nameServer.c_str());
  std::string modelfile = m_pManager->getConfig()["model"];

  if (!loadBodyFromModelLoader(body, modelfile.c_str(), CosNaming::NamingContext::_duplicate(naming.getRootContext())))
  {
    std::cerr << "[HrpsysJointTrajectoryBridge] failed to load model[" << prop["model"] << "]" << std::endl;
  }
  bool ret = false;
  while (!ret)
  {
    try
    {
      bodyinfo = hrp::loadBodyInfo(modelfile.c_str(), CosNaming::NamingContext::_duplicate(naming.getRootContext()));
      ret = loadBodyFromBodyInfo(body, bodyinfo);
    }
    catch (CORBA::SystemException& ex)
    {
      std::cerr << "[HrpsysJointTrajectoryBridge] loadBodyInfo(): CORBA::SystemException " << ex._name() << std::endl;
      sleep(1);
    }
    catch (...)
    {
      std::cerr << "[HrpsysJointTrajectoryBridge] loadBodyInfo(): failed to load model[" << modelfile << "]"
          << std::endl;
      ;
      sleep(1);
    }
  }

  if (body == NULL)
  {
    return RTC::RTC_ERROR;
  }
  body->calcForwardKinematics();

  ROS_INFO_STREAM("[HrpsysJointTrajectoryBridge] @Initilize name : " << getInstanceName() << " done");

  return RTC::RTC_OK;
}
void EnPlayerAnimation::initialize()
{
    log_info << "  initializing player animation instance '" << getInstanceName() << "' ..." << std::endl;

    if ( !_animCfgFile.length() )
    {
        log_error << "*** missing animation config file parameter" << std::endl;
        return;
    }
    
    // setup and create a new model
    std::string file     = yaf3d::Application::get()->getMediaPath() + _animCfgFile;
    std::string rootDir  = yaf3d::extractPath( file );
    std::string configfilename = yaf3d::extractFileName( file );
    // all textures and cal3d files must be in root dir!
    if ( !setupAnimation( rootDir, configfilename ) )
        return;

    // set initial animation
    _model->startLoop( _IdAnimIdle, 1.0f, 0.0f );
    _anim = eIdle;

    // scale the model
    _coreModel->get()->scale( _scale );

    // create a transform node in order to set position and rotation offsets
    _animNode = new osg::PositionAttitudeTransform;
    _animNode->setPosition( _position );
    osg::Quat quat( 
        _rotation.x() * osg::PI / 180.0f, osg::Vec3f( 1, 0, 0 ),
        _rotation.y() * osg::PI / 180.0f, osg::Vec3f( 0, 1, 0 ),
        _rotation.z() * osg::PI / 180.0f, osg::Vec3f( 0, 0, 1 )
        );
    _animNode->setAttitude( quat );
    _animNode->addChild( _model.get() );

    // setup the shaders for ( currently just disable glsl usage )
        
    // first check if glsl is supported before setting up the shaders ( gl context 0  is assumed )
    const osg::GL2Extensions* p_extensions = osg::GL2Extensions::Get( 0, true );
    if ( p_extensions->isGlslSupported() ) 
    {
        if ( !s_program.valid() )
        {
            s_program = new osg::Program;
            s_program->setName( "_playerAnim_" );
            s_program->addShader( new osg::Shader( osg::Shader::VERTEX, glsl_vp ) );
            s_program->addShader( new osg::Shader( osg::Shader::FRAGMENT, glsl_fp ) );
        }
        osg::StateSet* p_stateSet = _animNode->getOrCreateStateSet();
        p_stateSet->setAttributeAndModes( s_program.get(), osg::StateAttribute::ON );
        _animNode->setStateSet( p_stateSet );    
    }

    log << "  initializing player animation instance completed" << std::endl;
}
Beispiel #11
0
    std::string IoDisk::buildPath(std::string pathToImage)
    {
        // -----------------------------------------------
        // Get timestamp, microseconds, random token, and instance name
        
        std::string instanceName = getInstanceName();
        kerberos::helper::replace(pathToImage, "instanceName", instanceName);

        return pathToImage;
    }
RTC::ReturnCode_t HrpsysSeqStateROSBridge::onFinalize() {
    ROS_INFO_STREAM("[HrpsysSeqStateROSBridge] @onFinalize : " << getInstanceName());
    if ( joint_trajectory_server.isActive() ) {
        joint_trajectory_server.setPreempted();
    }

    if (   follow_joint_trajectory_server.isActive() ) {
        follow_joint_trajectory_server.setPreempted();
    }

    return RTC_OK;
}
Beispiel #13
0
	void fprint(FILE *out) {
		for (int i=0;i<getNumInstances();i++) {
			fprintf(out,"%13s\t%10.2f\t%10.2f\t%5.2f\t%5.2f\t%5.2f\t%7.2f\t%7.2f\t%7.2f\n"
				,getInstanceName(i)
				,getDoubleField(i,SOLUTIONS_RLT)
				,getDoubleField(i,SOLUTIONS_OPT)
				,getDoubleField(i,SOLUTIONS_V1GAP)
				,getDoubleField(i,SOLUTIONS_V2GAP)
				,getDoubleField(i,SOLUTIONS_V3GAP)
				,getDoubleField(i,SOLUTIONS_V1TIME)
				,getDoubleField(i,SOLUTIONS_V2TIME)
				,getDoubleField(i,SOLUTIONS_V3TIME));
		}
	}
Beispiel #14
0
void Light::injectSourceBlocks(ShaderProgram& _shader) {

    // Inject all needed #defines for this light instance
    _shader.addSourceBlock("defines", getInstanceDefinesBlock(), false);

    if (m_dynamic) {
        // If the light is dynamic, initialize it using the corresponding uniform at the start of main()
        _shader.addSourceBlock("setup", getInstanceName() + " = " + getUniformName() + ";", false);
    }

    _shader.addSourceBlock("__lighting", getClassBlock(), false);
    _shader.addSourceBlock("__lighting", getInstanceBlock());
    _shader.addSourceBlock("__lights_to_compute", getInstanceComputeBlock());
}
En3DSound::~En3DSound()
{
    // release sound
    if ( _soundID > 0 )
    {
        try
        {
            yaf3d::SoundManager::get()->releaseSound( _soundID );
        }
        catch ( const yaf3d::SoundException& e )
        {
            log_error << ENTITY_NAME_3DSOUND << ":" << getInstanceName() << " problem releasing sound, reason: " << e.what() << std::endl;
        }
    }
}
bool HrpsysSeqStateROSBridge::sendMsg (dynamic_reconfigure::Reconfigure::Request &req,
                                       dynamic_reconfigure::Reconfigure::Response &res)
{
    if ( req.config.strs.size() == 2 ) {
        res.config.strs = req.config.strs;
        ROS_INFO_STREAM("[" << getInstanceName() << "] @sendMsg [" << req.config.strs[0].value << "]");
        if (req.config.strs[0].value == "setInterpolationMode") {
            ROS_INFO_STREAM("[" << getInstanceName() << "] @sendMsg [" << req.config.strs[1].value  << "]");
            if ( req.config.strs[1].value == ":linear" ) {
                ROS_DEBUG("set interpolation mode -> :linear");
                m_service0->setInterpolationMode(OpenHRP::SequencePlayerService::LINEAR);
            } else {
                ROS_DEBUG("set interpolation mode -> :hoffarbib");
                m_service0->setInterpolationMode(OpenHRP::SequencePlayerService::HOFFARBIB);
            }
        } else if (req.config.strs[0].value == "setJointAngles") {
            std::istringstream iss(req.config.strs[1].value);
            OpenHRP::dSequence js;
            js.length(body->joints().size());
            double duration;
            for (size_t ii = 0; ii < body->joints().size(); ii++) iss >> js[ii];
            iss >> duration;
            m_service0->setJointAngles(js, duration);
        } else if (req.config.strs[0].value == "waitInterpolation") {
Beispiel #17
0
static
int startUDPClient(void* instance)
{
	UDPClientComponent* i = (UDPClientComponent*)instance;
	KevContext* ctx = getContext(i);
	printf("Hey instance of udp client %s\n", getInstanceName(ctx));

	/* setting parameters based on the dictionary or, as in this case, using constant values */
	i->remotePort = UDP_PORT;
	i->interval = 10000; // 10 seconds as interval

	free(ctx);

	process_start(&udp_component_kev, instance);
	return 0;
}
Beispiel #18
0
void ExeTask::cbackBy_Timerfunc(PVOID param, bool timerOrWaitFired)
{

  	QueryPerformanceFrequency(&liFrequency);  // retrieves the frequency of the high-resolution performance counter    
	QueryPerformanceCounter(&liCounter1);         // Start
	litemp = (double)(liCounter1.QuadPart - liCounter0.QuadPart) / (double)liFrequency.QuadPart;
	liCounter0 = liCounter1;

	if(m_stop){
		SetEvent(m_DoneEvent);
		//m_running = false; //이건 RThread에게 있는 멤버 데이터
		return;
	}
		
	try{
		if(m_runner->isDebugMode() && !m_isDbgCondCreated){
			//디버깅인데 cond가 아직 생성이 안되면 아무것도 안한다.
		}
		else{
			m_runner->enterTask(this, m_task);
			if(isCompleted()) {
				SetEvent(m_DoneEvent);
				return;
			}
		}
	}
	catch(RuntimeEH& runEH){
		//runEH.printError();
		FLOG_ERROR(m_logFile, "  (RUNNING:%d) 값을 획득하는데 실패하였습니다.", runEH.getErrorCode());
		//return runEH.getErrorCode();
	}

	FLOG_TRACE(m_logFile, "  (RUNNING:CYCLE) This is the end of a cycle.\n");
	m_iterCount++;			

	QueryPerformanceCounter(&liCounter2);
	PeRecord rec;
	rec.name = getInstanceName();
	rec.cycle = litemp;
	rec.proc = (double)(liCounter2.QuadPart - liCounter1.QuadPart) / (double)liFrequency.QuadPart;
	PerformTable::addPeRecord(rec);

	//printf("<%s> Cycle Time : %f, Process Time : %f\n", getInstanceName().c_str(), litemp, (double)(liCounter2.QuadPart - liCounter1.QuadPart) / (double)liFrequency.QuadPart);
	
}
RTC::ReturnCode_t JointStateROSBridge::onInitialize()
{
  // Registration: InPort/OutPort/Service
  // <rtc-template block="registration">
  // Set InPort buffers
  addInPort("qRef", m_angleIn);

  // Set OutPort buffer

  // Set service provider to Ports

  // Set service consumers to Ports

  // Set CORBA Service Ports

  // </rtc-template>

  // <rtc-template block="bind_config">
  // Bind variables and configuration variable

  // </rtc-template>
  jstate_pub = node.advertise<sensor_msgs::JointState>("joint_states", 1);

  if(ros::param::has("~names")) {
    //std::vector<std::string> name_list;
    ros::param::get("~names", joint_name_list);

    ROS_INFO_STREAM("[JointStateROSBridge] @Initilize joint_name_list :");
    for(int i = 0; i < joint_name_list.size(); i++) {
      ROS_INFO_STREAM(i << " : " << joint_name_list[i]);
    }
  }

  if(ros::param::has("~rate")) {
    double rate;
    ros::param::get("~rate", rate);
    if(rate != 0) {
      pub_cycle = 1/rate;
    }
  }
  // initialize
  ROS_INFO_STREAM("[JointStateROSBridge] @Initilize name : " << getInstanceName());

  return RTC::RTC_OK;
}
unsigned int EnPlayerSound::createSound( const std::string& filename )
{
    unsigned int soundID = 0;
    try
    {
        // player sounds are all FX sounds
        unsigned int soundgroup = yaf3d::SoundManager::get()->getSoundGroupIdFromString( "FX" );
        float volume = std::max( std::min( _volume, 1.0f ), 0.0f );
        soundID      = yaf3d::SoundManager::get()->createSound( soundgroup, filename, volume, false, yaf3d::SoundManager::fmodDefaultCreationFlags3D );
    }
    catch ( const yaf3d::SoundException& e )
    {
        log_error << ENTITY_NAME_PLSOUND << ":" << getInstanceName() << "  error loading sound file " << filename << std::endl;
        log_error << "  reason: " << e.what() << std::endl;
        return 0;
    }

    return soundID;
}
Beispiel #21
0
    std::string IoDisk::buildPath(std::string pathToImage)
    {
        // -----------------------------------------------
        // Get timestamp, microseconds, random token, and instance name
        
        std::string instanceName = getInstanceName();
        kerberos::helper::replace(pathToImage, "instanceName", instanceName);
        
        std::string timestamp = kerberos::helper::getTimestamp();
        kerberos::helper::replace(pathToImage, "timestamp", timestamp);

        std::string microseconds = kerberos::helper::getMicroseconds();
        std::string size = kerberos::helper::to_string((int)microseconds.length());
        kerberos::helper::replace(pathToImage, "microseconds", size + "-" + microseconds);
        
        std::string token = kerberos::helper::to_string(rand()%1000);
        kerberos::helper::replace(pathToImage, "token", token);

        return pathToImage;
    }
void EnMesh::initialize()
{
    _mesh = setupMesh();

    getTransformationNode()->setName( getInstanceName() );

    // is dynamic shadows enabled in the configuration?
    yaf3d::Configuration::get()->getSettingValue( YAF3D_GS_SHADOW_ENABLE, _cgfShadow );

    // is dynamic shadow for this mesh desired?
    _shadowEnable = ( _throwShadow || _receiveShadow ) && _cgfShadow;

    if ( _mesh.valid() )
        addToTransformationNode( _mesh.get() );

    // the node is added and removed by notification callback!
    yaf3d::EntityManager::get()->removeFromScene( this );

    // register entity in order to get menu notifications
    yaf3d::EntityManager::get()->registerNotification( this, true );
}
EnPlayer::EnPlayer() :
_gameMode( yaf3d::GameState::get()->getMode() ),
_p_playerImpl( NULL ),
_networkID( -1 ),
_voiceChatEnabled( false ),
_deltaTime( 0.03f )
{
    log_debug << "creating player entity"  << getInstanceName() << ", time: " << yaf3d::getTimeStamp() << std::endl;

    // assign some defaults
    _attributeContainer._chatGuiConfig = "gui/chat.xml";
    _attributeContainer._rot = 0;

    getAttributeManager().addAttribute( "physicsentity"             , _attributeContainer._physicsEntity        );
    getAttributeManager().addAttribute( "animationentity"           , _attributeContainer._animationEntity      );
    getAttributeManager().addAttribute( "soundentity"               , _attributeContainer._soundEntity          );
    getAttributeManager().addAttribute( "position"                  , _attributeContainer._pos                  );
    getAttributeManager().addAttribute( "rotation"                  , _attributeContainer._rot                  );
    getAttributeManager().addAttribute( "cameraPosOffsetSpheric"    , _attributeContainer._camPosOffsetSpheric  );
    getAttributeManager().addAttribute( "cameraRotOffsetSpheric"    , _attributeContainer._camRotOffsetSpheric  );
    getAttributeManager().addAttribute( "cameraPosOffsetEgo"        , _attributeContainer._camPosOffsetEgo      );
    getAttributeManager().addAttribute( "cameraRotOffsetEgo"        , _attributeContainer._camRotOffsetEgo      );
    getAttributeManager().addAttribute( "chatGuiConfig"             , _attributeContainer._chatGuiConfig        );
}
osg::Node* EnMesh::setupMesh()
{
    osg::Node* p_node;

    // don't cache the mesh if lod is used
    if ( _useLOD )
        p_node = yaf3d::LevelManager::get()->loadMesh( _meshFile, false );
    else
        p_node = yaf3d::LevelManager::get()->loadMesh( _meshFile, true );

    if ( !p_node )
    {
        log_error << "EnMesh: could not load mesh file: " << _meshFile << ", in '" << getInstanceName() << "'" << std::endl;
        return NULL;
    }

    setPosition( _position );
    osg::Quat   rot(
                     osg::DegreesToRadians( _rotation.x() ), osg::Vec3f( 1.0f, 0.0f, 0.0f ),
                     osg::DegreesToRadians( _rotation.y() ), osg::Vec3f( 0.0f, 1.0f, 0.0f ),
                     osg::DegreesToRadians( _rotation.z() ), osg::Vec3f( 0.0f, 0.0f, 1.0f )
                    );
    setRotation( rot );
    setScale( _scale );

    // store the original position and rotation for animation in relative mode
    _orgPostition = _position;
    _orgRotation  = rot;

    // invalidate a previously loaded animation
    if ( _animPath.valid() )
        _animPath = NULL;

    // is an animation file defined?
    if ( _animFile.length() )
    {
        osg::Node* p_animnode = yaf3d::LevelManager::get()->loadMesh( _animFile, true );
        if ( !p_animnode )
        {
            log_warning << "EnMesh: invalid animation mesh file (only osg and ive file formats are accepted)" << _animFile << std::endl;

            // remove update registration, it is needed only for animation
            if ( yaf3d::EntityManager::get()->isRegisteredUpdate( this ) )
                yaf3d::EntityManager::get()->registerUpdate( this, false );
        }
        else
        {
            osg::AnimationPath* p_path   = NULL;
            osg::Group*         p_topgrp = dynamic_cast< osg::Group* >( p_animnode );

            // find the animation callback in loaded mesh
            FindAnimPathVisitor v;
            v.apply( *p_topgrp );
            p_path = v.getAnimPath();
            // any animation path found?
            if ( p_path )
            {
                _animPath = p_path;
                // if a valid animation is defined then we need the update function
                yaf3d::EntityManager::get()->registerUpdate( this, true );

                // reset animation time
                _animTime = 0.0f;
            }
        }
    }

#ifndef DONT_USE_GLOD
    if ( _useLOD )
        p_node = setupLODObject( p_node );
#endif

    return p_node;
}
Beispiel #25
0
void ExeTask::cbackBy_Thrfunc()
{
	bool isWin = false;
	m_iterCount = 0;
	m_running = true;
	m_joining = false;
	setCompleted(false);
	if(m_task != NULL){

		std::string performFile = getNodeName();
		if(TaskConfig::isloggingTimePeriod()) {
			PerformTable::init();			
		}
		#ifdef _WIN32	
		isWin = true;
		QueryPerformanceCounter(&liCounter0);  
		#else
		struct timespec tp0, tp1, tp2;
		double litemp;
		clock_gettime(CLOCK_MONOTONIC, &tp0);
		#endif

		if(isWin && TaskConfig::isUsingQueueTimer()){
			this->start_que(m_TimerQueue, getNodeName());
			if(TaskConfig::isloggingTimePeriod()) performFile.append("-Timer");	
		}
		else{
			//2. run
			while(1){
				
				#ifdef _WIN32	
				QueryPerformanceFrequency(&liFrequency);  // retrieves the frequency of the high-resolution performance counter    
				QueryPerformanceCounter(&liCounter1);         // Start
				litemp = (double)(liCounter1.QuadPart - liCounter0.QuadPart) / (double)liFrequency.QuadPart;
				liCounter0 = liCounter1;
				#else
				clock_gettime(CLOCK_MONOTONIC, &tp1);
				litemp = ((double)(tp1.tv_sec*1000) + (double)(tp1.tv_nsec)/1000000)-((double)(tp0.tv_sec*1000) + (double)(tp0.tv_nsec)/1000000);
				tp0.tv_sec = tp1.tv_sec;
				tp0.tv_nsec = tp1.tv_nsec;
				#endif

				if(m_stop){  //외부로 부터 쓰레드 중지 명령			
					break;
				}
					
				try{
					if(m_runner->isDebugMode() && !m_isDbgCondCreated){
						//디버깅인데 cond가 아직 생성이 안되면 아무것도 안한다.
					}
					else{
						m_runner->enterTask(this, m_task);
						if(isCompleted()) break;
					}
				}
				catch(RuntimeEH& runEH){
					//runEH.printError();
					FLOG_ERROR(m_logFile, "  (RUNNING:%d) 값을 획득하는데 실패하였습니다.", runEH.getErrorCode());
					//return runEH.getErrorCode();
				}
			
				FLOG_TRACE(m_logFile, "  (RUNNING:CYCLE) This is the end of a cycle.\n");
				m_iterCount++;	

				#ifdef _WIN32			
				QueryPerformanceCounter(&liCounter2);
				PeRecord rec;
				rec.name = getInstanceName();
				rec.cycle = litemp;
				rec.proc = (double)(liCounter2.QuadPart - liCounter1.QuadPart) / (double)liFrequency.QuadPart;				
				//printf("<%s> Cycle Time : %f, Process Time : %f\n", getInstanceName().c_str(), litemp, (double)(liCounter2.QuadPart - liCounter1.QuadPart) / (double)liFrequency.QuadPart);
				#else
				clock_gettime(CLOCK_MONOTONIC, &tp2);
				PeRecord rec;
				rec.name = getInstanceName();
				rec.cycle = litemp;
				rec.proc = ((double)(tp2.tv_sec*1000) + (double)(tp2.tv_nsec)/1000000)-((double)(tp1.tv_sec*1000) + (double)(tp1.tv_nsec)/1000000);				
				#endif

				if(TaskConfig::isloggingTimePeriod()){
					PerformTable::addPeRecord(rec);
				}
				
				float sleeptime = m_timePeriod - rec.proc*1000;
				if(sleeptime<0) sleeptime = 0;
				thread_sleep(sleeptime);
			
				//timespec a;
				//a.tv_sec = 0;
				//a.tv_nsec = 5000000 - rec.proc * 1000000;
				//nanosleep(&a, NULL);
				
			}
			if(TaskConfig::isloggingTimePeriod()) performFile.append("-Thread");	
		}
		m_runner->enterDestruct(this);
		m_running = false;
		
		if(TaskConfig::isloggingTimePeriod()) PerformTable::makeFile(performFile);
	}
	
	if(m_runner->isDebugMode()||m_runner->isMonitorMode()){
		m_runner->delCondMu4BP(getThreadNum());
		m_isDbgCondCreated = false;
		this->sendThreadInfo("delete"); //Task 쓰레드 delete가 전송되면 종료임을 알 수 있다.
		this->sendMonitorMsg("RES-EOT");
		DbgTable::clearTable();
	}
}
void En3DSound::setupSound()
{
    // check if sound is enabled in menu system
    bool skiptypecheck = false;
    unsigned int soundgroup = yaf3d::SoundManager::get()->getSoundGroupIdFromString( _soundGroup );
    bool sndenable;
    std::string settingskey;
    if ( soundgroup == yaf3d::SoundManager::SoundGroupMusic )
        settingskey = VRC_GS_MUSIC_ENABLE;
    else if ( soundgroup == yaf3d::SoundManager::SoundGroupFX )
        settingskey = VRC_GS_FX_ENABLE;
    else if ( soundgroup == yaf3d::SoundManager::SoundGroupCommon )
        skiptypecheck = true;
    else
        log_error << ENTITY_NAME_3DSOUND << ":" << getInstanceName() << " invalid sound group type" << std::endl;

    if ( !skiptypecheck )
    {
        yaf3d::Configuration::get()->getSettingValue( settingskey, sndenable );
        if ( _soundID > 0 )
        {
            // destroy sound if it exists but even disabled in menu
            if ( !sndenable )
            {
                try
                {
                    yaf3d::SoundManager::get()->releaseSound( _soundID );
                    _soundID = 0;
                }
                catch ( const yaf3d::SoundException& e )
                {
                    log_error << ENTITY_NAME_3DSOUND << ":" << getInstanceName() << " problem releasing sound, reason: " << e.what() << std::endl;
                }
                return;
            }
            else return;
        }
        // no sound exists and no sound enabling in menu? then we have nothing to do
        else if ( !sndenable )
            return;
    }
    else if ( _soundID > 0 )
        return;

    try 
    {
        unsigned int flags = 0;
        if ( _loop )
            flags = yaf3d::SoundManager::fmodDefaultCreationFlags3DLoop;
        else
            flags = yaf3d::SoundManager::fmodDefaultCreationFlags3D;

        _soundID    = yaf3d::SoundManager::get()->createSound( soundgroup, _soundFile, _volume, _autoPlay, flags );
        _p_channel  = yaf3d::SoundManager::get()->getSoundResource( _soundID )->getChannel();

        setVolume( _volume );

        // set position and velocity
        FMOD_VECTOR pos;
        pos.x = _position.x();
        pos.y = _position.y();
        pos.z = _position.z();
        _p_channel->set3DAttributes( &pos, NULL );
        _p_channel->set3DMinMaxDistance( _minDistance, _maxDistance );
    } 
    catch ( const yaf3d::SoundException& e )
    {
        log_error << ENTITY_NAME_3DSOUND << ":" << getInstanceName() << "  error loading sound file " << _soundFile << std::endl;
        log_error << "  reason: " << e.what() << std::endl;
    }

    // this is for debugging
    if ( _sourceMesh.length() )
    {
        osg::Node* p_mesh = yaf3d::LevelManager::get()->loadMesh( _sourceMesh );
        if ( p_mesh )
        {
            addToTransformationNode( p_mesh );
            setPosition( _position );
        }
        else
        {
            log_error << "3DSound: error loading mesh file for sound source: " << _sourceMesh << std::endl;
        }
    }
}
void En2DSound::setupSound()
{
    // check for ambient sound
    if ( !_ambient )
    {
        if ( _minDistance > _maxDistance )
        {
            log_warning << ENTITY_NAME_2DSOUND << ": min distance > max distance for a non-ambient sound, fallback to ambient sound!" << std::endl;
            _ambient = true;
        }
    }

    // check if sound is enabled in menu system
    bool skiptypecheck      = false;
    unsigned int soundgroup = yaf3d::SoundManager::get()->getSoundGroupIdFromString( _soundGroup );
    bool sndenable          = false;
    std::string settingskey;

    if ( soundgroup == yaf3d::SoundManager::SoundGroupMusic )
        settingskey = VRC_GS_MUSIC_ENABLE;
    else if ( soundgroup == yaf3d::SoundManager::SoundGroupFX )
        settingskey = VRC_GS_FX_ENABLE;
    else if ( soundgroup == yaf3d::SoundManager::SoundGroupCommon )
        skiptypecheck = true;
    else
        log_error << ENTITY_NAME_2DSOUND << ":" << getInstanceName() << " invalid sound group type" << std::endl;


    // sound group Common is always created
    if ( !skiptypecheck )
    {
        yaf3d::Configuration::get()->getSettingValue( settingskey, sndenable );
        if ( _soundID > 0 )
        {
            // destroy sound if it exists but even disabled in menu
            if ( !sndenable )
            {
                try
                {
                    yaf3d::SoundManager::get()->releaseSound( _soundID );
                    _soundID = 0;
                }
                catch ( const yaf3d::SoundException& e )
                {
                    log_error << ENTITY_NAME_2DSOUND << ":" << getInstanceName() << " problem releasing sound, reason: " << e.what() << std::endl;
                }
                return;
            }
            else return;
        }
        // no sound exists and no sound enabling in menu? then we have nothing to do
        else if ( !sndenable )
            return;
    }
    else if ( _soundID > 0 )
        return;

    try
    {
        unsigned int flags = 0;
        if ( _loop )
            flags = yaf3d::SoundManager::fmodDefaultCreationFlags2DLoop;
        else
            flags = yaf3d::SoundManager::fmodDefaultCreationFlags2D;

        _soundID    = yaf3d::SoundManager::get()->createSound( soundgroup, _soundFile, _volume, _autoPlay, flags );
        _p_channel  = yaf3d::SoundManager::get()->getSoundResource( _soundID )->getChannel();
    }
    catch ( const yaf3d::SoundException& e )
    {
        log_error << ENTITY_NAME_2DSOUND << ":" << getInstanceName() << "  error loading sound file " << _soundFile << std::endl;
        log_error << "  reason: " << e.what() << std::endl;
    }

    // re-add the debug mesh if one exists
    if ( getTransformationNode()->getNumChildren() )
    {
        // first remove the current mesh
        osg::Node* p_currmesh = getTransformationNode()->getChild( 0 );
        if ( p_currmesh )
            removeFromTransformationNode( p_currmesh );
    }
    if ( _sourceMesh.length() )
    {
        osg::Node* p_mesh = yaf3d::LevelManager::get()->loadMesh( _sourceMesh );
        if ( p_mesh )
        {
            addToTransformationNode( p_mesh );
            setPosition( _position );
        }
        else
        {
            log_warning << "2DSound: error loading mesh file for sound source: " << _sourceMesh << std::endl;
        }
    }

    // if the sound is ambient then we need no update
    if ( !_ambient && _soundID )
    {
        if ( !yaf3d::EntityManager::get()->isRegisteredUpdate( this ) )
            yaf3d::EntityManager::get()->registerUpdate( this, true );
    }
}
Beispiel #28
0
std::string Light::getInstanceComputeBlock() {
    return  "calculateLight(" + getInstanceName() + ", _eyeToPoint, _normal);\n";
}
bool ParameterReflection::emitEvents()
{
    bool st = true;

    for (auto& event : events)
    {
        // Manually tie event evaluation to the parameter thats tracking it. Obvious thing
        // to do here is go back and refactor this code so that Events ARE Parameters..
        Parameter* param = lookupParameter(event.name);
        if (param == NULL)
        {
            CONTROLIT_PR_ERROR << "This should not have happened. Couldn't find event " << event.name << " in parameter list.";
            st = false;
            continue;
        }

        std::string eventName = getInstanceName() + ReflectionRegistry::ParameterNameDelimiter + event.name;

        // Evaluate condition and update parameter
        double val;
        try
        {
            val = event.condition.Eval();
        }
        catch (mu::Parser::exception_type const& e)
        {
            CONTROLIT_PR_ERROR
                << "Expression eval failed: " << e.GetMsg() << "\n"
                << "-- Formula:  " << e.GetExpr() << "\n"
                << "-- Token:    " << e.GetToken() << "\n"
                << "-- Position: " << e.GetPos() << "\n"
                << "-- Errc:     " << e.GetCode();
            st = false;
            continue;
        }

        param->set(val);
        if (val > 0.5)
        {
            if (event.enabled) // event fire-once semantics
            {
                notifyListeners(eventName);
                PRINT_INFO("Firing event '" << event.name << "' (expression: " << event.condition.GetExpr() << " == true)");
                event.enabled = false; // event fire-once semantics
            }
            else
            {
                PRINT_INFO("Supressing event '" << event.name << "' (expression: " << event.condition.GetExpr() << " == true).");
            }
        }
        else
        {
            if (!event.enabled)
            {
                PRINT_INFO("Resetting event '" << event.name << "' (expression: " << event.condition.GetExpr() << " == false).");
                event.enabled = true;  // event fire-once semantics
            }
        }
    }
    return st;
}
void EnMesh::addToSceneGraph()
{
    if ( !_mesh.valid() )
        return;

    // is a shader name given?
    osg::Group* p_shadernode = NULL;
    if ( _shaderName.length() )
    {
        // try to get the shader node and append our node to it
        p_shadernode = yaf3d::ShaderContainer::get()->getShaderNode( _shaderName ).get();
        if ( !p_shadernode )
        {
            log_error << "EnMesh: invalid shader name: " << _shaderName << " in mesh instance " << getInstanceName() << std::endl;
        }
    }

    // enable shadow only if it is enabled in configuration
    if ( _shadowEnable )
    {
        // set the shadow mode
        unsigned int shadowmode = 0;
        if ( _throwShadow )
            shadowmode |= yaf3d::ShadowManager::eThrowShadow;
        if ( _receiveShadow )
            shadowmode |= yaf3d::ShadowManager::eReceiveShadow;

        // first remove it for the case that this method is called on modification of entity attributes
        yaf3d::ShadowManager::get()->removeShadowNode( p_shadernode ? p_shadernode : getTransformationNode() );
        yaf3d::ShadowManager::get()->addShadowNode( p_shadernode ? p_shadernode : getTransformationNode(), shadowmode, _shadowCullDist );

        // the mesh needs at least one subgraph for getting rendered; the shadow throwing subgraph does not render the mesh (but only its shadow)
        // so we put meshes which should throw shadow and not receive shadow to the default scene node.
        if ( !_receiveShadow && !p_shadernode )
            yaf3d::EntityManager::get()->addToScene( this );
    }
    else if ( !p_shadernode ) // add to scene only if the mesh has no shader
    {
        yaf3d::EntityManager::get()->addToScene( this );
    }

    // if the node has a shader append it also to the shader node
    if ( p_shadernode )
    {
        // if not already added then add it now ( this method is called on every modification of entity attributes! )
        if ( !p_shadernode->containsNode( getTransformationNode() ) )
            p_shadernode->addChild( getTransformationNode() );
    }
}