Exemple #1
0
Map::Map(std::string config_filename):
    map_config(config_filename),
    user_start(&map_config,"Find the exit after collecting all the coins!",180,300,SDL_Color{255,255,255}),
    user_won(&map_config,"You have won!",100,300,SDL_Color{255,255,255}),
    coin_counter(&map_config,"Coins left = 0",50,20,SDL_Color{240,240,0}),
    time(&map_config,"Timer = 0",850,20,SDL_Color{255,0,0})
{
    // enable tile texture
    std::string tile_texture_location = map_config.find_string("wall_texture");
    tiles_surface=std::make_shared<SDL_Surface*>(SDL_LoadBMP(tile_texture_location.c_str()));
    tiles_texture=std::make_shared<SDL_Texture*>(SDL_CreateTextureFromSurface(video::Video_subsystem::get_instance().get_renderer(),*tiles_surface.get()));
    std::vector<std::string> enable_tiles =  map_config.find_strings("wall");
    // create tiles
    unsigned int position_one=0;
    for(auto &x : enable_tiles)
    {
        vector<int> position = utility::get_numbers_from_string(x);
        SDL_Rect location;
        location.x=position[0];
        location.y=position[1];
        location.h=(*tiles_surface)->h;
        location.w=(*tiles_surface)->w;
        bool is_repeating=false;
        for(unsigned int a = position_one + 1; a<enable_tiles.size();a++)
        {
            if(x==enable_tiles[a])
            {
                is_repeating = true;
            }
        }
        position_one++;
        if(is_repeating)
        {
            continue;
        }
        tiles.push_back(objects::Tile(location,tiles_texture));
    }
    // create coins
    std::string coin_texture_location = map_config.find_string("coin_texture");
    coin_surface=std::make_shared<SDL_Surface*>(SDL_LoadBMP(coin_texture_location.c_str()));
    Uint32 key = SDL_MapRGB((*coin_surface)->format,255,0,255);
    SDL_SetColorKey( *coin_surface , SDL_TRUE , key );
    coin_texture=std::make_shared<SDL_Texture*>(SDL_CreateTextureFromSurface(video::Video_subsystem::get_instance().get_renderer(),*coin_surface.get()));
    std::vector<std::string> enable_coins =  map_config.find_strings("coin");

    for(auto &x : enable_coins)
    {
        vector<int> position = utility::get_numbers_from_string(x);
        SDL_Rect location;
        location.x=position[0];
        location.y=position[1];
        location.h=(*coin_surface)->h;
        location.w=(*coin_surface)->w;
        coins.push_back(objects::Prop(location,coin_texture));
    }

    map_gravity = atoi(map_config.find_string("gravity").c_str());
    // create the player
    main_player=new objects::Player(map_config.find_string("players_config"));

    start_timer.start();

    user_won.hide();

    std::ostringstream oss;
    oss<<"Coins left = "<<coins.size();
    coin_counter.change_text(oss.str());

    printf("Initialized map with %i tiles\n",tiles.size());
}
Exemple #2
0
bool VideoDriver_SDL::CreateMainSurface(uint w, uint h)
{
	SDL_Surface *newscreen, *icon;
	char caption[50];
	int bpp = BlitterFactory::GetCurrentBlitter()->GetScreenDepth();
	bool want_hwpalette;

	GetAvailableVideoMode(&w, &h);

	DEBUG(driver, 1, "SDL: using mode %ux%ux%d", w, h, bpp);

	if (bpp == 0) usererror("Can't use a blitter that blits 0 bpp for normal visuals");

	char icon_path[MAX_PATH];
	if (FioFindFullPath(icon_path, lastof(icon_path), BASESET_DIR, "openttd.32.bmp") != NULL) {
		/* Give the application an icon */
		icon = SDL_CALL SDL_LoadBMP(icon_path);
		if (icon != NULL) {
			/* Get the colourkey, which will be magenta */
			uint32 rgbmap = SDL_CALL SDL_MapRGB(icon->format, 255, 0, 255);

			SDL_CALL SDL_SetColorKey(icon, SDL_SRCCOLORKEY, rgbmap);
			SDL_CALL SDL_WM_SetIcon(icon, NULL);
			SDL_CALL SDL_FreeSurface(icon);
		}
	}

	if (_use_hwpalette == 2) {
		/* Default is to autodetect when to use SDL_HWPALETTE.
		 * In this case, SDL_HWPALETTE is only used for 8bpp
		 * blitters in fullscreen.
		 *
		 * When using an 8bpp blitter on a 8bpp system in
		 * windowed mode with SDL_HWPALETTE, OpenTTD will claim
		 * the system palette, making all other applications
		 * get the wrong colours. In this case, we're better of
		 * trying to approximate the colors we need using system
		 * colors, using a shadow surface (see below).
		 *
		 * On a 32bpp system, SDL_HWPALETTE is ignored, so it
		 * doesn't matter what we do.
		 *
		 * When using a 32bpp blitter on a 8bpp system, setting
		 * SDL_HWPALETTE messes up rendering (at least on X11),
		 * so we don't do that. In this case, SDL takes care of
		 * color approximation using its own shadow surface
		 * (which we can't force in 8bpp on 8bpp mode,
		 * unfortunately).
		 */
		want_hwpalette = bpp == 8 && _fullscreen && _support8bpp == S8BPP_HARDWARE;
	} else {
		/* User specified a value manually */
		want_hwpalette = _use_hwpalette;
	}

	if (want_hwpalette) DEBUG(driver, 1, "SDL: requesting hardware palete");

	/* Free any previously allocated shadow surface */
	if (_sdl_screen != NULL && _sdl_screen != _sdl_realscreen) SDL_CALL SDL_FreeSurface(_sdl_screen);

	if (_sdl_realscreen != NULL) {
		if (_requested_hwpalette != want_hwpalette) {
			/* SDL (at least the X11 driver), reuses the
			 * same window and palette settings when the bpp
			 * (and a few flags) are the same. Since we need
			 * to hwpalette value to change (in particular
			 * when switching between fullscreen and
			 * windowed), we restart the entire video
			 * subsystem to force creating a new window.
			 */
			DEBUG(driver, 0, "SDL: Restarting SDL video subsystem, to force hwpalette change");
			SDL_CALL SDL_QuitSubSystem(SDL_INIT_VIDEO);
			SDL_CALL SDL_InitSubSystem(SDL_INIT_VIDEO);
			ClaimMousePointer();
			SetupKeyboard();
		}
	}
	/* Remember if we wanted a hwpalette. We can't reliably query
	 * SDL for the SDL_HWPALETTE flag, since it might get set even
	 * though we didn't ask for it (when SDL creates a shadow
	 * surface, for example). */
	_requested_hwpalette = want_hwpalette;

	/* DO NOT CHANGE TO HWSURFACE, IT DOES NOT WORK */
	newscreen = SDL_CALL SDL_SetVideoMode(w, h, bpp, SDL_SWSURFACE | (want_hwpalette ? SDL_HWPALETTE : 0) | (_fullscreen ? SDL_FULLSCREEN : SDL_RESIZABLE));
	if (newscreen == NULL) {
		DEBUG(driver, 0, "SDL: Couldn't allocate a window to draw on");
		return false;
	}
	_sdl_realscreen = newscreen;

	if (bpp == 8 && (_sdl_realscreen->flags & SDL_HWPALETTE) != SDL_HWPALETTE) {
		/* Using an 8bpp blitter, if we didn't get a hardware
		 * palette (most likely because we didn't request one,
		 * see above), we'll have to set up a shadow surface to
		 * render on.
		 *
		 * Our palette will be applied to this shadow surface,
		 * while the real screen surface will use the shared
		 * system palette (which will partly contain our colors,
		 * but most likely will not have enough free color cells
		 * for all of our colors). SDL can use these two
		 * palettes at blit time to approximate colors used in
		 * the shadow surface using system colors automatically.
		 *
		 * Note that when using an 8bpp blitter on a 32bpp
		 * system, SDL will create an internal shadow surface.
		 * This shadow surface will have SDL_HWPALLETE set, so
		 * we won't create a second shadow surface in this case.
		 */
		DEBUG(driver, 1, "SDL: using shadow surface");
		newscreen = SDL_CALL SDL_CreateRGBSurface(SDL_SWSURFACE, w, h, bpp, 0, 0, 0, 0);
		if (newscreen == NULL) {
			DEBUG(driver, 0, "SDL: Couldn't allocate a shadow surface to draw on");
			return false;
		}
	}

	/* Delay drawing for this cycle; the next cycle will redraw the whole screen */
	_num_dirty_rects = 0;

	_screen.width = newscreen->w;
	_screen.height = newscreen->h;
	_screen.pitch = newscreen->pitch / (bpp / 8);
	_screen.dst_ptr = newscreen->pixels;
	_sdl_screen = newscreen;

	/* When in full screen, we will always have the mouse cursor
	 * within the window, even though SDL does not give us the
	 * appropriate event to know this. */
	if (_fullscreen) _cursor.in_window = true;

	Blitter *blitter = BlitterFactory::GetCurrentBlitter();
	blitter->PostResize();

	InitPalette();
	switch (blitter->UsePaletteAnimation()) {
		case Blitter::PALETTE_ANIMATION_NONE:
		case Blitter::PALETTE_ANIMATION_VIDEO_BACKEND:
			UpdatePalette();
			break;

		case Blitter::PALETTE_ANIMATION_BLITTER:
			if (VideoDriver::GetInstance() != NULL) blitter->PaletteAnimate(_local_palette);
			break;

		default:
			NOT_REACHED();
	}

	seprintf(caption, lastof(caption), "OpenTTD %s", _openttd_revision);
	SDL_CALL SDL_WM_SetCaption(caption, caption);

	GameSizeChanged();

	return true;
}
Exemple #3
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);

}
Exemple #4
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;
}
Exemple #5
0
void DrawLogoTexture(void)
{
	static GLfloat texMinX, texMinY;
	static GLfloat texMaxX, texMaxY;
	static int x = 0;
	static int y = 0;
	static int w, h;
	static int delta_x = 1;
	static int delta_y = 1;

	SDL_Surface *screen = SDL_GetVideoSurface();

	if ( ! global_texture ) {
		SDL_Surface *image;
		GLfloat texcoord[4];

		/* Load the image (could use SDL_image library here) */
		image = SDL_LoadBMP(LOGO_FILE);
		if ( image == NULL ) {
			return;
		}
		w = image->w;
		h = image->h;

		/* Convert the image into an OpenGL texture */
		global_texture = SDL_GL_LoadTexture(image, texcoord);

		/* Make texture coordinates easy to understand */
		texMinX = texcoord[0];
		texMinY = texcoord[1];
		texMaxX = texcoord[2];
		texMaxY = texcoord[3];

		/* We don't need the original image anymore */
		SDL_FreeSurface(image);

		/* Make sure that the texture conversion is okay */
		if ( ! global_texture ) {
			return;
		}
	}

	/* Move the image around */
	x += delta_x;
	if ( x < 0 ) {
		x = 0;
		delta_x = -delta_x;
	} else
	if ( (x+w) > screen->w ) {
		x = screen->w-w;
		delta_x = -delta_x;
	}
	y += delta_y;
	if ( y < 0 ) {
		y = 0;
		delta_y = -delta_y;
	} else
	if ( (y+h) > screen->h ) {
		y = screen->h-h;
		delta_y = -delta_y;
	}

	/* Show the image on the screen */
	SDL_GL_Enter2DMode();
	glBindTexture(GL_TEXTURE_2D, global_texture);
	glBegin(GL_TRIANGLE_STRIP);
	glTexCoord2f(texMinX, texMinY); glVertex2i(x,   y  );
	glTexCoord2f(texMaxX, texMinY); glVertex2i(x+w, y  );
	glTexCoord2f(texMinX, texMaxY); glVertex2i(x,   y+h);
	glTexCoord2f(texMaxX, texMaxY); glVertex2i(x+w, y+h);
	glEnd();
	SDL_GL_Leave2DMode();
}
Exemple #6
0
int main(int argc,char* argv[])
{
  SDL_Surface *screen;
  SDL_Surface *ball_bmp;

  struct ball red_ball, blue_ball;

  SDL_TimerID timer, timer2;

  int done;

  init(&screen);

  /* Load the BMP file into a surface */
  red_ball.ball_bmp = SDL_LoadBMP("ball.bmp");
  if (red_ball.ball_bmp == NULL) {
    fprintf(stderr, "Couldn't load %s: %sn", "ball.bmp", SDL_GetError());
    exit(1);
  }

  /* Load the BMP file into a surface */
  blue_ball.ball_bmp = SDL_LoadBMP("ball2.bmp");
  if (blue_ball.ball_bmp == NULL) {
    fprintf(stderr, "Couldn't load %s: %sn", "ball2.bmp", SDL_GetError());
    exit(1);
  }


  /*
   * Palettized screen modes will have a default palette (a standard
   * 8*8*4 colour cube), but if the image is palettized as well we can
   * use that palette for a nicer colour matching.
   * */
			         
  if (red_ball.ball_bmp->format->palette && screen->format->palette) {
    SDL_SetColors(screen, ball_bmp->format->palette->colors, 0, ball_bmp->format->palette->ncolors);
  }

  /* Blit onto the screen surface */
  if(SDL_BlitSurface(red_ball.ball_bmp, NULL, screen, NULL) < 0)
    fprintf(stderr, "BlitSurface error: %sn", SDL_GetError());

  if(SDL_BlitSurface(blue_ball.ball_bmp, NULL, screen, NULL) < 0)
      fprintf(stderr, "BlitSurface error: %sn", SDL_GetError());

  SDL_UpdateRect(screen, 0, 0, red_ball.ball_bmp->w, red_ball.ball_bmp->h);

  //This could be put in an init function:
  red_ball.startx=0; red_ball.starty=0; red_ball.destx=0; red_ball.desty=0;
  red_ball.x = (float)red_ball.startx; red_ball.y = (float)red_ball.starty;
  red_ball.dx = 0.0; red_ball.dy = 0.0;
  red_ball.screen = screen;

  blue_ball.startx=0; blue_ball.starty=0; blue_ball.destx=0; blue_ball.desty=0;
  blue_ball.x = (float)blue_ball.startx; blue_ball.y = (float)blue_ball.starty;
  blue_ball.dx = 0.0; blue_ball.dy = 0.0;
  blue_ball.screen = screen;


  glClearColor(0, 0, 0, 0);
  glClearDepth(1.0f);
  glViewport(0, 0, 640, 480);
  glMatrixMode(GL_PROJECTION);
  glLoadIdentity();
  glOrtho(0, 640, 480, 0, 1, -1);
  glMatrixMode(GL_MODELVIEW);
  glEnable(GL_TEXTURE_2D);
  glLoadIdentity();

  glBegin(GL_QUADS);
    glColor3f(1, 0, 0); glVertex3f(0, 0, 0);
    glColor3f(1, 1, 0); glVertex3f(100, 0, 0);
    glColor3f(1, 0, 1); glVertex3f(100, 100, 0);
    glColor3f(1, 1, 1); glVertex3f(0, 100, 0);
  glEnd();

  SDL_GL_SwapBuffers();


  timer = SDL_AddTimer(20, move_ball, &red_ball);
  SDL_Delay(10);
  timer2 = SDL_AddTimer(20, move_ball, &blue_ball);

  /*Handle the keyboards events here. Catch the SDL_Quit event to exit*/
  done = 0;
  while (!done)
  {
    SDL_Event event;

    /* Check for events */
    while (SDL_PollEvent (&event))
    {
      switch (event.type)
      {
        case SDL_KEYDOWN:
	  break;

        case SDL_MOUSEBUTTONDOWN: 
	{
          switch(event.button.button) 
	  {
	    case SDL_BUTTON_LEFT: 
	    {
	      
              red_ball.destx = event.button.x;
	      red_ball.desty = event.button.y;

	      red_ball.dx = (red_ball.destx - red_ball.x)/50.0;
	      red_ball.dy = (red_ball.desty - red_ball.y)/50.0;

	      break;
	    }

	    case SDL_BUTTON_RIGHT:
	    {
              blue_ball.destx = event.button.x;
	      blue_ball.desty = event.button.y;

	      blue_ball.dx = (blue_ball.destx - blue_ball.x)/50.0;
	      blue_ball.dy = (blue_ball.desty - blue_ball.y)/50.0;

	      break;
	    }

	  }
	}
	break;

	case SDL_QUIT:
	  done = 1;
	  break;

	default:
	  break;

      }
    } 
  }

  /* Free the allocated surface*/
  SDL_FreeSurface(red_ball.ball_bmp);
  SDL_FreeSurface(blue_ball.ball_bmp);

}
Exemple #7
0
int main(int argc, char* argv[])
{	
	Grille g1 = lirefichier(argv[1]); //Création d'une nouvelle grille à partir d'un fichier chargé
	
	//La grille servira de contrôleur mais l'utilisateur ne la voit jamais : il ne voit que l'interface graphique qui en découlera
	
	joueur j1; //Création d'un nouveau joueur
	j1.posn = 0; 
	j1.posm = 0;
	posjoueur(g1, j1);
		
	SDL_Surface *screen, *temp, *sprite, *grass, *wall; //Création de surfaces SDL
	SDL_Rect rcSprite, rcGrass;
	SDL_Event event;
	Uint8 *keystate;
	int colorkey, gameover;
	
	SDL_Init(SDL_INIT_VIDEO); //initialisation de la fenêtre
	
	SDL_WM_SetCaption("Jeu TecDev SDL", "Jeu TecDev SDL"); //Définission du titre de la fenêtre
	
	screen = SDL_SetVideoMode(SCREEN_WIDTH, SCREEN_HEIGHT, 0, 0); //Création de la fenêtre
	
	temp   = SDL_LoadBMP("mushroom.bmp"); //Chargement du sprite mushroom.bmp dans la surface sprite
	sprite = SDL_DisplayFormat(temp);
	SDL_FreeSurface(temp);
	
	colorkey = SDL_MapRGB(screen->format, 255, 255, 255); //Création de la transparence du sprite
	SDL_SetColorKey(sprite, SDL_SRCCOLORKEY | SDL_RLEACCEL, colorkey); 
	
	temp  = SDL_LoadBMP("grass.bmp"); //Chargement du background grass.bmp dans la surface grass
	grass = SDL_DisplayFormat(temp);
	SDL_FreeSurface(temp);
				 
	temp  = SDL_LoadBMP("wall.bmp"); //Chargement de l'image wall.bmp dans la surface wall
	wall = SDL_DisplayFormat(temp);
	SDL_FreeSurface(temp);
	
	colorkey = SDL_MapRGB(screen->format, 255, 255, 255); //Transparence du mur
	SDL_SetColorKey(wall, SDL_SRCCOLORKEY | SDL_RLEACCEL, colorkey);

	rcSprite.x = 0; //Le sprite est en (0,0) à la base
	rcSprite.y = 0;
	
	gameover = 0; //Si gameover à 1 => Fin du jeu
	
	while (!gameover)
	{
	 if (SDL_PollEvent(&event)) {
		switch (event.type) {
			case SDL_QUIT:
				gameover = 1;
				break;
				
				case SDL_KEYDOWN:
				switch (event.key.keysym.sym) {
					case SDLK_ESCAPE: //Si la touche entrée est échap
					case SDLK_q: //ou q
						gameover = 1; //Alors quitter le jeu
						break;
					case SDLK_p: //Si la touche entrée est p
						while (event.key.keysym.sym != SDLK_p) { //Alors tant que la touche entrée n'est pas p
							rcSprite.x = rcSprite.x; //Le joueur ne bouge pas
							rcSprite.y = rcSprite.y;
						}
						break;
					case SDLK_r: //Si la touche entrée est r
						rcSprite.x = 0; //Réinitialisation du sprite en 0
						rcSprite.y = 0;
						j1.posn = 0; //Réinitialisation du joueur en 0
						j1.posm = 0;
						posjoueur(g1, j1); //Replacement du joueur dans la grille
						break;
					default:
						break;
				}
				break;
			}
		}
		
		//Traitement des cas ou l'utilisateur entre une touche fléchée
		
		keystate = SDL_GetKeyState(NULL); //L'utilisateur entre une touche qui sera contenue dans keystate
		
		int tempn = j1.posn;
		int tempm = j1.posm;
		
		if (keystate[SDLK_LEFT] ) 
		{ 
			if (j1.posm-1 >= 0) 
			{ 
				if (g1.g[j1.posn][j1.posm-1] == 0) 
				{
					j1.posm--;
					g1 = posjoueur(g1, j1); //Placement du joueur dans la grille aux cases correspondantes
					rcSprite.x -= STEP_SIZE;
					retiretrace(g1, j1); //Retire la présence précédente du joueur dans la grille
				}
				else 
				{
					j1.posm = tempm;
				}
			}
			else 
			{
				j1.posm = 0;
			}
		}
		if (keystate[SDLK_RIGHT] ) 
		{
			if (j1.posm+1 <= SCREEN_WIDTH/STEP_SIZE) 
			{
				if (g1.g[j1.posn][j1.posm+1] == 0)
				{
					j1.posm++;
					g1 = posjoueur(g1, j1);
					rcSprite.x += STEP_SIZE;
					retiretrace(g1, j1);
				}
				else
				{
					j1.posm = tempm;
				}
			}
			else 
			{
				j1.posm = SCREEN_WIDTH/STEP_SIZE;
			}
		}
		if (keystate[SDLK_UP] ) 
		{
			if (j1.posn-1 >= 0)
			{
				if (g1.g[j1.posn - 1][j1.posm] == 0) 
				{
					j1.posn--;
					g1 = posjoueur(g1, j1);
					rcSprite.y -= STEP_SIZE;
					retiretrace(g1, j1);
				}
				else 
				{
					j1.posn = tempn;
				}
			}
			else 
			{
				j1.posn = 0;
			}
		}
		if (keystate[SDLK_DOWN] ) 
		{
			if (j1.posn+1 < SCREEN_HEIGHT/STEP_SIZE) 
			{
				if (g1.g[j1.posn+1][j1.posm] == 0)
				{
					j1.posn++;
					g1 = posjoueur(g1, j1);
					rcSprite.y += STEP_SIZE;
					retiretrace(g1, j1);
				}
				else 
				{
					j1.posn = tempn;
				}
			}
			else
			{
				j1.posn = SCREEN_HEIGHT/STEP_SIZE;
			}
		}
		
		//Traitement des cas de collision avec les bords de l'écran
		
		/*if ( rcSprite.x < 0 ) {
			rcSprite.x = 0;
		}
		else if ( rcSprite.x > SCREEN_WIDTH-SPRITE_SIZE ) {
			rcSprite.x = SCREEN_WIDTH-SPRITE_SIZE;
		}
		if ( rcSprite.y < 0 ) {
			rcSprite.y = 0;
		}
		else if ( rcSprite.y > SCREEN_HEIGHT-SPRITE_SIZE ) {
			rcSprite.y = SCREEN_HEIGHT-SPRITE_SIZE;
		}*/
		
		// Placement des images en fonction de la grille => Création de l'aire de jeu
		
		int x, y;
		
		for (x = 0; x <= SCREEN_WIDTH/SPRITE_SIZE; x++)
		{
			for (y = 0; y < SCREEN_HEIGHT/SPRITE_SIZE; y++)
			{
				if (g1.g[y][x] == 0 || g1.g[y][x] == 8)//Si a cet endroit de la grille c'est libre
				{
					rcGrass.x = x * SPRITE_SIZE; //Déplacement du "curseur" rcGrass à cet endroit
					rcGrass.y = y * SPRITE_SIZE;
					SDL_BlitSurface(grass, NULL, screen, &rcGrass); //Placement de l'image grass à cet endroit
				}
				else if (g1.g[y][x] == 1) // Si à cet endroit il ya un mur
				{
					rcGrass.x = x * SPRITE_SIZE;
					rcGrass.y = y * SPRITE_SIZE;
					SDL_BlitSurface(wall, NULL, screen, &rcGrass); //Placement de l'image wall à cet endroit
				}
			}
		}
		
		SDL_BlitSurface(sprite, NULL, screen, &rcSprite); //Placement de l'image sprite à l'endroit indiqué par les coordonnées de rcSprite
		SDL_UpdateRect(screen,0,0,0,0); //Rafraîchissement de l'écran
	}
	
	//Quand le jeu est quitté :
	SDL_FreeSurface(sprite);
	SDL_FreeSurface(grass);
	SDL_FreeSurface(wall);
	SDL_Quit();

	return 0;
}
Exemple #8
0
int game(SDL_Surface* Screen, int score)
    {
        int keep=1;
        int timebg=0, time=0;
        int sizesnake = 1;
        int direction = RIGHT;
        int i=0, j=0;
        SDL_Surface *Wall = NULL, *Snake = NULL, *Empty = NULL, *Mush;
        SDL_Rect position;
            position.x;
            position.y;
        int map[BLOCK_WIDTH][BLOCK_HEIGHT]= {{0}};
        SDL_Event event;

        Snake = SDL_LoadBMP("BodySnake.bmp");
        Wall = SDL_LoadBMP("Wall.bmp");
        Empty = SDL_LoadBMP("MorceauFond.bmp");
        Mush = SDL_LoadBMP("mush.bmp");

        buildmap(map);

       while (keep)
            {
                SDL_PollEvent(&event);
                switch(event.type)
                {
                    case SDL_QUIT:
                    keep = 0;
                    break;

                    case SDL_KEYDOWN:
                        switch (event.key.keysym.sym)
                        {
                            case SDLK_DOWN:
                                        direction = BOT;
                                    break;

                            case SDLK_UP:
                                        direction = TOP;
                                    break;

                            case SDLK_LEFT:
                                        direction = LEFT;
                                    break;

                            case SDLK_RIGHT:
                                        direction = RIGHT;
                                break;

                            case SDLK_ESCAPE:
                                    keep = 0;
                                    break;
                        default:
                            break;

                            }
                        break;

                }

            time = SDL_GetTicks();

            if ( (time - timebg) > 80 )

                {
                    keep = movement(map , direction, sizesnake);
                    timebg=time;
                }
                BlitAll(map, Screen, Wall ,Empty, Snake, Mush);
                SDL_Flip(Screen);
            }
            
        SDL_Surface *Echec = NULL;//chargement de l'écran en cas d'échec
        SDL_Rect posEchec;
        posEchec.x = 0;
        posEchec.y = 0;
        Echec = SDL_LoadBMP("Echec.bmp");


        SDL_FillRect(Screen, NULL, SDL_MapRGB(Screen->format, 0, 0, 0));
        SDL_BlitSurface(Echec, NULL, Screen, &posEchec);
        SDL_Flip(Screen);

    return EXIT_SUCCESS;
    }
Exemple #9
0
int main(int argc, char **argv)
{
	struct birdPackage infoToSend, infoReceived;
	int	port;
	char serverIp  [16];
	if (argc != 3) {
        std::cout << "USO flappy <serverIp> <port>" << std::endl;
		exit(-1);
	}

	strcpy(serverIp, argv[1]);
	port = atoi(argv[2]);

	SocketDatagrama	socket;

	std::cout << "Enviando al servidor: " << serverIp << " : " << port << " datos iniciados" << std::endl;

	bzero(&infoToSend,sizeof(birdPackage));
	bzero(&infoReceived,sizeof(birdPackage));

	/* CONEXION POR PRIMERA VEZ */
	infoToSend.opcode = NEW;

	std::cout << "OPCODE: " << infoToSend.opcode << std::endl;

	PaqueteDatagrama paq((char *)&infoToSend, sizeof(birdPackage), serverIp, port);
	socket.envia(paq);

    PaqueteDatagrama receive(sizeof(birdPackage));
    socket.recibe(receive);

    memcpy(&infoReceived, receive.obtieneDatos(), sizeof(birdPackage));

	if(infoReceived.opcode == DENY) //Se rechaza al jugador, por lo que se tiene que salir
	{
		std::cout << "Partida llena intente más tarde..." << std::endl;
		exit(-1);
	}else{
		nJugador = infoReceived.jugadorNum;
		infoToSend.opcode = JUMP;
		std::cout << "Partida iniciada, jugador: " << nJugador << std::endl;
	}

	SDL_Init(SDL_INIT_VIDEO);
	SDL_Window     *ventana = SDL_CreateWindow("Hi", 200, 200, 864, 510, SDL_WINDOW_SHOWN);
	SDL_Renderer   *render = SDL_CreateRenderer(ventana, -1, SDL_RENDERER_ACCELERATED);
	//se carga la imagen que contiene todos los graficos
	SDL_Surface * bmp = SDL_LoadBMP("atlas.bmp");
	//se define el blanco como color transparente
	SDL_SetColorKey(bmp, 1, SDL_MapRGB(bmp->format, 255, 255, 255));
	SDL_Texture    *textura = SDL_CreateTextureFromSurface(render, bmp);
	SDL_FreeSurface(bmp);
	SDL_Event	event;
	if (textura == NULL) {
        std::cout << "FAILED TO FIND THE IMAGE" << std::endl;
	}
	SDL_RenderClear(render);
	renderFondo(render, textura);

	//Inicializa la posición de los pajaros dentro de la pantalla, pasandolos del atlas.bmp al recuadro del juego
	initPajarosOrigen(render, textura);
	SDL_RenderPresent(render);


	int		done = 1;
	double		angulo = 330;
	const int	FPS = 24;
	//Cuantos frames por segundo queremos, 60 es el que utilizan los televisores
    const int	DELAY_TIME = 1000.0f / FPS;
	//1000 ms entre los fps da el numero de milisegundos entre cada frame
    Uint32 frameStart, frameTime;
	while (done) {
		frameStart = SDL_GetTicks();

		//validacion del piso
		if (rectangulo_destino[nJugador].y < 500) {
			rectangulo_destino[nJugador].y += 10;
		}
		//validacion del angulo maximo
		if (angulo < 450) {
			angulo += 15;
		}
		//mientras exista un evento en el pila de eventos
			while (SDL_PollEvent(&event)) {
			//salto
			if (event.type == SDL_KEYDOWN && event.key.keysym.sym == SDLK_SPACE) {
				rectangulo_destino[nJugador].y -= 100;
				angulo = 300;
				infoToSend.opcode = 1;
			} else if (event.type == SDL_QUIT) {
				infoToSend.opcode = CLOSE;
				done = 0;
			}
		}
		//enviar Paquete con las coordenadas
		infoToSend.jugadorNum = nJugador;
		infoToSend.posicionJUMP_X[nJugador] = rectangulo_destino[nJugador].x;
		infoToSend.posicionJUMP_Y[nJugador] = rectangulo_destino[nJugador].y;
		infoToSend.angulo[nJugador] = angulo;
		PaqueteDatagrama paq((char *)&infoToSend, sizeof(birdPackage), serverIp, port);
		socket.envia(paq);
		//Recibir paquete con las coordenadas actualizadas
		PaqueteDatagrama receive(sizeof(birdPackage));
    	socket.recibe(receive);
    	memcpy(&infoReceived, receive.obtieneDatos(), sizeof(birdPackage));
		//se pinta actualiza el render
		SDL_RenderClear(render);
		renderFondo(render, textura);

		int i = 0;
		//Actualiza la posicion de los pajaros
		for (int i = 0; i < 3; ++i)
		{
			rectangulo_destino[i].x = infoReceived.posicionJUMP_X[i];
			rectangulo_destino[i].y = infoReceived.posicionJUMP_Y[i];
			angulos[i] = infoReceived.angulo[i];

		}
		for (i = 0; i < infoReceived.jugadoresTotales; ++i)
		{
			//funciona como copy pero rota la imagen con el angulo
			SDL_RenderCopyEx(render, textura, &rectangulo_origen[i], &rectangulo_destino[i], infoReceived.angulo[i], NULL, SDL_FLIP_NONE);
		}
		SDL_RenderPresent(render);

		frameTime = SDL_GetTicks() - frameStart;
		//Tiempo que ha tardado en presentarse el frame
		if (frameTime < DELAY_TIME)//Si es menor al tiempo que deber à ­a ser
		{
			SDL_Delay((int)(DELAY_TIME - frameTime));//Espera un tiempo
		}
	}

	/* Free all objects */
	SDL_DestroyTexture(textura);
	SDL_DestroyRenderer(render);
	SDL_DestroyWindow(ventana);

	/* Quit program */
	SDL_Quit();
	return 0;
}
void LoadGameData(void)
{
    SDL_Surface *tmp;
	
    /* The player's ship is stored as a 8640x96 image.
       This strip contains 90 individual images of the ship, rotated in
       four-degree increments. Take a look at fighter.bmp in an image
       viewer to see exactly what this means. */
    tmp = SDL_LoadBMP("fighter.bmp");
    if (tmp == NULL) {
	fprintf(stderr, "Unable to load ship image: %s\n", SDL_GetError());
	exit(1);
    }
	
    /* Set the color key on the ship animation strip to black.
       Enable RLE acceleration for a performance boost. */
    SDL_SetColorKey(tmp, SDL_SRCCOLORKEY|SDL_RLEACCEL, 0);
	
    /* Optimize the entire strip for fast display. */
    ship_strip = SDL_DisplayFormat(tmp);
    if (ship_strip == NULL) {
	/* We were unable to convert the image (for some foul reason),
	   but we can still use the copy we already have. This will
	   involve a performance loss. However, this should never happen. */
	ship_strip = tmp;
    } else SDL_FreeSurface(tmp);
	
    /* Now load the star tiles. Each tile is 64x64, assembled into a strip.
       We'll derive the number of tiles from the width of the loaded bitmap. */
    tmp = SDL_LoadBMP("back-stars.bmp");
    if (tmp == NULL) {
	fprintf(stderr, "Unable to load background tiles: %s\n", 
		SDL_GetError());
	exit(EXIT_FAILURE);
    }
	
    /* Determine how many star tiles are in the strip. We'll assume that the
       foreground and background strips contain the same number of stars. */
    num_star_tiles = tmp->w / 64;
    num_star_tiles = 4;
	
    /* Attempt to optimize this strip for fast blitting. */
    back_star_tiles = SDL_DisplayFormat(tmp);
    if (back_star_tiles == NULL)
	back_star_tiles = tmp;
    else	SDL_FreeSurface(tmp);	

    /* Load the front (parallaxing) set of star tiles. */
    tmp = SDL_LoadBMP("front-stars.bmp");
    if (tmp == NULL) {
	printf("Unable to load parallax tiles: %s\n", SDL_GetError());
	exit(EXIT_FAILURE);
    }
	
    /* Set a black color key and request RLE acceleration. */
    SDL_SetColorKey(tmp, SDL_SRCCOLORKEY | SDL_RLEACCEL, 0);

    /* Attempt to optimize this strip for fast blitting. */
    front_star_tiles = SDL_DisplayFormat(tmp);
    if (front_star_tiles == NULL)
      front_star_tiles = tmp;
    else	
      SDL_FreeSurface(tmp);	
}
Exemple #11
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
}
int main()
{
  SDL_Surface *temp;
  SDL_Surface *background;
  SDL_Rect src, dest;
  int frames;

  // Initialise SDL and test for errors
  if (SDL_Init(SDL_INIT_VIDEO) != 0)
    {
      printf("Unable to initialise SDL: %s\n", SDL_GetError());
      exit(EXIT_FAILURE);
      // PFJ - Changed from return 1;
    }

  // Ensure SDL_Quit is called on termination
  atexit(SDL_Quit);

  // Attempt to set a 640 x 480 hicolor mode with double buffer
  screen = SDL_SetVideoMode(640, 480, 16, SDL_DOUBLEBUF);
  if (screen == NULL)
    {
      printf("Unable to set video mode: %s\n", SDL_GetError());
      exit(EXIT_FAILURE);
      // PFJ - Changed from return 1;
    }

  /* Load the background image and convert it to the display's pixel format. 
     This conversion will drastically improve the performance of 
     SDL_BlitSurface, as it will not have to convert the surface on the fly */
  temp = SDL_LoadBMP("background.bmp");
  background = SDL_DisplayFormat(temp);
  if (background == NULL)
    {
      printf("Unable to load background image\n");
      exit(EXIT_FAILURE);
      // Both lines changed for correct exit and descriptive error message
    }

  // Free the temp surface as we don't need it now
  SDL_FreeSurface(temp);

  // Load penguin image
  temp = SDL_LoadBMP("smallpenguin.bmp");
  if (temp == NULL)
    {
      printf("Unable to load the penguin\n");
      exit(EXIT_FAILURE);
      // Both lines changed for correct exit and descriptive error message
    }

  /* Set the penguin's colorkey. Ask for RLE acceleration, a technique that 
     can significantly speed up colorkey blits */

  SDL_SetColorKey(temp, SDL_SRCCOLORKEY | SDL_RLEACCEL, 
		  (Uint16) SDL_MapRGB(temp->format, 0, 0, 255));


  /* Convert the penguin to the display's format. We do this after we set the 
     colorkey, since colorkey blits can sometimes be optimised for a 
     particular display */

  penguin = SDL_DisplayFormat(temp);
  if (penguin == NULL)
    {
      printf("Unable to convert the penguin bitmap\n");
      exit(EXIT_FAILURE);
      // Both lines changed for correct exit and descriptive error message
    }

  // Free temp surface - it's now stored in penguin
  SDL_FreeSurface(temp);

  // Initialise the penguin position data
  init_penguins();

  // Animate 300 frames [about 10 seconds]
  for (frames = 0; frames < 300; ++frames)
    {
      // Draw the background image
      src.x = 0;
      src.y = 0;
      src.w = background->w;
      src.h = background->h;
      dest = src;
      SDL_BlitSurface(background, &src, screen, &dest);

      // Put the penguins on the screen
      draw_penguins();

      // Ask SD: to swap the back buffer to the screen
      SDL_Flip(screen);

      // Move the penguins for the next frame
      move_penguins();
    }

  // Free the memory
  SDL_FreeSurface(background);
  SDL_FreeSurface(penguin);
}
/* A short example of the Pango use */
main(int argc, char *argv[])
{
    if ( SDL_Init(SDL_INIT_EVERYTHING) < 0 ) {
        fprintf(stderr, "Unable to init SDL: %s\n", SDL_GetError());
        exit(1);
    }
    puts("Initialisation of the SDL library succeed") ;

    if (SDLPango_Init() != 0) {
        perror("Failed to initialize the pango library") ;
        exit(1) ;
    }
    puts ("Initialisation of SDL_pango library succeed") ;

    /*The operation of SDL_Pango is done via context.*/
    SDLPango_Context *context = SDLPango_CreateContext();
    /* Specify default colors and minimum surface size. */
    SDLPango_SetDefaultColor(context, MATRIX_TRANSPARENT_BACK_WHITE_LETTER );
    SDLPango_SetMinimumSize( context, 640, 0 );
    /* Set markup text.*/
    SDLPango_SetMarkup(context, "This is <i>markup</i> text.", -1);
    /* Now you can get the size of surface.*/
    int w = SDLPango_GetLayoutWidth(context);
    int h = SDLPango_GetLayoutHeight(context);
    /* Create surface to draw. */
    int margin_x = 10;
    int margin_y = 10;

    SDL_Surface *screen;
    screen = SDL_SetVideoMode(640, 480, 16, SDL_SWSURFACE);
    if ( screen == NULL ) {
        fprintf(stderr, "Unable to set 640x480 video: %s\n", SDL_GetError());
        exit(1);
    }
    puts("success to set 640x480 video mode") ;

    SDL_Surface * surface = SDL_CreateRGBSurface(SDL_SWSURFACE,
        w + margin_x * 2, h + margin_y * 2,
        32, (Uint32)(255 << (8 * 3)), (Uint32)(255 << (8 * 2)),
        (Uint32)(255 << (8 * 1)), 255);
    if ( surface != NULL ) {
        SDLPango_Draw( context , surface , margin_x , margin_y );
        SDL_BlitSurface( surface, NULL, screen, NULL) ;
        SDL_Flip( screen );
        SDL_Delay( 2000 );
    }

    /* And draw on it. margin_x,y gives the space between
    the context and the edges of the SDL_Surface*/

    SDL_Surface * hello = SDL_LoadBMP( "hello.bmp" );
    if ( hello != NULL ){
        SDL_BlitSurface( hello , NULL , screen, NULL );
        SDL_Flip( screen );
        SDL_Delay( 2000 );
    }

    SDL_FreeSurface(hello) ;
    SDL_FreeSurface(surface);
    SDL_FreeSurface(screen) ;

    atexit(SDL_Quit);
    return 0 ;
}
Exemple #14
0
// Testing....
void CreateBackground(SDL_Renderer *renderer)
{
    bmp_surface = SDL_LoadBMP("background.bmp");
    background = SDL_CreateTextureFromSurface(renderer, bmp_surface);
    SDL_FreeSurface(bmp_surface);
}
Exemple #15
0
int main(int argc, char * argv[])
{
    /*variable declarations,
	remember, all v. decls. are at the beginning of each function in C*/
    int done = 0;
    const Uint8 * keys;
    
    int mx,my;
    float mf = 0;
	float guyFrame = 0;
	Sprite *thing;
	Sprite *thing2;
	Sprite *guyx;
	Sprite *galSprite;
	Sprite *mehSprite;
	int controllerConnected = 0;
	/*Sprite *myTileMap;
	const int level[] = 
	{ 2, 3, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 2, 3, 
	  3, 2, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 3, 2, 
	  2, 3, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 2, 3,
	  3, 2, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 3, 2,
	  2, 3, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 2, 3, 
	  3, 2, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 3, 2,
	  2, 3, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 2, 3, 
	  3, 2, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 3, 2,
	  2, 3, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 2, 3,
	  3, 2, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 3, 2 };*/
	FILE *tilemapFile;
	int tileClicked = 0;
	int p = 0;

    Vector4D mouseColor = {100,255,255,200};
	Vector2D flipVert = { 0, 1 };
	Vector2D scaleDown = { 0.5, 0.5 };
	Vector2D scaleUp = { 2, 2 };
	Vector2D scaleHalfUp = { 1.5, 1.5 };
	//IntNode *myLL = IntNode_init(5);
	/*Student *person;*/
	/*Entity *guy, *testDude;
	Entity *en = NULL;
	Entity *biggo = NULL;
	FILE *infile;
	Entity *fileLoadedDude = NULL;
	Entity *fileLoadedDude2 = NULL;*/
	SDL_Event e;
	SDL_Surface *icon = SDL_LoadBMP("images/sprites/guy16x.bmp");

	FILE *bandFile;
	FILE *levelFile;

	Sound *NJITtheme = NULL;
	Sound *snareDrum = NULL;
	Sound *flute = NULL;
	Sound *trumpet = NULL;
	Sound *altoSax = NULL;
	Sound *tenorSax = NULL;
	Uint32 musicPlaying = 0;
	//Sound *clap = NULL;
	Sound *cdEject = NULL;

	/*TTF_Font *PencilFont = TTF_OpenFont("fonts/Pencil.ttf", 24);
	if (!PencilFont)
	{
		slog("Error loading font");
	}
	SDL_Color colorBlack = { 255, 255, 255, 255 };
	SDL_Surface *surfaceMessage = TTF_RenderText_Solid(PencilFont, "placeholdha", colorBlack);
	SDL_Texture *message = SDL_CreateTextureFromSurface(gf2d_graphics_get_renderer, surfaceMessage);
	Sprite *textBox;*/
	TTF_Font *PencilFont;
	SDL_Color colorBlack = { 0, 0, 0, 255 };
	SDL_Surface *surfaceMessage;
	SDL_Texture *message;
	Sprite *textBox;
	TextDisplay *nameText;
	int texW = 0, texH = 0;
	SDL_Rect rect = { 65, 630, 0, 0 };

	SDL_Surface *instrumentSurface;
	SDL_Texture *instrumentTexture;
	int instX = 0, instY = 0;
	SDL_Rect instrumentRect = { 65, 660, 0, 0 };

	Uint8 playButtonPressed = 0;

	srand(time(NULL));

    /*program initializtion*/
    init_logger("dmdwa.log");
    slog("---==== BEGIN ====---");
    gf2d_graphics_initialize(
        "Drum Majors Don't Wear Aussies",
        1200,
        720,
        1200,
        720,
        vector4d(0,0,0,255),
        0,
		icon);
	//SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, "0"); //This line makes images render crisp instead of blurry
    gf2d_graphics_set_frame_delay(16);
    gf2d_sprite_init(1024);
	entitySystemInit(1024);
	audioSystemInit(50, 10, 2, 0, 0, 0);
	soundSystemInit(25);
	text_system_init(50);
    SDL_ShowCursor(SDL_DISABLE);
	TTF_Init();
	//fileLoadedDude = entityNew();

	//derp
	//slog("%i", myLL->data);
    
    /*demo setup*/
    //backgroundSprite = gf2d_sprite_load_image("images/backgrounds/bg_flat.png");
	//textBox = gf2d_sprite_load_image("images/backgrounds/bg_flat.png");
    mouseSprite = gf2d_sprite_load_all("images/pointer.png",32,32,16);
	mouse = mouseSprite;
	//thing = gf2d_sprite_load_all("images/sprites/test_dude.png", 32, 32, 1);
	//thing2 = gf2d_sprite_load_all("images/sprites/test_dude3.png", 64, 64, 1);
	//guyx = gf2d_sprite_load_all("images/sprites/guy32x.png", 32, 32, 2);
	//galSprite = gf2d_sprite_load_all("images/sprites/gal32x.png", 32, 32, 2);
	//mehSprite = gf2d_sprite_load_all("images/sprites/meh32x.png", 32, 32, 2);
	//musicSheet = gf2d_sprite_load_image("images/gui/music_sheet.png");
	controllerIcon = gf2d_sprite_load_all("images/gui/controller64x.png", 64, 64, 1);
	//myTileMap = gf2d_sprite_load_all("images/field_tiles.png", 64, 64, 2);
	//person = student("Test", "Sex", thing2);
	//slog("Initializing student %s", person->name);
	/*guy = entityNew();
	strncpy(guy->name, "McBandgeek", 32);
	guy->mySprite = guyx;
	guy->scale = scaleUp;
	guy->currentFrame = 0;
	guy->minFrame = 0;
	guy->maxFrame = 2;
	guy->position = vector2d(300, 100);
	guy->update = move;
	guy->myInstrument = Instrument_Tenor_Saxophone;
	guy->instrumentSprite = gf2d_sprite_load_all("images/sprites/instrument_tenor_sax.png", 32, 32, 1);
	guy->boundingBox = rect_new(guy->position.x, guy->position.y, 64, 64);
	testDude = NULL;
	//SDL_SetTextureColorMod(thing2->texture, 100, 60, 0);
	infile = fopen("def/dude.dude", "r");
	fileLoadedDude = entityNew();
	fileLoadedDude = entityLoadFromFile(infile, fileLoadedDude);
	fclose(infile);
	//fileLoadedDude->mySprite = mehSprite;
	fileLoadedDude->instrumentSprite = gf2d_sprite_load_all(&fileLoadedDude->instrumentSpriteFilePath, 32, 32, 1);
	fileLoadedDude->position = vector2d(64, 64);
	fileLoadedDude->boundingBox = rect_new(fileLoadedDude->position.x, fileLoadedDude->position.y, 64, 64);
	fileLoadedDude->scale = vector2d(2, 2);
	fileLoadedDude->currentFrame = 0;
	fileLoadedDude->minFrame = 0;
	fileLoadedDude->maxFrame = 2;
	fileLoadedDude->currentPosition = 19;
	slog("the thing made has name: %s", &fileLoadedDude->name);

	infile = fopen("def/dude2.dude", "r");
	fileLoadedDude2 = entityNew();
	fileLoadedDude2 = entityLoadFromFile(infile, fileLoadedDude2);
	fclose(infile);
	fileLoadedDude2->instrumentSprite = gf2d_sprite_load_all(&fileLoadedDude2->instrumentSpriteFilePath, 32, 32, 1);
	fileLoadedDude2->position = vector2d(128, 64);
	fileLoadedDude2->boundingBox = rect_new(fileLoadedDude2->position.x, fileLoadedDude2->position.y, 64, 64);
	fileLoadedDude2->scale = vector2d(2, 2);
	fileLoadedDude2->currentFrame = 0;
	fileLoadedDude2->minFrame = 0;
	fileLoadedDude2->maxFrame = 2;
	fileLoadedDude2->currentPosition = 20;*/

	tile_map = tilemap_init();
	load_level("def/level/mainMenu.txt", 0);

	//textBox->texture = message;

	//Trying to load a tilemap from file
	//tilemapFile = fopen("def/level/field_0.tilemap", "r");
	//tilemap_load_from_file(tilemapFile, tile_map);
	//fclose(tilemapFile);
	//slog("tilewidth: (%i) tileheight: (%i) tperline: (%i) filepath: (...) width: (%i) height: (%i) xPos: (%i) yPos: (%i)", tile_map->tileWidth,	tile_map->tileHeight, tile_map->tilesPerLine, tile_map->width, tile_map->height, tile_map->xPos, tile_map->yPos);
	//slog("do i have a sprite? %i", tile_map->tilemapSprite != NULL);
	//tile_map->space[19] = 1;
	//tile_map->space[20] = 1;
	/*slog("tile pq start");
	while (tile_map->tiles_head != NULL)
	{
		p = pq_delete(tile_map->tiles_head, tile_map->tiles_tail);
		if (p == NULL)
		{
			break;
		}
		slog("Removing (%d) from pq", p);
	}
	slog("tile pq end");*/
	/*slog("start array");
	for (p = 0; p < tile_map->width * tile_map->height; p++)
	{
		if (p == 512)
		{
			slog("end of array");
		}
		else if (tile_map->tiles[p] == -1)
		{
			slog("found a -1");
		}
		else
		{
			slog("tiles at index (%i) is (%i)", p, tile_map->tiles[p]);
		}
	}
	slog("end array");*/

	//Trying to load all entities from a file
	//bandFile = fopen("def/_myBand.band", "r");
	//entityLoadAllFromFile(bandFile);
	//fclose(bandFile);

	//Load sounds
	//NJITtheme = soundNew("music/bg/NJIT.ogg");
	//NJITtheme = soundLoad("music/bg/NJIT.ogg", 12.0f, 3);
	//slog("do i have a sound? %i", NJITtheme->sound != NULL);
	//soundPlay(NJITtheme, 1, 0, 0, 0);
	//Mix_VolumeChunk(NJITtheme->sound, MIX_MAX_VOLUME); //Use this to change volume on the fly!
	//clap = soundLoad("music/sfx/clap.ogg", 5.0f, 1);
	cdEject = soundNew();
	cdEject = soundLoad("music/sfx/cd_play.ogg", 18.0f, 0);

	snareDrum = soundNew("music/bg/meeeeh-Snare_Drum.ogg");
	snareDrum = soundLoad("music/bg/meeeeh-Snare_Drum.ogg", 12.0f, Instrument_Snare_Drum);
	flute = soundNew("music/bg/meeeeh-Flute.ogg");
	flute = soundLoad("music/bg/meeeeh-Flute.ogg", 12.0f, Instrument_Flute);
	trumpet = soundNew("music/bg/meeeeh-Bb_Trumpet.ogg");
	trumpet = soundLoad("music/bg/meeeeh-Bb_Trumpet.ogg", 12.0f, Instrument_Trumpet);
	altoSax = soundNew("music/bg/meeeeh-Alto_Saxophone.ogg");
	altoSax = soundLoad("music/bg/meeeeh-Alto_Saxophone.ogg", 12.0f, Instrument_Alto_Saxophone);
	tenorSax = soundNew("music/bg/meeeeh-Tenor_Saxophone.ogg");
	tenorSax = soundLoad("music/bg/meeeeh-Tenor_Saxophone.ogg", 12.0f, Instrument_Tenor_Saxophone);

	//soundPlay(snareDrum, -1, 1, snareDrum->defaultChannel, 0);
	//soundPlay(flute, -1, 1, flute->defaultChannel, 0);
	//soundPlay(trumpet, -1, 1, trumpet->defaultChannel, 0);
	//soundPlay(altoSax, -1, 1, altoSax->defaultChannel, 0);
	//soundPlay(tenorSax, -1, 1, tenorSax->defaultChannel, 0);

	//text testing stuff
	PencilFont = TTF_OpenFont("fonts/Pencil.ttf", 36);
	if (!PencilFont)
	{
		slog("Error loading font");
	}
	surfaceMessage = TTF_RenderText_Solid(PencilFont, "None selected", colorBlack);
	message = SDL_CreateTextureFromSurface(gf2d_graphics_get_renderer(), surfaceMessage);
	SDL_QueryTexture(message, NULL, NULL, &texW, &texH);
	rect.w = texW;
	rect.h = texH;
	nameText = text_new(PencilFont, "placeholda", colorBlack);
	//slog("nameText inuse (%i)", nameText->inUse);

	instrumentSurface = TTF_RenderText_Solid(PencilFont, "", colorBlack);
	instrumentTexture = SDL_CreateTextureFromSurface(gf2d_graphics_get_renderer(), instrumentSurface);
	SDL_QueryTexture(instrumentTexture, NULL, NULL, &instX, &instY);
	instrumentRect.w = instX;
	instrumentRect.h = instY;

	cd = entityNew();
	cd->mySprite = gf2d_sprite_load_all("images/gui/cd.png", 128, 128, 1);
	cd->position = vector2d(0, 0);
	cd->scale = vector2d(2, 2);
	cd->boundingBox = rect_new(cd->position.x, cd->position.y, 128, 128);

	playButton = entityNew();
	playButton->mySprite = gf2d_sprite_load_image("images/gui/play.png");
	playButton->position = vector2d(64, 256);
	strncpy(playButton->name, "playButton", MAX_CHARS);
	playButton->boundingBox = rect_new(playButton->position.x, playButton->position.y, playButton->mySprite->frame_w, playButton->mySprite->frame_h);
	

    /*main game loop*/
    while(!done)
    {
        SDL_PumpEvents();   // update SDL's internal event structures
        keys = SDL_GetKeyboardState(NULL); // get the keyboard state for this frame
        /*update things here*/
        SDL_GetMouseState(&mx,&my);
		SDL_PollEvent(&e);
        mf+=0.1;
        if (mf >= 16.0)mf = 0;        
		guyFrame += 0.05;
		if (guyFrame >= 2.0)guyFrame = 0;
        
        gf2d_graphics_clear_screen();// clears drawing buffers
        // all drawing should happen betweem clear_screen and next_frame
		//backgrounds drawn first
		if (backgroundSprite)
		{
			gf2d_sprite_draw_image(backgroundSprite, vector2d(0, 0));
		}

		//Me! trying to add a sprite
		/*tilemap_draw(
			myTileMap,
			level,
			18,
			10,
			0,
			0);*/
		if (tile_map)
		{
			tilemap_draw_from_data(tile_map);
		}

		//gf2d_sprite_draw(thing, vector2d(100, 10), &scaleUp, NULL, NULL, NULL, NULL, 0);
		//gf2d_sprite_draw(thing, vector2d(100, 10), NULL, NULL, NULL, NULL, NULL, 0);
		//gf2d_sprite_draw(guy->mySprite, guy->position, &(guy->scale), NULL, NULL, NULL, NULL, 0);

		/*if (keys[SDL_SCANCODE_W])
		{
			(*guy->update)(guy, vector2d(0, -2));
		}
		if (keys[SDL_SCANCODE_A])
		{
			(*guy->update)(guy, vector2d(-2, 0));
		}
		if (keys[SDL_SCANCODE_S])
		{
			(*guy->update)(guy, vector2d(0, 2));
		}
		if (keys[SDL_SCANCODE_D])
		{
			(*guy->update)(guy, vector2d(2, 0));
		}*/
		//guy->currentFrame = guyFrame;
		//fileLoadedDude->currentFrame = guyFrame;

		/*
		//create an entity if it doesn't exist
		if (keys[SDL_SCANCODE_O] && testDude == NULL)
		{
			testDude = entityNew();
			testDude->mySprite = thing;
			testDude->position = vector2d(500, 500);
			testDude->update = move;
		}
		//if it exists, call its update function
		//slog("%i", testDude != NULL);
		if (testDude != NULL)
		{
			//(*testDude->update)(testDude, vector2d(1, 1));
			gf2d_sprite_draw(testDude->mySprite, testDude->position, NULL, NULL, NULL, NULL, NULL, 0);
		}
		//delete it from memory
		if (keys[SDL_SCANCODE_P] && testDude != NULL)
		{
			entityDelete(testDude);
		}*/
		/*if (keys[SDL_SCANCODE_L] && biggo == NULL)
		{
			biggo = entityNew();
			biggo->mySprite = guyx;
			biggo->position = vector2d(10, 10);
			biggo->scale = vector2d(25, 25);
			biggo->inUse = 1;
			biggo->currentFrame = 0;
			biggo->minFrame = 0;
			biggo->maxFrame = 2;
			biggo->update = move;
			biggo->velocity = vector2d(0.5f, 0.5f);
			biggo->acceleration = vector2d(0.5f, 0.5f);
			biggo->myInstrument = Instrument_Flute;
			biggo->instrumentSprite = gf2d_sprite_load_all("images/sprites/instrument_flute.png", 32, 32, 1);
		}
		if (biggo != NULL)
		{
			//entityDraw(biggo);
			(*biggo->update)(biggo, vector2d(0.5f, 0.5f));
			//biggo->currentFrame = guyFrame;
		}
		if (biggo != NULL && biggo->inUse == 1 && keys[SDL_SCANCODE_P])
		{
			biggo->inUse = 0;
			entityDelete(biggo);
			biggo = NULL;
		}
		if (keys[SDL_SCANCODE_O] && testDude == NULL)
		{
			//slog("Let's make a new thing!");
			testDude = entityNew();
			testDude->mySprite = mehSprite;
			testDude->position = vector2d(200, 200);
			testDude->scale = scaleUp;
			testDude->inUse = 1;
			testDude->currentFrame = 0;
			testDude->minFrame = 1;
			testDude->maxFrame = 3;
			testDude->update = move;
			testDude->instrumentSprite = gf2d_sprite_load_all("images/sprites/instrument_tuba.png", 32, 32, 1);
		}
		if (testDude != NULL)
		{
			//gf2d_sprite_draw(testDude->mySprite, testDude->position, &(testDude->scale), NULL, NULL, NULL, NULL, 0);
			//entityDraw(testDude);
			(*testDude->update)(testDude, vector2d(1, 1));
			//testDude->currentFrame = guyFrame;
		}
		if (testDude != NULL && testDude->inUse == 1 && keys[SDL_SCANCODE_P])
		{
			testDude->inUse = 0;
			entityDelete(testDude);
			testDude = NULL;
		}
		if (keys[SDL_SCANCODE_M] && en == NULL)
		{
			en = entityNew();
			en->mySprite = galSprite;
			en->position = vector2d(300, 500);
			en->scale = vector2d(1,1);
			en->inUse = 1;
			en->currentFrame = 0;
			en->minFrame = 0;
			en->maxFrame = 4;
			en->update = move;
			en->instrumentSprite = gf2d_sprite_load_all("images/sprites/instrument_clarinet.png", 32, 32, 1);
			//soundPlay(clap, 0, clap->volume, clap->defaultChannel, 0);
		}
		if (en != NULL && en->inUse == 1)
		{
			//entityDraw(en);
			(*en->update)(en, vector2d(1, -1));
			//en->currentFrame = guyFrame;
		}
		if (en != NULL && en->inUse == 1 && keys[SDL_SCANCODE_P])
		{
			en->inUse = 0;
			entityDelete(en);
			en = NULL;
		}
		if (en != NULL && en->inUse == 1 && en->position.x >= 400)
		{
			en->inUse = 0;
			entityDelete(en);
			en = NULL;
		}*/

		/*gf2d_sprite_draw(
			guyx,
			vector2d(64, 64),
			&scaleUp,
			NULL,
			NULL,
			NULL,
			NULL,
			0
		);
		gf2d_sprite_draw(
			galSprite,
			vector2d(128, 64),
			&scaleUp,
			NULL,
			NULL,
			NULL,
			NULL,
			0
		);
		gf2d_sprite_draw(
			mehSprite,
			vector2d(192, 64),
			&scaleUp,
			NULL,
			NULL,
			NULL,
			NULL,
			0
		);*/

		//entityDraw(fileLoadedDude);

		entityDrawAll();
		entityUpdateAll();
		entityIncrementCurrentFrameAll();

		if (pickedUp != NULL)
		{
			draw_line(vector2d(pickedUp->position.x + pickedUp->mySprite->frame_w, pickedUp->position.y + pickedUp->mySprite->frame_h),
						vector2d(mx, my), COLOR_RED);
		}

		switch (e.type)
		{
		case SDL_QUIT:
			done = 1;
			break;
		case SDL_MOUSEBUTTONDOWN:
			if (e.button.button == SDL_BUTTON_RIGHT)
			{
				tileClicked = tilemap_find_tile(mx, my, tile_map);
				if (tileClicked >= 0 && pickedUp != NULL)
				{
					if (tile_map->space[tileClicked] == 0)
					{
						slog("poop");
						tile_map->space[pickedUp->currentPosition] = 0;
						tile_map->space[tileClicked] = 1;
						pickedUp->currentPosition = tileClicked;
						mouse = mouseSprite;
						pickedUp->position.x = (mx - tile_map->xPos) / tile_map->tileWidth * (tile_map->tileWidth);
						pickedUp->position.y = (my - tile_map->yPos) / tile_map->tileHeight * (tile_map->tileHeight);
						pickedUp = NULL;
						surfaceMessage = TTF_RenderText_Solid(PencilFont, "None selected", colorBlack);
						message = SDL_CreateTextureFromSurface(gf2d_graphics_get_renderer(), surfaceMessage);
						SDL_QueryTexture(message, NULL, NULL, &texW, &texH);
						rect.w = texW;
						rect.h = texH;

						instrumentSurface = TTF_RenderText_Solid(PencilFont, "", colorBlack);
						instrumentTexture = SDL_CreateTextureFromSurface(gf2d_graphics_get_renderer(), instrumentSurface);
						SDL_QueryTexture(instrumentTexture, NULL, NULL, &instX, &instY);
						instrumentRect.w = instX;
						instrumentRect.h = instY;
					}
				}
			}
			else if (e.button.button == SDL_BUTTON_LEFT)
			{
				if (playButton != NULL)
				{
					if (point_in_rect(mx, my, playButton->boundingBox))
					{
						//slog("hit da BUTT");
						playButtonPressed = 1;
						soundPlay(cdEject, 0, 5.0f, -1, 0);
					}
				}
			}
			break;
		case SDL_MOUSEBUTTONUP:
			if (e.button.button == SDL_BUTTON_LEFT)
			//if (mousePress(&e.button))
			{
				/*if (point_in_rect(mx, my, guy->boundingBox))
				{
					slog("collision with guy (%s)", guy->name);
				}
				if (point_in_rect(mx, my, fileLoadedDude->boundingBox))
				{
					slog("collision with guy (%s)", &fileLoadedDude->name);
					if (pickedUp == NULL)
					{
						pickedUp = fileLoadedDude;
						mouse = fileLoadedDude->mySprite;
					}
				}
				if (point_in_rect(mx, my, fileLoadedDude2->boundingBox))
				{
					slog("collision with guy (%s)", &fileLoadedDude2->name);
					if (pickedUp == NULL)
					{
						pickedUp = fileLoadedDude2;
						mouse = fileLoadedDude2->mySprite;
					}
				}*/

				collision = entityCheckCollisionInAll(mx, my);
				if (collision != NULL && collision->myInstrument != Instrument_Unassigned)
				{
					slog("collision with guy (%s)", &collision->name);
					if (pickedUp == NULL)
					{
						pickedUp = collision;
						mouse = collision->mySprite;
						surfaceMessage = TTF_RenderText_Solid(PencilFont, &pickedUp->name, colorBlack);
						message = SDL_CreateTextureFromSurface(gf2d_graphics_get_renderer(), surfaceMessage);
						SDL_QueryTexture(message, NULL, NULL, &texW, &texH);
						rect.w = texW;
						rect.h = texH;

						instrumentSurface = TTF_RenderText_Solid(PencilFont, entityGetInstrumentName(pickedUp), colorBlack);
						instrumentTexture = SDL_CreateTextureFromSurface(gf2d_graphics_get_renderer(), instrumentSurface);
						SDL_QueryTexture(instrumentTexture, NULL, NULL, &instX, &instY);
						instrumentRect.w = instX;
						instrumentRect.h = instY;
					}
				}

				//if (point_in_rect(mx, my, tile_map->boundingBox))
				tileClicked = tilemap_find_tile(mx, my, tile_map);
				if (tileClicked >= 0)
				{
					//slog("collided with tilemap on tile (%i), occupied (%i)", tileClicked, tile_map->space[tileClicked]);
				}
			}
			break;
		case SDL_CONTROLLERDEVICEADDED:
			slog("Connected a controller");
			controllerConnected = 1;
			break;
		case SDL_CONTROLLERDEVICEREMOVED:
			slog("Removed a controller");
			controllerConnected = 0;
			break;
		}

		if (playButtonPressed && cd != NULL)
		{
			cd->position.x += 5;
		}

		if (cd != NULL)
		{
			if (point_in_rect(1000, 10, cd->boundingBox))
			{
				load_level("def/level/myLevel.txt", 1);
				if (musicPlaying > 0)
				{
					//Mix_RewindMusic();
					Mix_HaltChannel(-1);
				}
				soundPlay(snareDrum, -1, 1, snareDrum->defaultChannel, 0);
				soundPlay(flute, -1, 1, flute->defaultChannel, 0);
				soundPlay(trumpet, -1, 1, trumpet->defaultChannel, 0);
				soundPlay(altoSax, -1, 1, altoSax->defaultChannel, 0);
				soundPlay(tenorSax, -1, 1, tenorSax->defaultChannel, 0);
				musicPlaying = 1;
			}
		}
		//slog("ds %i %i %i %i", cd->boundingBox->x, cd->boundingBox->y, cd->boundingBox->w, cd->boundingBox->h);

		//UI elements last
		if (musicSheet)
			gf2d_sprite_draw(musicSheet, vector2d(0, 592), &scaleUp, NULL, NULL, NULL, NULL, 0);
		if (gui)
			gf2d_sprite_draw(gui, vector2d(0, 0), &scaleUp, NULL, NULL, NULL, NULL, 0);
		//text_draw_all();
		//text_draw(nameText);
		if (message && musicSheet)
		{
			SDL_RenderCopy(gf2d_graphics_get_renderer(), message, NULL, &rect);
			SDL_RenderCopy(gf2d_graphics_get_renderer(), instrumentTexture, NULL, &instrumentRect);
		}
		//SDL_RenderPresent(renderer);
		//gf2d_sprite_draw_image(textBox, vector2d(50, 50));
		if (controllerConnected && controllerIcon)
			gf2d_sprite_draw(controllerIcon, vector2d(700, 600), &scaleUp, NULL, NULL, NULL, NULL, 0);
		if (pickedUp == NULL)
		{
			gf2d_sprite_draw(
				mouse,				//Sprite to load
				vector2d(mx, my),	//Position to draw it at
				NULL,				//If you want to scale the sprite
				NULL,				//Scale the sprite from a certain position
				NULL,				//Rotation
				NULL,				//Flip
				&mouseColor,		//Color shift
				(int)mf);			//Which frame to draw at
		}
		else
		{
			gf2d_sprite_draw(
				mouse,				//Sprite to load
				vector2d(mx, my),	//Position to draw it at
				&scaleHalfUp,		//If you want to scale the sprite
				NULL,				//Scale the sprite from a certain position
				NULL,				//Rotation
				NULL,				//Flip
				&mouseColor,		//Color shift
				0);			//Which frame to draw at
		}
		gf2d_grahics_next_frame();// render current draw frame and skip to the next frame
        
		if (keys[SDL_SCANCODE_Q])
		{
			//close_level(tile_map);
			load_level("def/level/myLevel.txt", 1);
			if (musicPlaying > 0)
			{
				//Mix_RewindMusic();
				Mix_HaltChannel(-1);
			}
			soundPlay(snareDrum, -1, 1, snareDrum->defaultChannel, 0);
			soundPlay(flute, -1, 1, flute->defaultChannel, 0);
			soundPlay(trumpet, -1, 1, trumpet->defaultChannel, 0);
			soundPlay(altoSax, -1, 1, altoSax->defaultChannel, 0);
			soundPlay(tenorSax, -1, 1, tenorSax->defaultChannel, 0);
			musicPlaying = 1;
		}

        if (keys[SDL_SCANCODE_ESCAPE])done = 1; // exit condition
        //slog("Rendering at %f FPS",gf2d_graphics_get_frames_per_second());
    }
    slog("---==== END ====---");
	TTF_Quit();
	SDL_DestroyTexture(message);
	SDL_FreeSurface(surfaceMessage);
    return 0;
}
//defines the file names for the SDL_Surfaces
void Application::loadSurfaces()
{
    camera = SDL_LoadBMP("media/backdrop.bmp");
    background = SDL_LoadBMP("media/background5.bmp");

    ground = addItem("media/ground.bmp", environment.groundPos);
    ground1 = addItem("media/ground4.bmp", environment.groundPos1);
    ground2 = addItem("media/ground6.bmp", environment.groundPos2);
    stairs1 = addItem("media/bricks.bmp", environment.stairs1Pos);
    stairs2 = addItem("media/bricks2.bmp", environment.stairs2Pos);
    stairs3 = addItem("media/stairs3.bmp", environment.stairs3Pos);
    pillar = addItem("media/pillar.bmp", environment.pillarPos);
    wall1 = addItem("media/wall1.bmp", environment.wallPos1);
    wall2 = addItem("media/wall3.bmp", environment.wall2Pos);
    wall3 = addItem("media/wall4.bmp", environment.wall3Pos);
    wall4 = addItem("media/wall5.bmp", environment.wall4Pos);
    wall5 = addItem("media/stairs3.bmp", environment.wall5Pos);
    platform1 = addItem("media/platform1.bmp", environment.platform1Pos);
    platform2 = addItem("media/platform1.bmp", environment.platform2Pos);
    platform3 = addItem("media/platform2.bmp", environment.platform3Pos);
    platform4 = addItem("media/platform1.bmp", environment.platform4Pos);
    platform5 = addItem("media/platform1.bmp", environment.platform5Pos);
    platform6 = addItem("media/platform1.bmp", environment.platform6Pos);
    platform7 = addItem("media/platform1.bmp", environment.platform7Pos);

    stairs4 = addItem("media/bricks.bmp", environment.stairs4Pos);
    stairs5 = addItem("media/bricks2.bmp", environment.stairs5Pos);
    stairs6 = addItem("media/stairs3.bmp", environment.stairs6Pos);

    island1 = SDL_LoadBMP("media/fisland1.bmp");
    island2 = SDL_LoadBMP("media/fisland1.bmp");
    island3 = SDL_LoadBMP("media/fisland1.bmp");
    island4 = SDL_LoadBMP("media/fisland1.bmp");
    spikes = SDL_LoadBMP("media/spikes1.bmp");
    spikes1 = SDL_LoadBMP("media/spikes2.bmp");

    finish = SDL_LoadBMP("media/finish.bmp");

    for(int i = 0; i<=99; i++)//load arrow surfaces
    {
        quiver[i].arrowR = SDL_LoadBMP("media/arrowR.bmp");
        quiver[i].arrowL = SDL_LoadBMP("media/arrowL.bmp");
    }

}
Exemple #17
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
}
void Sprite::CargarImagen(char*path)
{
	image=SDL_LoadBMP(path);
}
/*
 * This thread will read the buttons in an interrupt like fashion, and
 * also initializes SDL_INIT_VIDEO and the surfaces
 *
 * it must be done in the same thread (at least on windows) because events only
 * work in the thread which called SDL_Init(SubSystem) with SDL_INIT_VIDEO
 *
 * This is an SDL thread and relies on preemptive behavoir of the host
 **/
static int sdl_event_thread(void * param)
{
    SDL_InitSubSystem(SDL_INIT_VIDEO);

#if (CONFIG_PLATFORM & PLATFORM_MAEMO)
    SDL_sem *wait_for_maemo_startup;
#endif
    SDL_Surface *picture_surface = NULL;
    int width, height;
    int depth;
    Uint32 flags;

    /* Try and load the background image. If it fails go without */
    if (background) {
        picture_surface = SDL_LoadBMP("UI256.bmp");
        if (picture_surface == NULL) {
            background = false;
            DEBUGF("warn: %s\n", SDL_GetError());
        }
    }
    
    /* Set things up */
    if (background)
    {
        width = UI_WIDTH;
        height = UI_HEIGHT;
    } 
    else 
    {
#ifdef HAVE_REMOTE_LCD
        if (showremote)
        {
            width = SIM_LCD_WIDTH > SIM_REMOTE_WIDTH ? SIM_LCD_WIDTH : SIM_REMOTE_WIDTH;
            height = SIM_LCD_HEIGHT + SIM_REMOTE_HEIGHT;
        }
        else
#endif
        {
            width = SIM_LCD_WIDTH;
            height = SIM_LCD_HEIGHT;
        }
    }

    depth = LCD_DEPTH;
    if (depth < 8)
        depth = 16;

    flags = SDL_HWSURFACE|SDL_DOUBLEBUF;
#if (CONFIG_PLATFORM & (PLATFORM_MAEMO|PLATFORM_PANDORA))
    /* Fullscreen mode for maemo app */
    flags |= SDL_FULLSCREEN;
#endif

    if ((gui_surface = SDL_SetVideoMode(width * display_zoom, height * display_zoom, depth, flags)) == NULL) {
        panicf("%s", SDL_GetError());
    }

#if (CONFIG_PLATFORM & (PLATFORM_MAEMO|PLATFORM_PANDORA))
    /* SDL touch screen fix: Work around a SDL assumption that returns
       relative mouse coordinates when you get to the screen edges
       using the touchscreen and a disabled mouse cursor.
     */
    uint8_t hiddenCursorData = 0;
    SDL_Cursor *hiddenCursor = SDL_CreateCursor(&hiddenCursorData, &hiddenCursorData, 8, 1, 0, 0);

    SDL_ShowCursor(SDL_ENABLE);
    SDL_SetCursor(hiddenCursor);
#endif

    SDL_WM_SetCaption(UI_TITLE, NULL);

    if (background && picture_surface != NULL)
        SDL_BlitSurface(picture_surface, NULL, gui_surface, NULL);

    /* let system_init proceed */
    SDL_SemPost((SDL_sem *)param);

#if (CONFIG_PLATFORM & PLATFORM_MAEMO)
    /* Start maemo thread: Listen to display on/off events and battery monitoring */
    wait_for_maemo_startup = SDL_CreateSemaphore(0); /* 0-count so it blocks */
    SDL_Thread *maemo_thread = SDL_CreateThread(maemo_thread_func, wait_for_maemo_startup);
#endif

    /*
     * finally enter the button loop */
    gui_message_loop();

#if (CONFIG_PLATFORM & PLATFORM_MAEMO)
    /* Ensure maemo thread is up and running */
    SDL_SemWait(wait_for_maemo_startup);
    SDL_DestroySemaphore(wait_for_maemo_startup);

#if (CONFIG_PLATFORM & PLATFORM_MAEMO5)
    pcm_shutdown_gstreamer();
#endif

    g_main_loop_quit (maemo_main_loop);
    g_main_loop_unref(maemo_main_loop);
    SDL_WaitThread(maemo_thread, NULL);
#endif

#if (CONFIG_PLATFORM & (PLATFORM_MAEMO|PLATFORM_PANDORA))
    SDL_FreeCursor(hiddenCursor);
#endif

    if(picture_surface)
        SDL_FreeSurface(picture_surface);

    /* Order here is relevent to prevent deadlocks and use of destroyed
       sync primitives by kernel threads */
#ifdef HAVE_SDL_THREADS
    sim_thread_shutdown(); /* not needed for native threads */
#endif
    return 0;
}
Exemple #20
0
/*
 * This thread will read the buttons in an interrupt like fashion, and
 * also initializes SDL_INIT_VIDEO and the surfaces
 *
 * it must be done in the same thread (at least on windows) because events only
 * work in the thread which called SDL_Init(SubSystem) with SDL_INIT_VIDEO
 *
 * This is an SDL thread and relies on preemptive behavoir of the host
 **/
static int sdl_event_thread(void * param)
{
    SDL_InitSubSystem(SDL_INIT_VIDEO);

    SDL_Surface *picture_surface;
    int width, height;

    /* Try and load the background image. If it fails go without */
    if (background) {
        picture_surface = SDL_LoadBMP("UI256.bmp");
        if (picture_surface == NULL) {
            background = false;
            DEBUGF("warn: %s\n", SDL_GetError());
        }
    }
    
    /* Set things up */
    if (background)
    {
        width = UI_WIDTH;
        height = UI_HEIGHT;
    } 
    else 
    {
#ifdef HAVE_REMOTE_LCD
        if (showremote)
        {
            width = SIM_LCD_WIDTH > SIM_REMOTE_WIDTH ? SIM_LCD_WIDTH : SIM_REMOTE_WIDTH;
            height = SIM_LCD_HEIGHT + SIM_REMOTE_HEIGHT;
        }
        else
#endif
        {
            width = SIM_LCD_WIDTH;
            height = SIM_LCD_HEIGHT;
        }
    }
   
    
    if ((gui_surface = SDL_SetVideoMode(width * display_zoom, height * display_zoom, 24, SDL_HWSURFACE|SDL_DOUBLEBUF)) == NULL) {
        panicf("%s", SDL_GetError());
    }

    SDL_WM_SetCaption(UI_TITLE, NULL);

    if (background && picture_surface != NULL)
        SDL_BlitSurface(picture_surface, NULL, gui_surface, NULL);

    /* let system_init proceed */
    SDL_SemPost((SDL_sem *)param);

    /*
     * finally enter the button loop */
    while(gui_message_loop());

    /* Order here is relevent to prevent deadlocks and use of destroyed
       sync primitives by kernel threads */
    sim_thread_shutdown();
    sim_kernel_shutdown();

    return 0;
}
Exemple #21
0
int main(int argc, char* argv[])
{
	ballfield_t	*balls;
	SDL_Surface	*screen;
	SDL_Surface	*temp_image;
	SDL_Surface	*back, *logo, *font, *font_hex;
	SDL_Event	event;
	int		bpp = 32,
			flags = 0,
			alpha = 1;
	int		x_offs = 0, y_offs = 0;
	long		tick,
			last_tick,
			last_avg_tick;
	double		t = 0;
	float		dt;
	int		i;
	float		fps = 0.0;
	int		fps_count = 0;
	int		fps_start = 0;
	float		x_speed, y_speed, z_speed;

	SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO | SDL_INIT_JOYSTICK);

	atexit(SDL_Quit);

	screen = SDL_SetVideoMode(SCREEN_W, SCREEN_H, bpp, flags);
	if(!screen)
	{
		fprintf(stderr, "Failed to open screen!\n");
		exit(-1);
	}

	SDL_WM_SetCaption("Ballfield", "Ballfield");
	if(flags & SDL_FULLSCREEN)
		SDL_ShowCursor(0);

	balls = ballfield_init();
	if(!balls)
	{
		fprintf(stderr, "Failed to create ballfield!\n");
		exit(-1);
	}

	/*
	 * Load and prepare balls...
	 */
	balls->use_alpha = alpha;
	if( ballfield_load_gfx(balls, "blueball.png", 0)
				||
			ballfield_load_gfx(balls, "redball.png", 1) )
	{
		fprintf(stderr, "Could not load balls!\n");
		exit(-1);
	}

	/*
	 * Load background image
	 */
	temp_image = IMG_Load("sun.gif");
	if(!temp_image)
	{
		fprintf(stderr, "Could not load background!\n");
		exit(-1);
	}
	back = SDL_DisplayFormat(temp_image);
	SDL_FreeSurface(temp_image);

	/*
	 * Load logo
	 */
	temp_image = SDL_LoadBMP("logo.bmp");
	if(!temp_image)
	{
		fprintf(stderr, "Could not load logo!\n");
		exit(-1);
	}
	SDL_SetColorKey(temp_image, SDL_SRCCOLORKEY,
			SDL_MapRGB(temp_image->format, 255, 0, 255));
	logo = SDL_DisplayFormat(temp_image);
	SDL_FreeSurface(temp_image);

	/*
	 * Load font
	 */
	temp_image = SDL_LoadBMP("font7x10.bmp");
	if(!temp_image)
	{
		fprintf(stderr, "Could not load font!\n");
		exit(-1);
	}
	SDL_SetColorKey(temp_image, SDL_SRCCOLORKEY,
			SDL_MapRGB(temp_image->format, 255, 0, 255));
	font = SDL_DisplayFormat(temp_image);
	SDL_FreeSurface(temp_image);

	temp_image = SDL_LoadBMP("font7x10-hex.bmp");
	if(!temp_image)
	{
		fprintf(stderr, "Could not load hex font!\n");
		exit(-1);
	}
	SDL_SetColorKey(temp_image, SDL_SRCCOLORKEY,
			SDL_MapRGB(temp_image->format, 255, 0, 255));
	font_hex = SDL_DisplayFormat(temp_image);
	SDL_FreeSurface(temp_image);

	last_avg_tick = last_tick = SDL_GetTicks();
	
	enum { MAX_POINTERS = 16, PTR_PRESSED = 4 };
	int touchPointers[MAX_POINTERS][5];
	
	memset(touchPointers, 0, sizeof(touchPointers));
	SDL_Joystick * joysticks[MAX_POINTERS+1];
	for(i=0; i<MAX_POINTERS; i++)
		joysticks[i] = SDL_JoystickOpen(i);

	while(1)
	{
		SDL_Rect r;

		/* Timing */
		tick = SDL_GetTicks();
		dt = (tick - last_tick) * 0.001f;
		last_tick = tick;
		
		if( bpp == 32 )
			SDL_FillRect(screen, NULL, 0); // Clear alpha channel

		/* Background image */
		tiled_back(back, screen, x_offs>>11, y_offs>>11);

		/* Ballfield */
		ballfield_render(balls, screen);

		/* Logo */
		r.x = 2;
		r.y = 2;
		SDL_BlitSurface(logo, NULL, screen, &r);

		/* FPS counter */
		if(tick > fps_start + 500)
		{
			fps = (float)fps_count * 1000.0 / (tick - fps_start);
			fps_count = 0;
			fps_start = tick;
		}
		++fps_count;

		for(i=0; i<MAX_POINTERS; i++)
		{
			if( !touchPointers[i][PTR_PRESSED] )
				continue;
			r.x = touchPointers[i][0];
			r.y = touchPointers[i][1];
			r.w = 80 + touchPointers[i][2] / 10; // Pressure
			r.h = 80 + touchPointers[i][3] / 10; // Touch point size
			r.x -= r.w/2;
			r.y -= r.h/2;
			SDL_FillRect(screen, &r, 0xaaaaaa);
			print_num(screen, font, r.x, r.y, i+1);
		}
		int mx, my;
		int b = SDL_GetMouseState(&mx, &my);
		Uint32 color = 0xff;
		if( b )
		{
			color = 0;
			if( b & SDL_BUTTON_LEFT )
				color |= 0xff00;
			if( b & SDL_BUTTON_RIGHT )
				color |= 0xff0000;
		}
		r.x = mx;
		r.y = my;
		r.w = 30;
		r.h = 30;
		r.x -= r.w/2;
		r.y -= r.h/2;
		SDL_FillRect(screen, &r, color);

		SDL_Flip(SDL_GetVideoSurface());
		SDL_Event evt;
		while( SDL_PollEvent(&evt) )
		{
			if(evt.type == SDL_KEYUP || evt.type == SDL_KEYDOWN)
			{
				if(evt.key.keysym.sym == SDLK_ESCAPE)
					return 0;
				__android_log_print(ANDROID_LOG_INFO, "Ballfield", "SDL key event: evt %s state %s key %d scancode %d mod %d unicode %d", evt.type == SDL_KEYUP ? "UP  " : "DOWN" , evt.key.state == SDL_PRESSED ? "PRESSED " : "RELEASED", (int)evt.key.keysym.sym, (int)evt.key.keysym.scancode, (int)evt.key.keysym.mod, (int)evt.key.keysym.unicode);
			}
			if(evt.type == SDL_VIDEORESIZE)
				__android_log_print(ANDROID_LOG_INFO, "Ballfield", "SDL resize event: %d x %d", evt.resize.w, evt.resize.h);
			if(evt.type == SDL_ACTIVEEVENT)
				__android_log_print(ANDROID_LOG_INFO, "Ballfield", "======= SDL active event: gain %d state %d", evt.active.gain, evt.active.state);
			/*
			if( evt.type == SDL_ACTIVEEVENT && evt.active.gain == 0 && evt.active.state & SDL_APPACTIVE )
			{
				// We've lost GL context, we are not allowed to do any GFX output here, or app will crash!
				while( 1 )
				{
					SDL_PollEvent(&evt);
					if( evt.type == SDL_ACTIVEEVENT && evt.active.gain && evt.active.state & SDL_APPACTIVE )
					{
						__android_log_print(ANDROID_LOG_INFO, "Ballfield", "======= SDL active event: gain %d state %d", evt.active.gain, evt.active.state);
						SDL_Flip(SDL_GetVideoSurface()); // One SDL_Flip() call is required here to restore OpenGL context
						// Re-load all textures, matrixes and all other GL states if we're in SDL+OpenGL mode
						// Re-load all images to SDL_Texture if we're using it
						// Now we can draw
						break;
					}
					// Process network stuff, maybe play some sounds using SDL_ANDROID_PauseAudioPlayback() / SDL_ANDROID_ResumeAudioPlayback()
					SDL_Delay(300);
					__android_log_print(ANDROID_LOG_INFO, "Ballfield", "Waiting");
				}
			}
			*/
			if( evt.type == SDL_JOYAXISMOTION )
			{
				if( evt.jaxis.which == 0 ) // 0 = The accelerometer
					continue;
				int joyid = evt.jaxis.which - 1;
				touchPointers[joyid][evt.jaxis.axis] = evt.jaxis.value; // Axis 0 and 1 are coordinates, 2 and 3 are pressure and touch point radius
			}
			if( evt.type == SDL_JOYBUTTONDOWN || evt.type == SDL_JOYBUTTONUP )
			{
				if( evt.jbutton.which == 0 ) // 0 = The accelerometer
					continue;
				int joyid = evt.jbutton.which - 1;
				touchPointers[joyid][PTR_PRESSED] = (evt.jbutton.state == SDL_PRESSED);
			}
		}

		/* Animate */
		x_speed = 500.0 * sin(t * 0.37);
		y_speed = 500.0 * sin(t * 0.53);
		z_speed = 400.0 * sin(t * 0.21);

		ballfield_move(balls, x_speed, y_speed, z_speed);
		x_offs -= x_speed;
		y_offs -= y_speed;

		t += dt;
	}

	ballfield_free(balls);
	SDL_FreeSurface(back);
	SDL_FreeSurface(logo);
	SDL_FreeSurface(font);
	std::ostringstream os;
	os << "lalala" << std::endl << "more text" << std::endl;
	std::cout << os.str() << std::endl << "text text" << std::endl;
	exit(0);
}
void Draw (SDL_Surface *screen, int start, int end)
{
	SDL_Surface *picture, *picture_again;
	char *bmpfile;

	/* Define masking bytes */
#if SDL_BYTEORDER == SDL_BIG_ENDIAN
	Uint32 rmask = 0xff000000; 
	Uint32 gmask = 0x00ff0000;
	Uint32 bmask = 0x0000ff00; 
	Uint32 amask = 0x000000ff;
#else
	Uint32 amask = 0xff000000; 
	Uint32 bmask = 0x00ff0000;
	Uint32 gmask = 0x0000ff00; 
	Uint32 rmask = 0x000000ff;
#endif

	/* --------- 8 bit tests -------- */

	if (start<=6) {

		/* Message */
		printf("8 bit tests ...\n");

		/* Load the image into a surface */
		bmpfile = "sample8.bmp";
		printf("Loading picture: %s\n", bmpfile);
		picture = SDL_LoadBMP(bmpfile);
		if ( picture == NULL ) {
			fprintf(stderr, "Couldn't load %s: %s\n", bmpfile, SDL_GetError());
			return;
		}
		
		/* Add white frame */
		rectangleColor(picture, 0, 0, picture->w-1, picture->h-1, 0xffffffff);

                if (start <= 1) {
			sprintf(messageText, "1.  rotozoom: Rotating and zooming");
			RotatePicture(screen,picture,ROTATE_ON,FLIP_OFF,SMOOTHING_OFF,POSITION_CENTER);
		}
		if (end == 1) goto done8bit;

                if (start <= 2) {
			sprintf(messageText, "2.  rotozoom: Just zooming (angle=0)");
			RotatePicture(screen,picture,ROTATE_OFF,FLIP_OFF,SMOOTHING_OFF,POSITION_CENTER);
			RotatePicture(screen,picture,ROTATE_OFF,FLIP_OFF,SMOOTHING_OFF,POSITION_BOTTOMRIGHT);
		}
		if (end == 2) goto done8bit;

                if (start <= 3) {
			sprintf(messageText, "3.  zoom: Just zooming");
			ZoomPicture(screen,picture,SMOOTHING_OFF);
		}
		if (end == 3) goto done8bit;

                if (start <= 4) {
			sprintf(messageText, "4.  rotozoom: Rotating and zooming, interpolation on but unused");
			RotatePicture(screen,picture,ROTATE_ON,FLIP_OFF,SMOOTHING_ON,POSITION_CENTER);
		}
		if (end == 4) goto done8bit;

                if (start <= 5) {
			sprintf(messageText, "5.  rotozoom: Just zooming (angle=0), interpolation on but unused");
			RotatePicture(screen,picture,ROTATE_OFF,FLIP_OFF,SMOOTHING_ON,POSITION_CENTER);
			RotatePicture(screen,picture,ROTATE_OFF,FLIP_OFF,SMOOTHING_ON,POSITION_BOTTOMRIGHT);
		}
		if (end == 5) goto done8bit;

                if (start <= 6) {
			sprintf(messageText, "6.  zoom: Just zooming, interpolation on but unused");
			ZoomPicture(screen,picture,SMOOTHING_ON);
		}
		if (end == 6) goto done8bit;

		done8bit:
		
		/* Free the picture */
		SDL_FreeSurface(picture);
		
		if (end <= 6) return;
	}

	/* -------- 24 bit test --------- */

	if (start<=12) {

		/* Message */
		printf("24 bit tests ...\n");

		/* Load the image into a surface */
		bmpfile = "sample24.bmp";
		printf("Loading picture: %s\n", bmpfile);
		picture = SDL_LoadBMP(bmpfile);
		if ( picture == NULL ) {
			fprintf(stderr, "Couldn't load %s: %s\n", bmpfile, SDL_GetError());
			return;
		}
		
		/* Add white frame */
		rectangleColor(picture, 0, 0, picture->w-1, picture->h-1, 0xffffffff);

                if (start <= 7) {
			sprintf(messageText, "7.  rotozoom: Rotating and zooming, no interpolation");
		  	RotatePicture(screen,picture,ROTATE_ON,FLIP_OFF,SMOOTHING_OFF,POSITION_CENTER);
		}
		if (end == 7) goto done24bit;

                if (start <= 8) {
			sprintf(messageText, "8a.  rotozoom: Just zooming (angle=0), no interpolation, centered");
			RotatePicture(screen,picture,ROTATE_OFF,FLIP_OFF,SMOOTHING_OFF,POSITION_CENTER);
			sprintf(messageText, "8b.  rotozoom: Just zooming (angle=0), no interpolation, corner");
			RotatePicture(screen,picture,ROTATE_OFF,FLIP_OFF,SMOOTHING_OFF,POSITION_BOTTOMRIGHT);
			sprintf(messageText, "8c.  rotozoom: Just zooming (angle=0), X flip, no interpolation, centered");
			RotatePicture(screen,picture,ROTATE_OFF,FLIP_X,SMOOTHING_OFF,POSITION_CENTER);
			sprintf(messageText, "8d.  rotozoom: Just zooming (angle=0), Y flip, no interpolation, centered");
			RotatePicture(screen,picture,ROTATE_OFF,FLIP_Y,SMOOTHING_OFF,POSITION_CENTER);
			sprintf(messageText, "8e.  rotozoom: Just zooming (angle=0), XY flip, no interpolation, centered");
			RotatePicture(screen,picture,ROTATE_OFF,FLIP_XY,SMOOTHING_OFF,POSITION_CENTER);
		}
		if (end == 8) goto done24bit;

                if (start <= 9) {
  			sprintf(messageText, "9.  zoom: Just zooming, no interpolation");
  			ZoomPicture(screen,picture,SMOOTHING_OFF);
		}
		if (end == 9) goto done24bit;

                if (start <= 10) {
			sprintf(messageText, "10. rotozoom: Rotating and zooming, with interpolation");
			RotatePicture(screen,picture,ROTATE_ON,FLIP_OFF,SMOOTHING_ON,POSITION_CENTER);
		}
		if (end == 10) goto done24bit;

                if (start <= 11) {
			sprintf(messageText, "11a. rotozoom: Just zooming (angle=0), with interpolation, centered");
			RotatePicture(screen,picture,ROTATE_OFF,FLIP_OFF,SMOOTHING_ON,POSITION_CENTER);
			sprintf(messageText, "11b. rotozoom: Just zooming (angle=0), with interpolation, corner");
			RotatePicture(screen,picture,ROTATE_OFF,FLIP_OFF,SMOOTHING_ON,POSITION_BOTTOMRIGHT);
			sprintf(messageText, "11c. rotozoom: Just zooming (angle=0), X flip, with interpolation, corner");
			RotatePicture(screen,picture,ROTATE_OFF,FLIP_X,SMOOTHING_ON,POSITION_CENTER);
			sprintf(messageText, "11d. rotozoom: Just zooming (angle=0), Y flip, with interpolation, corner");
			RotatePicture(screen,picture,ROTATE_OFF,FLIP_Y,SMOOTHING_ON,POSITION_CENTER);
			sprintf(messageText, "11e. rotozoom: Just zooming (angle=0), XY flip, with interpolation, corner");
			RotatePicture(screen,picture,ROTATE_OFF,FLIP_XY,SMOOTHING_ON,POSITION_CENTER);
		}
		if (end == 11) goto done24bit;

                if (start <= 12) {
			sprintf(messageText, "12. zoom: Just zooming, with interpolation");
			ZoomPicture(screen,picture,SMOOTHING_ON);
		}
		if (end == 12) goto done24bit;
		
		done24bit:

		/* Free the picture */
		SDL_FreeSurface(picture);
		
		if (end <= 12) return;
	}

	/* -------- 32 bit test --------- */

	if (start<=16) {

		/* Message */
		printf("32 bit tests ...\n");

		/* Load the image into a surface */
		bmpfile = "sample24.bmp";
		printf("Loading picture: %s\n", bmpfile);
		picture = SDL_LoadBMP(bmpfile);
		if ( picture == NULL ) {
			fprintf(stderr, "Couldn't load %s: %s\n", bmpfile, SDL_GetError());
			return;
		}

		/* Add white frame */
		rectangleColor(picture, 0, 0, picture->w-1, picture->h-1, 0xffffffff);

		/* New source surface is 32bit with defined RGBA ordering */
		/* Much faster to do this once rather than the routine on the fly */
		fprintf(stderr,"Converting 24bit image into 32bit RGBA surface ...\n");
		picture_again = SDL_CreateRGBSurface(SDL_SWSURFACE, picture->w, picture->h, 32, rmask, gmask, bmask, amask);
		if (picture_again == NULL) goto done32bit;		
		SDL_BlitSurface(picture,NULL,picture_again,NULL);

                if (start <= 13) {
			sprintf(messageText, "13. Rotating and zooming, with interpolation (RGBA source)");
			RotatePicture(screen,picture_again,ROTATE_ON,FLIP_OFF,SMOOTHING_ON,POSITION_CENTER);
		}
		if (end == 13) goto done32bit;

                if (start <= 14) {
			sprintf(messageText, "14. Just zooming (angle=0), with interpolation (RGBA source)");
			RotatePicture(screen,picture_again,ROTATE_OFF,FLIP_OFF,SMOOTHING_ON,POSITION_CENTER);
			RotatePicture(screen,picture_again,ROTATE_OFF,FLIP_OFF,SMOOTHING_ON,POSITION_BOTTOMRIGHT);
		}
		if (end == 14) goto done32bit;

		SDL_FreeSurface(picture_again);
		picture_again=NULL;

		/* New source surface is 32bit with defined ABGR ordering */
		/* Much faster to do this once rather than the routine on the fly */
		fprintf(stderr,"Converting 24bit image into 32bit ABGR surface ...\n");
		picture_again = SDL_CreateRGBSurface(SDL_SWSURFACE, picture->w, picture->h, 32, amask, bmask, gmask, rmask);
		if (picture_again == NULL) goto done32bit;		
		SDL_BlitSurface(picture,NULL,picture_again,NULL);

                if (start <= 14) {
			sprintf(messageText, "15. Rotating and zooming, with interpolation (ABGR source)");
			RotatePicture(screen,picture_again,ROTATE_ON,FLIP_OFF,SMOOTHING_ON,POSITION_CENTER);
		}
		if (end == 14) goto done32bit;

                if (start <= 14) {
			sprintf(messageText, "16. Just zooming (angle=0), with interpolation (ABGR source)");
			RotatePicture(screen,picture_again,ROTATE_OFF,FLIP_OFF,SMOOTHING_ON,POSITION_CENTER);
			RotatePicture(screen,picture_again,ROTATE_OFF,FLIP_OFF,SMOOTHING_ON,POSITION_BOTTOMRIGHT);
		}
		if (end == 14) goto done32bit;


		done32bit:
		
		/* Free the picture */
		SDL_FreeSurface(picture);
		if (picture_again) SDL_FreeSurface(picture_again);
		
		if (end <= 16) return;
	}

	/* -------- 32 bit flip test --------- */

	if (start<=22) {

		/* Message */
		printf("32 bit flip tests ...\n");

		/* Load the image into a surface */
		bmpfile = "sample24.bmp";
		printf("Loading picture: %s\n", bmpfile);
		picture = SDL_LoadBMP(bmpfile);
		if ( picture == NULL ) {
			fprintf(stderr, "Couldn't load %s: %s\n", bmpfile, SDL_GetError());
			return;
		}

		/* Add white frame */
		rectangleColor(picture, 0, 0, picture->w-1, picture->h-1, 0xffffffff);

		/* Excercise flipping functions on 32bit RGBA */
		printf("Converting 24bit image into 32bit RGBA surface ...\n");
		picture_again = SDL_CreateRGBSurface(SDL_SWSURFACE, picture->w, picture->h, 32, rmask, gmask, bmask, amask);
		if (picture_again == NULL) goto doneflip;
		SDL_BlitSurface(picture,NULL,picture_again,NULL);
			
                if (start <= 17) {
			sprintf(messageText, "17. Rotating with x-flip, no interpolation (RGBA source)");
			RotatePicture(screen,picture_again,ROTATE_ON,FLIP_X,SMOOTHING_OFF,POSITION_CENTER);
		}
		if (end == 17) goto doneflip;

                if (start <= 18) {
			sprintf(messageText, "18. Rotating with y-flip, no interpolation");
			RotatePicture(screen,picture_again,ROTATE_ON,FLIP_Y,SMOOTHING_OFF,POSITION_CENTER);
		}
		if (end == 18) goto doneflip;

                if (start <= 19) {
			sprintf(messageText, "19. Rotating with xy-flip, no interpolation");
			RotatePicture(screen,picture_again,ROTATE_ON,FLIP_XY,SMOOTHING_OFF,POSITION_CENTER);
		}
		if (end == 19) goto doneflip;

                if (start <= 20) {
			sprintf(messageText, "20. Rotating with x-flip, with interpolation");
			RotatePicture(screen,picture_again,ROTATE_ON,FLIP_X,SMOOTHING_ON,POSITION_CENTER);
		}
		if (end == 20) goto doneflip;

                if (start <= 21) {
			sprintf(messageText, "21. Rotating with y-flip, with interpolation");
			RotatePicture(screen,picture_again,ROTATE_ON,FLIP_Y,SMOOTHING_ON,POSITION_CENTER);
		}
		if (end == 21) goto doneflip;

                if (start <= 22) {
			sprintf(messageText, "22. Rotating with xy-flip, with interpolation");
			RotatePicture(screen,picture_again,ROTATE_ON,FLIP_XY,SMOOTHING_ON,POSITION_CENTER);
		}
		if (end == 22) goto doneflip;

		doneflip:
		
		/* Free the pictures */
		SDL_FreeSurface(picture);
		if (picture_again) SDL_FreeSurface(picture_again);
		
		if (end <= 22) return;
	}

	if (start<=24) {

		/* Message */
		printf("Loading 24bit image\n");

		/* Load the image into a surface */
		bmpfile = "sample24.bmp";
		printf("Loading picture: %s\n", bmpfile);
		picture = SDL_LoadBMP(bmpfile);
		if ( picture == NULL ) {
			fprintf(stderr, "Couldn't load %s: %s\n", bmpfile, SDL_GetError());
			return;
		}

		/* Add white frame */
		rectangleColor(picture, 0, 0, picture->w-1, picture->h-1, 0xffffffff);

		/* Excercise flipping functions on 32bit RGBA */
		fprintf(stderr,"Converting 24bit image into 32bit RGBA surface ...\n");
		picture_again = SDL_CreateRGBSurface(SDL_SWSURFACE, picture->w, picture->h, 32, rmask, gmask, bmask, amask);
		SDL_BlitSurface(picture,NULL,picture_again,NULL);

		sprintf(messageText, "23. CustomTest, values from commandline (32bit)");
		CustomTest(screen, picture_again, custom_angle, custom_fx, custom_fy, custom_smooth);

		SDL_FreeSurface(picture_again);

		/* Free the picture */
		SDL_FreeSurface(picture);

		/* Message */
		printf("Loading 8bit image\n");

		/* Load the image into a surface */
		bmpfile = "sample8.bmp";
		printf("Loading picture: %s\n", bmpfile);
		picture = SDL_LoadBMP(bmpfile);
		if ( picture == NULL ) {
			fprintf(stderr, "Couldn't load %s: %s\n", bmpfile, SDL_GetError());
			return;
		}

		sprintf(messageText, "24. CustomTest, values from commandline (8bit)");
		CustomTest(screen, picture, custom_angle, custom_fx, custom_fy, custom_smooth);

		/* Free the picture */
		SDL_FreeSurface(picture);
		
		if (end <= 24) return;
	}

	if (start<=25) {

		/* Message */
		printf("Loading 24bit image\n");

		/* Load the image into a surface */
		bmpfile = "sample24.bmp";
		printf("Loading picture: %s\n", bmpfile);
		picture = SDL_LoadBMP(bmpfile);
		if ( picture == NULL ) {
			fprintf(stderr, "Couldn't load %s: %s\n", bmpfile, SDL_GetError());
			return;
		}

		/* Add white frame */
		rectangleColor(picture, 0, 0, picture->w-1, picture->h-1, 0xffffffff);

		/* New source surface is 32bit with defined RGBA ordering */
		printf("Converting 24bit image into 32bit RGBA surface ...\n");
		picture_again = SDL_CreateRGBSurface(SDL_SWSURFACE, picture->w, picture->h, 32, rmask, gmask, bmask, amask);
		if (picture_again == NULL) goto donerotate90;
		SDL_BlitSurface(picture,NULL,picture_again,NULL);

		/* Excercise rotate90 function on 32bit RGBA */
		sprintf(messageText, "25.  rotate90: Rotate 90 degrees clockwise (32bit)");
		RotatePicture90Degrees(screen, picture_again);

		donerotate90:
		
		/* Free the pictures */
		SDL_FreeSurface(picture);
		if (picture_again) SDL_FreeSurface(picture_again);

		if (end <= 25) return;
	}

	if (start<=26) {
		/* Run accuracy test */
		sprintf(messageText, "26.  accuracy: zoom by factor of 2");
		AccuracyTest1(screen);

		if (end <= 26) return;
	}

	if (start <= 27) {
		/* Load the image into a surface */
		bmpfile = "sample2x2.bmp";
		printf("Loading picture: %s\n", bmpfile);
		picture = SDL_LoadBMP(bmpfile);
		if ( picture == NULL ) {
			fprintf(stderr, "Couldn't load %s: %s\n", bmpfile, SDL_GetError());
			return;
		}

		sprintf(messageText, "27a.  zoom accuracy: zoom 2x2 bitmap");		
		AccuracyTest2(screen, picture);

		/* Free the pictures */
		SDL_FreeSurface(picture);

		/* Load the image into a surface */
		bmpfile = "sample3x3.bmp";
		printf("Loading picture: %s\n", bmpfile);
		picture = SDL_LoadBMP(bmpfile);
		if ( picture == NULL ) {
			fprintf(stderr, "Couldn't load %s: %s\n", bmpfile, SDL_GetError());
			return;
		}		
		
		sprintf(messageText, "27b.  zoom accuracy: zoom 3x3 bitmap");		
		AccuracyTest2(screen, picture);

		/* Free the pictures */
		SDL_FreeSurface(picture);

		/* Load the image into a surface */
		bmpfile = "sample16x16.bmp";
		printf("Loading picture: %s\n", bmpfile);
		picture = SDL_LoadBMP(bmpfile);
		if ( picture == NULL ) {
			fprintf(stderr, "Couldn't load %s: %s\n", bmpfile, SDL_GetError());
			return;
		}		
		
		sprintf(messageText, "27c.  zoom accuracy: zoom 16x16 bitmap");		
		AccuracyTest2(screen, picture);

		/* Free the pictures */
		SDL_FreeSurface(picture);
	
		if (end <= 27) return;
	}
	
	return;
}
int main()
{   
	SDL_Surface *screen;
	SDL_Surface *tmp;
	SDL_Surface *bitmap;
	SDL_Surface *bitmap2; /* 8-Bit */

	SDL_Rect src, src2, dest, dest2;

	if(SDL_Init(SDL_INIT_VIDEO)){
		printf("Error with SDL init\n");
	}
	
	
	screen = SDL_SetVideoMode(640, 480, 16, SDL_DOUBLEBUF);

	if(!screen)
		printf("Error with screen\n");
	

	tmp = SDL_LoadBMP("data/FLAG_B24.BMP");
	if(!tmp)
		printf("Error loading file\n");

	bitmap = SDL_DisplayFormat(tmp);
	bitmap2 = SDL_DisplayFormat(tmp);

	SDL_FreeSurface(tmp);

	src.x = 0;
	src.y = 0;
	src.w = bitmap->w;
	src.h = bitmap->h;

	dest.x = 50;
	dest.y = 50;
	dest.w = bitmap->w;
	dest.h = bitmap->h;

	src2.x = 0;
	src2.y = 0;
	src2.w = bitmap2->w;
	src2.h = bitmap2->h;

	dest2.x = 200;
	dest2.y = 200;
	dest2.w = bitmap2->w;
	dest2.h = bitmap2->h;

	Uint16 *pixels = (Uint16*)bitmap->pixels;
	int i;
	//printf("val: %x - r:%x - g:%x - b:%x - avg:%d\n", pixels[0],
	//R(pixels[0]), G(pixels[0]), B(pixels[0]), 
	//AVG(B(pixels[0]),G(pixels[0]),R(pixels[0])));
	
	for(i = 0; i < bitmap->w*bitmap->h; i++){
        
		pixels[i]  = AVG(B(pixels[i]),G(pixels[i]),R(pixels[i]));
		
	}

	// R    G     B
	//00000 000000 00000
	
	bitmap->pixels = (Uint16*)pixels;

	SDL_BlitSurface(bitmap, &src, screen, &dest);
	SDL_BlitSurface(bitmap2, &src2, screen, &dest2);

	printf("Bytes per pixel: %d", bitmap->format->BitsPerPixel); 

	SDL_Flip(screen);
	SDL_Delay(2500);
	
	atexit(SDL_Quit);
    return 0;
}
Exemple #24
0
Fichier : main.c Projet : Zix777/C
int main(int argc, char** argv)
{
    SDL_Init(SDL_INIT_VIDEO);
    SDL_Window* window = SDL_CreateWindow("SDL Practice4",
                                          SDL_WINDOWPOS_UNDEFINED,SDL_WINDOWPOS_UNDEFINED,
                                          800,700,
                                          SDL_WINDOW_SHOWN);
    SDL_Surface* surface = SDL_GetWindowSurface(window);
    SDL_Surface* image = SDL_LoadBMP("x.bmp");

    SDL_Event event;
    SDL_Rect pos;
    pos.x=0;
    pos.y=0;

    SDL_Rect image_pos;
    image_pos.x = 0;
    image_pos.y = 0;
    image_pos.w = image->w;
    image_pos.h = image->h;
    bool quit=false;
    bool pressed = false;
    SDL_BlitSurface(image, NULL, surface, &pos);
    SDL_UpdateWindowSurface(window);
    while(!quit)
    {
        while(SDL_PollEvent(&event))
        {
            if(event.type == SDL_QUIT)
                quit = true;
            if(event.type == SDL_MOUSEBUTTONDOWN)
            {
                if(event.button.button == SDL_BUTTON_LEFT)
                {
                    image_pos.x = event.motion.x - pos.x;
                    image_pos.y = event.motion.y - pos.y;
                    if(image_pos.x>=0 && image_pos.x<=image_pos.w && image_pos.y>0 && image_pos.y<image_pos.h)
                        pressed = true;
                }
            }
            if(pressed && event.type == SDL_MOUSEMOTION)
            {
                pos.x = event.motion.x - image_pos.x;
                pos.y = event.motion.y - image_pos.y;
                SDL_FillRect(surface, NULL, 0);
                SDL_BlitSurface(image, NULL, surface, &pos);
                SDL_UpdateWindowSurface(window);
            }
            if(event.type == SDL_MOUSEBUTTONUP)
            {
                if(pressed && event.button.button == SDL_BUTTON_LEFT)
                {
                    pressed = false;
                }
            }
        }
    }
    SDL_DestroyWindow(window);
    SDL_Quit();
    return 0;
}
Exemple #25
0
/* This code is deprecated, but available for speed comparisons */
void DrawLogoBlit(void)
{
	static int x = 0;
	static int y = 0;
	static int w, h;
	static int delta_x = 1;
	static int delta_y = 1;

	SDL_Rect dst;
	SDL_Surface *screen = SDL_GetVideoSurface();

	if ( global_image == NULL ) {
		SDL_Surface *temp;

		/* Load the image (could use SDL_image library here) */
		temp = SDL_LoadBMP(LOGO_FILE);
		if ( temp == NULL ) {
			return;
		}
		w = temp->w;
		h = temp->h;

		/* Convert the image into the screen format */
		global_image = SDL_CreateRGBSurface(
				SDL_SWSURFACE,
				w, h,
				screen->format->BitsPerPixel,
				screen->format->Rmask,
				screen->format->Gmask,
				screen->format->Bmask,
				screen->format->Amask);
		if ( global_image ) {
			SDL_BlitSurface(temp, NULL, global_image, NULL);
		}
		SDL_FreeSurface(temp);

		/* Make sure that the texture conversion is okay */
		if ( ! global_image ) {
			return;
		}
	}

	/* Move the image around
           Note that we do not clear the old position.  This is because we
           perform a glClear() which clears the framebuffer and then only
           update the new area.
           Note that you can also achieve interesting effects by modifying
           the screen surface alpha channel.  It's set to 255 by default..
         */
	x += delta_x;
	if ( x < 0 ) {
		x = 0;
		delta_x = -delta_x;
	} else
	if ( (x+w) > screen->w ) {
		x = screen->w-w;
		delta_x = -delta_x;
	}
	y += delta_y;
	if ( y < 0 ) {
		y = 0;
		delta_y = -delta_y;
	} else
	if ( (y+h) > screen->h ) {
		y = screen->h-h;
		delta_y = -delta_y;
	}
	dst.x = x;
	dst.y = y;
	dst.w = w;
	dst.h = h;
	SDL_BlitSurface(global_image, NULL, screen, &dst);

	/* Show the image on the screen */
	SDL_UpdateRects(screen, 1, &dst);
}
Exemple #26
0
/* Setup SDL */
void InitGFX(){
	static int flags=0;

	/* Define the program icon */
#ifdef _WIN32
	program_icon = SDL_LoadBMP("irixbasic-icon-32px.bmp");
#else
	program_icon = SDL_LoadBMP("irixbasic-icon-128px.bmp");
#endif
	
	char *msg;
	
	/* Initialize SDL */
	if (SDL_Init (SDL_INIT_VIDEO) < 0)
	{
		sprintf (msg, "Couldn't initialize SDL: %s\n", SDL_GetError ());
		/*MessageBox (0, msg, "Error", program_icon);*/
		free (msg);
		exit (1);
	}
	atexit (SDL_Quit);
	
	/* Set video mode */
	screen = SDL_SetVideoMode (screen_width, screen_height, 16, SDL_HWSURFACE | SDL_DOUBLEBUF);
	
	if (screen == NULL)
	{
		sprintf (msg, "Couldn't set %dx%dx16 video mode: %s\n", screen_width, screen_height, SDL_GetError ());
		printf("%s",msg);
		free (msg);
		exit (2);
	}
	
	flags = screen->flags;
	
	/* Check if the enable fullscreen argument is turned on */
	if(enable_fullscreen){
		screen = SDL_SetVideoMode(0, 0, 0, screen->flags ^ SDL_FULLSCREEN);
		screen_width = screen->w;
		screen_height = screen->h;
		
		if(screen == NULL) 
		{
			screen = SDL_SetVideoMode(0, 0, 0, flags); /* If toggle FullScreen failed, then switch back */
		}
		if(screen == NULL)
		{
			exit(1); /* If you can't switch back for some reason, then fail */
		}
	}
	
	
	
	SDL_WM_SetIcon(program_icon, NULL);
	SDL_WM_SetCaption ("IRIXBASIC", "IRIXBASIC");
	
	/* Create background screen colors*/
	screen_color = SDL_MapRGB(screen->format, 66, 66, 231);
	frame_color = SDL_MapRGB(screen->format, 165, 165, 255);
	debug_color = SDL_MapRGB(screen->format, 126, 126, 126);
	
	
	/* light blue */
	foreground_color.r = 165;
	foreground_color.g = 165;
	foreground_color.b = 255;
	
	/* dark blue */
	background_color.r = 66;
	background_color.g = 66;
	background_color.b = 231;
	
	
	/* Setup a rect for the full screen */
	screen_rect.h = screen->h;
	screen_rect.w = screen->w; 
	
	/* frame border width 36px / height 45px */
	display_area_rect.x = 36;
	display_area_rect.y = 45;
	display_area_rect.w = screen->w-(36*2);
	display_area_rect.h = screen->h-(45*2);
	
	
	/* Set up the SDL_TTF */
	TTF_Init();
	atexit(TTF_Quit);
	/* TTF_Init() is like SDL_Init(), but with no parameters.  Basically, it initializes
	 SDL_TTF.  There's really not much to it.  Remember, when the program ends, we
	 have to call TTF_Quit().  atexit(TTF_Quit) ensures that when we call exit(), the
	 program calls TTF_Quit() for us. */
	
	fntc64 = TTF_OpenFont( "./C64_User_Mono_v1.0-STYLE.ttf", fontsize );
	
	/* Get the size of a character in pixels */
	if(TTF_SizeText(fntc64,"B",&character_with,&character_height)) {
		printf("SDL_TTF error: %s", TTF_GetError());
	} else {
		total_text_rows = (display_area_rect.h/character_height)-1;
		total_text_cols = (display_area_rect.w/character_with)-1;
		printf("Current Screen Size: width=%d height=%d\n", screen_width, screen_height);
		printf("Text Settings: %d=points rows=%d columns=%d \n", fontsize, total_text_rows, total_text_cols);
		printf("\n");
	}
	
	/*Wait a moment for the screen to switch*/
	if(enable_fullscreen)
	{
		SDL_Flip(screen);
		SDL_Delay(1500);
	}
	
	/*-------------------------------
	 * Fill the screen
	 * -------------------------------
	 */
	
	/* Fill the screen with the light blue frame */
	SDL_FillRect(screen, NULL, frame_color);
	
	/*Fill the center of the screen with dark blue */ 			
	SDL_FillRect(screen, &display_area_rect, screen_color);
	
	/* Make sure everything is displayed on screen */
	SDL_Flip(screen);
	
	
	isbutton_down = 0;
	
}
Exemple #27
0
int main(int argc,char** argv)
{
    Uint8 num_pictures;
    LoadedPicture* pictures;
    int i, j;
    SDL_PixelFormat* format = NULL;
    SDL_Window *window;
    SDL_Renderer *renderer;
    SDL_Color black = {0,0,0,0xff};
    SDL_Event event;
    int event_pending = 0;
    int should_exit = 0;
    unsigned int current_picture;
    int button_down;
    Uint32 pixelFormat = 0;
    int access = 0;
    SDL_Rect texture_dimensions;

    /* Enable standard application logging */
    SDL_LogSetPriority(SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_INFO);

    if(argc < 2) {
		SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "SDL_Shape requires at least one bitmap file as argument.");
        exit(-1);
    }

    if(SDL_VideoInit(NULL) == -1) {
        SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Could not initialize SDL video.");
        exit(-2);
    }

    num_pictures = argc - 1;
    pictures = (LoadedPicture *)SDL_malloc(sizeof(LoadedPicture)*num_pictures);
    for(i=0;i<num_pictures;i++)
        pictures[i].surface = NULL;
    for(i=0;i<num_pictures;i++) {
        pictures[i].surface = SDL_LoadBMP(argv[i+1]);
        pictures[i].name = argv[i+1];
        if(pictures[i].surface == NULL) {
            j = 0;
            for(j=0;j<num_pictures;j++)
                SDL_FreeSurface(pictures[j].surface);
            SDL_free(pictures);
            SDL_VideoQuit();
            SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Could not load surface from named bitmap file: %s", argv[i+1]);
            exit(-3);
        }

        format = pictures[i].surface->format;
        if(SDL_ISPIXELFORMAT_ALPHA(format->format)) {
            pictures[i].mode.mode = ShapeModeBinarizeAlpha;
            pictures[i].mode.parameters.binarizationCutoff = 255;
        }
        else {
            pictures[i].mode.mode = ShapeModeColorKey;
            pictures[i].mode.parameters.colorKey = black;
        }
    }

    window = SDL_CreateShapedWindow("SDL_Shape test",
        SHAPED_WINDOW_X, SHAPED_WINDOW_Y,
        SHAPED_WINDOW_DIMENSION,SHAPED_WINDOW_DIMENSION,
        0);
    SDL_SetWindowPosition(window, SHAPED_WINDOW_X, SHAPED_WINDOW_Y);
    if(window == NULL) {
        for(i=0;i<num_pictures;i++)
            SDL_FreeSurface(pictures[i].surface);
        SDL_free(pictures);
        SDL_VideoQuit();
        SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Could not create shaped window for SDL_Shape.");
        exit(-4);
    }
    renderer = SDL_CreateRenderer(window,-1,0);
    if (!renderer) {
        SDL_DestroyWindow(window);
        for(i=0;i<num_pictures;i++)
            SDL_FreeSurface(pictures[i].surface);
        SDL_free(pictures);
        SDL_VideoQuit();
        SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Could not create rendering context for SDL_Shape window.");
        exit(-5);
    }

    for(i=0;i<num_pictures;i++)
        pictures[i].texture = NULL;
    for(i=0;i<num_pictures;i++) {
        pictures[i].texture = SDL_CreateTextureFromSurface(renderer,pictures[i].surface);
        if(pictures[i].texture == NULL) {
            j = 0;
            for(j=0;j<num_pictures;i++)
                if(pictures[i].texture != NULL)
                    SDL_DestroyTexture(pictures[i].texture);
            for(i=0;i<num_pictures;i++)
                SDL_FreeSurface(pictures[i].surface);
            SDL_free(pictures);
            SDL_DestroyRenderer(renderer);
            SDL_DestroyWindow(window);
            SDL_VideoQuit();
            SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Could not create texture for SDL_shape.");
            exit(-6);
        }
    }

    event_pending = 0;
    should_exit = 0;
    event_pending = SDL_PollEvent(&event);
    current_picture = 0;
    button_down = 0;
    texture_dimensions.h = 0;
    texture_dimensions.w = 0;
    texture_dimensions.x = 0;
    texture_dimensions.y = 0;
    SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "Changing to shaped bmp: %s", pictures[current_picture].name);
    SDL_QueryTexture(pictures[current_picture].texture,(Uint32 *)&pixelFormat,(int *)&access,&texture_dimensions.w,&texture_dimensions.h);
    SDL_SetWindowSize(window,texture_dimensions.w,texture_dimensions.h);
    SDL_SetWindowShape(window,pictures[current_picture].surface,&pictures[current_picture].mode);
    while(should_exit == 0) {
        event_pending = SDL_PollEvent(&event);
        if(event_pending == 1) {
            if(event.type == SDL_KEYDOWN) {
                button_down = 1;
                if(event.key.keysym.sym == SDLK_ESCAPE) {
                    should_exit = 1;
                    break;
                }
            }
            if(button_down && event.type == SDL_KEYUP) {
                button_down = 0;
                current_picture += 1;
                if(current_picture >= num_pictures)
                    current_picture = 0;
                SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "Changing to shaped bmp: %s", pictures[current_picture].name);
                SDL_QueryTexture(pictures[current_picture].texture,(Uint32 *)&pixelFormat,(int *)&access,&texture_dimensions.w,&texture_dimensions.h);
                SDL_SetWindowSize(window,texture_dimensions.w,texture_dimensions.h);
                SDL_SetWindowShape(window,pictures[current_picture].surface,&pictures[current_picture].mode);
            }
            if(event.type == SDL_QUIT)
                should_exit = 1;
            event_pending = 0;
        }
        render(renderer,pictures[current_picture].texture,texture_dimensions);
        SDL_Delay(10);
    }

    /* Free the textures. */
    for(i=0;i<num_pictures;i++)
        SDL_DestroyTexture(pictures[i].texture);
    SDL_DestroyRenderer(renderer);
    /* Destroy the window. */
    SDL_DestroyWindow(window);
    /* Free the original surfaces backing the textures. */
    for(i=0;i<num_pictures;i++)
        SDL_FreeSurface(pictures[i].surface);
    SDL_free(pictures);
    /* Call SDL_VideoQuit() before quitting. */
    SDL_VideoQuit();

    return 0;
}
Exemple #28
0
int main(int argc,char** argv)
{
    Uint8 num_pictures;
    LoadedPicture* pictures;
    int i, j;
    SDL_PixelFormat* format = NULL;
    SDL_Window *window;
    SDL_Renderer *renderer;
    SDL_Color black = {0,0,0,0xff};
    SDL_Event event;
    int event_pending = 0;
    int should_exit = 0;
    unsigned int current_picture;
    int button_down;
    Uint32 pixelFormat = 0;
    int access = 0;
    SDL_Rect texture_dimensions;;

    if(argc < 2) {
        printf("SDL_Shape requires at least one bitmap file as argument.\n");
        exit(-1);
    }

    if(SDL_VideoInit(NULL) == -1) {
        printf("Could not initialize SDL video.\n");
        exit(-2);
    }

    num_pictures = argc - 1;
    pictures = (LoadedPicture *)malloc(sizeof(LoadedPicture)*num_pictures);
    for(i=0;i<num_pictures;i++)
        pictures[i].surface = NULL;
    for(i=0;i<num_pictures;i++) {
        pictures[i].surface = SDL_LoadBMP(argv[i+1]);
        if(pictures[i].surface == NULL) {
            j = 0;
            for(j=0;j<num_pictures;j++)
                if(pictures[j].surface != NULL)
                    SDL_FreeSurface(pictures[j].surface);
            free(pictures);
            SDL_VideoQuit();
            printf("Could not load surface from named bitmap file.\n");
            exit(-3);
        }

        format = pictures[i].surface->format;
        if(format->Amask != 0) {
            pictures[i].mode.mode = ShapeModeBinarizeAlpha;
            pictures[i].mode.parameters.binarizationCutoff = 255;
        }
        else {
            pictures[i].mode.mode = ShapeModeColorKey;
            pictures[i].mode.parameters.colorKey = black;
        }
    }

    window = SDL_CreateShapedWindow("SDL_Shape test",SHAPED_WINDOW_X,SHAPED_WINDOW_Y,SHAPED_WINDOW_DIMENSION,SHAPED_WINDOW_DIMENSION,SDL_WINDOW_RESIZABLE | SDL_WINDOW_SHOWN);
    if(window == NULL) {
        for(i=0;i<num_pictures;i++)
            SDL_FreeSurface(pictures[i].surface);
        free(pictures);
        SDL_VideoQuit();
        printf("Could not create shaped window for SDL_Shape.\n");
        exit(-4);
    }
    renderer = SDL_CreateRenderer(window,-1,0);
    if (!renderer) {
        SDL_DestroyWindow(window);
        for(i=0;i<num_pictures;i++)
            SDL_FreeSurface(pictures[i].surface);
        free(pictures);
        SDL_VideoQuit();
        printf("Could not create rendering context for SDL_Shape window.\n");
        exit(-5);
    }

    for(i=0;i<num_pictures;i++)
        pictures[i].texture = NULL;
    for(i=0;i<num_pictures;i++) {
        pictures[i].texture = SDL_CreateTextureFromSurface(renderer,pictures[i].surface);
        if(pictures[i].texture == NULL) {
            j = 0;
            for(j=0;j<num_pictures;i++)
                if(pictures[i].texture != NULL)
                    SDL_DestroyTexture(pictures[i].texture);
            for(i=0;i<num_pictures;i++)
                SDL_FreeSurface(pictures[i].surface);
            free(pictures);
            SDL_DestroyRenderer(renderer);
            SDL_DestroyWindow(window);
            SDL_VideoQuit();
            printf("Could not create texture for SDL_shape.\n");
            exit(-6);
        }
    }

    event_pending = 0;
    should_exit = 0;
    event_pending = SDL_PollEvent(&event);
    current_picture = 0;
    button_down = 0;
    texture_dimensions.h = 0;
    texture_dimensions.w = 0;
    texture_dimensions.x = 0;
    texture_dimensions.y = 0;
    SDL_QueryTexture(pictures[current_picture].texture,(Uint32 *)&pixelFormat,(int *)&access,&texture_dimensions.w,&texture_dimensions.h);
    SDL_SetWindowSize(window,texture_dimensions.w,texture_dimensions.h);
    SDL_SetWindowShape(window,pictures[current_picture].surface,&pictures[current_picture].mode);
    next_time = SDL_GetTicks() + TICK_INTERVAL;
    while(should_exit == 0) {
        event_pending = SDL_PollEvent(&event);
        if(event_pending == 1) {
            if(event.type == SDL_KEYDOWN) {
                button_down = 1;
                if(event.key.keysym.sym == SDLK_ESCAPE)
                    should_exit = 1;
            }
            if(button_down && event.type == SDL_KEYUP) {
                button_down = 0;
                current_picture += 1;
                if(current_picture >= num_pictures)
                    current_picture = 0;
                SDL_QueryTexture(pictures[current_picture].texture,(Uint32 *)&pixelFormat,(int *)&access,&texture_dimensions.w,&texture_dimensions.h);
                SDL_SetWindowSize(window,texture_dimensions.w,texture_dimensions.h);
                SDL_SetWindowShape(window,pictures[current_picture].surface,&pictures[current_picture].mode);
            }
            if(event.type == SDL_QUIT)
                should_exit = 1;
            event_pending = 0;
        }
        render(renderer,pictures[current_picture].texture,texture_dimensions);
        SDL_Delay(time_left());
        next_time += TICK_INTERVAL;
    }

    //Free the textures.
    for(i=0;i<num_pictures;i++)
        SDL_DestroyTexture(pictures[i].texture);
    SDL_DestroyRenderer(renderer);
    //Destroy the window.
    SDL_DestroyWindow(window);
    //Free the original surfaces backing the textures.
    for(i=0;i<num_pictures;i++)
        SDL_FreeSurface(pictures[i].surface);
    free(pictures);
    //Call SDL_VideoQuit() before quitting.
    SDL_VideoQuit();

    return 0;
}
Exemple #29
0
Image &Laser::sprite()
{
  static Image sprite(SDL_LoadBMP("resources/shoot.bmp"), Image::Wrap);

  return sprite;
}
Exemple #30
0
/* ------------------------------------------- */
int main(int argc, char *argv[]){

 Uint8* keys;
 char mes[100];

 if ( SDL_Init(SDL_INIT_AUDIO|SDL_INIT_VIDEO) < 0 ){
   printf("Unable to init SDL: %s\n", SDL_GetError());
   exit(1);
 }

 atexit(SDL_Quit);

if(Mix_OpenAudio(44100, AUDIO_S16SYS, 2, 2048) < 0)
  {
    printf("Warning: Couldn't set 44100 Hz 16-bit audio\n- Reason: %s\n",
							SDL_GetError());
  }
    music = Mix_LoadMUS("(sblu)moon6.xm");



 SDL_WM_SetCaption("arcanoid","arcanoid");
 SDL_WM_SetIcon(SDL_LoadBMP("icon.bmp"), NULL);


 screen = SDL_SetVideoMode(640, 480, 32, SDL_SWSURFACE);
 if ( screen == NULL ){
   printf("Unable to set 640x480 video: %s\n", SDL_GetError());
   exit(1);
 }

 InitImages();
 InitGame();


CreateThread(NULL, 0, GoBall , (LPVOID)0, NULL, NULL);

DrawScene();
 int done=0;
 while(done == 0)
 {

   SDL_Event event;

   while ( SDL_PollEvent(&event) )
   {
     if ( event.type == SDL_QUIT ){ done = 1; }
     if ( event.type == SDL_KEYDOWN )
     {
       if ( event.key.keysym.sym == SDLK_ESCAPE ){ done = 1; }
     }
   }

    if (NewGame)
    {
        bool t= false;
        if ((Win1!=5)&&(Win2!=5))
        {
            InitGame();
            CreateThread(NULL, 0, GoBall , (LPVOID)0, NULL, NULL);
        }

        if (Win1==5)
        {
            strcpy(mes, "The first one wins!\nDo you want to play again?");
            t= true;
        } else
        if (Win2==5)
        {
            strcpy(mes, "The second one wins!\nDo you want to play again?");
            t=true;
        }
        if (t)
        if (MessageBoxA(NULL, mes, "Game Over", MB_YESNO)==IDYES)
        {
            InitGame();
            CreateThread(NULL, 0, GoBall , (LPVOID)0, NULL, NULL);
        } else
            break;

    }


   keys = SDL_GetKeyState(NULL);

   if(keys[SDLK_UP])
   {
       if (ypos-3>=VG)
        ypos -= 3;
   }
   if(keys[SDLK_DOWN])
   {
       if (ypos+3<=480-85)
        ypos += 3;
   }


   if(keys[SDLK_w])
   {
       if (ypos1-3>=VG)
        ypos1 -= 3;
   }

    if(keys[SDLK_s])
    {
        if (ypos1+3<=480-85)
         ypos1 += 3;
    }


    while (redraw)
    {

    }
    DrawScene();
 }
 CloseThread= true;
SDL_Quit();
 return 0;

}