I need a double buffer because i'm starting to notice tearing when I want to move my texture made tile map around the screen via mouse click.
I'm using SDL2 and this is a SDL2 specific question, check out my code that produces tearing, whats wrong?
//set up buffer and display
bufferTexture = SDL_CreateTexture(renderer,SDL_PIXELFORMAT_RGBA8888,SDL_TEXTUREACCESS_STREAMING,800,600);
displayTexture = SDL_CreateTexture(renderer,SDL_PIXELFORMAT_RGBA8888,SDL_TEXTUREACCESS_TARGET,800,600);
while(running)
{
handleEvents();
SDL_SetRenderTarget(renderer,bufferTexture); // everything goes into this buffer
SDL_RenderClear(renderer); // clear buffer before draw
gTileMovement.updateMapCoordinates();
for(int i = 0; i < MAP_ROWS; i++)//rows
{
for(int j = 0; j < MAP_COLUMNS; j++)//columns
{
x = (j * 100) - (i * 100);
y = ((i * 100) + (j * 100)) / 2;
drawTiles(i,j,x,y);
}
}
//move from buffer to display texture
memcpy(&displayTexture,&bufferTexture,sizeof((&bufferTexture)+1));
//change render target back to display texture
SDL_SetRenderTarget(renderer,displayTexture);
//show it all on screen
SDL_RenderPresent(renderer);
}
for all it matters here is my drawTiles function too, is this not conventional? :
void drawTiles(int i,int j,int x,int y)
{
//updates based on a mouse clicks xy coords
gTileMovement.updateMapCoordinates();
if(tileMap[i][j] == 1) // grass?
{
gSpriteSheetTexture.render(x+gTileMovement.getUpdatedX(),y+gTileMovement.getUpdatedY(),&gSpriteClips[1]);
}
if(tileMap[i][j] == 0) // wall?
{
gSpriteSheetTexture.render(x+gTileMovement.getUpdatedX(),y+gTileMovement.getUpdatedY(),&gSpriteClips[0]);
}
if(tileMap[i][j] == 2) // tree?
{
gSpriteSheetTexture.render(x+gTileMovement.getUpdatedX(),y+gTileMovement.getUpdatedY(),&gSpriteClips[2]);
}
}
Which followes into how I SDL_RenderCopy the tiles through a class. This copies the textures onto the current targeted renderer does it not? Which is the buffer texture if i'm not mistaken.
void LTexture::render(int x, int y, SDL_Rect * clip)
{
SDL_Rect renderQuad = {x, y, mWidth, mHeight};
if(clip != NULL)
{
renderQuad.w = clip->w;
renderQuad.h = clip->h;
}
SDL_RenderCopy(renderer, mTexture, clip, &renderQuad);
}
Related
I have this function:
void Texture::render(int x, int y, int w, int h, SDL_Renderer *&renderer, double angle, SDL_Point* center, SDL_RendererFlip flip)
{
// Set a destination value to -1 to keep the current value
if (x < 0) { x = rect.x; }
if (y < 0) { y = rect.y; }
if (w < 0) { w = rect.w; }
if (h < 0) { h = rect.h; }
// Create destination rectangle
SDL_Rect dstRect = { x, y, w, h };
// Render to screen
SDL_RenderCopyEx(renderer, texture, &rect, &dstRect, angle, center, flip);
}
It works. It creates an image of the correct size at the location I want. But I want to add a chunk of code where it resizes the texture itself to be the size given in the destRect.
So, anyone who finds this and reads the conversation I had with Nelfeal in the comments will see that I had a misunderstanding of how SDL_RenderCopyEx works. There's no need to resize the texture. If you need to do something like that, you can just use the dstRect when you copy it.
Actually, as far as I can find, there isn't a method to resize the actual texture itself. I'm sure one exists, but it's definitely not something people are commonly using. Which is usually a sign that it's a bad idea.
I've tweaked my code to try and simplify it, for anybody who's trying to do something similar to me:
void render(SDL_Renderer *&renderer, SDL_Rect *dstRect=NULL, SDL_Rect &srcRect=NULL, double angle=0.0, SDL_Point* center=NULL, SDL_RendererFlip flip=SDL_FLIP_NONE);
void Texture::render(SDL_Renderer *&renderer, SDL_Rect *dstRect, SDL_Rect *srcRect, double angle, SDL_Point* center, SDL_RendererFlip flip)
{
// Check to see if a destination was provided
bool check = false;
if (dstRect == NULL)
{
check = true;
dstRect = new SDL_Rect();
dstRect->x = 0;
dstRect->y = 0;
dstRect->w = SCREEN_WIDTH;
dstRect->h = SCREEN_HEIGHT;
}
// Check to see if the entire texture is being copied
if (srcRect == NULL) { srcRect = ▭ }
// Render to screen
SDL_RenderCopyEx(renderer, texture, srcRect, dstRect, angle, center, flip);
// Free dstRect
if (check) delete dstRect;}
And it looks like this when using the function:
bgTex.render(renderer);
blobTex.render(renderer, &blobDstRect);
I have a 32-bit png file with an alpha (transparent) layer. I want to change the color of some pixels on a per-pixel basis using MFC. Performance isn't an issue (although faster is better).
I wrote code to call CImage::GetPixel() tweak the returned COLORREF, and SetPixel() the new color, but the entire image was transparent. So I wrote the following block which simply gets and sets the original color. The resulting image is entirely transparent. I also tried simply using SetPixel(x, y, RGB(255, 0, 0)) to set all pixels to red. Any advice to resolve this?
CImage image;
if(image.Load(sFilename) == S_OK)
{
TRACE(L"IsTransparencySupported %d", image.IsTransparencySupported()); // Returns 1.
TRACE(L"IsDIBSection %d", image.IsDIBSection()); // Returns 1.
TRACE(L"Size %dx%d", image.GetWidth(), image.GetHeight()); // Displays 141x165.
TRACE(L"BPP %d", image.GetBPP()); // Returns 32.
TRACE(L"Pitch %d", image.GetPitch()); // Returns -564.
COLORREF color;
for(int x = 0; x < image.GetWidth(); x++)
{
for(int y = 0; y < image.GetHeight(); y++)
{
color = image.GetPixel(x, y);
image.SetPixel(x, y, color);
}
}
if(image.Save(sFilenameNew, Gdiplus::ImageFormatPNG) != S_OK)
TRACE(L"Error saving %s.", sFilenameNew);
}
else
TRACE(L"Error loading png %s.", sFilename);
Thanks!
CImage image;
for (int i=0;i<image.ImgHeight;i++)
{
for (int j=0;j<image.ImgWidth;j++)
{
int index = i*image.ImgWidth+j;
unsigned char* pucColor = reinterpret_cast<unsigned char *> (image.GetPixelAddress(j , i));
pucColor[0] = bValues[index];
pucColor[1] = gValues[index];
pucColor[2] = rValues[index];
}
}
I am trying to create a transparent surface, blit it bigger surface (size of my screen), then create a texture of it, copy to the renderer, and finaly render present.
I have seen many other forums saying I have to use SetBlendMode (for surface, texture, and renderer), ColorKey, SetSurfaceBlendMode. I tried them all but I can't seem to get it to work. I read that SDL_BlitScaled is not suitable for combining surfaces that have transparent pixels, but I am completely lost as to what I have to do instead.
What I noticed, when I use SDL_CreateRGBSurface (with an alpha value) to create a surface, the surface's PixelFormat is RGB888 instead of RGBA8888 (what I am expecting since I provide the alpha value). Using SDL_ConvertSurfaceFormat did not help.
Can somebody tell me what I am missing?
Complete code: removed, my appologies
Please note that I have removed the attempts to get transparency working
The renderer:
mRenderer = SDL_CreateRenderer(mWindow, -1, SDL_RENDERER_ACCELERATED);
My render loop:
void CApp::Render()
{
SDL_RenderClear(mRenderer);
mBackGround->Render(mRenderer);
mForeGround->Render(mRenderer);
SDL_RenderPresent(mRenderer);
}
The big surface I am blitting to:
mSurface = SDL_CreateRGBSurface(0, CApp::Window_W(), CApp::Window_H(), 32, 0, 0, 0, 0);
The code to get tiles from a spritesheet:
bool Map::GetTilesFromSpriteSheet(SDL_Surface *pSpriteSheet, int pTile_w, int pTile_h)
{
if(pSpriteSheet->w % pTile_w == 0 && pSpriteSheet->h % pTile_h == 0) {
SDL_Rect srcRect;
srcRect.w = pTile_w;
srcRect.h = pTile_h;
for(int y = 0; y < pSpriteSheet->h / pTile_h; y++) {
for(int x = 0; x < pSpriteSheet->w / pTile_w; x++) {
srcRect.x = x*pTile_w;
srcRect.y = y*pTile_h;
SDL_Surface* tempSurface = SDL_CreateRGBSurface(0, pTile_w, pTile_h, 32, 0, 0, 0, 0);
if(SDL_BlitSurface(pSpriteSheet, &srcRect, tempSurface, nullptr)==0) {
mTiles.push_back(tempSurface);
} else {
Log("Error extracting tile (%d,%d)(w,h): %s", x, y, SDL_GetError());
return false;
}
}
}
Log("Number of tiles: %d", static_cast<int>(mTiles.size()));
} else {
Log("Background spritesheet is incompatible with tile dimensions (%d,%d)(w,h).", pTile_w, pTile_h);
return false;
}
return true;
}
This is where I combine the tiles to create the big surface:
bool Map::GenerateMap(std::vector<std::vector<int>> &pMap, std::vector<SDL_Surface*> &pTiles, SDL_Surface* pDestination)
{
SDL_Rect rect;
rect.w = mDstTile_W;
rect.h = mDstTile_H;
SDL_Surface* transparent = SDL_CreateRGBSurface(0, mDstTile_W, mDstTile_H, 32, 0, 0, 0, 0);
for(int y = 0; y < static_cast<int>(pMap.size()); y++) {
for(int x = 0; x < static_cast<int>(pMap.at(static_cast<unsigned long>(y)).size()); x++) {
rect.x = x*mDstTile_W;
rect.y = y*mDstTile_H;
int index = static_cast<int>(pMap.at(static_cast<unsigned long>(y)).at(static_cast<unsigned long>(x)));
if(index < 0) {
if(SDL_BlitScaled(transparent, nullptr, pDestination, &rect) != 0) {
Log("Error blitting transparent surface to destination: %s", SDL_GetError());
}
} else if(SDL_BlitScaled(pTiles[static_cast<unsigned long>(index)],
nullptr, pDestination, &rect) != 0) {
Log("Error blitting surface to destination: %s", SDL_GetError());
return false;
}
}
}
SDL_FreeSurface(transparent);
return true;
}
And finaly, this is the code to render the big surface to the screen, first by creating a texture:
void ForeGround::Render(SDL_Renderer* pRenderer)
{
if(mTexture) SDL_DestroyTexture(mTexture);
mTexture = SDL_CreateTextureFromSurface(pRenderer, mSurface);
if(mTexture == nullptr) {
Log("Unable to create foreground texture: %s", SDL_GetError());
} else if (SDL_RenderCopy(pRenderer, mTexture, nullptr, nullptr)) {
Log("Unable to render foreground: %s", SDL_GetError());
}
}
As #keltar mentioned, I was not creating surfaces with an alpha value.
I had to change the SDL_CreateRGBSurface call. The code snippet below creates an empty, transparent surface where I can blit to if needed (for example, tiles from a spritesheet).
SDL_Surface* tempSurface = SDL_CreateRGBSurface(..., 32, 0xff, 0xff00, 0xff0000, 0xff000000);
The code snippet below creates a black, non-transparent surface.
SDL_Surface* tempSurface = SDL_CreateRGBSurface(..., 32, 0xff, 0xff00, 0xff0000, 0x00000000);
This was enough for me, I did not have to use SDL_SetRenderDrawBlendMode, SDL_SetSurfaceBlendMode, SDL_SetTextureBlendMode, or SDL_ConvertSurface. A quick look at the SDL wiki showed:
By default surfaces with an alpha mask are set up for blending as with
SDL_SetSurfaceBlendMode(surface, SDL_BLENDMODE_BLEND)
Which explained why I did not have to call any of those functions. A big shout-out to keltar for his quick answer!
I'm having an issue with a program I'm working on. Occasionally, it will just freeze. No errors or anything.
The game is a multiplayer game where you fly a ship around. Pictures of other players and powerups move in and out of view depending on your location. For the most part, it works great, but under certain circumstances, it locks up.
I've tracked it down to when it BLITs one surface onto another. (SDL_BlitSurface).
If I comment out the single line of code where it blits (SDL_BlitSurface), and replace the graphic with a simple circle, it'll never freeze under any circumstances. But, comment out the circle and replace it with blitting the graphic again, and it'll randomly freeze. The frustrating part is, sometimes it will, sometimes it won't. Sometimes the graphic will sit on screen for a few moments and then freeze, sometimes it'll freeze the moment it shows up. Sometimes, it won't freeze at all. I simply cannot track it down to anything in particular.
I have ample amount of code that checks for NULL surfaces and it doesn't seem to stop it.
I also have it set up to output information about all the graphics to a file (such as width, height, location in memory, x, y, etc) and nothing seems out of the ordinary.
My main questions are, what about surfaces can cause SDL_BlitSurface to freeze? And what other checks can I add for surfaces to make sure it doesn't try to blit bad surfaces?
The code is too long to list, but here is how it works:
class Player
{
Player();
int x;
int y;
int xvel;
int yvel;
SDL_Surface *DrawScreen;
SDL_Surface *ShipPic;
void check_player_dist();
void check_powerup_dist();
void update();
};
class PowerUp
{
int x;
int y;
int type;
SDL_Surface *Powerup_Pic;
};
Player::Player()
{
Apply_Surface(0, 0, PlayerShipPics, ShipPic);
}
Player::Update(Player p[], PowerUp pu[])
{
x += xvel;
y += yvel;
for (int i = 0; i < Num_Players; i++)
{
if (check_on_screen(p[i].x, p[i].y) == true)
{
Apply_Surface(x - p[i].x, y - p[i].y, p[i].ShipPic, DrawScreen);
}
}
for (int i = 0; i < Num_PowerUps; i++)
{
if (check_on_screen(pu[i].x, pu[i].y) == true)
{
Apply_Surface(x - pu[i].x, y - pu[i].y, pu[i].Pic, DrawScreen);
}
}
}
int main()
{
SDL_Surface *Screen;
Player players[4];
PowerUp powerups[200];
Num_Players = 4;
Num_PowerUps = 200;
while (quit == false)
{
for (int i = 0; i < Num_Players; i++)
{
players[i].update(players, powerups);
switch (i)
{
case 0: ScreenX = 0; ScreenY = 0; break;
case 1: ScreenX = ScreenWid / 2; ScreenY = 0; break;
case 2: ScreenX = 0; ScreenY = ScreenHigh / 2; break;
case 3: ScreenX = ScreenWid / 2; ScreenY = ScreenHigh / 2; break;
}
Apply_Surface (ScreenX, ScreenY, players[i].DrawScreen, Screen);
}
if (SDL_Flip(Screen) == -1)
{
return -1;
}
}
}
void Apply_Surface (int x, int y, SDL_Surface* Source, SDL_Surface* Destination, SDL_Rect* Clip)
{
SDL_Rect Offset;
Offset.x = x;
Offset.y = y;
if ((Source != NULL) && (Destination != NULL))
{
SDL_BlitSurface (Source, Clip, Destination, &Offset );
}
}
I've noticed it generally freezes when two or more players are near each other and it tries to draw the same power-up on both of their screens. But again...not always!
Well, I figured out what it was.
I was using the SDL_GFX library along with my game. Many of the images were created using rotozoomSurface(), which is a function of SDL_GFX.
Turns out there's a bug in it where, under certain circumstances that I don't know, it'll create a bad surface that will work "most" of the time, but under the right conditions, will crash. Such as, being placed at a particular x & y coordinate on the screen. (Don't know for sure). The rotated/zoomed images would work about 95% of the time, so it was very difficult to pin point what the issue was.
The work around was, when the image was created, just SDL_BlitSurface() it onto another surface under controlled conditions, such as putting it at coordinates (0, 0). Then, delete the rotated and zoomed surface, and just use the new "safe" surface.
Works great after that.
Hopefully this will help anyone who's using SDL_GFX and cannot figure out why their program is crashing.
Example:
Before:
SDL_Surface *original = SDL_CreateRGBSurface(SDL_SWSURFACE, Ship_Width, Ship_Height, Screen_BPP, 0, 0, 0, 0);
Apply_Surface(0, 0, ShipsPic, original, &bounds);
SDL_Surface *finished = rotozoomSurface(original, pic_angle, zoom, SMOOTHING_ON);
SDL_FreeSurface(original);
return finished;
After (fixed):
SDL_Surface *original = SDL_CreateRGBSurface(SDL_SWSURFACE, Ship_Width, Ship_Height, Screen_BPP, 0, 0, 0, 0);
Apply_Surface(0, 0, ShipsPic, original, &bounds);
SDL_Surface *temp = rotozoomSurface(original, pic_angle, zoom, SMOOTHING_ON);
SDL_Surface *finished = SDL_CreateRGBSurface(SDL_SWSURFACE, temp->w, temp->h, Screen_BPP, 0, 0, 0, 0);
Apply_Surface(0, 0, temp, finished);
SDL_FreeSurface(temp);
SDL_FreeSurface(original);
return finished;
And for what it's worth, the Apply_Surface() function:
void Apply_Surface (int x, int y, SDL_Surface* Source, SDL_Surface* Destination, SDL_Rect* Clip)
{
SDL_Rect Offset;
Offset.x = x;
Offset.y = y;
if ((Source != NULL) && (Destination != NULL))
{
SDL_BlitSurface (Source, Clip, Destination, &Offset );
}
}
There's not really enough information to figure out what exactly is going on. Computers don't like to do things "sometimes," they either do them or not, so it leads me to believe that maybe there's some variable that's doing something it shouldn't.
Just in case, what does your Apply_Surface() function look like? I assume that's where you're doing your actual blitting, and if that's where you're having your problems, that would be useful for those of us trying to figure out your dilemma.
I'm developing game in iPhone in that pixel perfect collision will work only if one sprite appears on scene otherwise it wont work.can you please provide me some information?
I used this code for pixel perfect collision between animated sprites(spritesheet).
-(BOOL) isCollisionBetweenSpriteA:(CCSprite*)spr1 spriteB:(CCSprite*)spr2 pixelPerfect:(BOOL)pp
{
BOOL isCollision = NO;
CGRect intersection = CGRectIntersection([spr1 boundingBox], [spr2 boundingBox]);
// Look for simple bounding box collision
if (!CGRectIsEmpty(intersection))
{
// If we're not checking for pixel perfect collisions, return true
if (!pp) {return YES;}
CGPoint spr1OldPosition = spr1.position;
CGPoint spr2OldPosition = spr2.position;
spr1.position = CGPointMake(spr1.position.x - intersection.origin.x, spr1.position.y - intersection.origin.y);
spr2.position = CGPointMake(spr2.position.x - intersection.origin.x, spr2.position.y - intersection.origin.y);
intersection = CGRectIntersection([spr1 boundingBox], [spr2 boundingBox]);
// Assuming that the spritebatchnode of both sprites is the same, I just use one. If each sprite has a different sprite batch node as parent you should modify the code to get the spriteBatchNode for each sprite and visit them.
CCSpriteBatchNode* _sbnMain =(CCSpriteBatchNode*) spr1.parent;
//NOTE: We are assuming that the spritebatchnode is always at 0,0
// Get intersection info
unsigned int x = (intersection.origin.x)* CC_CONTENT_SCALE_FACTOR();
unsigned int y = (intersection.origin.y)* CC_CONTENT_SCALE_FACTOR();
unsigned int w = intersection.size.width* CC_CONTENT_SCALE_FACTOR();
unsigned int h = intersection.size.height* CC_CONTENT_SCALE_FACTOR();
unsigned int numPixels = w * h;// * CC_CONTENT_SCALE_FACTOR();
// create render texture and make it visible for testing purposes
int renderWidth = w+1;
int renderHeight = h+1;
if(renderWidth<32)
{
renderWidth =32;
}
if(renderHeight < 32)
{
renderHeight =32;
}
renderTexture = [[CCRenderTexture alloc] initWithWidth:renderWidth height:renderHeight pixelFormat:kCCTexture2DPixelFormat_RGBA8888];
//rt is always going to be at 0,0 - can't change it.
renderTexture.position = CGPointMake(0, 0);
[self addChild:renderTexture];
renderTexture.visible = NO;
//NSLog(#"\nintersection = (%u,%u,%u,%u), area = %u",x,y,w,h,numPixels);
// Draw into the RenderTexture
[renderTexture beginWithClear:0 g:0 b:0 a:0];
// Render both sprites: first one in RED and second one in GREEN
glColorMask(1, 0, 0, 1);
[_sbnMain visitSprite:spr1];
glColorMask(0, 1, 0, 1);
[_sbnMain visitSprite:spr2];
glColorMask(1, 1, 1, 1);
// Get color values of intersection area
ccColor4B *buffer = malloc( sizeof(ccColor4B) * numPixels );
glReadPixels(x, y, w, h, GL_RGBA, GL_UNSIGNED_BYTE, buffer);
[renderTexture end];
// Read buffer
unsigned int step = 1;
for(unsigned int i=0; i<numPixels; i+=step)
{
ccColor4B color = buffer[i];
if (color.r > 0 && color.g > 0)
{
isCollision = YES;
break;
}
}
// Free buffer memory
free(buffer);
spr1.position = spr1OldPosition;
spr2.position = spr2OldPosition;
[renderTexture release];
[self removeChild:renderTexture cleanup:YES];
} return isCollision;}