void DefaultSensors::init(Point2d position, double orientation){
	_sensorCount = 0;

	//count sensors
	for (int x = 0; x != gAgentWidth; x++){ // image is analysed a first time to count the number of sensors (faster than dynamically re-allocating array size for every new sensor)
		for (int y = 0; y != gAgentHeight; y++) {
			Uint32 pixel = getPixel32(gAgentSpecsImage, x, y);
			if (pixel != SDL_MapRGB(gAgentSpecsImage->format, 0xFF, 0xFF, 0xFF)) {
				_sensorCount++;
            }
        }
    }
//	_sensors = new double[_sensorCount][7]; // see header for details.
	_ditchSensor = new double[_sensorCount];
	_energySensor = new double[_sensorCount][2];

	for (int i = 0; i < _sensorCount; i++) {
        std::vector<double> _sensor(7);
		_sensor[0] = -1;
		// 1 - 4 set below
		_sensor[5] = -1;
		_sensor[6] = -1;
        
        _sensors.push_back(_sensor);

		_ditchSensor[i] = -1;
        _energySensor[i][0] = -1;
        _energySensor[i][1] = -1;
    }
	//int sensorIt = 0;

	//register sensors
	for (int x = 0; x != gAgentWidth; x++){
		for (int y = 0; y != gAgentHeight; y++) {
			Uint32 pixel = getPixel32(gAgentSpecsImage, x, y);
			if (pixel != SDL_MapRGB(gAgentSpecsImage->format, 0xFF, 0xFF, 0xFF)) {
				// sensor found, register sensor.

				Uint8 r, g, b;
				SDL_GetRGB(pixel, gAgentSpecsImage->format, &r, &g, &b);

				if (_sensors[r][0] != -1) {
					std::cout << "[ERROR] robot sensor id already in use -- check agent specification image." << std::endl;
					exit(-1);
				}

				if (r >= _sensorCount) {
					std::cout << "[ERROR] robot sensor id is not permitted (must be defined btw 0 and " << (_sensorCount - 1) << ", got: " << r << ") -- check agent specification image." << std::endl;
					exit(-1);
				}


				_sensors[r][0] = r; // no. sensor

				// sensor origini point location wrt. agent center
				_sensors[r][1] = sqrt((x - gAgentWidth / 2) * (x - gAgentWidth / 2) + (y - gAgentHeight / 2) * (y - gAgentHeight / 2)); // length
				double angleCosinus = ((x - (gAgentWidth / 2)) / _sensors[r][1]);
				double angleSinus = ((y - (gAgentHeight / 2)) / _sensors[r][1]);
				if (angleSinus >= 0)
					_sensors[r][2] = acos(angleCosinus) + M_PI / 2; // angle (in radian)
				else
					_sensors[r][2] = -acos(angleCosinus) + M_PI / 2 + M_PI * 2; // angle (in radian)

				// sensor target point location wrt. agent center -- sensor target angle is (green+blue) component values
				double angle = g + b - 90; // note: '-90deg' is due to image definition convention (in image, 0° means front of agent, which is upward -- while 0° in simulation means facing right)
				double xTarget = (x - gAgentWidth / 2) + cos(angle * M_PI / 180) * gSensorRange;
				double yTarget = (y - gAgentHeight / 2) + sin(angle * M_PI / 180) * gSensorRange;
				_sensors[r][3] = sqrt(xTarget * xTarget + yTarget * yTarget); // length (**from agent center**)
				angleCosinus = xTarget / _sensors[r][3];
				angleSinus = yTarget / _sensors[r][3];
				if (angleSinus >= 0)
					_sensors[r][4] = acos(angleCosinus) + M_PI / 2; // angle (in radian) wrt. agent center
				else
					_sensors[r][4] = -acos(angleCosinus) + M_PI / 2 + M_PI * 2;
				r++;
			}
		}
	}
}
Exemple #2
0
void CPlayer::Save(CFile &file) const
{
	const CPlayer &p = *this;
	file.printf("Player(%d,\n", this->Index);
	file.printf("  \"name\", \"%s\",\n", p.Name.c_str());
	file.printf("  \"type\", ");
	switch (p.Type) {
		case PlayerNeutral:       file.printf("\"neutral\",");         break;
		case PlayerNobody:        file.printf("\"nobody\",");          break;
		case PlayerComputer:      file.printf("\"computer\",");        break;
		case PlayerPerson:        file.printf("\"person\",");          break;
		case PlayerRescuePassive: file.printf("\"rescue-passive\","); break;
		case PlayerRescueActive:  file.printf("\"rescue-active\","); break;
		default:                  file.printf("%d,", p.Type); break;
	}
	file.printf(" \"race\", \"%s\",", PlayerRaces.Name[p.Race].c_str());
	file.printf(" \"ai-name\", \"%s\",\n", p.AiName.c_str());
	file.printf("  \"team\", %d,", p.Team);

	file.printf(" \"enemy\", \"");
	for (int j = 0; j < PlayerMax; ++j) {
		file.printf("%c", (p.Enemy & (1 << j)) ? 'X' : '_');
	}
	file.printf("\", \"allied\", \"");
	for (int j = 0; j < PlayerMax; ++j) {
		file.printf("%c", (p.Allied & (1 << j)) ? 'X' : '_');
	}
	file.printf("\", \"shared-vision\", \"");
	for (int j = 0; j < PlayerMax; ++j) {
		file.printf("%c", (p.SharedVision & (1 << j)) ? 'X' : '_');
	}
	file.printf("\",\n  \"start\", {%d, %d},\n", p.StartPos.x, p.StartPos.y);

	// Resources
	file.printf("  \"resources\", {");
	for (int j = 0; j < MaxCosts; ++j) {
		file.printf("\"%s\", %d, ", DefaultResourceNames[j].c_str(), p.Resources[j]);
	}
	// Stored Resources
	file.printf("},\n  \"stored-resources\", {");
	for (int j = 0; j < MaxCosts; ++j) {
		file.printf("\"%s\", %d, ", DefaultResourceNames[j].c_str(), p.StoredResources[j]);
	}
	// Max Resources
	file.printf("},\n  \"max-resources\", {");
	for (int j = 0; j < MaxCosts; ++j) {
		file.printf("\"%s\", %d, ", DefaultResourceNames[j].c_str(), p.MaxResources[j]);
	}
	// Last Resources
	file.printf("},\n  \"last-resources\", {");
	for (int j = 0; j < MaxCosts; ++j) {
		file.printf("\"%s\", %d, ", DefaultResourceNames[j].c_str(), p.LastResources[j]);
	}
	// Incomes
	file.printf("},\n  \"incomes\", {");
	for (int j = 0; j < MaxCosts; ++j) {
		if (j) {
			if (j == MaxCosts / 2) {
				file.printf("\n ");
			} else {
				file.printf(" ");
			}
		}
		file.printf("\"%s\", %d,", DefaultResourceNames[j].c_str(), p.Incomes[j]);
	}
	// Revenue
	file.printf("},\n  \"revenue\", {");
	for (int j = 0; j < MaxCosts; ++j) {
		if (j) {
			if (j == MaxCosts / 2) {
				file.printf("\n ");
			} else {
				file.printf(" ");
			}
		}
		file.printf("\"%s\", %d,", DefaultResourceNames[j].c_str(), p.Revenue[j]);
	}

	// UnitTypesCount done by load units.

	file.printf("},\n  \"%s\",\n", p.AiEnabled ? "ai-enabled" : "ai-disabled");

	// Ai done by load ais.
	// Units done by load units.
	// TotalNumUnits done by load units.
	// NumBuildings done by load units.

	file.printf(" \"supply\", %d,", p.Supply);
	file.printf(" \"unit-limit\", %d,", p.UnitLimit);
	file.printf(" \"building-limit\", %d,", p.BuildingLimit);
	file.printf(" \"total-unit-limit\", %d,", p.TotalUnitLimit);

	file.printf("\n  \"score\", %d,", p.Score);
	file.printf("\n  \"total-units\", %d,", p.TotalUnits);
	file.printf("\n  \"total-buildings\", %d,", p.TotalBuildings);
	file.printf("\n  \"total-resources\", {");
	for (int j = 0; j < MaxCosts; ++j) {
		if (j) {
			file.printf(" ");
		}
		file.printf("%d,", p.TotalResources[j]);
	}
	file.printf("},");
	file.printf("\n  \"total-razings\", %d,", p.TotalRazings);
	file.printf("\n  \"total-kills\", %d,", p.TotalKills);

	file.printf("\n  \"speed-resource-harvest\", {");
	for (int j = 0; j < MaxCosts; ++j) {
		if (j) {
			file.printf(" ");
		}
		file.printf("%d,", p.SpeedResourcesHarvest[j]);
	}
	file.printf("},");
	file.printf("\n  \"speed-resource-return\", {");
	for (int j = 0; j < MaxCosts; ++j) {
		if (j) {
			file.printf(" ");
		}
		file.printf("%d,", p.SpeedResourcesReturn[j]);
	}
	file.printf("},");
	file.printf("\n  \"speed-build\", %d,", p.SpeedBuild);
	file.printf("\n  \"speed-train\", %d,", p.SpeedTrain);
	file.printf("\n  \"speed-upgrade\", %d,", p.SpeedUpgrade);
	file.printf("\n  \"speed-research\", %d,", p.SpeedResearch);

	Uint8 r, g, b;

	SDL_GetRGB(p.Color, TheScreen->format, &r, &g, &b);
	file.printf("\n  \"color\", { %d, %d, %d },", r, g, b);

	// UnitColors done by init code.
	// Allow saved by allow.

	file.printf("\n  \"timers\", {");
	for (int j = 0; j < UpgradeMax; ++j) {
		if (j) {
			file.printf(" ,");
		}
		file.printf("%d", p.UpgradeTimers.Upgrades[j]);
	}
	file.printf("}");

	file.printf(")\n\n");

	DebugPrint("FIXME: must save unit-stats?\n");
}
Exemple #3
0
int main( int argc, char* argv[] )
{
  Uint32 i, pitch;
  Uint8 temp;
  SDL_Rect crect1 = {0, 1, SCREEN_WIDTH, 127};
  SDL_Rect crect2 = {0, 0, SCREEN_WIDTH, 127};
  SDL_Rect crect3 = {0, 127, SCREEN_WIDTH, 1};
  SDL_Rect crect4 = {0, (SCREEN_HEIGHT >> 1) - 64, SCREEN_WIDTH, 1};
  SDL_Color col;
 
  if (argc > 1)
    {
      printf("Retro Amiga Candybar - W.P. van Paassen - 2002\n");
      return -1;
    }

  if (!TDEC_set_video(SCREEN_WIDTH, SCREEN_HEIGHT, 8, SDL_HWSURFACE | SDL_HWPALETTE /*| SDL_FULLSCREEN*/))
   quit(1);
  
  TDEC_init_timer();
  
  SDL_WM_SetCaption("Retro - Amiga Candybar - ", "");
  
  init();

  /* Lock the screen for direct access to the pixels */
  SDL_LockSurface(screen);

  /* time based demo loop */
  while( 1 ) 
    {
      TDEC_new_time();

      process_events();

      /* scroll candy bars up */

      temp = *(Uint8*)copper_surface->pixels;
      SDL_BlitSurface(copper_surface, &crect1, copper_surface, &crect2);
      SDL_FillRect(copper_surface, &crect3, temp);

      /*shade candy*/

      pitch = 0;
 
      for (i = 0; i < 128; ++i)
	{
	  temp = *((Uint8*)copper_surface->pixels + pitch);
	  SDL_GetRGB(temp, screen->format, &col.r, &col.g, &col.b);
	  
	  if (i < 64)
	    {
	      col.r &= i << 2;
	      col.b &= i << 2;
	      col.g &= i << 2;
	    }
	  else
	    {
	      col.r &= 0xFF - (i << 2);
	      col.b &= 0xFF - (i << 2);
	      col.g &= 0xFF - (i << 2);	    
	    }
	  temp = SDL_MapRGB(screen->format, col.r, col.g, col.b);
	  SDL_FillRect(screen, &crect4, temp);
	  crect4.y++;
	  pitch += copper_surface->pitch;
	}

      crect4.y = (SCREEN_HEIGHT >> 1) - 64;

      if (TDEC_fps_ok())
	SDL_UpdateRect(screen, 0, crect4.y, SCREEN_WIDTH, 128);
    }
  
  return 0; /* never reached */
}
Exemple #4
0
/***************************************************************************
 *      input_string()
 * Read input from the user ... on the widget layer. 
 *********************************************************************PROTO*/
char *
input_string(SDL_Surface *screen, int x, int y, int opaque)
{
    int pos;
    char c;
    char retval[1024];
    SDL_Surface *text, *ctext;
    SDL_Color tc, cc;
    SDL_Rect rect;
    SDL_Event event;
    Uint32 text_color = int_input_color0;
    Uint32 cursor_color = int_input_color1;
    Uint32 our_black = opaque ? int_solid_black : int_black;

    memset(retval, 0, sizeof(retval));
    retval[0] = ' ';
    pos = 1;

    SDL_GetRGB(text_color, screen->format, &tc.r, &tc.g, &tc.b);
    SDL_GetRGB(cursor_color, screen->format, &cc.r, &cc.g, &cc.b);

    ctext = TTF_RenderText_Blended(font, "_", cc); Assert(ctext);

    while (1) {
	int changed = 0;	/* did they change the text string? */
	int blink = 1;		/* toggle the blinking the cursor */
	Uint32  flip_when = SDL_GetTicks();
	/* display the current string */

	text = TTF_RenderText_Blended(font, retval, tc); Assert(text);

	rect.x = x;
	rect.y = y;
	rect.w = text->w;
	rect.h = text->h;

	SDL_BlitSurface(text, NULL, widget_layer, &rect);
	/* OK to ignore the intervening flame layer */
	SDL_BlitSurface(text, NULL, screen, &rect);
	SDL_UpdateSafe(screen, 1, &rect);

	rect.x += rect.w;
	rect.w = ctext->w;
	rect.h = ctext->h;

	changed = 0;
	while (!changed) { 
	    if (SDL_GetTicks() > flip_when) {
		if (blink) {
		    SDL_BlitSurface(ctext, NULL, screen, &rect);
		    SDL_BlitSurface(ctext, NULL, widget_layer, &rect);
		} else {
		    SDL_FillRect(widget_layer, &rect, our_black);
		    SDL_FillRect(screen, &rect, our_black);
		    SDL_BlitSurface(flame_layer, &rect, screen, &rect);
		    SDL_BlitSurface(widget_layer, &rect, screen, &rect);
		}
		SDL_UpdateSafe(screen, 1, &rect);
		flip_when = SDL_GetTicks() + 400;
		blink = !blink;
	    }
	    if (SDL_PollEvent(&event)) {
		if (event.type == SDL_KEYDOWN) {
		    changed = 1;
		    switch (event.key.keysym.sym) {
			case SDLK_RETURN:
			    return strdup(retval + 1);

			case SDLK_BACKSPACE:
			    if (pos > 1) pos--;
			    retval[pos] = 0;

			    rect.x = x;
			    rect.w = text->w + ctext->w;
			    SDL_FillRect(widget_layer, &rect, our_black);
			    SDL_FillRect(screen, &rect, our_black);
			    SDL_BlitSurface(flame_layer, &rect, screen, &rect);
			    SDL_BlitSurface(widget_layer, &rect, screen, &rect);
			    SDL_UpdateSafe(screen, 1, &rect);
			    break;

			default:
			    c = event.key.keysym.unicode;
			    if (c == 0) break;

			    SDL_FillRect(widget_layer, &rect, our_black);
			    SDL_FillRect(screen, &rect, our_black);
			    SDL_BlitSurface(flame_layer, &rect, screen, &rect);
			    SDL_BlitSurface(widget_layer, &rect, screen, &rect);
			    SDL_UpdateSafe(screen, 1, &rect);

			    if (isalpha(c) || isdigit(c) || isspace(c) || ispunct(c))
				retval[pos++] = c;
			    break;
		    }
		}
	    } else atris_run_flame();
	}
	SDL_FreeSurface(text);
    }
}
Exemple #5
0
/* Takes in SDL 32 bit RGB pixel and extracts each 8 bit channel. From these channels, performs
 * relevant comparisons to get which hue sector we are in (specifies Value), then attempts to find
 * the Saturation level by comparing to epsilon. Finally the hue degree is found from getting each
 * channel's chrominace and performing calculations depending on which hue sector we are calculated
 * to be in.
 */
struct hsv rgb_to_hsv(Uint32 pixel, SDL_PixelFormat *format)
{
    struct hsv hsv;
    double epsilon = 1e-5;
    Uint8 r, g, b;
    SDL_GetRGB(pixel, format, &r, &g, &b);

    double R = (double) r / PIXEL_MAXVAL;
    double G = (double) g / PIXEL_MAXVAL;
    double B = (double) b / PIXEL_MAXVAL;

    enum hue_sector {SECTOR_RED, SECTOR_GRN, SECTOR_BLU};
    enum hue_sector hue_sector;

    if (R >= G)
    {
        if (R >= B)
        {
            hue_sector = SECTOR_RED;
            hsv.v = R;
        }
        else
        {
            hue_sector = SECTOR_BLU;
            hsv.v = B;
        }
    }
    else
    {
        if (G >= B)
        {
            hue_sector = SECTOR_GRN;
            hsv.v = G;
        }
        else
        {
            hue_sector = SECTOR_BLU;
            hsv.v = B;
        }
    }

    double range = hsv.v - fmin(R, fmin(G, B));

    if (hsv.v < epsilon)
        hsv.s = 0.0;
    else
        hsv.s = range / hsv.v;

    if (range < epsilon)
        hsv.h = 0.0;        // It's gray so arbitrarily pick 0
    else
    {
        double cr = (hsv.v - R) / range;
        double cg = (hsv.v - G) / range;
        double cb = (hsv.v - B) / range;

        double angle;   // Hue angle (-30 to +330)

        switch (hue_sector)
        {
            case SECTOR_RED:
                angle = 0.0 + 60.0 * (cb - cg);
                break;
            case SECTOR_GRN:
                angle = 120.0 + 60.0 * (cr - cb);
                break;
            case SECTOR_BLU:
                angle = 240.0 + 60.0 * (cg - cr);
                break;
        }
        hsv.h = angle >= 0.0 ? angle : 360 + angle;
    }

    return hsv;
}
Exemple #6
0
    *init_try_folder(char *path) {
        FILE *fp = fopen(path, "r");
        
        if(fp == NULL)
        {
            printf("wrong path");
            abort();
        }

        char *path_tmp = NULL;
        char i_char[50] ={0};
        ssize_t read;
        size_t n = 0;
        read = getline(&path_tmp,&n,fp);

        size_t nb_line = atoi(path_tmp) -1 ;
        printf("%zu", nb_line);
        size_t nb_char = (26*2+10);
        struct try
            *trys = calloc(nb_line * nb_char, sizeof(struct try));
        init_sdl();
        for(size_t i = 0; i < nb_line; i++)
        {
            read = getline(&path_tmp,&n,fp);
            printf("%s", path_tmp);
            char tmp[50];
            scanf("%s", tmp);
            if(read)
            {
                path_tmp[read-1] = '\0';
                for(size_t j = 0; j < nb_char; j++)
                {
                    i_char[0]='\0';
                    sprintf(i_char, "%zu", j);

                    char full_path[500] = {0};
                    strcpy(full_path, path_tmp);
                    strcat(full_path, i_char);
                    strcat(full_path, ".png");

                    SDL_Surface *img = load_image(full_path);
                    trys[i*nb_char + j].in = calloc(16 * 16, sizeof(double));
                    
                    for(int k = 0; k < 16; k++)
                    {
                        for(int l = 0; l < 16; l++)
                        {
                            trys[i*nb_char + j].in[k * 16 + l] = 0;
                        }
                    }

                    for(int k = 0; k < img->h; k++)
                    {
                        for(int l = 0; l < img->w; l++)
                        {
                            Uint32 pixel = getpixel(img,l,k);
                            Uint8 r = 0, g = 0, b = 0;
                            SDL_GetRGB(pixel, img->format, &r, &g, &b);
                            Uint8 res = r * 0.3 + g * 0.59 + b * 0.11;
                           if (res < 127)
                           {
                                trys[i*nb_char + j].in[k * 16 + l] = 1;
                            
                            }
                            else
                            {
                                trys[i*nb_char + j].in[k * 16 + l] = 0;
 
                            }
                        }
                    }

                    printf("w : %d, h: %d\n", img->w, img->h);
                
                    for(int k = 0; k < 16; k++)
                    {
                        for(int l = 0; l < 16; l++)
                        {
                            if(trys[i*nb_char + j].in[k * 16 + l] == 1)
                               printf("1 ");
                            else
                               printf("0 "); 
                        }
                        printf("\n");
                    }
                    printf("\n");

                    trys[i*nb_char+j].res = calloc(nb_char, sizeof(double)); 
                    trys[i*nb_char+j].res[j] = 1;
                }
            }
        }
    return trys;
    }
void Draw_AALine(SDL_Surface* screen, float x0, float y0, float x1, float y1, uint32_t color){
	Uint8 r, g, b;
	SDL_GetRGB(color, screen->format, &r, &g, &b);
	Draw_AALine(screen, x0+0.5f, y0+0.5f, x1+0.5f, y1+0.5f, 1.0f, r, g, b, 0xFF);
}
void OriginalWorldObserver::updateMonitoring()
{
    // * Log at end of each generation
    //std::cout << gWorld->getIterations() << std::endl;
    if( _lifeIterationCount >= OriginalSharedData::gEvaluationTime ) // end of generation.
	{
		if ( gVerbose )
		{
            std::cout << "[gen:" << (gWorld->getIterations()/OriginalSharedData::gEvaluationTime)
                      << "]\n";
		}
        // Logging here
        double sumFitness = 0.0;
        int gatheredGenomes = 0;
        double forgetMeasure = 0.0;
        for ( int i = 0 ; i != gNumberOfRobots ; i++ )
        {

             sumFitness += (dynamic_cast<OriginalController*>(gWorld->getRobot(i)->getController()))
                     -> getFitness();
             OriginalController* ctrl = (dynamic_cast<OriginalController*>
                                         (gWorld->getRobot(i)->getController()));
             gatheredGenomes += (ctrl->_doEvoTopo? ctrl ->_genomesList.size():ctrl ->_genomesFList.size());

             if(ctrl -> _storedF.empty())
            {
                 forgetMeasure += -1.0;
            }
            else
            {
                forgetMeasure += ctrl -> forget();
            }
            //Forget measure for each robot ? what to do

        }
        //std::cout << gWorld->getIterations() << " ";
        //<< (sumFitness  / gNumberOfRobots) / Collect2SharedData::gEvaluationTime
        //average forget measure. TODO other estimator/or all the data?

            std::cout << sumFitness
                      //<< " " << (forgetMeasure/ gNumberOfRobots)
                      <<  std::endl;
	}

    if (gWorld->getIterations() == (gMaxIt - 1))
    {
        double sumFitness = 0.0;
        for ( int i = 0 ; i != gNumberOfRobots ; i++ )
        {

             sumFitness += (dynamic_cast<OriginalController*>(gWorld->getRobot(i)
                                                    ->getController()))-> getFitness();

        }

        std::cout << "End fitness: " << sumFitness  / gNumberOfRobots
                  << " at it: " << gWorld->getIterations() << std::endl;
        if(OriginalSharedData::gSaveGenome)
        {
            for (int i = 0 ; i != gNumberOfRobots ; i++ )
            {
                OriginalController* ctrl = (dynamic_cast<OriginalController*>(gWorld->getRobot(i)->getController()));
                if(!ctrl->_doEvoTopo)
                        ctrl -> logGenomeF(OriginalSharedData::gOutGenomeFile + std::to_string(i) + ".log");
                else
                {//TODO
                }
            }
        }

    }
    switch (OriginalSharedData::gFitness)
    {
        case 2:
            for(int i = 0; i < gNbOfPhysicalObjects;i++)
            {
                double color = -2.0;
                bool isSynchColor = false;
                if(listCollected[i].size() >= 2)
                {
                    //test if all agents (maybe more than 2) same color
                    for(auto it = listCollected[i].begin(); it != listCollected[i].end();it++)
                    {
                        if(color == -2.0)
                        {
                            color = it->second;
                            isSynchColor = true;
                        }
                        else
                        {
                            if(color != it->second)
                            {
                                isSynchColor = false;
                                break;
                            }
                        }
                    }
                    if(isSynchColor)
                    {
                        gPhysicalObjects[i]->isWalked(0); //Default agent for callback (unused callback)
                        for(auto it = listCollected[i].begin(); it != listCollected[i].end();it++)
                        {
                            //Share reward of one item between the agents involved
                            dynamic_cast<OriginalController*>(gWorld->getRobot(it->first)
                            ->getController())->updateFitness(1.0 / (double)listCollected[i].size());
                        }
                    }
                }
                listCollected[i].clear();
            }
            for(int i = 0; i < gNumberOfRobots; i++)
            {
                Uint8 r, g, b;
                RobotWorldModel* wm = gWorld->getRobot(i)->getWorldModel();
                Uint32 pixel = getPixel32( gGroundSensorImage, wm->_xReal+0.5, wm->_yReal+0.5);
                SDL_GetRGB(pixel,gGroundSensorImage->format,&r,&g,&b);
                wm->_groundSensorValue[0] = r;
                wm->_groundSensorValue[1] = g;
                wm->_groundSensorValue[2] = b;
            }

            break;
        default:
            break;
    }
    //TOERASE test seamless node mutation
    /*if(gWorld->getIterations() == 10000)
    {
        Helper::mutateLinkWeightsProb = 0.0;
        Helper::mutateAddNodeProb = 1.0;
        std::cout << "Now only node mutation" << std::endl;
    }*/
    if(gWorld->getIterations() ==
            OriginalSharedData::gTimeSeq[OriginalSharedData::gTaskIdx])
    {
        //std::cout << "----------------------------" << std::endl;
        //std::cout << "Task changed!" << std::endl;
        OriginalSharedData::gFitness =
                OriginalSharedData::gTaskSeq[OriginalSharedData::gTaskIdx];
        OriginalSharedData::gTaskIdx++;

        //Store representative for forget measure? For each robot? (previous task)
        for (int i = 0 ; i != gNumberOfRobots ; i++)
        {
            (dynamic_cast<OriginalController*>(gWorld->getRobot(i)->getController()))->storeRepresentative();
        }
    }
}
Exemple #9
0
static void envRenderEnvironment (Environment env, Camera *cam)
{
	double xh, yh, xv, yv, xhInc, xvInc, yhInc, yvInc;
	double angle, angleInc, tan_angle;
	int col;

	angle = cam->angle + cam->fov / 2;
	angleInc = cam->fov / cam->screen->w;

	for (col = 0; col < cam->screen->w; col++)
	{
		/* Normalize the angle value. */
		if      (angle <= 0.)       angle += 2 * M_PI;
		else if (angle > 2 * M_PI)  angle -= 2 * M_PI;

		tan_angle = tan (angle);

		/* TODO: What's up with the almost-zero decrement? */

		/* Find the first intersection with the horizontal grid. */
		/* Facing up or down? */
		if (angle < M_PI)
		{
			yh = floor (cam->y) - 10e-8;
			yhInc = -1;
			yvInc = -fabs (tan_angle);
		}
		else
		{
			yh = floor (cam->y) + 1;
			yhInc =  1;
			yvInc =  fabs (tan_angle);
		}
		xh = cam->x + (cam->y - yh) / tan_angle;

		/* Find the first intersection with the vertical grid. */
		/* To the left or to the right? */
		if (angle > M_PI_2 && angle < M_PI_2 * 3)
		{
			xv = floor (cam->x) - 10e-8;
			xvInc = -1;
			xhInc = -1 / fabs (tan_angle);
		}
		else
		{
			xv = floor (cam->x) + 1;
			xvInc =  1;
			xhInc =  1 / fabs (tan_angle);
		}
		yv = cam->y + (cam->x - xv) * tan_angle;

		/* FIXME: It should not pretend there's a wall behind the border. */
		/* There's a slight problem with looking back at the area with a map.
		 * We should somehow detect whether the ray will EVER hit a wall.
		 */

		/* Stop when either there's a wall or we've reached the border. */
		while (yh < env->map->height && yh >= 0
			&& xh < env->map->width  && xh >= 0
			&& !mapGetField (env->map, xh, yh))
		{
			xh += xhInc;
			yh += yhInc;
		}

		while (yv < env->map->height && yv >= 0
			&& xv < env->map->width  && xv >= 0
			&& !mapGetField (env->map, xv, yv))
		{
			xv += xvInc;
			yv += yvInc;
		}

		double distH, distV, dist, offset;
		int height, blockX, blockY, texId;

		/* Compute the distance to both intersections. */
		/* See http://www.permadi.com/tutorial/raycast/rayc8.html for optim. */
		distH = (xh - cam->x) * (xh - cam->x) + (yh - cam->y) * (yh - cam->y);
		distV = (xv - cam->x) * (xv - cam->x) + (yv - cam->y) * (yv - cam->y);

		/* Find the nearer intersection and texture offset. */
		if (distH < distV)
		{
			dist = sqrt (distH);
			offset = fmod (xh, 1.0);
			blockX = xh;
			blockY = yh;
		}
		else
		{
			dist = sqrt (distV);
			offset = fmod (yv, 1.0);
			blockX = xv;
			blockY = yv;
		}

		/* The texture ID is one less than the number in the map array. */
		if (blockX >= 0 && blockX < env->map->width
		 && blockY >= 0 && blockY < env->map->height)
			texId = mapGetField (env->map, blockX, blockY) - 1;
		else
			texId = 0;

		assert (texId < env->textures_len);

		/* Remove distortion. */
		/* TODO: Precompute into an array. */
		dist *= cos (angle - cam->angle);

		/* Compute the projected wall height. */
		height = cam->distance / dist;

		/* Draw the wall with a texture. */
		int i, yy, wallYStart, wallYStop;
		int texXPrecomp;
		double texYPrecomp;
		Uint32 pixel;

		texXPrecomp = offset * env->textures[texId]->w;
		texYPrecomp = (double) env->textures[texId]->h / height;

		if (height > cam->screen->h)
		{
			wallYStart = (height - cam->screen->h) / 2;
			wallYStop  =  height - wallYStart - 1;
		}
		else
		{
			wallYStart =  0;
			wallYStop  =  height;
		}

		for (i = wallYStart; i < wallYStop; i++)
		{
			yy = (cam->screen->h - height) / 2 + i;

			pixel = sdluGetPixel32Unsafe (env->textures[texId],
				texXPrecomp, (int) (i * texYPrecomp));

			/* Enhance the 3D effect a bit by darkening some walls. */
			if (distH < distV)
				pixel = (pixel >> 1) & 0x7F7F7F7F & ~RGB_AMASK;

			sdluPutPixel (cam->screen, col, yy,
				SDL_MapRGB (cam->screen->format,
				RGB_GETR (pixel), RGB_GETG (pixel), RGB_GETB (pixel)));

			/* Set the Z-buffer. */
			cam->zbuffer[yy * cam->screen->w + col] = dist;
		}

		/* Draw the floor. */
		double fdist, dx, dy;
		double fdistPrecomp;
		int k = 0;

		fdistPrecomp = cam->distance * cam->z / cos (angle - cam->angle);

		for (i = (cam->screen->h + height) / 2; i < cam->screen->h; i++)
		{
			fdist = fdistPrecomp / (i - cam->screen->h / 2);
			dx = fabs (fmod (fdist * cos (angle) + cam->x, 1.0));
			dy = fabs (fmod (fdist * sin (angle) - cam->y, 1.0));

			/* XXX: Hard-coded texture ID. */
			pixel = sdluGetPixel32Unsafe (env->textures[0],
				(int) (dx * env->textures[0]->w),
				(int) (dy * env->textures[0]->h));
			sdluPutPixel (cam->screen, col, i, SDL_MapRGB (cam->screen->format,
					RGB_GETR (pixel), RGB_GETG (pixel), RGB_GETB (pixel)));

			/* Some relatively low-cost glass effect. */
			if ((cam->renderFlags & GAME_FLAG_FLOOR_REFLECTION)
				&& k++ < GAME_FLOOR_REFLECTION_HEIGHT)
			{
				Uint8 xr, xg, xb;
				SDL_GetRGB (sdluGetPixel (cam->screen, col, i - 2 * k),
					cam->screen->format, &xr, &xg, &xb);
				sdluPutPixelAlpha (cam->screen, col, i,
					RGB_BUILDCOLOR_A (xr, xg, xb, 128 - (int)
					((double) k / GAME_FLOOR_REFLECTION_HEIGHT * 128)));
			}

			/* Set the Z-buffer. */
			cam->zbuffer[i * cam->screen->w + col]
				= fdist * cos (angle - cam->angle);
		}

		/* Advance to the next ray. */
		angle -= angleInc;
	}
}
Exemple #10
0
int main(int argc, char *argv[])
{
	/* initialize SDL and its subsystems */
	if (SDL_Init(SDL_INIT_EVERYTHING) == -1) die();
	if (TTF_Init() == -1) die();

	/* set the height and width of the main window, as well as the number
	   of bits per pixel; this needs to be done prior to initializing the 
	   main window (*screen, below) */
	initWindowAttributes();

	/* the frame buffer */
	SDL_Surface *screen = SDL_SetVideoMode(W_WIDTH, W_HEIGHT,
			W_COLOR_DEPTH, SDL_HWSURFACE|SDL_FULLSCREEN);
	if (!screen) die();

	/* hide the mouse cursor */
	SDL_ShowCursor(SDL_DISABLE);

	/* the background color of the screen */
	const Uint32 clearColor = CLEAR_COLOR(screen->format);
	clearScreen(screen, clearColor);

	/* clearColor as an SDL_Color, for use with TTF */
	Uint8 r, g, b;
	SDL_GetRGB(clearColor, screen->format, &r, &g, &b);
	SDL_Color bgColor = { r: r, g: g, b: b };

	/* the score font */
	TTF_Font *font = TTF_OpenFont("resources/VeraMono.ttf", FONT_SIZE);
	if (!font) die();
	SDL_Color fontColor = FONT_COLOR;

	/* the score text; we'll allow three digits plus the terminating '\0' */
	char *lScoreStr = malloc(sizeof(char) * 4);
	char *rScoreStr = malloc(sizeof(char) * 4);
	if (!lScoreStr || !rScoreStr) die();
	SDL_Surface *lScore = NULL, *rScore = NULL;
	SDL_Rect lScorePos = { x: C_X+FONT_SIZE, y: C_HEIGHT/5,
		w: F_WIDTH, h: F_HEIGHT };
	SDL_Rect rScorePos = { x: (C_X+C_WIDTH)-3*FONT_SIZE, y: C_HEIGHT/5,
		w: F_WIDTH, h: F_HEIGHT };

	/* set up the playing court */
	Court *court = makeCourt(screen);
	if (!court) die();

	/* set up the players and their paddles */
	Player *lPlayer = makePlayer(screen);
	Player *rPlayer = makePlayer(screen);
	if (!lPlayer || !rPlayer) die();
	rPlayer->paddle.rect.x = C_X + C_WIDTH - P_WIDTH;

	/* add the ball */
	Ball *ball = makeBall(screen);
	if (!ball) die();

	/* because SDL_KEY(UP|DOWN) occurs only once, not continuously while
	   the key is pressed, we need to keep track of whether a key is
	   (still) pressed */
	bool lPlayerShouldMoveUp = false, lPlayerShouldMoveDown = false,
	     rPlayerShouldMoveUp = false, rPlayerShouldMoveDown = false;

	Uint32 startTime;	/* denotes the beginning of each iteration
				   of the main event loop */
	bool running = true;	/* true till the application should exit */
	while (running) {
		startTime = SDL_GetTicks();

		/* clear the previous frame's paddles and ball */
		SDL_FillRect(screen, &lPlayer->paddle.rect, clearColor);
		SDL_FillRect(screen, &rPlayer->paddle.rect, clearColor);
		SDL_FillRect(screen, &ball->rect, clearColor);

		/* clear the previous frame's score */
		SDL_FillRect(screen, &lScorePos, clearColor);
		SDL_FillRect(screen, &rScorePos, clearColor);

		/* redraw the walls in case they were clipped by the ball
		   in a previous frame */
		SDL_FillRect(screen, &court->upperWall, court->color);
		SDL_FillRect(screen, &court->lowerWall, court->color);

		/* get the current state of the players' controls */
		readPlayerInput(&running,
				&lPlayerShouldMoveUp, &lPlayerShouldMoveDown,
				&rPlayerShouldMoveUp, &rPlayerShouldMoveDown);

		/* save the current position of the paddles */
		lPlayer->paddle.prevY = lPlayer->paddle.rect.y;
		rPlayer->paddle.prevY = rPlayer->paddle.rect.y;

		/* move the paddles if appropriate */
		if (lPlayerShouldMoveUp)
			movePaddle(court, &lPlayer->paddle, UP);
		else if (lPlayerShouldMoveDown)
			movePaddle(court, &lPlayer->paddle, DOWN);
		if (rPlayerShouldMoveUp)
			movePaddle(court, &rPlayer->paddle, UP);
		else if (rPlayerShouldMoveDown)
			movePaddle(court, &rPlayer->paddle, DOWN);

		/* move the ball */
		moveBall(court, ball, lPlayer, rPlayer);

		/* update the score */
		updateScore(ball, lPlayer, rPlayer);

		/* update the on-screen score */
		if (lScore) SDL_FreeSurface(lScore);
		snprintf(lScoreStr, 4, "%2d", lPlayer->points);
		lScore = TTF_RenderText_Shaded(font, lScoreStr, fontColor,
				bgColor);
		if (rScore) SDL_FreeSurface(rScore);
		snprintf(rScoreStr, 4, "%2d", rPlayer->points);
		rScore = TTF_RenderText_Shaded(font, rScoreStr, fontColor,
				bgColor);

		/* draw the score */
		SDL_BlitSurface(lScore, NULL, screen, &lScorePos);
		SDL_BlitSurface(rScore, NULL, screen, &rScorePos);

		/* draw the paddles */
		SDL_FillRect(screen, &lPlayer->paddle.rect,
				lPlayer->paddle.color);
		SDL_FillRect(screen, &rPlayer->paddle.rect,
				rPlayer->paddle.color);

		/* draw the ball */
		SDL_FillRect(screen, &ball->rect, ball->color);

		/* render frame to screen */
		SDL_Flip(screen);

		/* keep a steady frame rate */
		Uint8 elapsedTime = SDL_GetTicks() - startTime;
		if (elapsedTime < FRAME_DURATION)
			SDL_Delay(FRAME_DURATION - elapsedTime);
	}

	/* free resources */
	free(lScoreStr);
	free(rScoreStr);
	free(court);
	free(lPlayer);
	free(rPlayer);
	free(ball);

	TTF_CloseFont(font);
	TTF_Quit();
	SDL_FreeSurface(lScore);
	SDL_FreeSurface(rScore);
	SDL_Quit();

	return EXIT_SUCCESS;
}
Exemple #11
0
void GsTilemap::applyGalaxyHiColourMask()
{

    auto rawSDLSfc = mTileSurface.getSDLSurface();

#if SDL_VERSION_ATLEAST(2, 0, 0)
    SDL_Surface *newSfc =
            SDL_ConvertSurfaceFormat(rawSDLSfc, SDL_PIXELFORMAT_RGBA8888, 0);
#else
    SDL_Surface *blit = gVideoDriver.getBlitSurface();
    SDL_Surface *newSfc = SDL_ConvertSurface(rawSDLSfc, blit->format, 0 );
#endif


    mTileSurface.createFromSDLSfc(newSfc);

    const auto format = mTileSurface.getSDLSurface()->format;

#if SDL_VERSION_ATLEAST(2, 0, 0)
    mTileSurface.setBlendMode(SDL_BLENDMODE_BLEND);
#endif

    mTileSurface.lock();

    // Pointer of start pixel
    Uint8 *pxStart = static_cast<Uint8*>(mTileSurface.getSDLSurface()->pixels);

    // From 0 to half width for every row ...
    int midRow = mTileSurface.width()/2;

    const auto pitch = mTileSurface.getSDLSurface()->pitch;

    for( int y=0 ; y<mTileSurface.height() ; y++ )
    {
        Uint8 *pxRow = pxStart + y*pitch;
        for( int x=0 ; x<midRow ; x++ )
        {
            Uint8 *px = pxRow + x*format->BytesPerPixel;
            Uint8 *pxMask = px + midRow*format->BytesPerPixel;

            Uint32 pix = 0;
            Uint32 mask = 0;
            memcpy(&pix, px, format->BytesPerPixel);
            memcpy(&mask, pxMask, format->BytesPerPixel);

            // Get the mask part
            Uint8 mask_r, mask_g, mask_b;
            SDL_GetRGB(mask, format, &mask_r, &mask_g, &mask_b);

            // Get the color
            Uint8 r, g, b;
            SDL_GetRGB(pix, format, &r, &g, &b);

            // Calculate the new alpha, which will do the transparency and even allow translucency
            const Uint8 alpha = 255-(( (mask_r<<16) + (mask_g<<8) + mask_b ) >> 16);

            pix = SDL_MapRGBA( format, r, g, b, alpha );

            memcpy(px, &pix, format->BytesPerPixel);

        }
    }

    mTileSurface.unlock();
}
Exemple #12
0
void CreateTexture(unsigned int textureArray[],char *strFileName,int textureID)
{
    SDL_Surface *pBitmap[1];

    if( strFileName == NULL )                           // Return from the function if no file name was passed in
        return ;

    // We need to load the texture data, so we use a cool function that SDL offers.
    
    pBitmap[0] = SDL_LoadBMP(strFileName);              // Load the bitmap and store the data

    if(pBitmap[0] == NULL)                                // If we can't load the file, quit!
    {
        cerr << " Failed loading " << strFileName << " : " << SDL_GetError() << endl;
        Quit(0);
    }

    // Now that we have the texture data, we need to register our texture with OpenGL
    // To do this we need to call glGenTextures().  The 1 for the first parameter is
    // how many texture we want to register this time (we could do a bunch in a row).
    // The second parameter is the array index that will hold the reference to this texture.

    // Generate a texture with the associative texture ID stored in the array
    glGenTextures(1, &textureArray[textureID]);

    // Now that we have a reference for the texture, we need to bind the texture
    // to tell OpenGL this is the reference that we are assigning the bitmap data too.
    // The first parameter tells OpenGL we want are using a 2D texture, while the
    // second parameter passes in the reference we are going to assign the texture too.
    // We will use this function later to tell OpenGL we want to use this texture to texture map.

    // Bind the texture to the texture arrays index and init the texture
    glBindTexture(GL_TEXTURE_2D, textureArray[textureID]);

    // WARNING   : GO THROUGH THESE FEW LINES FOR SWAPPING ROWS ONLY IF YOU REALLY NEED TO, OR ELSE SKIP
    // THE LINES MARKED BELOW. Just take it for granted that these lines of code swap rows in the texture 
    // as required by us.
    
    // <SKIP> <SKIP> <SKIP> <SKIP>   (FROM HERE)        -------------------
    //
    // IMPORTANT : SDL loads Bitmaps differently when compared to the default windows loader. The row 0
    // corresponds to the top row and NOT the bottom row. Therefore if we don't invert the order of the rows,
    // then the textures will appear (vertically) inverted.
    // Therefore we must reverse the ordering of the rows in the data of the loaded surface ( the member
    //  'pixels' of the structure)
    
    // Rearrange the pixelData 
    
    int width  = pBitmap[0] -> w;
    int height = pBitmap[0] -> h;
    unsigned char * data = (unsigned char *) (pBitmap[0] -> pixels);         // the pixel data
    unsigned char * newData = new unsigned char[width*height*3];
    int channels = 3; // R,G,B

    int BytesPerPixel = pBitmap[0] -> format -> BytesPerPixel ; 

    //////////// This is how we swap the rows :
    // For half the rows, we swap row 'i' with row 'height - i -1'. (if we swap all the rows
    // like this and not the first half or the last half, then we get the same texture again !
    //
    // Now these rows are not stored as 2D arrays, instead they are stored as a long 1D array.
    // So each row is concatenated after the previous one to make this long array. Our swap 
    // function swaps one byte at a time and therefore we swap BytesPerPixel (= total bits per pixel)
    // bytes succesively.
    //
    // so the three loops below are :
    // for the first half of the rows
    //   for all the width (which is width of image * BytesPerPixel, where BytesPerPixel = total bits per pixel).
    //   (Here, for each pixel, we have to increment j by total bits per pixel (to get to next pixel to swap))
    //      for(each byte in this pixel i.e k = 0 to BytesPerPixel - 1, i.e BytesPerPixel bytes.
    //        swap the byte with the corresponding byte in the 'height -i -1'th row ('i'th row from bottom)
    for( int i = 0 ; i < (height / 2) ; ++i )
        for( int j = 0 ; j < width * BytesPerPixel; j += BytesPerPixel )
            for(int k = 0; k < BytesPerPixel; ++k)
                swap( data[ (i * width * BytesPerPixel) + j + k], data[ ( (height - i - 1) * width * BytesPerPixel ) + j + k]);
 
    // </SKIP> </SKIP> </SKIP> </SKIP>    (TO HERE)   -------------------
   
    // the following lines extract R,G and B values from any bitmap

    for(int i = 0; i < (width * height); ++i)
    {
        byte r,g,b;                                                // R,G and B that we will put into pImage

        Uint32 pixel_value = 0;                                    // 32 bit unsigned int (as dictated by SDL)

        // the following loop extracts the pixel (however wide it is 8,16,24 or 32) and 
        // creates a long with all these bytes taken together.
        
        for(int j = BytesPerPixel - 1 ; j >=0; --j)                // for each byte in the pixel (from the right)
        {
            pixel_value = pixel_value << 8;                        // left shift pixel value by 8 bits
            pixel_value = pixel_value | data[ (i * BytesPerPixel) + j ];  // then make the last 8 bits of pixel value  =
        }                                                                 // the byte that we extract from pBitmap's data

        SDL_GetRGB(pixel_value, pBitmap[0] -> format, (Uint8 *)&r, (Uint8 *)&g, (Uint8 *)&b);     // here we get r,g,b from pixel_value which is stored in the form specified by pBitmap->format

        newData[(i * channels) + 0] = r;          // in our tImage classes we store r first
        newData[(i * channels) + 1] = g;          // then g
        newData[(i * channels) + 2] = b;          // and finally b (for bmps - three channels only)

        pixel_value = 0;                                           // reset pixel , else we get incorrect values of r,g,b
    }


    // Now comes the important part, we actually pass in all the data from the bitmap to
    // create the texture. Here is what the parameters mean in gluBuild2DMipmaps():
    // (We want a 2D texture, 3 channels (RGB), bitmap width, bitmap height, It's an RGB format,
    //  the data is stored as unsigned bytes, and the actuall pixel data);

    // What is a Mip map?  Mip maps are a bunch of scaled pictures from the original.  This makes
    // it look better when we are near and farther away from the texture map.  It chooses the
    // best looking scaled size depending on where the camera is according to the texture map.
    // Otherwise, if we didn't use mip maps, it would scale the original UP and down which would
    // look not so good when we got far away or up close, it would look pixelated.

    // Build Mipmaps (builds different versions of the picture for distances - looks better)

    // Build Mipmaps (builds different versions of the picture for distances - looks better)
    gluBuild2DMipmaps(GL_TEXTURE_2D, 3, pBitmap[0]->w, pBitmap[0]->h, GL_RGB, GL_UNSIGNED_BYTE, newData);

    // Lastly, we need to tell OpenGL the quality of our texture map.  GL_LINEAR_MIPMAP_LINEAR
    // is the smoothest.  GL_LINEAR_MIPMAP_NEAREST is faster than GL_LINEAR_MIPMAP_LINEAR, 
    // but looks blochy and pixilated.  Good for slower computers though.  Read more about 
    // the MIN and MAG filters at the bottom of main.cpp
    glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);    
    glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR_MIPMAP_NEAREST);

    // Now we need to free the bitmap data that we loaded since openGL stored it as a texture
    delete [] newData;
    
    SDL_FreeSurface(pBitmap[0]);                        // Free the texture data we dont need it anymore
}
Exemple #13
0
Uint32 SetColor(Uint32 color, int newcolor1, int newcolor2, int newcolor3)
{
    Uint8 r,g,b;
    Uint8 intensity;
    int newcolor;
    SDL_GetRGB(color, screen->format, &r, &g, &b);
    if((r == 0) && (g == 0) && (b != 0))
    {
        intensity = b;
        newcolor = newcolor3;
    }
    else if((r == 0) && (b == 0) && (g != 0))
		 {
			 intensity = g;
			 newcolor = newcolor2;
		 }
		 else if((g == 0) && (b == 0) && (r != 0))
			  {
				  intensity = r;
				  newcolor = newcolor1;
			  }
			  else return color;
    switch(newcolor)
    {
        case Red:
            r = intensity;
            g = (Uint8)(intensity * 0.2);
            b = (Uint8)(intensity * 0.2);
            break;
        case Green:
            r = (Uint8)(intensity * 0.2);
            g = intensity;
            b = (Uint8)(intensity * 0.2);
            break;
        case Blue:
            r = (Uint8)(intensity * 0.2);
            g = (Uint8)(intensity * 0.2);
            b = intensity;
            break;
        case Yellow:
            r = (Uint8)(intensity * 0.8);
            g = (Uint8)(intensity * 0.8);
            b = (Uint8)(intensity * 0.2);
            break;
        case Orange:
            r = intensity;
            g = (Uint8)(intensity * 0.5);
            b = (Uint8)(intensity * 0.2);
            break;
        case Violet:
            r = (Uint8)(intensity * 0.8);
            g = (Uint8)(intensity * 0.2);
            b = (Uint8)(intensity * 0.8);
            break;
        case Brown:
            r = (Uint8)(intensity * 0.8);
            g = (Uint8)(intensity * 0.3);
            b = (Uint8)(intensity * 0.25);
            break;
        case Grey:
            r = (Uint8)(intensity * 0.5);
            g = (Uint8)(intensity * 0.5);
            b = (Uint8)(intensity * 0.5);
            break;
        case DarkRed:
            r = (Uint8)(intensity * 0.8);
            g = 0;
            b = 0;
            break;
        case DarkGreen:
            r = 0;
            g = (Uint8)(intensity * 0.8);
            b = 0;
            break;
        case DarkBlue:
            r = 0;
            g = 0;
            b = (Uint8)(intensity * 0.8);
            break;
        case DarkYellow:
            r = (Uint8)(intensity * 0.6);
            g = (Uint8)(intensity * 0.6);
            b = 0;
            break;
        case DarkOrange:
            r = (Uint8)(intensity * 0.8);
            g = (Uint8)(intensity * 0.4);
            b = (Uint8)(intensity * 0.1);
            break;
        case DarkViolet:
            r = (Uint8)(intensity * 0.6);
            g = 0;
            b = (Uint8)(intensity * 0.6);
            break;
        case DarkBrown:
            r = (Uint8)(intensity * 0.3);
            g = (Uint8)(intensity * 0.2);
            b = (Uint8)(intensity * 0.1);
            break;
        case DarkGrey:
            r = (Uint8)(intensity * 0.3);
            g = (Uint8)(intensity * 0.3);
            b = (Uint8)(intensity * 0.3);
            break;
        case LightRed:
            r = intensity;
            g = (Uint8)(intensity * 0.45);
            b = (Uint8)(intensity * 0.45);
            break;
        case LightGreen:
            r = (Uint8)(intensity * 0.45);
            g = intensity;
            b = (Uint8)(intensity * 0.45);
            break;
        case LightBlue:
            r = (Uint8)(intensity * 0.45);
            b = intensity;
            g = (Uint8)(intensity * 0.45);
            break;
        case LightYellow:
            r = intensity;
            g = intensity;
            b = (Uint8)(intensity * 0.45);
            break;
        case LightOrange:
            r = intensity;
            g = (Uint8)(intensity * 0.75);
            b = (Uint8)(intensity * 0.35);
            break;
        case LightViolet:
            r = intensity;
            g = (Uint8)(intensity * 0.45);
            b = intensity;
            break;
        case LightBrown:
            r = intensity;
            g = (Uint8)(intensity * 0.85);
            b = (Uint8)(intensity * 0.45);
            break;
        case LightGrey:
            r = (Uint8)(intensity * 0.85);
            g = (Uint8)(intensity * 0.85);
            b = (Uint8)(intensity * 0.85);
            break;
        case Black:
            r = (Uint8)(intensity * 0.15);
            g = (Uint8)(intensity * 0.15);
            b = (Uint8)(intensity * 0.15);
            break;
        case White:
            r = intensity;
            g = intensity;
            b = intensity;
            break;
        case Tan:
            r = intensity;
            g = (Uint8)(intensity * 0.9);
            b = (Uint8)(intensity * 0.6);
            break;
        case Gold:
            r = (Uint8)(intensity * 0.9);
            g = (Uint8)(intensity * 0.8);
            b = (Uint8)(intensity * 0.3);
            break;
        case Silver:
            r = (Uint8)(intensity * 0.99);
            g = (Uint8)(intensity * 0.99);
            b = intensity;
            break;
        case YellowGreen:
            r = (Uint8)(intensity * 0.5);
            g = (Uint8)(intensity * 0.8);
            b = (Uint8)(intensity * 0.3);
            break;
        case Cyan:
            r = 0;
            g = (Uint8)(intensity * 0.9);
            b = (Uint8)(intensity * 0.9);
            break;
        case Magenta:
            r = (Uint8)(intensity * 0.8);
            g = 0;
            b = (Uint8)(intensity * 0.8);
            break;
		default:
			r = 0;
			g = (Uint8)(intensity * 0.9);
			b = (Uint8)(intensity * 0.9);
			break;
    }
	color = SDL_MapRGB(screen->format, r, g, b);
    
	return color;
}
Exemple #14
0
void particle::draw(SDL_Surface*s)
{
	float xstep = 1.0/s->w;
	float ystep = 1.0/s->h;
	float total=0;
	float x0 = x > size? -size : -x;
	float x1 = x < 1-size? size : 1-x;
	float y0 = y > size? -size : -y;
	float y1 = y < 1-size? size : 1-y;
	for (float i = x0 ; i < x1; i+=xstep)
	{
		for (float j = y0; j < y1; j+=ystep)
		{
			float aa = 0;
			//simple filter, test four coordinates in the square to see if they are in the circle
			if ((i + xstep) * (i + xstep) + (j + ystep) * (j + ystep) < size * size)
				aa += .25;
			if ((i - xstep) * (i - xstep) + (j + ystep) * (j + ystep) < size * size)
				aa += .25;
			if ((i + xstep) * (i + xstep) + (j - ystep) * (j - ystep) < size * size)
				aa += .25;
			if ((i - xstep) * (i - xstep) + (j - ystep) * (j - ystep) < size * size)
				aa += .25;
			total += aa;
			Uint8 r,g,b;
			Uint8 nr,ng,nb;
			SDL_GetRGB(PIXEL(s, (x + i)*s->w, (y+j)*s->h), s->format, &r, &g, &b);
			SDL_GetRGB(color, s->format, &nr, &ng, &nb);
			if (nr * aa + r > 255)
				r = 255;
			else
				r = nr * aa + r;
			if (ng * aa + g > 255)
				g = 255;
			else
				g = ng * aa + g;
			if (nb * aa + b > 255)
				b = 255;
			else
				b = nb * aa + b;
			
			PIXEL(s, (x + i) * s->w , (y+j)*s->h ) = SDL_MapRGB(s->format, r, g, b);

		}
	}
	//if no pixels have been set, set a bare minimum
	if (total < .24) 
	{
		float aa = .25;
		Uint8 r,g,b;
		Uint8 nr,ng,nb;
		SDL_GetRGB(PIXEL(s, (x )*s->w, (y)*s->h), s->format, &r, &g, &b);
		SDL_GetRGB(color, s->format, &nr, &ng, &nb);
		if (nr * aa + r > 255)
			r = 255;
		else
			r = nr * aa + r;
		if (ng * aa + g > 255)
			g = 255;
		else
			g = ng * aa + g;
		if (nb * aa + b > 255)
			b = 255;
		else
			b = nb * aa + b;
		
		PIXEL(s, (x ) * s->w , (y)*s->h ) = SDL_MapRGB(s->format, r, g, b);
	}
}
Exemple #15
0
/****************************************************************************
 * DecodeBlock: the whole thing
 ****************************************************************************
 * This function must be fed with a complete compressed frame.
 ****************************************************************************/
static picture_t *DecodeBlock( decoder_t *p_dec, block_t **pp_block )
{
    decoder_sys_t *p_sys = p_dec->p_sys;
    block_t *p_block;
    picture_t *p_pic = NULL;
    SDL_Surface *p_surface;
    SDL_RWops *p_rw;

    if( pp_block == NULL || *pp_block == NULL ) return NULL;
    p_block = *pp_block;

    if( p_block->i_flags & BLOCK_FLAG_DISCONTINUITY )
    {
        block_Release( p_block ); *pp_block = NULL;
        return NULL;
    }

    p_rw = SDL_RWFromConstMem( p_block->p_buffer, p_block->i_buffer );

    /* Decode picture. */
    p_surface = IMG_LoadTyped_RW( p_rw, 1, (char*)p_sys->psz_sdl_type );
    if ( p_surface == NULL )
    {
        msg_Warn( p_dec, "SDL_image couldn't load the image (%s)",
                  IMG_GetError() );
        goto error;
    }

    switch ( p_surface->format->BitsPerPixel )
    {
    case 16:
        p_dec->fmt_out.i_codec = VLC_CODEC_RGB16;
        break;
    case 8:
    case 24:
        p_dec->fmt_out.i_codec = VLC_CODEC_RGB24;
        break;
    case 32:
        p_dec->fmt_out.i_codec = VLC_CODEC_RGB32;
        break;
    default:
        msg_Warn( p_dec, "unknown bits/pixel format (%d)",
                  p_surface->format->BitsPerPixel );
        goto error;
    }
    p_dec->fmt_out.video.i_width = p_surface->w;
    p_dec->fmt_out.video.i_height = p_surface->h;
    p_dec->fmt_out.video.i_aspect = VOUT_ASPECT_FACTOR * p_surface->w
                                     / p_surface->h;

    /* Get a new picture. */
    p_pic = decoder_NewPicture( p_dec );
    if ( p_pic == NULL ) goto error;

    switch ( p_surface->format->BitsPerPixel )
    {
        case 8:
        {
            int i, j;
            uint8_t *p_src, *p_dst;
            uint8_t r, g, b;
            for ( i = 0; i < p_surface->h; i++ )
            {
                p_src = (uint8_t*)p_surface->pixels + i * p_surface->pitch;
                p_dst = p_pic->p[0].p_pixels + i * p_pic->p[0].i_pitch;
                for ( j = 0; j < p_surface->w; j++ )
                {
                    SDL_GetRGB( *(p_src++), p_surface->format,
                                &r, &g, &b );
                    *(p_dst++) = r;
                    *(p_dst++) = g;
                    *(p_dst++) = b;
                }
            }
            break;
        }
        case 16:
        {
            int i;
            uint8_t *p_src = p_surface->pixels;
            uint8_t *p_dst = p_pic->p[0].p_pixels;
            int i_pitch = p_pic->p[0].i_pitch < p_surface->pitch ?
                p_pic->p[0].i_pitch : p_surface->pitch;

            for ( i = 0; i < p_surface->h; i++ )
            {
                vlc_memcpy( p_dst, p_src, i_pitch );
                p_src += p_surface->pitch;
                p_dst += p_pic->p[0].i_pitch;
            }
            break;
        }
        case 24:
        {
            int i, j;
            uint8_t *p_src, *p_dst;
            uint8_t r, g, b;
            for ( i = 0; i < p_surface->h; i++ )
            {
                p_src = (uint8_t*)p_surface->pixels + i * p_surface->pitch;
                p_dst = p_pic->p[0].p_pixels + i * p_pic->p[0].i_pitch;
                for ( j = 0; j < p_surface->w; j++ )
                {
                    SDL_GetRGB( *(uint32_t*)p_src, p_surface->format,
                                &r, &g, &b );
                    *(p_dst++) = r;
                    *(p_dst++) = g;
                    *(p_dst++) = b;
                    p_src += 3;
                }
            }
            break;
        }
        case 32:
        {
            int i, j;
            uint8_t *p_src, *p_dst;
            uint8_t r, g, b, a;
            for ( i = 0; i < p_surface->h; i++ )
            {
                p_src = (uint8_t*)p_surface->pixels + i * p_surface->pitch;
                p_dst = p_pic->p[0].p_pixels + i * p_pic->p[0].i_pitch;
                for ( j = 0; j < p_surface->w; j++ )
                {
                    SDL_GetRGBA( *(uint32_t*)p_src, p_surface->format,
                                &r, &g, &b, &a );
                    *(p_dst++) = b;
                    *(p_dst++) = g;
                    *(p_dst++) = r;
                    *(p_dst++) = a;
                    p_src += 4;
                }
            }
            break;
        }
    }

    p_pic->date = p_block->i_pts > 0 ? p_block->i_pts : p_block->i_dts;

    SDL_FreeSurface( p_surface );
    block_Release( p_block ); *pp_block = NULL;
    return p_pic;

error:
    if ( p_surface != NULL ) SDL_FreeSurface( p_surface );
    block_Release( p_block ); *pp_block = NULL;
    return NULL;
}
Exemple #16
0
void CreateTexture(unsigned int textureArray[],char *strFileName,int textureID)
{
    SDL_Surface *pBitmap[1];

    if( strFileName == NULL )                           // Return from the function if no file name was passed in
        return ;

    // We need to load the texture data, so we use a cool function that SDL offers.
    
    pBitmap[0] = SDL_LoadBMP(strFileName);              // Load the bitmap and store the data

    if(pBitmap[0] == NULL)                                // If we can't load the file, quit!
    {
        cerr << " Failed loading " << strFileName << " : " << SDL_GetError() << endl;
        Quit(0);
    }

    // Generate a texture with the associative texture ID stored in the array
    glGenTextures(1, &textureArray[textureID]);

    // Bind the texture to the texture arrays index and init the texture
    glBindTexture(GL_TEXTURE_2D, textureArray[textureID]);

    // WARNING   : GO THROUGH THESE FEW LINES FOR SWAPPING ROWS ONLY IF YOU REALLY NEED TO, OR ELSE SKIP
    // THE LINES MARKED BELOW. Just take it for granted that these lines of code swap rows in the texture 
    // as required by us.
    
    // <SKIP> <SKIP> <SKIP> <SKIP>   (FROM HERE)        -------------------
    //
    // IMPORTANT : SDL loads Bitmaps differently when compared to the default windows loader. The row 0
    // corresponds to the top row and NOT the bottom row. Therefore if we don't invert the order of the rows,
    // then the textures will appear (vertically) inverted.
    // Therefore we must reverse the ordering of the rows in the data of the loaded surface ( the member
    //  'pixels' of the structure)
    
    // Rearrange the pixelData 
    
    int width  = pBitmap[0] -> w;
    int height = pBitmap[0] -> h;
    unsigned char * data = (unsigned char *) (pBitmap[0] -> pixels);         // the pixel data

    int BytesPerPixel = pBitmap[0] -> format -> BytesPerPixel;

    //////////// This is how we swap the rows :
    // For half the rows, we swap row 'i' with row 'height - i -1'. (if we swap all the rows
    // like this and not the first half or the last half, then we get the same texture again !
    //
    // Now these rows are not stored as 2D arrays, instead they are stored as a long 1D array.
    // So each row is concatenated after the previous one to make this long array. Our swap 
    // function swaps one byte at a time and therefore we swap BytesPerPixel (= total bits per pixel)
    // bytes succesively.
    //
    // so the three loops below are :
    // for the first half of the rows
    //   for all the width (which is width of image * BytesPerPixel, where BytesPerPixel = total bits per pixel).
    //   (Here, for each pixel, we have to increment j by total bits per pixel (to get to next pixel to swap))
    //      for(each byte in this pixel i.e k = 0 to BytesPerPixel - 1, i.e BytesPerPixel bytes.
    //        swap the byte with the corresponding byte in the 'height -i -1'th row ('i'th row from bottom)
    for( int i = 0 ; i < (height / 2) ; ++i )
        for( int j = 0 ; j < width * BytesPerPixel; j += BytesPerPixel )
            for(int k = 0; k < BytesPerPixel; ++k)
                swap( data[ (i * width * BytesPerPixel) + j + k], data[ ( (height - i - 1) * width * BytesPerPixel ) + j + k]);
    
    unsigned char *pixels = new unsigned char[width * height * 3];

    int count = 0;
    
    // the following lines extract R,G and B values from any bitmap

    for(int i = 0; i < (width * height); ++i)
    {
        byte r,g,b;                                                // R,G and B that we will put into pImage

        Uint32 pixel_value = 0;                                    // 32 bit unsigned int (as dictated by SDL)

        // the following loop extracts the pixel (however wide it is 8,16,24 or 32) and 
        // creates a long with all these bytes taken together.
        
        for(int j = BytesPerPixel - 1 ; j >=0; --j)                // for each byte in the pixel (from the right)
        {
            pixel_value = pixel_value << 8;                        // left shift pixel value by 8 bits
            pixel_value = pixel_value | data[ (i * BytesPerPixel) + j ];  // then make the last 8 bits of pixel value  =
        }                                                                 // the byte that we extract from pBitmap's data

        SDL_GetRGB(pixel_value, pBitmap[0] -> format, (Uint8 *)&r, (Uint8 *)&g, (Uint8 *)&b);     // here we get r,g,b from pixel_value which is stored in the form specified by pBitmap->format

        pixels[count++] = r;          // in our tImage classes we store r first
        pixels[count++] = g;          // then g
        pixels[count++] = b;          // and finally b (for bmps - three channels only)
        /*pixels[(i * BytesPerPixel) + 0] = r;          // in our tImage classes we store r first
        pixels[(i * BytesPerPixel) + 1] = g;          // then g
        pixels[(i * BytesPerPixel) + 2] = b;          // and finally b (for bmps - three channels only)*/

        pixel_value = 0;                                           // reset pixel , else we get incorrect values of r,g,b
    }


    // </SKIP> </SKIP> </SKIP> </SKIP>    (TO HERE)   -------------------
    
    // Build Mipmaps (builds different versions of the picture for distances - looks better)
    gluBuild2DMipmaps(GL_TEXTURE_2D, 3, pBitmap[0]->w, pBitmap[0]->h, GL_RGB, GL_UNSIGNED_BYTE, pixels);

    // Lastly, we need to tell OpenGL the quality of our texture map.  GL_LINEAR is the smoothest.    
    glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);    
    glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR_MIPMAP_NEAREST);
    glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);

    // Now we need to free the bitmap data that we loaded since openGL stored it as a texture
    
    SDL_FreeSurface(pBitmap[0]);                        // Free the texture data we dont need it anymore
}
//propagate - propagation of the classical ball during dt milliseconds
// 
// it propagates the ball in mini-steps, each moving forward oonly one pixel
// according to the following scheme
//
//	1. move the ball one pixel ("trial move")
//  2. check for a wall collision (either with the hole or the 
//     "hard" part of the potential)
//	   In case of a collision, undo the trial move and change the velocity
//  3. Modify the velocity according to the soft potential
//  4. apply friction
//  5. goto 1
int ClassicSimulator::propagate(Uint32 dt){

	float speed = sqrt(vel[0]*vel[0] + vel[1]*vel[1]);

	// determine, how much 1-pixel will be neccessary during dt
	int steps = (int)(speed*dt); 
	float t, tic = 1/speed; // tic: time increment during a 1-pixel step

	// normalized components of the velocity
	float nvx = vel[0]/speed; 
	float nvy = vel[1]/speed;
	
	float slow = .001, shrink;

	Uint32 *sdat = (Uint32 *)(soft->pixels);
	Uint32 *hdat = (Uint32 *)(hard->pixels);
	
	bool hit = false; // have we hit a wall ?

	int x, y, xx, yy, xl, xu, yl, yu;
	float wx, wy, wn; // direction of the wall normal and wall vector length at a collision
	unsigned char pot = 0, mops;
	unsigned char lpot, rpot, upot, dpot; //potentials left /right / up /down the current position
										// used to compute potential gradient;
	bool inhole;

	// do steps iterations, each tic long, moving each time one pixel 
	// tic may change during the propagation due to a changing speed !
	for(t=0; t<dt; t+=tic){

		//check whether we are in the hole
		inhole = (holer*holer > 
			(pos[0]-holex)*(pos[0]-holex) + 
			(pos[1]-holey)*(pos[1]-holey) );

		// move the ball forward one pixel, check for collision
		pos[0] += nvx; pos[1] += nvy;
		x = (int)(pos[0]); y = (int)(pos[1]);
		if(pos[0] < 5) pos[0] = 5;
		if(pos[0] > width-5) pos[0] = width-5;
		if(pos[1] < 5) pos[1] = 5;
		if(pos[1] > height-5) pos[1] = height-5;

		// check whether we have left the hole, if so, simulate a wall 
		// collision to reflect from the hole wall
		if(inhole && (holer*holer < 
			(pos[0]-holex)*(pos[0]-holex) + 
			(pos[1]-holey)*(pos[1]-holey) )){
				hit = true;
				wx = pos[0]-holex; wy = pos[1]-holey;
				wn = sqrt(wx*wx+wy*wy);
				wx /= wn; wy /= wn;
		}
		// check whether we have collided with a potential wall
		SDL_GetRGB(hdat[y*width+x], hard->format, &pot, &mops, &mops);
		if(pot == 255 ){ // collision detected, determine the wall normal
						 // by taking the potential-weighted position average 
						 // in the 8x8 square around as
			hit = true;
			wx = 0; wy = 0;
			xl = x-3; if (xl < 0) xl=0;
			xu = x+4; if (xu > width) xu=width;
			yl = y-3; if (xl < 0) yl=0;
			yu = y+4; if (yu > height) yu=height;

			for(xx=xl; xx<xu; xx++){
				for(yy=yl; yy<yu; yy++){
					SDL_GetRGB(	hdat[yy*width+xx], hard->format, 
								&pot, &mops, &mops);
						wx += pot*(x-xx); wy += pot * (y-yy);
				}
			}
			wn = sqrt(wx*wx+wy*wy);
			wx /= wn;
			wy /= wn;
		}
		// we have been hit and know the wall normal
		// => undo test move to get off from the wall
		if(hit){
			pos[0] -= nvx; pos[1] -= nvy;
			x = (int)(pos[0]); y = (int)(pos[1]);

			float sp = vel[0]*wx + vel[1]*wy;
			float cvx = vel[0] - sp*wx; 
			float cvy = vel[1] - sp*wy; 
			vel[0] = -wx*sp +cvx; vel[1] = -wy*sp + cvy;

			nvx = vel[0]/speed;
			nvy = vel[1]/speed;
			hit=false;
		}

		//change velocity according to potential gradient
		if(y>0 && y<height-1 && x>0 && x<width-1){
			SDL_GetRGB(sdat[y*width+x-1], soft->format, &lpot, &mops, &mops);
			SDL_GetRGB(sdat[y*width+x+1], soft->format, &rpot, &mops, &mops);
			SDL_GetRGB(sdat[(y-1)*width+x], soft->format, &upot, &mops, &mops);
			SDL_GetRGB(sdat[(y+1)*width+x], soft->format, &dpot, &mops, &mops);
			vel[0] -= .002/1.2*tic*(rpot-lpot);
			vel[1] += .002/1.2*tic*(upot-dpot);
		}

		//simulate friction and update tic length due to changed speed
		speed = sqrt(vel[0]*vel[0] + vel[1]*vel[1]);
		shrink = 1 - tic*slow/speed; if(shrink<=0)shrink=0;
		speed *= shrink;
		vel[0]*= shrink; vel[1]*= shrink;
		if(speed==0)tic=1e4;
		else  tic = 1/speed;
	}
	
	if(speed ==0 )
		return 1;
	else
		return 0;
}
Exemple #18
0
/* temporary measure! */
void CGUI::InstallResource(int id, char *i, char *m)
{
	char *img = GetHost()->ResolveFileName(i);
	char *msk = GetHost()->ResolveFileName(m);
	CUEFChunkSelector *GFXFile = GetHost()->GetUEFSelector("%GFXPATH%/guidata.uef", 0x0000);

	SDL_Surface *Image = SDL_LoadBMP(img);
	if(!Image) { delete[] img; delete[] msk; return; }
	SDL_Surface *Mask = msk ? SDL_LoadBMP(msk) : NULL;
	if(Mask)
	{
		/* okay, build composite bitmap of gfx data and alpha channel */

		int rmask, gmask, bmask, amask;
#if SDL_BYTEORDER == SDL_BIG_ENDIAN
		rmask = 0xff000000;
	    gmask = 0x00ff0000;
		bmask = 0x0000ff00;
	    amask = 0x000000ff;
#else
	    rmask = 0x000000ff;
	    gmask = 0x0000ff00;
	    bmask = 0x00ff0000;
	    amask = 0xff000000;
#endif

		SDL_Surface *Composite = SDL_CreateRGBSurface(SDL_SRCALPHA, Image->w, Image->h, 32, rmask, gmask, bmask, amask);

		SDL_Surface *T = SDL_ConvertSurface(Image, Composite->format, 0);
		SDL_FreeSurface(Image); Image = T; 

		SDL_LockSurface(Composite);
		SDL_LockSurface(Image);
		SDL_LockSurface(Mask);

		for(int y = 0; y < Image->h; y++)
		{
			for(int x = 0; x < Image->w; x++)
			{
				int Component = 3;
				while(Component--)
					((Uint8 *)Composite->pixels)[y*Composite->pitch + (x << 2) + Component] = 
					((Uint8 *)Image->pixels)[y*Image->pitch + (x << 2) + Component];

				((Uint8 *)Composite->pixels)[y*Composite->pitch + (x << 2) + 3] = ((Uint8 *)Mask->pixels)[y*Mask->pitch + x];
			}
		}

		SDL_UnlockSurface(Composite);
		SDL_UnlockSurface(Image);
		SDL_UnlockSurface(Mask);

		SDL_FreeSurface(Mask);
		SDL_FreeSurface(Image);

		SrcResources[id] = Composite;
	}
	else
		SrcResources[id] = Image;

	CUEFChunk *NewChunk = GFXFile->EstablishChunk();
	NewChunk->SetId(0xff01 + id);

	/* type: paletted, 24bpp or 32bpp */
	switch(SrcResources[id]->format->BytesPerPixel)
	{
		case 1:	NewChunk->PutC(0); break;
		default:NewChunk->PutC(1); break;
		case 4:	NewChunk->PutC(2); break;
	}

	/* dimensions */
	NewChunk->Put16(SrcResources[id]->w);
	NewChunk->Put16(SrcResources[id]->h);

	/* image data */
	SDL_LockSurface(SrcResources[id]);
	switch(SrcResources[id]->format->BytesPerPixel)
	{
		case 1:
		{
			Uint8 *PelPtr = (Uint8 *)SrcResources[id]->pixels;
			for(int y = 0; y < SrcResources[id]->h; y++)
			{
				NewChunk->Write(PelPtr, SrcResources[id]->w);
				PelPtr += SrcResources[id]->pitch;
			}
		}
		break;

		case 3:
		{
			for(int y = 0; y < SrcResources[id]->h; y++)
			{
				for(int x = 0; x < SrcResources[id]->w; x++)
				{
					Uint8 R, G, B;
					SDL_GetRGB(*((Uint32 *)&((Uint8 *)SrcResources[id]->pixels)[ (SrcResources[id]->pitch*y) + x*SrcResources[id]->format->BytesPerPixel]), SrcResources[id]->format, &R, &G, &B);

					NewChunk->PutC(R);
					NewChunk->PutC(G);
					NewChunk->PutC(B);
				}
			}
		}
		break;

		case 4:
		{
			for(int y = 0; y < SrcResources[id]->h; y++)
			{
				for(int x = 0; x < SrcResources[id]->w; x++)
				{
					Uint8 R, G, B, A;
					SDL_GetRGBA(*((Uint32 *)&((Uint8 *)SrcResources[id]->pixels)[ (SrcResources[id]->pitch*y) + x*SrcResources[id]->format->BytesPerPixel]), SrcResources[id]->format, &R, &G, &B, &A);

					NewChunk->PutC(R);
					NewChunk->PutC(G);
					NewChunk->PutC(B);
					NewChunk->PutC(A);
				}
			}
		}
		break;
	}
	SDL_UnlockSurface(SrcResources[id]);

	/* palette maybe */
	if(SrcResources[id]->format->BytesPerPixel == 1)
	{
		for(int c = 0; c < 256; c++)
		{
			NewChunk->PutC(SrcResources[id]->format->palette->colors[c].r);
			NewChunk->PutC(SrcResources[id]->format->palette->colors[c].g);
			NewChunk->PutC(SrcResources[id]->format->palette->colors[c].b);
		}
	}

	GetHost()->ReleaseUEFSelector(GFXFile);
	delete[] img;
	delete[] msk;
}
void
Screenshot::save(SDL_Surface* surface, const std::string& filename)
{
  std::unique_ptr<uint8_t[]> buffer(new uint8_t[surface->w * surface->h * 3]);

#ifdef HAVE_OPENGL
  if(surface->flags & SDL_OPENGL)
  {
    glPixelStorei(GL_PACK_ALIGNMENT, 1);
    glReadPixels(0, 0, surface->w, surface->h, GL_RGB, GL_UNSIGNED_BYTE, buffer.get());
    save_png(filename, buffer.get(), surface->w, surface->h, true);
  }
  else
#endif
  {
    SDL_LockSurface(surface);

    switch(surface->format->BitsPerPixel)
    {
      case 16: // 16bit
      {
        uint8_t* pixels = static_cast<uint8_t*>(surface->pixels);
        for (int y = 0; y < surface->h; ++y)
          for (int x = 0; x < surface->w; ++x)
          {
            int i = (y * surface->w + x);
            SDL_GetRGB(*(reinterpret_cast<uint16_t*>(pixels + y * surface->pitch + x*2)),
                       surface->format, 
                       buffer.get() + i*3 + 0, buffer.get() + i*3 + 1, buffer.get() + i*3 + 2);
          }
        break;
      }

      case 24: // 24bit
      {
        uint8_t* pixels = static_cast<uint8_t*>(surface->pixels);
        for (int y = 0; y < surface->h; ++y)
          for (int x = 0; x < surface->w; ++x)
          {
            int i = (y * surface->w + x);
            SDL_GetRGB(*(reinterpret_cast<uint32_t*>(pixels + y * surface->pitch + x*3)),
                       surface->format, 
                       buffer.get() + i*3 + 0, buffer.get() + i*3 + 1, buffer.get() + i*3 + 2);
          }
        break;
      }

      case 32: // 32bit
      {
        uint8_t* pixels = static_cast<uint8_t*>(surface->pixels);
        for (int y = 0; y < surface->h; ++y)
          for (int x = 0; x < surface->w; ++x)
          {
            int i = (y * surface->w + x);
            SDL_GetRGB(*(reinterpret_cast<uint32_t*>(pixels + y * surface->pitch + x*4)),
                       surface->format, 
                       buffer.get() + i*3 + 0, buffer.get() + i*3 + 1, buffer.get() + i*3 + 2);
          }
        break;
      }
      default:
        log_info("BitsPerPixel: " << int(surface->format->BitsPerPixel));
        assert(!"Unknown color format");
        break;
    }

    save_png(filename, buffer.get(), surface->w, surface->h);

    SDL_UnlockSurface(surface);
  }
}
Exemple #20
0
void CFont::getBGColour(bool highlighted, Uint8 *r, Uint8 *g, Uint8 *b)
{
	Uint32 colour = getBGColour(false);
	SDL_GetRGB(colour, m_ColouredSurface->format, r, g, b);
}
void SystemStub_SDL::getPaletteEntry(uint8 i, Color *c) {
	SDL_GetRGB(_pal[i], _screen->format, &c->r, &c->g, &c->b);
	c->r >>= 2;
	c->g >>= 2;
	c->b >>= 2;
}
Exemple #22
0
/*
* Initialization of buffers and EduRaster structures.
*/
static void setup(){
    /* Allocate color buffer */
    color_buffer = (unsigned int*)malloc(window_width*window_height*sizeof(unsigned int));
    if(color_buffer == NULL){
        fprintf(stderr, "Unable to allocate color buffer. Out of memory\n");
        quit();
    }
    /* Allocate depth buffer */
    depth_buffer = (float* )malloc(window_width*window_height*sizeof(float));
    if(depth_buffer == NULL){
        fprintf(stderr, "Unable to allocate depth buffer. Out of memory\n");
        quit();
    }
    /* Init EduRaster */
    if(er_init() != 0) {
        fprintf(stderr, "Unable to init eduraster: %s\n", er_get_error_string(er_get_error()));
        quit();
    }
    er_viewport(0 , 0 , window_width, window_height);
    /* Set perspective projection */
    er_matrix_mode(ER_PROJECTION);
    er_load_identity();
    er_perspective(60.0f, (float)window_width / (float)window_height, 2.0f, 40.0f);
    er_matrix_mode(ER_MODELVIEW);
    /* Load image and create texture */
    const char *image_path = "textures/lenna.bmp";
    SDL_Surface *image = SDL_LoadBMP(image_path);
    if(image == NULL){
        fprintf(stderr, "Unable to load image %s. Error: %s\n", SDL_GetError());
        quit();
    }

    tex = er_create_texture2D(image->w, image->h, ER_RGB32F);
    if(tex == NULL){
        fprintf(stderr, "Unable to create texture %s. Error: %s\n", er_get_error_string(er_get_error()));
        quit();
    }
    er_texture_filtering(tex, ER_MAGNIFICATION_FILTER, ER_LINEAR);
    er_texture_filtering(tex, ER_MINIFICATION_FILTER, ER_LINEAR_MIPMAP_LINEAR);
    er_texture_wrap_mode(tex, ER_WRAP_S, ER_REPEAT);
    er_texture_wrap_mode(tex, ER_WRAP_T, ER_REPEAT);
    
    SDL_PixelFormat *format = image->format;
    SDL_LockSurface(image);
    unsigned char *src_data = image->pixels;
    float *dst_data = er_texture_ptr(tex, ER_TEXTURE_2D, 0);
    int i, j;
    unsigned int src_color = 0;
    unsigned char r, g, b;
    for(i = 0; i < image->h;i++){
        for(j = 0; j < image->w; j++){
            memcpy(&src_color, &src_data[(image->h-1-i)*image->pitch+j*format->BytesPerPixel], format->BytesPerPixel);
            SDL_GetRGB(src_color, format, &r, &g, &b);
            dst_data[i*image->w*3+j*3] = (float)r / 255.0f;
            dst_data[i*image->w*3+j*3+1] = (float)g / 255.0f;
            dst_data[i*image->w*3+j*3+2] = (float)b / 255.0f;
        }
    }
    SDL_UnlockSurface(image);
    SDL_FreeSurface(image);
    /* Generate mipmaps */
    er_generate_mipmaps(tex);
    int error = er_get_error();
    if(error != ER_NO_ERROR){
        fprintf(stderr, "%s\n",er_get_error_string(error));
        quit();
    }
    /* Create program for texture */
    prog = er_create_program();
    if(prog == NULL){
        fprintf(stderr, "Unable to create eduraster program: %s\n", er_get_error_string(er_get_error()));
        quit();
    }
    er_use_program(prog);
    er_varying_attributes(prog, 2);
    er_load_vertex_shader(prog, vs_cube);
    er_load_homogeneous_division(prog, hd_cube);
    er_load_fragment_shader(prog, fs_cube);
    er_uniform_texture_ptr(prog, 0, tex);
    /* Enable backface culling */
    er_cull_face(ER_BACK);
    er_enable(ER_CULL_FACE, ER_TRUE);

}
/**
 * Copied from the RoboRobo branch of Nikita
 *
 * TODO: Use the ResourceFactory instead of this.
 
 * @param surface
 * @param sensorRay
 * @param ranges
 * @param pixels
 * @return
 */
int castSensorRay(SDL_Surface* surface, SensorRay sensorRay, int* ranges, int* pixels) {
    double x1 = sensorRay.x1;
    double y1 = sensorRay.y1;
    double x2 = sensorRay.x2;
    double y2 = sensorRay.y2;
    double maxRange = sensorRay.maxRange;

	if (SDL_MUSTLOCK(surface))
		SDL_LockSurface(surface);

	//Convert the pixels to 32 bit
	Uint32 *pixelData = (Uint32 *)surface->pixels;
    Uint32 activePixel;
    Uint32 regionPixel = G_COLOR_WHITE;
	Uint8 r, g, b;
	int count = 0;
	bool isObstacleCollision = false;

	int xInt, yInt, dxInt, dyInt; double xReal = x1, yReal = y1, dxReal, dyReal, xDist, yDist;

    dxInt = 1;
    dyInt = 1;
	dxReal = (x2 - x1) / (y2 - y1);
	dyReal = 1 / dxReal;

	if (abs(dxReal) > 1) {
	    if (x1 > x2) {
	        dxInt = -1;
	        dyReal = -dyReal;
        }
		for (xInt = (int)(x1 + 0.5); xInt != (int)(x2 + 0.5); xInt += dxInt, yReal += dyReal) {
		    yInt = (int)(yReal + 0.5);
			activePixel = pixelData[yInt * (surface->w) + xInt];
			// If current pixel is different from ones visited previously ...
			if (activePixel != regionPixel) {
                if (activePixel == G_COLOR_WHITE) {
                    regionPixel = G_COLOR_WHITE;
                } else {
                    // Then we have a collision, so we are going to record collision range ...
                    xReal = (double)xInt;
                    xDist = xReal - x1;
                    yDist = yReal - y1;
                    ranges[count] = sqrt(xDist * xDist + yDist * yDist);
                    // And pixel data at the collision point ...
                    SDL_GetRGB(activePixel, gEnvironmentImage->format, &r, &g, &b);
                    pixels[count++] = (r << 16) + (g << 8) + b;
                    // Stop scanning if collided with obstacle, but continue scanning if it was a puck.
                    if (r != 0xFF) {isObstacleCollision = true; break;}
                    regionPixel = activePixel;
                }
			}
		}
	} else {
	    if (y1 > y2) {
	        dyInt = -1;
	        dxReal = -dxReal;
	    }
		for (yInt = (int)(y1 + 0.5); yInt != (int)(y2 + 0.5); yInt += dyInt, xReal += dxReal) {
		    xInt = (int)(xReal + 0.5);
			activePixel = pixelData[yInt * (surface->w) + xInt];
			// If current pixel is different from ones visited previously ...
			if (activePixel != regionPixel) {
                if (activePixel == G_COLOR_WHITE) {
                    regionPixel = G_COLOR_WHITE;
                } else {
                    // Then we have a collision, so we are going to record collision range ...
                    yReal = (double)yInt;
                    xDist = xReal - x1;
                    yDist = yReal - y1;
                    ranges[count] = sqrt(xDist * xDist + yDist * yDist);
                    // And pixel data at the collision point ...
                    SDL_GetRGB(activePixel, gEnvironmentImage->format, &r, &g, &b);
                    pixels[count++] = (r << 16) + (g << 8) + b;
                    // Stop scanning if collided with obstacle, but continue scanning if it was a puck.
                    if (r != 0xFF) {isObstacleCollision = true; break;}
                    regionPixel = activePixel;
                }
			}
		}
	}

	if (SDL_MUSTLOCK(surface))
		SDL_UnlockSurface(surface);

    // If we recorded no collisions while scanning (even if there were some collisions with pucks).
    if (!isObstacleCollision) {
	    if (maxRange != -1) {
		    ranges[count] = maxRange;
	    } else {
            xDist = xReal - x1;
            yDist = yReal - y1;
            ranges[count] = sqrt(xDist * xDist + yDist * yDist);
        }
        pixels[count++] = 0xFFFFFF;
    }

    return count;
}
Exemple #24
0
void draw_drop(SDL_Surface *dst, int x, int y, drop_t *drop, int w, int h, SDL_Rect *clip) {
 float dx,dy;
 int ix,iy;
 Uint16 alpha;
 Uint8 r,g,b;
 int sx, sy;
 int j;
 Uint8 *pix;
 int color;
 int mask;
 int *intp;
 int real_w, real_h;
 int offset_x, offset_y;

 /*XXX if drop is bigger then dst this doesn't work right */

 if((x> dst->w) || y > dst->h) return;

 if( (y+h) > dst->h) 
  real_h = dst->h - y;
 else
  real_h = h;

 if( (x+w) >= dst->w)
  real_w = dst->w - x - 1;
 else
  real_w = w;

 if(x < 0) {
  real_w = w + x;
  offset_x = x * -1; 
  x = 0;
 } else
  offset_x = 0;

 if(y < 0) {
  real_h = h + y;
  offset_y = y * -1;
  y = 0;
 } else
  offset_y = 0;

 /* XXX pointer math */
 pix = (Uint8 *)(dst->pixels + 
                 (dst->pitch * y) + (dst->format->BytesPerPixel * x));

 mask = 0;
 for(j=0;j<dst->format->BytesPerPixel;j++)
  mask |= (0xff << (8*j));
#ifdef WORDS_BIGENDIAN
 mask<<=8;
#endif

 mask^=~0;

 LOCK;
 dx = (float)drop->w / (float)w;
 dy = (float)drop->h / (float)h;
 for(iy = 0;iy<real_h;iy++) {
  for(ix =0;ix<real_w;ix++) {
   sx = (int)((float)(ix+offset_x) * dx);
   sy = (int)((float)(iy+offset_y) * dy);
   intp = (int *)pix;
  
   alpha = drop->buffer[sx+(sy*drop->w)];
   color = *intp & (mask^~0);
#ifdef WORDS_BIGENDIAN
   color>>=8;
#endif
   r = g = b= 0;
   SDL_GetRGB((Uint32)color, dst->format, &r, &g, &b);


   color = SDL_MapRGB(dst->format, (r*(alpha))>>8, 
                                   (g*(alpha))>>8,
                                   (b*(alpha))>>8);
#ifdef WORDS_BIGENDIAN
   color<<=8;
#endif
//   color = SDL_MapRGB(dst->format, alpha, 0, 0);
   *intp &= mask;
   *intp += color;
   pix+=dst->format->BytesPerPixel;
  }
  pix-=(dst->format->BytesPerPixel * real_w);
  pix+=dst->pitch;
 }
}
MONEEControlArchitecture::MONEEControlArchitecture( RobotAgentWorldModel *__wm ) : BehaviorControlArchitecture ( __wm ) {
	_wm = (MONEEAgentWorldModel*)__wm;

	/**
	 * Adds the extra puckSensors to the active core sensor list, such that it
	 * can be used
	 */
	//register sensors
    _rangeSensors.resize(_wm->getDefaultSensors()->getSensorCount());
	for (int x = 0; x != gAgentWidth; x++) {
		for (int y = 0; y != gAgentHeight; y++) {
			Uint32 pixel = getPixel32(gAgentSpecsImage, x, y);
			if (pixel != SDL_MapRGB(gAgentSpecsImage->format, 0xFF, 0xFF, 0xFF)) {
				// sensor found, register sensor.
				Uint8 r, g, b;
				SDL_GetRGB(pixel, gAgentSpecsImage->format, &r, &g, &b);

//				if (_wm->getDefaultSensors()->getSensors()[r][0] != -1) {
//					std::cout << "[ERROR] robot sensor id already in use -- check agent specification image." << std::endl;
//					exit(-1);
//				}
//
				if (r >= _wm->getDefaultSensors()->getSensorCount()) {
					std::cout << "[ERROR] robot sensor id is not permitted (must be defined btw 0 and " << (_wm->getDefaultSensors()->getSensorCount() - 1) << ", got: " << r << ") -- check agent specification image." << std::endl;
					exit(-1);
				}

				int sensorId = r;

				double dxOrigin = x - gAgentWidth / 2;
				double dyOrigin = y - gAgentHeight / 2;
				double originDistance = sqrt(dxOrigin * dxOrigin + dyOrigin * dyOrigin);

				double cosOrigin = dxOrigin / originDistance;
				double sinOrigin = dyOrigin / originDistance;

				// atan2 ?
				double originAngle;
				if (sinOrigin >= 0)
					originAngle = acos(cosOrigin) + M_PI * 0.5;
				else
					originAngle = -acos(cosOrigin) + M_PI * 2.5;

				// sensor target point location wrt. agent center -- sensor target angle is (green+blue) component values
				// note: '-90deg' is due to image definition convention (in image, 0° means front of agent, which is upward -- while 0° in simulation means facing right)
				double targetAngle = (g + b - 90) * M_PI / 180;
				double sinTarget, cosTarget;
				sinOrigin = std::sin(targetAngle);
                cosOrigin = std::cos(targetAngle);
                sinTarget = std::sin(targetAngle);
                cosTarget = std::cos(targetAngle);
				double dxTarget = dxOrigin + cosTarget * gSensorRange;
				double dyTarget = dyOrigin + sinTarget * gSensorRange;
				double targetDistance = sqrt(dxTarget * dxTarget + dyTarget * dyTarget); // length (**from agent center**)

				// Now relatively to the center of agent, not the origin point
				cosTarget = dxTarget / targetDistance;
				sinTarget = dyTarget / targetDistance;

				if (sinTarget >= 0)
					targetAngle = acos(cosTarget) + M_PI * 0.5;
				else
					targetAngle = -acos(cosTarget) + M_PI * 2.5;

				_rangeSensors[sensorId] = new PuckSensors(sensorId, originDistance, originAngle, targetDistance, targetAngle, gSensorRange);
                // THIS IS UGLY GETTING ADDRESS FROM REFERENCE, DO NOT COPY!
				_rangeSensors[sensorId]->getOldSensorData(&(_wm->getDefaultSensors()->getSensors()[sensorId].front()));

				r++;
			}
		}
	}
	for(unsigned int i = 0; i < _rangeSensors.size(); i++){
		_wm->addSensors(_rangeSensors[i]);
	}

    int tmpInt = 0;
    gProperties.checkAndGetPropertyValue("gMaxGenePool", &tmpInt, true);
    gMaxGenePool = tmpInt;
    gProperties.checkAndGetPropertyValue("gMaxLifetimeGathering", &tmpInt, true);
    _maxLifetime[PHASE_GATHERING] = tmpInt;
    gProperties.checkAndGetPropertyValue("gMaxLifetimeMating", &tmpInt, true);
    _maxLifetime[PHASE_MATING] = tmpInt;
    gProperties.checkAndGetPropertyValue("gHiddenNeuronCount", &tmpInt, true);
    _hiddenNeuronCount = tmpInt;
    
    _randomSelection = false;
    gProperties.checkAndGetPropertyValue("gRandomSelection", &_randomSelection, false);
    _useMarket = true;
    gProperties.checkAndGetPropertyValue("gUseMarket", &_useMarket, true);
    _useSpecBonus = false;
    gProperties.checkAndGetPropertyValue("gUseSpecBonus", &_useSpecBonus, false);
    _task1Premium = 1.0;
    gProperties.checkAndGetPropertyValue("gTask1Premium", &_task1Premium, 1.0);
    _selectionPressure = 1.5;
    gProperties.checkAndGetPropertyValue("gSelectionPressure", &_selectionPressure, 1.5);
    
    if (_hiddenNeuronCount > 0) {
        _parameterCount = (_wm->getDefaultSensors()->getSensorCount() * (gPuckColors + 1) + 1 + 2) * _hiddenNeuronCount + (_hiddenNeuronCount + 1) * 2;
        _response.assign(_hiddenNeuronCount, .0);
    } else {
        _parameterCount = (_wm->getDefaultSensors()->getSensorCount() * (gPuckColors + 1) + 1 + 2) * 2;
    }

    _wm->_genePool.reserve(gMaxGenePool);

    _nearbyGenomes.reserve(gNbOfAgents); // Agent counter is unpredictable at this time

    _activeGenome.parameters.assign(_parameterCount, .0);
    mutate(_activeGenome.parameters, 1.0);

    _wm->_puckCounters = &(_activeGenome.pucks);
}
bool CTexture::loadBMPTexture(char *strFileName)
{
  SDL_Surface *pBitmap[1];
  if(strFileName==NULL) return false ;
  
  pBitmap[0]=SDL_LoadBMP(strFileName);
  
  if(pBitmap[0]==NULL)
  {
      fprintf(stderr,"Failed to load texture %s",SDL_GetError());
      return false;
  }
  fprintf(stdout,"file ok");
  glGenTextures(1,&textureID);
  glBindTexture(GL_TEXTURE_2D,textureID);
  
  int width=pBitmap[0]->w;
  int height=pBitmap[0]->h;
  unsigned char *data=(unsigned char*)(pBitmap[0]->pixels);
  //this->width=width;
  //this->height=height;
  int BytesPerPixel=pBitmap[0]->format->BytesPerPixel;
  
  for(int i=0;i<(height/2);i++)
   for(int j=0;j<width*BytesPerPixel;j+=BytesPerPixel)
     for(int k=0;k<BytesPerPixel;++k)
        swap( data[ (i * width * BytesPerPixel) + j + k], data[ ( (height - i - 1) * width * BytesPerPixel ) + j + k]);
      
  unsigned char *pixel=new unsigned char[width*height*3];
  int count=0;

  
  for(int i=0;i< (width*height);++i)
  {
    unsigned int r,g,b;
    Uint32 pixel_value=0;
    
    for(int j=BytesPerPixel-1;j>=0;--j)
    {
      pixel_value=pixel_value<<8;
      pixel_value=pixel_value | data[(i*BytesPerPixel)+j];      
    }
      fprintf(stdout,"OK");
    SDL_GetRGB(pixel_value,pBitmap[0]->format,(Uint8 *)&r,(Uint8 *)&g,(Uint8 *)&b );
    
    pixels[count++]=r;
    pixels[count++]=g;
    pixels[count++]=b;
    pixel_value=0;
      //rintf(stdout,"OK");
  }
 
     
   gluBuild2DMipmaps(GL_TEXTURE_2D,3,pBitmap[0]->w,pBitmap[0]->h,GL_RGB,GL_UNSIGNED_BYTE,pixels);
   glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);    
   glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR_MIPMAP_NEAREST);
   glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
   SDL_FreeSurface(pBitmap[0]);        
   fprintf(stdout,"texture load ok");
   return true; 
 }
Exemple #27
0
int main(int argc, char *argv[])
{
	int x, y, i, OK, startIndex;
	char name[20];
	SDL_Rect src, dest;
	unsigned char r, g, b;
	int *pixels, xx, yy, pixel;
	int colour;

	i = 0;

	if (argc != 3)
	{
		printf("Usage: %s <PNG File> <Start_Index>\n", argv[0]);

		exit(0);
	}

	atexit(cleanup);

	if (SDL_Init(SDL_INIT_VIDEO|SDL_INIT_JOYSTICK|SDL_INIT_AUDIO) < 0)
	{
		printf("Could not initialize SDL: %s\n", SDL_GetError());

		exit(1);
	}

	screen = SDL_SetVideoMode(SCREEN_WIDTH, SCREEN_HEIGHT, 0, 0);

	image = loadImage(argv[1]);

	i = atoi(argv[2]);

	startIndex = i;

	temp = SDL_CreateRGBSurface(SDL_HWSURFACE, TILE_SIZE, TILE_SIZE, image->format->BitsPerPixel, image->format->Rmask, image->format->Gmask, image->format->Bmask, 0);

	newSurface = SDL_DisplayFormat(temp);

	colour = SDL_MapRGB(image->format, TRANS_R, TRANS_G, TRANS_B);

	for (y=0;y<image->h;y+=TILE_SIZE)
	{
		for (x=0;x<image->w;x+=TILE_SIZE)
		{
			SDL_FillRect(newSurface, NULL, colour);

			src.x = x;
			src.y = y;
			src.w = image->w - x >= TILE_SIZE ? TILE_SIZE : image->w - x;
			src.h = image->h - y >= TILE_SIZE ? TILE_SIZE : image->h - y;

			dest.x = 0;
			dest.y = 0;
			dest.w = src.w;
			dest.h = src.h;

			SDL_BlitSurface(image, &src, newSurface, &dest);

			sprintf(name, "%d.png", i);

			OK = 0;

			for (yy=0;yy<newSurface->h;yy++)
			{
				for (xx=0;xx<newSurface->w;xx++)
				{
					pixels = (int *)newSurface->pixels;

					pixel = pixels[(yy * newSurface->w) + xx];

					SDL_GetRGB(pixel, newSurface->format, &r, &g, &b);

					if (r != TRANS_R && g != TRANS_G && b != TRANS_B)
					{
						OK = 1;

						break;
					}
				}
			}

			if (OK == 1 && isDuplicate(newSurface, startIndex, i) == FALSE)
			{
				printf("Saving %s\n", name);

				savePNG(newSurface, name);

				i++;
			}

		}
	}

	exit(0);
}
Exemple #28
0
/**
**  Save state of players to file.
**
**  @param file  Output file.
**
**  @note FIXME: Not completely saved.
*/
void SavePlayers(CFile *file)
{
	int j;
	Uint8 r, g, b;
	CPlayer *p;

	file->printf("\n--------------------------------------------\n");
	file->printf("--- MODULE: players\n\n");

	//
	//  Dump all players
	//
	for (int i = 0; i < NumPlayers; ++i) {
		p = &Players[i];
		file->printf("Player(%d,\n", i);
		file->printf("  \"name\", \"%s\",\n", p->Name.c_str());
		file->printf("  \"type\", ");
		switch (p->Type) {
			case PlayerNeutral:       file->printf("\"neutral\",");         break;
			case PlayerNobody:        file->printf("\"nobody\",");          break;
			case PlayerComputer:      file->printf("\"computer\",");        break;
			case PlayerPerson:        file->printf("\"person\",");          break;
			case PlayerRescuePassive: file->printf("\"rescue-passive\",");break;
			case PlayerRescueActive:  file->printf("\"rescue-active\","); break;
			default:                  file->printf("%d,",p->Type);break;
		}
		file->printf(" \"ai-name\", \"%s\",\n", p->AiName.c_str());
		file->printf("  \"team\", %d,", p->Team);

		file->printf(" \"enemy\", \"");
		for (j = 0; j < PlayerMax; ++j) {
			file->printf("%c",(p->Enemy & (1 << j)) ? 'X' : '_');
		}
		file->printf("\", \"allied\", \"");
		for (j = 0; j < PlayerMax; ++j) {
			file->printf("%c", (p->Allied & (1 << j)) ? 'X' : '_');
		}
		file->printf("\", \"shared-vision\", \"");
		for (j = 0; j < PlayerMax; ++j) {
			file->printf("%c", (p->SharedVision & (1 << j)) ? 'X' : '_');
		}
		file->printf("\",\n  \"start\", {%d, %d},\n", p->StartX,
			p->StartY);

		// ProductionRate
		file->printf("  \"production-rate\", {");
		for (j = 0; j < MaxCosts; ++j) {
			if (j) {
				file->printf(" ");
			}
			file->printf("\"%s\", %d,", DefaultResourceNames[j].c_str(),
				p->ProductionRate[j]);
		}
		// StoredResources
		file->printf("},\n  \"stored-resources\", {");
		for (j = 0; j < MaxCosts; ++j) {
			if (j) {
				file->printf(" ");
			}
			file->printf("\"%s\", %d,", DefaultResourceNames[j].c_str(),
				p->StoredResources[j]);
		}
		// StorageCapacity
		file->printf("},\n  \"storage-capacity\", {");
		for (j = 0; j < MaxCosts; ++j) {
			if (j) {
				file->printf(" ");
			}
			file->printf("\"%s\", %d,", DefaultResourceNames[j].c_str(),
				p->StorageCapacity[j]);
		}

		// UnitTypesCount done by load units.

		file->printf("},\n  \"%s\",\n", p->AiEnabled ?
			"ai-enabled" : "ai-disabled");

		// Ai done by load ais.
		// Units done by load units.
		// TotalNumUnits done by load units.
		// NumBuildings done by load units.

		file->printf(" \"unit-limit\", %d,", p->UnitLimit);
		file->printf(" \"building-limit\", %d,", p->BuildingLimit);
		file->printf(" \"total-unit-limit\", %d,", p->TotalUnitLimit);

		file->printf("\n  \"score\", %d,", p->Score);
		file->printf("\n  \"total-units\", %d,", p->TotalUnits);
		file->printf("\n  \"total-buildings\", %d,", p->TotalBuildings);
		file->printf("\n  \"total-resources\", {");
		for (j = 0; j < MaxCosts; ++j) {
			if (j) {
				file->printf(" ");
			}
			file->printf("%d,", p->TotalResources[j]);
		}
		file->printf("},");
		file->printf("\n  \"total-razings\", %d,", p->TotalRazings);
		file->printf("\n  \"total-kills\", %d,", p->TotalKills);

		SDL_GetRGB(p->Color, TheScreen->format, &r, &g, &b);
		file->printf("\n  \"color\", { %d, %d, %d }", r, g, b); // no comma after last parameter

		// UnitColors done by init code.
		// Allow saved by allow.

		file->printf(")\n\n");
	}

	DebugPrint("FIXME: must save unit-stats?\n");

	//
	//  Dump local variables
	//
	file->printf("ThisPlayer = Players[%d]\n\n", ThisPlayer->Index);
}
bool ParcoursWorldInterface::checkDitch(double x, double y){
	Uint8 r, g, b;
	Uint32 pixel = getPixel32(gZoneImage, x, y);
	SDL_GetRGB(pixel, gZoneImage->format, &r, &g, &b);
	return (r == ParcoursSharedData::ZONE_VALUE);
}
Exemple #30
0
bool per_pixel_collision(celestial_object *obj1, celestial_object *obj2, SDL_Surface **surfaces)
{
	int i, j;
	int offsetx1, offsety1, offsetx2, offsety2;
	SDL_Rect rect;
	SDL_Surface *screen, *surface1, *surface2;
	Uint8 r1, r2, g1, g2, b1, b2;
	bool ret;
	indice id;

	screen = surfaces[0];
	surface1 = obj1->surface;
	surface2 = obj2->surface;  
	ret = false;

	if (obj1->position.x >= obj2->position.x)
	{
		rect.x = obj1->position.x;
		rect.w = obj2->position.x + obj2->sprite_size - rect.x;
		if (rect.w > obj1->sprite_size)
			rect.w = obj1->sprite_size;
		offsetx1 = 0;
		offsetx2 = rect.x - obj2->position.x;
	}
	else {
		rect.x = obj2->position.x;
		rect.w = obj1->position.x + obj1->sprite_size - rect.x;
		if (rect.w > obj2->sprite_size)
			rect.w = obj2->sprite_size;
		offsetx2 = 0;
		offsetx1 = rect.x - obj1->position.x;
	}

	if (obj1->position.y >= obj2->position.y)
	{
		rect.y = obj1->position.y;
		rect.h = obj2->position.y + obj2->sprite_size - rect.y;
		if (rect.h > obj1->sprite_size)
			rect.h = obj1->sprite_size;
		offsety1 = 0;
		offsety2 = rect.y - obj2->position.y;
	}
	else {
		rect.y = obj2->position.y;
		rect.h = obj1->position.y + obj1->sprite_size - rect.y;
		if (rect.h > obj2->sprite_size)
			rect.h = obj2->sprite_size;
		offsety2 = 0;
		offsety1 = rect.y - obj1->position.y;
	}

	SDL_LockSurface(surface1);
	SDL_LockSurface(surface2);

	for (j = 0; j < rect.h; j++) {
		for (i = 0; i < rect.w; i++) {
			SDL_GetRGB(pixel(surface1, i + obj1->rcSrc.x + offsetx1, j + offsety1), screen->format, &r1, &g1, &b1);
			SDL_GetRGB(pixel(surface2, i + obj2->rcSrc.x + offsetx2, j + offsety2), screen->format, &r2, &g2, &b2);

			if (!isColorkey(r1, g1, b1) && !isColorkey(r2, g2, b2)) {
				ret = true;
			}
		}
	}

	SDL_UnlockSurface(surface1);
	SDL_UnlockSurface(surface2);

	return ret;
}