void CMessageBoxSelection::init() { mpMBSurface.reset(CG_CreateRGBSurface( mMBRect ), &SDL_FreeSurface); mpMBSurface.reset(gVideoDriver.convertThroughBlitSfc( mpMBSurface.get() ), &SDL_FreeSurface); initGalaxyFrame(); SDL_Rect rect = mMBRect; rect.x = 8; rect.y = 10; rect.w -= 16; rect.h -= 16; GsFont &Font = gGraphics.getFont(FONT_ID); SDL_PixelFormat *format = gVideoDriver.getBlitSurface()->format; SDL_Surface *pColoredTextSurface = CG_CreateRGBSurface(rect); const Uint32 oldColor = Font.getFGColor(); Font.setupColor( SDL_MapRGB( format, 0, 0, 0 ) ); auto textList = explode(mText, "\n"); int yoff = 0; for( auto &it : textList ) { int xmid = (rect.w-Font.getPixelTextWidth(it))/2+rect.x; Font.drawFont( pColoredTextSurface, it, xmid, yoff); yoff += 12; } // Adapt the newly created surface to the running screen. SDL_Surface *temp; if(RES_BPP == 32) // Only if there is an Alpha Channel (32 BPP) temp = gVideoDriver.convertThroughBlitSfc(pColoredTextSurface); else // or temp = gVideoDriver.convertThroughBlitSfc(pColoredTextSurface); SDL_FreeSurface(pColoredTextSurface); pColoredTextSurface = temp; Font.setupColor( oldColor ); std::unique_ptr<SDL_Surface,SDL_Surface_Deleter> pTextSfc(pColoredTextSurface); SDL_BlitSurface(pTextSfc.get(), NULL, mpMBSurface.get(), const_cast<SDL_Rect*>(&rect)); // Create the Border and with two Surfaces of different colors create the rectangle SDL_Rect selRect; SDL_Rect cutRect; selRect.x = selRect.y = 0; selRect.w = rect.w-rect.x; selRect.h = 14; cutRect = selRect; cutRect.x += 2; cutRect.y += 2; cutRect.w -= 4; cutRect.h -= 4; mpSelSurface1.reset( SDL_CreateRGBSurface( SDL_SWSURFACE, selRect.w, selRect.h, RES_BPP, format->Rmask, format->Gmask, format->Bmask, 0 ), &SDL_FreeSurface); mpSelSurface2.reset( SDL_CreateRGBSurface( SDL_SWSURFACE, selRect.w, selRect.h, RES_BPP, format->Rmask, format->Gmask, format->Bmask, 0 ), &SDL_FreeSurface); SDL_FillRect( mpSelSurface1.get(), &selRect, SDL_MapRGB( format, 255, 0, 0 ) ); SDL_FillRect( mpSelSurface2.get(), &selRect, SDL_MapRGB( format, 0, 0, 255 ) ); #if SDL_VERSION_ATLEAST(2, 0, 0) SDL_SetColorKey(mpSelSurface1.get(), SDL_TRUE, SDL_MapRGB( format, 0, 0, 0 )); SDL_SetColorKey(mpSelSurface2.get(), SDL_TRUE, SDL_MapRGB( format, 0, 0, 0 )); SDL_SetSurfaceBlendMode(mpSelSurface1.get(), SDL_BLENDMODE_BLEND); SDL_SetSurfaceBlendMode(mpSelSurface2.get(), SDL_BLENDMODE_BLEND); #else SDL_SetColorKey( mpSelSurface1.get(), SDL_SRCCOLORKEY, SDL_MapRGB( format, 0, 0, 0 ) ); SDL_SetColorKey( mpSelSurface2.get(), SDL_SRCCOLORKEY, SDL_MapRGB( format, 0, 0, 0 ) ); #endif SDL_FillRect( mpSelSurface1.get(), &cutRect, SDL_MapRGB( format, 0, 0, 0 ) ); SDL_FillRect( mpSelSurface2.get(), &cutRect, SDL_MapRGB( format, 0, 0, 0 ) ); }
//Basic Init, create the font, backbuffer, etc WINDOW *curses_init(void) { lastchar = -1; inputdelay = -1; std::string typeface = "Terminus"; std::string blending = "solid"; std::ifstream fin; int faceIndex = 0; int fontsize = 0; //actuall size fin.open("data/FONTDATA"); if (!fin.is_open()){ fontwidth = 8; fontheight = 16; std::ofstream fout;//create data/FONDATA file fout.open("data/FONTDATA"); if(fout.is_open()) { fout << typeface << "\n"; fout << fontwidth << "\n"; fout << fontheight; fout.close(); } } else { getline(fin, typeface); fin >> fontwidth; fin >> fontheight; fin >> fontsize; fin >> blending; if ((fontwidth <= 4) || (fontheight <= 4)) { fontheight = 16; fontwidth = 8; } fin.close(); } fontblending = (blending=="blended"); halfwidth=fontwidth / 2; halfheight=fontheight / 2; if(!InitSDL()) { DebugLog() << (std::string)"Failed to initialize SDL!\n"; } #ifdef SDLTILES DebugLog() << "Initializing SDL Tiles context\n"; tilecontext = new cata_tiles; tilecontext->init("gfx"); #endif // SDLTILES DebugLog() << (std::string)"Tiles initialized successfully.\n"; WindowWidth= OPTIONS["TERMINAL_X"]; if (WindowWidth < FULL_SCREEN_WIDTH) WindowWidth = FULL_SCREEN_WIDTH; WindowWidth *= fontwidth; WindowHeight = OPTIONS["TERMINAL_Y"] * fontheight; if(!WinCreate()) { DebugLog() << (std::string)"Failed to create game window!\n"; return NULL; } #ifdef SDLTILES tilecontext->set_screen(screen); while(!strcasecmp(typeface.substr(typeface.length()-4).c_str(),".bmp") || !strcasecmp(typeface.substr(typeface.length()-4).c_str(),".png")) { SDL_Surface *asciiload; typeface = "data/font/" + typeface; asciiload = IMG_Load(typeface.c_str()); if(!asciiload || asciiload->w*asciiload->h < (fontwidth * fontheight * 256)) { SDL_FreeSurface(asciiload); break; } Uint32 key = SDL_MapRGB(asciiload->format, 0xFF, 0, 0xFF); SDL_SetColorKey(asciiload,SDL_SRCCOLORKEY,key); ascii[0] = SDL_DisplayFormat(asciiload); SDL_FreeSurface(asciiload); for(int a = 1; a < 16; a++) { ascii[a]=SDL_ConvertSurface(ascii[0],ascii[0]->format,ascii[0]->flags); } init_colors(); for(int a = 0; a < 15; a++) { SDL_LockSurface(ascii[a]); int size = ascii[a]->h * ascii[a]->w; Uint32 *pixels = (Uint32 *)ascii[a]->pixels; Uint32 color = (windowsPalette[a].r << 16) | (windowsPalette[a].g << 8) | windowsPalette[a].b; for(int i=0;i<size;i++) { if(pixels[i] == 0xFFFFFF) pixels[i] = color; } SDL_UnlockSurface(ascii[a]); } if(fontwidth)tilewidth=ascii[0]->w/fontwidth; OutputChar = &OutputImageChar; mainwin = newwin(OPTIONS["TERMINAL_Y"], OPTIONS["TERMINAL_X"],0,0); return mainwin; } #endif // SDLTILES std::string sysfnt = find_system_font(typeface, faceIndex); if(sysfnt != "") typeface = sysfnt; //make fontdata compatible with wincurse if(!fexists(typeface.c_str())) { faceIndex = 0; typeface = "data/font/" + typeface + ".ttf"; } //different default font with wincurse if(!fexists(typeface.c_str())) { faceIndex = 0; typeface = "data/font/fixedsys.ttf"; } if(fontsize <= 0) fontsize = fontheight - 1; // SDL_ttf handles bitmap fonts size incorrectly if(0 == strcasecmp(typeface.substr(typeface.length() - 4).c_str(), ".fon")) faceIndex = test_face_size(typeface, fontsize, faceIndex); font = TTF_OpenFontIndex(typeface.c_str(), fontsize, faceIndex); //if(!font) something went wrong TTF_SetFontStyle(font, TTF_STYLE_NORMAL); // glyph height hack by utunnels // SDL_ttf doesn't use FT_HAS_VERTICAL for function TTF_GlyphMetrics // this causes baseline problems for certain fonts // I can only guess by check a certain tall character... cache_glyphs(); init_colors(); OutputChar = &OutputFontChar; mainwin = newwin(OPTIONS["TERMINAL_Y"], OPTIONS["TERMINAL_X"],0,0); return mainwin; //create the 'stdscr' window and return its ref }
/* * Convert a surface into the specified pixel format. */ SDL_Surface * SDL_ConvertSurface(SDL_Surface * surface, SDL_PixelFormat * format, Uint32 flags) { SDL_Surface *convert; Uint32 copy_flags; 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; surface->map->info.flags = 0; /* 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 = surface->map->info.r; convert->map->info.g = surface->map->info.g; convert->map->info.b = surface->map->info.b; convert->map->info.a = surface->map->info.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.flags = copy_flags; 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); }
SDL_Surface *IMG_LoadLBM_RW( SDL_RWops *src ) { int start; SDL_Surface *Image; Uint8 id[4], pbm, colormap[MAXCOLORS*3], *MiniBuf, *ptr, count, color, msk; Uint32 size, bytesloaded, nbcolors; Uint32 i, j, bytesperline, nbplanes, stencil, plane, h; Uint32 remainingbytes; Uint32 width; BMHD bmhd; char *error; Uint8 flagHAM,flagEHB; Image = NULL; error = NULL; MiniBuf = NULL; if ( !src ) { /* The error message has been set in SDL_RWFromFile */ return NULL; } start = SDL_RWtell(src); if ( !SDL_RWread( src, id, 4, 1 ) ) { error="error reading IFF chunk"; goto done; } /* Should be the size of the file minus 4+4 ( 'FORM'+size ) */ if ( !SDL_RWread( src, &size, 4, 1 ) ) { error="error reading IFF chunk size"; goto done; } /* As size is not used here, no need to swap it */ if ( memcmp( id, "FORM", 4 ) != 0 ) { error="not a IFF file"; goto done; } if ( !SDL_RWread( src, id, 4, 1 ) ) { error="error reading IFF chunk"; goto done; } pbm = 0; /* File format : PBM=Packed Bitmap, ILBM=Interleaved Bitmap */ if ( !memcmp( id, "PBM ", 4 ) ) pbm = 1; else if ( memcmp( id, "ILBM", 4 ) ) { error="not a IFF picture"; goto done; } nbcolors = 0; memset( &bmhd, 0, sizeof( BMHD ) ); flagHAM = 0; flagEHB = 0; while ( memcmp( id, "BODY", 4 ) != 0 ) { if ( !SDL_RWread( src, id, 4, 1 ) ) { error="error reading IFF chunk"; goto done; } if ( !SDL_RWread( src, &size, 4, 1 ) ) { error="error reading IFF chunk size"; goto done; } bytesloaded = 0; size = SDL_SwapBE32( size ); if ( !memcmp( id, "BMHD", 4 ) ) /* Bitmap header */ { if ( !SDL_RWread( src, &bmhd, sizeof( BMHD ), 1 ) ) { error="error reading BMHD chunk"; goto done; } bytesloaded = sizeof( BMHD ); bmhd.w = SDL_SwapBE16( bmhd.w ); bmhd.h = SDL_SwapBE16( bmhd.h ); bmhd.x = SDL_SwapBE16( bmhd.x ); bmhd.y = SDL_SwapBE16( bmhd.y ); bmhd.tcolor = SDL_SwapBE16( bmhd.tcolor ); bmhd.Lpage = SDL_SwapBE16( bmhd.Lpage ); bmhd.Hpage = SDL_SwapBE16( bmhd.Hpage ); } if ( !memcmp( id, "CMAP", 4 ) ) /* palette ( Color Map ) */ { if ( !SDL_RWread( src, &colormap, size, 1 ) ) { error="error reading CMAP chunk"; goto done; } bytesloaded = size; nbcolors = size / 3; } if ( !memcmp( id, "CAMG", 4 ) ) /* Amiga ViewMode */ { Uint32 viewmodes; if ( !SDL_RWread( src, &viewmodes, sizeof(viewmodes), 1 ) ) { error="error reading CAMG chunk"; goto done; } bytesloaded = size; viewmodes = SDL_SwapBE32( viewmodes ); if ( viewmodes & 0x0800 ) flagHAM = 1; if ( viewmodes & 0x0080 ) flagEHB = 1; } if ( memcmp( id, "BODY", 4 ) ) { if ( size & 1 ) ++size; /* padding ! */ size -= bytesloaded; /* skip the remaining bytes of this chunk */ if ( size ) SDL_RWseek( src, size, RW_SEEK_CUR ); } } /* compute some usefull values, based on the bitmap header */ width = ( bmhd.w + 15 ) & 0xFFFFFFF0; /* Width in pixels modulo 16 */ bytesperline = ( ( bmhd.w + 15 ) / 16 ) * 2; nbplanes = bmhd.planes; if ( pbm ) /* File format : 'Packed Bitmap' */ { bytesperline *= 8; nbplanes = 1; } stencil = (bmhd.mask & 1); /* There is a mask ( 'stencil' ) */ /* Allocate memory for a temporary buffer ( used for decompression/deinterleaving ) */ MiniBuf = (void *)malloc( bytesperline * (nbplanes + stencil) ); if ( MiniBuf == NULL ) { error="no enough memory for temporary buffer"; goto done; } if ( ( Image = SDL_CreateRGBSurface( SDL_SWSURFACE, width, bmhd.h, (bmhd.planes==24 || flagHAM==1)?24:8, 0, 0, 0, 0 ) ) == NULL ) goto done; if ( bmhd.mask & 2 ) /* There is a transparent color */ #if (SDL_VERSION_ATLEAST(1,3,0)) SDL_SetColorKey( Image, SDL_TRUE, bmhd.tcolor ); #else SDL_SetColorKey( Image, SDL_SRCCOLORKEY, bmhd.tcolor ); #endif /* Update palette informations */ /* There is no palette in 24 bits ILBM file */ if ( nbcolors>0 && flagHAM==0 ) { /* FIXME: Should this include the stencil? See comment below */ int nbrcolorsfinal = 1 << (nbplanes + stencil); ptr = &colormap[0]; for ( i=0; i<nbcolors; i++ ) { Image->format->palette->colors[i].r = *ptr++; Image->format->palette->colors[i].g = *ptr++; Image->format->palette->colors[i].b = *ptr++; } /* Amiga EHB mode (Extra-Half-Bright) */ /* 6 bitplanes mode with a 32 colors palette */ /* The 32 last colors are the same but divided by 2 */ /* Some Amiga pictures save 64 colors with 32 last wrong colors, */ /* they shouldn't !, and here we overwrite these 32 bad colors. */ if ( (nbcolors==32 || flagEHB ) && (1<<bmhd.planes)==64 ) { nbcolors = 64; ptr = &colormap[0]; for ( i=32; i<64; i++ ) { Image->format->palette->colors[i].r = (*ptr++)/2; Image->format->palette->colors[i].g = (*ptr++)/2; Image->format->palette->colors[i].b = (*ptr++)/2; } } /* If nbcolors < 2^nbplanes, repeat the colormap */ /* This happens when pictures have a stencil mask */ if ( nbrcolorsfinal > (1<<bmhd.planes) ) { nbrcolorsfinal = (1<<bmhd.planes); } for ( i=nbcolors; i < (Uint32)nbrcolorsfinal; i++ ) { Image->format->palette->colors[i].r = Image->format->palette->colors[i%nbcolors].r; Image->format->palette->colors[i].g = Image->format->palette->colors[i%nbcolors].g; Image->format->palette->colors[i].b = Image->format->palette->colors[i%nbcolors].b; } if ( !pbm ) Image->format->palette->ncolors = nbrcolorsfinal; } /* Get the bitmap */ for ( h=0; h < bmhd.h; h++ ) { /* uncompress the datas of each planes */ for ( plane=0; plane < (nbplanes+stencil); plane++ ) { ptr = MiniBuf + ( plane * bytesperline ); remainingbytes = bytesperline; if ( bmhd.tcomp == 1 ) /* Datas are compressed */ { do { if ( !SDL_RWread( src, &count, 1, 1 ) ) { error="error reading BODY chunk"; goto done; } if ( count & 0x80 ) { count ^= 0xFF; count += 2; /* now it */ if ( ( count > remainingbytes ) || !SDL_RWread( src, &color, 1, 1 ) ) { error="error reading BODY chunk"; goto done; } memset( ptr, color, count ); } else { ++count; if ( ( count > remainingbytes ) || !SDL_RWread( src, ptr, count, 1 ) ) { error="error reading BODY chunk"; goto done; } } ptr += count; remainingbytes -= count; } while ( remainingbytes > 0 ); } else { if ( !SDL_RWread( src, ptr, bytesperline, 1 ) ) { error="error reading BODY chunk"; goto done; } } } /* One line has been read, store it ! */ ptr = Image->pixels; if ( nbplanes==24 || flagHAM==1 ) ptr += h * width * 3; else ptr += h * width; if ( pbm ) /* File format : 'Packed Bitmap' */ { memcpy( ptr, MiniBuf, width ); } else /* We have to un-interlace the bits ! */ { if ( nbplanes!=24 && flagHAM==0 ) { size = ( width + 7 ) / 8; for ( i=0; i < size; i++ ) { memset( ptr, 0, 8 ); for ( plane=0; plane < (nbplanes + stencil); plane++ ) { color = *( MiniBuf + i + ( plane * bytesperline ) ); msk = 0x80; for ( j=0; j<8; j++ ) { if ( ( plane + j ) <= 7 ) ptr[j] |= (Uint8)( color & msk ) >> ( 7 - plane - j ); else ptr[j] |= (Uint8)( color & msk ) << ( plane + j - 7 ); msk >>= 1; } } ptr += 8; } } else {
/** * Creates a texture from a surface. Set the alpha according to the color key. * Pixels that match the color key get an alpha of zero while all other * pixels get an alpha of one. * * The source surface can come from example from a PNG file. * * @url:http://osdl.sourceforge.net/main/documentation/rendering/SDL-openGL-examples.html#loadnonalphaexample */ static GLuint uploadTextureFromSurface( SDL_Surface* sourceSurface, Uint8 colorKeyRed, Uint8 colorKeyGreen, Uint8 colorKeyBlue, Uint8 colorKeyAlpha) { /* * Use the surface width and height expanded to powers of 2 : * (one may call also gluScaleImage. */ //int w = powerOfTwo( sourceSurface->w ) ; //int h = powerOfTwo( sourceSurface->h ) ; int w = ( sourceSurface->w ) ; int h = ( sourceSurface->h ) ; // int w = sourceSurface->w; // int h = sourceSurface->h; /* //TODO:Remove // Min X : texcoord[0] = 0.0f ; // Min Y : texcoord[1] = 0.0f ; // Max X : texcoord[2] = (GLfloat) surface->w / w ; // Max Y : texcoord[3] = (GLfloat) surface->h / h ; */ /* Create the target alpha surface with correct color component ordering */ SDL_Surface* alphaImage = SDL_CreateRGBSurface( SDL_SWSURFACE, sourceSurface->w, sourceSurface->h, 32 /* bits */, #if SDL_BYTEORDER == SDL_LIL_ENDIAN // OpenGL RGBA masks 0x000000FF, 0x0000FF00, 0x00FF0000, 0xFF000000 #else 0xFF000000, 0x00FF0000, 0x0000FF00, 0x000000FF #endif ); if ( alphaImage == NX_NULL ) { nxAssertFail("uploadTextureFromSurface : RGB surface creation failed."); } // Set up so that colorkey pixels become transparent : //Uint32 colorkey = SDL_MapRGBA( alphaImage->format, colorKeyRed, colorKeyGreen, colorKeyBlue, colorKeyAlpha ); Uint32 colorkey = SDL_MapRGBA( alphaImage->format, colorKeyRed, colorKeyGreen, colorKeyBlue, colorKeyAlpha ); SDL_FillRect( alphaImage, 0, colorkey ); colorkey = SDL_MapRGBA( sourceSurface->format, colorKeyRed, colorKeyGreen, colorKeyBlue, colorKeyAlpha); SDL_SetColorKey( sourceSurface, SDL_SRCCOLORKEY, colorkey ); SDL_Rect area; // SDL_SetAlpha(sourceSurface, 0, 0); //http://www.gamedev.net/topic/518525-opengl--sdl--transparent-image-make-textures/ SDL_SetAlpha(sourceSurface, 0, colorKeyAlpha); //http://www.gamedev.net/topic/518525-opengl--sdl--transparent-image-make-textures/ // SDL_SetAlpha(sourceSurface, SDL_ALPHA_TRANSPARENT, 255); //http://www.gamedev.net/topic/518525-opengl--sdl--transparent-image-make-textures/ // Copy the surface into the GL texture image : area.x = 0; area.y = 0; area.w = sourceSurface->w; area.h = sourceSurface->h; SDL_BlitSurface( sourceSurface, &area, alphaImage, &area ); // Create an OpenGL texture for the image GLuint textureID; glGenTextures( 1, &textureID ); glBindTexture( GL_TEXTURE_2D, textureID ); /* Prepare the filtering of the texture image */ glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST ); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST ); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT ); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT ); /* Map the alpha surface to the texture */ glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, alphaImage->pixels ); // No longer needed : SDL_FreeSurface(alphaImage); return textureID ; }
// Draw // Paints the surface onto the destination bool Sprite::Draw(){ if(m_Animate){ if(m_AnimationSpeed > 0){ Uint32 now = SDL_GetTicks(); if(m_NextFrameTime <= now){ IncrementFrameX(); m_NextFrameTime = now + m_AnimationSpeed; } } } if(m_alpha <= 0) return true; // Invisible if(pImageSource){ //SDL_SetAlpha(pImageSource, SDL_SRCALPHA, m_alpha); if(m_TileWidth >= pImageSource->w && m_TileHeight >= pImageSource->h && m_TileX == 0 && m_TileY == 0){ if(m_angle != 0 || m_zoom != 1){ // Just rotated/zoomed SDL_SetAlpha(pImageSource, SDL_SRCALPHA, 255); SDL_Surface* pImageOutput = rotozoomSurface(pImageSource, m_angle, m_zoom, m_smoothing); if(pImageOutput != NULL){ SDL_SetColorKey(pImageOutput, SDL_SRCCOLORKEY, pImageSource->format->colorkey); SDL_SetAlpha(pImageOutput, SDL_SRCALPHA, m_alpha); SDL_Rect dest; dest.x = (int)m_x - pImageOutput->w/2 - System::CameraX; dest.y = (int)m_y - pImageOutput->h/2 - System::CameraY; SDL_BlitSurface(pImageOutput, NULL, System::Screen, &dest); SDL_FreeSurface(pImageOutput); return true; } } else { // No rotation or zoom - fast SDL_Rect dest; dest.x = (int)m_x - pImageSource->w/2 - System::CameraX; dest.y = (int)m_y - pImageSource->h/2 - System::CameraY; SDL_SetAlpha(pImageSource, SDL_SRCALPHA, m_alpha); SDL_BlitSurface(pImageSource, NULL, System::Screen, &dest); return true; } } else { // Different tile if(m_angle != 0 || m_zoom != 1){ // Rotated/zoomed and different tile SDL_Surface* pImageTile = SDL_CreateRGBSurface(SDL_SWSURFACE|SDL_SRCCOLORKEY, m_TileWidth, m_TileHeight, pImageSource->format->BitsPerPixel, pImageSource->format->Rmask, pImageSource->format->Gmask, pImageSource->format->Bmask, pImageSource->format->Amask); if(pImageTile){ SDL_Rect source; source.x = m_TileX * m_TileWidth; source.y = m_TileY * m_TileHeight; source.w = m_TileWidth; source.h = m_TileHeight; SDL_SetAlpha(pImageSource, SDL_SRCALPHA, 255); SDL_FillRect(pImageTile, NULL, pImageSource->format->colorkey); SDL_BlitSurface(pImageSource, &source, pImageTile, NULL); SDL_SetColorKey(pImageTile, SDL_SRCCOLORKEY, pImageSource->format->colorkey); SDL_Surface* pImageOutput = rotozoomSurface(pImageTile, m_angle, m_zoom, m_smoothing); SDL_FreeSurface(pImageTile); if(pImageOutput){ SDL_Rect dest; dest.x = (int)m_x - pImageOutput->w/2 - System::CameraX; dest.y = (int)m_y - pImageOutput->h/2 - System::CameraY; SDL_SetColorKey(pImageOutput, SDL_SRCCOLORKEY, pImageSource->format->colorkey); SDL_SetAlpha(pImageOutput, SDL_SRCALPHA, m_alpha); SDL_BlitSurface(pImageOutput, NULL, System::Screen, &dest); SDL_FreeSurface(pImageOutput); return true; } } } else { // Just different tile SDL_Rect source; source.x = m_TileX * m_TileWidth; source.y = m_TileY * m_TileHeight; source.w = m_TileWidth; source.h = m_TileHeight; SDL_Rect dest; dest.x = (int)m_x - m_TileWidth/2 - System::CameraX; dest.y = (int)m_y - m_TileHeight/2 - System::CameraY; SDL_SetAlpha(pImageSource, SDL_SRCALPHA, m_alpha); SDL_BlitSurface(pImageSource, &source, System::Screen, &dest); return true; } } } return false; }
void SDLImage::convertToDisplayFormat() { if (mSurface == NULL) { throw FCN_EXCEPTION("Trying to convert a non loaded image to display format."); } int i; bool hasPink = false; bool hasAlpha = false; for (i = 0; i < mSurface->w * mSurface->h; ++i) { if (((unsigned int*)mSurface->pixels)[i] == SDL_MapRGB(mSurface->format,255,0,255)) { hasPink = true; break; } } for (i = 0; i < mSurface->w * mSurface->h; ++i) { Uint8 r, g, b, a; SDL_GetRGBA(((unsigned int*)mSurface->pixels)[i], mSurface->format, &r, &g, &b, &a); if (a != 255) { hasAlpha = true; break; } } SDL_Surface *tmp; if (hasAlpha) { tmp = SDL_DisplayFormatAlpha(mSurface); SDL_FreeSurface(mSurface); mSurface = NULL; } else { tmp = SDL_DisplayFormat(mSurface); SDL_FreeSurface(mSurface); mSurface = NULL; } if (tmp == NULL) { throw FCN_EXCEPTION("Unable to convert image to display format."); } if (hasPink) { SDL_SetColorKey(tmp, SDL_SRCCOLORKEY, SDL_MapRGB(tmp->format,255,0,255)); } if (hasAlpha) { SDL_SetAlpha(tmp, SDL_SRCALPHA, 255); } mSurface = tmp; }
bool render_text(font_data *ft_font, const char *text, string_tex_t *string_tex) { SDL_Color white = { 0xFF, 0xFF, 0xFF, 0x00 }; SDL_Color *forecol; SDL_Surface *string_glyph = NULL; SDL_Surface *glyph = NULL; SDL_Rect src, dest; GLenum gl_error; if (!(ft_font)) return false; if (!(ft_font->ttffont)) return false; if (!(string_tex)) return false; #if 0 if (!strlen(text)) return false; /* something is printing an empty string each frame */ #else /* kps - fix for empty author field in cannon dodgers */ if (!strlen(text)) text = " "; #endif forecol = &white; string_tex->font_height = ft_font->h; string_glyph = TTF_RenderText_Blended( ft_font->ttffont, text, *forecol ); string_tex->tex_list = Arraylist_alloc(sizeof(tex_t)); string_tex->width = 0; string_tex->height = string_glyph->h; if (string_glyph) { int i, num = 1 + string_glyph->w / 254; string_tex->text = (char *)malloc(sizeof(char)*(strlen(text)+1)); sprintf(string_tex->text,"%s",text); for( i=0 ; i<num ; ++i ) { tex_t tex; tex.texture = 0; tex.texcoords.MinX = 0.0; tex.texcoords.MaxX = 0.0; tex.texcoords.MinY = 0.0; tex.texcoords.MaxY = 0.0; tex.width = 0; src.x = i*254; dest.x = 0; src.y = dest.y = 0; if (i==num-1) dest.w = src.w = string_glyph->w - i*254; else dest.w = src.w = 254; src.h = dest.h = string_glyph->h; glyph = SDL_CreateRGBSurface(0,dest.w,dest.h,32,0,0,0,0); SDL_SetColorKey(glyph, SDL_SRCCOLORKEY, 0x00000000); SDL_BlitSurface(string_glyph,&src,glyph,&dest); glGetError(); tex.texture = SDL_GL_LoadTexture(glyph,&(tex.texcoords)); if ( (gl_error = glGetError()) != GL_NO_ERROR ) printf("Warning: Couldn't create texture: 0x%x\n", gl_error); tex.width = dest.w; string_tex->width += dest.w; SDL_FreeSurface(glyph); Arraylist_add(string_tex->tex_list,&tex); } SDL_FreeSurface(string_glyph); } else { printf("TTF_RenderText_Blended failed for [%s]\n",text); return false; } return true; }
int main(int argc, char* argv[]) { Grille g1 = lirefichier(argv[1]); //Création d'une nouvelle grille à partir d'un fichier chargé //La grille servira de contrôleur mais l'utilisateur ne la voit jamais : il ne voit que l'interface graphique qui en découlera joueur j1; //Création d'un nouveau joueur j1.posn = 0; j1.posm = 0; posjoueur(g1, j1); SDL_Surface *screen, *temp, *sprite, *grass, *wall; //Création de surfaces SDL SDL_Rect rcSprite, rcGrass; SDL_Event event; Uint8 *keystate; int colorkey, gameover; SDL_Init(SDL_INIT_VIDEO); //initialisation de la fenêtre SDL_WM_SetCaption("Jeu TecDev SDL", "Jeu TecDev SDL"); //Définission du titre de la fenêtre screen = SDL_SetVideoMode(SCREEN_WIDTH, SCREEN_HEIGHT, 0, 0); //Création de la fenêtre temp = SDL_LoadBMP("mushroom.bmp"); //Chargement du sprite mushroom.bmp dans la surface sprite sprite = SDL_DisplayFormat(temp); SDL_FreeSurface(temp); colorkey = SDL_MapRGB(screen->format, 255, 255, 255); //Création de la transparence du sprite SDL_SetColorKey(sprite, SDL_SRCCOLORKEY | SDL_RLEACCEL, colorkey); temp = SDL_LoadBMP("grass.bmp"); //Chargement du background grass.bmp dans la surface grass grass = SDL_DisplayFormat(temp); SDL_FreeSurface(temp); temp = SDL_LoadBMP("wall.bmp"); //Chargement de l'image wall.bmp dans la surface wall wall = SDL_DisplayFormat(temp); SDL_FreeSurface(temp); colorkey = SDL_MapRGB(screen->format, 255, 255, 255); //Transparence du mur SDL_SetColorKey(wall, SDL_SRCCOLORKEY | SDL_RLEACCEL, colorkey); rcSprite.x = 0; //Le sprite est en (0,0) à la base rcSprite.y = 0; gameover = 0; //Si gameover à 1 => Fin du jeu while (!gameover) { if (SDL_PollEvent(&event)) { switch (event.type) { case SDL_QUIT: gameover = 1; break; case SDL_KEYDOWN: switch (event.key.keysym.sym) { case SDLK_ESCAPE: //Si la touche entrée est échap case SDLK_q: //ou q gameover = 1; //Alors quitter le jeu break; case SDLK_p: //Si la touche entrée est p while (event.key.keysym.sym != SDLK_p) { //Alors tant que la touche entrée n'est pas p rcSprite.x = rcSprite.x; //Le joueur ne bouge pas rcSprite.y = rcSprite.y; } break; case SDLK_r: //Si la touche entrée est r rcSprite.x = 0; //Réinitialisation du sprite en 0 rcSprite.y = 0; j1.posn = 0; //Réinitialisation du joueur en 0 j1.posm = 0; posjoueur(g1, j1); //Replacement du joueur dans la grille break; default: break; } break; } } //Traitement des cas ou l'utilisateur entre une touche fléchée keystate = SDL_GetKeyState(NULL); //L'utilisateur entre une touche qui sera contenue dans keystate int tempn = j1.posn; int tempm = j1.posm; if (keystate[SDLK_LEFT] ) { if (j1.posm-1 >= 0) { if (g1.g[j1.posn][j1.posm-1] == 0) { j1.posm--; g1 = posjoueur(g1, j1); //Placement du joueur dans la grille aux cases correspondantes rcSprite.x -= STEP_SIZE; retiretrace(g1, j1); //Retire la présence précédente du joueur dans la grille } else { j1.posm = tempm; } } else { j1.posm = 0; } } if (keystate[SDLK_RIGHT] ) { if (j1.posm+1 <= SCREEN_WIDTH/STEP_SIZE) { if (g1.g[j1.posn][j1.posm+1] == 0) { j1.posm++; g1 = posjoueur(g1, j1); rcSprite.x += STEP_SIZE; retiretrace(g1, j1); } else { j1.posm = tempm; } } else { j1.posm = SCREEN_WIDTH/STEP_SIZE; } } if (keystate[SDLK_UP] ) { if (j1.posn-1 >= 0) { if (g1.g[j1.posn - 1][j1.posm] == 0) { j1.posn--; g1 = posjoueur(g1, j1); rcSprite.y -= STEP_SIZE; retiretrace(g1, j1); } else { j1.posn = tempn; } } else { j1.posn = 0; } } if (keystate[SDLK_DOWN] ) { if (j1.posn+1 < SCREEN_HEIGHT/STEP_SIZE) { if (g1.g[j1.posn+1][j1.posm] == 0) { j1.posn++; g1 = posjoueur(g1, j1); rcSprite.y += STEP_SIZE; retiretrace(g1, j1); } else { j1.posn = tempn; } } else { j1.posn = SCREEN_HEIGHT/STEP_SIZE; } } //Traitement des cas de collision avec les bords de l'écran /*if ( rcSprite.x < 0 ) { rcSprite.x = 0; } else if ( rcSprite.x > SCREEN_WIDTH-SPRITE_SIZE ) { rcSprite.x = SCREEN_WIDTH-SPRITE_SIZE; } if ( rcSprite.y < 0 ) { rcSprite.y = 0; } else if ( rcSprite.y > SCREEN_HEIGHT-SPRITE_SIZE ) { rcSprite.y = SCREEN_HEIGHT-SPRITE_SIZE; }*/ // Placement des images en fonction de la grille => Création de l'aire de jeu int x, y; for (x = 0; x <= SCREEN_WIDTH/SPRITE_SIZE; x++) { for (y = 0; y < SCREEN_HEIGHT/SPRITE_SIZE; y++) { if (g1.g[y][x] == 0 || g1.g[y][x] == 8)//Si a cet endroit de la grille c'est libre { rcGrass.x = x * SPRITE_SIZE; //Déplacement du "curseur" rcGrass à cet endroit rcGrass.y = y * SPRITE_SIZE; SDL_BlitSurface(grass, NULL, screen, &rcGrass); //Placement de l'image grass à cet endroit } else if (g1.g[y][x] == 1) // Si à cet endroit il ya un mur { rcGrass.x = x * SPRITE_SIZE; rcGrass.y = y * SPRITE_SIZE; SDL_BlitSurface(wall, NULL, screen, &rcGrass); //Placement de l'image wall à cet endroit } } } SDL_BlitSurface(sprite, NULL, screen, &rcSprite); //Placement de l'image sprite à l'endroit indiqué par les coordonnées de rcSprite SDL_UpdateRect(screen,0,0,0,0); //Rafraîchissement de l'écran } //Quand le jeu est quitté : SDL_FreeSurface(sprite); SDL_FreeSurface(grass); SDL_FreeSurface(wall); SDL_Quit(); return 0; }
void view::Surface::setShadowSurface(SDL_Surface* surface) { this->shadow = SDL_DisplayFormat(surface); SDL_SetColorKey(this->shadow,SDL_SRCCOLORKEY|SDL_RLEACCEL, SDL_MapRGB(this->surface->format,255,0,255)); }
void player::showplayer() { SDL_BlitSurface(image,&clips[1],SDL_GetVideoSurface(),&box); SDL_SetColorKey(image,SDL_SRCCOLORKEY,SDL_MapRGB(SDL_GetVideoSurface()->format,255,0,255)); }
//sets the color key for the objects within the world void Application::setKey() { SDL_SetColorKey(player.player, SDL_SRCCOLORKEY, SDL_MapRGB(player.player->format, 0, 128, 128)); for(int i = 0; i<2; i++)//set key for wraiths { SDL_SetColorKey(wraithFactory[i].wraith, SDL_SRCCOLORKEY, SDL_MapRGB(wraithFactory[i].wraith->format, 0, 128, 128)); } for(int i = 0; i<2; i++)//set key for mummy { SDL_SetColorKey(mummyFactory[i].mummy, SDL_SRCCOLORKEY, SDL_MapRGB(mummyFactory[i].mummy->format, 0, 128, 128)); } SDL_SetColorKey(seeker.seeker, SDL_SRCCOLORKEY, SDL_MapRGB(seeker.seeker->format, 0, 128, 128)); SDL_SetColorKey(ghost.ghost, SDL_SRCCOLORKEY, SDL_MapRGB(ghost.ghost->format, 0, 128, 128)); SDL_SetColorKey(island1, SDL_SRCCOLORKEY, SDL_MapRGB(island1->format, 0, 128, 128)); SDL_SetColorKey(island2, SDL_SRCCOLORKEY, SDL_MapRGB(island2->format, 0, 128, 128)); SDL_SetColorKey(island3, SDL_SRCCOLORKEY, SDL_MapRGB(island3->format, 0, 128, 128)); SDL_SetColorKey(island4, SDL_SRCCOLORKEY, SDL_MapRGB(island4->format, 0, 128, 128)); SDL_SetColorKey(spikes, SDL_SRCCOLORKEY, SDL_MapRGB(spikes->format, 0, 128, 128)); SDL_SetColorKey(spikes1, SDL_SRCCOLORKEY, SDL_MapRGB(spikes1->format, 0, 128, 128)); SDL_SetColorKey(pillar, SDL_SRCCOLORKEY, SDL_MapRGB(pillar->format, 0, 128, 128)); SDL_SetColorKey(finish, SDL_SRCCOLORKEY, SDL_MapRGB(finish->format, 0, 128, 128)); SDL_SetColorKey(ghost.lightning, SDL_SRCCOLORKEY, SDL_MapRGB(ghost.lightning->format, 0, 128, 128)); for(int i = 0; i<100; i++)//set key for all the arrows { SDL_SetColorKey(quiver[i].arrowR, SDL_SRCCOLORKEY, SDL_MapRGB(quiver[i].arrowR->format, 0, 128, 128)); SDL_SetColorKey(quiver[i].arrowL, SDL_SRCCOLORKEY, SDL_MapRGB(quiver[i].arrowL->format, 0, 128, 128)); } }
int main(int argc, char **argv) { struct birdPackage infoToSend, infoReceived; int port; char serverIp [16]; if (argc != 3) { std::cout << "USO flappy <serverIp> <port>" << std::endl; exit(-1); } strcpy(serverIp, argv[1]); port = atoi(argv[2]); SocketDatagrama socket; std::cout << "Enviando al servidor: " << serverIp << " : " << port << " datos iniciados" << std::endl; bzero(&infoToSend,sizeof(birdPackage)); bzero(&infoReceived,sizeof(birdPackage)); /* CONEXION POR PRIMERA VEZ */ infoToSend.opcode = NEW; std::cout << "OPCODE: " << infoToSend.opcode << std::endl; PaqueteDatagrama paq((char *)&infoToSend, sizeof(birdPackage), serverIp, port); socket.envia(paq); PaqueteDatagrama receive(sizeof(birdPackage)); socket.recibe(receive); memcpy(&infoReceived, receive.obtieneDatos(), sizeof(birdPackage)); if(infoReceived.opcode == DENY) //Se rechaza al jugador, por lo que se tiene que salir { std::cout << "Partida llena intente más tarde..." << std::endl; exit(-1); }else{ nJugador = infoReceived.jugadorNum; infoToSend.opcode = JUMP; std::cout << "Partida iniciada, jugador: " << nJugador << std::endl; } SDL_Init(SDL_INIT_VIDEO); SDL_Window *ventana = SDL_CreateWindow("Hi", 200, 200, 864, 510, SDL_WINDOW_SHOWN); SDL_Renderer *render = SDL_CreateRenderer(ventana, -1, SDL_RENDERER_ACCELERATED); //se carga la imagen que contiene todos los graficos SDL_Surface * bmp = SDL_LoadBMP("atlas.bmp"); //se define el blanco como color transparente SDL_SetColorKey(bmp, 1, SDL_MapRGB(bmp->format, 255, 255, 255)); SDL_Texture *textura = SDL_CreateTextureFromSurface(render, bmp); SDL_FreeSurface(bmp); SDL_Event event; if (textura == NULL) { std::cout << "FAILED TO FIND THE IMAGE" << std::endl; } SDL_RenderClear(render); renderFondo(render, textura); //Inicializa la posición de los pajaros dentro de la pantalla, pasandolos del atlas.bmp al recuadro del juego initPajarosOrigen(render, textura); SDL_RenderPresent(render); int done = 1; double angulo = 330; const int FPS = 24; //Cuantos frames por segundo queremos, 60 es el que utilizan los televisores const int DELAY_TIME = 1000.0f / FPS; //1000 ms entre los fps da el numero de milisegundos entre cada frame Uint32 frameStart, frameTime; while (done) { frameStart = SDL_GetTicks(); //validacion del piso if (rectangulo_destino[nJugador].y < 500) { rectangulo_destino[nJugador].y += 10; } //validacion del angulo maximo if (angulo < 450) { angulo += 15; } //mientras exista un evento en el pila de eventos while (SDL_PollEvent(&event)) { //salto if (event.type == SDL_KEYDOWN && event.key.keysym.sym == SDLK_SPACE) { rectangulo_destino[nJugador].y -= 100; angulo = 300; infoToSend.opcode = 1; } else if (event.type == SDL_QUIT) { infoToSend.opcode = CLOSE; done = 0; } } //enviar Paquete con las coordenadas infoToSend.jugadorNum = nJugador; infoToSend.posicionJUMP_X[nJugador] = rectangulo_destino[nJugador].x; infoToSend.posicionJUMP_Y[nJugador] = rectangulo_destino[nJugador].y; infoToSend.angulo[nJugador] = angulo; PaqueteDatagrama paq((char *)&infoToSend, sizeof(birdPackage), serverIp, port); socket.envia(paq); //Recibir paquete con las coordenadas actualizadas PaqueteDatagrama receive(sizeof(birdPackage)); socket.recibe(receive); memcpy(&infoReceived, receive.obtieneDatos(), sizeof(birdPackage)); //se pinta actualiza el render SDL_RenderClear(render); renderFondo(render, textura); int i = 0; //Actualiza la posicion de los pajaros for (int i = 0; i < 3; ++i) { rectangulo_destino[i].x = infoReceived.posicionJUMP_X[i]; rectangulo_destino[i].y = infoReceived.posicionJUMP_Y[i]; angulos[i] = infoReceived.angulo[i]; } for (i = 0; i < infoReceived.jugadoresTotales; ++i) { //funciona como copy pero rota la imagen con el angulo SDL_RenderCopyEx(render, textura, &rectangulo_origen[i], &rectangulo_destino[i], infoReceived.angulo[i], NULL, SDL_FLIP_NONE); } SDL_RenderPresent(render); frameTime = SDL_GetTicks() - frameStart; //Tiempo que ha tardado en presentarse el frame if (frameTime < DELAY_TIME)//Si es menor al tiempo que deber à a ser { SDL_Delay((int)(DELAY_TIME - frameTime));//Espera un tiempo } } /* Free all objects */ SDL_DestroyTexture(textura); SDL_DestroyRenderer(render); SDL_DestroyWindow(ventana); /* Quit program */ SDL_Quit(); return 0; }
/*--------------------------------------------------------------------------*/ int AG_LoadGIF_RW( SDL_RWops* src, AG_Frame* frames, int maxFrames ) { int start; unsigned char buf[16]; unsigned char c; int useGlobalColormap; int bitPixel; int iFrame = 0; char version[4]; SDL_Surface* image = NULL; gifdata* gd; if ( src == NULL ) return 0; gd = (gifdata *)malloc( sizeof(*gd) ); memset( gd, 0, sizeof(*gd) ); gd->src = src; start = SDL_RWtell( src ); if ( !SDL_RWread(src,buf,6,1) ) { SDL_SetError( "error reading magic number" ); goto done; } if ( strncmp((char*)buf,"GIF",3) != 0 ) { SDL_SetError( "not a GIF file" ); goto done; } strncpy( version, (char*)buf+3, 3 ); version[3] = '\0'; if ( (strcmp(version,"87a") != 0) && (strcmp(version,"89a") != 0) ) { SDL_SetError( "bad version number, not '87a' or '89a'" ); goto done; } gd->g89.transparent = -1; gd->g89.delayTime = -1; gd->g89.inputFlag = -1; gd->g89.disposal = AG_DISPOSE_NA; if ( !SDL_RWread(src,buf,7,1) ) { SDL_SetError( "failed to read screen descriptor" ); goto done; } gd->gs.Width = LM_to_uint(buf[0],buf[1]); gd->gs.Height = LM_to_uint(buf[2],buf[3]); gd->gs.BitPixel = 2 << (buf[4] & 0x07); gd->gs.ColorResolution = (((buf[4] & 0x70) >> 3) + 1); gd->gs.Background = buf[5]; gd->gs.AspectRatio = buf[6]; if ( BitSet(buf[4],LOCALCOLORMAP) ) /* Global Colormap */ { if ( ReadColorMap(gd,gd->gs.BitPixel,gd->gs.ColorMap) ) { SDL_SetError( "error reading global colormap" ); goto done; } } do { if ( !SDL_RWread(src,&c,1,1) ) { SDL_SetError( "EOF / read error on image data" ); goto done; } if ( c == ';' ) /* GIF terminator */ goto done; if ( c == '!' ) /* Extension */ { if ( !SDL_RWread(src,&c,1,1) ) { SDL_SetError( "EOF / read error on extention function code" ); goto done; } DoExtension( gd, c ); continue; } if ( c != ',' ) /* Not a valid start character */ continue; if ( !SDL_RWread(src,buf,9,1) ) { SDL_SetError( "couldn't read left/top/width/height" ); goto done; } useGlobalColormap = !BitSet(buf[8],LOCALCOLORMAP); bitPixel = 1 << ((buf[8] & 0x07) + 1); if ( !useGlobalColormap ) { if ( ReadColorMap(gd,bitPixel,gd->localColorMap) ) { SDL_SetError( "error reading local colormap" ); goto done; } image = ReadImage( gd, LM_to_uint(buf[4],buf[5]), LM_to_uint(buf[6],buf[7]), bitPixel, gd->localColorMap, BitSet(buf[8],INTERLACE), (frames==NULL) ); } else { image = ReadImage( gd, LM_to_uint(buf[4],buf[5]), LM_to_uint(buf[6],buf[7]), gd->gs.BitPixel, gd->gs.ColorMap, BitSet(buf[8],INTERLACE), (frames==NULL) ); } if ( frames ) { if ( image == NULL ) goto done; if ( gd->g89.transparent >= 0 ) SDL_SetColorKey( image, SDL_SRCCOLORKEY, gd->g89.transparent ); frames[iFrame].surface = image; frames[iFrame].x = LM_to_uint(buf[0], buf[1]); frames[iFrame].y = LM_to_uint(buf[2], buf[3]); frames[iFrame].disposal = gd->g89.disposal; frames[iFrame].delay = gd->g89.delayTime*10; /* gd->g89.transparent = -1; ** Hmmm, not sure if this should be reset for each frame? */ } iFrame++; } while ( iFrame < maxFrames || frames == NULL ); done: if ( image == NULL ) SDL_RWseek( src, start, SEEK_SET ); free( gd ); return iFrame; }
/** * Load a font from the given .0FN file. * * @param fileName Name of an .0FN file */ Font::Font (const char* fileName) { File* file; unsigned char* pixels; unsigned char* blank; int fileSize; int count, size, width, height; // Load font from a font file try { file = new File(fileName, false); } catch (int e) { throw e; } fileSize = file->getSize(); nCharacters = 128; file->seek(20, true); lineHeight = file->loadChar() << 1; // Create blank character data blank = new unsigned char[3]; memset(blank, 0, 3); // Load characters for (count = 0; count < 128; count++) { if (file->tell() >= fileSize) { nCharacters = count; break; } size = file->loadShort(); if (size > 4) { pixels = file->loadRLE(size); width = pixels[0]; width += pixels[1] << 8; height = pixels[2]; height += pixels[3] << 8; if (size - 4 >= width * height) characters[count] = createSurface(pixels + 4, width, height); else characters[count] = createSurface(blank, 3, 1); delete[] pixels; } else characters[count] = createSurface(blank, 3, 1); SDL_SetColorKey(characters[count], SDL_SRCCOLORKEY, 0); } delete[] blank; delete file; // Create ASCII->font map for (count = 0; count < 33; count++) map[count] = 0; map[33] = 107; // ! map[34] = 116; // " map[35] = 0; // # map[36] = 63; // $ map[37] = 0; // % map[38] = 0; // & map[39] = 115; // ' map[40] = 111; // ( map[41] = 112; // ) map[42] = 0; // * map[43] = 105; // + map[44] = 101; // , map[45] = 104; // - map[46] = 102; // . map[47] = 108; // / for (count = 48; count < 58; count++) map[count] = count + 5; // Numbers map[58] = 114; // : map[59] = 113; // ; map[60] = 0; // < map[61] = 106; // = map[62] = 0; // > map[63] = 103; // ? map[64] = 0; // @ for (count = 65; count < 91; count++) map[count] = count - 38; // Upper-case letters for (; count < 97; count++) map[count] = 0; for (; count < 123; count++) map[count] = count - 96; // Lower-case letters for (; count < 128; count++) map[count] = 0; for (count = 0; count < 128; count++) { if (map[count] >= nCharacters) map[count] = 0; } return; }
void img_init_suite(t_image *img) { unsigned int col; col = SDL_MapRGB(img->monster1->format, 255, 255, 255); SDL_SetColorKey(img->monster1, SDL_RLEACCEL | SDL_SRCCOLORKEY, col); SDL_SetColorKey(img->monster2, SDL_RLEACCEL | SDL_SRCCOLORKEY, col); SDL_SetColorKey(img->monster3, SDL_RLEACCEL | SDL_SRCCOLORKEY, col); SDL_SetColorKey(img->monster4, SDL_RLEACCEL | SDL_SRCCOLORKEY, col); SDL_SetColorKey(img->monster5, SDL_RLEACCEL | SDL_SRCCOLORKEY, col); SDL_SetColorKey(img->monster6, SDL_RLEACCEL | SDL_SRCCOLORKEY, col); SDL_SetColorKey(img->hero1, SDL_RLEACCEL | SDL_SRCCOLORKEY, col); SDL_SetColorKey(img->hero2, SDL_RLEACCEL | SDL_SRCCOLORKEY, col); SDL_SetColorKey(img->hero3, SDL_RLEACCEL | SDL_SRCCOLORKEY, col); SDL_SetColorKey(img->hero4, SDL_RLEACCEL | SDL_SRCCOLORKEY, col); SDL_SetColorKey(img->hero5, SDL_RLEACCEL | SDL_SRCCOLORKEY, col); SDL_SetColorKey(img->hero6, SDL_RLEACCEL | SDL_SRCCOLORKEY, col); }
static PyObject* font_render(PyObject* self, PyObject* args) { TTF_Font* font = PyFont_AsFont (self); int aa; PyObject* text, *final; PyObject* fg_rgba_obj, *bg_rgba_obj = NULL; Uint8 rgba[] = {0, 0, 0, 0}; SDL_Surface* surf; SDL_Color foreg, backg; int just_return; if (!PyArg_ParseTuple(args, "OiO|O", &text, &aa, &fg_rgba_obj, &bg_rgba_obj)) { return NULL; } if (!RGBAFromColorObj(fg_rgba_obj, rgba)) { return RAISE(PyExc_TypeError, "Invalid foreground RGBA argument"); } foreg.r = rgba[0]; foreg.g = rgba[1]; foreg.b = rgba[2]; foreg.unused = 0; if (bg_rgba_obj != NULL) { if (!RGBAFromColorObj(bg_rgba_obj, rgba)) { bg_rgba_obj = NULL; backg.r = 0; backg.g = 0; backg.b = 0; backg.unused = 0; } else { backg.r = rgba[0]; backg.g = rgba[1]; backg.b = rgba[2]; backg.unused = 0; } } else { backg.r = 0; backg.g = 0; backg.b = 0; backg.unused = 0; } just_return = PyObject_Not(text); if (just_return) { int height = TTF_FontHeight(font); if (just_return == -1 || !(PyUnicode_Check(text) || Bytes_Check(text) || text == Py_None)) { PyErr_Clear(); return RAISE_TEXT_TYPE_ERROR(); } surf = SDL_CreateRGBSurface(SDL_SWSURFACE, 1, height, 32, 0xff<<16, 0xff<<8, 0xff, 0); if (surf == NULL) { return RAISE(PyExc_SDLError, SDL_GetError()); } if (bg_rgba_obj != NULL) { Uint32 c = SDL_MapRGB(surf->format, backg.r, backg.g, backg.b); SDL_FillRect(surf, NULL, c); } else { SDL_SetColorKey(surf, SDL_SRCCOLORKEY, 0); } } else if (PyUnicode_Check(text)) { PyObject *bytes = PyUnicode_AsEncodedString(text, "utf-8", "replace"); const char *astring = NULL; if (!bytes) { return NULL; } astring = Bytes_AsString(bytes); if (strlen(astring) != Bytes_GET_SIZE(bytes)) { Py_DECREF(bytes); return RAISE(PyExc_ValueError, "A null character was found in the text"); } if (utf_8_needs_UCS_4(astring)) { Py_DECREF(bytes); return RAISE(PyExc_UnicodeError, "A Unicode character above '\\uFFFF' was found;" " not supported"); } if (aa) { if (bg_rgba_obj == NULL) { surf = TTF_RenderUTF8_Blended(font, astring, foreg); } else { surf = TTF_RenderUTF8_Shaded(font, astring, foreg, backg); } } else { surf = TTF_RenderUTF8_Solid(font, astring, foreg); } Py_DECREF(bytes); } else if (Bytes_Check(text)) { const char *astring = Bytes_AsString(text); if (strlen(astring) != Bytes_GET_SIZE(text)) { return RAISE(PyExc_ValueError, "A null character was found in the text"); } if (aa) { if (bg_rgba_obj == NULL) { surf = TTF_RenderText_Blended(font, astring, foreg); } else { surf = TTF_RenderText_Shaded(font, astring, foreg, backg); } } else { surf = TTF_RenderText_Solid(font, astring, foreg); } } else { return RAISE_TEXT_TYPE_ERROR(); } if (surf == NULL) { return RAISE(PyExc_SDLError, TTF_GetError()); } if (!aa && (bg_rgba_obj != NULL) && !just_return) { /* turn off transparancy */ SDL_SetColorKey(surf, 0, 0); surf->format->palette->colors[0].r = backg.r; surf->format->palette->colors[0].g = backg.g; surf->format->palette->colors[0].b = backg.b; } final = PySurface_New(surf);
int main(int argc, char* argv[]) { ballfield_t *balls; SDL_Surface *screen; SDL_Surface *temp_image; SDL_Surface *back, *logo, *font, *font_hex; SDL_Event event; int bpp = 32, flags = 0, alpha = 1; int x_offs = 0, y_offs = 0; long tick, last_tick, last_avg_tick; double t = 0; float dt; int i; float fps = 0.0; int fps_count = 0; int fps_start = 0; float x_speed, y_speed, z_speed; SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO | SDL_INIT_JOYSTICK); atexit(SDL_Quit); screen = SDL_SetVideoMode(SCREEN_W, SCREEN_H, bpp, flags); if(!screen) { fprintf(stderr, "Failed to open screen!\n"); exit(-1); } SDL_WM_SetCaption("Ballfield", "Ballfield"); if(flags & SDL_FULLSCREEN) SDL_ShowCursor(0); balls = ballfield_init(); if(!balls) { fprintf(stderr, "Failed to create ballfield!\n"); exit(-1); } /* * Load and prepare balls... */ balls->use_alpha = alpha; if( ballfield_load_gfx(balls, "blueball.png", 0) || ballfield_load_gfx(balls, "redball.png", 1) ) { fprintf(stderr, "Could not load balls!\n"); exit(-1); } /* * Load background image */ temp_image = IMG_Load("sun.gif"); if(!temp_image) { fprintf(stderr, "Could not load background!\n"); exit(-1); } back = SDL_DisplayFormat(temp_image); SDL_FreeSurface(temp_image); /* * Load logo */ temp_image = SDL_LoadBMP("logo.bmp"); if(!temp_image) { fprintf(stderr, "Could not load logo!\n"); exit(-1); } SDL_SetColorKey(temp_image, SDL_SRCCOLORKEY, SDL_MapRGB(temp_image->format, 255, 0, 255)); logo = SDL_DisplayFormat(temp_image); SDL_FreeSurface(temp_image); /* * Load font */ temp_image = SDL_LoadBMP("font7x10.bmp"); if(!temp_image) { fprintf(stderr, "Could not load font!\n"); exit(-1); } SDL_SetColorKey(temp_image, SDL_SRCCOLORKEY, SDL_MapRGB(temp_image->format, 255, 0, 255)); font = SDL_DisplayFormat(temp_image); SDL_FreeSurface(temp_image); temp_image = SDL_LoadBMP("font7x10-hex.bmp"); if(!temp_image) { fprintf(stderr, "Could not load hex font!\n"); exit(-1); } SDL_SetColorKey(temp_image, SDL_SRCCOLORKEY, SDL_MapRGB(temp_image->format, 255, 0, 255)); font_hex = SDL_DisplayFormat(temp_image); SDL_FreeSurface(temp_image); last_avg_tick = last_tick = SDL_GetTicks(); enum { MAX_POINTERS = 16, PTR_PRESSED = 4 }; int touchPointers[MAX_POINTERS][5]; memset(touchPointers, 0, sizeof(touchPointers)); SDL_Joystick * joysticks[MAX_POINTERS+1]; for(i=0; i<MAX_POINTERS; i++) joysticks[i] = SDL_JoystickOpen(i); while(1) { SDL_Rect r; /* Timing */ tick = SDL_GetTicks(); dt = (tick - last_tick) * 0.001f; last_tick = tick; if( bpp == 32 ) SDL_FillRect(screen, NULL, 0); // Clear alpha channel /* Background image */ tiled_back(back, screen, x_offs>>11, y_offs>>11); /* Ballfield */ ballfield_render(balls, screen); /* Logo */ r.x = 2; r.y = 2; SDL_BlitSurface(logo, NULL, screen, &r); /* FPS counter */ if(tick > fps_start + 500) { fps = (float)fps_count * 1000.0 / (tick - fps_start); fps_count = 0; fps_start = tick; } ++fps_count; for(i=0; i<MAX_POINTERS; i++) { if( !touchPointers[i][PTR_PRESSED] ) continue; r.x = touchPointers[i][0]; r.y = touchPointers[i][1]; r.w = 80 + touchPointers[i][2] / 10; // Pressure r.h = 80 + touchPointers[i][3] / 10; // Touch point size r.x -= r.w/2; r.y -= r.h/2; SDL_FillRect(screen, &r, 0xaaaaaa); print_num(screen, font, r.x, r.y, i+1); } int mx, my; int b = SDL_GetMouseState(&mx, &my); Uint32 color = 0xff; if( b ) { color = 0; if( b & SDL_BUTTON_LEFT ) color |= 0xff00; if( b & SDL_BUTTON_RIGHT ) color |= 0xff0000; } r.x = mx; r.y = my; r.w = 30; r.h = 30; r.x -= r.w/2; r.y -= r.h/2; SDL_FillRect(screen, &r, color); SDL_Flip(SDL_GetVideoSurface()); SDL_Event evt; while( SDL_PollEvent(&evt) ) { if(evt.type == SDL_KEYUP || evt.type == SDL_KEYDOWN) { if(evt.key.keysym.sym == SDLK_ESCAPE) return 0; __android_log_print(ANDROID_LOG_INFO, "Ballfield", "SDL key event: evt %s state %s key %d scancode %d mod %d unicode %d", evt.type == SDL_KEYUP ? "UP " : "DOWN" , evt.key.state == SDL_PRESSED ? "PRESSED " : "RELEASED", (int)evt.key.keysym.sym, (int)evt.key.keysym.scancode, (int)evt.key.keysym.mod, (int)evt.key.keysym.unicode); } if(evt.type == SDL_VIDEORESIZE) __android_log_print(ANDROID_LOG_INFO, "Ballfield", "SDL resize event: %d x %d", evt.resize.w, evt.resize.h); if(evt.type == SDL_ACTIVEEVENT) __android_log_print(ANDROID_LOG_INFO, "Ballfield", "======= SDL active event: gain %d state %d", evt.active.gain, evt.active.state); /* if( evt.type == SDL_ACTIVEEVENT && evt.active.gain == 0 && evt.active.state & SDL_APPACTIVE ) { // We've lost GL context, we are not allowed to do any GFX output here, or app will crash! while( 1 ) { SDL_PollEvent(&evt); if( evt.type == SDL_ACTIVEEVENT && evt.active.gain && evt.active.state & SDL_APPACTIVE ) { __android_log_print(ANDROID_LOG_INFO, "Ballfield", "======= SDL active event: gain %d state %d", evt.active.gain, evt.active.state); SDL_Flip(SDL_GetVideoSurface()); // One SDL_Flip() call is required here to restore OpenGL context // Re-load all textures, matrixes and all other GL states if we're in SDL+OpenGL mode // Re-load all images to SDL_Texture if we're using it // Now we can draw break; } // Process network stuff, maybe play some sounds using SDL_ANDROID_PauseAudioPlayback() / SDL_ANDROID_ResumeAudioPlayback() SDL_Delay(300); __android_log_print(ANDROID_LOG_INFO, "Ballfield", "Waiting"); } } */ if( evt.type == SDL_JOYAXISMOTION ) { if( evt.jaxis.which == 0 ) // 0 = The accelerometer continue; int joyid = evt.jaxis.which - 1; touchPointers[joyid][evt.jaxis.axis] = evt.jaxis.value; // Axis 0 and 1 are coordinates, 2 and 3 are pressure and touch point radius } if( evt.type == SDL_JOYBUTTONDOWN || evt.type == SDL_JOYBUTTONUP ) { if( evt.jbutton.which == 0 ) // 0 = The accelerometer continue; int joyid = evt.jbutton.which - 1; touchPointers[joyid][PTR_PRESSED] = (evt.jbutton.state == SDL_PRESSED); } } /* Animate */ x_speed = 500.0 * sin(t * 0.37); y_speed = 500.0 * sin(t * 0.53); z_speed = 400.0 * sin(t * 0.21); ballfield_move(balls, x_speed, y_speed, z_speed); x_offs -= x_speed; y_offs -= y_speed; t += dt; } ballfield_free(balls); SDL_FreeSurface(back); SDL_FreeSurface(logo); SDL_FreeSurface(font); std::ostringstream os; os << "lalala" << std::endl << "more text" << std::endl; std::cout << os.str() << std::endl << "text text" << std::endl; exit(0); }
int main() { SDL_Surface *background; SDL_Rect src, dest; int frames; /* Initialize SDL's video system and check for errors. */ if (SDL_Init(SDL_INIT_VIDEO) != 0) { printf("Unable to initialize SDL: %s\n", SDL_GetError()); return 1; } /* Make sure SDL_Quit gets called when the program exits! */ atexit(SDL_Quit); /* Attempt to set a 640x480 hicolor (16-bit) video mode. */ screen = SDL_SetVideoMode(640, 480, 16, 0); if (screen == NULL) { printf("Unable to set video mode: %s\n", SDL_GetError()); return 1; } /* Load the bitmap files. */ background = SDL_LoadBMP("background.bmp"); if (background == NULL) { printf("Unable to load bitmap.\n"); return 1; } penguin = SDL_LoadBMP("smallpenguin.bmp"); if (penguin == NULL) { printf("Unable to load bitmap.\n"); return 1; } /* Set the penguin's colorkey. */ SDL_SetColorKey(penguin, SDL_SRCCOLORKEY, (Uint16) SDL_MapRGB(penguin->format, 0, 0, 255)); /* Initialize the penguin position data. */ init_penguins(); /* Animate 300 frames (approximately 10 seconds). */ for (frames = 0; frames < 300; frames++) { /* Draw the background image. */ src.x = 0; src.y = 0; src.w = background->w; src.h = background->h; dest = src; SDL_BlitSurface(background, &src, screen, &dest); /* Put the penguins on the screen. */ draw_penguins(); /* Ask SDL to update the entire screen. */ SDL_UpdateRect(screen, 0, 0, 0, 0); /* Move the penguins for the next frame. */ move_penguins(); } /* Free the memory that was allocated to the bitmap. */ SDL_FreeSurface(background); SDL_FreeSurface(penguin); return 0; }
void CGUI::MapResources() { SDL_PixelFormat *SInfo = SDL_GetVideoSurface()->format; /* if paletted, install palette */ if(SInfo->BytesPerPixel == 1) { FILE *pal = fopen("GFX/gui.pal", "rt"); /* ignore first two lines */ char TBuf[256]; fscanf(pal, "%s\n", TBuf); fscanf(pal, "%s\n", TBuf); /* get number of palette entries */ int NumEntries; SDL_Color ColSet[256]; fscanf(pal, "%d\n", &NumEntries); if(NumEntries > 256) NumEntries = 256; int c; for(c = 0; c < NumEntries; c++) fscanf(pal, "%d %d %d\n", &ColSet[c].r, &ColSet[c].g, &ColSet[c].b); for(;c < 256; c++) ColSet[c].r = ColSet[c].g = ColSet[c].b = 0; fclose(pal); ((CDisplay *)PPool->GetWellDefinedComponent(COMPONENT_DISPLAY))->IOCtl(DISPIOCTL_SEEDPALETTE, ColSet, NumEntries); // c = SDL_SetColors(DisplayBuffer, ColSet, 256 - NumEntries, NumEntries); c = SDL_SetColors(StaticBuffer, ColSet, 256 - NumEntries, NumEntries); } int c= 256; while(c--) { if(SrcResources[c]) { if(SrcResources[c]->format->Aloss == 8) Resources[c] = OptimiseSurface(SrcResources[c]); else { /* if in paletted mode, just go for a src keyed fade to black */ if(SInfo->BytesPerPixel == 1) { Resources[c] = OptimiseSurface(SrcResources[c]); SDL_LockSurface(Resources[c]); SDL_LockSurface(SrcResources[c]); /* find an unused colour */ bool ColourList[256]; int cc = 256, x, y; while(cc--) ColourList[cc] = false; for(y = 0; y < Resources[c]->h; y++) for(x = 0; x < Resources[c]->w; x++) ColourList[((Uint8 *)Resources[c]->pixels)[ y * Resources[c]->pitch + x]] = true; Uint8 UnusedColour = 0; cc = 256; while(cc--) if(!ColourList[cc]) {UnusedColour = cc; break; } for(y = 0; y < Resources[c]->h; y++) { for(x = 0; x < Resources[c]->w; x++) { if( ((Uint8 *)SrcResources[c]->pixels)[ y * SrcResources[c]->pitch + (x << 2) + 3] < 0x80) ((Uint8 *)Resources[c]->pixels)[ y * Resources[c]->pitch + x] = UnusedColour; } } SDL_UnlockSurface(Resources[c]); SDL_UnlockSurface(SrcResources[c]); SDL_SetColorKey(Resources[c], SDL_SRCCOLORKEY, UnusedColour); } else Resources[c] = OptimiseSurface(SrcResources[c], true); } } } }
int main(int argc, char *argv[]) { /** COMMS ************************************************************/ struct ftdi_context *ftdic = bub_init(57600, 1, 0, BUF_SIZE); if(ftdic == NULL) abort(); // FIXME printf("Ready.\n"); uint8_t buf[BUF_SIZE]; memset(&buf, 0, BUF_SIZE); long rxb = -1; /** GFX **************************************************************/ gam_screen screen = { .w = 512, .h = 512, .depth = 32, .flags = SDL_HWACCEL | SDL_DOUBLEBUF, .info = 0, .surface = NULL }; if(gam_init(GAM_ALL, 1) != EXIT_SUCCESS) abort(); if(gam_video_init(&screen) != 0) return(EXIT_FAILURE); SDL_Surface *backdrop = gam_get_surface_from_png_file("backdrop.png", SDL_HWSURFACE); if(backdrop == NULL){ fprintf(stderr, "Can't allocate surface: %s\n", SDL_GetError()); return(EXIT_FAILURE); } SDL_Surface *spot = gam_get_surface_from_png_file("spot.png", SDL_HWSURFACE); //SDL_Surface *spot = gam_get_surface_sphere(screen.surface, 100); if(spot == NULL){ fprintf(stderr, "Can't allocate surface: %s\n", SDL_GetError()); return(EXIT_FAILURE); } SDL_SetColorKey(spot, SDL_SRCCOLORKEY, SDL_MapRGB(spot->format, 255, 255, 255)); if(spot == NULL){ fprintf(stderr, "Can't allocate surface: %s\n", SDL_GetError()); return(EXIT_FAILURE); } TTF_Font *ttf = gam_init_sdlttf("StayPuft.ttf", 22); if(ttf == NULL) abort(); Uint32 text_color = SDL_MapRGB(screen.surface->format, 0, 0, 0); gam_state->print_mode = GAM_PRINT_BLEND; gam_state->alpha = SDL_MapRGB(screen.surface->format, 140, 140, 160); /*********************************************************************/ typedef struct { int x, y, z; } point_t; point_t point[TAIL_COUNT]; int i; for(i = 0; i < TAIL_COUNT; i++) { point[i].x = (.5 * screen.w - .5 * spot->w); point[i].y = (.5 * screen.h - .5 * spot->h); point[i].z = 0; } memset(&buf, 0, BUF_SIZE); ftdi_usb_purge_rx_buffer(ftdic); SDL_Event event; SDL_Rect rect; int busy = 1; while(busy) { while(SDL_PollEvent(&event)) if(event.type == SDL_KEYDOWN) if(event.key.keysym.sym == SDLK_ESCAPE) busy = 0; SDL_BlitSurface(backdrop, NULL, screen.surface, NULL); rxb = ftdi_read_data(ftdic, buf, BUF_SIZE); if(rxb > 0) { if(rxb == BUF_SIZE) { if(buf[BUF_SIZE - 1] == 10 && buf[BUF_SIZE - 2] == 13) { int16_t x, y, z; x = (buf[1] << 8) ^ buf[0]; y = (buf[3] << 8) ^ buf[2]; z = (buf[5] << 8) ^ buf[4]; printf("\e[32mGREAT SUCCESS\e[0m %4d %4d %4d\n", x, y, z); //gam_print_core(screen.surface, 0, 0, text_color, "X: %d", x); gam_print(screen.surface, 0, 0, ttf, text_color, "X: %1.2f", x / 256.0); gam_print(screen.surface, 0, 23, ttf, text_color, "Y: %1.2f", y / 256.0); gam_print(screen.surface, 0, 46, ttf, text_color, "Z: %1.2f", z / 256.0); //printf("%1.3f %1.3f %1.3f\n", // x / 256.0, // y / 256.0, // z / 256.0); point[0].x = (.5 * screen.w - .5 * spot->w) + x; point[0].y = (.5 * screen.h - .5 * spot->h) + y; for(i = TAIL_COUNT - 1; i > 0; i--) { point[i].x = point[i - 1].x; point[i].y = point[i - 1].y; point[i].z = point[i - 1].z; } for(i = TAIL_COUNT - 1; i >= 0; i--) { rect.x = point[i].x; rect.y = point[i].y; SDL_SetAlpha(spot, SDL_SRCALPHA, (255 / TAIL_COUNT) * (TAIL_COUNT - i)); SDL_BlitSurface(spot, NULL, screen.surface, &rect); } SDL_Flip(screen.surface); } else { fprintf(stderr, "Packet of right length but wrong signature\n"); } } else if(rxb < BUF_SIZE) { // Underrun? fprintf(stderr, "Packet of unknown size %ld\n", rxb); } else { abort(); } } else if(rxb < 0){
void CPainter::TransparentColor(const CRGBColor& TransparentColor) { SDL_SetColorKey(m_pSurface, SDL_SRCCOLORKEY, TransparentColor.SDLColor(m_pSurface->format)); }
SDL_Surface *IMG_LoadPNG_RW(SDL_RWops *src) { int start; const char *error; SDL_Surface *volatile surface; png_structp png_ptr; png_infop info_ptr; png_uint_32 width, height; int bit_depth, color_type, interlace_type; Uint32 Rmask; Uint32 Gmask; Uint32 Bmask; Uint32 Amask; SDL_Palette *palette; png_bytep *volatile row_pointers; int row, i; volatile int ckey = -1; png_color_16 *transv; if ( !src ) { /* The error message has been set in SDL_RWFromFile */ return NULL; } start = SDL_RWtell(src); if ( IMG_InitPNG() < 0 ) { return NULL; } /* Initialize the data we will clean up when we're done */ error = NULL; png_ptr = NULL; info_ptr = NULL; row_pointers = NULL; surface = NULL; /* Create the PNG loading context structure */ png_ptr = lib.png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL,NULL,NULL); if (png_ptr == NULL){ error = "Couldn't allocate memory for PNG file or incompatible PNG dll"; goto done; } /* Allocate/initialize the memory for image information. REQUIRED. */ info_ptr = lib.png_create_info_struct(png_ptr); if (info_ptr == NULL) { error = "Couldn't create image information for PNG file"; goto done; } /* Set error handling if you are using setjmp/longjmp method (this is * the normal method of doing things with libpng). REQUIRED unless you * set up your own error handlers in png_create_read_struct() earlier. */ #ifndef LIBPNG_VERSION_12 if ( setjmp(*lib.png_set_longjmp_fn(png_ptr, longjmp, sizeof (jmp_buf))) ) #else if ( setjmp(png_ptr->jmpbuf) ) #endif { error = "Error reading the PNG file."; goto done; } /* Set up the input control */ lib.png_set_read_fn(png_ptr, src, png_read_data); /* Read PNG header info */ lib.png_read_info(png_ptr, info_ptr); lib.png_get_IHDR(png_ptr, info_ptr, &width, &height, &bit_depth, &color_type, &interlace_type, NULL, NULL); /* tell libpng to strip 16 bit/color files down to 8 bits/color */ lib.png_set_strip_16(png_ptr) ; /* Extract multiple pixels with bit depths of 1, 2, and 4 from a single * byte into separate bytes (useful for paletted and grayscale images). */ lib.png_set_packing(png_ptr); /* scale greyscale values to the range 0..255 */ if(color_type == PNG_COLOR_TYPE_GRAY) lib.png_set_expand(png_ptr); /* For images with a single "transparent colour", set colour key; if more than one index has transparency, or if partially transparent entries exist, use full alpha channel */ if (lib.png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS)) { int num_trans; Uint8 *trans; lib.png_get_tRNS(png_ptr, info_ptr, &trans, &num_trans, &transv); if(color_type == PNG_COLOR_TYPE_PALETTE) { /* Check if all tRNS entries are opaque except one */ int i, t = -1; for(i = 0; i < num_trans; i++) if(trans[i] == 0) { if(t >= 0) break; t = i; } else if(trans[i] != 255) break; if(i == num_trans) { /* exactly one transparent index */ ckey = t; } else { /* more than one transparent index, or translucency */ lib.png_set_expand(png_ptr); } } else ckey = 0; /* actual value will be set later */ } if ( color_type == PNG_COLOR_TYPE_GRAY_ALPHA ) lib.png_set_gray_to_rgb(png_ptr); lib.png_read_update_info(png_ptr, info_ptr); lib.png_get_IHDR(png_ptr, info_ptr, &width, &height, &bit_depth, &color_type, &interlace_type, NULL, NULL); /* Allocate the SDL surface to hold the image */ Rmask = Gmask = Bmask = Amask = 0 ; if ( color_type != PNG_COLOR_TYPE_PALETTE ) { if ( SDL_BYTEORDER == SDL_LIL_ENDIAN ) { Rmask = 0x000000FF; Gmask = 0x0000FF00; Bmask = 0x00FF0000; Amask = (lib.png_get_channels(png_ptr, info_ptr) == 4) ? 0xFF000000 : 0; } else { int s = (lib.png_get_channels(png_ptr, info_ptr) == 4) ? 0 : 8; Rmask = 0xFF000000 >> s; Gmask = 0x00FF0000 >> s; Bmask = 0x0000FF00 >> s; Amask = 0x000000FF >> s; } } surface = SDL_AllocSurface(SDL_SWSURFACE, width, height, bit_depth*lib.png_get_channels(png_ptr, info_ptr), Rmask,Gmask,Bmask,Amask); if ( surface == NULL ) { error = "Out of memory"; goto done; } if(ckey != -1) { if(color_type != PNG_COLOR_TYPE_PALETTE) /* FIXME: Should these be truncated or shifted down? */ ckey = SDL_MapRGB(surface->format, (Uint8)transv->red, (Uint8)transv->green, (Uint8)transv->blue); SDL_SetColorKey(surface, SDL_SRCCOLORKEY, ckey); } /* Create the array of pointers to image data */ row_pointers = (png_bytep*) malloc(sizeof(png_bytep)*height); if ( (row_pointers == NULL) ) { error = "Out of memory"; goto done; } for (row = 0; row < (int)height; row++) { row_pointers[row] = (png_bytep) (Uint8 *)surface->pixels + row*surface->pitch; } /* Read the entire image in one go */ lib.png_read_image(png_ptr, row_pointers); /* and we're done! (png_read_end() can be omitted if no processing of * post-IDAT text/time/etc. is desired) * In some cases it can't read PNG's created by some popular programs (ACDSEE), * we do not want to process comments, so we omit png_read_end lib.png_read_end(png_ptr, info_ptr); */ /* Load the palette, if any */ palette = surface->format->palette; if ( palette ) { int png_num_palette; png_colorp png_palette; lib.png_get_PLTE(png_ptr, info_ptr, &png_palette, &png_num_palette); if(color_type == PNG_COLOR_TYPE_GRAY) { palette->ncolors = 256; for(i = 0; i < 256; i++) { palette->colors[i].r = i; palette->colors[i].g = i; palette->colors[i].b = i; } } else if (png_num_palette > 0 ) { palette->ncolors = png_num_palette; for( i=0; i<png_num_palette; ++i ) { palette->colors[i].b = png_palette[i].blue; palette->colors[i].g = png_palette[i].green; palette->colors[i].r = png_palette[i].red; } } } done: /* Clean up and return */ if ( png_ptr ) { lib.png_destroy_read_struct(&png_ptr, info_ptr ? &info_ptr : (png_infopp)0, (png_infopp)0); } if ( row_pointers ) { free(row_pointers); } if ( error ) { SDL_RWseek(src, start, SEEK_SET); if ( surface ) { SDL_FreeSurface(surface); surface = NULL; } IMG_QuitPNG(); IMG_SetError(error); } else { IMG_QuitPNG(); } return(surface); }
void TCOD_sys_load_font() { int i; bool hasTransparent=false; int x,y; charmap=TCOD_sys_load_image(font_file); if (charmap == NULL ) TCOD_fatal("SDL : cannot load %s",font_file); if ( (float)(charmap->w / fontNbCharHoriz) != charmap->w / fontNbCharHoriz || (float)(charmap->h / fontNbCharVertic) != charmap->h / fontNbCharVertic ) TCOD_fatal(" %s size is not a multiple of font layout (%dx%d)\n", font_file,fontNbCharHoriz,fontNbCharVertic); fontWidth=charmap->w/fontNbCharHoriz; fontHeight=charmap->h/fontNbCharVertic; check_ascii_to_tcod(); // figure out what kind of font we have // check if the alpha layer is actually used if ( charmap->format->BytesPerPixel == 4 ) for (x=0; !hasTransparent && x < charmap->w; x ++ ) { for (y=0;!hasTransparent && y < charmap->h; y++ ) { Uint8 *pixel=(Uint8 *)(charmap->pixels) + y * charmap->pitch + x * charmap->format->BytesPerPixel; Uint8 alpha=*((pixel)+charmap->format->Ashift/8); if ( alpha < 255 ) { hasTransparent=true; } } } if (! hasTransparent ) { // 24 bit font. check if greyscale int x,y,keyx,keyy; Uint8 *pixel; // the key color is found on the character corresponding to space ' ' if ( fontTcodLayout ) { keyx = fontWidth/2; keyy = fontHeight/2; } else if (fontInRow) { keyx = ((int)(' ') % fontNbCharHoriz ) * fontWidth + fontWidth/2; keyy = ((int)(' ') / fontNbCharHoriz ) * fontHeight + fontHeight/2; } else { keyx = ((int)(' ') / fontNbCharVertic ) * fontWidth + fontWidth/2; keyy = ((int)(' ') % fontNbCharVertic ) * fontHeight + fontHeight/2; } pixel=(Uint8 *)(charmap->pixels) + keyy * charmap->pitch + keyx * charmap->format->BytesPerPixel; fontKeyCol.r=*((pixel)+charmap->format->Rshift/8); fontKeyCol.g=*((pixel)+charmap->format->Gshift/8); fontKeyCol.b=*((pixel)+charmap->format->Bshift/8); // convert greyscale to font with alpha layer if ( fontIsGreyscale ) { bool invert=( fontKeyCol.r > 128 ); // black on white font ? // convert it to 32 bits if needed if ( charmap->format->BytesPerPixel != 4 ) { SDL_Surface *temp=(SDL_Surface *)TCOD_sys_get_surface(charmap->w,charmap->h,true); SDL_BlitSurface(charmap,NULL,temp,NULL); SDL_FreeSurface(charmap); charmap=temp; } for (x=0; x < charmap->w; x ++ ) { for (y=0;y < charmap->h; y++ ) { Uint8 *pixel=(Uint8 *)(charmap->pixels) + y * charmap->pitch + x * charmap->format->BytesPerPixel; Uint8 r=*((pixel)+charmap->format->Rshift/8); *((pixel)+charmap->format->Ashift/8) = (invert ? 255-r : r); *((pixel)+charmap->format->Rshift/8)=255; *((pixel)+charmap->format->Gshift/8)=255; *((pixel)+charmap->format->Bshift/8)=255; } } } else { // alpha layer not used. convert to 24 bits (faster) SDL_Surface *temp=(SDL_Surface *)TCOD_sys_get_surface(charmap->w,charmap->h,false); SDL_BlitSurface(charmap,NULL,temp,NULL); SDL_FreeSurface(charmap); charmap=temp; } } /* charmap=SDL_CreateRGBSurface(SDL_SWSURFACE,charmap->w,charmap->h,24,0xFF0000, 0xFF00, 0xFF, 0); if ( SDL_MUSTLOCK( charmap ) ) SDL_LockSurface( charmap ); SDL_BlitSurface(charmap,NULL,charmap,NULL); */ sdl_key=SDL_MapRGB(charmap->format,fontKeyCol.r,fontKeyCol.g,fontKeyCol.b); rgb_mask=charmap->format->Rmask|charmap->format->Gmask|charmap->format->Bmask; nrgb_mask = ~ rgb_mask; sdl_key &= rgb_mask; // remove the alpha part if ( charmap->format->BytesPerPixel == 3 ) SDL_SetColorKey(charmap,SDL_SRCCOLORKEY|SDL_RLEACCEL,sdl_key); for (i=0; i < fontNbCharHoriz*fontNbCharVertic; i++ ) { charcols[i]=fontKeyCol; first_draw[i]=true; } check_ascii_to_tcod(); if (!fontTcodLayout) { // apply standard ascii mapping for (i=0; i < TCOD_max_font_chars; i++ ) ascii_to_tcod[i]=i; } }
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 palette"); /* 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(); seprintf(caption, lastof(caption), "OpenTTD %s", _openttd_revision); SDL_CALL SDL_WM_SetCaption(caption, caption); GameSizeChanged(); return true; }
Image * IMG_LoadGIF_RW(SDL_RWops *src) { unsigned char buf[16]; unsigned char c; unsigned char localColorMap[3][MAXCOLORMAPSIZE]; int grayScale; int useGlobalColormap; int bitPixel; int imageCount = 0; char version[4]; int imageNumber = 1; Image *image = NULL; if ( src == NULL ) { goto done; } if (!ReadOK(src, buf, 6)) { RWSetMsg("error reading magic number"); goto done; } if (strncmp((char *) buf, "GIF", 3) != 0) { RWSetMsg("not a GIF file"); goto done; } strncpy(version, (char *) buf + 3, 3); version[3] = '\0'; if ((strcmp(version, "87a") != 0) && (strcmp(version, "89a") != 0)) { RWSetMsg("bad version number, not '87a' or '89a'"); goto done; } Gif89.transparent = -1; Gif89.delayTime = -1; Gif89.inputFlag = -1; Gif89.disposal = 0; if (!ReadOK(src, buf, 7)) { RWSetMsg("failed to read screen descriptor"); goto done; } GifScreen.Width = LM_to_uint(buf[0], buf[1]); GifScreen.Height = LM_to_uint(buf[2], buf[3]); GifScreen.BitPixel = 2 << (buf[4] & 0x07); GifScreen.ColorResolution = (((buf[4] & 0x70) >> 3) + 1); GifScreen.Background = buf[5]; GifScreen.AspectRatio = buf[6]; if (BitSet(buf[4], LOCALCOLORMAP)) { /* Global Colormap */ if (ReadColorMap(src, GifScreen.BitPixel, GifScreen.ColorMap, &GifScreen.GrayScale)) { RWSetMsg("error reading global colormap"); goto done; } } do { if (!ReadOK(src, &c, 1)) { RWSetMsg("EOF / read error on image data"); goto done; } if (c == ';') { /* GIF terminator */ if (imageCount < imageNumber) { RWSetMsg("only %d image%s found in file", imageCount, imageCount > 1 ? "s" : ""); goto done; } } if (c == '!') { /* Extension */ if (!ReadOK(src, &c, 1)) { RWSetMsg("EOF / read error on extention function code"); goto done; } DoExtension(src, c); continue; } if (c != ',') { /* Not a valid start character */ continue; } ++imageCount; if (!ReadOK(src, buf, 9)) { RWSetMsg("couldn't read left/top/width/height"); goto done; } useGlobalColormap = !BitSet(buf[8], LOCALCOLORMAP); bitPixel = 1 << ((buf[8] & 0x07) + 1); if (!useGlobalColormap) { if (ReadColorMap(src, bitPixel, localColorMap, &grayScale)) { RWSetMsg("error reading local colormap"); goto done; } image = ReadImage(src, LM_to_uint(buf[4], buf[5]), LM_to_uint(buf[6], buf[7]), bitPixel, localColorMap, grayScale, BitSet(buf[8], INTERLACE), imageCount != imageNumber); } else { image = ReadImage(src, LM_to_uint(buf[4], buf[5]), LM_to_uint(buf[6], buf[7]), GifScreen.BitPixel, GifScreen.ColorMap, GifScreen.GrayScale, BitSet(buf[8], INTERLACE), imageCount != imageNumber); } } while (image == NULL); #ifdef USED_BY_SDL if ( Gif89.transparent >= 0 ) { SDL_SetColorKey(image, SDL_SRCCOLORKEY, Gif89.transparent); } #endif done: return image; }
/* This is a fairly slow function to switch from colorkey to alpha */ static void SDL_ConvertColorkeyToAlpha(SDL_Surface * surface) { int x, y; if (!surface) { return; } if (!(surface->map->info.flags & SDL_COPY_COLORKEY) || !surface->format->Amask) { return; } SDL_LockSurface(surface); switch (surface->format->BytesPerPixel) { case 2: { Uint16 *row, *spot; Uint16 ckey = (Uint16) surface->map->info.colorkey; Uint16 mask = (Uint16) (~surface->format->Amask); row = (Uint16 *) surface->pixels; for (y = surface->h; y--;) { spot = row; for (x = surface->w; x--;) { if (*spot == ckey) { *spot &= mask; } ++spot; } row += surface->pitch / 2; } } break; case 3: /* FIXME */ break; case 4: { Uint32 *row, *spot; Uint32 ckey = surface->map->info.colorkey; Uint32 mask = ~surface->format->Amask; row = (Uint32 *) surface->pixels; for (y = surface->h; y--;) { spot = row; for (x = surface->w; x--;) { if (*spot == ckey) { *spot &= mask; } ++spot; } row += surface->pitch / 4; } } break; } SDL_UnlockSurface(surface); SDL_SetColorKey(surface, 0, 0); SDL_SetSurfaceBlendMode(surface, SDL_BLENDMODE_BLEND); }
/** * Load a font from a .000 file. * * @param bonus whether to use FONTS.000 or BONUS.000 */ Font::Font (bool bonus) { File* file; unsigned char* pixels; int fileSize; int count, width, height; // Load font from FONTS.000 or BONUS.000 try { file = new File(bonus? F_BONUS: F_FONTS, false); } catch (int e) { throw e; } fileSize = file->getSize(); nCharacters = file->loadShort(256); if (bonus) { count = file->loadShort(); nCharacters -= count; // Skip sprites for (; count > 0; count--) { file->seek(4, false); width = file->loadShort(); if (width == 0xFFFF) width = 0; file->seek((width << 2) + file->loadShort(), false); } } // Load characters for (count = 0; count < nCharacters; count++) { if (file->tell() >= fileSize) { nCharacters = count; break; } width = file->loadShort(SW); height = file->loadShort(SH); if (bonus) width = (width + 3) & ~3; else width <<= 2; file->seek(4, false); pixels = file->loadPixels(width * height); characters[count] = createSurface(pixels, width, height); SDL_SetColorKey(characters[count], SDL_SRCCOLORKEY, 254); delete[] pixels; } delete file; lineHeight = characters[0]->h; // Create blank character data pixels = new unsigned char[3]; memset(pixels, 254, 3); characters[nCharacters] = createSurface(pixels, 3, 1); SDL_SetColorKey(characters[nCharacters], SDL_SRCCOLORKEY, 254); delete[] pixels; // Create ASCII->font map count = 0; if (bonus) { for (; count < 42; count++) map[count] = nCharacters; map[count++] = 37; // * for (; count < 46; count++) map[count] = nCharacters; map[count++] = 39; // . map[count++] = 38; // / for (; count < 59; count++) map[count] = count - 22; // Numbers and : } else { for (; count < 37; count++) map[count] = nCharacters; map[count++] = 36; // % for (; count < 48; count++) map[count] = nCharacters; for (; count < 58; count++) map[count] = count - 22; // Numbers } for (; count < 65; count++) map[count] = nCharacters; for (; count < 91; count++) map[count] = count - 65; // Upper-case letters for (; count < 97; count++) map[count] = nCharacters; for (; count < 123; count++) map[count] = count - 97; // Lower-case letters for (; count < 128; count++) map[count] = nCharacters; nCharacters++; for (count = 0; count < 128; count++) { if (map[count] >= nCharacters) map[count] = 0; } return; }
int init_car_list(SDL_Surface *surface, struct cars *list_cars) { struct cars *car_player = NULL; /*, *computer_player = NULL;*/ SDL_Surface *img_temp = NULL, *image = NULL; int nb = 0,bcl, computer = 0, human = 0, viewHeight, viewWidth; char *car_img = NULL, carHuman[] = IMGCAR1, carComputer[] = IMGCAR2; /******************/ /*if(list_cars == NULL) return(-1);*/ /******************/ if(CODEDEBUG) printf(" - init_car_list() : Set the critical variables for each car in the car list.\n"); car_player = list_cars; while(car_player != NULL) { car_player->my_car.playerNumber = nb; car_player->my_car.finished = 0; if(car_player -> prev != NULL) { car_player -> my_car.computer = 1; sprintf(car_player -> my_car.player_name, "Computer %d", (computer+1)); car_player -> my_car.k.keys[KEY_MOVEUP] = 0; car_player -> my_car.k.keys[KEY_MOVERIGHT] = 0; car_player -> my_car.k.keys[KEY_MOVEDOWN] = 0; car_player -> my_car.k.keys[KEY_MOVELEFT] = 0; computer++; /* car_player->my_car.computer = 0; sprintf(car_player->my_car.player_name, "Player %d", (human+1)); human++; car_player -> my_car.k.keys[KEY_MOVEUP] = SDLK_z; car_player -> my_car.k.keys[KEY_MOVERIGHT] = SDLK_d; car_player -> my_car.k.keys[KEY_MOVEDOWN] = SDLK_s; car_player -> my_car.k.keys[KEY_MOVELEFT] = SDLK_q; */ /* end here */ car_img = carComputer; } else { car_player -> my_car.computer = 0; sprintf(car_player -> my_car.player_name, "Player %d", (human+1) ); human++; car_player -> my_car.k.keys[KEY_MOVEUP] = SDLK_UP; car_player -> my_car.k.keys[KEY_MOVERIGHT] = SDLK_RIGHT; car_player -> my_car.k.keys[KEY_MOVEDOWN] = SDLK_DOWN; car_player -> my_car.k.keys[KEY_MOVELEFT] = SDLK_LEFT; car_img = carHuman; } image = Load_img_from(car_img); if(image == NULL) { fprintf(stderr, "Error loading car img\n"); /*break;*/ } else /*if(image != NULL)*/ { car_player->my_car.car = SDL_DisplayFormatAlpha(image); SDL_FreeSurface(image); image = NULL; if(car_player -> my_car.car == NULL) { fprintf(stderr, "Error allocating car img\n."); /*break;*/ } else if(CODEDEBUG) { printf("The car img has been successfully "); printf("loaded and initialized.\n"); } } car_player -> my_car.car_width = 20; car_player -> my_car.car_height = 20; /*car_player -> my_car.car = NULL; car_player -> my_car.my_car_buffer = NULL; car_player -> my_car.cmap_surface = NULL;*/ if(CODEDEBUG) printf(" -%d- One car found.\n", (nb+1) ); /*SDL_SetColorKey(car_player->my_car.car, SDL_SRCCOLORKEY, SDL_MapRGB(car_player->my_car.car->format, 0, 252, 255)); img_temp = SDL_CreateRGBSurface( SDL_SWSURFACE, car_player -> my_car.car_width*3, car_player -> my_car.car_height*3, 16, rmask, gmask, bmask, amask); if(img_temp == NULL) { fprintf(stderr, "Error creating second rgb surface\n"); return; } car_player->my_car.my_car_buffer = SDL_DisplayFormat(img_temp); if(car_player->my_car.my_car_buffer == NULL) { fprintf(stderr, "Error copying temp surface\n"); return; } SDL_FreeSurface(img_temp); img_temp = car_player -> my_car.my_car_buffer; if(0 != SDL_FillRect(img_temp, NULL, SDL_MapRGB(surface->format, 0, 252, 255)) ) { fprintf(stderr,"Error filling color in 2\n"); return; } SDL_BlitSurface(car_player->my_car.car, NULL, img_temp, NULL); SDL_FreeSurface(car_player -> my_car.car); car_player -> my_car.car = img_temp; */ /* creating the buffer */ car_player -> my_car.my_car_buffer = SDL_CreateRGBSurface( SDL_SWSURFACE /*SDL_SRCCOLORKEY*/, car_player -> my_car.car_width*3, car_player -> my_car.car_height*3, 16, rmask, gmask, bmask, amask); if(car_player -> my_car.my_car_buffer == NULL) { fprintf(stderr, "CreateRGBSurface failed: %s\n", SDL_GetError()); return(-1); } if(CODEDEBUG) printf(" 1/4 - Car buffer surface created.\n"); img_temp = SDL_DisplayFormat(car_player -> my_car.my_car_buffer); SDL_FreeSurface(car_player -> my_car.my_car_buffer); car_player -> my_car.my_car_buffer = img_temp; if(img_temp == NULL) { fprintf(stderr, "Error copying img_temp surface\n"); return(-1); } if(CODEDEBUG) printf(" 2/4 - Surface transformed successfully.\n"); if(0 != SDL_FillRect(car_player -> my_car.my_car_buffer, NULL, SDL_MapRGB(surface->format, 0, 252, 255)) ) { fprintf(stderr,"Error filling color\n"); return(-1); } if(CODEDEBUG) printf(" 3/4 - Filled with color.\n"); if(car_player->my_car.car != NULL) { SDL_SetColorKey(car_player->my_car.car, SDL_SRCCOLORKEY, SDL_MapRGB(surface->format, 0, 252, 255)); } else fprintf(stderr, "Error with car surface, please restart the game.\n"); if(CODEDEBUG) printf(" 4/4 - color key set.\n"); car_player -> my_car.speed = 0.0; car_player-> my_car.SPEED_MAX = MAX_SPEED_ROAD; if(car_player -> my_car.computer) car_player->my_car.SPEED_MAX += 1.4; car_player-> my_car.ADD_SPEED = ADD_SPEED_ROAD; car_player -> my_car.xvel = 0; car_player -> my_car.yvel = 0; car_player -> my_car.is_grass = 0; car_player -> my_car.grass_detection = 0; car_player -> my_car.rotation_side = 0; car_player -> my_car.turning = 0; car_player -> my_car.time_penality = 0; car_player -> my_car.last_checkpoint_color = 0; car_player -> my_car.last_elapsed = 0; for(bcl =0; bcl < MAX_LAPS; bcl++) { car_player -> my_car.lap_time[bcl] = 0; } car_player -> my_car.startTime = 0; car_player -> my_car.total_time = 0; car_player -> my_car.num_lap = 0; car_player -> my_car.position = 0; /*computer_player = car_player ; */ /*printf("%lf %lf\n",car_player -> my_car.car_x, car_player -> my_car.car_y); */ nb++; /*if(car_player -> my_car.car == NULL) { fprintf(stderr, "Car not set up correctly, unable to continue\n"); return(nb); }*/ car_player = car_player -> next; } car_player = list_cars; bcl = 0; if(nb > 0) { if(human == 0) nb = computer; else nb = human; /* Split the screen in horizontal */ viewHeight = surface->h/nb; viewWidth = surface->w; while(car_player != NULL) { if(car_player->my_car.computer == 0) { car_player->my_car.destView.x = 0; car_player->my_car.destView.y = bcl*viewHeight; car_player->my_car.destView.h = car_player->my_car.offsetView.h = viewHeight; car_player->my_car.destView.w = car_player->my_car.offsetView.w = viewWidth; /* printf("%s - %d %d %d %d\n", car_player->my_car.player_name, car_player->my_car.destView.x, car_player->my_car.destView.y, car_player->my_car.destView.w, car_player->my_car.destView.h); */ bcl++; } else { car_player->my_car.destView.x = car_player->my_car.destView.y = car_player->my_car.destView.w = car_player->my_car.destView.h = 0; } car_player = car_player -> next; } nb = human + computer; } return ( nb ); }
void LoadGameData(void) { SDL_Surface *tmp; /* The player's ship is stored as a 8640x96 image. This strip contains 90 individual images of the ship, rotated in four-degree increments. Take a look at fighter.bmp in an image viewer to see exactly what this means. */ tmp = SDL_LoadBMP("fighter.bmp"); if (tmp == NULL) { fprintf(stderr, "Unable to load ship image: %s\n", SDL_GetError()); exit(1); } /* Set the color key on the ship animation strip to black. Enable RLE acceleration for a performance boost. */ SDL_SetColorKey(tmp, SDL_SRCCOLORKEY|SDL_RLEACCEL, 0); /* Optimize the entire strip for fast display. */ ship_strip = SDL_DisplayFormat(tmp); if (ship_strip == NULL) { /* We were unable to convert the image (for some foul reason), but we can still use the copy we already have. This will involve a performance loss. However, this should never happen. */ ship_strip = tmp; } else SDL_FreeSurface(tmp); /* Now load the star tiles. Each tile is 64x64, assembled into a strip. We'll derive the number of tiles from the width of the loaded bitmap. */ tmp = SDL_LoadBMP("back-stars.bmp"); if (tmp == NULL) { fprintf(stderr, "Unable to load background tiles: %s\n", SDL_GetError()); exit(EXIT_FAILURE); } /* Determine how many star tiles are in the strip. We'll assume that the foreground and background strips contain the same number of stars. */ num_star_tiles = tmp->w / 64; num_star_tiles = 4; /* Attempt to optimize this strip for fast blitting. */ back_star_tiles = SDL_DisplayFormat(tmp); if (back_star_tiles == NULL) back_star_tiles = tmp; else SDL_FreeSurface(tmp); /* Load the front (parallaxing) set of star tiles. */ tmp = SDL_LoadBMP("front-stars.bmp"); if (tmp == NULL) { printf("Unable to load parallax tiles: %s\n", SDL_GetError()); exit(EXIT_FAILURE); } /* Set a black color key and request RLE acceleration. */ SDL_SetColorKey(tmp, SDL_SRCCOLORKEY | SDL_RLEACCEL, 0); /* Attempt to optimize this strip for fast blitting. */ front_star_tiles = SDL_DisplayFormat(tmp); if (front_star_tiles == NULL) front_star_tiles = tmp; else SDL_FreeSurface(tmp); }