Example #1
0
	surface surface::create_surface(uint32_t flags, int width, int height, int depth,
		uint32_t Rmask, uint32_t Gmask, uint32_t Bmask, uint32_t Amask) {
		return surface().build(SDL_CreateRGBSurface(flags,width,height,depth
			,Rmask,Gmask,Bmask,Amask));
	}
void Draw(SDL_Surface *screen)
{
	int rate,x,y,s;
	SDL_Rect dest,clip;
	SDL_Surface *texture_image;
	SDL_Surface *texture_target1;
	SDL_Surface *texture_target2;
	FPSmanager fpsm;
	Uint32 rmask, gmask, bmask, amask;
	int width_half = screen->w/2;
	int height_half = screen->h/2;
	Uint32 text_color = 0xffffffff;

	/* Define masks for 32bit surface */
#if SDL_BYTEORDER == SDL_BIG_ENDIAN
	rmask = 0xff000000;
	gmask = 0x00ff0000;
	bmask = 0x0000ff00;
	amask = 0x000000ff;
#else 
	rmask = 0x000000ff;
	gmask = 0x0000ff00;
	bmask = 0x00ff0000;
	amask = 0xff000000;                               
#endif

	/* Create semi-transparent textured surface */
	s=64;
	texture_image = SDL_DisplayFormatAlpha(SDL_CreateRGBSurface(SDL_SWSURFACE, s, s, 32, rmask, gmask, bmask, amask));
	/* Add some color */
	boxRGBA(texture_image, 0,  0, s/2, s/2, 255, 0, 0, 255); 
	boxRGBA(texture_image, s/2, 0, s, s/2, 0, 255, 0, 255); 
	boxRGBA(texture_image, 0, s/2, s/2, s, 0, 0, 255, 255); 
	boxRGBA(texture_image, s/2, s/2, s, s, 255, 255, 255, 255);  
	/* Make 75%-transparent */
	SDL_gfxSetAlpha(texture_image, 96);
	/* Set alpha channel use to per-pixel blending */
	SDL_SetAlpha(texture_image, SDL_SRCALPHA, 255);

	/* Create an all transparent surface */
	texture_target1 = SDL_DisplayFormatAlpha(SDL_CreateRGBSurface(SDL_SWSURFACE, 256, 256, 32, rmask, gmask, bmask, amask));
	/* Make 75%-transparent */
	SDL_gfxSetAlpha(texture_target1, 64);
	/* Set alpha channel use to per-pixel blending */
	SDL_SetAlpha(texture_target1, SDL_SRCALPHA, 255);

	/* Create an all transparent surface (2) */
	texture_target2 = SDL_DisplayFormatAlpha(SDL_CreateRGBSurface(SDL_SWSURFACE, 256, 256, 32, rmask, gmask, bmask, amask));
	/* Make 75%-transparent */
	SDL_gfxSetAlpha(texture_target2, 64);
	/* Set alpha channel use to per-pixel blending */
	SDL_SetAlpha(texture_target2, SDL_SRCALPHA, 255);

	/* Define clipping region for left box */
	clip.x = width_half-256-10 ;
	clip.y = height_half-256/2 ;
	clip.w = 256;
	clip.h = 256;

	/* Initialize Framerate manager */  
	SDL_initFramerate(&fpsm);

	/* Set/switch framerate */
	rate=5;
	SDL_setFramerate(&fpsm,rate);

	/* --- Drawing loop */
	while (1) {

		/* Event handler */
		HandleEvent();

		/* Black screen */
		ClearScreen(screen);

		/* Random position of new texture */
		x=(rand() % (256+2*s))-s;
		y=(rand() % (256+2*s))-s;

		/* Same for comparison texture */
		dest.x = x;
		dest.y = y;
		dest.w = texture_image->w;
		dest.h = texture_image->h;
		SDL_BlitSurface(texture_image, NULL, texture_target1, &dest);

		/* Blit image into the target using custom Blit function. */
		dest.x = x;
		dest.y = y;
		dest.w = texture_image->w;
		dest.h = texture_image->h;
		SDL_gfxBlitRGBA(texture_image, NULL, texture_target2, &dest);

		/* Draw comparison target on screen (left) */
		dest.x = width_half-256-10;
		dest.y = height_half-256/2;
		dest.w = 256;
		dest.h = 256;
		SDL_BlitSurface(texture_target1, NULL, screen, &dest);

		/* Draw combiner target on screen (right) */
		dest.x = width_half+10;
		dest.y = height_half-256/2;
		dest.w = 256;
		dest.h = 256;
		SDL_BlitSurface(texture_target2, NULL, screen, &dest);

		/* Draw some frames with titles */
		rectangleColor(screen, width_half-256-10-1, height_half-256/2-1, width_half-256-10-1+257, height_half-256/2-1+257,  text_color);
		rectangleColor(screen, width_half+10-1, height_half-256/2-1, width_half+10-1+257, height_half-256/2-1+257, text_color);
		stringColor(screen, width_half-256-10-1, height_half-256/2-1-36, "     SDL Standard Blitter     ", text_color);
		stringColor(screen, width_half-256-10-1, height_half-256/2-1-24, "Image    --sdlBlit-->  Target1", text_color);
		stringColor(screen, width_half-256-10-1, height_half-256/2-1-12, "Target1  --sdlBlit-->  Screen", text_color);
		stringColor(screen, width_half+10-1, height_half-256/2-1-36, " SDL_gfx Compositing Blitter", text_color);  
		stringColor(screen, width_half+10-1, height_half-256/2-1-24, "Image    --gfxBlit-->  Target2", text_color);  
		stringColor(screen, width_half+10-1, height_half-256/2-1-12, "Target2  --sdlBlit-->  Screen", text_color);  

		stringColor(screen, width_half-256-10-1, height_half-256/2-1-60, "gfxBlitRGBA Demo: Target1/2 A=64 (25%), Image A=96 (37%)", text_color);  

		/* Display by flipping screens */
		SDL_Flip(screen);

		/* Delay to fix rate */                   
		SDL_framerateDelay(&fpsm);  
	}
}
    //------------------------------------------------------------------------
    bool platform_support::init(unsigned width, unsigned height, unsigned flags)
    {
        m_window_flags = flags;
        unsigned wflags = SDL_SWSURFACE;

        if(m_window_flags & window_hw_buffer)
        {
            wflags = SDL_HWSURFACE;
        }

        if(m_window_flags & window_resize)
        {
            wflags |= SDL_RESIZABLE;
        }

        if(m_specific->m_surf_screen) SDL_FreeSurface(m_specific->m_surf_screen);

        m_specific->m_surf_screen = SDL_SetVideoMode(width, height, m_bpp, wflags);
        if(m_specific->m_surf_screen == 0) 
        {
            fprintf(stderr, 
                    "Unable to set %dx%d %d bpp video: %s\n", 
                    width, 
                    height, 
                    m_bpp, 
                    ::SDL_GetError());
            return false;
        }

        SDL_WM_SetCaption(m_caption, 0);

        if(m_specific->m_surf_window) SDL_FreeSurface(m_specific->m_surf_window);

        m_specific->m_surf_window = 
            SDL_CreateRGBSurface(SDL_HWSURFACE, 
                                 m_specific->m_surf_screen->w, 
                                 m_specific->m_surf_screen->h,
                                 m_specific->m_surf_screen->format->BitsPerPixel,
                                 m_specific->m_rmask, 
                                 m_specific->m_gmask, 
                                 m_specific->m_bmask, 
                                 m_specific->m_amask);

        if(m_specific->m_surf_window == 0) 
        {
            fprintf(stderr, 
                    "Unable to create image buffer %dx%d %d bpp: %s\n", 
                    width, 
                    height, 
                    m_bpp, 
                    SDL_GetError());
            return false;
        }

        m_rbuf_window.attach((unsigned char*)m_specific->m_surf_window->pixels, 
                             m_specific->m_surf_window->w, 
                             m_specific->m_surf_window->h, 
                             m_flip_y ? -m_specific->m_surf_window->pitch : 
                                         m_specific->m_surf_window->pitch);

        if(!m_specific->m_initialized)
        {
            m_initial_width = width;
            m_initial_height = height;
            on_init();
            m_specific->m_initialized = true;
        }
        on_resize(m_rbuf_window.width(), m_rbuf_window.height());
        m_specific->m_update_flag = true;
        return true;
    }
Example #4
0
VOID
PAL_ScrollFBP(
   WORD         wChunkNum,
   WORD         wScrollSpeed,
   BOOL         fScrollDown
)
/*++
  Purpose:

    Scroll up an FBP picture to the screen.

  Parameters:

    [IN]  wChunkNum - number of chunk in fbp.mkf file.

    [IN]  wScrollSpeed - scrolling speed of showing the picture.

    [IN]  fScrollDown - TRUE if scroll down, FALSE if scroll up.

  Return value:

    None.

--*/
{
   SDL_Surface          *p;
   PAL_LARGE BYTE        buf[320 * 200];
   PAL_LARGE BYTE        bufSprite[320 * 200];
   int                   i, l;
   SDL_Rect              rect, dstrect;

   if (PAL_MKFDecompressChunk(buf, 320 * 200, wChunkNum, gpGlobals->f.fpFBP) <= 0)
   {
      return;
   }

   if (g_wCurEffectSprite != 0)
   {
      PAL_MKFDecompressChunk(bufSprite, 320 * 200, g_wCurEffectSprite, gpGlobals->f.fpMGO);
   }

   p = SDL_CreateRGBSurface(gpScreen->flags & ~SDL_HWSURFACE, 320, 200, 8,
      gpScreen->format->Rmask, gpScreen->format->Gmask,
      gpScreen->format->Bmask, gpScreen->format->Amask);

   if (p == NULL)
   {
      return;
   }

   VIDEO_BackupScreen();
   PAL_FBPBlitToSurface(buf, p);

   if (wScrollSpeed == 0)
   {
      wScrollSpeed = 1;
   }

   rect.x = 0;
   rect.w = 320;
   dstrect.x = 0;
   dstrect.w = 320;

   for (l = 0; l < 220; l++)
   {
      i = l;
      if (i > 200)
      {
         i = 200;
      }

      if (fScrollDown)
      {
         rect.y = 0;
         dstrect.y = i;
         rect.h = 200 - i;
         dstrect.h = 200 - i;
      }
      else
      {
         rect.y = i;
         dstrect.y = 0;
         rect.h = 200 - i;
         dstrect.h = 200 - i;
      }

      SDL_BlitSurface(gpScreenBak, &rect, gpScreen, &dstrect);

      if (fScrollDown)
      {
         rect.y = 200 - i;
         dstrect.y = 0;
         rect.h = i;
         dstrect.h = i;
      }
      else
      {
         rect.y = 0;
         dstrect.y = 200 - i;
         rect.h = i;
         dstrect.h = i;
      }

      SDL_BlitSurface(p, &rect, gpScreen, &dstrect);

      PAL_ApplyWave(gpScreen);

      if (g_wCurEffectSprite != 0)
      {
         int f = SDL_GetTicks() / 150;
         PAL_RLEBlitToSurface(PAL_SpriteGetFrame(bufSprite, f % PAL_SpriteGetNumFrames(bufSprite)),
            gpScreen, PAL_XY(0, 0));
      }

      VIDEO_UpdateScreen(NULL);

      if (gpGlobals->fNeedToFadeIn)
      {
         PAL_FadeIn(gpGlobals->wNumPalette, gpGlobals->fNightPalette, 1);
         gpGlobals->fNeedToFadeIn = FALSE;
      }

      UTIL_Delay(800 / wScrollSpeed);
   }

   SDL_BlitSurface(p, NULL, gpScreen, NULL);
   SDL_FreeSurface(p);
   VIDEO_UpdateScreen(NULL);
}
Example #5
0
VOID
PAL_ShowFBP(
   WORD         wChunkNum,
   WORD         wFade
)
/*++
  Purpose:

    Draw an FBP picture to the screen.

  Parameters:

    [IN]  wChunkNum - number of chunk in fbp.mkf file.

    [IN]  wFade - fading speed of showing the picture.

  Return value:

    None.

--*/
{
   PAL_LARGE BYTE            buf[320 * 200];
   PAL_LARGE BYTE            bufSprite[320 * 200];
   const int                 rgIndex[6] = {0, 3, 1, 5, 2, 4};
   SDL_Surface              *p;
   int                       i, j, k;
   BYTE                      a, b;

   if (PAL_MKFDecompressChunk(buf, 320 * 200, wChunkNum, gpGlobals->f.fpFBP) <= 0)
   {
      memset(buf, 0, sizeof(buf));
   }

   if (g_wCurEffectSprite != 0)
   {
      PAL_MKFDecompressChunk(bufSprite, 320 * 200, g_wCurEffectSprite, gpGlobals->f.fpMGO);
   }

   if (wFade)
   {
      wFade++;
      wFade *= 10;

      p = SDL_CreateRGBSurface(gpScreen->flags & ~SDL_HWSURFACE, 320, 200, 8,
         gpScreen->format->Rmask, gpScreen->format->Gmask,
         gpScreen->format->Bmask, gpScreen->format->Amask);

      PAL_FBPBlitToSurface(buf, p);
      VIDEO_BackupScreen();

      for (i = 0; i < 16; i++)
      {
         for (j = 0; j < 6; j++)
         {
            //
            // Blend the pixels in the 2 buffers, and put the result into the
            // backup buffer
            //
            for (k = rgIndex[j]; k < gpScreen->pitch * gpScreen->h; k += 6)
            {
               a = ((LPBYTE)(p->pixels))[k];
               b = ((LPBYTE)(gpScreenBak->pixels))[k];

               if (i > 0)
               {
                  if ((a & 0x0F) > (b & 0x0F))
                  {
                     b++;
                  }
                  else if ((a & 0x0F) < (b & 0x0F))
                  {
                     b--;
                  }
               }

               ((LPBYTE)(gpScreenBak->pixels))[k] = ((a & 0xF0) | (b & 0x0F));
            }

            SDL_BlitSurface(gpScreenBak, NULL, gpScreen, NULL);

            if (g_wCurEffectSprite != 0)
            {
               int f = SDL_GetTicks() / 150;
               PAL_RLEBlitToSurface(PAL_SpriteGetFrame(bufSprite, f % PAL_SpriteGetNumFrames(bufSprite)),
                  gpScreen, PAL_XY(0, 0));
            }

            VIDEO_UpdateScreen(NULL);
            UTIL_Delay(wFade);
         }
      }

      SDL_FreeSurface(p);
   }

   //
   // HACKHACK: to make the ending show correctly
   //
   if (wChunkNum != 49)
   {
      PAL_FBPBlitToSurface(buf, gpScreen);
   }

   VIDEO_UpdateScreen(NULL);
}
Example #6
0
void Renderer::init()
{
	for (int i = 0;i < 10;i++) {
		effectList[i].duration = 0;
	}

	if ( SDL_Init(SDL_INIT_AUDIO|SDL_INIT_VIDEO) < 0 ) {
		fprintf(stderr, "Impossible d'initialiser SDL: %s\n", SDL_GetError());
		exit(1);
	}

    //atexit(SDL_Quit);

     SDL_Init(SDL_INIT_VIDEO);

    // Version d'OpenGL
      
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 1);
      
      
    // Double Buffer
      
    SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
    SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24);


    displayWindow = SDL_CreateWindow("Test SDL 2.0", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, Renderer::screenWidth, Renderer::screenHeight, SDL_WINDOW_OPENGL);
    
    // Création du contexte OpenGL
  
    contexteOpenGL = SDL_GL_CreateContext(displayWindow);
  
    if(contexteOpenGL == 0)
    {
        std::cout << SDL_GetError() << std::endl; //// >> AFFICHE : " the specified window isn't an OpenGL window"
        SDL_DestroyWindow(displayWindow);
        SDL_Quit();
  
        exit(-1); //// >> PLANTE ICI : return -1 ..
    }
      

	if (TTF_Init() < 0) {
		puts("ERROR : unable to initialize font library");
		exit(1);
	}

	//this->font = TTF_OpenFont( "INSPIRAT.ttf", 28 ); 
	this->font = TTF_OpenFont( "digital display tfb.ttf",28);
	if (this->font == NULL)
	{
		puts("ERROR : unable to load font");
		exit(1);
	}


#if SDL_BYTEORDER == SDL_BIG_ENDIAN
    unsigned int rmask = 0xff000000;
    unsigned int gmask = 0x00ff0000;
    unsigned int bmask = 0x0000ff00;
    unsigned int amask = 0x000000ff;
#else
    unsigned int rmask = 0x000000ff;
    unsigned int gmask = 0x0000ff00;
    unsigned int bmask = 0x00ff0000;
    unsigned int amask = 0xff000000;
#endif
	this->textSurface = SDL_CreateRGBSurface( 0, Renderer::screenWidth, Renderer::screenHeight, 32, rmask, gmask, bmask, amask);

	OGLRenderableFactory factory = OGLRenderableFactory();

	this->game = GameFactory::loadGame("game.xml");
	this->game->loadCurrentLevel(&factory);
	bExit = false;

	
	soundManager = new SoundManager();
	soundManager->init();
	
	//soundManager->loadMusic("A991Project.ogg");
	//soundManager->playCurrentMusic();
	
	//soundManager->loadExplosionSound("Grenade-SoundBible.com-1777900486.wav");
	


	particleManager = new ParticleManager();
	/*
    drawthread = SDL_CreateThread(thread_func, this);
    if ( drawthread == NULL ) {
        fprintf(stderr, "Unable to create draw thread: %s\n", SDL_GetError());
        exit(0);
    }
	*/
	this->game->setOnDestroyCallback(onDestroyCallback,this);
	this->game->setOnHitCallback(onHitCallback,this);

	this->fbAccumulation = NULL;
	this->fbDrawing = NULL;
	this->fbHalfRes1 = NULL;
	this->fbHalfRes2 = NULL;

	shaderTexturing = new Shader();
	shaderTexturing->load_fragment("fragment_texturing.gl");
	shaderTexturing->load_vertex("test.gl");

	shaderDistort = new Shader();
	shaderDistort->load_fragment("fragment_distort.gl");
	shaderDistort->load_vertex("test.gl");

	shaderGaussianBlurVertical = new Shader();
	shaderGaussianBlurVertical->load_fragment("fragment_gaussian_vertical.gl");
	shaderGaussianBlurVertical->load_vertex("test02.gl");

	shaderGaussianBlurHorizontal = new Shader();
	shaderGaussianBlurHorizontal->load_fragment("fragment_gaussian_horizontal.gl");
	shaderGaussianBlurHorizontal->load_vertex("test02.gl");


	Texture * texture = new Texture(2,2,(unsigned char*)g_texdata);

	unsigned int * pixels = (unsigned int *)malloc(sizeof(unsigned int)*30*30);
	TextureGenerator::generateTriangle(10,4,pixels,30,0xffffffff);

	this->spriteAccumulation = new Sprite(texture,100.f,100.f,0,0,1,1);
	this->spriteBullet = new Sprite(texture,5.f,5.f,1,1,0,0);
	this->spriteDrawing = new Sprite(texture,100.f,100.f,0,0,1,1);
	this->spriteDummy = new Sprite(texture,100.f,100.f,0,0,1,1);
	this->spriteCovering = new Sprite(texture,Renderer::screenWidth,Renderer::screenHeight,0,0,1,1);
	this->spriteRectangle = new Sprite(texture,10.f,1.f,0,0,1,1);


	unsigned int * pixels2 = (unsigned int *)malloc(sizeof(unsigned int)*30*30);
	TextureGenerator::generateCircle(0,0,pixels2,30,0xffffffff);
	this->spriteCircle = new Sprite(new Texture(30,30,(unsigned char*)pixels2),10.f,10.f,1,1,0,0);
	//this->spriteCircle = this->spriteBullet;

	Texture * textSurfaceTexture = new Texture(Renderer::screenWidth,Renderer::screenHeight,(unsigned char*)this->textSurface->pixels);
	this->spriteTextSurface = new Sprite(textSurfaceTexture,Renderer::screenWidth,Renderer::screenHeight,0,1,1,0);

	this->spriteShip = new Sprite(new Texture(30,30,(unsigned char*)pixels),30.f,30.f,1,1,0,0);

	unsigned int * pixelsgrid = (unsigned int*)malloc(sizeof(unsigned int)* 100 * 100);
	TextureGenerator::generateGrid(pixelsgrid,100,100,20,0xff0909aa);
	this->spriteGrid = new Sprite(new Texture(100,100,(unsigned char*)pixelsgrid),100.f,100.f,0,0,1,1);
	BackgroundLayer * backgroundLayer = new BackgroundLayer(Renderer::screenWidth,Renderer::screenHeight);
	backgroundLayer->addElement(this->spriteGrid,100,100);
	this->backgroundManager.addLayer(backgroundLayer);
	
	unsigned int * pixelsStarfield = (unsigned int*)calloc(sizeof(unsigned int), 100 * 100);
	TextureGenerator::generateStarfield(pixelsStarfield,100,100,10);
	backgroundLayer = new BackgroundLayer(Renderer::screenWidth,Renderer::screenHeight,0.0,-1.5f);
	backgroundLayer->addElement(new Sprite(new Texture(100,100,(unsigned char*)pixelsStarfield),100.f,100.f,0,0,1,1),100,100);
	this->backgroundManager.addLayer(backgroundLayer);

	unsigned int * pixelsStarfield2 = (unsigned int*)calloc(sizeof(unsigned int), 100 * 100);
	TextureGenerator::generateStarfield(pixelsStarfield2,100,100,10);
	backgroundLayer = new BackgroundLayer(Renderer::screenWidth,Renderer::screenHeight,0.0,-1.0f);
	backgroundLayer->addElement(new Sprite(new Texture(100,100,(unsigned char*)pixelsStarfield2),100.f,100.f,0,0,1,1),100,100);
	this->backgroundManager.addLayer(backgroundLayer);
	
}
Example #7
0
// Does not account for converting luminance...
SDL_Surface * ILAPIENTRY ilutConvertToSDLSurface(unsigned int flags)
{
	SDL_Surface *Bitmap;
	ILuint	i = 0, Pad, BppPal;
	ILubyte	*Dest;

	ilutCurImage = ilGetCurImage();
	if (ilutCurImage == NULL) {
		ilSetError(ILUT_ILLEGAL_OPERATION);
		return NULL;
	}

	InitSDL();

	// Should be IL_BGR(A).
	if (ilutCurImage->Format == IL_RGB || ilutCurImage->Format == IL_RGBA) {
		if (!isBigEndian)
			iluSwapColours();
	}

	if (ilutCurImage->Origin == IL_ORIGIN_LOWER_LEFT)
		iluFlipImage();
	if (ilutCurImage->Type > IL_UNSIGNED_BYTE) {}  // Can't do anything about this right now...
	if (ilutCurImage->Type == IL_BYTE) {}  // Can't do anything about this right now...

	Bitmap = SDL_CreateRGBSurface(flags,ilutCurImage->Width,ilutCurImage->Height,ilutCurImage->Bpp * 8,
					rmask,gmask,bmask,amask);

	if (Bitmap == NULL) {
		return IL_FALSE;
	}

	if (SDL_MUSTLOCK(Bitmap))
		SDL_LockSurface(Bitmap);

	Pad = Bitmap->pitch - ilutCurImage->Bps;
	if (Pad == 0) {
		memcpy(Bitmap->pixels, ilutCurImage->Data, ilutCurImage->SizeOfData);
	}
	else {  // Must pad the lines on some images.
		Dest = Bitmap->pixels;
		for (i = 0; i < ilutCurImage->Height; i++) {
			memcpy(Dest, ilutCurImage->Data + i * ilutCurImage->Bps, ilutCurImage->Bps);
			imemclear(Dest + ilutCurImage->Bps, Pad);
			Dest += Bitmap->pitch;
		}
	}

	if (SDL_MUSTLOCK(Bitmap))
		SDL_UnlockSurface(Bitmap);

	if (ilutCurImage->Bpp == 1) {
		BppPal = ilGetBppPal(ilutCurImage->Pal.PalType);
		switch (ilutCurImage->Pal.PalType)
		{
			case IL_PAL_RGB24:
			case IL_PAL_RGB32:
			case IL_PAL_RGBA32:
				for (i = 0; i < ilutCurImage->Pal.PalSize / BppPal; i++) {
					(Bitmap->format)->palette->colors[i].r = ilutCurImage->Pal.Palette[i*BppPal+0];
					(Bitmap->format)->palette->colors[i].g = ilutCurImage->Pal.Palette[i*BppPal+1];
					(Bitmap->format)->palette->colors[i].b = ilutCurImage->Pal.Palette[i*BppPal+2];
					(Bitmap->format)->palette->colors[i].unused = 255;
				}
				break;
			case IL_PAL_BGR24:
			case IL_PAL_BGR32:
			case IL_PAL_BGRA32:
				for (i = 0; i < ilutCurImage->Pal.PalSize / BppPal; i++) {
					(Bitmap->format)->palette->colors[i].b = ilutCurImage->Pal.Palette[i*BppPal+0];
					(Bitmap->format)->palette->colors[i].g = ilutCurImage->Pal.Palette[i*BppPal+1];
					(Bitmap->format)->palette->colors[i].r = ilutCurImage->Pal.Palette[i*BppPal+2];
					(Bitmap->format)->palette->colors[i].unused = 255;
				}
				break;
			default:
				ilSetError(IL_INTERNAL_ERROR);  // Do anything else?
		}
	}

	return Bitmap;
}
Example #8
0
GLuint Graphic::SDL_GL_LoadTexture( SDL_Surface *surface, GLfloat *texcoord ) {
    GLuint tex;
    int w, h;
    SDL_Surface *image;
    SDL_Rect area;
    SDL_BlendMode saved_mode;

    /* Use the surface width and height expanded to powers of 2 */
    w = power_of_two(surface->w);
    h = power_of_two(surface->h);
    texcoord[0] = 0.0f;         /* Min X */
    texcoord[1] = 0.0f;         /* Min Y */
    texcoord[2] = (GLfloat)surface->w / w;  /* Max X */
    texcoord[3] = (GLfloat)surface->h / h;  /* Max Y */

    image = SDL_CreateRGBSurface(
                SDL_SWSURFACE,
                w, h,
                32,
#if SDL_BYTEORDER == SDL_LIL_ENDIAN /* OpenGL RGBA masks */
                0x000000FF,
                0x0000FF00,
                0x00FF0000,
                0xFF000000
#else
                0xFF000000,
                0x00FF0000,
                0x0000FF00,
                0x000000FF
#endif
            );
    if ( image == NULL ) {
        return 0;
    }

    SDL_GetSurfaceBlendMode(surface, &saved_mode);
    SDL_SetSurfaceBlendMode(surface, SDL_BLENDMODE_NONE);

    /* Copy the surface into the GL texture image */
    area.x = 0;
    area.y = 0;
    area.w = surface->w;
    area.h = surface->h;
    SDL_BlitSurface(surface, &area, image, &area);

    SDL_SetSurfaceBlendMode(surface, saved_mode);
    /* Create an OpenGL texture for the image */
    glGenTextures(1, &tex);
    glBindTexture(GL_TEXTURE_2D, tex);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexImage2D(GL_TEXTURE_2D,
                 0,
                 GL_RGBA,
                 w, h,
                 0,
                 GL_RGBA,
                 GL_UNSIGNED_BYTE,
                 image->pixels);
    SDL_FreeSurface(image); /* No longer needed */

    return tex;
}
Example #9
0
/* Load a XPM type image from an SDL datasource */
SDL_Surface *IMG_LoadXPM_RW(SDL_RWops *src)
{
	SDL_Surface *image;
	char line[1024];
	char *here;
	int index;
	int x, y;
	int w, h, ncolors, cpp;
	int pixels_len;
	char *pixels = NULL;
	int indexed;
	Uint8 *dst;
	struct color_hash *colors;
	SDL_Color *im_colors = NULL;
	char *keystrings, *nextkey;
	char *error = NULL;

	/* Skip to the first string, which describes the image */
	do {
	        here = SDL_RWgets(line, sizeof(line), src);
		if ( !here ) {
			IMG_SetError("Premature end of data");
			return(NULL);
		}
		here = skipspace(here);
	} while(*here != '"');
	/*
	 * The header string of an XPMv3 image has the format
	 *
	 * <width> <height> <ncolors> <cpp> [ <hotspot_x> <hotspot_y> ]
	 *
	 * where the hotspot coords are intended for mouse cursors.
	 * Right now we don't use the hotspots but it should be handled
	 * one day.
	 */
	if(sscanf(here + 1, "%d %d %d %d", &w, &h, &ncolors, &cpp) != 4
	   || w <= 0 || h <= 0 || ncolors <= 0 || cpp <= 0) {
		IMG_SetError("Invalid format description");
		return(NULL);
	}

	keystrings = malloc(ncolors * cpp);
	if(!keystrings) {
		IMG_SetError("Out of memory");
		free(pixels);
		return NULL;
	}
	nextkey = keystrings;

	/* Create the new surface */
	if(ncolors <= 256) {
		indexed = 1;
		image = SDL_CreateRGBSurface(SDL_SWSURFACE, w, h, 8,
					     0, 0, 0, 0);
		im_colors = image->format->palette->colors;
		image->format->palette->ncolors = ncolors;
	} else {
		indexed = 0;
		image = SDL_CreateRGBSurface(SDL_SWSURFACE, w, h, 32,
					     0xff0000, 0x00ff00, 0x0000ff, 0);
	}
	if(!image) {
		/* Hmm, some SDL error (out of memory?) */
		free(pixels);
		return(NULL);
	}

	/* Read the colors */
	colors = create_colorhash(ncolors);
	if ( ! colors ) {
		error = "Out of memory";
		goto done;
	}
	for(index = 0; index < ncolors; ++index ) {
		char *key;
		int len;

		do {
			here = SDL_RWgets(line, sizeof(line), src);
			if(!here) {
				error = "Premature end of data";
				goto done;
			}
			here = skipspace(here);
		} while(*here != '"');

		++here;
		len = strlen(here);
		if(len < cpp + 7)
			continue;	/* cannot be a valid line */

		key = here;
		key[cpp] = '\0';
		here += cpp + 1;

		/* parse a colour definition */
		for(;;) {
			char nametype;
			char *colname;
			char delim;
			Uint32 rgb;

			here = skipspace(here);
			nametype = *here;
			here = skipnonspace(here);
			here = skipspace(here);
			colname = here;
			while(*here && !isspace((unsigned char)*here)
			      && *here != '"')
				here++;
			if(!*here) {
				error = "color parse error";
				goto done;
			}
			if(nametype == 's')
				continue;      /* skip symbolic colour names */

			delim = *here;
			*here = '\0';
			if(delim)
			    here++;

			if(!color_to_rgb(colname, &rgb))
				continue;

			memcpy(nextkey, key, cpp);
			if(indexed) {
				SDL_Color *c = im_colors + index;
				c->r = rgb >> 16;
				c->g = rgb >> 8;
				c->b = rgb;
				add_colorhash(colors, nextkey, cpp, index);
			} else
				add_colorhash(colors, nextkey, cpp, rgb);
			nextkey += cpp;
			if(rgb == 0xffffffff)
				SDL_SetColorKey(image, SDL_SRCCOLORKEY,
						indexed ? index : rgb);
			break;
		}
	}
Example #10
0
File: main.c Project: jcnix/c8
int main(int argc, char** argv)
{
	srand(time(NULL));
	struct chip8 cpu;

	initialize(&cpu);
	load_game(&cpu, argv[1]);

	//setup graphics
	SDL_Window *window = NULL;
	SDL_Surface *screen = NULL;
	if(SDL_Init(SDL_INIT_VIDEO) < 0)
	{
		printf( "SDL could not initialize! SDL_Error: %s\n", SDL_GetError() );
	}
	else
	{
		window = SDL_CreateWindow( "Chip8", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN );
		if(!window)
		{
			printf( "Window could not be created! SDL_Error: %s\n", SDL_GetError() );
		}
		else
		{
			//Get window surface
			screen = SDL_GetWindowSurface(window);

			//Fill the surface white
			SDL_FillRect( screen, NULL, SDL_MapRGB(screen->format, 0xFF, 0xFF, 0xFF ) );
			
			//Update the surface
			SDL_UpdateWindowSurface(window);
		}
	}

	SDL_Surface *s;
	s = SDL_CreateRGBSurface(0, 640, 320, 32, 0,0,0,0);
	SDL_FillRect(s, NULL, SDL_MapRGB(s->format, 0, 0, 0));
	SDL_Surface *pixel = NULL;
	pixel = SDL_LoadBMP("pixel.bmp");
	if(!pixel)
	{
			printf( "Unable to load image! SDL Error: %s\n", SDL_GetError() );
	}
	SDL_BlitSurface(s, NULL, screen, NULL);
	SDL_BlitSurface(pixel, NULL, screen, NULL);
	SDL_UpdateWindowSurface(window);
	
	//init keys
	reset_keys(&cpu);

	int quit = 0;
	while(!quit)
	{
		usleep(1000);
		emulate_cycle(&cpu);
		if(cpu.drawFlag)
		{
			//draw graphics
			SDL_BlitSurface(s, NULL, screen, NULL);
			for(int i = 0; i < DISP_T; i++)
			{
				if(cpu.gfx[i])
				{
					int x = (i % 64) * 10;
					int y = (i / 64) *10;
					SDL_Rect r;
					r.x = x;
					r.y = y;
					r.w = 10;
					r.h = 10;
					SDL_BlitSurface(pixel, NULL, screen, &r);
				}
			}
			SDL_UpdateWindowSurface(window);
			cpu.drawFlag = 0;
		}

		//set keys
		reset_keys(&cpu);
		SDL_Event e;
		SDL_PollEvent(&e);
		if(e.type == SDL_QUIT) {
			quit = 1;
		} else if(e.type == SDL_KEYDOWN) {
			long k = e.key.keysym.sym;
			switch(k) {
				case SDLK_1:
					cpu.keys[0] = 1;
					break;
				case SDLK_2:
					cpu.keys[1] = 1;
					break;
				case SDLK_3:
					cpu.keys[2] = 1;
					break;
				case SDLK_4:
					cpu.keys[3] = 1;
					break;
				case SDLK_q:
					cpu.keys[4] = 1;
					break;
				case SDLK_w:
					cpu.keys[5] = 1;
					break;
				case SDLK_e:
					cpu.keys[6] = 1;
					break;
				case SDLK_r:
					cpu.keys[7] = 1;
					break;
				case SDLK_a:
					cpu.keys[8] = 1;
					break;
				case SDLK_s:
					cpu.keys[9] = 1;
					break;	
				case SDLK_d:
					cpu.keys[10] = 1;
					break;
				case SDLK_f:
					cpu.keys[11] = 1;
					break;
				case SDLK_z:
					cpu.keys[12] = 1;
					break;
				case SDLK_x:
					cpu.keys[13] = 1;
					break;
				case SDLK_c:
					cpu.keys[14] = 1;
					break;
				case SDLK_v:
					cpu.keys[15] = 1;
					break;
			}
		}
	}

	SDL_FreeSurface(s);
	SDL_FreeSurface(pixel);
	pixel = NULL;

	SDL_DestroyWindow(window);
	SDL_DestroyWindow(screen);
	SDL_Quit();

	return 0;
}
Example #11
0
int gui_init (void)
{

//Se ejecuta justo despues del MAIN

    if (prSDLScreen==NULL)
#ifdef DREAMCAST
	prSDLScreen=SDL_SetVideoMode(320,240,16,VIDEO_FLAGS);
#else

#ifdef PANDORA
	if(hwScaled)
		prSDLScreen = SDL_SetVideoMode(320, gfxHeight, 16, VIDEO_FLAGS);
	else
	{
		prSDLScreen = SDL_CreateRGBSurface(SDL_SWSURFACE,320,240,16,0,0,0,0);
		prSDLScaleScreen = SDL_SetVideoMode(640, 480, 16, VIDEO_FLAGS);
	}
#else
	prSDLScreen=SDL_SetVideoMode(320,240,16,VIDEO_FLAGS);
#endif

#endif
    SDL_ShowCursor(SDL_DISABLE);
    SDL_JoystickEventState(SDL_ENABLE);
    SDL_JoystickOpen(0);
    if (prSDLScreen!=NULL)
    {
	emulating=0;

#if !defined(DEBUG_UAE4ALL) && !defined(PROFILER_UAE4ALL) && !defined(AUTO_RUN) && !defined(AUTO_FRAMERATE)
	//uae4all_image_file[0]=0;
	//uae4all_image_file2[0]=0;
#else
	//strcpy(uae4all_image_file,"prueba.adz");
	//strcpy(uae4all_image_file2,"prueba2.adz");
#endif
	init_text(1);
	if (!uae4all_image_file0[0])
		run_mainMenu();
	quit_text();
	vkbd_init();

#ifdef GP2X
	inputmode_init();
#if !defined(PANDORA) && !defined(GCW0)
	volumecontrol_init();
#endif
#endif
printf("4\n");
#if defined (PSP) || defined (GIZMONDO)
	inputmode_init();
#endif

	uae4all_pause_music();
printf("5\n");
	emulating=1;
	getChanges();
printf("6\n");
	check_all_prefs();
printf("7\n");
	reset_frameskip();
printf("8\n");
#ifdef DEBUG_FRAMERATE
	uae4all_update_time();
#endif
#ifdef PROFILER_UAE4ALL
	uae4all_prof_init();
	uae4all_prof_add("M68K");			// 0
	uae4all_prof_add("EVENTS");			// 1
	uae4all_prof_add("HSync");			// 2
	uae4all_prof_add("Copper");			// 3
	uae4all_prof_add("Audio");			// 4
	uae4all_prof_add("CIA");			// 5
	uae4all_prof_add("Blitter");			// 6
	uae4all_prof_add("Vsync");			// 7
	uae4all_prof_add("update_fetch");		// 8
	uae4all_prof_add("linetoscr");			// 9
	uae4all_prof_add("do_long_fetch");		// 10
	uae4all_prof_add("pfield_doline");		// 11
	uae4all_prof_add("draw_sprites_ecs");		// 12
	uae4all_prof_add("flush_block");		// 13
	uae4all_prof_add("SET_INTERRUPT");		// 14
/*
	uae4all_prof_add("15");		// 15
	uae4all_prof_add("16");		// 16
	uae4all_prof_add("17");		// 17
	uae4all_prof_add("18");		// 18
	uae4all_prof_add("19");		// 19
	uae4all_prof_add("20");		// 20
	uae4all_prof_add("21");		// 21
	uae4all_prof_add("22");		// 22
*/
#endif
#ifdef DREAMCAST
	SDL_DC_EmulateKeyboard(SDL_FALSE);
#endif

	/*int test = pnd_evdev_open(pnd_evdev_nub1);
	printf("nub1 open: %d\n", test);
	test = pnd_evdev_open(pnd_evdev_nub2);
	printf("nub2 open: %d\n", test);*/

	return 0;
    }
    return -1;
}
Example #12
0
void Draw (SDL_Surface *screen, int start)
{
	SDL_Surface *picture, *picture_again;
	char *bmpfile;

	/* --------- 8 bit test -------- */

	if (start<=1) {
	
  	 /* Message */
         fprintf (stderr,"Loading 8bit square image\n");

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


	 fprintf (stderr,"1. shrink 8bit\n");
	 ShrinkPicture(screen,picture);

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

	if (start<=2) {
	
  	 /* Message */
         fprintf (stderr,"Loading 8bit image\n");

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


	 fprintf (stderr,"1. shrink 8bit\n");
	 ShrinkPicture(screen,picture);

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

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


	if (start<=3) {

	 /* Message */
         fprintf (stderr,"Loading 24bit square image\n");

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

	 fprintf (stderr,"2. shrink 24bit\n");
	 ShrinkPicture(screen,picture);

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

	}

	if (start<=4) {

	 /* Message */
         fprintf (stderr,"Loading 24bit image\n");

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

	 fprintf (stderr,"2. shrink 24bit\n");
	 ShrinkPicture(screen,picture);

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

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

	if (start<=5) {

	 /* Message */
         fprintf (stderr,"Loading 24bit square image\n");

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

  	 /* 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, 0x000000ff, 0x0000ff00, 0x00ff0000, 0xff000000);
	 SDL_BlitSurface(picture,NULL,picture_again,NULL);
 
	 /* Message */
	 fprintf (stderr,"3. shrink 32bit \n");
	 ShrinkPicture(screen,picture_again);

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

        }

	if (start<=6) {

	 /* Message */
         fprintf (stderr,"Loading 24bit image\n");

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

  	 /* 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, 0x000000ff, 0x0000ff00, 0x00ff0000, 0xff000000);
	 SDL_BlitSurface(picture,NULL,picture_again,NULL);
 
	 /* Message */
	 fprintf (stderr,"3. shrink 32bit \n");
	 ShrinkPicture(screen,picture_again);

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

        }
	
	return;
}
Example #13
0
void CGX_SetIcon(_THIS, SDL_Surface *icon, Uint8 *mask)
{
#if 0
	SDL_Surface *sicon;
	XWMHints *wmhints;
	XImage *icon_image;
	Pixmap icon_pixmap;
	Pixmap mask_pixmap;
#ifdef USE_ICON_WINDOW
	Window icon_window;
#endif
	GC GC;
	XGCValues GCvalues;
	int i, b, dbpp;
	SDL_Rect bounds;
	Uint8 *LSBmask, *color_tried;
	Visual *dvis;

	/* Lock the event thread, in multi-threading environments */
	SDL_Lock_EventThread();

	/* The icon must use the default visual, depth and colormap of the
	   screen, so it might need a conversion */
	dbpp = DefaultDepth(SDL_Display, SDL_Screen);
	switch(dbpp) {
	case 15:
	    dbpp = 16; break;
	case 24:
	    dbpp = 32; break;
	}
	dvis = DefaultVisual(SDL_Display, SDL_Screen);

	/* The Visual struct is supposed to be opaque but we cheat a little */
	sicon = SDL_CreateRGBSurface(SDL_SWSURFACE, icon->w, icon->h,
				     dbpp,
				     dvis->red_mask, dvis->green_mask,
				     dvis->blue_mask, 0);

	if ( sicon == NULL ) {
		goto done;
	}
	/* If we already have allocated colours from the default colormap,
	   copy them */
	if(SDL_Visual == dvis && SDL_XColorMap == SDL_DisplayColormap
	   && this->screen->format->palette && sicon->format->palette) {
	    memcpy(sicon->format->palette->colors,
		   this->screen->format->palette->colors,
		   this->screen->format->palette->ncolors * sizeof(SDL_Color));
	}

	bounds.x = 0;
	bounds.y = 0;
	bounds.w = icon->w;
	bounds.h = icon->h;
	if ( SDL_LowerBlit(icon, &bounds, sicon, &bounds) < 0 )
		goto done;

	/* Lock down the colors used in the colormap */
	color_tried = NULL;
	if ( sicon->format->BitsPerPixel == 8 ) {
		SDL_Palette *palette;
		Uint8 *p;
		XColor wanted;

		palette = sicon->format->palette;
		color_tried = malloc(palette->ncolors);
		if ( color_tried == NULL ) {
			goto done;
		}
		if ( SDL_iconcolors != NULL ) {
			free(SDL_iconcolors);
		}
		SDL_iconcolors = malloc(palette->ncolors
					* sizeof(*SDL_iconcolors));
		if ( SDL_iconcolors == NULL ) {
			free(color_tried);
			goto done;
		}
		memset(color_tried, 0, palette->ncolors);
		memset(SDL_iconcolors, 0,
		       palette->ncolors * sizeof(*SDL_iconcolors));

		p = (Uint8 *)sicon->pixels; 
		for ( i = sicon->w*sicon->h; i > 0; --i, ++p ) {
			if ( ! color_tried[*p] ) {
				wanted.pixel = *p;
				wanted.red   = (palette->colors[*p].r<<8);
				wanted.green = (palette->colors[*p].g<<8);
				wanted.blue  = (palette->colors[*p].b<<8);
				wanted.flags = (DoRed|DoGreen|DoBlue);
				if (XAllocColor(SDL_Display,
						SDL_DisplayColormap, &wanted)) {
					++SDL_iconcolors[wanted.pixel];
				}
				color_tried[*p] = 1;
			}
		}
	}
	if ( color_tried != NULL ) {
		free(color_tried);
	}

	/* Translate mask data to LSB order and set the icon mask */
	i = (sicon->w/8)*sicon->h;
	LSBmask = (Uint8 *)malloc(i);
	if ( LSBmask == NULL ) {
		goto done;
	}
	memset(LSBmask, 0, i);
	while ( --i >= 0 ) {
		for ( b=0; b<8; ++b )
			LSBmask[i] |= (((mask[i]>>b)&0x01)<<(7-b));
	}
	mask_pixmap = XCreatePixmapFromBitmapData(SDL_Display, WMwindow,
					LSBmask, sicon->w, sicon->h, 1L, 0L, 1);

	/* Transfer the image to an X11 pixmap */
	icon_image = XCreateImage(SDL_Display,
			DefaultVisual(SDL_Display, SDL_Screen),
			DefaultDepth(SDL_Display, SDL_Screen),
			ZPixmap, 0, (char *)sicon->pixels, sicon->w, sicon->h,
			((sicon->format)->BytesPerPixel == 3) ? 32 :
				(sicon->format)->BytesPerPixel*8, 0);
	icon_pixmap = XCreatePixmap(SDL_Display, SDL_Root, sicon->w, sicon->h,
			DefaultDepth(SDL_Display, SDL_Screen));
	GC = XCreateGC(SDL_Display, icon_pixmap, 0, &GCvalues);
	XPutImage(SDL_Display, icon_pixmap, GC, icon_image,
					0, 0, 0, 0, sicon->w, sicon->h);
	XFreeGC(SDL_Display, GC);
	XDestroyImage(icon_image);
	free(LSBmask);
	sicon->pixels = NULL;

#ifdef USE_ICON_WINDOW
	/* Create an icon window and set the pixmap as its background */
	icon_window = XCreateSimpleWindow(SDL_Display, SDL_Root,
					0, 0, sicon->w, sicon->h, 0,
					CopyFromParent, CopyFromParent);
	XSetWindowBackgroundPixmap(SDL_Display, icon_window, icon_pixmap);
	XClearWindow(SDL_Display, icon_window);
#endif

	/* Set the window icon to the icon pixmap (and icon window) */
	wmhints = XAllocWMHints();
	wmhints->flags = (IconPixmapHint | IconMaskHint);
	wmhints->icon_pixmap = icon_pixmap;
	wmhints->icon_mask = mask_pixmap;
#ifdef USE_ICON_WINDOW
	wmhints->flags |= IconWindowHint;
	wmhints->icon_window = icon_window;
#endif
	XSetWMHints(SDL_Display, WMwindow, wmhints);
	XFree(wmhints);
	XSync(SDL_Display, False);

  done:
	SDL_Unlock_EventThread();
	if ( sicon != NULL ) {
		SDL_FreeSurface(sicon);
	}
#endif
	return;
}
Example #14
0
/*
 * Convert a surface into the specified pixel format.
 */
SDL_Surface *
SDL_ConvertSurface(SDL_Surface * surface, const SDL_PixelFormat * format,
                   Uint32 flags)
{
    SDL_Surface *convert;
    Uint32 copy_flags;
    SDL_Color copy_color;
    SDL_Rect bounds;

    /* Check for empty destination palette! (results in empty image) */
    if (format->palette != NULL) {
        int i;
        for (i = 0; i < format->palette->ncolors; ++i) {
            if ((format->palette->colors[i].r != 0xFF) ||
                (format->palette->colors[i].g != 0xFF) ||
                (format->palette->colors[i].b != 0xFF))
                break;
        }
        if (i == format->palette->ncolors) {
            SDL_SetError("Empty destination palette");
            return (NULL);
        }
    }

    /* Create a new surface with the desired format */
    convert = SDL_CreateRGBSurface(flags, surface->w, surface->h,
                                   format->BitsPerPixel, format->Rmask,
                                   format->Gmask, format->Bmask,
                                   format->Amask);
    if (convert == NULL) {
        return (NULL);
    }

    /* Copy the palette if any */
    if (format->palette && convert->format->palette) {
        SDL_memcpy(convert->format->palette->colors,
                   format->palette->colors,
                   format->palette->ncolors * sizeof(SDL_Color));
        convert->format->palette->ncolors = format->palette->ncolors;
    }

    /* Save the original copy flags */
    copy_flags = surface->map->info.flags;
    copy_color.r = surface->map->info.r;
    copy_color.g = surface->map->info.g;
    copy_color.b = surface->map->info.b;
    copy_color.a = surface->map->info.a;
    surface->map->info.r = 0xFF;
    surface->map->info.g = 0xFF;
    surface->map->info.b = 0xFF;
    surface->map->info.a = 0xFF;
    surface->map->info.flags = 0;
    SDL_InvalidateMap(surface->map);

    /* Copy over the image data */
    bounds.x = 0;
    bounds.y = 0;
    bounds.w = surface->w;
    bounds.h = surface->h;
    SDL_LowerBlit(surface, &bounds, convert, &bounds);

    /* Clean up the original surface, and update converted surface */
    convert->map->info.r = copy_color.r;
    convert->map->info.g = copy_color.g;
    convert->map->info.b = copy_color.b;
    convert->map->info.a = copy_color.a;
    convert->map->info.flags =
        (copy_flags &
         ~(SDL_COPY_COLORKEY | SDL_COPY_BLEND
           | SDL_COPY_RLE_DESIRED | SDL_COPY_RLE_COLORKEY |
           SDL_COPY_RLE_ALPHAKEY));
    surface->map->info.r = copy_color.r;
    surface->map->info.g = copy_color.g;
    surface->map->info.b = copy_color.b;
    surface->map->info.a = copy_color.a;
    surface->map->info.flags = copy_flags;
    SDL_InvalidateMap(surface->map);
    if (copy_flags & SDL_COPY_COLORKEY) {
        SDL_bool set_colorkey_by_color = SDL_FALSE;

        if (surface->format->palette) {
            if (format->palette &&
                surface->format->palette->ncolors <= format->palette->ncolors &&
                (SDL_memcmp(surface->format->palette->colors, format->palette->colors,
                  surface->format->palette->ncolors * sizeof(SDL_Color)) == 0)) {
                /* The palette is identical, just set the same colorkey */
                SDL_SetColorKey(convert, 1, surface->map->info.colorkey);
            } else if (format->Amask) {
                /* The alpha was set in the destination from the palette */
            } else {
                set_colorkey_by_color = SDL_TRUE;
            }
        } else {
            set_colorkey_by_color = SDL_TRUE;
        }

        if (set_colorkey_by_color) {
            /* Set the colorkey by color, which needs to be unique */
            Uint8 keyR, keyG, keyB, keyA;

            SDL_GetRGBA(surface->map->info.colorkey, surface->format, &keyR,
                        &keyG, &keyB, &keyA);
            SDL_SetColorKey(convert, 1,
                            SDL_MapRGBA(convert->format, keyR, keyG, keyB, keyA));
            /* This is needed when converting for 3D texture upload */
            SDL_ConvertColorkeyToAlpha(convert);
        }
    }
    SDL_SetClipRect(convert, &surface->clip_rect);

    /* Enable alpha blending by default if the new surface has an
     * alpha channel or alpha modulation */
    if ((surface->format->Amask && format->Amask) ||
        (copy_flags & (SDL_COPY_COLORKEY|SDL_COPY_MODULATE_ALPHA))) {
        SDL_SetSurfaceBlendMode(convert, SDL_BLENDMODE_BLEND);
    }
    if ((copy_flags & SDL_COPY_RLE_DESIRED) || (flags & SDL_RLEACCEL)) {
        SDL_SetSurfaceRLE(convert, SDL_RLEACCEL);
    }

    /* We're ready to go! */
    return (convert);
}
Example #15
0
BATTLERESULT
PAL_StartBattle(
   WORD        wEnemyTeam,
   BOOL        fIsBoss
)
/*++
  Purpose:

    Start a battle.

  Parameters:

    [IN]  wEnemyTeam - the number of the enemy team.

    [IN]  fIsBoss - TRUE for boss fight (not allowed to flee).

  Return value:

    The result of the battle.

--*/
{
   int            i;
   WORD           w, wPrevWaveLevel;
   SHORT          sPrevWaveProgression;
   
   UTIL_WriteLog(LOG_DEBUG, "[0x%08x][%s][%s] - [%d],[%d]", (long)PAL_StartBattle, "PAL_StartBattle", __FILE__, wEnemyTeam, fIsBoss);

   //
   // Set the screen waving effects
   //
   wPrevWaveLevel = gpGlobals->wScreenWave;
   sPrevWaveProgression = gpGlobals->sWaveProgression;

   gpGlobals->sWaveProgression = 0;
   gpGlobals->wScreenWave = gpGlobals->g.lprgBattleField[gpGlobals->wNumBattleField].wScreenWave;

   //
   // Make sure everyone in the party is alive, also clear all hidden
   // EXP count records
   //
   for (i = 0; i <= gpGlobals->wMaxPartyMemberIndex; i++)
   {
      w = gpGlobals->rgParty[i].wPlayerRole;

      if (gpGlobals->g.PlayerRoles.rgwHP[w] == 0)
      {
         gpGlobals->g.PlayerRoles.rgwHP[w] = 1;
         gpGlobals->rgPlayerStatus[w][kStatusPuppet] = 0;
      }

      gpGlobals->Exp.rgHealthExp[w].wCount = 0;
      gpGlobals->Exp.rgMagicExp[w].wCount = 0;
      gpGlobals->Exp.rgAttackExp[w].wCount = 0;
      gpGlobals->Exp.rgMagicPowerExp[w].wCount = 0;
      gpGlobals->Exp.rgDefenseExp[w].wCount = 0;
      gpGlobals->Exp.rgDexterityExp[w].wCount = 0;
      gpGlobals->Exp.rgFleeExp[w].wCount = 0;
   }

   //
   // Clear all item-using records
   //
   for (i = 0; i < MAX_INVENTORY; i++)
   {
      gpGlobals->rgInventory[i].nAmountInUse = 0;
   }

   //
   // Store all enemies
   //
   for (i = 0; i < MAX_ENEMIES_IN_TEAM; i++)
   {
      memset(&(g_Battle.rgEnemy[i]), 0, sizeof(BATTLEENEMY));
      w = gpGlobals->g.lprgEnemyTeam[wEnemyTeam].rgwEnemy[i];

      if (w == 0xFFFF)
      {
         break;
      }

      if (w != 0)
      {
         g_Battle.rgEnemy[i].e = gpGlobals->g.lprgEnemy[gpGlobals->g.rgObject[w].enemy.wEnemyID];
         g_Battle.rgEnemy[i].wObjectID = w;
         g_Battle.rgEnemy[i].state = kFighterWait;
         g_Battle.rgEnemy[i].wScriptOnTurnStart = gpGlobals->g.rgObject[w].enemy.wScriptOnTurnStart;
         g_Battle.rgEnemy[i].wScriptOnBattleEnd = gpGlobals->g.rgObject[w].enemy.wScriptOnBattleEnd;
         g_Battle.rgEnemy[i].wScriptOnReady = gpGlobals->g.rgObject[w].enemy.wScriptOnReady;
         g_Battle.rgEnemy[i].iColorShift = 0;

#ifndef PAL_CLASSIC
         g_Battle.rgEnemy[i].flTimeMeter = 50;

         //
         // HACK: Otherwise the black thief lady will be too hard to beat
         //
         if (g_Battle.rgEnemy[i].e.wDexterity == 164)
         {
            g_Battle.rgEnemy[i].e.wDexterity /= ((gpGlobals->wMaxPartyMemberIndex == 0) ? 6 : 3);
         }

         //
         // HACK: Heal up automatically for final boss
         //
         if (g_Battle.rgEnemy[i].e.wHealth == 32760)
         {
            for (w = 0; w < MAX_PLAYER_ROLES; w++)
            {
               gpGlobals->g.PlayerRoles.rgwHP[w] = gpGlobals->g.PlayerRoles.rgwMaxHP[w];
               gpGlobals->g.PlayerRoles.rgwMP[w] = gpGlobals->g.PlayerRoles.rgwMaxMP[w];
            }
         }

         //
         // Yet another HACKs
         //
         if ((SHORT)g_Battle.rgEnemy[i].e.wDexterity == -32)
         {
            g_Battle.rgEnemy[i].e.wDexterity = 0; // for Grandma Knife
         }
         else if (g_Battle.rgEnemy[i].e.wDexterity == 20)
         {
            //
            // for Fox Demon
            //
            if (gpGlobals->g.PlayerRoles.rgwLevel[0] < 15)
            {
               g_Battle.rgEnemy[i].e.wDexterity = 8;
            }
            else if (gpGlobals->g.PlayerRoles.rgwLevel[4] > 28 ||
               gpGlobals->Exp.rgPrimaryExp[4].wExp > 0)
            {
               g_Battle.rgEnemy[i].e.wDexterity = 60;
            }
         }
         else if (g_Battle.rgEnemy[i].e.wExp == 250 &&
            g_Battle.rgEnemy[i].e.wCash == 1100)
         {
            g_Battle.rgEnemy[i].e.wDexterity += 12; // for Snake Demon
         }
         else if ((SHORT)g_Battle.rgEnemy[i].e.wDexterity == -60)
         {
            g_Battle.rgEnemy[i].e.wDexterity = 15; // for Spider
         }
         else if ((SHORT)g_Battle.rgEnemy[i].e.wDexterity == -30)
         {
            g_Battle.rgEnemy[i].e.wDexterity = (WORD)-10; // for Stone Head
         }
         else if ((SHORT)g_Battle.rgEnemy[i].e.wDexterity == -16)
         {
            g_Battle.rgEnemy[i].e.wDexterity = 0; // for Zombie
         }
         else if ((SHORT)g_Battle.rgEnemy[i].e.wDexterity == -20)
         {
            g_Battle.rgEnemy[i].e.wDexterity = -8; // for Flower Demon
         }
         else if (g_Battle.rgEnemy[i].e.wLevel < 20 &&
            gpGlobals->wNumScene >= 0xD8 && gpGlobals->wNumScene <= 0xE2)
         {
            //
            // for low-level monsters in the Cave of Trial
            //
            g_Battle.rgEnemy[i].e.wLevel += 15;
            g_Battle.rgEnemy[i].e.wDexterity += 25;
         }
         else if (gpGlobals->wNumScene == 0x90)
         {
            g_Battle.rgEnemy[i].e.wDexterity += 25; // for Tower Dragons
         }
         else if (g_Battle.rgEnemy[i].e.wLevel == 2 &&
            g_Battle.rgEnemy[i].e.wCash == 48)
         {
            g_Battle.rgEnemy[i].e.wDexterity += 8; // for Miao Fists
         }
         else if (g_Battle.rgEnemy[i].e.wLevel == 4 &&
            g_Battle.rgEnemy[i].e.wCash == 240)
         {
            g_Battle.rgEnemy[i].e.wDexterity += 18; // for Fat Miao
         }
         else if (g_Battle.rgEnemy[i].e.wLevel == 16 &&
            g_Battle.rgEnemy[i].e.wMagicRate == 4 &&
            g_Battle.rgEnemy[i].e.wAttackEquivItemRate == 4)
         {
            g_Battle.rgEnemy[i].e.wDexterity += 50; // for Black Spider
         }
#endif
      }
   }

   g_Battle.wMaxEnemyIndex = i - 1;

   //
   // Store all players
   //
   for (i = 0; i <= gpGlobals->wMaxPartyMemberIndex; i++)
   {
      g_Battle.rgPlayer[i].flTimeMeter = 15.0f;
#ifndef PAL_CLASSIC
      g_Battle.rgPlayer[i].flTimeSpeedModifier = 2.0f;
      g_Battle.rgPlayer[i].sTurnOrder = -1;
#endif
      g_Battle.rgPlayer[i].wHidingTime = 0;
      g_Battle.rgPlayer[i].state = kFighterWait;
      g_Battle.rgPlayer[i].action.sTarget = -1;
      g_Battle.rgPlayer[i].fDefending = FALSE;
      g_Battle.rgPlayer[i].wCurrentFrame = 0;
      g_Battle.rgPlayer[i].iColorShift = FALSE;
   }

   //
   // Load sprites and background
   //
   PAL_LoadBattleSprites();
   PAL_LoadBattleBackground();

   //
   // Create the surface for scene buffer
   //
   g_Battle.lpSceneBuf =
      SDL_CreateRGBSurface(gpScreen->flags & ~SDL_HWSURFACE, 320, 200, 8,
      gpScreen->format->Rmask, gpScreen->format->Gmask,
      gpScreen->format->Bmask, gpScreen->format->Amask);

   if (g_Battle.lpSceneBuf == NULL)
   {
      TerminateOnError("PAL_StartBattle(): creating surface for scene buffer failed!");
   }

   PAL_UpdateEquipments();

   g_Battle.iExpGained = 0;
   g_Battle.iCashGained = 0;

   g_Battle.fIsBoss = fIsBoss;
   g_Battle.fEnemyCleared = FALSE;
   g_Battle.fEnemyMoving = FALSE;
   g_Battle.iHidingTime = 0;
   g_Battle.wMovingPlayerIndex = 0;

   g_Battle.UI.szMsg[0] = '\0';
   g_Battle.UI.szNextMsg[0] = '\0';
   g_Battle.UI.dwMsgShowTime = 0;
   g_Battle.UI.state = kBattleUIWait;
   g_Battle.UI.fAutoAttack = FALSE;
   g_Battle.UI.wSelectedIndex = 0;
   g_Battle.UI.wPrevEnemyTarget = 0;

   memset(g_Battle.UI.rgShowNum, 0, sizeof(g_Battle.UI.rgShowNum));

   g_Battle.lpSummonSprite = NULL;
   g_Battle.sBackgroundColorShift = 0;

   gpGlobals->fInBattle = TRUE;
   g_Battle.BattleResult = kBattleResultPreBattle;

   PAL_BattleUpdateFighters();

   //
   // Load the battle effect sprite.
   //
   i = PAL_MKFGetChunkSize(10, gpGlobals->f.fpDATA);
   g_Battle.lpEffectSprite = UTIL_malloc(i);

   PAL_MKFReadChunk(g_Battle.lpEffectSprite, i, 10, gpGlobals->f.fpDATA);

#ifdef PAL_CLASSIC
   g_Battle.Phase = kBattlePhaseSelectAction;
   g_Battle.fRepeat = FALSE;
   g_Battle.fForce = FALSE;
   g_Battle.fFlee = FALSE;
#endif

#ifdef PAL_ALLOW_KEYREPEAT
   SDL_EnableKeyRepeat(120, 75);
#endif

   //
   // Run the main battle routine.
   //
   i = PAL_BattleMain();

#ifdef PAL_ALLOW_KEYREPEAT
   SDL_EnableKeyRepeat(0, 0);
   PAL_ClearKeyState();
   g_InputState.prevdir = kDirUnknown;
#endif

   if (i == kBattleResultWon)
   {
      //
      // Player won the battle. Add the Experience points.
      //
      PAL_BattleWon();
   }

   //
   // Clear all item-using records
   //
   for (w = 0; w < MAX_INVENTORY; w++)
   {
      gpGlobals->rgInventory[w].nAmountInUse = 0;
   }

   //
   // Clear all player status, poisons and temporary effects
   //
   PAL_ClearAllPlayerStatus();
   for (w = 0; w < MAX_PLAYER_ROLES; w++)
   {
      PAL_CurePoisonByLevel(w, 3);
      PAL_RemoveEquipmentEffect(w, kBodyPartExtra);
   }

   //
   // Free all the battle sprites
   //
   PAL_FreeBattleSprites();
   free(g_Battle.lpEffectSprite);

   //
   // Free the surfaces for the background picture and scene buffer
   //
   SDL_FreeSurface(g_Battle.lpBackground);
   SDL_FreeSurface(g_Battle.lpSceneBuf);

   g_Battle.lpBackground = NULL;
   g_Battle.lpSceneBuf = NULL;

   gpGlobals->fInBattle = FALSE;

   RIX_Play(gpGlobals->wNumMusic, TRUE, 1);

   //
   // Restore the screen waving effects
   //
   gpGlobals->sWaveProgression = sPrevWaveProgression;
   gpGlobals->wScreenWave = wPrevWaveLevel;

   UTIL_WriteLog(LOG_DEBUG, "[0x%08x][%s][%s] - %s", (long)PAL_StartBattle, "PAL_StartBattle", __FILE__, "end");
   
   return i;
}
static DFBResult
sdlAllocateBuffer( CoreSurfacePool       *pool,
                   void                  *pool_data,
                   void                  *pool_local,
                   CoreSurfaceBuffer     *buffer,
                   CoreSurfaceAllocation *allocation,
                   void                  *alloc_data )
{
     DFBResult          ret;
     CoreSurface       *surface;
     SDLAllocationData *alloc = alloc_data;

     D_DEBUG_AT( SDL_Pool, "%s()\n", __FUNCTION__ );

     D_MAGIC_ASSERT( pool, CoreSurfacePool );
     D_MAGIC_ASSERT( buffer, CoreSurfaceBuffer );

     surface = buffer->surface;
     D_MAGIC_ASSERT( surface, CoreSurface );

     if (surface->type & CSTF_LAYER) {
          dfb_sdl->screen = NULL; /* clear? */

          ret = dfb_sdl_set_video_mode( dfb_sdl_core, &surface->config );
          if (ret) {
               D_DERROR( ret, "SDL/Surface: dfb_sdl_set_video_mode() failed!\n" );
               return ret;
          }

          D_ASSERT( dfb_sdl->screen != NULL );

          if (!dfb_sdl->screen) {
               D_ERROR( "SDL/Surface: No screen surface!?\n" );
               return DFB_BUG;
          }

          alloc->sdl_surf = dfb_sdl->screen;

          D_DEBUG_AT( SDL_Pool, "  -> screen surface  %dx%d, %d, 0x%08x, pitch %d\n",
                      dfb_sdl->screen->w, dfb_sdl->screen->h, dfb_sdl->screen->format->BitsPerPixel,
                      dfb_sdl->screen->flags, dfb_sdl->screen->pitch );

          allocation->flags |= CSALF_ONEFORALL;
     }
     else {
          DFBSurfacePixelFormat  format = surface->config.format;
          Uint32                 flags  = SDL_HWSURFACE;// | SDL_ASYNCBLIT | SDL_FULLSCREEN;
          Uint32                 rmask;
          Uint32                 gmask;
          Uint32                 bmask;
          Uint32                 amask;

          if (surface->config.caps & DSCAPS_FLIPPING)
               flags |= SDL_DOUBLEBUF;

          switch (format) {
               case DSPF_A8:
                    rmask = 0x00;
                    gmask = 0x00;
                    bmask = 0x00;
                    amask = 0xff;
                    break;

               case DSPF_RGB16:
                    rmask = 0xf800;
                    gmask = 0x07e0;
                    bmask = 0x001f;
                    amask = 0x0000;
                    break;

               case DSPF_RGB32:
                    rmask = 0x00ff0000;
                    gmask = 0x0000ff00;
                    bmask = 0x000000ff;
                    amask = 0x00000000;
                    break;

               case DSPF_ARGB:
                    rmask = 0x00ff0000;
                    gmask = 0x0000ff00;
                    bmask = 0x000000ff;
                    amask = 0xff000000;
                    break;

               default:
                    D_ERROR( "SDL/Surface: %s() has no support for %s!\n",
                             __FUNCTION__, dfb_pixelformat_name(format) );
                    return DFB_UNSUPPORTED;
          }

          D_DEBUG_AT( SDL_Pool, "  -> SDL_CreateRGBSurface( 0x%08x, "
                      "%dx%d, %d, 0x%08x, 0x%08x, 0x%08x, 0x%08x )\n",
                      flags, surface->config.size.w, surface->config.size.h,
                      DFB_BITS_PER_PIXEL(format), rmask, gmask, bmask, amask );

          alloc->sdl_surf = SDL_CreateRGBSurface( flags,
                                                  surface->config.size.w,
                                                  surface->config.size.h,
                                                  DFB_BITS_PER_PIXEL(format),
                                                  rmask, gmask, bmask, amask );
          if (!alloc->sdl_surf) {
               D_ERROR( "SDL/Surface: SDL_CreateRGBSurface( 0x%08x, "
                        "%dx%d, %d, 0x%08x, 0x%08x, 0x%08x, 0x%08x ) failed!\n",
                        flags, surface->config.size.w, surface->config.size.h,
                        DFB_BITS_PER_PIXEL(format), rmask, gmask, bmask, amask );

               return DFB_FAILURE;
          }
     }

     D_MAGIC_SET( alloc, SDLAllocationData );

     return DFB_OK;
}
GLuint RenderManagerGL2D::loadTexture(SDL_Surface *surface, 
	bool specular)
{
	SDL_Surface* textureSurface;
	SDL_Surface* convertedTexture;
	
	textureSurface = surface;

	// Determine size of padding for 2^n format
	int oldX = textureSurface->w;
	int oldY = textureSurface->h;
	int paddedX = getNextPOT(textureSurface->w);
	int paddedY = getNextPOT(textureSurface->h);

	SDL_Rect targetRect;
	targetRect.w = oldX;
	targetRect.h = oldY;
	targetRect.x = (paddedX - oldX) / 2;
	targetRect.y = (paddedY - oldY) / 2;

	SDL_SetColorKey(textureSurface, SDL_SRCCOLORKEY, 
			SDL_MapRGB(textureSurface->format, 0, 0, 0));
	convertedTexture = 
		SDL_CreateRGBSurface(SDL_SWSURFACE,
			paddedX, paddedY, 32,
#if SDL_BYTEORDER == SDL_BIG_ENDIAN
			0xff000000, 0x00ff0000, 0x0000ff00, 0x000000ff);
#else
			0x000000ff, 0x0000ff00, 0x00ff0000, 0xff000000);
#endif
	SDL_BlitSurface(textureSurface, 0, convertedTexture, &targetRect);

	if (specular)
	{
		for (int y = 0; y < convertedTexture->h; ++y)
		for (int x = 0; x < convertedTexture->w; ++x)
		{
			SDL_Color* pixel = 
				&(((SDL_Color*)convertedTexture->pixels)
				[y * convertedTexture->w +x]);
			int luminance = int(pixel->r) * 5 - 4 * 256 - 138;
			luminance = luminance > 0 ? luminance : 0;
			luminance = luminance < 255 ? luminance : 255;
			pixel->r = luminance;
			pixel->g = luminance;
			pixel->b = luminance;
		}
	}

	GLuint texture;
	glGenTextures(1, &texture);
	glBindTexture(texture);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
	glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8,
			convertedTexture->w, convertedTexture->h, 0, GL_RGBA,
			GL_UNSIGNED_BYTE, convertedTexture->pixels);
	SDL_FreeSurface(textureSurface);
	SDL_FreeSurface(convertedTexture);
	
	return texture;
}
Example #18
0
// WARNING:
//      This function contains an unusual amount of raw pointers, and is
//      the most C-like function you can get without being C++.
//      Sorry Joshua.
void Text::render() {
    int width = this->width;
    int height = this->height;
    std::pair<int,int> window_size = window->get_window_size();
    // Automatic sizing if dimension is 0.
    if (width == 0) {
        switch (alignment_h) {
        default:
        case Alignment::LEFT:
            width = window_size.first - this->x;
            break;
        case Alignment::CENTRE:
            width = ((window_size.first / 2) < this->x) ? this->x
                                                        : window_size.first - this->x;
            break;
        case Alignment::RIGHT:
            width = this->x;
            break;
        }
    }
    if (height == 0) {
        switch (alignment_v) {
        default:
        case Alignment::TOP:
            height = this->y;
            break;
        case Alignment::CENTRE:
            height = ((window_size.second / 2) < this->y) ? window_size.second - this->y
                                                          : this->y;
            break;
        case Alignment::BOTTOM:
            height = window_size.second - this->y;
            break;
        }
    }

    // If they are still zero, don't continue.
    if (width == 0 || height == 0) {
        throw Text::RenderException("Invalid dimensions after auto-sizing.");
    }

    int available_width = width;
    // It took a whole day to discover that there was a bug in
    // SDL_ttf. Starting with certain characters on certain
    // fonts seems to break it. :(
    // As a hack, prepend and (for balance) append a space.
    int border;
    TTF_SizeUTF8(font.font, " ", &border, NULL);
    border *= 2;

    // If they are still zero, don't continue.
    if (available_width <= 0) {
        throw Text::RenderException("No available width for rendering text.");
    }

    int line_height = TTF_FontHeight(font.font);
    int line_number = 0;
    int lost_lines = 0;

    int used_width = 0;

    int length = (int)text.length();
    // Entire text.
    const char* ctext = text.c_str();

    // Line of text.
    char* line = new char[length+1];

    // Null-terminator separated lines of text.
    // The worst case is a character per line, so we need to do
    // 2 * length (character, null, character, null, ...).
    char* lines = new char[2*length+1];
    // Pointer to within lines.
    char* lines_scan = lines;

    // Text indexing.
    for (int t = 0; t < length; t++) {
        int line_width = 0;
        // Word indexing.
        int w = 0;
        // Stores (from the beginning) a word in ctext (copy).
        line[0] = '\0';
        // Points to the end of the last successfully fitting word in
        // line.
        int ll = 0;

        // Line indexing.
        for (int l = t; l < length; l++) {
            // Find word end.
            for (w = l; w < length && (ctext[w] != ' ' && ctext[w] != '\n'); w++) {
                // As we are dealing with UTF-8, we must make sure to
                // copy an entire character if it is more than one byte.
                // The bit formats of UTF-8 characters are:
                // 0xxxxxxx
                // 110xxxxx 10xxxxxx
                // 1110xxxx 10xxxxxx 10xxxxxx
                // 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
                // 111110xx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx
                // 1111110x 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx
                //
                // ... Well, actually it's not THAT simple, because
                // there are these magical characters which modify other
                // characters... But it's not worth the effort.
                if (ctext[l] & 0x80) {
                    // The number of bits in the first byte set to 1
                    // before the first zero indicate the total number
                    // of bytes to use for the UTF-8 character.
                    for (int bits = ctext[w] << 1; w < length && (bits & 0x80); w++, bits <<= 1);
                }
            }
            // Copy word into line.
            for (; l < w; l++) {
                line[l - t] = ctext[l];
            }
            line[l - t] = '\0';
            // Test line length.
            TTF_SizeUTF8(font.font, line, &line_width, NULL);
            // Part of SDL_ttf bug workaround.
            line_width+=border;
            if (line_width <= available_width) {
                if (line_width > used_width) {
                    used_width = line_width;
                }
                // Mark current position as valid.
                ll = l - t;
                // If this is the end of a line, or whole text, stop.
                if (ctext[w] == '\n' || ctext[w] == '\0') {
                    t = l;
                    // Note the string is already null terminated.
                    break;
                }
                else {
                    // Replace null terminator with word separator.
                    line[ll] = ctext[w];
                }
            }
            else {
                if (ll > 0) {
                    // There are some fittable words.
                    // As the line overflows with the current l, set the
                    // text index to the last fit.
                    t += ll;
                }
                else {
                    // There are no separators to break on.
                    // We're going to have to cut a word in half.

                    // Swapped-out character
                    char c;
                    int left = 0;
                    int right = l - t;
                    // Search index within line.
                    int ls;
                    ll = 0;
                    for (ls = (right + left) / 2; ls != ll; ls = (right + left) / 2) {
                        ll = ls;
                        c = line[ls];
                        line[ls] = 0;
                        TTF_SizeUTF8(font.font, line, &line_width, NULL);
                        // Part of SDL_ttf bug workaround.
                        line_width+=border;
                        if (line_width <= available_width) {
                            if (line_width > used_width) {
                                used_width = line_width;
                            }
                            left = ls;
                        }
                        else {
                            right = ls;
                        }
                        line[ls] = c;
                    }
                    // Don't skip the non-separating character.
                    t += ll - 1;
                }
                // Null terminate for rendering.
                line[ll] = '\0';
                break;
            }
        }

        // Copy the line into lines (using lines_scan).
        int i;
        for (i = 0; line[i] != '\0'; ++i) {
            lines_scan[i] = line[i];
        }
        lines_scan[i] = '\0';
        lines_scan = &lines_scan[i+1];

        ++line_number;
        if (line[0] == '\0') {
            // Check that we aren't going to chase our tailes trying to fit an unfittable character.
            if (ctext[w] != '\n') {
                LOG(WARNING) << "Cannot render text: character too large.";
                delete[] line;
                delete[] lines;
                throw Text::RenderException("A character is too large");
            }
            else {
                // It's a blank line.
                continue;
            }
        }
    }
    int line_count = line_number;

    int used_height = line_count * line_height;

    used_width += border;

    image = Image(used_width, (used_height < height) ? used_height : height, true);
    uint8_t clear_colour[4] = {rgba[0], rgba[1], rgba[2], 0x00};
    uint8_t clear_mask[4] = {0xff, 0xff, 0xff, 0xff};
    image.clear(clear_colour, clear_mask);
    // image.clear(0xffffff00, 0xffffffff);

    // Render all lines of text.
    SDL_Color blank;
    blank.r = blank.g = blank.b = blank.a = 0;
    SDL_Color colour;
    colour.r = rgba[0];
    colour.g = rgba[1];
    colour.b = rgba[2];
    colour.a = rgba[3];
    lines_scan = lines;
    for (int line_number = 0; line_number < line_count; ++line_number) {
        // Render line
        VLOG(2) << "Rendering line of text: \"" << lines_scan << "\".";
        if (lines_scan[0] == '\0') {
            // Skip it - it's a new line.
            lines_scan = &lines_scan[1];
            continue;
        }

        SDL_Surface* rendered_line;
        {
            // It took a whole day to discover that there was a bug in
            // SDL_ttf. Starting with certain characters on certain
            // fonts seems to break it. :(
            // As a hack, prepend and (for balance) append a space.
            std::stringstream safe;
            safe << " " << lines_scan << " ";
            std::string safe_str(safe.str());
            if (smooth) {
                rendered_line = TTF_RenderUTF8_Shaded(font.font, safe_str.c_str(), colour, blank);
            }
            else {
                rendered_line = TTF_RenderUTF8_Solid(font.font, safe_str.c_str(), colour);
            }
        }

        if (rendered_line == nullptr) {
            LOG(WARNING) << "Cannot render line of text: \"" << lines_scan << "\".";
            delete[] line;
            delete[] lines;
            throw Text::RenderException("Cannot render line of text");
        }

#ifdef TEXT_SAFE_SURFACE
        // This surface has a known format.
        SDL_Surface* compatible = SDL_CreateRGBSurface(0, // Unsed
                                                       rendered_line->w,
                                                       rendered_line->h,
                                                       32,
                                                       0x00,
                                                       0x00,
                                                       0x00,
                                                       0xff
                                                       );
        SDL_FillRect(compatible, NULL, 0);
        SDL_SetSurfaceBlendMode(rendered_line, SDL_BLENDMODE_NONE);
        SDL_BlitSurface(rendered_line, NULL, compatible, NULL);
        SDL_LockSurface(compatible);
        // pitch is in bytes, not pixels. RGBA = 4 bytes.
        int jump = compatible->pitch / 4;
#else
        SDL_LockSurface(rendered_line);
        int jump = rendered_line->pitch;
#endif
        // "What is this pointless copy?" you might ask.
        //   Well, it is a suggestion to the c++ compiler that smooth
        //   will not change throughout this function, so it can
        //   optimise the if containing _smooth out of the for loop
        //   entirely, rather than checking it every single iteration.
        int _smooth = smooth;
        int x_offset;
        int y_offset;
        switch (alignment_h) {
        default:
        case Alignment::LEFT:
            x_offset = 0;
            break;
        case Alignment::CENTRE:
            x_offset = (used_width - rendered_line->w) / 2;
            break;
        case Alignment::RIGHT:
            x_offset = used_width - rendered_line->w;
            break;
        }
        switch (alignment_v) {
        default:
        case Alignment::TOP:
            y_offset = line_number * line_height;
            break;
        case Alignment::CENTRE:
            y_offset = line_number * line_height - (used_height - image.height) / 2;
            break;
        case Alignment::BOTTOM:
            y_offset = line_number * line_height - (used_height - image.height);
            break;
        }
        // x surface
        int xs;
        // y surface
        int ys;
        for (ys = 0; ys < rendered_line->h; ++ys) {
            int yi = ys + y_offset;
            if (yi >= image.height) {
                lost_lines++;
                break;
            }
            else if (yi < 0) {
                continue;
            }
            int begin_xs((x_offset >= 0) ? 0 : -x_offset);
            int end_xs((rendered_line->w < image.width - x_offset) ? rendered_line->w : image.width - x_offset);
            for (xs = begin_xs; xs < end_xs; ++xs) {
#ifdef TEXT_SAFE_SURFACE
                image.flipped_pixels[yi][xs + x_offset].a = (((Uint32*)compatible->pixels)[(ys*jump + xs)]);
#else
                if (_smooth) {
                    image.flipped_pixels[yi][xs + x_offset].a = (((Uint8*)rendered_line->pixels)[(ys*jump + xs)]);
                }
                else {
                    image.flipped_pixels[yi][xs + x_offset].a = (((Uint8*)rendered_line->pixels)[(ys*jump + xs)]) ? 255 : 0;
                }
#endif
            }
        }
#ifdef TEXT_SAFE_SURFACE
        SDL_UnlockSurface(compatible);
        SDL_FreeSurface(compatible);
#else
        SDL_UnlockSurface(rendered_line);
#endif
        SDL_FreeSurface(rendered_line);
        if (ys < line_height) {
            LOG(WARNING) << "Text overflow.";
            break;
        }

        // Set lines_scan to start next line
        while (lines_scan[0] != '\0') {
            lines_scan = &lines_scan[1];
        }
        lines_scan = &lines_scan[1];
    }

    this->used_width  = used_width;
    this->used_height = used_height;
    delete[] line;
    delete[] lines;
    generate_texture();
    dirty_texture = false;
    dirty_vbo = true;
}
Example #19
0
int main(int argc, char *argv[])
{
    Uint32 initflags = SDL_INIT_VIDEO; //| SDL_DOUBLEBUF;  /* See documentation for details */
    SDL_Surface *ecran, *rectangle, *board, *texte1; // quelques surfaces

    Dimensions fenetre; // main window
   
    fenetre.h = WINHI;  // en pixels
    fenetre.w = WINWI;   

    Uint8  video_bpp = 32; // 32 bits de couleur

    Uint32 videoflags = SDL_HWSURFACE; // utiliser la mémoire vidéo

    Uint32 vert, rouge; // des variables pour des couleurs

    bool continuer; // pour la boucle principale des évènements
    
    SDL_Event event; // aussi
 
    /* Initialize the SDL library */
    if ( SDL_Init(initflags) < 0 )
    {
        fprintf(stderr, "N'arrive pas a` initialiser la SDL : %s\n", SDL_GetError());
        exit(1);
    }
 
    /* Set video mode */
    ecran = SDL_SetVideoMode(fenetre.w, fenetre.h, video_bpp, videoflags); // surface principale

    if (ecran == NULL)
    {
        fprintf(stderr, "N'arrive pas a` etablir mode video%dx%dx%d : %s\n", fenetre.w, fenetre.h, video_bpp, SDL_GetError());
        SDL_Quit();
        exit(2);
    }

    vert = SDL_MapRGB(ecran->format,0,128,0); // c'est du vert
    rouge = SDL_MapRGB(ecran->format,255,0,0); // c'est du rouge

    SDL_FillRect(ecran,NULL,vert); // de la couleur dans le fond de la fenêtre principale
    SDL_WM_SetCaption("Jeu de Hex", NULL); // legende de la fenêtre

    // Une autre surface avec du texte
    TTF_Init();
    
    TTF_Font *fontMenu = TTF_OpenFont("CAC-Champagne/cac_champagne.ttf",60); // charger une fonte (un peu moche)
    SDL_Color fontBlack = {0,0,0};
    texte1 = TTF_RenderText_Blended(fontMenu,"Projet Hex !",fontBlack);

    // encore une surface
    rectangle = SDL_CreateRGBSurface(initflags,225,80,video_bpp,0,0,0,0); // une autre surface pour inclure dans l'autre
    SDL_FillRect(rectangle,NULL,rouge); // un fond rouge

    // position des surfaces
    SDL_Rect posRect, posTexte1;
    posRect.x = 20;
    posRect.y = 80;

    posTexte1.x = 25;
    posTexte1.y = 85;

    SDL_BlitSurface(rectangle,NULL,ecran,&posRect); // on associe avec la fenêtre principale
    SDL_BlitSurface(texte1,NULL,ecran,&posTexte1); // idem pour superposer avec la précédente

    // Affichage du plateau de jeu
    board = IMG_Load("Images/hex.png");    // plateau de jeu la taille en pixels est celle de l'image
    SDL_Rect posBoard;                     // sa position
    posBoard.x = 280;
    posBoard.y = 100;
    SDL_BlitSurface(board,NULL,ecran,&posBoard); // on l'associe avec la surface principale

    // affichage du pion bleu
    SDL_Surface *pionBleu;
    pionBleu = IMG_Load("Images/button-blue22.png");
    SDL_Rect posPionBleu;               
    posPionBleu.x = 385;
    posPionBleu.y = 149;
    SDL_BlitSurface(pionBleu,NULL,ecran,&posPionBleu);

    // Affichege du pion rouge
    SDL_Surface *pionRouge = IMG_Load("Images/button-red22.png");
    SDL_Rect posPionRouge;               
    posPionRouge.x = 543;
    posPionRouge.y = 273;
    SDL_BlitSurface(pionRouge,NULL,ecran,&posPionRouge);

    SDL_Flip(ecran); //maj des surfaces
 
 // boucle des évènements
    continuer = true; // un furieux du c ferait plutôt une boucle infinie. Je préfère rester correct.
    SDLKey key_pressed ;
    while (continuer)
    {
        while ( SDL_PollEvent(&event))
        {
            switch (event.type)
            {
                case SDL_MOUSEMOTION:
                    printf("Ça bouge\n"); // sans intérêt, c'est juste pour montrer
                    break;
                case SDL_MOUSEBUTTONDOWN:
                    if (event.button.button == SDL_BUTTON_LEFT)
                    {   
                        int clicX = event.motion.x;
                        int clicY = event.motion.y;
                        printf("X=%d Y=%d\n",clicX,clicY); // on récupère les coordonnées du clic
                    }
                    break;
                case SDL_KEYDOWN:
                    key_pressed = event.key.keysym.sym; // on récupère la touche
                    switch (key_pressed)
                    {
                    case SDLK_ESCAPE: /* Esc keypress quits the app... */
                        continuer = false;
                        break;
                    case SDLK_LEFT:
                        printf("left +1\n"); // par exemple
                        break;
                    case SDLK_RIGHT:
                        printf("right +1\n"); 
                        break;
                    case SDLK_UP:
                        printf("up +1\n");
                        break;
                    case SDLK_DOWN:
                        printf("down +1\n");
                        break;
                    }
                    break;
                case SDL_QUIT:
                    continuer = false;
                    break;
                default:
                    break;
            }
        }
        // refresh screen
        // mettre ici tous les blit utiles s'il y a des changements dans les surfaces, board, nouveaux pions
        SDL_Flip(ecran); //maj des surfaces pour affichage
    }
    //
    /* Clean up the SDL library */
    SDL_FreeSurface(ecran);
    SDL_FreeSurface(rectangle);
    SDL_FreeSurface(board);
    TTF_CloseFont(fontMenu);
    SDL_FreeSurface(texte1);
    TTF_Quit();
    SDL_Quit();
    return(0);
}
Example #20
0
SDL_Surface *DIB_SetVideoMode(_THIS, SDL_Surface *current,
				int width, int height, int bpp, Uint32 flags)
{
	SDL_Surface *video;
	Uint32 prev_flags;
	DWORD style;
	const DWORD directstyle =
			(WS_POPUP);
	const DWORD windowstyle = 
			(WS_OVERLAPPED|WS_CAPTION|WS_SYSMENU|WS_MINIMIZEBOX);
	const DWORD resizestyle =
			(WS_THICKFRAME|WS_MAXIMIZEBOX);
	int binfo_size;
	BITMAPINFO *binfo;
	HDC hdc;
	RECT bounds;
	int x, y;
	Uint32 Rmask, Gmask, Bmask;
#ifdef HAVE_OPENGL //maks
	/* Clean up any GL context that may be hanging around */
	if ( current->flags & SDL_OPENGL ) { //maks: close only in viewo quit to avoid texture lost when go to game mode
		WIN_GL_ShutDown(this);
	}
#endif

	/* Recalculate the bitmasks if necessary */
	if ( bpp == current->format->BitsPerPixel ) {
		video = current;
	} else {
		switch (bpp) {
			case 15:
			case 16:
				if ( DIB_SussScreenDepth() == 15 ) {
					/* 5-5-5 */
					Rmask = 0x00007c00;
					Gmask = 0x000003e0;
					Bmask = 0x0000001f;
				} else {
					/* 5-6-5 */
					Rmask = 0x0000f800;
					Gmask = 0x000007e0;
					Bmask = 0x0000001f;
				}
				break;
			case 24:
			case 32:
				/* GDI defined as 8-8-8 */
				Rmask = 0x00ff0000;
				Gmask = 0x0000ff00;
				Bmask = 0x000000ff;
				break;
			default:
				Rmask = 0x00000000;
				Gmask = 0x00000000;
				Bmask = 0x00000000;
				break;
		}
		video = SDL_CreateRGBSurface(SDL_SWSURFACE,
					0, 0, bpp, Rmask, Gmask, Bmask, 0);
		if ( video == NULL ) {
			SDL_OutOfMemory();
			return(NULL);
		}
	}

	/* Fill in part of the video surface */
	prev_flags = video->flags;
	video->flags = 0;	/* Clear flags */
	video->w = width;
	video->h = height;
	video->pitch = SDL_CalculatePitch(video);

#ifdef WIN32_PLATFORM_PSPC
	 /* Stuff to hide that $#!^%#$ WinCE taskbar in fullscreen... */
	if ( flags & SDL_FULLSCREEN ) {
		if ( !(prev_flags & SDL_FULLSCREEN) ) {
			SHFullScreen(SDL_Window, SHFS_HIDETASKBAR);
			SHFullScreen(SDL_Window, SHFS_HIDESIPBUTTON);
			ShowWindow(FindWindow(TEXT("HHTaskBar"),NULL),SW_HIDE);
		}
		video->flags |= SDL_FULLSCREEN;
	} else {
		if ( prev_flags & SDL_FULLSCREEN ) {
			SHFullScreen(SDL_Window, SHFS_SHOWTASKBAR);
			SHFullScreen(SDL_Window, SHFS_SHOWSIPBUTTON);
			ShowWindow(FindWindow(TEXT("HHTaskBar"),NULL),SW_SHOWNORMAL);
		}
	}
#endif
#ifndef NO_CHANGEDISPLAYSETTINGS
	/* Set fullscreen mode if appropriate */
	if ( (flags & SDL_FULLSCREEN) == SDL_FULLSCREEN ) {
		DEVMODE settings;

		memset(&settings, 0, sizeof(DEVMODE));
		settings.dmSize = sizeof(DEVMODE);
		settings.dmBitsPerPel = video->format->BitsPerPixel;
		settings.dmPelsWidth = width;
		settings.dmPelsHeight = height;
		settings.dmFields = DM_PELSWIDTH | DM_PELSHEIGHT | DM_BITSPERPEL;
		if ( ChangeDisplaySettings(&settings, CDS_FULLSCREEN) == DISP_CHANGE_SUCCESSFUL ) {
			video->flags |= SDL_FULLSCREEN;
			SDL_fullscreen_mode = settings;
		}
	}
#endif /* !NO_CHANGEDISPLAYSETTINGS */

	/* Reset the palette and create a new one if necessary */
	if ( screen_pal != NULL ) {
	/*	RJR: March 28, 2000
		delete identity palette if switching from a palettized mode */
		DeleteObject(screen_pal);
		screen_pal = NULL;
	}
	if ( bpp <= 8 )
	{
	/*	RJR: March 28, 2000
		create identity palette switching to a palettized mode */
		screen_pal = DIB_CreatePalette(bpp);
	}

	style = GetWindowLong(SDL_Window, GWL_STYLE);
	style &= ~(resizestyle|WS_MAXIMIZE);
	if ( (video->flags & SDL_FULLSCREEN) == SDL_FULLSCREEN ) {
		style &= ~windowstyle;
		style |= directstyle;
	} else {
#ifndef NO_CHANGEDISPLAYSETTINGS
		if ( (prev_flags & SDL_FULLSCREEN) == SDL_FULLSCREEN ) {
			ChangeDisplaySettings(NULL, 0);
		}
#endif
		if ( flags & SDL_NOFRAME ) {
			style &= ~windowstyle;
			style |= directstyle;
			video->flags |= SDL_NOFRAME;
		} else {
			style &= ~directstyle;
			style |= windowstyle;
			if ( flags & SDL_RESIZABLE ) {
				style |= resizestyle;
				video->flags |= SDL_RESIZABLE;
			}
		}
#if WS_MAXIMIZE
		if (IsZoomed(SDL_Window)) style |= WS_MAXIMIZE;
#endif
	}

	/* DJM: Don't piss of anyone who has setup his own window */
	if ( SDL_windowid == NULL )
		SetWindowLong(SDL_Window, GWL_STYLE, style);

	/* Delete the old bitmap if necessary */
	if ( screen_bmp != NULL ) {
		DeleteObject(screen_bmp);
	}
	if ( ! (flags & SDL_OPENGL) ) {
		BOOL is16bitmode = (video->format->BytesPerPixel == 2);

		/* Suss out the bitmap info header */
		binfo_size = sizeof(*binfo);
		if( is16bitmode ) {
			/* 16bit modes, palette area used for rgb bitmasks */
			binfo_size += 3*sizeof(DWORD);
		} else if ( video->format->palette ) {
			binfo_size += video->format->palette->ncolors *
							sizeof(RGBQUAD);
		}
		binfo = (BITMAPINFO *)malloc(binfo_size);
		if ( ! binfo ) {
			if ( video != current ) {
				SDL_FreeSurface(video);
			}
			SDL_OutOfMemory();
			return(NULL);
		}

		binfo->bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
		binfo->bmiHeader.biWidth = video->w;
		binfo->bmiHeader.biHeight = -video->h;	/* -ve for topdown bitmap */
		binfo->bmiHeader.biPlanes = 1;
		binfo->bmiHeader.biSizeImage = video->h * video->pitch;
		binfo->bmiHeader.biXPelsPerMeter = 0;
		binfo->bmiHeader.biYPelsPerMeter = 0;
		binfo->bmiHeader.biClrUsed = 0;
		binfo->bmiHeader.biClrImportant = 0;
		binfo->bmiHeader.biBitCount = video->format->BitsPerPixel;

		if ( is16bitmode ) {
			/* BI_BITFIELDS tells CreateDIBSection about the rgb masks in the palette */
			binfo->bmiHeader.biCompression = BI_BITFIELDS;
			((Uint32*)binfo->bmiColors)[0] = video->format->Rmask;
			((Uint32*)binfo->bmiColors)[1] = video->format->Gmask;
			((Uint32*)binfo->bmiColors)[2] = video->format->Bmask;
		} else {
			binfo->bmiHeader.biCompression = BI_RGB;	/* BI_BITFIELDS for 565 vs 555 */
			if ( video->format->palette ) {
				memset(binfo->bmiColors, 0,
					video->format->palette->ncolors*sizeof(RGBQUAD));
			}
		}

		/* Create the offscreen bitmap buffer */
		hdc = GetDC(SDL_Window);
		screen_bmp = CreateDIBSection(hdc, binfo, DIB_RGB_COLORS,
					(void **)(&video->pixels), NULL, 0);
		ReleaseDC(SDL_Window, hdc);
		free(binfo);
		if ( screen_bmp == NULL ) {
			if ( video != current ) {
				SDL_FreeSurface(video);
			}
			SDL_SetError("Couldn't create DIB section");
			return(NULL);
		}
		this->UpdateRects = DIB_NormalUpdate;

		/* Set video surface flags */
		if ( bpp <= 8 ) {
			/* BitBlt() maps colors for us */
			video->flags |= SDL_HWPALETTE;
		}
	}

	/* Resize the window */
	if ( SDL_windowid == NULL ) {
		HWND top;
		UINT swp_flags;
		const char *window = getenv("SDL_VIDEO_WINDOW_POS");
		const char *center = getenv("SDL_VIDEO_CENTERED");

		if ( !SDL_windowX && !SDL_windowY ) {
			if ( window ) {
				if ( sscanf(window, "%d,%d", &x, &y) == 2 ) {
					SDL_windowX = x;
					SDL_windowY = y;
				}
				if ( strcmp(window, "center") == 0 ) {
					center = window;
					window = NULL;
				}
			}
		}
		swp_flags = (SWP_NOCOPYBITS | SWP_SHOWWINDOW);

		SDL_resizing = 1;
		bounds.left = SDL_windowX;
		bounds.top = SDL_windowY;
		bounds.right = SDL_windowX+video->w;
		bounds.bottom = SDL_windowY+video->h;
		AdjustWindowRectEx(&bounds, GetWindowLong(SDL_Window, GWL_STYLE), FALSE, 0);
		width = bounds.right-bounds.left;
		height = bounds.bottom-bounds.top;
		if ( (flags & SDL_FULLSCREEN) ) {
			x = (GetSystemMetrics(SM_CXSCREEN)-width)/2;
			y = (GetSystemMetrics(SM_CYSCREEN)-height)/2;
		} else if ( SDL_windowX || SDL_windowY || window ) {
			x = bounds.left;
			y = bounds.top;
		} else if ( center ) {
			x = (GetSystemMetrics(SM_CXSCREEN)-width)/2;
			y = (GetSystemMetrics(SM_CYSCREEN)-height)/2;
		} else {
			x = y = -1;
			swp_flags |= SWP_NOMOVE;
		}
		if ( y < 0 ) { /* Cover up title bar for more client area */
			y -= GetSystemMetrics(SM_CYCAPTION)/2;
		}
		if ( flags & SDL_FULLSCREEN ) {
			top = HWND_TOPMOST;
		} else {
			top = HWND_NOTOPMOST;
		}
		SetWindowPos(SDL_Window, top, x, y, width, height, swp_flags);
		SDL_resizing = 0;
		SetForegroundWindow(SDL_Window);
	}
#ifdef HAVE_OPENGL //maks
	/* Set up for OpenGL */
	if ( flags & SDL_OPENGL ) 
	{
		/*if ( WIN_GL_SetupWindow(this) < 0 ) {
			return(NULL);
		}

		video->flags |= SDL_OPENGL;*/

		if ( WIN_GL_SetupWindow(this) >= 0 )
		{
			video->flags |= SDL_OPENGL;
		}
	}
#endif

	/* We're live! */
	return(video);
}
Example #21
0
//Private
sFont cFontManager::GenerateFont(TTF_Font *font, int size){
	sFont tFont;
	int tmpWidth = size; 
	int tmpHeight = TTF_FontHeight(font);
	tFont.newLine = tmpHeight;
    Uint32 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
    int xMax = 0, yMax = 0;
	SDL_Surface *tmpSurface = SDL_CreateRGBSurface(0, 
					1024, 1024, 32, rmask, gmask, bmask, amask);
	xMax = 1024 / tmpWidth;
	yMax = 1024 / tmpHeight;
	SDL_FillRect(tmpSurface, NULL, SDL_MapRGBA(tmpSurface->format, 255, 255, 255, 0));

	SDL_Rect tmpRect = {0, 0, tmpWidth, tmpHeight};
	SDL_Color color = {255, 255, 255};
	std::vector<std::string> horLines;	//[0] Holds all character on first horizontal line
	std::vector<std::vector<sRect> > horLinesRect;//Holds position and size for each character
	bool isDone = false;
	uint tmpP = 0;						//Temp pointer for chars array
	for(int i = 0; i < yMax && !isDone; i++){
		tmpRect.y = (int)(i * tmpHeight);
		std::string tmpLine = "";
		std::vector<sRect> tmpRectVec;
		for(int j = 0; j < xMax; j++){
			tmpRect.x = (int)(j * tmpWidth);
			if(tmpP < chars.size() - 1){
				SDL_Surface *tmpSur;
				int minX = 0, maxX = 0, minY = 0, maxY = 0;;
				sRect tRect;
				tRect.x = tmpRect.x;
				tRect.y = tmpRect.y;
				tRect.w = 0;
				tRect.h = tmpRect.h;
				if(IsUtf8(chars, tmpP)){
					std::string ts = chars.substr(tmpP, 2);
					tmpSur = TTF_RenderUTF8_Solid(font, (char*)ts.c_str(), color);
					Uint16 ch = ts.c_str()[0] + ts.c_str()[1];
					ch =(ch<<8) | ts.c_str()[1];	//This may not work 
					ch =(ch<<8) | ts.c_str()[0];
					TTF_GlyphMetrics(font, ch, &minX, &maxX, &minY, &maxY, NULL);
					tmpP += 2;
					tmpLine += ts;
				}else{
					char tmpC[2];
					tmpC[0] = chars.at(tmpP);
					tmpC[1] = '\0';
					tmpSur = TTF_RenderUTF8_Solid(font, (char*)tmpC, color);
					TTF_GlyphMetrics(font, tmpC[0], &minX, &maxX, &minY, &maxY, NULL);
					if(tmpC[0] == 'j' || tmpC[0] == 'J'){
						maxX += 2;
					}
					tmpLine += chars.at(tmpP);
					tmpP += 1;
				}
				//tRect.y += maxY;
				tRect.x += minX;
				tRect.w = maxX - minX;
				tmpRectVec.push_back(tRect);
				SDL_BlitSurface(tmpSur, NULL, tmpSurface, &tmpRect);
				SDL_FreeSurface(tmpSur);
			}else{
				isDone = true;
				break;
			}
		}
		horLines.push_back(tmpLine);
		horLinesRect.push_back(tmpRectVec);
		tmpRectVec.clear();
	}

	tFont.spacing = DEF_SPACING;
	tFont.size = size;
	tFont.texture = tManager->LoadTextureFromMemory(tmpSurface);
	for(int i = 0; i < (int)horLinesRect.size(); i++){
		tmpP = 0;
		for(int j = 0; j < (int)horLinesRect[i].size(); j++){
			sRect *tmpR = &horLinesRect[i][j];
			uint tmpS = tManager->CreateSection(tFont.texture, 
												tmpR->x, tmpR->y, 
												tmpR->w, tmpR->h);
			if(IsUtf8(horLines[i], tmpP)){
				std::string tmpG = horLines[i].substr(tmpP, 2);
				tFont.glyphs[tmpG] = tmpS;
				tmpP += 2;
			}else{
				char tmpchar[2];
				tmpchar[0] = horLines[i].at(tmpP);
				tmpchar[1] = '\0';
				tFont.glyphs[(char*)tmpchar] = tmpS;
				tmpP += 1;
			}
		}
	}
	//SDL_SaveBMP(tmpSurface, "temp_font.bmp");
	SDL_FreeSurface(tmpSurface);
	return tFont;
}
//--------------------------------------------------
int Texture::loadFile(string pName)
{
	ErrorLog *log = ErrorLog::getInstance();
	stringstream logStream;

	logStream << "Load Texture " << pName.c_str() << endl;
	log->reportError(logStream.str());

	string name;
	name = "./Daten/Textures/";
	name.append(pName);
	name.append(".bmp");

	SDL_Surface *bitmap;													// SDL_Surface to load the image into
	SDL_Surface *conv;														// SDL_Surface to copy the image into (with correct color order)

	int pitch;																// Variable to store the length of one pixel-line
	int height_div_2;														// Variable to store the size of half the number of rows

	void* temp_row;															// Variable to store the pointer to a pixel-line

	bitmap = SDL_LoadBMP(name.c_str());										// Load image into an SDL_Surface

	if (!bitmap)															// If loading failed
	{																		//
		// print an error message
		logStream.str("");
		logStream << "Could not load BMP texture: " << name.c_str() << endl;
		log->reportError(logStream.str());
		return -1;															// and quit
	}

#if SDL_BYTEORDER == SDL_BIG_ENDIAN											// Select wether we use RGB or BGR mode 
	conv = SDL_CreateRGBSurface(SDL_SWSURFACE, bitmap->w, bitmap->h, 32, 0xff000000, 0x00ff0000, 0x0000ff00, 0x000000ff); // Create an SDL-Surface (big endian)
#else
	conv = SDL_CreateRGBSurface(SDL_SWSURFACE, bitmap->w, bitmap->h, 32, 0x000000ff, 0x0000ff00, 0x00ff0000, 0xff000000); // Create an SDL-Surface (little endian)
#endif

	SDL_BlitSurface(bitmap, 0, conv, 0);									// Copy the loaded image to the surface with the correct color order

	// Flip Loaded Bitmap upside down
	// (SDL and OpenGL use diffrent Coordinate Systems)
	////////////////////////////////////////////////////////
	pitch = conv->pitch;													// length of one pixel-line

	temp_row = (void *)malloc(pitch);										// Allocate memory for the inversion
	if (NULL == temp_row)													// If you're not able to allocate the memory
	{																		//
		//SDL_SetError("Not enough memory for image inversion");				// display an error message
		logStream.str("");
		logStream << "Not enough memory for image inversion" << endl;
		log->reportError(logStream.str());
	}
	height_div_2 = (int) (conv->h * .5);									// use only one half of the rows. (Works also with a odd number of rows)

	for (int index = 0; index < height_div_2; index++)							// for every line in the lower half swap it with the corresponding line
	{																		// in the upper half
		memcpy(
		    (Uint8 *)temp_row,												//
		    (Uint8 *)(conv->pixels) + pitch * index,						// copy one line from the first half to the temp variable
		    pitch);															// size of one line
		memcpy(
		    (Uint8 *)(conv->pixels) + pitch * index,						//
		    (Uint8 *)(conv->pixels) + pitch * (conv->h - index - 1),			// copy the corresponding line from the upper half to the line in the lower half
		    pitch);															// size of one line
		memcpy(
		    (Uint8 *)(conv->pixels) + pitch * (conv->h - index - 1),			//
		    temp_row,														// copy the tempvariable back to the corresponding line in the upper half
		    pitch);															// size of one line
	}
	free(temp_row);															// free allocated memory now that we don't need it anymore

	//use purple as transparent
	/*for (int i = 0;i < conv->w;i++)
	{
		for (int j = 0;j < conv->h;j++)
		{
			unsigned int color;
			color = ((unsigned int*)conv->pixels)[j*(conv->pitch/sizeof(unsigned int)) + i];
			color = color & 0x00ffffff;
			if (color == 16711935)
			{
				((unsigned int*)conv->pixels)[j*(conv->pitch/sizeof(unsigned int)) + i] = 0x00ffffff;
			}
		}
	}*/

	unsigned int texture;

	glGenTextures(1, &texture);
	glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
	glBindTexture(GL_TEXTURE_2D, texture);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);

	glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, conv->w, conv->h, 0, GL_RGBA, GL_UNSIGNED_BYTE, conv->pixels);	//copy the image into the texture
	SDL_FreeSurface(bitmap);
	SDL_FreeSurface(conv);

	return texture;

}
Example #23
0
VOID
PAL_EndingAnimation(
   VOID
)
/*++
  Purpose:

    Show the ending animation.

  Parameters:

    None.

  Return value:

    None.

--*/
{
   LPBYTE            buf;
   LPBYTE            bufGirl;
   SDL_Surface      *pUpper;
   SDL_Surface      *pLower;
   SDL_Rect          srcrect, dstrect;

   int               yPosGirl = 180;
   int               i;

   buf = (LPBYTE)UTIL_calloc(1, 64000);
   bufGirl = (LPBYTE)UTIL_calloc(1, 6000);

   pUpper = SDL_CreateRGBSurface(gpScreen->flags & ~SDL_HWSURFACE, 320, 200, 8,
      gpScreen->format->Rmask, gpScreen->format->Gmask,
      gpScreen->format->Bmask, gpScreen->format->Amask);

   pLower = SDL_CreateRGBSurface(gpScreen->flags & ~SDL_HWSURFACE, 320, 200, 8,
      gpScreen->format->Rmask, gpScreen->format->Gmask,
      gpScreen->format->Bmask, gpScreen->format->Amask);

   PAL_MKFDecompressChunk(buf, 64000, 61, gpGlobals->f.fpFBP);
   PAL_FBPBlitToSurface(buf, pUpper);

   PAL_MKFDecompressChunk(buf, 64000, 62, gpGlobals->f.fpFBP);
   PAL_FBPBlitToSurface(buf, pLower);

   PAL_MKFDecompressChunk(buf, 64000, 571, gpGlobals->f.fpMGO);
   PAL_MKFDecompressChunk(bufGirl, 6000, 572, gpGlobals->f.fpMGO);

   srcrect.x = 0;
   dstrect.x = 0;
   srcrect.w = 320;
   dstrect.w = 320;

   gpGlobals->wScreenWave = 2;

   for (i = 0; i < 400; i++)
   {
      //
      // Draw the background
      //
      srcrect.y = 0;
      srcrect.h = 200 - i / 2;

      dstrect.y = i / 2;
      dstrect.h = 200 - i / 2;

      SDL_BlitSurface(pLower, &srcrect, gpScreen, &dstrect);

      srcrect.y = 200 - i / 2;
      srcrect.h = i / 2;

      dstrect.y = 0;
      dstrect.h = i / 2;

      SDL_BlitSurface(pUpper, &srcrect, gpScreen, &dstrect);

      PAL_ApplyWave(gpScreen);

      //
      // Draw the beast
      //
      PAL_RLEBlitToSurface(PAL_SpriteGetFrame(buf, 0), gpScreen, PAL_XY(0, -400 + i));
      PAL_RLEBlitToSurface(PAL_SpriteGetFrame(buf, 1), gpScreen, PAL_XY(0, -200 + i));

      //
      // Draw the girl
      //
      yPosGirl -= i & 1;
      if (yPosGirl < 80)
      {
         yPosGirl = 80;
      }

      PAL_RLEBlitToSurface(PAL_SpriteGetFrame(bufGirl, (SDL_GetTicks() / 50) % 4),
         gpScreen, PAL_XY(220, yPosGirl));

      //
      // Update the screen
      //
      VIDEO_UpdateScreen(NULL);
      if (gpGlobals->fNeedToFadeIn)
      {
         PAL_FadeIn(gpGlobals->wNumPalette, gpGlobals->fNightPalette, 1);
         gpGlobals->fNeedToFadeIn = FALSE;
      }

      UTIL_Delay(50);
   }

   gpGlobals->wScreenWave = 0;

   SDL_FreeSurface(pUpper);
   SDL_FreeSurface(pLower);

   free(buf);
   free(bufGirl);
}
static void ANDROID_UnlockHWSurface(_THIS, SDL_Surface *surface)
{
	SDL_PixelFormat format;
	Uint32 hwformat = SDL_PIXELFORMAT_RGBA5551;
	int bpp;
	SDL_Surface * converted = NULL;

	if( !SDL_ANDROID_InsideVideoThread() )
	{
		__android_log_print(ANDROID_LOG_INFO, "libSDL", "Error: calling %s not from the main thread!", __PRETTY_FUNCTION__);
		return;
	}

	if( !surface->hwdata )
		return;
	
	if( surface->format->Amask )
		hwformat = SDL_PIXELFORMAT_RGBA4444;
		
	if( surface == SDL_CurrentVideoSurface ) // Special case
		hwformat = SDL_PIXELFORMAT_RGB565;
	
		/* Allocate the new pixel format for the screen */
    SDL_memset(&format, 0, sizeof(format));
	SDL_PixelFormatEnumToMasks( hwformat, &bpp,
								&format.Rmask, &format.Gmask,
								&format.Bmask, &format.Amask );
	format.BytesPerPixel = ANDROID_BYTESPERPIXEL;
	format.BitsPerPixel = bpp;
	
	if( format.BitsPerPixel == surface->format->BitsPerPixel &&
		format.Rmask == surface->format->Rmask &&
		format.Gmask == surface->format->Gmask &&
		format.Bmask == surface->format->Bmask &&
		format.Amask == surface->format->Amask )
	{
		DEBUGOUT("ANDROID_UnlockHWSurface() no conversion");
		converted = surface; // No need for conversion
	}
	else
	{
		Uint16 x, y;

		converted = SDL_CreateRGBSurface(SDL_SWSURFACE, surface->w, surface->h, format.BitsPerPixel,
											format.Rmask, format.Gmask, format.Bmask, format.Amask);
		if( !converted ) {
			SDL_OutOfMemory();
			return;
		}

		#define CONVERT_RGB565_RGBA5551( pixel ) (0x1 | ( (pixel & 0xFFC0) | ( (pixel & 0x1F) << 1 ) ))
		
		if( surface->flags & SDL_SRCCOLORKEY )
		{
			DEBUGOUT("ANDROID_UnlockHWSurface() CONVERT_RGB565_RGBA5551 + colorkey");
			for( y = 0; y < surface->h; y++ )
			{
				Uint16* src = (Uint16 *)( surface->pixels + surface->pitch * y );
				Uint16* dst = (Uint16 *)( converted->pixels + converted->pitch * y );
				Uint16 w = surface->w;
				Uint16 key = surface->format->colorkey;
				Uint16 pixel;
				for( x = 0; x < w; x++, src++, dst++ )
				{
					pixel = *src;
					*dst = (pixel == key) ? 0 : CONVERT_RGB565_RGBA5551( pixel );
				}
			}
		}
		else
		{
			DEBUGOUT("ANDROID_UnlockHWSurface() CONVERT_RGB565_RGBA5551");
			for( y = 0; y < surface->h; y++ )
			{
				Uint16* src = (Uint16 *)( surface->pixels + surface->pitch * y );
				Uint16* dst = (Uint16 *)( converted->pixels + converted->pitch * y );
				Uint16 w = surface->w;
				Uint16 pixel;
				for( x = 0; x < w; x++, src++, dst++ )
				{
					pixel = *src;
					*dst = CONVERT_RGB565_RGBA5551( pixel );
				}
			}
		}
	}

	SDL_Rect rect;
	rect.x = 0;
	rect.y = 0;
	rect.w = surface->w;
	rect.h = surface->h;
	SDL_UpdateTexture((struct SDL_Texture *)surface->hwdata, &rect, converted->pixels, converted->pitch);

	if( surface == SDL_CurrentVideoSurface ) // Special case
		SDL_RenderCopy((struct SDL_Texture *)SDL_CurrentVideoSurface->hwdata, NULL, NULL);
	
	if( converted != surface )
		SDL_FreeSurface(converted);
}
Example #25
0
bool CApp::OnInit() {
    if (SDL_Init(SDL_INIT_EVERYTHING) < 0) {
        return false;
    }

    if (IMG_Init(IMG_INIT_PNG) == 0) {
        return false;
    }

    SDL_LogSetAllPriority(SDL_LOG_PRIORITY_WARN);
    SDL_LogGetOutputFunction(&logfunc, NULL);
    SDL_LogSetOutputFunction(myLog, NULL);

    SDL_CreateWindowAndRenderer(SCREEN_W, SCREEN_H, 0, &Window, &Renderer);
    if (!Window || !Renderer) {
        SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "CreateWindowAndRenderer: %s", SDL_GetError());
        return false;
    }
    SDL_SetWindowTitle(Window, TITLE);

    Surf_Display = SDL_CreateRGBSurface(0, SCREEN_W, SCREEN_H, BPP,
                                        RMASK, GMASK, BMASK, AMASK);
    if (!Surf_Display) {
        SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "CreateRGBSurface: %s", SDL_GetError());
        return false;
    }
    SDL_FillRect(Surf_Display, NULL, 0);

    Texture = SDL_CreateTexture(Renderer, SDL_PIXELFORMAT_ARGB8888, SDL_TEXTUREACCESS_STREAMING, SCREEN_W, SCREEN_H);
    if (!Texture) {
        SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "CreateTexture: %s", SDL_GetError());
        return false;
    }

    CEventFilter::SetDefaults(); // or use your own filters
    CEventFilter::TurnFilterOn(&InputHappened);

    // PROGRAM SPECIFIC CODE HERE

    bg = SDL_CreateRGBSurface(0, SCREEN_W, SCREEN_H, BPP, RMASK, GMASK, BMASK, AMASK);
    if (!bg) {
        SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "CSurface::OnLoad: %s", SDL_GetError());
        return false;
    }
    SDL_FillRect(bg, NULL, 0xfff0f0f0);

    VerticalSpriteSheet* dude = new VerticalSpriteSheet("gfx/char.png", 1, Surf_Display->format);

    ActionJackson.SetSpriteSheet(dude);
    ActionJackson.AnimState = 0;
    CEntity::EntityList.push_back(&ActionJackson);

    SDL_SetWindowIcon(Window, dude->sheet);

    tiles = new TiledSpriteSheet("gfx/tiles.png", 2, 2, Surf_Display->format);

    block = new VerticalSpriteSheet("gfx/block.png", 1, Surf_Display->format);

    if (!LoadMaps("maps/sokoban.map", tiles))
        return false;

    std::ifstream fin("save");
    if (fin) {
        fin >> CurrentMap;
        fin.ignore(1, '\n');
        fin >> highestLevel;
    }
    fin.close();
    ResetMap(CurrentMap);

    return true;
}
Example #26
0
/* read XPM from either array or RWops */
static SDL_Surface *load_xpm(const char **xpm, SDL_RWops *src)
{
        SDL_Surface *image = NULL;
        int indexc;
        int x, y;
        int w, h, ncolors, cpp;
        int indexed;
        Uint8 *dst;
        struct color_hash *colors = NULL;
        SDL_Color *im_colors = NULL;
        char *keystrings = NULL, *nextkey;
        const char *line;
        const char ***xpmlines = NULL;
        int pixels_len;

        error = NULL;
        linebuf = NULL;
        buflen = 0;

        if (xpm)
                xpmlines = &xpm;

        line = get_next_line(xpmlines, src, 0);
        if (!line)
                goto done;
        /*
         * The header string of an XPMv3 image has the format
         *
         * <width> <height> <ncolors> <cpp> [ <hotspot_x> <hotspot_y> ]
         *
         * where the hotspot coords are intended for mouse cursors.
         * Right now we don't use the hotspots but it should be handled
         * one day.
         */
        if (sscanf(line, "%d %d %d %d", &w, &h, &ncolors, &cpp) != 4
           || w <= 0 || h <= 0 || ncolors <= 0 || cpp <= 0) {
                error = "Invalid format description";
                goto done;
        }

        keystrings = malloc(ncolors * cpp);
        if (!keystrings) {
                error = "Out of memory";
                goto done;
        }
        nextkey = keystrings;

        /* Create the new surface */
        if (ncolors <= 256) {
                indexed = 1;
                image = SDL_CreateRGBSurface(SDL_SWSURFACE, w, h, 8,
                                             0, 0, 0, 0);
                im_colors = image->format->palette->colors;
                image->format->palette->ncolors = ncolors;
        } else {
                indexed = 0;
                image = SDL_CreateRGBSurface(SDL_SWSURFACE, w, h, 32,
                                             0xff0000, 0x00ff00, 0x0000ff, 0);
        }
        if (!image) {
                /* Hmm, some SDL error (out of memory?) */
                goto done;
        }

        /* Read the colors */
        colors = create_colorhash(ncolors);
        if (!colors) {
                error = "Out of memory";
                goto done;
        }
        for (indexc = 0; indexc < ncolors; ++indexc ) {
                const char *p;
                line = get_next_line(xpmlines, src, 0);
                if (!line)
                        goto done;

                p = line + cpp + 1;

                /* parse a colour definition */
                for (;;) {
                        char nametype;
                        const char *colname;
                        Uint32 rgb, pixel;

                        SKIPSPACE(p);
                        if (!*p) {
                                error = "colour parse error";
                                goto done;
                        }
                        nametype = *p;
                        SKIPNONSPACE(p);
                        SKIPSPACE(p);
                        colname = p;
                        SKIPNONSPACE(p);
                        if (nametype == 's')
                                continue;      /* skip symbolic colour names */

                        if (!color_to_rgb(colname, p - colname, &rgb))
                                continue;

                        memcpy(nextkey, line, cpp);
                        if (indexed) {
                                SDL_Color *c = im_colors + indexc;
                                c->r = (Uint8)(rgb >> 16);
                                c->g = (Uint8)(rgb >> 8);
                                c->b = (Uint8)(rgb);
                                pixel = indexc;
                        } else
                                pixel = rgb;
                        add_colorhash(colors, nextkey, cpp, pixel);
                        nextkey += cpp;
                        if (rgb == 0xffffffff)
                                SDL_SetColorKey(image, SDL_SRCCOLORKEY, pixel);
                        break;
                }
        }
Example #27
0
int Engine::createBackground() {
    background = SDL_CreateRGBSurface(0, win_width, win_height, 32, 0, 0, 0, 0);
    return 0;
}
Example #28
0
void TextureBuilder::PrepareSurface()
{
	if (m_prepared) return;

	if (!m_surface && !m_filename.empty()) {
		std::string filename = m_filename;
		std::transform(filename.begin(), filename.end(), filename.begin(), ::tolower);
		if (ends_with_ci(filename, ".dds")) {
			LoadDDS();
		} else {
			LoadSurface();
		}
	}

	TextureFormat targetTextureFormat;
	unsigned int virtualWidth, actualWidth, virtualHeight, actualHeight, numberOfMipMaps = 0, numberOfImages = 1;
	if( m_surface ) {
		SDL_PixelFormat *targetPixelFormat;
		bool needConvert = !GetTargetFormat(m_surface->format, &targetTextureFormat, &targetPixelFormat, m_forceRGBA);

		if (needConvert) {
			if(m_textureType == TEXTURE_2D) {
				SDL_Surface *s = SDL_ConvertSurface(m_surface.Get(), targetPixelFormat, SDL_SWSURFACE);
				m_surface = SDLSurfacePtr::WrapNew(s);
			} else if(m_textureType == TEXTURE_CUBE_MAP) {
				assert(m_cubemap.size() == 6);
				for(unsigned int i = 0; i < 6; ++i) {
					SDL_Surface *s = SDL_ConvertSurface(m_cubemap[i].Get(), targetPixelFormat, SDL_SWSURFACE);
					m_cubemap[i] = SDLSurfacePtr::WrapNew(s);
				}
			} else {
				// Unknown texture type
				assert(0);
			}
		}

		virtualWidth = actualWidth = m_surface->w;
		virtualHeight = actualHeight = m_surface->h;

		if (m_potExtend) {
			// extend to power-of-two if necessary
			actualWidth = ceil_pow2(m_surface->w);
			actualHeight = ceil_pow2(m_surface->h);
			if (actualWidth != virtualWidth || actualHeight != virtualHeight) {
				if(m_textureType == TEXTURE_2D) {
					SDL_Surface *s = SDL_CreateRGBSurface(SDL_SWSURFACE, actualWidth, actualHeight, targetPixelFormat->BitsPerPixel,
						targetPixelFormat->Rmask, targetPixelFormat->Gmask, targetPixelFormat->Bmask, targetPixelFormat->Amask);
					SDL_SetSurfaceBlendMode(m_surface.Get(), SDL_BLENDMODE_NONE);
					SDL_BlitSurface(m_surface.Get(), 0, s, 0);

					m_surface = SDLSurfacePtr::WrapNew(s);
				} else if(m_textureType == TEXTURE_CUBE_MAP) {
					assert(m_cubemap.size() == 6);
					for(unsigned int i = 0; i < 6; ++i) {
						SDL_Surface *s = SDL_CreateRGBSurface(SDL_SWSURFACE, actualWidth, actualHeight, targetPixelFormat->BitsPerPixel,
							targetPixelFormat->Rmask, targetPixelFormat->Gmask, targetPixelFormat->Bmask, targetPixelFormat->Amask);
						SDL_SetSurfaceBlendMode(m_cubemap[i].Get(), SDL_BLENDMODE_NONE);
						SDL_BlitSurface(m_cubemap[i].Get(), 0, s, 0);
						m_cubemap[i] = SDLSurfacePtr::WrapNew(s);
					}
				} else {
					assert(0);
				}
			}
		}
		else if (! m_filename.empty()) {
			// power-of-two check
			unsigned long width = ceil_pow2(m_surface->w);
			unsigned long height = ceil_pow2(m_surface->h);

			if (width != virtualWidth || height != virtualHeight)
				Output("WARNING: texture '%s' is not power-of-two and may not display correctly\n", m_filename.c_str());
		}
	} else {
		switch(m_dds.GetTextureFormat()) {
		case PicoDDS::FORMAT_DXT1: targetTextureFormat = TEXTURE_DXT1; break;
		case PicoDDS::FORMAT_DXT5: targetTextureFormat = TEXTURE_DXT5; break;
		default:
			Output("ERROR: DDS texture with invalid format '%s' (only DXT1 and DXT5 are supported)\n", m_filename.c_str());
			assert(false);
			return;
		}

		virtualWidth = actualWidth = m_dds.imgdata_.width;
		virtualHeight = actualHeight = m_dds.imgdata_.height;
		numberOfMipMaps = m_dds.imgdata_.numMipMaps;
		numberOfImages = m_dds.imgdata_.numImages;
		if(m_textureType == TEXTURE_CUBE_MAP) {
			// Cube map must be fully defined (6 images) to be used correctly
			assert(numberOfImages == 6);
		}
	}

	m_descriptor = TextureDescriptor(
		targetTextureFormat,
		vector2f(actualWidth,actualHeight),
		vector2f(float(virtualWidth)/float(actualWidth),float(virtualHeight)/float(actualHeight)),
		m_sampleMode, m_generateMipmaps, m_compressTextures, m_anisotropicFiltering, numberOfMipMaps, m_textureType);

	m_prepared = true;
}
Example #29
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;
}
Example #30
0
void Tankas::atnaujinti(int xp, int yp, vector<Kulka*> &kulkos)
{
    if(sprogsta)
    {
        Sprogimas();
        return;
    }
    int dx, dy;

    dx = X+Tanks->w/2 - xp;
    dy = Y+Tanks->h/2 - yp;

    vk = atan2(dx , dy) * 180 / M_PI;
    pk = vk - kampas + 90;

//    if( kulkos != NULL )
    {
            int i = 0;
            while(i < kulkos.size())
            {
               // cout<<"kulkos x"<<kulkos[i]->GetX()<<endl;
                if( SDL_CollidePixel(rotation, X, Y, kulkos[i]->KPasukta, kulkos[i]->GetX(), kulkos[i]->GetY()) != 0 )
                {
                    /*I mane pataike!*/
                    sprogsta = true;
                    lastW=rotation->w;
                    lastH=rotation->h;
                    cout<<"Pataike!"<<endl;
                }
                i++;
            }
    }



     if(senas_kampas!=kampas || senas_kampasP != pk)
     {

     SDL_Surface* Tn = new SDL_Surface;   //Tanko vamzdis
     SDL_Surface* ND = new SDL_Surface;   //Laikinas sluoksnis
     SDL_Surface* Tm = new SDL_Surface;   //Originaliojo tanko sluoksnio kopija
//-----------------------------------------------------------------------------
    ND = SDL_CreateRGBSurface(SDL_HWSURFACE|SDL_SRCALPHA, Tanks->w, Tanks->h, 32, NULL, NULL, NULL, 0);
    SDL_BlitSurface(Tanks, NULL, ND, NULL);

    Uint32 colorkey1 = SDL_MapRGB( Tanks->format, 0, 255, 0 );
    SDL_SetColorKey( ND, SDL_SRCCOLORKEY, colorkey1 );//naujai sukurtam sluoksniu nustatom sena color key

    Tm = SDL_DisplayFormatAlpha( ND );

    std::swap(Tm, ND);

    SDL_FreeSurface(ND);
    //delete(ND);
//-----------------------------------------------------------------------------

    Tn =  rotozoomSurfaceXY(Patranka, pk, 1, 1, 0);

    SDL_Rect dst = {Tn->w / 2,  Tn->h / 2};

    dst.x = ( Tanks->w - Tn->w ) / 2;
    dst.y = ( Tanks->h - Tn->h ) / 2;

    SDL_BlitSurface(Tn, NULL, Tm, &dst);

    SDL_FreeSurface(Tn);
    //delete(Tn);

    SDL_FreeSurface(rotation);
    rotation = rotozoomSurface(Tm, kampas, 0.45, 0);

    SDL_FreeSurface(Tm);
    //delete(Tm);

    Uint32 colorkey = SDL_MapRGB( rotation->format, 0, 255, 0 );
    SDL_SetColorKey( rotation, SDL_SRCCOLORKEY, colorkey );

    SDL_Surface * www = new SDL_Surface;
    www = SDL_DisplayFormatAlpha(rotation);
    std::swap(www, rotation);
    SDL_FreeSurface(www);
    //delete(www);


    senas_kampas = kampas;
    senas_kampasP = pk;

}
}