Repeating texture to fit certain size in SFML - sfml

I have a file that contains textures. I load it to sf::Texture and split into sprites with setTextureRect.
Now lets say one sprite contains part of texture that is 20 pixels wide. How can I render it to fit width of e.g. 213 pixels. The only way I can think about is to render it to sf::RenderTexture and crop it with another sprite.
Is there a better way to do this?

You can use sf::Texture::setRepeated to do that.
However, you'll need to copy that part of your bigger image into an independant texture.
Here is an example:
#include <SFML/Graphics.hpp>
int main(int, char const**)
{
sf::RenderWindow window(sf::VideoMode(800, 600), "SFML window");
sf::Image img;
img.create(20, 20);
for (auto i = 0; i < 20; ++i) {
for (auto j = 0; j < 20; ++j) {
img.setPixel(i, j, sf::Color(255 * i / 20, 255 * j / 20, 255 * i / 20 * j / 20));
}
}
sf::Texture texture;
texture.loadFromImage(img);
texture.setRepeated(true);
sf::Sprite sprite;
sprite.setTexture(texture);
sprite.setTextureRect({ 0, 0, 800, 600 });
while (window.isOpen()) {
sf::Event event;
while (window.pollEvent(event)) {
if (event.type == sf::Event::Closed) {
window.close();
}
if (event.type == sf::Event::KeyPressed && event.key.code == sf::Keyboard::Escape) {
window.close();
}
}
window.clear();
window.draw(sprite);
window.display();
}
return EXIT_SUCCESS;
}

Related

Compile error in SFML 2.5.1 sample code in Linux

Compile error
I was looking at a configuration video in yt for linux mint but it doesn't give me the same results in arch.
#include <SFML/Graphics.hpp>
int main()
{
sf::RenderWindow window(sf::VideoMode(200, 200), "SFML works!");
sf::CircleShape shape(100.f);
shape.setFillColor(sf::Color::Green);
while (window.isOpen())
{
sf::Event event;
while (window.pollEvent(event))
{
if (event.type == sf::Event::Closed)
window.close();
}
window.clear();
window.draw(shape);
window.display();
}
return 0;
}
As the error message indicate, there is no constructor for sf::VideoMode which takes two int input for width and height. The constructor expect an argument of type Vector2u.
Create the Window as follows:
sf::RenderWindow window(sf::VideoMode({200, 200}), "SFML works!");

Strange behaviour when drawing convex shape figure in SFML

I'm drawing a convex shape figure using SFML library:
#include <SFML/Graphics.hpp>
using namespace sf;
int main()
{
RenderWindow window(VideoMode(400, 400), "SFML window");
ConvexShape convex;
convex.setPointCount(8);
convex.setPoint(0, sf::Vector2f(0, 0));
convex.setPoint(1, sf::Vector2f(180, 0));
convex.setPoint(2, sf::Vector2f(180, 90));
convex.setPoint(3, sf::Vector2f(100, 90));
convex.setPoint(4, sf::Vector2f(100, 180));
convex.setPoint(5, sf::Vector2f(30, 180));
convex.setPoint(6, sf::Vector2f(30, 90));
convex.setPoint(7, sf::Vector2f(0, 90));
convex.setPosition(100, 100);
while (window.isOpen())
{
sf::Event event;
while (window.pollEvent(event))
{
if (event.type == sf::Event::Closed)
window.close();
}
window.clear();
window.draw(convex);
window.display();
}
return EXIT_SUCCESS;
}
The points defined in clockwise order and everything is ok!
convex1
But when I change two coordinates a little bit I'm getting something that I really don't expect:
#include <SFML/Graphics.hpp>
using namespace sf;
int main()
{
RenderWindow window(VideoMode(400, 400), "SFML window");
ConvexShape convex;
convex.setPointCount(8);
convex.setPoint(0, sf::Vector2f(0, 0));
convex.setPoint(1, sf::Vector2f(180, 0));
convex.setPoint(2, sf::Vector2f(180, 90));
convex.setPoint(3, sf::Vector2f(100, 90));
convex.setPoint(4, sf::Vector2f(100, 200)); // CHANGED 180 to 200
convex.setPoint(5, sf::Vector2f(30, 200)); // CHANGED 180 to 200
convex.setPoint(6, sf::Vector2f(30, 90));
convex.setPoint(7, sf::Vector2f(0, 90));
convex.setPosition(50, 50);
while (window.isOpen())
{
sf::Event event;
while (window.pollEvent(event))
{
if (event.type == sf::Event::Closed)
window.close();
}
window.clear();
window.draw(convex);
window.display();
}
return EXIT_SUCCESS;
}
I'm getting the following window:
convex2
Why this situation take place?
These coordinates are related to the points in your Convex shape, you should use those only to change the format of the object. In order to move your entire object you should use this:
convex.move(x Position, y Position);

Rotate an axis aligned rectangle by a 90 degrees

I have rectangle object (sf::IntRect) , with attributes: left, top, width and height on a 2D plane. I want to rotate it by a multiple of 90 degrees (that is 90, 180 or 270), around point (0,0). Thus I am writing a function like this:
void rotateRect(sf::IntRect& rect, int rot)
{
//code I need
}
the rotation is either 0 (0), 1 (90), 2 (180) or 3 (270).
How can I achieve this as simply as possible.
Here is a basic solution using sf::Tranform on sf::FloatRect:
constexpr auto rotationAngle(int rot) { return rot * 90.f; }
void rotateRect(sf::IntRect& rect, int rot)
{
auto deg = rotationAngle(rot);
auto transform = sf::Transform();
transform.rotate(deg);
// Would be better if rect was a FloatRect...
auto rectf = sf::FloatRect(rect);
rectf = transform.transformRect(rectf);
rect = static_cast<sf::IntRect>(rectf);
}
However, I personally would slightly change the signature of your function to use float rects and a more compact notation:
sf::FloatRect rotateRect(sf::FloatRect const& rect, int rot)
{
return sf::Transform().rotate(rotationAngle(rot)).transformRect(rect);
}
And below a full example showing how it behaves.
#include <SFML/Graphics.hpp>
constexpr auto rotationAngle(int rot) { return rot * 90.f; }
sf::FloatRect rotateRect(sf::FloatRect const& rect, int rot)
{
return sf::Transform().rotate(rotationAngle(rot)).transformRect(rect);
}
void updateShape(sf::RectangleShape& shape, sf::FloatRect const& rect)
{
shape.setPosition(rect.left, rect.top);
shape.setSize({ static_cast<float>(rect.width), static_cast<float>(rect.height) });
}
int main(int, char const**)
{
sf::RenderWindow window(sf::VideoMode(500, 500), "rotate");
auto rect = sf::FloatRect(0, 0, 100, 50);
auto shape = sf::RectangleShape();
shape.setFillColor(sf::Color::Red);
updateShape(shape, rect);
auto view = window.getView();
view.move({ -250, -250 });
window.setView(view);
while (window.isOpen())
{
sf::Event event;
while (window.pollEvent(event))
{
if (event.type == sf::Event::Closed)
window.close();
if (event.type == sf::Event::KeyReleased && event.key.code == sf::Keyboard::R)
{
rect = rotateRect(rect, 1);
updateShape(shape, rect);
}
if (event.type == sf::Event::KeyReleased && event.key.code == sf::Keyboard::N)
{
rect = sf::FloatRect(50, 50, 100, 50);
updateShape(shape, rect);
}
if (event.type == sf::Event::KeyReleased && event.key.code == sf::Keyboard::M)
{
rect = sf::FloatRect(0, 0, 100, 50);
updateShape(shape, rect);
}
}
window.clear();
window.draw(shape);
window.display();
}
return EXIT_SUCCESS;
}
NB: I used a few trick from C++14 but I'm sure you can convert that code to C++11/C++98 if you need to.

SDL 2 program uses 1.4 GB of memory?

Okay, so I've been working on this little bouncing DVD logo thingy and I'm running to it slowly taking up more and more memory. Eventually it ends up taking a whopping 1.4 GB then slows down and crashes. Here is the code, what is wrong with it that causes it to do this?
#include <iostream>
#include <stdlib.h>
#include <time.h>
#include <SDL2/SDL.h>
#include <SDL2_ttf/SDL_ttf.h>
#include <SDL2_image/SDL_image.h>
// This sets ups the display.
SDL_Window* window = SDL_CreateWindow("DVD Thingy", 100, 100,
800, 600, SDL_WINDOW_SHOWN
| SDL_RENDERER_ACCELERATED
| SDL_RENDERER_PRESENTVSYNC);
SDL_Renderer* screen = SDL_CreateRenderer(window, -1, 0);
void drawText(char text[], int origX, int origY, SDL_Renderer* ren, TTF_Font* font, SDL_Color color) {
SDL_Surface* surfaceMessage = TTF_RenderText_Blended(font, text, color);
SDL_Texture* Message = SDL_CreateTextureFromSurface(ren, surfaceMessage);
int w = surfaceMessage->w;
int h = surfaceMessage->h;
SDL_Rect messageRect = {origX, origY, w, h};
SDL_RenderCopy(ren, Message, NULL, &messageRect);
SDL_DestroyTexture(Message);
}
int main() {
// This initializes the font class.
srand(time(NULL));
TTF_Init();
int skyboxColor = 240;
bool done = false;
int dirX = 1, dirY = 1;
TTF_Font* font = TTF_OpenFont("./Impact.ttf", 18);
TTF_SetFontOutline(font, 1);
int dvdX = rand() % 800, dvdY = rand() % 600-20;
SDL_Color white = {255, 255, 255};
SDL_Event event;
while (!done) {
while (SDL_PollEvent(&event)) {
switch(event.type) {
case SDL_QUIT:
SDL_Quit();
return 0;
default:
break;
}
}
dvdX += dirX;
dvdY += dirY;
if (dvdX > 770) {
dirX = -1;
}
if (dvdX < 0) {
dirX = 1;
}
if (dvdY < -3) {
dirY = 1;
}
if (dvdY > 580) {
dirY = -1;
}
SDL_SetRenderDrawColor( screen, 0, 0, 0, 255);
SDL_RenderClear(screen);
drawText("DVD", dvdX, dvdY, screen, font, white);
SDL_RenderPresent(screen);
SDL_Delay (1/1000 * 60);
}
return 0;
}
It would appear that in the drawText() function you are creating a new SDL_Surface by means of a call to TTF_RenderText_Blended().
You must ensure to free this surface when you are finished with it, which would appear to be at the end of the function it is created in. You already destroy the texture which you create from the surface so all you need to add is one line after that:
SDL_DestroyTexture(Message);
SDL_FreeSurface(surfaceMessage); <- Free the surface
As drawText() was being called constantly in the main while loop, it was bloating memory with SDL_Surfaces.
Just one other point, as you don't seem to be changing the text from "DVD" you could create the texture once and then just draw it where ever you need to. This would be much more efficient than creating, drawing and then destroying every single drame.

C++ SDL Movement Player "duplication"?

I'm a beginner in SDL and I am simply experimenting with movement of sprites in SDL. I have a rectangle at the bottom of the screen that you can move left and right. However, when you move the sprite left and right, it "duplicates", creating a sort of trace/snake-game-like effect when you move the player left and right. Any ideas on how to fix this?
///the headers
#include "stdafx.h"
#include <SDL.h>
#include <SDL_image.h>
#include <string>
using namespace std;
//screen attributes
const int SCREEN_WIDTH = 800;
const int SCREEN_HEIGHT = 480;
const int SPRITE_SIZE = 32;
//the surfaces
SDL_Surface *image = NULL;
SDL_Surface *screen = NULL;
int main( int argc, char* argv[] )
{
SDL_Surface *screen, *temp,/* *temp2*/ *sprite/*, *sprite2*/;
SDL_Rect rcSprite/*, rcSprite2*/;
SDL_Event event;
Uint8 *keystate;
int gameover;
//initiailise sdl
SDL_Init(SDL_INIT_VIDEO);
SDL_WM_SetCaption("Pong Move Test", "Pong Move Test");
screen = SDL_SetVideoMode(SCREEN_WIDTH, SCREEN_HEIGHT, 0, 0);
//load the sprite (paddle)
temp = SDL_LoadBMP("pongpaddle1.bmp");
sprite = SDL_DisplayFormat(temp);
SDL_FreeSurface(temp);
//set positions of sprite
rcSprite.x = 400;
rcSprite.y = 450;
gameover = 0;
//message pump
while (!gameover)
{
//look for an event
if (SDL_PollEvent(&event))
{
switch (event.type)
{
case SDL_QUIT:
gameover = 1;
break;
case SDL_KEYDOWN:
switch (event.key.keysym.sym)
{
case SDLK_ESCAPE:
case SDLK_q:
gameover = 1;
break;
}
break;
}
}
//handle sprite movement
keystate = SDL_GetKeyState(NULL);
if (keystate[SDLK_LEFT])
{
rcSprite.x -= 1;
}
if (keystate[SDLK_RIGHT])
{
rcSprite.x += 1;
}
//colide with edges of screen
if (rcSprite.x < 0)
{
rcSprite.x =0;
}
else if (rcSprite.x > (SCREEN_WIDTH - SPRITE_SIZE))
{
rcSprite.x = (SCREEN_WIDTH - SPRITE_SIZE);
}
//draw the sprite
SDL_BlitSurface(sprite, NULL, screen, &rcSprite);
//update the screen
SDL_UpdateRect(screen, 0, 0, 0, 0);
}
//clean up area
SDL_FreeSurface(sprite);
SDL_Quit();
return 0;
}
You aren't clearing the screen before drawing each frame, so you're actually drawing over the previous frame, which is why you get a 'trailing' effect.
You can solve this by using SDL_FillRect to fill the entire screen with a background color before drawing each frame:
SDL_FillRect(screen, NULL, SDL_MapRGB(screen->format, 0, 0, 0));