Beispiel #1
0
void MeshResourceMarker::onNewMessage(const MarkerConstPtr& old_message, const MarkerConstPtr& new_message)
{
  ROS_ASSERT(new_message->type == visualization_msgs::Marker::MESH_RESOURCE);

  // flag indicating if the mesh material color needs to be updated
  bool update_color = false;

  scene_node_->setVisible(false);

  if (!entity_ ||
      old_message->mesh_resource != new_message->mesh_resource ||
      old_message->mesh_use_embedded_materials != new_message->mesh_use_embedded_materials)
  {
    reset();

    if (new_message->mesh_resource.empty())
    {
      return;
    }

    if (loadMeshFromResource(new_message->mesh_resource).isNull())
    {
      std::stringstream ss;
      ss << "Mesh resource marker [" << getStringID() << "] could not load [" << new_message->mesh_resource << "]";
      if (owner_)
      {
        owner_->setMarkerStatus(getID(), StatusProperty::Error, ss.str());
      }
      ROS_DEBUG("%s", ss.str().c_str());
      return;
    }

    static uint32_t count = 0;
    std::stringstream ss;
    ss << "mesh_resource_marker_" << count++;
    std::string id = ss.str();
    entity_ = context_->getSceneManager()->createEntity(id, new_message->mesh_resource);
    scene_node_->attachObject(entity_);

    // create a default material for any sub-entities which don't have their own.
    ss << "Material";
    Ogre::MaterialPtr default_material = Ogre::MaterialManager::getSingleton().create(ss.str(), ROS_PACKAGE_NAME);
    default_material->setReceiveShadows(false);
    default_material->getTechnique(0)->setLightingEnabled(true);
    default_material->getTechnique(0)->setAmbient(0.5, 0.5, 0.5);
    materials_.insert(default_material);

    if (new_message->mesh_use_embedded_materials)
    {
      // make clones of all embedded materials so selection works correctly
      S_MaterialPtr materials = getMaterials();

      S_MaterialPtr::iterator it;
      for (it = materials.begin(); it != materials.end(); it++)
      {
        if ((*it)->getName() != "BaseWhiteNoLighting")
        {
          Ogre::MaterialPtr new_material = (*it)->clone(id + (*it)->getName());
          materials_.insert(new_material);
        }
      }

      // make sub-entities use cloned materials
      for (uint32_t i = 0; i < entity_->getNumSubEntities(); ++i)
      {
        std::string mat_name = entity_->getSubEntity(i)->getMaterialName();
        if (mat_name != "BaseWhiteNoLighting")
        {
          entity_->getSubEntity(i)->setMaterialName(id + mat_name);
        }
        else
        {
          // BaseWhiteNoLighting is the default material Ogre uses
          // when it sees a mesh with no material.  Here we replace
          // that with our default_material which gets colored with
          // new_message->color.
          entity_->getSubEntity(i)->setMaterial(default_material);
        }
      }
    }
    else
    {
      entity_->setMaterial(default_material);
    }

    // add a pass to every material to perform the color tinting
    S_MaterialPtr::iterator material_it;
    for (material_it = materials_.begin(); material_it != materials_.end(); material_it++)
    {
      Ogre::Technique* technique = (*material_it)->getTechnique(0);
      color_tint_passes_.push_back(technique->createPass());
    }

    // always update color on resource change
    update_color = true;

    handler_.reset(new MarkerSelectionHandler(this, MarkerID(new_message->ns, new_message->id), context_));
    handler_->addTrackedObject(entity_);
  }
  else
  {
    // underlying mesh resource has not changed but if the color has
    //  then we need to update the materials color
    if (!old_message
        || old_message->color.r != new_message->color.r
        || old_message->color.g != new_message->color.g
        || old_message->color.b != new_message->color.b
        || old_message->color.a != new_message->color.a)
    {
      update_color = true;
    }
  }

  // update material color
  //  if the mesh_use_embedded_materials is true and color is non-zero
  //  then the color will be used to tint the embedded materials
  if (update_color)
  {
    float r = new_message->color.r;
    float g = new_message->color.g;
    float b = new_message->color.b;
    float a = new_message->color.a;

    Ogre::SceneBlendType blending;
    bool depth_write;

    if (a < 0.9998)
    {
      blending = Ogre::SBT_TRANSPARENT_ALPHA;
      depth_write = false;
    }
    else
    {
      blending = Ogre::SBT_REPLACE;
      depth_write = true;
    }

    for (std::vector<Ogre::Pass*>::iterator it = color_tint_passes_.begin();
         it != color_tint_passes_.end();
         ++it)
    {
      (*it)->setAmbient(0.5 * r, 0.5 * g, 0.5 * b);
      (*it)->setDiffuse(r, g, b, a);
      (*it)->setSceneBlending(blending);
      (*it)->setDepthWriteEnabled(depth_write);
      (*it)->setLightingEnabled(true);
    }
  }

  Ogre::Vector3 pos, scale;
  Ogre::Quaternion orient;
  transform(new_message, pos, orient, scale);

  scene_node_->setVisible(true);
  setPosition(pos);
  setOrientation(orient);

  scene_node_->setScale(scale);
}
Beispiel #2
0
void GameState::BuildSkeleton()
{
	CEGUI::Editbox* heightbox = static_cast<CEGUI::Editbox*>(mGUIRoot->getChild("Settings Box/Skeleton Height/HeightEdit"));
	CEGUI::Editbox* widthbox = static_cast<CEGUI::Editbox*>(mGUIRoot->getChild("Settings Box/Skeleton Width/WidthEditBox"));
	CEGUI::Editbox* depthbox = static_cast<CEGUI::Editbox*>(mGUIRoot->getChild("Settings Box/Skeleton Depth/DepthEditBox"));
	CEGUI::Editbox* neckbox = static_cast<CEGUI::Editbox*>(mGUIRoot->getChild("Settings Box/Neck Incline/NeckEditbox"));
	CEGUI::Editbox* tailbox = static_cast<CEGUI::Editbox*>(mGUIRoot->getChild("Settings Box/Tail Incline/TailEditbox"));
	CEGUI::Editbox* Xbox = static_cast<CEGUI::Editbox*>(mGUIRoot->getChild("Settings Box/Spawn Position/X Editbox"));
	CEGUI::Editbox* Ybox = static_cast<CEGUI::Editbox*>(mGUIRoot->getChild("Settings Box/Spawn Position/Y Editbox"));
	CEGUI::Editbox* Zbox = static_cast<CEGUI::Editbox*>(mGUIRoot->getChild("Settings Box/Spawn Position/Z Editbox"));
	Skeleton_Builder::TorsoType Torso;
	Skeleton_Builder::ArmType Arm;
	Skeleton_Builder::LegType Leg;
	Skeleton_Builder::NeckType Neck;
	Skeleton_Builder::TailType Tail;
	auto legitem = static_cast<CEGUI::Combobox*>(mGUIRoot->getChild("Settings Box/Leg Combobox"))->getSelectedItem();
	auto torsoitem = static_cast<CEGUI::Combobox*>(mGUIRoot->getChild("Settings Box/Torso Combobox"))->getSelectedItem();
	auto armitem = static_cast<CEGUI::Combobox*>(mGUIRoot->getChild("Settings Box/Arm Combobox"))->getSelectedItem();
	auto tailitem = static_cast<CEGUI::Combobox*>(mGUIRoot->getChild("Settings Box/Tail Combobox"))->getSelectedItem();
	auto neckitem = static_cast<CEGUI::Combobox*>(mGUIRoot->getChild("Settings Box/Neck Combobox"))->getSelectedItem();

	if (legitem->getID() == 0)
		Leg = Skeleton_Builder::LegType::Uninverted;
	else
		Leg = Skeleton_Builder::LegType::Inverted;

	if (torsoitem->getID() == 0)
		Torso = Skeleton_Builder::TorsoType::Upright;
	else
		Torso = Skeleton_Builder::TorsoType::Horizontal;

	if (armitem->getID() == 0)
		Arm = Skeleton_Builder::ArmType::NoArms;
	else if (armitem->getID() == 1)
		Arm = Skeleton_Builder::ArmType::ShortArms;
	else
		Arm = Skeleton_Builder::ArmType::LongArms;

	if (tailitem->getID() == 0)
		Tail = Skeleton_Builder::TailType::NoTail;
	else if (tailitem->getID() == 1)
		Tail = Skeleton_Builder::TailType::ShortTail;
	else
		Tail = Skeleton_Builder::TailType::LongTail;

	if (neckitem->getID() == 1)
		Neck = Skeleton_Builder::NeckType::ShortNeck;
	else if (neckitem->getID() == 0)
		Neck = Skeleton_Builder::NeckType::LongNeck;

	auto Position = Ogre::Vector3(std::stof(Xbox->getText().c_str()), std::stof(Ybox->getText().c_str()), std::stof(Zbox->getText().c_str()));
	mPhysics->BuildCharacter(Torso, Arm, Leg,Neck,Tail,
		std::stof(heightbox->getText().c_str()),
		std::stof(widthbox->getText().c_str()),
		std::stof(depthbox->getText().c_str()),
		std::stof(neckbox->getText().c_str()),
		std::stof(tailbox->getText().c_str()),
		static_cast<CEGUI::ToggleButton*>(mGUIRoot->getChild("Settings Box/Hide Arm/Checkbox"))->isSelected(),
		static_cast<CEGUI::ToggleButton*>(mGUIRoot->getChild("Settings Box/Hide Leg/Checkbox"))->isSelected(),
		static_cast<CEGUI::ToggleButton*>(mGUIRoot->getChild("Settings Box/Hide Neck/Checkbox"))->isSelected(),
		static_cast<CEGUI::ToggleButton*>(mGUIRoot->getChild("Settings Box/Has Muscles/Checkbox"))->isSelected(),
		static_cast<CEGUI::ToggleButton*>(mGUIRoot->getChild("Settings Box/Is Fixed/Checkbox"))->isSelected(),
		Position);
}
Beispiel #3
0
void
MSRightOfWayJunction::postloadInit() {
    // inform links where they have to report approaching vehicles to
    int requestPos = 0;
    std::vector<MSLane*>::iterator i;
    // going through the incoming lanes...
    int maxNo = 0;
    std::vector<std::pair<MSLane*, MSLink*> > sortedLinks;
    for (i = myIncomingLanes.begin(); i != myIncomingLanes.end(); ++i) {
        const MSLinkCont& links = (*i)->getLinkCont();
        // ... set information for every link
        for (MSLinkCont::const_iterator j = links.begin(); j != links.end(); j++) {
            if ((*j)->getLane()->getEdge().isWalkingArea() ||
                    ((*i)->getEdge().isWalkingArea() && !(*j)->getLane()->getEdge().isCrossing())) {
                continue;
            }
            sortedLinks.push_back(std::make_pair(*i, *j));
            ++maxNo;
        }
    }

    const bool hasFoes = myLogic->hasFoes();
    for (i = myIncomingLanes.begin(); i != myIncomingLanes.end(); ++i) {
        const MSLinkCont& links = (*i)->getLinkCont();
        // ... set information for every link
        const MSLane* walkingAreaFoe = nullptr;
        for (MSLinkCont::const_iterator j = links.begin(); j != links.end(); j++) {
            if ((*j)->getLane()->getEdge().isWalkingArea()) {
                if ((*i)->getPermissions() != SVC_PEDESTRIAN) {
                    // vehicular lane connects to a walkingarea
                    walkingAreaFoe = (*j)->getLane();
                }
                continue;
            } else if (((*i)->getEdge().isWalkingArea() && !(*j)->getLane()->getEdge().isCrossing())) {
                continue;
            }
            if (myLogic->getLogicSize() <= requestPos) {
                throw ProcessError("Found invalid logic position of a link for junction '" + getID() + "' (" + toString(requestPos) + ", max " + toString(myLogic->getLogicSize()) + ") -> (network error)");
            }
            const MSLogicJunction::LinkBits& linkResponse = myLogic->getResponseFor(requestPos); // SUMO_ATTR_RESPONSE
            const MSLogicJunction::LinkBits& linkFoes = myLogic->getFoesFor(requestPos); // SUMO_ATTR_FOES
            bool cont = myLogic->getIsCont(requestPos);
            myLinkFoeLinks[*j] = std::vector<MSLink*>();
            for (int c = 0; c < maxNo; ++c) {
                if (linkResponse.test(c)) {
                    MSLink* foe = sortedLinks[c].second;
                    myLinkFoeLinks[*j].push_back(foe);
                    if (MSGlobals::gUsingInternalLanes && foe->getViaLane() != nullptr) {
                        assert(foe->getViaLane()->getLinkCont().size() == 1);
                        MSLink* foeExitLink = foe->getViaLane()->getLinkCont()[0];
                        // add foe links after an internal junction
                        if (foeExitLink->getViaLane() != nullptr) {
                            myLinkFoeLinks[*j].push_back(foeExitLink);
                        }
                    }
                }
            }
            std::vector<MSLink*> foes;
            for (int c = 0; c < maxNo; ++c) {
                if (linkFoes.test(c)) {
                    MSLink* foe = sortedLinks[c].second;
                    foes.push_back(foe);
                    MSLane* l = foe->getViaLane();
                    if (l == nullptr) {
                        continue;
                    }
                    // add foe links after an internal junction
                    const MSLinkCont& lc = l->getLinkCont();
                    for (MSLinkCont::const_iterator q = lc.begin(); q != lc.end(); ++q) {
                        if ((*q)->getViaLane() != nullptr) {
                            foes.push_back(*q);
                        }
                    }
                }
            }

            myLinkFoeInternalLanes[*j] = std::vector<MSLane*>();
            if (MSGlobals::gUsingInternalLanes && myInternalLanes.size() > 0) {
                int li = 0;
                for (int c = 0; c < (int)sortedLinks.size(); ++c) {
                    if (sortedLinks[c].second->getLane() == nullptr) { // dead end
                        continue;
                    }
                    if (linkFoes.test(c)) {
                        myLinkFoeInternalLanes[*j].push_back(myInternalLanes[li]);
                        if (linkResponse.test(c)) {
                            const std::vector<MSLane::IncomingLaneInfo>& l = myInternalLanes[li]->getIncomingLanes();
                            if (l.size() == 1 && l[0].lane->getEdge().isInternal()) {
                                myLinkFoeInternalLanes[*j].push_back(l[0].lane);
                            }
                        }
                    }
                    ++li;
                }
            }
            (*j)->setRequestInformation((int)requestPos, hasFoes, cont, myLinkFoeLinks[*j], myLinkFoeInternalLanes[*j]);
            // the exit link for a link before an internal junction is handled in MSInternalJunction
            // so we need to skip if cont=true
            if (MSGlobals::gUsingInternalLanes && (*j)->getViaLane() != nullptr && !cont) {
                assert((*j)->getViaLane()->getLinkCont().size() == 1);
                MSLink* exitLink = (*j)->getViaLane()->getLinkCont()[0];
                exitLink->setRequestInformation((int)requestPos, false, false, std::vector<MSLink*>(),
                                                myLinkFoeInternalLanes[*j], (*j)->getViaLane());
                for (const auto& ili : exitLink->getLane()->getIncomingLanes()) {
                    if (ili.lane->getEdge().isWalkingArea()) {
                        exitLink->addWalkingAreaFoeExit(ili.lane);
                        break;
                    }
                }
            }
            // the exit link for a crossing is needed for the pedestrian model
            if (MSGlobals::gUsingInternalLanes && (*j)->getLane()->getEdge().isCrossing()) {
                MSLink* exitLink = (*j)->getLane()->getLinkCont()[0];
                exitLink->setRequestInformation((int)requestPos, false, false, std::vector<MSLink*>(),
                                                myLinkFoeInternalLanes[*j], (*j)->getLane());
            }
            for (std::vector<MSLink*>::const_iterator k = foes.begin(); k != foes.end(); ++k) {
                (*j)->addBlockedLink(*k);
                (*k)->addBlockedLink(*j);
            }
            requestPos++;
        }
        if (walkingAreaFoe != nullptr && links.size() > 1) {
            for (MSLinkCont::const_iterator j = links.begin(); j != links.end(); j++) {
                if (!(*j)->getLane()->getEdge().isWalkingArea()) {
                    MSLink* exitLink = (*j)->getViaLane()->getLinkCont()[0];
                    exitLink->addWalkingAreaFoe(walkingAreaFoe);
                }
            }
        }
    }
}
Beispiel #4
0
bool
RODFDetector::writeEmitterDefinition(const std::string& file,
                                     const std::map<size_t, RandomDistributor<size_t>* > &dists,
                                     const RODFDetectorFlows& flows,
                                     SUMOTime startTime, SUMOTime endTime,
                                     SUMOTime stepOffset,
                                     bool includeUnusedRoutes,
                                     SUMOReal scale,
                                     bool insertionsOnly,
                                     SUMOReal defaultSpeed) const {
    OutputDevice& out = OutputDevice::getDevice(file);
    if (getType() != SOURCE_DETECTOR) {
        out.writeXMLHeader("calibrator");
    }
    // routes
    if (myRoutes != 0 && myRoutes->get().size() != 0) {
        const std::vector<RODFRouteDesc> &routes = myRoutes->get();
        out.openTag("routeDistribution") <<  " id=\"" << myID << "\">\n";
        bool isEmptyDist = true;
        for (std::vector<RODFRouteDesc>::const_iterator i = routes.begin(); i != routes.end(); ++i) {
            if ((*i).overallProb > 0) {
                isEmptyDist = false;
            }
        }
        for (std::vector<RODFRouteDesc>::const_iterator i = routes.begin(); i != routes.end(); ++i) {
            if ((*i).overallProb > 0 || includeUnusedRoutes) {
                out.openTag("route") << " refId=\"" << (*i).routename << "\" probability=\"" << (*i).overallProb << "\"";
                out.closeTag(true);
            }
            if (isEmptyDist) {
                out.openTag("route") << " refId=\"" << (*i).routename << "\" probability=\"1\"";
                out.closeTag(true);
            }
        }
        out.closeTag();
    } else {
        WRITE_ERROR("Detector '" + getID() + "' has no routes!?");
        return false;
    }
    // emissions
    if (insertionsOnly || flows.knows(myID)) {
        // get the flows for this detector

        const std::vector<FlowDef> &mflows = flows.getFlowDefs(myID);
        // go through the simulation seconds
        int index = 0;
        for (SUMOTime time = startTime; time < endTime; time += stepOffset, index++) {
            // get own (departure flow)
            assert(index < mflows.size());
            const FlowDef& srcFD = mflows[index];  // !!! check stepOffset
            // get flows at end
            RandomDistributor<size_t> *destDist = dists.find(time) != dists.end() ? dists.find(time)->second : 0;
            // go through the cars
            size_t carNo = (size_t)((srcFD.qPKW + srcFD.qLKW) * scale);
            for (size_t car = 0; car < carNo; ++car) {
                // get the vehicle parameter
                std::string type = "test";
                SUMOReal v = -1;
                int destIndex = destDist != 0 && destDist->getOverallProb() > 0 ? (int) destDist->get() : -1;
                if (srcFD.isLKW >= 1) {
                    srcFD.isLKW = srcFD.isLKW - (SUMOReal) 1.;
//!!!		        	type = lkwTypes[vehSpeedDist.get()];
                    v = srcFD.vLKW;
                } else {
//!!!	    			type = pkwTypes[vehSpeedDist.get()];
                    v = srcFD.vPKW;
                }
                // compute emission speed
                if (v < 0 || v > 250) {
                    v = defaultSpeed;
                } else {
                    v = (SUMOReal)(v / 3.6);
                }
                // compute the departure time
                SUMOTime ctime = (SUMOTime)(time + ((SUMOReal) stepOffset * (SUMOReal) car / (SUMOReal) carNo));

                // write
                out.openTag("vehicle") << " id=\"";
                if (getType() == SOURCE_DETECTOR) {
                    out << "emitter_" << myID;
                } else {
                    out << "calibrator_" << myID;
                }
                out << "_" << ctime  << "\"" // !!! running
                    << " depart=\"" << time2string(ctime) << "\""
                    << " departSpeed=\"";
                if (v > defaultSpeed) {
                    out << "max";
                } else {
                    out << v;
                }
                out << "\" departPos=\"" << myPosition << "\""
                    << " departLane=\"" << myLaneID.substr(myLaneID.rfind("_") + 1) << "\" route=\"";
                if (destIndex >= 0) {
                    out << myRoutes->get()[destIndex].routename << "\"";
                } else {
                    out << myID << "\"";
                }
                out.closeTag(true);
                srcFD.isLKW += srcFD.fLKW;
            }
        }
    }
    if (getType() != SOURCE_DETECTOR) {
        out.close();
    }
    return true;
}
/*
 * Class:     guidoengine_guidodate
 * Method:    Init
 * Signature: ()V
 */
JNIEXPORT void JNICALL Java_guidoengine_guidodate_Init (JNIEnv * env, jclass cls)
{
	getID (env, cls, gDateNumID, "fNum", "I");
	getID (env, cls, gDateDenumID, "fDenum", "I");
}
Beispiel #6
0
OctreeElement::AppendState EntityItem::appendEntityData(OctreePacketData* packetData, EncodeBitstreamParams& params, 
                                            EntityTreeElementExtraEncodeData* entityTreeElementExtraEncodeData) const {
                                            
    // ALL this fits...
    //    object ID [16 bytes]
    //    ByteCountCoded(type code) [~1 byte]
    //    last edited [8 bytes]
    //    ByteCountCoded(last_edited to last_updated delta) [~1-8 bytes]
    //    PropertyFlags<>( everything ) [1-2 bytes]
    // ~27-35 bytes...
    
    OctreeElement::AppendState appendState = OctreeElement::COMPLETED; // assume the best

    // encode our ID as a byte count coded byte stream
    QByteArray encodedID = getID().toRfc4122();

    // encode our type as a byte count coded byte stream
    ByteCountCoded<quint32> typeCoder = getType();
    QByteArray encodedType = typeCoder;

    quint64 updateDelta = getLastUpdated() <= getLastEdited() ? 0 : getLastUpdated() - getLastEdited();
    ByteCountCoded<quint64> updateDeltaCoder = updateDelta;
    QByteArray encodedUpdateDelta = updateDeltaCoder;
    EntityPropertyFlags propertyFlags(PROP_LAST_ITEM);
    EntityPropertyFlags requestedProperties = getEntityProperties(params);
    EntityPropertyFlags propertiesDidntFit = requestedProperties;

    // If we are being called for a subsequent pass at appendEntityData() that failed to completely encode this item,
    // then our entityTreeElementExtraEncodeData should include data about which properties we need to append.
    if (entityTreeElementExtraEncodeData && entityTreeElementExtraEncodeData->entities.contains(getEntityItemID())) {
        requestedProperties = entityTreeElementExtraEncodeData->entities.value(getEntityItemID());
    }

    LevelDetails entityLevel = packetData->startLevel();

    quint64 lastEdited = getLastEdited();

    const bool wantDebug = false;
    if (wantDebug) {
        float editedAgo = getEditedAgo();
        QString agoAsString = formatSecondsElapsed(editedAgo);
        qDebug() << "Writing entity " << getEntityItemID() << " to buffer, lastEdited =" << lastEdited 
                        << " ago=" << editedAgo << "seconds - " << agoAsString;
    }

    bool successIDFits = false;
    bool successTypeFits = false;
    bool successCreatedFits = false;
    bool successLastEditedFits = false;
    bool successLastUpdatedFits = false;
    bool successPropertyFlagsFits = false;
    int propertyFlagsOffset = 0;
    int oldPropertyFlagsLength = 0;
    QByteArray encodedPropertyFlags;
    int propertyCount = 0;

    successIDFits = packetData->appendValue(encodedID);
    if (successIDFits) {
        successTypeFits = packetData->appendValue(encodedType);
    }
    if (successTypeFits) {
        successCreatedFits = packetData->appendValue(_created);
    }
    if (successCreatedFits) {
        successLastEditedFits = packetData->appendValue(lastEdited);
    }
    if (successLastEditedFits) {
        successLastUpdatedFits = packetData->appendValue(encodedUpdateDelta);
    }
    
    if (successLastUpdatedFits) {
        propertyFlagsOffset = packetData->getUncompressedByteOffset();
        encodedPropertyFlags = propertyFlags;
        oldPropertyFlagsLength = encodedPropertyFlags.length();
        successPropertyFlagsFits = packetData->appendValue(encodedPropertyFlags);
    }

    bool headerFits = successIDFits && successTypeFits && successCreatedFits && successLastEditedFits 
                              && successLastUpdatedFits && successPropertyFlagsFits;

    int startOfEntityItemData = packetData->getUncompressedByteOffset();

    if (headerFits) {
        bool successPropertyFits;

        propertyFlags -= PROP_LAST_ITEM; // clear the last item for now, we may or may not set it as the actual item

        // These items would go here once supported....
        //      PROP_PAGED_PROPERTY,
        //      PROP_CUSTOM_PROPERTIES_INCLUDED,

        APPEND_ENTITY_PROPERTY(PROP_POSITION, appendPosition, getPosition());
        APPEND_ENTITY_PROPERTY(PROP_DIMENSIONS, appendValue, getDimensions()); // NOTE: PROP_RADIUS obsolete

        if (wantDebug) {
            qDebug() << "    APPEND_ENTITY_PROPERTY() PROP_DIMENSIONS:" << getDimensions();
        }

        APPEND_ENTITY_PROPERTY(PROP_ROTATION, appendValue, getRotation());
        APPEND_ENTITY_PROPERTY(PROP_MASS, appendValue, getMass());
        APPEND_ENTITY_PROPERTY(PROP_VELOCITY, appendValue, getVelocity());
        APPEND_ENTITY_PROPERTY(PROP_GRAVITY, appendValue, getGravity());
        APPEND_ENTITY_PROPERTY(PROP_DAMPING, appendValue, getDamping());
        APPEND_ENTITY_PROPERTY(PROP_LIFETIME, appendValue, getLifetime());
        APPEND_ENTITY_PROPERTY(PROP_SCRIPT, appendValue, getScript());
        APPEND_ENTITY_PROPERTY(PROP_REGISTRATION_POINT, appendValue, getRegistrationPoint());
        APPEND_ENTITY_PROPERTY(PROP_ANGULAR_VELOCITY, appendValue, getAngularVelocity());
        APPEND_ENTITY_PROPERTY(PROP_ANGULAR_DAMPING, appendValue, getAngularDamping());
        APPEND_ENTITY_PROPERTY(PROP_VISIBLE, appendValue, getVisible());
        APPEND_ENTITY_PROPERTY(PROP_IGNORE_FOR_COLLISIONS, appendValue, getIgnoreForCollisions());
        APPEND_ENTITY_PROPERTY(PROP_COLLISIONS_WILL_MOVE, appendValue, getCollisionsWillMove());

        appendSubclassData(packetData, params, entityTreeElementExtraEncodeData,
                                requestedProperties,
                                propertyFlags,
                                propertiesDidntFit,
                                propertyCount,
                                appendState);
    }

    if (propertyCount > 0) {
        int endOfEntityItemData = packetData->getUncompressedByteOffset();
        encodedPropertyFlags = propertyFlags;
        int newPropertyFlagsLength = encodedPropertyFlags.length();
        packetData->updatePriorBytes(propertyFlagsOffset, 
                (const unsigned char*)encodedPropertyFlags.constData(), encodedPropertyFlags.length());
        
        // if the size of the PropertyFlags shrunk, we need to shift everything down to front of packet.
        if (newPropertyFlagsLength < oldPropertyFlagsLength) {
            int oldSize = packetData->getUncompressedSize();
            const unsigned char* modelItemData = packetData->getUncompressedData(propertyFlagsOffset + oldPropertyFlagsLength);
            int modelItemDataLength = endOfEntityItemData - startOfEntityItemData;
            int newEntityItemDataStart = propertyFlagsOffset + newPropertyFlagsLength;
            packetData->updatePriorBytes(newEntityItemDataStart, modelItemData, modelItemDataLength);
            int newSize = oldSize - (oldPropertyFlagsLength - newPropertyFlagsLength);
            packetData->setUncompressedSize(newSize);

        } else {
            assert(newPropertyFlagsLength == oldPropertyFlagsLength); // should not have grown
        }
       
        packetData->endLevel(entityLevel);
    } else {
        packetData->discardLevel(entityLevel);
        appendState = OctreeElement::NONE; // if we got here, then we didn't include the item
    }
    
    // If any part of the model items didn't fit, then the element is considered partial
    if (appendState != OctreeElement::COMPLETED) {
        // add this item into our list for the next appendElementData() pass
        entityTreeElementExtraEncodeData->entities.insert(getEntityItemID(), propertiesDidntFit);
    }

    return appendState;
}
Beispiel #7
0
char supla_client::register_client(TCS_SuplaRegisterClient_B *register_client_b,
                                   TCS_SuplaRegisterClient_C *register_client_c,
                                   unsigned char proto_version) {
  int resultcode = SUPLA_RESULTCODE_TEMPORARILY_UNAVAILABLE;
  char result = 0;

  char *GUID = NULL;
  char *AuthKey = NULL;
  char *Name = NULL;
  char *SoftVer = NULL;
  _supla_int_t AccessID = 0;

  if (register_client_b != NULL) {
    GUID = register_client_b->GUID;
    Name = register_client_b->Name;
    AccessID = register_client_b->AccessID;
    SoftVer = register_client_b->SoftVer;
  } else {
    GUID = register_client_c->GUID;
    Name = register_client_c->Name;
    AuthKey = register_client_c->AuthKey;
    SoftVer = register_client_c->SoftVer;
  }

  if (!setGUID(GUID)) {
    resultcode = SUPLA_RESULTCODE_GUID_ERROR;

  } else if (register_client_c != NULL &&
             !setAuthKey(register_client_c->AuthKey)) {
    resultcode = SUPLA_RESULTCODE_AUTHKEY_ERROR;

  } else if (register_client_b == NULL && register_client_c == NULL) {
    resultcode = SUPLA_RESULTCODE_UNSUPORTED;

  } else {
    database *db = new database();

    if (db->connect() == true) {
      int UserID = 0;
      bool accessid_enabled = false;

      if (register_client_b != NULL &&
          false ==
              db->accessid_auth(AccessID, register_client_b->AccessIDpwd,
                                &UserID, &accessid_enabled)) {
        resultcode = SUPLA_RESULTCODE_BAD_CREDENTIALS;

      } else if (register_client_c != NULL &&
                 false ==
                     db->client_authkey_auth(GUID, register_client_c->Email,
                                             register_client_c->AuthKey,
                                             &UserID)) {
        resultcode = SUPLA_RESULTCODE_BAD_CREDENTIALS;

      } else if (UserID == 0) {
        resultcode = SUPLA_RESULTCODE_BAD_CREDENTIALS;

      } else {
        _supla_int_t _AccessID = AccessID;

        bool client_enabled = true;
        bool do_update = true;
        bool _accessid_enabled = false;

        db->start_transaction();

        int ClientID =
            db->get_client(db->get_client_id(UserID, GUID), &client_enabled,
                           &_AccessID, &_accessid_enabled);

        if (_accessid_enabled) accessid_enabled = true;

        if (ClientID == 0) {
          do_update = false;

          if (false == db->get_client_reg_enabled(UserID)) {
            db->rollback();
            resultcode = SUPLA_RESULTCODE_REGISTRATION_DISABLED;

          } else if (db->get_client_limit_left(UserID) <= 0) {
            db->rollback();
            resultcode = SUPLA_RESULTCODE_CLIENT_LIMITEXCEEDED;

          } else {
            if (AccessID == 0 && register_client_c != NULL &&
                db->get_client_count(UserID) == 0) {
              AccessID = db->get_access_id(UserID, true);

              if (AccessID > 0) {
                accessid_enabled = true;
              } else {
                accessid_enabled = false;
                AccessID = db->get_access_id(UserID, false);
              }
            }

            ClientID = db->add_client(AccessID, GUID, AuthKey, Name,
                                      getSvrConn()->getClientIpv4(), SoftVer,
                                      proto_version, UserID);

            if (ClientID == 0) {
              // something goes wrong
              db->rollback();

            } else {
              client_enabled = true;
            }
          }

        } else if (_AccessID > 0 && register_client_c != NULL) {
          AccessID = _AccessID;
        }

        if (ClientID != 0) {
          if (!client_enabled) {
            db->rollback();
            resultcode = SUPLA_RESULTCODE_CLIENT_DISABLED;

          } else {
            if (do_update) {
              if (false ==
                  db->update_client(ClientID, AccessID, AuthKey, Name,
                                    getSvrConn()->getClientIpv4(), SoftVer,
                                    proto_version)) {
                // something goes wrong
                ClientID = 0;
                db->rollback();
              }
            }

            if (ClientID) {
              db->commit();

              if (AccessID == 0) {
                resultcode = SUPLA_RESULTCODE_ACCESSID_NOT_ASSIGNED;

              } else if (!accessid_enabled) {
                resultcode = SUPLA_RESULTCODE_ACCESSID_DISABLED;

              } else {
                setID(ClientID);
                setName(Name);

                loadConfig();

                resultcode = SUPLA_RESULTCODE_TRUE;
                result = 1;
                setUser(supla_user::add_client(this, UserID));
              }
            }
          }
        }
      }
    }

    delete db;
  }

  TSC_SuplaRegisterClientResult srcr;
  srcr.result_code = resultcode;
  srcr.ClientID = getID();
  srcr.activity_timeout = getSvrConn()->GetActivityTimeout();
  srcr.version_min = SUPLA_PROTO_VERSION;
  srcr.version = SUPLA_PROTO_VERSION;
  srcr.LocationCount = locations->count();
  srcr.ChannelCount = channels->count();
  srpc_sc_async_registerclient_result(getSvrConn()->srpc(), &srcr);

  // !After srpc_async_registerclient_result
  if (resultcode == SUPLA_RESULTCODE_TRUE) {
    remote_update_lists();
    supla_log(LOG_INFO, "Client registered. ClientSD: %i Protocol Version: %i",
              getSvrConn()->getClientSD(), getSvrConn()->getProtocolVersion());
  } else {
    usleep(2000000);
  }

  return result;
}
Beispiel #8
0
bool IExtensionsExtension::updateExtension(shared_ptr<Portal> portal, shared_ptr<IPortalDatabase> db, const Version &version)
{
	OS_ASSERT(portal != nullptr);

	//shared_ptr<IPortalDatabase> db = portal->getDatabase();
	OS_EXCEPT_IF(db == nullptr, "Invalid database");

	DbSqlValues values;
	values.set(DBTABLES::EXTENSIONS::VERSION, static_cast<String>(version.toString()));

	String sql = db->getConnection()->prepare_update(DBTABLES::EXTENSIONS_TABLE, values, DBTABLES::EXTENSIONS::ID, Convert::toSQL(getID().toUTF16()));
	return db->getConnection()->executeStatement(sql, values);
}
Beispiel #9
0
int main(void)
{
	int ID = 0; // ID associated with the person. starts at invalid value
	char email[100]; // email address of user
	char *roomSize; // Size of the desired room
	int month = 0; // month from 1-12. starts at invalid value
	int day = 0; // day from 1-31. starts at invalid value.
	int year = 0; // month from 2014 up. starts at invalid value.
	int useTime[2] = {-1, -1}; // start and end time in 24 hour format. starts at invalid value.
	int loggedIn = 0; // Whether the user has entered their ID, username
	bool sub = false; // wilingness to substitute
	char output[MAX_STRING*10]; // final output of the Request

	// Enter details to proceed
	printf("Please log in to proceed. Enter your 6 digit ID: ");
	while (loggedIn == 0) {
		ID = getID();
		buf[0] = '\0'; // reset buffer
		getEmail(email);
		buf[0] = '\0'; // reset buffer
		loggedIn = logIn();
		buf[0] = '\0'; // reset buffer
	} 
	
	// Get the year the user would like to book for.
	printf("Would you like to book for this calendar year? (Y/N): ");
	while (year == 0) {
	    year = getYear();
	    buf[0] = '\0'; // reset buffer
	}

	// Get the month the user would like to book for.
	printf("Would you like to book for this month in %i? (Y/N): ", year);
	while ((month < 1) || (month > 12)) {
	    month = getMonth(year);
	    buf[0] = '\0'; // reset buffer
	}

	// Get the day the user would like to book for. Dynamicly change valid days in getDay
	printf("What day would you like to book for? ");
	while (day == 0) {
	    day = getDay(month, year);
	    buf[0] = '\0'; // reset buffer
	}

	// Get the time the user will use the room.
	printf("What time would you like to start using the room? (24 hour): ");
	while (useTime[0] == -1) {
		getTime(useTime, day, month, year);
		buf[0] = '\0'; // reset buffer
	}

	// Get the room size the user would like to book
	printf("What is the size of the room you are looking to reserve? (\"small\", \"standard\", or \"very large\"): ");
    roomSize = getRoomSize();
    strcat (roomSize, "\0"); // add end of string character
    buf[0] = '\0'; // reset buffer

    printf("Would you be willing to take a larger room if there is no %s room available? (Y/N): ", roomSize);
    buf[0] = '\0'; // reset buffer
	fgets(buf, MAX_STRING, stdin);
	strcat (buf, "\0"); // add end of string character

	// willingness to substitute
	if ((buf[0] == 'y') || (buf[0] == 'Y')) {
		sub = true;
	}

	else {
		while ((buf[0] != 'n') || (buf[0] == 'N')) {
			printf("\nIncorrect input. Please answer with \'Y\' or \'N\': ");
			buf[0] = '\0'; // reset buffer
			fgets(buf, MAX_STRING, stdin);
			strcat (buf, "\0"); // add end of string character
		}
	}

	printf("\n\nBooking %i (%s) for a %s room on %i/%i/%i from %i to %i...", ID, email, roomSize, month, day, year, useTime[0], useTime[1]);
	sprintf(output, "%i,%i,%i,%i,%i,%s,%d,%i,%i,%s", month, day, year, useTime[0], useTime[1], roomSize, sub, ID, loggedIn, email);
	
	FILE *f = fopen("file.txt", "w");
	if (f == NULL)
	{
	  printf("Error opening file!\n");
	  exit(1);
	}
	
	// write to file where handler can process it
	fprintf(f, "%s\n", output);

	printf("Press enter to continue...\n");
	getchar();

	return 0;
}
void MeshResourceMarker::onNewMessage(const MarkerConstPtr& old_message, const MarkerConstPtr& new_message)
{
  ROS_ASSERT(new_message->type == visualization_msgs::Marker::MESH_RESOURCE);

  bool need_color = false;

  scene_node_->setVisible(false);

  if( !entity_ ||
      old_message->mesh_resource != new_message->mesh_resource ||
      old_message->mesh_use_embedded_materials != new_message->mesh_use_embedded_materials )
  {
    reset();

    if (new_message->mesh_resource.empty())
    {
      return;
    }

    if (loadMeshFromResource(new_message->mesh_resource).isNull())
    {
      std::stringstream ss;
      ss << "Mesh resource marker [" << getStringID() << "] could not load [" << new_message->mesh_resource << "]";
      if ( owner_ )
      {
        owner_->setMarkerStatus(getID(), StatusProperty::Error, ss.str());
      }
      ROS_DEBUG("%s", ss.str().c_str());
      return;
    }

    static uint32_t count = 0;
    std::stringstream ss;
    ss << "mesh_resource_marker_" << count++;
    std::string id = ss.str();
    entity_ = context_->getSceneManager()->createEntity(id, new_message->mesh_resource);
    scene_node_->attachObject(entity_);
    need_color = true;

    // create a default material for any sub-entities which don't have their own.
    ss << "Material";
    Ogre::MaterialPtr default_material = Ogre::MaterialManager::getSingleton().create( ss.str(), ROS_PACKAGE_NAME );
    default_material->setReceiveShadows(false);
    default_material->getTechnique(0)->setLightingEnabled(true);
    default_material->getTechnique(0)->setAmbient( 0.5, 0.5, 0.5 );
    materials_.insert( default_material );

    if ( new_message->mesh_use_embedded_materials )
    {
      // make clones of all embedded materials so selection works correctly
      S_MaterialPtr materials = getMaterials();

      S_MaterialPtr::iterator it;
      for ( it = materials.begin(); it!=materials.end(); it++ )
      {
        if( (*it)->getName() != "BaseWhiteNoLighting" )
        {
          Ogre::MaterialPtr new_material = (*it)->clone( id + (*it)->getName() );
          materials_.insert( new_material );
        }
      }

      // make sub-entities use cloned materials
      for (uint32_t i = 0; i < entity_->getNumSubEntities(); ++i)
      {
        std::string mat_name = entity_->getSubEntity(i)->getMaterialName();
        if( mat_name != "BaseWhiteNoLighting" )
        {
          entity_->getSubEntity(i)->setMaterialName( id + mat_name );
        }
        else
        {
          // BaseWhiteNoLighting is the default material Ogre uses
          // when it sees a mesh with no material.  Here we replace
          // that with our default_material which gets colored with
          // new_message->color.
          entity_->getSubEntity(i)->setMaterial( default_material );
        }
      }
    }
    else
    {
      entity_->setMaterial( default_material );
    }

    context_->getSelectionManager()->removeObject(coll_);
    coll_ = context_->getSelectionManager()->createCollisionForEntity(entity_, SelectionHandlerPtr(new MarkerSelectionHandler(this, MarkerID(new_message->ns, new_message->id))), coll_);
  }

  if( need_color ||
      old_message->color.r != new_message->color.r ||
      old_message->color.g != new_message->color.g ||
      old_message->color.b != new_message->color.b ||
      old_message->color.a != new_message->color.a )
  {
    float r = new_message->color.r;
    float g = new_message->color.g;
    float b = new_message->color.b;
    float a = new_message->color.a;

    // Old way was to ignore the color and alpha when using embedded
    // materials, which meant you could leave them unset, which means
    // 0.  Since we now USE the color and alpha values, leaving them
    // all 0 will mean the object will be invisible.  Therefore detect
    // the situation where RGBA are all 0 and treat that the same as
    // all 1 (full white).
    if( new_message->mesh_use_embedded_materials && r == 0 && g == 0 && b == 0 && a == 0 )
    {
      r = 1; g = 1; b = 1; a = 1;
    }

    Ogre::SceneBlendType blending;
    bool depth_write;

    if ( a < 0.9998 )
    {
      blending = Ogre::SBT_TRANSPARENT_ALPHA;
      depth_write = false;
    }
    else
    {
      blending = Ogre::SBT_REPLACE;
      depth_write = true;
    }

    S_MaterialPtr::iterator it;
    for( it = materials_.begin(); it != materials_.end(); it++ )
    {    
      Ogre::Technique* technique = (*it)->getTechnique( 0 );

      technique->setAmbient( r*0.5, g*0.5, b*0.5 );
      technique->setDiffuse( r, g, b, a );
      technique->setSceneBlending( blending );
      technique->setDepthWriteEnabled( depth_write );
    }
  }

  Ogre::Vector3 pos, scale;
  Ogre::Quaternion orient;
  transform(new_message, pos, orient, scale);

  scene_node_->setVisible(true);
  setPosition(pos);
  setOrientation(orient);

  // In Ogre, mesh surface normals are not normalized if object is not
  // scaled.  This forces the surface normals to be renormalized by
  // invisibly tweaking the scale.
  if( scale.x == 1.0 && scale.y == 1.0 && scale.z == 1.0 )
  {
    scale.z = 1.0001;
  }
  scene_node_->setScale(scale);
}
Beispiel #11
0
String IExtensionsExtension::getDataPath() const
{
	return utils::makeFolderPath(utils::makeFolderPath(Options::instance()->getDataPath(), OS_EXTENSIONS_EXTENSIONS_PATH), getID().toUTF16());
}
Beispiel #12
0
int Service::run()
{
  writeCommandFile();
  writeOptionsFile();

  logUser("Info: Starting daemon: '%s'", getID());

  #ifdef __CYGWIN32__
 
  if ((pid_ = waitFork()) != 0)

  #else

  if ((pid_ = fork()) != 0)

  #endif

  {
    if (pid_ < 0)
    {
      logUser("Error: Fork failed.");
    }
    else
    {
      #ifdef DEBUG
      logUser("Info: Created process with pid=%d", pid_);
      #endif
    }

    writePidFile();

    //
    // The parent waits for a signal or a log
    // to know if its child (the service) starts
    // successfully.
    //

    if (pid_ > 0)
    {
      checkServiceStart();
    }

    return pid_;
  }

  #ifdef DEBUG
  logUser("Info: Executing child with pid=%d and ppid=%d", getpid(), getppid());
  #endif

  if (execvp(executablePath_, (char *const *) arguments_) == -1)
  {
    logUser("Error: Cannot execute '%s'. Error: '%s'", executablePath_, strerror(errno));
    exit(-1);
  }

   /*
    * checkServiceStart() get rid of this.
    *
    exit(0);
    */

  //
  // just to shut up the compiler
  //
  return 0;
}
Beispiel #13
0
void Teleporter::createVisual(SceneManager* sceneManager)
{
    inTelNode=sceneManager->getRootSceneNode()->createChildSceneNode("in_teleporter_node"+Converter::intToString(getID()));
    outTelNode=sceneManager->getRootSceneNode()->createChildSceneNode("out_teleporter_node"+Converter::intToString(getID()));
    inTelEnt=sceneManager->createEntity("TeleporterIn.mesh");
    outTelEnt=sceneManager->createEntity("TeleporterOut.mesh");
    inTelNode->attachObject(inTelEnt);
    outTelNode->attachObject(outTelEnt);
    inTelNode->setPosition(inTelPos);
    outTelNode->setPosition(outTelPos);
    outTelNode->scale(20,20,20);
    inTelNode->scale(20,20,20);
    //inTelNode->translate(0,inTelEnt->getBoundingBox().getSize().y/2*20,0);
    outTelNode->translate(0,outTelEnt->getBoundingBox().getSize().y/2*20,0);


    teleportPointNode=sceneManager->getRootSceneNode()->createChildSceneNode("teleporter_node_blink"+Converter::intToString(getID()));
    teleportPointNode->scale(.2,.2,.2);
    teleportPointNode->setPosition(inTelNode->getPosition()+Ogre::Vector3(0,inTelEnt->getBoundingBox().getSize().y*14,0));

    bbLight=sceneManager->createLight();
    bbLight->setDiffuseColour(0,0,1);
    bbLight->setAttenuation(250, 1.0, 4.5/250, 75./Ogre::Math::Pow(250,2.));
    bbLight->setPosition(teleportPointNode->getPosition());

	inParticleSystem=sceneManager->createParticleSystem("teleporterin_particle"+Converter::intToString(getID()),"TeleporterIN_Particle");
	outParticleSystem=sceneManager->createParticleSystem("teleporterout_particle"+Converter::intToString(getID()),"teleporterOut_Particle");
	inParticleNode=sceneManager->getRootSceneNode()->createChildSceneNode();
	outParticleNode=sceneManager->getRootSceneNode()->createChildSceneNode();
	inParticleNode->attachObject(inParticleSystem);
	outParticleNode->attachObject(outParticleSystem);
	inParticleNode->scale(.05,.05,.05);
	outParticleNode->scale(.05,.05,.05);
	inParticleNode->setPosition(teleportPointNode->getPosition());
	outParticleNode->setPosition(outTelNode->getPosition()+Ogre::Vector3(0,25,0));
	inParticleSystem->setRenderQueueGroup(RENDER_QUEUE_6);
	outParticleSystem->setRenderQueueGroup(RENDER_QUEUE_6);


    inTelSoundID="in_tel_"+Converter::intToString(id);
    outTelSoundID="out_tel_"+Converter::intToString(id);
    SoundController::getSingleton()->attachDynamicSound(inTelNode,inTelSoundID,ConfigReader::getConfigFile("GameSettings")->getFieldValueAsString("GameSounds","teleport-in"),false);
    SoundController::getSingleton()->attachDynamicSound(outTelNode,outTelSoundID,ConfigReader::getConfigFile("GameSettings")->getFieldValueAsString("GameSounds","teleport-out"),false);
}
Beispiel #14
0
PostProcessTool::PostProcessTool(
    MeshLib::Mesh const& org_mesh,
    std::vector<std::vector<MeshLib::Node*>> const& vec_vec_fracture_nodes,
    std::vector<std::vector<MeshLib::Element*>> const&
        vec_vec_fracture_matrix_elements)
    : _org_mesh(org_mesh)
{
    if (!org_mesh.getProperties().hasPropertyVector("displacement") ||
        !org_mesh.getProperties().hasPropertyVector("displacement_jump1") ||
        !org_mesh.getProperties().hasPropertyVector("levelset1"))
    {
        OGS_FATAL("The given mesh does not have relevant properties");
    }

    // clone nodes and elements
    std::vector<MeshLib::Node*> new_nodes(
        MeshLib::copyNodeVector(org_mesh.getNodes()));
    std::vector<MeshLib::Element*> new_eles(
        MeshLib::copyElementVector(org_mesh.getElements(), new_nodes));

    // duplicate fracture nodes
    for (auto const& vec_fracture_nodes : vec_vec_fracture_nodes)
    {
        for (auto const* org_node : vec_fracture_nodes)
        {
            auto duplicated_node =
                new MeshLib::Node(org_node->getCoords(), new_nodes.size());
            new_nodes.push_back(duplicated_node);
            if (_map_dup_newNodeIDs.count(org_node->getID()) > 0)
                OGS_FATAL("Intersection of fractures is not supported");
            _map_dup_newNodeIDs[org_node->getID()] = duplicated_node->getID();
        }
    }

    // split elements using the new duplicated nodes
    for (unsigned fracture_id = 0;
         fracture_id < vec_vec_fracture_matrix_elements.size();
         fracture_id++)
    {
        auto const& vec_fracture_matrix_elements =
            vec_vec_fracture_matrix_elements[fracture_id];
        auto const& vec_fracture_nodes = vec_vec_fracture_nodes[fracture_id];
        auto prop_levelset = org_mesh.getProperties().getPropertyVector<double>(
            "levelset" + std::to_string(fracture_id + 1));
        for (auto const* org_e : vec_fracture_matrix_elements)
        {
            // only matrix elements
            if (org_e->getDimension() != org_mesh.getDimension())
                continue;

            auto const eid = org_e->getID();

            // keep original if the element has levelset=0
            if ((*prop_levelset)[eid] == 0)
                continue;

            // replace fracture nodes with duplicated ones
            MeshLib::Element* e = new_eles[eid];
            for (unsigned i = 0; i < e->getNumberOfNodes(); i++)
            {
                // only fracture nodes
                auto itr = _map_dup_newNodeIDs.find(e->getNodeIndex(i));
                if (itr == _map_dup_newNodeIDs.end())
                    continue;

                // check if a node belongs to the particular fracture group
                auto itr2 = std::find_if(
                    vec_fracture_nodes.begin(), vec_fracture_nodes.end(),
                    [&](MeshLib::Node const* node) {
                        return node->getID() == e->getNodeIndex(i);
                    });
                if (itr2 == vec_fracture_nodes.end())
                    continue;

                e->setNode(i, new_nodes[itr->second]);
            }
        }
    }

    // new mesh
    _output_mesh = std::make_unique<MeshLib::Mesh>(org_mesh.getName(),
                                                   new_nodes, new_eles);
    createProperties<int>();
    createProperties<double>();
    copyProperties<int>();
    copyProperties<double>();
    calculateTotalDisplacement(vec_vec_fracture_nodes.size());
}
bool RenderableWebEntityItem::buildWebSurface(EntityTreeRenderer* renderer) {
    if (_currentWebCount >= MAX_CONCURRENT_WEB_VIEWS) {
        qWarning() << "Too many concurrent web views to create new view";
        return false;
    }
    qDebug() << "Building web surface";

    ++_currentWebCount;
    // Save the original GL context, because creating a QML surface will create a new context
    QOpenGLContext * currentContext = QOpenGLContext::currentContext();
    QSurface * currentSurface = currentContext->surface();
    _webSurface = new OffscreenQmlSurface();
    _webSurface->create(currentContext);
    _webSurface->setBaseUrl(QUrl::fromLocalFile(PathUtils::resourcesPath() + "/qml/"));
    _webSurface->load("WebEntity.qml");
    _webSurface->resume();
    _webSurface->getRootItem()->setProperty("url", _sourceUrl);
    _connection = QObject::connect(_webSurface, &OffscreenQmlSurface::textureUpdated, [&](GLuint textureId) {
        _texture = textureId;
    });
    // Restore the original GL context
    currentContext->makeCurrent(currentSurface);

    auto forwardMouseEvent = [=](const RayToEntityIntersectionResult& intersection, const QMouseEvent* event) {
        // Ignore mouse interaction if we're locked
        if (this->getLocked()) {
            return;
        }

        if (event->button() == Qt::MouseButton::RightButton) {
            if (event->type() == QEvent::MouseButtonPress) {
                const QMouseEvent* mouseEvent = static_cast<const QMouseEvent*>(event);
                _lastPress = toGlm(mouseEvent->pos());
            }
        }

        if (intersection.entityID == getID()) {
            if (event->button() == Qt::MouseButton::RightButton) {
                if (event->type() == QEvent::MouseButtonRelease) {
                    const QMouseEvent* mouseEvent = static_cast<const QMouseEvent*>(event);
                    ivec2 dist = glm::abs(toGlm(mouseEvent->pos()) - _lastPress);
                    if (!glm::any(glm::greaterThan(dist, ivec2(1)))) {
                        AbstractViewStateInterface::instance()->postLambdaEvent([this] {
                            QMetaObject::invokeMethod(_webSurface->getRootItem(), "goBack");
                        });
                    }
                    _lastPress = ivec2(INT_MIN);
                }
                return;
            }

            // FIXME doesn't work... double click events not received
            if (event->type() == QEvent::MouseButtonDblClick) {
                AbstractViewStateInterface::instance()->postLambdaEvent([this] {
                    _webSurface->getRootItem()->setProperty("url", _sourceUrl);
                });
            }

            if (event->button() == Qt::MouseButton::MiddleButton) {
                if (event->type() == QEvent::MouseButtonRelease) {
                    AbstractViewStateInterface::instance()->postLambdaEvent([this] {
                        _webSurface->getRootItem()->setProperty("url", _sourceUrl);
                    });
                }
                return;
            }

            // Map the intersection point to an actual offscreen pixel
            glm::vec3 point = intersection.intersection;
            glm::vec3 dimensions = getDimensions();
            point -= getPosition();
            point = glm::inverse(getRotation()) * point;
            point /= dimensions;
            point += 0.5f;
            point.y = 1.0f - point.y;
            point *= dimensions * (METERS_TO_INCHES * DPI);

            if (event->button() == Qt::MouseButton::LeftButton) {
                if (event->type() == QEvent::MouseButtonPress) {
                    this->_pressed = true;
                    this->_lastMove = ivec2((int)point.x, (int)point.y);
                } else if (event->type() == QEvent::MouseButtonRelease) {
                    this->_pressed = false;
                }
            }
            if (event->type() == QEvent::MouseMove) {
                this->_lastMove = ivec2((int)point.x, (int)point.y);
            }

            // Forward the mouse event.  
            QMouseEvent mappedEvent(event->type(),
                QPoint((int)point.x, (int)point.y),
                event->screenPos(), event->button(),
                event->buttons(), event->modifiers());
            QCoreApplication::sendEvent(_webSurface->getWindow(), &mappedEvent);
        }
    };
    _mousePressConnection = QObject::connect(renderer, &EntityTreeRenderer::mousePressOnEntity, forwardMouseEvent);
    _mouseReleaseConnection = QObject::connect(renderer, &EntityTreeRenderer::mouseReleaseOnEntity, forwardMouseEvent);
    _mouseMoveConnection = QObject::connect(renderer, &EntityTreeRenderer::mouseMoveOnEntity, forwardMouseEvent);
    _hoverLeaveConnection = QObject::connect(renderer, &EntityTreeRenderer::hoverLeaveEntity, [=](const EntityItemID& entityItemID, const MouseEvent& event) {
        if (this->_pressed && this->getID() == entityItemID) {
            // If the user mouses off the entity while the button is down, simulate a mouse release
            QMouseEvent mappedEvent(QEvent::MouseButtonRelease,
                QPoint(_lastMove.x, _lastMove.y),
                Qt::MouseButton::LeftButton,
                Qt::MouseButtons(), Qt::KeyboardModifiers());
            QCoreApplication::sendEvent(_webSurface->getWindow(), &mappedEvent);
        }
    });
    return true;
}
Beispiel #16
0
bool
MSEdge::insertVehicle(SUMOVehicle& v, SUMOTime time, const bool checkOnly) const {
    // when vaporizing, no vehicles are inserted, but checking needs to be successful to trigger removal
    if (isVaporizing()) {
        return checkOnly;
    }
    const SUMOVehicleParameter& pars = v.getParameter();
    const MSVehicleType& type = v.getVehicleType();
    if (pars.departSpeedProcedure == DEPART_SPEED_GIVEN && pars.departSpeed > getVehicleMaxSpeed(&v)) {
        if (type.getSpeedDeviation() > 0 && pars.departSpeed <= type.getSpeedFactor() * getSpeedLimit() * (2 * type.getSpeedDeviation() + 1.)) {
            WRITE_WARNING("Choosing new speed factor for vehicle '" + pars.id + "' to match departure speed.");
            v.setChosenSpeedFactor(type.computeChosenSpeedDeviation(0, pars.departSpeed / (type.getSpeedFactor() * getSpeedLimit())));
        } else {
            throw ProcessError("Departure speed for vehicle '" + pars.id +
                               "' is too high for the departure edge '" + getID() + "'.");
        }
    }
    if (checkOnly && v.getEdge()->getPurpose() == MSEdge::EDGEFUNCTION_DISTRICT) {
        return true;
    }
    if (!checkOnly) {
        std::string msg;
        if (!v.hasValidRoute(msg)) {
            if (MSGlobals::gCheckRoutes) {
                throw ProcessError("Vehicle '" + v.getID() + "' has no valid route. " + msg);
            } else if (v.getEdge()->getPurpose() == MSEdge::EDGEFUNCTION_DISTRICT) {
                WRITE_WARNING("Removing vehicle '" + pars.id + "' which has no valid route.");
                MSNet::getInstance()->getInsertionControl().descheduleDeparture(&v);
                return false;
            }
        }
    }
#ifdef HAVE_INTERNAL
    if (MSGlobals::gUseMesoSim) {
        SUMOReal pos = 0.0;
        switch (pars.departPosProcedure) {
            case DEPART_POS_GIVEN:
                if (pars.departPos >= 0.) {
                    pos = pars.departPos;
                } else {
                    pos = pars.departPos + getLength();
                }
                if (pos < 0 || pos > getLength()) {
                    WRITE_WARNING("Invalid departPos " + toString(pos) + " given for vehicle '" +
                                  v.getID() + "'. Inserting at lane end instead.");
                    pos = getLength();
                }
                break;
            case DEPART_POS_RANDOM:
            case DEPART_POS_RANDOM_FREE:
                pos = RandHelper::rand(getLength());
                break;
            default:
                break;
        }
        bool result = false;
        MESegment* segment = MSGlobals::gMesoNet->getSegmentForEdge(*this, pos);
        MEVehicle* veh = static_cast<MEVehicle*>(&v);
        if (pars.departPosProcedure == DEPART_POS_FREE) {
            while (segment != 0 && !result) {
                if (checkOnly) {
                    result = segment->hasSpaceFor(veh, time, true);
                } else {
                    result = segment->initialise(veh, time);
                }
                segment = segment->getNextSegment();
            }
        } else {
            if (checkOnly) {
                result = segment->hasSpaceFor(veh, time, true);
            } else {
                result = segment->initialise(veh, time);
            }
        }
        return result;
    }
#else
    UNUSED_PARAMETER(time);
#endif
    if (checkOnly) {
        switch (v.getParameter().departLaneProcedure) {
            case DEPART_LANE_GIVEN:
            case DEPART_LANE_DEFAULT:
            case DEPART_LANE_FIRST_ALLOWED: {
                const SUMOReal occupancy = getDepartLane(static_cast<MSVehicle&>(v))->getBruttoOccupancy();
                return occupancy == (SUMOReal)0 || occupancy * myLength + v.getVehicleType().getLengthWithGap() <= myLength;
            }
            default:
                for (std::vector<MSLane*>::const_iterator i = myLanes->begin(); i != myLanes->end(); ++i) {
                    const SUMOReal occupancy = (*i)->getBruttoOccupancy();
                    if (occupancy == (SUMOReal)0 || occupancy * myLength + v.getVehicleType().getLengthWithGap() <= myLength) {
                        return true;
                    }
                }
        }
        return false;
    }
    MSLane* insertionLane = getDepartLane(static_cast<MSVehicle&>(v));
    return insertionLane != 0 && insertionLane->insertVehicle(static_cast<MSVehicle&>(v));
}
/*
 * Class:     guidoengine_parserError
 * Method:    Init
 * Signature: ()V
 */
JNIEXPORT void JNICALL Java_guidoengine_parserError_Init(JNIEnv * env, jclass cls)
{
	if (!getID (env, cls, gCol, "col", "I")) return;
	if (!getID (env, cls, gLigne, "ligne", "I")) return;
	if (!getID (env, cls, gMessage, "message", "Ljava/lang/String;")) return;
}
bool JPetTRB::operator!=(const JPetTRB& trb) const
{
  return getID() != trb.getID();
}
Beispiel #19
0
void supla_client::loadConfig(void) {
  locations->load(getID());
  channels->load();
}
//virtual 
void LLDriverParamInfo::toStream(std::ostream &out)
{
	LLViewerVisualParamInfo::toStream(out);
	out << "driver" << "\t";
	out << mDrivenInfoList.size() << "\t";
	for (entry_info_list_t::iterator iter = mDrivenInfoList.begin(); iter != mDrivenInfoList.end(); iter++)
	{
		LLDrivenEntryInfo driven = *iter;
		out << driven.mDrivenID << "\t";
	}

	out << std::endl;

	LLVOAvatarSelf *avatar = gAgent.getAvatarObject();
	if(avatar)
	{
		for (entry_info_list_t::iterator iter = mDrivenInfoList.begin(); iter != mDrivenInfoList.end(); iter++)
		{
			LLDrivenEntryInfo driven = *iter;
			LLViewerVisualParam *param = (LLViewerVisualParam*)avatar->getVisualParam(driven.mDrivenID);
			if (param)
			{
				param->getInfo()->toStream(out);
				if (param->getWearableType() != mWearableType)
				{
					if(param->getCrossWearable())
					{
						out << "cross-wearable" << "\t";
					}
					else
					{
						out << "ERROR!" << "\t";
					}
				}
				else
				{
					out << "valid" << "\t";
				}
			}
			else
			{
				llwarns << "could not get parameter " << driven.mDrivenID << " from avatar " << avatar << " for driver parameter " << getID() << llendl;
			}
			out << std::endl;
		}
	}
}
Beispiel #21
0
const String Project::Item::getImageFileID() const      { return "id:" + getID(); }
Beispiel #22
0
void
MSInternalJunction::postloadInit() {
    if (myIncomingLanes.size() == 0) {
        throw ProcessError("Internal junction " + getID() + " has no incoming lanes");
    }
    // the first lane in the list of incoming lanes is special. It defines the
    // link that needs to do all the checking for this internal junction
    const MSLane* specialLane = myIncomingLanes[0];
    assert(specialLane->getLinkCont().size() == 1);
    MSLink* thisLink = specialLane->getLinkCont()[0];
    const MSRightOfWayJunction* parent = dynamic_cast<const MSRightOfWayJunction*>(specialLane->getEdge().getToJunction());
    if (parent == nullptr) {
        // parent has type traffic_light_unregulated
        return;
    }
    const int ownLinkIndex = specialLane->getIncomingLanes()[0].viaLink->getIndex();
    const MSLogicJunction::LinkBits& response = parent->getLogic()->getResponseFor(ownLinkIndex);
    // inform links where they have to report approaching vehicles to
    //std::cout << " special=" << specialLane->getID() << " incoming=" << toString(myIncomingLanes) << " internal=" << toString(myInternalLanes) << "\n";
    for (std::vector<MSLane*>::iterator i = myInternalLanes.begin(); i != myInternalLanes.end(); ++i) {
        const MSLinkCont& lc = (*i)->getLinkCont();
        for (MSLinkCont::const_iterator q = lc.begin(); q != lc.end(); ++q) {
            if ((*q)->getViaLane() != nullptr) {
                const int foeIndex = (*i)->getIncomingLanes()[0].viaLink->getIndex();
                //std::cout << "       response=" << response << " index=" << ownLinkIndex << " foeIndex=" << foeIndex << " ibct=" << indirectBicycleTurn(specialLane, thisLink, *i, *q) << "\n";
                if (response.test(foeIndex) || indirectBicycleTurn(specialLane, thisLink, *i, *q)) {
                    // only respect vehicles before internal junctions if they
                    // have priority (see the analogous foeLinks.test() when
                    // initializing myLinkFoeInternalLanes in MSRightOfWayJunction
                    // Indirect left turns for bicycles are a special case
                    // because they both intersect on their second part with the first part of the other one
                    // and only one of the has priority
                    myInternalLaneFoes.push_back(*i);
                }
                myInternalLaneFoes.push_back((*q)->getViaLane());
            } else {
                myInternalLaneFoes.push_back(*i);
            }
            //std::cout << "  i=" << (*i)->getID() << " qLane=" << (*q)->getLane()->getID() << " qVia=" << Named::getIDSecure((*q)->getViaLane()) << " foes=" << toString(myInternalLaneFoes) << "\n";
        }

    }
    for (std::vector<MSLane*>::const_iterator i = myIncomingLanes.begin() + 1; i != myIncomingLanes.end(); ++i) {
        MSLane* l = *i;
        const MSLinkCont& lc = l->getLinkCont();
        for (MSLinkCont::const_iterator j = lc.begin(); j != lc.end(); ++j) {
            MSLane* via = (*j)->getViaLane();
            if (std::find(myInternalLanes.begin(), myInternalLanes.end(), via) == myInternalLanes.end()) {
                continue;
            }
            myInternalLinkFoes.push_back(*j);
        }
    }
    // thisLinks is itself an exitLink of the preceding internal lane
    thisLink->setRequestInformation(ownLinkIndex, true, false, myInternalLinkFoes, myInternalLaneFoes, thisLink->getViaLane()->getLogicalPredecessorLane());
    assert(thisLink->getViaLane()->getLinkCont().size() == 1);
    MSLink* exitLink = thisLink->getViaLane()->getLinkCont()[0];
    exitLink->setRequestInformation(ownLinkIndex, false, false, std::vector<MSLink*>(),
                                    myInternalLaneFoes, thisLink->getViaLane());
    for (const auto& ili : exitLink->getLane()->getIncomingLanes()) {
        if (ili.lane->getEdge().isWalkingArea()) {
            exitLink->addWalkingAreaFoeExit(ili.lane);
            break;
        }
    }
    for (std::vector<MSLink*>::const_iterator k = myInternalLinkFoes.begin(); k != myInternalLinkFoes.end(); ++k) {
        thisLink->addBlockedLink(*k);
        (*k)->addBlockedLink(thisLink);
    }
}
void
MSSOTLTrafficLightLogic::init(NLDetectorBuilder& nb) throw(ProcessError) {

    MSTrafficLightLogic::init(nb);

    if (isDecayThresholdActivated()) {
        decayThreshold = 1;
    }
    if (sensorsSelfBuilt) {
        //Building SOTLSensors
        switch (SENSORS_TYPE) {
            case SENSORS_TYPE_E1:
                assert(0); // Throw exception because TLS can only handle E2 sensors
            case SENSORS_TYPE_E2:

                //Adding Sensors to the ingoing Lanes

                LaneVectorVector lvv = getLaneVectors();

                DBG(
                    WRITE_MESSAGE("Listing lanes for TLS " + getID());

                for (unsigned int i = 0; i < lvv.size(); i++) {
                LaneVector lv = lvv[i];

                    for (unsigned int j = 0; j < lv.size(); j++) {
                        MSLane* lane = lv[j];
                        WRITE_MESSAGE(lane ->getID());
                    }
                }
                )

                mySensors = new MSSOTLE2Sensors(myID, &(getPhases()));
                ((MSSOTLE2Sensors*)mySensors)->buildSensors(myLanes, nb, getInputSensorsLength());
                mySensors->stepChanged(getCurrentPhaseIndex());
                if (getParameter("USE_VEHICLE_TYPES_WEIGHTS", "0") == "1") {
                    ((MSSOTLE2Sensors*) mySensors)->setVehicleWeigths(getParameter("VEHICLE_TYPES_WEIGHTS", ""));
                }

                //threshold speed param for tuning with irace
                ((MSSOTLE2Sensors*)mySensors)->setSpeedThresholdParam(getSpeedThreshold());

                myCountSensors = new MSSOTLE2Sensors(myID + "Count", &(getPhases()));
                myCountSensors->buildCountSensors(myLanes, nb);
                myCountSensors->stepChanged(getCurrentPhaseIndex());

                //Adding Sensors to the outgoing Lanes

                LinkVectorVector myLinks = getLinks();


                DBG(
                    WRITE_MESSAGE("Listing output lanes");
                for (unsigned int i = 0; i < myLinks.size(); i++) {
                LinkVector oneLink = getLinksAt(i);

                    for (unsigned int j = 0; j < oneLink.size(); j++) {

                        MSLane* lane  = oneLink[j]->getLane();
                        WRITE_MESSAGE(lane ->getID());

                    }
                }
                )


                LaneVectorVector myLaneVector;

                LaneVector outLanes;
                LinkVectorVector myoutLinks = getLinks();

                for (unsigned int i = 0; i < myLinks.size(); i++) {
                    LinkVector oneLink = getLinksAt(i);
                    for (unsigned int j = 0; j < oneLink.size(); j++) {
                        MSLane* lane  = oneLink[j]->getLane();
                        outLanes.push_back(lane);
                    }
                }

                if (outLanes.size() > 0) {
                    myLaneVector.push_back(outLanes);
                }
                if (myLaneVector.size() > 0) {
                    ((MSSOTLE2Sensors*)mySensors)->buildOutSensors(myLaneVector, nb, getOutputSensorsLength());
                    myCountSensors->buildCountOutSensors(myLaneVector, nb);
                }

        }
Beispiel #24
0
void
AGStreet::print() const {
    std::cout << "- AGStreet: Name=" << getID() << " Length=" << getLength() << " pop=" << myPopulation << " work=" << myNumWorkplaces << std::endl;
}
Beispiel #25
0
bool Container::hasParent() const
{
	return getID() != ITEM_BROWSEFIELD && dynamic_cast<const Player*>(getParent()) == NULL;
}
RenderableWebEntityItem::RenderableWebEntityItem(const EntityItemID& entityItemID) :
    WebEntityItem(entityItemID) {
    qDebug() << "Created web entity " << getID();
}
int getID() {
    FILE *file = stdin;
    int c = fgetc(file);
    while (c != EOF && isspace(c)) {
        c = fgetc(file);
    }
    if (isdigit(c)) {
        ungetc(c, file);
        scanf("%d", &c);
        return c;
    }
    return -1;
}

void delete() {
    int id = getID();
    int found = 0;
    int i = 0;
    for (i = 0; i < book.length; i++) {
        if (book.people[i].id == id) {
            found = 1;
            book.length--;

            free(book.people[i].phone);
            free(book.people[i].name);

            book.people[i].id = book.people[book.length].id;
            book.people[i].name = book.people[book.length].name;
            book.people[i].phone = book.people[book.length].phone;
            book.people = (Person *)realloc(book.people, book.length * sizeof(Person));
            break;
RenderableWebEntityItem::~RenderableWebEntityItem() {
    destroyWebSurface();
    qDebug() << "Destroyed web entity " << getID();
}
Beispiel #29
0
// ------------ loading begin
void
MSTriggeredRerouter::myStartElement(int element,
                                    const SUMOSAXAttributes& attrs) {
    if (element == SUMO_TAG_INTERVAL) {
        bool ok = true;
        myCurrentIntervalBegin = attrs.getOptSUMOTimeReporting(SUMO_ATTR_BEGIN, 0, ok, -1);
        myCurrentIntervalEnd = attrs.getOptSUMOTimeReporting(SUMO_ATTR_END, 0, ok, -1);
    }
    if (element == SUMO_TAG_DEST_PROB_REROUTE) {
        // by giving probabilities of new destinations
        // get the destination edge
        std::string dest = attrs.getStringSecure(SUMO_ATTR_ID, "");
        if (dest == "") {
            throw ProcessError("MSTriggeredRerouter " + getID() + ": No destination edge id given.");
        }
        MSEdge* to = MSEdge::dictionary(dest);
        if (to == 0) {
            if (dest == "keepDestination") {
                to = &mySpecialDest_keepDestination;
            } else if (dest == "terminateRoute") {
                to = &mySpecialDest_terminateRoute;
            } else {
                throw ProcessError("MSTriggeredRerouter " + getID() + ": Destination edge '" + dest + "' is not known.");
            }
        }
        // get the probability to reroute
        bool ok = true;
        SUMOReal prob = attrs.getOpt<SUMOReal>(SUMO_ATTR_PROB, getID().c_str(), ok, 1.);
        if (!ok) {
            throw ProcessError();
        }
        if (prob < 0) {
            throw ProcessError("MSTriggeredRerouter " + getID() + ": Attribute 'probability' for destination '" + dest + "' is negative (must not).");
        }
        // add
        myCurrentEdgeProb.add(prob, to);
    }

    if (element == SUMO_TAG_CLOSING_REROUTE) {
        // by closing
        std::string closed_id = attrs.getStringSecure(SUMO_ATTR_ID, "");
        if (closed_id == "") {
            throw ProcessError("MSTriggeredRerouter " + getID() + ": closed edge id given.");
        }
        MSEdge* closed = MSEdge::dictionary(closed_id);
        if (closed == 0) {
            throw ProcessError("MSTriggeredRerouter " + getID() + ": Edge '" + closed_id + "' to close is not known.");
        }
        myCurrentClosed.push_back(closed);
    }

    if (element == SUMO_TAG_ROUTE_PROB_REROUTE) {
        // by explicit rerouting using routes
        // check if route exists
        std::string routeStr = attrs.getStringSecure(SUMO_ATTR_ID, "");
        if (routeStr == "") {
            throw ProcessError("MSTriggeredRerouter " + getID() + ": No route id given.");
        }
        const MSRoute* route = MSRoute::dictionary(routeStr);
        if (route == 0) {
            throw ProcessError("MSTriggeredRerouter " + getID() + ": Route '" + routeStr + "' does not exist.");
        }

        // get the probability to reroute
        bool ok = true;
        SUMOReal prob = attrs.getOpt<SUMOReal>(SUMO_ATTR_PROB, getID().c_str(), ok, 1.);
        if (!ok) {
            throw ProcessError();
        }
        if (prob < 0) {
            throw ProcessError("MSTriggeredRerouter " + getID() + ": Attribute 'probability' for route '" + routeStr + "' is negative (must not).");
        }
        // add
        myCurrentRouteProb.add(prob, route);
    }
}
 const string Road::toString() const {
     stringstream s;
     s << "ID: " << getID() << ", Name: " << getName();
     return s.str();
 }