Example #1
0
/* Generate solutionCandidates that will be solution's neighbourhood */
void generateNeighbourhood(Solution& baseSolution, std::vector<SolutionCandidate>& neighbourhood, const CitiesData& area, std::vector<TabuItem>& tabuList)
{
 	for (int i=0; i<neighbourhood.size(); i++)
 	{
		destroySolution(neighbourhood[i].solution);
			free(neighbourhood[i].modifiedRoutes);
	}
	neighbourhood.clear();


	int j=0;
	while (neighbourhood.size() < NEIGHBOURHOOD_SIZE && j<baseSolution.num_routes)
	{
		//find longest route in the solution and swap each of its cities with its neighbour
		Route longest = getLongestRouteIn(baseSolution, j);
		City neighbourCity;

		for (int i = 1; i< longest.num_cities-1; i++)
			{
				neighbourCity = getNeighbour(area, longest.cities[i]);
				SolutionCandidate candidate = swapCitiesIn(baseSolution, longest.cities[i], neighbourCity);
				neighbourhood.push_back(candidate);
			}
		Route shortest = getLongestRouteIn(baseSolution,baseSolution.num_routes-1-j);
		for (int i = 1; i< shortest.num_cities-1; i++)
		{
			neighbourCity = getNeighbour(area, shortest.cities[i]);
			SolutionCandidate candidate = swapCitiesIn(baseSolution, shortest.cities[i], neighbourCity);
			neighbourhood.push_back(candidate);
		}
		j++;
	}
}
Example #2
0
void Text2D::init( System* system )
{
	_renderer = system->getSubSystem<Renderer2D>("Renderer2D");
	_renderID = _renderer->addRenderCall<Text2D, &Text2D::renderCall>(this);
	_font2d = 	_renderer->getFont2D( _fontName );

	_attributes = (Attributes2D*)getNeighbour("Attributes2D");
}
Example #3
0
// {{{ handleRequest
int handleRequest(msg_t msg) {
	strncpy(ip(msg), ask(msg), IPLONG * sizeof(char));
	unsigned long int ipt = (unsigned long int)inet_addr(ask(msg));

	// TODO: Add unknown Neighbour to the list of neighbour and handle REEQUEST
	if(getNeighbour(ipt)==-1) {
		if (_verbose) fprintf (stderr, "======> Received a REQUEST from an unknown neighbour. <======\n");
		return 0;
	}

	if(last == -1) {
		if(state != IDLE) {
			if (next == -1) {
				next = getNeighbour(ipt);
				last = next;
				if (_verbose) fprintf (stdout, "Got a request, but expecting the TOKEN. Sending COMMIT to %d.\n", next);
				type(msg) = COMMIT;
				pos(msg) = position + 1;
				int j;
				for (j=0; j<TOLERANCE; memcpy(pred(msg)+j,predec+j,sizeof(struct sockaddr_in)), j++);
				if (sendMessageWithAdd(msg) == -1)
					return -1;
			}
		}
		else if(tokenPresent == 1) {
			if (_verbose) fprintf (stdout, "Sending TOKEN.\n");
			type(msg) = TOKEN;
			if(sendMessageWithAdd(msg) == -1){
				if (_verbose) fprintf (stderr, "======> Error while sending message <======\n");
				return -1;
			}
			tokenPresent = 0;
			position = -1;
		}
	}
	else {
		type(msg) = REQUEST;
		if(sendMessage(last, msg) == -1)
			return -1;
	}

	last = getNeighbour(ipt);
	if (_verbose) fprintf (stdout, "New last after receiving request : %d. \n", last);

	return 0;
}
void TabuSearchClass::BeginSolve() {
	int n;
	bestTabuSearchValue = 0;
	number4Gene = 0;
	initGene();
	copyGene(initNode, bestNode);
	curtEvaluationValue = Evaluat(initNode);
	bestEvauValue = curtEvaluationValue;
	bestNodeNumber = G.chosNum;
	while (number4Gene < MAX_GENERATION) {
		n = 0;
		while (n < neighbourNum) {
			getNeighbour(initNode, tempNode);
			tempEvaluationValue = Evaluat(tempNode);
			if (isTabuTable(tempNode) != 0)
					{
				if (tempEvaluationValue < bestEvauValue) {
					copyGene(tempNode, currenttNode);
					curtEvaluationValue = tempEvaluationValue;
				}

				n++;
			} else if (isTabuTable(tempNode) == 0) {
				if (G.Nnum < 500) {
					if (n == 0) {
						if (tempEvaluationValue
								<= (int) curtEvaluationValue * 1.0005) {
							copyGene(tempNode, currenttNode);
							curtEvaluationValue = tempEvaluationValue;
							n++;
						}
						continue;
					}
				}
				if (tempEvaluationValue < curtEvaluationValue) {
					copyGene(tempNode, currenttNode);
					curtEvaluationValue = tempEvaluationValue;

				}
				n++;
			}
		}
		if (curtEvaluationValue < bestEvauValue) {
			bestTabuSearchValue = number4Gene;
			copyGene(currenttNode, bestNode);
			bestEvauValue = curtEvaluationValue;
			bestNodeNumber = G.chosNum;
		}

		if ((int) clock() / (CLOCKS_PER_SEC /*/ 1000*/) >= 87)
			break;
		number4Gene++;
		copyGene(currenttNode, initNode);
		TabuTableFlush(currenttNode);
	}
}
Example #5
0
// {{{ handleRequest
int handleRequest(msg_t msg) {
	strncpy(ip(msg), ask(msg), IPLONG * sizeof(char));
	unsigned long int ipt = (unsigned long int)inet_addr(ask(msg));

	// TODO: Add unknown Neighbour to the list of neighbour and handle REEQUEST
	if(getNeighbour(ipt)==-1) {
		fprintf (stderr, "======> Received a REQUEST from an unknown neighbour. <======\n");
		return 0;
	}

	if(last == -1) {
		if(state != IDLE) {
			if (next == -1) {
				next = getNeighbour(ipt);
				last = next;
				fprintf (stdout, "Got a request, but expecting the TOKEN.\n");
				type(msg) = COMMIT;
				if (sendMessageWithAdd(msg) == -1)
					return -1;
			}
		}
		else if(tokenPresent == 1) {
			fprintf (stdout, "Sending TOKEN.\n");
			type(msg) = TOKEN;
			if(sendMessageWithAdd(msg) == -1){
				fprintf (stderr, "======> Error while sending message <======\n");
				return -1;
			}
			tokenPresent = 0;
		}
	}
	else {
		type(msg) = REQUEST;
		if(sendMessage(last, msg) == -1)
			return -1;
	}

	last = getNeighbour(ipt);
	fprintf (stdout, "New last after receiving request : %d. \n", last);

	return 0;
}
Foam::fvPatchField<Foam::scalar> Foam::myHeatFluxFvPatchVectorField::interpolateTheta_i
(
	const vectorField& normals
)
{

	const scalar numPatchCells = patch().lookupPatchField<volScalarField, scalar>("Theta").size();		// Anzahl Randzellen

	// Feld zum Speichern der Werte von Theta_i
	const volScalarField& iTheta = db().lookupObject<volScalarField>("Theta");
 	const label patchID = patch().boundaryMesh().findPatchID(patch().name()); 
 	fvPatchField<scalar> Theta_i = iTheta.boundaryField()[patchID]; 

	const fvMesh& mesh = iTheta.mesh();  							// Mesh
	const labelListList& cellNeighbours = mesh.cellCells();	// Nachbarn jeder Zelle des Mesh
	const vectorField& cellCenters = mesh.C();					// Zellmittelpunkte
	//const vectorField& patchNormals = patch().nf();			// NormalenVektoren des Randes
	const vectorField& patchFaceCenters = patch().Cf();		// Feld mit Zellmittelpunkten der Randzellen
	const labelList& patchCellLabels = patch().faceCells();	// Label der Randzellen

	label patchCell, neighbour;
	scalar delta1 = 0, delta2 = 0;
	scalar Theta1 = 0, Theta2 = 0;
	
	for(int i=0; i<numPatchCells; i++){

		vector direction = (-1) * normals[i];
		patchCell = patchCellLabels[i];

		neighbour = getNeighbour( direction,
										  patchCell,
										  cellCenters,
										  cellNeighbours[patchCell] );
		//Info << "patchFaceCenter: " << patchFaceCenters[i] << endl;
		//Info << "cellCenter:" << cellCenters[patchCell] << endl;
		//Info << "cellCenter:" << cellCenters[neighbour] << endl;
		delta1 = mag(patchFaceCenters[i] - cellCenters[patchCell]);
		delta2 = mag(cellCenters[patchCell] - cellCenters[neighbour]);
		Theta1 = iTheta[patchCell];
		Theta2 = iTheta[neighbour];
		//if (patchCell == numPatchCells){ 
			//Info << "patchCell: " << patchCell << "\t neighbour: " << neighbour << endl;
			//Info << "Theta1: " << Theta1 << "\t Theta2: " << Theta2 << endl;
			//Info << "delta1: " << delta1 << "\t delta2: " << delta2 << endl;
		//}

		// Lineare Interpolation
		Theta_i[i] = Theta1 + delta1 * ( Theta1 - Theta2 ) / delta2;
	}

	return Theta_i;
	
}
Example #7
0
bool Crossroad::build(BuildStatus status) {
	switch (status) {
		case FREE:
			constructed = FREE;
			break;
		case ROAD:
			if (constructed == FREE) {
				constructed = ROAD;
				return true;
			}
			break;
		case BUILDING:
			constructed = BUILDING;
			break;
		case FLAG:
			if (getNeighbour(Directions::EAST)->constructed != FLAG &&
				getNeighbour(Directions::WEST)->constructed != FLAG &&
				getNeighbour(Directions::SOUTH_EAST)->constructed != FLAG &&
				getNeighbour(Directions::SOUTH_WEST)->constructed != FLAG &&
				getNeighbour(Directions::NORTH_EAST)->constructed != FLAG &&
				getNeighbour(Directions::NORTH_WEST)->constructed != FLAG &&
				(constructed == FREE || constructed == FLAG || constructed == ROAD)) 
			{
				constructed = FLAG;
				return true;
			}
			else
				return false;
			break;
	}
	return false;
}
Example #8
0
Node* Node::getNeighbour(int _dir, int _num)
{
	if (_num == 0 && (int)edges.size() > _dir)
	{
		return edges[_dir];
	}
	else if ((int)edges.size() <= _dir)
	{
		return NULL;
	}
	else
	{
		_num--;
		getNeighbour(_dir, _num);
	}
	return NULL;
}
Example #9
0
int TEST_getNeighbour()
{
  int x=5, y=5;
  direction dir=LEFT;
  cell grid[H][W], *testCell;
  initGrid(grid);
  fillGrid(grid);
  testCell=getNeighbour(x, y, dir, grid);
  if(testCell->background!=grid[y][x-1].background){
    printf("%25s %s\n",__func__, FAIL );
    return ERROR;
  }
  else{
    printf("%25s %s\n",__func__, PASS );
    return SUCCESS;
  }
}
Example #10
0
void generateLandscape(Node * c, long long k, char required, char fill)
{
    unsigned char directions[4] = {EDGE_CELL_RIGHT, EDGE_CELL_LEFT,
        EDGE_CELL_BOTTOM, EDGE_CELL_TOP};
    int tries = 4;
    while(k >= 0 && tries >= 0)
    {
        tries--;
        Node * neighbour = getNeighbour(c, directions[rand() % 4]);

        if( ((Cell *) neighbour -> data) -> territory == required )
        {
            k--;
            ( (Cell *) neighbour -> data) -> territory = fill;
            generateLandscape(neighbour, k, required, fill);
        }
    }
}
Example #11
0
void GameOfLife::GoLstep(){
  // Run 1 simulation step of the GoL algorithm
  
  // Loop through all cells and determine their next state
  for(uint8_t y=0; y!=_rows; ++y){
    for(uint8_t x=0; x!=_cols; ++x){
      // First reset the next array
      next[xy2i(x,y)] = false;
      // Then calculate number of neighbours (n)
      uint8_t n = 0;
      // loop through all neighbouring cells
      for(int8_t dy=-1; dy!=2; ++dy){
        for(int8_t dx=-1; dx!=2; ++dx){
          if( dx==0 && dy==0 ) continue; //do not count itself
          n += getNeighbour((int8_t)y+dy,(int8_t)x+dx);
        }
      }
      // Make a decision based on number of alive neighbours
      if(n==3){
        // keeps living or is born next round
        next[xy2i(x,y)] = true;
      } else if(alive[xy2i(x,y)] && n==2){
        //stays alive with 2 neighbours
        next[xy2i(x,y)] = true;
      }
      // All other cases: die or stay dead
    }
  }
  // Try to find a stall, or period-1 oscillation
  boolean same_prev = true;
  boolean same_alive = true;
  for(uint8_t i=0; i!=_num_leds; ++i){
    if(next[i] != prev[i]) same_prev = false;
    if(next[i] != alive[i]) same_alive = false;
  }
  if((same_prev || same_alive) && !seedFlag){
    seedFlag = true;
    seedTime = millis();
  }
  
  // Now copy current to prev and next to current (alive)
  memcpy(prev,alive,_num_leds * sizeof(bool));
  memcpy(alive,next,_num_leds * sizeof(bool));
}
Example #12
0
//{{{ handleCommit
int handleCommit (msg_t msg) {
	unsigned long int ipa = (unsigned long int)inet_addr(ips(msg));
	pthread_t thread_id;

	if (_verbose) fprintf (stdout, "Got a COMMIT, creating a thread to verify validity of predecessor\n");

	if(!getNeighbour(ipa))
		return 0;

	position = pos(msg);
	last = -1;
	int i;
	if (_verbose) fprintf (stdout,"Copy the predecessor adress contained in received COMMIT.\n");
	for (i=0; i<TOLERANCE; predec[i+1] = pred(msg)[i], i++);

	inet_aton(ips(msg),&(predec[0].sin_addr));

	if(pthread_create(&thread_id, NULL, (void*)(checkNeighbour), (void*)predec) != 0)
		if (_verbose) fprintf(stderr, "Thread creation failure.\n");


	return 0;
}
Example #13
0
/*!
 ***********************************************************************
 * \return
 *    best SAD
 ***********************************************************************
 */
int intrapred_luma_16x16(struct img_par *img, //!< image parameters
                         int predmode)        //!< prediction mode
{
  int s0=0,s1,s2;

  int i,j;

  int ih,iv;
  int ib,ic,iaa;

  byte **imgY=dec_picture->imgY;

  int mb_nr=img->current_mb_nr;
  //printf("******* %d ******** %d\n", img->current_mb_nr, FPindex);

  PixelPos up;          //!< pixel position p(0,-1)
  PixelPos left[17];    //!< pixel positions p(-1, -1..15)

  int up_avail, left_avail, left_up_avail;

  s1=s2=0;

  for (i=0;i<17;i++)
  {
    getNeighbour(mb_nr, -1 ,  i-1 , 1, &left[i]);
  }
  
  getNeighbour(mb_nr, 0     ,  -1 , 1, &up);

  if (!img->constrained_intra_pred_flag)
  {
    up_avail   = up.available;
    left_avail = left[1].available;
    left_up_avail = left[0].available;
  }
  else
  {
    up_avail      = up.available ? img->intra_block[up.mb_addr] : 0;
    for (i=1, left_avail=1; i<17;i++)
      left_avail  &= left[i].available ? img->intra_block[left[i].mb_addr]: 0;
    left_up_avail = left[0].available ? img->intra_block[left[0].mb_addr]: 0;
  }

  switch (predmode)
  {
  case VERT_PRED_16:                       // vertical prediction from block above
    if (!up_avail)
      error ("invalid 16x16 intra pred Mode VERT_PRED_16",500);
    for(j=0;j<MB_BLOCK_SIZE;j++)
      for(i=0;i<MB_BLOCK_SIZE;i++)
        img->mpr[i][j]=imgY[up.pos_y][up.pos_x+i];// store predicted 16x16 block
    break;

  case HOR_PRED_16:                        // horisontal prediction from left block
    if (!left_avail)
      error ("invalid 16x16 intra pred Mode VERT_PRED_16",500);
    for(j=0;j<MB_BLOCK_SIZE;j++)
      for(i=0;i<MB_BLOCK_SIZE;i++)
        img->mpr[i][j]=imgY[left[j+1].pos_y][left[j+1].pos_x]; // store predicted 16x16 block
    break;

  case DC_PRED_16:                         // DC prediction
    s1=s2=0;
    for (i=0; i < MB_BLOCK_SIZE; i++)
    {
      if (up_avail)
        s1 += imgY[up.pos_y][up.pos_x+i];    // sum hor pix
      if (left_avail)
        s2 += imgY[left[i+1].pos_y][left[i+1].pos_x];    // sum vert pix
    }
    if (up_avail && left_avail)
      s0=(s1+s2+16)>>5;       // no edge
    if (!up_avail && left_avail)
      s0=(s2+8)>>4;              // upper edge
    if (up_avail && !left_avail)
      s0=(s1+8)>>4;              // left edge
    if (!up_avail && !left_avail)
      s0=128;                            // top left corner, nothing to predict from
    for(i=0;i<MB_BLOCK_SIZE;i++)
      for(j=0;j<MB_BLOCK_SIZE;j++)
      {
        img->mpr[i][j]=s0;
      }
    break;
  case PLANE_16:// 16 bit integer plan pred
    if (!up_avail || !left_up_avail  || !left_avail)
      error ("invalid 16x16 intra pred Mode PLANE_16",500);

    ih=0;
    iv=0;
    for (i=1;i<9;i++)
    {
      if (i<8)
        ih += i*(imgY[up.pos_y][up.pos_x+7+i] - imgY[up.pos_y][up.pos_x+7-i]);
      else
        ih += i*(imgY[up.pos_y][up.pos_x+7+i] - imgY[left[0].pos_y][left[0].pos_x]);

      iv += i*(imgY[left[8+i].pos_y][left[8+i].pos_x] - imgY[left[8-i].pos_y][left[8-i].pos_x]);
    }
    ib=(5*ih+32)>>6;
    ic=(5*iv+32)>>6;

    iaa=16*(imgY[up.pos_y][up.pos_x+15]+imgY[left[16].pos_y][left[16].pos_x]);
    for (j=0;j< MB_BLOCK_SIZE;j++)
    {
      for (i=0;i< MB_BLOCK_SIZE;i++)
      {
        img->mpr[i][j]=max(0,min((iaa+(i-7)*ib +(j-7)*ic + 16)>>5,255));
      }
    }// store plane prediction
    break;

  default:
    {                                    // indication of fault in bitstream,exit
      printf("illegal 16x16 intra prediction mode input: %d\n",predmode);
      return SEARCH_SYNC;
    }
  }

  return DECODING_OK;
}
Example #14
0
//{{{ site_failure
void site_failure(int sig) {
	if (_verbose) fprintf (stderr, "/* FAILURE OF A SITE SPOTTED */\n");
	int i=0;
	int sortie = 0;
	msg_t msg;
	time_t timeStart, timeCur;

		pthread_mutex_lock(&mut_check);
		if (check)
			check = 0;
		pthread_mutex_unlock(&mut_check);

	int flags = fcntl(this_site.sdRecv, F_GETFL);
	int flags2 = flags | O_NONBLOCK;
	fcntl(this_site.sdRecv, F_SETFL, flags2);

	// Sends ARE_YOU_ALIVE to other pred
	if (_verbose) fprintf (stdout, "Checking predecessor validity\n");
	for (i=1; i<TOLERANCE+1; i++) {
		if (!strcmp ("0.0.0.0", inet_ntoa(predec[i].sin_addr))) {
			if (_verbose) fprintf (stdout, "Bad ip address\n");
			continue;
		}
		type(msg) = ARE_YOU_ALIVE;
		char *tmp = inet_ntoa(predec[i].sin_addr);
		strncpy (ip(msg), tmp, IPLONG *sizeof(char));
		unsigned long int ipa = (unsigned long int) inet_addr(ip(msg));
		sendMessageWithAdd(msg);

		pthread_mutex_lock(&mut_check);
		if (check)
			check = 0;
		pthread_mutex_unlock(&mut_check);

		timeStart = time(&timeStart);
		timeCur = time(&timeCur);

		while(timeCur - timeStart < (2*TMESG)) {
			timeCur = time(&timeCur);
			memset (&msg, 0, SIZE);

			if(recvMessage(&msg, NULL) == -1) 
				continue;

			// Receive I_AM_ALIVE --> Connection
			if (_verbose) fprintf (stdout, "Received I_AM_ALIVE\n");
			if (type(msg) == I_AM_ALIVE && !isMe(ips(msg))) {
				handleIAmAlive(msg);
				type(msg) = CONNECTION;
				strncpy(ip(msg), ips(msg), IPLONG * sizeof(char));
				sendMessageWithAdd(msg);
				if (_verbose) fprintf (stdout, "Asking for connection\n");
				last = getNeighbour(ipa);
				if (_verbose) fprintf (stdout, "New last after receiving I_AM_ALIVE message : %d\n", last);
				state = IDLE;
				critSectionRequest();
				sortie++;
				break;
			}
			else if (type(msg) == REQUEST) {}
			else
				handleMessage(msg);
		}
	}

	// No pred is alive, broadcast SEARCH_PREV
	fcntl(this_site.sdRecv, F_SETFL, flags);

	if (_verbose) fprintf (stdout, "No alive predecessor found, looking for other sites\n");
	if (!sortie) {
		msg_t min;

		type(msg) = SEARCH_PREV;
		pos(msg) = position;
		if (_verbose) fprintf (stdout, "Broadcasting SEARCH_PREV.\n");
		broadcast(msg);

		fcntl(this_site.sdRecv, F_SETFL, flags2);

		timeStart = time(&timeStart);
		timeCur = time(&timeCur);

		// Wait for ACK_SEARCH_PREV
		while(timeCur - timeStart < (2*TMESG)) {
			timeCur = time(&timeCur);
			memset (&msg, 0, SIZE);

			if(recvMessage(&msg, NULL) == -1) 
				continue;

			pos(min) = -1;
			if (type(msg) == ACK_SEARCH_PREV) {
				if (pos(min) == -1)
					memcpy (&min, &msg, SIZE);
				else if (pos(min) < pos(msg))
					memcpy (&min, &msg, SIZE);
				if (_verbose) fprintf (stdout, "Got an answer.\n");
			}
			else if (type(msg) == REQUEST) {}
			else
				handleMessage(msg);
		}

		fcntl(this_site.sdRecv, F_SETFL, flags);

		// No answers, regenerate the TOKEN
		if (pos(min) == -1) {
			if (_verbose) fprintf (stdout, "No answers, regenerating TOKEN\n");
			tokenPresent = 1;
			last = next;
			takeCriticalSection();
			sortie ++;
		}

		// Got an answer, ask for connection
		if (!sortie) {
			if (_verbose) fprintf (stdout, "Asking for connection\n");
			type(msg) = CONNECTION;
			strncpy(ip(msg), ips(min), IPLONG * sizeof(char));
			last = getNeighbour((unsigned long int)inet_addr(ips(min)));
			sendMessageWithAdd(msg);
			state = IDLE;
			critSectionRequest();
		}
	}
}
Example #15
0
// {{{ critSectionRequest
// Ask for critical section
int critSectionRequest() {
	msg_t msg;
	type(msg) = REQUEST;
	char *ip_tmp = inet_ntoa(this_site.neighbours[0].sin_addr);
	strncpy (ask(msg), ip_tmp, IPLONG);

	// If already in SC just return -1
	if (state != IDLE) {
		if (_verbose) fprintf (stderr,"Already in critical section.\n");
		return -1;
	}
	state = WAITING;

	// Owns Token ?
	if(tokenPresent) 
		return takeCriticalSection();
	// Sends request to last
	else if(last != -1) {
		// Get ip of last
		char *tmpter = getIPstrFromNb (last);
		if (_verbose) fprintf (stdout, "Last is %d, sending it a request.\n", last);
		strncpy(ip(msg), tmpter, IPLONG);
		free (tmpter);

		strncpy (ask(msg), inet_ntoa(this_site.neighbours[0].sin_addr), IPLONG);

		if(sendMessageWithAdd(msg) == -1){
			if (_verbose) fprintf (stderr, "======> Sending request failure... <======\n");
			return -1;
		}

		// Arms a timer
		time_t timeStart, timeCur;
		int flags = fcntl(this_site.sdRecv, F_GETFL);
		int flags2 = flags | O_NONBLOCK;
		fcntl(this_site.sdRecv, F_SETFL, flags2);

		timeStart = time(&timeStart);
		timeCur = time(&timeCur);

		// Wait for an answer
		if (_verbose) fprintf (stdout, "Waiting for COMMIT.\n");
		while(timeCur - timeStart < (2*TMESG)) {
			timeCur = time(&timeCur);

			if(recvMessage(&msg, NULL) == -1) 
				continue;

			if (type(msg) == COMMIT)
				return handleCommit(msg);
			else {
				// TODO: Work on reaction when receiving request while waiting commit
				if (type(msg) == REQUEST) {
					if (_verbose) fprintf (stdout, "Received a REQUEST instead of a COMMIT.\n");
				}
				else if (type(msg) == TOKEN){
					last = -1;
					return handleToken(msg);
				}
				else
					handleMessage(msg);
			}
		}

		// If receive no answers
		if (_verbose) fprintf (stdout, "I didn't get any COMMIT, looking for the queue...\n");
		fcntl(this_site.sdRecv, F_SETFL, flags);

		memset (&msg, 0, SIZE);
		type(msg) = SEARCH_QUEUE;
		nb_acc(msg) = acces;
		// Broadcast Search_Queue
		if (_verbose) fprintf (stdout, "Broadcasting SEARCH_QUEUE.\n");
		broadcast(msg);

		msg_t max;
		pos(max) = -1;

		fcntl(this_site.sdRecv, F_SETFL, flags2);

		timeStart = time(&timeStart);
		timeCur = time(&timeCur);

		// Wait for ACK_SEARCH_QUEUE
		if (_verbose) fprintf (stdout, "Expecting ACK_SEARCH_QUEUE.\n");
		while(timeCur - timeStart < 2*TMESG) {
			timeCur = time(&timeCur);
			memset (&msg, 0, SIZE);

			if(recvMessage(&msg, NULL) == -1) 
				continue;

			switch(type(msg)) {
				case ACK_SEARCH_QUEUE:
					if (_verbose) fprintf (stdout, "Got an ACK_SEARCH_QUEUE.\n");
					// Save greatest position in the queue
					if (pos(msg) > pos(max)) {
						if (_verbose) fprintf (stdout, "New position in QUEUE : %d.\n", pos(msg));
						memcpy(&max, &msg, SIZE);
					}
					break;
					// Another site discovers the failure
				case SEARCH_QUEUE:
					if (isMe(ips(msg)))
						continue;
					if (_verbose) fprintf (stdout, "Another site discovered the failure.\n");
					// The other site hasn't priority, just continue
					if (nb_acc(msg) > acces) 
						continue;
					// Both of sites have the same numbers of access, defines priority with ip
					if (nb_acc(msg) == acces) {
						char *ip_pers = inet_ntoa(this_site.neighbours[0].sin_addr);
						if (strcmp(ip_pers, ips(msg)) <= 0)
							continue;
					}
					// If the other has the priority, just change last and ask it for CS
					unsigned long int ipa = (unsigned long int) inet_addr(ips(msg));
					last = getNeighbour(ipa);
					if (_verbose) fprintf (stdout, "I don't have priority, changing my last (%d) and asking for CS again.\n", last);
					state = IDLE;
					return critSectionRequest();
					// TODO: Request processing
				case REQUEST:
					break;
				default:
					handleMessage(msg);
					break;
			}
		}

		if (_verbose) fprintf (stdout, "Waiting time passed.\n");

		fcntl(this_site.sdRecv, F_SETFL, flags);

		// No other site in the queue, juste regenerate TOKEN
		if (pos(max) < 0) {
			if (_verbose) fprintf (stdout, "No other sites in the queue, regenerate TOKEN (last = next)\n");
			last = next;
			tokenPresent = 1;
			takeCriticalSection();
		}
		else {
			// Ask for connection to the site with the highest position
			unsigned long int ipa = (unsigned long int) inet_addr(ips(max));
			last = getNeighbour(ipa);
			if (_verbose) fprintf (stdout, "Ask for Connection, new last = %d\n", last);
			strncpy(ip(msg), ips(max),IPLONG *sizeof(char));
			if (next(max)) {
				type(msg) = CONNECTION;
				if (sendMessageWithAdd(msg) == -1)
					return -1;
			}
			state = IDLE;
			critSectionRequest();
		}
	}
	else
		if (_verbose) fprintf (stderr, "======> Last = -1, but don't have TOKEN <======\n");
	return 0;
}
Example #16
0
int main(void)
{

FILE *f;
int N;
double T,Euu,Edd,Edu,conc;
f=fopen("input.dat","r");
fscanf(f,"%d",&N);
fscanf(f,"%le",&conc);
fscanf(f,"%le",&T);
fscanf(f,"%le",&Euu);
fscanf(f,"%le",&Edd);
fscanf(f,"%le",&Edu);

fclose(f);

int *comp;
comp=(int*)malloc(N*N*sizeof(int));

int i,j;

const gsl_rng_type *t;
gsl_rng *r;
gsl_rng_env_setup();
t=gsl_rng_default;
r=gsl_rng_alloc(t);

double u;

//initialisation of the matrix
//print to file
f=fopen("initialProfile.dat","w");
for(i=0;i<N;i++)
{
	for(j=0;j<N;j++)
	{
		u=gsl_rng_uniform(r);
		if(u<conc)
		{
			comp[j+N*i]=1;
		}
		else
		{
			comp[j+N*i]=-1;
		}
		fprintf(f,"%d\t",comp[j+N*i]);
	}
	fprintf(f,"\n");

}

fclose(f);

int k,l,k1,k2;
double Ei,Ef,delE;

//main evolution loop
for(k=0;k<N*N;k++)
{
	//choose random cell
	u=gsl_rng_uniform(r);
	i=(int)(u*1e4)%N;

	u=gsl_rng_uniform(r);
	j=(int)(u*1e4)%N;

	//find Ei
	Ei=0;
	for(l=1;l<=8;l++)
	{
		getNeighbour(i,j,N,l,&k1,&k2);
		if(comp[j+N*i]!=comp[k2+N*k1])
		{
			Ei+=Edu;
		}
		else
		{
			if(comp[j+N*i]==1)Ei+=Euu;
			else Ei+=Edd;
		}
	}

	//flip state
	comp[j+N*i]*=-1;

	//find Ef
	Ef=0;
	for(l=1;l<=8;l++)
	{
		getNeighbour(i,j,N,l,&k1,&k2);
		if(comp[j+N*i]!=comp[k2+N*k1])
		{
			Ef+=Edu;
		}
		else
		{
			if(comp[j+N*i]==1)Ef+=Euu;
			else Ef+=Edd;
		}
	}

	delE=Ef-Ei;

	if(delE>0)
	{
		u=gsl_rng_uniform(r);
		double p=exp(-delE/T);
		if(p<=u)
		{
			//flip state
			comp[j+N*i]*=-1;
		}
	}

}

//print to file
f=fopen("finalProfile.dat","w");
for(i=0;i<N;i++)
{
	for(j=0;j<N;j++)
	{
		fprintf(f,"%d\t",comp[j+N*i]);
	}
	fprintf(f,"\n");
}
fclose(f);

free(comp);
gsl_rng_free(r);
}
Example #17
0
std::vector<PieceMove> CheckersGame::moves(){
    std::vector<PieceMove> ret;
    
    //find any player coin to be kinged..
    for (int i=0; i<8; i++){
        //check the top row, 0th row
        if (curState[i] == 'P' && prevState[i] == 'p'){
            PieceMove pOut, pIn;
            pOut.piece = 'p';
            pOut.r1 = 0;
            pOut.c1 = i;
            pOut.r2 = -1;
            pOut.c2 = -1;
            pOut.description = "Player kinging - out";
            ret.push_back(pOut);
            
            pOut.piece = 'P';
            pOut.r1 = -1;
            pOut.c1 = -1;
            pOut.r2 = 0;
            pOut.c2 = i;
            pOut.description = "Player kinging - in";
            ret.push_back(pIn);
            break;
        }
    }
    
    //find the computer-coin that has changed
    int coin_initial_r=-1,coin_initial_c=-1;
    int coin_final_r=-1,coin_final_c=-1;
    char coin_initial;
    
    //find coin that disappeared..
    for (int i=0; i<64; i++){
        if (curState[i] == '.' && (prevState[i] == 'c' || prevState[i] == 'C')){
            coin_initial = prevState[i];
            coin_initial_r = i/8;
            coin_initial_c = i%8;
            break;
        }
    }
    if (coin_initial_r == -1 && coin_initial_c == -1)
        return ret;
    
    //find coin that appeared..
    for (int i=0; i<64; i++){
        if (prevState[i] == '.' && (curState[i] == 'c' || curState[i] == 'C')){
            coin_final_r = i/8;
            coin_final_c = i%8;
            break;
        }
    }
    if (coin_final_r == -1 && coin_final_c == -1)
        return ret;
    
    int temp_r, temp_c;
    while (coin_final_c != coin_initial_c && coin_final_r != coin_initial_r){
        //Non-Jump move?
        if (std::abs(coin_final_c - coin_initial_c) == 1 && 
                std::abs(coin_final_r - coin_initial_r) == 1){
            PieceMove p;
            p.r1 = coin_initial_r;
            p.c1 = coin_initial_c;
            p.r2 = coin_final_r;
            p.c2 = coin_final_c;
            p.piece = coin_initial;
            p.description = "Piece move";
            ret.push_back(p);
            coin_initial_r = coin_final_r;
            coin_initial_c = coin_final_c;
        }else{
            PieceMove pOut, pMove;
            int mid_r, mid_c, jump_r, jump_c;
            bool found = false;
            //check north-west
            Neighbour array[] = {NORTH_WEST, NORTH_EAST, SOUTH_EAST, SOUTH_WEST};
            
            for (int i=0; i<4 && !found; i++){
                if (getNeighbour(array[i], coin_initial_r, coin_initial_c, temp_r, temp_c)
                        && prevState[temp_r*8 + temp_c] != curState[temp_r*8 + temp_c]){
                    mid_r = temp_r;
                    mid_c = temp_c;
                    if (getNeighbour(array[i], temp_r,temp_c, temp_r, temp_c)){
                        jump_c = temp_c;
                        jump_r = temp_r;
                        found = true;
                    }
                }
            }
                                
            pOut.r1 = mid_r;
            pOut.c1 = mid_c;
            pOut.r2 = -1;
            pOut.piece = prevState[mid_r*8 + mid_c];
            pOut.c2 = -1;
            pOut.description = "Piece capture";
            ret.push_back(pOut);
            
            pMove.piece = coin_initial;
            pMove.r1 = coin_initial_r;
            pMove.c1 = coin_initial_c;
            pMove.r2 = jump_r;
            pMove.c2 = jump_c;
            pMove.description = "Piece Move";
            ret.push_back(pMove);
            
            coin_initial_c = jump_c;
            coin_initial_r = jump_r;
        }
        //check for kinging of piece on initial variables..
        //check the bottom row, 7th row
        if (coin_initial_r == 7 && coin_initial == 'c'){
            PieceMove pOut, pIn;
            pOut.piece = 'c';
            pOut.r1 = 7;
            pOut.c1 = coin_initial_c;
            pOut.r2 = -1;
            pOut.c2 = -1;
            pOut.description = "Computer kinging - out";
            ret.push_back(pOut);
            
            pOut.piece = 'C';
            pOut.r1 = -1;
            pOut.c1 = -1;
            pOut.r2 = 7;
            pOut.c2 = coin_initial_c;
            pOut.description = "Computer kinging - in";
            ret.push_back(pIn);
            
            coin_initial = 'C';
        }
    }
    return ret;        
}
Example #18
0
PolygonChangeData
BreakableMesh::breakMesh(int init, PointSegment crack, bool initialCrackTip, UniqueList<Pair<int>> &newPoints,
                         std::vector<int> previous, std::vector<int> &createdPolygonIndexes, Polygon &mergedPolygon) {
    std::vector<Polygon> oldPolygons;
    std::vector<Polygon> newPolygons;

    SimplePolygonMerger merger;
    int last = previous.size()==0? -1: (previous[0]==init? previous[1] : previous[0]);
    NeighbourInfo n1 = getNeighbour(init, crack, previous);
    bool firstTime = true;
    Polygon merged;


    if(n1.neighbour<0){
        //If the crack is in one element, return the same element
        return PolygonChangeData(oldPolygons, newPolygons);
    }

    if(initialCrackTip){
        IndexSegment container_edge = this->getPolygon(init).containerEdge(getPoints().getList(), crack.getFirst());
        NeighbourInfo n0 = NeighbourInfo(init, container_edge,crack.getFirst() ,false);
        n0.isVertex = container_edge.isEndPoint(crack.getFirst(), this->points.getList());

        breakPolygons(n0, n1, -1, oldPolygons, newPolygons,
                      newPoints);
        last = this->polygons.size() - 1;
    }


    bool oneLastIteration = false;

    while(true){
        Polygon& poly1 = getPolygon(n1.neighbour);

        if(poly1.containsPoint(this->points.getList(), crack.getSecond())){
            if(poly1.inEdges(this->points.getList(), crack.getSecond())){
                if(!oneLastIteration){
                    oneLastIteration = true;
                }
            }else{
                mergedPolygon = merged;
                return PolygonChangeData(oldPolygons, newPolygons);
            }
        }

        if(firstTime){
            merged = getPolygon(n1.neighbour);
            firstTime = false;
        }else{
            merged = merger.mergePolygons(merged, this->polygons[n1.neighbour], this->points.getList());
        }

        std::vector<int> poly1_points = poly1.getPoints();

        if(!n1.isVertex){
            previous = {init, last};
        }else{
            if(last==-1){
                previous.push_back(last);
            }else{
                previous = {init, last};
            }

        }

        NeighbourInfo n2 = getNeighbour(n1.neighbour, crack, previous);


        if(n1.isEdge){
            init = n1.neighbour;
            n1 = n2;

            continue;
        }

        Pair<int> exit = breakPolygons(n1, n2, init, oldPolygons, newPolygons,
                      newPoints);
        createdPolygonIndexes.push_back(n1.neighbour);
        createdPolygonIndexes.push_back(this->polygons.size()-1);

        // Iterate
        if(oneLastIteration){
            return PolygonChangeData(oldPolygons, newPolygons);
        }

        IndexSegment edge = n2.edge;
        edge.orderCCW(this->points.getList(), merged.getCentroid());
        merged.insertOnSegment(n2.edge, {exit.second, exit.first});

        last = this->polygons.size()-1;
        init = n1.neighbour;
        n1 = n2;

        this->printInFile("afterBreaking.txt");
    }
}
Example #19
0
/*!
 ************************************************************************
 * \brief
 *    Make intra 8x8 prediction according to all 9 prediction modes.
 *    The routine uses left and upper neighbouring points from
 *    previous coded blocks to do this (if available). Notice that
 *    inaccessible neighbouring points are signalled with a negative
 *    value in the predmode array .
 *
 *  \par Input:
 *     Starting point of current 8x8 block image posision
 *
 ************************************************************************
 */
int intrapred8x8( struct img_par *img,  //!< image parameters
                  int b8)

{
  int i,j;
  int s0;
  imgpel PredPel[25];  // array of predictor pels
  imgpel **imgY = dec_picture->imgY;  // For MB level frame/field coding tools -- set default to imgY

  int mb_nr=img->current_mb_nr;

  PixelPos pix_a[8];
  PixelPos pix_b, pix_c, pix_d;

  int block_available_up;
  int block_available_left;
  int block_available_up_left;
  int block_available_up_right;
  int img_block_x = (img->mb_x)*4 + 2*(b8%2);
  int img_block_y = (img->mb_y)*4 + 2*(b8/2);
  int ioff = (b8%2)*8;
  int joff = (b8/2)*8;
  int jpos0 = joff    , jpos1 = joff + 1, jpos2 = joff + 2, jpos3 = joff + 3;
  int jpos4 = joff + 4, jpos5 = joff + 5, jpos6 = joff + 6, jpos7 = joff + 7;
  int ipos0 = ioff    , ipos1 = ioff + 1, ipos2 = ioff + 2, ipos3 = ioff + 3;
  int ipos4 = ioff + 4, ipos5 = ioff + 5, ipos6 = ioff + 6, ipos7 = ioff + 7;
  int jpos, ipos;
  imgpel *pred_pels;

  byte predmode = img->ipredmode[img_block_y][img_block_x];

  for (i=0;i<8;i++)
  {
    getNeighbour(mb_nr, ioff -1 , joff +i , IS_LUMA, &pix_a[i]);
  }

  getNeighbour(mb_nr, ioff    , joff -1 , IS_LUMA, &pix_b);
  getNeighbour(mb_nr, ioff +8 , joff -1 , IS_LUMA, &pix_c);
  getNeighbour(mb_nr, ioff -1 , joff -1 , IS_LUMA, &pix_d);

  pix_c.available = pix_c.available &&!(ioff == 8 && joff == 8);

  if (active_pps->constrained_intra_pred_flag)
  {
    for (i=0, block_available_left=1; i<8;i++)
      block_available_left  &= pix_a[i].available ? img->intra_block[pix_a[i].mb_addr]: 0;
    block_available_up       = pix_b.available ? img->intra_block [pix_b.mb_addr] : 0;
    block_available_up_right = pix_c.available ? img->intra_block [pix_c.mb_addr] : 0;
    block_available_up_left  = pix_d.available ? img->intra_block [pix_d.mb_addr] : 0;
  }
  else
  {
    block_available_left     = pix_a[0].available;
    block_available_up       = pix_b.available;
    block_available_up_right = pix_c.available;
    block_available_up_left  = pix_d.available;
  }

//  *left_available = block_available_left;
//  *up_available   = block_available_up;
//  *all_available  = block_available_up && block_available_left && block_available_up_left;

  // form predictor pels
  // form predictor pels
  if (block_available_up)
  {
    pred_pels = &imgY[pix_b.pos_y][pix_b.pos_x];
    P_A = pred_pels[0];
    P_B = pred_pels[1];
    P_C = pred_pels[2];
    P_D = pred_pels[3];
    P_E = pred_pels[4];
    P_F = pred_pels[5];
    P_G = pred_pels[6];
    P_H = pred_pels[7];
  }
  else
  {
    P_A = P_B = P_C = P_D = P_E = P_F = P_G = P_H = img->dc_pred_value_luma;
  }

  if (block_available_up_right)
  {
    pred_pels = &imgY[pix_c.pos_y][pix_c.pos_x];
    P_I = pred_pels[0];
    P_J = pred_pels[1];
    P_K = pred_pels[2];
    P_L = pred_pels[3];
    P_M = pred_pels[4];
    P_N = pred_pels[5];
    P_O = pred_pels[6];
    P_P = pred_pels[7];

  }
  else
  {
    P_I = P_J = P_K = P_L = P_M = P_N = P_O = P_P = P_H;
  }

  if (block_available_left)
  {
    P_Q = imgY[pix_a[0].pos_y][pix_a[0].pos_x];
    P_R = imgY[pix_a[1].pos_y][pix_a[1].pos_x];
    P_S = imgY[pix_a[2].pos_y][pix_a[2].pos_x];
    P_T = imgY[pix_a[3].pos_y][pix_a[3].pos_x];
    P_U = imgY[pix_a[4].pos_y][pix_a[4].pos_x];
    P_V = imgY[pix_a[5].pos_y][pix_a[5].pos_x];
    P_W = imgY[pix_a[6].pos_y][pix_a[6].pos_x];
    P_X = imgY[pix_a[7].pos_y][pix_a[7].pos_x];
  }
  else
  {
    P_Q = P_R = P_S = P_T = P_U = P_V = P_W = P_X = img->dc_pred_value_luma;
  }

  if (block_available_up_left)
  {
    P_Z = imgY[pix_d.pos_y][pix_d.pos_x];
  }
  else
  {
    P_Z = img->dc_pred_value_luma;
  }

  LowPassForIntra8x8Pred(&(P_Z), block_available_up_left, block_available_up, block_available_left);

//img->mpr[y][x]
  switch(predmode)
  {
  case DC_PRED:
    s0 = 0;
    if (block_available_up && block_available_left)
    {
      // no edge
      s0 = (P_A + P_B + P_C + P_D + P_E + P_F + P_G + P_H + P_Q + P_R + P_S + P_T + P_U + P_V + P_W + P_X + 8) >> 4;
    }
    else if (!block_available_up && block_available_left)
Example #20
0
void intrapred_chroma(struct img_par *img, int uv)
{
  int i,j, ii, jj, ioff, joff;

  byte ***imgUV = dec_picture->imgUV;
  
  int js0=0;
  int js1=0;
  int js2=0;
  int js3=0;

  int js[2][2];

  int pred;
  int ih, iv, ib, ic, iaa;

  int mb_nr=img->current_mb_nr;
  Macroblock *currMB = &img->mb_data[img->current_mb_nr];

  PixelPos up;       //!< pixel position p(0,-1)
  PixelPos left[9];  //!< pixel positions p(-1, -1..8)

  int up_avail, left_avail[2], left_up_avail;

  for (i=0;i<9;i++)
  {
    getNeighbour(mb_nr, -1 ,  i-1 , 0, &left[i]);
  }
  
  getNeighbour(mb_nr, 0     ,  -1 , 0, &up);

  if (!img->constrained_intra_pred_flag)
  {
    up_avail   = up.available;
    left_avail[0] = left_avail[1] = left[1].available;
    left_up_avail = left[0].available;
  }
  else
  {
    up_avail      = up.available ? img->intra_block[up.mb_addr] : 0;
    for (i=1, left_avail[0]=1; i<5;i++)
      left_avail[0]  &= left[i].available ? img->intra_block[left[i].mb_addr]: 0;
    for (i=5, left_avail[1]=1; i<9;i++)
      left_avail[1]  &= left[i].available ? img->intra_block[left[i].mb_addr]: 0;
    left_up_avail = left[0].available ? img->intra_block[left[0].mb_addr]: 0;
  }

  if (currMB->c_ipred_mode == DC_PRED_8)
  {
    for(i=0;i<4;i++)
    {
      if(up_avail)
      {
        js0=js0+imgUV[uv][up.pos_y][up.pos_x+i];
        js1=js1+imgUV[uv][up.pos_y][up.pos_x+i+4];
      }
      if(left_avail[0])
      {
        js2=js2+imgUV[uv][left[1+i].pos_y][left[1+i].pos_x];
	  }
      if(left_avail[1])
	  {
        js3=js3+imgUV[uv][left[1+i+4].pos_y][left[1+i+4].pos_x];
      }
    }
    if(up_avail && left_avail[0])
    {
      js[0][0]=(js0+js2+4)/8;
      js[1][0]=(js1+2)/4;
	}
    if(up_avail && left_avail[1])
	{
      js[0][1]=(js3+2)/4;
      js[1][1]=(js1+js3+4)/8;
    }
    if(up_avail && !left_avail[0])
    {
      js[0][0]=(js0+2)/4;
      js[1][0]=(js1+2)/4;
	}
    if(up_avail && !left_avail[1])
	{
      js[0][1]=(js0+2)/4;
      js[1][1]=(js1+2)/4;
    }
    if(left_avail[0] && !up_avail)
    {
      js[0][0]=(js2+2)/4;
      js[1][0]=(js2+2)/4;
	}
    if(left_avail[1] && !up_avail)
	{
      js[0][1]=(js3+2)/4;
      js[1][1]=(js3+2)/4;
    }
    if(!up_avail && !left_avail[0])
    {
      js[0][0]=128;
      js[1][0]=128;
	}
    if(!up_avail && !left_avail[1])
	{
      js[0][1]=128;
      js[1][1]=128;
    }
  }
  
  for (j=0;j<2;j++)
  {
    joff=j*4;

    for(i=0;i<2;i++)
    {
      ioff=i*4;
      
      switch (currMB->c_ipred_mode)
      {
      case DC_PRED_8:
        for (ii=0; ii<4; ii++)
          for (jj=0; jj<4; jj++)
          {
            img->mpr[ii+ioff][jj+joff]=js[i][j];
          }
        break;
      case HOR_PRED_8:
        if ( !left_avail[0] || !left_avail[1] )
          error("unexpected HOR_PRED_8 chroma intra prediction mode",-1);

        for (jj=0; jj<4; jj++)
        {
          pred = imgUV[uv][left[1+jj+joff].pos_y][left[1+jj+joff].pos_x];
          for (ii=0; ii<4; ii++)
            img->mpr[ii+ioff][jj+joff]=pred;
        }
        break;
      case VERT_PRED_8:
        if (!up_avail)
          error("unexpected VERT_PRED_8 chroma intra prediction mode",-1);

        for (ii=0; ii<4; ii++)
        {
          pred = imgUV[uv][up.pos_y][up.pos_x+ii+ioff];
          for (jj=0; jj<4; jj++)
            img->mpr[ii+ioff][jj+joff]=pred;
        }
        break;
      case PLANE_8:
        if (!left_up_avail || !left_avail[0] || !left_avail[1] || !up_avail)
          error("unexpected PLANE_8 chroma intra prediction mode",-1);

        ih=iv=0;

        for (ii=1;ii<5;ii++)
        {
          if (ii<4)
            ih += ii*(imgUV[uv][up.pos_y][up.pos_x+3+ii] - imgUV[uv][up.pos_y][up.pos_x+3-ii]);
          else
            ih += ii*(imgUV[uv][up.pos_y][up.pos_x+3+ii] - imgUV[uv][left[0].pos_y][left[0].pos_x]);
            
          iv += ii*(imgUV[uv][left[4+ii].pos_y][left[4+ii].pos_x] - imgUV[uv][left[4-ii].pos_y][left[4-ii].pos_x]);
        }
        ib=(17*ih+16)>>5;
        ic=(17*iv+16)>>5;
        iaa=16*(imgUV[uv][up.pos_y][up.pos_x+7]+imgUV[uv][left[8].pos_y][left[8].pos_x]);
        for (ii=0; ii<4; ii++)
          for (jj=0; jj<4; jj++)
            img->mpr[ii+ioff][jj+joff]=max(0,min(255,(iaa+(ii+ioff-3)*ib +(jj+joff-3)*ic + 16)>>5));
          break;
      default:
        error("illegal chroma intra prediction mode", 600);
        break;
      }
    }
  }
}
Example #21
0
void generateMap(Map * map)
{
    unsigned char territories[4] = {CELL_TYPE_WATER, CELL_TYPE_TREE,
        CELL_TYPE_HILL, CELL_TYPE_MOUNTAIN};
    unsigned char required[4] = {CELL_TYPE_GRASS, CELL_TYPE_GRASS,
        CELL_TYPE_GRASS, CELL_TYPE_HILL};

    srand(time(NULL));

    Node * current = map -> head;

    // Filling up by default type of territory (grass).
    for(int i = 0; i < map -> max_r; i++)
    {
        for(int j = 0; j < map -> max_c; j++)
        {
            ((Cell *) current -> data) -> territory = CELL_TYPE_GRASS;
            current = getNeighbour(current, EDGE_CELL_RIGHT);
        }
        current = getNeighbour(current, EDGE_CELL_BOTTOM);
    }

    // Generating landscape.
    for(int i = 0; i < 4; i++)
    {
        long long n = 7;
        long long k = pow(2, n);
        for(int j = 0; j < n; j++)
        {
            Node * c = getMapCell(map, rand() % map -> max_r, rand() % map -> max_c);
            generateLandscape(c, k, required[i], territories[i]);
            k /= 2;
        }
    }

    // Generating resources.
    unsigned char resources[CELL_RES_COUNT] = {CELL_RES_BRONZE, CELL_RES_IRON,
        CELL_RES_COAL, CELL_RES_GUNPOWDER, CELL_RES_HORSES};
    for(int i = 0; i < map -> max_r; i++)
    {
        for(int j = 0; j < map -> max_c; j++)
        {
            Cell * c = (Cell *) current -> data;
            if(c -> territory != CELL_TYPE_WATER)
            {
                int random = rand() % 3;
                if(random == 2)
                {
                    c -> resources = resources[rand() % CELL_RES_COUNT];
                }
            }
            current = getNeighbour(current, EDGE_CELL_RIGHT);
        }
        current = getNeighbour(current, EDGE_CELL_BOTTOM);
    }

    // Putting mushrooms on the map.
    int r;
    int c;
    do
    {
        r = rand () % map -> max_r;
        c = rand () % map -> max_c;
    } while( ((Cell *) getMapCell(map, r, c) -> data) -> territory == CELL_TYPE_WATER );
    ((Cell *) getMapCell(map, r, c) -> data) -> resources = CELL_RES_MUSHROOMS;
}
Example #22
0
int intrapred(
  struct img_par *img,  //!< image parameters
  int ioff,             //!< pixel offset X within MB
  int joff,             //!< pixel offset Y within MB
  int img_block_x,      //!< location of block X, multiples of 4
  int img_block_y)      //!< location of block Y, multiples of 4
{
  int i,j;
  int s0;
  int img_y,img_x;
  int PredPel[13];  // array of predictor pels

  byte **imgY = dec_picture->imgY;

  PixelPos pix_a[4];
  PixelPos pix_b, pix_c, pix_d;

  int block_available_up;
  int block_available_left;
  int block_available_up_left;
  int block_available_up_right;

  int mb_nr=img->current_mb_nr;

  byte predmode = img->ipredmode[img_block_x][img_block_y];

  img_x=img_block_x*4;
  img_y=img_block_y*4;

  for (i=0;i<4;i++)
  {
    getNeighbour(mb_nr, ioff -1 , joff +i , 1, &pix_a[i]);
  }
  
  
  getNeighbour(mb_nr, ioff    , joff -1 , 1, &pix_b);
  getNeighbour(mb_nr, ioff +4 , joff -1 , 1, &pix_c);
  getNeighbour(mb_nr, ioff -1 , joff -1 , 1, &pix_d);

  pix_c.available = pix_c.available && !(((ioff==4)||(ioff==12)) && ((joff==4)||(joff==12)));

  if (img->constrained_intra_pred_flag)
  {
    for (i=0, block_available_left=1; i<4;i++)
      block_available_left  &= pix_a[i].available ? img->intra_block[pix_a[i].mb_addr]: 0;
    block_available_up       = pix_b.available ? img->intra_block [pix_b.mb_addr] : 0;
    block_available_up_right = pix_c.available ? img->intra_block [pix_c.mb_addr] : 0;
    block_available_up_left  = pix_d.available ? img->intra_block [pix_d.mb_addr] : 0;
  }
  else
  {
    block_available_left     = pix_a[0].available;
    block_available_up       = pix_b.available;
    block_available_up_right = pix_c.available;
    block_available_up_left  = pix_d.available;
  }

  // form predictor pels
  if (block_available_up)
  {
    P_A = imgY[pix_b.pos_y][pix_b.pos_x+0];
    P_B = imgY[pix_b.pos_y][pix_b.pos_x+1];
    P_C = imgY[pix_b.pos_y][pix_b.pos_x+2];
    P_D = imgY[pix_b.pos_y][pix_b.pos_x+3];

  }
  else
  {
    P_A = P_B = P_C = P_D = 128;
  }

  if (block_available_up_right)
  {
    P_E = imgY[pix_c.pos_y][pix_c.pos_x+0];
    P_F = imgY[pix_c.pos_y][pix_c.pos_x+1];
    P_G = imgY[pix_c.pos_y][pix_c.pos_x+2];
    P_H = imgY[pix_c.pos_y][pix_c.pos_x+3];
  }
  else
  {
    P_E = P_F = P_G = P_H = P_D;
  }

  if (block_available_left)
  {
    P_I = imgY[pix_a[0].pos_y][pix_a[0].pos_x];
    P_J = imgY[pix_a[1].pos_y][pix_a[1].pos_x];
    P_K = imgY[pix_a[2].pos_y][pix_a[2].pos_x];
    P_L = imgY[pix_a[3].pos_y][pix_a[3].pos_x];
  }
  else
  {
    P_I = P_J = P_K = P_L = 128;
  }

  if (block_available_up_left)
  {
    P_X = imgY[pix_d.pos_y][pix_d.pos_x];
  }
  else
  {
    P_X = 128;
  }

  
  switch (predmode)
  {
  case DC_PRED:                         /* DC prediction */

    s0 = 0;
    if (block_available_up && block_available_left)
    {   
      // no edge
      s0 = (P_A + P_B + P_C + P_D + P_I + P_J + P_K + P_L + 4)/(2*BLOCK_SIZE);
    }
    else if (!block_available_up && block_available_left)
    {
      // upper edge
      s0 = (P_I + P_J + P_K + P_L + 2)/BLOCK_SIZE;             
    }
    else if (block_available_up && !block_available_left)
    {
      // left edge
      s0 = (P_A + P_B + P_C + P_D + 2)/BLOCK_SIZE;             
    }
    else //if (!block_available_up && !block_available_left)
    {
      // top left corner, nothing to predict from
      s0 = 128;                           
    }

    for (j=0; j < BLOCK_SIZE; j++)
    {
      for (i=0; i < BLOCK_SIZE; i++)
      {
        // store DC prediction
        img->mpr[i+ioff][j+joff] = s0;
      }
    }
    break;

  case VERT_PRED:                       /* vertical prediction from block above */
    if (!block_available_up)
      printf ("warning: Intra_4x4_Vertical prediction mode not allowed at mb %d\n",img->current_mb_nr);

    for(j=0;j<BLOCK_SIZE;j++)
      for(i=0;i<BLOCK_SIZE;i++)
        img->mpr[i+ioff][j+joff]=imgY[pix_b.pos_y][pix_b.pos_x+i];/* store predicted 4x4 block */
    break;

  case HOR_PRED:                        /* horizontal prediction from left block */
    if (!block_available_left)
      printf ("warning: Intra_4x4_Horizontal prediction mode not allowed at mb %d\n",img->current_mb_nr);

    for(j=0;j<BLOCK_SIZE;j++)
      for(i=0;i<BLOCK_SIZE;i++)
        img->mpr[i+ioff][j+joff]=imgY[pix_a[j].pos_y][pix_a[j].pos_x]; /* store predicted 4x4 block */
    break;

  case DIAG_DOWN_RIGHT_PRED:
    if ((!block_available_up)||(!block_available_left)||(!block_available_up_left))
      printf ("warning: Intra_4x4_Diagonal_Down_Right prediction mode not allowed at mb %d\n",img->current_mb_nr);

    img->mpr[0+ioff][3+joff] = (P_L + 2*P_K + P_J + 2) / 4; 
    img->mpr[0+ioff][2+joff] =
    img->mpr[1+ioff][3+joff] = (P_K + 2*P_J + P_I + 2) / 4; 
    img->mpr[0+ioff][1+joff] =
    img->mpr[1+ioff][2+joff] = 
    img->mpr[2+ioff][3+joff] = (P_J + 2*P_I + P_X + 2) / 4; 
    img->mpr[0+ioff][0+joff] =
    img->mpr[1+ioff][1+joff] =
    img->mpr[2+ioff][2+joff] =
    img->mpr[3+ioff][3+joff] = (P_I + 2*P_X + P_A + 2) / 4; 
    img->mpr[1+ioff][0+joff] =
    img->mpr[2+ioff][1+joff] =
    img->mpr[3+ioff][2+joff] = (P_X + 2*P_A + P_B + 2) / 4;
    img->mpr[2+ioff][0+joff] =
    img->mpr[3+ioff][1+joff] = (P_A + 2*P_B + P_C + 2) / 4;
    img->mpr[3+ioff][0+joff] = (P_B + 2*P_C + P_D + 2) / 4;
    break;

  case DIAG_DOWN_LEFT_PRED:
    if (!block_available_up)
      printf ("warning: Intra_4x4_Diagonal_Down_Left prediction mode not allowed at mb %d\n",img->current_mb_nr);

    img->mpr[0+ioff][0+joff] = (P_A + P_C + 2*(P_B) + 2) / 4;
    img->mpr[1+ioff][0+joff] = 
    img->mpr[0+ioff][1+joff] = (P_B + P_D + 2*(P_C) + 2) / 4;
    img->mpr[2+ioff][0+joff] =
    img->mpr[1+ioff][1+joff] =
    img->mpr[0+ioff][2+joff] = (P_C + P_E + 2*(P_D) + 2) / 4;
    img->mpr[3+ioff][0+joff] = 
    img->mpr[2+ioff][1+joff] = 
    img->mpr[1+ioff][2+joff] = 
    img->mpr[0+ioff][3+joff] = (P_D + P_F + 2*(P_E) + 2) / 4;
    img->mpr[3+ioff][1+joff] = 
    img->mpr[2+ioff][2+joff] = 
    img->mpr[1+ioff][3+joff] = (P_E + P_G + 2*(P_F) + 2) / 4;
    img->mpr[3+ioff][2+joff] = 
    img->mpr[2+ioff][3+joff] = (P_F + P_H + 2*(P_G) + 2) / 4;
    img->mpr[3+ioff][3+joff] = (P_G + 3*(P_H) + 2) / 4;
    break;

  case  VERT_RIGHT_PRED:/* diagonal prediction -22.5 deg to horizontal plane */
    if ((!block_available_up)||(!block_available_left)||(!block_available_up_left))
      printf ("warning: Intra_4x4_Vertical_Right prediction mode not allowed at mb %d\n",img->current_mb_nr);

    img->mpr[0+ioff][0+joff] = 
    img->mpr[1+ioff][2+joff] = (P_X + P_A + 1) / 2;
    img->mpr[1+ioff][0+joff] = 
    img->mpr[2+ioff][2+joff] = (P_A + P_B + 1) / 2;
    img->mpr[2+ioff][0+joff] = 
    img->mpr[3+ioff][2+joff] = (P_B + P_C + 1) / 2;
    img->mpr[3+ioff][0+joff] = (P_C + P_D + 1) / 2;
    img->mpr[0+ioff][1+joff] = 
    img->mpr[1+ioff][3+joff] = (P_I + 2*P_X + P_A + 2) / 4;
    img->mpr[1+ioff][1+joff] = 
    img->mpr[2+ioff][3+joff] = (P_X + 2*P_A + P_B + 2) / 4;
    img->mpr[2+ioff][1+joff] = 
    img->mpr[3+ioff][3+joff] = (P_A + 2*P_B + P_C + 2) / 4;
    img->mpr[3+ioff][1+joff] = (P_B + 2*P_C + P_D + 2) / 4;
    img->mpr[0+ioff][2+joff] = (P_X + 2*P_I + P_J + 2) / 4;
    img->mpr[0+ioff][3+joff] = (P_I + 2*P_J + P_K + 2) / 4;
    break;

  case  VERT_LEFT_PRED:/* diagonal prediction -22.5 deg to horizontal plane */
    if (!block_available_up)
      printf ("warning: Intra_4x4_Vertical_Left prediction mode not allowed at mb %d\n",img->current_mb_nr);
    
    img->mpr[0+ioff][0+joff] = (P_A + P_B + 1) / 2;
    img->mpr[1+ioff][0+joff] = 
    img->mpr[0+ioff][2+joff] = (P_B + P_C + 1) / 2;
    img->mpr[2+ioff][0+joff] = 
    img->mpr[1+ioff][2+joff] = (P_C + P_D + 1) / 2;
    img->mpr[3+ioff][0+joff] = 
    img->mpr[2+ioff][2+joff] = (P_D + P_E + 1) / 2;
    img->mpr[3+ioff][2+joff] = (P_E + P_F + 1) / 2;
    img->mpr[0+ioff][1+joff] = (P_A + 2*P_B + P_C + 2) / 4;
    img->mpr[1+ioff][1+joff] = 
    img->mpr[0+ioff][3+joff] = (P_B + 2*P_C + P_D + 2) / 4;
    img->mpr[2+ioff][1+joff] = 
    img->mpr[1+ioff][3+joff] = (P_C + 2*P_D + P_E + 2) / 4;
    img->mpr[3+ioff][1+joff] = 
    img->mpr[2+ioff][3+joff] = (P_D + 2*P_E + P_F + 2) / 4;
    img->mpr[3+ioff][3+joff] = (P_E + 2*P_F + P_G + 2) / 4;
    break;

  case  HOR_UP_PRED:/* diagonal prediction -22.5 deg to horizontal plane */
    if (!block_available_left)
      printf ("warning: Intra_4x4_Horizontal_Up prediction mode not allowed at mb %d\n",img->current_mb_nr);
    
    img->mpr[0+ioff][0+joff] = (P_I + P_J + 1) / 2;
    img->mpr[1+ioff][0+joff] = (P_I + 2*P_J + P_K + 2) / 4;
    img->mpr[2+ioff][0+joff] = 
    img->mpr[0+ioff][1+joff] = (P_J + P_K + 1) / 2;
    img->mpr[3+ioff][0+joff] = 
    img->mpr[1+ioff][1+joff] = (P_J + 2*P_K + P_L + 2) / 4;
    img->mpr[2+ioff][1+joff] = 
    img->mpr[0+ioff][2+joff] = (P_K + P_L + 1) / 2;
    img->mpr[3+ioff][1+joff] = 
    img->mpr[1+ioff][2+joff] = (P_K + 2*P_L + P_L + 2) / 4;
    img->mpr[3+ioff][2+joff] = 
    img->mpr[1+ioff][3+joff] = 
    img->mpr[0+ioff][3+joff] = 
    img->mpr[2+ioff][2+joff] = 
    img->mpr[2+ioff][3+joff] = 
    img->mpr[3+ioff][3+joff] = P_L;
    break;

  case  HOR_DOWN_PRED:/* diagonal prediction -22.5 deg to horizontal plane */
    if ((!block_available_up)||(!block_available_left)||(!block_available_up_left))
      printf ("warning: Intra_4x4_Horizontal_Down prediction mode not allowed at mb %d\n",img->current_mb_nr);

    img->mpr[0+ioff][0+joff] = 
    img->mpr[2+ioff][1+joff] = (P_X + P_I + 1) / 2;
    img->mpr[1+ioff][0+joff] = 
    img->mpr[3+ioff][1+joff] = (P_I + 2*P_X + P_A + 2) / 4;
    img->mpr[2+ioff][0+joff] = (P_X + 2*P_A + P_B + 2) / 4;
    img->mpr[3+ioff][0+joff] = (P_A + 2*P_B + P_C + 2) / 4;
    img->mpr[0+ioff][1+joff] = 
    img->mpr[2+ioff][2+joff] = (P_I + P_J + 1) / 2;
    img->mpr[1+ioff][1+joff] = 
    img->mpr[3+ioff][2+joff] = (P_X + 2*P_I + P_J + 2) / 4;
    img->mpr[0+ioff][2+joff] = 
    img->mpr[2+ioff][3+joff] = (P_J + P_K + 1) / 2;
    img->mpr[1+ioff][2+joff] = 
    img->mpr[3+ioff][3+joff] = (P_I + 2*P_J + P_K + 2) / 4;
    img->mpr[0+ioff][3+joff] = (P_K + P_L + 1) / 2;
    img->mpr[1+ioff][3+joff] = (P_J + 2*P_K + P_L + 2) / 4;
    break;

  default:
    printf("Error: illegal intra_4x4 prediction mode: %d\n",predmode);
    return SEARCH_SYNC;
    break;
  }

  return DECODING_OK;
}
Example #23
0
waypoints getWpts(float wptLon[], float wptLat[], float robotPos[], float rad) {

    waypoints wpts;
    wpts.longitudes = std::vector<float>();
    wpts.latitudes = std::vector<float>();
    wpts.wptDirections = std::vector<int>();
    
    //convert GPS to XY
    waypoints input = convertInputArrayFromGPStoXY(wptLon, wptLat);

    float pos[2];
    convertFromGPStoXY(robotPos[0], robotPos[1], pos);

    int i = 0;
    int clWpt = 0; //index of closest waypoint
    float minDist = 0;
    for (i = 0; i < NUM_OF_WPTS; i++) {
        if (i == 0) {
            minDist = calculateDistance(input.longitudes[i], input.latitudes[i], pos[0], pos[1]);
        } else {
            float dist = calculateDistance(input.longitudes[i], input.latitudes[i], pos[0], pos[1]);
            if (dist < minDist) {
                minDist = dist;
                clWpt = i;
            }
        }
    }
    
    //std::cout << "Closest to: " << clWpt << "\n";

    int ln = getNeighbour(clWpt, -1, NUM_OF_WPTS);
    int rn = getNeighbour(clWpt, 1, NUM_OF_WPTS);

    //get longer edge 
    float distLeft = calculateDistance(input.longitudes[clWpt], input.latitudes[clWpt], input.longitudes[ln], input.latitudes[ln]);
    float distRight = calculateDistance(input.longitudes[clWpt], input.latitudes[clWpt], input.longitudes[rn], input.latitudes[rn]);    
    
    int pair1[2];
    int pair2[2];

    //change the condition to get sweeping by longer or shorter edge
    if (distLeft < distRight) {
        pair1[0] = clWpt;
        pair1[1] = rn;
        pair2[0] = ln;
        pair2[1] = getNeighbour(ln, -1, NUM_OF_WPTS);
    } else {
        pair1[0] = clWpt;
        pair1[1] = ln;
        pair2[0] = rn;
        pair2[1] = getNeighbour(rn, 1, NUM_OF_WPTS);
    }

    //std::cout << pair1[0] << " "<< pair1[1] << " "<< pair2[0] << " "<< pair2[1];
    
    float angle1 = atan2(input.latitudes[pair1[1]] - input.latitudes[pair1[0]], input.longitudes[pair1[1]] - input.longitudes[pair1[0]]);
    float angle2 = atan2(input.latitudes[pair2[1]] - input.latitudes[pair2[0]], input.longitudes[pair2[1]] - input.longitudes[pair2[0]]);

    wpts.longitudes.push_back(input.longitudes[pair1[0]]);
    wpts.latitudes.push_back(input.latitudes[pair1[0]]);

    bool stopCond = false;
    float distance1 = calculateDistance(input.longitudes[pair1[0]], input.latitudes[pair1[0]], input.longitudes[pair1[1]], input.latitudes[pair1[1]]);
    float distance2 = calculateDistance(input.longitudes[pair2[0]], input.latitudes[pair2[0]], input.longitudes[pair2[1]],  input.latitudes[pair2[1]]);
    
    i = 0;
    while (!stopCond) {
        if ((i % 2) == 0) {
            //add wpt oposite to the starting edge
            float newLong = (2*rad*(i+1))*cos(angle2) + input.longitudes[pair2[0]];
            float newLat = (2*rad*(i+1))*sin(angle2) + input.latitudes[pair2[0]];

            float newDist = calculateDistance(newLong, newLat, input.longitudes[pair2[1]], input.latitudes[pair2[1]]);
            if (newDist > distance2) {
                stopCond = true;
            } else {
                distance2 = newDist;                
                wpts.longitudes.push_back(newLong);
                wpts.latitudes.push_back(newLat);
            }
            
        } else {
            float newLong = (2*rad*(i+1))*cos(angle1) + input.longitudes[pair1[0]];
            float newLat = (2*rad*(i+1))*sin(angle1) + input.latitudes[pair1[0]];

            float newDist = calculateDistance(newLong, newLat, input.longitudes[pair1[1]], input.latitudes[pair1[1]]);  
            if (newDist > distance1) {
                stopCond = true;
            } else {
                distance1 = newDist;                
                wpts.longitudes.push_back(newLong);
                wpts.latitudes.push_back(newLat);
            }
        }
        i++;
    }

    wpts.wptDirections.push_back(getFirstWPTDir(wpts));
    //std::cout << "Dist 1 " << calculateDistance(wpts.longitudes[1],wpts.latitudes[1],wpts.longitudes[3],wpts.latitudes[3]) << "\n";
    //std::cout << "Dist 2 " << calculateDistance(wpts.longitudes[0],wpts.latitudes[0],wpts.longitudes[2],wpts.latitudes[2]) << "\n";
    return convertListFromXYtoGPS(wpts);
}
void addUnitInfoToTextbox(Textbox * tb, World * world, View * view)
{
    // Getting unit.
    Node * n = getNeighbour(view -> current_cell, EDGE_CELL_UNIT);
    Unit * u = (Unit *) n -> data;
    UnitCommonInfo * u_info = (UnitCommonInfo *) daGetByIndex(world -> units_info, u -> unit_id);

    // Add unit info.
    addBoldString(tb, u_info -> name);
    addEnter(tb);

    addString(tb, "Symbol       %c", u_info -> c);
    addEnter(tb);

    addString(tb, "Health       %d", u_info -> max_health);
    addString(tb, "Damage       %d", u_info -> max_damage);
    addString(tb, "Moves        %d", u_info -> max_moves);
    addEnter(tb);

    addString(tb, "Hiring turns %d", u_info -> hiring_turns);
    addEnter(tb);

    addString(tb, "Gold drop    %d", u_info -> gold_drop);
    addEnter(tb);

    addString(tb, "Requires for hiring:");
    if(u_info -> resources == NULL || u_info -> resources -> length == 0)
    {
        addString(tb, "    Nothing");
    }
    else
    {
        for(int i = 0; i < u_info -> resources -> length; i++)
        {
            int r = iaGetByIndex(u_info -> resources, i);
            for(int j = 0; j < CELL_RES_COUNT; j++)
            {
                if(VIEW_RES_VALUES[j] == r)
                {
                    addString(tb, "    %s", VIEW_RES_NAMES[j]);
                    break;
                }
            }
        }
    }

    addEnter(tb);

    addString(tb, "Privileges:");
    if(u_info -> privileges == NULL || u_info -> privileges -> length == 0)
    {
        addString(tb, "    Nothing");
    }
    else
    {
        for(int i = 0; i < u_info -> privileges -> length; i++)
        {
            int r = iaGetByIndex(u_info -> privileges, i);
            for(int j = 0; j < UNIT_PRVL_COUNT; j++)
            {
                if(VIEW_PRVL_VALUES[j] == r)
                {
                    addString(tb, "    %s", VIEW_PRVL_NAMES[j]);
                    break;
                }
            }
        }
    }
}