Example #1
0
void Btree<T>::cutNode(T& x,
                      unsigned xRST,
                      unsigned ptr,
                      unsigned pos,
                      T& y,
                      unsigned &yRST)
//
// Purpose: divides the node accessed by index ptr that contains
// item x and index xRST at index pos.  The new nodes are accessed
// by pointers ptr and yRST.  The median element is y.
//
// Parameters:
//
//    input: x - the inserted data
//           xRST - the inserted index associated with item x
//           ptr - the index to the manipulated node
//           pos - the index of the dividing line
//
//    output:
//           y - the new median
//           yRST - the index to the other node.
//
{
   unsigned median, i;
   Bstruct<T> *buf1, *buf2;

   buf1 = new Bstruct<T>;
   buf2 = new Bstruct<T>;
   readNode(buf1, ptr);
   // calculate the median element which also determines if
   // the new inserted item x is placed in the new left or the
   // new right nodes
   median = (pos <= BTREE_MIN) ? BTREE_MIN : BTREE_MIN + 1;
   // create a new tree node and put it on the right
   yRST = getNodeIndex();
   for (i = 0; i <= BTREE_MAX; i++)
     buf2->nodeLink[i] = BTREE_NIL;
   numNodes++;

   // loop to move half of the keys
   for (i = median + 1; i <= BTREE_MAX; i++) {
     buf2->data[i - median] = buf1->data[i];
     buf2->nodeLink[i - median] = buf1->nodeLink[i];
   }
   buf2->count = BTREE_MAX - median;
   buf1->count = median;
   // push in the new data
   if (pos <= BTREE_MIN)
     pushIn(x, xRST, buf1, pos);
   else
     pushIn(x, xRST, buf2, pos - median);
   y = buf1->data[buf1->count];
   buf2->nodeLink[0] = buf1->nodeLink[buf1->count--];
   writeNode(buf1, ptr);
   writeNode(buf2, yRST);
   delete buf1;
   delete buf2;
}
//--------------------------------------------------------------------------------------------//
int recomputeDV(){
  isRecomputeExists=1;


  while(1)
    {

      pthread_mutex_lock(&mutex);
      if(zeroReceived>=routing_table->directNeighbors)
        break;

      pthread_cond_wait(&convar3,&mutex);
      if(zeroReceived>=routing_table->directNeighbors)
        break;

      //-------recomputing-------------------------------------------------------------------------------//
      //          receivedZeroCounter=0;
      //printf("recomputeDV():recomputing\n");
      int i=0;
      int myIndex;
      int* lastDV=(int*)malloc(sizeof(int)*routing_table->numOfNodes);
      myIndex=getNodeIndex(routing_table->table_node->name);
      for(i=0;i<routing_table->numOfNodes;i++){
          lastDV[i]=routing_table->r_table[myIndex][i];
          if(i!=myIndex)
            routing_table->r_table[myIndex][i]=D(myIndex,i);



      }
    //  printf("recomputeDV():recomputed\n");
      //checking if changed
      if(checkIfChanged(lastDV,routing_table->r_table[myIndex])==0)
        {
          changed=1;
        }
      else
        {
          //if did'nt changed
          changed=0;
        }
      doneComputing=1;
     // printTable();
      free(lastDV);
      pthread_mutex_unlock(&mutex);
      //sleep(1);
    }


  //exiting
  //printf("recomputeDV():oudside main loop\n");

  pthread_mutex_unlock(&mutex);
  return 0;


}
Example #3
0
void AdjacencyMatrix::removeEdge(Edge* edge)
{
    Node* n1 = edge->getNode1();
    Node* n2 = edge->getNode2();
    if(!edge || !n1 || !n2)
        throw LogException("invalid edge",__LINE__,__FILE__);
    if(!getEdge(n1,n2))
        throw LogException("edge is not in the matrix",__LINE__,__FILE__);   //the edge is not in the matrix

    int idx1 = getNodeIndex(n1);
    int idx2 = getNodeIndex(n2);
    if(idx1==-1 || idx2==-1)
        throw LogException("an extremity is not in the matrix",__LINE__,__FILE__);   //a node does not exist

    this->SquareMatrix<Edge*>::set(idx1, idx2, nullptr);
    if(!edge->isOriented())
        this->SquareMatrix<Edge*>::set(idx2, idx1, nullptr);
}
//this method prints the "via des cost" to all of the other routers
//--------------------------------------------------------------------------------------------//
void printFinalResualt(){
  int i=0;
  int myIndex=getNodeIndex(routing_table->table_node->name);
  for(i=0;i<routing_table->numOfNodes;i++){
      int last=routing_table->via[i];
      while(routing_table->via[last]!=last)
        last=routing_table->via[last];
      printf("%s\t%s\t%d\n",routing_table->nodes[i].name,routing_table->nodes[last].name,routing_table->r_table[myIndex][i]);
  }
}
Example #5
0
void ClassGraph::insertConnection(int node1, const ModelType *type,
        const ClassConnectItem &connectItem)
    {
    if(type)
        {
        size_t n2Index = getNodeIndex(type);
        if(n2Index != NO_INDEX)
            {
            insertConnection(node1, n2Index, connectItem);
            }
        }
    }
//this method calculates does 'relax'.
//--------------------------------------------------------------------------------------------//
int D(int x,int y){
  int i=0;
  int myIndex=getNodeIndex(routing_table->table_node->name);

  int min_value=INFINITY;
  for(i=0;i<routing_table->directNeighbors;i++){
      min_value=min(min_value, c(myIndex,routing_table->directNeig[i])+c(routing_table->directNeig[i],y) );
      if(c(myIndex,y)>c(myIndex,routing_table->directNeig[i])+c(routing_table->directNeig[i],y))//doing relax
        routing_table->via[y]=routing_table->directNeig[i];
  }
  return min_value;
}
//this method returns all a array of indexes of the direct neighbors of a router
//--------------------------------------------------------------------------------------------//
int* getAllDirectNeighbors(int x){
  int i=0;
  int j=0;
  int myIndex=getNodeIndex(routing_table->table_node->name);
  int* neighbors=(int*)malloc(sizeof(int)*routing_table->directNeighbors);
  for(i=0;i<routing_table->numOfNodes;i++){
      if(routing_table->r_table[myIndex][i]!=INFINITY && i!=myIndex){
          neighbors[j]=i;
          j++;
      }

  }
  return neighbors;
}
Example #8
0
void AdjacencyMatrix::removeNode(Node *node)
{
    if(!node)
        throw LogException("invalid node",__LINE__,__FILE__);
    int idx = getNodeIndex(node);
    if(idx == -1)
        throw LogException("node is not in the matrix",__LINE__,__FILE__);
    this->SquareMatrix<Edge*>::shrink(idx);
    idToIndex.erase(node->getId());
    for(auto it = idToIndex.begin(); it != idToIndex.end(); it++)
    {
        if(it->second > idx)
            it->second--;
    }
}
Example #9
0
void Structure::Graph::removeNode( QString nid )
{
	// node index
	int idx = getNodeIndex(nid);
	if (idx == -1) return;

	// remove incident links
	foreach (Link* l , links)	{
		if (l->hasNode(nid)) removeLink(l);
	}

	// remove
	delete nodes[idx];
	nodes.remove(idx);
}
Example #10
0
Boolean Btree<T>::insert(T& x)
//
// Purpose: performs node insertion in a B-tree.
//
//  Parameters:
//
//    input: x - the inserted data
//
{
  T r;  // data for the node that is inserted as the new root
  unsigned p, rRST; // the right subtree of 'r'
  Bstruct<T> *buf;

  // if item x is in the tree exit
  if (search(x))
    return FALSE;

  // did the tree grow in height?
  if (pushDown(x, root, r, rRST)) {
     // get the index of a new node
     p = getNodeIndex();
     // make new root
     buf = new Bstruct<T>;
     numNodes++;
     buf->count = 1;
     buf->data[1] = r;
     buf->nodeLink[0] = root;
     buf->nodeLink[1] = rRST;
     for (unsigned i = 2; i <= BTREE_MAX; i++)
       buf->nodeLink[i] = BTREE_NIL;
     root = p;
     // save the new node
     writeNode(buf, p);
     delete buf;
  }
  numData++;
  return TRUE;
}
Example #11
0
  void insertNode(int node){
    std::map<int,int>::iterator nodeLook = nodeHash_.find(node);
      
    if(nodeLook==nodeHash_.end()){
      // not yet in: 
      std::pair<std::map<int, int>::iterator, bool> insertCheck  
	= nodeHash_.insert(
			   std::pair<int,int>(
					      node,
					      getNodeIndex()
					      )

			   );
      //      nodeHash_[node] = getNodeIndex();
      
      incrementNodeIndex();

      if(!insertCheck.second){
	std::cout<<"fail to insert: "<<node<<std::endl;
      }
    }
    // open the edge account 
  }
int main(int argc, char* argv[])
{
	/* Declarations */
	List list;
	List list_1;
	List list_2;
	List list_3;
	List list_4;
	List list_5;
	List list_6;
	Position pos;
	Position pos_1;
	Position pos_2;
	Position pos_3;
	Position pos_4;
	Position pos_a, pos_b;
	int len;
	int idx;
	ElementType elem;

	/* Initialize list */
	list=createList();

	/* Test functions 'insertNode' and 'appendNode' */
	printf("Test functions 'insertNode' and 'appendNode'\n\n");
	printf("Before 'insertNode':\n");
	printList(list);
	pos_1=getHeaderNode(list);
	insertNode(11, list, pos_1);
	pos_2=advanceNode(pos_1);
	insertNode(2, list, pos_2);
	pos_3=advanceNode(pos_2);
	insertNode(3, list, pos_3);
	pos_4=advanceNode(pos_3);
	insertNode(10, list, pos_4);
	insertNode(9, list, pos_2);
	printf("After 'insertNode':\n");
	printList(list);
	printf("Before 'appendNode':\n");
	printList(list);
	appendNode(7, list);
	appendNode(2, list);
	printf("After 'appendNode'\n");
	printList(list);
	printf("\n");

	/* Test functions 'cloneList', 'deleteNode' and 'deleteList' */
	printf("Test functions 'cloneList', 'deleteNode' and 'deleteList'\n\n");
	list_1=cloneList(list);
	printf("Before 'deleteNode':\n");
	printList(list_1);
	deleteNode(2, list_1);
	printf("After 'deleteNode':\n");
	printList(list_1);
	printf("Before 'deleteList':\n");
	printList(list_1);
	deleteList(list_1);
	printf("After 'deleteList':\n");
	printList(list_1);
	printf("\n");

	/* Test function 'getListLength' */
	printf("Test function 'getListLength'\n\n");
	len=getListLength(list);
	printf("Length: %d\n", len);
	printf("\n");

	/* Test functions 'findNode', 'findNodePrevious' and 'getNodeIndex' */
	printf("Test functions 'findNode', 'findNodePrevious' and 'getNodeIndex'\n\n");
	elem=2;
	pos=findNode(elem, list);
	if(pos!=NULL)
	{
		idx=getNodeIndex(pos, list);
		printList(list);
		printf("finding %d, Element at index %d found\n", elem, idx);
	}
	else
	{
		printf("finding %d, not found\n", elem);
	}
	elem=3;
	pos=findNodePrevious(elem, list);
	/* Check whether elem is found in list */
	if(pos->m_next!=NULL)
	{
		idx=getNodeIndex(pos, list);
		printf("finding previous element of %d, Element at index %d found\n", elem, idx);
	}
	else
	{
		/* elem is not in list */
		printf("finding previous element of %d, not found\n", elem);
	}
	printf("\n");

	/* Test functions 'makeListEmpty' and 'isListEmpty' */
	printf("Test functions 'makeListEmpty' and 'isListEmpty'\n\n");
	list_2=cloneList(list);
	printf("Before 'makeListEmpty':\n");
	printList(list_2);
	list_2=makeListEmpty(list_2);
	if(isListEmpty(list_2))
	{
		printf("List emptied successfully\n");
		printf("After 'makeListEmpty'\n");
		printList(list_2);
	}
	printf("\n");

	/* Test functions 'getHeaderNode', 'getFirstNode', 'getLastNode', 'advanceNode' and 'getNodeElem' */
	printf("Test functions 'getHeaderNode', 'getFirstNode', 'getLastNode', 'advanceNode' and 'getNodeElem'\n\n");
	printList(list);
	pos=getHeaderNode(list);
	printf("Header at index %d\n", getNodeIndex(pos, list));
	pos=getFirstNode(list);
	printf("First element at index %d have value %d\n", getNodeIndex(pos, list), getNodeElem(pos));
	pos=getLastNode(list);
	printf("Last element at index %d have value %d\n", getNodeIndex(pos, list), getNodeElem(pos));
	pos=getFirstNode(list);
	pos=advanceNode(pos);
	printf("Second element at index %d have value %d\n", getNodeIndex(pos, list), getNodeElem(pos));
	printf("\n");

	/* Test function 'reverseList' */
	printf("Test function 'reverseList'\n\n");
	list_3=cloneList(list);
	printf("Before 'reverseList':\n");
	printList(list_3);
	list_3=reverseList(list_3);
	printf("After 'reverseList':\n");
	printList(list_3);
	printf("\n");

	/* Test function 'swapNode' */
	printf("Test function 'swapNode'\n\n");
	list_4=cloneList(list);
	printf("Before 'swapNode':\n");
	printList(list_4);
	pos_a=getHeaderNode(list_4);
	pos_a=advanceNode(pos_a);
	pos_a=advanceNode(pos_a);
	pos_b=advanceNode(pos_a);
	swapNode(pos_a, pos_b, list_4);
	printf("After 'swapNode':\n");
	printList(list_4);
	printf("\n");

	/* Test function 'bubbleSortList' */
	printf("Test function 'bubbleSortList'\n\n");
	list_5=cloneList(list);
	printf("Before 'bubbleSortList':\n");
	printList(list_5);
	bubbleSortList(list_5);
	printf("After 'bubbleSortList':\n");
	printList(list_5);
	printf("\n");

	/* Test function 'connectList' */
	printf("Test function 'connectList'\n\n");
	printf("List 1:\n");
	printList(list);
	printf("Length: %d\n", getListLength(list));
	printf("List 2:\n");
	printList(list_5);
	printf("Length: %d\n", getListLength(list_5));
	list_6=connectList(list, list_5);
	printf("Connected list:\n");
	printList(list_6);
	printf("Length: %d\n", getListLength(list_6));
	printf("\n");

	/* Cleanup memory */
	destroyList(list);
	destroyList(list_1);
	destroyList(list_2);
	destroyList(list_3);
	destroyList(list_4);
	destroyList(list_5);
	destroyList(list_6);

	return 0;
}
Example #13
0
void ClassGraph::updateConnections(const ModelData &modelData)
    {
    mConnectMap.clear();
//    Diagram *node1, Diagram *node2
    for(size_t ni=0; ni<mNodes.size(); ni++)
        {
        const ModelType *type = mNodes[ni].getType();

        if(type)
            {
            if(mGraphOptions.drawTemplateRelations)
                {
                // Go through templates
                if(type->isTemplateUseType())
                    {
                    ConstModelClassifierVector relatedClassifiers;
                    modelData.getRelatedTypeArgClasses(*type, relatedClassifiers);
                    for(auto const &cl : relatedClassifiers)
                        {
                        insertConnection(ni, cl, ClassConnectItem(ctTemplateDependency));
                        }
                    }
                }
            const ModelClassifier *classifier = type->getClass();
            if(classifier)
                {
                // Get attributes of classifier, and get the decl type
                for(const auto &attr : classifier->getAttributes())
                    {
                    insertConnection(ni, attr->getDeclType(),
                            ClassConnectItem(ctAggregation, attr->isConst(),
                                        attr->isRefer(), attr->getAccess()));
                    }

                if(mGraphOptions.drawOperParamRelations)
                    {
                    // Get operations parameters of classifier, and get the decl type
                    ConstModelDeclClasses declClasses;
                    modelData.getRelatedFuncParamClasses(*classifier, declClasses);
                    for(const auto &declCl : declClasses)
                        {
                        const ModelDeclarator *decl = declCl.getDecl();
                        insertConnection(ni, declCl.getClass(), ClassConnectItem(ctFuncParam,
                                decl->isConst(), decl->isRefer(), Visibility()));
                        }
                    }

                if(mGraphOptions.drawOperBodyVarRelations)
                    {
                    // Get operations parameters of classifier, and get the decl type
                    ConstModelDeclClasses declClasses;
                    modelData.getRelatedBodyVarClasses(*classifier, declClasses);
                    for(const auto &declCl : declClasses)
                        {
                        const ModelDeclarator *decl = declCl.getDecl();
                        insertConnection(ni, declCl.getClass(), ClassConnectItem(ctFuncVar,
                                decl->isConst(), decl->isRefer(), Visibility()));
                        }
                    }

                // Go through associations, and get related classes.
                for(const auto &assoc : modelData.mAssociations)
                    {
                    size_t n1Index = NO_INDEX;
                    size_t n2Index = NO_INDEX;
                    if(assoc->getChild() == classifier)
                        {
                        n1Index = getNodeIndex(assoc->getParent());
                        n2Index = ni;
                        }
                    else if(assoc->getParent() == classifier)
                        {
                        n1Index = ni;
                        n2Index = getNodeIndex(assoc->getChild());
                        }
                    if(n1Index != NO_INDEX && n2Index != NO_INDEX)
                        {
                        insertConnection(n1Index, n2Index,
                                ClassConnectItem(ctIneritance, assoc->getAccess()));
                        }
                    }
                }
            }
        }
    }
Example #14
0
QList<unsigned char> cPathfinding::find(P_CHAR pChar, const Coord &from, const Coord &to)
{
	QList<unsigned char> result;
	int i;

	// We can only calculate a path on the normal maps and if the destination is not out of range
	if (from.isInternalMap() || from.distance(to) > (unsigned int)areaSize) {
		return result;
	}

	memset(touched, 0, sizeof(bool) * nodeCount); // Clear the touched nodes
	this->goal = to; // Save the goal

	// Actually th�s should be the x/y offset of our area
	xoffset = (from.x + to.x - areaSize) / 2;
	yoffset = (from.y + to.y - areaSize) / 2;

	int fromNode = getNodeIndex(from.x, from.y, from.z);
	int toNode = getNodeIndex(to.x, to.y, to.z);
	openlist = fromNode; // Where are we

	// Initialize the node
	nodes[fromNode].cost = 0;
	nodes[fromNode].total = heuristic(from.x - xoffset, from.y - yoffset, from.z);
	nodes[fromNode].parent = -1;
	nodes[fromNode].next = -1;
	nodes[fromNode].prev = -1;
	nodes[fromNode].z = from.z;

	// We touched this node
	onopen[fromNode] = true;
	touched[fromNode] = true;

	int depth = 0;
	int newTotal, newCost;

	// This is controlled by the npc moving. Some npcs can fly (move over impassables)
	// others can open doors
	ignoreDoors = false;
	ignoreMovableImpassables = false;
	int successors[8]; // List of successor nodes used in subsequent iterations. Never more than 8
	int successorCount; // Number of successors found

	while (openlist != -1) {
		if (++depth > maxDepth)
			break; // Break if we would exceed the maximum iteration count

		int bestnode = findBest(openlist);

		// Get adjacent nodes that we can walk to
		successorCount = getSuccessors(bestnode, pChar, successors);

		if (successorCount == 0) {
			break; // We've run into a situation where we'll never find a suitable successor
		}

		// Follow every possible successor
		for (i = 0; i < successorCount; ++i) {
			int successor = successors[i];

			if (touched[successor]) {
				continue; // If we worked on the node already, skip this part
			}

			// calculate the cost of the successor based on the currents node cost
			newCost = nodes[bestnode].cost + 1;
			newTotal = newCost + heuristic(successor % areaSize, (successor / areaSize) % areaSize, nodes[successor].z);

			// Always execute, !wasTouched was always true here
			// if ( !wasTouched || m_Nodes[newNode].total > newTotal )
			nodes[successor].parent = bestnode;
			nodes[successor].cost = newCost;
			nodes[successor].total = newTotal;
			addToChain(successor);

			// We found our target
			if (successor == toNode) {
				int pathCount = 0; // Stack allocation speed isn't a concern here anymore
				int parent = nodes[successor].parent;

				// Record the path in reverse order
				while (parent != -1) {
					path[pathCount++] = getDirection(parent % areaSize, (parent / areaSize) % areaSize, successor % areaSize, (successor / areaSize) % areaSize);
					successor = parent; // Track back
					parent = nodes[successor].parent;

					if (successor == fromNode) {
						break;
					}
				}

				int backtrack = 0;
				while (pathCount != 0) {
					result.append( path[--pathCount] );
				}
				return result; // Immediately return
			}
		}
	}

	return result; // Nothing found
}
Example #15
0
NodeControl* NodeGraphDisplay::getNodeControl(Node *node_ptr)
{
	int index = getNodeIndex(node_ptr);
	return (index < nodeControls.size()) ? nodeControls[index] : nullptr;
}
//this method runs the DV algorithm
//--------------------------------------------------------------------------------------------//
void Bellman_Ford(){
  initialize();


  int i,j,rc;
  int myIndex;
  i=0;
  j=0;
 // printTable();

 // printf("num of neig%d\n",routing_table->directNeighbors);
  threads=malloc(sizeof(pthread_t)*routing_table->directNeighbors*2);
  myIndex=getNodeIndex(routing_table->table_node->name);


  //creating thread for calculation
  //^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ //
  pthread_t recompute;
  rc=pthread_create(&recompute,NULL,(void*)recomputeDV,NULL);
  if(rc){
      printf("%s\n", strerror(errno));
      exit(0);
  }
  //^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ //


  //creating threads for sending
  //^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ //
  while(i<routing_table->directNeighbors){
      rc=pthread_create(&threads[j],NULL,(void*)rcvDV,routing_table->nodes[routing_table->directNeig[i]].name);
      if(rc){
          printf("%s\n", strerror(errno));
          exit(0);
      }
      j++;
      i++;
  }
  //^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ //


  //creating threads for receiving
  //^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ //
  i=0;
  while(i<routing_table->directNeighbors){
      //  if(routing_table->r_table[myIndex][i]!=999 &&i!=myIndex){

      //sending
      rc=pthread_create(&threads[j],NULL,(void*)sendDV,&routing_table->nodes[routing_table->directNeig[i]]);

      if(rc){
          printf("%s\n", strerror(errno));
          exit(0);
      }
      j++;
      i++;
  }
  //^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ //


  //Synchronizing the sending's ,receving's and recomputing's mutex and conditional variables
  //^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ //
  int sentOnce=0;
  //waiting for all the threads to be exist and go into wait mode
  while(numOfSentThreadExists<routing_table->directNeighbors||numOfReceivedThreadExists<routing_table->directNeighbors||isRecomputeExists==0);

  while(1){
      pthread_mutex_lock(&mutex);


      //waking all the sending threads.
      //^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ //
      if(sent==0 &&sentOnce==0 ){
      //    printf("Bellman_Ford():signal sent to convar1\n");
          sentOnce=1;
          for(i=0;i<routing_table->directNeighbors;i++){

              pthread_cond_signal(&convar1);
              pthread_mutex_unlock(&mutex);

          }
          pthread_mutex_lock(&mutex);
      }
      //^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ //


      //waking all the sending threads.
      //^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ //
//      if(sent==routing_table->directNeighbors){
//
////          printf("Bellman_Ford():signal sent to convar2\n");
// //         sent=-1;
////          for(i=0;i<routing_table->directNeighbors;i++){
////              pthread_cond_signal(&convar2);
////          }
////          pthread_mutex_unlock(&mutex);
////          pthread_mutex_lock(&mutex);
//      }
      //^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ //


      //^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ //
      //in the case which all of the other nodes sent 0 then finishing the algorithm
      if(zeroReceived>=routing_table->directNeighbors){
          received=-1;
          sent=-1;
    //      printf("Bellman_Ford():signal sent to convar1+2+3\n");
          for(i=0;i<routing_table->directNeighbors;i++){
              pthread_cond_signal(&convar1);
          }
//          for(i=0;i<routing_table->directNeighbors;i++){
//              pthread_cond_signal(&convar2);
//          }

          pthread_cond_signal(&convar3);
          pthread_mutex_unlock(&mutex);

          pthread_mutex_lock(&mutex);
      //    printf("Bellman_Ford():done=1\n");

          break;
      }
      //^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ //


      //^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ //
      //in the case which all neighbors's DV received ,waking the recomputing thread.
      if(received>=routing_table->directNeighbors&& sent>=routing_table->directNeighbors){

         // printf("Bellman_Ford():signal sent to convar3\n");
          received=-1;
          sent=-1;
          pthread_cond_signal(&convar3);
          pthread_mutex_unlock(&mutex);
          pthread_mutex_lock(&mutex);
      }
      //^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ //


      //^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ ^_^ //
      //reset all the global variables
      if(doneComputing==1){
          received=0;
          sent=0;
          sentOnce=0;
          doneComputing=0;
      }


      pthread_mutex_unlock(&mutex);
  }
 // printf("Bellman_Ford():outside main loop\n");

  pthread_mutex_unlock(&mutex);









  //joining all the threads-this means the main thread will wait until all of the threads will exist.
  pthread_join(recompute, NULL);
  for (i=0; i<routing_table->directNeighbors*2; i++) {
      pthread_join(threads[i], NULL);
  }



 // printTable();
 // printf("printing via\n\n\n");
//  for(i=0;i<routing_table->numOfNodes;i++)
//    printf("%d\t",routing_table->via[i]);
//  printf("\n\n\n");
  printFinalResualt();//printing resualt
//  printf("\n\n\n");
  clean();//cleaning all the dynamically allocated memory,

  exit(0);
}
Example #17
0
bool NodeGraphDisplay::nodeIsVisible(Node *node_ptr)
{
	int index = getNodeIndex(node_ptr);
	return (index >= 0) && nodeIsVisible(index);
}
Example #18
0
//-----------------------------------------------------------------------------
//
// VMotionTrack::getObjectSpeed();
// 
// Determine the Speed that an object must move at to travel over the segment
// length of the Path.
//
//-----------------------------------------------------------------------------
F32 VMotionEvent::getObjectSpeed( void )
{
    // Fetch Parent Track.
    VMotionTrack *track;
    if ( !getTrack( track ) )
    {
        // Invalid Track.
        return 0.f;
    }

    // Fetch Path & Reference Object.
    VTorque::PathObjectType  *path   = track->getPath();
    VTorque::SceneObjectType *object = getSceneObject();
    if ( !path || !object )
    {
        // Invalid Object(s).
        return 0.f;
    }

    // Fetch Node Index.
    const S32 &srcNodeIndex = getNodeIndex( ( isControllerPlayingForward() ) ? 0 : -1 );

    // Fetch the Next Event.
    VEvent *nextEvent = getNextEvent();

    // Valid Destination Node?
    if ( !isControllerLooping() && !nextEvent )
    {
        // No Next Node.
        return 0.f;
    }

    // Valid Next Node?
    if ( nextEvent )
    {
        // Fetch Segment Length & Duration.
        const F32 &length   = VTorque::getPathNodeLength( path, srcNodeIndex );
        const F32 &duration = mAbs( getTriggerTime() - nextEvent->getTriggerTime() );

        // Speed = Distance / Duration.
        return ( length / ( duration / 1000.f ) );
    }

    // Playing Forwards?
    if ( isControllerPlayingForward() )
    {
        // Fetch the First Event.
        VEvent *firstEvent = dynamic_cast<VEvent*>( track->getChild() );

        // Fetch Segment Length & Duration.
        const F32 &length   = VTorque::getPathNodeLength( path, srcNodeIndex );
        const F32 &duration = ( getControllerDuration() - getTriggerTime() ) + firstEvent->getTriggerTime();

        // Speed = Distance / Duration.
        return ( length / ( duration / 1000.f ) );
    }

    // Fetch the Last Event.
    VEvent *lastEvent = dynamic_cast<VEvent*>( track->getLastChild() );

    // Fetch Segment Length & Duration.
    const F32 &length   = VTorque::getPathNodeLength( path, srcNodeIndex );
    const F32 &duration = ( getControllerDuration() - lastEvent->getTriggerTime() ) + getTriggerTime();

    // Speed = Distance / Duration.
    return ( length / ( duration / 1000.f ) );
}
//this method sends DV to a router
//--------------------------------------------------------------------------------------------//
int sendDV(Node* node){

  //printf("sendDV():thread :%d created for %s\n",getTid(pthread_self()),node->name);
  //------opening TCP  socket--------------------------------------------------------------------------------//
  int socket_fd= socket(AF_INET,SOCK_STREAM,0);
  if(socket_fd<0){
      printf("%s\n", strerror(errno));
      return 0;
  }
  //--------------------------------------------------------------------------------------//

  //--------filling struct sockaddr_in gmail_server in the ip and the port of the server (from struct hostent* gmail_info)------------------------------------------------------------------------------//
  struct sockaddr_in neighbor;//this struct contains ip address and a port of the server.
  bzero(&neighbor,sizeof(neighbor));
  neighbor.sin_family=AF_INET;//AF_INIT means Internet doamin socket.
  neighbor.sin_port=htons(node->port+asciiSum(routing_table->table_node->name));//port 25=SMTP.
  neighbor.sin_addr.s_addr = inet_addr(node->ip);//converts char ip to s_addr.
  //--------------------------------------------------------------------------------------//
  int i=0;
  int con;
  while(i<numOfAttempts){
      //----connecting to to the server via above socket----------------------------------------------------------------------------------//
      con=connect(socket_fd,(struct sockaddr *)&neighbor,sizeof(neighbor));
      if(con<0)
        sleep(1);
      else
        break;
      i++;
  }
  if(con<0){
      printf("%s\n", strerror(errno));
      return 0;
  }

  //--------------------------------------------------------------------------------------//
  while(1)
    {
      pthread_mutex_lock(&mutex);
      numOfSentThreadExists++;
      if(zeroReceived>=routing_table->directNeighbors)
        break;
      pthread_cond_wait(&convar1,&mutex);
      if(zeroReceived>=routing_table->directNeighbors)
        break;
    //  printf("sendDV():  trying to send to:%s\n",node->name);

      int n=0;
      int j=0;
      if(changed==1)
        {
          //sending 1|dv.
          int* d_vector=(int*)malloc((1+routing_table->numOfNodes) *sizeof(int));
          d_vector[0]=1;
          for(j=1;j<routing_table->numOfNodes+1;j++)
            d_vector[j]=routing_table->r_table[getNodeIndex(routing_table->table_node->name)][j-1];
          n=write(socket_fd, d_vector, ((1+routing_table->numOfNodes) *sizeof(int)));
          free(d_vector);

          if(n<0){
           //   printf("%s\n", strerror(errno));
              return 0;
          }
      //    printf("sendDV():  DV sent to:%s\n",node->name);

        }


      else
        {
          //sending zero
          int zero=0;
          n=write(socket_fd, &zero, sizeof(int));

        //  printf("sendDV():  ZERO sent to:%s\n",node->name);

          if(n<0){
              printf("%s\n", strerror(errno));
              return 0;
          }
        }

      sent++;
      //--------------------------------------------------------------------------------------//

      //--------------------------------------------------------------------------------------//
      pthread_mutex_unlock(&mutex);

      //--------------------------------------------------------------------------------------//
      //sleep(1);
    }


  //closing socket
  int socket_close=close(socket_fd);
  if(socket_close==-1){
      printf("%s\n", strerror(errno));
      return 0;
  }
  //printf("sendDV():oudside main loop\n");
  pthread_mutex_unlock(&mutex);

  return 0;

  return 0;
}
//--------------------------------------------------------------------------------------------//
void* rcvDV(char* name){

  //printf("rcvDV():thread number:%d created for:%s\n",getTid(pthread_self()),name);
  //------opening TCP  socket--------------------------------------------------------------------------------//
  int socket_fd= socket(AF_INET,SOCK_STREAM,0);
  if(socket_fd<0){
      printf("%s\n", strerror(errno));
      return 0;
  }
  //--------------------------------------------------------------------------------------//

  //--------filling struct sockaddr_in  in the ip and the port of the server (from struct hostent* gmail_info)------------------------------------------------------------------------------//
  struct sockaddr_in myAddress;
  bzero(&myAddress,sizeof(myAddress));
  myAddress.sin_family=AF_INET;//AF_INIT means Internet doamin socket.
  myAddress.sin_port=htons(routing_table->table_node->port+asciiSum(name));//port 25=SMTP.
  myAddress.sin_addr.s_addr=inet_addr(routing_table->table_node->ip);
  //--------------------------------------------------------------------------------------//

  //--------------------------------------------------------------------------------------//
  ///binding the socket to the TCP port which it's listen to
  //in other words defining the new socket as the information of neighbor
  int bind_socket=bind(socket_fd,(struct sockaddr*)&myAddress,sizeof(myAddress));
  if(bind_socket==-1){
      printf("%s\n", strerror(errno));
      return 0;
  }

  //initiating listening and defining the max length of connection queue to only 5
  //connection
  int listen_socket=listen(socket_fd,routing_table->numOfNodes);
  if(listen_socket==-1){
      printf("%s\n", strerror(errno));
      return 0;
  }

  //accepting connection requests and delete them from the request queue
  //the client information is returned and placed by the function 'accept'
  //to the struct 'client_addr'
  //also the function returns the socket fd of the client
  struct sockaddr_in client_addr;
  socklen_t client_length=sizeof(client_addr);
  int client_socket_fd=accept(socket_fd,(struct sockaddr*)&client_addr,&client_length);
  if(client_socket_fd==-1){
      printf("%s\n", strerror(errno));
     // printTable();
      return 0;
  }




  while(1){

      //--------------------------------------------------------------------------------------//
      pthread_mutex_lock(&mutex);
      numOfReceivedThreadExists++;
      if(zeroReceived>=routing_table->directNeighbors)
        break;
      pthread_mutex_unlock(&mutex);

      //--------------------------------------------------------------------------------------//

     // printf("rcvDV():trying to receive from:%s\n",name);



      //-----receiving---------------------------------------------------------------------------------//

      int k=0;
      //-------writing the data to the server and printing it to the screen-------------------------------------------------------------------------------//
      int* dv=calloc(sizeof(int),routing_table->numOfNodes+1);
      int n=read(client_socket_fd, dv, ((1+routing_table->numOfNodes) *sizeof(int)));
      if(n<0){
          printf("%s\n", strerror(errno));
          return 0;
      }
      //--------------------------------------------------------------------------------------//
      pthread_mutex_lock(&mutex);
      if(received<=routing_table->directNeighbors){
      k=0;
      if(dv[0]==0)
        {
          //did get zero

          zeroReceived++;
        //  printf("rcvDV():ZERO received from:%s\n",name);

        }
      else
        {
          //did'nt get zero
          k=0;
          for(k=1;k<routing_table->numOfNodes+1;k++)
            routing_table->r_table[getNodeIndex(name)][k-1]=dv[k];
       //   printf("rcvDV():dv received from:%s\n",name);

        }
      received++;
      }
      pthread_mutex_unlock(&mutex);

      free(dv);



      //--------------------------------------------------------------------------------------//
      //sleep(1);

  }
  //printf("rcvDV():oudside main loop\n");

  //closing socket
  int socket_close=close(socket_fd);
  if(socket_close==-1){
      printf("%s\n", strerror(errno));
      return 0;
  }
  pthread_mutex_unlock(&mutex);
  return 0;
  return NULL;
}
Example #21
0
bool Structure::Graph::containsNode( QString nid )
{
	int i = getNodeIndex(nid);
	return (i >= 0) && (i < nodes.size());
}