You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
class sf::InputSoundFile
: private sf::NonCopyable
Provide read access to sound files.
This class decodes audio samples from a sound file.
It is used internally by higher-level classes such as sf::SoundBuffer and sf::Music, but can also be useful if you want to process or analyze audio files without playing them, or if you want to implement your own version of sf::Music with more specific features.
Usage example:
// Open a sound file
sf::InputSoundFile file;
if (!file.openFromFile("music.ogg"))
/* error */;
// Print the sound attributes
std::cout << "duration: " << file.getDuration().asSeconds() << std::endl;
std::cout << "channels: " << file.getChannelCount() << std::endl;
std::cout << "sample rate: " << file.getSampleRate() << std::endl;
std::cout << "sample count: " << file.getSampleCount() << std::endl;
// Read and process batches of samples until the end of file is reached
sf::Int16 samples[1024];
sf::Uint64 count;
do
{
count = file.read(samples, 1024);
// process, analyze, play, convert, or whatever// you want to do with the samples...
}
while (count > 0);
Change the current read position to the given sample offset.
This function takes a sample offset to provide maximum precision. If you need to jump to a given time, use the other overload.
The sample offset takes the channels into account. If you have a time offset instead, you can easily find the corresponding sample offset with the following formula: timeInSeconds * sampleRate * channelCount If the given offset exceeds to total number of samples, this function jumps to the end of the sound file.
Parameters
sampleOffset Index of the sample to jump to, relative to the beginning
Change the current read position to the given time offset.
Using a time offset is handy but imprecise. If you need an accurate result, consider using the overload which takes a sample offset.
If the given time exceeds to total duration, this function jumps to the end of the sound file.
Parameters
timeOffsetTime to jump to, relative to the beginning
public Uint64 read(Int16 * samples,Uint64 maxCount)
Read audio samples from the open file.
Parameters
samples Pointer to the sample array to fill
maxCount Maximum number of samples to read
Returns
Number of samples actually read (may be less than maxCount)
class sf::Listener
The audio listener is the point in the scene from where all the sounds are heard.
The audio listener defines the global properties of the audio environment, it defines where and how sounds and musics are heard.
If sf::View is the eyes of the user, then sf::Listener is his ears (by the way, they are often linked together same position, orientation, etc.).
sf::Listener is a simple interface, which allows to setup the listener in the 3D audio environment (position, direction and up vector), and to adjust the global volume.
Because the listener is unique in the scene, sf::Listener only contains static functions and doesn't have to be instantiated.
Usage example:
// Move the listener to the position (1, 0, -5)sf::Listener::setPosition(1, 0, -5);
// Make it face the right axis (1, 0, 0)sf::Listener::setDirection(1, 0, 0);
// Reduce the global volumesf::Listener::setGlobalVolume(50);
Summary
Members
Descriptions
Members
class sf::Music
class sf::Music
: public sf::SoundStream
Streamed music played from an audio file.
Musics are sounds that are streamed rather than completely loaded in memory.
This is especially useful for compressed musics that usually take hundreds of MB when they are uncompressed: by streaming it instead of loading it entirely, you avoid saturating the memory and have almost no loading delay. This implies that the underlying resource (file, stream or memory buffer) must remain valid for the lifetime of the sf::Music object.
Apart from that, a sf::Music has almost the same features as the sf::SoundBuffer / sf::Sound pair: you can play/pause/stop it, request its parameters (channels, sample rate), change the way it is played (pitch, volume, 3D position, ...), etc.
As a sound stream, a music is played in its own thread in order not to block the rest of the program. This means that you can leave the music alone after calling play(), it will manage itself very well.
Usage example:
// Declare a new music
sf::Music music;
// Open it from an audio fileif (!music.openFromFile("music.ogg"))
{
// error...
}
// Change some parameters
music.setPosition(0, 1, 10); // change its 3D position
music.setPitch(2); // increase the pitch
music.setVolume(50); // reduce the volume
music.setLoop(true); // make it loop// Play it
music.play();
public bool openFromFile(const std::string & filename)
Open a music from an audio file.
This function doesn't start playing the music (call play() to do so). See the documentation of sf::InputSoundFile for the list of supported formats.
Since the music is not loaded at once but rather streamed continuously, the file must remain accessible until the sf::Music object loads a new music or is destroyed.
public bool openFromMemory(const void * data,std::size_t sizeInBytes)
Open a music from an audio file in memory.
This function doesn't start playing the music (call play() to do so). See the documentation of sf::InputSoundFile for the list of supported formats.
Since the music is not loaded at once but rather streamed continuously, the data buffer must remain accessible until the sf::Music object loads a new music or is destroyed. That is, you can't deallocate the buffer right after calling this function.
Open a music from an audio file in a custom stream.
This function doesn't start playing the music (call play() to do so). See the documentation of sf::InputSoundFile for the list of supported formats.
Since the music is not loaded at once but rather streamed continuously, the stream must remain accessible until the sf::Music object loads a new music or is destroyed.
Since setLoopPoints() performs some adjustments on the provided values and rounds them to internal samples, a call to getLoopPoints() is not guaranteed to return the same times passed into a previous call to setLoopPoints(). However, it is guaranteed to return times that will map to the valid internal samples of this Music if they are later passed to setLoopPoints().
Sets the beginning and end of the sound's looping sequence using sf::Time.
Loop points allow one to specify a pair of positions such that, when the music is enabled for looping, it will seamlessly seek to the beginning whenever it encounters the end. Valid ranges for timePoints.offset and timePoints.length are [0, Dur) and (0, Dur-offset] respectively, where Dur is the value returned by getDuration(). Note that the EOF "loop point" from the end to the beginning of the stream is still honored, in case the caller seeks to a point after the end of the loop range. This function can be safely called at any point after a stream is opened, and will be applied to a playing sound without affecting the current playing offset.
Setting the loop points while the stream's status is Paused will set its status to Stopped. The playing offset will be unaffected.
Parameters
timePoints The definition of the loop. Can be any time points within the sound's length
This function starts the stream if it was stopped, resumes it if it was paused, and restarts it from the beginning if it was already playing. This function uses its own thread so that it doesn't block the rest of the program while the stream is played.
This function stops the stream if it was playing or paused, and does nothing if it was already stopped. It also resets the playing position (unlike pause()).
Change the current playing position of the stream.
The playing position can be changed when the stream is either paused or playing. Changing the playing position when the stream is stopped has no effect, since playing the stream would reset its position.
Parameters
timeOffset New playing position, from the beginning of the stream
Set whether or not the stream should loop after reaching the end.
If set, the stream will restart from beginning after reaching the end and so on, until it is stopped or setLoop(false) is called. The default looping state for streams is false.
The pitch represents the perceived fundamental frequency of a sound; thus you can make a sound more acute or grave by changing its pitch. A side effect of changing the pitch is to modify the playing speed of the sound as well. The default value for the pitch is 1.
Make the sound's position relative to the listener or absolute.
Making a sound relative to the listener will ensure that it will always be played the same way regardless of the position of the listener. This can be useful for non-spatialized sounds, sounds that are produced by the listener, or sounds attached to it. The default value is false (position is absolute).
Parameters
relative True to set the position relative, false to set it absolute
The "minimum distance" of a sound is the maximum distance at which it is heard at its maximum volume. Further than the minimum distance, it will start to fade out according to its attenuation factor. A value of 0 ("inside the head
of the listener") is an invalid value and is forbidden. The default value of the minimum distance is 1.
The attenuation is a multiplicative factor which makes the sound more or less loud according to its distance from the listener. An attenuation of 0 will produce a non-attenuated sound, i.e. its volume will always be the same whether it is heard from near or from far. On the other hand, an attenuation value such as 100 will make the sound fade out very quickly as it gets further from the listener. The default value of the attenuation is 1.
Change the current playing position in the stream source to the loop offset.
This is called by the underlying SoundStream whenever it needs us to reset the seek position for a loop. We then determine whether we are looping on a loop point or the end-of-file, perform the seek, and return the new position.
Returns
The seek position after looping (or -1 if there's no loop)
protected void initialize(unsigned int channelCount,unsigned int sampleRate)
Define the audio stream parameters.
This function must be called by derived classes as soon as they know the audio settings of the stream to play. Any attempt to manipulate the stream (play(), ...) before calling this function will fail. It can be called multiple times if the settings of the audio stream change, but only when the stream is stopped.
class sf::OutputSoundFile
: private sf::NonCopyable
Provide write access to sound files.
This class encodes audio samples to a sound file.
It is used internally by higher-level classes such as sf::SoundBuffer, but can also be useful if you want to create audio files from custom data sources, like generated audio samples.
Usage example:
// Create a sound file, ogg/vorbis format, 44100 Hz, stereo
sf::OutputSoundFile file;
if (!file.openFromFile("music.ogg", 44100, 2))
/* error */;
while (...)
{
// Read or generate audio samples from your custom source
std::vector<sf::Int16> samples = ...;
// Write them to the file
file.write(samples.data(), samples.size());
}
Ability to modify output parameters in real-time (pitch, volume, ...)
3D spatial features (position, attenuation, ...).
sf::Sound is perfect for playing short sounds that can fit in memory and require no latency, like foot steps or gun shots. For longer sounds, like background musics or long speeches, rather see sf::Music (which is based on streaming).
In order to work, a sound must be given a buffer of audio data to play. Audio data (samples) is stored in sf::SoundBuffer, and attached to a sound with the setBuffer() function. The buffer object attached to a sound must remain alive as long as the sound uses it. Note that multiple sounds can use the same sound buffer at the same time.
This function starts the stream if it was stopped, resumes it if it was paused, and restarts it from beginning if it was it already playing. This function uses its own thread so that it doesn't block the rest of the program while the sound is played.
This function stops the sound if it was playing or paused, and does nothing if it was already stopped. It also resets the playing position (unlike pause()).
Set the source buffer containing the audio data to play.
It is important to note that the sound buffer is not copied, thus the sf::SoundBuffer instance must remain alive as long as it is attached to the sound.
Set whether or not the sound should loop after reaching the end.
If set, the sound will restart from beginning after reaching the end and so on, until it is stopped or setLoop(false) is called. The default looping state for sound is false.
The playing position can be changed when the sound is either paused or playing. Changing the playing position when the sound is stopped has no effect, since playing the sound will reset its position.
Parameters
timeOffset New playing position, from the beginning of the sound
This function is for internal use only, you don't have to use it. It is called by the sf::SoundBuffer that this sound uses, when it is destroyed in order to prevent the sound from using a dead buffer.
The pitch represents the perceived fundamental frequency of a sound; thus you can make a sound more acute or grave by changing its pitch. A side effect of changing the pitch is to modify the playing speed of the sound as well. The default value for the pitch is 1.
Make the sound's position relative to the listener or absolute.
Making a sound relative to the listener will ensure that it will always be played the same way regardless of the position of the listener. This can be useful for non-spatialized sounds, sounds that are produced by the listener, or sounds attached to it. The default value is false (position is absolute).
Parameters
relative True to set the position relative, false to set it absolute
The "minimum distance" of a sound is the maximum distance at which it is heard at its maximum volume. Further than the minimum distance, it will start to fade out according to its attenuation factor. A value of 0 ("inside the head
of the listener") is an invalid value and is forbidden. The default value of the minimum distance is 1.
The attenuation is a multiplicative factor which makes the sound more or less loud according to its distance from the listener. An attenuation of 0 will produce a non-attenuated sound, i.e. its volume will always be the same whether it is heard from near or from far. On the other hand, an attenuation value such as 100 will make the sound fade out very quickly as it gets further from the listener. The default value of the attenuation is 1.
A sound buffer holds the data of a sound, which is an array of audio samples.
A sample is a 16 bits signed integer that defines the amplitude of the sound at a given time. The sound is then reconstituted by playing these samples at a high rate (for example, 44100 samples per second is the standard rate used for playing CDs). In short, audio samples are like texture pixels, and a sf::SoundBuffer is similar to a sf::Texture.
A sound buffer can be loaded from a file (see loadFromFile() for the complete list of supported formats), from memory, from a custom stream (see sf::InputStream) or directly from an array of samples. It can also be saved back to a file.
Sound buffers alone are not very useful: they hold the audio data but cannot be played. To do so, you need to use the sf::Sound class, which provides functions to play/pause/stop the sound as well as changing the way it is outputted (volume, pitch, 3D position, ...). This separation allows more flexibility and better performances: indeed a sf::SoundBuffer is a heavy resource, and any operation on it is slow (often too slow for real-time applications). On the other side, a sf::Sound is a lightweight object, which can use the audio data of a sound buffer and change the way it is played without actually modifying that data. Note that it is also possible to bind several sf::Sound instances to the same sf::SoundBuffer.
It is important to note that the sf::Sound instance doesn't copy the buffer that it uses, it only keeps a reference to it. Thus, a sf::SoundBuffer must not be destructed while it is used by a sf::Sound (i.e. never write a function that uses a local sf::SoundBuffer instance for loading a sound).
Usage example:
// Declare a new sound buffer
sf::SoundBuffer buffer;
// Load it from a fileif (!buffer.loadFromFile("sound.wav"))
{
// error...
}
// Create a sound source and bind it to the buffer
sf::Sound sound1;
sound1.setBuffer(buffer);
// Play the sound
sound1.play();
// Create another sound source bound to the same buffer
sf::Sound sound2;
sound2.setBuffer(buffer);
// Play it with a higher pitch -- the first sound remains unchanged
sound2.setPitch(2);
sound2.play();
Get the array of audio samples stored in the buffer.
The format of the returned samples is 16 bits signed integer (sf::Int16). The total number of samples in this array is given by the getSampleCount() function.
It has the same simple interface as its base class (start(), stop()) and adds a function to retrieve the recorded sound buffer (getBuffer()).
As usual, don't forget to call the isAvailable() function before using this class (see sf::SoundRecorder for more details about this).
Usage example:
if (sf::SoundBufferRecorder::isAvailable())
{
// Record some audio data
sf::SoundBufferRecorder recorder;
recorder.start();
...
recorder.stop();
// Get the buffer containing the captured audio dataconst sf::SoundBuffer& buffer = recorder.getBuffer();
// Save it to a file (for example...)
buffer.saveToFile("my_record.ogg");
}
Get the sound buffer containing the captured audio data.
The sound buffer is valid only after the capture has ended. This function provides a read-only access to the internal sound buffer, but it can be copied if you need to make any modification to it.
The sampleRate parameter defines the number of audio samples captured per second. The higher, the better the quality (for example, 44100 samples/sec is CD quality). This function uses its own thread so that it doesn't block the rest of the program while the capture runs. Please note that only one capture can happen at the same time. You can select which capture device will be used, by passing the name to the setDevice() method. If none was selected before, the default capture device will be used. You can get a list of the names of all available capture devices by calling getAvailableDevices().
Parameters
sampleRate Desired capture rate, in number of samples per second
The sample rate defines the number of audio samples captured per second. The higher, the better the quality (for example, 44100 samples/sec is CD quality).
This function sets the audio capture device to the device with the given name. It can be called on the fly (i.e: while recording). If you do so while recording and opening the device fails, it stops the recording.
The processing interval controls the period between calls to the onProcessSamples function. You may want to use a small interval if you want to process the recorded data in real time, for example.
Note: this is only a hint, the actual period may vary. So don't rely on this parameter to implement precise timing.
The default processing interval is 100 ms.
Parameters
interval Processing interval
class sf::SoundFileFactory
Manages and instantiates sound file readers and writers.
This class is where all the sound file readers and writers are registered.
You should normally only need to use its registration and unregistration functions; readers/writers creation and manipulation are wrapped into the higher-level classes sf::InputSoundFile and sf::OutputSoundFile.
To register a new reader (writer) use the sf::SoundFileFactory::registerReader (registerWriter) static function. You don't have to call the unregisterReader (unregisterWriter) function, unless you want to unregister a format before your application ends (typically, when a plugin is unloaded).
This class allows users to read audio file formats not natively supported by SFML, and thus extend the set of supported readable audio formats.
A valid sound file reader must override the open, seek and write functions, as well as providing a static check function; the latter is used by SFML to find a suitable writer for a given input file.
classMySoundFileReader : publicsf::SoundFileReader
{
public:staticboolcheck(sf::InputStream& stream)
{
// typically, read the first few header bytes and check fields that identify the format// return true if the reader can handle the format
}
virtualboolopen(sf::InputStream& stream, Info& info)
{
// read the sound file header and fill the sound attributes// (channel count, sample count and sample rate)// return true on success
}
virtualvoidseek(sf::Uint64 sampleOffset)
{
// advance to the sampleOffset-th sample from the beginning of the sound
}
virtual sf::Uint64 read(sf::Int16* samples, sf::Uint64 maxCount)
{
// read up to 'maxCount' samples into the 'samples' array,// convert them (for example from normalized float) if they are not stored// as 16-bits signed integers in the file// return the actual number of samples read
}
};
sf::SoundFileFactory::registerReader<MySoundFileReader>();
Change the current read position to the given sample offset.
The sample offset takes the channels into account. If you have a time offset instead, you can easily find the corresponding sample offset with the following formula: timeInSeconds * sampleRate * channelCount If the given offset exceeds to total number of samples, this function must jump to the end of the file.
Parameters
sampleOffset Index of the sample to jump to, relative to the beginning
public Uint64 read(Int16 * samples,Uint64 maxCount)
Read audio samples from the open file.
Parameters
samples Pointer to the sample array to fill
maxCount Maximum number of samples to read
Returns
Number of samples actually read (may be less than maxCount)
class sf::SoundFileWriter
Abstract base class for sound file encoding.
This class allows users to write audio file formats not natively supported by SFML, and thus extend the set of supported writable audio formats.
A valid sound file writer must override the open and write functions, as well as providing a static check function; the latter is used by SFML to find a suitable writer for a given filename.
classMySoundFileWriter : publicsf::SoundFileWriter
{
public:staticboolcheck(const std::string& filename)
{
// typically, check the extension// return true if the writer can handle the format
}
virtualboolopen(const std::string& filename, unsignedint sampleRate, unsignedint channelCount)
{
// open the file 'filename' for writing,// write the given sample rate and channel count to the file header// return true on success
}
virtualvoidwrite(const sf::Int16* samples, sf::Uint64 count)
{
// write 'count' samples stored at address 'samples',// convert them (for example to normalized float) if the format requires it
}
};
sf::SoundFileFactory::registerWriter<MySoundFileWriter>();
public bool open(const std::string & filename,unsigned int sampleRate,unsigned int channelCount)
Open a sound file for writing.
Parameters
filename Path of the file to open
sampleRate Sample rate of the sound
channelCount Number of channels of the sound
Returns
True if the file was successfully opened
public void write(const Int16 * samples,Uint64 count)
Write audio samples to the open file.
Parameters
samples Pointer to the sample array to write
count Number of samples to write
class sf::SoundRecorder
class sf::SoundRecorder
: private sf::AlResource
Abstract base class for capturing sound data.
sf::SoundBuffer provides a simple interface to access the audio recording capabilities of the computer (the microphone).
As an abstract base class, it only cares about capturing sound samples, the task of making something useful with them is left to the derived class. Note that SFML provides a built-in specialization for saving the captured data to a sound buffer (see sf::SoundBufferRecorder).
A derived class has only one virtual function to override:
onProcessSamples provides the new chunks of audio samples while the capture happens
Moreover, two additional virtual functions can be overridden as well if necessary:
onStart is called before the capture happens, to perform custom initializations
onStop is called after the capture ends, to perform custom cleanup
A derived class can also control the frequency of the onProcessSamples calls, with the setProcessingInterval protected function. The default interval is chosen so that recording thread doesn't consume too much CPU, but it can be changed to a smaller value if you need to process the recorded data in real time, for example.
The audio capture feature may not be supported or activated on every platform, thus it is recommended to check its availability with the isAvailable() function. If it returns false, then any attempt to use an audio recorder will fail.
If you have multiple sound input devices connected to your computer (for example: microphone, external soundcard, webcam mic, ...) you can get a list of all available devices through the getAvailableDevices() function. You can then select a device by calling setDevice() with the appropriate device. Otherwise the default capturing device will be used.
By default the recording is in 16-bit mono. Using the setChannelCount method you can change the number of channels used by the audio capture device to record. Note that you have to decide whether you want to record in mono or stereo before starting the recording.
It is important to note that the audio capture happens in a separate thread, so that it doesn't block the rest of the program. In particular, the onProcessSamples virtual function (but not onStart and not onStop) will be called from this separate thread. It is important to keep this in mind, because you may have to take care of synchronization issues if you share data between threads. Another thing to bear in mind is that you must call stop() in the destructor of your derived class, so that the recording thread finishes before your object is destroyed.
Usage example:
classCustomRecorder : publicsf::SoundRecorder
{
~CustomRecorder()
{
// Make sure to stop the recording threadstop();
}
virtualboolonStart() // optional
{
// Initialize whatever has to be done before the capture starts
...
// Return true to start playingreturntrue;
}
virtualboolonProcessSamples(const Int16* samples, std::size_t sampleCount)
{
// Do something with the new chunk of samples (store them, send them, ...)
...
// Return true to continue playingreturntrue;
}
virtualvoidonStop() // optional
{
// Clean up whatever has to be done after the capture ends
...
}
}
// Usageif (CustomRecorder::isAvailable())
{
CustomRecorder recorder;
if (!recorder.start())
return -1;
...
recorder.stop();
}
The sampleRate parameter defines the number of audio samples captured per second. The higher, the better the quality (for example, 44100 samples/sec is CD quality). This function uses its own thread so that it doesn't block the rest of the program while the capture runs. Please note that only one capture can happen at the same time. You can select which capture device will be used, by passing the name to the setDevice() method. If none was selected before, the default capture device will be used. You can get a list of the names of all available capture devices by calling getAvailableDevices().
Parameters
sampleRate Desired capture rate, in number of samples per second
The sample rate defines the number of audio samples captured per second. The higher, the better the quality (for example, 44100 samples/sec is CD quality).
This function sets the audio capture device to the device with the given name. It can be called on the fly (i.e: while recording). If you do so while recording and opening the device fails, it stops the recording.
The processing interval controls the period between calls to the onProcessSamples function. You may want to use a small interval if you want to process the recorded data in real time, for example.
Note: this is only a hint, the actual period may vary. So don't rely on this parameter to implement precise timing.
This virtual function may be overridden by a derived class if something has to be done every time a new capture starts. If not, this function can be ignored; the default implementation does nothing.
This virtual function is called every time a new chunk of recorded data is available. The derived class can then do whatever it wants with it (storing it, playing it, sending it over the network, etc.).
Parameters
samples Pointer to the new chunk of recorded samples
This virtual function may be overridden by a derived class if something has to be done every time the capture ends. If not, this function can be ignored; the default implementation does nothing.
class sf::SoundSource
class sf::SoundSource
: private sf::AlResource
Base class defining a sound's properties.
sf::SoundSource is not meant to be used directly, it only serves as a common base for all audio objects that can live in the audio environment.
It defines several properties for the sound: pitch, volume, position, attenuation, etc. All of them can be changed at any time with no impact on performances.
The pitch represents the perceived fundamental frequency of a sound; thus you can make a sound more acute or grave by changing its pitch. A side effect of changing the pitch is to modify the playing speed of the sound as well. The default value for the pitch is 1.
Make the sound's position relative to the listener or absolute.
Making a sound relative to the listener will ensure that it will always be played the same way regardless of the position of the listener. This can be useful for non-spatialized sounds, sounds that are produced by the listener, or sounds attached to it. The default value is false (position is absolute).
Parameters
relative True to set the position relative, false to set it absolute
The "minimum distance" of a sound is the maximum distance at which it is heard at its maximum volume. Further than the minimum distance, it will start to fade out according to its attenuation factor. A value of 0 ("inside the head
of the listener") is an invalid value and is forbidden. The default value of the minimum distance is 1.
The attenuation is a multiplicative factor which makes the sound more or less loud according to its distance from the listener. An attenuation of 0 will produce a non-attenuated sound, i.e. its volume will always be the same whether it is heard from near or from far. On the other hand, an attenuation value such as 100 will make the sound fade out very quickly as it gets further from the listener. The default value of the attenuation is 1.
This function stops the source if it was playing or paused, and does nothing if it was already stopped. It also resets the playing position (unlike pause()).
Unlike audio buffers (see sf::SoundBuffer), audio streams are never completely loaded in memory.
Instead, the audio data is acquired continuously while the stream is playing. This behavior allows to play a sound with no loading delay, and keeps the memory consumption very low.
Sound sources that need to be streamed are usually big files (compressed audio musics that would eat hundreds of MB in memory) or files that would take a lot of time to be received (sounds played over the network).
sf::SoundStream is a base class that doesn't care about the stream source, which is left to the derived class. SFML provides a built-in specialization for big files (see sf::Music). No network stream source is provided, but you can write your own by combining this class with the network module.
A derived class has to override two virtual functions:
onGetData fills a new chunk of audio data to be played
onSeek changes the current playing position in the source
It is important to note that each SoundStream is played in its own separate thread, so that the streaming loop doesn't block the rest of the program. In particular, the OnGetData and OnSeek virtual functions may sometimes be called from this separate thread. It is important to keep this in mind, because you may have to take care of synchronization issues if you share data between threads.
Usage example:
classCustomStream : publicsf::SoundStream
{
public:boolopen(const std::string& location)
{
// Open the source and get audio settings
...
unsignedint channelCount = ...;
unsignedint sampleRate = ...;
// Initialize the stream -- important!initialize(channelCount, sampleRate);
}
private:virtualboolonGetData(Chunk& data)
{
// Fill the chunk with audio data from the stream source// (note: must not be empty if you want to continue playing)
data.samples = ...;
data.sampleCount = ...;
// Return true to continue playingreturntrue;
}
virtualvoidonSeek(Uint32 timeOffset)
{
// Change the current position in the stream source
...
}
}
// Usage
CustomStream stream;
stream.open("path/to/stream");
stream.play();
This function starts the stream if it was stopped, resumes it if it was paused, and restarts it from the beginning if it was already playing. This function uses its own thread so that it doesn't block the rest of the program while the stream is played.
This function stops the stream if it was playing or paused, and does nothing if it was already stopped. It also resets the playing position (unlike pause()).
Change the current playing position of the stream.
The playing position can be changed when the stream is either paused or playing. Changing the playing position when the stream is stopped has no effect, since playing the stream would reset its position.
Parameters
timeOffset New playing position, from the beginning of the stream
Set whether or not the stream should loop after reaching the end.
If set, the stream will restart from beginning after reaching the end and so on, until it is stopped or setLoop(false) is called. The default looping state for streams is false.
The pitch represents the perceived fundamental frequency of a sound; thus you can make a sound more acute or grave by changing its pitch. A side effect of changing the pitch is to modify the playing speed of the sound as well. The default value for the pitch is 1.
Make the sound's position relative to the listener or absolute.
Making a sound relative to the listener will ensure that it will always be played the same way regardless of the position of the listener. This can be useful for non-spatialized sounds, sounds that are produced by the listener, or sounds attached to it. The default value is false (position is absolute).
Parameters
relative True to set the position relative, false to set it absolute
The "minimum distance" of a sound is the maximum distance at which it is heard at its maximum volume. Further than the minimum distance, it will start to fade out according to its attenuation factor. A value of 0 ("inside the head
of the listener") is an invalid value and is forbidden. The default value of the minimum distance is 1.
The attenuation is a multiplicative factor which makes the sound more or less loud according to its distance from the listener. An attenuation of 0 will produce a non-attenuated sound, i.e. its volume will always be the same whether it is heard from near or from far. On the other hand, an attenuation value such as 100 will make the sound fade out very quickly as it gets further from the listener. The default value of the attenuation is 1.
This constructor is only meant to be called by derived classes.
protected void initialize(unsigned int channelCount,unsigned int sampleRate)
Define the audio stream parameters.
This function must be called by derived classes as soon as they know the audio settings of the stream to play. Any attempt to manipulate the stream (play(), ...) before calling this function will fail. It can be called multiple times if the settings of the audio stream change, but only when the stream is stopped.
Request a new chunk of audio samples from the stream source.
This function must be overridden by derived classes to provide the audio samples to play. It is called continuously by the streaming loop, in a separate thread. The source can choose to stop the streaming loop at any time, by returning false to the caller. If you return true (i.e. continue streaming) it is important that the returned array of samples is not empty; this would stop the stream due to an internal limitation.
Change the current playing position in the stream source to the beginning of the loop.
This function can be overridden by derived classes to allow implementation of custom loop points. Otherwise, it just calls onSeek(Time::Zero) and returns 0.
Returns
The seek position after looping (or -1 if there's no loop)
The source factor specifies how the pixel you are drawing contributes to the final color. The destination factor specifies how the pixel already drawn in the buffer contributes to the final color.
The color channels RGB (red, green, blue; simply referred to as color) and A (alpha; the transparency) can be treated separately. This separation can be useful for specific blend modes, but most often you won't need it and will simply treat the color as a single unit.
The blend factors and equations correspond to their OpenGL equivalents. In general, the color of the resulting pixel is calculated according to the following formula (src is the color of the source pixel, dst the color of the destination pixel, the other variables correspond to the public members, with the equations being + or - operators):
In SFML, a blend mode can be specified every time you draw a sf::Drawable object to a render target. It is part of the sf::RenderStates compound that is passed to the member function sf::RenderTarget::draw().
The equations are mapped directly to their OpenGL equivalents, specified by glBlendEquation() or glBlendEquationSeparate().
class sf::CircleShape
class sf::CircleShape
: public sf::Shape
Specialized shape representing a circle.
This class inherits all the functions of sf::Transformable (position, rotation, scale, bounds, ...) as well as the functions of sf::Shape (outline, color, texture, ...).
Since the graphics card can't draw perfect circles, we have to fake them with multiple triangles connected to each other. The "points count" property of sf::CircleShape defines how many of these triangles to use, and therefore defines the quality of the circle.
The number of points can also be used for another purpose; with small numbers you can create any regular polygon shape: equilateral triangle, square, pentagon, hexagon, ...
The returned point is in local coordinates, that is, the shape's transforms (position, rotation, scale) are not taken into account. The result is undefined if index is out of the valid range.
Parameters
index Index of the point to get, in range [0 .. getPointCount() - 1]
The texture argument refers to a texture that must exist as long as the shape uses it. Indeed, the shape doesn't store its own copy of the texture, but rather keeps a pointer to the one that you passed to this function. If the source texture is destroyed and the shape tries to use it, the behavior is undefined. texture can be NULL to disable texturing. If resetRect is true, the TextureRect property of the shape is automatically adjusted to the size of the new texture. If it is false, the texture rect is left unchanged.
Parameters
texture New texture
resetRect Should the texture rect be reset to the size of the new texture?
Set the sub-rectangle of the texture that the shape will display.
The texture rect is useful when you don't want to display the whole texture, but rather a part of it. By default, the texture rect covers the entire texture.
Parameters
rect Rectangle defining the region of the texture to display
This color is modulated (multiplied) with the shape's texture if any. It can be used to colorize the shape, or change its global opacity. You can use sf::Color::Transparent to make the inside of the shape transparent, and have the outline alone. By default, the shape's fill color is opaque white.
Note that negative values are allowed (so that the outline expands towards the center of the shape), and using zero disables the outline. By default, the outline thickness is 0.
If the shape has no source texture, a NULL pointer is returned. The returned pointer is const, which means that you can't modify the texture when you retrieve it with this function.
The returned rectangle is in local coordinates, which means that it ignores the transformations (translation, rotation, scale, ...) that are applied to the entity. In other words, this function returns the bounds of the entity in the entity's coordinate system.
Get the global (non-minimal) bounding rectangle of the entity.
The returned rectangle is in global coordinates, which means that it takes into account the transformations (translation, rotation, scale, ...) that are applied to the entity. In other words, this function returns the bounds of the shape in the global 2D world's coordinate system.
This function does not necessarily return the minimal bounding rectangle. It merely ensures that the returned rectangle covers all the vertices (but possibly more). This allows for a fast approximation of the bounds as a first check; you may want to use more precise checks on top of that.
This function completely overwrites the previous position. See the move function to apply an offset based on the previous position instead. The default position of a transformable object is (0, 0).
This function completely overwrites the previous position. See the move function to apply an offset based on the previous position instead. The default position of a transformable object is (0, 0).
This function completely overwrites the previous rotation. See the rotate function to add an angle based on the previous rotation instead. The default rotation of a transformable object is 0.
This function completely overwrites the previous scale. See the scale function to add a factor based on the previous scale instead. The default scale of a transformable object is (1, 1).
This function completely overwrites the previous scale. See the scale function to add a factor based on the previous scale instead. The default scale of a transformable object is (1, 1).
The origin of an object defines the center point for all transformations (position, scale, rotation). The coordinates of this point must be relative to the top-left corner of the object, and ignore all transformations (position, scale, rotation). The default origin of a transformable object is (0, 0).
The origin of an object defines the center point for all transformations (position, scale, rotation). The coordinates of this point must be relative to the top-left corner of the object, and ignore all transformations (position, scale, rotation). The default origin of a transformable object is (0, 0).
This function must be called by the derived class everytime the shape's points change (i.e. the result of either getPointCount or getPoint is different).
class sf::Color
Utility class for manipulating RGBA colors.
sf::Color is a simple color class composed of 4 components:
Red
Green
Blue
Alpha (opacity)
Each component is a public member, an unsigned integer in the range [0, 255]. Thus, colors can be constructed and manipulated very easily:
sf::Color color(255, 0, 0); // red
color.r = 0; // make it black
color.b = 128; // make it dark blue
The fourth component of colors, named "alpha", represents the opacity of the color. A color with an alpha value of 255 will be fully opaque, while an alpha value of 0 will make a color fully transparent, whatever the value of the other components is.
The most common colors are already defined as static variables:
sf::Color black = sf::Color::Black;
sf::Color white = sf::Color::White;
sf::Color red = sf::Color::Red;
sf::Color green = sf::Color::Green;
sf::Color blue = sf::Color::Blue;
sf::Color yellow = sf::Color::Yellow;
sf::Color magenta = sf::Color::Magenta;
sf::Color cyan = sf::Color::Cyan;
sf::Color transparent = sf::Color::Transparent;
Colors can also be added and modulated (multiplied) using the overloaded operators + and *.
This class inherits all the functions of sf::Transformable (position, rotation, scale, bounds, ...) as well as the functions of sf::Shape (outline, color, texture, ...).
It is important to keep in mind that a convex shape must always be... convex, otherwise it may not be drawn correctly. Moreover, the points must be defined in order; using a random order would result in an incorrect shape.
Don't forget that the polygon must remain convex, and the points need to stay ordered! setPointCount must be called first in order to set the total number of points. The result is undefined if index is out of the valid range.
Parameters
index Index of the point to change, in range [0 .. getPointCount() - 1]
The returned point is in local coordinates, that is, the shape's transforms (position, rotation, scale) are not taken into account. The result is undefined if index is out of the valid range.
Parameters
index Index of the point to get, in range [0 .. getPointCount() - 1]
The texture argument refers to a texture that must exist as long as the shape uses it. Indeed, the shape doesn't store its own copy of the texture, but rather keeps a pointer to the one that you passed to this function. If the source texture is destroyed and the shape tries to use it, the behavior is undefined. texture can be NULL to disable texturing. If resetRect is true, the TextureRect property of the shape is automatically adjusted to the size of the new texture. If it is false, the texture rect is left unchanged.
Parameters
texture New texture
resetRect Should the texture rect be reset to the size of the new texture?
Set the sub-rectangle of the texture that the shape will display.
The texture rect is useful when you don't want to display the whole texture, but rather a part of it. By default, the texture rect covers the entire texture.
Parameters
rect Rectangle defining the region of the texture to display
This color is modulated (multiplied) with the shape's texture if any. It can be used to colorize the shape, or change its global opacity. You can use sf::Color::Transparent to make the inside of the shape transparent, and have the outline alone. By default, the shape's fill color is opaque white.
Note that negative values are allowed (so that the outline expands towards the center of the shape), and using zero disables the outline. By default, the outline thickness is 0.
If the shape has no source texture, a NULL pointer is returned. The returned pointer is const, which means that you can't modify the texture when you retrieve it with this function.
The returned rectangle is in local coordinates, which means that it ignores the transformations (translation, rotation, scale, ...) that are applied to the entity. In other words, this function returns the bounds of the entity in the entity's coordinate system.
Get the global (non-minimal) bounding rectangle of the entity.
The returned rectangle is in global coordinates, which means that it takes into account the transformations (translation, rotation, scale, ...) that are applied to the entity. In other words, this function returns the bounds of the shape in the global 2D world's coordinate system.
This function does not necessarily return the minimal bounding rectangle. It merely ensures that the returned rectangle covers all the vertices (but possibly more). This allows for a fast approximation of the bounds as a first check; you may want to use more precise checks on top of that.
This function completely overwrites the previous position. See the move function to apply an offset based on the previous position instead. The default position of a transformable object is (0, 0).
This function completely overwrites the previous position. See the move function to apply an offset based on the previous position instead. The default position of a transformable object is (0, 0).
This function completely overwrites the previous rotation. See the rotate function to add an angle based on the previous rotation instead. The default rotation of a transformable object is 0.
This function completely overwrites the previous scale. See the scale function to add a factor based on the previous scale instead. The default scale of a transformable object is (1, 1).
This function completely overwrites the previous scale. See the scale function to add a factor based on the previous scale instead. The default scale of a transformable object is (1, 1).
The origin of an object defines the center point for all transformations (position, scale, rotation). The coordinates of this point must be relative to the top-left corner of the object, and ignore all transformations (position, scale, rotation). The default origin of a transformable object is (0, 0).
The origin of an object defines the center point for all transformations (position, scale, rotation). The coordinates of this point must be relative to the top-left corner of the object, and ignore all transformations (position, scale, rotation). The default origin of a transformable object is (0, 0).
This function must be called by the derived class everytime the shape's points change (i.e. the result of either getPointCount or getPoint is different).
class sf::Drawable
Abstract base class for objects that can be drawn to a render target.
sf::Drawable is a very simple base class that allows objects of derived classes to be drawn to a sf::RenderTarget.
All you have to do in your derived class is to override the draw virtual function.
Note that inheriting from sf::Drawable is not mandatory, but it allows this nice syntax "window.draw(object)" rather than "object.draw(window)", which is more consistent with other SFML classes.
Example:
classMyDrawable : publicsf::Drawable
{
public:
...
private:virtualvoiddraw(sf::RenderTarget& target, sf::RenderStates states) const
{
// You can draw other high-level objects
target.draw(m_sprite, states);
// ... or use the low-level API
states.texture = &m_texture;
target.draw(m_vertices, states);
// ... or draw with OpenGL directlyglBegin(GL_QUADS);
...
glEnd();
}
sf::Sprite m_sprite;
sf::Texture m_texture;
sf::VertexArray m_vertices;
};
This is a pure virtual function that has to be implemented by the derived class to define how the drawable should be drawn.
Parameters
target Render target to draw to
states Current render states
class sf::Font
Class for loading and manipulating character fonts.
Fonts can be loaded from a file, from memory or from a custom stream, and supports the most common types of fonts.
See the loadFromFile function for the complete list of supported formats.
Once it is loaded, a sf::Font instance provides three types of information about the font:
Global metrics, such as the line spacing
Per-glyph metrics, such as bounding box or kerning
Pixel representation of glyphs
Fonts alone are not very useful: they hold the font data but cannot make anything useful of it. To do so you need to use the sf::Text class, which is able to properly output text with several options such as character size, style, color, position, rotation, etc. This separation allows more flexibility and better performances: indeed a sf::Font is a heavy resource, and any operation on it is slow (often too slow for real-time applications). On the other side, a sf::Text is a lightweight object which can combine the glyphs data and metrics of a sf::Font to display any text on a render target. Note that it is also possible to bind several sf::Text instances to the same sf::Font.
It is important to note that the sf::Text instance doesn't copy the font that it uses, it only keeps a reference to it. Thus, a sf::Font must not be destructed while it is used by a sf::Text (i.e. never write a function that uses a local sf::Font instance for creating a text).
Usage example:
// Declare a new font
sf::Font font;
// Load it from a fileif (!font.loadFromFile("arial.ttf"))
{
// error...
}
// Create a text which uses our font
sf::Text text1;
text1.setFont(font);
text1.setCharacterSize(30);
text1.setStyle(sf::Text::Regular);
// Create another text using the same font, but with different parameters
sf::Text text2;
text2.setFont(font);
text2.setCharacterSize(50);
text2.setStyle(sf::Text::Italic);
Apart from loading font files, and passing them to instances of sf::Text, you should normally not have to deal directly with this class. However, it may be useful to access the font metrics or rasterized glyphs for advanced usage.
Note that if the font is a bitmap font, it is not scalable, thus not all requested sizes will be available to use. This needs to be taken into consideration when using sf::Text. If you need to display text of a certain size, make sure the corresponding bitmap font that supports that size is used.
Cleans up all the internal resources used by the font
public bool loadFromFile(const std::string & filename)
Load the font from a file.
The supported font formats are: TrueType, Type 1, CFF, OpenType, SFNT, X11 PCF, Windows FNT, BDF, PFR and Type 42. Note that this function knows nothing about the standard fonts installed on the user's system, thus you can't load them directly.
SFML cannot preload all the font data in this function, so the file has to remain accessible until the sf::Font object loads a new font or is destroyed.
public bool loadFromMemory(const void * data,std::size_t sizeInBytes)
Load the font from a file in memory.
The supported font formats are: TrueType, Type 1, CFF, OpenType, SFNT, X11 PCF, Windows FNT, BDF, PFR and Type 42.
SFML cannot preload all the font data in this function, so the buffer pointed by data has to remain valid until the sf::Font object loads a new font or is destroyed.
The supported font formats are: TrueType, Type 1, CFF, OpenType, SFNT, X11 PCF, Windows FNT, BDF, PFR and Type 42. Warning: SFML cannot preload all the font data in this function, so the contents of stream have to remain valid as long as the font is used.
SFML cannot preload all the font data in this function, so the stream has to remain accessible until the sf::Font object loads a new font or is destroyed.
public const Glyph&getGlyph(Uint32 codePoint,unsigned int characterSize,bool bold,float outlineThickness) const
Retrieve a glyph of the font.
If the font is a bitmap font, not all character sizes might be available. If the glyph is not available at the requested size, an empty glyph is returned.
Be aware that using a negative value for the outline thickness will cause distorted rendering.
Parameters
codePoint Unicode code point of the character to get
characterSize Reference character size
bold Retrieve the bold version or the regular one?
outlineThickness Thickness of outline (when != 0 the glyph will not be filled)
Returns
The glyph corresponding to codePoint and characterSize
public float getKerning(Uint32 first,Uint32 second,unsigned int characterSize) const
Get the kerning offset of two glyphs.
The kerning is an extra offset (negative) to apply between two glyphs when rendering them, to make the pair look more "natural". For example, the pair "AV" have a special kerning to make them closer than other characters. Most of the glyphs pairs have a kerning offset of zero, though.
Parameters
first Unicode code point of the first character
second Unicode code point of the second character
characterSize Reference character size
Returns
Kerning value for first and second, in pixels
public float getLineSpacing(unsigned int characterSize) const
Get the line spacing.
Line spacing is the vertical offset to apply between two consecutive lines of text.
Class for loading, manipulating and saving images.
sf::Image is an abstraction to manipulate images as bidimensional arrays of pixels.
The class provides functions to load, read, write and save pixels, as well as many other useful functions.
sf::Image can handle a unique internal representation of pixels, which is RGBA 32 bits. This means that a pixel must be composed of 8 bits red, green, blue and alpha channels just like a sf::Color. All the functions that return an array of pixels follow this rule, and all parameters that you pass to sf::Image functions (such as loadFromMemory) must use this representation as well.
A sf::Image can be copied, but it is a heavy resource and if possible you should always use [const] references to pass or return them to avoid useless copies.
Usage example:
// Load an image file from a file
sf::Image background;
if (!background.loadFromFile("background.jpg"))
return -1;
// Create a 20x20 image filled with black color
sf::Image image;
image.create(20, 20, sf::Color::Black);
// Copy image1 on image2 at position (10, 10)
image.copy(background, 10, 10);
// Make the top-left pixel transparent
sf::Color color = image.getPixel(0, 0);
color.a = 0;
image.setPixel(0, 0, color);
// Save the image to a fileif (!image.saveToFile("result.png"))
return -1;
public void create(unsigned int width,unsigned int height,const Color & color)
Create the image and fill it with a unique color.
Parameters
width Width of the image
height Height of the image
color Fill color
public void create(unsigned int width,unsigned int height,const Uint8 * pixels)
Create the image from an array of pixels.
The pixel array is assumed to contain 32-bits RGBA pixels, and have the given width and height. If not, this is an undefined behavior. If pixels is null, an empty image is created.
Parameters
width Width of the image
height Height of the image
pixels Array of pixels to copy to the image
public bool loadFromFile(const std::string & filename)
Load the image from a file on disk.
The supported image formats are bmp, png, tga, jpg, gif, psd, hdr and pic. Some format options are not supported, like progressive jpeg. If this function fails, the image is left unchanged.
public bool loadFromMemory(const void * data,std::size_t size)
Load the image from a file in memory.
The supported image formats are bmp, png, tga, jpg, gif, psd, hdr and pic. Some format options are not supported, like progressive jpeg. If this function fails, the image is left unchanged.
The supported image formats are bmp, png, tga, jpg, gif, psd, hdr and pic. Some format options are not supported, like progressive jpeg. If this function fails, the image is left unchanged.
public bool saveToFile(const std::string & filename) const
Save the image to a file on disk.
The format of the image is automatically deduced from the extension. The supported image formats are bmp, png, tga and jpg. The destination file is overwritten if it already exists. This function fails if the image is empty.
public void copy(const Image& source,unsigned int destX,unsigned int destY,constIntRect & sourceRect,bool applyAlpha)
Copy pixels from another image onto this one.
This function does a slow pixel copy and should not be used intensively. It can be used to prepare a complex static image from several others, but if you need this kind of feature in real-time you'd better use sf::RenderTexture.
If sourceRect is empty, the whole image is copied. If applyAlpha is set to true, the transparency of source pixels is applied. If it is false, the pixels are copied unchanged with their alpha value.
Parameters
source Source image to copy
destX X coordinate of the destination position
destY Y coordinate of the destination position
sourceRect Sub-rectangle of the source image to copy
applyAlpha Should the copy take into account the source transparency?
public void setPixel(unsigned int x,unsigned int y,const Color & color)
Change the color of a pixel.
This function doesn't check the validity of the pixel coordinates, using out-of-range values will result in an undefined behavior.
The returned value points to an array of RGBA pixels made of 8 bits integers components. The size of the array is width * height * 4 (getSize().x * getSize().y * 4). Warning: the returned pointer may become invalid if you modify the image, so you should never store it for too long. If the image is empty, a null pointer is returned.
Utility class for manipulating 2D axis aligned rectangles.
A rectangle is defined by its top-left corner and its size.
It is a very simple class defined for convenience, so its member variables (left, top, width and height) are public and can be accessed directly, just like the vector classes (Vector2 and Vector3).
To keep things simple, sf::Rect doesn't define functions to emulate the properties that are not directly members (such as right, bottom, center, etc.), it rather only provides intersection functions.
The left and top edges are included in the rectangle's area
The right (left + width) and bottom (top + height) edges are excluded from the rectangle's area
This means that sf::IntRect(0, 0, 1, 1) and sf::IntRect(1, 1, 1, 1) don't intersect.
sf::Rect is a template and may be used with any numeric type, but for simplicity the instantiations used by SFML are typedef'd:
sf::Rect is sf::IntRect
sf::Rect is sf::FloatRect
So that you don't have to care about the template syntax.
Usage example:
// Define a rectangle, located at (0, 0) with a size of 20x5
sf::IntRect r1(0, 0, 20, 5);
// Define another rectangle, located at (4, 2) with a size of 18x10
sf::Vector2i position(4, 2);
sf::Vector2i size(18, 10);
sf::IntRect r2(position, size);
// Test intersections with the point (3, 1)bool b1 = r1.contains(3, 1); // truebool b2 = r2.contains(3, 1); // false// Test the intersection between r1 and r2
sf::IntRect result;
bool b3 = r1.intersects(r2, result); // true// result == (4, 2, 16, 3)
Be careful, the last parameter is the size, not the bottom-right corner!
Parameters
position Position of the top-left corner of the rectangle
size Size of the rectangle
public template<> explicitRect(const Rect< U > & rectangle)
Construct the rectangle from another type of rectangle.
This constructor doesn't replace the copy constructor, it's called only when U != T. A call to this constructor will fail to compile if U is not convertible to T.
This class inherits all the functions of sf::Transformable (position, rotation, scale, bounds, ...) as well as the functions of sf::Shape (outline, color, texture, ...).
The returned point is in local coordinates, that is, the shape's transforms (position, rotation, scale) are not taken into account. The result is undefined if index is out of the valid range.
Parameters
index Index of the point to get, in range [0 .. 3]
The texture argument refers to a texture that must exist as long as the shape uses it. Indeed, the shape doesn't store its own copy of the texture, but rather keeps a pointer to the one that you passed to this function. If the source texture is destroyed and the shape tries to use it, the behavior is undefined. texture can be NULL to disable texturing. If resetRect is true, the TextureRect property of the shape is automatically adjusted to the size of the new texture. If it is false, the texture rect is left unchanged.
Parameters
texture New texture
resetRect Should the texture rect be reset to the size of the new texture?
Set the sub-rectangle of the texture that the shape will display.
The texture rect is useful when you don't want to display the whole texture, but rather a part of it. By default, the texture rect covers the entire texture.
Parameters
rect Rectangle defining the region of the texture to display
This color is modulated (multiplied) with the shape's texture if any. It can be used to colorize the shape, or change its global opacity. You can use sf::Color::Transparent to make the inside of the shape transparent, and have the outline alone. By default, the shape's fill color is opaque white.
Note that negative values are allowed (so that the outline expands towards the center of the shape), and using zero disables the outline. By default, the outline thickness is 0.
If the shape has no source texture, a NULL pointer is returned. The returned pointer is const, which means that you can't modify the texture when you retrieve it with this function.
The returned rectangle is in local coordinates, which means that it ignores the transformations (translation, rotation, scale, ...) that are applied to the entity. In other words, this function returns the bounds of the entity in the entity's coordinate system.
Get the global (non-minimal) bounding rectangle of the entity.
The returned rectangle is in global coordinates, which means that it takes into account the transformations (translation, rotation, scale, ...) that are applied to the entity. In other words, this function returns the bounds of the shape in the global 2D world's coordinate system.
This function does not necessarily return the minimal bounding rectangle. It merely ensures that the returned rectangle covers all the vertices (but possibly more). This allows for a fast approximation of the bounds as a first check; you may want to use more precise checks on top of that.
This function completely overwrites the previous position. See the move function to apply an offset based on the previous position instead. The default position of a transformable object is (0, 0).
This function completely overwrites the previous position. See the move function to apply an offset based on the previous position instead. The default position of a transformable object is (0, 0).
This function completely overwrites the previous rotation. See the rotate function to add an angle based on the previous rotation instead. The default rotation of a transformable object is 0.
This function completely overwrites the previous scale. See the scale function to add a factor based on the previous scale instead. The default scale of a transformable object is (1, 1).
This function completely overwrites the previous scale. See the scale function to add a factor based on the previous scale instead. The default scale of a transformable object is (1, 1).
The origin of an object defines the center point for all transformations (position, scale, rotation). The coordinates of this point must be relative to the top-left corner of the object, and ignore all transformations (position, scale, rotation). The default origin of a transformable object is (0, 0).
The origin of an object defines the center point for all transformations (position, scale, rotation). The coordinates of this point must be relative to the top-left corner of the object, and ignore all transformations (position, scale, rotation). The default origin of a transformable object is (0, 0).
This function must be called by the derived class everytime the shape's points change (i.e. the result of either getPointCount or getPoint is different).
class sf::RenderStates
Define the states used for drawing to a RenderTarget.
There are four global states that can be applied to the drawn objects:
the blend mode: how pixels of the object are blended with the background
the transform: how the object is positioned/rotated/scaled
the texture: what image is mapped to the object
the shader: what custom effect is applied to the object
High-level objects such as sprites or text force some of these states when they are drawn. For example, a sprite will set its own texture, so that you don't have to care about it when drawing the sprite.
The transform is a special case: sprites, texts and shapes (and it's a good idea to do it with your own drawable classes too) combine their transform with the one that is passed in the RenderStates structure. So that you can use a "global" transform on top of each object's transform.
Most objects, especially high-level drawables, can be drawn directly without defining render states explicitly the default set of states is ok in most cases.
window.draw(sprite);
If you want to use a single specific render state, for example a shader, you can pass it directly to the Draw function: sf::RenderStates has an implicit one-argument constructor for each state.
window.draw(sprite, shader);
When you're inside the Draw function of a drawable object (inherited from sf::Drawable), you can either pass the render states unmodified, or change some of them. For example, a transformable object will combine the current transform with its own transform. A sprite will set its texture. Etc.
Base class for all render targets (window, texture, ...)
sf::RenderTarget defines the common behavior of all the 2D render targets usable in the graphics module.
It makes it possible to draw 2D entities like sprites, shapes, text without using any OpenGL command directly.
A sf::RenderTarget is also able to use views (sf::View), which are a kind of 2D cameras. With views you can globally scroll, rotate or zoom everything that is drawn, without having to transform every single entity. See the documentation of sf::View for more details and sample pieces of code about this class.
On top of that, render targets are still able to render direct OpenGL stuff. It is even possible to mix together OpenGL calls and regular SFML drawing commands. When doing so, make sure that OpenGL states are not messed up by calling the pushGLStates/popGLStates functions.
The view is like a 2D camera, it controls which part of the 2D scene is visible, and how it is viewed in the render target. The new view will affect everything that is drawn, until another view is set. The render target keeps its own copy of the view object, so it is not necessary to keep the original one alive after calling this function. To restore the original view of the target, you can pass the result of getDefaultView() to this function.
Get the viewport of a view, applied to this render target.
The viewport is defined in the view as a ratio, this function simply applies this ratio to the current dimensions of the render target to calculate the pixels rectangle that the viewport actually covers in the target.
Parameters
view The view for which we want to compute the viewport
Convert a point from target coordinates to world coordinates.
This function finds the 2D position that matches the given pixel of the render target. In other words, it does the inverse of what the graphics card does, to find the initial position of a rendered pixel.
Initially, both coordinate systems (world units and target pixels) match perfectly. But if you define a custom view or resize your render target, this assertion is not true anymore, i.e. a point located at (10, 50) in your render target may map to the point (150, 75) in your 2D world if the view is translated by (140, 25).
For render-windows, this function is typically used to find which point (or object) is located below the mouse cursor.
This version uses a custom view for calculations, see the other overload of the function if you want to use the current view of the render target.
Convert a point from world coordinates to target coordinates.
This function finds the pixel of the render target that matches the given 2D point. In other words, it goes through the same process as the graphics card, to compute the final position of a rendered point.
Initially, both coordinate systems (world units and target pixels) match perfectly. But if you define a custom view or resize your render target, this assertion is not true anymore, i.e. a point located at (150, 75) in your 2D world may map to the pixel (10, 50) of your render target if the view is translated by (140, 25).
This version uses a custom view for calculations, see the other overload of the function if you want to use the current view of the render target.
Parameters
point Point to convert
view The view to use for converting the point
Returns
The converted point, in target coordinates (pixels)
Activate or deactivate the render target for rendering.
This function makes the render target's context current for future OpenGL rendering operations (so you shouldn't care about it if you're not doing direct OpenGL stuff). A render target's context is active only on the current thread, if you want to make it active on another thread you have to deactivate it on the previous thread first if it was active. Only one context can be current in a thread, so if you want to draw OpenGL geometry to another render target don't forget to activate it again. Activating a render target will automatically deactivate the previously active context (if any).
Note that this function is quite expensive: it saves all the possible OpenGL states and matrices, even the ones you don't care about. Therefore it should be used wisely. It is provided for convenience, but the best results will be achieved if you handle OpenGL states yourself (because you know which states have really changed, and need to be saved and restored). Take a look at the resetGLStates function if you do so.
Reset the internal OpenGL states so that the target is ready for drawing.
This function can be used when you mix SFML drawing and direct OpenGL rendering, if you choose not to use pushGLStates/popGLStates. It makes sure that all OpenGL states needed by SFML are set, so that subsequent draw() calls will work as expected.
It implements the same 2D drawing and OpenGL-related functions (see their base class sf::RenderTarget for more details), the difference is that the result is stored in an off-screen texture rather than being show in a window.
Rendering to a texture can be useful in a variety of situations:
precomputing a complex static texture (like a level's background from multiple tiles)
applying post-effects to the whole scene with shaders
creating a sprite from a 3D object rendered with OpenGL
etc.
Usage example:
// Create a new render-window
sf::RenderWindow window(sf::VideoMode(800, 600), "SFML window");
// Create a new render-texture
sf::RenderTexture texture;
if (!texture.create(500, 500))
return -1;
// The main loopwhile (window.isOpen())
{
// Event processing// ...// Clear the whole texture with red color
texture.clear(sf::Color::Red);
// Draw stuff to the texture
texture.draw(sprite); // sprite is a sf::Sprite
texture.draw(shape); // shape is a sf::Shape
texture.draw(text); // text is a sf::Text// We're done drawing to the texture
texture.display();
// Now we start rendering to the window, clear it first
window.clear();
// Draw the texture
sf::Sprite sprite(texture.getTexture());
window.draw(sprite);
// End the current frame and display its contents on screen
window.display();
}
Like sf::RenderWindow, sf::RenderTexture is still able to render direct OpenGL stuff. It is even possible to mix together OpenGL calls and regular SFML drawing commands. If you need a depth buffer for 3D rendering, don't forget to request it when calling RenderTexture::create.
public bool create(unsigned int width,unsigned int height,bool depthBuffer)
Create the render-texture.
Before calling this function, the render-texture is in an invalid state, thus it is mandatory to call it before doing anything with the render-texture. The last parameter, depthBuffer, is useful if you want to use the render-texture for 3D OpenGL rendering that requires a depth buffer. Otherwise it is unnecessary, and you should leave this parameter to false (which is its default value).
Parameters
width Width of the render-texture
height Height of the render-texture
depthBuffer Do you want this render-texture to have a depth buffer?
public bool create(unsigned int width,unsigned int height,const ContextSettings & settings)
Create the render-texture.
Before calling this function, the render-texture is in an invalid state, thus it is mandatory to call it before doing anything with the render-texture. The last parameter, settings, is useful if you want to enable multi-sampling or use the render-texture for OpenGL rendering that requires a depth or stencil buffer. Otherwise it is unnecessary, and you should leave this parameter at its default value.
Parameters
width Width of the render-texture
height Height of the render-texture
settings Additional settings for the underlying OpenGL texture and context
This function is similar to Texture::generateMipmap and operates on the texture used as the target for drawing. Be aware that any draw operation may modify the base level image data. For this reason, calling this function only makes sense after all drawing is completed and display has been called. Not calling display after subsequent drawing will lead to undefined behavior if a mipmap had been previously generated.
Returns
True if mipmap generation was successful, false if unsuccessful
Activate or deactivate the render-texture for rendering.
This function makes the render-texture's context current for future OpenGL rendering operations (so you shouldn't care about it if you're not doing direct OpenGL stuff). Only one context can be current in a thread, so if you want to draw OpenGL geometry to another render target (like a RenderWindow) don't forget to activate it again.
This function updates the target texture with what has been drawn so far. Like for windows, calling this function is mandatory at the end of rendering. Not calling it may leave the texture in an undefined state.
After drawing to the render-texture and calling Display, you can retrieve the updated texture using this function, and draw it using a sprite (for example). The internal sf::Texture of a render-texture is always the same instance, so that it is possible to call this function once and keep a reference to the texture even after it is modified.
The view is like a 2D camera, it controls which part of the 2D scene is visible, and how it is viewed in the render target. The new view will affect everything that is drawn, until another view is set. The render target keeps its own copy of the view object, so it is not necessary to keep the original one alive after calling this function. To restore the original view of the target, you can pass the result of getDefaultView() to this function.
Get the viewport of a view, applied to this render target.
The viewport is defined in the view as a ratio, this function simply applies this ratio to the current dimensions of the render target to calculate the pixels rectangle that the viewport actually covers in the target.
Parameters
view The view for which we want to compute the viewport
Convert a point from target coordinates to world coordinates.
This function finds the 2D position that matches the given pixel of the render target. In other words, it does the inverse of what the graphics card does, to find the initial position of a rendered pixel.
Initially, both coordinate systems (world units and target pixels) match perfectly. But if you define a custom view or resize your render target, this assertion is not true anymore, i.e. a point located at (10, 50) in your render target may map to the point (150, 75) in your 2D world if the view is translated by (140, 25).
For render-windows, this function is typically used to find which point (or object) is located below the mouse cursor.
This version uses a custom view for calculations, see the other overload of the function if you want to use the current view of the render target.
Convert a point from world coordinates to target coordinates.
This function finds the pixel of the render target that matches the given 2D point. In other words, it goes through the same process as the graphics card, to compute the final position of a rendered point.
Initially, both coordinate systems (world units and target pixels) match perfectly. But if you define a custom view or resize your render target, this assertion is not true anymore, i.e. a point located at (150, 75) in your 2D world may map to the pixel (10, 50) of your render target if the view is translated by (140, 25).
This version uses a custom view for calculations, see the other overload of the function if you want to use the current view of the render target.
Parameters
point Point to convert
view The view to use for converting the point
Returns
The converted point, in target coordinates (pixels)
Note that this function is quite expensive: it saves all the possible OpenGL states and matrices, even the ones you don't care about. Therefore it should be used wisely. It is provided for convenience, but the best results will be achieved if you handle OpenGL states yourself (because you know which states have really changed, and need to be saved and restored). Take a look at the resetGLStates function if you do so.
Reset the internal OpenGL states so that the target is ready for drawing.
This function can be used when you mix SFML drawing and direct OpenGL rendering, if you choose not to use pushGLStates/popGLStates. It makes sure that all OpenGL states needed by SFML are set, so that subsequent draw() calls will work as expected.
It defines an OS window that can be painted using the other classes of the graphics module.
sf::RenderWindow is derived from sf::Window, thus it inherits all its features: events, window management, OpenGL rendering, etc. See the documentation of sf::Window for a more complete description of all these features, as well as code examples.
On top of that, sf::RenderWindow adds more features related to 2D drawing with the graphics module (see its base class sf::RenderTarget for more details). Here is a typical rendering and event loop with a sf::RenderWindow:
// Declare and create a new render-window
sf::RenderWindow window(sf::VideoMode(800, 600), "SFML window");
// Limit the framerate to 60 frames per second (this step is optional)
window.setFramerateLimit(60);
// The main loop - ends as soon as the window is closedwhile (window.isOpen())
{
// Event processing
sf::Event event;
while (window.pollEvent(event))
{
// Request for closing the windowif (event.type == sf::Event::Closed)
window.close();
}
// Clear the whole window before rendering a new frame
window.clear();
// Draw some graphical entities
window.draw(sprite);
window.draw(circle);
window.draw(text);
// End the current frame and display its contents on screen
window.display();
}
Like sf::Window, sf::RenderWindow is still able to render direct OpenGL stuff. It is even possible to mix together OpenGL calls and regular SFML drawing commands.
// Create the render window
sf::RenderWindow window(sf::VideoMode(800, 600), "SFML OpenGL");
// Create a sprite and a text to display
sf::Sprite sprite;
sf::Text text;
...
// Perform OpenGL initializationsglMatrixMode(GL_PROJECTION);
...
// Start the rendering loopwhile (window.isOpen())
{
// Process events
...
// Draw a background sprite
window.pushGLStates();
window.draw(sprite);
window.popGLStates();
// Draw a 3D object using OpenGLglBegin(GL_QUADS);
glVertex3f(...);
...
glEnd();
// Draw text on top of the 3D object
window.pushGLStates();
window.draw(text);
window.popGLStates();
// Finally, display the rendered frame on screen
window.display();
}
This constructor creates the window with the size and pixel depth defined in mode. An optional style can be passed to customize the look and behavior of the window (borders, title bar, resizable, closable, ...).
The fourth parameter is an optional structure specifying advanced OpenGL context settings such as antialiasing, depth-buffer bits, etc. You shouldn't care about these parameters for a regular usage of the graphics module.
Parameters
mode Video mode to use (defines the width, height and depth of the rendering area of the window)
title Title of the window
style Window style, a bitwise OR combination of sf::Style enumerators
settings Additional settings for the underlying OpenGL context
Use this constructor if you want to create an SFML rendering area into an already existing control.
The second parameter is an optional structure specifying advanced OpenGL context settings such as antialiasing, depth-buffer bits, etc. You shouldn't care about these parameters for a regular usage of the graphics module.
Parameters
handle Platform-specific handle of the control (HWND on Windows, Window on Linux/FreeBSD, NSWindow on OS X)
settings Additional settings for the underlying OpenGL context
Activate or deactivate the window as the current target for OpenGL rendering.
A window is active only on the current thread, if you want to make it active on another thread you have to deactivate it on the previous thread first if it was active. Only one window can be active on a thread at a time, thus the window previously active (if any) automatically gets deactivated. This is not to be confused with requestFocus().
This is a slow operation, whose main purpose is to make screenshots of the application. If you want to update an image with the contents of the window and then use it for drawing, you should rather use a sf::Texture and its update(Window&) function. You can also draw things directly to a texture with the sf::RenderTexture class.
Create (or recreate) the window from an existing control.
Use this function if you want to create an OpenGL rendering area into an already existing control. If the window was already created, it closes it first.
The second parameter is an optional structure specifying advanced OpenGL context settings such as antialiasing, depth-buffer bits, etc.
Parameters
handle Platform-specific handle of the control
settings Additional settings for the underlying OpenGL context
Close the window and destroy all the attached resources.
After calling this function, the sf::Window instance remains valid and you can call create() to recreate the window. All other functions such as pollEvent() or display() will still work (i.e. you don't have to test isOpen() every time), and will have no effect on closed windows.
This function returns whether or not the window exists. Note that a hidden window (setVisible(false)) is open (therefore this function would return true).
Returns
True if the window is open, false if it has been closed
Get the settings of the OpenGL context of the window.
Note that these settings may be different from what was passed to the constructor or the create() function, if one or more settings were not supported. In this case, SFML chose the closest match.
Pop the event on top of the event queue, if any, and return it.
This function is not blocking: if there's no pending event then it will return false and leave event unmodified. Note that more than one event may be present in the event queue, thus you should always call this function in a loop to make sure that you process every pending event.
sf::Event event;
while (window.pollEvent(event))
{
// process event...
}
This function is blocking: if there's no pending event then it will wait until an event is received. After this function returns (and no error occurred), the event object is always valid and filled properly. This function is typically used when you have a thread that is dedicated to events handling: you want to make this thread sleep as long as no new event is received.
sf::Event event;
if (window.waitEvent(event))
{
// process event...
}
Activating vertical synchronization will limit the number of frames displayed to the refresh rate of the monitor. This can avoid some visual artifacts, and limit the framerate to a good value (but not constant across different computers).
Vertical synchronization is disabled by default.
Parameters
enabled True to enable v-sync, false to deactivate it
If set, grabs the mouse cursor inside this window's client area so it may no longer be moved outside its bounds. Note that grabbing is only active while the window has focus.
If key repeat is enabled, you will receive repeated KeyPressed events while keeping a key pressed. If it is disabled, you will only get a single event when the key is pressed.
If a limit is set, the window will use a small delay after each call to display() to ensure that the current frame lasted long enough to match the framerate limit. SFML will try to match the given limit as much as it can, but since it internally uses sf::sleep, whose precision depends on the underlying OS, the results may be a little unprecise as well (for example, you can get 65 FPS when requesting 60).
Parameters
limit Framerate limit, in frames per seconds (use 0 to disable limit)
Activate or deactivate the window as the current target for OpenGL rendering.
A window is active only on the current thread, if you want to make it active on another thread you have to deactivate it on the previous thread first if it was active. Only one window can be active on a thread at a time, thus the window previously active (if any) automatically gets deactivated. This is not to be confused with requestFocus().
Request the current window to be made the active foreground window.
At any given time, only one window may have the input focus to receive input events such as keystrokes or mouse events. If a window requests focus, it only hints to the operating system, that it would like to be focused. The operating system is free to deny the request. This is not to be confused with setActive().
The type of the returned handle is sf::WindowHandle, which is a typedef to the handle type defined by the OS. You shouldn't need to use this function, unless you have very specific stuff to implement that SFML doesn't support, or implement a temporary workaround until a bug is fixed.
The view is like a 2D camera, it controls which part of the 2D scene is visible, and how it is viewed in the render target. The new view will affect everything that is drawn, until another view is set. The render target keeps its own copy of the view object, so it is not necessary to keep the original one alive after calling this function. To restore the original view of the target, you can pass the result of getDefaultView() to this function.
Get the viewport of a view, applied to this render target.
The viewport is defined in the view as a ratio, this function simply applies this ratio to the current dimensions of the render target to calculate the pixels rectangle that the viewport actually covers in the target.
Parameters
view The view for which we want to compute the viewport
Convert a point from target coordinates to world coordinates.
This function finds the 2D position that matches the given pixel of the render target. In other words, it does the inverse of what the graphics card does, to find the initial position of a rendered pixel.
Initially, both coordinate systems (world units and target pixels) match perfectly. But if you define a custom view or resize your render target, this assertion is not true anymore, i.e. a point located at (10, 50) in your render target may map to the point (150, 75) in your 2D world if the view is translated by (140, 25).
For render-windows, this function is typically used to find which point (or object) is located below the mouse cursor.
This version uses a custom view for calculations, see the other overload of the function if you want to use the current view of the render target.
Convert a point from world coordinates to target coordinates.
This function finds the pixel of the render target that matches the given 2D point. In other words, it goes through the same process as the graphics card, to compute the final position of a rendered point.
Initially, both coordinate systems (world units and target pixels) match perfectly. But if you define a custom view or resize your render target, this assertion is not true anymore, i.e. a point located at (150, 75) in your 2D world may map to the pixel (10, 50) of your render target if the view is translated by (140, 25).
This version uses a custom view for calculations, see the other overload of the function if you want to use the current view of the render target.
Parameters
point Point to convert
view The view to use for converting the point
Returns
The converted point, in target coordinates (pixels)
Note that this function is quite expensive: it saves all the possible OpenGL states and matrices, even the ones you don't care about. Therefore it should be used wisely. It is provided for convenience, but the best results will be achieved if you handle OpenGL states yourself (because you know which states have really changed, and need to be saved and restored). Take a look at the resetGLStates function if you do so.
Reset the internal OpenGL states so that the target is ready for drawing.
This function can be used when you mix SFML drawing and direct OpenGL rendering, if you choose not to use pushGLStates/popGLStates. It makes sure that all OpenGL states needed by SFML are set, so that subsequent draw() calls will work as expected.
Shaders are programs written using a specific language, executed directly by the graphics card and allowing to apply real-time operations to the rendered entities.
There are three kinds of shaders:
Vertex shaders, that process vertices
Geometry shaders, that process primitives
Fragment (pixel) shaders, that process pixels
A sf::Shader can be composed of either a vertex shader alone, a geometry shader alone, a fragment shader alone, or any combination of them. (see the variants of the load functions).
Shaders are written in GLSL, which is a C-like language dedicated to OpenGL shaders. You'll probably need to learn its basics before writing your own shaders for SFML.
Like any C/C++ program, a GLSL shader has its own variables called uniforms that you can set from your C++ application. sf::Shader handles different types of uniforms:
Every uniform variable in a shader can be set through one of the setUniform() or setUniformArray() overloads. For example, if you have a shader with the following uniforms:
You can set their values from C++ code as follows, using the types defined in the sf::Glsl namespace:
shader.setUniform("offset", 2.f);
shader.setUniform("point", sf::Vector3f(0.5f, 0.8f, 0.3f));
shader.setUniform("color", sf::Glsl::Vec4(color)); // color is a sf::Color
shader.setUniform("matrix", sf::Glsl::Mat4(transform)); // transform is a sf::Transform
shader.setUniform("overlay", texture); // texture is a sf::Texture
shader.setUniform("current", sf::Shader::CurrentTexture);
The old setParameter() overloads are deprecated and will be removed in a future version. You should use their setUniform() equivalents instead.
The special Shader::CurrentTexture argument maps the given sampler2D uniform to the current texture of the object being drawn (which cannot be known in advance).
To apply a shader to a drawable, you must pass it as an additional parameter to the Window::draw() draw() function:
In the code above we pass a pointer to the shader, because it may be null (which means "no shader").
Shaders can be used on any drawable, but some combinations are not interesting. For example, using a vertex shader on a sf::Sprite is limited because there are only 4 vertices, the sprite would have to be subdivided in order to apply wave effects. Another bad example is a fragment shader with sf::Text: the texture of the text is not the actual text that you see on screen, it is a big texture containing all the characters of the font in an arbitrary order; thus, texture lookups on pixels other than the current one may not give you the expected result.
Shaders can also be used to apply global post-effects to the current contents of the target (like the old sf::PostFx class in SFML 1). This can be done in two different ways:
draw everything to a sf::RenderTexture, then draw it to the main target using the shader
draw everything directly to the main target, then use sf::Texture::update(Window&) to copy its contents to a texture and draw it to the main target using the shader
The first technique is more optimized because it doesn't involve retrieving the target's pixels to system memory, but the second one doesn't impact the rendering process and can be easily inserted anywhere without impacting all the code.
Like sf::Texture that can be used as a raw OpenGL texture, sf::Shader can also be used directly as a raw shader for custom OpenGL geometry.
public bool loadFromFile(const std::string & filename,Type type)
Load the vertex, geometry or fragment shader from a file.
This function loads a single shader, vertex, geometry or fragment, identified by the second argument. The source must be a text file containing a valid shader in GLSL language. GLSL is a C-like language dedicated to OpenGL shaders; you'll probably need to read a good documentation for it before writing your own shaders.
Parameters
filename Path of the vertex, geometry or fragment shader file to load
type Type of shader (vertex, geometry or fragment)
public bool loadFromFile(const std::string & vertexShaderFilename,const std::string & fragmentShaderFilename)
Load both the vertex and fragment shaders from files.
This function loads both the vertex and the fragment shaders. If one of them fails to load, the shader is left empty (the valid shader is unloaded). The sources must be text files containing valid shaders in GLSL language. GLSL is a C-like language dedicated to OpenGL shaders; you'll probably need to read a good documentation for it before writing your own shaders.
Parameters
vertexShaderFilename Path of the vertex shader file to load
fragmentShaderFilename Path of the fragment shader file to load
Load the vertex, geometry and fragment shaders from files.
This function loads the vertex, geometry and fragment shaders. If one of them fails to load, the shader is left empty (the valid shader is unloaded). The sources must be text files containing valid shaders in GLSL language. GLSL is a C-like language dedicated to OpenGL shaders; you'll probably need to read a good documentation for it before writing your own shaders.
Parameters
vertexShaderFilename Path of the vertex shader file to load
geometryShaderFilename Path of the geometry shader file to load
fragmentShaderFilename Path of the fragment shader file to load
Load the vertex, geometry or fragment shader from a source code in memory.
This function loads a single shader, vertex, geometry or fragment, identified by the second argument. The source code must be a valid shader in GLSL language. GLSL is a C-like language dedicated to OpenGL shaders; you'll probably need to read a good documentation for it before writing your own shaders.
Parameters
shaderString containing the source code of the shader
type Type of shader (vertex, geometry or fragment)
public bool loadFromMemory(const std::string & vertexShader,const std::string & fragmentShader)
Load both the vertex and fragment shaders from source codes in memory.
This function loads both the vertex and the fragment shaders. If one of them fails to load, the shader is left empty (the valid shader is unloaded). The sources must be valid shaders in GLSL language. GLSL is a C-like language dedicated to OpenGL shaders; you'll probably need to read a good documentation for it before writing your own shaders.
Parameters
vertexShaderString containing the source code of the vertex shader
fragmentShaderString containing the source code of the fragment shader
Load the vertex, geometry and fragment shaders from source codes in memory.
This function loads the vertex, geometry and fragment shaders. If one of them fails to load, the shader is left empty (the valid shader is unloaded). The sources must be valid shaders in GLSL language. GLSL is a C-like language dedicated to OpenGL shaders; you'll probably need to read a good documentation for it before writing your own shaders.
Parameters
vertexShaderString containing the source code of the vertex shader
geometryShaderString containing the source code of the geometry shader
fragmentShaderString containing the source code of the fragment shader
Load the vertex, geometry or fragment shader from a custom stream.
This function loads a single shader, vertex, geometry or fragment, identified by the second argument. The source code must be a valid shader in GLSL language. GLSL is a C-like language dedicated to OpenGL shaders; you'll probably need to read a good documentation for it before writing your own shaders.
Parameters
stream Source stream to read from
type Type of shader (vertex, geometry or fragment)
Load both the vertex and fragment shaders from custom streams.
This function loads both the vertex and the fragment shaders. If one of them fails to load, the shader is left empty (the valid shader is unloaded). The source codes must be valid shaders in GLSL language. GLSL is a C-like language dedicated to OpenGL shaders; you'll probably need to read a good documentation for it before writing your own shaders.
Parameters
vertexShaderStream Source stream to read the vertex shader from
fragmentShaderStream Source stream to read the fragment shader from
Load the vertex, geometry and fragment shaders from custom streams.
This function loads the vertex, geometry and fragment shaders. If one of them fails to load, the shader is left empty (the valid shader is unloaded). The source codes must be valid shaders in GLSL language. GLSL is a C-like language dedicated to OpenGL shaders; you'll probably need to read a good documentation for it before writing your own shaders.
Parameters
vertexShaderStream Source stream to read the vertex shader from
geometryShaderStream Source stream to read the geometry shader from
fragmentShaderStream Source stream to read the fragment shader from
This overload can also be called with sf::Color objects that are converted to sf::Glsl::Vec4.
It is important to note that the components of the color are normalized before being passed to the shader. Therefore, they are converted from range [0 .. 255] to range [0 .. 1]. For example, a sf::Color(255, 127, 0, 255) will be transformed to a vec4(1.0, 0.5, 0.0, 1.0) in the shader.
Parameters
name Name of the uniform variable in GLSL
vector Value of the vec4 vector
public void setUniform(const std::string & name,int x)
If color conversions are used, the ivec4 uniform in GLSL will hold the same values as the original sf::Color instance. For example, sf::Color(255, 127, 0, 255) is mapped to ivec4(255, 127, 0, 255).
Parameters
name Name of the uniform variable in GLSL
vector Value of the ivec4 vector
public void setUniform(const std::string & name,bool x)
This overload maps a shader texture variable to the texture of the object being drawn, which cannot be known in advance. The second argument must be sf::Shader::CurrentTexture. The corresponding parameter in the shader must be a 2D texture (sampler2D GLSL type).
Example:
uniform sampler2D current; // this is the variable in the shader
You shouldn't need to use this function, unless you have very specific stuff to implement that SFML doesn't support, or implement a temporary workaround until a bug is fixed.
Returns
OpenGL handle of the shader or 0 if not yet loaded
The texture argument refers to a texture that must exist as long as the shape uses it. Indeed, the shape doesn't store its own copy of the texture, but rather keeps a pointer to the one that you passed to this function. If the source texture is destroyed and the shape tries to use it, the behavior is undefined. texture can be NULL to disable texturing. If resetRect is true, the TextureRect property of the shape is automatically adjusted to the size of the new texture. If it is false, the texture rect is left unchanged.
Parameters
texture New texture
resetRect Should the texture rect be reset to the size of the new texture?
Set the sub-rectangle of the texture that the shape will display.
The texture rect is useful when you don't want to display the whole texture, but rather a part of it. By default, the texture rect covers the entire texture.
Parameters
rect Rectangle defining the region of the texture to display
This color is modulated (multiplied) with the shape's texture if any. It can be used to colorize the shape, or change its global opacity. You can use sf::Color::Transparent to make the inside of the shape transparent, and have the outline alone. By default, the shape's fill color is opaque white.
Note that negative values are allowed (so that the outline expands towards the center of the shape), and using zero disables the outline. By default, the outline thickness is 0.
If the shape has no source texture, a NULL pointer is returned. The returned pointer is const, which means that you can't modify the texture when you retrieve it with this function.
The returned point is in local coordinates, that is, the shape's transforms (position, rotation, scale) are not taken into account. The result is undefined if index is out of the valid range.
Parameters
index Index of the point to get, in range [0 .. getPointCount() - 1]
The returned rectangle is in local coordinates, which means that it ignores the transformations (translation, rotation, scale, ...) that are applied to the entity. In other words, this function returns the bounds of the entity in the entity's coordinate system.
Get the global (non-minimal) bounding rectangle of the entity.
The returned rectangle is in global coordinates, which means that it takes into account the transformations (translation, rotation, scale, ...) that are applied to the entity. In other words, this function returns the bounds of the shape in the global 2D world's coordinate system.
This function does not necessarily return the minimal bounding rectangle. It merely ensures that the returned rectangle covers all the vertices (but possibly more). This allows for a fast approximation of the bounds as a first check; you may want to use more precise checks on top of that.
This function completely overwrites the previous position. See the move function to apply an offset based on the previous position instead. The default position of a transformable object is (0, 0).
This function completely overwrites the previous position. See the move function to apply an offset based on the previous position instead. The default position of a transformable object is (0, 0).
This function completely overwrites the previous rotation. See the rotate function to add an angle based on the previous rotation instead. The default rotation of a transformable object is 0.
This function completely overwrites the previous scale. See the scale function to add a factor based on the previous scale instead. The default scale of a transformable object is (1, 1).
This function completely overwrites the previous scale. See the scale function to add a factor based on the previous scale instead. The default scale of a transformable object is (1, 1).
The origin of an object defines the center point for all transformations (position, scale, rotation). The coordinates of this point must be relative to the top-left corner of the object, and ignore all transformations (position, scale, rotation). The default origin of a transformable object is (0, 0).
The origin of an object defines the center point for all transformations (position, scale, rotation). The coordinates of this point must be relative to the top-left corner of the object, and ignore all transformations (position, scale, rotation). The default origin of a transformable object is (0, 0).
This function must be called by the derived class everytime the shape's points change (i.e. the result of either getPointCount or getPoint is different).
class sf::Sprite
class sf::Sprite
: public sf::Drawable
: public sf::Transformable
Drawable representation of a texture, with its own transformations, color, etc.
sf::Sprite is a drawable class that allows to easily display a texture (or a part of it) on a render target.
It inherits all the functions from sf::Transformable: position, rotation, scale, origin. It also adds sprite-specific properties such as the texture to use, the part of it to display, and some convenience functions to change the overall color of the sprite, or to get its bounding rectangle.
sf::Sprite works in combination with the sf::Texture class, which loads and provides the pixel data of a given texture.
The separation of sf::Sprite and sf::Texture allows more flexibility and better performances: indeed a sf::Texture is a heavy resource, and any operation on it is slow (often too slow for real-time applications). On the other side, a sf::Sprite is a lightweight object which can use the pixel data of a sf::Texture and draw it with its own transformation/color/blending attributes.
It is important to note that the sf::Sprite instance doesn't copy the texture that it uses, it only keeps a reference to it. Thus, a sf::Texture must not be destroyed while it is used by a sf::Sprite (i.e. never write a function that uses a local sf::Texture instance for creating a sprite).
See also the note on coordinates and undistorted rendering in sf::Transformable.
Usage example:
// Declare and load a texture
sf::Texture texture;
texture.loadFromFile("texture.png");
// Create a sprite
sf::Sprite sprite;
sprite.setTexture(texture);
sprite.setTextureRect(sf::IntRect(10, 10, 50, 30));
sprite.setColor(sf::Color(255, 255, 255, 200));
sprite.setPosition(100, 25);
// Draw it
window.draw(sprite);
The texture argument refers to a texture that must exist as long as the sprite uses it. Indeed, the sprite doesn't store its own copy of the texture, but rather keeps a pointer to the one that you passed to this function. If the source texture is destroyed and the sprite tries to use it, the behavior is undefined. If resetRect is true, the TextureRect property of the sprite is automatically adjusted to the size of the new texture. If it is false, the texture rect is left unchanged.
Parameters
texture New texture
resetRect Should the texture rect be reset to the size of the new texture?
Set the sub-rectangle of the texture that the sprite will display.
The texture rect is useful when you don't want to display the whole texture, but rather a part of it. By default, the texture rect covers the entire texture.
Parameters
rectangle Rectangle defining the region of the texture to display
This color is modulated (multiplied) with the sprite's texture. It can be used to colorize the sprite, or change its global opacity. By default, the sprite's color is opaque white.
If the sprite has no source texture, a NULL pointer is returned. The returned pointer is const, which means that you can't modify the texture when you retrieve it with this function.
The returned rectangle is in local coordinates, which means that it ignores the transformations (translation, rotation, scale, ...) that are applied to the entity. In other words, this function returns the bounds of the entity in the entity's coordinate system.
The returned rectangle is in global coordinates, which means that it takes into account the transformations (translation, rotation, scale, ...) that are applied to the entity. In other words, this function returns the bounds of the sprite in the global 2D world's coordinate system.
This function completely overwrites the previous position. See the move function to apply an offset based on the previous position instead. The default position of a transformable object is (0, 0).
This function completely overwrites the previous position. See the move function to apply an offset based on the previous position instead. The default position of a transformable object is (0, 0).
This function completely overwrites the previous rotation. See the rotate function to add an angle based on the previous rotation instead. The default rotation of a transformable object is 0.
This function completely overwrites the previous scale. See the scale function to add a factor based on the previous scale instead. The default scale of a transformable object is (1, 1).
This function completely overwrites the previous scale. See the scale function to add a factor based on the previous scale instead. The default scale of a transformable object is (1, 1).
The origin of an object defines the center point for all transformations (position, scale, rotation). The coordinates of this point must be relative to the top-left corner of the object, and ignore all transformations (position, scale, rotation). The default origin of a transformable object is (0, 0).
The origin of an object defines the center point for all transformations (position, scale, rotation). The coordinates of this point must be relative to the top-left corner of the object, and ignore all transformations (position, scale, rotation). The default origin of a transformable object is (0, 0).
class sf::Text
: public sf::Drawable
: public sf::Transformable
Graphical text that can be drawn to a render target.
sf::Text is a drawable class that allows to easily display some text with custom style and color on a render target.
It inherits all the functions from sf::Transformable: position, rotation, scale, origin. It also adds text-specific properties such as the font to use, the character size, the font style (bold, italic, underlined and strike through), the text color, the outline thickness, the outline color, the character spacing, the line spacing and the text to display of course. It also provides convenience functions to calculate the graphical size of the text, or to get the global position of a given character.
sf::Text works in combination with the sf::Font class, which loads and provides the glyphs (visual characters) of a given font.
The separation of sf::Font and sf::Text allows more flexibility and better performances: indeed a sf::Font is a heavy resource, and any operation on it is slow (often too slow for real-time applications). On the other side, a sf::Text is a lightweight object which can combine the glyphs data and metrics of a sf::Font to display any text on a render target.
It is important to note that the sf::Text instance doesn't copy the font that it uses, it only keeps a reference to it. Thus, a sf::Font must not be destructed while it is used by a sf::Text (i.e. never write a function that uses a local sf::Font instance for creating a text).
See also the note on coordinates and undistorted rendering in sf::Transformable.
Usage example:
// Declare and load a font
sf::Font font;
font.loadFromFile("arial.ttf");
// Create a text
sf::Text text("hello", font);
text.setCharacterSize(30);
text.setStyle(sf::Text::Bold);
text.setFillColor(sf::Color::Red);
// Draw it
window.draw(text);
public Text(const String& string,constFont & font,unsigned int characterSize)
Construct the text from a string, font and size.
Note that if the used font is a bitmap font, it is not scalable, thus not all requested sizes will be available to use. This needs to be taken into consideration when setting the character size. If you need to display text of a certain size, make sure the corresponding bitmap font that supports that size is used.
The font argument refers to a font that must exist as long as the text uses it. Indeed, the text doesn't store its own copy of the font, but rather keeps a pointer to the one that you passed to this function. If the font is destroyed and the text tries to use it, the behavior is undefined.
Note that if the used font is a bitmap font, it is not scalable, thus not all requested sizes will be available to use. This needs to be taken into consideration when setting the character size. If you need to display text of a certain size, make sure the corresponding bitmap font that supports that size is used.
The default spacing between lines is defined by the font. This method enables you to set a factor for the spacing between lines. By default the line spacing factor is 1.
The default spacing between letters is defined by the font. This factor doesn't directly apply to the existing spacing between each character, it rather adds a fixed space between them which is calculated from the font metrics and the character size. Note that factors below 1 (including negative numbers) bring characters closer to each other. By default the letter spacing factor is 1.
By default, the text's fill color is opaque white. Setting the fill color to a transparent color with an outline will cause the outline to be displayed in the fill area of the text.
By default, the text's fill color is opaque white. Setting the fill color to a transparent color with an outline will cause the outline to be displayed in the fill area of the text.
If the text has no font attached, a NULL pointer is returned. The returned pointer is const, which means that you cannot modify the font when you get it from this function.
This function computes the visual position of a character from its index in the string. The returned position is in global coordinates (translation, rotation, scale and origin are applied). If index is out of range, the position of the end of the string is returned.
The returned rectangle is in local coordinates, which means that it ignores the transformations (translation, rotation, scale, ...) that are applied to the entity. In other words, this function returns the bounds of the entity in the entity's coordinate system.
The returned rectangle is in global coordinates, which means that it takes into account the transformations (translation, rotation, scale, ...) that are applied to the entity. In other words, this function returns the bounds of the text in the global 2D world's coordinate system.
This function completely overwrites the previous position. See the move function to apply an offset based on the previous position instead. The default position of a transformable object is (0, 0).
This function completely overwrites the previous position. See the move function to apply an offset based on the previous position instead. The default position of a transformable object is (0, 0).
This function completely overwrites the previous rotation. See the rotate function to add an angle based on the previous rotation instead. The default rotation of a transformable object is 0.
This function completely overwrites the previous scale. See the scale function to add a factor based on the previous scale instead. The default scale of a transformable object is (1, 1).
This function completely overwrites the previous scale. See the scale function to add a factor based on the previous scale instead. The default scale of a transformable object is (1, 1).
The origin of an object defines the center point for all transformations (position, scale, rotation). The coordinates of this point must be relative to the top-left corner of the object, and ignore all transformations (position, scale, rotation). The default origin of a transformable object is (0, 0).
The origin of an object defines the center point for all transformations (position, scale, rotation). The coordinates of this point must be relative to the top-left corner of the object, and ignore all transformations (position, scale, rotation). The default origin of a transformable object is (0, 0).
Image living on the graphics card that can be used for drawing.
sf::Texture stores pixels that can be drawn, with a sprite for example.
A texture lives in the graphics card memory, therefore it is very fast to draw a texture to a render target, or copy a render target to a texture (the graphics card can access both directly).
Being stored in the graphics card memory has some drawbacks. A texture cannot be manipulated as freely as a sf::Image, you need to prepare the pixels first and then upload them to the texture in a single operation (see Texture::update).
sf::Texture makes it easy to convert from/to sf::Image, but keep in mind that these calls require transfers between the graphics card and the central memory, therefore they are slow operations.
A texture can be loaded from an image, but also directly from a file/memory/stream. The necessary shortcuts are defined so that you don't need an image first for the most common cases. However, if you want to perform some modifications on the pixels before creating the final texture, you can load your file to a sf::Image, do whatever you need with the pixels, and then call Texture::loadFromImage.
Since they live in the graphics card memory, the pixels of a texture cannot be accessed without a slow copy first. And they cannot be accessed individually. Therefore, if you need to read the texture's pixels (like for pixel-perfect collisions), it is recommended to store the collision information separately, for example in an array of booleans.
Like sf::Image, sf::Texture can handle a unique internal representation of pixels, which is RGBA 32 bits. This means that a pixel must be composed of 8 bits red, green, blue and alpha channels just like a sf::Color.
Usage example:
// This example shows the most common use of sf::Texture:// drawing a sprite// Load a texture from a file
sf::Texture texture;
if (!texture.loadFromFile("texture.png"))
return -1;
// Assign it to a sprite
sf::Sprite sprite;
sprite.setTexture(texture);
// Draw the textured sprite
window.draw(sprite);
// This example shows another common use of sf::Texture:// streaming real-time data, like video frames// Create an empty texture
sf::Texture texture;
if (!texture.create(640, 480))
return -1;
// Create a sprite that will display the texture
sf::Sprite sprite(texture);
while (...) // the main loop
{
...
// update the texture
sf::Uint8* pixels = ...; // get a fresh chunk of pixels (the next frame of a movie, for example)
texture.update(pixels);
// draw it
window.draw(sprite);
...
}
Like sf::Shader that can be used as a raw OpenGL shader, sf::Texture can also be used directly as a raw texture for custom OpenGL geometry.
The area argument can be used to load only a sub-rectangle of the whole image. If you want the entire image then leave the default value (which is an empty IntRect). If the area rectangle crosses the bounds of the image, it is adjusted to fit the image size.
The maximum size for a texture depends on the graphics driver and can be retrieved with the getMaximumSize function.
If this function fails, the texture is left unchanged.
The area argument can be used to load only a sub-rectangle of the whole image. If you want the entire image then leave the default value (which is an empty IntRect). If the area rectangle crosses the bounds of the image, it is adjusted to fit the image size.
The maximum size for a texture depends on the graphics driver and can be retrieved with the getMaximumSize function.
If this function fails, the texture is left unchanged.
The area argument can be used to load only a sub-rectangle of the whole image. If you want the entire image then leave the default value (which is an empty IntRect). If the area rectangle crosses the bounds of the image, it is adjusted to fit the image size.
The maximum size for a texture depends on the graphics driver and can be retrieved with the getMaximumSize function.
If this function fails, the texture is left unchanged.
The area argument can be used to load only a sub-rectangle of the whole image. If you want the entire image then leave the default value (which is an empty IntRect). If the area rectangle crosses the bounds of the image, it is adjusted to fit the image size.
The maximum size for a texture depends on the graphics driver and can be retrieved with the getMaximumSize function.
If this function fails, the texture is left unchanged.
This function performs a slow operation that downloads the texture's pixels from the graphics card and copies them to a new image, potentially applying transformations to pixels if necessary (texture may be padded or flipped).
The pixel array is assumed to have the same size as the area rectangle, and to contain 32-bits RGBA pixels.
No additional check is performed on the size of the pixel array, passing invalid arguments will lead to an undefined behavior.
This function does nothing if pixels is null or if the texture was not previously created.
Parameters
pixels Array of pixels to copy to the texture
public void update(const Uint8 * pixels,unsigned int width,unsigned int height,unsigned int x,unsigned int y)
Update a part of the texture from an array of pixels.
The size of the pixel array must match the width and height arguments, and it must contain 32-bits RGBA pixels.
No additional check is performed on the size of the pixel array or the bounds of the area to update, passing invalid arguments will lead to an undefined behavior.
This function does nothing if pixels is null or if the texture was not previously created.
Parameters
pixels Array of pixels to copy to the texture
width Width of the pixel region contained in pixels
height Height of the pixel region contained in pixels
x X offset in the texture where to copy the source pixels
y Y offset in the texture where to copy the source pixels
Update a part of this texture from another texture.
Although the source texture can be smaller than this texture, this function is usually used for updating the whole texture. The other overload, which has (x, y) additional arguments, is more convenient for updating a sub-area of this texture.
No additional check is performed on the size of the passed texture, passing a texture bigger than this texture will lead to an undefined behavior.
This function does nothing if either texture was not previously created.
Parameters
texture Source texture to copy to this texture
public void update(const Texture & texture,unsigned int x,unsigned int y)
Update a part of this texture from another texture.
No additional check is performed on the size of the texture, passing an invalid combination of texture size and offset will lead to an undefined behavior.
This function does nothing if either texture was not previously created.
Parameters
texture Source texture to copy to this texture
x X offset in this texture where to copy the source texture
y Y offset in this texture where to copy the source texture
Although the source image can be smaller than the texture, this function is usually used for updating the whole texture. The other overload, which has (x, y) additional arguments, is more convenient for updating a sub-area of the texture.
No additional check is performed on the size of the image, passing an image bigger than the texture will lead to an undefined behavior.
This function does nothing if the texture was not previously created.
Although the source window can be smaller than the texture, this function is usually used for updating the whole texture. The other overload, which has (x, y) additional arguments, is more convenient for updating a sub-area of the texture.
No additional check is performed on the size of the window, passing a window bigger than the texture will lead to an undefined behavior.
This function does nothing if either the texture or the window was not previously created.
public void update(const Window & window,unsigned int x,unsigned int y)
Update a part of the texture from the contents of a window.
No additional check is performed on the size of the window, passing an invalid combination of window size and offset will lead to an undefined behavior.
This function does nothing if either the texture or the window was not previously created.
When the filter is activated, the texture appears smoother so that pixels are less noticeable. However if you want the texture to look exactly the same as its source file, you should leave it disabled. The smooth filter is disabled by default.
Parameters
smooth True to enable smoothing, false to disable it
When providing texture data from an image file or memory, it can either be stored in a linear color space or an sRGB color space. Most digital images account for gamma correction already, so they would need to be "uncorrected" back to linear color space before being processed by the hardware. The hardware can automatically convert it from the sRGB color space to a linear color space when it gets sampled. When the rendered image gets output to the final framebuffer, it gets converted back to sRGB.
After enabling or disabling sRGB conversion, make sure to reload the texture data in order for the setting to take effect.
This option is only useful in conjunction with an sRGB capable framebuffer. This can be requested during window creation.
Parameters
sRgb True to enable sRGB conversion, false to disable it
Repeating is involved when using texture coordinates outside the texture rectangle [0, 0, width, height]. In this case, if repeat mode is enabled, the whole texture will be repeated as many times as needed to reach the coordinate (for example, if the X texture coordinate is 3 * width, the texture will be repeated 3 times). If repeat mode is disabled, the "extra space" will instead be filled with border pixels. Warning: on very old graphics cards, white pixels may appear when the texture is repeated. With such cards, repeat mode can be used reliably only if the texture has power-of-two dimensions (such as 256x128). Repeating is disabled by default.
Parameters
repeated True to repeat the texture, false to disable repeating
Mipmaps are pre-computed chains of optimized textures. Each level of texture in a mipmap is generated by halving each of the previous level's dimensions. This is done until the final level has the size of 1x1. The textures generated in this process may make use of more advanced filters which might improve the visual quality of textures when they are applied to objects much smaller than they are. This is known as minification. Because fewer texels (texture elements) have to be sampled from when heavily minified, usage of mipmaps can also improve rendering performance in certain scenarios.
Mipmap generation relies on the necessary OpenGL extension being available. If it is unavailable or generation fails due to another reason, this function will return false. Mipmap data is only valid from the time it is generated until the next time the base level image is modified, at which point this function will have to be called again to regenerate it.
Returns
True if mipmap generation was successful, false if unsuccessful
You shouldn't need to use this function, unless you have very specific stuff to implement that SFML doesn't support, or implement a temporary workaround until a bug is fixed.
Returns
OpenGL handle of the texture or 0 if not yet created
Types of texture coordinates that can be used for rendering.
class sf::Transform
Define a 3x3 transform matrix.
A sf::Transform specifies how to translate, rotate, scale, shear, project, whatever things.
In mathematical terms, it defines how to transform a coordinate system into another.
For example, if you apply a rotation transform to a sprite, the result will be a rotated sprite. And anything that is transformed by this rotation transform will be rotated the same way, according to its initial position.
Transforms are typically used for drawing. But they can also be used for any computation that requires to transform points between the local and global coordinate systems of an entity (like collision detection).
Example:
// define a translation transform
sf::Transform translation;
translation.translate(20, 50);
// define a rotation transform
sf::Transform rotation;
rotation.rotate(45);
// combine them
sf::Transform transform = translation * rotation;
// use the result to transform stuff...
sf::Vector2f point = transform.transformPoint(10, 20);
sf::FloatRect rect = transform.transformRect(sf::FloatRect(0, 0, 10, 100));
This function returns a pointer to an array of 16 floats containing the transform elements as a 4x4 matrix, which is directly compatible with OpenGL functions.
Since SFML doesn't provide support for oriented rectangles, the result of this function is always an axis-aligned rectangle. Which means that if the transform contains a rotation, the bounding rectangle of the transformed rectangle is returned.
public Transform&rotate(float angle,float centerX,float centerY)
Combine the current transform with a rotation.
The center of rotation is provided for convenience as a second argument, so that you can build rotations around arbitrary points more easily (and efficiently) than the usual translate(-center).rotate(angle).translate(center).
This function returns a reference to *this, so that calls can be chained.
The center of rotation is provided for convenience as a second argument, so that you can build rotations around arbitrary points more easily (and efficiently) than the usual translate(-center).rotate(angle).translate(center).
This function returns a reference to *this, so that calls can be chained.
public Transform&scale(float scaleX,float scaleY,float centerX,float centerY)
Combine the current transform with a scaling.
The center of scaling is provided for convenience as a second argument, so that you can build scaling around arbitrary points more easily (and efficiently) than the usual translate(-center).scale(factors).translate(center).
This function returns a reference to *this, so that calls can be chained.
The center of scaling is provided for convenience as a second argument, so that you can build scaling around arbitrary points more easily (and efficiently) than the usual translate(-center).scale(factors).translate(center).
This function returns a reference to *this, so that calls can be chained.
Decomposed transform defined by a position, a rotation and a scale.
This class is provided for convenience, on top of sf::Transform.
sf::Transform, as a low-level class, offers a great level of flexibility but it is not always convenient to manage. Indeed, one can easily combine any kind of operation, such as a translation followed by a rotation followed by a scaling, but once the result transform is built, there's no way to go backward and, let's say, change only the rotation without modifying the translation and scaling. The entire transform must be recomputed, which means that you need to retrieve the initial translation and scale factors as well, and combine them the same way you did before updating the rotation. This is a tedious operation, and it requires to store all the individual components of the final transform.
That's exactly what sf::Transformable was written for: it hides these variables and the composed transform behind an easy to use interface. You can set or get any of the individual components without worrying about the others. It also provides the composed transform (as a sf::Transform), and keeps it up-to-date.
In addition to the position, rotation and scale, sf::Transformable provides an "origin" component, which represents the local origin of the three other components. Let's take an example with a 10x10 pixels sprite. By default, the sprite is positioned/rotated/scaled relatively to its top-left corner, because it is the local point (0, 0). But if we change the origin to be (5, 5), the sprite will be positioned/rotated/scaled around its center instead. And if we set the origin to (10, 10), it will be transformed around its bottom-right corner.
To keep the sf::Transformable class simple, there's only one origin for all the components. You cannot position the sprite relatively to its top-left corner while rotating it around its center, for example. To do such things, use sf::Transform directly.
sf::Transformable can be used as a base class. It is often combined with sf::Drawable that's what SFML's sprites, texts and shapes do.
It can also be used as a member, if you don't want to use its API directly (because you don't need all its functions, or you have different naming conventions for example).
A note on coordinates and undistorted rendering:
By default, SFML (or more exactly, OpenGL) may interpolate drawable objects such as sprites or texts when rendering. While this allows transitions like slow movements or rotations to appear smoothly, it can lead to unwanted results in some cases, for example blurred or distorted objects. In order to render a sf::Drawable object pixel-perfectly, make sure the involved coordinates allow a 1:1 mapping of pixels in the window to texels (pixels in the texture). More specifically, this means:
The object's position, origin and scale have no fractional part
The object's and the view's rotation are a multiple of 90 degrees
The view's center and size have no fractional part
This function completely overwrites the previous position. See the move function to apply an offset based on the previous position instead. The default position of a transformable object is (0, 0).
This function completely overwrites the previous position. See the move function to apply an offset based on the previous position instead. The default position of a transformable object is (0, 0).
This function completely overwrites the previous rotation. See the rotate function to add an angle based on the previous rotation instead. The default rotation of a transformable object is 0.
This function completely overwrites the previous scale. See the scale function to add a factor based on the previous scale instead. The default scale of a transformable object is (1, 1).
This function completely overwrites the previous scale. See the scale function to add a factor based on the previous scale instead. The default scale of a transformable object is (1, 1).
The origin of an object defines the center point for all transformations (position, scale, rotation). The coordinates of this point must be relative to the top-left corner of the object, and ignore all transformations (position, scale, rotation). The default origin of a transformable object is (0, 0).
The origin of an object defines the center point for all transformations (position, scale, rotation). The coordinates of this point must be relative to the top-left corner of the object, and ignore all transformations (position, scale, rotation). The default origin of a transformable object is (0, 0).
Define a point with color and texture coordinates.
A vertex is an improved point.
It has a position and other extra attributes that will be used for drawing: in SFML, vertices also have a color and a pair of texture coordinates.
The vertex is the building block of drawing. Everything which is visible on screen is made of vertices. They are grouped as 2D primitives (triangles, quads, ...), and these primitives are grouped to create even more complex 2D entities such as sprites, texts, etc.
If you use the graphical entities of SFML (sprite, text, shape) you won't have to deal with vertices directly. But if you want to define your own 2D entities, such as tiled maps or particle systems, using vertices will allow you to get maximum performances.
Example:
// define a 100x100 square, red, with a 10x10 texture mapped on it
sf::Vertex vertices[] =
{
sf::Vertex(sf::Vector2f( 0, 0), sf::Color::Red, sf::Vector2f( 0, 0)),
sf::Vertex(sf::Vector2f( 0, 100), sf::Color::Red, sf::Vector2f( 0, 10)),
sf::Vertex(sf::Vector2f(100, 100), sf::Color::Red, sf::Vector2f(10, 10)),
sf::Vertex(sf::Vector2f(100, 0), sf::Color::Red, sf::Vector2f(10, 0))
};
// draw it
window.draw(vertices, 4, sf::Quads);
Note: although texture coordinates are supposed to be an integer amount of pixels, their type is float because of some buggy graphics drivers that are not able to process integer coordinates correctly.
This function removes all the vertices from the array. It doesn't deallocate the corresponding memory, so that adding new vertices after clearing doesn't involve reallocating all the memory.
If vertexCount is greater than the current size, the previous vertices are kept and new (default-constructed) vertices are added. If vertexCount is less than the current size, existing vertices are removed from the array.
Parameters
vertexCount New size of the array (number of vertices)
Compute the bounding rectangle of the vertex array.
This function returns the minimal axis-aligned rectangle that contains all the vertices of the array.
Returns
Bounding rectangle of the vertex array
class sf::VertexBuffer
class sf::VertexBuffer
: public sf::Drawable
: private sf::GlResource
Vertex buffer storage for one or more 2D primitives.
sf::VertexBuffer is a simple wrapper around a dynamic buffer of vertices and a primitives type.
Unlike sf::VertexArray, the vertex data is stored in graphics memory.
In situations where a large amount of vertex data would have to be transferred from system memory to graphics memory every frame, using sf::VertexBuffer can help. By using a sf::VertexBuffer, data that has not been changed between frames does not have to be re-transferred from system to graphics memory as would be the case with sf::VertexArray. If data transfer is a bottleneck, this can lead to performance gains.
Using sf::VertexBuffer, the user also has the ability to only modify a portion of the buffer in graphics memory. This way, a large buffer can be allocated at the start of the application and only the applicable portions of it need to be updated during the course of the application. This allows the user to take full control of data transfers between system and graphics memory if they need to.
In special cases, the user can make use of multiple threads to update vertex data in multiple distinct regions of the buffer simultaneously. This might make sense when e.g. the position of multiple objects has to be recalculated very frequently. The computation load can be spread across multiple threads as long as there are no other data dependencies.
Simultaneous updates to the vertex buffer are not guaranteed to be carried out by the driver in any specific order. Updating the same region of the buffer from multiple threads will not cause undefined behaviour, however the final state of the buffer will be unpredictable.
Simultaneous updates of distinct non-overlapping regions of the buffer are also not guaranteed to complete in a specific order. However, in this case the user can make sure to synchronize the writer threads at well-defined points in their code. The driver will make sure that all pending data transfers complete before the vertex buffer is sourced by the rendering pipeline.
It inherits sf::Drawable, but unlike other drawables it is not transformable.
Creates the vertex buffer and allocates enough graphics memory to hold vertexCount vertices. Any previously allocated memory is freed in the process.
In order to deallocate previously allocated memory pass 0 as vertexCount. Don't forget to recreate with a non-zero value when graphics memory should be allocated again.
Parameters
vertexCount Number of vertices worth of memory to allocate
Get the underlying OpenGL handle of the vertex buffer.
You shouldn't need to use this function, unless you have very specific stuff to implement that SFML doesn't support, or implement a temporary workaround until a bug is fixed.
Returns
OpenGL handle of the vertex buffer or 0 if not yet created
If data is going to be updated once or more every frame, set the usage to Stream. If data is going to be set once and used for a long time without being modified, set the usage to Static. For everything else Dynamic should be a good compromise.
class sf::View
2D camera that defines what region is shown on screen
This is a very powerful concept: you can scroll, rotate or zoom the entire scene without altering the way that your drawable objects are drawn.
A view is composed of a source rectangle, which defines what part of the 2D scene is shown, and a target viewport, which defines where the contents of the source rectangle will be displayed on the render target (window or texture).
The viewport allows to map the scene to a custom part of the render target, and can be used for split-screen or for displaying a minimap, for example. If the source rectangle doesn't have the same size as the viewport, its contents will be stretched to fit in.
To apply a view, you have to assign it to the render target. Then, objects drawn in this render target will be affected by the view until you use another view.
Usage example:
sf::RenderWindow window;
sf::View view;
// Initialize the view to a rectangle located at (100, 100) and with a size of 400x200
view.reset(sf::FloatRect(100, 100, 400, 200));
// Rotate it by 45 degrees
view.rotate(45);
// Set its target viewport to be half of the window
view.setViewport(sf::FloatRect(0.f, 0.f, 0.5f, 1.f));
// Apply it
window.setView(view);
// Render stuff
window.draw(someSprite);
// Set the default view back
window.setView(window.getDefaultView());
// Render stuff not affected by the view
window.draw(someText);
See also the note on coordinates and undistorted rendering in sf::Transformable.
The viewport is the rectangle into which the contents of the view are displayed, expressed as a factor (between 0 and 1) of the size of the RenderTarget to which the view is applied. For example, a view which takes the left side of the target would be defined with View.setViewport(sf::FloatRect(0, 0, 0.5, 1)). By default, a view has a viewport which covers the entire target.
sf::Ftp is a very simple FTP client that allows you to communicate with a FTP server.
The FTP protocol allows you to manipulate a remote file system (list files, upload, download, create, remove, ...).
Using the FTP client consists of 4 parts:
Connecting to the FTP server
Logging in (either as a registered user or anonymously)
Sending commands to the server
Disconnecting (this part can be done implicitly by the destructor)
Every command returns a FTP response, which contains the status code as well as a message from the server. Some commands such as getWorkingDirectory() and getDirectoryListing() return additional data, and use a class derived from sf::Ftp::Response to provide this data. The most often used commands are directly provided as member functions, but it is also possible to use specific commands with the sendCommand() function.
Note that response statuses >= 1000 are not part of the FTP standard, they are generated by SFML when an internal error occurs.
All commands, especially upload and download, may take some time to complete. This is important to know if you don't want to block your application while the server is completing the task.
Usage example:
// Create a new FTP client
sf::Ftp ftp;
// Connect to the server
sf::Ftp::Response response = ftp.connect("ftp://ftp.myserver.com");
if (response.isOk())
std::cout << "Connected" << std::endl;
// Log in
response = ftp.login("laurent", "dF6Zm89D");
if (response.isOk())
std::cout << "Logged in" << std::endl;
// Print the working directory
sf::Ftp::DirectoryResponse directory = ftp.getWorkingDirectory();
if (directory.isOk())
std::cout << "Working directory: " << directory.getDirectory() << std::endl;
// Create a new directory
response = ftp.createDirectory("files");
if (response.isOk())
std::cout << "Created new directory" << std::endl;
// Upload a file to this new directory
response = ftp.upload("local-path/file.txt", "files", sf::Ftp::Ascii);
if (response.isOk())
std::cout << "File uploaded" << std::endl;
// Send specific commands (here: FEAT to list supported FTP features)
response = ftp.sendCommand("FEAT");
if (response.isOk())
std::cout << "Feature list:\n" << response.getMessage() << std::endl;
// Disconnect from the server (optional)
ftp.disconnect();
The port has a default value of 21, which is the standard port used by the FTP protocol. You shouldn't use a different value, unless you really know what you do. This function tries to connect to the server so it may take a while to complete, especially if the server is not reachable. To avoid blocking your application for too long, you can use a timeout. The default value, Time::Zero, means that the system timeout will be used (which is usually pretty long).
Parameters
server Name or address of the FTP server to connect to
This function retrieves the sub-directories and files contained in the given directory. It is not recursive. The directory parameter is relative to the current working directory.
The filename of the distant file is relative to the current working directory of the server, and the local destination path is relative to the current directory of your application. If a file with the same filename as the distant file already exists in the local destination path, it will be overwritten.
Parameters
remoteFile Filename of the distant file to download
localPath The directory in which to put the file on the local computer
public Responseupload(const std::string & localFile,const std::string & remotePath,TransferMode mode,bool append)
Upload a file to the server.
The name of the local file is relative to the current working directory of your application, and the remote path is relative to the current directory of the FTP server.
The append parameter controls whether the remote file is appended to or overwritten if it already exists.
Parameters
localFile Path of the local file to upload
remotePath The directory in which to put the file on the server
mode Transfer mode
append Pass true to append to or false to overwrite the remote file if it already exists
public ResponsesendCommand(const std::string & command,const std::string & parameter)
Send a command to the FTP server.
While the most often used commands are provided as member functions in the sf::Ftp class, this method can be used to send any FTP command to the server. If the command requires one or more parameters, they can be specified in parameter. If the server returns information, you can extract it from the response using Response::getMessage().
// Create a new HTTP client
sf::Http http;
// We'll work on http://www.sfml-dev.org
http.setHost("http://www.sfml-dev.org");
// Prepare a request to get the 'features.php' page
sf::Http::Request request("features.php");
// Send the request
sf::Http::Response response = http.sendRequest(request);
// Check the status code and display the result
sf::Http::Response::Status status = response.getStatus();
if (status == sf::Http::Response::Ok)
{
std::cout << response.getBody() << std::endl;
}
else
{
std::cout << "Error " << status << std::endl;
}
public Http(const std::string & host,unsigned short port)
Construct the HTTP client with the target host.
This is equivalent to calling setHost(host, port). The port has a default value of 0, which means that the HTTP client will use the right port according to the protocol used (80 for HTTP). You should leave it like this unless you really need a port other than the standard one, or use an unknown protocol.
Parameters
host Web server to connect to
port Port to use for connection
public void setHost(const std::string & host,unsigned short port)
Set the target host.
This function just stores the host address and port, it doesn't actually connect to it until you send a request. The port has a default value of 0, which means that the HTTP client will use the right port according to the protocol used (80 for HTTP). You should leave it like this unless you really need a port other than the standard one, or use an unknown protocol.
Send a HTTP request and return the server's response.
You must have a valid host before sending a request (see setHost). Any missing mandatory header field in the request will be added with an appropriate value. Warning: this function waits for the server's response and may not return instantly; use a thread if you don't want to block your application, or use a timeout to limit the time to wait. A value of Time::Zero means that the client will use the system default timeout (which is usually pretty long).
sf::IpAddress is a utility class for manipulating network addresses.
It provides a set a implicit constructors and conversion functions to easily build or transform an IP address from/to various representations.
Usage example:
sf::IpAddress a0; // an invalid address
sf::IpAddress a1 = sf::IpAddress::None; // an invalid address (same as a0)
sf::IpAddress a2("127.0.0.1"); // the local host address
sf::IpAddress a3 = sf::IpAddress::Broadcast; // the broadcast address
sf::IpAddress a4(192, 168, 1, 56); // a local address
sf::IpAddress a5("my_computer"); // a local address created from a network name
sf::IpAddress a6("89.54.1.169"); // a distant address
sf::IpAddress a7("www.google.com"); // a distant address created from a network name
sf::IpAddress a8 = sf::IpAddress::getLocalAddress(); // my address on the local network
sf::IpAddress a9 = sf::IpAddress::getPublicAddress(); // my address on the internet
Note that sf::IpAddress currently doesn't support IPv6 nor other types of network addresses.
Here address can be either a decimal address (ex: "192.168.1.56") or a network name (ex: "localhost"). This is equivalent to the constructor taking a std::string parameter, it is defined for convenience so that the implicit conversions from literal strings to IpAddress work.
Parameters
address IP address or network name
public IpAddress(Uint8 byte0,Uint8 byte1,Uint8 byte2,Uint8 byte3)
Construct the address from 4 bytes.
Calling IpAddress(a, b, c, d) is equivalent to calling IpAddress("a.b.c.d"), but safer as it doesn't have to parse a string to get the address components.
This constructor uses the internal representation of the address directly. It should be used for optimization purposes, and only if you got that representation from IpAddress::toInteger().
Parameters
address 4 bytes of the address packed into a 32-bits integer
The returned number is the internal representation of the address, and should be used for optimization purposes only (like sending the address through a socket). The integer produced by this function can then be converted back to a sf::IpAddress with the proper constructor.
Returns
32-bits unsigned integer representation of the address
Utility class to build blocks of data to transfer over the network.
Packets provide a safe and easy way to serialize data, in order to send it over the network using sockets (sf::TcpSocket, sf::UdpSocket).
Packets solve 2 fundamental problems that arise when transferring data over the network:
data is interpreted correctly according to the endianness
the bounds of the packet are preserved (one send == one receive)
The sf::Packet class provides both input and output modes. It is designed to follow the behavior of standard C++ streams, using operators >> and << to extract and insert data.
It is recommended to use only fixed-size types (like sf::Int32, etc.), to avoid possible differences between the sender and the receiver. Indeed, the native C++ types may have different sizes on two platforms and your data may be corrupted if that happens.
Usage example:
sf::Uint32 x = 24;
std::string s = "hello";
double d = 5.89;
// Group the variables to send into a packet
sf::Packet packet;
packet << x << s << d;
// Send it over the network (socket is a valid sf::TcpSocket)
socket.send(packet);
-----------------------------------------------------------------
// Receive the packet at the other end
sf::Packet packet;
socket.receive(packet);
// Extract the variables contained in the packet
sf::Uint32 x;
std::string s;
double d;
if (packet >> x >> s >> d)
{
// Data extracted successfully...
}
Packets have built-in operator >> and << overloads for standard types:
Packets also provide an extra feature that allows to apply custom transformations to the data before it is sent, and after it is received. This is typically used to handle automatic compression or encryption of the data. This is achieved by inheriting from sf::Packet, and overriding the onSend and onReceive functions.
Get a pointer to the data contained in the packet.
Warning: the returned pointer may become invalid after you append data to the packet, therefore it should never be stored. The return pointer is NULL if the packet is empty.
Called before the packet is sent over the network.
This function can be defined by derived classes to transform the data before it is sent; this can be used for compression, encryption, etc. The function must return a pointer to the modified data, as well as the number of bytes pointed. The default implementation provides the packet's data without transforming it.
Parameters
size Variable to fill with the size of data to send
Called after the packet is received over the network.
This function can be defined by derived classes to transform the data after it is received; this can be used for decompression, decryption, etc. The function receives a pointer to the received data, and must fill the packet with the transformed bytes. The default implementation fills the packet directly without transforming the data.
This class mainly defines internal stuff to be used by derived classes.
The only public features that it defines, and which is therefore common to all the socket classes, is the blocking state. All sockets can be set as blocking or non-blocking.
In blocking mode, socket functions will hang until the operation completes, which means that the entire program (well, in fact the current thread if you use multiple ones) will be stuck waiting for your socket operation to complete.
In non-blocking mode, all the socket functions will return immediately. If the socket is not ready to complete the requested operation, the function simply returns the proper status code (Socket::NotReady).
The default mode, which is blocking, is the one that is generally used, in combination with threads or selectors. The non-blocking mode is rather used in real-time applications that run an endless loop that can poll the socket often enough, and cannot afford blocking this loop.
In blocking mode, calls will not return until they have completed their task. For example, a call to Receive in blocking mode won't return until some data was actually received. In non-blocking mode, calls will always return immediately, using the return code to signal whether there was data available or not. By default, all sockets are blocking.
Parameters
blocking True to set the socket as blocking, false for non-blocking
Special value that tells the system to pick any available port.
Some special values used by sockets.
class sf::SocketSelector
Multiplexer that allows to read from multiple sockets.
Socket selectors provide a way to wait until some data is available on a set of sockets, instead of just one.
This is convenient when you have multiple sockets that may possibly receive data, but you don't know which one will be ready first. In particular, it avoids to use a thread for each socket; with selectors, a single thread can handle all the sockets.
A selector doesn't store its own copies of the sockets (socket classes are not copyable anyway), it simply keeps a reference to the original sockets that you pass to the "add" function. Therefore, you can't use the selector as a socket container, you must store them outside and make sure that they are alive as long as they are used in the selector.
Using a selector is simple:
populate the selector with all the sockets that you want to observe
make it wait until there is data available on any of the sockets
test each socket to find out which ones are ready
Usage example:
// Create a socket to listen to new connections
sf::TcpListener listener;
listener.listen(55001);
// Create a list to store the future clients
std::list<sf::TcpSocket*> clients;
// Create a selector
sf::SocketSelector selector;
// Add the listener to the selector
selector.add(listener);
// Endless loop that waits for new connectionswhile (running)
{
// Make the selector wait for data on any socketif (selector.wait())
{
// Test the listenerif (selector.isReady(listener))
{
// The listener is ready: there is a pending connection
sf::TcpSocket* client = new sf::TcpSocket;
if (listener.accept(*client) == sf::Socket::Done)
{
// Add the new client to the clients list
clients.push_back(client);
// Add the new client to the selector so that we will// be notified when he sends something
selector.add(*client);
}
else
{
// Error, we won't get a new connection, delete the socketdelete client;
}
}
else
{
// The listener socket is not ready, test all other sockets (the clients)for (std::list<sf::TcpSocket*>::iterator it = clients.begin(); it != clients.end(); ++it)
{
sf::TcpSocket& client = **it;
if (selector.isReady(client))
{
// The client has sent some data, we can receive it
sf::Packet packet;
if (client.receive(packet) == sf::Socket::Done)
{
...
}
}
}
}
}
}
This function keeps a weak reference to the socket, so you have to make sure that the socket is not destroyed while it is stored in the selector. This function does nothing if the socket is not valid.
Wait until one or more sockets are ready to receive.
This function returns as soon as at least one socket has some data available to be received. To know which sockets are ready, use the isReady function. If you use a timeout and no socket is ready before the timeout is over, the function returns false.
Parameters
timeout Maximum time to wait, (use Time::Zero for infinity)
Test a socket to know if it is ready to receive data.
This function must be used after a call to Wait, to know which sockets are ready to receive data. If a socket is ready, a call to receive will never block because we know that there is data available to read. Note that if this function returns true for a TcpListener, this means that it is ready to accept a new connection.
A listener socket is a special type of socket that listens to a given port and waits for connections on that port.
This is all it can do.
When a new connection is received, you must call accept and the listener returns a new instance of sf::TcpSocket that is properly initialized and can be used to communicate with the new client.
Listener sockets are specific to the TCP protocol, UDP sockets are connectionless and can therefore communicate directly. As a consequence, a listener socket will always return the new connections as sf::TcpSocket instances.
A listener is automatically closed on destruction, like all other types of socket. However if you want to stop listening before the socket is destroyed, you can call its close() function.
Usage example:
// Create a listener socket and make it wait for new// connections on port 55001
sf::TcpListener listener;
listener.listen(55001);
// Endless loop that waits for new connectionswhile (running)
{
sf::TcpSocket client;
if (listener.accept(client) == sf::Socket::Done)
{
// A new client just connected!
std::cout << "New connection received from " << client.getRemoteAddress() << std::endl;
doSomethingWith(client);
}
}
This functions makes the socket listen to the specified port, waiting for new connections. If the socket was previously listening to another port, it will be stopped first and bound to the new port.
In blocking mode, calls will not return until they have completed their task. For example, a call to Receive in blocking mode won't return until some data was actually received. In non-blocking mode, calls will always return immediately, using the return code to signal whether there was data available or not. By default, all sockets are blocking.
Parameters
blocking True to set the socket as blocking, false for non-blocking
Special value that tells the system to pick any available port.
Some special values used by sockets.
class sf::TcpSocket
class sf::TcpSocket
: public sf::Socket
Specialized socket using the TCP protocol.
TCP is a connected protocol, which means that a TCP socket can only communicate with the host it is connected to.
It can't send or receive anything if it is not connected.
The TCP protocol is reliable but adds a slight overhead. It ensures that your data will always be received in order and without errors (no data corrupted, lost or duplicated).
When a socket is connected to a remote host, you can retrieve informations about this host with the getRemoteAddress and getRemotePort functions. You can also get the local port to which the socket is bound (which is automatically chosen when the socket is connected), with the getLocalPort function.
Sending and receiving data can use either the low-level or the high-level functions. The low-level functions process a raw sequence of bytes, and cannot ensure that one call to Send will exactly match one call to Receive at the other end of the socket.
The high-level interface uses packets (see sf::Packet), which are easier to use and provide more safety regarding the data that is exchanged. You can look at the sf::Packet class to get more details about how they work.
The socket is automatically disconnected when it is destroyed, but if you want to explicitly close the connection while the socket instance is still alive, you can call disconnect.
Usage example:
// ----- The client -----// Create a socket and connect it to 192.168.1.50 on port 55001
sf::TcpSocket socket;
socket.connect("192.168.1.50", 55001);
// Send a message to the connected host
std::string message = "Hi, I am a client";
socket.send(message.c_str(), message.size() + 1);
// Receive an answer from the serverchar buffer[1024];
std::size_t received = 0;
socket.receive(buffer, sizeof(buffer), received);
std::cout << "The server said: " << buffer << std::endl;
// ----- The server -----// Create a listener to wait for incoming connections on port 55001
sf::TcpListener listener;
listener.listen(55001);
// Wait for a connection
sf::TcpSocket socket;
listener.accept(socket);
std::cout << "New client connected: " << socket.getRemoteAddress() << std::endl;
// Receive a message from the clientchar buffer[1024];
std::size_t received = 0;
socket.receive(buffer, sizeof(buffer), received);
std::cout << "The client said: " << buffer << std::endl;
// Send an answer
std::string message = "Welcome, client";
socket.send(message.c_str(), message.size() + 1);
In blocking mode, this function may take a while, especially if the remote peer is not reachable. The last parameter allows you to stop trying to connect after a given timeout. If the socket was previously connected, it is first disconnected.
public Statussend(const void * data,std::size_t size)
Send raw data to the remote peer.
To be able to handle partial sends over non-blocking sockets, use the send(const void*, std::size_t, std::size_t&) overload instead. This function will fail if the socket is not connected.
Send a formatted packet of data to the remote peer.
In non-blocking mode, if this function returns sf::Socket::Partial, you must retry sending the same unmodified packet before sending anything else in order to guarantee the packet arrives at the remote peer uncorrupted. This function will fail if the socket is not connected.
In blocking mode, calls will not return until they have completed their task. For example, a call to Receive in blocking mode won't return until some data was actually received. In non-blocking mode, calls will always return immediately, using the return code to signal whether there was data available or not. By default, all sockets are blocking.
Parameters
blocking True to set the socket as blocking, false for non-blocking
Special value that tells the system to pick any available port.
Some special values used by sockets.
class sf::UdpSocket
class sf::UdpSocket
: public sf::Socket
Specialized socket using the UDP protocol.
A UDP socket is a connectionless socket.
Instead of connecting once to a remote host, like TCP sockets, it can send to and receive from any host at any time.
It is a datagram protocol: bounded blocks of data (datagrams) are transfered over the network rather than a continuous stream of data (TCP). Therefore, one call to send will always match one call to receive (if the datagram is not lost), with the same data that was sent.
The UDP protocol is lightweight but unreliable. Unreliable means that datagrams may be duplicated, be lost or arrive reordered. However, if a datagram arrives, its data is guaranteed to be valid.
UDP is generally used for real-time communication (audio or video streaming, real-time games, etc.) where speed is crucial and lost data doesn't matter much.
Sending and receiving data can use either the low-level or the high-level functions. The low-level functions process a raw sequence of bytes, whereas the high-level interface uses packets (see sf::Packet), which are easier to use and provide more safety regarding the data that is exchanged. You can look at the sf::Packet class to get more details about how they work.
It is important to note that UdpSocket is unable to send datagrams bigger than MaxDatagramSize. In this case, it returns an error and doesn't send anything. This applies to both raw data and packets. Indeed, even packets are unable to split and recompose data, due to the unreliability of the protocol (dropped, mixed or duplicated datagrams may lead to a big mess when trying to recompose a packet).
If the socket is bound to a port, it is automatically unbound from it when the socket is destroyed. However, you can unbind the socket explicitly with the Unbind function if necessary, to stop receiving messages or make the port available for other sockets.
Usage example:
// ----- The client -----// Create a socket and bind it to the port 55001
sf::UdpSocket socket;
socket.bind(55001);
// Send a message to 192.168.1.50 on port 55002
std::string message = "Hi, I am " + sf::IpAddress::getLocalAddress().toString();
socket.send(message.c_str(), message.size() + 1, "192.168.1.50", 55002);
// Receive an answer (most likely from 192.168.1.50, but could be anyone else)char buffer[1024];
std::size_t received = 0;
sf::IpAddress sender;
unsignedshort port;
socket.receive(buffer, sizeof(buffer), received, sender, port);
std::cout << sender.ToString() << " said: " << buffer << std::endl;
// ----- The server -----// Create a socket and bind it to the port 55002
sf::UdpSocket socket;
socket.bind(55002);
// Receive a message from anyonechar buffer[1024];
std::size_t received = 0;
sf::IpAddress sender;
unsignedshort port;
socket.receive(buffer, sizeof(buffer), received, sender, port);
std::cout << sender.ToString() << " said: " << buffer << std::endl;
// Send an answer
std::string message = "Welcome " + sender.toString();
socket.send(message.c_str(), message.size() + 1, sender, port);
Binding the socket to a port is necessary for being able to receive data on that port. You can use the special value Socket::AnyPort to tell the system to automatically pick an available port, and then call getLocalPort to retrieve the chosen port.
Unbind the socket from the local port to which it is bound.
The port that the socket was previously bound to is immediately made available to the operating system after this function is called. This means that a subsequent call to bind() will be able to re-bind the port if no other process has done so in the mean time. If the socket is not bound to a port, this function has no effect.
public Statusreceive(void * data,std::size_t size,std::size_t & received,IpAddress & remoteAddress,unsigned short & remotePort)
Receive raw data from a remote peer.
In blocking mode, this function will wait until some bytes are actually received. Be careful to use a buffer which is large enough for the data that you intend to receive, if it is too small then an error will be returned and all the data will be lost.
Parameters
data Pointer to the array to fill with the received bytes
size Maximum number of bytes that can be received
received This variable is filled with the actual number of bytes received
remoteAddress Address of the peer that sent the data
In blocking mode, calls will not return until they have completed their task. For example, a call to Receive in blocking mode won't return until some data was actually received. In non-blocking mode, calls will always return immediately, using the return code to signal whether there was data available or not. By default, all sockets are blocking.
Parameters
blocking True to set the socket as blocking, false for non-blocking
You shouldn't have to use this function, unless you want to implement very specific details, that SFML doesn't support, or to use a workaround for a known issue.
Returns
Pointer to Android native activity structure
Platform Limitation* This is only available on Android and to use it, you'll have to specifically include SFML/System/NativeActivity.hpp in your code.
Standard stream used by SFML to output warnings and errors.
By default, sf::err() outputs to the same location as std::cerr, (-> the stderr descriptor) which is the console if there's one available.
It is a standard std::ostream instance, so it supports all the insertion operations defined by the STL (operator <<, manipulators, etc.).
sf::err() can be redirected to write to another output, independently of std::cerr, by using the rdbuf() function provided by the std::ostream class.
Example:
// Redirect to a file
std::ofstream file("sfml-log.txt");
std::streambuf* previous = sf::err().rdbuf(file.rdbuf());
// Redirect to nothingsf::err().rdbuf(NULL);
// Restore the original outputsf::err().rdbuf(previous);
Returns
Reference to std::ostream representing the SFML error stream
class sf::Clock
Utility class that measures the elapsed time.
sf::Clock is a lightweight class for measuring time.
Its provides the most precise time that the underlying OS can achieve (generally microseconds or nanoseconds). It also ensures monotonicity, which means that the returned time can never go backward, even if the system time is changed.
Usage example:
sf::Clock clock;
...
Time time1 = clock.getElapsedTime();
...
Time time2 = clock.restart();
The sf::Time value returned by the clock can then be converted to a number of seconds, milliseconds or even microseconds.
class sf::FileInputStream
: public sf::InputStream
: private sf::NonCopyable
Implementation of input stream based on a file.
This class is a specialization of InputStream that reads from a file on disk.
It wraps a file in the common InputStream interface and therefore allows to use generic classes or functions that accept such a stream, with a file on disk as the data source.
In addition to the virtual functions inherited from InputStream, FileInputStream adds a function to specify the file to open.
SFML resource classes can usually be loaded directly from a filename, so this class shouldn't be useful to you unless you create your own algorithms that operate on an InputStream.
Usage example:
voidprocess(InputStream& stream);
FileInputStream stream;
if (stream.open("some_file.dat"))
process(stream);
The total number of bytes available in the stream, or -1 on error
class sf::InputStream
Abstract class for custom file input streams.
This class allows users to define their own file input sources from which SFML can load resources.
SFML resource classes like sf::Texture and sf::SoundBuffer provide loadFromFile and loadFromMemory functions, which read data from conventional sources. However, if you have data coming from a different source (over a network, embedded, encrypted, compressed, etc) you can derive your own class from sf::InputStream and load SFML resources with their loadFromStream function.
Usage example:
// custom stream class that reads from inside a zip fileclassZipStream : publicsf::InputStream
{
public:ZipStream(std::string archive);
boolopen(std::string filename);
Int64 read(void* data, Int64 size);
Int64 seek(Int64 position);
Int64 tell();
Int64 getSize();
private:
...
};
// now you can load textures...
sf::Texture texture;
ZipStream stream("resources.zip");
stream.open("images/img.png");
texture.loadFromStream(stream);
// musics...
sf::Music music;
ZipStream stream("resources.zip");
stream.open("musics/msc.ogg");
music.openFromStream(stream);
// etc.
By unlocking it in its destructor, it ensures that the mutex will always be released when the current scope (most likely a function) ends. This is even more important when an exception or an early return statement can interrupt the execution flow of the function.
For maximum robustness, sf::Lock should always be used to lock/unlock a mutex.
Usage example:
sf::Mutex mutex;
voidfunction()
{
sf::Lock lock(mutex); // mutex is now lockedfunctionThatMayThrowAnException(); // mutex is unlocked if this function throwsif (someCondition)
return; // mutex is unlocked
} // mutex is unlocked
Because the mutex is not explicitly unlocked in the code, it may remain locked longer than needed. If the region of the code that needs to be protected by the mutex is not the entire function, a good practice is to create a smaller, inner scope so that the lock is limited to this part of the code.
Having a mutex locked longer than required is a bad practice which can lead to bad performances. Don't forget that when a mutex is locked, other threads may be waiting doing nothing until it is released.
The destructor of sf::Lock automatically unlocks its mutex.
class sf::MemoryInputStream
class sf::MemoryInputStream
: public sf::InputStream
Implementation of input stream based on a memory chunk.
This class is a specialization of InputStream that reads from data in memory.
It wraps a memory chunk in the common InputStream interface and therefore allows to use generic classes or functions that accept such a stream, with content already loaded in memory.
In addition to the virtual functions inherited from InputStream, MemoryInputStream adds a function to specify the pointer and size of the data in memory.
SFML resource classes can usually be loaded directly from memory, so this class shouldn't be useful to you unless you create your own algorithms that operate on an InputStream.
A mutex is a synchronization object, used when multiple threads are involved.
When you want to protect a part of the code from being accessed simultaneously by multiple threads, you typically use a mutex. When a thread is locked by a mutex, any other thread trying to lock it will be blocked until the mutex is released by the thread that locked it. This way, you can allow only one thread at a time to access a critical region of your code.
Usage example:
Database database; // this is a critical resource that needs some protection
sf::Mutex mutex;
voidthread1()
{
mutex.lock(); // this call will block the thread if the mutex is already locked by thread2
database.write(...);
mutex.unlock(); // if thread2 was waiting, it will now be unblocked
}
voidthread2()
{
mutex.lock(); // this call will block the thread if the mutex is already locked by thread1
database.write(...);
mutex.unlock(); // if thread1 was waiting, it will now be unblocked
}
Be very careful with mutexes. A bad usage can lead to bad problems, like deadlocks (two threads are waiting for each other and the application is globally stuck).
To make the usage of mutexes more robust, particularly in environments where exceptions can be thrown, you should use the helper class sf::Lock to lock/unlock mutexes.
SFML mutexes are recursive, which means that you can lock a mutex multiple times in the same thread without creating a deadlock. In this case, the first call to lock() behaves as usual, and the following ones have no effect. However, you must call unlock() exactly as many times as you called lock(). If you don't, the mutex won't be released.
Utility class that makes any derived class non-copyable.
This class makes its instances non-copyable, by explicitly disabling its copy constructor and its assignment operator.
To create a non-copyable class, simply inherit from sf::NonCopyable.
The type of inheritance (public or private) doesn't matter, the copy constructor and assignment operator are declared private in sf::NonCopyable so they will end up being inaccessible in both cases. Thus you can use a shorter syntax for inheriting from it (see below).
Deciding whether the instances of a class can be copied or not is a very important design choice. You are strongly encouraged to think about it before writing a class, and to use sf::NonCopyable when necessary to prevent many potential future errors when using it. This is also a very important indication to users of your class.
Because this class has a copy constructor, the compiler will not automatically generate the default constructor. That's why we must define it explicitly.
By declaring a protected destructor it's impossible to call delete on a pointer of sf::NonCopyable, thus preventing possible resource leaks.
class sf::String
Utility string class that automatically handles conversions between types and encodings.
sf::String is a utility string class defined mainly for convenience.
It is a Unicode string (implemented using UTF-32), thus it can store any character in the world (European, Chinese, Arabic, Hebrew, etc.).
It automatically handles conversions from/to ANSI and wide strings, so that you can work with standard string classes and still be compatible with functions taking a sf::String.
sf::String s;
std::string s1 = s; // automatically converted to ANSI string
std::wstring s2 = s; // automatically converted to wide string
s = "hello"; // automatically converted from ANSI string
s = L"hello"; // automatically converted from wide string
s += 'a'; // automatically converted from ANSI string
s += L'a'; // automatically converted from wide string
Conversions involving ANSI strings use the default user locale. However it is possible to use a custom locale if necessary:
sf::String defines the most important functions of the standard std::string class: removing, random access, iterating, appending, comparing, etc. However it is a simple class provided for convenience, and you may have to consider using a more optimized class if your program requires complex string handling. The automatic conversion functions will then take care of converting your string to sf::String whenever SFML requires it.
Please note that SFML also defines a low-level, generic interface for Unicode handling, see the sf::Utf classes.
Implicit conversion operator to std::string (ANSI string)
The current global locale is used for conversion. If you want to explicitly specify a locale, see toAnsiString. Characters that do not fit in the target encoding are discarded from the returned string. This operator is defined for convenience, and is equivalent to calling toAnsiString().
Implicit conversion operator to std::wstring (wide string)
Characters that do not fit in the target encoding are discarded from the returned string. This operator is defined for convenience, and is equivalent to calling toWideString().
public std::string toAnsiString(const std::locale & locale) const
Convert the Unicode string to an ANSI string.
The UTF-32 string is converted to an ANSI string in the encoding defined by locale. Characters that do not fit in the target encoding are discarded from the returned string.
Replace all occurrences of a substring with a replacement string.
This function replaces all occurrences of searchFor in this string with the string replaceWith.
Parameters
searchFor The value being searched for
replaceWith The value that replaces found searchFor values
public Stringsubstring(std::size_t position,std::size_t length) const
Return a part of the string.
This function returns the substring that starts at index position and spans length characters.
Parameters
position Index of the first character
length Number of characters to include in the substring (if the string is shorter, as many characters as possible are included). InvalidPos can be used to include all characters until the end of the string.
Returns
String object containing a substring of this object
This functions provides a read-only access to a null-terminated C-style representation of the string. The returned pointer is temporary and is meant only for immediate use, thus it is not recommended to store it.
Threads provide a way to run multiple parts of the code in parallel.
When you launch a new thread, the execution is split and both the new thread and the caller run in parallel.
To use a sf::Thread, you construct it directly with the function to execute as the entry point of the thread. sf::Thread has multiple template constructors, which means that you can use several types of entry points:
non-member functions with no argument
non-member functions with one argument of any type
functors with no argument (this one is particularly useful for compatibility with boost/std::bind)
functors with one argument of any type
member functions from any class with no argument
The function argument, if any, is copied in the sf::Thread instance, as well as the functor (if the corresponding constructor is used). Class instances, however, are passed by pointer so you must make sure that the object won't be destroyed while the thread is still using it.
The thread ends when its function is terminated. If the owner sf::Thread instance is destroyed before the thread is finished, the destructor will wait (see wait())
Usage examples:
// example 1: non member function with one argumentvoidthreadFunc(int argument)
{
...
}
sf::Thread thread(&threadFunc, 5);
thread.launch(); // start the thread (internally calls threadFunc(5))
// example 2: member functionclassTask
{
public:voidrun()
{
...
}
};
Task task;
sf::Thread thread(&Task::run, &task);
thread.launch(); // start the thread (internally calls task.run())
// example 3: functorstructTask
{
voidoperator()()
{
...
}
};
sf::Thread thread(Task());
thread.launch(); // start the thread (internally calls operator() on the Task instance)
Creating parallel threads of execution can be dangerous: all threads inside the same process share the same memory space, which means that you may end up accessing the same variable from multiple threads at the same time. To prevent this kind of situations, you can use mutexes (see sf::Mutex).
Construct the thread from a functor with an argument.
This constructor works for function objects, as well as free functions. It is a template, which means that the argument can have any type (int, std::string, void*, Toto, ...).
Use this constructor for this kind of function:
voidfunction(int arg);
// --- or ----structFunctor
{
voidoperator()(std::string arg);
};
This function starts the entry point passed to the thread's constructor, and returns immediately. After this function returns, the thread's function is running in parallel to the calling code.
This function will block the execution until the thread's function ends. Warning: if the thread function never ends, the calling thread will block forever. If this function is called from its owner thread, it returns without doing anything.
This function immediately stops the thread, without waiting for its function to finish. Terminating a thread with this function is not safe, and can lead to local variables not being destroyed on some operating systems. You should rather try to make the thread function terminate by itself.
class sf::ThreadLocal
class sf::ThreadLocal
: private sf::NonCopyable
Defines variables with thread-local storage.
This class manipulates void* parameters and thus is not appropriate for strongly-typed variables.
sf::Time encapsulates a time value in a flexible way.
It allows to define a time value either as a number of seconds, milliseconds or microseconds. It also works the other way round: you can read a time value as either a number of seconds, milliseconds or microseconds.
By using such a flexible interface, the API doesn't impose any fixed type or resolution for time values, and let the user choose its own favorite representation.
Time values support the usual mathematical operations: you can add or subtract two times, multiply or divide a time by a number, compare two times, etc.
Since they represent a time span and not an absolute time value, times can also be negative.
Utility class providing generic functions for UTF conversions.
sf::Utf is a low-level, generic interface for counting, iterating, encoding and decoding Unicode characters and strings. It is able to handle ANSI, wide, latin-1, UTF-8, UTF-16 and UTF-32 encodings.
sf::Utf functions are all static, these classes are not meant to be instantiated. All the functions are template, so that you can use any character / string type for a given encoding.
Utility template class for manipulating 2-dimensional vectors.
sf::Vector2 is a simple class that defines a mathematical vector with two coordinates (x and y).
It can be used to represent anything that has two dimensions: a size, a point, a velocity, etc.
The template parameter T is the type of the coordinates. It can be any type that supports arithmetic operations (+, -, /, *) and comparisons (==, !=), for example int or float.
You generally don't have to care about the templated form (sf::Vector2), the most common specializations have special typedefs:
sf::Vector2 is sf::Vector2f
sf::Vector2 is sf::Vector2i
sf::Vector2 is sf::Vector2u
The sf::Vector2 class has a small and simple interface, its x and y members can be accessed directly (there are no accessors like setX(), getX()) and it contains no mathematical function like dot product, cross product, length, etc.
public template<> explicitVector2(const Vector2< U > & vector)
Construct the vector from another type of vector.
This constructor doesn't replace the copy constructor, it's called only when U != T. A call to this constructor will fail to compile if U is not convertible to T.
Parameters
vector Vector to convert
class sf::Vector3
Utility template class for manipulating 3-dimensional vectors.
sf::Vector3 is a simple class that defines a mathematical vector with three coordinates (x, y and z).
It can be used to represent anything that has three dimensions: a size, a point, a velocity, etc.
The template parameter T is the type of the coordinates. It can be any type that supports arithmetic operations (+, -, /, *) and comparisons (==, !=), for example int or float.
You generally don't have to care about the templated form (sf::Vector3), the most common specializations have special typedefs:
sf::Vector3 is sf::Vector3f
sf::Vector3 is sf::Vector3i
The sf::Vector3 class has a small and simple interface, its x and y members can be accessed directly (there are no accessors like setX(), getX()) and it contains no mathematical function like dot product, cross product, length, etc.
public template<> explicitVector3(const Vector3< U > & vector)
Construct the vector from another type of vector.
This constructor doesn't replace the copy constructor, it's called only when U != T. A call to this constructor will fail to compile if U is not convertible to T.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Warns the user that some specific class or function is only available on
# specific platforms.
#
# This shouldn't be used for incomplete implementations. It's meant for things
# that will never appear on another platform, e.g. Android's native activity.
#
# If a header is given, the user is informed, that this header must be included
# for the mentioned element to be defined.
ALIASES += sfplatform{1}="<dl class=\"attention\"><dt>Platform Limitation</dt><dd><b>This is only available on \1.</b></dd></dl>"
ALIASES += sfplatform{2}="<dl class=\"attention\"><dt>Platform Limitation</dt><dd><b>This is only available on \1</b> and to use it, you'll have to specifically include \2 in your code.</dd></dl>"
No border / title bar (this flag and all others are mutually exclusive)
Titlebar
Title bar + fixed border.
Resize
Title bar + resizable border + maximize button.
Close
Title bar + close button.
Fullscreen
Fullscreen mode (this flag and all others are mutually exclusive)
Default
Default window style.
Enumeration of the window styles.
class sf::Clipboard
Give access to the system clipboard.
sf::Clipboard provides an interface for getting and setting the contents of the system clipboard.
Usage example:
// get the clipboard content as a string
sf::String string = sf::Clipboard::getString();
// or use it in the event loop
sf::Event event;
while(window.pollEvent(event))
{
if(event.type == sf::Event::Closed)
window.close();
if(event.type == sf::Event::KeyPressed)
{
// Using Ctrl + V to paste a string into SFMLif(event.key.control && event.key.code == sf::Keyboard::V)
string = sf::Clipboard::getString();
}
}
// set the clipboard to a stringsf::Clipboard::setString("Hello World!");
class sf::Context
: private sf::GlResource
: private sf::NonCopyable
Class holding a valid drawing context.
If you need to make OpenGL calls without having an active window (like in a thread), you can use an instance of this class to get a valid context.
Having a valid context is necessary for every OpenGL call.
Note that a context is only active in its current thread, if you create a new thread it will have no valid context by default.
To use a sf::Context instance, just construct it and let it live as long as you need a valid context. No explicit activation is needed, all it has to do is to exist. Its destructor will take care of deactivating and freeing all the attached resources.
Usage example:
voidthreadFunction(void*)
{
sf::Context context;
// from now on, you have a valid context// you can make OpenGL callsglClear(GL_DEPTH_BUFFER_BIT);
}
// the context is automatically deactivated and destroyed// by the sf::Context destructor
Note that these settings may be different than the ones passed to the constructor; they are indeed adjusted if the original settings are not directly supported by the system.
This constructor is for internal use, you don't need to bother with it.
Parameters
settings Creation parameters
width Back buffer width
height Back buffer height
class sf::ContextSettings
Structure defining the settings of the OpenGL context attached to a window.
ContextSettings allows to define several advanced settings of the OpenGL context attached to a window.
All these settings with the exception of the compatibility flag and anti-aliasing level have no impact on the regular SFML rendering (graphics module), so you may need to use this structure only if you're using SFML as a windowing system for custom OpenGL rendering.
The depthBits and stencilBits members define the number of bits per pixel requested for the (respectively) depth and stencil buffers.
antialiasingLevel represents the requested number of multisampling levels for anti-aliasing.
majorVersion and minorVersion define the version of the OpenGL context that you want. Only versions greater or equal to 3.0 are relevant; versions lesser than 3.0 are all handled the same way (i.e. you can use any version < 3.0 if you don't want an OpenGL 3 context).
When requesting a context with a version greater or equal to 3.2, you have the option of specifying whether the context should follow the core or compatibility profile of all newer (>= 3.2) OpenGL specifications. For versions 3.0 and 3.1 there is only the core profile. By default a compatibility context is created. You only need to specify the core flag if you want a core profile context to use with your own OpenGL rendering. Warning: The graphics module will not function if you request a core profile context. Make sure the attributes are set to Default if you want to use the graphics module.
Setting the debug attribute flag will request a context with additional debugging features enabled. Depending on the system, this might be required for advanced OpenGL debugging. OpenGL debugging is disabled by default.
Special Note for OS X: Apple only supports choosing between either a legacy context (OpenGL 2.1) or a core context (OpenGL version depends on the operating system version but is at least 3.2). Compatibility contexts are not supported. Further information is available on the OpenGL Capabilities Tables page. OS X also currently does not support debug contexts.
Please note that these values are only a hint. No failure will be reported if one or more of these values are not supported by the system; instead, SFML will try to find the closest valid match. You can then retrieve the settings that the window actually used to create its context, with Window::getSettings().
public inline explicit ContextSettings(unsigned int depth,unsigned int stencil,unsigned int antialiasing,unsigned int major,unsigned int minor,unsigned int attributes,bool sRgb)
public inline explicit ContextSettings(unsigned int depth,unsigned int stencil,unsigned int antialiasing,unsigned int major,unsigned int minor,unsigned int attributes,bool sRgb)
This constructor doesn't actually create the cursor; initially the new instance is invalid and must not be used until either loadFromPixels() or loadFromSystem() is called and successfully created a cursor.
pixels must be an array of width by height pixels in 32-bit RGBA format. If not, this will cause undefined behavior.
If pixels is null or either width or height are 0, the current cursor is left unchanged and the function will return false.
In addition to specifying the pixel data, you can also specify the location of the hotspot of the cursor. The hotspot is the pixel coordinate within the cursor image which will be located exactly where the mouse pointer position is. Any mouse actions that are performed will return the window/screen location of the hotspot.
On Unix, the pixels are mapped into a monochrome bitmap: pixels with an alpha channel to 0 are transparent, black if the RGB channel are close to zero, and white otherwise.
Parameters
pixels Array of pixels of the image
size Width and height of the image
hotspot (x,y) location of the hotspot
Returns
true if the cursor was successfully loaded; false otherwise
Refer to the list of cursor available on each system (see sf::Cursor::Type) to know whether a given cursor is expected to load successfully or is not supported by the operating system.
Parameters
type Native system cursor type
Returns
true if and only if the corresponding cursor is natively supported by the operating system; false otherwise
A sf::Event instance contains the type of the event (mouse moved, key pressed, window closed, ...) as well as the details about this particular event. Please note that the event parameters are defined in a union, which means that only the member matching the type of the event will be properly filled; all other members will have undefined values and must not be read if the type of the event doesn't match. For example, if you received a KeyPressed event, then you must read the event.key member, all other members such as event.mouseMove or event.text will have undefined values.
Usage example:
sf::Event event;
while (window.pollEvent(event))
{
// Request for closing the windowif (event.type == sf::Event::Closed)
window.close();
// The escape key was pressedif ((event.type == sf::Event::KeyPressed) && (event.key.code == sf::Keyboard::Escape))
window.close();
// The window was resizedif (event.type == sf::Event::Resized)
doSomethingWithTheNewSize(event.size.width, event.size.height);
// etc ...
}
Give access to the real-time state of the joysticks.
sf::Joystick provides an interface to the state of the joysticks.
It only contains static functions, so it's not meant to be instantiated. Instead, each joystick is identified by an index that is passed to the functions of this class.
This class allows users to query the state of joysticks at any time and directly, without having to deal with a window and its events. Compared to the JoystickMoved, JoystickButtonPressed and JoystickButtonReleased events, sf::Joystick can retrieve the state of axes and buttons of joysticks at any time (you don't need to store and update a boolean on your side in order to know if a button is pressed or released), and you always get the real state of joysticks, even if they are moved, pressed or released when your window is out of focus and no event is triggered.
Unlike the keyboard or mouse, the state of joysticks is sometimes not directly available (depending on the OS), therefore an update() function must be called in order to update the current state of joysticks. When you have a window with event handling, this is done automatically, you don't need to call anything. But if you have no window, or if you want to check joysticks state before creating one, you must call sf::Joystick::update explicitly.
Usage example:
// Is joystick #0 connected?bool connected = sf::Joystick::isConnected(0);
// How many buttons does joystick #0 support?unsignedint buttons = sf::Joystick::getButtonCount(0);
// Does joystick #0 define a X axis?bool hasX = sf::Joystick::hasAxis(0, sf::Joystick::X);
// Is button #2 pressed on joystick #0?bool pressed = sf::Joystick::isButtonPressed(0, 2);
// What's the current position of the Y axis on joystick #0?float position = sf::Joystick::getAxisPosition(0, sf::Joystick::Y);
Give access to the real-time state of the keyboard.
sf::Keyboard provides an interface to the state of the keyboard.
It only contains static functions (a single keyboard is assumed), so it's not meant to be instantiated.
This class allows users to query the keyboard state at any time and directly, without having to deal with a window and its events. Compared to the KeyPressed and KeyReleased events, sf::Keyboard can retrieve the state of a key at any time (you don't need to store and update a boolean on your side in order to know if a key is pressed or released), and you always get the real state of the keyboard, even if keys are pressed or released when your window is out of focus and no event is triggered.
The left OS specific key: window (Windows and Linux), apple (MacOS X), ...
RControl
The right Control key.
RShift
The right Shift key.
RAlt
The right Alt key.
RSystem
The right OS specific key: window (Windows and Linux), apple (MacOS X), ...
Menu
The Menu key.
LBracket
The [ key.
RBracket
The ] key.
Semicolon
The ; key.
Comma
The , key.
Period
The . key.
Quote
The ' key.
Slash
The / key.
Backslash
The \ key.
Tilde
The ~ key.
Equal
The = key.
Hyphen
The - key (hyphen)
Space
The Space key.
Enter
The Enter/Return keys.
Backspace
The Backspace key.
Tab
The Tabulation key.
PageUp
The Page up key.
PageDown
The Page down key.
End
The End key.
Home
The Home key.
Insert
The Insert key.
Delete
The Delete key.
Add
The + key.
Subtract
The - key (minus, usually from numpad)
Multiply
The * key.
Divide
The / key.
Left
Left arrow.
Right
Right arrow.
Up
Up arrow.
Down
Down arrow.
Numpad0
The numpad 0 key.
Numpad1
The numpad 1 key.
Numpad2
The numpad 2 key.
Numpad3
The numpad 3 key.
Numpad4
The numpad 4 key.
Numpad5
The numpad 5 key.
Numpad6
The numpad 6 key.
Numpad7
The numpad 7 key.
Numpad8
The numpad 8 key.
Numpad9
The numpad 9 key.
F1
The F1 key.
F2
The F2 key.
F3
The F3 key.
F4
The F4 key.
F5
The F5 key.
F6
The F6 key.
F7
The F7 key.
F8
The F8 key.
F9
The F9 key.
F10
The F10 key.
F11
The F11 key.
F12
The F12 key.
F13
The F13 key.
F14
The F14 key.
F15
The F15 key.
Pause
The Pause key.
KeyCount
Keep last the total number of keyboard keys.
Dash
> Deprecated: Use Hyphen instead
BackSpace
> Deprecated: Use Backspace instead
BackSlash
> Deprecated: Use Backslash instead
SemiColon
> Deprecated: Use Semicolon instead
Return
> Deprecated: Use Enter instead
Key codes.
class sf::Mouse
Give access to the real-time state of the mouse.
sf::Mouse provides an interface to the state of the mouse.
It only contains static functions (a single mouse is assumed), so it's not meant to be instantiated.
This class allows users to query the mouse state at any time and directly, without having to deal with a window and its events. Compared to the MouseMoved, MouseButtonPressed and MouseButtonReleased events, sf::Mouse can retrieve the state of the cursor and the buttons at any time (you don't need to store and update a boolean on your side in order to know if a button is pressed or released), and you always get the real state of the mouse, even if it is moved, pressed or released when your window is out of focus and no event is triggered.
The setPosition and getPosition functions can be used to change or retrieve the current position of the mouse pointer. There are two versions: one that operates in global coordinates (relative to the desktop) and one that operates in window coordinates (relative to a specific window).
Usage example:
if (sf::Mouse::isButtonPressed(sf::Mouse::Left))
{
// left click...
}
// get global mouse position
sf::Vector2i position = sf::Mouse::getPosition();
// set mouse position relative to a windowsf::Mouse::setPosition(sf::Vector2i(100, 200), window);
Give access to the real-time state of the sensors.
sf::Sensor provides an interface to the state of the various sensors that a device provides.
It only contains static functions, so it's not meant to be instantiated.
This class allows users to query the sensors values at any time and directly, without having to deal with a window and its events. Compared to the SensorChanged event, sf::Sensor can retrieve the state of a sensor at any time (you don't need to store and update its current value on your side).
Depending on the OS and hardware of the device (phone, tablet, ...), some sensor types may not be available. You should always check the availability of a sensor before trying to read it, with the sf::Sensor::isAvailable function.
You may wonder why some sensor types look so similar, for example Accelerometer and Gravity / UserAcceleration. The first one is the raw measurement of the acceleration, and takes into account both the earth gravity and the user movement. The others are more precise: they provide these components separately, which is usually more useful. In fact they are not direct sensors, they are computed internally based on the raw acceleration and other sensors. This is exactly the same for Gyroscope vs Orientation.
Because sensors consume a non-negligible amount of current, they are all disabled by default. You must call sf::Sensor::setEnabled for each sensor in which you are interested.
Usage example:
if (sf::Sensor::isAvailable(sf::Sensor::Gravity))
{
// gravity sensor is available
}
// enable the gravity sensorsf::Sensor::setEnabled(sf::Sensor::Gravity, true);
// get the current value of gravity
sf::Vector3f gravity = sf::Sensor::getValue(sf::Sensor::Gravity);
Give access to the real-time state of the touches.
sf::Touch provides an interface to the state of the touches.
It only contains static functions, so it's not meant to be instantiated.
This class allows users to query the touches state at any time and directly, without having to deal with a window and its events. Compared to the TouchBegan, TouchMoved and TouchEnded events, sf::Touch can retrieve the state of the touches at any time (you don't need to store and update a boolean on your side in order to know if a touch is down), and you always get the real state of the touches, even if they happen when your window is out of focus and no event is triggered.
The getPosition function can be used to retrieve the current position of a touch. There are two versions: one that operates in global coordinates (relative to the desktop) and one that operates in window coordinates (relative to a specific window).
Touches are identified by an index (the "finger"), so that in multi-touch events, individual touches can be tracked correctly. As long as a finger touches the screen, it will keep the same index even if other fingers start or stop touching the screen in the meantime. As a consequence, active touch indices may not always be sequential (i.e. touch number 0 may be released while touch number 1 is still down).
Usage example:
if (sf::Touch::isDown(0))
{
// touch 0 is down
}
// get global position of touch 1
sf::Vector2i globalPos = sf::Touch::getPosition(1);
// get position of touch 1 relative to a window
sf::Vector2i relativePos = sf::Touch::getPosition(1, window);
VideoMode defines a video mode (width, height, bpp)
A video mode is defined by a width and a height (in pixels) and a depth (in bits per pixel).
Video modes are used to setup windows (sf::Window) at creation time.
The main usage of video modes is for fullscreen mode: indeed you must use one of the valid video modes allowed by the OS (which are defined by what the monitor and the graphics card support), otherwise your window creation will just fail.
sf::VideoMode provides a static function for retrieving the list of all the video modes supported by the system: getFullscreenModes().
A custom video mode can also be checked directly for fullscreen compatibility with its isValid() function.
Additionally, sf::VideoMode provides a static function to get the mode currently used by the desktop: getDesktopMode(). This allows to build windows with the same size or pixel depth as the current resolution.
Usage example:
// Display the list of all the video modes available for fullscreen
std::vector<sf::VideoMode> modes = sf::VideoMode::getFullscreenModes();
for (std::size_t i = 0; i < modes.size(); ++i)
{
sf::VideoMode mode = modes[i];
std::cout << "Mode #" << i << ": "
<< mode.width << "x" << mode.height << " - "
<< mode.bitsPerPixel << " bpp" << std::endl;
}
// Create a window with the same pixel depth as the desktop
sf::VideoMode desktop = sf::VideoMode::getDesktopMode();
window.create(sf::VideoMode(1024, 768, desktop.bitsPerPixel), "SFML window");
It defines an OS window that is able to receive an OpenGL rendering.
A sf::Window can create its own new window, or be embedded into an already existing control using the create(handle) function. This can be useful for embedding an OpenGL rendering area into a view which is part of a bigger GUI with existing windows, controls, etc. It can also serve as embedding an OpenGL rendering area into a window created by another (probably richer) GUI library like Qt or wxWidgets.
The sf::Window class provides a simple interface for manipulating the window: move, resize, show/hide, control mouse cursor, etc. It also provides event handling through its pollEvent() and waitEvent() functions.
Note that OpenGL experts can pass their own parameters (antialiasing level, bits for the depth and stencil buffers, etc.) to the OpenGL context attached to the window, with the sf::ContextSettings structure which is passed as an optional argument when creating the window.
Usage example:
// Declare and create a new window
sf::Window window(sf::VideoMode(800, 600), "SFML window");
// Limit the framerate to 60 frames per second (this step is optional)
window.setFramerateLimit(60);
// The main loop - ends as soon as the window is closedwhile (window.isOpen())
{
// Event processing
sf::Event event;
while (window.pollEvent(event))
{
// Request for closing the windowif (event.type == sf::Event::Closed)
window.close();
}
// Activate the window for OpenGL rendering
window.setActive();
// OpenGL drawing commands go here...// End the current frame and display its contents on screen
window.display();
}
This constructor creates the window with the size and pixel depth defined in mode. An optional style can be passed to customize the look and behavior of the window (borders, title bar, resizable, closable, ...). If style contains Style::Fullscreen, then mode must be a valid video mode.
The fourth parameter is an optional structure specifying advanced OpenGL context settings such as antialiasing, depth-buffer bits, etc.
Parameters
mode Video mode to use (defines the width, height and depth of the rendering area of the window)
title Title of the window
style Window style, a bitwise OR combination of sf::Style enumerators
settings Additional settings for the underlying OpenGL context
Create (or recreate) the window from an existing control.
Use this function if you want to create an OpenGL rendering area into an already existing control. If the window was already created, it closes it first.
The second parameter is an optional structure specifying advanced OpenGL context settings such as antialiasing, depth-buffer bits, etc.
Parameters
handle Platform-specific handle of the control
settings Additional settings for the underlying OpenGL context
Close the window and destroy all the attached resources.
After calling this function, the sf::Window instance remains valid and you can call create() to recreate the window. All other functions such as pollEvent() or display() will still work (i.e. you don't have to test isOpen() every time), and will have no effect on closed windows.
This function returns whether or not the window exists. Note that a hidden window (setVisible(false)) is open (therefore this function would return true).
Returns
True if the window is open, false if it has been closed
Get the settings of the OpenGL context of the window.
Note that these settings may be different from what was passed to the constructor or the create() function, if one or more settings were not supported. In this case, SFML chose the closest match.
Pop the event on top of the event queue, if any, and return it.
This function is not blocking: if there's no pending event then it will return false and leave event unmodified. Note that more than one event may be present in the event queue, thus you should always call this function in a loop to make sure that you process every pending event.
sf::Event event;
while (window.pollEvent(event))
{
// process event...
}
This function is blocking: if there's no pending event then it will wait until an event is received. After this function returns (and no error occurred), the event object is always valid and filled properly. This function is typically used when you have a thread that is dedicated to events handling: you want to make this thread sleep as long as no new event is received.
sf::Event event;
if (window.waitEvent(event))
{
// process event...
}