Exemplo n.º 1
0
DataVar_ptr SpeckleyDomain::getDataVarByName(const string& name) const
{
    if (!initialized) {
        throw "Domain not initialized";
    }

    DataVar_ptr var(new DataVar(name));
    if (name.find("FaceElements_") != name.npos) {
        const IntVec& data =  faces->getVarDataByName(name);
        string elementName = name.substr(0, name.find('_'));
        ElementData_ptr elements = getElementsByName(elementName);
        var->initFromMeshData(shared_from_this(), data,
                speckley::FaceElements, ZONE_CENTERED, elements->getNodes(),
                elements->getIDs());
    } else if (name.find("Elements_") != name.npos) {
        const IntVec& data =  cells->getVarDataByName(name);
        string elementName = name.substr(0, name.find('_'));
        ElementData_ptr elements = getElementsByName(elementName);
        var->initFromMeshData(shared_from_this(), data, speckley::Elements,
                ZONE_CENTERED, elements->getNodes(), elements->getIDs());
    } else if (name.find("Nodes_") != name.npos) {
        const IntVec& data =  nodes->getVarDataByName(name);
        var->initFromMeshData(shared_from_this(), data, speckley::Nodes,
                NODE_CENTERED, getNodes(), getNodes()->getNodeIDs());
    } else {
        cerr << "WARNING: Unrecognized domain variable '" << name << "'\n";
        return DataVar_ptr();
    }

    return var;
}
Exemplo n.º 2
0
string Graph<E>::getString()
{
    string graph_type = "digraph ";
    string graph_name = "G";
    string rankdir    = "rankdir = ";
    string dir        = "TB"; // "LR"
    string node_lab   = "node[label = \"";
    string shape      = "\", shape = ";
    string shapename  = "record"; // "circle"
    string fontname   = ", fontname = ";
    string font       = "Helvetica";
    string fontsize   = "\", fontsize = ";
    string size       = "10";

    std::stringstream os;
    os << graph_type << graph_name << " {\n";
    os << rankdir << dir <<  "\n";
    os << node_lab << shape << "]\n";

    typename set<E>::iterator node;
    for (node = getNodes().begin(); node != getNodes().end(); ++node) {
        os << node_lab << node->getLabel();
        os << fontname << font << fontsize << size << "];\n";
    }

    typename multimap<E, E>::iterator edge;
    for (edge = getEdges().begin(); edge != getEdges().end(); ++edge)
        os << edge->first  << " -> " << edge->second << ";\n";

    os << "}\n";

    return os.str();
}
Exemplo n.º 3
0
TEST_F(NumLibMeshComponentMapTest, DISABLED_SubsetOfNodesByLocation)
#endif
{
    cmap = new MeshComponentMap(components,
        NumLib::ComponentOrder::BY_LOCATION);

    // Select some nodes from the full mesh.
    std::vector<std::size_t> const ids = {0, 5, 9};
    // A smaller mesh without elements containing the selected nodes.
    auto boundary_mesh = createMeshFromSelectedNodes(*mesh, ids);

    MeshLib::MeshSubset const selected_component(boundary_mesh,
                                                 boundary_mesh.getNodes());

    int const selected_component_id = 1;

    // Subset the original cmap.
    MeshComponentMap const cmap_subset = cmap->getSubset(
        components, selected_component, {selected_component_id});

    // Check number of components as selected
    ASSERT_EQ(ids.size(), cmap_subset.dofSizeWithGhosts());

    // .. and the content of the subset.
    for (auto const* n : boundary_mesh.getNodes())
    {
        std::size_t const id = n->getID();
        Location const l_bulk(mesh->getID(), MeshItemType::Node, ids[id]);
        Location const l_boundary(boundary_mesh.getID(), MeshItemType::Node,
                                  id);
        EXPECT_EQ(cmap->getGlobalIndex(l_bulk, comp1_id),
                  cmap_subset.getGlobalIndex(l_boundary, comp1_id));
    }
}
Exemplo n.º 4
0
SceneGraph::~SceneGraph() 
{
	Node *node=getNodes();
	while (node) {
		delete node;
		node = getNodes();
	}
	Route *route=getRoutes();
	while (route) {
		Route *nextRoute=route->next();
		delete route;
		route = nextRoute;
	}

	delete mBackgroundNodeVector;
	delete mFogNodeVector;
	delete mNavigationInfoNodeVector;
	delete mViewpointNodeVector;	

	delete mDefaultBackgroundNode;
	delete mDefaultFogNode;
	delete mDefaultNavigationInfoNode;
	delete mDefaultViewpointNode;

#ifdef SUPPORT_URL
	delete mUrl;
#endif

#ifdef SUPPORT_JSAI
	DeleteJavaVM();
#endif
}
Exemplo n.º 5
0
void ZoneGraph::updateConnections()
    {
    bool drawFuncRels = mDrawOptions.mDrawFunctionRelations;
    ReverseIndexLookup indexLookup(getNodes());
    mConnections.clear();
    for(size_t nodeIndex=0; nodeIndex<getNodes().size(); nodeIndex++)
        {
        const ModelClassifier *classifier = ModelClassifier::getClass(
            getNodes()[nodeIndex].mType);
        if(classifier)
            {
            // Get attributes of classifier, and get the decl type
            for(const auto &attr : classifier->getAttributes())
                {
                mConnections.insertConnection(nodeIndex,
                    ModelClassifier::getClass(attr->getDeclType()),
                    indexLookup, ZDD_FirstIsClient);
                }
            if(drawFuncRels)
                {
                ConstModelClassifierVector relatedClasses;
                mModel->getRelatedFuncInterfaceClasses(*classifier, relatedClasses);
                for(auto const &item : relatedClasses)
                    {
                    mConnections.insertConnection(nodeIndex, item,
                            indexLookup, ZDD_FirstIsClient);
                    }

                ConstModelDeclClasses relatedDeclClasses;
                mModel->getRelatedBodyVarClasses(*classifier, relatedDeclClasses);
                for(auto const &item : relatedDeclClasses)
                    {
                    mConnections.insertConnection(nodeIndex, item.getClass(),
                            indexLookup, ZDD_FirstIsClient);
                    }
                }

            // Go through associations, and get related classes.
            for(const auto &assoc : mModel->mAssociations)
                {
                size_t n1Index = NO_INDEX;
                size_t n2Index = NO_INDEX;
                if(assoc->getChild() == classifier)
                    {
                    n1Index = indexLookup.getClassIndex(assoc->getParent());
                    n2Index = indexLookup.getClassIndex(classifier);
                    }
                else if(assoc->getParent() == classifier)
                    {
                    n2Index = indexLookup.getClassIndex(assoc->getChild());
                    n1Index = indexLookup.getClassIndex(classifier);
                    }
                if(n1Index != NO_INDEX && n2Index != NO_INDEX)
                    {
                    mConnections.insertConnection(n1Index, n2Index, ZDD_SecondIsClient);
                    }
                }
            }
        }
    }
Exemplo n.º 6
0
TEST_F(NumLibLocalToGlobalIndexMapTest, DISABLED_SubsetByComponent)
#endif
{
    dof_map = std::make_unique<NumLib::LocalToGlobalIndexMap>(
        std::move(components), NumLib::ComponentOrder::BY_COMPONENT);

    // Select some elements from the full mesh.
    std::array<std::size_t, 3> const ids = {{ 0, 5, 8 }};
    std::vector<MeshLib::Element*> some_elements;
    for (std::size_t id : ids)
        some_elements.push_back(mesh->getElement(id)->clone());

    auto boundary_mesh =
        MeshLib::createMeshFromElementSelection("boundary_mesh", some_elements);

    MeshLib::MeshSubset selected_component(*boundary_mesh,
                                           boundary_mesh->getNodes());

    auto dof_map_subset = std::unique_ptr<NumLib::LocalToGlobalIndexMap>{
        dof_map->deriveBoundaryConstrainedMap(1,    // variable id
                                              {0},  // component id
                                              std::move(selected_component))};

    // There must be as many rows as nodes in the input times the number of
    // components.
    ASSERT_EQ(boundary_mesh->getNodes().size(),
              dof_map_subset->dofSizeWithGhosts());
}
Exemplo n.º 7
0
void UndoDeleteNodeCommand::undo()
{
    // Deserialize the saved node.
    NodeRoot temp_root;
    SceneDeserializer ds(&temp_root);
    ds.run(data);

    // Extract the node from the temporary root
    n = temp_root.findChild<Node*>();

    // Find the new lists of node and datum pointers
    auto new_nodes = getNodes();
    auto new_datums = getDatums();

    // Swap all the pointers!
    for (auto a = nodes.begin(), b = new_nodes.begin();
              a != nodes.end() && b != new_nodes.end(); ++a, ++b)
        stack->swapPointer(*a, *b);

    for (auto a = datums.begin(); a != datums.end(); ++a)
    {
        Q_ASSERT(new_datums.contains(a.key()));
        stack->swapPointer(a.value(), new_datums[a.key()]);
    }

    if (app)
    {
        app->makeUI(&temp_root);
        app->getGraphScene()->setInspectorPositions(ds.inspectors);
    }
}
Exemplo n.º 8
0
int MonolingualModel::trainSentence(const string& sent, int sent_id) {
    auto nodes = getNodes(sent);  // same size as sent, OOV words are replaced by <UNK>

    // counts the number of words that are in the vocabulary
    int words = nodes.size() - count(nodes.begin(), nodes.end(), HuffmanNode::UNK);

    if (config.subsampling > 0) {
        subsample(nodes); // puts <UNK> tokens in place of the discarded tokens
    }

    if (nodes.empty()) {
        return words;
    }

    // remove <UNK> tokens
    nodes.erase(
        remove(nodes.begin(), nodes.end(), HuffmanNode::UNK),
        nodes.end());

    // Monolingual training
    for (int pos = 0; pos < nodes.size(); ++pos) {
        trainWord(nodes, pos, sent_id);
    }

    return words; // returns the number of words processed, for progress estimation
}
Iterator<unsigned int> *ParallelCoordinatesGraphProxy::getDataIterator() {
  if (getDataLocation() == NODE) {
    return new ParallelCoordinatesDataIterator<node>(getNodes());
  } else {
    return new ParallelCoordinatesDataIterator<edge>(getEdges());
  }
}
Exemplo n.º 10
0
//----------------------------------------------------------------------
// Connecting a node
//----------------------------------------------------------------------
NodePtr LocalNode::connect( const NodeID& nodeID )
{
    EQASSERT( nodeID != NodeID::ZERO );
    EQASSERT( _state == STATE_LISTENING );

    Nodes nodes;
    getNodes( nodes );

    for( Nodes::const_iterator i = nodes.begin(); i != nodes.end(); ++i )
    {
        NodePtr peer = *i;
        if( peer->getNodeID() == nodeID && peer->isConnected( )) // early out
            return peer;
    }

    for( Nodes::const_iterator i = nodes.begin(); i != nodes.end(); ++i )
    {
        NodePtr peer = *i;
        NodePtr node = _connect( nodeID, peer );
        if( node.isValid( ))
            return node;
    }
        
    EQWARN << "Node " << nodeID << " connection failed" << std::endl;
    return 0;
}
Exemplo n.º 11
0
void SceneGraph::recomputeBoundingBox() 
{
	Node	*node;
	float	center[3];
	float	size[3];

	BoundingBox bbox;

	for (node=getNodes(); node; node=node->nextTraversal()) {
		if (node->isGroupingNode()) {
			GroupingNode *gnode = (GroupingNode *)node;
			gnode->getBoundingBoxCenter(center);
			gnode->getBoundingBoxSize(size);
			bbox.addBoundingBox(center, size);
		}
		else if (node->isGeometryNode()) { 
			GeometryNode *gnode = (GeometryNode *)node; 
			gnode->getBoundingBoxCenter(center); 
			gnode->getBoundingBoxSize(size); 
			bbox.addBoundingBox(center, size); 
		} 
	}

	setBoundingBox(&bbox);
}
Exemplo n.º 12
0
void Config::notifyNodeFrameFinished( const uint32_t frameNumber )
{
    if( _finishedFrame >= frameNumber ) // node finish already done
        return;

    const Nodes& nodes = getNodes();
    for( Nodes::const_iterator i = nodes.begin(); i != nodes.end(); ++i )
    {
        const Node* node = *i;
        if( node->isRunning() && node->getFinishedFrame() < frameNumber )
        {
            LBASSERT( _needsFinish || node->isActive( ));
            return;
        }
    }

    _finishedFrame = frameNumber;

    // All nodes have finished the frame. Notify the application's config that
    // the frame is finished

    // do not use send/_bufferedTasks, not thread-safe!
    send( findApplicationNetNode(),
          fabric::CMD_CONFIG_FRAME_FINISH ) << frameNumber;
    LBLOG( LOG_TASKS ) << "TASK config frame finished  " << " frame "
                       << frameNumber << std::endl;
}
Exemplo n.º 13
0
//---------------------------------------------------------------------------
// update running entities (init/exit/runtime change)
//---------------------------------------------------------------------------
bool Config::_updateRunning( const bool canFail )
{
    if( _state == STATE_STOPPED )
        return true;

    LBASSERT( _state == STATE_RUNNING || _state == STATE_INITIALIZING ||
              _state == STATE_EXITING );

    if( !_connectNodes() && !canFail )
        return false;

    _startNodes();
    _updateCanvases();
    const bool result = _updateNodes( canFail );
    _stopNodes();

    // Don't use visitor, it would get confused with modified child vectors
    _deleteEntities( getCanvases( ));
    _deleteEntities( getLayouts( ));
    _deleteEntities( getObservers( ));
    const Nodes& nodes = getNodes();
    for( Nodes::const_iterator i = nodes.begin(); i != nodes.end(); ++i )
    {
        const Pipes& pipes = (*i)->getPipes();
        for( Pipes::const_iterator j = pipes.begin(); j != pipes.end(); ++j )
        {
            const Windows& windows = (*j)->getWindows();
            _deleteEntities( windows );
        }
    }

    return result;
}
Exemplo n.º 14
0
void testDFS()
{
	Tree_2X<int> tree;
	Node<int> *node = getNodes();
	tree.DFS(node);
	delete[] node;
}
Exemplo n.º 15
0
void SCIPSolver::printStatistics(){
  std::cout << "\td Time: " << getTime() << "\tNodes:" << getNodes()
	    << std::endl;
  if(_verbosity > 1){
    SCIP_CALL_EXC(SCIPprintStatistics(_scip, NULL));
  }
}
Exemplo n.º 16
0
bool MeshFace::isPtInsideFace(double x, double y, double z)
{
   int i;
   double m1,m2;
   double anglesum=0,costheta;
   point p1,p2;
   vector<Node*> nodes = getNodes();
   int nen = nodes.size();

   for (i=0;i<nen;i++) {

      p1.x = nodes[i]->x() - x;
      p1.y = nodes[i]->y() - y;
      p1.z = nodes[i]->z() - z;
      p2.x = nodes[(i+1)%nen]->x() - x;
      p2.y = nodes[(i+1)%nen]->y() - y;
      p2.z = nodes[(i+1)%nen]->z() - z;

      m1 = MODULUS(p1);
      m2 = MODULUS(p2);
      if (m1*m2 <= EPSILON)
         return(true); /* We are on a node, consider this inside */
      else
         costheta = (p1.x*p2.x + p1.y*p2.y + p1.z*p2.z) / (m1*m2);

      anglesum += acos(costheta);
   }
   if(anglesum <= (TWOPI+EPSILON) && anglesum >= (TWOPI-EPSILON)){
	   return(true);
   }else{
	   return(false);
   }
}
Exemplo n.º 17
0
bool Config::_needsLocalSync() const
{
    const Nodes& nodes = getNodes();
    if( nodes.empty( ))
        return true; // server sends unlock command - process it

    EQASSERT( nodes.size() == 1 );
    const Node* node = nodes.front();
    switch( node->getIAttribute( Node::IATTR_THREAD_MODEL ))
    {
        case ASYNC:
            return false;
            break;

        case DRAW_SYNC:
            if( !(node->getTasks() & fabric::TASK_DRAW) )
                return false;
            break;

        case LOCAL_SYNC:
            if( node->getTasks() == fabric::TASK_NONE )
                return false;
            break;
                
        default:
            EQUNIMPLEMENTED;
    }

    return true;
}
Exemplo n.º 18
0
const Model* Config::getModel( const eq::uint128_t& modelID )
{
    if( modelID == 0 )
        return 0;

    // Protect if accessed concurrently from multiple pipe threads
    const eq::Node* node = getNodes().front();
    const bool needModelLock = (node->getPipes().size() > 1);
    lunchbox::ScopedWrite _mutex( needModelLock ? &_modelLock : 0 );

    const size_t nModels = _models.size();
    LBASSERT( _modelDist.size() == nModels );

    for( size_t i = 0; i < nModels; ++i )
    {
        const ModelDist* dist = _modelDist[ i ];
        if( dist->getID() == modelID )
            return _models[ i ];
    }

    _modelDist.push_back( new ModelDist );
    Model* model = _modelDist.back()->loadModel( getApplicationNode(),
                                                 getClient(), modelID );
    LBASSERT( model );
    _models.push_back( model );

    return model;
}
Exemplo n.º 19
0
void Config::_stopNodes()
{
    // wait for the nodes to stop, destroy entities, disconnect
    Nodes stoppingNodes;
    const Nodes& nodes = getNodes();
    for( Nodes::const_iterator i = nodes.begin(); i != nodes.end(); ++i )
    {
        Node* node = *i;
        const State state = node->getState();
        if( state != STATE_STOPPED && state != STATE_FAILED )
            continue;

        LBASSERT( !node->isActive() || state == STATE_FAILED );
        if( node->isApplicationNode( ))
            continue;

        co::NodePtr netNode = node->getNode();
        if( !netNode ) // already disconnected
            continue;

        LBLOG( LOG_INIT ) << "Exiting node" << std::endl;

        if( state == STATE_FAILED )
            node->setState( STATE_STOPPED );

        stoppingNodes.push_back( node );
        LBASSERT( netNode.isValid( ));

        netNode->send( fabric::CMD_SERVER_DESTROY_CONFIG )
                << getID() << LB_UNDEFINED_UINT32;
        netNode->send( fabric::CMD_CLIENT_EXIT );
    }

    // now wait that the render clients disconnect
    uint32_t nSleeps = 50; // max 5 seconds for all clients
    for( Nodes::const_iterator i = stoppingNodes.begin();
         i != stoppingNodes.end(); ++i )
    {
        Node*        node    = *i;
        co::NodePtr netNode = node->getNode();
        node->setNode( 0 );

        if( nSleeps )
            while( netNode->isConnected() && --nSleeps )
                lunchbox::sleep( 100 ); // ms

        if( netNode->isConnected( ))
        {
            co::LocalNodePtr localNode = getLocalNode();
            LBASSERT( localNode.isValid( ));

            LBWARN << "Forcefully disconnecting exited render client node"
                   << std::endl;
            localNode->disconnect( netNode );
        }

        LBLOG( LOG_INIT ) << "Disconnected node" << std::endl;
    }
}
Exemplo n.º 20
0
bool ClassDiagram::loadDiagram(File &file)
    {
    NameValueFile nameValFile;
    bool success = nameValFile.readFile(file);
    if(success)
        {
        CompoundValue names;
        names.parseString(nameValFile.getValue("Names"));
        CompoundValue xPositions;
        xPositions.parseString(nameValFile.getValue("XPositions"));
        CompoundValue yPositions;
        yPositions.parseString(nameValFile.getValue("YPositions"));
        std::vector<ClassNode> &nodes = getNodes();
        for(size_t i=0; i<names.size(); i++)
            {
            OovString name = names[i];
            if(i == 0)
                {
                // The node at index zero is the graph key, and is not stored in
                // the graph with a name or type.
                // The node at index one is the first class, which is typically the
                // same as the drawing name.
                eDiagramStorageTypes drawingType;
                OovString drawingName;
                DiagramStorage::getDrawingHeader(nameValFile, drawingType, drawingName);
                // This adds the key automatically as item index zero.
                // Call this function to set the last selected class name for the journal.
                clearGraphAndAddClass(drawingName, ClassGraph::AN_All,
                        ClassDiagram::DEPTH_SINGLE_CLASS, false);
                int x=0;
                int y=0;
                xPositions[i].getInt(0, INT_MAX, x);
                yPositions[i].getInt(0, INT_MAX, y);
                nodes[0].setPosition(GraphPoint(x, y));
                }
            else
                {
                // This will not add duplicates, so if the name is different
                // from the drawingName, it will be added.
                addClass(name, ClassGraph::AN_All,
                    ClassDiagram::DEPTH_SINGLE_CLASS, false);
                }

            auto nodeIter = std::find_if(nodes.begin(), nodes.end(),
                [&name](ClassNode &node)
                { return(node.getType() && name == node.getType()->getName()); });
            if(nodeIter != nodes.end())
                {
                int x=0;
                int y=0;
                xPositions[i].getInt(0, INT_MAX, x);
                yPositions[i].getInt(0, INT_MAX, y);
                nodeIter->setPosition(GraphPoint(x, y));
                }
            }
        }
    return success;
    }
Exemplo n.º 21
0
 template<typename T> static void getNodesAs(
     const pugi::xml_document& cfg, const std::string xpath,
     std::list<T>& nodes ) {
   std::list<std::string> snodes ;
   getNodes( cfg, xpath, snodes ) ;
   for( auto n : snodes ) {
     nodes.push_back( boost::lexical_cast<T>( n ) ) ;
   }
 }
Exemplo n.º 22
0
 void GroupTree::getNodes(std::shared_ptr< GroupTreeNode > fromNode, std::vector<std::shared_ptr< const GroupTreeNode >>& nodes) const {
     std::map<std::string, std::shared_ptr< GroupTreeNode > >::const_iterator iter = fromNode->begin();
     while (iter != fromNode->end()) {
         std::shared_ptr< GroupTreeNode > child = (*iter).second;
         nodes.push_back(child);
         getNodes(child, nodes);
         ++iter;
     }
 }
Exemplo n.º 23
0
void GroupTree::getNodes(GroupTreeNodePtr fromNode, std::vector<GroupTreeNodeConstPtr>& nodes) const {
    std::map<std::string, GroupTreeNodePtr >::const_iterator iter = fromNode->begin();
    while (iter != fromNode->end()) {
        GroupTreeNodePtr child = (*iter).second;
        nodes.push_back(child);
        getNodes(child, nodes);
        ++iter;
    }
}
Exemplo n.º 24
0
unsigned int SceneGraph::getNodeNumber(Node *node) {
	unsigned int nNode = 1;
	for (Node *n = getNodes(); n; n = n->nextTraversal()) {
		if (n == node)
			return nNode;
		nNode++;
	}
	return 0;
}
Exemplo n.º 25
0
void SceneManager::setCameraNode(const string &node)
{
    camera = NULL;
    cameraNode = node;
    SceneManager::NodeIterator i = getNodes(node);
    if (i.hasNext()) {
        camera = i.next();
    }
}
Exemplo n.º 26
0
// The darwin linker processes input files in two phases.  The first phase
// links in all object (.o) files in command line order. The second phase
// links in libraries in command line order.
// In this function we reorder the input files so that all the object files
// comes before any library file. We also make a group for the library files
// so that the Resolver will reiterate over the libraries as long as we find
// new undefines from libraries.
void MachOLinkingContext::finalizeInputFiles() {
    std::vector<std::unique_ptr<Node>> &elements = getNodes();
    std::stable_sort(elements.begin(), elements.end(),
                     [](const std::unique_ptr<Node> &a,
    const std::unique_ptr<Node> &b) {
        return !isLibrary(a) && isLibrary(b);
    });
    size_t numLibs = std::count_if(elements.begin(), elements.end(), isLibrary);
    elements.push_back(llvm::make_unique<GroupEnd>(numLibs));
}
Exemplo n.º 27
0
CompiledMaterial MaterialEditorModel::compileMaterial() {
	if(getNodes().isEmpty()) {
		return material;
	}

	MaterialCompiler comp;
	Node *n = getNodes().first();
	if(n) {
		if(comp.serialize(n, getLinks())) {
			material = comp.getCompiledMaterial();
			QDataStream str(&material.data, QIODevice::WriteOnly);
			serialize(str);

		} else {
			qDebug(QString("Unable to compile material : error %1").arg(comp.getError()).toUtf8());
		}
	}
	return material;
}
Exemplo n.º 28
0
std::string Graph::getGraph(){
    std::string temp;
    temp += str_gdef;
    temp += getKeys();
    temp += str_head;
    temp += getNodes();
    temp += getEdges();
    temp += str_foot;
    return temp;
}
Exemplo n.º 29
0
QVector<Terminal *> Device::getTerminals() {
    QVector<GraphNode*> nodes = getNodes();
    QVector<Terminal*> terminals;
    int nNodes = nodes.size();
    for(int i=0; i < nNodes; ++i) {
        terminals.append( static_cast<Terminal*>(nodes[i]) );
    }

    return terminals;
}
Exemplo n.º 30
0
bool Config::_cmdCheckFrame( co::ICommand& cmd )
{
    const int64_t lastInterval = getServer()->getTime() - _lastCheck;
    _lastCheck = getServer()->getTime();

    co::ObjectICommand command( cmd );
    LBVERB << "Check nodes for frame finish " << command << std::endl;

    const uint32_t frameNumber = command.read< uint32_t >();
    const uint32_t timeout = getTimeout();

    bool retry = false;
    const Nodes& nodes = getNodes();
    for( Nodes::const_iterator i = nodes.begin(); i != nodes.end(); ++i )
    {
        Node* node = *i;
        if( node->isRunning() && node->isActive() )
        {
            co::NodePtr netNode = node->getNode();
            if ( netNode->isClosed() )
                continue;

            if ( node->getFinishedFrame() >= frameNumber )
                continue;

            const int64_t interval = getServer()->getTime() -
                                     netNode->getLastReceiveTime();
            getLocalNode()->ping( netNode );

            // TODO?: handle timed out nodes.
            // currently we get a false positive due to lack of communication
            // from client to server. we do not get ping responses in time.
            // running clients should inform the server about their status with
            // a timeout/2 period.

            if ( interval > timeout && lastInterval <= timeout )
                continue;

            // retry
            LBINFO << "Retry waiting for node " << node->getName()
                   << " to finish frame " << frameNumber << " last seen "
                   << interval << " ms ago" << " last run " << lastInterval
                   << std::endl;
            retry = true;
            // else node timeout
        }
    }

    if( retry )
        return true;

    send( command.getRemoteNode(), fabric::CMD_CONFIG_FRAME_FINISH )
        << _currentFrame;
    return true;
}