Changed internal naming convention (local variables now start with a lower case character)

Removed the AudioResource class

git-svn-id: https://sfml.svn.sourceforge.net/svnroot/sfml/branches/sfml2@1166 4e206d99-4929-0410-ac5d-dfc041789085
This commit is contained in:
LaurentGom 2009-07-11 22:17:24 +00:00
parent 7cc00085d8
commit 45b150648d
245 changed files with 7865 additions and 8065 deletions

View file

@ -32,21 +32,23 @@
#include <iostream>
////////////////////////////////////////////////////////////
// Private data
////////////////////////////////////////////////////////////
namespace
{
sf::priv::AudioDevice globalDevice;
}
namespace sf
{
namespace priv
{
////////////////////////////////////////////////////////////
// Static member data
////////////////////////////////////////////////////////////
AudioDevice* AudioDevice::ourInstance;
////////////////////////////////////////////////////////////
/// Default constructor
////////////////////////////////////////////////////////////
AudioDevice::AudioDevice() :
myRefCount(0)
AudioDevice::AudioDevice()
{
// Create the device
myDevice = alcOpenDevice(NULL);
@ -98,42 +100,7 @@ AudioDevice::~AudioDevice()
////////////////////////////////////////////////////////////
AudioDevice& AudioDevice::GetInstance()
{
// Create the audio device if it doesn't exist
if (!ourInstance)
ourInstance = new AudioDevice;
return *ourInstance;
}
////////////////////////////////////////////////////////////
/// Add a reference to the audio device
////////////////////////////////////////////////////////////
void AudioDevice::AddReference()
{
// Create the audio device if it doesn't exist
if (!ourInstance)
ourInstance = new AudioDevice;
// Increase the references count
ourInstance->myRefCount++;
}
////////////////////////////////////////////////////////////
/// Remove a reference to the audio device
////////////////////////////////////////////////////////////
void AudioDevice::RemoveReference()
{
// Decrease the references count
ourInstance->myRefCount--;
// Destroy the audio device if the references count reaches 0
if (ourInstance->myRefCount == 0)
{
delete ourInstance;
ourInstance = NULL;
}
return globalDevice;
}
@ -149,10 +116,10 @@ ALCdevice* AudioDevice::GetDevice() const
////////////////////////////////////////////////////////////
/// Get the OpenAL format that matches the given number of channels
////////////////////////////////////////////////////////////
ALenum AudioDevice::GetFormatFromChannelsCount(unsigned int ChannelsCount) const
ALenum AudioDevice::GetFormatFromChannelsCount(unsigned int channelsCount) const
{
// Find the good format according to the number of channels
switch (ChannelsCount)
switch (channelsCount)
{
case 1 : return AL_FORMAT_MONO16;
case 2 : return AL_FORMAT_STEREO16;

View file

@ -35,8 +35,6 @@
namespace sf
{
class AudioResource;
namespace priv
{
@ -49,46 +47,6 @@ class AudioDevice
{
public :
////////////////////////////////////////////////////////////
/// Get the unique instance of the class
///
/// \return Unique instance of the class
///
////////////////////////////////////////////////////////////
static AudioDevice& GetInstance();
////////////////////////////////////////////////////////////
/// Add a reference to the audio device
///
////////////////////////////////////////////////////////////
static void AddReference();
////////////////////////////////////////////////////////////
/// Remove a reference to the audio device
///
////////////////////////////////////////////////////////////
static void RemoveReference();
////////////////////////////////////////////////////////////
/// Get the OpenAL audio device
///
/// \return OpenAL device (cannot be NULL)
///
////////////////////////////////////////////////////////////
ALCdevice* GetDevice() const;
////////////////////////////////////////////////////////////
/// Get the OpenAL format that matches the given number of channels
///
/// \param ChannelsCount : Number of channels
///
/// \return OpenAL device (cannot be NULL)
///
////////////////////////////////////////////////////////////
ALenum GetFormatFromChannelsCount(unsigned int ChannelsCount) const;
private :
////////////////////////////////////////////////////////////
/// Default constructor
///
@ -102,16 +60,38 @@ private :
~AudioDevice();
////////////////////////////////////////////////////////////
// Static member data
/// Get the unique instance of the class
///
/// \return Unique instance of the class
///
////////////////////////////////////////////////////////////
static AudioDevice* ourInstance; ///< Unique instance of the audio device
static AudioDevice& GetInstance();
////////////////////////////////////////////////////////////
/// Get the OpenAL audio device
///
/// \return OpenAL device (cannot be NULL)
///
////////////////////////////////////////////////////////////
ALCdevice* GetDevice() const;
////////////////////////////////////////////////////////////
/// Get the OpenAL format that matches the given number of channels
///
/// \param channelsCount : Number of channels
///
/// \return Corresponding format
///
////////////////////////////////////////////////////////////
ALenum GetFormatFromChannelsCount(unsigned int channelsCount) const;
private :
////////////////////////////////////////////////////////////
// Member data
////////////////////////////////////////////////////////////
ALCdevice* myDevice; ///< Audio device
ALCcontext* myContext; ///< Audio context
unsigned int myRefCount; ///< References count
ALCdevice* myDevice; ///< Audio device
ALCcontext* myContext; ///< Audio context
};
} // namespace priv

View file

@ -1,60 +0,0 @@
////////////////////////////////////////////////////////////
//
// SFML - Simple and Fast Multimedia Library
// Copyright (C) 2007-2009 Laurent Gomila (laurent.gom@gmail.com)
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it freely,
// subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented;
// you must not claim that you wrote the original software.
// If you use this software in a product, an acknowledgment
// in the product documentation would be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such,
// and must not be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source distribution.
//
////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <SFML/Audio/AudioResource.hpp>
#include <SFML/Audio/AudioDevice.hpp>
namespace sf
{
////////////////////////////////////////////////////////////
/// Default constructor
////////////////////////////////////////////////////////////
AudioResource::AudioResource()
{
priv::AudioDevice::AddReference();
}
////////////////////////////////////////////////////////////
/// Copy constructor
////////////////////////////////////////////////////////////
AudioResource::AudioResource(const AudioResource&)
{
priv::AudioDevice::AddReference();
}
////////////////////////////////////////////////////////////
/// Destructor
////////////////////////////////////////////////////////////
AudioResource::~AudioResource()
{
priv::AudioDevice::RemoveReference();
}
} // namespace sf

View file

@ -34,9 +34,9 @@ namespace sf
////////////////////////////////////////////////////////////
/// Change the global volume of all the sounds
////////////////////////////////////////////////////////////
void Listener::SetGlobalVolume(float Volume)
void Listener::SetGlobalVolume(float volume)
{
ALCheck(alListenerf(AL_GAIN, Volume * 0.01f));
ALCheck(alListenerf(AL_GAIN, volume * 0.01f));
}
@ -45,28 +45,28 @@ void Listener::SetGlobalVolume(float Volume)
////////////////////////////////////////////////////////////
float Listener::GetGlobalVolume()
{
float Volume = 0.f;
ALCheck(alGetListenerf(AL_GAIN, &Volume));
float volume = 0.f;
ALCheck(alGetListenerf(AL_GAIN, &volume));
return Volume;
return volume;
}
////////////////////////////////////////////////////////////
/// Change the position of the listener (take 3 values)
////////////////////////////////////////////////////////////
void Listener::SetPosition(float X, float Y, float Z)
void Listener::SetPosition(float x, float y, float z)
{
ALCheck(alListener3f(AL_POSITION, X, Y, Z));
ALCheck(alListener3f(AL_POSITION, x, y, z));
}
////////////////////////////////////////////////////////////
/// Change the position of the listener (take a 3D vector)
////////////////////////////////////////////////////////////
void Listener::SetPosition(const Vector3f& Position)
void Listener::SetPosition(const Vector3f& position)
{
SetPosition(Position.x, Position.y, Position.z);
SetPosition(position.x, position.y, position.z);
}
@ -75,10 +75,10 @@ void Listener::SetPosition(const Vector3f& Position)
////////////////////////////////////////////////////////////
Vector3f Listener::GetPosition()
{
Vector3f Position;
ALCheck(alGetListener3f(AL_POSITION, &Position.x, &Position.y, &Position.z));
Vector3f position;
ALCheck(alGetListener3f(AL_POSITION, &position.x, &position.y, &position.z));
return Position;
return position;
}
@ -86,10 +86,10 @@ Vector3f Listener::GetPosition()
/// Change the orientation of the listener (the point
/// he must look at) (take 3 values)
////////////////////////////////////////////////////////////
void Listener::SetTarget(float X, float Y, float Z)
void Listener::SetTarget(float x, float y, float z)
{
float Orientation[] = {X, Y, Z, 0.f, 1.f, 0.f};
ALCheck(alListenerfv(AL_ORIENTATION, Orientation));
float orientation[] = {x, y, z, 0.f, 1.f, 0.f};
ALCheck(alListenerfv(AL_ORIENTATION, orientation));
}
@ -97,9 +97,9 @@ void Listener::SetTarget(float X, float Y, float Z)
/// Change the orientation of the listener (the point
/// he must look at) (take a 3D vector)
////////////////////////////////////////////////////////////
void Listener::SetTarget(const Vector3f& Target)
void Listener::SetTarget(const Vector3f& target)
{
SetTarget(Target.x, Target.y, Target.z);
SetTarget(target.x, target.y, target.z);
}
@ -109,10 +109,10 @@ void Listener::SetTarget(const Vector3f& Target)
////////////////////////////////////////////////////////////
Vector3f Listener::GetTarget()
{
float Orientation[6];
ALCheck(alGetListenerfv(AL_ORIENTATION, Orientation));
float orientation[6];
ALCheck(alGetListenerfv(AL_ORIENTATION, orientation));
return Vector3f(Orientation[0], Orientation[1], Orientation[2]);
return Vector3f(orientation[0], orientation[1], orientation[2]);
}
} // namespace sf

View file

@ -38,10 +38,10 @@ namespace sf
////////////////////////////////////////////////////////////
/// Construct the music with a buffer size
////////////////////////////////////////////////////////////
Music::Music(std::size_t BufferSize) :
Music::Music(std::size_t bufferSize) :
myFile (new priv::SoundFile),
myDuration(0.f),
mySamples (BufferSize)
mySamples (bufferSize)
{
}
@ -62,15 +62,15 @@ Music::~Music()
////////////////////////////////////////////////////////////
/// Open a music file (doesn't play it -- call Play() for that)
////////////////////////////////////////////////////////////
bool Music::OpenFromFile(const std::string& Filename)
bool Music::OpenFromFile(const std::string& filename)
{
// First stop the music if it was already running
Stop();
// Create the sound file implementation, and open it in read mode
if (!myFile->OpenRead(Filename))
if (!myFile->OpenRead(filename))
{
std::cerr << "Failed to open \"" << Filename << "\" for reading" << std::endl;
std::cerr << "Failed to open \"" << filename << "\" for reading" << std::endl;
return false;
}
@ -87,13 +87,13 @@ bool Music::OpenFromFile(const std::string& Filename)
////////////////////////////////////////////////////////////
/// Open a music file from memory (doesn't play it -- call Play() for that)
////////////////////////////////////////////////////////////
bool Music::OpenFromMemory(const char* Data, std::size_t SizeInBytes)
bool Music::OpenFromMemory(const char* data, std::size_t sizeInBytes)
{
// First stop the music if it was already running
Stop();
// Create the sound file implementation, and open it in read mode
if (!myFile->OpenRead(Data, SizeInBytes))
if (!myFile->OpenRead(data, sizeInBytes))
{
std::cerr << "Failed to open music from memory for reading" << std::endl;
return false;
@ -121,27 +121,27 @@ float Music::GetDuration() const
////////////////////////////////////////////////////////////
/// /see SoundStream::OnGetData
////////////////////////////////////////////////////////////
bool Music::OnGetData(SoundStream::Chunk& Data)
bool Music::OnGetData(SoundStream::Chunk& data)
{
sf::Lock Lock(myMutex);
sf::Lock lock(myMutex);
// Fill the chunk parameters
Data.Samples = &mySamples[0];
Data.NbSamples = myFile->Read(&mySamples[0], mySamples.size());
data.Samples = &mySamples[0];
data.NbSamples = myFile->Read(&mySamples[0], mySamples.size());
// Check if we have reached the end of the audio file
return Data.NbSamples == mySamples.size();
return data.NbSamples == mySamples.size();
}
////////////////////////////////////////////////////////////
/// /see SoundStream::OnSeek
////////////////////////////////////////////////////////////
void Music::OnSeek(float TimeOffset)
void Music::OnSeek(float timeOffset)
{
sf::Lock Lock(myMutex);
sf::Lock lock(myMutex);
myFile->Seek(TimeOffset);
myFile->Seek(timeOffset);
}
} // namespace sf

View file

@ -29,18 +29,17 @@
// Headers
////////////////////////////////////////////////////////////
#include <SFML/Config.hpp>
#if defined(SFML_SYSTEM_MACOS)
#include <OpenAL/al.h>
#include <OpenAL/alc.h>
#else
#include <AL/al.h>
#include <AL/alc.h>
#endif
#include <iostream>
#include <string>
#if defined(SFML_SYSTEM_MACOS)
#include <OpenAL/al.h>
#include <OpenAL/alc.h>
#else
#include <AL/al.h>
#include <AL/alc.h>
#endif
namespace sf
{
@ -68,58 +67,58 @@ namespace priv
/// Check last OpenAL error
///
////////////////////////////////////////////////////////////
inline void ALCheckError(const std::string& File, unsigned int Line)
inline void ALCheckError(const std::string& file, unsigned int line)
{
// Get the last error
ALenum ErrorCode = alGetError();
ALenum errorCode = alGetError();
if (ErrorCode != AL_NO_ERROR)
if (errorCode != AL_NO_ERROR)
{
std::string Error, Desc;
std::string error, description;
// Decode the error code
switch (ErrorCode)
switch (errorCode)
{
case AL_INVALID_NAME :
{
Error = "AL_INVALID_NAME";
Desc = "an unacceptable name has been specified";
error = "AL_INVALID_NAME";
description = "an unacceptable name has been specified";
break;
}
case AL_INVALID_ENUM :
{
Error = "AL_INVALID_ENUM";
Desc = "an unacceptable value has been specified for an enumerated argument";
error = "AL_INVALID_ENUM";
description = "an unacceptable value has been specified for an enumerated argument";
break;
}
case AL_INVALID_VALUE :
{
Error = "AL_INVALID_VALUE";
Desc = "a numeric argument is out of range";
error = "AL_INVALID_VALUE";
description = "a numeric argument is out of range";
break;
}
case AL_INVALID_OPERATION :
{
Error = "AL_INVALID_OPERATION";
Desc = "the specified operation is not allowed in the current state";
error = "AL_INVALID_OPERATION";
description = "the specified operation is not allowed in the current state";
break;
}
case AL_OUT_OF_MEMORY :
{
Error = "AL_OUT_OF_MEMORY";
Desc = "there is not enough memory left to execute the command";
error = "AL_OUT_OF_MEMORY";
description = "there is not enough memory left to execute the command";
break;
}
}
// Log the error
std::cerr << "An internal OpenAL call failed in "
<< File.substr(File.find_last_of("\\/") + 1) << " (" << Line << ") : "
<< Error << ", " << Desc
<< file.substr(file.find_last_of("\\/") + 1) << " (" << line << ") : "
<< error << ", " << description
<< std::endl;
}
}

View file

@ -45,33 +45,32 @@ Sound::Sound()
////////////////////////////////////////////////////////////
/// Construct the sound from its parameters
////////////////////////////////////////////////////////////
Sound::Sound(const SoundBuffer& Buffer, bool Loop, float Pitch, float Volume, const Vector3f& Position) :
myBuffer(&Buffer)
Sound::Sound(const SoundBuffer& buffer, bool loop, float pitch, float volume, const Vector3f& position) :
myBuffer(&buffer)
{
ALCheck(alGenSources(1, &mySource));
ALCheck(alSourcei (mySource, AL_BUFFER, Buffer.myBuffer));
ALCheck(alSourcei (mySource, AL_LOOPING, Loop));
ALCheck(alSourcef (mySource, AL_PITCH, Pitch));
ALCheck(alSourcef (mySource, AL_GAIN, Volume * 0.01f));
ALCheck(alSource3f(mySource, AL_POSITION, Position.x, Position.y, Position.z));
ALCheck(alSourcei (mySource, AL_BUFFER, buffer.myBuffer));
ALCheck(alSourcei (mySource, AL_LOOPING, loop));
ALCheck(alSourcef (mySource, AL_PITCH, pitch));
ALCheck(alSourcef (mySource, AL_GAIN, volume * 0.01f));
ALCheck(alSource3f(mySource, AL_POSITION, position.x, position.y, position.z));
}
////////////////////////////////////////////////////////////
/// Copy constructor
////////////////////////////////////////////////////////////
Sound::Sound(const Sound& Copy) :
AudioResource(Copy),
myBuffer (Copy.myBuffer)
Sound::Sound(const Sound& copy) :
myBuffer(copy.myBuffer)
{
ALCheck(alGenSources(1, &mySource));
ALCheck(alSourcei (mySource, AL_BUFFER, myBuffer ? myBuffer->myBuffer : 0));
ALCheck(alSourcei (mySource, AL_LOOPING, Copy.GetLoop()));
ALCheck(alSourcef (mySource, AL_PITCH, Copy.GetPitch()));
ALCheck(alSourcef (mySource, AL_GAIN, Copy.GetVolume() * 0.01f));
ALCheck(alSource3f(mySource, AL_POSITION, Copy.GetPosition().x, Copy.GetPosition().y, Copy.GetPosition().z));
ALCheck(alSourcei (mySource, AL_LOOPING, copy.GetLoop()));
ALCheck(alSourcef (mySource, AL_PITCH, copy.GetPitch()));
ALCheck(alSourcef (mySource, AL_GAIN, copy.GetVolume() * 0.01f));
ALCheck(alSource3f(mySource, AL_POSITION, copy.GetPosition().x, copy.GetPosition().y, copy.GetPosition().z));
}
@ -122,10 +121,10 @@ void Sound::Stop()
////////////////////////////////////////////////////////////
/// Set the source buffer
////////////////////////////////////////////////////////////
void Sound::SetBuffer(const SoundBuffer& Buffer)
void Sound::SetBuffer(const SoundBuffer& buffer)
{
myBuffer = &Buffer;
ALCheck(alSourcei(mySource, AL_BUFFER, myBuffer ? myBuffer->myBuffer : 0));
myBuffer = &buffer;
ALCheck(alSourcei(mySource, AL_BUFFER, myBuffer->myBuffer));
}
@ -141,27 +140,27 @@ void Sound::SetLoop(bool Loop)
////////////////////////////////////////////////////////////
/// Set the sound pitch
////////////////////////////////////////////////////////////
void Sound::SetPitch(float Pitch)
void Sound::SetPitch(float pitch)
{
ALCheck(alSourcef(mySource, AL_PITCH, Pitch));
ALCheck(alSourcef(mySource, AL_PITCH, pitch));
}
////////////////////////////////////////////////////////////
/// Set the sound volume
////////////////////////////////////////////////////////////
void Sound::SetVolume(float Volume)
void Sound::SetVolume(float volume)
{
ALCheck(alSourcef(mySource, AL_GAIN, Volume * 0.01f));
ALCheck(alSourcef(mySource, AL_GAIN, volume * 0.01f));
}
////////////////////////////////////////////////////////////
/// Set the sound position (take 3 values).
/// The default position is (0, 0, 0)
////////////////////////////////////////////////////////////
void Sound::SetPosition(float X, float Y, float Z)
void Sound::SetPosition(float x, float y, float z)
{
ALCheck(alSource3f(mySource, AL_POSITION, X, Y, Z));
ALCheck(alSource3f(mySource, AL_POSITION, x, y, z));
}
@ -169,9 +168,9 @@ void Sound::SetPosition(float X, float Y, float Z)
/// Set the sound position (take a 3D vector).
/// The default position is (0, 0, 0)
////////////////////////////////////////////////////////////
void Sound::SetPosition(const Vector3f& Position)
void Sound::SetPosition(const Vector3f& position)
{
SetPosition(Position.x, Position.y, Position.z);
SetPosition(position.x, position.y, position.z);
}
@ -180,9 +179,9 @@ void Sound::SetPosition(const Vector3f& Position)
/// position, or absolute.
/// The default value is false (absolute)
////////////////////////////////////////////////////////////
void Sound::SetRelativeToListener(bool Relative)
void Sound::SetRelativeToListener(bool relative)
{
ALCheck(alSourcei(mySource, AL_SOURCE_RELATIVE, Relative));
ALCheck(alSourcei(mySource, AL_SOURCE_RELATIVE, relative));
}
@ -191,9 +190,9 @@ void Sound::SetRelativeToListener(bool Relative)
/// the listener will hear the sound at its maximum volume.
/// The default minimum distance is 1.0
////////////////////////////////////////////////////////////
void Sound::SetMinDistance(float MinDistance)
void Sound::SetMinDistance(float distance)
{
ALCheck(alSourcef(mySource, AL_REFERENCE_DISTANCE, MinDistance));
ALCheck(alSourcef(mySource, AL_REFERENCE_DISTANCE, distance));
}
@ -202,18 +201,18 @@ void Sound::SetMinDistance(float MinDistance)
/// more the sound will be attenuated with distance from listener.
/// The default attenuation factor 1.0
////////////////////////////////////////////////////////////
void Sound::SetAttenuation(float Attenuation)
void Sound::SetAttenuation(float attenuation)
{
ALCheck(alSourcef(mySource, AL_ROLLOFF_FACTOR, Attenuation));
ALCheck(alSourcef(mySource, AL_ROLLOFF_FACTOR, attenuation));
}
////////////////////////////////////////////////////////////
/// Set the current playing position of the sound
////////////////////////////////////////////////////////////
void Sound::SetPlayingOffset(float TimeOffset)
void Sound::SetPlayingOffset(float timeOffset)
{
ALCheck(alSourcef(mySource, AL_SEC_OFFSET, TimeOffset));
ALCheck(alSourcef(mySource, AL_SEC_OFFSET, timeOffset));
}
@ -231,10 +230,10 @@ const SoundBuffer* Sound::GetBuffer() const
////////////////////////////////////////////////////////////
bool Sound::GetLoop() const
{
ALint Loop;
ALCheck(alGetSourcei(mySource, AL_LOOPING, &Loop));
ALint loop;
ALCheck(alGetSourcei(mySource, AL_LOOPING, &loop));
return Loop != 0;
return loop != 0;
}
@ -243,10 +242,10 @@ bool Sound::GetLoop() const
////////////////////////////////////////////////////////////
float Sound::GetPitch() const
{
ALfloat Pitch;
ALCheck(alGetSourcef(mySource, AL_PITCH, &Pitch));
ALfloat pitch;
ALCheck(alGetSourcef(mySource, AL_PITCH, &pitch));
return Pitch;
return pitch;
}
@ -255,10 +254,10 @@ float Sound::GetPitch() const
////////////////////////////////////////////////////////////
float Sound::GetVolume() const
{
ALfloat Gain;
ALCheck(alGetSourcef(mySource, AL_GAIN, &Gain));
ALfloat gain;
ALCheck(alGetSourcef(mySource, AL_GAIN, &gain));
return Gain * 100.f;
return gain * 100.f;
}
@ -267,10 +266,10 @@ float Sound::GetVolume() const
////////////////////////////////////////////////////////////
Vector3f Sound::GetPosition() const
{
Vector3f Position;
ALCheck(alGetSource3f(mySource, AL_POSITION, &Position.x, &Position.y, &Position.z));
Vector3f position;
ALCheck(alGetSource3f(mySource, AL_POSITION, &position.x, &position.y, &position.z));
return Position;
return position;
}
@ -280,10 +279,10 @@ Vector3f Sound::GetPosition() const
////////////////////////////////////////////////////////////
bool Sound::IsRelativeToListener() const
{
ALint Relative;
ALCheck(alGetSourcei(mySource, AL_SOURCE_RELATIVE, &Relative));
ALint relative;
ALCheck(alGetSourcei(mySource, AL_SOURCE_RELATIVE, &relative));
return Relative != 0;
return relative != 0;
}
@ -292,10 +291,10 @@ bool Sound::IsRelativeToListener() const
////////////////////////////////////////////////////////////
float Sound::GetMinDistance() const
{
ALfloat MinDistance;
ALCheck(alGetSourcef(mySource, AL_REFERENCE_DISTANCE, &MinDistance));
ALfloat distance;
ALCheck(alGetSourcef(mySource, AL_REFERENCE_DISTANCE, &distance));
return MinDistance;
return distance;
}
@ -304,10 +303,10 @@ float Sound::GetMinDistance() const
////////////////////////////////////////////////////////////
float Sound::GetAttenuation() const
{
ALfloat Attenuation;
ALCheck(alGetSourcef(mySource, AL_ROLLOFF_FACTOR, &Attenuation));
ALfloat attenuation;
ALCheck(alGetSourcef(mySource, AL_ROLLOFF_FACTOR, &attenuation));
return Attenuation;
return attenuation;
}
@ -316,10 +315,10 @@ float Sound::GetAttenuation() const
////////////////////////////////////////////////////////////
float Sound::GetPlayingOffset() const
{
ALfloat Seconds = 0.f;
ALCheck(alGetSourcef(mySource, AL_SEC_OFFSET, &Seconds));
ALfloat seconds = 0.f;
ALCheck(alGetSourcef(mySource, AL_SEC_OFFSET, &seconds));
return Seconds;
return seconds;
}
@ -328,10 +327,10 @@ float Sound::GetPlayingOffset() const
////////////////////////////////////////////////////////////
Sound::Status Sound::GetStatus() const
{
ALint State;
ALCheck(alGetSourcei(mySource, AL_SOURCE_STATE, &State));
ALint status;
ALCheck(alGetSourcei(mySource, AL_SOURCE_STATE, &status));
switch (State)
switch (status)
{
case AL_INITIAL :
case AL_STOPPED : return Stopped;
@ -346,12 +345,12 @@ Sound::Status Sound::GetStatus() const
////////////////////////////////////////////////////////////
/// Assignment operator
////////////////////////////////////////////////////////////
Sound& Sound::operator =(const Sound& Other)
Sound& Sound::operator =(const Sound& other)
{
Sound Temp(Other);
Sound temp(other);
std::swap(mySource, Temp.mySource);
std::swap(myBuffer, Temp.myBuffer);
std::swap(mySource, temp.mySource);
std::swap(myBuffer, temp.myBuffer);
return *this;
}

View file

@ -50,18 +50,17 @@ myDuration(0.f)
////////////////////////////////////////////////////////////
/// Copy constructor
////////////////////////////////////////////////////////////
SoundBuffer::SoundBuffer(const SoundBuffer& Copy) :
AudioResource (Copy),
Resource<SoundBuffer>(Copy),
SoundBuffer::SoundBuffer(const SoundBuffer& copy) :
Resource<SoundBuffer>(copy),
myBuffer (0),
mySamples (Copy.mySamples),
myDuration (Copy.myDuration)
mySamples (copy.mySamples),
myDuration (copy.myDuration)
{
// Create the buffer
ALCheck(alGenBuffers(1, &myBuffer));
// Update the internal buffer with the new samples
Update(Copy.GetChannelsCount(), Copy.GetSampleRate());
Update(copy.GetChannelsCount(), copy.GetSampleRate());
}
@ -78,23 +77,23 @@ SoundBuffer::~SoundBuffer()
////////////////////////////////////////////////////////////
/// Load the sound buffer from a file
////////////////////////////////////////////////////////////
bool SoundBuffer::LoadFromFile(const std::string& Filename)
bool SoundBuffer::LoadFromFile(const std::string& filename)
{
// Open the sound file
priv::SoundFile File;
if (File.OpenRead(Filename))
priv::SoundFile file;
if (file.OpenRead(filename))
{
// Get the sound parameters
std::size_t NbSamples = File.GetSamplesCount();
unsigned int ChannelsCount = File.GetChannelsCount();
unsigned int SampleRate = File.GetSampleRate();
std::size_t nbSamples = file.GetSamplesCount();
unsigned int channelsCount = file.GetChannelsCount();
unsigned int sampleRate = file.GetSampleRate();
// Read the samples from the opened file
mySamples.resize(NbSamples);
if (File.Read(&mySamples[0], NbSamples) == NbSamples)
mySamples.resize(nbSamples);
if (file.Read(&mySamples[0], nbSamples) == nbSamples)
{
// Update the internal buffer with the new samples
return Update(ChannelsCount, SampleRate);
return Update(channelsCount, sampleRate);
}
else
{
@ -111,23 +110,23 @@ bool SoundBuffer::LoadFromFile(const std::string& Filename)
////////////////////////////////////////////////////////////
/// Load the sound buffer from a file in memory
////////////////////////////////////////////////////////////
bool SoundBuffer::LoadFromMemory(const char* Data, std::size_t SizeInBytes)
bool SoundBuffer::LoadFromMemory(const char* data, std::size_t sizeInBytes)
{
// Open the sound file
priv::SoundFile File;
if (File.OpenRead(Data, SizeInBytes))
priv::SoundFile file;
if (file.OpenRead(data, sizeInBytes))
{
// Get the sound parameters
std::size_t NbSamples = File.GetSamplesCount();
unsigned int ChannelsCount = File.GetChannelsCount();
unsigned int SampleRate = File.GetSampleRate();
std::size_t nbSamples = file.GetSamplesCount();
unsigned int channelsCount = file.GetChannelsCount();
unsigned int sampleRate = file.GetSampleRate();
// Read the samples from the opened file
mySamples.resize(NbSamples);
if (File.Read(&mySamples[0], NbSamples) == NbSamples)
mySamples.resize(nbSamples);
if (file.Read(&mySamples[0], nbSamples) == nbSamples)
{
// Update the internal buffer with the new samples
return Update(ChannelsCount, SampleRate);
return Update(channelsCount, sampleRate);
}
else
{
@ -145,24 +144,24 @@ bool SoundBuffer::LoadFromMemory(const char* Data, std::size_t SizeInBytes)
/// Load the sound buffer from an array of samples - assumed format for
/// samples is 16 bits signed integer
////////////////////////////////////////////////////////////
bool SoundBuffer::LoadFromSamples(const Int16* Samples, std::size_t SamplesCount, unsigned int ChannelsCount, unsigned int SampleRate)
bool SoundBuffer::LoadFromSamples(const Int16* samples, std::size_t samplesCount, unsigned int channelsCount, unsigned int sampleRate)
{
if (Samples && SamplesCount && ChannelsCount && SampleRate)
if (samples && samplesCount && channelsCount && sampleRate)
{
// Copy the new audio samples
mySamples.assign(Samples, Samples + SamplesCount);
mySamples.assign(samples, samples + samplesCount);
// Update the internal buffer with the new samples
return Update(ChannelsCount, SampleRate);
return Update(channelsCount, sampleRate);
}
else
{
// Error...
std::cerr << "Failed to load sound buffer from memory ("
<< "Samples : " << Samples << ", "
<< "Samples count : " << SamplesCount << ", "
<< "Channels count : " << ChannelsCount << ", "
<< "Sample rate : " << SampleRate << ")"
<< "Samples : " << samples << ", "
<< "Samples count : " << samplesCount << ", "
<< "Channels count : " << channelsCount << ", "
<< "Sample rate : " << sampleRate << ")"
<< std::endl;
return false;
@ -173,14 +172,14 @@ bool SoundBuffer::LoadFromSamples(const Int16* Samples, std::size_t SamplesCount
////////////////////////////////////////////////////////////
/// Save the sound buffer to a file
////////////////////////////////////////////////////////////
bool SoundBuffer::SaveToFile(const std::string& Filename) const
bool SoundBuffer::SaveToFile(const std::string& filename) const
{
// Create the sound file in write mode
priv::SoundFile File;
if (File.OpenWrite(Filename, GetChannelsCount(), GetSampleRate()))
priv::SoundFile file;
if (file.OpenWrite(filename, GetChannelsCount(), GetSampleRate()))
{
// Write the samples to the opened file
File.Write(&mySamples[0], mySamples.size());
file.Write(&mySamples[0], mySamples.size());
return true;
}
@ -214,10 +213,10 @@ std::size_t SoundBuffer::GetSamplesCount() const
////////////////////////////////////////////////////////////
unsigned int SoundBuffer::GetSampleRate() const
{
ALint SampleRate;
ALCheck(alGetBufferi(myBuffer, AL_FREQUENCY, &SampleRate));
ALint sampleRate;
ALCheck(alGetBufferi(myBuffer, AL_FREQUENCY, &sampleRate));
return SampleRate;
return sampleRate;
}
@ -226,10 +225,10 @@ unsigned int SoundBuffer::GetSampleRate() const
////////////////////////////////////////////////////////////
unsigned int SoundBuffer::GetChannelsCount() const
{
ALint ChannelsCount;
ALCheck(alGetBufferi(myBuffer, AL_CHANNELS, &ChannelsCount));
ALint channelsCount;
ALCheck(alGetBufferi(myBuffer, AL_CHANNELS, &channelsCount));
return ChannelsCount;
return channelsCount;
}
@ -245,13 +244,13 @@ float SoundBuffer::GetDuration() const
////////////////////////////////////////////////////////////
/// Assignment operator
////////////////////////////////////////////////////////////
SoundBuffer& SoundBuffer::operator =(const SoundBuffer& Other)
SoundBuffer& SoundBuffer::operator =(const SoundBuffer& other)
{
SoundBuffer Temp(Other);
SoundBuffer temp(other);
mySamples.swap(Temp.mySamples);
std::swap(myBuffer, Temp.myBuffer);
std::swap(myDuration, Temp.myDuration);
mySamples.swap(temp.mySamples);
std::swap(myBuffer, temp.myBuffer);
std::swap(myDuration, temp.myDuration);
return *this;
}
@ -260,28 +259,28 @@ SoundBuffer& SoundBuffer::operator =(const SoundBuffer& Other)
////////////////////////////////////////////////////////////
/// Update the internal buffer with the audio samples
////////////////////////////////////////////////////////////
bool SoundBuffer::Update(unsigned int ChannelsCount, unsigned int SampleRate)
bool SoundBuffer::Update(unsigned int channelsCount, unsigned int sampleRate)
{
// Check parameters
if (!SampleRate || !ChannelsCount || mySamples.empty())
if (!channelsCount || !sampleRate || mySamples.empty())
return false;
// Find the good format according to the number of channels
ALenum Format = priv::AudioDevice::GetInstance().GetFormatFromChannelsCount(ChannelsCount);
ALenum format = priv::AudioDevice::GetInstance().GetFormatFromChannelsCount(channelsCount);
// Check if the format is valid
if (Format == 0)
if (format == 0)
{
std::cerr << "Unsupported number of channels (" << ChannelsCount << ")" << std::endl;
std::cerr << "Unsupported number of channels (" << channelsCount << ")" << std::endl;
return false;
}
// Fill the buffer
ALsizei Size = static_cast<ALsizei>(mySamples.size()) * sizeof(Int16);
ALCheck(alBufferData(myBuffer, Format, &mySamples[0], Size, SampleRate));
ALsizei size = static_cast<ALsizei>(mySamples.size()) * sizeof(Int16);
ALCheck(alBufferData(myBuffer, format, &mySamples[0], size, sampleRate));
// Compute the duration
myDuration = static_cast<float>(mySamples.size()) / SampleRate / ChannelsCount;
myDuration = static_cast<float>(mySamples.size()) / sampleRate / channelsCount;
return true;
}

View file

@ -46,9 +46,9 @@ bool SoundBufferRecorder::OnStart()
////////////////////////////////////////////////////////////
/// /see SoundBuffer::OnProcessSamples
////////////////////////////////////////////////////////////
bool SoundBufferRecorder::OnProcessSamples(const Int16* Samples, std::size_t SamplesCount)
bool SoundBufferRecorder::OnProcessSamples(const Int16* samples, std::size_t samplesCount)
{
std::copy(Samples, Samples + SamplesCount, std::back_inserter(mySamples));
std::copy(samples, samples + samplesCount, std::back_inserter(mySamples));
return true;
}

View file

@ -87,25 +87,25 @@ unsigned int SoundFile::GetSampleRate() const
////////////////////////////////////////////////////////////
/// Open the sound file for reading
////////////////////////////////////////////////////////////
bool SoundFile::OpenRead(const std::string& Filename)
bool SoundFile::OpenRead(const std::string& filename)
{
// If the file is already opened, first close it
if (myFile)
sf_close(myFile);
// Open the sound file
SF_INFO FileInfos;
myFile = sf_open(Filename.c_str(), SFM_READ, &FileInfos);
SF_INFO fileInfos;
myFile = sf_open(filename.c_str(), SFM_READ, &fileInfos);
if (!myFile)
{
std::cerr << "Failed to read sound file \"" << Filename << "\" (" << sf_strerror(myFile) << ")" << std::endl;
std::cerr << "Failed to read sound file \"" << filename << "\" (" << sf_strerror(myFile) << ")" << std::endl;
return false;
}
// Set the sound parameters
myChannelsCount = FileInfos.channels;
mySampleRate = FileInfos.samplerate;
myNbSamples = static_cast<std::size_t>(FileInfos.frames) * myChannelsCount;
myChannelsCount = fileInfos.channels;
mySampleRate = fileInfos.samplerate;
myNbSamples = static_cast<std::size_t>(fileInfos.frames) * myChannelsCount;
return true;
}
@ -114,28 +114,28 @@ bool SoundFile::OpenRead(const std::string& Filename)
////////////////////////////////////////////////////////////
/// Open the sound file in memory for reading
////////////////////////////////////////////////////////////
bool SoundFile::OpenRead(const char* Data, std::size_t SizeInBytes)
bool SoundFile::OpenRead(const char* data, std::size_t sizeInBytes)
{
// If the file is already opened, first close it
if (myFile)
sf_close(myFile);
// Define the I/O custom functions for reading from memory
SF_VIRTUAL_IO VirtualIO;
VirtualIO.get_filelen = &SoundFile::MemoryGetLength;
VirtualIO.read = &SoundFile::MemoryRead;
VirtualIO.seek = &SoundFile::MemorySeek;
VirtualIO.tell = &SoundFile::MemoryTell;
VirtualIO.write = &SoundFile::MemoryWrite;
SF_VIRTUAL_IO io;
io.get_filelen = &SoundFile::MemoryGetLength;
io.read = &SoundFile::MemoryRead;
io.seek = &SoundFile::MemorySeek;
io.tell = &SoundFile::MemoryTell;
io.write = &SoundFile::MemoryWrite;
// Initialize the memory data
myMemory.DataStart = Data;
myMemory.DataPtr = Data;
myMemory.TotalSize = SizeInBytes;
myMemory.DataStart = data;
myMemory.DataPtr = data;
myMemory.TotalSize = sizeInBytes;
// Open the sound file
SF_INFO FileInfos;
myFile = sf_open_virtual(&VirtualIO, SFM_READ, &FileInfos, &myMemory);
SF_INFO fileInfos;
myFile = sf_open_virtual(&io, SFM_READ, &fileInfos, &myMemory);
if (!myFile)
{
std::cerr << "Failed to read sound file from memory (" << sf_strerror(myFile) << ")" << std::endl;
@ -143,9 +143,9 @@ bool SoundFile::OpenRead(const char* Data, std::size_t SizeInBytes)
}
// Set the sound parameters
myChannelsCount = FileInfos.channels;
mySampleRate = FileInfos.samplerate;
myNbSamples = static_cast<std::size_t>(FileInfos.frames) * myChannelsCount;
myChannelsCount = fileInfos.channels;
mySampleRate = fileInfos.samplerate;
myNbSamples = static_cast<std::size_t>(fileInfos.frames) * myChannelsCount;
return true;
}
@ -154,38 +154,38 @@ bool SoundFile::OpenRead(const char* Data, std::size_t SizeInBytes)
////////////////////////////////////////////////////////////
/// Open the sound file for writing
////////////////////////////////////////////////////////////
bool SoundFile::OpenWrite(const std::string& Filename, unsigned int ChannelsCount, unsigned int SampleRate)
bool SoundFile::OpenWrite(const std::string& filename, unsigned int channelsCount, unsigned int sampleRate)
{
// If the file is already opened, first close it
if (myFile)
sf_close(myFile);
// Find the right format according to the file extension
int Format = GetFormatFromFilename(Filename);
if (Format == -1)
int format = GetFormatFromFilename(filename);
if (format == -1)
{
// Error : unrecognized extension
std::cerr << "Failed to create sound file \"" << Filename << "\" (unknown format)" << std::endl;
std::cerr << "Failed to create sound file \"" << filename << "\" (unknown format)" << std::endl;
return false;
}
// Fill the sound infos with parameters
SF_INFO FileInfos;
FileInfos.channels = ChannelsCount;
FileInfos.samplerate = SampleRate;
FileInfos.format = Format | (Format == SF_FORMAT_OGG ? SF_FORMAT_VORBIS : SF_FORMAT_PCM_16);
SF_INFO fileInfos;
fileInfos.channels = channelsCount;
fileInfos.samplerate = sampleRate;
fileInfos.format = format | (format == SF_FORMAT_OGG ? SF_FORMAT_VORBIS : SF_FORMAT_PCM_16);
// Open the sound file for writing
myFile = sf_open(Filename.c_str(), SFM_WRITE, &FileInfos);
myFile = sf_open(filename.c_str(), SFM_WRITE, &fileInfos);
if (!myFile)
{
std::cerr << "Failed to create sound file \"" << Filename << "\" (" << sf_strerror(myFile) << ")" << std::endl;
std::cerr << "Failed to create sound file \"" << filename << "\" (" << sf_strerror(myFile) << ")" << std::endl;
return false;
}
// Set the sound parameters
myChannelsCount = ChannelsCount;
mySampleRate = SampleRate;
myChannelsCount = channelsCount;
mySampleRate = sampleRate;
myNbSamples = 0;
return true;
@ -195,10 +195,10 @@ bool SoundFile::OpenWrite(const std::string& Filename, unsigned int ChannelsCoun
////////////////////////////////////////////////////////////
/// Read samples from the loaded sound
////////////////////////////////////////////////////////////
std::size_t SoundFile::Read(Int16* Data, std::size_t NbSamples)
std::size_t SoundFile::Read(Int16* data, std::size_t nbSamples)
{
if (myFile && Data && NbSamples)
return static_cast<std::size_t>(sf_read_short(myFile, Data, NbSamples));
if (myFile && data && nbSamples)
return static_cast<std::size_t>(sf_read_short(myFile, data, nbSamples));
else
return 0;
}
@ -207,18 +207,18 @@ std::size_t SoundFile::Read(Int16* Data, std::size_t NbSamples)
////////////////////////////////////////////////////////////
/// Write samples to the file
////////////////////////////////////////////////////////////
void SoundFile::Write(const Int16* Data, std::size_t NbSamples)
void SoundFile::Write(const Int16* data, std::size_t nbSamples)
{
if (myFile && Data && NbSamples)
if (myFile && data && nbSamples)
{
// Write small chunks instead of everything at once,
// to avoid a stack overflow in libsndfile (happens only with OGG format)
while (NbSamples > 0)
while (nbSamples > 0)
{
std::size_t Count = NbSamples > 10000 ? 10000 : NbSamples;
sf_write_short(myFile, Data, Count);
Data += Count;
NbSamples -= Count;
std::size_t count = nbSamples > 10000 ? 10000 : nbSamples;
sf_write_short(myFile, data, count);
data += count;
nbSamples -= count;
}
}
}
@ -227,12 +227,12 @@ void SoundFile::Write(const Int16* Data, std::size_t NbSamples)
////////////////////////////////////////////////////////////
/// Move the current reading position in the file
////////////////////////////////////////////////////////////
void SoundFile::Seek(float TimeOffset)
void SoundFile::Seek(float timeOffset)
{
if (myFile)
{
sf_count_t FrameOffset = static_cast<sf_count_t>(TimeOffset * mySampleRate);
sf_seek(myFile, FrameOffset, SEEK_SET);
sf_count_t frameOffset = static_cast<sf_count_t>(timeOffset * mySampleRate);
sf_seek(myFile, frameOffset, SEEK_SET);
}
}
@ -241,40 +241,40 @@ void SoundFile::Seek(float TimeOffset)
/// Get the internal format of an audio file according to
/// its filename extension
////////////////////////////////////////////////////////////
int SoundFile::GetFormatFromFilename(const std::string& Filename)
int SoundFile::GetFormatFromFilename(const std::string& filename)
{
// Extract the extension
std::string Ext = "wav";
std::string::size_type Pos = Filename.find_last_of(".");
if (Pos != std::string::npos)
Ext = Filename.substr(Pos + 1);
std::string ext = "wav";
std::string::size_type pos = filename.find_last_of(".");
if (pos != std::string::npos)
ext = filename.substr(pos + 1);
// Match every supported extension with its format constant
if (Ext == "wav" || Ext == "WAV" ) return SF_FORMAT_WAV;
if (Ext == "aif" || Ext == "AIF" ) return SF_FORMAT_AIFF;
if (Ext == "aiff" || Ext == "AIFF") return SF_FORMAT_AIFF;
if (Ext == "au" || Ext == "AU" ) return SF_FORMAT_AU;
if (Ext == "raw" || Ext == "RAW" ) return SF_FORMAT_RAW;
if (Ext == "paf" || Ext == "PAF" ) return SF_FORMAT_PAF;
if (Ext == "svx" || Ext == "SVX" ) return SF_FORMAT_SVX;
if (Ext == "nist" || Ext == "NIST") return SF_FORMAT_NIST;
if (Ext == "voc" || Ext == "VOC" ) return SF_FORMAT_VOC;
if (Ext == "sf" || Ext == "SF" ) return SF_FORMAT_IRCAM;
if (Ext == "w64" || Ext == "W64" ) return SF_FORMAT_W64;
if (Ext == "mat4" || Ext == "MAT4") return SF_FORMAT_MAT4;
if (Ext == "mat5" || Ext == "MAT5") return SF_FORMAT_MAT5;
if (Ext == "pvf" || Ext == "PVF" ) return SF_FORMAT_PVF;
if (Ext == "xi" || Ext == "XI" ) return SF_FORMAT_XI;
if (Ext == "htk" || Ext == "HTK" ) return SF_FORMAT_HTK;
if (Ext == "sds" || Ext == "SDS" ) return SF_FORMAT_SDS;
if (Ext == "avr" || Ext == "AVR" ) return SF_FORMAT_AVR;
if (Ext == "sd2" || Ext == "SD2" ) return SF_FORMAT_SD2;
if (Ext == "flac" || Ext == "FLAC") return SF_FORMAT_FLAC;
if (Ext == "caf" || Ext == "CAF" ) return SF_FORMAT_CAF;
if (Ext == "wve" || Ext == "WVE" ) return SF_FORMAT_WVE;
if (Ext == "ogg" || Ext == "OGG") return SF_FORMAT_OGG;
if (Ext == "mpc2k" || Ext == "MPC2K") return SF_FORMAT_MPC2K;
if (Ext == "rf64" || Ext == "RF64") return SF_FORMAT_RF64;
if (ext == "wav" || ext == "WAV" ) return SF_FORMAT_WAV;
if (ext == "aif" || ext == "AIF" ) return SF_FORMAT_AIFF;
if (ext == "aiff" || ext == "AIFF") return SF_FORMAT_AIFF;
if (ext == "au" || ext == "AU" ) return SF_FORMAT_AU;
if (ext == "raw" || ext == "RAW" ) return SF_FORMAT_RAW;
if (ext == "paf" || ext == "PAF" ) return SF_FORMAT_PAF;
if (ext == "svx" || ext == "SVX" ) return SF_FORMAT_SVX;
if (ext == "nist" || ext == "NIST") return SF_FORMAT_NIST;
if (ext == "voc" || ext == "VOC" ) return SF_FORMAT_VOC;
if (ext == "sf" || ext == "SF" ) return SF_FORMAT_IRCAM;
if (ext == "w64" || ext == "W64" ) return SF_FORMAT_W64;
if (ext == "mat4" || ext == "MAT4") return SF_FORMAT_MAT4;
if (ext == "mat5" || ext == "MAT5") return SF_FORMAT_MAT5;
if (ext == "pvf" || ext == "PVF" ) return SF_FORMAT_PVF;
if (ext == "xi" || ext == "XI" ) return SF_FORMAT_XI;
if (ext == "htk" || ext == "HTK" ) return SF_FORMAT_HTK;
if (ext == "sds" || ext == "SDS" ) return SF_FORMAT_SDS;
if (ext == "avr" || ext == "AVR" ) return SF_FORMAT_AVR;
if (ext == "sd2" || ext == "SD2" ) return SF_FORMAT_SD2;
if (ext == "flac" || ext == "FLAC") return SF_FORMAT_FLAC;
if (ext == "caf" || ext == "CAF" ) return SF_FORMAT_CAF;
if (ext == "wve" || ext == "WVE" ) return SF_FORMAT_WVE;
if (ext == "ogg" || ext == "OGG") return SF_FORMAT_OGG;
if (ext == "mpc2k" || ext == "MPC2K") return SF_FORMAT_MPC2K;
if (ext == "rf64" || ext == "RF64") return SF_FORMAT_RF64;
return -1;
}
@ -283,61 +283,61 @@ int SoundFile::GetFormatFromFilename(const std::string& Filename)
////////////////////////////////////////////////////////////
/// Functions for implementing custom read and write to memory files
////////////////////////////////////////////////////////////
sf_count_t SoundFile::MemoryGetLength(void* UserData)
sf_count_t SoundFile::MemoryGetLength(void* userData)
{
MemoryInfos* Memory = static_cast<MemoryInfos*>(UserData);
MemoryInfos* memory = static_cast<MemoryInfos*>(userData);
return Memory->TotalSize;
return memory->TotalSize;
}
sf_count_t SoundFile::MemoryRead(void* Ptr, sf_count_t Count, void* UserData)
sf_count_t SoundFile::MemoryRead(void* ptr, sf_count_t count, void* userData)
{
MemoryInfos* Memory = static_cast<MemoryInfos*>(UserData);
MemoryInfos* memory = static_cast<MemoryInfos*>(userData);
sf_count_t Position = Memory->DataPtr - Memory->DataStart;
if (Position + Count >= Memory->TotalSize)
Count = Memory->TotalSize - Position;
sf_count_t position = memory->DataPtr - memory->DataStart;
if (position + count >= memory->TotalSize)
count = memory->TotalSize - position;
memcpy(Ptr, Memory->DataPtr, static_cast<std::size_t>(Count));
memcpy(ptr, memory->DataPtr, static_cast<std::size_t>(count));
Memory->DataPtr += Count;
memory->DataPtr += count;
return Count;
return count;
}
sf_count_t SoundFile::MemorySeek(sf_count_t Offset, int Whence, void* UserData)
sf_count_t SoundFile::MemorySeek(sf_count_t offset, int whence, void* userData)
{
MemoryInfos* Memory = static_cast<MemoryInfos*>(UserData);
MemoryInfos* memory = static_cast<MemoryInfos*>(userData);
sf_count_t Position = 0;
switch (Whence)
sf_count_t position = 0;
switch (whence)
{
case SEEK_SET :
Position = Offset;
position = offset;
break;
case SEEK_CUR :
Position = Memory->DataPtr - Memory->DataStart + Offset;
position = memory->DataPtr - memory->DataStart + offset;
break;
case SEEK_END :
Position = Memory->TotalSize - Offset;
position = memory->TotalSize - offset;
break;
default :
Position = 0;
position = 0;
break;
}
if (Position >= Memory->TotalSize)
Position = Memory->TotalSize - 1;
else if (Position < 0)
Position = 0;
if (position >= memory->TotalSize)
position = memory->TotalSize - 1;
else if (position < 0)
position = 0;
Memory->DataPtr = Memory->DataStart + Position;
memory->DataPtr = memory->DataStart + position;
return Position;
return position;
}
sf_count_t SoundFile::MemoryTell(void* UserData)
sf_count_t SoundFile::MemoryTell(void* userData)
{
MemoryInfos* Memory = static_cast<MemoryInfos*>(UserData);
MemoryInfos* memory = static_cast<MemoryInfos*>(userData);
return Memory->DataPtr - Memory->DataStart;
return memory->DataPtr - memory->DataStart;
}
sf_count_t SoundFile::MemoryWrite(const void*, sf_count_t, void*)
{

View file

@ -84,63 +84,63 @@ public :
////////////////////////////////////////////////////////////
/// Open the sound file for reading
///
/// \param Filename : Path of sound file to load
/// \param filename : Path of sound file to load
///
/// \return True if the file was successfully opened
///
////////////////////////////////////////////////////////////
bool OpenRead(const std::string& Filename);
bool OpenRead(const std::string& filename);
////////////////////////////////////////////////////////////
/// Open the sound file in memory for reading
///
/// \param Data : Pointer to the file data in memory
/// \param SizeInBytes : Size of the data to load, in bytes
/// \param data : Pointer to the file data in memory
/// \param sizeInBytes : Size of the data to load, in bytes
///
/// \return True if the file was successfully opened
///
////////////////////////////////////////////////////////////
bool OpenRead(const char* Data, std::size_t SizeInBytes);
bool OpenRead(const char* data, std::size_t sizeInBytes);
////////////////////////////////////////////////////////////
/// Open the sound file for writing
///
/// \param Filename : Path of sound file to write
/// \param ChannelsCount : Number of channels in the sound
/// \param SampleRate : Sample rate of the sound
/// \param filename : Path of sound file to write
/// \param channelsCount : Number of channels in the sound
/// \param sampleRate : Sample rate of the sound
///
/// \return True if the file was successfully opened
///
////////////////////////////////////////////////////////////
bool OpenWrite(const std::string& Filename, unsigned int ChannelsCount, unsigned int SampleRate);
bool OpenWrite(const std::string& filename, unsigned int channelsCount, unsigned int sampleRate);
////////////////////////////////////////////////////////////
/// Read samples from the loaded sound
///
/// \param Data : Pointer to the samples array to fill
/// \param NbSamples : Number of samples to read
/// \param data : Pointer to the samples array to fill
/// \param nbSamples : Number of samples to read
///
/// \return Number of samples read
///
////////////////////////////////////////////////////////////
std::size_t Read(Int16* Data, std::size_t NbSamples);
std::size_t Read(Int16* data, std::size_t nbSamples);
////////////////////////////////////////////////////////////
/// Write samples to the file
///
/// \param Data : Pointer to the samples array to write
/// \param NbSamples : Number of samples to write
/// \param data : Pointer to the samples array to write
/// \param nbSamples : Number of samples to write
///
////////////////////////////////////////////////////////////
void Write(const Int16* Data, std::size_t NbSamples);
void Write(const Int16* data, std::size_t nbSamples);
////////////////////////////////////////////////////////////
/// Move the current reading position in the file
///
/// \param TimeOffset : New position, expressed in seconds
/// \param timeOffset : New position, expressed in seconds
///
////////////////////////////////////////////////////////////
void Seek(float TimeOffset);
void Seek(float timeOffset);
private :
@ -148,12 +148,12 @@ private :
/// Get the internal format of an audio file according to
/// its filename extension
///
/// \param Filename : Filename to check
/// \param filename : Filename to check
///
/// \return Internal format matching the filename (-1 if no match)
///
////////////////////////////////////////////////////////////
static int GetFormatFromFilename(const std::string& Filename);
static int GetFormatFromFilename(const std::string& filename);
////////////////////////////////////////////////////////////
/// Functions for implementing custom read and write to memory files

View file

@ -37,7 +37,7 @@
////////////////////////////////////////////////////////////
namespace
{
ALCdevice* CaptureDevice = NULL;
ALCdevice* captureDevice = NULL;
}
namespace sf
@ -66,7 +66,7 @@ SoundRecorder::~SoundRecorder()
/// Start the capture.
/// Warning : only one capture can happen at the same time
////////////////////////////////////////////////////////////
void SoundRecorder::Start(unsigned int SampleRate)
void SoundRecorder::Start(unsigned int sampleRate)
{
// Check if the device can do audio capture
if (!CanCapture())
@ -76,15 +76,15 @@ void SoundRecorder::Start(unsigned int SampleRate)
}
// Check that another capture is not already running
if (CaptureDevice)
if (captureDevice)
{
std::cerr << "Trying to start audio capture, but another capture is already running" << std::endl;
return;
}
// Open the capture device for capturing 16 bits mono samples
CaptureDevice = alcCaptureOpenDevice(NULL, SampleRate, AL_FORMAT_MONO16, SampleRate);
if (!CaptureDevice)
captureDevice = alcCaptureOpenDevice(NULL, sampleRate, AL_FORMAT_MONO16, sampleRate);
if (!captureDevice)
{
std::cerr << "Failed to open the audio capture device" << std::endl;
return;
@ -94,13 +94,13 @@ void SoundRecorder::Start(unsigned int SampleRate)
mySamples.clear();
// Store the sample rate
mySampleRate = SampleRate;
mySampleRate = sampleRate;
// Notify derived class
if (OnStart())
{
// Start the capture
alcCaptureStart(CaptureDevice);
alcCaptureStart(captureDevice);
// Start the capture in a new thread, to avoid blocking the main thread
myIsCapturing = true;
@ -135,9 +135,9 @@ unsigned int SoundRecorder::GetSampleRate() const
////////////////////////////////////////////////////////////
bool SoundRecorder::CanCapture()
{
ALCdevice* Device = priv::AudioDevice::GetInstance().GetDevice();
ALCdevice* device = priv::AudioDevice::GetInstance().GetDevice();
return alcIsExtensionPresent(Device, "ALC_EXT_CAPTURE") != AL_FALSE;
return alcIsExtensionPresent(device, "ALC_EXT_CAPTURE") != AL_FALSE;
}
@ -188,14 +188,14 @@ void SoundRecorder::Run()
void SoundRecorder::ProcessCapturedSamples()
{
// Get the number of samples available
ALCint SamplesAvailable;
alcGetIntegerv(CaptureDevice, ALC_CAPTURE_SAMPLES, 1, &SamplesAvailable);
ALCint samplesAvailable;
alcGetIntegerv(captureDevice, ALC_CAPTURE_SAMPLES, 1, &samplesAvailable);
if (SamplesAvailable > 0)
if (samplesAvailable > 0)
{
// Get the recorded samples
mySamples.resize(SamplesAvailable);
alcCaptureSamples(CaptureDevice, &mySamples[0], SamplesAvailable);
mySamples.resize(samplesAvailable);
alcCaptureSamples(captureDevice, &mySamples[0], samplesAvailable);
// Forward them to the derived class
if (!OnProcessSamples(&mySamples[0], mySamples.size()))
@ -213,14 +213,14 @@ void SoundRecorder::ProcessCapturedSamples()
void SoundRecorder::CleanUp()
{
// Stop the capture
alcCaptureStop(CaptureDevice);
alcCaptureStop(captureDevice);
// Get the samples left in the buffer
ProcessCapturedSamples();
// Close the device
alcCaptureCloseDevice(CaptureDevice);
CaptureDevice = NULL;
alcCaptureCloseDevice(captureDevice);
captureDevice = NULL;
}
} // namespace sf

View file

@ -61,13 +61,13 @@ SoundStream::~SoundStream()
////////////////////////////////////////////////////////////
/// Set the audio stream parameters, you must call it before Play()
////////////////////////////////////////////////////////////
void SoundStream::Initialize(unsigned int ChannelsCount, unsigned int SampleRate)
void SoundStream::Initialize(unsigned int channelsCount, unsigned int sampleRate)
{
myChannelsCount = ChannelsCount;
mySampleRate = SampleRate;
myChannelsCount = channelsCount;
mySampleRate = sampleRate;
// Deduce the format from the number of channels
myFormat = priv::AudioDevice::GetInstance().GetFormatFromChannelsCount(ChannelsCount);
myFormat = priv::AudioDevice::GetInstance().GetFormatFromChannelsCount(channelsCount);
// Check if the format is valid
if (myFormat == 0)
@ -142,29 +142,29 @@ unsigned int SoundStream::GetSampleRate() const
////////////////////////////////////////////////////////////
Sound::Status SoundStream::GetStatus() const
{
Status Status = Sound::GetStatus();
Status status = Sound::GetStatus();
// To compensate for the lag between Play() and alSourcePlay()
if ((Status == Stopped) && myIsStreaming)
Status = Playing;
if ((status == Stopped) && myIsStreaming)
status = Playing;
return Status;
return status;
}
////////////////////////////////////////////////////////////
/// Set the current playing position of the stream
////////////////////////////////////////////////////////////
void SoundStream::SetPlayingOffset(float TimeOffset)
void SoundStream::SetPlayingOffset(float timeOffset)
{
// Stop the stream
Stop();
// Let the derived class update the current position
OnSeek(TimeOffset);
OnSeek(timeOffset);
// Restart streaming
mySamplesProcessed = static_cast<unsigned int>(TimeOffset * mySampleRate * myChannelsCount);
mySamplesProcessed = static_cast<unsigned int>(timeOffset * mySampleRate * myChannelsCount);
myIsStreaming = true;
Launch();
}
@ -185,9 +185,9 @@ float SoundStream::GetPlayingOffset() const
////////////////////////////////////////////////////////////
/// Set the music loop state
////////////////////////////////////////////////////////////
void SoundStream::SetLoop(bool Loop)
void SoundStream::SetLoop(bool loop)
{
myLoop = Loop;
myLoop = loop;
}
@ -207,10 +207,10 @@ void SoundStream::Run()
{
// Create buffers
ALCheck(alGenBuffers(BuffersCount, myBuffers));
unsigned int EndBuffer = 0xFFFF;
unsigned int endBuffer = 0xFFFF;
// Fill the queue
bool RequestStop = FillQueue();
bool requestStop = FillQueue();
// Play the sound
Sound::Play();
@ -220,7 +220,7 @@ void SoundStream::Run()
// The stream has been interrupted !
if (Sound::GetStatus() == Stopped)
{
if (!RequestStop)
if (!requestStop)
{
// Just continue
Sound::Play();
@ -233,33 +233,33 @@ void SoundStream::Run()
}
// Get the number of buffers that have been processed (ie. ready for reuse)
ALint NbProcessed;
ALCheck(alGetSourcei(Sound::mySource, AL_BUFFERS_PROCESSED, &NbProcessed));
ALint nbProcessed;
ALCheck(alGetSourcei(Sound::mySource, AL_BUFFERS_PROCESSED, &nbProcessed));
while (NbProcessed--)
while (nbProcessed--)
{
// Pop the first unused buffer from the queue
ALuint Buffer;
ALCheck(alSourceUnqueueBuffers(Sound::mySource, 1, &Buffer));
ALuint buffer;
ALCheck(alSourceUnqueueBuffers(Sound::mySource, 1, &buffer));
// Retrieve its size and add it to the samples count
if (Buffer == EndBuffer)
if (buffer == endBuffer)
{
// This was the last buffer: reset the sample count
mySamplesProcessed = 0;
EndBuffer = 0xFFFF;
endBuffer = 0xFFFF;
}
else
{
ALint Size;
ALCheck(alGetBufferi(Buffer, AL_SIZE, &Size));
mySamplesProcessed += Size / sizeof(Int16);
ALint size;
ALCheck(alGetBufferi(buffer, AL_SIZE, &size));
mySamplesProcessed += size / sizeof(Int16);
}
// Fill it and push it back into the playing queue
if (!RequestStop)
if (!requestStop)
{
if (FillAndPushBuffer(Buffer))
if (FillAndPushBuffer(buffer))
{
// User requested to stop: check if we must loop or really stop
if (myLoop)
@ -267,12 +267,12 @@ void SoundStream::Run()
// Looping: restart and mark the current buffer as the last one
// (to know when to reset the sample count)
OnSeek(0);
EndBuffer = Buffer;
endBuffer = buffer;
}
else
{
// Not looping: request stop
RequestStop = true;
requestStop = true;
}
}
}
@ -299,27 +299,27 @@ void SoundStream::Run()
/// Fill a new buffer with audio data, and push it to the
/// playing queue
////////////////////////////////////////////////////////////
bool SoundStream::FillAndPushBuffer(unsigned int Buffer)
bool SoundStream::FillAndPushBuffer(unsigned int buffer)
{
bool RequestStop = false;
bool requestStop = false;
// Acquire audio data
Chunk Data = {NULL, 0};
if (!OnGetData(Data))
RequestStop = true;
Chunk data = {NULL, 0};
if (!OnGetData(data))
requestStop = true;
// Create and fill the buffer, and push it to the queue
if (Data.Samples && Data.NbSamples)
if (data.Samples && data.NbSamples)
{
// Fill the buffer
ALsizei Size = static_cast<ALsizei>(Data.NbSamples) * sizeof(Int16);
ALCheck(alBufferData(Buffer, myFormat, Data.Samples, Size, mySampleRate));
ALsizei size = static_cast<ALsizei>(data.NbSamples) * sizeof(Int16);
ALCheck(alBufferData(buffer, myFormat, data.Samples, size, mySampleRate));
// Push it into the sound queue
ALCheck(alSourceQueueBuffers(Sound::mySource, 1, &Buffer));
ALCheck(alSourceQueueBuffers(Sound::mySource, 1, &buffer));
}
return RequestStop;
return requestStop;
}
@ -329,14 +329,14 @@ bool SoundStream::FillAndPushBuffer(unsigned int Buffer)
bool SoundStream::FillQueue()
{
// Fill and enqueue all the available buffers
bool RequestStop = false;
for (int i = 0; (i < BuffersCount) && !RequestStop; ++i)
bool requestStop = false;
for (int i = 0; (i < BuffersCount) && !requestStop; ++i)
{
if (FillAndPushBuffer(myBuffers[i]))
RequestStop = true;
requestStop = true;
}
return RequestStop;
return requestStop;
}
@ -346,13 +346,13 @@ bool SoundStream::FillQueue()
void SoundStream::ClearQueue()
{
// Get the number of buffers still in the queue
ALint NbQueued;
ALCheck(alGetSourcei(Sound::mySource, AL_BUFFERS_QUEUED, &NbQueued));
ALint nbQueued;
ALCheck(alGetSourcei(Sound::mySource, AL_BUFFERS_QUEUED, &nbQueued));
// Unqueue them all
ALuint Buffer;
for (ALint i = 0; i < NbQueued; ++i)
ALCheck(alSourceUnqueueBuffers(Sound::mySource, 1, &Buffer));
ALuint buffer;
for (ALint i = 0; i < nbQueued; ++i)
ALCheck(alSourceUnqueueBuffers(Sound::mySource, 1, &buffer));
}
} // namespace sf

View file

@ -60,83 +60,76 @@ a(255)
////////////////////////////////////////////////////////////
/// Construct the color from its 4 RGBA components
////////////////////////////////////////////////////////////
Color::Color(Uint8 R, Uint8 G, Uint8 B, Uint8 A) :
r(R),
g(G),
b(B),
a(A)
Color::Color(Uint8 red, Uint8 green, Uint8 blue, Uint8 alpha) :
r(red),
g(green),
b(blue),
a(alpha)
{
}
////////////////////////////////////////////////////////////
/// Operator += overload to add a color
////////////////////////////////////////////////////////////
Color& Color::operator +=(const Color& Other)
{
r = static_cast<Uint8>(std::min(r + Other.r, 255));
g = static_cast<Uint8>(std::min(g + Other.g, 255));
b = static_cast<Uint8>(std::min(b + Other.b, 255));
a = static_cast<Uint8>(std::min(a + Other.a, 255));
return *this;
}
////////////////////////////////////////////////////////////
/// Operator *= overload to modulate a color
////////////////////////////////////////////////////////////
Color& Color::operator *=(const Color& Other)
{
r = static_cast<Uint8>(r * Other.r / 255);
g = static_cast<Uint8>(g * Other.g / 255);
b = static_cast<Uint8>(b * Other.b / 255);
a = static_cast<Uint8>(a * Other.a / 255);
return *this;
}
////////////////////////////////////////////////////////////
/// Compare two colors (for equality)
////////////////////////////////////////////////////////////
bool Color::operator ==(const Color& Other) const
bool operator ==(const Color& left, const Color& right)
{
return (r == Other.r) && (g == Other.g) && (b == Other.b) && (a == Other.a);
return (left.r == right.r) &&
(left.g == right.g) &&
(left.b == right.b) &&
(left.a == right.a);
}
////////////////////////////////////////////////////////////
/// Compare two colors (for difference)
////////////////////////////////////////////////////////////
bool Color::operator !=(const Color& Other) const
bool operator !=(const Color& left, const Color& right)
{
return (r != Other.r) || (g != Other.g) || (b != Other.b) || (a != Other.a);
return !(left == right);
}
////////////////////////////////////////////////////////////
/// Operator + overload to add two colors
////////////////////////////////////////////////////////////
Color operator +(const Color& Color1, const Color& Color2)
Color operator +(const Color& left, const Color& right)
{
Color c = Color1;
c += Color2;
return c;
return Color(static_cast<Uint8>(std::min(left.r + right.r, 255)),
static_cast<Uint8>(std::min(left.g + right.g, 255)),
static_cast<Uint8>(std::min(left.b + right.b, 255)),
static_cast<Uint8>(std::min(left.a + right.a, 255)));
}
////////////////////////////////////////////////////////////
/// Operator * overload to modulate two colors
////////////////////////////////////////////////////////////
Color operator *(const Color& Color1, const Color& Color2)
Color operator *(const Color& left, const Color& right)
{
Color c = Color1;
c *= Color2;
return Color(static_cast<Uint8>(left.r * right.r / 255),
static_cast<Uint8>(left.g * right.g / 255),
static_cast<Uint8>(left.b * right.b / 255),
static_cast<Uint8>(left.a * right.a / 255));
}
return c;
////////////////////////////////////////////////////////////
/// Operator += overload to add a color
////////////////////////////////////////////////////////////
Color& operator +=(Color& left, const Color& right)
{
return left = left + right;
}
////////////////////////////////////////////////////////////
/// Operator *= overload to modulate a color
////////////////////////////////////////////////////////////
Color& operator *=(Color& left, const Color& right)
{
return left = left * right;
}
} // namespace sf

View file

@ -36,12 +36,12 @@ namespace sf
////////////////////////////////////////////////////////////
/// Default constructor
////////////////////////////////////////////////////////////
Drawable::Drawable(const Vector2f& Position, const Vector2f& Scale, float Rotation, const Color& Col) :
myPosition (Position),
myScale (Scale),
Drawable::Drawable(const Vector2f& position, const Vector2f& scale, float rotation, const Color& color) :
myPosition (position),
myScale (scale),
myOrigin (0, 0),
myRotation (Rotation),
myColor (Col),
myRotation (rotation),
myColor (color),
myBlendMode (Blend::Alpha),
myNeedUpdate (true),
myInvNeedUpdate(true)
@ -63,29 +63,29 @@ Drawable::~Drawable()
////////////////////////////////////////////////////////////
/// Set the position of the object (take 2 values)
////////////////////////////////////////////////////////////
void Drawable::SetPosition(float X, float Y)
void Drawable::SetPosition(float x, float y)
{
SetX(X);
SetY(Y);
SetX(x);
SetY(y);
}
////////////////////////////////////////////////////////////
/// Set the position of the object (take a 2D vector)
////////////////////////////////////////////////////////////
void Drawable::SetPosition(const Vector2f& Position)
void Drawable::SetPosition(const Vector2f& position)
{
SetX(Position.x);
SetY(Position.y);
SetX(position.x);
SetY(position.y);
}
////////////////////////////////////////////////////////////
/// Set the X position of the object
////////////////////////////////////////////////////////////
void Drawable::SetX(float X)
void Drawable::SetX(float x)
{
myPosition.x = X;
myPosition.x = x;
myNeedUpdate = true;
myInvNeedUpdate = true;
}
@ -94,9 +94,9 @@ void Drawable::SetX(float X)
////////////////////////////////////////////////////////////
/// Set the Y position of the object
////////////////////////////////////////////////////////////
void Drawable::SetY(float Y)
void Drawable::SetY(float y)
{
myPosition.y = Y;
myPosition.y = y;
myNeedUpdate = true;
myInvNeedUpdate = true;
}
@ -105,31 +105,31 @@ void Drawable::SetY(float Y)
////////////////////////////////////////////////////////////
/// Set the scale of the object (take 2 values)
////////////////////////////////////////////////////////////
void Drawable::SetScale(float ScaleX, float ScaleY)
void Drawable::SetScale(float factorX, float factorY)
{
SetScaleX(ScaleX);
SetScaleY(ScaleY);
SetScaleX(factorX);
SetScaleY(factorY);
}
////////////////////////////////////////////////////////////
/// Set the scale of the object (take a 2D vector)
////////////////////////////////////////////////////////////
void Drawable::SetScale(const Vector2f& Scale)
void Drawable::SetScale(const Vector2f& scale)
{
SetScaleX(Scale.x);
SetScaleY(Scale.y);
SetScaleX(scale.x);
SetScaleY(scale.y);
}
////////////////////////////////////////////////////////////
/// Set the X scale factor of the object
////////////////////////////////////////////////////////////
void Drawable::SetScaleX(float FactorX)
void Drawable::SetScaleX(float factor)
{
if (FactorX > 0)
if (factor > 0)
{
myScale.x = FactorX;
myScale.x = factor;
myNeedUpdate = true;
myInvNeedUpdate = true;
}
@ -139,11 +139,11 @@ void Drawable::SetScaleX(float FactorX)
////////////////////////////////////////////////////////////
/// Set the Y scale factor of the object
////////////////////////////////////////////////////////////
void Drawable::SetScaleY(float FactorY)
void Drawable::SetScaleY(float factor)
{
if (FactorY > 0)
if (factor > 0)
{
myScale.y = FactorY;
myScale.y = factor;
myNeedUpdate = true;
myInvNeedUpdate = true;
}
@ -155,10 +155,10 @@ void Drawable::SetScaleY(float FactorY)
/// top-left of the object (take 2 values).
/// The default origin is (0, 0)
////////////////////////////////////////////////////////////
void Drawable::SetOrigin(float OriginX, float OriginY)
void Drawable::SetOrigin(float x, float y)
{
myOrigin.x = OriginX;
myOrigin.y = OriginY;
myOrigin.x = x;
myOrigin.y = y;
myNeedUpdate = true;
myInvNeedUpdate = true;
}
@ -169,18 +169,18 @@ void Drawable::SetOrigin(float OriginX, float OriginY)
/// top-left of the object (take a 2D vector).
/// The default origin is (0, 0)
////////////////////////////////////////////////////////////
void Drawable::SetOrigin(const Vector2f& Origin)
void Drawable::SetOrigin(const Vector2f& origin)
{
SetOrigin(Origin.x, Origin.y);
SetOrigin(origin.x, origin.y);
}
////////////////////////////////////////////////////////////
/// Set the orientation of the object
////////////////////////////////////////////////////////////
void Drawable::SetRotation(float Rotation)
void Drawable::SetRotation(float angle)
{
myRotation = static_cast<float>(fmod(Rotation, 360));
myRotation = static_cast<float>(fmod(angle, 360));
if (myRotation < 0)
myRotation += 360.f;
myNeedUpdate = true;
@ -192,9 +192,9 @@ void Drawable::SetRotation(float Rotation)
/// Set the color of the object.
/// The default color is white
////////////////////////////////////////////////////////////
void Drawable::SetColor(const Color& Col)
void Drawable::SetColor(const Color& color)
{
myColor = Col;
myColor = color;
}
@ -202,9 +202,9 @@ void Drawable::SetColor(const Color& Col)
/// Set the blending mode for the object.
/// The default blend mode is Blend::Alpha
////////////////////////////////////////////////////////////
void Drawable::SetBlendMode(Blend::Mode Mode)
void Drawable::SetBlendMode(Blend::Mode mode)
{
myBlendMode = Mode;
myBlendMode = mode;
}
@ -266,47 +266,45 @@ Blend::Mode Drawable::GetBlendMode() const
/// Move the object of a given offset (take 2 values)
///
////////////////////////////////////////////////////////////
void Drawable::Move(float OffsetX, float OffsetY)
void Drawable::Move(float offsetX, float offsetY)
{
SetX(myPosition.x + OffsetX);
SetY(myPosition.y + OffsetY);
SetPosition(myPosition.x + offsetX, myPosition.y + offsetY);
}
////////////////////////////////////////////////////////////
/// Move the object of a given offset (take a 2D vector)
////////////////////////////////////////////////////////////
void Drawable::Move(const Vector2f& Offset)
void Drawable::Move(const Vector2f& offset)
{
Move(Offset.x, Offset.y);
SetPosition(myPosition + offset);
}
////////////////////////////////////////////////////////////
/// Scale the object (take 2 values)
////////////////////////////////////////////////////////////
void Drawable::Scale(float FactorX, float FactorY)
void Drawable::Scale(float factorX, float factorY)
{
SetScaleX(myScale.x * FactorX);
SetScaleY(myScale.y * FactorY);
SetScale(myScale.x * factorX, myScale.y * factorY);
}
////////////////////////////////////////////////////////////
/// Scale the object (take a 2D vector)
////////////////////////////////////////////////////////////
void Drawable::Scale(const Vector2f& Factor)
void Drawable::Scale(const Vector2f& factor)
{
Scale(Factor.x, Factor.y);
SetScale(myScale.x * factor.x, myScale.y * factor.y);
}
////////////////////////////////////////////////////////////
/// Rotate the object
////////////////////////////////////////////////////////////
void Drawable::Rotate(float Angle)
void Drawable::Rotate(float angle)
{
SetRotation(myRotation + Angle);
SetRotation(myRotation + angle);
}
@ -314,18 +312,18 @@ void Drawable::Rotate(float Angle)
/// Transform a point from global coordinates into local coordinates
/// (ie it applies the inverse of object's origin, translation, rotation and scale to the point)
////////////////////////////////////////////////////////////
sf::Vector2f Drawable::TransformToLocal(const sf::Vector2f& Point) const
sf::Vector2f Drawable::TransformToLocal(const sf::Vector2f& point) const
{
return GetInverseMatrix().Transform(Point);
return GetInverseMatrix().Transform(point);
}
////////////////////////////////////////////////////////////
/// Transform a point from local coordinates into global coordinates
/// (ie it applies the object's origin, translation, rotation and scale to the point)
////////////////////////////////////////////////////////////
sf::Vector2f Drawable::TransformToGlobal(const sf::Vector2f& Point) const
sf::Vector2f Drawable::TransformToGlobal(const sf::Vector2f& point) const
{
return GetMatrix().Transform(Point);
return GetMatrix().Transform(point);
}
@ -364,7 +362,7 @@ const Matrix3& Drawable::GetInverseMatrix() const
////////////////////////////////////////////////////////////
/// Draw the object into the specified window
////////////////////////////////////////////////////////////
void Drawable::Draw(RenderTarget& Target) const
void Drawable::Draw(RenderTarget& target) const
{
// Save the current modelview matrix and set the new one
GLCheck(glMatrixMode(GL_MODELVIEW));
@ -382,7 +380,7 @@ void Drawable::Draw(RenderTarget& Target) const
// We have to use glBlendFuncSeparate so that the resulting alpha is
// not alpha², which is incorrect and would cause problems when rendering
// alpha pixels to a RenderImage that would be in turn be rendered to another render target
// alpha pixels to a RenderImage that would be in turn rendered to another render target
switch (myBlendMode)
{
case Blend::Alpha :
@ -403,7 +401,7 @@ void Drawable::Draw(RenderTarget& Target) const
GLCheck(glColor4f(myColor.r / 255.f, myColor.g / 255.f, myColor.b / 255.f, myColor.a / 255.f));
// Let the derived class render the object geometry
Render(Target);
Render(target);
// Restore the previous modelview matrix
GLCheck(glMatrixMode(GL_MODELVIEW));

View file

@ -71,45 +71,45 @@ myCharSize(0)
////////////////////////////////////////////////////////////
/// Load the font from a file
////////////////////////////////////////////////////////////
bool Font::LoadFromFile(const std::string& Filename, unsigned int CharSize, const Unicode::Text& Charset)
bool Font::LoadFromFile(const std::string& filename, unsigned int charSize, const Unicode::Text& charset)
{
// Clear the previous character map
myGlyphs.clear();
// Always add these special characters
Unicode::UTF32String UTFCharset = Charset;
Unicode::UTF32String UTFCharset = charset;
if (UTFCharset.find(L' ') != Unicode::UTF32String::npos) UTFCharset += L' ';
if (UTFCharset.find(L'\n') != Unicode::UTF32String::npos) UTFCharset += L'\n';
if (UTFCharset.find(L'\v') != Unicode::UTF32String::npos) UTFCharset += L'\v';
if (UTFCharset.find(L'\t') != Unicode::UTF32String::npos) UTFCharset += L'\t';
return priv::FontLoader::GetInstance().LoadFontFromFile(Filename, CharSize, UTFCharset, *this);
return priv::FontLoader::GetInstance().LoadFontFromFile(filename, charSize, UTFCharset, *this);
}
////////////////////////////////////////////////////////////
/// Load the font from a file in memory
////////////////////////////////////////////////////////////
bool Font::LoadFromMemory(const char* Data, std::size_t SizeInBytes, unsigned int CharSize, const Unicode::Text& Charset)
bool Font::LoadFromMemory(const char* data, std::size_t sizeInBytes, unsigned int charSize, const Unicode::Text& charset)
{
// Clear the previous character map
myGlyphs.clear();
// Check parameters
if (!Data || (SizeInBytes == 0))
if (!data || (sizeInBytes == 0))
{
std::cerr << "Failed to load font from memory, no data provided" << std::endl;
return false;
}
// Always add these special characters
Unicode::UTF32String UTFCharset = Charset;
Unicode::UTF32String UTFCharset = charset;
if (UTFCharset.find(L' ') != Unicode::UTF32String::npos) UTFCharset += L' ';
if (UTFCharset.find(L'\n') != Unicode::UTF32String::npos) UTFCharset += L'\n';
if (UTFCharset.find(L'\v') != Unicode::UTF32String::npos) UTFCharset += L'\v';
if (UTFCharset.find(L'\t') != Unicode::UTF32String::npos) UTFCharset += L'\t';
return priv::FontLoader::GetInstance().LoadFontFromMemory(Data, SizeInBytes, CharSize, UTFCharset, *this);
return priv::FontLoader::GetInstance().LoadFontFromMemory(data, sizeInBytes, charSize, UTFCharset, *this);
}
@ -127,19 +127,19 @@ unsigned int Font::GetCharacterSize() const
/// Get the description of a glyph (character)
/// given by its unicode value
////////////////////////////////////////////////////////////
const Glyph& Font::GetGlyph(Uint32 CodePoint) const
const Glyph& Font::GetGlyph(Uint32 codePoint) const
{
std::map<Uint32, Glyph>::const_iterator It = myGlyphs.find(CodePoint);
if (It != myGlyphs.end())
std::map<Uint32, Glyph>::const_iterator it = myGlyphs.find(codePoint);
if (it != myGlyphs.end())
{
// Valid glyph
return It->second;
return it->second;
}
else
{
// Invalid glyph -- return an invalid glyph
static const Glyph InvalidGlyph;
return InvalidGlyph;
static const Glyph invalid;
return invalid;
}
}
@ -158,21 +158,21 @@ const Image& Font::GetImage() const
////////////////////////////////////////////////////////////
const Font& Font::GetDefaultFont()
{
static Font DefaultFont;
static bool DefaultFontLoaded = false;
static const char DefaultFontData[] =
static Font defaultFont;
static bool defaultFontLoaded = false;
static const char defaultFontData[] =
{
#include <SFML/Graphics/Arial.hpp>
};
// Load the default font on first call
if (!DefaultFontLoaded)
if (!defaultFontLoaded)
{
DefaultFont.LoadFromMemory(DefaultFontData, sizeof(DefaultFontData), 30);
DefaultFontLoaded = true;
defaultFont.LoadFromMemory(defaultFontData, sizeof(defaultFontData), 30);
defaultFontLoaded = true;
}
return DefaultFont;
return defaultFont;
}
} // namespace sf

View file

@ -44,9 +44,9 @@ namespace
////////////////////////////////////////////////////////////
struct SizeCompare
{
bool operator ()(FT_BitmapGlyph Glyph1, FT_BitmapGlyph Glyph2) const
bool operator ()(FT_BitmapGlyph left, FT_BitmapGlyph right) const
{
return Glyph2->bitmap.rows < Glyph1->bitmap.rows;
return left->bitmap.rows < right->bitmap.rows;
}
};
}
@ -60,9 +60,9 @@ namespace priv
////////////////////////////////////////////////////////////
FontLoader& FontLoader::GetInstance()
{
static FontLoader Instance;
static FontLoader instance;
return Instance;
return instance;
}
@ -72,10 +72,10 @@ FontLoader& FontLoader::GetInstance()
FontLoader::FontLoader()
{
// Initialize FreeType library
FT_Error Error = FT_Init_FreeType(&myLibrary);
if (Error)
FT_Error error = FT_Init_FreeType(&myLibrary);
if (error)
{
std::cerr << "Failed to initialize FreeType library (error code : " << Error << ")" << std::endl;
std::cerr << "Failed to initialize FreeType library (error code : " << error << ")" << std::endl;
return;
}
}
@ -95,40 +95,40 @@ FontLoader::~FontLoader()
////////////////////////////////////////////////////////////
/// Load a font from a file
////////////////////////////////////////////////////////////
bool FontLoader::LoadFontFromFile(const std::string& Filename, unsigned int CharSize, const Unicode::UTF32String& Charset, Font& LoadedFont)
bool FontLoader::LoadFontFromFile(const std::string& filename, unsigned int charSize, const Unicode::UTF32String& charset, Font& font)
{
// Check if Freetype is correctly initialized
if (!myLibrary)
{
std::cerr << "Failed to load font \"" << Filename << "\", FreeType has not been initialized" << std::endl;
std::cerr << "Failed to load font \"" << filename << "\", FreeType has not been initialized" << std::endl;
return false;
}
// Create a new font face from the specified file
FT_Face FontFace;
FT_Error Error = FT_New_Face(myLibrary, Filename.c_str(), 0, &FontFace);
if (Error)
FT_Face face;
FT_Error error = FT_New_Face(myLibrary, filename.c_str(), 0, &face);
if (error)
{
std::cerr << "Failed to load font \"" << Filename << "\" (" << GetErrorDesc(Error) << ")" << std::endl;
std::cerr << "Failed to load font \"" << filename << "\" (" << GetErrorDesc(error) << ")" << std::endl;
return false;
}
// Create the bitmap font
Error = CreateBitmapFont(FontFace, CharSize, Charset, LoadedFont);
if (Error)
std::cerr << "Failed to load font \"" << Filename << "\" (" << GetErrorDesc(Error) << ")" << std::endl;
error = CreateBitmapFont(face, charSize, charset, font);
if (error)
std::cerr << "Failed to load font \"" << filename << "\" (" << GetErrorDesc(error) << ")" << std::endl;
// Delete the font
FT_Done_Face(FontFace);
FT_Done_Face(face);
return Error == 0;
return error == 0;
}
////////////////////////////////////////////////////////////
/// Load the font from a file in memory
////////////////////////////////////////////////////////////
bool FontLoader::LoadFontFromMemory(const char* Data, std::size_t SizeInBytes, unsigned int CharSize, const Unicode::UTF32String& Charset, Font& LoadedFont)
bool FontLoader::LoadFontFromMemory(const char* data, std::size_t sizeInBytes, unsigned int charSize, const Unicode::UTF32String& charset, Font& font)
{
// Check if Freetype is correctly initialized
if (!myLibrary)
@ -138,163 +138,163 @@ bool FontLoader::LoadFontFromMemory(const char* Data, std::size_t SizeInBytes, u
}
// Create a new font face from the specified memory data
FT_Face FontFace;
FT_Error Error = FT_New_Memory_Face(myLibrary, reinterpret_cast<const FT_Byte*>(Data), static_cast<FT_Long>(SizeInBytes), 0, &FontFace);
if (Error)
FT_Face face;
FT_Error error = FT_New_Memory_Face(myLibrary, reinterpret_cast<const FT_Byte*>(data), static_cast<FT_Long>(sizeInBytes), 0, &face);
if (error)
{
std::cerr << "Failed to load font from memory (" << GetErrorDesc(Error) << ")" << std::endl;
std::cerr << "Failed to load font from memory (" << GetErrorDesc(error) << ")" << std::endl;
return false;
}
// Create the bitmap font
Error = CreateBitmapFont(FontFace, CharSize, Charset, LoadedFont);
if (Error)
std::cerr << "Failed to load font from memory (" << GetErrorDesc(Error) << ")" << std::endl;
error = CreateBitmapFont(face, charSize, charset, font);
if (error)
std::cerr << "Failed to load font from memory (" << GetErrorDesc(error) << ")" << std::endl;
// Delete the font
FT_Done_Face(FontFace);
FT_Done_Face(face);
return Error == 0;
return error == 0;
}
////////////////////////////////////////////////////////////
/// Create a bitmap font from a font face and a characters set
////////////////////////////////////////////////////////////
FT_Error FontLoader::CreateBitmapFont(FT_Face FontFace, unsigned int CharSize, const Unicode::UTF32String& Charset, Font& LoadedFont)
FT_Error FontLoader::CreateBitmapFont(FT_Face face, unsigned int charSize, const Unicode::UTF32String& charset, Font& font)
{
// Let's find how many characters to put in each row to make them fit into a squared texture
GLint MaxSize;
GLCheck(glGetIntegerv(GL_MAX_TEXTURE_SIZE, &MaxSize));
int NbChars = static_cast<int>(sqrt(static_cast<double>(Charset.length())) * 0.75);
GLint maxSize;
GLCheck(glGetIntegerv(GL_MAX_TEXTURE_SIZE, &maxSize));
int nbChars = static_cast<int>(sqrt(static_cast<double>(charset.length())) * 0.75);
// Clamp the character size to make sure we won't create a texture too big
if (NbChars * CharSize >= static_cast<unsigned int>(MaxSize))
CharSize = MaxSize / NbChars;
if (nbChars * charSize >= static_cast<unsigned int>(maxSize))
charSize = maxSize / nbChars;
// Initialize the dimensions
unsigned int Left = 0;
unsigned int Top = 0;
unsigned int TexWidth = Image::GetValidTextureSize(CharSize * NbChars);
unsigned int TexHeight = CharSize * NbChars;
std::vector<unsigned int> Tops(TexWidth, 0);
unsigned int left = 0;
unsigned int top = 0;
unsigned int texWidth = Image::GetValidTextureSize(charSize * nbChars);
unsigned int texHeight = charSize * nbChars;
std::vector<unsigned int> tops(texWidth, 0);
// Create a pixel buffer for rendering every glyph
std::vector<Uint8> GlyphsBuffer(TexWidth * TexHeight * 4);
std::vector<Uint8> glyphsBuffer(texWidth * texHeight * 4);
// Setup the font size
FT_Error Error = FT_Set_Pixel_Sizes(FontFace, CharSize, CharSize);
if (Error)
return Error;
FT_Error error = FT_Set_Pixel_Sizes(face, charSize, charSize);
if (error)
return error;
// Select the unicode character map
Error = FT_Select_Charmap(FontFace, FT_ENCODING_UNICODE);
if (Error)
return Error;
error = FT_Select_Charmap(face, FT_ENCODING_UNICODE);
if (error)
return error;
// Render all glyphs and sort them by size to optimize texture space
typedef std::multimap<FT_BitmapGlyph, Uint32, SizeCompare> GlyphTable;
GlyphTable Glyphs;
for (std::size_t i = 0; i < Charset.length(); ++i)
GlyphTable glyphs;
for (std::size_t i = 0; i < charset.length(); ++i)
{
// Load the glyph corresponding to the current character
Error = FT_Load_Char(FontFace, Charset[i], FT_LOAD_TARGET_NORMAL);
if (Error)
return Error;
error = FT_Load_Char(face, charset[i], FT_LOAD_TARGET_NORMAL);
if (error)
return error;
// Convert the glyph to a bitmap (ie. rasterize it)
FT_Glyph Glyph;
Error = FT_Get_Glyph(FontFace->glyph, &Glyph);
if (Error)
return Error;
FT_Glyph_To_Bitmap(&Glyph, FT_RENDER_MODE_NORMAL, 0, 1);
FT_BitmapGlyph BitmapGlyph = (FT_BitmapGlyph)Glyph;
FT_Glyph glyph;
error = FT_Get_Glyph(face->glyph, &glyph);
if (error)
return error;
FT_Glyph_To_Bitmap(&glyph, FT_RENDER_MODE_NORMAL, 0, 1);
FT_BitmapGlyph bitmapGlyph = (FT_BitmapGlyph)glyph;
// Should we handle other pixel modes ?
if (BitmapGlyph->bitmap.pixel_mode != FT_PIXEL_MODE_GRAY)
if (bitmapGlyph->bitmap.pixel_mode != FT_PIXEL_MODE_GRAY)
return FT_Err_Cannot_Render_Glyph;
// Add it to the sorted table of glyphs
Glyphs.insert(std::make_pair(BitmapGlyph, Charset[i]));
glyphs.insert(std::make_pair(bitmapGlyph, charset[i]));
}
// Copy the rendered glyphs into the texture
unsigned int MaxHeight = 0;
std::map<Uint32, IntRect> Coords;
for (GlyphTable::const_iterator i = Glyphs.begin(); i != Glyphs.end(); ++i)
unsigned int maxHeight = 0;
std::map<Uint32, IntRect> coords;
for (GlyphTable::const_iterator i = glyphs.begin(); i != glyphs.end(); ++i)
{
// Get the bitmap of the current glyph
Glyph& CurGlyph = LoadedFont.myGlyphs[i->second];
FT_BitmapGlyph BitmapGlyph = i->first;
FT_Bitmap& Bitmap = BitmapGlyph->bitmap;
Glyph& curGlyph = font.myGlyphs[i->second];
FT_BitmapGlyph bitmapGlyph = i->first;
FT_Bitmap& bitmap = bitmapGlyph->bitmap;
// Make sure we don't go over the texture width
if (Left + Bitmap.width + 1 >= TexWidth)
Left = 0;
if (left + bitmap.width + 1 >= texWidth)
left = 0;
// Compute the top coordinate
Top = Tops[Left];
for (int x = 0; x < Bitmap.width + 1; ++x)
Top = std::max(Top, Tops[Left + x]);
Top++;
top = tops[left];
for (int x = 0; x < bitmap.width + 1; ++x)
top = std::max(top, tops[left + x]);
top++;
// Make sure we don't go over the texture height -- resize it if we need more space
if (Top + Bitmap.rows + 1 >= TexHeight)
if (top + bitmap.rows + 1 >= texHeight)
{
TexHeight *= 2;
GlyphsBuffer.resize(TexWidth * TexHeight * 4);
texHeight *= 2;
glyphsBuffer.resize(texWidth * texHeight * 4);
}
// Store the character's position and size
CurGlyph.Rectangle.Left = BitmapGlyph->left;
CurGlyph.Rectangle.Top = -BitmapGlyph->top;
CurGlyph.Rectangle.Right = CurGlyph.Rectangle.Left + Bitmap.width;
CurGlyph.Rectangle.Bottom = Bitmap.rows - BitmapGlyph->top;
CurGlyph.Advance = BitmapGlyph->root.advance.x >> 16;
curGlyph.Rectangle.Left = bitmapGlyph->left;
curGlyph.Rectangle.Top = -bitmapGlyph->top;
curGlyph.Rectangle.Right = curGlyph.Rectangle.Left + bitmap.width;
curGlyph.Rectangle.Bottom = bitmap.rows - bitmapGlyph->top;
curGlyph.Advance = bitmapGlyph->root.advance.x >> 16;
// Texture size may change, so let the texture coordinates be calculated later
Coords[i->second] = IntRect(Left + 1, Top + 1, Left + Bitmap.width + 1, Top + Bitmap.rows + 1);
coords[i->second] = IntRect(left + 1, top + 1, left + bitmap.width + 1, top + bitmap.rows + 1);
// Draw the glyph into our bitmap font
const Uint8* Pixels = Bitmap.buffer;
for (int y = 0; y < Bitmap.rows; ++y)
const Uint8* pixels = bitmap.buffer;
for (int y = 0; y < bitmap.rows; ++y)
{
for (int x = 0; x < Bitmap.width; ++x)
for (int x = 0; x < bitmap.width; ++x)
{
std::size_t Index = x + Left + 1 + (y + Top + 1) * TexWidth;
GlyphsBuffer[Index * 4 + 0] = 255;
GlyphsBuffer[Index * 4 + 1] = 255;
GlyphsBuffer[Index * 4 + 2] = 255;
GlyphsBuffer[Index * 4 + 3] = Pixels[x];
std::size_t index = x + left + 1 + (y + top + 1) * texWidth;
glyphsBuffer[index * 4 + 0] = 255;
glyphsBuffer[index * 4 + 1] = 255;
glyphsBuffer[index * 4 + 2] = 255;
glyphsBuffer[index * 4 + 3] = pixels[x];
}
Pixels += Bitmap.pitch;
pixels += bitmap.pitch;
}
// Update the rendering coordinates
for (int x = 0; x < Bitmap.width + 1; ++x)
Tops[Left + x] = Top + Bitmap.rows;
Left += Bitmap.width + 1;
if (Top + Bitmap.rows > MaxHeight)
MaxHeight = Top + Bitmap.rows;
for (int x = 0; x < bitmap.width + 1; ++x)
tops[left + x] = top + bitmap.rows;
left += bitmap.width + 1;
if (top + bitmap.rows > maxHeight)
maxHeight = top + bitmap.rows;
// Delete the glyph
FT_Done_Glyph((FT_Glyph)BitmapGlyph);
FT_Done_Glyph((FT_Glyph)bitmapGlyph);
}
// Create the font's texture
TexHeight = MaxHeight + 1;
GlyphsBuffer.resize(TexWidth * TexHeight * 4);
LoadedFont.myTexture.LoadFromPixels(TexWidth, TexHeight, &GlyphsBuffer[0]);
texHeight = maxHeight + 1;
glyphsBuffer.resize(texWidth * texHeight * 4);
font.myTexture.LoadFromPixels(texWidth, texHeight, &glyphsBuffer[0]);
// Now that the texture is created, we can precompute texture coordinates
for (std::size_t i = 0; i < Charset.size(); ++i)
for (std::size_t i = 0; i < charset.size(); ++i)
{
Uint32 CurChar = Charset[i];
LoadedFont.myGlyphs[CurChar].TexCoords = LoadedFont.myTexture.GetTexCoords(Coords[CurChar], false);
Uint32 curChar = charset[i];
font.myGlyphs[curChar].TexCoords = font.myTexture.GetTexCoords(coords[curChar], false);
}
// Update the character size (it may have been changed by the function)
LoadedFont.myCharSize = CharSize;
font.myCharSize = charSize;
return 0;
}
@ -303,9 +303,9 @@ FT_Error FontLoader::CreateBitmapFont(FT_Face FontFace, unsigned int CharSize, c
////////////////////////////////////////////////////////////
/// Get a description from a FT error code
////////////////////////////////////////////////////////////
std::string FontLoader::GetErrorDesc(FT_Error Error)
std::string FontLoader::GetErrorDesc(FT_Error error)
{
switch (Error)
switch (error)
{
// Generic errors
case FT_Err_Cannot_Open_Resource : return "cannot open resource";

View file

@ -59,29 +59,29 @@ public :
////////////////////////////////////////////////////////////
/// Load a font from a file
///
/// \param Filename : Path of the font file to load
/// \param CharSize : Size of characters in bitmap - the bigger, the higher quality
/// \param Charset : Characters set to generate
/// \param LoadedFont : Font object to fill up
/// \param filename : Path of the font file to load
/// \param charSize : Size of characters in bitmap - the bigger, the higher quality
/// \param charset : Characters set to generate
/// \param font : Font object to fill up
///
/// \return True if loading was successful
///
////////////////////////////////////////////////////////////
bool LoadFontFromFile(const std::string& Filename, unsigned int CharSize, const Unicode::UTF32String& Charset, Font& LoadedFont);
bool LoadFontFromFile(const std::string& filename, unsigned int charSize, const Unicode::UTF32String& charset, Font& font);
////////////////////////////////////////////////////////////
/// Load the font from a file in memory
///
/// \param Data : Pointer to the data to load
/// \param SizeInBytes : Size of the data, in bytes
/// \param CharSize : Size of characters in bitmap - the bigger, the higher quality
/// \param Charset : Characters set to generate
/// \param LoadedFont : Font object to fill up
/// \param data : Pointer to the data to load
/// \param sizeInBytes : Size of the data, in bytes
/// \param charSize : Size of characters in bitmap - the bigger, the higher quality
/// \param charset : Characters set to generate
/// \param font : Font object to fill up
///
/// \return True if loading was successful
///
////////////////////////////////////////////////////////////
bool LoadFontFromMemory(const char* Data, std::size_t SizeInBytes, unsigned int CharSize, const Unicode::UTF32String& Charset, Font& LoadedFont);
bool LoadFontFromMemory(const char* data, std::size_t sizeInBytes, unsigned int charSize, const Unicode::UTF32String& charset, Font& font);
private :
@ -100,23 +100,23 @@ private :
////////////////////////////////////////////////////////////
/// Create a bitmap font from a font face and a characters set
///
/// \param FontFace : Font face containing the loaded font
/// \param CharSize : Size of characters in bitmap
/// \param Charset : Characters set to generate
/// \param LoadedFont : Font object to fill up
/// \param face : Font face containing the loaded font
/// \param charSize : Size of characters in bitmap
/// \param charset : Characters set to generate
/// \param font : Font object to fill up
///
////////////////////////////////////////////////////////////
FT_Error CreateBitmapFont(FT_Face FontFace, unsigned int CharSize, const Unicode::UTF32String& Charset, Font& LoadedFont);
FT_Error CreateBitmapFont(FT_Face face, unsigned int charSize, const Unicode::UTF32String& charset, Font& font);
////////////////////////////////////////////////////////////
/// Get a description from a FT error code
///
/// \param Error : FreeType error code
/// \param error : FreeType error code
///
/// \return Error description
///
////////////////////////////////////////////////////////////
static std::string GetErrorDesc(FT_Error Error);
static std::string GetErrorDesc(FT_Error error);
////////////////////////////////////////////////////////////
// Member data

View file

@ -34,73 +34,73 @@ namespace sf
////////////////////////////////////////////////////////////
/// Check the last OpenGL error
////////////////////////////////////////////////////////////
void GLCheckError(const std::string& File, unsigned int Line)
void GLCheckError(const std::string& file, unsigned int line)
{
// Get the last error
GLenum ErrorCode = glGetError();
GLenum errorCode = glGetError();
if (ErrorCode != GL_NO_ERROR)
if (errorCode != GL_NO_ERROR)
{
std::string Error = "unknown error";
std::string Desc = "no description";
std::string error = "unknown error";
std::string description = "no description";
// Decode the error code
switch (ErrorCode)
switch (errorCode)
{
case GL_INVALID_ENUM :
{
Error = "GL_INVALID_ENUM";
Desc = "an unacceptable value has been specified for an enumerated argument";
error = "GL_INVALID_ENUM";
description = "an unacceptable value has been specified for an enumerated argument";
break;
}
case GL_INVALID_VALUE :
{
Error = "GL_INVALID_VALUE";
Desc = "a numeric argument is out of range";
error = "GL_INVALID_VALUE";
description = "a numeric argument is out of range";
break;
}
case GL_INVALID_OPERATION :
{
Error = "GL_INVALID_OPERATION";
Desc = "the specified operation is not allowed in the current state";
error = "GL_INVALID_OPERATION";
description = "the specified operation is not allowed in the current state";
break;
}
case GL_STACK_OVERFLOW :
{
Error = "GL_STACK_OVERFLOW";
Desc = "this command would cause a stack overflow";
error = "GL_STACK_OVERFLOW";
description = "this command would cause a stack overflow";
break;
}
case GL_STACK_UNDERFLOW :
{
Error = "GL_STACK_UNDERFLOW";
Desc = "this command would cause a stack underflow";
error = "GL_STACK_UNDERFLOW";
description = "this command would cause a stack underflow";
break;
}
case GL_OUT_OF_MEMORY :
{
Error = "GL_OUT_OF_MEMORY";
Desc = "there is not enough memory left to execute the command";
error = "GL_OUT_OF_MEMORY";
description = "there is not enough memory left to execute the command";
break;
}
case GL_INVALID_FRAMEBUFFER_OPERATION_EXT :
{
Error = "GL_INVALID_FRAMEBUFFER_OPERATION_EXT";
Desc = "the object bound to FRAMEBUFFER_BINDING_EXT is not \"framebuffer complete\"";
error = "GL_INVALID_FRAMEBUFFER_OPERATION_EXT";
description = "the object bound to FRAMEBUFFER_BINDING_EXT is not \"framebuffer complete\"";
break;
}
}
// Log the error
std::cerr << "An internal OpenGL call failed in "
<< File.substr(File.find_last_of("\\/") + 1) << " (" << Line << ") : "
<< Error << ", " << Desc
<< file.substr(file.find_last_of("\\/") + 1) << " (" << line << ") : "
<< error << ", " << description
<< std::endl;
}
}
@ -111,11 +111,11 @@ void GLCheckError(const std::string& File, unsigned int Line)
////////////////////////////////////////////////////////////
void EnsureGlewInit()
{
static bool Initialized = false;
if (!Initialized)
static bool initialized = false;
if (!initialized)
{
glewInit();
Initialized = true;
initialized = true;
}
}

View file

@ -42,12 +42,12 @@ namespace sf
#ifdef SFML_DEBUG
// In debug mode, perform a test on every OpenGL call
#define GLCheck(Func) ((Func), GLCheckError(__FILE__, __LINE__))
#define GLCheck(call) ((call), GLCheckError(__FILE__, __LINE__))
#else
// Else, we don't add any overhead
#define GLCheck(Func) (Func)
#define GLCheck(call) (call)
#endif
@ -55,11 +55,11 @@ namespace sf
////////////////////////////////////////////////////////////
/// Check the last OpenGL error
///
/// \param File Source file where the call is located
/// \param Line Line number of the source file where the call is located
/// \param file : Source file where the call is located
/// \param line : Line number of the source file where the call is located
///
////////////////////////////////////////////////////////////
void GLCheckError(const std::string& File, unsigned int Line);
void GLCheckError(const std::string& file, unsigned int line);
////////////////////////////////////////////////////////////
/// Make sure that GLEW is initialized

View file

@ -60,19 +60,19 @@ myPixelsFlipped (false)
////////////////////////////////////////////////////////////
/// Copy constructor
////////////////////////////////////////////////////////////
Image::Image(const Image& Copy) :
Resource<Image> (Copy),
myWidth (Copy.myWidth),
myHeight (Copy.myHeight),
myTextureWidth (Copy.myTextureWidth),
myTextureHeight (Copy.myTextureHeight),
Image::Image(const Image& copy) :
Resource<Image> (copy),
myWidth (copy.myWidth),
myHeight (copy.myHeight),
myTextureWidth (copy.myTextureWidth),
myTextureHeight (copy.myTextureHeight),
myTexture (0),
myIsSmooth (Copy.myIsSmooth),
myPixels (Copy.myPixels),
myIsSmooth (copy.myIsSmooth),
myPixels (copy.myPixels),
myNeedTextureUpdate(false),
myNeedArrayUpdate (false),
myUpdateSource (Copy.myUpdateSource),
myPixelsFlipped (Copy.myPixelsFlipped)
myUpdateSource (copy.myUpdateSource),
myPixelsFlipped (copy.myPixelsFlipped)
{
CreateTexture();
}
@ -81,7 +81,7 @@ myPixelsFlipped (Copy.myPixelsFlipped)
////////////////////////////////////////////////////////////
/// Construct an empty image
////////////////////////////////////////////////////////////
Image::Image(unsigned int Width, unsigned int Height, const Color& Col) :
Image::Image(unsigned int width, unsigned int height, const Color& color) :
myWidth (0),
myHeight (0),
myTextureWidth (0),
@ -93,14 +93,14 @@ myNeedArrayUpdate (false),
myUpdateSource (NULL),
myPixelsFlipped (false)
{
Create(Width, Height, Col);
Create(width, height, color);
}
////////////////////////////////////////////////////////////
/// Construct the image from pixels in memory
////////////////////////////////////////////////////////////
Image::Image(unsigned int Width, unsigned int Height, const Uint8* Data) :
Image::Image(unsigned int width, unsigned int height, const Uint8* data) :
myWidth (0),
myHeight (0),
myTextureWidth (0),
@ -112,7 +112,7 @@ myNeedArrayUpdate (false),
myUpdateSource (NULL),
myPixelsFlipped (false)
{
LoadFromPixels(Width, Height, Data);
LoadFromPixels(width, height, data);
}
@ -129,12 +129,12 @@ Image::~Image()
////////////////////////////////////////////////////////////
/// Load the image from a file
////////////////////////////////////////////////////////////
bool Image::LoadFromFile(const std::string& Filename)
bool Image::LoadFromFile(const std::string& filename)
{
// Let the image loader load the image into our pixel array
bool Success = priv::ImageLoader::GetInstance().LoadImageFromFile(Filename, myPixels, myWidth, myHeight);
bool success = priv::ImageLoader::GetInstance().LoadImageFromFile(filename, myPixels, myWidth, myHeight);
if (Success)
if (success)
{
// Loading succeeded : we can create the texture
if (CreateTexture())
@ -151,19 +151,19 @@ bool Image::LoadFromFile(const std::string& Filename)
////////////////////////////////////////////////////////////
/// Load the image from a file in memory
////////////////////////////////////////////////////////////
bool Image::LoadFromMemory(const char* Data, std::size_t SizeInBytes)
bool Image::LoadFromMemory(const char* data, std::size_t sizeInBytes)
{
// Check parameters
if (!Data || (SizeInBytes == 0))
if (!data || (sizeInBytes == 0))
{
std::cerr << "Failed to image font from memory, no data provided" << std::endl;
return false;
}
// Let the image loader load the image into our pixel array
bool Success = priv::ImageLoader::GetInstance().LoadImageFromMemory(Data, SizeInBytes, myPixels, myWidth, myHeight);
bool success = priv::ImageLoader::GetInstance().LoadImageFromMemory(data, sizeInBytes, myPixels, myWidth, myHeight);
if (Success)
if (success)
{
// Loading succeeded : we can create the texture
if (CreateTexture())
@ -180,17 +180,17 @@ bool Image::LoadFromMemory(const char* Data, std::size_t SizeInBytes)
////////////////////////////////////////////////////////////
/// Load the image directly from an array of pixels
////////////////////////////////////////////////////////////
bool Image::LoadFromPixels(unsigned int Width, unsigned int Height, const Uint8* Data)
bool Image::LoadFromPixels(unsigned int width, unsigned int height, const Uint8* data)
{
if (Data)
if (data)
{
// Store the texture dimensions
myWidth = Width;
myHeight = Height;
myWidth = width;
myHeight = height;
// Fill the pixel buffer with the specified raw data
const Color* Ptr = reinterpret_cast<const Color*>(Data);
myPixels.assign(Ptr, Ptr + Width * Height);
const Color* ptr = reinterpret_cast<const Color*>(data);
myPixels.assign(ptr, ptr + width * height);
// We can create the texture
if (CreateTexture())
@ -207,7 +207,7 @@ bool Image::LoadFromPixels(unsigned int Width, unsigned int Height, const Uint8*
else
{
// No data provided : create a white image
return Create(Width, Height, Color(255, 255, 255, 255));
return Create(width, height, Color(255, 255, 255));
}
}
@ -215,28 +215,28 @@ bool Image::LoadFromPixels(unsigned int Width, unsigned int Height, const Uint8*
////////////////////////////////////////////////////////////
/// Save the content of the image to a file
////////////////////////////////////////////////////////////
bool Image::SaveToFile(const std::string& Filename) const
bool Image::SaveToFile(const std::string& filename) const
{
// Check if the array of pixels needs to be updated
const_cast<Image*>(this)->EnsureArrayUpdate();
// Let the image loader save our pixel array into the image
return priv::ImageLoader::GetInstance().SaveImageToFile(Filename, myPixels, myWidth, myHeight);
return priv::ImageLoader::GetInstance().SaveImageToFile(filename, myPixels, myWidth, myHeight);
}
////////////////////////////////////////////////////////////
/// Create an empty image
////////////////////////////////////////////////////////////
bool Image::Create(unsigned int Width, unsigned int Height, Color Col)
bool Image::Create(unsigned int width, unsigned int height, const Color& color)
{
// Store the texture dimensions
myWidth = Width;
myHeight = Height;
myWidth = width;
myHeight = height;
// Recreate the pixel buffer and fill it with the specified color
myPixels.clear();
myPixels.resize(Width * Height, Col);
myPixels.resize(width * height, color);
// We can create the texture
if (CreateTexture())
@ -255,16 +255,16 @@ bool Image::Create(unsigned int Width, unsigned int Height, Color Col)
////////////////////////////////////////////////////////////
/// Create transparency mask from a specified colorkey
////////////////////////////////////////////////////////////
void Image::CreateMaskFromColor(Color ColorKey, Uint8 Alpha)
void Image::CreateMaskFromColor(const Color& transparentColor, Uint8 alpha)
{
// Check if the array of pixels needs to be updated
EnsureArrayUpdate();
// Calculate the new color (old color with no alpha)
Color NewColor(ColorKey.r, ColorKey.g, ColorKey.b, Alpha);
Color newColor(transparentColor.r, transparentColor.g, transparentColor.b, alpha);
// Replace the old color by the new one
std::replace(myPixels.begin(), myPixels.end(), ColorKey, NewColor);
// Replace the old color with the new one
std::replace(myPixels.begin(), myPixels.end(), transparentColor, newColor);
// The texture will need to be updated
myNeedTextureUpdate = true;
@ -276,82 +276,82 @@ void Image::CreateMaskFromColor(Color ColorKey, Uint8 Alpha)
/// This function does a slow pixel copy and should only
/// be used at initialization time
////////////////////////////////////////////////////////////
void Image::Copy(const Image& Source, unsigned int DestX, unsigned int DestY, const IntRect& SourceRect, bool ApplyAlpha)
void Image::Copy(const Image& source, unsigned int destX, unsigned int destY, const IntRect& sourceRect, bool applyAlpha)
{
// Make sure both images are valid
if ((Source.myWidth == 0) || (Source.myHeight == 0) || (myWidth == 0) || (myHeight == 0))
if ((source.myWidth == 0) || (source.myHeight == 0) || (myWidth == 0) || (myHeight == 0))
return;
// Make sure both images have up-to-date arrays
EnsureArrayUpdate();
const_cast<Image&>(Source).EnsureArrayUpdate();
const_cast<Image&>(source).EnsureArrayUpdate();
// Adjust the source rectangle
IntRect SrcRect = SourceRect;
if (SrcRect.GetSize().x == 0 || (SrcRect.GetSize().y == 0))
IntRect srcRect = sourceRect;
if (srcRect.GetSize().x == 0 || (srcRect.GetSize().y == 0))
{
SrcRect.Left = 0;
SrcRect.Top = 0;
SrcRect.Right = Source.myWidth;
SrcRect.Bottom = Source.myHeight;
srcRect.Left = 0;
srcRect.Top = 0;
srcRect.Right = source.myWidth;
srcRect.Bottom = source.myHeight;
}
else
{
if (SrcRect.Left < 0) SrcRect.Left = 0;
if (SrcRect.Top < 0) SrcRect.Top = 0;
if (SrcRect.Right > static_cast<int>(Source.myWidth)) SrcRect.Right = Source.myWidth;
if (SrcRect.Bottom > static_cast<int>(Source.myHeight)) SrcRect.Bottom = Source.myHeight;
if (srcRect.Left < 0) srcRect.Left = 0;
if (srcRect.Top < 0) srcRect.Top = 0;
if (srcRect.Right > static_cast<int>(source.myWidth)) srcRect.Right = source.myWidth;
if (srcRect.Bottom > static_cast<int>(source.myHeight)) srcRect.Bottom = source.myHeight;
}
// Then find the valid bounds of the destination rectangle
int Width = SrcRect.GetSize().x;
int Height = SrcRect.GetSize().y;
if (DestX + Width > myWidth) Width = myWidth - DestX;
if (DestY + Height > myHeight) Height = myHeight - DestY;
int width = srcRect.GetSize().x;
int height = srcRect.GetSize().y;
if (destX + width > myWidth) width = myWidth - destX;
if (destY + height > myHeight) height = myHeight - destY;
// Make sure the destination area is valid
if ((Width <= 0) || (Height <= 0))
if ((width <= 0) || (height <= 0))
return;
// Precompute as much as possible
int Pitch = Width * 4;
int Rows = Height;
int SrcStride = Source.myWidth * 4;
int DstStride = myWidth * 4;
const Uint8* SrcPixels = Source.GetPixelsPtr() + (SrcRect.Left + SrcRect.Top * Source.myWidth) * 4;
Uint8* DstPixels = reinterpret_cast<Uint8*>(&myPixels[0]) + (DestX + DestY * myWidth) * 4;
int pitch = width * 4;
int rows = height;
int srcStride = source.myWidth * 4;
int dstStride = myWidth * 4;
const Uint8* srcPixels = source.GetPixelsPtr() + (srcRect.Left + srcRect.Top * source.myWidth) * 4;
Uint8* dstPixels = reinterpret_cast<Uint8*>(&myPixels[0]) + (destX + destY * myWidth) * 4;
// Copy the pixels
if (ApplyAlpha)
if (applyAlpha)
{
// Interpolation using alpha values, pixel by pixel (slower)
for (int i = 0; i < Rows; ++i)
for (int i = 0; i < rows; ++i)
{
for (int j = 0; j < Width; ++j)
for (int j = 0; j < width; ++j)
{
// Get a direct pointer to the components of the current pixel
const Uint8* Src = SrcPixels + j * 4;
Uint8* Dst = DstPixels + j * 4;
const Uint8* src = srcPixels + j * 4;
Uint8* dst = dstPixels + j * 4;
// Interpolate RGB components using the alpha value of the source pixel
Uint8 Alpha = Src[3];
Dst[0] = (Src[0] * Alpha + Dst[0] * (255 - Alpha)) / 255;
Dst[1] = (Src[1] * Alpha + Dst[1] * (255 - Alpha)) / 255;
Dst[2] = (Src[2] * Alpha + Dst[2] * (255 - Alpha)) / 255;
Uint8 alpha = src[3];
dst[0] = (src[0] * alpha + dst[0] * (255 - alpha)) / 255;
dst[1] = (src[1] * alpha + dst[1] * (255 - alpha)) / 255;
dst[2] = (src[2] * alpha + dst[2] * (255 - alpha)) / 255;
}
SrcPixels += SrcStride;
DstPixels += DstStride;
srcPixels += srcStride;
dstPixels += dstStride;
}
}
else
{
// Optimized copy ignoring alpha values, row by row (faster)
for (int i = 0; i < Rows; ++i)
for (int i = 0; i < rows; ++i)
{
memcpy(DstPixels, SrcPixels, Pitch);
SrcPixels += SrcStride;
DstPixels += DstStride;
memcpy(dstPixels, srcPixels, pitch);
srcPixels += srcStride;
dstPixels += dstStride;
}
}
@ -364,39 +364,39 @@ void Image::Copy(const Image& Source, unsigned int DestX, unsigned int DestY, co
/// Create the image from the current contents of the
/// given window
////////////////////////////////////////////////////////////
bool Image::CopyScreen(RenderWindow& Window, const IntRect& SourceRect)
bool Image::CopyScreen(RenderWindow& window, const IntRect& sourceRect)
{
// Adjust the source rectangle
IntRect SrcRect = SourceRect;
if (SrcRect.GetSize().x == 0 || (SrcRect.GetSize().y == 0))
IntRect srcRect = sourceRect;
if (srcRect.GetSize().x == 0 || (srcRect.GetSize().y == 0))
{
SrcRect.Left = 0;
SrcRect.Top = 0;
SrcRect.Right = Window.GetWidth();
SrcRect.Bottom = Window.GetHeight();
srcRect.Left = 0;
srcRect.Top = 0;
srcRect.Right = window.GetWidth();
srcRect.Bottom = window.GetHeight();
}
else
{
if (SrcRect.Left < 0) SrcRect.Left = 0;
if (SrcRect.Top < 0) SrcRect.Top = 0;
if (SrcRect.Right > static_cast<int>(Window.GetWidth())) SrcRect.Right = Window.GetWidth();
if (SrcRect.Bottom > static_cast<int>(Window.GetHeight())) SrcRect.Bottom = Window.GetHeight();
if (srcRect.Left < 0) srcRect.Left = 0;
if (srcRect.Top < 0) srcRect.Top = 0;
if (srcRect.Right > static_cast<int>(window.GetWidth())) srcRect.Right = window.GetWidth();
if (srcRect.Bottom > static_cast<int>(window.GetHeight())) srcRect.Bottom = window.GetHeight();
}
// Store the texture dimensions
myWidth = SrcRect.GetSize().x;
myHeight = SrcRect.GetSize().y;
myWidth = srcRect.GetSize().x;
myHeight = srcRect.GetSize().y;
// We can then create the texture
if (Window.SetActive() && CreateTexture())
if (window.SetActive() && CreateTexture())
{
GLint PreviousTexture;
GLCheck(glGetIntegerv(GL_TEXTURE_BINDING_2D, &PreviousTexture));
GLint previous;
GLCheck(glGetIntegerv(GL_TEXTURE_BINDING_2D, &previous));
GLCheck(glBindTexture(GL_TEXTURE_2D, myTexture));
GLCheck(glCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, SrcRect.Left, SrcRect.Top, myWidth, myHeight));
GLCheck(glCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, srcRect.Left, srcRect.Top, myWidth, myHeight));
GLCheck(glBindTexture(GL_TEXTURE_2D, PreviousTexture));
GLCheck(glBindTexture(GL_TEXTURE_2D, previous));
myNeedTextureUpdate = false;
myNeedArrayUpdate = true;
@ -415,20 +415,20 @@ bool Image::CopyScreen(RenderWindow& Window, const IntRect& SourceRect)
////////////////////////////////////////////////////////////
/// Change the color of a pixel
////////////////////////////////////////////////////////////
void Image::SetPixel(unsigned int X, unsigned int Y, const Color& Col)
void Image::SetPixel(unsigned int x, unsigned int y, const Color& color)
{
// First check if the array of pixels needs to be updated
EnsureArrayUpdate();
// Check if pixel is whithin the image bounds
if ((X >= myWidth) || (Y >= myHeight))
if ((x >= myWidth) || (y >= myHeight))
{
std::cerr << "Cannot set pixel (" << X << "," << Y << ") for image "
std::cerr << "Cannot set pixel (" << x << "," << y << ") for image "
<< "(width = " << myWidth << ", height = " << myHeight << ")" << std::endl;
return;
}
myPixels[X + Y * myWidth] = Col;
myPixels[x + y * myWidth] = color;
// The texture will need to be updated
myNeedTextureUpdate = true;
@ -438,20 +438,20 @@ void Image::SetPixel(unsigned int X, unsigned int Y, const Color& Col)
////////////////////////////////////////////////////////////
/// Get a pixel from the image
////////////////////////////////////////////////////////////
const Color& Image::GetPixel(unsigned int X, unsigned int Y) const
const Color& Image::GetPixel(unsigned int x, unsigned int y) const
{
// First check if the array of pixels needs to be updated
const_cast<Image*>(this)->EnsureArrayUpdate();
// Check if pixel is whithin the image bounds
if ((X >= myWidth) || (Y >= myHeight))
if ((x >= myWidth) || (y >= myHeight))
{
std::cerr << "Cannot get pixel (" << X << "," << Y << ") for image "
std::cerr << "Cannot get pixel (" << x << "," << y << ") for image "
<< "(width = " << myWidth << ", height = " << myHeight << ")" << std::endl;
return Color::Black;
}
return myPixels[X + Y * myWidth];
return myPixels[x + y * myWidth];
}
@ -497,22 +497,22 @@ void Image::Bind() const
////////////////////////////////////////////////////////////
/// Enable or disable image smoothing filter
////////////////////////////////////////////////////////////
void Image::SetSmooth(bool Smooth)
void Image::SetSmooth(bool smooth)
{
if (Smooth != myIsSmooth)
if (smooth != myIsSmooth)
{
myIsSmooth = Smooth;
myIsSmooth = smooth;
if (myTexture)
{
GLint PreviousTexture;
GLCheck(glGetIntegerv(GL_TEXTURE_BINDING_2D, &PreviousTexture));
GLint previous;
GLCheck(glGetIntegerv(GL_TEXTURE_BINDING_2D, &previous));
GLCheck(glBindTexture(GL_TEXTURE_2D, myTexture));
GLCheck(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, myIsSmooth ? GL_LINEAR : GL_NEAREST));
GLCheck(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, myIsSmooth ? GL_LINEAR : GL_NEAREST));
GLCheck(glBindTexture(GL_TEXTURE_2D, PreviousTexture));
GLCheck(glBindTexture(GL_TEXTURE_2D, previous));
}
}
}
@ -549,38 +549,38 @@ bool Image::IsSmooth() const
/// Convert a subrect expressed in pixels, into float
/// texture coordinates
////////////////////////////////////////////////////////////
FloatRect Image::GetTexCoords(const IntRect& Rect, bool Adjust) const
FloatRect Image::GetTexCoords(const IntRect& rect, bool adjust) const
{
float Width = static_cast<float>(myTextureWidth);
float Height = static_cast<float>(myTextureHeight);
float width = static_cast<float>(myTextureWidth);
float height = static_cast<float>(myTextureHeight);
FloatRect Coords;
if (Adjust && myIsSmooth)
FloatRect coords;
if (adjust && myIsSmooth)
{
Coords.Left = (Rect.Left + 0.5f) / Width;
Coords.Top = (Rect.Top + 0.5f) / Height;
Coords.Right = (Rect.Right - 0.5f) / Width;
Coords.Bottom = (Rect.Bottom - 0.5f) / Height;
coords.Left = (rect.Left + 0.5f) / width;
coords.Top = (rect.Top + 0.5f) / height;
coords.Right = (rect.Right - 0.5f) / width;
coords.Bottom = (rect.Bottom - 0.5f) / height;
}
else
{
Coords.Left = Rect.Left / Width;
Coords.Top = Rect.Top / Height;
Coords.Right = Rect.Right / Width;
Coords.Bottom = Rect.Bottom / Height;
coords.Left = rect.Left / width;
coords.Top = rect.Top / height;
coords.Right = rect.Right / width;
coords.Bottom = rect.Bottom / height;
}
if (myPixelsFlipped)
std::swap(Coords.Top, Coords.Bottom);
std::swap(coords.Top, coords.Bottom);
return Coords;
return coords;
}
////////////////////////////////////////////////////////////
/// Get a valid texture size according to hardware support
////////////////////////////////////////////////////////////
unsigned int Image::GetValidTextureSize(unsigned int Size)
unsigned int Image::GetValidTextureSize(unsigned int size)
{
// Make sure that GLEW is initialized
EnsureGlewInit();
@ -588,16 +588,16 @@ unsigned int Image::GetValidTextureSize(unsigned int Size)
if (glewIsSupported("GL_ARB_texture_non_power_of_two") != 0)
{
// If hardware supports NPOT textures, then just return the unmodified size
return Size;
return size;
}
else
{
// If hardware doesn't support NPOT textures, we calculate the nearest power of two
unsigned int PowerOfTwo = 1;
while (PowerOfTwo < Size)
PowerOfTwo *= 2;
unsigned int powerOfTwo = 1;
while (powerOfTwo < size)
powerOfTwo *= 2;
return PowerOfTwo;
return powerOfTwo;
}
}
@ -605,21 +605,21 @@ unsigned int Image::GetValidTextureSize(unsigned int Size)
////////////////////////////////////////////////////////////
/// Assignment operator
////////////////////////////////////////////////////////////
Image& Image::operator =(const Image& Other)
Image& Image::operator =(const Image& other)
{
Image Temp(Other);
Image temp(other);
std::swap(myWidth, Temp.myWidth);
std::swap(myHeight, Temp.myHeight);
std::swap(myTextureWidth, Temp.myTextureWidth);
std::swap(myTextureHeight, Temp.myTextureHeight);
std::swap(myTexture, Temp.myTexture);
std::swap(myIsSmooth, Temp.myIsSmooth);
std::swap(myNeedArrayUpdate, Temp.myNeedArrayUpdate);
std::swap(myNeedTextureUpdate, Temp.myNeedTextureUpdate);
std::swap(myUpdateSource, Temp.myUpdateSource);
std::swap(myPixelsFlipped, Temp.myPixelsFlipped);
myPixels.swap(Temp.myPixels);
std::swap(myWidth, temp.myWidth);
std::swap(myHeight, temp.myHeight);
std::swap(myTextureWidth, temp.myTextureWidth);
std::swap(myTextureHeight, temp.myTextureHeight);
std::swap(myTexture, temp.myTexture);
std::swap(myIsSmooth, temp.myIsSmooth);
std::swap(myNeedArrayUpdate, temp.myNeedArrayUpdate);
std::swap(myNeedTextureUpdate, temp.myNeedTextureUpdate);
std::swap(myUpdateSource, temp.myUpdateSource);
std::swap(myPixelsFlipped, temp.myPixelsFlipped);
myPixels.swap(temp.myPixels);
return *this;
}
@ -635,43 +635,43 @@ bool Image::CreateTexture()
return false;
// Adjust internal texture dimensions depending on NPOT textures support
unsigned int TextureWidth = GetValidTextureSize(myWidth);
unsigned int TextureHeight = GetValidTextureSize(myHeight);
unsigned int textureWidth = GetValidTextureSize(myWidth);
unsigned int textureHeight = GetValidTextureSize(myHeight);
// Check the maximum texture size
GLint MaxSize;
GLCheck(glGetIntegerv(GL_MAX_TEXTURE_SIZE, &MaxSize));
if ((TextureWidth > static_cast<unsigned int>(MaxSize)) || (TextureHeight > static_cast<unsigned int>(MaxSize)))
GLint maxSize;
GLCheck(glGetIntegerv(GL_MAX_TEXTURE_SIZE, &maxSize));
if ((textureWidth > static_cast<unsigned int>(maxSize)) || (textureHeight > static_cast<unsigned int>(maxSize)))
{
std::cerr << "Failed to create image, its internal size is too high (" << TextureWidth << "x" << TextureHeight << ")" << std::endl;
std::cerr << "Failed to create image, its internal size is too high (" << textureWidth << "x" << textureHeight << ")" << std::endl;
return false;
}
// Destroy the previous OpenGL texture if it already exists with another size
if ((TextureWidth != myTextureWidth) || (TextureHeight != myTextureHeight))
if ((textureWidth != myTextureWidth) || (textureHeight != myTextureHeight))
{
DestroyTexture();
myTextureWidth = TextureWidth;
myTextureHeight = TextureHeight;
myTextureWidth = textureWidth;
myTextureHeight = textureHeight;
}
// Create the OpenGL texture
if (!myTexture)
{
GLint PreviousTexture;
GLCheck(glGetIntegerv(GL_TEXTURE_BINDING_2D, &PreviousTexture));
GLint previous;
GLCheck(glGetIntegerv(GL_TEXTURE_BINDING_2D, &previous));
GLuint Texture = 0;
GLCheck(glGenTextures(1, &Texture));
GLCheck(glBindTexture(GL_TEXTURE_2D, Texture));
GLuint texture = 0;
GLCheck(glGenTextures(1, &texture));
GLCheck(glBindTexture(GL_TEXTURE_2D, texture));
GLCheck(glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, myTextureWidth, myTextureHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL));
GLCheck(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP));
GLCheck(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP));
GLCheck(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, myIsSmooth ? GL_LINEAR : GL_NEAREST));
GLCheck(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, myIsSmooth ? GL_LINEAR : GL_NEAREST));
myTexture = static_cast<unsigned int>(Texture);
myTexture = static_cast<unsigned int>(texture);
GLCheck(glBindTexture(GL_TEXTURE_2D, PreviousTexture));
GLCheck(glBindTexture(GL_TEXTURE_2D, previous));
}
myNeedTextureUpdate = true;
@ -690,8 +690,8 @@ void Image::EnsureTextureUpdate()
{
if (myTexture)
{
GLint PreviousTexture;
GLCheck(glGetIntegerv(GL_TEXTURE_BINDING_2D, &PreviousTexture));
GLint previous;
GLCheck(glGetIntegerv(GL_TEXTURE_BINDING_2D, &previous));
if (myUpdateSource)
{
@ -707,7 +707,7 @@ void Image::EnsureTextureUpdate()
myPixelsFlipped = false;
}
GLCheck(glBindTexture(GL_TEXTURE_2D, PreviousTexture));
GLCheck(glBindTexture(GL_TEXTURE_2D, previous));
}
myNeedTextureUpdate = false;
@ -728,8 +728,8 @@ void Image::EnsureArrayUpdate()
EnsureTextureUpdate();
// Save the previous texture
GLint PreviousTexture;
GLCheck(glGetIntegerv(GL_TEXTURE_BINDING_2D, &PreviousTexture));
GLint previous;
GLCheck(glGetIntegerv(GL_TEXTURE_BINDING_2D, &previous));
// Resize the destination array of pixels
myPixels.resize(myWidth * myHeight);
@ -747,32 +747,32 @@ void Image::EnsureArrayUpdate()
// Texture and array don't have the same size, we have to use a slower algorithm
// All the pixels will first be copied to a temporary array
std::vector<Color> AllPixels(myTextureWidth * myTextureHeight);
std::vector<Color> allPixels(myTextureWidth * myTextureHeight);
GLCheck(glBindTexture(GL_TEXTURE_2D, myTexture));
GLCheck(glGetTexImage(GL_TEXTURE_2D, 0, GL_RGBA, GL_UNSIGNED_BYTE, &AllPixels[0]));
GLCheck(glGetTexImage(GL_TEXTURE_2D, 0, GL_RGBA, GL_UNSIGNED_BYTE, &allPixels[0]));
// The we copy the useful pixels from the temporary array to the final one
const Color* Src = &AllPixels[0];
Color* Dst = &myPixels[0];
int SrcPitch = myTextureWidth;
const Color* src = &allPixels[0];
Color* dst = &myPixels[0];
int srcPitch = myTextureWidth;
// Handle the case where source pixels are flipped vertically
if (myPixelsFlipped)
{
Src += myTextureWidth * (myHeight - 1);
SrcPitch = -SrcPitch;
src += myTextureWidth * (myHeight - 1);
srcPitch = -srcPitch;
}
for (unsigned int i = 0; i < myHeight; ++i)
{
std::copy(Src, Src + myWidth, Dst);
Src += SrcPitch;
Dst += myWidth;
std::copy(src, src + myWidth, dst);
src += srcPitch;
dst += myWidth;
}
}
// Restore the previous texture
GLCheck(glBindTexture(GL_TEXTURE_2D, PreviousTexture));
GLCheck(glBindTexture(GL_TEXTURE_2D, previous));
myNeedArrayUpdate = false;
}
@ -784,11 +784,11 @@ void Image::EnsureArrayUpdate()
/// its content.
/// For internal use only (see RenderImage class).
////////////////////////////////////////////////////////////
void Image::ExternalUpdate(RenderImage& Source)
void Image::ExternalUpdate(RenderImage& source)
{
myNeedTextureUpdate = true;
myNeedArrayUpdate = true;
myUpdateSource = &Source;
myUpdateSource = &source;
}

View file

@ -41,10 +41,10 @@ namespace
////////////////////////////////////////////////////////////
/// Error callback for PNG writing
////////////////////////////////////////////////////////////
void PngErrorHandler(png_structp Png, png_const_charp Message)
void PngErrorHandler(png_structp png, png_const_charp message)
{
std::cerr << "Failed to write PNG image. Reason : " << Message << std::endl;
longjmp(Png->jmpbuf, 1);
std::cerr << "Failed to write PNG image. Reason : " << message << std::endl;
longjmp(png->jmpbuf, 1);
}
}
@ -85,34 +85,34 @@ ImageLoader::~ImageLoader()
////////////////////////////////////////////////////////////
/// Load pixels from an image file
////////////////////////////////////////////////////////////
bool ImageLoader::LoadImageFromFile(const std::string& Filename, std::vector<Color>& Pixels, unsigned int& Width, unsigned int& Height)
bool ImageLoader::LoadImageFromFile(const std::string& filename, std::vector<Color>& pixels, unsigned int& width, unsigned int& height)
{
// Clear the array (just in case)
Pixels.clear();
pixels.clear();
// Load the image and get a pointer to the pixels in memory
int ImgWidth, ImgHeight, ImgChannels;
unsigned char* PixelsPtr = SOIL_load_image(Filename.c_str(), &ImgWidth, &ImgHeight, &ImgChannels, SOIL_LOAD_RGBA);
int imgWidth, imgHeight, imgChannels;
unsigned char* ptr = SOIL_load_image(filename.c_str(), &imgWidth, &imgHeight, &imgChannels, SOIL_LOAD_RGBA);
if (PixelsPtr)
if (ptr)
{
// Assign the image properties
Width = ImgWidth;
Height = ImgHeight;
width = imgWidth;
height = imgHeight;
// Copy the loaded pixels to the pixel buffer
Pixels.resize(Width * Height);
memcpy(&Pixels[0], PixelsPtr, Width * Height * 4);
pixels.resize(width * height);
memcpy(&pixels[0], ptr, width * height * 4);
// Free the loaded pixels (they are now in our own pixel buffer)
SOIL_free_image_data(PixelsPtr);
SOIL_free_image_data(ptr);
return true;
}
else
{
// Error, failed to load the image
std::cerr << "Failed to load image \"" << Filename << "\". Reason : " << SOIL_last_result() << std::endl;
std::cerr << "Failed to load image \"" << filename << "\". Reason : " << SOIL_last_result() << std::endl;
return false;
}
@ -122,29 +122,29 @@ bool ImageLoader::LoadImageFromFile(const std::string& Filename, std::vector<Col
////////////////////////////////////////////////////////////
/// Load pixels from an image file in memory
////////////////////////////////////////////////////////////
bool ImageLoader::LoadImageFromMemory(const char* Data, std::size_t SizeInBytes, std::vector<Color>& Pixels, unsigned int& Width, unsigned int& Height)
bool ImageLoader::LoadImageFromMemory(const char* data, std::size_t sizeInBytes, std::vector<Color>& pixels, unsigned int& width, unsigned int& height)
{
// Clear the array (just in case)
Pixels.clear();
pixels.clear();
// Load the image and get a pointer to the pixels in memory
const unsigned char* Buffer = reinterpret_cast<const unsigned char*>(Data);
int Size = static_cast<int>(SizeInBytes);
int ImgWidth, ImgHeight, ImgChannels;
unsigned char* PixelsPtr = SOIL_load_image_from_memory(Buffer, Size, &ImgWidth, &ImgHeight, &ImgChannels, SOIL_LOAD_RGBA);
const unsigned char* buffer = reinterpret_cast<const unsigned char*>(data);
int size = static_cast<int>(sizeInBytes);
int imgWidth, imgHeight, imgChannels;
unsigned char* ptr = SOIL_load_image_from_memory(buffer, size, &imgWidth, &imgHeight, &imgChannels, SOIL_LOAD_RGBA);
if (PixelsPtr)
if (ptr)
{
// Assign the image properties
Width = ImgWidth;
Height = ImgHeight;
width = imgWidth;
height = imgHeight;
// Copy the loaded pixels to the pixel buffer
Pixels.resize(Width * Height);
memcpy(&Pixels[0], PixelsPtr, Width * Height * 4);
pixels.resize(width * height);
memcpy(&pixels[0], ptr, width * height * 4);
// Free the loaded pixels (they are now in our own pixel buffer)
SOIL_free_image_data(PixelsPtr);
SOIL_free_image_data(ptr);
return true;
}
@ -161,35 +161,35 @@ bool ImageLoader::LoadImageFromMemory(const char* Data, std::size_t SizeInBytes,
////////////////////////////////////////////////////////////
/// Save pixels to an image file
////////////////////////////////////////////////////////////
bool ImageLoader::SaveImageToFile(const std::string& Filename, const std::vector<Color>& Pixels, unsigned int Width, unsigned int Height)
bool ImageLoader::SaveImageToFile(const std::string& filename, const std::vector<Color>& pixels, unsigned int width, unsigned int height)
{
// Deduce the image type from its extension
int Type = -1;
if (Filename.size() > 3)
int type = -1;
if (filename.size() > 3)
{
std::string Extension = Filename.substr(Filename.size() - 3);
if (Extension == "bmp" || Extension == "BMP") Type = SOIL_SAVE_TYPE_BMP;
else if (Extension == "tga" || Extension == "TGA") Type = SOIL_SAVE_TYPE_TGA;
else if (Extension == "dds" || Extension == "DDS") Type = SOIL_SAVE_TYPE_DDS;
std::string extension = filename.substr(filename.size() - 3);
if (extension == "bmp" || extension == "BMP") type = SOIL_SAVE_TYPE_BMP;
else if (extension == "tga" || extension == "TGA") type = SOIL_SAVE_TYPE_TGA;
else if (extension == "dds" || extension == "DDS") type = SOIL_SAVE_TYPE_DDS;
// Special handling for PNG and JPG -- not handled by SOIL
else if (Extension == "png" || Extension == "PNG") return WritePng(Filename, Pixels, Width, Height);
else if (Extension == "jpg" || Extension == "JPG") return WriteJpg(Filename, Pixels, Width, Height);
else if (extension == "png" || extension == "PNG") return WritePng(filename, pixels, width, height);
else if (extension == "jpg" || extension == "JPG") return WriteJpg(filename, pixels, width, height);
}
if (Type == -1)
if (type == -1)
{
// Error, incompatible type
std::cerr << "Failed to save image \"" << Filename << "\". Reason : this image format is not supported" << std::endl;
std::cerr << "Failed to save image \"" << filename << "\". Reason: this image format is not supported" << std::endl;
return false;
}
// Finally save the image
const unsigned char* PixelsPtr = reinterpret_cast<const unsigned char*>(&Pixels[0]);
if (!SOIL_save_image(Filename.c_str(), Type, static_cast<int>(Width), static_cast<int>(Height), 4, PixelsPtr))
const unsigned char* ptr = reinterpret_cast<const unsigned char*>(&pixels[0]);
if (!SOIL_save_image(filename.c_str(), type, static_cast<int>(width), static_cast<int>(height), 4, ptr))
{
// Error, failed to save the image
std::cerr << "Failed to save image \"" << Filename << "\". Reason : " << SOIL_last_result() << std::endl;
std::cerr << "Failed to save image \"" << filename << "\". Reason: " << SOIL_last_result() << std::endl;
return false;
}
@ -200,57 +200,57 @@ bool ImageLoader::SaveImageToFile(const std::string& Filename, const std::vector
////////////////////////////////////////////////////////////
/// Save a JPG image file
////////////////////////////////////////////////////////////
bool ImageLoader::WriteJpg(const std::string& Filename, const std::vector<Color>& Pixels, unsigned int Width, unsigned int Height)
bool ImageLoader::WriteJpg(const std::string& filename, const std::vector<Color>& pixels, unsigned int width, unsigned int height)
{
// Open the file to write in
FILE* File = fopen(Filename.c_str(), "wb");
if (!File)
FILE* file = fopen(filename.c_str(), "wb");
if (!file)
{
std::cerr << "Failed to save image file \"" << Filename << "\". Reason : cannot open file" << std::endl;
std::cerr << "Failed to save image file \"" << filename << "\". Reason : cannot open file" << std::endl;
return false;
}
// Initialize the error handler
jpeg_compress_struct CompressInfo;
jpeg_error_mgr ErrorManager;
CompressInfo.err = jpeg_std_error(&ErrorManager);
jpeg_compress_struct compressInfos;
jpeg_error_mgr errorManager;
compressInfos.err = jpeg_std_error(&errorManager);
// Initialize all the writing and compression infos
jpeg_create_compress(&CompressInfo);
CompressInfo.image_width = Width;
CompressInfo.image_height = Height;
CompressInfo.input_components = 3;
CompressInfo.in_color_space = JCS_RGB;
jpeg_stdio_dest(&CompressInfo, File);
jpeg_set_defaults(&CompressInfo);
jpeg_set_quality(&CompressInfo, 90, TRUE);
jpeg_create_compress(&compressInfos);
compressInfos.image_width = width;
compressInfos.image_height = height;
compressInfos.input_components = 3;
compressInfos.in_color_space = JCS_RGB;
jpeg_stdio_dest(&compressInfos, file);
jpeg_set_defaults(&compressInfos);
jpeg_set_quality(&compressInfos, 90, TRUE);
// Get rid of the aplha channel
std::vector<Uint8> PixelsBuffer(Width * Height * 3);
for (std::size_t i = 0; i < Pixels.size(); ++i)
std::vector<Uint8> buffer(width * height * 3);
for (std::size_t i = 0; i < pixels.size(); ++i)
{
PixelsBuffer[i * 3 + 0] = Pixels[i].r;
PixelsBuffer[i * 3 + 1] = Pixels[i].g;
PixelsBuffer[i * 3 + 2] = Pixels[i].b;
buffer[i * 3 + 0] = pixels[i].r;
buffer[i * 3 + 1] = pixels[i].g;
buffer[i * 3 + 2] = pixels[i].b;
}
Uint8* PixelsPtr = &PixelsBuffer[0];
Uint8* ptr = &buffer[0];
// Start compression
jpeg_start_compress(&CompressInfo, TRUE);
jpeg_start_compress(&compressInfos, TRUE);
// Write each row of the image
while (CompressInfo.next_scanline < CompressInfo.image_height)
while (compressInfos.next_scanline < compressInfos.image_height)
{
JSAMPROW RowPointer = PixelsPtr + (CompressInfo.next_scanline * Width * 3);
jpeg_write_scanlines(&CompressInfo, &RowPointer, 1);
JSAMPROW rawPointer = ptr + (compressInfos.next_scanline * width * 3);
jpeg_write_scanlines(&compressInfos, &rawPointer, 1);
}
// Finish compression
jpeg_finish_compress(&CompressInfo);
jpeg_destroy_compress(&CompressInfo);
jpeg_finish_compress(&compressInfos);
jpeg_destroy_compress(&compressInfos);
// Close the file
fclose(File);
fclose(file);
return true;
}
@ -259,70 +259,70 @@ bool ImageLoader::WriteJpg(const std::string& Filename, const std::vector<Color>
////////////////////////////////////////////////////////////
/// Save a PNG image file
////////////////////////////////////////////////////////////
bool ImageLoader::WritePng(const std::string& Filename, const std::vector<Color>& Pixels, unsigned int Width, unsigned int Height)
bool ImageLoader::WritePng(const std::string& filename, const std::vector<Color>& pixels, unsigned int width, unsigned int height)
{
// Open the file to write in
FILE* File = fopen(Filename.c_str(), "wb");
if (!File)
FILE* file = fopen(filename.c_str(), "wb");
if (!file)
{
std::cerr << "Failed to save image file \"" << Filename << "\". Reason : cannot open file" << std::endl;
std::cerr << "Failed to save image file \"" << filename << "\". Reason : cannot open file" << std::endl;
return false;
}
// Create the main PNG structure
png_structp Png = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, &PngErrorHandler, NULL);
if (!Png)
png_structp png = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, &PngErrorHandler, NULL);
if (!png)
{
fclose(File);
std::cerr << "Failed to save image file \"" << Filename << "\". Reason : cannot allocate PNG write structure" << std::endl;
fclose(file);
std::cerr << "Failed to save image file \"" << filename << "\". Reason : cannot allocate PNG write structure" << std::endl;
return false;
}
// Initialize the image informations
png_infop PngInfo = png_create_info_struct(Png);
if (!PngInfo)
png_infop pngInfos = png_create_info_struct(png);
if (!pngInfos)
{
fclose(File);
png_destroy_write_struct(&Png, NULL);
std::cerr << "Failed to save image file \"" << Filename << "\". Reason : cannot allocate PNG info structure" << std::endl;
fclose(file);
png_destroy_write_struct(&png, NULL);
std::cerr << "Failed to save image file \"" << filename << "\". Reason : cannot allocate PNG info structure" << std::endl;
return false;
}
// For proper error handling...
if (setjmp(Png->jmpbuf))
if (setjmp(png->jmpbuf))
{
png_destroy_write_struct(&Png, &PngInfo);
png_destroy_write_struct(&png, &pngInfos);
return false;
}
// Link the file to the PNG structure
png_init_io(Png, File);
png_init_io(png, file);
// Set the image informations
png_set_IHDR(Png, PngInfo, Width, Height, 8, PNG_COLOR_TYPE_RGB_ALPHA, PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
png_set_IHDR(png, pngInfos, width, height, 8, PNG_COLOR_TYPE_RGB_ALPHA, PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
// Write the header
png_write_info(Png, PngInfo);
png_write_info(png, pngInfos);
// Get the pointers to the pixels rows into an array
png_byte* PixelsPtr = (png_byte*)&Pixels[0];
std::vector<png_byte*> RowPointers(Height);
for (unsigned int i = 0; i < Height; ++i)
png_byte* ptr = (png_byte*)&pixels[0];
std::vector<png_byte*> rawPointers(height);
for (unsigned int i = 0; i < height; ++i)
{
RowPointers[i] = PixelsPtr;
PixelsPtr += Width * 4;
rawPointers[i] = ptr;
ptr += width * 4;
}
// Write pixels row by row
png_set_rows(Png, PngInfo, &RowPointers[0]);
png_write_png(Png, PngInfo, PNG_TRANSFORM_IDENTITY, NULL);
png_set_rows(png, pngInfos, &rawPointers[0]);
png_write_png(png, pngInfos, PNG_TRANSFORM_IDENTITY, NULL);
// Finish writing the file
png_write_end(Png, PngInfo);
png_write_end(png, pngInfos);
// Cleanup resources
png_destroy_write_struct(&Png, &PngInfo);
fclose(File);
png_destroy_write_struct(&png, &pngInfos);
fclose(file);
return true;
}

View file

@ -57,42 +57,42 @@ public :
////////////////////////////////////////////////////////////
/// Load pixels from an image file
///
/// \param Filename : Path of image file to load
/// \param Pixels : Array of pixels to fill with loaded image
/// \param Width : Width of loaded image, in pixels
/// \param Height : Height of loaded image, in pixels
/// \param filename : Path of image file to load
/// \param pixels : Array of pixels to fill with loaded image
/// \param width : Width of loaded image, in pixels
/// \param height : Height of loaded image, in pixels
///
/// \return True if loading was successful
///
////////////////////////////////////////////////////////////
bool LoadImageFromFile(const std::string& Filename, std::vector<Color>& Pixels, unsigned int& Width, unsigned int& Height);
bool LoadImageFromFile(const std::string& filename, std::vector<Color>& pixels, unsigned int& width, unsigned int& height);
////////////////////////////////////////////////////////////
/// Load pixels from an image file in memory
///
/// \param Data : Pointer to the file data in memory
/// \param SizeInBytes : Size of the data to load, in bytes
/// \param Pixels : Array of pixels to fill with loaded image
/// \param Width : Width of loaded image, in pixels
/// \param Height : Height of loaded image, in pixels
/// \param data : Pointer to the file data in memory
/// \param sizeInBytes : Size of the data to load, in bytes
/// \param pixels : Array of pixels to fill with loaded image
/// \param width : Width of loaded image, in pixels
/// \param height : Height of loaded image, in pixels
///
/// \return True if loading was successful
///
////////////////////////////////////////////////////////////
bool LoadImageFromMemory(const char* Data, std::size_t SizeInBytes, std::vector<Color>& Pixels, unsigned int& Width, unsigned int& Height);
bool LoadImageFromMemory(const char* data, std::size_t sizeInBytes, std::vector<Color>& pixels, unsigned int& width, unsigned int& height);
////////////////////////////////////////////////////////////
/// Save pixels to an image file
///
/// \param Filename : Path of image file to save
/// \param Pixels : Array of pixels to save to image
/// \param Width : Width of image to save, in pixels
/// \param Height : Height of image to save, in pixels
/// \param filename : Path of image file to save
/// \param pixels : Array of pixels to save to image
/// \param width : Width of image to save, in pixels
/// \param height : Height of image to save, in pixels
///
/// \return True if saving was successful
///
////////////////////////////////////////////////////////////
bool SaveImageToFile(const std::string& Filename, const std::vector<Color>& Pixels, unsigned int Width, unsigned int Height);
bool SaveImageToFile(const std::string& filename, const std::vector<Color>& pixels, unsigned int width, unsigned int height);
private :
@ -111,28 +111,28 @@ private :
////////////////////////////////////////////////////////////
/// Save a JPG image file
///
/// \param Filename : Path of image file to save
/// \param Pixels : Array of pixels to save to image
/// \param Width : Width of image to save, in pixels
/// \param Height : Height of image to save, in pixels
/// \param filename : Path of image file to save
/// \param pixels : Array of pixels to save to image
/// \param width : Width of image to save, in pixels
/// \param height : Height of image to save, in pixels
///
/// \return True if saving was successful
///
////////////////////////////////////////////////////////////
bool WriteJpg(const std::string& Filename, const std::vector<Color>& Pixels, unsigned int Width, unsigned int Height);
bool WriteJpg(const std::string& filename, const std::vector<Color>& pixels, unsigned int width, unsigned int height);
////////////////////////////////////////////////////////////
/// Save a PNG image file
///
/// \param Filename : Path of image file to save
/// \param Pixels : Array of pixels to save to image
/// \param Width : Width of image to save, in pixels
/// \param Height : Height of image to save, in pixels
/// \param filename : Path of image file to save
/// \param pixels : Array of pixels to save to image
/// \param width : Width of image to save, in pixels
/// \param height : Height of image to save, in pixels
///
/// \return True if saving was successful
///
////////////////////////////////////////////////////////////
bool WritePng(const std::string& Filename, const std::vector<Color>& Pixels, unsigned int Width, unsigned int Height);
bool WritePng(const std::string& filename, const std::vector<Color>& pixels, unsigned int width, unsigned int height);
};
} // namespace priv

View file

@ -63,7 +63,7 @@ RenderImageImplPBuffer::~RenderImageImplPBuffer()
// This is to make sure that another valid context is made
// active after we destroy the P-Buffer's one
Context Ctx;
Context context;
}
@ -82,14 +82,14 @@ bool RenderImageImplPBuffer::IsSupported()
////////////////////////////////////////////////////////////
/// /see RenderImageImpl::Create
////////////////////////////////////////////////////////////
bool RenderImageImplPBuffer::Create(unsigned int Width, unsigned int Height, unsigned int /*TextureId*/, bool DepthBuffer)
bool RenderImageImplPBuffer::Create(unsigned int width, unsigned int height, unsigned int, bool depthBuffer)
{
// Store the dimensions
myWidth = Width;
myHeight = Height;
myWidth = width;
myHeight = height;
// Define the PBuffer attributes
int VisualAttributes[] =
int visualAttributes[] =
{
GLX_RENDER_TYPE, GLX_RGBA_BIT,
GLX_DRAWABLE_TYPE, GLX_PBUFFER_BIT,
@ -97,72 +97,72 @@ bool RenderImageImplPBuffer::Create(unsigned int Width, unsigned int Height, uns
GLX_GREEN_SIZE, 8,
GLX_BLUE_SIZE, 8,
GLX_ALPHA_SIZE, 8,
GLX_DEPTH_SIZE, (DepthBuffer ? 24 : 0),
GLX_DEPTH_SIZE, (depthBuffer ? 24 : 0),
0
};
int PBufferAttributes[] =
{
GLX_PBUFFER_WIDTH, Width,
GLX_PBUFFER_HEIGHT, Height,
GLX_PBUFFER_WIDTH, width,
GLX_PBUFFER_HEIGHT, height,
0
};
// Get the available FB configurations
int NbConfigs = 0;
GLXFBConfig* Configs = glXChooseFBConfigSGIX(myDisplay, DefaultScreen(myDisplay), VisualAttributes, &NbConfigs);
if (!Configs || !NbConfigs)
int nbConfigs = 0;
GLXFBConfig* configs = glXChooseFBConfigSGIX(myDisplay, DefaultScreen(myDisplay), visualAttributes, &nbConfigs);
if (!configs || !nbConfigs)
{
std::cerr << "Impossible to create render image (failed to find a suitable pixel format for PBuffer)" << std::endl;
return false;
}
// Create the P-Buffer
myPBuffer = glXCreateGLXPbufferSGIX(myDisplay, Configs[0], Width, Height, PBufferAttributes);
myPBuffer = glXCreateGLXPbufferSGIX(myDisplay, configs[0], width, height, PBufferAttributes);
if (!myPBuffer)
{
std::cerr << "Impossible to create render image (failed to create the OpenGL PBuffer)" << std::endl;
XFree(Configs);
XFree(configs);
return false;
}
// Check the actual size of the P-Buffer
unsigned int ActualWidth, ActualHeight;
glXQueryGLXPbufferSGIX(myDisplay, myPBuffer, GLX_WIDTH_SGIX, &ActualWidth);
glXQueryGLXPbufferSGIX(myDisplay, myPBuffer, GLX_HEIGHT_SGIX, &ActualHeight);
if ((ActualWidth != Width) || (ActualHeight != Height))
unsigned int actualWidth, actualHeight;
glXQueryGLXPbufferSGIX(myDisplay, myPBuffer, GLX_WIDTH_SGIX, &actualWidth);
glXQueryGLXPbufferSGIX(myDisplay, myPBuffer, GLX_HEIGHT_SGIX, &actualHeight);
if ((actualWidth != width) || (actualHeight != height))
{
std::cerr << "Impossible to create render image (failed to match the requested size). "
<< "Size: " << ActualWidth << "x" << ActualHeight << " - "
<< "Requested: " << Width << "x" << Height
<< "Size: " << actualWidth << "x" << actualHeight << " - "
<< "Requested: " << width << "x" << height
<< std::endl;
XFree(Configs);
XFree(configs);
return false;
}
// We'll have to share the P-Buffer context with the current context
GLXDrawable CurrentDrawable = glXGetCurrentDrawable();
GLXContext CurrentContext = glXGetCurrentContext();
if (CurrentContext)
GLXDrawable currentDrawable = glXGetCurrentDrawable();
GLXContext currentContext = glXGetCurrentContext();
if (currentContext)
glXMakeCurrent(myDisplay, NULL, NULL);
// Create the context
XVisualInfo* Visual = glXGetVisualFromFBConfig(myDisplay, Configs[0]);
myContext = glXCreateContext(myDisplay, Visual, CurrentContext, true);
XVisualInfo* Visual = glXGetVisualFromFBConfig(myDisplay, configs[0]);
myContext = glXCreateContext(myDisplay, visual, currentContext, true);
if (!myContext)
{
std::cerr << "Impossible to create render image (failed to create the OpenGL context)" << std::endl;
XFree(Configs);
XFree(Visual);
XFree(configs);
XFree(visual);
return false;
}
// Restore the previous active context
if (CurrentContext)
glXMakeCurrent(myDisplay, CurrentDrawable, CurrentContext);
if (currentContext)
glXMakeCurrent(myDisplay, currentDrawable, currentContext);
// Cleanup resources
XFree(Configs);
XFree(Visual);
XFree(configs);
XFree(visual);
return true;
}
@ -171,7 +171,7 @@ bool RenderImageImplPBuffer::Create(unsigned int Width, unsigned int Height, uns
////////////////////////////////////////////////////////////
/// /see RenderImageImpl::Activate
////////////////////////////////////////////////////////////
bool RenderImageImplPBuffer::Activate(bool Active)
bool RenderImageImplPBuffer::Activate(bool active)
{
if (Active)
{
@ -197,23 +197,23 @@ bool RenderImageImplPBuffer::Activate(bool Active)
////////////////////////////////////////////////////////////
/// /see RenderImageImpl::UpdateTexture
////////////////////////////////////////////////////////////
bool RenderImageImplPBuffer::UpdateTexture(unsigned int TextureId)
bool RenderImageImplPBuffer::UpdateTexture(unsigned int textureId)
{
// Store the current active context
GLXDrawable CurrentDrawable = glXGetCurrentDrawable();
GLXContext CurrentContext = glXGetCurrentContext();
GLXDrawable currentDrawable = glXGetCurrentDrawable();
GLXContext currentContext = glXGetCurrentContext();
if (Activate(true))
{
// Bind the texture
GLCheck(glEnable(GL_TEXTURE_2D));
GLCheck(glBindTexture(GL_TEXTURE_2D, TextureId));
GLCheck(glBindTexture(GL_TEXTURE_2D, textureId));
// Copy the rendered pixels to the image
GLCheck(glCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, 0, 0, myWidth, myHeight));
// Restore the previous context
glXMakeCurrent(myDisplay, CurrentDrawable, CurrentContext);
glXMakeCurrent(myDisplay, currentDrawable, currentContext);
return true;
}

View file

@ -71,19 +71,19 @@ private :
/// /see RenderImageImpl::Create
///
////////////////////////////////////////////////////////////
virtual bool Create(unsigned int Width, unsigned int Height, unsigned int TextureId, bool DepthBuffer);
virtual bool Create(unsigned int width, unsigned int height, unsigned int textureId, bool depthBuffer);
////////////////////////////////////////////////////////////
/// /see RenderImageImpl::Activate
///
////////////////////////////////////////////////////////////
virtual bool Activate(bool Active);
virtual bool Activate(bool active);
////////////////////////////////////////////////////////////
/// /see RenderImageImpl::UpdateTexture
///
////////////////////////////////////////////////////////////
virtual bool UpdateTexture(unsigned TextureId);
virtual bool UpdateTexture(unsigned textureId);
////////////////////////////////////////////////////////////
// Member data

View file

@ -54,18 +54,18 @@ myShaderProgram(0)
////////////////////////////////////////////////////////////
/// Copy constructor
////////////////////////////////////////////////////////////
PostFX::PostFX(const PostFX& Copy) :
Drawable (Copy),
PostFX::PostFX(const PostFX& copy) :
Drawable (copy),
myShaderProgram (0),
myTextures (Copy.myTextures),
myFragmentShader(Copy.myFragmentShader),
myFrameBuffer (Copy.myFrameBuffer)
myTextures (copy.myTextures),
myFragmentShader(copy.myFragmentShader),
myFrameBuffer (copy.myFrameBuffer)
{
// No filtering on frame buffer
myFrameBuffer.SetSmooth(false);
// Create the shaders and the program
if (Copy.myShaderProgram)
if (copy.myShaderProgram)
CreateProgram();
}
@ -84,18 +84,18 @@ PostFX::~PostFX()
////////////////////////////////////////////////////////////
/// Load the effect from a file
////////////////////////////////////////////////////////////
bool PostFX::LoadFromFile(const std::string& Filename)
bool PostFX::LoadFromFile(const std::string& filename)
{
// Open the file
std::ifstream File(Filename.c_str());
if (!File)
std::ifstream file(filename.c_str());
if (!file)
{
std::cerr << "Failed to open effect file \"" << Filename << "\"" << std::endl;
std::cerr << "Failed to open effect file \"" << filename << "\"" << std::endl;
return false;
}
// Apply the preprocessing pass to the fragment shader code
myFragmentShader = PreprocessEffect(File);
myFragmentShader = PreprocessEffect(file);
// Create the shaders and the program
CreateProgram();
@ -107,13 +107,13 @@ bool PostFX::LoadFromFile(const std::string& Filename)
////////////////////////////////////////////////////////////
/// Load the effect from a text in memory
////////////////////////////////////////////////////////////
bool PostFX::LoadFromMemory(const std::string& Effect)
bool PostFX::LoadFromMemory(const std::string& effect)
{
// Open a stream and copy the effect code
std::istringstream Stream(Effect.c_str());
std::istringstream stream(effect.c_str());
// Apply the preprocessing pass to the fragment shader code
myFragmentShader = PreprocessEffect(Stream);
myFragmentShader = PreprocessEffect(stream);
// Create the shaders and the program
CreateProgram();
@ -125,7 +125,7 @@ bool PostFX::LoadFromMemory(const std::string& Effect)
////////////////////////////////////////////////////////////
/// Change a parameter of the effect (1 float)
////////////////////////////////////////////////////////////
void PostFX::SetParameter(const std::string& Name, float X)
void PostFX::SetParameter(const std::string& name, float x)
{
if (myShaderProgram)
{
@ -133,11 +133,11 @@ void PostFX::SetParameter(const std::string& Name, float X)
GLCheck(glUseProgramObjectARB(myShaderProgram));
// Get parameter location and assign it new values
GLint Location = glGetUniformLocationARB(myShaderProgram, Name.c_str());
if (Location != -1)
GLCheck(glUniform1fARB(Location, X));
GLint location = glGetUniformLocationARB(myShaderProgram, name.c_str());
if (location != -1)
GLCheck(glUniform1fARB(location, x));
else
std::cerr << "Parameter \"" << Name << "\" not found in post-effect" << std::endl;
std::cerr << "Parameter \"" << name << "\" not found in post-effect" << std::endl;
// Disable program
GLCheck(glUseProgramObjectARB(0));
@ -148,7 +148,7 @@ void PostFX::SetParameter(const std::string& Name, float X)
////////////////////////////////////////////////////////////
/// Change a parameter of the effect (2 floats)
////////////////////////////////////////////////////////////
void PostFX::SetParameter(const std::string& Name, float X, float Y)
void PostFX::SetParameter(const std::string& name, float x, float y)
{
if (myShaderProgram)
{
@ -156,11 +156,11 @@ void PostFX::SetParameter(const std::string& Name, float X, float Y)
GLCheck(glUseProgramObjectARB(myShaderProgram));
// Get parameter location and assign it new values
GLint Location = glGetUniformLocationARB(myShaderProgram, Name.c_str());
if (Location != -1)
GLCheck(glUniform2fARB(Location, X, Y));
GLint location = glGetUniformLocationARB(myShaderProgram, name.c_str());
if (location != -1)
GLCheck(glUniform2fARB(location, x, y));
else
std::cerr << "Parameter \"" << Name << "\" not found in post-effect" << std::endl;
std::cerr << "Parameter \"" << name << "\" not found in post-effect" << std::endl;
// Disable program
GLCheck(glUseProgramObjectARB(0));
@ -171,7 +171,7 @@ void PostFX::SetParameter(const std::string& Name, float X, float Y)
////////////////////////////////////////////////////////////
/// Change a parameter of the effect (3 floats)
////////////////////////////////////////////////////////////
void PostFX::SetParameter(const std::string& Name, float X, float Y, float Z)
void PostFX::SetParameter(const std::string& name, float x, float y, float z)
{
if (myShaderProgram)
{
@ -179,11 +179,11 @@ void PostFX::SetParameter(const std::string& Name, float X, float Y, float Z)
GLCheck(glUseProgramObjectARB(myShaderProgram));
// Get parameter location and assign it new values
GLint Location = glGetUniformLocationARB(myShaderProgram, Name.c_str());
if (Location != -1)
GLCheck(glUniform3fARB(Location, X, Y, Z));
GLint location = glGetUniformLocationARB(myShaderProgram, name.c_str());
if (location != -1)
GLCheck(glUniform3fARB(location, x, y, z));
else
std::cerr << "Parameter \"" << Name << "\" not found in post-effect" << std::endl;
std::cerr << "Parameter \"" << name << "\" not found in post-effect" << std::endl;
// Disable program
GLCheck(glUseProgramObjectARB(0));
@ -194,7 +194,7 @@ void PostFX::SetParameter(const std::string& Name, float X, float Y, float Z)
////////////////////////////////////////////////////////////
/// Change a parameter of the effect (4 floats)
////////////////////////////////////////////////////////////
void PostFX::SetParameter(const std::string& Name, float X, float Y, float Z, float W)
void PostFX::SetParameter(const std::string& name, float x, float y, float z, float w)
{
if (myShaderProgram)
{
@ -202,11 +202,11 @@ void PostFX::SetParameter(const std::string& Name, float X, float Y, float Z, fl
GLCheck(glUseProgramObjectARB(myShaderProgram));
// Get parameter location and assign it new values
GLint Location = glGetUniformLocationARB(myShaderProgram, Name.c_str());
if (Location != -1)
GLCheck(glUniform4fARB(Location, X, Y, Z, W));
GLint location = glGetUniformLocationARB(myShaderProgram, name.c_str());
if (location != -1)
GLCheck(glUniform4fARB(location, x, y, z, w));
else
std::cerr << "Parameter \"" << Name << "\" not found in post-effect" << std::endl;
std::cerr << "Parameter \"" << name << "\" not found in post-effect" << std::endl;
// Disable program
GLCheck(glUseProgramObjectARB(0));
@ -217,41 +217,41 @@ void PostFX::SetParameter(const std::string& Name, float X, float Y, float Z, fl
////////////////////////////////////////////////////////////
/// Set a texture parameter
////////////////////////////////////////////////////////////
void PostFX::SetTexture(const std::string& Name, const Image* Texture)
void PostFX::SetTexture(const std::string& name, const Image* texture)
{
// Check that the current texture unit is available
GLint MaxUnits;
GLCheck(glGetIntegerv(GL_MAX_TEXTURE_COORDS_ARB, &MaxUnits));
if (myTextures.size() >= static_cast<std::size_t>(MaxUnits))
GLint maxUnits;
GLCheck(glGetIntegerv(GL_MAX_TEXTURE_COORDS_ARB, &maxUnits));
if (myTextures.size() >= static_cast<std::size_t>(maxUnits))
{
std::cerr << "Impossible to use texture \"" << Name << "\" for post-effect : all available texture units are used" << std::endl;
std::cerr << "Impossible to use texture \"" << name << "\" for post-effect : all available texture units are used" << std::endl;
return;
}
// Make sure the given name is a valid variable in the effect
int Location = glGetUniformLocationARB(myShaderProgram, Name.c_str());
if (Location == -1)
int location = glGetUniformLocationARB(myShaderProgram, name.c_str());
if (location == -1)
{
std::cerr << "Texture \"" << Name << "\" not found in post-effect" << std::endl;
std::cerr << "Texture \"" << name << "\" not found in post-effect" << std::endl;
return;
}
// Store the texture for later use
myTextures[Name] = Texture ? Texture : &myFrameBuffer;
myTextures[name] = texture ? texture : &myFrameBuffer;
}
////////////////////////////////////////////////////////////
/// Assignment operator
////////////////////////////////////////////////////////////
PostFX& PostFX::operator =(const PostFX& Other)
PostFX& PostFX::operator =(const PostFX& other)
{
PostFX Temp(Other);
PostFX temp(other);
std::swap(myShaderProgram, Temp.myShaderProgram);
std::swap(myTextures, Temp.myTextures);
std::swap(myFragmentShader, Temp.myFragmentShader);
std::swap(myFrameBuffer, Temp.myFrameBuffer);
std::swap(myShaderProgram, temp.myShaderProgram);
std::swap(myTextures, temp.myTextures);
std::swap(myFragmentShader, temp.myFragmentShader);
std::swap(myFrameBuffer, temp.myFrameBuffer);
return *this;
}
@ -275,7 +275,7 @@ bool PostFX::CanUsePostFX()
////////////////////////////////////////////////////////////
/// /see Drawable::Render
////////////////////////////////////////////////////////////
void PostFX::Render(RenderTarget& Target) const
void PostFX::Render(RenderTarget& target) const
{
// Check that we have a valid program
if (!myShaderProgram)
@ -283,25 +283,25 @@ void PostFX::Render(RenderTarget& Target) const
// Copy the current framebuffer pixels to our frame buffer texture
// The ugly cast is temporary until PostFx are rewritten :)
myFrameBuffer.CopyScreen((RenderWindow&)Target);
myFrameBuffer.CopyScreen((RenderWindow&)target);
// Enable program
GLCheck(glUseProgramObjectARB(myShaderProgram));
// Bind textures
TextureTable::const_iterator ItTex = myTextures.begin();
TextureTable::const_iterator it = myTextures.begin();
for (std::size_t i = 0; i < myTextures.size(); ++i)
{
int Location = glGetUniformLocationARB(myShaderProgram, ItTex->first.c_str());
GLCheck(glUniform1iARB(Location, static_cast<GLint>(i)));
int location = glGetUniformLocationARB(myShaderProgram, it->first.c_str());
GLCheck(glUniform1iARB(location, static_cast<GLint>(i)));
GLCheck(glActiveTextureARB(static_cast<GLenum>(GL_TEXTURE0_ARB + i)));
ItTex->second->Bind();
ItTex++;
it->second->Bind();
it++;
}
// Compute the texture coordinates (in case the texture is larger than the screen, or flipped)
IntRect FrameBufferRect(0, 0, myFrameBuffer.GetWidth(), myFrameBuffer.GetHeight());
FloatRect TexCoords = myFrameBuffer.GetTexCoords(FrameBufferRect);
IntRect frameBufferRect(0, 0, myFrameBuffer.GetWidth(), myFrameBuffer.GetHeight());
FloatRect texCoords = myFrameBuffer.GetTexCoords(frameBufferRect);
// Set the projection matrix to the identity so that the screen coordinates are in the range [-1, 1]
GLCheck(glMatrixMode(GL_PROJECTION));
@ -309,10 +309,10 @@ void PostFX::Render(RenderTarget& Target) const
// Render a fullscreen quad using the effect on our framebuffer
glBegin(GL_QUADS);
glTexCoord2f(TexCoords.Left, TexCoords.Top); glVertex2f(-1, 1);
glTexCoord2f(TexCoords.Right, TexCoords.Top); glVertex2f( 1, 1);
glTexCoord2f(TexCoords.Right, TexCoords.Bottom); glVertex2f( 1, -1);
glTexCoord2f(TexCoords.Left, TexCoords.Bottom); glVertex2f(-1, -1);
glTexCoord2f(texCoords.Left, texCoords.Top); glVertex2f(-1, 1);
glTexCoord2f(texCoords.Right, texCoords.Top); glVertex2f( 1, 1);
glTexCoord2f(texCoords.Right, texCoords.Bottom); glVertex2f( 1, -1);
glTexCoord2f(texCoords.Left, texCoords.Bottom); glVertex2f(-1, -1);
glEnd();
// Disable program
@ -332,78 +332,78 @@ void PostFX::Render(RenderTarget& Target) const
/// Preprocess a SFML effect file
/// to convert it to a valid GLSL fragment shader
////////////////////////////////////////////////////////////
std::string PostFX::PreprocessEffect(std::istream& File)
std::string PostFX::PreprocessEffect(std::istream& file)
{
// Initialize output string
std::set<std::string> myTextures;
std::string Out = "";
std::set<std::string> textures;
std::string out = "";
// Variable declarations
std::string Line;
while (std::getline(File, Line) && (Line.substr(0, 6) != "effect"))
std::string line;
while (std::getline(file, line) && (line.substr(0, 6) != "effect"))
{
// Remove the ending '\r', if any
if (!Line.empty() && (Line[Line.size() - 1] == '\r'))
Line.erase(Line.size() - 1);
if (!line.empty() && (line[line.size() - 1] == '\r'))
line.erase(line.size() - 1);
// Skip empty lines
if (Line == "")
if (line == "")
continue;
// Extract variables type and name and convert them
std::string Type, Name;
std::istringstream iss(Line);
if (!(iss >> Type >> Name))
std::string type, name;
std::istringstream iss(line);
if (!(iss >> type >> name))
{
std::cerr << "Post-effect error : invalid declaration (should be \"[type][name]\")" << std::endl
<< "> " << Line << std::endl;
<< "> " << line << std::endl;
return "";
}
if (Type == "texture")
if (type == "texture")
{
// Textures need some checking and conversion
if (myTextures.find(Name) != myTextures.end())
if (textures.find(name) != textures.end())
{
std::cerr << "Post-effect error : texture \"" << Name << "\" already exists" << std::endl;
std::cerr << "Post-effect error : texture \"" << name << "\" already exists" << std::endl;
return "";
}
Out += "uniform sampler2D " + Name + ";\n";
myTextures.insert(Name);
out += "uniform sampler2D " + name + ";\n";
textures.insert(name);
}
else
{
// Other types are just copied to output with "uniform" prefix
Out += "uniform " + Type + " " + Name + ";\n";
out += "uniform " + type + " " + name + ";\n";
}
}
// Effect code
Out += "void main()\n";
while (std::getline(File, Line))
out += "void main()\n";
while (std::getline(file, line))
{
// Replace any texture lookup "T(" by "texture2D(T, "
for (std::set<std::string>::const_iterator i = myTextures.begin(); i != myTextures.end(); ++i)
for (std::set<std::string>::const_iterator it = textures.begin(); it != textures.end(); ++it)
{
std::string::size_type Pos = Line.find(*i);
if (Pos != std::string::npos)
Line.replace(Pos, i->size() + 1, "texture2D(" + *i + ", ");
std::string::size_type pos = line.find(*it);
if (pos != std::string::npos)
line.replace(pos, it->size() + 1, "texture2D(" + *it + ", ");
}
// Replace "_in" by "gl_TexCoord[0].xy"
for (std::string::size_type Pos = Line.find("_in"); Pos != std::string::npos; Pos = Line.find("_in"))
Line.replace(Pos, 3, "gl_TexCoord[0].xy");
for (std::string::size_type pos = line.find("_in"); pos != std::string::npos; pos = line.find("_in"))
line.replace(pos, 3, "gl_TexCoord[0].xy");
// Replace "_out" by "gl_FragColor"
for (std::string::size_type Pos = Line.find("_out"); Pos != std::string::npos; Pos = Line.find("_out"))
Line.replace(Pos, 4, "gl_FragColor");
for (std::string::size_type pos = line.find("_out"); pos != std::string::npos; pos = line.find("_out"))
line.replace(pos, 4, "gl_FragColor");
// Write modified line to output string
Out += Line + "\n";
out += line + "\n";
}
return Out;
return out;
}
@ -424,7 +424,7 @@ void PostFX::CreateProgram()
GLCheck(glDeleteObjectARB(myShaderProgram));
// Define vertex shader source (we provide it directly as it doesn't have to change)
static const std::string VertexShaderSrc =
static const std::string vertexShaderSrc =
"void main()"
"{"
" gl_TexCoord[0] = gl_MultiTexCoord0;"
@ -435,66 +435,66 @@ void PostFX::CreateProgram()
myShaderProgram = glCreateProgramObjectARB();
// Create the shaders
GLhandleARB VertexShader = glCreateShaderObjectARB(GL_VERTEX_SHADER_ARB);
GLhandleARB FragmentShader = glCreateShaderObjectARB(GL_FRAGMENT_SHADER_ARB);
GLhandleARB vertexShader = glCreateShaderObjectARB(GL_VERTEX_SHADER_ARB);
GLhandleARB fragmentShader = glCreateShaderObjectARB(GL_FRAGMENT_SHADER_ARB);
// Compile them
const char* VertexSrc = VertexShaderSrc.c_str();
const char* FragmentSrc = myFragmentShader.c_str();
GLCheck(glShaderSourceARB(VertexShader, 1, &VertexSrc, NULL));
GLCheck(glShaderSourceARB(FragmentShader, 1, &FragmentSrc, NULL));
GLCheck(glCompileShaderARB(VertexShader));
GLCheck(glCompileShaderARB(FragmentShader));
const char* vertexSrc = vertexShaderSrc.c_str();
const char* fragmentSrc = myFragmentShader.c_str();
GLCheck(glShaderSourceARB(vertexShader, 1, &vertexSrc, NULL));
GLCheck(glShaderSourceARB(fragmentShader, 1, &fragmentSrc, NULL));
GLCheck(glCompileShaderARB(vertexShader));
GLCheck(glCompileShaderARB(fragmentShader));
// Check the compile logs
GLint Success;
GLCheck(glGetObjectParameterivARB(VertexShader, GL_OBJECT_COMPILE_STATUS_ARB, &Success));
if (Success == GL_FALSE)
GLint success;
GLCheck(glGetObjectParameterivARB(vertexShader, GL_OBJECT_COMPILE_STATUS_ARB, &success));
if (success == GL_FALSE)
{
char CompileLog[1024];
GLCheck(glGetInfoLogARB(VertexShader, sizeof(CompileLog), 0, CompileLog));
char log[1024];
GLCheck(glGetInfoLogARB(vertexShader, sizeof(log), 0, log));
std::cerr << "Failed to compile post-effect :" << std::endl
<< CompileLog << std::endl;
GLCheck(glDeleteObjectARB(VertexShader));
GLCheck(glDeleteObjectARB(FragmentShader));
<< log << std::endl;
GLCheck(glDeleteObjectARB(vertexShader));
GLCheck(glDeleteObjectARB(fragmentShader));
GLCheck(glDeleteObjectARB(myShaderProgram));
myShaderProgram = 0;
return;
}
GLCheck(glGetObjectParameterivARB(FragmentShader, GL_OBJECT_COMPILE_STATUS_ARB, &Success));
if (Success == GL_FALSE)
GLCheck(glGetObjectParameterivARB(fragmentShader, GL_OBJECT_COMPILE_STATUS_ARB, &success));
if (success == GL_FALSE)
{
char CompileLog[1024];
GLCheck(glGetInfoLogARB(FragmentShader, sizeof(CompileLog), 0, CompileLog));
char log[1024];
GLCheck(glGetInfoLogARB(fragmentShader, sizeof(log), 0, log));
std::cerr << "Failed to compile post-effect :" << std::endl
<< CompileLog << std::endl;
GLCheck(glDeleteObjectARB(VertexShader));
GLCheck(glDeleteObjectARB(FragmentShader));
<< log << std::endl;
GLCheck(glDeleteObjectARB(vertexShader));
GLCheck(glDeleteObjectARB(fragmentShader));
GLCheck(glDeleteObjectARB(myShaderProgram));
myShaderProgram = 0;
return;
}
// Attach the shaders to the program
GLCheck(glAttachObjectARB(myShaderProgram, VertexShader));
GLCheck(glAttachObjectARB(myShaderProgram, FragmentShader));
GLCheck(glAttachObjectARB(myShaderProgram, vertexShader));
GLCheck(glAttachObjectARB(myShaderProgram, fragmentShader));
// We can now delete the shaders
GLCheck(glDeleteObjectARB(VertexShader));
GLCheck(glDeleteObjectARB(FragmentShader));
GLCheck(glDeleteObjectARB(vertexShader));
GLCheck(glDeleteObjectARB(fragmentShader));
// Link the program
GLCheck(glLinkProgramARB(myShaderProgram));
// Get link log
GLCheck(glGetObjectParameterivARB(myShaderProgram, GL_OBJECT_LINK_STATUS_ARB, &Success));
if (Success == GL_FALSE)
GLCheck(glGetObjectParameterivARB(myShaderProgram, GL_OBJECT_LINK_STATUS_ARB, &success));
if (success == GL_FALSE)
{
// Oops... link errors
char LinkLog[1024];
GLCheck(glGetInfoLogARB(myShaderProgram, sizeof(LinkLog), 0, LinkLog));
char log[1024];
GLCheck(glGetInfoLogARB(myShaderProgram, sizeof(log), 0, log));
std::cerr << "Failed to link post-effect :" << std::endl
<< LinkLog << std::endl;
<< log << std::endl;
GLCheck(glDeleteObjectARB(myShaderProgram));
myShaderProgram = 0;
return;

View file

@ -56,7 +56,7 @@ RenderImage::~RenderImage()
////////////////////////////////////////////////////////////
/// Create the render image from its dimensions
////////////////////////////////////////////////////////////
bool RenderImage::Create(unsigned int Width, unsigned int Height, bool DepthBuffer)
bool RenderImage::Create(unsigned int width, unsigned int height, bool depthBuffer)
{
// Make sure that render-images are supported
if (!CanUseRenderImage())
@ -66,7 +66,7 @@ bool RenderImage::Create(unsigned int Width, unsigned int Height, bool DepthBuff
}
// Create the image
if (!myImage.Create(Width, Height))
if (!myImage.Create(width, height))
{
std::cerr << "Impossible to create render image (failed to create the target image)" << std::endl;
return false;
@ -89,7 +89,7 @@ bool RenderImage::Create(unsigned int Width, unsigned int Height, bool DepthBuff
}
// Initialize the render image
if (!myRenderImage->Create(Width, Height, myImage.myTexture, DepthBuffer))
if (!myRenderImage->Create(width, height, myImage.myTexture, depthBuffer))
return false;
// We can now initialize the render target part
@ -103,13 +103,13 @@ bool RenderImage::Create(unsigned int Width, unsigned int Height, bool DepthBuff
/// Activate of deactivate the render-image as the current target
/// for rendering
////////////////////////////////////////////////////////////
bool RenderImage::SetActive(bool Active)
bool RenderImage::SetActive(bool active)
{
if (myRenderImage && myRenderImage->Activate(Active))
if (myRenderImage && myRenderImage->Activate(active))
{
// After the RenderImage has been modified, we have to notify
// the underlying image that its pixels have changed
if (!Active)
if (!active)
myImage.ExternalUpdate(*this);
return true;
@ -163,18 +163,18 @@ bool RenderImage::CanUseRenderImage()
/// This function is called automatically by the image when it
/// needs to update its pixels, and is only meant for internal use.
////////////////////////////////////////////////////////////
bool RenderImage::UpdateImage(Image& Target)
bool RenderImage::UpdateImage(Image& target)
{
return myRenderImage && myRenderImage->UpdateTexture(Target.myTexture);
return myRenderImage && myRenderImage->UpdateTexture(target.myTexture);
}
////////////////////////////////////////////////////////////
/// Activate / deactivate the render image for rendering
////////////////////////////////////////////////////////////
bool RenderImage::Activate(bool Active)
bool RenderImage::Activate(bool active)
{
return SetActive(Active);
return SetActive(active);
}
} // namespace sf

View file

@ -51,33 +51,33 @@ public :
////////////////////////////////////////////////////////////
/// Create the render image
///
/// \param Width : Width of the image to render to
/// \param Height : Height of the image to render to
/// \param TextureId : OpenGL texture identifier of the target image
/// \param DepthBuffer : Do you want a depth buffer attached ?
/// \param width : Width of the image to render to
/// \param height : Height of the image to render to
/// \param textureId : OpenGL texture identifier of the target image
/// \param depthBuffer : Do you want a depth buffer attached ?
///
/// \return True if creation has been successful
///
////////////////////////////////////////////////////////////
virtual bool Create(unsigned int Width, unsigned int Height, unsigned int TextureId, bool DepthBuffer) = 0;
virtual bool Create(unsigned int width, unsigned int height, unsigned int textureId, bool depthBuffer) = 0;
////////////////////////////////////////////////////////////
/// Activate / deactivate the render image for rendering
///
/// \param Active : True to activate, false to deactivate
/// \param active : True to activate, false to deactivate
///
////////////////////////////////////////////////////////////
virtual bool Activate(bool Active) = 0;
virtual bool Activate(bool active) = 0;
////////////////////////////////////////////////////////////
/// Update the pixels of the target texture
///
/// \param TextureId : OpenGL identifier of the target texture
/// \param textureId : OpenGL identifier of the target texture
///
/// \return True if the new pixels are flipped vertically
///
////////////////////////////////////////////////////////////
virtual bool UpdateTexture(unsigned int TextureId) = 0;
virtual bool UpdateTexture(unsigned int textureId) = 0;
};
} // namespace priv

View file

@ -54,15 +54,15 @@ RenderImageImplFBO::~RenderImageImplFBO()
// Destroy the depth buffer
if (myDepthBuffer)
{
GLuint DepthBuffer = static_cast<GLuint>(myDepthBuffer);
GLCheck(glDeleteFramebuffersEXT(1, &DepthBuffer));
GLuint depthBuffer = static_cast<GLuint>(myDepthBuffer);
GLCheck(glDeleteFramebuffersEXT(1, &depthBuffer));
}
// Destroy the frame buffer
if (myFrameBuffer)
{
GLuint FrameBuffer = static_cast<GLuint>(myFrameBuffer);
GLCheck(glDeleteFramebuffersEXT(1, &FrameBuffer));
GLuint frameBuffer = static_cast<GLuint>(myFrameBuffer);
GLCheck(glDeleteFramebuffersEXT(1, &frameBuffer));
}
}
@ -82,14 +82,14 @@ bool RenderImageImplFBO::IsSupported()
////////////////////////////////////////////////////////////
/// /see RenderImageImpl::Create
////////////////////////////////////////////////////////////
bool RenderImageImplFBO::Create(unsigned int Width, unsigned int Height, unsigned int TextureId, bool DepthBuffer)
bool RenderImageImplFBO::Create(unsigned int width, unsigned int height, unsigned int textureId, bool depthBuffer)
{
// Create the framebuffer object if not already done
if (!myFrameBuffer)
{
GLuint FrameBuffer = 0;
GLCheck(glGenFramebuffersEXT(1, &FrameBuffer));
myFrameBuffer = static_cast<unsigned int>(FrameBuffer);
GLuint frameBuffer = 0;
GLCheck(glGenFramebuffersEXT(1, &frameBuffer));
myFrameBuffer = static_cast<unsigned int>(frameBuffer);
if (!myFrameBuffer)
{
std::cerr << "Impossible to create render image (failed to create the frame buffer object)" << std::endl;
@ -103,26 +103,26 @@ bool RenderImageImplFBO::Create(unsigned int Width, unsigned int Height, unsigne
// Create the depth buffer
if (myDepthBuffer)
{
GLuint DepthBuffer = static_cast<GLuint>(myDepthBuffer);
GLCheck(glDeleteRenderbuffersEXT(1, &DepthBuffer));
GLuint depth = static_cast<GLuint>(myDepthBuffer);
GLCheck(glDeleteRenderbuffersEXT(1, &depth));
}
if (DepthBuffer)
if (depthBuffer)
{
GLuint DepthBuffer = 0;
GLCheck(glGenRenderbuffersEXT(1, &DepthBuffer));
myDepthBuffer = static_cast<unsigned int>(DepthBuffer);
GLuint depth = 0;
GLCheck(glGenRenderbuffersEXT(1, &depth));
myDepthBuffer = static_cast<unsigned int>(depth);
if (!myDepthBuffer)
{
std::cerr << "Impossible to create render image (failed to create the attached depth buffer)" << std::endl;
return false;
}
GLCheck(glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, myDepthBuffer));
GLCheck(glRenderbufferStorageEXT(GL_RENDERBUFFER_EXT, GL_DEPTH_COMPONENT, Width, Height));
GLCheck(glRenderbufferStorageEXT(GL_RENDERBUFFER_EXT, GL_DEPTH_COMPONENT, width, height));
GLCheck(glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, myDepthBuffer));
}
// Link the image to the frame buffer
GLCheck(glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_2D, TextureId, 0));
GLCheck(glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_2D, textureId, 0));
// A final check, just to be sure...
if (glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT) != GL_FRAMEBUFFER_COMPLETE_EXT)
@ -142,9 +142,9 @@ bool RenderImageImplFBO::Create(unsigned int Width, unsigned int Height, unsigne
////////////////////////////////////////////////////////////
/// /see RenderImageImpl::Activate
////////////////////////////////////////////////////////////
bool RenderImageImplFBO::Activate(bool Active)
bool RenderImageImplFBO::Activate(bool active)
{
if (Active)
if (active)
{
// Bind the buffers
GLCheck(glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, myFrameBuffer));
@ -164,7 +164,7 @@ bool RenderImageImplFBO::Activate(bool Active)
////////////////////////////////////////////////////////////
/// /see RenderImageImpl::UpdateTexture
////////////////////////////////////////////////////////////
bool RenderImageImplFBO::UpdateTexture(unsigned int /*TextureId*/)
bool RenderImageImplFBO::UpdateTexture(unsigned int)
{
// Nothing to do: the FBO draws directly into the target image
return true;

View file

@ -69,19 +69,19 @@ private :
/// /see RenderImageImpl::Create
///
////////////////////////////////////////////////////////////
virtual bool Create(unsigned int Width, unsigned int Height, unsigned int TextureId, bool DepthBuffer);
virtual bool Create(unsigned int width, unsigned int height, unsigned int textureId, bool depthBuffer);
////////////////////////////////////////////////////////////
/// /see RenderImageImpl::Activate
///
////////////////////////////////////////////////////////////
virtual bool Activate(bool Active);
virtual bool Activate(bool active);
////////////////////////////////////////////////////////////
/// /see RenderImageImpl::UpdateTexture
///
////////////////////////////////////////////////////////////
virtual bool UpdateTexture(unsigned TextureId);
virtual bool UpdateTexture(unsigned textureId);
////////////////////////////////////////////////////////////
// Member data

View file

@ -57,12 +57,12 @@ RenderTarget::~RenderTarget()
////////////////////////////////////////////////////////////
/// Clear the entire target with a single color
////////////////////////////////////////////////////////////
void RenderTarget::Clear(const Color& FillColor)
void RenderTarget::Clear(const Color& color)
{
if (Activate(true))
{
// Clear the frame buffer
GLCheck(glClearColor(FillColor.r / 255.f, FillColor.g / 255.f, FillColor.b / 255.f, FillColor.a / 255.f));
GLCheck(glClearColor(color.r / 255.f, color.g / 255.f, color.b / 255.f, color.a / 255.f));
GLCheck(glClear(GL_COLOR_BUFFER_BIT));
Activate(false);
@ -73,7 +73,7 @@ void RenderTarget::Clear(const Color& FillColor)
////////////////////////////////////////////////////////////
/// Draw something on the window
////////////////////////////////////////////////////////////
void RenderTarget::Draw(const Drawable& Object)
void RenderTarget::Draw(const Drawable& object)
{
// Check whether we are called from the outside or from a previous call to Draw
if (!myIsDrawing)
@ -94,12 +94,12 @@ void RenderTarget::Draw(const Drawable& Object)
}
// Setup the viewport
const FloatRect& Viewport = myCurrentView->GetViewport();
int Left = static_cast<int>(0.5f + GetWidth() * Viewport.Left);
int Top = static_cast<int>(0.5f + GetHeight() * (1.f - Viewport.Bottom));
int Width = static_cast<int>(0.5f + GetWidth() * Viewport.GetSize().x);
int Height = static_cast<int>(0.5f + GetHeight() * Viewport.GetSize().y);
GLCheck(glViewport(Left, Top, Width, Height));
const FloatRect& viewport = myCurrentView->GetViewport();
int left = static_cast<int>(0.5f + GetWidth() * viewport.Left);
int top = static_cast<int>(0.5f + GetHeight() * (1.f - viewport.Bottom));
int width = static_cast<int>(0.5f + GetWidth() * viewport.GetSize().x);
int height = static_cast<int>(0.5f + GetHeight() * viewport.GetSize().y);
GLCheck(glViewport(left, top, width, height));
// Setup the transform matrices
GLCheck(glMatrixMode(GL_PROJECTION));
@ -108,7 +108,7 @@ void RenderTarget::Draw(const Drawable& Object)
GLCheck(glLoadIdentity());
// Let the object draw itself
Object.Draw(*this);
object.Draw(*this);
// Restore render states
if (myPreserveStates)
@ -127,7 +127,7 @@ void RenderTarget::Draw(const Drawable& Object)
else
{
// We are already called from a previous Draw : we don't need to set the states again, just draw the object
Object.Draw(*this);
object.Draw(*this);
}
}
@ -135,9 +135,9 @@ void RenderTarget::Draw(const Drawable& Object)
////////////////////////////////////////////////////////////
/// Change the current active view
////////////////////////////////////////////////////////////
void RenderTarget::SetView(const View& NewView)
void RenderTarget::SetView(const View& view)
{
myCurrentView = &NewView;
myCurrentView = &view;
}
@ -167,9 +167,9 @@ View& RenderTarget::GetDefaultView()
/// SFML to do internal optimizations and improve performances.
/// This parameter is false by default
////////////////////////////////////////////////////////////
void RenderTarget::PreserveOpenGLStates(bool Preserve)
void RenderTarget::PreserveOpenGLStates(bool preserve)
{
myPreserveStates = Preserve;
myPreserveStates = preserve;
}

View file

@ -46,18 +46,18 @@ RenderWindow::RenderWindow()
////////////////////////////////////////////////////////////
/// Construct the window
////////////////////////////////////////////////////////////
RenderWindow::RenderWindow(VideoMode Mode, const std::string& Title, unsigned long WindowStyle, const ContextSettings& Settings)
RenderWindow::RenderWindow(VideoMode mode, const std::string& title, unsigned long style, const ContextSettings& settings)
{
Create(Mode, Title, WindowStyle, Settings);
Create(mode, title, style, settings);
}
////////////////////////////////////////////////////////////
/// Construct the window from an existing control
////////////////////////////////////////////////////////////
RenderWindow::RenderWindow(WindowHandle Handle, const ContextSettings& Settings)
RenderWindow::RenderWindow(WindowHandle handle, const ContextSettings& settings)
{
Create(Handle, Settings);
Create(handle, settings);
}
@ -73,10 +73,10 @@ RenderWindow::~RenderWindow()
////////////////////////////////////////////////////////////
/// /see RenderTarget::Activate
////////////////////////////////////////////////////////////
bool RenderWindow::Activate(bool Active)
bool RenderWindow::Activate(bool active)
{
// For performances and consistency reasons, we only handle activation
if (Active)
if (active)
return SetActive();
else
return true;
@ -107,28 +107,28 @@ unsigned int RenderWindow::GetHeight() const
Image RenderWindow::Capture() const
{
// Get the window dimensions
const unsigned int Width = GetWidth();
const unsigned int Height = GetHeight();
const unsigned int width = GetWidth();
const unsigned int height = GetHeight();
// Set our window as the current target for rendering
if (SetActive())
{
// Get pixels from the backbuffer
std::vector<Uint8> Pixels(Width * Height * 4);
Uint8* PixelsPtr = &Pixels[0];
GLCheck(glReadPixels(0, 0, Width, Height, GL_RGBA, GL_UNSIGNED_BYTE, PixelsPtr));
std::vector<Uint8> pixels(width * height * 4);
Uint8* ptr = &pixels[0];
GLCheck(glReadPixels(0, 0, width, height, GL_RGBA, GL_UNSIGNED_BYTE, ptr));
// Flip the pixels
unsigned int Pitch = Width * 4;
for (unsigned int y = 0; y < Height / 2; ++y)
std::swap_ranges(PixelsPtr + y * Pitch, PixelsPtr + (y + 1) * Pitch, PixelsPtr + (Height - y - 1) * Pitch);
unsigned int pitch = width * 4;
for (unsigned int y = 0; y < height / 2; ++y)
std::swap_ranges(ptr + y * pitch, ptr + (y + 1) * pitch, ptr + (height - y - 1) * pitch);
// Create an image from the pixel buffer and return it
return Image(Width, Height, PixelsPtr);
return Image(width, height, ptr);
}
else
{
return Image(Width, Height, Color::White);
return Image(width, height, Color::White);
}
}
@ -137,9 +137,9 @@ Image RenderWindow::Capture() const
/// Convert a point in window coordinates into view coordinates
/// This version uses the current view of the window
////////////////////////////////////////////////////////////
sf::Vector2f RenderWindow::ConvertCoords(unsigned int WindowX, unsigned int WindowY) const
sf::Vector2f RenderWindow::ConvertCoords(unsigned int x, unsigned int y) const
{
return ConvertCoords(WindowX, WindowY, GetView());
return ConvertCoords(x, y, GetView());
}
@ -147,21 +147,21 @@ sf::Vector2f RenderWindow::ConvertCoords(unsigned int WindowX, unsigned int Wind
/// Convert a point in window coordinates into view coordinates
/// This version uses the given view
////////////////////////////////////////////////////////////
sf::Vector2f RenderWindow::ConvertCoords(unsigned int WindowX, unsigned int WindowY, const View& TargetView) const
sf::Vector2f RenderWindow::ConvertCoords(unsigned int x, unsigned int y, const View& view) const
{
// First, convert from viewport coordinates to homogeneous coordinates
const FloatRect& Viewport = TargetView.GetViewport();
int Left = static_cast<int>(0.5f + GetWidth() * Viewport.Left);
int Top = static_cast<int>(0.5f + GetHeight() * Viewport.Top);
int Width = static_cast<int>(0.5f + GetWidth() * Viewport.GetSize().x);
int Height = static_cast<int>(0.5f + GetHeight() * Viewport.GetSize().y);
const FloatRect& viewport = view.GetViewport();
int left = static_cast<int>(0.5f + GetWidth() * viewport.Left);
int top = static_cast<int>(0.5f + GetHeight() * viewport.Top);
int width = static_cast<int>(0.5f + GetWidth() * viewport.GetSize().x);
int height = static_cast<int>(0.5f + GetHeight() * viewport.GetSize().y);
Vector2f Coords;
Coords.x = -1.f + 2.f * (static_cast<int>(WindowX) - Left) / Width;
Coords.y = 1.f - 2.f * (static_cast<int>(WindowY) - Top) / Height;
Vector2f coords;
coords.x = -1.f + 2.f * (static_cast<int>(x) - left) / width;
coords.y = 1.f - 2.f * (static_cast<int>(y) - top) / height;
// Then transform by the inverse of the view matrix
return TargetView.GetInverseMatrix().Transform(Coords);
return view.GetInverseMatrix().Transform(coords);
}

View file

@ -49,18 +49,18 @@ myIsCompiled (false)
////////////////////////////////////////////////////////////
/// Add a point to the shape
////////////////////////////////////////////////////////////
void Shape::AddPoint(float X, float Y, const Color& Col, const Color& OutlineCol)
void Shape::AddPoint(float x, float y, const Color& color, const Color& outlineColor)
{
AddPoint(Vector2f(X, Y), Col, OutlineCol);
AddPoint(Vector2f(x, y), color, outlineColor);
}
////////////////////////////////////////////////////////////
/// Add a point to the shape
////////////////////////////////////////////////////////////
void Shape::AddPoint(const Vector2f& Position, const Color& Col, const Color& OutlineCol)
void Shape::AddPoint(const Vector2f& position, const Color& color, const Color& outlineColor)
{
myPoints.push_back(Point(Position, Col, OutlineCol));
myPoints.push_back(Point(position, color, outlineColor));
myIsCompiled = false;
}
@ -78,9 +78,9 @@ unsigned int Shape::GetNbPoints() const
/// Enable or disable filling the shape.
/// Fill is enabled by default
////////////////////////////////////////////////////////////
void Shape::EnableFill(bool Enable)
void Shape::EnableFill(bool enable)
{
myIsFillEnabled = Enable;
myIsFillEnabled = enable;
}
@ -88,18 +88,18 @@ void Shape::EnableFill(bool Enable)
/// Enable or disable drawing the shape outline.
/// Outline is enabled by default
////////////////////////////////////////////////////////////
void Shape::EnableOutline(bool Enable)
void Shape::EnableOutline(bool enable)
{
myIsOutlineEnabled = Enable;
myIsOutlineEnabled = enable;
}
////////////////////////////////////////////////////////////
/// Set the position of a point
////////////////////////////////////////////////////////////
void Shape::SetPointPosition(unsigned int Index, const Vector2f& Position)
void Shape::SetPointPosition(unsigned int index, const Vector2f& position)
{
myPoints[Index + 1].Position = Position;
myPoints[index + 1].Position = position;
myIsCompiled = false;
}
@ -107,18 +107,18 @@ void Shape::SetPointPosition(unsigned int Index, const Vector2f& Position)
////////////////////////////////////////////////////////////
/// Set the position of a point
////////////////////////////////////////////////////////////
void Shape::SetPointPosition(unsigned int Index, float X, float Y)
void Shape::SetPointPosition(unsigned int index, float x, float y)
{
SetPointPosition(Index, Vector2f(X, Y));
SetPointPosition(index, Vector2f(x, y));
}
////////////////////////////////////////////////////////////
/// Set the color of a point
////////////////////////////////////////////////////////////
void Shape::SetPointColor(unsigned int Index, const Color& Col)
void Shape::SetPointColor(unsigned int index, const Color& color)
{
myPoints[Index + 1].Col = Col;
myPoints[index + 1].Col = color;
myIsCompiled = false;
}
@ -126,9 +126,9 @@ void Shape::SetPointColor(unsigned int Index, const Color& Col)
////////////////////////////////////////////////////////////
/// Set the outline color of a point
////////////////////////////////////////////////////////////
void Shape::SetPointOutlineColor(unsigned int Index, const Color& OutlineCol)
void Shape::SetPointOutlineColor(unsigned int index, const Color& outlineColor)
{
myPoints[Index + 1].OutlineCol = OutlineCol;
myPoints[index + 1].OutlineCol = outlineColor;
myIsCompiled = false;
}
@ -136,36 +136,36 @@ void Shape::SetPointOutlineColor(unsigned int Index, const Color& OutlineCol)
////////////////////////////////////////////////////////////
/// Change the width of the shape outline
////////////////////////////////////////////////////////////
void Shape::SetOutlineWidth(float Width)
void Shape::SetOutlineWidth(float width)
{
myOutline = Width;
myOutline = width;
}
////////////////////////////////////////////////////////////
/// Get the position of a point
////////////////////////////////////////////////////////////
const Vector2f& Shape::GetPointPosition(unsigned int Index) const
const Vector2f& Shape::GetPointPosition(unsigned int index) const
{
return myPoints[Index + 1].Position;
return myPoints[index + 1].Position;
}
////////////////////////////////////////////////////////////
/// Get the color of a point
////////////////////////////////////////////////////////////
const Color& Shape::GetPointColor(unsigned int Index) const
const Color& Shape::GetPointColor(unsigned int index) const
{
return myPoints[Index + 1].Col;
return myPoints[index + 1].Col;
}
////////////////////////////////////////////////////////////
/// Get the outline color of a point
////////////////////////////////////////////////////////////
const Color& Shape::GetPointOutlineColor(unsigned int Index) const
const Color& Shape::GetPointOutlineColor(unsigned int index) const
{
return myPoints[Index + 1].OutlineCol;
return myPoints[index + 1].OutlineCol;
}
@ -181,101 +181,100 @@ float Shape::GetOutlineWidth() const
////////////////////////////////////////////////////////////
/// Create a shape made of a single line
////////////////////////////////////////////////////////////
Shape Shape::Line(float P1X, float P1Y, float P2X, float P2Y, float Thickness, const Color& Col, float Outline, const Color& OutlineCol)
Shape Shape::Line(float p1x, float p1y, float p2x, float p2y, float thickness, const Color& color, float outline, const Color& outlineColor)
{
Vector2f P1(P1X, P1Y);
Vector2f P2(P2X, P2Y);
Vector2f p1(p1x, p1y);
Vector2f p2(p2x, p2y);
// Compute the extrusion direction
Vector2f Normal;
ComputeNormal(P1, P2, Normal);
Normal *= Thickness / 2;
// Create the shape's points
Shape S;
S.AddPoint(P1 - Normal, Col, OutlineCol);
S.AddPoint(P2 - Normal, Col, OutlineCol);
S.AddPoint(P2 + Normal, Col, OutlineCol);
S.AddPoint(P1 + Normal, Col, OutlineCol);
S.SetOutlineWidth(Outline);
// Compile it
S.Compile();
return S;
return Shape::Line(p1, p2, thickness, color, outline, outlineColor);
}
////////////////////////////////////////////////////////////
/// Create a shape made of a single line (use vectors)
////////////////////////////////////////////////////////////
Shape Shape::Line(const Vector2f& P1, const Vector2f& P2, float Thickness, const Color& Col, float Outline, const Color& OutlineCol)
Shape Shape::Line(const Vector2f& p1, const Vector2f& p2, float thickness, const Color& color, float outline, const Color& outlineColor)
{
return Shape::Line(P1.x, P1.y, P2.x, P2.y, Thickness, Col, Outline, OutlineCol);
// Compute the extrusion direction
Vector2f normal;
ComputeNormal(p1, p2, normal);
normal *= thickness / 2;
// Create the shape's points
Shape shape;
shape.AddPoint(p1 - normal, color, outlineColor);
shape.AddPoint(p2 - normal, color, outlineColor);
shape.AddPoint(p2 + normal, color, outlineColor);
shape.AddPoint(p1 + normal, color, outlineColor);
shape.SetOutlineWidth(outline);
// Compile it
shape.Compile();
return shape;
}
////////////////////////////////////////////////////////////
/// Create a shape made of a single rectangle
////////////////////////////////////////////////////////////
Shape Shape::Rectangle(float P1X, float P1Y, float P2X, float P2Y, const Color& Col, float Outline, const Color& OutlineCol)
Shape Shape::Rectangle(float p1x, float p1y, float p2x, float p2y, const Color& color, float outline, const Color& outlineColor)
{
// Create the shape's points
Shape S;
S.AddPoint(Vector2f(P1X, P1Y), Col, OutlineCol);
S.AddPoint(Vector2f(P2X, P1Y), Col, OutlineCol);
S.AddPoint(Vector2f(P2X, P2Y), Col, OutlineCol);
S.AddPoint(Vector2f(P1X, P2Y), Col, OutlineCol);
S.SetOutlineWidth(Outline);
Shape shape;
shape.AddPoint(Vector2f(p1x, p1y), color, outlineColor);
shape.AddPoint(Vector2f(p2x, p1y), color, outlineColor);
shape.AddPoint(Vector2f(p2x, p2y), color, outlineColor);
shape.AddPoint(Vector2f(p1x, p2y), color, outlineColor);
shape.SetOutlineWidth(outline);
// Compile it
S.Compile();
shape.Compile();
return S;
return shape;
}
////////////////////////////////////////////////////////////
/// Create a shape made of a single rectangle (use vectors)
////////////////////////////////////////////////////////////
Shape Shape::Rectangle(const Vector2f& P1, const Vector2f& P2, const Color& Col, float Outline, const Color& OutlineCol)
Shape Shape::Rectangle(const Vector2f& p1, const Vector2f& p2, const Color& color, float outline, const Color& outlineColor)
{
return Shape::Rectangle(P1.x, P1.y, P2.x, P2.y, Col, Outline, OutlineCol);
return Shape::Rectangle(p1.x, p1.y, p2.x, p2.y, color, outline, outlineColor);
}
////////////////////////////////////////////////////////////
/// Create a shape made of a single circle
////////////////////////////////////////////////////////////
Shape Shape::Circle(float X, float Y, float Radius, const Color& Col, float Outline, const Color& OutlineCol)
Shape Shape::Circle(float x, float y, float radius, const Color& color, float outline, const Color& outlineColor)
{
static const int NbSegments = 40;
// Create the points set
Shape S;
Vector2f Center(X, Y);
for (int i = 0; i < NbSegments; ++i)
{
float Angle = i * 2 * 3.141592654f / NbSegments;
Vector2f Offset(cos(Angle), sin(Angle));
S.AddPoint(Center + Offset * Radius, Col, OutlineCol);
}
// Compile it
S.SetOutlineWidth(Outline);
S.Compile();
return S;
return Shape::Circle(Vector2f(x, y), radius, color, outline, outlineColor);
}
////////////////////////////////////////////////////////////
/// Create a shape made of a single circle (use vectors)
////////////////////////////////////////////////////////////
Shape Shape::Circle(const Vector2f& Center, float Radius, const Color& Col, float Outline, const Color& OutlineCol)
Shape Shape::Circle(const Vector2f& center, float radius, const Color& color, float outline, const Color& outlineColor)
{
return Shape::Circle(Center.x, Center.y, Radius, Col, Outline, OutlineCol);
static const int nbSegments = 40;
// Create the points set
Shape shape;
for (int i = 0; i < nbSegments; ++i)
{
float angle = i * 2 * 3.141592654f / nbSegments;
Vector2f offset(cos(angle), sin(angle));
shape.AddPoint(center + offset * radius, color, outlineColor);
}
// Compile it
shape.SetOutlineWidth(outline);
shape.Compile();
return shape;
}
@ -302,14 +301,14 @@ void Shape::Render(RenderTarget&) const
{
for (std::vector<Point>::const_iterator i = myPoints.begin(); i != myPoints.end(); ++i)
{
Color PointColor = i->Col * GetColor();
glColor4f(PointColor.r / 255.f, PointColor.g / 255.f, PointColor.b / 255.f, PointColor.a / 255.f);
Color color = i->Col * GetColor();
glColor4f(color.r / 255.f, color.g / 255.f, color.b / 255.f, color.a / 255.f);
glVertex2f(i->Position.x, i->Position.y);
}
// Close the shape by duplicating the first point at the end
Color PointColor = myPoints[1].Col * GetColor();
glColor4f(PointColor.r / 255.f, PointColor.g / 255.f, PointColor.b / 255.f, PointColor.a / 255.f);
Color color = myPoints[1].Col * GetColor();
glColor4f(color.r / 255.f, color.g / 255.f, color.b / 255.f, color.a / 255.f);
glVertex2f(myPoints[1].Position.x, myPoints[1].Position.y);
}
glEnd();
@ -322,18 +321,18 @@ void Shape::Render(RenderTarget&) const
{
for (std::size_t i = 1; i < myPoints.size(); ++i)
{
Color PointColor = myPoints[i].OutlineCol * GetColor();
glColor4f(PointColor.r / 255.f, PointColor.g / 255.f, PointColor.b / 255.f, PointColor.a / 255.f);
Color color = myPoints[i].OutlineCol * GetColor();
glColor4f(color.r / 255.f, color.g / 255.f, color.b / 255.f, color.a / 255.f);
glVertex2f(myPoints[i].Position.x, myPoints[i].Position.y);
glColor4f(PointColor.r / 255.f, PointColor.g / 255.f, PointColor.b / 255.f, PointColor.a / 255.f);
glColor4f(color.r / 255.f, color.g / 255.f, color.b / 255.f, color.a / 255.f);
glVertex2f(myPoints[i].Position.x + myPoints[i].Normal.x * myOutline, myPoints[i].Position.y + myPoints[i].Normal.y * myOutline);
}
// Close the shape by duplicating the first point at the end
Color PointColor = myPoints[1].OutlineCol * GetColor();
glColor4f(PointColor.r / 255.f, PointColor.g / 255.f, PointColor.b / 255.f, PointColor.a / 255.f);
Color color = myPoints[1].OutlineCol * GetColor();
glColor4f(color.r / 255.f, color.g / 255.f, color.b / 255.f, color.a / 255.f);
glVertex2f(myPoints[1].Position.x, myPoints[1].Position.y);
glColor4f(PointColor.r / 255.f, PointColor.g / 255.f, PointColor.b / 255.f, PointColor.a / 255.f);
glColor4f(color.r / 255.f, color.g / 255.f, color.b / 255.f, color.a / 255.f);
glVertex2f(myPoints[1].Position.x + myPoints[1].Normal.x * myOutline, myPoints[1].Position.y + myPoints[1].Normal.y * myOutline);
}
glEnd();
@ -347,44 +346,44 @@ void Shape::Render(RenderTarget&) const
void Shape::Compile()
{
// Compute the center
float NbPoints = static_cast<float>(myPoints.size() - 1);
float R = 0, G = 0, B = 0, A = 0;
Point Center(Vector2f(0, 0), Color(0, 0, 0, 0));
float nbPoints = static_cast<float>(myPoints.size() - 1);
float r = 0, g = 0, b = 0, a = 0;
Point center(Vector2f(0, 0), Color(0, 0, 0, 0));
for (std::size_t i = 1; i < myPoints.size(); ++i)
{
Center.Position += myPoints[i].Position / NbPoints;
R += myPoints[i].Col.r / NbPoints;
G += myPoints[i].Col.g / NbPoints;
B += myPoints[i].Col.b / NbPoints;
A += myPoints[i].Col.a / NbPoints;
center.Position += myPoints[i].Position / nbPoints;
r += myPoints[i].Col.r / nbPoints;
g += myPoints[i].Col.g / nbPoints;
b += myPoints[i].Col.b / nbPoints;
a += myPoints[i].Col.a / nbPoints;
}
Center.Col.r = static_cast<Uint8>(R);
Center.Col.g = static_cast<Uint8>(G);
Center.Col.b = static_cast<Uint8>(B);
Center.Col.a = static_cast<Uint8>(A);
myPoints[0] = Center;
center.Col.r = static_cast<Uint8>(r);
center.Col.g = static_cast<Uint8>(g);
center.Col.b = static_cast<Uint8>(b);
center.Col.a = static_cast<Uint8>(a);
myPoints[0] = center;
// Compute the outline
for (std::size_t i = 1; i < myPoints.size(); ++i)
{
// Get the two segments shared by the current point
Point& P0 = (i == 1) ? myPoints[myPoints.size() - 1] : myPoints[i - 1];
Point& P1 = myPoints[i];
Point& P2 = (i == myPoints.size() - 1) ? myPoints[1] : myPoints[i + 1];
Point& p0 = (i == 1) ? myPoints[myPoints.size() - 1] : myPoints[i - 1];
Point& p1 = myPoints[i];
Point& p2 = (i == myPoints.size() - 1) ? myPoints[1] : myPoints[i + 1];
// Compute their normal
Vector2f Normal1, Normal2;
if (!ComputeNormal(P0.Position, P1.Position, Normal1) || !ComputeNormal(P1.Position, P2.Position, Normal2))
Vector2f normal1, normal2;
if (!ComputeNormal(p0.Position, p1.Position, normal1) || !ComputeNormal(p1.Position, p2.Position, normal2))
continue;
// Add them to get the extrusion direction
float Factor = 1.f + (Normal1.x * Normal2.x + Normal1.y * Normal2.y);
P1.Normal = (Normal1 + Normal2) / Factor;
float factor = 1.f + (normal1.x * normal2.x + normal1.y * normal2.y);
p1.Normal = (normal1 + normal2) / factor;
// Make sure it points towards the outside of the shape
float Dot = (P1.Position.x - Center.Position.x) * P1.Normal.x + (P1.Position.y - Center.Position.y) * P1.Normal.y;
if (Dot < 0)
P1.Normal = -P1.Normal;
float dot = (p1.Position.x - center.Position.x) * p1.Normal.x + (p1.Position.y - center.Position.y) * p1.Normal.y;
if (dot < 0)
p1.Normal = -p1.Normal;
}
myIsCompiled = true;
@ -394,17 +393,17 @@ void Shape::Compile()
////////////////////////////////////////////////////////////
/// Compute the normal of a given 2D segment
////////////////////////////////////////////////////////////
bool Shape::ComputeNormal(const Vector2f& P1, const Vector2f& P2, Vector2f& Normal)
bool Shape::ComputeNormal(const Vector2f& p1, const Vector2f& p2, Vector2f& normal)
{
Normal.x = P1.y - P2.y;
Normal.y = P2.x - P1.x;
normal.x = p1.y - p2.y;
normal.y = p2.x - p1.x;
float Len = sqrt(Normal.x * Normal.x + Normal.y * Normal.y);
if (Len == 0.f)
float len = sqrt(normal.x * normal.x + normal.y * normal.y);
if (len == 0.f)
return false;
Normal.x /= Len;
Normal.y /= Len;
normal.x /= len;
normal.y /= len;
return true;
}
@ -413,11 +412,11 @@ bool Shape::ComputeNormal(const Vector2f& P1, const Vector2f& P2, Vector2f& Norm
////////////////////////////////////////////////////////////
/// Default constructor for Point
////////////////////////////////////////////////////////////
Shape::Point::Point(const Vector2f& Pos, const Color& C, const Color& OutlineC) :
Position (Pos),
Shape::Point::Point(const Vector2f& position, const Color& color, const Color& outlineColor) :
Position (position),
Normal (0.f, 0.f),
Col (C),
OutlineCol(OutlineC)
Col (color),
OutlineCol(outlineColor)
{
}

View file

@ -47,38 +47,38 @@ myIsFlippedY(false)
////////////////////////////////////////////////////////////
/// Construct the sprite from a source image
////////////////////////////////////////////////////////////
Sprite::Sprite(const Image& Img, const Vector2f& Position, const Vector2f& Scale, float Rotation, const Color& Col) :
Drawable (Position, Scale, Rotation, Col),
Sprite::Sprite(const Image& image, const Vector2f& position, const Vector2f& scale, float rotation, const Color& color) :
Drawable (position, scale, rotation, color),
mySubRect (0, 0, 1, 1),
myIsFlippedX(false),
myIsFlippedY(false)
{
SetImage(Img);
SetImage(image);
}
////////////////////////////////////////////////////////////
/// Set the image of the sprite
////////////////////////////////////////////////////////////
void Sprite::SetImage(const Image& Img)
void Sprite::SetImage(const Image& image)
{
// If there was no source image before and the new image is valid, adjust the source rectangle
if (!myImage && (Img.GetWidth() > 0) && (Img.GetHeight() > 0))
if (!myImage && (image.GetWidth() > 0) && (image.GetHeight() > 0))
{
SetSubRect(IntRect(0, 0, Img.GetWidth(), Img.GetHeight()));
SetSubRect(IntRect(0, 0, image.GetWidth(), image.GetHeight()));
}
// Assign the new image
myImage = &Img;
myImage = &image;
}
////////////////////////////////////////////////////////////
/// Set the sub-rectangle of the sprite inside the source image
////////////////////////////////////////////////////////////
void Sprite::SetSubRect(const IntRect& SubRect)
void Sprite::SetSubRect(const IntRect& rectangle)
{
mySubRect = SubRect;
mySubRect = rectangle;
}
@ -86,13 +86,13 @@ void Sprite::SetSubRect(const IntRect& SubRect)
/// Resize the sprite (by changing its scale factors) (take 2 values).
/// The default size is defined by the subrect
////////////////////////////////////////////////////////////
void Sprite::Resize(float Width, float Height)
void Sprite::Resize(float width, float height)
{
int LocalWidth = mySubRect.GetSize().x;
int LocalHeight = mySubRect.GetSize().y;
int localWidth = mySubRect.GetSize().x;
int localHeight = mySubRect.GetSize().y;
if ((LocalWidth > 0) && (LocalHeight > 0))
SetScale(Width / LocalWidth, Height / LocalHeight);
if ((localWidth > 0) && (localHeight > 0))
SetScale(width / localWidth, height / localHeight);
}
@ -100,27 +100,27 @@ void Sprite::Resize(float Width, float Height)
/// Resize the object (by changing its scale factors) (take a 2D vector)
/// The default size is defined by the subrect
////////////////////////////////////////////////////////////
void Sprite::Resize(const Vector2f& Size)
void Sprite::Resize(const Vector2f& size)
{
Resize(Size.x, Size.y);
Resize(size.x, size.y);
}
////////////////////////////////////////////////////////////
/// Flip the sprite horizontally
////////////////////////////////////////////////////////////
void Sprite::FlipX(bool Flipped)
void Sprite::FlipX(bool flipped)
{
myIsFlippedX = Flipped;
myIsFlippedX = flipped;
}
////////////////////////////////////////////////////////////
/// Flip the sprite vertically
////////////////////////////////////////////////////////////
void Sprite::FlipY(bool Flipped)
void Sprite::FlipY(bool flipped)
{
myIsFlippedY = Flipped;
myIsFlippedY = flipped;
}
@ -155,17 +155,17 @@ Vector2f Sprite::GetSize() const
/// Get the color of a given pixel in the sprite
/// (point is in local coordinates)
////////////////////////////////////////////////////////////
Color Sprite::GetPixel(unsigned int X, unsigned int Y) const
Color Sprite::GetPixel(unsigned int x, unsigned int y) const
{
if (myImage)
{
unsigned int ImageX = mySubRect.Left + X;
unsigned int ImageY = mySubRect.Top + Y;
unsigned int imageX = mySubRect.Left + x;
unsigned int imageY = mySubRect.Top + y;
if (myIsFlippedX) ImageX = mySubRect.GetSize().x - ImageX - 1;
if (myIsFlippedY) ImageY = mySubRect.GetSize().y - ImageY - 1;
if (myIsFlippedX) imageX = mySubRect.GetSize().x - imageX - 1;
if (myIsFlippedY) imageY = mySubRect.GetSize().y - imageY - 1;
return myImage->GetPixel(ImageX, ImageY) * GetColor();
return myImage->GetPixel(imageX, imageY) * GetColor();
}
else
{
@ -180,8 +180,8 @@ Color Sprite::GetPixel(unsigned int X, unsigned int Y) const
void Sprite::Render(RenderTarget&) const
{
// Get the sprite size
float Width = static_cast<float>(mySubRect.GetSize().x);
float Height = static_cast<float>(mySubRect.GetSize().y);
float width = static_cast<float>(mySubRect.GetSize().x);
float height = static_cast<float>(mySubRect.GetSize().y);
// Check if the image is valid
if (myImage && (myImage->GetWidth() > 0) && (myImage->GetHeight() > 0))
@ -190,18 +190,18 @@ void Sprite::Render(RenderTarget&) const
myImage->Bind();
// Calculate the texture coordinates
FloatRect TexCoords = myImage->GetTexCoords(mySubRect);
FloatRect Rect(myIsFlippedX ? TexCoords.Right : TexCoords.Left,
myIsFlippedY ? TexCoords.Bottom : TexCoords.Top,
myIsFlippedX ? TexCoords.Left : TexCoords.Right,
myIsFlippedY ? TexCoords.Top : TexCoords.Bottom);
FloatRect texCoords = myImage->GetTexCoords(mySubRect);
FloatRect rect(myIsFlippedX ? texCoords.Right : texCoords.Left,
myIsFlippedY ? texCoords.Bottom : texCoords.Top,
myIsFlippedX ? texCoords.Left : texCoords.Right,
myIsFlippedY ? texCoords.Top : texCoords.Bottom);
// Draw the sprite's triangles
glBegin(GL_QUADS);
glTexCoord2f(Rect.Left, Rect.Top); glVertex2f(0, 0);
glTexCoord2f(Rect.Left, Rect.Bottom); glVertex2f(0, Height);
glTexCoord2f(Rect.Right, Rect.Bottom); glVertex2f(Width, Height);
glTexCoord2f(Rect.Right, Rect.Top); glVertex2f(Width, 0) ;
glTexCoord2f(rect.Left, rect.Top); glVertex2f(0, 0);
glTexCoord2f(rect.Left, rect.Bottom); glVertex2f(0, height);
glTexCoord2f(rect.Right, rect.Bottom); glVertex2f(width, height);
glTexCoord2f(rect.Right, rect.Top); glVertex2f(width, 0) ;
glEnd();
}
else
@ -212,9 +212,9 @@ void Sprite::Render(RenderTarget&) const
// Draw the sprite's triangles
glBegin(GL_QUADS);
glVertex2f(0, 0);
glVertex2f(0, Height);
glVertex2f(Width, Height);
glVertex2f(Width, 0);
glVertex2f(0, height);
glVertex2f(width, height);
glVertex2f(width, 0);
glEnd();
}
}

View file

@ -49,35 +49,35 @@ myNeedRectUpdate(true)
////////////////////////////////////////////////////////////
/// Construct the string from any kind of text
////////////////////////////////////////////////////////////
String::String(const Unicode::Text& Text, const Font& CharFont, float Size) :
myFont (&CharFont),
mySize (Size),
String::String(const Unicode::Text& text, const Font& font, float size) :
myFont (&font),
mySize (size),
myStyle (Regular),
myNeedRectUpdate(true)
{
SetText(Text);
SetText(text);
}
////////////////////////////////////////////////////////////
/// Set the text (from any kind of string)
////////////////////////////////////////////////////////////
void String::SetText(const Unicode::Text& Text)
void String::SetText(const Unicode::Text& text)
{
myNeedRectUpdate = true;
myText = Text;
myText = text;
}
////////////////////////////////////////////////////////////
/// Set the font of the string
////////////////////////////////////////////////////////////
void String::SetFont(const Font& CharFont)
void String::SetFont(const Font& font)
{
if (myFont != &CharFont)
if (myFont != &font)
{
myNeedRectUpdate = true;
myFont = &CharFont;
myFont = &font;
}
}
@ -85,12 +85,12 @@ void String::SetFont(const Font& CharFont)
////////////////////////////////////////////////////////////
/// Set the size of the string
////////////////////////////////////////////////////////////
void String::SetSize(float Size)
void String::SetSize(float size)
{
if (mySize != Size)
if (mySize != size)
{
myNeedRectUpdate = true;
mySize = Size;
mySize = size;
}
}
@ -99,12 +99,12 @@ void String::SetSize(float Size)
/// Set the style of the text
/// The default style is Regular
////////////////////////////////////////////////////////////
void String::SetStyle(unsigned long TextStyle)
void String::SetStyle(unsigned long style)
{
if (myStyle != TextStyle)
if (myStyle != style)
{
myNeedRectUpdate = true;
myStyle = TextStyle;
myStyle = style;
}
}
@ -150,42 +150,42 @@ unsigned long String::GetStyle() const
/// in coordinates relative to the string
/// (note : translation, center, rotation and scale are not applied)
////////////////////////////////////////////////////////////
sf::Vector2f String::GetCharacterPos(std::size_t Index) const
sf::Vector2f String::GetCharacterPos(std::size_t index) const
{
// First get the UTF32 representation of the text
const Unicode::UTF32String& Text = myText;
const Unicode::UTF32String& text = myText;
// Adjust the index if it's out of range
if (Index > Text.length())
Index = Text.length();
if (index > text.length())
index = text.length();
// The final size is based on the text size
float FactorX = mySize / myFont->GetCharacterSize();
float AdvanceY = mySize;
float factor = mySize / myFont->GetCharacterSize();
float advanceY = mySize;
// Compute the position
sf::Vector2f Position;
for (std::size_t i = 0; i < Index; ++i)
sf::Vector2f position;
for (std::size_t i = 0; i < index; ++i)
{
// Get the current character and its corresponding glyph
Uint32 CurChar = Text[i];
const Glyph& CurGlyph = myFont->GetGlyph(CurChar);
float AdvanceX = CurGlyph.Advance * FactorX;
Uint32 curChar = text[i];
const Glyph& curGlyph = myFont->GetGlyph(curChar);
float advanceX = curGlyph.Advance * factor;
switch (CurChar)
switch (curChar)
{
// Handle special characters
case L' ' : Position.x += AdvanceX; break;
case L'\t' : Position.x += AdvanceX * 4; break;
case L'\v' : Position.y += AdvanceY * 4; break;
case L'\n' : Position.y += AdvanceY; Position.x = 0; break;
case L' ' : position.x += advanceX; break;
case L'\t' : position.x += advanceX * 4; break;
case L'\v' : position.y += advanceY * 4; break;
case L'\n' : position.y += advanceY; position.x = 0; break;
// Regular character : just add its advance value
default : Position.x += AdvanceX; break;
default : position.x += advanceX; break;
}
}
return Position;
return position;
}
@ -197,13 +197,13 @@ FloatRect String::GetRect() const
if (myNeedRectUpdate)
const_cast<String*>(this)->RecomputeRect();
FloatRect Rect;
Rect.Left = (myBaseRect.Left - GetOrigin().x) * GetScale().x + GetPosition().x;
Rect.Top = (myBaseRect.Top - GetOrigin().y) * GetScale().y + GetPosition().y;
Rect.Right = (myBaseRect.Right - GetOrigin().x) * GetScale().x + GetPosition().x;
Rect.Bottom = (myBaseRect.Bottom - GetOrigin().y) * GetScale().y + GetPosition().y;
FloatRect rect;
rect.Left = (myBaseRect.Left - GetOrigin().x) * GetScale().x + GetPosition().x;
rect.Top = (myBaseRect.Top - GetOrigin().y) * GetScale().y + GetPosition().y;
rect.Right = (myBaseRect.Right - GetOrigin().x) * GetScale().x + GetPosition().x;
rect.Bottom = (myBaseRect.Bottom - GetOrigin().y) * GetScale().y + GetPosition().y;
return Rect;
return rect;
}
@ -213,83 +213,83 @@ FloatRect String::GetRect() const
void String::Render(RenderTarget&) const
{
// First get the internal UTF-32 string of the text
const Unicode::UTF32String& Text = myText;
const Unicode::UTF32String& text = myText;
// No text, no rendering :)
if (Text.empty())
if (text.empty())
return;
// Set the scaling factor to get the actual size
float CharSize = static_cast<float>(myFont->GetCharacterSize());
float Factor = mySize / CharSize;
GLCheck(glScalef(Factor, Factor, 1.f));
float charSize = static_cast<float>(myFont->GetCharacterSize());
float factor = mySize / charSize;
GLCheck(glScalef(factor, factor, 1.f));
// Bind the font texture
myFont->GetImage().Bind();
// Initialize the rendering coordinates
float X = 0.f;
float Y = CharSize;
float x = 0.f;
float y = charSize;
// Holds the lines to draw later, for underlined style
std::vector<float> UnderlineCoords;
UnderlineCoords.reserve(16);
std::vector<float> underlineCoords;
underlineCoords.reserve(16);
// Compute the shearing to apply if we're using the italic style
float ItalicCoeff = (myStyle & Italic) ? 0.208f : 0.f; // 12 degrees
float italicCoeff = (myStyle & Italic) ? 0.208f : 0.f; // 12 degrees
// Draw one quad for each character
glBegin(GL_QUADS);
for (std::size_t i = 0; i < Text.size(); ++i)
for (std::size_t i = 0; i < text.size(); ++i)
{
// Get the current character and its corresponding glyph
Uint32 CurChar = Text[i];
const Glyph& CurGlyph = myFont->GetGlyph(CurChar);
int Advance = CurGlyph.Advance;
const IntRect& Rect = CurGlyph.Rectangle;
const FloatRect& Coord = CurGlyph.TexCoords;
Uint32 curChar = text[i];
const Glyph& curGlyph = myFont->GetGlyph(curChar);
int advance = curGlyph.Advance;
const IntRect& rect = curGlyph.Rectangle;
const FloatRect& coord = curGlyph.TexCoords;
// If we're using the underlined style and there's a new line,
// we keep track of the previous line to draw it later
if ((CurChar == L'\n') && (myStyle & Underlined))
if ((curChar == L'\n') && (myStyle & Underlined))
{
UnderlineCoords.push_back(X);
UnderlineCoords.push_back(Y + 2);
underlineCoords.push_back(x);
underlineCoords.push_back(y + 2);
}
// Handle special characters
switch (CurChar)
switch (curChar)
{
case L' ' : X += Advance; continue;
case L'\n' : Y += CharSize; X = 0; continue;
case L'\t' : X += Advance * 4; continue;
case L'\v' : Y += CharSize * 4; continue;
case L' ' : x += advance; continue;
case L'\n' : y += charSize; x = 0; continue;
case L'\t' : x += advance * 4; continue;
case L'\v' : y += charSize * 4; continue;
}
// Draw a textured quad for the current character
glTexCoord2f(Coord.Left, Coord.Top); glVertex2f(X + Rect.Left - ItalicCoeff * Rect.Top, Y + Rect.Top);
glTexCoord2f(Coord.Left, Coord.Bottom); glVertex2f(X + Rect.Left - ItalicCoeff * Rect.Bottom, Y + Rect.Bottom);
glTexCoord2f(Coord.Right, Coord.Bottom); glVertex2f(X + Rect.Right - ItalicCoeff * Rect.Bottom, Y + Rect.Bottom);
glTexCoord2f(Coord.Right, Coord.Top); glVertex2f(X + Rect.Right - ItalicCoeff * Rect.Top, Y + Rect.Top);
glTexCoord2f(coord.Left, coord.Top); glVertex2f(x + rect.Left - italicCoeff * rect.Top, y + rect.Top);
glTexCoord2f(coord.Left, coord.Bottom); glVertex2f(x + rect.Left - italicCoeff * rect.Bottom, y + rect.Bottom);
glTexCoord2f(coord.Right, coord.Bottom); glVertex2f(x + rect.Right - italicCoeff * rect.Bottom, y + rect.Bottom);
glTexCoord2f(coord.Right, coord.Top); glVertex2f(x + rect.Right - italicCoeff * rect.Top, y + rect.Top);
// If we're using the bold style, we must render the character 4 more times,
// slightly offseted, to simulate a higher weight
if (myStyle & Bold)
{
static const float OffsetsX[] = {-0.5f, 0.5f, 0.f, 0.f};
static const float OffsetsY[] = {0.f, 0.f, -0.5f, 0.5f};
static const float offsetsX[] = {-0.5f, 0.5f, 0.f, 0.f};
static const float offsetsY[] = {0.f, 0.f, -0.5f, 0.5f};
for (int j = 0; j < 4; ++j)
{
glTexCoord2f(Coord.Left, Coord.Top); glVertex2f(X + OffsetsX[j] + Rect.Left - ItalicCoeff * Rect.Top, Y + OffsetsY[j] + Rect.Top);
glTexCoord2f(Coord.Left, Coord.Bottom); glVertex2f(X + OffsetsX[j] + Rect.Left - ItalicCoeff * Rect.Bottom, Y + OffsetsY[j] + Rect.Bottom);
glTexCoord2f(Coord.Right, Coord.Bottom); glVertex2f(X + OffsetsX[j] + Rect.Right - ItalicCoeff * Rect.Bottom, Y + OffsetsY[j] + Rect.Bottom);
glTexCoord2f(Coord.Right, Coord.Top); glVertex2f(X + OffsetsX[j] + Rect.Right - ItalicCoeff * Rect.Top, Y + OffsetsY[j] + Rect.Top);
glTexCoord2f(coord.Left, coord.Top); glVertex2f(x + offsetsX[j] + rect.Left - italicCoeff * rect.Top, y + offsetsY[j] + rect.Top);
glTexCoord2f(coord.Left, coord.Bottom); glVertex2f(x + offsetsX[j] + rect.Left - italicCoeff * rect.Bottom, y + offsetsY[j] + rect.Bottom);
glTexCoord2f(coord.Right, coord.Bottom); glVertex2f(x + offsetsX[j] + rect.Right - italicCoeff * rect.Bottom, y + offsetsY[j] + rect.Bottom);
glTexCoord2f(coord.Right, coord.Top); glVertex2f(x + offsetsX[j] + rect.Right - italicCoeff * rect.Top, y + offsetsY[j] + rect.Top);
}
}
// Advance to the next character
X += Advance;
x += advance;
}
glEnd();
@ -297,21 +297,21 @@ void String::Render(RenderTarget&) const
if (myStyle & Underlined)
{
// Compute the line thickness
float Thickness = (myStyle & Bold) ? 3.f : 2.f;
float thickness = (myStyle & Bold) ? 3.f : 2.f;
// Add the last line (which was not finished with a \n)
UnderlineCoords.push_back(X);
UnderlineCoords.push_back(Y + 2);
underlineCoords.push_back(x);
underlineCoords.push_back(y + 2);
// Draw the underlines as quads
GLCheck(glDisable(GL_TEXTURE_2D));
glBegin(GL_QUADS);
for (std::size_t i = 0; i < UnderlineCoords.size(); i += 2)
for (std::size_t i = 0; i < underlineCoords.size(); i += 2)
{
glVertex2f(0, UnderlineCoords[i + 1]);
glVertex2f(0, UnderlineCoords[i + 1] + Thickness);
glVertex2f(UnderlineCoords[i], UnderlineCoords[i + 1] + Thickness);
glVertex2f(UnderlineCoords[i], UnderlineCoords[i + 1]);
glVertex2f(0, underlineCoords[i + 1]);
glVertex2f(0, underlineCoords[i + 1] + thickness);
glVertex2f(underlineCoords[i], underlineCoords[i + 1] + thickness);
glVertex2f(underlineCoords[i], underlineCoords[i + 1]);
}
glEnd();
}
@ -324,89 +324,89 @@ void String::Render(RenderTarget&) const
void String::RecomputeRect()
{
// First get the internal UTF-32 string of the text
const Unicode::UTF32String& Text = myText;
const Unicode::UTF32String& text = myText;
// Reset the "need update" state
myNeedRectUpdate = false;
// No text, empty box :)
if (Text.empty())
if (text.empty())
{
myBaseRect = FloatRect(0, 0, 0, 0);
return;
}
// Initial values
float CurWidth = 0;
float CurHeight = 0;
float Width = 0;
float Height = 0;
float Factor = mySize / myFont->GetCharacterSize();
float curWidth = 0;
float curHeight = 0;
float width = 0;
float height = 0;
float factor = mySize / myFont->GetCharacterSize();
// Go through each character
for (std::size_t i = 0; i < Text.size(); ++i)
for (std::size_t i = 0; i < text.size(); ++i)
{
// Get the current character and its corresponding glyph
Uint32 CurChar = Text[i];
const Glyph& CurGlyph = myFont->GetGlyph(CurChar);
float Advance = CurGlyph.Advance * Factor;
const IntRect& Rect = CurGlyph.Rectangle;
Uint32 curChar = text[i];
const Glyph& curGlyph = myFont->GetGlyph(curChar);
float advance = curGlyph.Advance * factor;
const IntRect& rect = curGlyph.Rectangle;
// Handle special characters
switch (CurChar)
switch (curChar)
{
case L' ' : CurWidth += Advance; continue;
case L'\t' : CurWidth += Advance * 4; continue;
case L'\v' : Height += mySize * 4; CurHeight = 0; continue;
case L' ' : curWidth += advance; continue;
case L'\t' : curWidth += advance * 4; continue;
case L'\v' : height += mySize * 4; curHeight = 0; continue;
case L'\n' :
Height += mySize;
CurHeight = 0;
if (CurWidth > Width)
Width = CurWidth;
CurWidth = 0;
height += mySize;
curHeight = 0;
if (curWidth > width)
width = curWidth;
curWidth = 0;
continue;
}
// Advance to the next character
CurWidth += Advance;
curWidth += advance;
// Update the maximum height
float CharHeight = (myFont->GetCharacterSize() + Rect.Bottom) * Factor;
if (CharHeight > CurHeight)
CurHeight = CharHeight;
float charHeight = (myFont->GetCharacterSize() + rect.Bottom) * factor;
if (charHeight > curHeight)
curHeight = charHeight;
}
// Update the last line
if (CurWidth > Width)
Width = CurWidth;
Height += CurHeight;
if (curWidth > width)
width = curWidth;
height += curHeight;
// Add a slight width / height if we're using the bold style
if (myStyle & Bold)
{
Width += 1 * Factor;
Height += 1 * Factor;
width += 1 * factor;
height += 1 * factor;
}
// Add a slight width if we're using the italic style
if (myStyle & Italic)
{
Width += 0.208f * mySize;
width += 0.208f * mySize;
}
// Add a slight height if we're using the underlined style
if (myStyle & Underlined)
{
if (CurHeight < mySize + 4 * Factor)
Height += 4 * Factor;
if (curHeight < mySize + 4 * factor)
height += 4 * factor;
}
// Finally update the rectangle
myBaseRect.Left = 0;
myBaseRect.Top = 0;
myBaseRect.Right = Width;
myBaseRect.Bottom = Height;
myBaseRect.Right = width;
myBaseRect.Bottom = height;
}
} // namespace sf

View file

@ -49,7 +49,7 @@ myNeedInvUpdate(true)
////////////////////////////////////////////////////////////
/// Construct the view from a rectangle
////////////////////////////////////////////////////////////
View::View(const FloatRect& Rectangle) :
View::View(const FloatRect& rectangle) :
myCenter (),
mySize (),
myRotation (0),
@ -57,16 +57,16 @@ myViewport (0, 0, 1, 1),
myNeedUpdate (true),
myNeedInvUpdate(true)
{
Reset(Rectangle);
Reset(rectangle);
}
////////////////////////////////////////////////////////////
/// Construct the view from its center and size
////////////////////////////////////////////////////////////
View::View(const Vector2f& Center, const Vector2f& Size) :
myCenter (Center),
mySize (Size),
View::View(const Vector2f& center, const Vector2f& size) :
myCenter (center),
mySize (size),
myRotation (0),
myViewport (0, 0, 1, 1),
myNeedUpdate (true),
@ -78,10 +78,10 @@ myNeedInvUpdate(true)
////////////////////////////////////////////////////////////
/// Change the center of the view
////////////////////////////////////////////////////////////
void View::SetCenter(float X, float Y)
void View::SetCenter(float x, float y)
{
myCenter.x = X;
myCenter.y = Y;
myCenter.x = x;
myCenter.y = y;
myNeedUpdate = true;
myNeedInvUpdate = true;
}
@ -90,19 +90,19 @@ void View::SetCenter(float X, float Y)
////////////////////////////////////////////////////////////
/// Change the center of the view
////////////////////////////////////////////////////////////
void View::SetCenter(const Vector2f& Center)
void View::SetCenter(const Vector2f& center)
{
SetCenter(Center.x, Center.y);
SetCenter(center.x, center.y);
}
////////////////////////////////////////////////////////////
/// Change the size of the view
////////////////////////////////////////////////////////////
void View::SetSize(float Width, float Height)
void View::SetSize(float width, float height)
{
mySize.x = Width;
mySize.y = Height;
mySize.x = width;
mySize.y = height;
myNeedUpdate = true;
myNeedInvUpdate = true;
}
@ -111,18 +111,20 @@ void View::SetSize(float Width, float Height)
////////////////////////////////////////////////////////////
/// Change the size of the view
////////////////////////////////////////////////////////////
void View::SetSize(const Vector2f& Size)
void View::SetSize(const Vector2f& size)
{
SetSize(Size.x, Size.y);
SetSize(size.x, size.y);
}
////////////////////////////////////////////////////////////
/// Set the angle of rotation of the view
////////////////////////////////////////////////////////////
void View::SetRotation(float Angle)
void View::SetRotation(float angle)
{
myRotation = Angle;
myRotation = static_cast<float>(fmod(angle, 360));
if (myRotation < 0)
myRotation += 360.f;
myNeedUpdate = true;
myNeedInvUpdate = true;
}
@ -131,19 +133,19 @@ void View::SetRotation(float Angle)
////////////////////////////////////////////////////////////
/// Set the target viewport
////////////////////////////////////////////////////////////
void View::SetViewport(const FloatRect& Viewport)
void View::SetViewport(const FloatRect& viewport)
{
myViewport = Viewport;
myViewport = viewport;
}
////////////////////////////////////////////////////////////
/// Reset the view to the given rectangle
////////////////////////////////////////////////////////////
void View::Reset(const FloatRect& Rectangle)
void View::Reset(const FloatRect& rectangle)
{
myCenter = Rectangle.GetCenter();
mySize = Rectangle.GetSize();
myCenter = rectangle.GetCenter();
mySize = rectangle.GetSize();
myNeedUpdate = true;
myNeedInvUpdate = true;
}
@ -188,44 +190,36 @@ const FloatRect& View::GetViewport() const
////////////////////////////////////////////////////////////
/// Move the view
////////////////////////////////////////////////////////////
void View::Move(float OffsetX, float OffsetY)
void View::Move(float offsetX, float offsetY)
{
myCenter.x += OffsetX;
myCenter.y += OffsetY;
myNeedUpdate = true;
myNeedInvUpdate = true;
SetCenter(myCenter.x + offsetX, myCenter.y + offsetY);
}
////////////////////////////////////////////////////////////
/// Move the view
////////////////////////////////////////////////////////////
void View::Move(const Vector2f& Offset)
void View::Move(const Vector2f& offset)
{
Move(Offset.x, Offset.y);
SetCenter(myCenter + offset);
}
////////////////////////////////////////////////////////////
/// Rotate the view
////////////////////////////////////////////////////////////
void View::Rotate(float Angle)
void View::Rotate(float angle)
{
myRotation += Angle;
myNeedUpdate = true;
myNeedInvUpdate = true;
SetRotation(myRotation + angle);
}
////////////////////////////////////////////////////////////
/// Resize the view rectangle to simulate a zoom / unzoom effect
////////////////////////////////////////////////////////////
void View::Zoom(float Factor)
void View::Zoom(float factor)
{
mySize.x *= Factor;
mySize.y *= Factor;
myNeedUpdate = true;
myNeedInvUpdate = true;
SetSize(mySize.x * factor, mySize.y * factor);
}

View file

@ -67,7 +67,7 @@ RenderImageImplPBuffer::~RenderImageImplPBuffer()
// This is to make sure that another valid context is made
// active after we destroy the P-Buffer's one
Context Ctx;
Context context;
}
@ -87,17 +87,17 @@ bool RenderImageImplPBuffer::IsSupported()
////////////////////////////////////////////////////////////
/// /see RenderImageImpl::Create
////////////////////////////////////////////////////////////
bool RenderImageImplPBuffer::Create(unsigned int Width, unsigned int Height, unsigned int /*TextureId*/, bool DepthBuffer)
bool RenderImageImplPBuffer::Create(unsigned int width, unsigned int height, unsigned int, bool depthBuffer)
{
// Store the dimensions
myWidth = Width;
myHeight = Height;
myWidth = width;
myHeight = height;
// Get the current HDC
HDC CurrentDeviceContext = wglGetCurrentDC();
HDC currentDC = wglGetCurrentDC();
// Define the minimum PBuffer attributes
int Attributes[] =
int attributes[] =
{
WGL_SUPPORT_OPENGL_ARB, GL_TRUE,
WGL_DRAW_TO_PBUFFER_ARB, GL_TRUE,
@ -105,25 +105,25 @@ bool RenderImageImplPBuffer::Create(unsigned int Width, unsigned int Height, uns
WGL_GREEN_BITS_ARB, 8,
WGL_BLUE_BITS_ARB, 8,
WGL_ALPHA_BITS_ARB, 8,
WGL_DEPTH_BITS_ARB, (DepthBuffer ? 24 : 0),
WGL_DEPTH_BITS_ARB, (depthBuffer ? 24 : 0),
WGL_DOUBLE_BUFFER_ARB, GL_FALSE,
0
};
// Select the best pixel format for our attributes
unsigned int NbFormats = 0;
int PixelFormat = -1;
wglChoosePixelFormatARB(CurrentDeviceContext, Attributes, NULL, 1, &PixelFormat, &NbFormats);
unsigned int nbFormats = 0;
int pixelFormat = -1;
wglChoosePixelFormatARB(currentDC, attributes, NULL, 1, &pixelFormat, &nbFormats);
// Make sure that one pixel format has been found
if (NbFormats == 0)
if (nbFormats == 0)
{
std::cerr << "Impossible to create render image (failed to find a suitable pixel format for PBuffer)" << std::endl;
return false;
}
// Create the P-Buffer and its OpenGL context
myPBuffer = wglCreatePbufferARB(CurrentDeviceContext, PixelFormat, Width, Height, NULL);
myPBuffer = wglCreatePbufferARB(currentDC, pixelFormat, width, height, NULL);
myDeviceContext = wglGetPbufferDCARB(myPBuffer);
myContext = wglCreateContext(myDeviceContext);
@ -135,25 +135,25 @@ bool RenderImageImplPBuffer::Create(unsigned int Width, unsigned int Height, uns
}
// Check the actual size of the P-Buffer
int ActualWidth, ActualHeight;
wglQueryPbufferARB(myPBuffer, WGL_PBUFFER_WIDTH_ARB, &ActualWidth);
wglQueryPbufferARB(myPBuffer, WGL_PBUFFER_HEIGHT_ARB, &ActualHeight);
if ((ActualWidth != static_cast<int>(Width)) || (ActualHeight != static_cast<int>(Height)))
int actualWidth, actualHeight;
wglQueryPbufferARB(myPBuffer, WGL_PBUFFER_WIDTH_ARB, &actualWidth);
wglQueryPbufferARB(myPBuffer, WGL_PBUFFER_HEIGHT_ARB, &actualHeight);
if ((actualWidth != static_cast<int>(width)) || (actualHeight != static_cast<int>(height)))
{
std::cerr << "Impossible to create render image (failed to match the requested size). "
<< "Size: " << ActualWidth << "x" << ActualHeight << " - "
<< "Requested: " << Width << "x" << Height
<< "Size: " << actualWidth << "x" << actualHeight << " - "
<< "Requested: " << width << "x" << height
<< std::endl;
return false;
}
// Share the P-Buffer context with the current context
HGLRC CurrentContext = wglGetCurrentContext();
if (CurrentContext)
HGLRC currentContext = wglGetCurrentContext();
if (currentContext)
{
wglMakeCurrent(NULL, NULL);
wglShareLists(CurrentContext, myContext);
wglMakeCurrent(CurrentDeviceContext, CurrentContext);
wglShareLists(currentContext, myContext);
wglMakeCurrent(currentDC, currentContext);
}
return true;
@ -163,9 +163,9 @@ bool RenderImageImplPBuffer::Create(unsigned int Width, unsigned int Height, uns
////////////////////////////////////////////////////////////
/// /see RenderImageImpl::Activate
////////////////////////////////////////////////////////////
bool RenderImageImplPBuffer::Activate(bool Active)
bool RenderImageImplPBuffer::Activate(bool active)
{
if (Active)
if (active)
{
if (myDeviceContext && myContext && (wglGetCurrentContext() != myContext))
{
@ -189,23 +189,23 @@ bool RenderImageImplPBuffer::Activate(bool Active)
////////////////////////////////////////////////////////////
/// /see RenderImageImpl::UpdateTexture
////////////////////////////////////////////////////////////
bool RenderImageImplPBuffer::UpdateTexture(unsigned int TextureId)
bool RenderImageImplPBuffer::UpdateTexture(unsigned int textureId)
{
// Store the current active context
HDC CurrentDeviceContext = wglGetCurrentDC();
HGLRC CurrentContext = wglGetCurrentContext();
HDC currentDC = wglGetCurrentDC();
HGLRC currentContext = wglGetCurrentContext();
if (Activate(true))
{
// Bind the texture
GLCheck(glEnable(GL_TEXTURE_2D));
GLCheck(glBindTexture(GL_TEXTURE_2D, TextureId));
GLCheck(glBindTexture(GL_TEXTURE_2D, textureId));
// Copy the rendered pixels to the image
GLCheck(glCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, 0, 0, myWidth, myHeight));
// Restore the previous context
wglMakeCurrent(CurrentDeviceContext, CurrentContext);
wglMakeCurrent(currentDC, currentContext);
return true;
}

View file

@ -70,19 +70,19 @@ private :
/// /see RenderImageImpl::Create
///
////////////////////////////////////////////////////////////
virtual bool Create(unsigned int Width, unsigned int Height, unsigned int TextureId, bool DepthBuffer);
virtual bool Create(unsigned int width, unsigned int height, unsigned int textureId, bool depthBuffer);
////////////////////////////////////////////////////////////
/// /see RenderImageImpl::Activate
///
////////////////////////////////////////////////////////////
virtual bool Activate(bool Active);
virtual bool Activate(bool active);
////////////////////////////////////////////////////////////
/// /see RenderImageImpl::UpdateTexture
///
////////////////////////////////////////////////////////////
virtual bool UpdateTexture(unsigned TextureId);
virtual bool UpdateTexture(unsigned textureId);
////////////////////////////////////////////////////////////
// Member data

View file

@ -46,7 +46,7 @@ public :
////////////////////////////////////////////////////////////
// Constructor
////////////////////////////////////////////////////////////
DataChannel(Ftp& Owner);
DataChannel(Ftp& owner);
////////////////////////////////////////////////////////////
// Destructor
@ -56,17 +56,17 @@ public :
////////////////////////////////////////////////////////////
// Open the data channel using the specified mode and port
////////////////////////////////////////////////////////////
Ftp::Response Open(Ftp::TransferMode Mode);
Ftp::Response Open(Ftp::TransferMode mode);
////////////////////////////////////////////////////////////
// Send data on the data channel
////////////////////////////////////////////////////////////
void Send(const std::vector<char>& Data);
void Send(const std::vector<char>& data);
////////////////////////////////////////////////////////////
// Receive data on the data channel until it is closed
////////////////////////////////////////////////////////////
void Receive(std::vector<char>& Data);
void Receive(std::vector<char>& data);
private :
@ -81,9 +81,9 @@ private :
////////////////////////////////////////////////////////////
/// Default constructor
////////////////////////////////////////////////////////////
Ftp::Response::Response(Status Code, const std::string& Message) :
myStatus (Code),
myMessage(Message)
Ftp::Response::Response(Status code, const std::string& message) :
myStatus (code),
myMessage(message)
{
}
@ -120,15 +120,15 @@ const std::string& Ftp::Response::GetMessage() const
////////////////////////////////////////////////////////////
/// Default constructor
////////////////////////////////////////////////////////////
Ftp::DirectoryResponse::DirectoryResponse(Ftp::Response Resp) :
Ftp::Response(Resp)
Ftp::DirectoryResponse::DirectoryResponse(Ftp::Response response) :
Ftp::Response(response)
{
if (IsOk())
{
// Extract the directory from the server response
std::string::size_type Begin = Resp.GetMessage().find('"', 0);
std::string::size_type End = Resp.GetMessage().find('"', Begin + 1);
myDirectory = Resp.GetMessage().substr(Begin + 1, End - Begin - 1);
std::string::size_type begin = response.GetMessage().find('"', 0);
std::string::size_type end = response.GetMessage().find('"', begin + 1);
myDirectory = response.GetMessage().substr(begin + 1, end - begin - 1);
}
}
@ -145,18 +145,18 @@ const std::string& Ftp::DirectoryResponse::GetDirectory() const
////////////////////////////////////////////////////////////
/// Default constructor
////////////////////////////////////////////////////////////
Ftp::ListingResponse::ListingResponse(Ftp::Response Resp, const std::vector<char>& Data) :
Ftp::Response(Resp)
Ftp::ListingResponse::ListingResponse(Ftp::Response response, const std::vector<char>& data) :
Ftp::Response(response)
{
if (IsOk())
{
// Fill the array of strings
std::string Paths(Data.begin(), Data.end());
std::string::size_type LastPos = 0;
for (std::string::size_type Pos = Paths.find("\r\n"); Pos != std::string::npos; Pos = Paths.find("\r\n", LastPos))
std::string paths(data.begin(), data.end());
std::string::size_type lastPos = 0;
for (std::string::size_type pos = paths.find("\r\n"); pos != std::string::npos; pos = paths.find("\r\n", lastPos))
{
myFilenames.push_back(Paths.substr(LastPos, Pos - LastPos));
LastPos = Pos + 2;
myFilenames.push_back(paths.substr(lastPos, pos - lastPos));
lastPos = pos + 2;
}
}
}
@ -174,9 +174,9 @@ std::size_t Ftp::ListingResponse::GetCount() const
////////////////////////////////////////////////////////////
/// Get the Index-th filename in the directory
////////////////////////////////////////////////////////////
const std::string& Ftp::ListingResponse::GetFilename(std::size_t Index) const
const std::string& Ftp::ListingResponse::GetFilename(std::size_t index) const
{
return myFilenames[Index];
return myFilenames[index];
}
@ -192,10 +192,10 @@ Ftp::~Ftp()
////////////////////////////////////////////////////////////
/// Connect to the specified FTP server
////////////////////////////////////////////////////////////
Ftp::Response Ftp::Connect(const IPAddress& Server, unsigned short Port, float Timeout)
Ftp::Response Ftp::Connect(const IPAddress& server, unsigned short port, float timeout)
{
// Connect to the server
if (myCommandSocket.Connect(Port, Server, Timeout) != Socket::Done)
if (myCommandSocket.Connect(port, server, timeout) != Socket::Done)
return Response(Response::ConnectionFailed);
// Get the response to the connection
@ -215,13 +215,13 @@ Ftp::Response Ftp::Login()
////////////////////////////////////////////////////////////
/// Log in using a username and a password
////////////////////////////////////////////////////////////
Ftp::Response Ftp::Login(const std::string& UserName, const std::string& Password)
Ftp::Response Ftp::Login(const std::string& name, const std::string& password)
{
Response Resp = SendCommand("USER", UserName);
if (Resp.IsOk())
Resp = SendCommand("PASS", Password);
Response response = SendCommand("USER", name);
if (response.IsOk())
response = SendCommand("PASS", password);
return Resp;
return response;
}
@ -231,11 +231,11 @@ Ftp::Response Ftp::Login(const std::string& UserName, const std::string& Passwor
Ftp::Response Ftp::Disconnect()
{
// Send the exit command
Response Resp = SendCommand("QUIT");
if (Resp.IsOk())
Response response = SendCommand("QUIT");
if (response.IsOk())
myCommandSocket.Close();
return Resp;
return response;
}
@ -261,36 +261,36 @@ Ftp::DirectoryResponse Ftp::GetWorkingDirectory()
/// Get the contents of the given directory
/// (subdirectories and files)
////////////////////////////////////////////////////////////
Ftp::ListingResponse Ftp::GetDirectoryListing(const std::string& Directory)
Ftp::ListingResponse Ftp::GetDirectoryListing(const std::string& directory)
{
// Open a data channel on default port (20) using ASCII transfer mode
std::vector<char> DirData;
DataChannel Data(*this);
Response Resp = Data.Open(Ascii);
if (Resp.IsOk())
std::vector<char> directoryData;
DataChannel data(*this);
Response response = data.Open(Ascii);
if (response.IsOk())
{
// Tell the server to send us the listing
Resp = SendCommand("NLST", Directory);
if (Resp.IsOk())
response = SendCommand("NLST", directory);
if (response.IsOk())
{
// Receive the listing
Data.Receive(DirData);
data.Receive(directoryData);
// Get the response from the server
Resp = GetResponse();
response = GetResponse();
}
}
return ListingResponse(Resp, DirData);
return ListingResponse(response, directoryData);
}
////////////////////////////////////////////////////////////
/// Change the current working directory
////////////////////////////////////////////////////////////
Ftp::Response Ftp::ChangeDirectory(const std::string& Directory)
Ftp::Response Ftp::ChangeDirectory(const std::string& directory)
{
return SendCommand("CWD", Directory);
return SendCommand("CWD", directory);
}
@ -306,150 +306,150 @@ Ftp::Response Ftp::ParentDirectory()
////////////////////////////////////////////////////////////
/// Create a new directory
////////////////////////////////////////////////////////////
Ftp::Response Ftp::MakeDirectory(const std::string& Name)
Ftp::Response Ftp::MakeDirectory(const std::string& name)
{
return SendCommand("MKD", Name);
return SendCommand("MKD", name);
}
////////////////////////////////////////////////////////////
/// Remove an existing directory
////////////////////////////////////////////////////////////
Ftp::Response Ftp::DeleteDirectory(const std::string& Name)
Ftp::Response Ftp::DeleteDirectory(const std::string& name)
{
return SendCommand("RMD", Name);
return SendCommand("RMD", name);
}
////////////////////////////////////////////////////////////
/// Rename a file
////////////////////////////////////////////////////////////
Ftp::Response Ftp::RenameFile(const std::string& File, const std::string& NewName)
Ftp::Response Ftp::RenameFile(const std::string& file, const std::string& newName)
{
Response Resp = SendCommand("RNFR", File);
if (Resp.IsOk())
Resp = SendCommand("RNTO", NewName);
Response response = SendCommand("RNFR", file);
if (response.IsOk())
response = SendCommand("RNTO", newName);
return Resp;
return response;
}
////////////////////////////////////////////////////////////
/// Remove an existing file
////////////////////////////////////////////////////////////
Ftp::Response Ftp::DeleteFile(const std::string& Name)
Ftp::Response Ftp::DeleteFile(const std::string& name)
{
return SendCommand("DELE", Name);
return SendCommand("DELE", name);
}
////////////////////////////////////////////////////////////
/// Download a file from the server
////////////////////////////////////////////////////////////
Ftp::Response Ftp::Download(const std::string& DistantFile, const std::string& DestPath, TransferMode Mode)
Ftp::Response Ftp::Download(const std::string& distantFile, const std::string& destPath, TransferMode mode)
{
// Open a data channel using the given transfer mode
DataChannel Data(*this);
Response Resp = Data.Open(Mode);
if (Resp.IsOk())
DataChannel data(*this);
Response response = data.Open(mode);
if (response.IsOk())
{
// Tell the server to start the transfer
Resp = SendCommand("RETR", DistantFile);
if (Resp.IsOk())
response = SendCommand("RETR", distantFile);
if (response.IsOk())
{
// Receive the file data
std::vector<char> FileData;
Data.Receive(FileData);
std::vector<char> fileData;
data.Receive(fileData);
// Get the response from the server
Resp = GetResponse();
if (Resp.IsOk())
response = GetResponse();
if (response.IsOk())
{
// Extract the filename from the file path
std::string Filename = DistantFile;
std::string::size_type Pos = Filename.find_last_of("/\\");
if (Pos != std::string::npos)
Filename = Filename.substr(Pos + 1);
std::string filename = distantFile;
std::string::size_type pos = filename.find_last_of("/\\");
if (pos != std::string::npos)
filename = filename.substr(pos + 1);
// Make sure the destination path ends with a slash
std::string Path = DestPath;
if (!Path.empty() && (Path[Path.size() - 1] != '\\') && (Path[Path.size() - 1] != '/'))
Path += "/";
std::string path = destPath;
if (!path.empty() && (path[path.size() - 1] != '\\') && (path[path.size() - 1] != '/'))
path += "/";
// Create the file and copy the received data into it
std::ofstream File((Path + Filename).c_str(), std::ios_base::binary);
if (!File)
std::ofstream file((path + filename).c_str(), std::ios_base::binary);
if (!file)
return Response(Response::InvalidFile);
File.write(&FileData[0], static_cast<std::streamsize>(FileData.size()));
file.write(&fileData[0], static_cast<std::streamsize>(fileData.size()));
}
}
}
return Resp;
return response;
}
////////////////////////////////////////////////////////////
/// Upload a file to the server
////////////////////////////////////////////////////////////
Ftp::Response Ftp::Upload(const std::string& LocalFile, const std::string& DestPath, TransferMode Mode)
Ftp::Response Ftp::Upload(const std::string& localFile, const std::string& destPath, TransferMode mode)
{
// Get the contents of the file to send
std::ifstream File(LocalFile.c_str(), std::ios_base::binary);
if (!File)
std::ifstream file(localFile.c_str(), std::ios_base::binary);
if (!file)
return Response(Response::InvalidFile);
File.seekg(0, std::ios::end);
std::size_t Length = File.tellg();
File.seekg(0, std::ios::beg);
std::vector<char> FileData(Length);
File.read(&FileData[0], static_cast<std::streamsize>(Length));
file.seekg(0, std::ios::end);
std::size_t length = file.tellg();
file.seekg(0, std::ios::beg);
std::vector<char> fileData(length);
file.read(&fileData[0], static_cast<std::streamsize>(length));
// Extract the filename from the file path
std::string Filename = LocalFile;
std::string::size_type Pos = Filename.find_last_of("/\\");
if (Pos != std::string::npos)
Filename = Filename.substr(Pos + 1);
std::string filename = localFile;
std::string::size_type pos = filename.find_last_of("/\\");
if (pos != std::string::npos)
filename = filename.substr(pos + 1);
// Make sure the destination path ends with a slash
std::string Path = DestPath;
if (!Path.empty() && (Path[Path.size() - 1] != '\\') && (Path[Path.size() - 1] != '/'))
Path += "/";
std::string path = destPath;
if (!path.empty() && (path[path.size() - 1] != '\\') && (path[path.size() - 1] != '/'))
path += "/";
// Open a data channel using the given transfer mode
DataChannel Data(*this);
Response Resp = Data.Open(Mode);
if (Resp.IsOk())
DataChannel data(*this);
Response response = data.Open(mode);
if (response.IsOk())
{
// Tell the server to start the transfer
Resp = SendCommand("STOR", Path + Filename);
if (Resp.IsOk())
response = SendCommand("STOR", path + filename);
if (response.IsOk())
{
// Send the file data
Data.Send(FileData);
data.Send(fileData);
// Get the response from the server
Resp = GetResponse();
response = GetResponse();
}
}
return Resp;
return response;
}
////////////////////////////////////////////////////////////
/// Send a command to the FTP server
////////////////////////////////////////////////////////////
Ftp::Response Ftp::SendCommand(const std::string& Command, const std::string& Parameter)
Ftp::Response Ftp::SendCommand(const std::string& command, const std::string& parameter)
{
// Build the command string
std::string CommandStr;
if (Parameter != "")
CommandStr = Command + " " + Parameter + "\r\n";
std::string commandStr;
if (parameter != "")
commandStr = command + " " + parameter + "\r\n";
else
CommandStr = Command + "\r\n";
commandStr = command + "\r\n";
// Send it to the server
if (myCommandSocket.Send(CommandStr.c_str(), CommandStr.length()) != sf::Socket::Done)
if (myCommandSocket.Send(commandStr.c_str(), commandStr.length()) != sf::Socket::Done)
return Response(Response::ConnectionClosed);
// Get the response
@ -466,77 +466,77 @@ Ftp::Response Ftp::GetResponse()
// We'll use a variable to keep track of the last valid code.
// It is useful in case of multi-lines responses, because the end of such a response
// will start by the same code
unsigned int LastCode = 0;
bool IsInsideMultiline = false;
std::string Message;
unsigned int lastCode = 0;
bool isInsideMultiline = false;
std::string message;
for (;;)
{
// Receive the response from the server
char Buffer[1024];
std::size_t Length;
if (myCommandSocket.Receive(Buffer, sizeof(Buffer), Length) != sf::Socket::Done)
char buffer[1024];
std::size_t length;
if (myCommandSocket.Receive(buffer, sizeof(buffer), length) != sf::Socket::Done)
return Response(Response::ConnectionClosed);
// There can be several lines inside the received buffer, extract them all
std::istringstream In(std::string(Buffer, Length), std::ios_base::binary);
while (In)
std::istringstream in(std::string(buffer, length), std::ios_base::binary);
while (in)
{
// Try to extract the code
unsigned int Code;
if (In >> Code)
unsigned int code;
if (in >> code)
{
// Extract the separator
char Sep;
In.get(Sep);
char separator;
in.get(separator);
// The '-' character means a multiline response
if ((Sep == '-') && !IsInsideMultiline)
if ((separator == '-') && !isInsideMultiline)
{
// Set the multiline flag
IsInsideMultiline = true;
isInsideMultiline = true;
// Keep track of the code
if (LastCode == 0)
LastCode = Code;
if (lastCode == 0)
lastCode = code;
// Extract the line
std::getline(In, Message);
std::getline(in, message);
// Remove the ending '\r' (all lines are terminated by "\r\n")
Message.erase(Message.length() - 1);
Message = Sep + Message + "\n";
message.erase(message.length() - 1);
message = separator + message + "\n";
}
else
{
// We must make sure that the code is the same, otherwise it means
// we haven't reached the end of the multiline response
if ((Sep != '-') && ((Code == LastCode) || (LastCode == 0)))
if ((separator != '-') && ((code == lastCode) || (lastCode == 0)))
{
// Clear the multiline flag
IsInsideMultiline = false;
isInsideMultiline = false;
// Extract the line
std::string Line;
std::getline(In, Line);
std::string line;
std::getline(in, line);
// Remove the ending '\r' (all lines are terminated by "\r\n")
Line.erase(Line.length() - 1);
line.erase(line.length() - 1);
// Append it to the message
if (Code == LastCode)
if (code == lastCode)
{
std::ostringstream Out;
Out << Code << Sep << Line;
Message += Out.str();
std::ostringstream out;
out << code << separator << line;
message += out.str();
}
else
{
Message = Sep + Line;
message = separator + line;
}
// Return the response code and message
return Response(static_cast<Response::Status>(Code), Message);
return Response(static_cast<Response::Status>(code), message);
}
else
{
@ -544,40 +544,40 @@ Ftp::Response Ftp::GetResponse()
// only a new part of the current multiline response
// Extract the line
std::string Line;
std::getline(In, Line);
std::string line;
std::getline(in, line);
if (!Line.empty())
if (!line.empty())
{
// Remove the ending '\r' (all lines are terminated by "\r\n")
Line.erase(Line.length() - 1);
line.erase(line.length() - 1);
// Append it to the current message
std::ostringstream Out;
Out << Code << Sep << Line << "\n";
Message += Out.str();
std::ostringstream out;
out << code << separator << line << "\n";
message += out.str();
}
}
}
}
else if (LastCode != 0)
else if (lastCode != 0)
{
// It seems we are in the middle of a multiline response
// Clear the error bits of the stream
In.clear();
in.clear();
// Extract the line
std::string Line;
std::getline(In, Line);
std::string line;
std::getline(in, line);
if (!Line.empty())
if (!line.empty())
{
// Remove the ending '\r' (all lines are terminated by "\r\n")
Line.erase(Line.length() - 1);
line.erase(line.length() - 1);
// Append it to the current message
Message += Line + "\n";
message += line + "\n";
}
}
else
@ -595,8 +595,8 @@ Ftp::Response Ftp::GetResponse()
////////////////////////////////////////////////////////////
/// Constructor
////////////////////////////////////////////////////////////
Ftp::DataChannel::DataChannel(Ftp& Owner) :
myFtp(Owner)
Ftp::DataChannel::DataChannel(Ftp& owner) :
myFtp(owner)
{
}
@ -615,78 +615,78 @@ Ftp::DataChannel::~DataChannel()
////////////////////////////////////////////////////////////
/// Open the data channel using the specified mode and port
////////////////////////////////////////////////////////////
Ftp::Response Ftp::DataChannel::Open(Ftp::TransferMode Mode)
Ftp::Response Ftp::DataChannel::Open(Ftp::TransferMode mode)
{
// Open a data connection in active mode (we connect to the server)
Ftp::Response Resp = myFtp.SendCommand("PASV");
if (Resp.IsOk())
Ftp::Response response = myFtp.SendCommand("PASV");
if (response.IsOk())
{
// Extract the connection address and port from the response
std::string::size_type begin = Resp.GetMessage().find_first_of("0123456789");
std::string::size_type begin = response.GetMessage().find_first_of("0123456789");
if (begin != std::string::npos)
{
sf::Uint8 Data[6] = {0, 0, 0, 0, 0, 0};
std::string Str = Resp.GetMessage().substr(begin);
std::size_t Index = 0;
sf::Uint8 data[6] = {0, 0, 0, 0, 0, 0};
std::string str = response.GetMessage().substr(begin);
std::size_t index = 0;
for (int i = 0; i < 6; ++i)
{
// Extract the current number
while (isdigit(Str[Index]))
while (isdigit(str[index]))
{
Data[i] = Data[i] * 10 + (Str[Index] - '0');
Index++;
data[i] = data[i] * 10 + (str[index] - '0');
index++;
}
// Skip separator
Index++;
index++;
}
// Reconstruct connection port and address
unsigned short Port = Data[4] * 256 + Data[5];
sf::IPAddress Address(static_cast<sf::Uint8>(Data[0]),
static_cast<sf::Uint8>(Data[1]),
static_cast<sf::Uint8>(Data[2]),
static_cast<sf::Uint8>(Data[3]));
unsigned short port = data[4] * 256 + data[5];
sf::IPAddress address(static_cast<sf::Uint8>(data[0]),
static_cast<sf::Uint8>(data[1]),
static_cast<sf::Uint8>(data[2]),
static_cast<sf::Uint8>(data[3]));
// Connect the data channel to the server
if (myDataSocket.Connect(Port, Address) == Socket::Done)
if (myDataSocket.Connect(port, address) == Socket::Done)
{
// Translate the transfer mode to the corresponding FTP parameter
std::string ModeStr;
switch (Mode)
std::string modeStr;
switch (mode)
{
case Ftp::Binary : ModeStr = "I"; break;
case Ftp::Ascii : ModeStr = "A"; break;
case Ftp::Ebcdic : ModeStr = "E"; break;
case Ftp::Binary : modeStr = "I"; break;
case Ftp::Ascii : modeStr = "A"; break;
case Ftp::Ebcdic : modeStr = "E"; break;
}
// Set the transfer mode
Resp = myFtp.SendCommand("TYPE", ModeStr);
response = myFtp.SendCommand("TYPE", modeStr);
}
else
{
// Failed to connect to the server
Resp = Ftp::Response(Ftp::Response::ConnectionFailed);
response = Ftp::Response(Ftp::Response::ConnectionFailed);
}
}
}
return Resp;
return response;
}
////////////////////////////////////////////////////////////
/// Receive data on the data channel until it is closed
////////////////////////////////////////////////////////////
void Ftp::DataChannel::Receive(std::vector<char>& Data)
void Ftp::DataChannel::Receive(std::vector<char>& data)
{
// Receive data
Data.clear();
char Buffer[1024];
std::size_t Received;
while (myDataSocket.Receive(Buffer, sizeof(Buffer), Received) == sf::Socket::Done)
data.clear();
char buffer[1024];
std::size_t received;
while (myDataSocket.Receive(buffer, sizeof(buffer), received) == sf::Socket::Done)
{
std::copy(Buffer, Buffer + Received, std::back_inserter(Data));
std::copy(buffer, buffer + received, std::back_inserter(data));
}
// Close the data socket
@ -697,10 +697,10 @@ void Ftp::DataChannel::Receive(std::vector<char>& Data)
////////////////////////////////////////////////////////////
/// Send data on the data channel
////////////////////////////////////////////////////////////
void Ftp::DataChannel::Send(const std::vector<char>& Data)
void Ftp::DataChannel::Send(const std::vector<char>& data)
{
// Send data
myDataSocket.Send(&Data[0], Data.size());
myDataSocket.Send(&data[0], data.size());
// Close the data socket
myDataSocket.Close();

View file

@ -35,13 +35,12 @@ namespace
////////////////////////////////////////////////////////////
// Convenience function to convert a string to lower case
////////////////////////////////////////////////////////////
std::string ToLower(const std::string& Str)
std::string ToLower(std::string str)
{
std::string Ret = Str;
for (std::string::iterator i = Ret.begin(); i != Ret.end(); ++i)
for (std::string::iterator i = str.begin(); i != str.end(); ++i)
*i = static_cast<char>(tolower(*i));
return Ret;
return str;
}
}
@ -51,12 +50,12 @@ namespace sf
////////////////////////////////////////////////////////////
/// Default constructor
////////////////////////////////////////////////////////////
Http::Request::Request(Method RequestMethod, const std::string& URI, const std::string& Body) :
myMethod (RequestMethod),
Http::Request::Request(Method method, const std::string& URI, const std::string& body) :
myMethod (method),
myURI (URI),
myMajorVersion(1),
myMinorVersion(0),
myBody (Body)
myBody (body)
{
}
@ -65,9 +64,9 @@ myBody (Body)
////////////////////////////////////////////////////////////
/// Set the value of a field; the field is added if it doesn't exist
////////////////////////////////////////////////////////////
void Http::Request::SetField(const std::string& Field, const std::string& Value)
void Http::Request::SetField(const std::string& field, const std::string& value)
{
myFields[ToLower(Field)] = Value;
myFields[ToLower(field)] = value;
}
@ -75,9 +74,9 @@ void Http::Request::SetField(const std::string& Field, const std::string& Value)
/// Set the request method.
/// This parameter is Get by default
////////////////////////////////////////////////////////////
void Http::Request::SetMethod(Http::Request::Method RequestMethod)
void Http::Request::SetMethod(Http::Request::Method method)
{
myMethod = RequestMethod;
myMethod = method;
}
@ -99,10 +98,10 @@ void Http::Request::SetURI(const std::string& URI)
/// Set the HTTP version of the request.
/// This parameter is 1.0 by default
////////////////////////////////////////////////////////////
void Http::Request::SetHttpVersion(unsigned int Major, unsigned int Minor)
void Http::Request::SetHttpVersion(unsigned int major, unsigned int minor)
{
myMajorVersion = Major;
myMinorVersion = Minor;
myMajorVersion = major;
myMinorVersion = minor;
}
@ -111,9 +110,9 @@ void Http::Request::SetHttpVersion(unsigned int Major, unsigned int Minor)
/// makes sense only for POST requests.
/// This parameter is empty by default
////////////////////////////////////////////////////////////
void Http::Request::SetBody(const std::string& Body)
void Http::Request::SetBody(const std::string& body)
{
myBody = Body;
myBody = body;
}
@ -122,44 +121,44 @@ void Http::Request::SetBody(const std::string& Body)
////////////////////////////////////////////////////////////
std::string Http::Request::ToString() const
{
std::ostringstream Out;
std::ostringstream out;
// Convert the method to its string representation
std::string RequestMethod;
std::string method;
switch (myMethod)
{
default :
case Get : RequestMethod = "GET"; break;
case Post : RequestMethod = "POST"; break;
case Head : RequestMethod = "HEAD"; break;
case Get : method = "GET"; break;
case Post : method = "POST"; break;
case Head : method = "HEAD"; break;
}
// Write the first line containing the request type
Out << RequestMethod << " " << myURI << " ";
Out << "HTTP/" << myMajorVersion << "." << myMinorVersion << "\r\n";
out << method << " " << myURI << " ";
out << "HTTP/" << myMajorVersion << "." << myMinorVersion << "\r\n";
// Write fields
for (FieldTable::const_iterator i = myFields.begin(); i != myFields.end(); ++i)
{
Out << i->first << ": " << i->second << "\r\n";
out << i->first << ": " << i->second << "\r\n";
}
// Use an extra \r\n to separate the header from the body
Out << "\r\n";
out << "\r\n";
// Add the body
Out << myBody;
out << myBody;
return Out.str();
return out.str();
}
////////////////////////////////////////////////////////////
/// Check if the given field has been defined
////////////////////////////////////////////////////////////
bool Http::Request::HasField(const std::string& Field) const
bool Http::Request::HasField(const std::string& field) const
{
return myFields.find(Field) != myFields.end();
return myFields.find(field) != myFields.end();
}
@ -178,17 +177,17 @@ myMinorVersion(0)
////////////////////////////////////////////////////////////
/// Get the value of a field
////////////////////////////////////////////////////////////
const std::string& Http::Response::GetField(const std::string& Field) const
const std::string& Http::Response::GetField(const std::string& field) const
{
FieldTable::const_iterator It = myFields.find(Field);
if (It != myFields.end())
FieldTable::const_iterator it = myFields.find(field);
if (it != myFields.end())
{
return It->second;
return it->second;
}
else
{
static const std::string Empty = "";
return Empty;
static const std::string empty = "";
return empty;
}
}
@ -236,20 +235,20 @@ const std::string& Http::Response::GetBody() const
////////////////////////////////////////////////////////////
/// Construct the header from a response string
////////////////////////////////////////////////////////////
void Http::Response::FromString(const std::string& Data)
void Http::Response::FromString(const std::string& data)
{
std::istringstream In(Data);
std::istringstream in(data);
// Extract the HTTP version from the first line
std::string Version;
if (In >> Version)
std::string version;
if (in >> version)
{
if ((Version.size() >= 8) && (Version[6] == '.') &&
(ToLower(Version.substr(0, 5)) == "http/") &&
isdigit(Version[5]) && isdigit(Version[7]))
if ((version.size() >= 8) && (version[6] == '.') &&
(ToLower(version.substr(0, 5)) == "http/") &&
isdigit(version[5]) && isdigit(version[7]))
{
myMajorVersion = Version[5] - '0';
myMinorVersion = Version[7] - '0';
myMajorVersion = version[5] - '0';
myMinorVersion = version[7] - '0';
}
else
{
@ -260,10 +259,10 @@ void Http::Response::FromString(const std::string& Data)
}
// Extract the status code from the first line
int StatusCode;
if (In >> StatusCode)
int status;
if (in >> status)
{
myStatus = static_cast<Status>(StatusCode);
myStatus = static_cast<Status>(status);
}
else
{
@ -273,32 +272,32 @@ void Http::Response::FromString(const std::string& Data)
}
// Ignore the end of the first line
In.ignore(10000, '\n');
in.ignore(10000, '\n');
// Parse the other lines, which contain fields, one by one
std::string Line;
while (std::getline(In, Line) && (Line.size() > 2))
std::string line;
while (std::getline(in, line) && (line.size() > 2))
{
std::string::size_type Pos = Line.find(": ");
if (Pos != std::string::npos)
std::string::size_type pos = line.find(": ");
if (pos != std::string::npos)
{
// Extract the field name and its value
std::string Field = Line.substr(0, Pos);
std::string Value = Line.substr(Pos + 2);
std::string field = line.substr(0, pos);
std::string value = line.substr(pos + 2);
// Remove any trailing \r
if (!Value.empty() && (*Value.rbegin() == '\r'))
Value.erase(Value.size() - 1);
if (!value.empty() && (*value.rbegin() == '\r'))
value.erase(value.size() - 1);
// Add the field
myFields[ToLower(Field)] = Value;
myFields[ToLower(field)] = value;
}
}
// Finally extract the body
myBody.clear();
while (std::getline(In, Line))
myBody += Line + "\n";
while (std::getline(in, line))
myBody += line + "\n";
}

View file

@ -52,19 +52,19 @@ myAddress(INADDR_NONE)
////////////////////////////////////////////////////////////
/// Construct the address from a string
////////////////////////////////////////////////////////////
IPAddress::IPAddress(const std::string& Address)
IPAddress::IPAddress(const std::string& address)
{
// First try to convert it as a byte representation ("xxx.xxx.xxx.xxx")
myAddress = inet_addr(Address.c_str());
myAddress = inet_addr(address.c_str());
// If not successful, try to convert it as a host name
if (!IsValid())
{
hostent* Host = gethostbyname(Address.c_str());
if (Host)
hostent* host = gethostbyname(address.c_str());
if (host)
{
// Host found, extract its IP address
myAddress = reinterpret_cast<in_addr*>(Host->h_addr)->s_addr;
myAddress = reinterpret_cast<in_addr*>(host->h_addr)->s_addr;
}
else
{
@ -79,19 +79,19 @@ IPAddress::IPAddress(const std::string& Address)
/// Construct the address from a C-style string ;
/// Needed for implicit conversions from literal strings to IPAddress to work
////////////////////////////////////////////////////////////
IPAddress::IPAddress(const char* Address)
IPAddress::IPAddress(const char* address)
{
// First try to convert it as a byte representation ("xxx.xxx.xxx.xxx")
myAddress = inet_addr(Address);
myAddress = inet_addr(address);
// If not successful, try to convert it as a host name
if (!IsValid())
{
hostent* Host = gethostbyname(Address);
if (Host)
hostent* host = gethostbyname(address);
if (host)
{
// Host found, extract its IP address
myAddress = reinterpret_cast<in_addr*>(Host->h_addr)->s_addr;
myAddress = reinterpret_cast<in_addr*>(host->h_addr)->s_addr;
}
else
{
@ -105,18 +105,18 @@ IPAddress::IPAddress(const char* Address)
////////////////////////////////////////////////////////////
/// Construct the address from 4 bytes
////////////////////////////////////////////////////////////
IPAddress::IPAddress(Uint8 Byte0, Uint8 Byte1, Uint8 Byte2, Uint8 Byte3)
IPAddress::IPAddress(Uint8 byte0, Uint8 byte1, Uint8 byte2, Uint8 byte3)
{
myAddress = htonl((Byte0 << 24) | (Byte1 << 16) | (Byte2 << 8) | Byte3);
myAddress = htonl((byte0 << 24) | (byte1 << 16) | (byte2 << 8) | byte3);
}
////////////////////////////////////////////////////////////
/// Construct the address from a 32-bits integer
////////////////////////////////////////////////////////////
IPAddress::IPAddress(Uint32 Address)
IPAddress::IPAddress(Uint32 address)
{
myAddress = htonl(Address);
myAddress = htonl(address);
}
@ -134,10 +134,10 @@ bool IPAddress::IsValid() const
////////////////////////////////////////////////////////////
std::string IPAddress::ToString() const
{
in_addr InAddr;
InAddr.s_addr = myAddress;
in_addr address;
address.s_addr = myAddress;
return inet_ntoa(InAddr);
return inet_ntoa(address);
}
@ -159,49 +159,49 @@ IPAddress IPAddress::GetLocalAddress()
// and get the local socket address with the getsockname function.
// UDP connection will not send anything to the network, so this function won't cause any overhead.
IPAddress LocalAddress;
IPAddress localAddress;
// Create the socket
SocketHelper::SocketType Socket = socket(PF_INET, SOCK_DGRAM, 0);
if (Socket == SocketHelper::InvalidSocket())
return LocalAddress;
SocketHelper::SocketType sock = socket(PF_INET, SOCK_DGRAM, 0);
if (sock == SocketHelper::InvalidSocket())
return localAddress;
// Build the host address (use a random port)
sockaddr_in SockAddr;
memset(SockAddr.sin_zero, 0, sizeof(SockAddr.sin_zero));
SockAddr.sin_addr.s_addr = INADDR_LOOPBACK;
SockAddr.sin_family = AF_INET;
SockAddr.sin_port = htons(4567);
sockaddr_in sockAddr;
memset(sockAddr.sin_zero, 0, sizeof(sockAddr.sin_zero));
sockAddr.sin_addr.s_addr = INADDR_LOOPBACK;
sockAddr.sin_family = AF_INET;
sockAddr.sin_port = htons(4567);
// Connect the socket
if (connect(Socket, reinterpret_cast<sockaddr*>(&SockAddr), sizeof(SockAddr)) == -1)
if (connect(sock, reinterpret_cast<sockaddr*>(&sockAddr), sizeof(sockAddr)) == -1)
{
SocketHelper::Close(Socket);
return LocalAddress;
SocketHelper::Close(sock);
return localAddress;
}
// Get the local address of the socket connection
SocketHelper::LengthType Size = sizeof(SockAddr);
if (getsockname(Socket, reinterpret_cast<sockaddr*>(&SockAddr), &Size) == -1)
SocketHelper::LengthType size = sizeof(sockAddr);
if (getsockname(sock, reinterpret_cast<sockaddr*>(&sockAddr), &size) == -1)
{
SocketHelper::Close(Socket);
return LocalAddress;
SocketHelper::Close(sock);
return localAddress;
}
// Close the socket
SocketHelper::Close(Socket);
SocketHelper::Close(sock);
// Finally build the IP address
LocalAddress.myAddress = SockAddr.sin_addr.s_addr;
localAddress.myAddress = sockAddr.sin_addr.s_addr;
return LocalAddress;
return localAddress;
}
////////////////////////////////////////////////////////////
/// Get the computer's public IP address (from the web point of view)
////////////////////////////////////////////////////////////
IPAddress IPAddress::GetPublicAddress(float Timeout)
IPAddress IPAddress::GetPublicAddress(float timeout)
{
// The trick here is more complicated, because the only way
// to get our public IP address is to get it from a distant computer.
@ -209,11 +209,11 @@ IPAddress IPAddress::GetPublicAddress(float Timeout)
// and parse the result to extract our IP address
// (not very hard : the web page contains only our IP address).
Http Server("www.sfml-dev.org");
Http::Request Request(Http::Request::Get, "/ip-provider.php");
Http::Response Page = Server.SendRequest(Request, Timeout);
if (Page.GetStatus() == Http::Response::Ok)
return IPAddress(Page.GetBody());
Http server("www.sfml-dev.org");
Http::Request request(Http::Request::Get, "/ip-provider.php");
Http::Response page = server.SendRequest(request, timeout);
if (page.GetStatus() == Http::Response::Ok)
return IPAddress(page.GetBody());
// Something failed: return an invalid address
return IPAddress();
@ -223,76 +223,76 @@ IPAddress IPAddress::GetPublicAddress(float Timeout)
////////////////////////////////////////////////////////////
/// Comparison operator ==
////////////////////////////////////////////////////////////
bool IPAddress::operator ==(const IPAddress& Other) const
bool IPAddress::operator ==(const IPAddress& other) const
{
return myAddress == Other.myAddress;
return myAddress == other.myAddress;
}
////////////////////////////////////////////////////////////
/// Comparison operator !=
////////////////////////////////////////////////////////////
bool IPAddress::operator !=(const IPAddress& Other) const
bool IPAddress::operator !=(const IPAddress& other) const
{
return myAddress != Other.myAddress;
return myAddress != other.myAddress;
}
////////////////////////////////////////////////////////////
/// Comparison operator <
////////////////////////////////////////////////////////////
bool IPAddress::operator <(const IPAddress& Other) const
bool IPAddress::operator <(const IPAddress& other) const
{
return myAddress < Other.myAddress;
return myAddress < other.myAddress;
}
////////////////////////////////////////////////////////////
/// Comparison operator >
////////////////////////////////////////////////////////////
bool IPAddress::operator >(const IPAddress& Other) const
bool IPAddress::operator >(const IPAddress& other) const
{
return myAddress > Other.myAddress;
return myAddress > other.myAddress;
}
////////////////////////////////////////////////////////////
/// Comparison operator <=
////////////////////////////////////////////////////////////
bool IPAddress::operator <=(const IPAddress& Other) const
bool IPAddress::operator <=(const IPAddress& other) const
{
return myAddress <= Other.myAddress;
return myAddress <= other.myAddress;
}
////////////////////////////////////////////////////////////
/// Comparison operator >=
////////////////////////////////////////////////////////////
bool IPAddress::operator >=(const IPAddress& Other) const
bool IPAddress::operator >=(const IPAddress& other) const
{
return myAddress >= Other.myAddress;
return myAddress >= other.myAddress;
}
////////////////////////////////////////////////////////////
/// Operator >> overload to extract an address from an input stream
////////////////////////////////////////////////////////////
std::istream& operator >>(std::istream& Stream, IPAddress& Address)
std::istream& operator >>(std::istream& stream, IPAddress& address)
{
std::string Str;
Stream >> Str;
Address = IPAddress(Str);
std::string str;
stream >> str;
address = IPAddress(str);
return Stream;
return stream;
}
////////////////////////////////////////////////////////////
/// Operator << overload to print an address to an output stream
////////////////////////////////////////////////////////////
std::ostream& operator <<(std::ostream& Stream, const IPAddress& Address)
std::ostream& operator <<(std::ostream& stream, const IPAddress& address)
{
return Stream << Address.ToString();
return stream << address.ToString();
}
} // namespace sf

View file

@ -55,13 +55,13 @@ Packet::~Packet()
////////////////////////////////////////////////////////////
/// Append data to the end of the packet
////////////////////////////////////////////////////////////
void Packet::Append(const void* Data, std::size_t SizeInBytes)
void Packet::Append(const void* data, std::size_t sizeInBytes)
{
if (Data && (SizeInBytes > 0))
if (data && (sizeInBytes > 0))
{
std::size_t Start = myData.size();
myData.resize(Start + SizeInBytes);
memcpy(&myData[Start], Data, SizeInBytes);
std::size_t start = myData.size();
myData.resize(start + sizeInBytes);
memcpy(&myData[start], data, sizeInBytes);
}
}
@ -118,165 +118,165 @@ Packet::operator bool() const
////////////////////////////////////////////////////////////
/// Operator >> overloads to extract data from the packet
////////////////////////////////////////////////////////////
Packet& Packet::operator >>(bool& Data)
Packet& Packet::operator >>(bool& data)
{
Uint8 Value;
if (*this >> Value)
Data = (Value != 0);
Uint8 value;
if (*this >> value)
data = (value != 0);
return *this;
}
Packet& Packet::operator >>(Int8& Data)
Packet& Packet::operator >>(Int8& data)
{
if (CheckSize(sizeof(Data)))
if (CheckSize(sizeof(data)))
{
Data = *reinterpret_cast<const Int8*>(GetData() + myReadPos);
myReadPos += sizeof(Data);
data = *reinterpret_cast<const Int8*>(GetData() + myReadPos);
myReadPos += sizeof(data);
}
return *this;
}
Packet& Packet::operator >>(Uint8& Data)
Packet& Packet::operator >>(Uint8& data)
{
if (CheckSize(sizeof(Data)))
if (CheckSize(sizeof(data)))
{
Data = *reinterpret_cast<const Uint8*>(GetData() + myReadPos);
myReadPos += sizeof(Data);
data = *reinterpret_cast<const Uint8*>(GetData() + myReadPos);
myReadPos += sizeof(data);
}
return *this;
}
Packet& Packet::operator >>(Int16& Data)
Packet& Packet::operator >>(Int16& data)
{
if (CheckSize(sizeof(Data)))
if (CheckSize(sizeof(data)))
{
Data = ntohs(*reinterpret_cast<const Int16*>(GetData() + myReadPos));
myReadPos += sizeof(Data);
data = ntohs(*reinterpret_cast<const Int16*>(GetData() + myReadPos));
myReadPos += sizeof(data);
}
return *this;
}
Packet& Packet::operator >>(Uint16& Data)
Packet& Packet::operator >>(Uint16& data)
{
if (CheckSize(sizeof(Data)))
if (CheckSize(sizeof(data)))
{
Data = ntohs(*reinterpret_cast<const Uint16*>(GetData() + myReadPos));
myReadPos += sizeof(Data);
data = ntohs(*reinterpret_cast<const Uint16*>(GetData() + myReadPos));
myReadPos += sizeof(data);
}
return *this;
}
Packet& Packet::operator >>(Int32& Data)
Packet& Packet::operator >>(Int32& data)
{
if (CheckSize(sizeof(Data)))
if (CheckSize(sizeof(data)))
{
Data = ntohl(*reinterpret_cast<const Int32*>(GetData() + myReadPos));
myReadPos += sizeof(Data);
data = ntohl(*reinterpret_cast<const Int32*>(GetData() + myReadPos));
myReadPos += sizeof(data);
}
return *this;
}
Packet& Packet::operator >>(Uint32& Data)
Packet& Packet::operator >>(Uint32& data)
{
if (CheckSize(sizeof(Data)))
if (CheckSize(sizeof(data)))
{
Data = ntohl(*reinterpret_cast<const Uint32*>(GetData() + myReadPos));
myReadPos += sizeof(Data);
data = ntohl(*reinterpret_cast<const Uint32*>(GetData() + myReadPos));
myReadPos += sizeof(data);
}
return *this;
}
Packet& Packet::operator >>(float& Data)
Packet& Packet::operator >>(float& data)
{
if (CheckSize(sizeof(Data)))
if (CheckSize(sizeof(data)))
{
Data = *reinterpret_cast<const float*>(GetData() + myReadPos);
myReadPos += sizeof(Data);
data = *reinterpret_cast<const float*>(GetData() + myReadPos);
myReadPos += sizeof(data);
}
return *this;
}
Packet& Packet::operator >>(double& Data)
Packet& Packet::operator >>(double& data)
{
if (CheckSize(sizeof(Data)))
if (CheckSize(sizeof(data)))
{
Data = *reinterpret_cast<const double*>(GetData() + myReadPos);
myReadPos += sizeof(Data);
data = *reinterpret_cast<const double*>(GetData() + myReadPos);
myReadPos += sizeof(data);
}
return *this;
}
Packet& Packet::operator >>(char* Data)
Packet& Packet::operator >>(char* data)
{
// First extract string length
Uint32 Length;
*this >> Length;
Uint32 length;
*this >> length;
if ((Length > 0) && CheckSize(Length))
if ((length > 0) && CheckSize(length))
{
// Then extract characters
memcpy(Data, GetData() + myReadPos, Length);
Data[Length] = '\0';
memcpy(data, GetData() + myReadPos, length);
data[length] = '\0';
// Update reading position
myReadPos += Length;
myReadPos += length;
}
return *this;
}
Packet& Packet::operator >>(std::string& Data)
Packet& Packet::operator >>(std::string& data)
{
// First extract string length
Uint32 Length;
*this >> Length;
Uint32 length;
*this >> length;
Data.clear();
if ((Length > 0) && CheckSize(Length))
data.clear();
if ((length > 0) && CheckSize(length))
{
// Then extract characters
Data.assign(GetData() + myReadPos, Length);
data.assign(GetData() + myReadPos, length);
// Update reading position
myReadPos += Length;
myReadPos += length;
}
return *this;
}
Packet& Packet::operator >>(wchar_t* Data)
Packet& Packet::operator >>(wchar_t* data)
{
// First extract string length
Uint32 Length;
*this >> Length;
Uint32 length;
*this >> length;
if ((Length > 0) && CheckSize(Length * sizeof(Int32)))
if ((length > 0) && CheckSize(length * sizeof(Int32)))
{
// Then extract characters
for (Uint32 i = 0; i < Length; ++i)
for (Uint32 i = 0; i < length; ++i)
{
Uint32 c;
*this >> c;
Data[i] = static_cast<wchar_t>(c);
Uint32 character;
*this >> character;
data[i] = static_cast<wchar_t>(character);
}
Data[Length] = L'\0';
data[length] = L'\0';
}
return *this;
}
Packet& Packet::operator >>(std::wstring& Data)
Packet& Packet::operator >>(std::wstring& data)
{
// First extract string length
Uint32 Length;
*this >> Length;
Uint32 length;
*this >> length;
Data.clear();
if ((Length > 0) && CheckSize(Length * sizeof(Int32)))
data.clear();
if ((length > 0) && CheckSize(length * sizeof(Int32)))
{
// Then extract characters
for (Uint32 i = 0; i < Length; ++i)
for (Uint32 i = 0; i < length; ++i)
{
Uint32 c;
*this >> c;
Data += static_cast<wchar_t>(c);
Uint32 character;
*this >> character;
data += static_cast<wchar_t>(character);
}
}
@ -287,106 +287,106 @@ Packet& Packet::operator >>(std::wstring& Data)
////////////////////////////////////////////////////////////
/// Operator << overloads to put data into the packet
////////////////////////////////////////////////////////////
Packet& Packet::operator <<(bool Data)
Packet& Packet::operator <<(bool data)
{
*this << static_cast<Uint8>(Data);
*this << static_cast<Uint8>(data);
return *this;
}
Packet& Packet::operator <<(Int8 Data)
Packet& Packet::operator <<(Int8 data)
{
Append(&Data, sizeof(Data));
Append(&data, sizeof(data));
return *this;
}
Packet& Packet::operator <<(Uint8 Data)
Packet& Packet::operator <<(Uint8 data)
{
Append(&Data, sizeof(Data));
Append(&data, sizeof(data));
return *this;
}
Packet& Packet::operator <<(Int16 Data)
Packet& Packet::operator <<(Int16 data)
{
Int16 ToWrite = htons(Data);
Append(&ToWrite, sizeof(ToWrite));
Int16 toWrite = htons(data);
Append(&toWrite, sizeof(toWrite));
return *this;
}
Packet& Packet::operator <<(Uint16 Data)
Packet& Packet::operator <<(Uint16 data)
{
Uint16 ToWrite = htons(Data);
Append(&ToWrite, sizeof(ToWrite));
Uint16 toWrite = htons(data);
Append(&toWrite, sizeof(toWrite));
return *this;
}
Packet& Packet::operator <<(Int32 Data)
Packet& Packet::operator <<(Int32 data)
{
Int32 ToWrite = htonl(Data);
Append(&ToWrite, sizeof(ToWrite));
Int32 toWrite = htonl(data);
Append(&toWrite, sizeof(toWrite));
return *this;
}
Packet& Packet::operator <<(Uint32 Data)
Packet& Packet::operator <<(Uint32 data)
{
Uint32 ToWrite = htonl(Data);
Append(&ToWrite, sizeof(ToWrite));
Uint32 toWrite = htonl(data);
Append(&toWrite, sizeof(toWrite));
return *this;
}
Packet& Packet::operator <<(float Data)
Packet& Packet::operator <<(float data)
{
Append(&Data, sizeof(Data));
Append(&data, sizeof(data));
return *this;
}
Packet& Packet::operator <<(double Data)
Packet& Packet::operator <<(double data)
{
Append(&Data, sizeof(Data));
Append(&data, sizeof(data));
return *this;
}
Packet& Packet::operator <<(const char* Data)
Packet& Packet::operator <<(const char* data)
{
// First insert string length
Uint32 Length = 0;
for (const char* c = Data; *c != '\0'; ++c)
++Length;
*this << Length;
Uint32 length = 0;
for (const char* c = data; *c != '\0'; ++c)
++length;
*this << length;
// Then insert characters
Append(Data, Length * sizeof(char));
Append(data, length * sizeof(char));
return *this;
}
Packet& Packet::operator <<(const std::string& Data)
Packet& Packet::operator <<(const std::string& data)
{
// First insert string length
Uint32 Length = static_cast<Uint32>(Data.size());
*this << Length;
Uint32 length = static_cast<Uint32>(data.size());
*this << length;
// Then insert characters
if (Length > 0)
if (length > 0)
{
Append(Data.c_str(), Length * sizeof(std::string::value_type));
Append(data.c_str(), length * sizeof(std::string::value_type));
}
return *this;
}
Packet& Packet::operator <<(const wchar_t* Data)
Packet& Packet::operator <<(const wchar_t* data)
{
// First insert string length
Uint32 Length = 0;
for (const wchar_t* c = Data; *c != L'\0'; ++c)
++Length;
*this << Length;
Uint32 length = 0;
for (const wchar_t* c = data; *c != L'\0'; ++c)
++length;
*this << length;
// Then insert characters
for (const wchar_t* c = Data; *c != L'\0'; ++c)
for (const wchar_t* c = data; *c != L'\0'; ++c)
*this << static_cast<Int32>(*c);
return *this;
}
Packet& Packet::operator <<(const std::wstring& Data)
Packet& Packet::operator <<(const std::wstring& data)
{
// First insert string length
Uint32 Length = static_cast<Uint32>(Data.size());
*this << Length;
Uint32 length = static_cast<Uint32>(data.size());
*this << length;
// Then insert characters
if (Length > 0)
if (length > 0)
{
for (std::wstring::const_iterator c = Data.begin(); c != Data.end(); ++c)
for (std::wstring::const_iterator c = data.begin(); c != data.end(); ++c)
*this << static_cast<Int32>(*c);
}
@ -397,9 +397,9 @@ Packet& Packet::operator <<(const std::wstring& Data)
////////////////////////////////////////////////////////////
/// Check if the packet can extract a given size of bytes
////////////////////////////////////////////////////////////
bool Packet::CheckSize(std::size_t Size)
bool Packet::CheckSize(std::size_t size)
{
myIsValid = myIsValid && (myReadPos + Size <= myData.size());
myIsValid = myIsValid && (myReadPos + size <= myData.size());
return myIsValid;
}
@ -408,9 +408,9 @@ bool Packet::CheckSize(std::size_t Size)
////////////////////////////////////////////////////////////
/// Called before the packet is sent to the network
////////////////////////////////////////////////////////////
const char* Packet::OnSend(std::size_t& DataSize)
const char* Packet::OnSend(std::size_t& dataSize)
{
DataSize = GetDataSize();
dataSize = GetDataSize();
return GetData();
}
@ -418,9 +418,9 @@ const char* Packet::OnSend(std::size_t& DataSize)
////////////////////////////////////////////////////////////
/// Called after the packet has been received from the network
////////////////////////////////////////////////////////////
void Packet::OnReceive(const char* Data, std::size_t DataSize)
void Packet::OnReceive(const char* data, std::size_t dataSize)
{
Append(Data, DataSize);
Append(data, dataSize);
}
} // namespace sf

View file

@ -47,22 +47,22 @@ myMaxSocket(0)
////////////////////////////////////////////////////////////
/// Add a socket to watch
////////////////////////////////////////////////////////////
void SelectorBase::Add(SocketHelper::SocketType Socket)
void SelectorBase::Add(SocketHelper::SocketType socket)
{
FD_SET(Socket, &mySet);
FD_SET(socket, &mySet);
int Size = static_cast<int>(Socket);
if (Size > myMaxSocket)
myMaxSocket = Size;
int size = static_cast<int>(socket);
if (size > myMaxSocket)
myMaxSocket = size;
}
////////////////////////////////////////////////////////////
/// Remove a socket
////////////////////////////////////////////////////////////
void SelectorBase::Remove(SocketHelper::SocketType Socket)
void SelectorBase::Remove(SocketHelper::SocketType socket)
{
FD_CLR(Socket, &mySet);
FD_CLR(socket, &mySet);
}
@ -83,20 +83,20 @@ void SelectorBase::Clear()
/// This functions will return either when at least one socket
/// is ready, or when the given time is out
////////////////////////////////////////////////////////////
unsigned int SelectorBase::Wait(float Timeout)
unsigned int SelectorBase::Wait(float timeout)
{
// Setup the timeout structure
timeval Time;
Time.tv_sec = static_cast<long>(Timeout);
Time.tv_usec = (static_cast<long>(Timeout * 1000) % 1000) * 1000;
timeval time;
time.tv_sec = static_cast<long>(timeout);
time.tv_usec = (static_cast<long>(timeout * 1000) % 1000) * 1000;
// Prepare the set of sockets to return
mySetReady = mySet;
// Wait until one of the sockets is ready for reading, or timeout is reached
int NbSockets = select(myMaxSocket + 1, &mySetReady, NULL, NULL, Timeout > 0 ? &Time : NULL);
int nbSockets = select(myMaxSocket + 1, &mySetReady, NULL, NULL, timeout > 0 ? &time : NULL);
return NbSockets >= 0 ? static_cast<unsigned int>(NbSockets) : 0;
return nbSockets >= 0 ? static_cast<unsigned int>(nbSockets) : 0;
}
@ -105,7 +105,7 @@ unsigned int SelectorBase::Wait(float Timeout)
/// ready for reading. The total number of sockets ready
/// is the integer returned by the previous call to Wait()
////////////////////////////////////////////////////////////
SocketHelper::SocketType SelectorBase::GetSocketReady(unsigned int Index)
SocketHelper::SocketType SelectorBase::GetSocketReady(unsigned int index)
{
// The standard FD_xxx interface doesn't define a direct access,
// so we must go through the whole set to find the socket we're looking for
@ -113,10 +113,10 @@ SocketHelper::SocketType SelectorBase::GetSocketReady(unsigned int Index)
{
if (FD_ISSET(i, &mySetReady))
{
// Current socket is ready, but is it the Index-th one ?
if (Index > 0)
// Current socket is ready, but is it the index-th one ?
if (index > 0)
{
Index--;
index--;
}
else
{

View file

@ -53,38 +53,38 @@ SocketTCP::SocketTCP()
////////////////////////////////////////////////////////////
/// Change the blocking state of the socket
////////////////////////////////////////////////////////////
void SocketTCP::SetBlocking(bool Blocking)
void SocketTCP::SetBlocking(bool blocking)
{
// Make sure our socket is valid
if (!IsValid())
Create();
SocketHelper::SetBlocking(mySocket, Blocking);
myIsBlocking = Blocking;
SocketHelper::SetBlocking(mySocket, blocking);
myIsBlocking = blocking;
}
////////////////////////////////////////////////////////////
/// Connect to another computer on a specified port
////////////////////////////////////////////////////////////
Socket::Status SocketTCP::Connect(unsigned short Port, const IPAddress& HostAddress, float Timeout)
Socket::Status SocketTCP::Connect(unsigned short port, const IPAddress& host, float timeout)
{
// Make sure our socket is valid
if (!IsValid())
Create();
// Build the host address
sockaddr_in SockAddr;
memset(SockAddr.sin_zero, 0, sizeof(SockAddr.sin_zero));
SockAddr.sin_addr.s_addr = inet_addr(HostAddress.ToString().c_str());
SockAddr.sin_family = AF_INET;
SockAddr.sin_port = htons(Port);
sockaddr_in sockAddr;
memset(sockAddr.sin_zero, 0, sizeof(sockAddr.sin_zero));
sockAddr.sin_addr.s_addr = inet_addr(host.ToString().c_str());
sockAddr.sin_family = AF_INET;
sockAddr.sin_port = htons(port);
if (Timeout <= 0)
if (timeout <= 0)
{
// ----- We're not using a timeout : just try to connect -----
if (connect(mySocket, reinterpret_cast<sockaddr*>(&SockAddr), sizeof(SockAddr)) == -1)
if (connect(mySocket, reinterpret_cast<sockaddr*>(&sockAddr), sizeof(sockAddr)) == -1)
{
// Failed to connect
return SocketHelper::GetErrorStatus();
@ -98,56 +98,56 @@ Socket::Status SocketTCP::Connect(unsigned short Port, const IPAddress& HostAddr
// ----- We're using a timeout : we'll need a few tricks to make it work -----
// Save the previous blocking state
bool IsBlocking = myIsBlocking;
bool blocking = myIsBlocking;
// Switch to non-blocking to enable our connection timeout
if (IsBlocking)
if (blocking)
SetBlocking(false);
// Try to connect to host
if (connect(mySocket, reinterpret_cast<sockaddr*>(&SockAddr), sizeof(SockAddr)) >= 0)
if (connect(mySocket, reinterpret_cast<sockaddr*>(&sockAddr), sizeof(sockAddr)) >= 0)
{
// We got instantly connected! (it may no happen a lot...)
return Socket::Done;
}
// Get the error status
Socket::Status Status = SocketHelper::GetErrorStatus();
Socket::Status status = SocketHelper::GetErrorStatus();
// If we were in non-blocking mode, return immediatly
if (!IsBlocking)
return Status;
if (!blocking)
return status;
// Otherwise, wait until something happens to our socket (success, timeout or error)
if (Status == Socket::NotReady)
if (status == Socket::NotReady)
{
// Setup the selector
fd_set Selector;
FD_ZERO(&Selector);
FD_SET(mySocket, &Selector);
fd_set selector;
FD_ZERO(&selector);
FD_SET(mySocket, &selector);
// Setup the timeout
timeval Time;
Time.tv_sec = static_cast<long>(Timeout);
Time.tv_usec = (static_cast<long>(Timeout * 1000) % 1000) * 1000;
timeval time;
time.tv_sec = static_cast<long>(timeout);
time.tv_usec = (static_cast<long>(timeout * 1000) % 1000) * 1000;
// Wait for something to write on our socket (would mean the connection has been accepted)
if (select(static_cast<int>(mySocket + 1), NULL, &Selector, NULL, &Time) > 0)
if (select(static_cast<int>(mySocket + 1), NULL, &selector, NULL, &time) > 0)
{
// Connection succeeded
Status = Socket::Done;
status = Socket::Done;
}
else
{
// Failed to connect before timeout is over
Status = SocketHelper::GetErrorStatus();
status = SocketHelper::GetErrorStatus();
}
}
// Switch back to blocking mode
SetBlocking(true);
return Status;
return status;
}
}
@ -155,24 +155,24 @@ Socket::Status SocketTCP::Connect(unsigned short Port, const IPAddress& HostAddr
////////////////////////////////////////////////////////////
/// Listen to a specified port for incoming data or connections
////////////////////////////////////////////////////////////
bool SocketTCP::Listen(unsigned short Port)
bool SocketTCP::Listen(unsigned short port)
{
// Make sure our socket is valid
if (!IsValid())
Create();
// Build the address
sockaddr_in SockAddr;
memset(SockAddr.sin_zero, 0, sizeof(SockAddr.sin_zero));
SockAddr.sin_addr.s_addr = htonl(INADDR_ANY);
SockAddr.sin_family = AF_INET;
SockAddr.sin_port = htons(Port);
sockaddr_in sockAddr;
memset(sockAddr.sin_zero, 0, sizeof(sockAddr.sin_zero));
sockAddr.sin_addr.s_addr = htonl(INADDR_ANY);
sockAddr.sin_family = AF_INET;
sockAddr.sin_port = htons(port);
// Bind the socket to the specified port
if (bind(mySocket, reinterpret_cast<sockaddr*>(&SockAddr), sizeof(SockAddr)) == -1)
if (bind(mySocket, reinterpret_cast<sockaddr*>(&sockAddr), sizeof(sockAddr)) == -1)
{
// Not likely to happen, but...
std::cerr << "Failed to bind socket to port " << Port << std::endl;
std::cerr << "Failed to bind socket to port " << port << std::endl;
return false;
}
@ -180,7 +180,7 @@ bool SocketTCP::Listen(unsigned short Port)
if (listen(mySocket, 0) == -1)
{
// Oops, socket is deaf
std::cerr << "Failed to listen to port " << Port << std::endl;
std::cerr << "Failed to listen to port " << port << std::endl;
return false;
}
@ -192,27 +192,27 @@ bool SocketTCP::Listen(unsigned short Port)
/// Wait for a connection (must be listening to a port).
/// This function will block if the socket is blocking
////////////////////////////////////////////////////////////
Socket::Status SocketTCP::Accept(SocketTCP& Connected, IPAddress* Address)
Socket::Status SocketTCP::Accept(SocketTCP& connected, IPAddress* address)
{
// Address that will be filled with client informations
sockaddr_in ClientAddress;
SocketHelper::LengthType Length = sizeof(ClientAddress);
sockaddr_in clientAddress;
SocketHelper::LengthType length = sizeof(clientAddress);
// Accept a new connection
Connected = accept(mySocket, reinterpret_cast<sockaddr*>(&ClientAddress), &Length);
connected = accept(mySocket, reinterpret_cast<sockaddr*>(&clientAddress), &length);
// Check errors
if (!Connected.IsValid())
if (!connected.IsValid())
{
if (Address)
*Address = IPAddress();
if (address)
*address = IPAddress();
return SocketHelper::GetErrorStatus();
}
// Fill address if requested
if (Address)
*Address = IPAddress(inet_ntoa(ClientAddress.sin_addr));
if (address)
*address = IPAddress(inet_ntoa(clientAddress.sin_addr));
return Socket::Done;
}
@ -221,25 +221,25 @@ Socket::Status SocketTCP::Accept(SocketTCP& Connected, IPAddress* Address)
////////////////////////////////////////////////////////////
/// Send an array of bytes to the host (must be connected first)
////////////////////////////////////////////////////////////
Socket::Status SocketTCP::Send(const char* Data, std::size_t Size)
Socket::Status SocketTCP::Send(const char* data, std::size_t size)
{
// First check that socket is valid
if (!IsValid())
return Socket::Error;
// Check parameters
if (Data && Size)
if (data && size)
{
// Loop until every byte has been sent
int Sent = 0;
int SizeToSend = static_cast<int>(Size);
for (int Length = 0; Length < SizeToSend; Length += Sent)
int sent = 0;
int sizeToSend = static_cast<int>(size);
for (int length = 0; length < sizeToSend; length += sent)
{
// Send a chunk of data
Sent = send(mySocket, Data + Length, SizeToSend - Length, 0);
sent = send(mySocket, data + length, sizeToSend - length, 0);
// Check if an error occured
if (Sent <= 0)
if (sent <= 0)
return SocketHelper::GetErrorStatus();
}
@ -258,28 +258,28 @@ Socket::Status SocketTCP::Send(const char* Data, std::size_t Size)
/// Receive an array of bytes from the host (must be connected first).
/// This function will block if the socket is blocking
////////////////////////////////////////////////////////////
Socket::Status SocketTCP::Receive(char* Data, std::size_t MaxSize, std::size_t& SizeReceived)
Socket::Status SocketTCP::Receive(char* data, std::size_t maxSize, std::size_t& sizeReceived)
{
// First clear the size received
SizeReceived = 0;
sizeReceived = 0;
// Check that socket is valid
if (!IsValid())
return Socket::Error;
// Check parameters
if (Data && MaxSize)
if (data && maxSize)
{
// Receive a chunk of bytes
int Received = recv(mySocket, Data, static_cast<int>(MaxSize), 0);
int received = recv(mySocket, data, static_cast<int>(maxSize), 0);
// Check the number of bytes received
if (Received > 0)
if (received > 0)
{
SizeReceived = static_cast<std::size_t>(Received);
sizeReceived = static_cast<std::size_t>(received);
return Socket::Done;
}
else if (Received == 0)
else if (received == 0)
{
return Socket::Disconnected;
}
@ -300,20 +300,20 @@ Socket::Status SocketTCP::Receive(char* Data, std::size_t MaxSize, std::size_t&
////////////////////////////////////////////////////////////
/// Send a packet of data to the host (must be connected first)
////////////////////////////////////////////////////////////
Socket::Status SocketTCP::Send(Packet& PacketToSend)
Socket::Status SocketTCP::Send(Packet& packet)
{
// Get the data to send from the packet
std::size_t DataSize = 0;
const char* Data = PacketToSend.OnSend(DataSize);
std::size_t dataSize = 0;
const char* data = packet.OnSend(dataSize);
// Send the packet size
Uint32 PacketSize = htonl(static_cast<unsigned long>(DataSize));
Send(reinterpret_cast<const char*>(&PacketSize), sizeof(PacketSize));
Uint32 packetSize = htonl(static_cast<unsigned long>(dataSize));
Send(reinterpret_cast<const char*>(&packetSize), sizeof(packetSize));
// Send the packet data
if (PacketSize > 0)
if (packetSize > 0)
{
return Send(Data, DataSize);
return Send(data, dataSize);
}
else
{
@ -326,53 +326,53 @@ Socket::Status SocketTCP::Send(Packet& PacketToSend)
/// Receive a packet from the host (must be connected first).
/// This function will block if the socket is blocking
////////////////////////////////////////////////////////////
Socket::Status SocketTCP::Receive(Packet& PacketToReceive)
Socket::Status SocketTCP::Receive(Packet& packet)
{
// We start by getting the size of the incoming packet
Uint32 PacketSize = 0;
std::size_t Received = 0;
Uint32 packetSize = 0;
std::size_t received = 0;
if (myPendingPacketSize < 0)
{
Socket::Status Status = Receive(reinterpret_cast<char*>(&PacketSize), sizeof(PacketSize), Received);
if (Status != Socket::Done)
return Status;
Socket::Status status = Receive(reinterpret_cast<char*>(&packetSize), sizeof(packetSize), received);
if (status != Socket::Done)
return status;
PacketSize = ntohl(PacketSize);
packetSize = ntohl(packetSize);
}
else
{
// There is a pending packet : we already know its size
PacketSize = myPendingPacketSize;
packetSize = myPendingPacketSize;
}
// Then loop until we receive all the packet data
char Buffer[1024];
while (myPendingPacket.size() < PacketSize)
char buffer[1024];
while (myPendingPacket.size() < packetSize)
{
// Receive a chunk of data
std::size_t SizeToGet = std::min(static_cast<std::size_t>(PacketSize - myPendingPacket.size()), sizeof(Buffer));
Socket::Status Status = Receive(Buffer, SizeToGet, Received);
if (Status != Socket::Done)
std::size_t sizeToGet = std::min(static_cast<std::size_t>(packetSize - myPendingPacket.size()), sizeof(buffer));
Socket::Status status = Receive(buffer, sizeToGet, received);
if (status != Socket::Done)
{
// We must save the size of the pending packet until we can receive its content
if (Status == Socket::NotReady)
myPendingPacketSize = PacketSize;
return Status;
if (status == Socket::NotReady)
myPendingPacketSize = packetSize;
return status;
}
// Append it into the packet
if (Received > 0)
if (received > 0)
{
myPendingPacket.resize(myPendingPacket.size() + Received);
char* Begin = &myPendingPacket[0] + myPendingPacket.size() - Received;
memcpy(Begin, Buffer, Received);
myPendingPacket.resize(myPendingPacket.size() + received);
char* begin = &myPendingPacket[0] + myPendingPacket.size() - received;
memcpy(begin, buffer, received);
}
}
// We have received all the datas : we can copy it to the user packet, and clear our internal packet
PacketToReceive.Clear();
packet.Clear();
if (!myPendingPacket.empty())
PacketToReceive.OnReceive(&myPendingPacket[0], myPendingPacket.size());
packet.OnReceive(&myPendingPacket[0], myPendingPacket.size());
myPendingPacket.clear();
myPendingPacketSize = -1;
@ -415,18 +415,18 @@ bool SocketTCP::IsValid() const
////////////////////////////////////////////////////////////
/// Comparison operator ==
////////////////////////////////////////////////////////////
bool SocketTCP::operator ==(const SocketTCP& Other) const
bool SocketTCP::operator ==(const SocketTCP& other) const
{
return mySocket == Other.mySocket;
return mySocket == other.mySocket;
}
////////////////////////////////////////////////////////////
/// Comparison operator !=
////////////////////////////////////////////////////////////
bool SocketTCP::operator !=(const SocketTCP& Other) const
bool SocketTCP::operator !=(const SocketTCP& other) const
{
return mySocket != Other.mySocket;
return mySocket != other.mySocket;
}
@ -435,9 +435,9 @@ bool SocketTCP::operator !=(const SocketTCP& Other) const
/// Provided for compatibility with standard containers, as
/// comparing two sockets doesn't make much sense...
////////////////////////////////////////////////////////////
bool SocketTCP::operator <(const SocketTCP& Other) const
bool SocketTCP::operator <(const SocketTCP& other) const
{
return mySocket < Other.mySocket;
return mySocket < other.mySocket;
}
@ -445,19 +445,19 @@ bool SocketTCP::operator <(const SocketTCP& Other) const
/// Construct the socket from a socket descriptor
/// (for internal use only)
////////////////////////////////////////////////////////////
SocketTCP::SocketTCP(SocketHelper::SocketType Descriptor)
SocketTCP::SocketTCP(SocketHelper::SocketType descriptor)
{
Create(Descriptor);
Create(descriptor);
}
////////////////////////////////////////////////////////////
/// Create the socket
////////////////////////////////////////////////////////////
void SocketTCP::Create(SocketHelper::SocketType Descriptor)
void SocketTCP::Create(SocketHelper::SocketType descriptor)
{
// Use the given socket descriptor, or get a new one
mySocket = Descriptor ? Descriptor : socket(PF_INET, SOCK_STREAM, 0);
mySocket = descriptor ? descriptor : socket(PF_INET, SOCK_STREAM, 0);
myIsBlocking = true;
// Reset the pending packet
@ -468,15 +468,15 @@ void SocketTCP::Create(SocketHelper::SocketType Descriptor)
if (IsValid())
{
// To avoid the "Address already in use" error message when trying to bind to the same port
int Yes = 1;
if (setsockopt(mySocket, SOL_SOCKET, SO_REUSEADDR, reinterpret_cast<char*>(&Yes), sizeof(Yes)) == -1)
int yes = 1;
if (setsockopt(mySocket, SOL_SOCKET, SO_REUSEADDR, reinterpret_cast<char*>(&yes), sizeof(yes)) == -1)
{
std::cerr << "Failed to set socket option \"SO_REUSEADDR\" ; "
<< "binding to a same port may fail if too fast" << std::endl;
}
// Disable the Nagle algorithm (ie. removes buffering of TCP packets)
if (setsockopt(mySocket, IPPROTO_TCP, TCP_NODELAY, reinterpret_cast<char*>(&Yes), sizeof(Yes)) == -1)
if (setsockopt(mySocket, IPPROTO_TCP, TCP_NODELAY, reinterpret_cast<char*>(&yes), sizeof(yes)) == -1)
{
std::cerr << "Failed to set socket option \"TCP_NODELAY\" ; "
<< "all your TCP packets will be buffered" << std::endl;

View file

@ -47,48 +47,48 @@ SocketUDP::SocketUDP()
////////////////////////////////////////////////////////////
/// Change the blocking state of the socket
////////////////////////////////////////////////////////////
void SocketUDP::SetBlocking(bool Blocking)
void SocketUDP::SetBlocking(bool blocking)
{
// Make sure our socket is valid
if (!IsValid())
Create();
SocketHelper::SetBlocking(mySocket, Blocking);
myIsBlocking = Blocking;
SocketHelper::SetBlocking(mySocket, blocking);
myIsBlocking = blocking;
}
////////////////////////////////////////////////////////////
/// Bind the socket to a specific port
////////////////////////////////////////////////////////////
bool SocketUDP::Bind(unsigned short Port)
bool SocketUDP::Bind(unsigned short port)
{
// Check if the socket is already bound to the specified port
if (myPort != Port)
if (myPort != port)
{
// If the socket was previously bound to another port, we need to unbind it first
Unbind();
if (Port != 0)
if (port != 0)
{
// Build an address with the specified port
sockaddr_in Addr;
Addr.sin_family = AF_INET;
Addr.sin_port = htons(Port);
Addr.sin_addr.s_addr = INADDR_ANY;
memset(Addr.sin_zero, 0, sizeof(Addr.sin_zero));
sockaddr_in sockAddr;
sockAddr.sin_family = AF_INET;
sockAddr.sin_port = htons(port);
sockAddr.sin_addr.s_addr = INADDR_ANY;
memset(sockAddr.sin_zero, 0, sizeof(sockAddr.sin_zero));
// Bind the socket to the port
if (bind(mySocket, reinterpret_cast<sockaddr*>(&Addr), sizeof(Addr)) == -1)
if (bind(mySocket, reinterpret_cast<sockaddr*>(&sockAddr), sizeof(sockAddr)) == -1)
{
std::cerr << "Failed to bind the socket to port " << Port << std::endl;
std::cerr << "Failed to bind the socket to port " << port << std::endl;
myPort = 0;
return false;
}
}
// Save the new port
myPort = Port;
myPort = port;
}
return true;
@ -115,32 +115,32 @@ bool SocketUDP::Unbind()
////////////////////////////////////////////////////////////
/// Send an array of bytes
////////////////////////////////////////////////////////////
Socket::Status SocketUDP::Send(const char* Data, std::size_t Size, const IPAddress& Address, unsigned short Port)
Socket::Status SocketUDP::Send(const char* data, std::size_t size, const IPAddress& address, unsigned short port)
{
// Make sure the socket is valid
if (!IsValid())
Create();
// Check parameters
if (Data && Size)
if (data && size)
{
// Build the target address
sockaddr_in Target;
Target.sin_family = AF_INET;
Target.sin_port = htons(Port);
Target.sin_addr.s_addr = inet_addr(Address.ToString().c_str());
memset(Target.sin_zero, 0, sizeof(Target.sin_zero));
sockaddr_in sockAddr;
sockAddr.sin_family = AF_INET;
sockAddr.sin_port = htons(port);
sockAddr.sin_addr.s_addr = inet_addr(address.ToString().c_str());
memset(sockAddr.sin_zero, 0, sizeof(sockAddr.sin_zero));
// Loop until every byte has been sent
int Sent = 0;
int SizeToSend = static_cast<int>(Size);
for (int Length = 0; Length < SizeToSend; Length += Sent)
int sent = 0;
int sizeToSend = static_cast<int>(size);
for (int length = 0; length < sizeToSend; length += sent)
{
// Send a chunk of data
Sent = sendto(mySocket, Data + Length, SizeToSend - Length, 0, reinterpret_cast<sockaddr*>(&Target), sizeof(Target));
sent = sendto(mySocket, data + length, sizeToSend - length, 0, reinterpret_cast<sockaddr*>(&sockAddr), sizeof(sockAddr));
// Check errors
if (Sent <= 0)
if (sent <= 0)
return SocketHelper::GetErrorStatus();
}
@ -159,10 +159,10 @@ Socket::Status SocketUDP::Send(const char* Data, std::size_t Size, const IPAddre
/// Receive an array of bytes.
/// This function will block if the socket is blocking
////////////////////////////////////////////////////////////
Socket::Status SocketUDP::Receive(char* Data, std::size_t MaxSize, std::size_t& SizeReceived, IPAddress& Address, unsigned short& Port)
Socket::Status SocketUDP::Receive(char* data, std::size_t maxSize, std::size_t& sizeReceived, IPAddress& address, unsigned short& port)
{
// First clear the size received
SizeReceived = 0;
sizeReceived = 0;
// Make sure the socket is bound to a port
if (myPort == 0)
@ -176,32 +176,32 @@ Socket::Status SocketUDP::Receive(char* Data, std::size_t MaxSize, std::size_t&
Create();
// Check parameters
if (Data && MaxSize)
if (data && maxSize)
{
// Data that will be filled with the other computer's address
sockaddr_in Sender;
Sender.sin_family = AF_INET;
Sender.sin_port = 0;
Sender.sin_addr.s_addr = INADDR_ANY;
memset(Sender.sin_zero, 0, sizeof(Sender.sin_zero));
SocketHelper::LengthType SenderSize = sizeof(Sender);
sockaddr_in sockAddr;
sockAddr.sin_family = AF_INET;
sockAddr.sin_port = 0;
sockAddr.sin_addr.s_addr = INADDR_ANY;
memset(sockAddr.sin_zero, 0, sizeof(sockAddr.sin_zero));
SocketHelper::LengthType sockAddrSize = sizeof(sockAddr);
// Receive a chunk of bytes
int Received = recvfrom(mySocket, Data, static_cast<int>(MaxSize), 0, reinterpret_cast<sockaddr*>(&Sender), &SenderSize);
int received = recvfrom(mySocket, data, static_cast<int>(maxSize), 0, reinterpret_cast<sockaddr*>(&sockAddr), &sockAddrSize);
// Check the number of bytes received
if (Received > 0)
if (received > 0)
{
Address = IPAddress(inet_ntoa(Sender.sin_addr));
Port = ntohs(Sender.sin_port);
SizeReceived = static_cast<std::size_t>(Received);
address = IPAddress(inet_ntoa(sockAddr.sin_addr));
port = ntohs(sockAddr.sin_port);
sizeReceived = static_cast<std::size_t>(received);
return Socket::Done;
}
else
{
Address = IPAddress();
Port = 0;
return Received == 0 ? Socket::Disconnected : SocketHelper::GetErrorStatus();
address = IPAddress();
port = 0;
return received == 0 ? Socket::Disconnected : SocketHelper::GetErrorStatus();
}
}
else
@ -216,20 +216,20 @@ Socket::Status SocketUDP::Receive(char* Data, std::size_t MaxSize, std::size_t&
////////////////////////////////////////////////////////////
/// Send a packet of data
////////////////////////////////////////////////////////////
Socket::Status SocketUDP::Send(Packet& PacketToSend, const IPAddress& Address, unsigned short Port)
Socket::Status SocketUDP::Send(Packet& packet, const IPAddress& address, unsigned short port)
{
// Get the data to send from the packet
std::size_t DataSize = 0;
const char* Data = PacketToSend.OnSend(DataSize);
std::size_t dataSize = 0;
const char* data = packet.OnSend(dataSize);
// Send the packet size
Uint32 PacketSize = htonl(static_cast<unsigned long>(DataSize));
Send(reinterpret_cast<const char*>(&PacketSize), sizeof(PacketSize), Address, Port);
Uint32 packetSize = htonl(static_cast<unsigned long>(dataSize));
Send(reinterpret_cast<const char*>(&packetSize), sizeof(packetSize), address, port);
// Send the packet data
if (PacketSize > 0)
if (packetSize > 0)
{
return Send(Data, DataSize, Address, Port);
return Send(data, dataSize, address, port);
}
else
{
@ -242,65 +242,65 @@ Socket::Status SocketUDP::Send(Packet& PacketToSend, const IPAddress& Address, u
/// Receive a packet.
/// This function will block if the socket is blocking
////////////////////////////////////////////////////////////
Socket::Status SocketUDP::Receive(Packet& PacketToReceive, IPAddress& Address, unsigned short& Port)
Socket::Status SocketUDP::Receive(Packet& packet, IPAddress& address, unsigned short& port)
{
// This is not safe at all, as data can be lost, duplicated, or arrive in a different order.
// So if a packet is split into more than one chunk, nobody knows what could happen...
// Conclusion : we shouldn't use packets with UDP, unless we build a more complex protocol on top of it.
// We start by getting the size of the incoming packet
Uint32 PacketSize = 0;
std::size_t Received = 0;
Uint32 packetSize = 0;
std::size_t received = 0;
if (myPendingPacketSize < 0)
{
Socket::Status Status = Receive(reinterpret_cast<char*>(&PacketSize), sizeof(PacketSize), Received, Address, Port);
if (Status != Socket::Done)
return Status;
Socket::Status status = Receive(reinterpret_cast<char*>(&packetSize), sizeof(packetSize), received, address, port);
if (status != Socket::Done)
return status;
PacketSize = ntohl(PacketSize);
packetSize = ntohl(packetSize);
}
else
{
// There is a pending packet : we already know its size
PacketSize = myPendingPacketSize;
packetSize = myPendingPacketSize;
}
// Clear the user packet
PacketToReceive.Clear();
packet.Clear();
// Use another address instance for receiving the packet data ;
// chunks of data coming from a different sender will be discarded (and lost...)
IPAddress Sender;
unsigned short SenderPort;
IPAddress sender;
unsigned short senderPort;
// Then loop until we receive all the packet data
char Buffer[1024];
while (myPendingPacket.size() < PacketSize)
char buffer[1024];
while (myPendingPacket.size() < packetSize)
{
// Receive a chunk of data
std::size_t SizeToGet = std::min(static_cast<std::size_t>(PacketSize - myPendingPacket.size()), sizeof(Buffer));
Socket::Status Status = Receive(Buffer, SizeToGet, Received, Sender, SenderPort);
if (Status != Socket::Done)
std::size_t sizeToGet = std::min(static_cast<std::size_t>(packetSize - myPendingPacket.size()), sizeof(buffer));
Socket::Status status = Receive(buffer, sizeToGet, received, sender, senderPort);
if (status != Socket::Done)
{
// We must save the size of the pending packet until we can receive its content
if (Status == Socket::NotReady)
myPendingPacketSize = PacketSize;
return Status;
if (status == Socket::NotReady)
myPendingPacketSize = packetSize;
return status;
}
// Append it into the packet
if ((Sender == Address) && (SenderPort == Port) && (Received > 0))
if ((sender == address) && (senderPort == port) && (received > 0))
{
myPendingPacket.resize(myPendingPacket.size() + Received);
char* Begin = &myPendingPacket[0] + myPendingPacket.size() - Received;
memcpy(Begin, Buffer, Received);
myPendingPacket.resize(myPendingPacket.size() + received);
char* begin = &myPendingPacket[0] + myPendingPacket.size() - received;
memcpy(begin, buffer, received);
}
}
// We have received all the datas : we can copy it to the user packet, and clear our internal packet
PacketToReceive.Clear();
packet.Clear();
if (!myPendingPacket.empty())
PacketToReceive.OnReceive(&myPendingPacket[0], myPendingPacket.size());
packet.OnReceive(&myPendingPacket[0], myPendingPacket.size());
myPendingPacket.clear();
myPendingPacketSize = -1;
@ -353,18 +353,18 @@ unsigned short SocketUDP::GetPort() const
////////////////////////////////////////////////////////////
/// Comparison operator ==
////////////////////////////////////////////////////////////
bool SocketUDP::operator ==(const SocketUDP& Other) const
bool SocketUDP::operator ==(const SocketUDP& other) const
{
return mySocket == Other.mySocket;
return mySocket == other.mySocket;
}
////////////////////////////////////////////////////////////
/// Comparison operator !=
////////////////////////////////////////////////////////////
bool SocketUDP::operator !=(const SocketUDP& Other) const
bool SocketUDP::operator !=(const SocketUDP& other) const
{
return mySocket != Other.mySocket;
return mySocket != other.mySocket;
}
@ -373,9 +373,9 @@ bool SocketUDP::operator !=(const SocketUDP& Other) const
/// Provided for compatibility with standard containers, as
/// comparing two sockets doesn't make much sense...
////////////////////////////////////////////////////////////
bool SocketUDP::operator <(const SocketUDP& Other) const
bool SocketUDP::operator <(const SocketUDP& other) const
{
return mySocket < Other.mySocket;
return mySocket < other.mySocket;
}
@ -383,19 +383,19 @@ bool SocketUDP::operator <(const SocketUDP& Other) const
/// Construct the socket from a socket descriptor
/// (for internal use only)
////////////////////////////////////////////////////////////
SocketUDP::SocketUDP(SocketHelper::SocketType Descriptor)
SocketUDP::SocketUDP(SocketHelper::SocketType descriptor)
{
Create(Descriptor);
Create(descriptor);
}
////////////////////////////////////////////////////////////
/// Create the socket
////////////////////////////////////////////////////////////
void SocketUDP::Create(SocketHelper::SocketType Descriptor)
void SocketUDP::Create(SocketHelper::SocketType descriptor)
{
// Use the given socket descriptor, or get a new one
mySocket = Descriptor ? Descriptor : socket(PF_INET, SOCK_DGRAM, 0);
mySocket = descriptor ? descriptor : socket(PF_INET, SOCK_DGRAM, 0);
myIsBlocking = true;
// Clear the last port used
@ -409,15 +409,15 @@ void SocketUDP::Create(SocketHelper::SocketType Descriptor)
if (IsValid())
{
// To avoid the "Address already in use" error message when trying to bind to the same port
int Yes = 1;
if (setsockopt(mySocket, SOL_SOCKET, SO_REUSEADDR, reinterpret_cast<char*>(&Yes), sizeof(Yes)) == -1)
int yes = 1;
if (setsockopt(mySocket, SOL_SOCKET, SO_REUSEADDR, reinterpret_cast<char*>(&yes), sizeof(yes)) == -1)
{
std::cerr << "Failed to set socket option \"reuse address\" ; "
<< "binding to a same port may fail if too fast" << std::endl;
}
// Enable broadcast by default
if (setsockopt(mySocket, SOL_SOCKET, SO_BROADCAST, reinterpret_cast<char*>(&Yes), sizeof(Yes)) == -1)
if (setsockopt(mySocket, SOL_SOCKET, SO_BROADCAST, reinterpret_cast<char*>(&yes), sizeof(yes)) == -1)
{
std::cerr << "Failed to enable broadcast on UDP socket" << std::endl;
}

View file

@ -44,22 +44,22 @@ SocketHelper::SocketType SocketHelper::InvalidSocket()
////////////////////////////////////////////////////////////
/// Close / destroy a socket
////////////////////////////////////////////////////////////
bool SocketHelper::Close(SocketHelper::SocketType Socket)
bool SocketHelper::Close(SocketHelper::SocketType socket)
{
return close(Socket) != -1;
return close(socket) != -1;
}
////////////////////////////////////////////////////////////
/// Set a socket as blocking or non-blocking
////////////////////////////////////////////////////////////
void SocketHelper::SetBlocking(SocketHelper::SocketType Socket, bool Block)
void SocketHelper::SetBlocking(SocketHelper::SocketType sock, bool block)
{
int Status = fcntl(Socket, F_GETFL);
if (Block)
fcntl(Socket, F_SETFL, Status & ~O_NONBLOCK);
int status = fcntl(sock, F_GETFL);
if (block)
fcntl(sock, F_SETFL, status & ~O_NONBLOCK);
else
fcntl(Socket, F_SETFL, Status | O_NONBLOCK);
fcntl(sock, F_SETFL, status | O_NONBLOCK);
}

View file

@ -42,19 +42,19 @@ SocketHelper::SocketType SocketHelper::InvalidSocket()
////////////////////////////////////////////////////////////
/// Close / destroy a socket
////////////////////////////////////////////////////////////
bool SocketHelper::Close(SocketHelper::SocketType Socket)
bool SocketHelper::Close(SocketHelper::SocketType socket)
{
return closesocket(Socket) != -1;
return closesocket(socket) != -1;
}
////////////////////////////////////////////////////////////
/// Set a socket as blocking or non-blocking
////////////////////////////////////////////////////////////
void SocketHelper::SetBlocking(SocketHelper::SocketType Socket, bool Block)
void SocketHelper::SetBlocking(SocketHelper::SocketType socket, bool block)
{
unsigned long Blocking = Block ? 0 : 1;
ioctlsocket(Socket, FIONBIO, &Blocking);
unsigned long blocking = block ? 0 : 1;
ioctlsocket(socket, FIONBIO, &blocking);
}
@ -85,8 +85,8 @@ struct SocketInitializer
{
SocketInitializer()
{
WSADATA InitData;
WSAStartup(MAKEWORD(2,2), &InitData);
WSADATA init;
WSAStartup(MAKEWORD(2,2), &init);
}
~SocketInitializer()
@ -95,6 +95,6 @@ struct SocketInitializer
}
};
SocketInitializer GlobalInitializer;
SocketInitializer globalInitializer;
} // namespace sf

View file

@ -34,8 +34,8 @@ namespace sf
////////////////////////////////////////////////////////////
/// Construct the lock with a target mutex (lock it)
////////////////////////////////////////////////////////////
Lock::Lock(Mutex& Mutex) :
myMutex(Mutex)
Lock::Lock(Mutex& mutex) :
myMutex(mutex)
{
myMutex.Lock();
}

View file

@ -35,13 +35,13 @@ namespace
// Set the random numbers sequence seed with the current system time, so that it is always different
unsigned int InitializeSeed()
{
unsigned int Seed = static_cast<unsigned int>(sf::priv::Platform::GetSystemTime() * 1000);
srand(Seed);
return Seed;
unsigned int seed = static_cast<unsigned int>(sf::priv::Platform::GetSystemTime() * 1000);
srand(seed);
return seed;
}
// Global storing the current seed
unsigned int GlobalSeed = InitializeSeed();
// Global variable storing the current seed
unsigned int globalSeed = InitializeSeed();
}
@ -51,10 +51,10 @@ namespace sf
/// Set the seed for the generator. Using a known seed
/// allows you to reproduce the same sequence of random number
////////////////////////////////////////////////////////////
void Randomizer::SetSeed(unsigned int Seed)
void Randomizer::SetSeed(unsigned int seed)
{
srand(Seed);
GlobalSeed = Seed;
srand(seed);
globalSeed = seed;
}
@ -63,31 +63,31 @@ void Randomizer::SetSeed(unsigned int Seed)
////////////////////////////////////////////////////////////
unsigned int Randomizer::GetSeed()
{
return GlobalSeed;
return globalSeed;
}
////////////////////////////////////////////////////////////
/// Get a random float number in a given range
////////////////////////////////////////////////////////////
float Randomizer::Random(float Begin, float End)
float Randomizer::Random(float begin, float end)
{
// This is not the best algorithm, but it is fast and will be enough in most cases
// (see Google for best approaches)
return static_cast<float>(rand()) / RAND_MAX * (End - Begin) + Begin;
return static_cast<float>(rand()) / RAND_MAX * (end - begin) + begin;
}
////////////////////////////////////////////////////////////
/// Get a random integer number in a given range
////////////////////////////////////////////////////////////
int Randomizer::Random(int Begin, int End)
int Randomizer::Random(int begin, int end)
{
// This is not the best algorithm, but it is fast and will be enough in most cases
// (see Google for best approaches)
return rand() % (End - Begin + 1) + Begin;
return rand() % (end - begin + 1) + begin;
}
} // namespace sf

View file

@ -34,10 +34,10 @@ namespace sf
////////////////////////////////////////////////////////////
/// Make the current thread sleep for a given time
////////////////////////////////////////////////////////////
void Sleep(float Duration)
void Sleep(float duration)
{
if (Duration >= 0)
priv::Platform::Sleep(Duration);
if (duration >= 0)
priv::Platform::Sleep(duration);
}
} // namespace sf

View file

@ -56,10 +56,10 @@ myUserData (NULL)
////////////////////////////////////////////////////////////
/// Construct the thread from a function pointer
////////////////////////////////////////////////////////////
Thread::Thread(Thread::FuncType Function, void* UserData) :
Thread::Thread(Thread::FuncType function, void* userData) :
myThreadImpl(NULL),
myFunction (Function),
myUserData (UserData)
myFunction (function),
myUserData (userData)
{
}

View file

@ -44,10 +44,10 @@ namespace sf
////////////////////////////////////////////////////////////
/// Default constructor
////////////////////////////////////////////////////////////
ThreadLocal::ThreadLocal(void* Value)
ThreadLocal::ThreadLocal(void* value)
{
myImpl = new priv::ThreadLocalImpl;
SetValue(Value);
SetValue(value);
}
@ -63,9 +63,9 @@ ThreadLocal::~ThreadLocal()
////////////////////////////////////////////////////////////
/// Set the thread-specific value of the variable
////////////////////////////////////////////////////////////
void ThreadLocal::SetValue(void* Value)
void ThreadLocal::SetValue(void* value)
{
myImpl->SetValue(Value);
myImpl->SetValue(value);
}

View file

@ -38,19 +38,19 @@ namespace priv
////////////////////////////////////////////////////////////
double Platform::GetSystemTime()
{
timeval Time = {0, 0};
gettimeofday(&Time, NULL);
timeval time = {0, 0};
gettimeofday(&time, NULL);
return Time.tv_sec + Time.tv_usec / 1000000.;
return time.tv_sec + time.tv_usec / 1000000.;
}
////////////////////////////////////////////////////////////
/// Suspend the execution of the current thread for a specified time
////////////////////////////////////////////////////////////
void Platform::Sleep(float Time)
void Platform::Sleep(float time)
{
usleep(static_cast<unsigned long>(Time * 1000000));
usleep(static_cast<unsigned long>(time * 1000000));
}
} // namespace priv

View file

@ -55,10 +55,10 @@ public :
////////////////////////////////////////////////////////////
/// Suspend the execution of the current thread for a specified time
///
/// \param Time : Time to sleep, in seconds
/// \param time : Time to sleep, in seconds
///
////////////////////////////////////////////////////////////
static void Sleep(float Time);
static void Sleep(float time);
};
} // namespace priv

View file

@ -37,10 +37,10 @@ namespace priv
////////////////////////////////////////////////////////////
/// Default constructor
////////////////////////////////////////////////////////////
ThreadImpl::ThreadImpl(Thread* Owner) :
ThreadImpl::ThreadImpl(Thread* owner) :
myIsActive(true)
{
myIsActive = pthread_create(&myThread, NULL, &ThreadImpl::EntryPoint, Owner) == 0;
myIsActive = pthread_create(&myThread, NULL, &ThreadImpl::EntryPoint, owner) == 0;
if (!myIsActive)
std::cerr << "Failed to create thread" << std::endl;
@ -73,16 +73,16 @@ void ThreadImpl::Terminate()
////////////////////////////////////////////////////////////
/// Global entry point for all threads
////////////////////////////////////////////////////////////
void* ThreadImpl::EntryPoint(void* UserData)
void* ThreadImpl::EntryPoint(void* userData)
{
// The Thread instance is stored in the user data
Thread* Owner = static_cast<Thread*>(UserData);
Thread* owner = static_cast<Thread*>(userData);
// Tell the thread to handle cancel requests immediatly
pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
// Forward to the owner
Owner->Run();
owner->Run();
return NULL;
}

View file

@ -48,10 +48,10 @@ public :
////////////////////////////////////////////////////////////
/// Default constructor, launch the thread
///
/// \param Owner : Owner Thread instance to run
/// \param owner : Owner Thread instance to run
///
////////////////////////////////////////////////////////////
ThreadImpl(Thread* Owner);
ThreadImpl(Thread* owner);
////////////////////////////////////////////////////////////
/// Wait until the thread finishes
@ -73,12 +73,12 @@ private :
////////////////////////////////////////////////////////////
/// Global entry point for all threads
///
/// \param UserData : User-defined data (contains the Thread instance)
/// \param userData : User-defined data (contains the Thread instance)
///
/// \return Error code
///
////////////////////////////////////////////////////////////
static void* EntryPoint(void* UserData);
static void* EntryPoint(void* userData);
////////////////////////////////////////////////////////////
// Member data

View file

@ -53,9 +53,9 @@ ThreadLocalImpl::~ThreadLocalImpl()
////////////////////////////////////////////////////////////
/// Set the thread-specific value of the variable
////////////////////////////////////////////////////////////
void ThreadLocalImpl::SetValue(void* Value)
void ThreadLocalImpl::SetValue(void* value)
{
pthread_setspecific(myKey, Value);
pthread_setspecific(myKey, value);
}

View file

@ -58,10 +58,10 @@ public :
////////////////////////////////////////////////////////////
/// Set the thread-specific value of the variable
///
/// \param Value : Value of the variable for this thread
/// \param value : Value of the variable for this thread
///
////////////////////////////////////////////////////////////
void SetValue(void* Value);
void SetValue(void* value);
////////////////////////////////////////////////////////////
/// Retrieve the thread-specific value of the variable

View file

@ -55,10 +55,10 @@ public :
////////////////////////////////////////////////////////////
/// Suspend the execution of the current thread for a specified time
///
/// \param Time : Time to sleep, in seconds
/// \param time : Time to sleep, in seconds
///
////////////////////////////////////////////////////////////
static void Sleep(float Time);
static void Sleep(float time);
};
} // namespace priv

View file

@ -38,9 +38,9 @@ namespace priv
////////////////////////////////////////////////////////////
/// Default constructor
////////////////////////////////////////////////////////////
ThreadImpl::ThreadImpl(Thread* Owner)
ThreadImpl::ThreadImpl(Thread* owner)
{
myThread = reinterpret_cast<HANDLE>(_beginthreadex(NULL, 0, &ThreadImpl::EntryPoint, Owner, 0, NULL));
myThread = reinterpret_cast<HANDLE>(_beginthreadex(NULL, 0, &ThreadImpl::EntryPoint, owner, 0, NULL));
if (!myThread)
std::cerr << "Failed to create thread" << std::endl;
@ -83,13 +83,13 @@ void ThreadImpl::Terminate()
////////////////////////////////////////////////////////////
/// Global entry point for all threads
////////////////////////////////////////////////////////////
unsigned int __stdcall ThreadImpl::EntryPoint(void* UserData)
unsigned int __stdcall ThreadImpl::EntryPoint(void* userData)
{
// The Thread instance is stored in the user data
Thread* Owner = static_cast<Thread*>(UserData);
Thread* owner = static_cast<Thread*>(userData);
// Forward to the owner
Owner->Run();
owner->Run();
// Optional, but it is cleaner
_endthreadex(0);

View file

@ -48,10 +48,10 @@ public :
////////////////////////////////////////////////////////////
/// Default constructor, launch the thread
///
/// \param Owner : Owner Thread instance to run
/// \param owner : Owner Thread instance to run
///
////////////////////////////////////////////////////////////
ThreadImpl(Thread* Owner);
ThreadImpl(Thread* owner);
////////////////////////////////////////////////////////////
/// Destructor
@ -79,12 +79,12 @@ private :
////////////////////////////////////////////////////////////
/// Global entry point for all threads
///
/// \param UserData : User-defined data (contains the Thread instance)
/// \param userData : User-defined data (contains the Thread instance)
///
/// \return Error code
///
////////////////////////////////////////////////////////////
static unsigned int __stdcall EntryPoint(void* UserData);
static unsigned int __stdcall EntryPoint(void* userData);
////////////////////////////////////////////////////////////
// Member data

View file

@ -53,9 +53,9 @@ ThreadLocalImpl::~ThreadLocalImpl()
////////////////////////////////////////////////////////////
/// Set the thread-specific value of the variable
////////////////////////////////////////////////////////////
void ThreadLocalImpl::SetValue(void* Value)
void ThreadLocalImpl::SetValue(void* value)
{
TlsSetValue(myIndex, Value);
TlsSetValue(myIndex, value);
}

View file

@ -58,10 +58,10 @@ public :
////////////////////////////////////////////////////////////
/// Set the thread-specific value of the variable
///
/// \param Value : Value of the variable for this thread
/// \param value : Value of the variable for this thread
///
////////////////////////////////////////////////////////////
void SetValue(void* Value);
void SetValue(void* value);
////////////////////////////////////////////////////////////
/// Retrieve the thread-specific value of the variable

View file

@ -54,9 +54,9 @@ Context::~Context()
////////////////////////////////////////////////////////////
/// Activate or deactivate explicitely the context
////////////////////////////////////////////////////////////
void Context::SetActive(bool Active)
void Context::SetActive(bool active)
{
myContext->SetActive(Active);
myContext->SetActive(active);
}

View file

@ -56,15 +56,15 @@
namespace
{
// This thread-local variable will hold the "global" context for each thread
sf::ThreadLocalPtr<sf::priv::ContextGL> ThreadContext(NULL);
sf::ThreadLocalPtr<sf::priv::ContextGL> threadContext(NULL);
// Now we create two global contexts.
// The first one is the reference context: it will be shared with every other
// context, and he can't be activated if we want the sharing operation to always succeed.
// That why we need the second context: this one will be activated and used
// context, and it can't be activated if we want the sharing operation to always succeed.
// That's why we need the second context: this one will be activated and used
// in the main thread whenever there's no other context (window) active.
ContextType ReferenceContext(NULL);
ContextType DefaultContext(&ReferenceContext);
ContextType referenceContext(NULL);
ContextType defaultContext(&referenceContext);
}
@ -77,22 +77,22 @@ namespace priv
////////////////////////////////////////////////////////////
ContextGL* ContextGL::New()
{
return new ContextType(&ReferenceContext);
return new ContextType(&referenceContext);
}
////////////////////////////////////////////////////////////
/// Create a new context attached to a window
////////////////////////////////////////////////////////////
ContextGL* ContextGL::New(const WindowImpl* Owner, unsigned int BitsPerPixel, const ContextSettings& Settings)
ContextGL* ContextGL::New(const WindowImpl* owner, unsigned int bitsPerPixel, const ContextSettings& settings)
{
ContextType* Context = new ContextType(&ReferenceContext, Owner, BitsPerPixel, Settings);
ContextType* context = new ContextType(&referenceContext, owner, bitsPerPixel, settings);
// Enable antialiasing if needed
if (Context->GetSettings().AntialiasingLevel > 0)
if (context->GetSettings().AntialiasingLevel > 0)
glEnable(GL_MULTISAMPLE_ARB);
return Context;
return context;
}
@ -101,13 +101,13 @@ ContextGL* ContextGL::New(const WindowImpl* Owner, unsigned int BitsPerPixel, co
////////////////////////////////////////////////////////////
ContextGL::~ContextGL()
{
if (ThreadContext == this)
if (threadContext == this)
{
ThreadContext = NULL;
threadContext = NULL;
}
else if (ThreadContext != NULL)
else if (threadContext != NULL)
{
ThreadContext->SetActive(true);
threadContext->SetActive(true);
}
}
@ -125,21 +125,21 @@ const ContextSettings& ContextGL::GetSettings() const
/// Activate or deactivate the context as the current target
/// for rendering
////////////////////////////////////////////////////////////
bool ContextGL::SetActive(bool Active)
bool ContextGL::SetActive(bool active)
{
if (MakeCurrent(Active))
if (MakeCurrent(active))
{
if (Active && (ThreadContext == NULL))
if (active && (threadContext == 0))
{
// If this is the first context to be activated on this thread, make
// it the reference context for the whole thread
ThreadContext = this;
threadContext = this;
}
else if (!Active && (ThreadContext != NULL) && (ThreadContext != this))
else if (!active && (threadContext != NULL) && (threadContext != this))
{
// Activate the reference context for this thread to ensure
// that there is always an active context for subsequent graphics operations
ThreadContext->SetActive(true);
threadContext->SetActive(true);
}
return true;
@ -165,12 +165,12 @@ ContextGL::ContextGL()
/// This functions can be used by implementations that have
/// several valid formats and want to get the best one
////////////////////////////////////////////////////////////
int ContextGL::EvaluateFormat(unsigned int BitsPerPixel, const ContextSettings& Settings, int ColorBits, int DepthBits, int StencilBits, int Antialiasing)
int ContextGL::EvaluateFormat(unsigned int bitsPerPixel, const ContextSettings& settings, int colorBits, int depthBits, int stencilBits, int antialiasing)
{
return abs(static_cast<int>(BitsPerPixel - ColorBits)) +
abs(static_cast<int>(Settings.DepthBits - DepthBits)) +
abs(static_cast<int>(Settings.StencilBits - StencilBits)) +
abs(static_cast<int>(Settings.AntialiasingLevel - Antialiasing));
return abs(static_cast<int>(bitsPerPixel - colorBits)) +
abs(static_cast<int>(settings.DepthBits - depthBits)) +
abs(static_cast<int>(settings.StencilBits - stencilBits)) +
abs(static_cast<int>(settings.AntialiasingLevel - antialiasing));
}
} // namespace priv

View file

@ -57,14 +57,14 @@ public :
////////////////////////////////////////////////////////////
/// Create a new context attached to a window
///
/// \param Owner : Pointer to the owner window
/// \param BitsPerPixel : Pixel depth (in bits per pixel)
/// \param Settings : Creation parameters
/// \param owner : Pointer to the owner window
/// \param bitsPerPixel : Pixel depth (in bits per pixel)
/// \param settings : Creation parameters
///
/// \return Pointer to the created context
///
////////////////////////////////////////////////////////////
static ContextGL* New(const WindowImpl* Owner, unsigned int BitsPerPixel, const ContextSettings& Settings);
static ContextGL* New(const WindowImpl* owner, unsigned int bitsPerPixel, const ContextSettings& settings);
public :
@ -86,12 +86,12 @@ public :
/// Activate or deactivate the context as the current target
/// for rendering
///
/// \param Active : True to activate, false to deactivate
/// \param active : True to activate, false to deactivate
///
/// \return True if operation was successful, false otherwise
///
////////////////////////////////////////////////////////////
bool SetActive(bool Active);
bool SetActive(bool active);
////////////////////////////////////////////////////////////
/// Display the contents of the context
@ -102,10 +102,10 @@ public :
////////////////////////////////////////////////////////////
/// Enable / disable vertical synchronization
///
/// \param Enabled : True to enable v-sync, false to deactivate
/// \param enabled : True to enable v-sync, false to deactivate
///
////////////////////////////////////////////////////////////
virtual void UseVerticalSync(bool Enabled) = 0;
virtual void UseVerticalSync(bool enabled) = 0;
protected :
@ -118,29 +118,29 @@ protected :
////////////////////////////////////////////////////////////
/// Make this context the current one
///
/// \param Active : True to activate, false to deactivate
/// \param active : True to activate, false to deactivate
///
/// \return True on success, false if any error happened
///
////////////////////////////////////////////////////////////
virtual bool MakeCurrent(bool Active) = 0;
virtual bool MakeCurrent(bool active) = 0;
////////////////////////////////////////////////////////////
/// Evaluate a pixel format configuration.
/// This functions can be used by implementations that have
/// several valid formats and want to get the best one
///
/// \param BitsPerPixel : Requested pixel depth (bits per pixel)
/// \param Settings : Requested additionnal settings
/// \param ColorBits : Color bits of the configuration to evaluate
/// \param DepthBits : Depth bits of the configuration to evaluate
/// \param StencilBits : Stencil bits of the configuration to evaluate
/// \param Antialiasing : Antialiasing level of the configuration to evaluate
/// \param bitsPerPixel : Requested pixel depth (bits per pixel)
/// \param settings : Requested additionnal settings
/// \param colorBits : Color bits of the configuration to evaluate
/// \param depthBits : Depth bits of the configuration to evaluate
/// \param stencilBits : Stencil bits of the configuration to evaluate
/// \param antialiasing : Antialiasing level of the configuration to evaluate
///
/// \return Score of the configuration : the lower the better
///
////////////////////////////////////////////////////////////
static int EvaluateFormat(unsigned int BitsPerPixel, const ContextSettings& Settings, int ColorBits, int DepthBits, int StencilBits, int Antialiasing);
static int EvaluateFormat(unsigned int bitsPerPixel, const ContextSettings& settings, int colorBits, int depthBits, int stencilBits, int antialiasing);
////////////////////////////////////////////////////////////
// Member data

View file

@ -60,28 +60,28 @@ myMouseY(0)
////////////////////////////////////////////////////////////
/// Get the state of a key
////////////////////////////////////////////////////////////
bool Input::IsKeyDown(Key::Code KeyCode) const
bool Input::IsKeyDown(Key::Code key) const
{
return myKeys[KeyCode];
return myKeys[key];
}
////////////////////////////////////////////////////////////
/// Get the state of a mouse button
////////////////////////////////////////////////////////////
bool Input::IsMouseButtonDown(Mouse::Button Button) const
bool Input::IsMouseButtonDown(Mouse::Button button) const
{
return myMouseButtons[Button];
return myMouseButtons[button];
}
////////////////////////////////////////////////////////////
/// Get the state of a joystick button
////////////////////////////////////////////////////////////
bool Input::IsJoystickButtonDown(unsigned int JoyId, unsigned int Button) const
bool Input::IsJoystickButtonDown(unsigned int joystick, unsigned int button) const
{
if ((JoyId < 2) && (Button < 16))
return myJoystickButtons[JoyId][Button];
if ((joystick < 2) && (button < 16))
return myJoystickButtons[joystick][button];
else
return false;
}
@ -108,40 +108,40 @@ int Input::GetMouseY() const
////////////////////////////////////////////////////////////
/// Get a joystick axis position
////////////////////////////////////////////////////////////
float Input::GetJoystickAxis(unsigned int JoyId, Joy::Axis Axis) const
float Input::GetJoystickAxis(unsigned int joystick, Joy::Axis axis) const
{
return myJoystickAxis[JoyId][Axis];
return myJoystickAxis[joystick][axis];
}
////////////////////////////////////////////////////////////
/// /see WindowListener::OnEvent
////////////////////////////////////////////////////////////
void Input::OnEvent(const Event& EventReceived)
void Input::OnEvent(const Event& event)
{
switch (EventReceived.Type)
switch (event.Type)
{
// Key events
case Event::KeyPressed : myKeys[EventReceived.Key.Code] = true; break;
case Event::KeyReleased : myKeys[EventReceived.Key.Code] = false; break;
case Event::KeyPressed : myKeys[event.Key.Code] = true; break;
case Event::KeyReleased : myKeys[event.Key.Code] = false; break;
// Mouse event
case Event::MouseButtonPressed : myMouseButtons[EventReceived.MouseButton.Button] = true; break;
case Event::MouseButtonReleased : myMouseButtons[EventReceived.MouseButton.Button] = false; break;
case Event::MouseButtonPressed : myMouseButtons[event.MouseButton.Button] = true; break;
case Event::MouseButtonReleased : myMouseButtons[event.MouseButton.Button] = false; break;
// Mouse move event
case Event::MouseMoved :
myMouseX = EventReceived.MouseMove.X;
myMouseY = EventReceived.MouseMove.Y;
myMouseX = event.MouseMove.X;
myMouseY = event.MouseMove.Y;
break;
// Joystick button events
case Event::JoyButtonPressed : myJoystickButtons[EventReceived.JoyButton.JoystickId][EventReceived.JoyButton.Button] = true; break;
case Event::JoyButtonReleased : myJoystickButtons[EventReceived.JoyButton.JoystickId][EventReceived.JoyButton.Button] = false; break;
case Event::JoyButtonPressed : myJoystickButtons[event.JoyButton.JoystickId][event.JoyButton.Button] = true; break;
case Event::JoyButtonReleased : myJoystickButtons[event.JoyButton.JoystickId][event.JoyButton.Button] = false; break;
// Joystick move event
case Event::JoyMoved :
myJoystickAxis[EventReceived.JoyMove.JoystickId][EventReceived.JoyMove.Axis] = EventReceived.JoyMove.Position;
myJoystickAxis[event.JoyMove.JoystickId][event.JoyMove.Axis] = event.JoyMove.Position;
break;
// Lost focus event : we must reset all persistent states

View file

@ -39,28 +39,28 @@ namespace priv
////////////////////////////////////////////////////////////
/// Create a new context, not associated to a window
////////////////////////////////////////////////////////////
ContextGLX::ContextGLX(ContextGLX* Shared) :
ContextGLX::ContextGLX(ContextGLX* shared) :
myWindow (0),
myContext (NULL),
myOwnsWindow(true)
{
// Create a dummy window (disabled and hidden)
int Screen = DefaultScreen(myDisplay.GetDisplay());
int screen = DefaultScreen(myDisplay.GetDisplay());
myWindow = XCreateWindow(myDisplay.GetDisplay(),
RootWindow(myDisplay.GetDisplay(), Screen),
RootWindow(myDisplay.GetDisplay(), screen),
0, 0,
1, 1,
0,
DefaultDepth(myDisplay.GetDisplay(), Screen),
DefaultDepth(myDisplay.GetDisplay(), screen),
InputOutput,
DefaultVisual(myDisplay.GetDisplay(), Screen),
DefaultVisual(myDisplay.GetDisplay(), screen),
0, NULL);
// Create the context
CreateContext(Shared, VideoMode::GetDesktopMode().BitsPerPixel, ContextSettings(0, 0, 0));
CreateContext(shared, VideoMode::GetDesktopMode().BitsPerPixel, ContextSettings(0, 0, 0));
// Activate the context
if (Shared)
if (shared)
SetActive(true);
}
@ -68,20 +68,20 @@ myOwnsWindow(true)
////////////////////////////////////////////////////////////
/// Create a new context attached to a window
////////////////////////////////////////////////////////////
ContextGLX::ContextGLX(ContextGLX* Shared, const WindowImpl* Owner, unsigned int BitsPerPixel, const ContextSettings& Settings) :
ContextGLX::ContextGLX(ContextGLX* shared, const WindowImpl* owner, unsigned int bitsPerPixel, const ContextSettings& settings) :
myWindow (0),
myContext (NULL),
myOwnsWindow(false)
{
// Get the owner window and its device context
myWindow = static_cast<Window>(Owner->GetHandle());
myWindow = static_cast<Window>(owner->GetHandle());
// Create the context
if (myWindow)
CreateContext(Shared, BitsPerPixel, Settings);
CreateContext(shared, bitsPerPixel, settings);
// Activate the context
if (Shared)
if (shared)
SetActive(true);
}
@ -111,9 +111,9 @@ ContextGLX::~ContextGLX()
////////////////////////////////////////////////////////////
/// \see Context::MakeCurrent
////////////////////////////////////////////////////////////
bool ContextGLX::MakeCurrent(bool Active)
bool ContextGLX::MakeCurrent(bool active)
{
if (Active)
if (active)
{
if (myContext)
{
@ -150,12 +150,12 @@ void ContextGLX::Display()
////////////////////////////////////////////////////////////
/// \see Context::UseVerticalSync
////////////////////////////////////////////////////////////
void ContextGLX::UseVerticalSync(bool Enabled)
void ContextGLX::UseVerticalSync(bool enabled)
{
const GLubyte* ProcAddress = reinterpret_cast<const GLubyte*>("glXSwapIntervalSGI");
PFNGLXSWAPINTERVALSGIPROC glXSwapIntervalSGI = reinterpret_cast<PFNGLXSWAPINTERVALSGIPROC>(glXGetProcAddress(ProcAddress));
const GLubyte* name = reinterpret_cast<const GLubyte*>("glXSwapIntervalSGI");
PFNGLXSWAPINTERVALSGIPROC glXSwapIntervalSGI = reinterpret_cast<PFNGLXSWAPINTERVALSGIPROC>(glXGetProcAddress(name));
if (glXSwapIntervalSGI)
glXSwapIntervalSGI(Enabled ? 1 : 0);
glXSwapIntervalSGI(enabled ? 1 : 0);
}
@ -171,28 +171,28 @@ bool ContextGLX::IsContextActive()
////////////////////////////////////////////////////////////
/// Create the context
////////////////////////////////////////////////////////////
void ContextGLX::CreateContext(ContextGLX* Shared, unsigned int BitsPerPixel, const ContextSettings& Settings)
void ContextGLX::CreateContext(ContextGLX* shared, unsigned int bitsPerPixel, const ContextSettings& settings)
{
// Save the creation settings
mySettings = Settings;
mySettings = settings;
// Get the attributes of the target window
XWindowAttributes WindowAttributes;
if (XGetWindowAttributes(myDisplay.GetDisplay(), myWindow, &WindowAttributes) == 0)
XWindowAttributes windowAttributes;
if (XGetWindowAttributes(myDisplay.GetDisplay(), myWindow, &windowAttributes) == 0)
{
std::cerr << "Failed to get the window attributes" << std::endl;
return;
}
// Setup the visual infos to match
XVisualInfo Template;
Template.depth = WindowAttributes.depth;
Template.visualid = XVisualIDFromVisual(WindowAttributes.visual);
Template.screen = DefaultScreen(myDisplay.GetDisplay());
XVisualInfo tpl;
tpl.depth = windowAttributes.depth;
tpl.visualid = XVisualIDFromVisual(windowAttributes.visual);
tpl.screen = DefaultScreen(myDisplay.GetDisplay());
// Get all the visuals matching the template
int NbVisuals = 0;
XVisualInfo* Visuals = XGetVisualInfo(myDisplay.GetDisplay(), VisualDepthMask | VisualIDMask | VisualScreenMask, &Template, &NbVisuals);
int nbVisuals = 0;
XVisualInfo* visuals = XGetVisualInfo(myDisplay.GetDisplay(), VisualDepthMask | VisualIDMask | VisualScreenMask, &tpl, &nbVisuals);
if (!Visuals || (NbVisuals == 0))
{
if (Visuals)
@ -202,43 +202,43 @@ void ContextGLX::CreateContext(ContextGLX* Shared, unsigned int BitsPerPixel, co
}
// Find the best visual
int BestScore = 0xFFFF;
XVisualInfo* BestVisual = NULL;
while (!BestVisual)
int bestScore = 0xFFFF;
XVisualInfo* bestVisual = NULL;
while (!bestVisual)
{
for (int i = 0; i < NbVisuals; ++i)
for (int i = 0; i < nbVisuals; ++i)
{
// Get the current visual attributes
int RGBA, DoubleBuffer, Red, Green, Blue, Alpha, Depth, Stencil, MultiSampling, Samples;
glXGetConfig(myDisplay.GetDisplay(), &Visuals[i], GLX_RGBA, &RGBA);
glXGetConfig(myDisplay.GetDisplay(), &Visuals[i], GLX_DOUBLEBUFFER, &DoubleBuffer);
glXGetConfig(myDisplay.GetDisplay(), &Visuals[i], GLX_RED_SIZE, &Red);
glXGetConfig(myDisplay.GetDisplay(), &Visuals[i], GLX_GREEN_SIZE, &Green);
glXGetConfig(myDisplay.GetDisplay(), &Visuals[i], GLX_BLUE_SIZE, &Blue);
glXGetConfig(myDisplay.GetDisplay(), &Visuals[i], GLX_ALPHA_SIZE, &Alpha);
glXGetConfig(myDisplay.GetDisplay(), &Visuals[i], GLX_DEPTH_SIZE, &Depth);
glXGetConfig(myDisplay.GetDisplay(), &Visuals[i], GLX_STENCIL_SIZE, &Stencil);
glXGetConfig(myDisplay.GetDisplay(), &Visuals[i], GLX_SAMPLE_BUFFERS_ARB, &MultiSampling);
glXGetConfig(myDisplay.GetDisplay(), &Visuals[i], GLX_SAMPLES_ARB, &Samples);
int RGBA, doubleBuffer, red, green, blue, alpha, depth, stencil, multiSampling, samples;
glXGetConfig(myDisplay.GetDisplay(), &visuals[i], GLX_RGBA, &RGBA);
glXGetConfig(myDisplay.GetDisplay(), &visuals[i], GLX_DOUBLEBUFFER, &doubleBuffer);
glXGetConfig(myDisplay.GetDisplay(), &visuals[i], GLX_RED_SIZE, &red);
glXGetConfig(myDisplay.GetDisplay(), &visuals[i], GLX_GREEN_SIZE, &green);
glXGetConfig(myDisplay.GetDisplay(), &visuals[i], GLX_BLUE_SIZE, &blue);
glXGetConfig(myDisplay.GetDisplay(), &visuals[i], GLX_ALPHA_SIZE, &alpha);
glXGetConfig(myDisplay.GetDisplay(), &visuals[i], GLX_DEPTH_SIZE, &depth);
glXGetConfig(myDisplay.GetDisplay(), &visuals[i], GLX_STENCIL_SIZE, &stencil);
glXGetConfig(myDisplay.GetDisplay(), &visuals[i], GLX_SAMPLE_BUFFERS_ARB, &multiSampling);
glXGetConfig(myDisplay.GetDisplay(), &visuals[i], GLX_SAMPLES_ARB, &samples);
// First check the mandatory parameters
if ((RGBA == 0) || (DoubleBuffer == 0))
if ((RGBA == 0) || (doubleBuffer == 0))
continue;
// Evaluate the current configuration
int Color = Red + Green + Blue + Alpha;
int Score = EvaluateFormat(BitsPerPixel, mySettings, Color, Depth, Stencil, MultiSampling ? Samples : 0);
int color = red + green + blue + alpha;
int score = EvaluateFormat(bitsPerPixel, mySettings, color, depth, stencil, multiSampling ? samples : 0);
// Keep it if it's better than the current best
if (Score < BestScore)
if (score < bestScore)
{
BestScore = Score;
BestVisual = &Visuals[i];
bestScore = score;
bestVisual = &visuals[i];
}
}
// If no visual has been found, try a lower level of antialiasing
if (!BestVisual)
if (!bestVisual)
{
if (mySettings.AntialiasingLevel > 2)
{
@ -260,10 +260,10 @@ void ContextGLX::CreateContext(ContextGLX* Shared, unsigned int BitsPerPixel, co
}
// Get the context to share display lists with
GLXContext ToShare = Shared ? Shared->myContext : NULL;
GLXContext toShare = shared ? shared->myContext : NULL;
// Create the context
myContext = glXCreateContext(myDisplay.GetDisplay(), BestVisual, ToShare, true);
myContext = glXCreateContext(myDisplay.GetDisplay(), bestVisual, toShare, true);
if (!myContext)
{
std::cerr << "Failed to create an OpenGL context for this window" << std::endl;
@ -271,19 +271,19 @@ void ContextGLX::CreateContext(ContextGLX* Shared, unsigned int BitsPerPixel, co
}
// Update the creation settings from the chosen format
int Depth, Stencil;
glXGetConfig(myDisplay.GetDisplay(), BestVisual, GLX_DEPTH_SIZE, &Depth);
glXGetConfig(myDisplay.GetDisplay(), BestVisual, GLX_STENCIL_SIZE, &Stencil);
mySettings.DepthBits = static_cast<unsigned int>(Depth);
mySettings.StencilBits = static_cast<unsigned int>(Stencil);
int depth, stencil;
glXGetConfig(myDisplay.GetDisplay(), bestVisual, GLX_DEPTH_SIZE, &depth);
glXGetConfig(myDisplay.GetDisplay(), bestVisual, GLX_STENCIL_SIZE, &stencil);
mySettings.DepthBits = static_cast<unsigned int>(depth);
mySettings.StencilBits = static_cast<unsigned int>(stencil);
// Change the target window's colormap so that it matches the context's one
::Window Root = RootWindow(myDisplay.GetDisplay(), DefaultScreen(myDisplay.GetDisplay()));
Colormap ColMap = XCreateColormap(myDisplay.GetDisplay(), Root, BestVisual->visual, AllocNone);
XSetWindowColormap(myDisplay.GetDisplay(), myWindow, ColMap);
::Window root = RootWindow(myDisplay.GetDisplay(), DefaultScreen(myDisplay.GetDisplay()));
Colormap colorMap = XCreateColormap(myDisplay.GetDisplay(), root, bestVisual->visual, AllocNone);
XSetWindowColormap(myDisplay.GetDisplay(), myWindow, colorMap);
// Free the temporary visuals array
XFree(Visuals);
XFree(visuals);
}
} // namespace priv

View file

@ -48,21 +48,21 @@ public :
////////////////////////////////////////////////////////////
/// Create a new context, not associated to a window
///
/// \param Shared : Context to share the new one with (can be NULL)
/// \param shared : Context to share the new one with (can be NULL)
///
////////////////////////////////////////////////////////////
ContextGLX(ContextGLX* Shared);
ContextGLX(ContextGLX* shared);
////////////////////////////////////////////////////////////
/// Create a new context attached to a window
///
/// \param Shared : Context to share the new one with (can be NULL)
/// \param Owner : Pointer to the owner window
/// \param BitsPerPixel : Pixel depth (in bits per pixel)
/// \param Settings : Creation parameters
/// \param shared : Context to share the new one with (can be NULL)
/// \param owner : Pointer to the owner window
/// \param bitsPerPixel : Pixel depth (in bits per pixel)
/// \param settings : Creation parameters
///
////////////////////////////////////////////////////////////
ContextGLX(ContextGLX* Shared, const WindowImpl* Owner, unsigned int BitsPerPixel, const ContextSettings& Settings);
ContextGLX(ContextGLX* shared, const WindowImpl* owner, unsigned int bitsPerPixel, const ContextSettings& settings);
////////////////////////////////////////////////////////////
/// Destructor
@ -74,7 +74,7 @@ public :
/// \see Context::MakeCurrent
///
////////////////////////////////////////////////////////////
virtual bool MakeCurrent(bool Active);
virtual bool MakeCurrent(bool active);
////////////////////////////////////////////////////////////
/// \see Context::Display
@ -86,7 +86,7 @@ public :
/// \see Context::UseVerticalSync
///
////////////////////////////////////////////////////////////
virtual void UseVerticalSync(bool Enabled);
virtual void UseVerticalSync(bool enabled);
////////////////////////////////////////////////////////////
/// Check if a context is active on the current thread
@ -101,12 +101,12 @@ private :
////////////////////////////////////////////////////////////
/// Create the context
///
/// \param Shared : Context to share the new one with (can be NULL)
/// \param BitsPerPixel : Pixel depth, in bits per pixel
/// \param Settings : Creation parameters
/// \param shared : Context to share the new one with (can be NULL)
/// \param bitsPerPixel : Pixel depth, in bits per pixel
/// \param settings : Creation parameters
///
////////////////////////////////////////////////////////////
void CreateContext(ContextGLX* Shared, unsigned int BitsPerPixel, const ContextSettings& Settings);
void CreateContext(ContextGLX* shared, unsigned int bitsPerPixel, const ContextSettings& settings);
////////////////////////////////////////////////////////////
// Member data

View file

@ -34,9 +34,9 @@
////////////////////////////////////////////////////////////
namespace
{
::Display* TheDisplay = NULL;
XIM TheInputMethod = NULL;
int RefCount = 0;
::Display* theDisplay = NULL;
XIM theInputMethod = NULL;
int refCount = 0;
}
@ -50,13 +50,13 @@ namespace priv
DisplayRef::DisplayRef()
{
// If the display hasn't been opened yet, open it
if (TheDisplay == NULL)
if (theDisplay == NULL)
{
TheDisplay = XOpenDisplay(NULL);
if (TheDisplay)
theDisplay = XOpenDisplay(NULL);
if (theDisplay)
{
// Create the input method object
TheInputMethod = XOpenIM(TheDisplay, NULL, NULL, NULL);
theInputMethod = XOpenIM(theDisplay, NULL, NULL, NULL);
}
else
{
@ -65,17 +65,17 @@ DisplayRef::DisplayRef()
}
// Increase the number of references
RefCount++;
refCount++;
}
////////////////////////////////////////////////////////////
/// Copy constructor
////////////////////////////////////////////////////////////
DisplayRef::DisplayRef(const DisplayRef& Copy)
DisplayRef::DisplayRef(const DisplayRef&)
{
// Increase the number of references
RefCount++;
refCount++;
}
@ -85,17 +85,17 @@ DisplayRef::DisplayRef(const DisplayRef& Copy)
DisplayRef::~DisplayRef()
{
// Decrease the number of references
RefCount--;
refCount--;
// If all references have been destroyed, we can close the display
if (RefCount == 0)
if (refCount == 0)
{
// Destroy the input method object
if (TheInputMethod)
XCloseIM(TheInputMethod);
if (theInputMethod)
XCloseIM(theInputMethod);
// Close the display
XCloseDisplay(TheDisplay);
XCloseDisplay(theDisplay);
}
}
@ -105,7 +105,7 @@ DisplayRef::~DisplayRef()
////////////////////////////////////////////////////////////
::Display* DisplayRef::GetDisplay() const
{
return TheDisplay;
return theDisplay;
}
@ -114,7 +114,7 @@ DisplayRef::~DisplayRef()
////////////////////////////////////////////////////////////
XIM DisplayRef::GetInputMethod() const
{
return TheInputMethod;
return theInputMethod;
}
} // namespace priv

View file

@ -51,10 +51,10 @@ public :
////////////////////////////////////////////////////////////
/// Copy constructor
///
/// \param Copy : Instance to copy
/// \param copy : Instance to copy
///
////////////////////////////////////////////////////////////
DisplayRef(const DisplayRef& Copy);
DisplayRef(const DisplayRef& copy);
////////////////////////////////////////////////////////////
/// Destructor

View file

@ -45,7 +45,7 @@ namespace priv
////////////////////////////////////////////////////////////
/// Initialize the instance and bind it to a physical joystick
////////////////////////////////////////////////////////////
void Joystick::Initialize(unsigned int Index)
void Joystick::Initialize(unsigned int index)
{
// Initial state
myNbAxes = 0;
@ -57,7 +57,7 @@ void Joystick::Initialize(unsigned int Index)
// Open the joystick handle
std::ostringstream oss;
oss << "/dev/input/js" << Index;
oss << "/dev/input/js" << index;
myDescriptor = open(oss.str().c_str(), O_RDONLY);
if (myDescriptor > 0)
{
@ -65,11 +65,11 @@ void Joystick::Initialize(unsigned int Index)
fcntl(myDescriptor, F_SETFL, O_NONBLOCK);
// Get number of axes and buttons
char NbAxes, NbButtons;
ioctl(myDescriptor, JSIOCGAXES, &NbAxes);
ioctl(myDescriptor, JSIOCGBUTTONS, &NbButtons);
myNbAxes = NbAxes;
myNbButtons = NbButtons;
char nbAxes, nbButtons;
ioctl(myDescriptor, JSIOCGAXES, &nbAxes);
ioctl(myDescriptor, JSIOCGBUTTONS, &nbButtons);
myNbAxes = nbAxes;
myNbButtons = nbButtons;
}
}
@ -81,24 +81,24 @@ JoystickState Joystick::UpdateState()
{
if (myDescriptor > 0)
{
js_event JoyState;
while (read(myDescriptor, &JoyState, sizeof(JoyState)) > 0)
js_event joyState;
while (read(myDescriptor, &joyState, sizeof(joyState)) > 0)
{
switch (JoyState.type & ~JS_EVENT_INIT)
switch (joyState.type & ~JS_EVENT_INIT)
{
// An axis has been moved
case JS_EVENT_AXIS :
{
if (JoyState.number < Joy::Count)
myState.Axis[JoyState.number] = JoyState.value * 100.f / 32767.f;
if (joyState.number < Joy::Count)
myState.Axis[joyState.number] = joyState.value * 100.f / 32767.f;
break;
}
// A button has been pressed
case JS_EVENT_BUTTON :
{
if (JoyState.number < GetButtonsCount())
myState.Buttons[JoyState.number] = (JoyState.value != 0);
if (joyState.number < GetButtonsCount())
myState.Buttons[joyState.number] = (joyState.value != 0);
break;
}
}
@ -133,7 +133,7 @@ unsigned int Joystick::GetButtonsCount() const
////////////////////////////////////////////////////////////
/// Initialize the instance and bind it to a physical joystick
////////////////////////////////////////////////////////////
void Joystick::Initialize(unsigned int Index)
void Joystick::Initialize(unsigned int index)
{
}

View file

@ -44,10 +44,10 @@ public :
////////////////////////////////////////////////////////////
/// Initialize the instance and bind it to a physical joystick
///
/// \param Index : Index of the physical joystick to bind to
/// \param index : Index of the physical joystick to bind to
///
////////////////////////////////////////////////////////////
void Initialize(unsigned int Index);
void Initialize(unsigned int index);
////////////////////////////////////////////////////////////
/// Update the current joystick and return its new state

View file

@ -40,51 +40,51 @@ namespace priv
////////////////////////////////////////////////////////////
/// Get supported video modes
////////////////////////////////////////////////////////////
void VideoModeSupport::GetSupportedVideoModes(std::vector<VideoMode>& Modes)
void VideoModeSupport::GetSupportedVideoModes(std::vector<VideoMode>& modes)
{
// First, clear array to fill
Modes.clear();
modes.clear();
// Get an access to the display
DisplayRef Disp;
int Screen = DefaultScreen(Disp.GetDisplay());
DisplayRef disp;
int screen = DefaultScreen(disp.GetDisplay());
// Check if the XRandR extension is present
int Version;
if (XQueryExtension(Disp.GetDisplay(), "RANDR", &Version, &Version, &Version))
int version;
if (XQueryExtension(Disp.GetDisplay(), "RANDR", &version, &version, &version))
{
// Get the current configuration
XRRScreenConfiguration* Config = XRRGetScreenInfo(Disp.GetDisplay(), RootWindow(Disp.GetDisplay(), Screen));
if (Config)
XRRScreenConfiguration* config = XRRGetScreenInfo(disp.GetDisplay(), RootWindow(disp.GetDisplay(), screen));
if (config)
{
// Get the available screen sizes
int NbSizes;
XRRScreenSize* Sizes = XRRConfigSizes(Config, &NbSizes);
if (Sizes && (NbSizes > 0))
int nbSizes;
XRRScreenSize* sizes = XRRConfigSizes(config, &nbSizes);
if (sizes && (nbSizes > 0))
{
// Get the list of supported depths
int NbDepths = 0;
int* Depths = XListDepths(Disp.GetDisplay(), Screen, &NbDepths);
if (Depths && (NbDepths > 0))
int nbDepths = 0;
int* depths = XListDepths(disp.GetDisplay(), screen, &nbDepths);
if (depths && (nbDepths > 0))
{
// Combine depths and sizes to fill the array of supported modes
for (int i = 0; i < NbDepths; ++i)
for (int i = 0; i < nbDepths; ++i)
{
for (int j = 0; j < NbSizes; ++j)
for (int j = 0; j < nbSizes; ++j)
{
// Convert to VideoMode
VideoMode Mode(Sizes[j].width, Sizes[j].height, Depths[i]);
VideoMode mode(sizes[j].width, sizes[j].height, depths[i]);
// Add it only if it is not already in the array
if (std::find(Modes.begin(), Modes.end(), Mode) == Modes.end())
Modes.push_back(Mode);
if (std::find(modes.begin(), modes.end(), mode) == modes.end())
modes.push_back(mode);
}
}
}
}
// Free the configuration instance
XRRFreeScreenConfigInfo(Config);
XRRFreeScreenConfigInfo(config);
}
else
{
@ -105,36 +105,36 @@ void VideoModeSupport::GetSupportedVideoModes(std::vector<VideoMode>& Modes)
////////////////////////////////////////////////////////////
VideoMode VideoModeSupport::GetDesktopVideoMode()
{
VideoMode DesktopMode;
VideoMode desktopMode;
// Get an access to the display
DisplayRef Disp;
int Screen = DefaultScreen(Disp.GetDisplay());
DisplayRef disp;
int screen = DefaultScreen(disp.GetDisplay());
// Check if the XRandR extension is present
int Version;
if (XQueryExtension(Disp.GetDisplay(), "RANDR", &Version, &Version, &Version))
int version;
if (XQueryExtension(disp.GetDisplay(), "RANDR", &version, &version, &version))
{
// Get the current configuration
XRRScreenConfiguration* Config = XRRGetScreenInfo(Disp.GetDisplay(), RootWindow(Disp.GetDisplay(), Screen));
if (Config)
XRRScreenConfiguration* config = XRRGetScreenInfo(disp.GetDisplay(), RootWindow(disp.GetDisplay(), screen));
if (config)
{
// Get the current video mode
Rotation CurrentRotation;
int CurrentMode = XRRConfigCurrentConfiguration(Config, &CurrentRotation);
Rotation currentRotation;
int currentMode = XRRConfigCurrentConfiguration(config, &currentRotation);
// Get the available screen sizes
int NbSizes;
XRRScreenSize* Sizes = XRRConfigSizes(Config, &NbSizes);
if (Sizes && (NbSizes > 0))
DesktopMode = VideoMode(Sizes[CurrentMode].width, Sizes[CurrentMode].height, DefaultDepth(Disp.GetDisplay(), Screen));
int nbSizes;
XRRScreenSize* sizes = XRRConfigSizes(Config, &nbSizes);
if (sizes && (nbSizes > 0))
desktopMode = VideoMode(sizes[currentMode].width, sizes[currentMode].height, DefaultDepth(disp.GetDisplay(), screen));
// Free the configuration instance
XRRFreeScreenConfigInfo(Config);
XRRFreeScreenConfigInfo(config);
}
}
return DesktopMode;
return desktopMode;
}
} // namespace priv

View file

@ -47,10 +47,10 @@ public :
////////////////////////////////////////////////////////////
/// Get supported video modes
///
/// \param Modes : Array to fill with available video modes
/// \param modes : Array to fill with available video modes
///
////////////////////////////////////////////////////////////
static void GetSupportedVideoModes(std::vector<VideoMode>& Modes);
static void GetSupportedVideoModes(std::vector<VideoMode>& modes);
////////////////////////////////////////////////////////////
/// Get current desktop video mode

View file

@ -41,8 +41,8 @@
////////////////////////////////////////////////////////////
namespace
{
sf::priv::WindowImplX11* FullscreenWindow = NULL;
unsigned long EventMask = FocusChangeMask | ButtonPressMask | ButtonReleaseMask | ButtonMotionMask |
sf::priv::WindowImplX11* fullscreenWindow = NULL;
unsigned long eventMask = FocusChangeMask | ButtonPressMask | ButtonReleaseMask | ButtonMotionMask |
PointerMotionMask | KeyPressMask | KeyReleaseMask | StructureNotifyMask |
EnterWindowMask | LeaveWindowMask;
@ -50,10 +50,10 @@ namespace
/// Filter the events received by windows
/// (only allow those matching a specific window)
////////////////////////////////////////////////////////////
Bool CheckEvent(::Display*, XEvent* Event, XPointer UserData)
Bool CheckEvent(::Display*, XEvent* event, XPointer userData)
{
// Just check if the event matches the window
return Event->xany.window == reinterpret_cast< ::Window >(UserData);
return event->xany.window == reinterpret_cast< ::Window >(userData);
}
}
@ -65,7 +65,7 @@ namespace priv
////////////////////////////////////////////////////////////
/// Create the window implementation from an existing control
////////////////////////////////////////////////////////////
WindowImplX11::WindowImplX11(WindowHandle Handle) :
WindowImplX11::WindowImplX11(WindowHandle handle) :
myWindow (0),
myIsExternal (true),
myAtomClose (0),
@ -79,19 +79,19 @@ myKeyRepeat (true)
myScreen = DefaultScreen(myDisplay);
// Save the window handle
myWindow = Handle;
myWindow = handle;
if (myWindow)
{
// Get the window size
XWindowAttributes WindowAttributes;
if (XGetWindowAttributes(myDisplay, myWindow, &WindowAttributes) == 0)
XWindowAttributes windowAttributes;
if (XGetWindowAttributes(myDisplay, myWindow, &windowAttributes) == 0)
{
std::cerr << "Failed to get the window attributes" << std::endl;
return;
}
myWidth = WindowAttributes.width;
myHeight = WindowAttributes.height;
myWidth = windowAttributes.width;
myHeight = windowAttributes.height;
// Make sure the window is listening to all the requiered events
XSelectInput(myDisplay, myWindow, EventMask & ~ButtonPressMask);
@ -105,7 +105,7 @@ myKeyRepeat (true)
////////////////////////////////////////////////////////////
/// Create the window implementation
////////////////////////////////////////////////////////////
WindowImplX11::WindowImplX11(VideoMode Mode, const std::string& Title, unsigned long WindowStyle) :
WindowImplX11::WindowImplX11(VideoMode mode, const std::string& title, unsigned long style) :
myWindow (0),
myIsExternal (false),
myAtomClose (0),
@ -119,40 +119,40 @@ myKeyRepeat (true)
myScreen = DefaultScreen(myDisplay);
// Compute position and size
int Left, Top;
bool Fullscreen = (WindowStyle & Style::Fullscreen) != 0;
if (!Fullscreen)
int left, top;
bool fullscreen = (style & Style::Fullscreen) != 0;
if (!fullscreen)
{
Left = (DisplayWidth(myDisplay, myScreen) - Mode.Width) / 2;
Top = (DisplayHeight(myDisplay, myScreen) - Mode.Height) / 2;
left = (DisplayWidth(myDisplay, myScreen) - mode.Width) / 2;
top = (DisplayHeight(myDisplay, myScreen) - mode.Height) / 2;
}
else
{
Left = 0;
Top = 0;
left = 0;
top = 0;
}
int Width = myWidth = Mode.Width;
int Height = myHeight = Mode.Height;
int width = myWidth = mode.Width;
int height = myHeight = mode.Height;
// Switch to fullscreen if necessary
if (Fullscreen)
SwitchToFullscreen(Mode);
if (fullscreen)
SwitchToFullscreen(mode);
// Define the window attributes
XSetWindowAttributes Attributes;
Attributes.event_mask = EventMask;
Attributes.override_redirect = Fullscreen;
XSetWindowAttributes attributes;
attributes.event_mask = eventMask;
attributes.override_redirect = fullscreen;
// Create the window
myWindow = XCreateWindow(myDisplay,
RootWindow(myDisplay, myScreen),
Left, Top,
Width, Height,
left, top,
width, height,
0,
DefaultDepth(myDisplay, myScreen),
InputOutput,
DefaultVisual(myDisplay, myScreen),
CWEventMask | CWOverrideRedirect, &Attributes);
CWEventMask | CWOverrideRedirect, &attributes);
if (!myWindow)
{
std::cerr << "Failed to create window" << std::endl;
@ -160,10 +160,10 @@ myKeyRepeat (true)
}
// Set the window's name
XStoreName(myDisplay, myWindow, Title.c_str());
XStoreName(myDisplay, myWindow, title.c_str());
// Set the window's style (tell the windows manager to change our window's decorations and functions according to the requested style)
if (!Fullscreen)
if (!fullscreen)
{
Atom WMHintsAtom = XInternAtom(myDisplay, "_MOTIF_WM_HINTS", false);
if (WMHintsAtom)
@ -195,39 +195,39 @@ myKeyRepeat (true)
unsigned long State;
};
WMHints Hints;
Hints.Flags = MWM_HINTS_FUNCTIONS | MWM_HINTS_DECORATIONS;
Hints.Decorations = 0;
Hints.Functions = 0;
WMHints hints;
hints.Flags = MWM_HINTS_FUNCTIONS | MWM_HINTS_DECORATIONS;
hints.Decorations = 0;
hints.Functions = 0;
if (WindowStyle & Style::Titlebar)
if (style & Style::Titlebar)
{
Hints.Decorations |= MWM_DECOR_BORDER | MWM_DECOR_TITLE | MWM_DECOR_MINIMIZE | MWM_DECOR_MENU;
Hints.Functions |= MWM_FUNC_MOVE | MWM_FUNC_MINIMIZE;
hints.Decorations |= MWM_DECOR_BORDER | MWM_DECOR_TITLE | MWM_DECOR_MINIMIZE | MWM_DECOR_MENU;
hints.Functions |= MWM_FUNC_MOVE | MWM_FUNC_MINIMIZE;
}
if (WindowStyle & Style::Resize)
if (style & Style::Resize)
{
Hints.Decorations |= MWM_DECOR_MAXIMIZE | MWM_DECOR_RESIZEH;
Hints.Functions |= MWM_FUNC_MAXIMIZE | MWM_FUNC_RESIZE;
hints.Decorations |= MWM_DECOR_MAXIMIZE | MWM_DECOR_RESIZEH;
hints.Functions |= MWM_FUNC_MAXIMIZE | MWM_FUNC_RESIZE;
}
if (WindowStyle & Style::Close)
if (style & Style::Close)
{
Hints.Decorations |= 0;
Hints.Functions |= MWM_FUNC_CLOSE;
hints.Decorations |= 0;
hints.Functions |= MWM_FUNC_CLOSE;
}
const unsigned char* HintsPtr = reinterpret_cast<const unsigned char*>(&Hints);
XChangeProperty(myDisplay, myWindow, WMHintsAtom, WMHintsAtom, 32, PropModeReplace, HintsPtr, 5);
const unsigned char* ptr = reinterpret_cast<const unsigned char*>(&hints);
XChangeProperty(myDisplay, myWindow, WMHintsAtom, WMHintsAtom, 32, PropModeReplace, ptr, 5);
}
// This is a hack to force some windows managers to disable resizing
if (!(WindowStyle & Style::Resize))
if (!(style & Style::Resize))
{
XSizeHints XSizeHints;
XSizeHints.flags = PMinSize | PMaxSize;
XSizeHints.min_width = XSizeHints.max_width = Width;
XSizeHints.min_height = XSizeHints.max_height = Height;
XSetWMNormalHints(myDisplay, myWindow, &XSizeHints);
XSizeHints sizeHints;
sizeHints.flags = PMinSize | PMaxSize;
sizeHints.min_width = sizeHints.max_width = width;
sizeHints.min_height = sizeHints.max_height = height;
XSetWMNormalHints(myDisplay, myWindow, &sizeHints);
}
}
@ -235,7 +235,7 @@ myKeyRepeat (true)
Initialize();
// In fullscreen mode, we must grab keyboard and mouse inputs
if (Fullscreen)
if (fullscreen)
{
XGrabPointer(myDisplay, myWindow, true, 0, GrabModeAsync, GrabModeAsync, myWindow, None, CurrentTime);
XGrabKeyboard(myDisplay, myWindow, true, GrabModeAsync, GrabModeAsync, CurrentTime);
@ -288,33 +288,33 @@ void WindowImplX11::ProcessEvents()
// Process any event in the queue matching our window
XEvent Event;
while (XCheckIfEvent(myDisplay, &Event, &CheckEvent, reinterpret_cast<XPointer>(myWindow)))
XEvent event;
while (XCheckIfEvent(myDisplay, &event, &CheckEvent, reinterpret_cast<XPointer>(myWindow)))
{
// Detect repeated key events
if ((Event.type == KeyPress) || (Event.type == KeyRelease))
if ((event.type == KeyPress) || (event.type == KeyRelease))
{
if (Event.xkey.keycode < 256)
if (event.xkey.keycode < 256)
{
// To detect if it is a repeated key event, we check the current state of the key.
// - If the state is "down", KeyReleased events must obviously be discarded.
// - KeyPress events are a little bit harder to handle: they depend on the EnableKeyRepeat state,
// and we need to properly forward the first one.
char Keys[32];
XQueryKeymap(myDisplay, Keys);
if (Keys[Event.xkey.keycode >> 3] & (1 << (Event.xkey.keycode % 8)))
char keys[32];
XQueryKeymap(myDisplay, keys);
if (keys[event.xkey.keycode >> 3] & (1 << (event.xkey.keycode % 8)))
{
// KeyRelease event + key down = repeated event --> discard
if (Event.type == KeyRelease)
if (event.type == KeyRelease)
{
myLastKeyReleaseEvent = Event;
myLastKeyReleaseEvent = event;
continue;
}
// KeyPress event + key repeat disabled + matching KeyRelease event = repeated event --> discard
if ((Event.type == KeyPress) && !myKeyRepeat &&
(myLastKeyReleaseEvent.xkey.keycode == Event.xkey.keycode) &&
(myLastKeyReleaseEvent.xkey.time == Event.xkey.time))
if ((event.type == KeyPress) && !myKeyRepeat &&
(myLastKeyReleaseEvent.xkey.keycode == event.xkey.keycode) &&
(myLastKeyReleaseEvent.xkey.time == event.xkey.time))
{
continue;
}
@ -323,7 +323,7 @@ void WindowImplX11::ProcessEvents()
}
// Process the event
ProcessEvent(Event);
ProcessEvent(event);
}
}
@ -331,9 +331,9 @@ void WindowImplX11::ProcessEvents()
////////////////////////////////////////////////////////////
/// /see WindowImpl::ShowMouseCursor
////////////////////////////////////////////////////////////
void WindowImplX11::ShowMouseCursor(bool Show)
void WindowImplX11::ShowMouseCursor(bool show)
{
XDefineCursor(myDisplay, myWindow, Show ? None : myHiddenCursor);
XDefineCursor(myDisplay, myWindow, show ? None : myHiddenCursor);
XFlush(myDisplay);
}
@ -341,9 +341,9 @@ void WindowImplX11::ShowMouseCursor(bool Show)
////////////////////////////////////////////////////////////
/// /see sfWindowImpl::SetCursorPosition
////////////////////////////////////////////////////////////
void WindowImplX11::SetCursorPosition(unsigned int Left, unsigned int Top)
void WindowImplX11::SetCursorPosition(unsigned int left, unsigned int top)
{
XWarpPointer(myDisplay, None, myWindow, 0, 0, 0, 0, Left, Top);
XWarpPointer(myDisplay, None, myWindow, 0, 0, 0, 0, left, top);
XFlush(myDisplay);
}
@ -351,9 +351,9 @@ void WindowImplX11::SetCursorPosition(unsigned int Left, unsigned int Top)
////////////////////////////////////////////////////////////
/// /see sfWindowImpl::SetPosition
////////////////////////////////////////////////////////////
void WindowImplX11::SetPosition(int Left, int Top)
void WindowImplX11::SetPosition(int left, int top)
{
XMoveWindow(myDisplay, myWindow, Left, Top);
XMoveWindow(myDisplay, myWindow, left, top);
XFlush(myDisplay);
}
@ -361,9 +361,9 @@ void WindowImplX11::SetPosition(int Left, int Top)
////////////////////////////////////////////////////////////
/// /see WindowImpl::SetSize
////////////////////////////////////////////////////////////
void WindowImplX11::SetSize(unsigned int Width, unsigned int Height)
void WindowImplX11::SetSize(unsigned int width, unsigned int height)
{
XResizeWindow(myDisplay, myWindow, Width, Height);
XResizeWindow(myDisplay, myWindow, width, height);
XFlush(myDisplay);
}
@ -371,9 +371,9 @@ void WindowImplX11::SetSize(unsigned int Width, unsigned int Height)
////////////////////////////////////////////////////////////
/// /see sfWindowImpl::Show
////////////////////////////////////////////////////////////
void WindowImplX11::Show(bool State)
void WindowImplX11::Show(bool show)
{
if (State)
if (show)
XMapWindow(myDisplay, myWindow);
else
XUnmapWindow(myDisplay, myWindow);
@ -385,70 +385,70 @@ void WindowImplX11::Show(bool State)
////////////////////////////////////////////////////////////
/// /see sfWindowImpl::EnableKeyRepeat
////////////////////////////////////////////////////////////
void WindowImplX11::EnableKeyRepeat(bool Enabled)
void WindowImplX11::EnableKeyRepeat(bool enabled)
{
myKeyRepeat = Enabled;
myKeyRepeat = enabled;
}
////////////////////////////////////////////////////////////
/// /see WindowImpl::SetIcon
////////////////////////////////////////////////////////////
void WindowImplX11::SetIcon(unsigned int Width, unsigned int Height, const Uint8* Pixels)
void WindowImplX11::SetIcon(unsigned int width, unsigned int height, const Uint8* pixels)
{
// X11 wants BGRA pixels : swap red and blue channels
// Note : this memory will never be freed, but it seems to cause a bug on exit if I do so
Uint8* IconPixels = new Uint8[Width * Height * 4];
for (std::size_t i = 0; i < Width * Height; ++i)
Uint8* iconPixels = new Uint8[width * height * 4];
for (std::size_t i = 0; i < width * height; ++i)
{
IconPixels[i * 4 + 0] = Pixels[i * 4 + 2];
IconPixels[i * 4 + 1] = Pixels[i * 4 + 1];
IconPixels[i * 4 + 2] = Pixels[i * 4 + 0];
IconPixels[i * 4 + 3] = Pixels[i * 4 + 3];
iconPixels[i * 4 + 0] = pixels[i * 4 + 2];
iconPixels[i * 4 + 1] = pixels[i * 4 + 1];
iconPixels[i * 4 + 2] = pixels[i * 4 + 0];
iconPixels[i * 4 + 3] = pixels[i * 4 + 3];
}
// Create the icon pixmap
Visual* DefVisual = DefaultVisual(myDisplay, myScreen);
unsigned int DefDepth = DefaultDepth(myDisplay, myScreen);
XImage* IconImage = XCreateImage(myDisplay, DefVisual, DefDepth, ZPixmap, 0, (char*)IconPixels, Width, Height, 32, 0);
if (!IconImage)
Visual* defVisual = DefaultVisual(myDisplay, myScreen);
unsigned int defDepth = DefaultDepth(myDisplay, myScreen);
XImage* iconImage = XCreateImage(myDisplay, defVisual, defDepth, ZPixmap, 0, (char*)iconPixels, width, height, 32, 0);
if (!iconImage)
{
std::cerr << "Failed to set the window's icon" << std::endl;
return;
}
Pixmap IconPixmap = XCreatePixmap(myDisplay, RootWindow(myDisplay, myScreen), Width, Height, DefDepth);
XGCValues Values;
GC IconGC = XCreateGC(myDisplay, IconPixmap, 0, &Values);
XPutImage(myDisplay, IconPixmap, IconGC, IconImage, 0, 0, 0, 0, Width, Height);
XFreeGC(myDisplay, IconGC);
XDestroyImage(IconImage);
Pixmap iconPixmap = XCreatePixmap(myDisplay, RootWindow(myDisplay, myScreen), width, height, defDepth);
XGCValues values;
GC iconGC = XCreateGC(myDisplay, iconPixmap, 0, &values);
XPutImage(myDisplay, iconPixmap, iconGC, iconImage, 0, 0, 0, 0, width, height);
XFreeGC(myDisplay, iconGC);
XDestroyImage(iconImage);
// Create the mask pixmap (must have 1 bit depth)
std::size_t Pitch = (Width + 7) / 8;
static std::vector<Uint8> MaskPixels(Pitch * Height, 0);
for (std::size_t j = 0; j < Height; ++j)
std::size_t pitch = (width + 7) / 8;
static std::vector<Uint8> maskPixels(pitch * height, 0);
for (std::size_t j = 0; j < height; ++j)
{
for (std::size_t i = 0; i < Pitch; ++i)
for (std::size_t i = 0; i < pitch; ++i)
{
for (std::size_t k = 0; k < 8; ++k)
{
if (i * 8 + k < Width)
if (i * 8 + k < width)
{
Uint8 Opacity = (Pixels[(i * 8 + k + j * Width) * 4 + 3] > 0) ? 1 : 0;
MaskPixels[i + j * Pitch] |= (Opacity << k);
Uint8 opacity = (pixels[(i * 8 + k + j * width) * 4 + 3] > 0) ? 1 : 0;
maskPixels[i + j * pitch] |= (opacity << k);
}
}
}
}
Pixmap MaskPixmap = XCreatePixmapFromBitmapData(myDisplay, myWindow, (char*)&MaskPixels[0], Width, Height, 1, 0, 1);
Pixmap maskPixmap = XCreatePixmapFromBitmapData(myDisplay, myWindow, (char*)&maskPixels[0], width, height, 1, 0, 1);
// Send our new icon to the window through the WMHints
XWMHints* Hints = XAllocWMHints();
Hints->flags = IconPixmapHint | IconMaskHint;
Hints->icon_pixmap = IconPixmap;
Hints->icon_mask = MaskPixmap;
XSetWMHints(myDisplay, myWindow, Hints);
XFree(Hints);
XWMHints* hints = XAllocWMHints();
hints->flags = IconPixmapHint | IconMaskHint;
hints->icon_pixmap = iconPixmap;
hints->icon_mask = maskPixmap;
XSetWMHints(myDisplay, myWindow, hints);
XFree(hints);
XFlush(myDisplay);
}
@ -457,42 +457,42 @@ void WindowImplX11::SetIcon(unsigned int Width, unsigned int Height, const Uint8
////////////////////////////////////////////////////////////
/// Switch to fullscreen mode
////////////////////////////////////////////////////////////
void WindowImplX11::SwitchToFullscreen(const VideoMode& Mode)
void WindowImplX11::SwitchToFullscreen(const VideoMode& mode)
{
// Check if the XRandR extension is present
int Version;
if (XQueryExtension(myDisplay, "RANDR", &Version, &Version, &Version))
int version;
if (XQueryExtension(myDisplay, "RANDR", &version, &version, &version))
{
// Get the current configuration
XRRScreenConfiguration* Config = XRRGetScreenInfo(myDisplay, RootWindow(myDisplay, myScreen));
if (Config)
XRRScreenConfiguration* config = XRRGetScreenInfo(myDisplay, RootWindow(myDisplay, myScreen));
if (config)
{
// Get the current rotation
Rotation CurrentRotation;
myOldVideoMode = XRRConfigCurrentConfiguration(Config, &CurrentRotation);
Rotation currentRotation;
myOldVideoMode = XRRConfigCurrentConfiguration(config, &currentRotation);
// Get the available screen sizes
int NbSizes;
XRRScreenSize* Sizes = XRRConfigSizes(Config, &NbSizes);
if (Sizes && (NbSizes > 0))
int nbSizes;
XRRScreenSize* sizes = XRRConfigSizes(config, &nbSizes);
if (sizes && (nbSizes > 0))
{
// Search a matching size
for (int i = 0; i < NbSizes; ++i)
for (int i = 0; i < nbSizes; ++i)
{
if ((Sizes[i].width == static_cast<int>(Mode.Width)) && (Sizes[i].height == static_cast<int>(Mode.Height)))
if ((sizes[i].width == static_cast<int>(mode.Width)) && (sizes[i].height == static_cast<int>(mode.Height)))
{
// Switch to fullscreen mode
XRRSetScreenConfig(myDisplay, Config, RootWindow(myDisplay, myScreen), i, CurrentRotation, CurrentTime);
XRRSetScreenConfig(myDisplay, config, RootWindow(myDisplay, myScreen), i, currentRotation, CurrentTime);
// Set "this" as the current fullscreen window
FullscreenWindow = this;
fullscreenWindow = this;
break;
}
}
}
// Free the configuration instance
XRRFreeScreenConfigInfo(Config);
XRRFreeScreenConfigInfo(config);
}
else
{
@ -521,13 +521,13 @@ void WindowImplX11::Initialize()
XSetWMProtocols(myDisplay, myWindow, &myAtomClose, 1);
// Create the input context
XIM InputMethod = myDisplayRef.GetInputMethod();
if (InputMethod)
XIM inputMethod = myDisplayRef.GetInputMethod();
if (inputMethod)
{
myInputContext = XCreateIC(InputMethod,
XNClientWindow, myWindow,
XNFocusWindow, myWindow,
XNInputStyle, XIMPreeditNothing | XIMStatusNothing,
myInputContext = XCreateIC(inputMethod,
XNClientWindow, myWindow,
XNFocusWindow, myWindow,
XNInputStyle, XIMPreeditNothing | XIMStatusNothing,
NULL);
if (!myInputContext)
@ -552,19 +552,19 @@ void WindowImplX11::Initialize()
void WindowImplX11::CreateHiddenCursor()
{
// Create the cursor's pixmap (1x1 pixels)
Pixmap CursorPixmap = XCreatePixmap(myDisplay, myWindow, 1, 1, 1);
GC GraphicsContext = XCreateGC(myDisplay, CursorPixmap, 0, NULL);
XDrawPoint(myDisplay, CursorPixmap, GraphicsContext, 0, 0);
XFreeGC(myDisplay, GraphicsContext);
Pixmap cursorPixmap = XCreatePixmap(myDisplay, myWindow, 1, 1, 1);
GC graphicsContext = XCreateGC(myDisplay, cursorPixmap, 0, NULL);
XDrawPoint(myDisplay, cursorPixmap, graphicsContext, 0, 0);
XFreeGC(myDisplay, graphicsContext);
// Create the cursor, using the pixmap as both the shape and the mask of the cursor
XColor Color;
Color.flags = DoRed | DoGreen | DoBlue;
Color.red = Color.blue = Color.green = 0;
myHiddenCursor = XCreatePixmapCursor(myDisplay, CursorPixmap, CursorPixmap, &Color, &Color, 0, 0);
XColor color;
color.flags = DoRed | DoGreen | DoBlue;
color.red = Color.blue = Color.green = 0;
myHiddenCursor = XCreatePixmapCursor(myDisplay, cursorPixmap, cursorPixmap, &color, &color, 0, 0);
// We don't need the pixmap any longer, free it
XFreePixmap(myDisplay, CursorPixmap);
XFreePixmap(myDisplay, cursorPixmap);
}
@ -574,25 +574,25 @@ void WindowImplX11::CreateHiddenCursor()
void WindowImplX11::CleanUp()
{
// Restore the previous video mode (in case we were running in fullscreen)
if (FullscreenWindow == this)
if (fullscreenWindow == this)
{
// Get current screen info
XRRScreenConfiguration* Config = XRRGetScreenInfo(myDisplay, RootWindow(myDisplay, myScreen));
if (Config)
XRRScreenConfiguration* config = XRRGetScreenInfo(myDisplay, RootWindow(myDisplay, myScreen));
if (config)
{
// Get the current rotation
Rotation CurrentRotation;
XRRConfigCurrentConfiguration(Config, &CurrentRotation);
Rotation currentRotation;
XRRConfigCurrentConfiguration(config, &currentRotation);
// Reset the video mode
XRRSetScreenConfig(myDisplay, Config, RootWindow(myDisplay, myScreen), myOldVideoMode, CurrentRotation, CurrentTime);
XRRSetScreenConfig(myDisplay, config, RootWindow(myDisplay, myScreen), myOldVideoMode, currentRotation, CurrentTime);
// Free the configuration instance
XRRFreeScreenConfigInfo(Config);
XRRFreeScreenConfigInfo(config);
}
// Reset the fullscreen window
FullscreenWindow = NULL;
fullscreenWindow = NULL;
}
// Unhide the mouse cursor (in case it was hidden)
@ -603,9 +603,9 @@ void WindowImplX11::CleanUp()
////////////////////////////////////////////////////////////
/// Process an incoming event from the window
////////////////////////////////////////////////////////////
void WindowImplX11::ProcessEvent(XEvent WinEvent)
void WindowImplX11::ProcessEvent(XEvent windowEvent)
{
switch (WinEvent.type)
switch (windowEvent.type)
{
// Destroy event
case DestroyNotify :
@ -622,9 +622,9 @@ void WindowImplX11::ProcessEvent(XEvent WinEvent)
if (myInputContext)
XSetICFocus(myInputContext);
Event Evt;
Evt.Type = Event::GainedFocus;
SendEvent(Evt);
Event event;
event.Type = Event::GainedFocus;
SendEvent(event);
break;
}
@ -635,25 +635,25 @@ void WindowImplX11::ProcessEvent(XEvent WinEvent)
if (myInputContext)
XUnsetICFocus(myInputContext);
Event Evt;
Evt.Type = Event::LostFocus;
SendEvent(Evt);
Event event;
event.Type = Event::LostFocus;
SendEvent(event);
break;
}
// Resize event
case ConfigureNotify :
{
if ((WinEvent.xconfigure.width != static_cast<int>(myWidth)) || (WinEvent.xconfigure.height != static_cast<int>(myHeight)))
if ((windowEvent.xconfigure.width != static_cast<int>(myWidth)) || (windowEvent.xconfigure.height != static_cast<int>(myHeight)))
{
myWidth = WinEvent.xconfigure.width;
myHeight = WinEvent.xconfigure.height;
myWidth = windowEvent.xconfigure.width;
myHeight = windowEvent.xconfigure.height;
Event Evt;
Evt.Type = Event::Resized;
Evt.Size.Width = myWidth;
Evt.Size.Height = myHeight;
SendEvent(Evt);
Event event;
event.Type = Event::Resized;
event.Size.Width = myWidth;
event.Size.Height = myHeight;
SendEvent(event);
}
break;
}
@ -661,11 +661,11 @@ void WindowImplX11::ProcessEvent(XEvent WinEvent)
// Close event
case ClientMessage :
{
if ((WinEvent.xclient.format == 32) && (WinEvent.xclient.data.l[0]) == static_cast<long>(myAtomClose))
if ((windowEvent.xclient.format == 32) && (windowEvent.xclient.data.l[0]) == static_cast<long>(myAtomClose))
{
Event Evt;
Evt.Type = Event::Closed;
SendEvent(Evt);
Event event;
event.Type = Event::Closed;
SendEvent(event);
}
break;
}
@ -674,54 +674,54 @@ void WindowImplX11::ProcessEvent(XEvent WinEvent)
case KeyPress :
{
// Get the keysym of the key that has been pressed
static XComposeStatus KeyboardStatus;
char Buffer[32];
KeySym Sym;
XLookupString(&WinEvent.xkey, Buffer, sizeof(Buffer), &Sym, &KeyboardStatus);
static XComposeStatus keyboard;
char buffer[32];
KeySym symbol;
XLookupString(&windowEvent.xkey, buffer, sizeof(buffer), &symbol, &keyboard);
// Fill the event parameters
Event Evt;
Evt.Type = Event::KeyPressed;
Evt.Key.Code = KeysymToSF(Sym);
Evt.Key.Alt = WinEvent.xkey.state & Mod1Mask;
Evt.Key.Control = WinEvent.xkey.state & ControlMask;
Evt.Key.Shift = WinEvent.xkey.state & ShiftMask;
SendEvent(Evt);
Event event;
event.Type = Event::KeyPressed;
event.Key.Code = KeysymToSF(symbol);
event.Key.Alt = windowEvent.xkey.state & Mod1Mask;
event.Key.Control = windowEvent.xkey.state & ControlMask;
event.Key.Shift = windowEvent.xkey.state & ShiftMask;
SendEvent(event);
// Generate a TextEntered event
if (!XFilterEvent(&WinEvent, None))
if (!XFilterEvent(&windowEvent, None))
{
#ifdef X_HAVE_UTF8_STRING
if (myInputContext)
{
Status ReturnedStatus;
Uint8 KeyBuffer[16];
int Length = Xutf8LookupString(myInputContext, &WinEvent.xkey, reinterpret_cast<char*>(KeyBuffer), sizeof(KeyBuffer), NULL, &ReturnedStatus);
if (Length > 0)
Status status;
Uint8 keyBuffer[16];
int length = Xutf8LookupString(myInputContext, &windowEvent.xkey, reinterpret_cast<char*>(keyBuffer), sizeof(keyBuffer), NULL, &status);
if (length > 0)
{
Uint32 Unicode[2]; // just in case, but 1 character should be enough
const Uint32* End = Unicode::UTF8ToUTF32(KeyBuffer, KeyBuffer + Length, Unicode);
Uint32 unicode[2]; // just in case, but 1 character should be enough
const Uint32* end = Unicode::UTF8ToUTF32(keyBuffer, keyBuffer + length, unicode);
if (End > Unicode)
if (end > unicode)
{
Event TextEvt;
TextEvt.Type = Event::TextEntered;
TextEvt.Text.Unicode = Unicode[0];
SendEvent(TextEvt);
Event textEvent;
textEvent.Type = Event::TextEntered;
textEvent.Text.Unicode = unicode[0];
SendEvent(textEvent);
}
}
}
else
#endif
{
static XComposeStatus ComposeStatus;
char KeyBuffer[16];
if (XLookupString(&WinEvent.xkey, KeyBuffer, sizeof(KeyBuffer), NULL, &ComposeStatus))
static XComposeStatus status;
char keyBuffer[16];
if (XLookupString(&windowEvent.xkey, keyBuffer, sizeof(keyBuffer), NULL, &status))
{
Event TextEvt;
TextEvt.Type = Event::TextEntered;
TextEvt.Text.Unicode = static_cast<Uint32>(KeyBuffer[0]);
SendEvent(TextEvt);
Event textEvent;
textEvent.Type = Event::TextEntered;
textEvent.Text.Unicode = static_cast<Uint32>(keyBuffer[0]);
SendEvent(textEvent);
}
}
}
@ -733,41 +733,41 @@ void WindowImplX11::ProcessEvent(XEvent WinEvent)
case KeyRelease :
{
// Get the keysym of the key that has been pressed
char Buffer[32];
KeySym Sym;
XLookupString(&WinEvent.xkey, Buffer, 32, &Sym, NULL);
char buffer[32];
KeySym symbol;
XLookupString(&windowEvent.xkey, buffer, 32, &symbol, NULL);
// Fill the event parameters
Event Evt;
Evt.Type = Event::KeyReleased;
Evt.Key.Code = KeysymToSF(Sym);
Evt.Key.Alt = WinEvent.xkey.state & Mod1Mask;
Evt.Key.Control = WinEvent.xkey.state & ControlMask;
Evt.Key.Shift = WinEvent.xkey.state & ShiftMask;
Event event;
event.Type = Event::KeyReleased;
event.Key.Code = KeysymToSF(symbol);
event.Key.Alt = windowEvent.xkey.state & Mod1Mask;
event.Key.Control = windowEvent.xkey.state & ControlMask;
event.Key.Shift = windowEvent.xkey.state & ShiftMask;
SendEvent(event);
SendEvent(Evt);
break;
}
// Mouse button pressed
case ButtonPress :
{
unsigned int Button = WinEvent.xbutton.button;
if ((Button == Button1) || (Button == Button2) || (Button == Button3) || (Button == 8) || (Button == 9))
unsigned int button = windowEvent.xbutton.button;
if ((button == Button1) || (button == Button2) || (button == Button3) || (button == 8) || (button == 9))
{
Event Evt;
Evt.Type = Event::MouseButtonPressed;
Evt.MouseButton.X = WinEvent.xbutton.x;
Evt.MouseButton.Y = WinEvent.xbutton.y;
Event event;
event.Type = Event::MouseButtonPressed;
event.MouseButton.X = windowEvent.xbutton.x;
event.MouseButton.Y = windowEvent.xbutton.y;
switch (Button)
{
case Button1 : Evt.MouseButton.Button = Mouse::Left; break;
case Button2 : Evt.MouseButton.Button = Mouse::Middle; break;
case Button3 : Evt.MouseButton.Button = Mouse::Right; break;
case 8 : Evt.MouseButton.Button = Mouse::XButton1; break;
case 9 : Evt.MouseButton.Button = Mouse::XButton2; break;
case Button1 : event.MouseButton.Button = Mouse::Left; break;
case Button2 : event.MouseButton.Button = Mouse::Middle; break;
case Button3 : event.MouseButton.Button = Mouse::Right; break;
case 8 : event.MouseButton.Button = Mouse::XButton1; break;
case 9 : event.MouseButton.Button = Mouse::XButton2; break;
}
SendEvent(Evt);
SendEvent(event);
}
break;
}
@ -775,29 +775,29 @@ void WindowImplX11::ProcessEvent(XEvent WinEvent)
// Mouse button released
case ButtonRelease :
{
unsigned int Button = WinEvent.xbutton.button;
if ((Button == Button1) || (Button == Button2) || (Button == Button3) || (Button == 8) || (Button == 9))
unsigned int button = windowEvent.xbutton.button;
if ((button == Button1) || (button == Button2) || (button == Button3) || (button == 8) || (button == 9))
{
Event Evt;
Evt.Type = Event::MouseButtonReleased;
Evt.MouseButton.X = WinEvent.xbutton.x;
Evt.MouseButton.Y = WinEvent.xbutton.y;
Event event;
event.Type = Event::MouseButtonReleased;
event.MouseButton.X = windowEvent.xbutton.x;
event.MouseButton.Y = windowEvent.xbutton.y;
switch (Button)
{
case Button1 : Evt.MouseButton.Button = Mouse::Left; break;
case Button2 : Evt.MouseButton.Button = Mouse::Middle; break;
case Button3 : Evt.MouseButton.Button = Mouse::Right; break;
case 8 : Evt.MouseButton.Button = Mouse::XButton1; break;
case 9 : Evt.MouseButton.Button = Mouse::XButton2; break;
case Button1 : event.MouseButton.Button = Mouse::Left; break;
case Button2 : event.MouseButton.Button = Mouse::Middle; break;
case Button3 : event.MouseButton.Button = Mouse::Right; break;
case 8 : event.MouseButton.Button = Mouse::XButton1; break;
case 9 : event.MouseButton.Button = Mouse::XButton2; break;
}
SendEvent(Evt);
SendEvent(event);
}
else if ((Button == Button4) || (Button == Button5))
else if ((button == Button4) || (button == Button5))
{
Event Evt;
Evt.Type = Event::MouseWheelMoved;
Evt.MouseWheel.Delta = WinEvent.xbutton.button == Button4 ? 1 : -1;
SendEvent(Evt);
Event event;
event.Type = Event::MouseWheelMoved;
event.MouseWheel.Delta = windowEvent.xbutton.button == Button4 ? 1 : -1;
SendEvent(event);
}
break;
}
@ -805,29 +805,29 @@ void WindowImplX11::ProcessEvent(XEvent WinEvent)
// Mouse moved
case MotionNotify :
{
Event Evt;
Evt.Type = Event::MouseMoved;
Evt.MouseMove.X = WinEvent.xmotion.x;
Evt.MouseMove.Y = WinEvent.xmotion.y;
SendEvent(Evt);
Event event;
event.Type = Event::MouseMoved;
event.MouseMove.X = windowEvent.xmotion.x;
event.MouseMove.Y = windowEvent.xmotion.y;
SendEvent(event);
break;
}
// Mouse entered
case EnterNotify :
{
Event Evt;
Evt.Type = Event::MouseEntered;
SendEvent(Evt);
Event event;
event.Type = Event::MouseEntered;
SendEvent(event);
break;
}
// Mouse left
case LeaveNotify :
{
Event Evt;
Evt.Type = Event::MouseLeft;
SendEvent(Evt);
Event event;
event.Type = Event::MouseLeft;
SendEvent(event);
break;
}
}
@ -837,13 +837,13 @@ void WindowImplX11::ProcessEvent(XEvent WinEvent)
////////////////////////////////////////////////////////////
/// Convert a X11 keysym to SFML key code
////////////////////////////////////////////////////////////
Key::Code WindowImplX11::KeysymToSF(KeySym Sym)
Key::Code WindowImplX11::KeysymToSF(KeySym symbol)
{
// First convert to uppercase (to avoid dealing with two different keysyms for the same key)
KeySym Lower, Key;
XConvertCase(Sym, &Lower, &Key);
KeySym lower, key;
XConvertCase(symbol, &lower, &key);
switch (Key)
switch (key)
{
case XK_Shift_L : return Key::LShift;
case XK_Shift_R : return Key::RShift;

View file

@ -50,20 +50,20 @@ public :
////////////////////////////////////////////////////////////
/// Construct the window implementation from an existing control
///
/// \param Handle : Platform-specific handle of the control
/// \param handle : Platform-specific handle of the control
///
////////////////////////////////////////////////////////////
WindowImplX11(WindowHandle Handle);
WindowImplX11(WindowHandle handle);
////////////////////////////////////////////////////////////
/// Create the window implementation
///
/// \param Mode : Video mode to use
/// \param Title : Title of the window
/// \param WindowStyle : Window style (resizable, fixed, or fullscren)
/// \param mode : Video mode to use
/// \param title : Title of the window
/// \param style : Window style (resizable, fixed, or fullscren)
///
////////////////////////////////////////////////////////////
WindowImplX11(VideoMode Mode, const std::string& Title, unsigned long WindowStyle);
WindowImplX11(VideoMode mode, const std::string& title, unsigned long style);
////////////////////////////////////////////////////////////
/// Destructor
@ -71,14 +71,6 @@ public :
////////////////////////////////////////////////////////////
~WindowImplX11();
////////////////////////////////////////////////////////////
/// Check if there's an active context on the current thread
///
/// \return True if there's a context bound to the current thread
///
////////////////////////////////////////////////////////////
static bool IsContextActive();
private :
////////////////////////////////////////////////////////////
@ -97,43 +89,43 @@ private :
/// /see WindowImpl::ShowMouseCursor
///
////////////////////////////////////////////////////////////
virtual void ShowMouseCursor(bool Show);
virtual void ShowMouseCursor(bool show);
////////////////////////////////////////////////////////////
/// /see sfWindowImpl::SetCursorPosition
///
////////////////////////////////////////////////////////////
virtual void SetCursorPosition(unsigned int Left, unsigned int Top);
virtual void SetCursorPosition(unsigned int left, unsigned int top);
////////////////////////////////////////////////////////////
/// /see sfWindowImpl::SetPosition
///
////////////////////////////////////////////////////////////
virtual void SetPosition(int Left, int Top);
virtual void SetPosition(int left, int top);
////////////////////////////////////////////////////////////
/// /see WindowImpl::SetSize
///
////////////////////////////////////////////////////////////
virtual void SetSize(unsigned int Width, unsigned int Height);
virtual void SetSize(unsigned int width, unsigned int height);
////////////////////////////////////////////////////////////
/// /see sfWindowImpl::Show
///
////////////////////////////////////////////////////////////
virtual void Show(bool State);
virtual void Show(bool show);
////////////////////////////////////////////////////////////
/// /see sfWindowImpl::EnableKeyRepeat
///
////////////////////////////////////////////////////////////
virtual void EnableKeyRepeat(bool Enabled);
virtual void EnableKeyRepeat(bool enabled);
////////////////////////////////////////////////////////////
/// /see WindowImpl::SetIcon
///
////////////////////////////////////////////////////////////
virtual void SetIcon(unsigned int Width, unsigned int Height, const Uint8* Pixels);
virtual void SetIcon(unsigned int width, unsigned int height, const Uint8* pixels);
////////////////////////////////////////////////////////////
/// Switch to fullscreen mode
@ -141,7 +133,7 @@ private :
/// \param Mode : video mode to switch to
///
////////////////////////////////////////////////////////////
void SwitchToFullscreen(const VideoMode& Mode);
void SwitchToFullscreen(const VideoMode& mode);
////////////////////////////////////////////////////////////
/// Do some common initializations after the window has been created
@ -164,20 +156,20 @@ private :
////////////////////////////////////////////////////////////
/// Process an incoming event from the window
///
/// \param WinEvent : Event which has been received
/// \param windowEvent : Event which has been received
///
////////////////////////////////////////////////////////////
void ProcessEvent(XEvent WinEvent);
void ProcessEvent(XEvent windowEvent);
////////////////////////////////////////////////////////////
/// Convert a X11 keysym to SFML key code
///
/// \param Sym : keysym to convert
/// \param symbol : keysym to convert
///
/// \return Corrsponding SFML key code
///
////////////////////////////////////////////////////////////
static Key::Code KeysymToSF(KeySym Sym);
static Key::Code KeysymToSF(KeySym symbol);
////////////////////////////////////////////////////////////
// Member data

View file

@ -37,25 +37,37 @@
namespace
{
// Global array of supported video modes
std::vector<sf::VideoMode> SupportedModes;
std::vector<sf::VideoMode> supportedModes;
// Functor for sorting modes from highest to lowest
struct CompareModes
{
bool operator ()(const sf::VideoMode& v1, const sf::VideoMode& v2) const
bool operator ()(const sf::VideoMode& left, const sf::VideoMode& right) const
{
if (v1.BitsPerPixel > v2.BitsPerPixel)
if (left.BitsPerPixel > right.BitsPerPixel)
return true;
else if (v1.BitsPerPixel < v2.BitsPerPixel)
else if (left.BitsPerPixel < right.BitsPerPixel)
return false;
else if (v1.Width > v2.Width)
else if (left.Width > right.Width)
return true;
else if (v1.Width < v2.Width)
else if (left.Width < right.Width)
return false;
else
return (v1.Height > v2.Height);
return (left.Height > right.Height);
}
};
////////////////////////////////////////////////////////////
/// Get and sort valid video modes
////////////////////////////////////////////////////////////
static void InitializeModes()
{
// We request the array of valid modes
sf::priv::VideoModeSupport::GetSupportedVideoModes(supportedModes);
// And we sort them from highest to lowest (so that number 0 is the best)
std::sort(supportedModes.begin(), supportedModes.end(), CompareModes());
}
}
@ -76,10 +88,10 @@ BitsPerPixel(0)
////////////////////////////////////////////////////////////
/// Construct the video mode with its attributes
////////////////////////////////////////////////////////////
VideoMode::VideoMode(unsigned int ModeWidth, unsigned int ModeHeight, unsigned int ModeBpp) :
Width (ModeWidth),
Height (ModeHeight),
BitsPerPixel(ModeBpp)
VideoMode::VideoMode(unsigned int width, unsigned int height, unsigned int bitsPerPixel) :
Width (width),
Height (height),
BitsPerPixel(bitsPerPixel)
{
}
@ -99,13 +111,13 @@ VideoMode VideoMode::GetDesktopMode()
/// Get a valid video mode
/// Index must be in range [0, GetModesCount()[
////////////////////////////////////////////////////////////
VideoMode VideoMode::GetMode(std::size_t Index)
VideoMode VideoMode::GetMode(std::size_t index)
{
if (SupportedModes.empty())
if (supportedModes.empty())
InitializeModes();
if (Index < GetModesCount())
return SupportedModes[Index];
if (index < GetModesCount())
return supportedModes[index];
else
return VideoMode();
}
@ -116,10 +128,10 @@ VideoMode VideoMode::GetMode(std::size_t Index)
////////////////////////////////////////////////////////////
std::size_t VideoMode::GetModesCount()
{
if (SupportedModes.empty())
if (supportedModes.empty())
InitializeModes();
return SupportedModes.size();
return supportedModes.size();
}
@ -128,43 +140,30 @@ std::size_t VideoMode::GetModesCount()
////////////////////////////////////////////////////////////
bool VideoMode::IsValid() const
{
if (SupportedModes.empty())
if (supportedModes.empty())
InitializeModes();
return std::find(SupportedModes.begin(), SupportedModes.end(), *this) != SupportedModes.end();
return std::find(supportedModes.begin(), supportedModes.end(), *this) != supportedModes.end();
}
////////////////////////////////////////////////////////////
/// Comparison operator overload -- tell if two video modes are equal
////////////////////////////////////////////////////////////
bool VideoMode::operator ==(const VideoMode& Other) const
bool VideoMode::operator ==(const VideoMode& other) const
{
return (Width == Other.Width) &&
(Height == Other.Height) &&
(BitsPerPixel == Other.BitsPerPixel);
return (Width == other.Width) &&
(Height == other.Height) &&
(BitsPerPixel == other.BitsPerPixel);
}
////////////////////////////////////////////////////////////
/// Comparison operator overload -- tell if two video modes are different
////////////////////////////////////////////////////////////
bool VideoMode::operator !=(const VideoMode& Other) const
bool VideoMode::operator !=(const VideoMode& other) const
{
return !(*this == Other);
}
////////////////////////////////////////////////////////////
/// Get and sort valid video modes
////////////////////////////////////////////////////////////
void VideoMode::InitializeModes()
{
// We request the array of valid modes
priv::VideoModeSupport::GetSupportedVideoModes(SupportedModes);
// And we sort them from highest to lowest (so that number 0 is the best)
std::sort(SupportedModes.begin(), SupportedModes.end(), CompareModes());
return !(*this == other);
}
} // namespace sf

View file

@ -39,7 +39,7 @@ namespace priv
////////////////////////////////////////////////////////////
/// Create a new context, not associated to a window
////////////////////////////////////////////////////////////
ContextWGL::ContextWGL(ContextWGL* Shared) :
ContextWGL::ContextWGL(ContextWGL* shared) :
myWindow (NULL),
myDC (NULL),
myContext (NULL),
@ -54,10 +54,10 @@ myOwnsWindow(true)
// Create the context
if (myDC)
CreateContext(Shared, VideoMode::GetDesktopMode().BitsPerPixel, ContextSettings(0, 0, 0));
CreateContext(shared, VideoMode::GetDesktopMode().BitsPerPixel, ContextSettings(0, 0, 0));
// Activate the context
if (Shared)
if (shared)
SetActive(true);
}
@ -65,22 +65,22 @@ myOwnsWindow(true)
////////////////////////////////////////////////////////////
/// Create a new context attached to a window
////////////////////////////////////////////////////////////
ContextWGL::ContextWGL(ContextWGL* Shared, const WindowImpl* Owner, unsigned int BitsPerPixel, const ContextSettings& Settings) :
ContextWGL::ContextWGL(ContextWGL* shared, const WindowImpl* owner, unsigned int bitsPerPixel, const ContextSettings& settings) :
myWindow (NULL),
myDC (NULL),
myContext (NULL),
myOwnsWindow(false)
{
// Get the owner window and its device context
myWindow = static_cast<HWND>(Owner->GetHandle());
myWindow = static_cast<HWND>(owner->GetHandle());
myDC = GetDC(myWindow);
// Create the context
if (myDC)
CreateContext(Shared, BitsPerPixel, Settings);
CreateContext(shared, bitsPerPixel, settings);
// Activate the context
if (Shared)
if (shared)
SetActive(true);
}
@ -111,9 +111,9 @@ ContextWGL::~ContextWGL()
////////////////////////////////////////////////////////////
/// \see Context::MakeCurrent
////////////////////////////////////////////////////////////
bool ContextWGL::MakeCurrent(bool Active)
bool ContextWGL::MakeCurrent(bool active)
{
if (Active)
if (active)
{
if (myDC && myContext)
{
@ -150,11 +150,11 @@ void ContextWGL::Display()
////////////////////////////////////////////////////////////
/// \see Context::UseVerticalSync
////////////////////////////////////////////////////////////
void ContextWGL::UseVerticalSync(bool Enabled)
void ContextWGL::UseVerticalSync(bool enabled)
{
PFNWGLSWAPINTERVALEXTPROC wglSwapIntervalEXT = reinterpret_cast<PFNWGLSWAPINTERVALEXTPROC>(wglGetProcAddress("wglSwapIntervalEXT"));
if (wglSwapIntervalEXT)
wglSwapIntervalEXT(Enabled ? 1 : 0);
wglSwapIntervalEXT(enabled ? 1 : 0);
}
@ -170,20 +170,20 @@ bool ContextWGL::IsContextActive()
////////////////////////////////////////////////////////////
/// Create the context
////////////////////////////////////////////////////////////
void ContextWGL::CreateContext(ContextWGL* Shared, unsigned int BitsPerPixel, const ContextSettings& Settings)
void ContextWGL::CreateContext(ContextWGL* shared, unsigned int bitsPerPixel, const ContextSettings& settings)
{
// Save the creation settings
mySettings = Settings;
mySettings = settings;
// Let's find a suitable pixel format -- first try with antialiasing
int BestFormat = 0;
int bestFormat = 0;
if (mySettings.AntialiasingLevel > 0)
{
// Get the wglChoosePixelFormatARB function (it is an extension)
PFNWGLCHOOSEPIXELFORMATARBPROC wglChoosePixelFormatARB = reinterpret_cast<PFNWGLCHOOSEPIXELFORMATARBPROC>(wglGetProcAddress("wglChoosePixelFormatARB"));
// Define the basic attributes we want for our window
int IntAttributes[] =
int intAttributes[] =
{
WGL_DRAW_TO_WINDOW_ARB, GL_TRUE,
WGL_SUPPORT_OPENGL_ARB, GL_TRUE,
@ -195,11 +195,11 @@ void ContextWGL::CreateContext(ContextWGL* Shared, unsigned int BitsPerPixel, co
};
// Let's check how many formats are supporting our requirements
int Formats[128];
UINT NbFormats;
float FloatAttributes[] = {0, 0};
bool IsValid = wglChoosePixelFormatARB(myDC, IntAttributes, FloatAttributes, sizeof(Formats) / sizeof(*Formats), Formats, &NbFormats) != 0;
if (!IsValid || (NbFormats == 0))
int formats[128];
UINT nbFormats;
float floatAttributes[] = {0, 0};
bool isValid = wglChoosePixelFormatARB(myDC, intAttributes, floatAttributes, sizeof(formats) / sizeof(*formats), formats, &nbFormats) != 0;
if (!isValid || (nbFormats == 0))
{
if (mySettings.AntialiasingLevel > 2)
{
@ -207,11 +207,11 @@ void ContextWGL::CreateContext(ContextWGL* Shared, unsigned int BitsPerPixel, co
std::cerr << "Failed to find a pixel format supporting "
<< mySettings.AntialiasingLevel << " antialiasing levels ; trying with 2 levels" << std::endl;
mySettings.AntialiasingLevel = IntAttributes[1] = 2;
IsValid = wglChoosePixelFormatARB(myDC, IntAttributes, FloatAttributes, sizeof(Formats) / sizeof(*Formats), Formats, &NbFormats) != 0;
mySettings.AntialiasingLevel = intAttributes[1] = 2;
isValid = wglChoosePixelFormatARB(myDC, intAttributes, floatAttributes, sizeof(formats) / sizeof(*formats), formats, &nbFormats) != 0;
}
if (!IsValid || (NbFormats == 0))
if (!isValid || (nbFormats == 0))
{
// Cannot find any pixel format supporting multisampling ; disabling antialiasing
std::cerr << "Failed to find a pixel format supporting antialiasing ; antialiasing will be disabled" << std::endl;
@ -220,49 +220,49 @@ void ContextWGL::CreateContext(ContextWGL* Shared, unsigned int BitsPerPixel, co
}
// Get the best format among the returned ones
if (IsValid && (NbFormats > 0))
if (isValid && (nbFormats > 0))
{
int BestScore = 0xFFFF;
for (UINT i = 0; i < NbFormats; ++i)
int bestScore = 0xFFFF;
for (UINT i = 0; i < nbFormats; ++i)
{
// Get the current format's attributes
PIXELFORMATDESCRIPTOR Attribs;
Attribs.nSize = sizeof(PIXELFORMATDESCRIPTOR);
Attribs.nVersion = 1;
DescribePixelFormat(myDC, Formats[i], sizeof(PIXELFORMATDESCRIPTOR), &Attribs);
PIXELFORMATDESCRIPTOR attributes;
attributes.nSize = sizeof(attributes);
attributes.nVersion = 1;
DescribePixelFormat(myDC, formats[i], sizeof(attributes), &attributes);
// Evaluate the current configuration
int Color = Attribs.cRedBits + Attribs.cGreenBits + Attribs.cBlueBits + Attribs.cAlphaBits;
int Score = EvaluateFormat(BitsPerPixel, mySettings, Color, Attribs.cDepthBits, Attribs.cStencilBits, mySettings.AntialiasingLevel);
int color = attributes.cRedBits + attributes.cGreenBits + attributes.cBlueBits + attributes.cAlphaBits;
int score = EvaluateFormat(bitsPerPixel, mySettings, color, attributes.cDepthBits, attributes.cStencilBits, mySettings.AntialiasingLevel);
// Keep it if it's better than the current best
if (Score < BestScore)
if (score < bestScore)
{
BestScore = Score;
BestFormat = Formats[i];
bestScore = score;
bestFormat = formats[i];
}
}
}
}
// Find a pixel format with no antialiasing, if not needed or not supported
if (BestFormat == 0)
if (bestFormat == 0)
{
// Setup a pixel format descriptor from the rendering settings
PIXELFORMATDESCRIPTOR PixelDescriptor;
ZeroMemory(&PixelDescriptor, sizeof(PIXELFORMATDESCRIPTOR));
PixelDescriptor.nSize = sizeof(PIXELFORMATDESCRIPTOR);
PixelDescriptor.nVersion = 1;
PixelDescriptor.iLayerType = PFD_MAIN_PLANE;
PixelDescriptor.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER;
PixelDescriptor.iPixelType = PFD_TYPE_RGBA;
PixelDescriptor.cColorBits = static_cast<BYTE>(BitsPerPixel);
PixelDescriptor.cDepthBits = static_cast<BYTE>(mySettings.DepthBits);
PixelDescriptor.cStencilBits = static_cast<BYTE>(mySettings.StencilBits);
PIXELFORMATDESCRIPTOR descriptor;
ZeroMemory(&descriptor, sizeof(descriptor));
descriptor.nSize = sizeof(descriptor);
descriptor.nVersion = 1;
descriptor.iLayerType = PFD_MAIN_PLANE;
descriptor.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER;
descriptor.iPixelType = PFD_TYPE_RGBA;
descriptor.cColorBits = static_cast<BYTE>(bitsPerPixel);
descriptor.cDepthBits = static_cast<BYTE>(mySettings.DepthBits);
descriptor.cStencilBits = static_cast<BYTE>(mySettings.StencilBits);
// Get the pixel format that best matches our requirements
BestFormat = ChoosePixelFormat(myDC, &PixelDescriptor);
if (BestFormat == 0)
bestFormat = ChoosePixelFormat(myDC, &descriptor);
if (bestFormat == 0)
{
std::cerr << "Failed to find a suitable pixel format for device context -- cannot create OpenGL context" << std::endl;
return;
@ -270,34 +270,34 @@ void ContextWGL::CreateContext(ContextWGL* Shared, unsigned int BitsPerPixel, co
}
// Extract the depth and stencil bits from the chosen format
PIXELFORMATDESCRIPTOR ActualFormat;
ActualFormat.nSize = sizeof(PIXELFORMATDESCRIPTOR);
ActualFormat.nVersion = 1;
DescribePixelFormat(myDC, BestFormat, sizeof(PIXELFORMATDESCRIPTOR), &ActualFormat);
mySettings.DepthBits = ActualFormat.cDepthBits;
mySettings.StencilBits = ActualFormat.cStencilBits;
PIXELFORMATDESCRIPTOR actualFormat;
actualFormat.nSize = sizeof(actualFormat);
actualFormat.nVersion = 1;
DescribePixelFormat(myDC, bestFormat, sizeof(actualFormat), &actualFormat);
mySettings.DepthBits = actualFormat.cDepthBits;
mySettings.StencilBits = actualFormat.cStencilBits;
// Set the chosen pixel format
if (!SetPixelFormat(myDC, BestFormat, &ActualFormat))
if (!SetPixelFormat(myDC, bestFormat, &actualFormat))
{
std::cerr << "Failed to set pixel format for device context -- cannot create OpenGL context" << std::endl;
return;
}
// Get the context to share display lists with
HGLRC SharedContext = Shared ? Shared->myContext : NULL;
HGLRC sharedContext = shared ? shared->myContext : NULL;
// Create the OpenGL context -- first try an OpenGL 3.0 context if it is supported
PFNWGLCREATECONTEXTATTRIBSARBPROC wglCreateContextAttribsARB = reinterpret_cast<PFNWGLCREATECONTEXTATTRIBSARBPROC>(wglGetProcAddress("wglCreateContextAttribsARB"));
if (wglCreateContextAttribsARB)
{
int Attributes[] =
int attributes[] =
{
WGL_CONTEXT_MAJOR_VERSION_ARB, 3,
WGL_CONTEXT_MINOR_VERSION_ARB, 0,
0, 0
};
myContext = wglCreateContextAttribsARB(myDC, SharedContext, Attributes);
myContext = wglCreateContextAttribsARB(myDC, sharedContext, attributes);
}
// If the OpenGL 3.0 context failed, create a regular OpenGL 1.x context
@ -311,9 +311,9 @@ void ContextWGL::CreateContext(ContextWGL* Shared, unsigned int BitsPerPixel, co
}
// Share this context with others
if (SharedContext)
if (sharedContext)
{
if (!wglShareLists(SharedContext, myContext))
if (!wglShareLists(sharedContext, myContext))
std::cerr << "Failed to share the OpenGL context" << std::endl;
}
}

View file

@ -46,21 +46,21 @@ public :
////////////////////////////////////////////////////////////
/// Create a new context, not associated to a window
///
/// \param Shared : Context to share the new one with (can be NULL)
/// \param shared : Context to share the new one with (can be NULL)
///
////////////////////////////////////////////////////////////
ContextWGL(ContextWGL* Shared);
ContextWGL(ContextWGL* shared);
////////////////////////////////////////////////////////////
/// Create a new context attached to a window
///
/// \param Shared : Context to share the new one with (can be NULL)
/// \param Owner : Pointer to the owner window
/// \param BitsPerPixel : Pixel depth (in bits per pixel)
/// \param Settings : Creation parameters
/// \param shared : Context to share the new one with (can be NULL)
/// \param owner : Pointer to the owner window
/// \param bitsPerPixel : Pixel depth (in bits per pixel)
/// \param settings : Creation parameters
///
////////////////////////////////////////////////////////////
ContextWGL(ContextWGL* Shared, const WindowImpl* Owner, unsigned int BitsPerPixel, const ContextSettings& Settings);
ContextWGL(ContextWGL* shared, const WindowImpl* owner, unsigned int bitsPerPixel, const ContextSettings& settings);
////////////////////////////////////////////////////////////
/// Destructor
@ -72,7 +72,7 @@ public :
/// \see Context::MakeCurrent
///
////////////////////////////////////////////////////////////
virtual bool MakeCurrent(bool Active);
virtual bool MakeCurrent(bool active);
////////////////////////////////////////////////////////////
/// \see Context::Display
@ -84,7 +84,7 @@ public :
/// \see Context::UseVerticalSync
///
////////////////////////////////////////////////////////////
virtual void UseVerticalSync(bool Enabled);
virtual void UseVerticalSync(bool enabled);
////////////////////////////////////////////////////////////
/// Check if a context is active on the current thread
@ -99,12 +99,12 @@ private :
////////////////////////////////////////////////////////////
/// Create the context
///
/// \param Shared : Context to share the new one with (can be NULL)
/// \param BitsPerPixel : Pixel depth, in bits per pixel
/// \param Settings : Creation parameters
/// \param shared : Context to share the new one with (can be NULL)
/// \param bitsPerPixel : Pixel depth, in bits per pixel
/// \param settings : Creation parameters
///
////////////////////////////////////////////////////////////
void CreateContext(ContextWGL* Shared, unsigned int BitsPerPixel, const ContextSettings& Settings);
void CreateContext(ContextWGL* shared, unsigned int bitsPerPixel, const ContextSettings& settings);
////////////////////////////////////////////////////////////
// Member data

View file

@ -39,7 +39,7 @@ namespace priv
////////////////////////////////////////////////////////////
/// Initialize the instance and bind it to a physical joystick
////////////////////////////////////////////////////////////
void Joystick::Initialize(unsigned int Index)
void Joystick::Initialize(unsigned int index)
{
// Reset state
myIndex = JOYSTICKID1;
@ -47,23 +47,23 @@ void Joystick::Initialize(unsigned int Index)
myNbButtons = 0;
// Get the Index-th connected joystick
MMRESULT Error;
JOYINFOEX JoyInfo;
JoyInfo.dwSize = sizeof(JoyInfo);
JoyInfo.dwFlags = JOY_RETURNALL;
for (unsigned int NbFound = 0; (Error = joyGetPosEx(myIndex, &JoyInfo)) != JOYERR_PARMS; myIndex++)
MMRESULT error;
JOYINFOEX joyInfos;
joyInfos.dwSize = sizeof(joyInfos);
joyInfos.dwFlags = JOY_RETURNALL;
for (unsigned int found = 0; (error = joyGetPosEx(myIndex, &joyInfos)) != JOYERR_PARMS; myIndex++)
{
// Check if the current joystick is connected
if (Error == JOYERR_NOERROR)
if (error == JOYERR_NOERROR)
{
// Check if it's the required index
if (NbFound == Index)
if (found == index)
{
// Ok : store its parameters and return
JOYCAPS Caps;
joyGetDevCaps(myIndex, &Caps, sizeof(Caps));
myNbAxes = Caps.wNumAxes;
myNbButtons = Caps.wNumButtons;
JOYCAPS caps;
joyGetDevCaps(myIndex, &caps, sizeof(caps));
myNbAxes = caps.wNumAxes;
myNbButtons = caps.wNumButtons;
if (myNbButtons > JoystickState::MaxButtons)
myNbButtons = JoystickState::MaxButtons;
@ -71,7 +71,7 @@ void Joystick::Initialize(unsigned int Index)
}
// Go to the next valid joystick
++NbFound;
++found;
}
}
}
@ -82,36 +82,36 @@ void Joystick::Initialize(unsigned int Index)
////////////////////////////////////////////////////////////
JoystickState Joystick::UpdateState()
{
JoystickState State = {0};
JoystickState state = {0};
// Get the joystick caps (for range conversions)
JOYCAPS Caps;
if (joyGetDevCaps(myIndex, &Caps, sizeof(Caps)) == JOYERR_NOERROR)
JOYCAPS caps;
if (joyGetDevCaps(myIndex, &caps, sizeof(caps)) == JOYERR_NOERROR)
{
// Get the current joystick state
JOYINFOEX Pos;
Pos.dwFlags = JOY_RETURNALL;
Pos.dwSize = sizeof(JOYINFOEX);
if (joyGetPosEx(myIndex, &Pos) == JOYERR_NOERROR)
JOYINFOEX pos;
pos.dwFlags = JOY_RETURNALL;
pos.dwSize = sizeof(JOYINFOEX);
if (joyGetPosEx(myIndex, &pos) == JOYERR_NOERROR)
{
// Axes
State.Axis[Joy::AxisX] = (Pos.dwXpos - (Caps.wXmax + Caps.wXmin) / 2.f) * 200.f / (Caps.wXmax - Caps.wXmin);
State.Axis[Joy::AxisY] = (Pos.dwYpos - (Caps.wYmax + Caps.wYmin) / 2.f) * 200.f / (Caps.wYmax - Caps.wYmin);
State.Axis[Joy::AxisZ] = (Pos.dwZpos - (Caps.wZmax + Caps.wZmin) / 2.f) * 200.f / (Caps.wZmax - Caps.wZmin);
State.Axis[Joy::AxisR] = (Pos.dwRpos - (Caps.wRmax + Caps.wRmin) / 2.f) * 200.f / (Caps.wRmax - Caps.wRmin);
State.Axis[Joy::AxisU] = (Pos.dwUpos - (Caps.wUmax + Caps.wUmin) / 2.f) * 200.f / (Caps.wUmax - Caps.wUmin);
State.Axis[Joy::AxisV] = (Pos.dwVpos - (Caps.wVmax + Caps.wVmin) / 2.f) * 200.f / (Caps.wVmax - Caps.wVmin);
state.Axis[Joy::AxisX] = (pos.dwXpos - (caps.wXmax + caps.wXmin) / 2.f) * 200.f / (caps.wXmax - caps.wXmin);
state.Axis[Joy::AxisY] = (pos.dwYpos - (caps.wYmax + caps.wYmin) / 2.f) * 200.f / (caps.wYmax - caps.wYmin);
state.Axis[Joy::AxisZ] = (pos.dwZpos - (caps.wZmax + caps.wZmin) / 2.f) * 200.f / (caps.wZmax - caps.wZmin);
state.Axis[Joy::AxisR] = (pos.dwRpos - (caps.wRmax + caps.wRmin) / 2.f) * 200.f / (caps.wRmax - caps.wRmin);
state.Axis[Joy::AxisU] = (pos.dwUpos - (caps.wUmax + caps.wUmin) / 2.f) * 200.f / (caps.wUmax - caps.wUmin);
state.Axis[Joy::AxisV] = (pos.dwVpos - (caps.wVmax + caps.wVmin) / 2.f) * 200.f / (caps.wVmax - caps.wVmin);
// POV
State.Axis[Joy::AxisPOV] = Pos.dwPOV / 100.f;
state.Axis[Joy::AxisPOV] = pos.dwPOV / 100.f;
// Buttons
for (unsigned int i = 0; i < GetButtonsCount(); ++i)
State.Buttons[i] = (Pos.dwButtons & (1 << i)) != 0;
state.Buttons[i] = (pos.dwButtons & (1 << i)) != 0;
}
}
return State;
return state;
}

View file

@ -44,10 +44,10 @@ public :
////////////////////////////////////////////////////////////
/// Initialize the instance and bind it to a physical joystick
///
/// \param Index : Index of the physical joystick to bind to
/// \param index : Index of the physical joystick to bind to
///
////////////////////////////////////////////////////////////
void Initialize(unsigned int Index);
void Initialize(unsigned int index);
////////////////////////////////////////////////////////////
/// Update the current joystick and return its new state

View file

@ -37,22 +37,22 @@ namespace priv
////////////////////////////////////////////////////////////
/// Get supported video modes
////////////////////////////////////////////////////////////
void VideoModeSupport::GetSupportedVideoModes(std::vector<VideoMode>& Modes)
void VideoModeSupport::GetSupportedVideoModes(std::vector<VideoMode>& modes)
{
// First, clear array to fill
Modes.clear();
modes.clear();
// Enumerate all available video modes for primary display adapter
DEVMODE Win32Mode;
Win32Mode.dmSize = sizeof(DEVMODE);
for (int Count = 0; EnumDisplaySettings(NULL, Count, &Win32Mode); ++Count)
DEVMODE win32Mode;
win32Mode.dmSize = sizeof(win32Mode);
for (int count = 0; EnumDisplaySettings(NULL, count, &win32Mode); ++count)
{
// Convert to sfVideoMode
VideoMode Mode(Win32Mode.dmPelsWidth, Win32Mode.dmPelsHeight, Win32Mode.dmBitsPerPel);
VideoMode mode(win32Mode.dmPelsWidth, win32Mode.dmPelsHeight, win32Mode.dmBitsPerPel);
// Add it only if it is not already in the array
if (std::find(Modes.begin(), Modes.end(), Mode) == Modes.end())
Modes.push_back(Mode);
if (std::find(modes.begin(), modes.end(), mode) == modes.end())
modes.push_back(mode);
}
}
@ -62,11 +62,11 @@ void VideoModeSupport::GetSupportedVideoModes(std::vector<VideoMode>& Modes)
////////////////////////////////////////////////////////////
VideoMode VideoModeSupport::GetDesktopVideoMode()
{
DEVMODE Win32Mode;
Win32Mode.dmSize = sizeof(DEVMODE);
EnumDisplaySettings(NULL, ENUM_CURRENT_SETTINGS, &Win32Mode);
DEVMODE win32Mode;
win32Mode.dmSize = sizeof(win32Mode);
EnumDisplaySettings(NULL, ENUM_CURRENT_SETTINGS, &win32Mode);
return VideoMode(Win32Mode.dmPelsWidth, Win32Mode.dmPelsHeight, Win32Mode.dmBitsPerPel);
return VideoMode(win32Mode.dmPelsWidth, win32Mode.dmPelsHeight, win32Mode.dmBitsPerPel);
}
} // namespace priv

View file

@ -50,7 +50,7 @@ public :
/// \param Modes : Array to fill with available video modes
///
////////////////////////////////////////////////////////////
static void GetSupportedVideoModes(std::vector<VideoMode>& Modes);
static void GetSupportedVideoModes(std::vector<VideoMode>& modes);
////////////////////////////////////////////////////////////
/// Get current desktop video mode

View file

@ -60,7 +60,7 @@ WindowImplWin32* WindowImplWin32::ourFullscreenWindow = NULL;
////////////////////////////////////////////////////////////
/// Create the window implementation from an existing control
////////////////////////////////////////////////////////////
WindowImplWin32::WindowImplWin32(WindowHandle Handle) :
WindowImplWin32::WindowImplWin32(WindowHandle handle) :
myHandle (NULL),
myCallback (0),
myCursor (NULL),
@ -69,15 +69,15 @@ myKeyRepeatEnabled(true),
myIsCursorIn (false)
{
// Save window handle
myHandle = static_cast<HWND>(Handle);
myHandle = static_cast<HWND>(handle);
if (myHandle)
{
// Get window client size
RECT Rect;
GetClientRect(myHandle, &Rect);
myWidth = Rect.right - Rect.left;
myHeight = Rect.bottom - Rect.top;
RECT rectangle;
GetClientRect(myHandle, &rectangle);
myWidth = rectangle.right - rectangle.left;
myHeight = rectangle.bottom - rectangle.top;
// We change the event procedure of the control (it is important to save the old one)
SetWindowLongPtr(myHandle, GWLP_USERDATA, reinterpret_cast<long>(this));
@ -89,7 +89,7 @@ myIsCursorIn (false)
////////////////////////////////////////////////////////////
/// Create the window implementation
////////////////////////////////////////////////////////////
WindowImplWin32::WindowImplWin32(VideoMode Mode, const std::string& Title, unsigned long WindowStyle) :
WindowImplWin32::WindowImplWin32(VideoMode mode, const std::string& title, unsigned long style) :
myHandle (NULL),
myCallback (0),
myCursor (NULL),
@ -102,60 +102,60 @@ myIsCursorIn (false)
RegisterWindowClass();
// Compute position and size
int Left = (GetDeviceCaps(GetDC(NULL), HORZRES) - Mode.Width) / 2;
int Top = (GetDeviceCaps(GetDC(NULL), VERTRES) - Mode.Height) / 2;
int Width = myWidth = Mode.Width;
int Height = myHeight = Mode.Height;
int left = (GetDeviceCaps(GetDC(NULL), HORZRES) - mode.Width) / 2;
int top = (GetDeviceCaps(GetDC(NULL), VERTRES) - mode.Height) / 2;
int width = myWidth = mode.Width;
int height = myHeight = mode.Height;
// Choose the window style according to the Style parameter
DWORD Win32Style = WS_VISIBLE;
if (WindowStyle == Style::None)
DWORD win32Style = WS_VISIBLE;
if (style == Style::None)
{
Win32Style |= WS_POPUP;
win32Style |= WS_POPUP;
}
else
{
if (WindowStyle & Style::Titlebar) Win32Style |= WS_CAPTION | WS_MINIMIZEBOX;
if (WindowStyle & Style::Resize) Win32Style |= WS_THICKFRAME | WS_MAXIMIZEBOX;
if (WindowStyle & Style::Close) Win32Style |= WS_SYSMENU;
if (style & Style::Titlebar) win32Style |= WS_CAPTION | WS_MINIMIZEBOX;
if (style & Style::Resize) win32Style |= WS_THICKFRAME | WS_MAXIMIZEBOX;
if (style & Style::Close) win32Style |= WS_SYSMENU;
}
// In windowed mode, adjust width and height so that window will have the requested client area
bool Fullscreen = (WindowStyle & Style::Fullscreen) != 0;
if (!Fullscreen)
bool fullscreen = (style & Style::Fullscreen) != 0;
if (!fullscreen)
{
RECT Rect = {0, 0, Width, Height};
AdjustWindowRect(&Rect, Win32Style, false);
Width = Rect.right - Rect.left;
Height = Rect.bottom - Rect.top;
RECT rectangle = {0, 0, width, height};
AdjustWindowRect(&rectangle, win32Style, false);
width = rectangle.right - rectangle.left;
height = rectangle.bottom - rectangle.top;
}
// Create the window
if (HasUnicodeSupport())
{
wchar_t WTitle[256];
int NbChars = MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, Title.c_str(), static_cast<int>(Title.size()), WTitle, sizeof(WTitle) / sizeof(*WTitle));
WTitle[NbChars] = L'\0';
myHandle = CreateWindowW(ourClassNameW, WTitle, Win32Style, Left, Top, Width, Height, NULL, NULL, GetModuleHandle(NULL), this);
wchar_t wTitle[256];
int count = MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, title.c_str(), static_cast<int>(title.size()), wTitle, sizeof(wTitle) / sizeof(*wTitle));
wTitle[count] = L'\0';
myHandle = CreateWindowW(ourClassNameW, wTitle, win32Style, left, top, width, height, NULL, NULL, GetModuleHandle(NULL), this);
}
else
{
myHandle = CreateWindowA(ourClassNameA, Title.c_str(), Win32Style, Left, Top, Width, Height, NULL, NULL, GetModuleHandle(NULL), this);
myHandle = CreateWindowA(ourClassNameA, title.c_str(), win32Style, left, top, width, height, NULL, NULL, GetModuleHandle(NULL), this);
}
// Switch to fullscreen if requested
if (Fullscreen)
SwitchToFullscreen(Mode);
if (fullscreen)
SwitchToFullscreen(mode);
// Increment window count
ourWindowCount++;
// Get the actual size of the window, which can be smaller even after the call to AdjustWindowRect
// This happens when the window is bigger than the desktop
RECT ActualRect;
GetClientRect(myHandle, &ActualRect);
myWidth = ActualRect.right - ActualRect.left;
myHeight = ActualRect.bottom - ActualRect.top;
RECT actualRectangle;
GetClientRect(myHandle, &actualRectangle);
myWidth = actualRectangle.right - actualRectangle.left;
myHeight = actualRectangle.bottom - actualRectangle.top;
}
@ -215,11 +215,11 @@ void WindowImplWin32::ProcessEvents()
// We update the window only if we own it
if (!myCallback)
{
MSG Message;
while (PeekMessage(&Message, myHandle, 0, 0, PM_REMOVE))
MSG message;
while (PeekMessage(&message, myHandle, 0, 0, PM_REMOVE))
{
TranslateMessage(&Message);
DispatchMessage(&Message);
TranslateMessage(&message);
DispatchMessage(&message);
}
}
}
@ -228,9 +228,9 @@ void WindowImplWin32::ProcessEvents()
////////////////////////////////////////////////////////////
/// /see WindowImpl::ShowMouseCursor
////////////////////////////////////////////////////////////
void WindowImplWin32::ShowMouseCursor(bool Show)
void WindowImplWin32::ShowMouseCursor(bool show)
{
if (Show)
if (show)
myCursor = LoadCursor(NULL, IDC_ARROW);
else
myCursor = NULL;
@ -242,78 +242,78 @@ void WindowImplWin32::ShowMouseCursor(bool Show)
////////////////////////////////////////////////////////////
/// /see WindowImpl::SetCursorPosition
////////////////////////////////////////////////////////////
void WindowImplWin32::SetCursorPosition(unsigned int Left, unsigned int Top)
void WindowImplWin32::SetCursorPosition(unsigned int left, unsigned int top)
{
POINT Pos = {Left, Top};
ClientToScreen(myHandle, &Pos);
SetCursorPos(Pos.x, Pos.y);
POINT position = {left, top};
ClientToScreen(myHandle, &position);
SetCursorPos(position.x, position.y);
}
////////////////////////////////////////////////////////////
/// /see WindowImpl::SetPosition
////////////////////////////////////////////////////////////
void WindowImplWin32::SetPosition(int Left, int Top)
void WindowImplWin32::SetPosition(int left, int top)
{
SetWindowPos(myHandle, NULL, Left, Top, 0, 0, SWP_NOSIZE | SWP_NOZORDER);
SetWindowPos(myHandle, NULL, left, top, 0, 0, SWP_NOSIZE | SWP_NOZORDER);
}
////////////////////////////////////////////////////////////
/// /see WindowImpl::SetSize
////////////////////////////////////////////////////////////
void WindowImplWin32::SetSize(unsigned int Width, unsigned int Height)
void WindowImplWin32::SetSize(unsigned int width, unsigned int height)
{
// SetWindowPos wants the total size of the window (including title bar and borders),
// so we have to compute it
RECT Rect = {0, 0, Width, Height};
AdjustWindowRect(&Rect, GetWindowLong(myHandle, GWL_STYLE), false);
Width = Rect.right - Rect.left;
Height = Rect.bottom - Rect.top;
RECT rectangle = {0, 0, width, height};
AdjustWindowRect(&rectangle, GetWindowLong(myHandle, GWL_STYLE), false);
width = rectangle.right - rectangle.left;
height = rectangle.bottom - rectangle.top;
SetWindowPos(myHandle, NULL, 0, 0, Width, Height, SWP_NOMOVE | SWP_NOZORDER);
SetWindowPos(myHandle, NULL, 0, 0, width, height, SWP_NOMOVE | SWP_NOZORDER);
}
////////////////////////////////////////////////////////////
/// /see WindowImpl::Show
////////////////////////////////////////////////////////////
void WindowImplWin32::Show(bool State)
void WindowImplWin32::Show(bool show)
{
ShowWindow(myHandle, State ? SW_SHOW : SW_HIDE);
ShowWindow(myHandle, show ? SW_SHOW : SW_HIDE);
}
////////////////////////////////////////////////////////////
/// /see WindowImpl::EnableKeyRepeat
////////////////////////////////////////////////////////////
void WindowImplWin32::EnableKeyRepeat(bool Enabled)
void WindowImplWin32::EnableKeyRepeat(bool enabled)
{
myKeyRepeatEnabled = Enabled;
myKeyRepeatEnabled = enabled;
}
////////////////////////////////////////////////////////////
/// /see WindowImpl::SetIcon
////////////////////////////////////////////////////////////
void WindowImplWin32::SetIcon(unsigned int Width, unsigned int Height, const Uint8* Pixels)
void WindowImplWin32::SetIcon(unsigned int width, unsigned int height, const Uint8* pixels)
{
// First destroy the previous one
if (myIcon)
DestroyIcon(myIcon);
// Windows wants BGRA pixels : swap red and blue channels
std::vector<Uint8> IconPixels(Width * Height * 4);
for (std::size_t i = 0; i < IconPixels.size() / 4; ++i)
std::vector<Uint8> iconPixels(width * height * 4);
for (std::size_t i = 0; i < iconPixels.size() / 4; ++i)
{
IconPixels[i * 4 + 0] = Pixels[i * 4 + 2];
IconPixels[i * 4 + 1] = Pixels[i * 4 + 1];
IconPixels[i * 4 + 2] = Pixels[i * 4 + 0];
IconPixels[i * 4 + 3] = Pixels[i * 4 + 3];
iconPixels[i * 4 + 0] = pixels[i * 4 + 2];
iconPixels[i * 4 + 1] = pixels[i * 4 + 1];
iconPixels[i * 4 + 2] = pixels[i * 4 + 0];
iconPixels[i * 4 + 3] = pixels[i * 4 + 3];
}
// Create the icon from the pixels array
myIcon = CreateIcon(GetModuleHandle(NULL), Width, Height, 1, 32, NULL, &IconPixels[0]);
myIcon = CreateIcon(GetModuleHandle(NULL), width, height, 1, 32, NULL, &iconPixels[0]);
// Set it as both big and small icon of the window
if (myIcon)
@ -369,17 +369,17 @@ void WindowImplWin32::RegisterWindowClass()
////////////////////////////////////////////////////////////
/// Switch to fullscreen mode
////////////////////////////////////////////////////////////
void WindowImplWin32::SwitchToFullscreen(const VideoMode& Mode)
void WindowImplWin32::SwitchToFullscreen(const VideoMode& mode)
{
DEVMODE DevMode;
DevMode.dmSize = sizeof(DEVMODE);
DevMode.dmPelsWidth = Mode.Width;
DevMode.dmPelsHeight = Mode.Height;
DevMode.dmBitsPerPel = Mode.BitsPerPixel;
DevMode.dmFields = DM_PELSWIDTH | DM_PELSHEIGHT | DM_BITSPERPEL;
DEVMODE devMode;
devMode.dmSize = sizeof(devMode);
devMode.dmPelsWidth = mode.Width;
devMode.dmPelsHeight = mode.Height;
devMode.dmBitsPerPel = mode.BitsPerPixel;
devMode.dmFields = DM_PELSWIDTH | DM_PELSHEIGHT | DM_BITSPERPEL;
// Apply fullscreen mode
if (ChangeDisplaySettings(&DevMode, CDS_FULLSCREEN) != DISP_CHANGE_SUCCESSFUL)
if (ChangeDisplaySettings(&devMode, CDS_FULLSCREEN) != DISP_CHANGE_SUCCESSFUL)
{
std::cerr << "Failed to change display mode for fullscreen" << std::endl;
return;
@ -390,15 +390,15 @@ void WindowImplWin32::SwitchToFullscreen(const VideoMode& Mode)
SetWindowLong(myHandle, GWL_EXSTYLE, WS_EX_APPWINDOW);
// And resize it so that it fits the entire screen
SetWindowPos(myHandle, HWND_TOP, 0, 0, Mode.Width, Mode.Height, SWP_FRAMECHANGED);
SetWindowPos(myHandle, HWND_TOP, 0, 0, mode.Width, mode.Height, SWP_FRAMECHANGED);
ShowWindow(myHandle, SW_SHOW);
// Set "this" as the current fullscreen window
ourFullscreenWindow = this;
// SetPixelFormat can fail (really ?) if window style doesn't contain these flags
long Style = GetWindowLong(myHandle, GWL_STYLE);
SetWindowLong(myHandle, GWL_STYLE, Style | WS_CLIPCHILDREN | WS_CLIPSIBLINGS);
long style = GetWindowLong(myHandle, GWL_STYLE);
SetWindowLong(myHandle, GWL_STYLE, style | WS_CLIPCHILDREN | WS_CLIPSIBLINGS);
}
@ -422,13 +422,13 @@ void WindowImplWin32::Cleanup()
////////////////////////////////////////////////////////////
/// Process a Win32 event
////////////////////////////////////////////////////////////
void WindowImplWin32::ProcessEvent(UINT Message, WPARAM WParam, LPARAM LParam)
void WindowImplWin32::ProcessEvent(UINT message, WPARAM wParam, LPARAM lParam)
{
// Don't process any message until window is created
if (myHandle == NULL)
return;
switch (Message)
switch (message)
{
// Destroy event
case WM_DESTROY :
@ -442,7 +442,7 @@ void WindowImplWin32::ProcessEvent(UINT Message, WPARAM WParam, LPARAM LParam)
case WM_SETCURSOR :
{
// The mouse has moved, if the cursor is in our window we must refresh the cursor
if (LOWORD(LParam) == HTCLIENT)
if (LOWORD(lParam) == HTCLIENT)
SetCursor(myCursor);
break;
@ -451,9 +451,9 @@ void WindowImplWin32::ProcessEvent(UINT Message, WPARAM WParam, LPARAM LParam)
// Close event
case WM_CLOSE :
{
Event Evt;
Evt.Type = Event::Closed;
SendEvent(Evt);
Event event;
event.Type = Event::Closed;
SendEvent(event);
break;
}
@ -461,44 +461,44 @@ void WindowImplWin32::ProcessEvent(UINT Message, WPARAM WParam, LPARAM LParam)
case WM_SIZE :
{
// Update window size
RECT Rect;
GetClientRect(myHandle, &Rect);
myWidth = Rect.right - Rect.left;
myHeight = Rect.bottom - Rect.top;
RECT rectangle;
GetClientRect(myHandle, &rectangle);
myWidth = rectangle.right - rectangle.left;
myHeight = rectangle.bottom - rectangle.top;
Event Evt;
Evt.Type = Event::Resized;
Evt.Size.Width = myWidth;
Evt.Size.Height = myHeight;
SendEvent(Evt);
Event event;
event.Type = Event::Resized;
event.Size.Width = myWidth;
event.Size.Height = myHeight;
SendEvent(event);
break;
}
// Gain focus event
case WM_SETFOCUS :
{
Event Evt;
Evt.Type = Event::GainedFocus;
SendEvent(Evt);
Event event;
event.Type = Event::GainedFocus;
SendEvent(event);
break;
}
// Lost focus event
case WM_KILLFOCUS :
{
Event Evt;
Evt.Type = Event::LostFocus;
SendEvent(Evt);
Event event;
event.Type = Event::LostFocus;
SendEvent(event);
break;
}
// Text event
case WM_CHAR :
{
Event Evt;
Evt.Type = Event::TextEntered;
Evt.Text.Unicode = static_cast<Uint32>(WParam);
SendEvent(Evt);
Event event;
event.Type = Event::TextEntered;
event.Text.Unicode = static_cast<Uint32>(wParam);
SendEvent(event);
break;
}
@ -506,25 +506,25 @@ void WindowImplWin32::ProcessEvent(UINT Message, WPARAM WParam, LPARAM LParam)
case WM_KEYDOWN :
case WM_SYSKEYDOWN :
{
if (myKeyRepeatEnabled || ((LParam & (1 << 30)) == 0))
if (myKeyRepeatEnabled || ((lParam & (1 << 30)) == 0))
{
Event Evt;
Evt.Type = Event::KeyPressed;
Evt.Key.Alt = HIWORD(GetAsyncKeyState(VK_MENU)) != 0;
Evt.Key.Control = HIWORD(GetAsyncKeyState(VK_CONTROL)) != 0;
Evt.Key.Shift = HIWORD(GetAsyncKeyState(VK_SHIFT)) != 0;
Event event;
event.Type = Event::KeyPressed;
event.Key.Alt = HIWORD(GetAsyncKeyState(VK_MENU)) != 0;
event.Key.Control = HIWORD(GetAsyncKeyState(VK_CONTROL)) != 0;
event.Key.Shift = HIWORD(GetAsyncKeyState(VK_SHIFT)) != 0;
if (WParam != VK_SHIFT)
if (wParam != VK_SHIFT)
{
Evt.Key.Code = VirtualKeyCodeToSF(WParam, LParam);
SendEvent(Evt);
event.Key.Code = VirtualKeyCodeToSF(wParam, lParam);
SendEvent(event);
}
else
{
// Special case for shift, its state can't be retrieved directly
Evt.Key.Code = GetShiftState(true);
if (Evt.Key.Code != 0)
SendEvent(Evt);
event.Key.Code = GetShiftState(true);
if (event.Key.Code != 0)
SendEvent(event);
}
}
break;
@ -534,23 +534,23 @@ void WindowImplWin32::ProcessEvent(UINT Message, WPARAM WParam, LPARAM LParam)
case WM_KEYUP :
case WM_SYSKEYUP :
{
Event Evt;
Evt.Type = Event::KeyReleased;
Evt.Key.Alt = HIWORD(GetAsyncKeyState(VK_MENU)) != 0;
Evt.Key.Control = HIWORD(GetAsyncKeyState(VK_CONTROL)) != 0;
Evt.Key.Shift = HIWORD(GetAsyncKeyState(VK_SHIFT)) != 0;
Event event;
event.Type = Event::KeyReleased;
event.Key.Alt = HIWORD(GetAsyncKeyState(VK_MENU)) != 0;
event.Key.Control = HIWORD(GetAsyncKeyState(VK_CONTROL)) != 0;
event.Key.Shift = HIWORD(GetAsyncKeyState(VK_SHIFT)) != 0;
if (WParam != VK_SHIFT)
if (wParam != VK_SHIFT)
{
Evt.Key.Code = VirtualKeyCodeToSF(WParam, LParam);
SendEvent(Evt);
event.Key.Code = VirtualKeyCodeToSF(wParam, lParam);
SendEvent(event);
}
else
{
// Special case for shift, its state can't be retrieved directly
Evt.Key.Code = GetShiftState(false);
if (Evt.Key.Code != 0)
SendEvent(Evt);
event.Key.Code = GetShiftState(false);
if (event.Key.Code != 0)
SendEvent(event);
}
break;
@ -559,106 +559,106 @@ void WindowImplWin32::ProcessEvent(UINT Message, WPARAM WParam, LPARAM LParam)
// Mouse wheel event
case WM_MOUSEWHEEL :
{
Event Evt;
Evt.Type = Event::MouseWheelMoved;
Evt.MouseWheel.Delta = static_cast<Int16>(HIWORD(WParam)) / 120;
SendEvent(Evt);
Event event;
event.Type = Event::MouseWheelMoved;
event.MouseWheel.Delta = static_cast<Int16>(HIWORD(wParam)) / 120;
SendEvent(event);
break;
}
// Mouse left button down event
case WM_LBUTTONDOWN :
{
Event Evt;
Evt.Type = Event::MouseButtonPressed;
Evt.MouseButton.Button = Mouse::Left;
Evt.MouseButton.X = LOWORD(LParam);
Evt.MouseButton.Y = HIWORD(LParam);
SendEvent(Evt);
Event event;
event.Type = Event::MouseButtonPressed;
event.MouseButton.Button = Mouse::Left;
event.MouseButton.X = LOWORD(lParam);
event.MouseButton.Y = HIWORD(lParam);
SendEvent(event);
break;
}
// Mouse left button up event
case WM_LBUTTONUP :
{
Event Evt;
Evt.Type = Event::MouseButtonReleased;
Evt.MouseButton.Button = Mouse::Left;
Evt.MouseButton.X = LOWORD(LParam);
Evt.MouseButton.Y = HIWORD(LParam);
SendEvent(Evt);
Event event;
event.Type = Event::MouseButtonReleased;
event.MouseButton.Button = Mouse::Left;
event.MouseButton.X = LOWORD(lParam);
event.MouseButton.Y = HIWORD(lParam);
SendEvent(event);
break;
}
// Mouse right button down event
case WM_RBUTTONDOWN :
{
Event Evt;
Evt.Type = Event::MouseButtonPressed;
Evt.MouseButton.Button = Mouse::Right;
Evt.MouseButton.X = LOWORD(LParam);
Evt.MouseButton.Y = HIWORD(LParam);
SendEvent(Evt);
Event event;
event.Type = Event::MouseButtonPressed;
event.MouseButton.Button = Mouse::Right;
event.MouseButton.X = LOWORD(lParam);
event.MouseButton.Y = HIWORD(lParam);
SendEvent(event);
break;
}
// Mouse right button up event
case WM_RBUTTONUP :
{
Event Evt;
Evt.Type = Event::MouseButtonReleased;
Evt.MouseButton.Button = Mouse::Right;
Evt.MouseButton.X = LOWORD(LParam);
Evt.MouseButton.Y = HIWORD(LParam);
SendEvent(Evt);
Event event;
event.Type = Event::MouseButtonReleased;
event.MouseButton.Button = Mouse::Right;
event.MouseButton.X = LOWORD(lParam);
event.MouseButton.Y = HIWORD(lParam);
SendEvent(event);
break;
}
// Mouse wheel button down event
case WM_MBUTTONDOWN :
{
Event Evt;
Evt.Type = Event::MouseButtonPressed;
Evt.MouseButton.Button = Mouse::Middle;
Evt.MouseButton.X = LOWORD(LParam);
Evt.MouseButton.Y = HIWORD(LParam);
SendEvent(Evt);
Event event;
event.Type = Event::MouseButtonPressed;
event.MouseButton.Button = Mouse::Middle;
event.MouseButton.X = LOWORD(lParam);
event.MouseButton.Y = HIWORD(lParam);
SendEvent(event);
break;
}
// Mouse wheel button up event
case WM_MBUTTONUP :
{
Event Evt;
Evt.Type = Event::MouseButtonReleased;
Evt.MouseButton.Button = Mouse::Middle;
Evt.MouseButton.X = LOWORD(LParam);
Evt.MouseButton.Y = HIWORD(LParam);
SendEvent(Evt);
Event event;
event.Type = Event::MouseButtonReleased;
event.MouseButton.Button = Mouse::Middle;
event.MouseButton.X = LOWORD(lParam);
event.MouseButton.Y = HIWORD(lParam);
SendEvent(event);
break;
}
// Mouse X button down event
case WM_XBUTTONDOWN :
{
Event Evt;
Evt.Type = Event::MouseButtonPressed;
Evt.MouseButton.Button = HIWORD(WParam) == XBUTTON1 ? Mouse::XButton1 : Mouse::XButton2;
Evt.MouseButton.X = LOWORD(LParam);
Evt.MouseButton.Y = HIWORD(LParam);
SendEvent(Evt);
Event event;
event.Type = Event::MouseButtonPressed;
event.MouseButton.Button = HIWORD(wParam) == XBUTTON1 ? Mouse::XButton1 : Mouse::XButton2;
event.MouseButton.X = LOWORD(lParam);
event.MouseButton.Y = HIWORD(lParam);
SendEvent(event);
break;
}
// Mouse X button up event
case WM_XBUTTONUP :
{
Event Evt;
Evt.Type = Event::MouseButtonReleased;
Evt.MouseButton.Button = HIWORD(WParam) == XBUTTON1 ? Mouse::XButton1 : Mouse::XButton2;
Evt.MouseButton.X = LOWORD(LParam);
Evt.MouseButton.Y = HIWORD(LParam);
SendEvent(Evt);
Event event;
event.Type = Event::MouseButtonReleased;
event.MouseButton.Button = HIWORD(wParam) == XBUTTON1 ? Mouse::XButton1 : Mouse::XButton2;
event.MouseButton.X = LOWORD(lParam);
event.MouseButton.Y = HIWORD(lParam);
SendEvent(event);
break;
}
@ -668,24 +668,24 @@ void WindowImplWin32::ProcessEvent(UINT Message, WPARAM WParam, LPARAM LParam)
// Check if we need to generate a MouseEntered event
if (!myIsCursorIn)
{
TRACKMOUSEEVENT MouseEvent;
MouseEvent.cbSize = sizeof(TRACKMOUSEEVENT);
MouseEvent.hwndTrack = myHandle;
MouseEvent.dwFlags = TME_LEAVE;
TrackMouseEvent(&MouseEvent);
TRACKMOUSEEVENT mouseEvent;
mouseEvent.cbSize = sizeof(TRACKMOUSEEVENT);
mouseEvent.hwndTrack = myHandle;
mouseEvent.dwFlags = TME_LEAVE;
TrackMouseEvent(&mouseEvent);
myIsCursorIn = true;
Event Evt;
Evt.Type = Event::MouseEntered;
SendEvent(Evt);
Event event;
event.Type = Event::MouseEntered;
SendEvent(event);
}
Event Evt;
Evt.Type = Event::MouseMoved;
Evt.MouseMove.X = LOWORD(LParam);
Evt.MouseMove.Y = HIWORD(LParam);
SendEvent(Evt);
Event event;
event.Type = Event::MouseMoved;
event.MouseMove.X = LOWORD(lParam);
event.MouseMove.Y = HIWORD(lParam);
SendEvent(event);
break;
}
@ -694,9 +694,9 @@ void WindowImplWin32::ProcessEvent(UINT Message, WPARAM WParam, LPARAM LParam)
{
myIsCursorIn = false;
Event Evt;
Evt.Type = Event::MouseLeft;
SendEvent(Evt);
Event event;
event.Type = Event::MouseLeft;
SendEvent(event);
break;
}
}
@ -707,43 +707,43 @@ void WindowImplWin32::ProcessEvent(UINT Message, WPARAM WParam, LPARAM LParam)
/// Check the state of the shift keys on a key event,
/// and return the corresponding SF key code
////////////////////////////////////////////////////////////
Key::Code WindowImplWin32::GetShiftState(bool KeyDown)
Key::Code WindowImplWin32::GetShiftState(bool keyDown)
{
static bool LShiftPrevDown = false;
static bool RShiftPrevDown = false;
static bool lShiftPrevDown = false;
static bool rShiftPrevDown = false;
bool LShiftDown = (HIWORD(GetAsyncKeyState(VK_LSHIFT)) != 0);
bool RShiftDown = (HIWORD(GetAsyncKeyState(VK_RSHIFT)) != 0);
bool lShiftDown = (HIWORD(GetAsyncKeyState(VK_LSHIFT)) != 0);
bool rShiftDown = (HIWORD(GetAsyncKeyState(VK_RSHIFT)) != 0);
Key::Code Code = Key::Code(0);
if (KeyDown)
Key::Code code = Key::Code(0);
if (keyDown)
{
if (!LShiftPrevDown && LShiftDown) Code = Key::LShift;
else if (!RShiftPrevDown && RShiftDown) Code = Key::RShift;
if (!lShiftPrevDown && lShiftDown) code = Key::LShift;
else if (!rShiftPrevDown && rShiftDown) code = Key::RShift;
}
else
{
if (LShiftPrevDown && !LShiftDown) Code = Key::LShift;
else if (RShiftPrevDown && !RShiftDown) Code = Key::RShift;
if (lShiftPrevDown && !lShiftDown) code = Key::LShift;
else if (rShiftPrevDown && !rShiftDown) code = Key::RShift;
}
LShiftPrevDown = LShiftDown;
RShiftPrevDown = RShiftDown;
lShiftPrevDown = lShiftDown;
rShiftPrevDown = rShiftDown;
return Code;
return code;
}
////////////////////////////////////////////////////////////
/// Convert a Win32 virtual key code to a SFML key code
////////////////////////////////////////////////////////////
Key::Code WindowImplWin32::VirtualKeyCodeToSF(WPARAM VirtualKey, LPARAM Flags)
Key::Code WindowImplWin32::VirtualKeyCodeToSF(WPARAM key, LPARAM flags)
{
switch (VirtualKey)
switch (key)
{
// VK_SHIFT is handled by the GetShiftState function
case VK_MENU : return (Flags & (1 << 24)) ? Key::RAlt : Key::LAlt;
case VK_CONTROL : return (Flags & (1 << 24)) ? Key::RControl : Key::LControl;
case VK_MENU : return (flags & (1 << 24)) ? Key::RAlt : Key::LAlt;
case VK_CONTROL : return (flags & (1 << 24)) ? Key::RControl : Key::LControl;
case VK_LWIN : return Key::LSystem;
case VK_RWIN : return Key::RSystem;
case VK_APPS : return Key::Menu;
@ -852,13 +852,13 @@ Key::Code WindowImplWin32::VirtualKeyCodeToSF(WPARAM VirtualKey, LPARAM Flags)
////////////////////////////////////////////////////////////
bool WindowImplWin32::HasUnicodeSupport()
{
OSVERSIONINFO VersionInfo;
ZeroMemory(&VersionInfo, sizeof(VersionInfo));
VersionInfo.dwOSVersionInfoSize = sizeof(VersionInfo);
OSVERSIONINFO version;
ZeroMemory(&version, sizeof(version));
version.dwOSVersionInfoSize = sizeof(version);
if (GetVersionEx(&VersionInfo))
if (GetVersionEx(&version))
{
return VersionInfo.dwPlatformId == VER_PLATFORM_WIN32_NT;
return version.dwPlatformId == VER_PLATFORM_WIN32_NT;
}
else
{
@ -870,37 +870,37 @@ bool WindowImplWin32::HasUnicodeSupport()
////////////////////////////////////////////////////////////
/// Function called whenever one of our windows receives a message
////////////////////////////////////////////////////////////
LRESULT CALLBACK WindowImplWin32::GlobalOnEvent(HWND Handle, UINT Message, WPARAM WParam, LPARAM LParam)
LRESULT CALLBACK WindowImplWin32::GlobalOnEvent(HWND handle, UINT message, WPARAM wParam, LPARAM lParam)
{
// Associate handle and Window instance when the creation message is received
if (Message == WM_CREATE)
if (message == WM_CREATE)
{
// Get WindowImplWin32 instance (it was passed as the last argument of CreateWindow)
long This = reinterpret_cast<long>(reinterpret_cast<CREATESTRUCT*>(LParam)->lpCreateParams);
long window = reinterpret_cast<long>(reinterpret_cast<CREATESTRUCT*>(lParam)->lpCreateParams);
// Set as the "user data" parameter of the window
SetWindowLongPtr(Handle, GWLP_USERDATA, This);
SetWindowLongPtr(handle, GWLP_USERDATA, window);
}
// Get the WindowImpl instance corresponding to the window handle
WindowImplWin32* Window = reinterpret_cast<WindowImplWin32*>(GetWindowLongPtr(Handle, GWLP_USERDATA));
WindowImplWin32* window = reinterpret_cast<WindowImplWin32*>(GetWindowLongPtr(handle, GWLP_USERDATA));
// Forward the event to the appropriate function
if (Window)
if (window)
{
Window->ProcessEvent(Message, WParam, LParam);
window->ProcessEvent(message, wParam, lParam);
if (Window->myCallback)
return CallWindowProc(reinterpret_cast<WNDPROC>(Window->myCallback), Handle, Message, WParam, LParam);
if (window->myCallback)
return CallWindowProc(reinterpret_cast<WNDPROC>(window->myCallback), handle, message, wParam, lParam);
}
// We don't forward the WM_CLOSE message to prevent the OS from automatically destroying the window
if (Message == WM_CLOSE)
if (message == WM_CLOSE)
return 0;
static const bool HasUnicode = HasUnicodeSupport();
return HasUnicode ? DefWindowProcW(Handle, Message, WParam, LParam) :
DefWindowProcA(Handle, Message, WParam, LParam);
static const bool hasUnicode = HasUnicodeSupport();
return hasUnicode ? DefWindowProcW(handle, message, wParam, lParam) :
DefWindowProcA(handle, message, wParam, lParam);
}
} // namespace priv

View file

@ -48,20 +48,20 @@ public :
////////////////////////////////////////////////////////////
/// Construct the window implementation from an existing control
///
/// \param Handle : Platform-specific handle of the control
/// \param handle : Platform-specific handle of the control
///
////////////////////////////////////////////////////////////
WindowImplWin32(WindowHandle Handle);
WindowImplWin32(WindowHandle handle);
////////////////////////////////////////////////////////////
/// Create the window implementation
///
/// \param Mode : Video mode to use
/// \param Title : Title of the window
/// \param WindowStyle : Window style
/// \param mode : Video mode to use
/// \param title : Title of the window
/// \param style : Window style
///
////////////////////////////////////////////////////////////
WindowImplWin32(VideoMode Mode, const std::string& Title, unsigned long WindowStyle);
WindowImplWin32(VideoMode mode, const std::string& title, unsigned long style);
////////////////////////////////////////////////////////////
/// Destructor
@ -87,43 +87,43 @@ private :
/// /see WindowImpl::ShowMouseCursor
///
////////////////////////////////////////////////////////////
virtual void ShowMouseCursor(bool Show);
virtual void ShowMouseCursor(bool show);
////////////////////////////////////////////////////////////
/// /see WindowImpl::SetCursorPosition
///
////////////////////////////////////////////////////////////
virtual void SetCursorPosition(unsigned int Left, unsigned int Top);
virtual void SetCursorPosition(unsigned int left, unsigned int top);
////////////////////////////////////////////////////////////
/// /see WindowImpl::SetPosition
///
////////////////////////////////////////////////////////////
virtual void SetPosition(int Left, int Top);
virtual void SetPosition(int left, int top);
////////////////////////////////////////////////////////////
/// /see WindowImpl::SetSize
///
////////////////////////////////////////////////////////////
virtual void SetSize(unsigned int Width, unsigned int Height);
virtual void SetSize(unsigned int width, unsigned int height);
////////////////////////////////////////////////////////////
/// /see WindowImpl::Show
///
////////////////////////////////////////////////////////////
virtual void Show(bool State);
virtual void Show(bool show);
////////////////////////////////////////////////////////////
/// /see WindowImpl::EnableKeyRepeat
///
////////////////////////////////////////////////////////////
virtual void EnableKeyRepeat(bool Enabled);
virtual void EnableKeyRepeat(bool enabled);
////////////////////////////////////////////////////////////
/// /see WindowImpl::SetIcon
///
////////////////////////////////////////////////////////////
virtual void SetIcon(unsigned int Width, unsigned int Height, const Uint8* Pixels);
virtual void SetIcon(unsigned int width, unsigned int height, const Uint8* pixels);
////////////////////////////////////////////////////////////
/// Register the window class
@ -134,10 +134,10 @@ private :
////////////////////////////////////////////////////////////
/// Switch to fullscreen mode
///
/// \param Mode : video mode to switch to
/// \param mode : video mode to switch to
///
////////////////////////////////////////////////////////////
void SwitchToFullscreen(const VideoMode& Mode);
void SwitchToFullscreen(const VideoMode& mode);
////////////////////////////////////////////////////////////
/// Free all the graphical resources attached to the window
@ -148,34 +148,34 @@ private :
////////////////////////////////////////////////////////////
/// Process a Win32 event
///
/// \param Message : Message to process
/// \param WParam : First parameter of the event
/// \param LParam : Second parameter of the event
/// \param message : Message to process
/// \param wParam : First parameter of the event
/// \param lParam : Second parameter of the event
///
////////////////////////////////////////////////////////////
void ProcessEvent(UINT Message, WPARAM WParam, LPARAM LParam);
void ProcessEvent(UINT message, WPARAM wParam, LPARAM lParam);
////////////////////////////////////////////////////////////
/// Check the state of the shift keys on a key event,
/// and return the corresponding SF key code
///
/// \param KeyDown : True for a keydown event, false for a keyup event
/// \param keyDown : True for a keydown event, false for a keyup event
///
/// \return SFML key code corresponding to the shift key
///
////////////////////////////////////////////////////////////
static Key::Code GetShiftState(bool KeyDown);
static Key::Code GetShiftState(bool keyDown);
////////////////////////////////////////////////////////////
/// Convert a Win32 virtual key code to a SFML key code
///
/// \param VirtualKey : Virtual key code to convert
/// \param Flags : Additional flags
/// \param key : Virtual key code to convert
/// \param flags : Additional flags
///
/// \return SFML key code corresponding to VirtualKey
/// \return SFML key code corresponding to the key
///
////////////////////////////////////////////////////////////
static Key::Code VirtualKeyCodeToSF(WPARAM VirtualKey, LPARAM Flags);
static Key::Code VirtualKeyCodeToSF(WPARAM key, LPARAM flags);
////////////////////////////////////////////////////////////
/// Check if the current version of the OS supports unicode
@ -190,15 +190,15 @@ private :
////////////////////////////////////////////////////////////
/// Function called whenever one of our windows receives a message
///
/// \param Handle : Win32 handle of the window
/// \param Message : Message received
/// \param WParam : First parameter of the message
/// \param LParam : Second parameter of the message
/// \param handle : Win32 handle of the window
/// \param message : Message received
/// \param wParam : First parameter of the message
/// \param lParam : Second parameter of the message
///
/// \return Something...
///
////////////////////////////////////////////////////////////
static LRESULT CALLBACK GlobalOnEvent(HWND Handle, UINT Message, WPARAM WParam, LPARAM LParam);
static LRESULT CALLBACK GlobalOnEvent(HWND handle, UINT message, WPARAM wParam, LPARAM lParam);
////////////////////////////////////////////////////////////
// Static member data

View file

@ -38,7 +38,7 @@
////////////////////////////////////////////////////////////
namespace
{
const sf::Window* FullscreenWindow = NULL;
const sf::Window* fullscreenWindow = NULL;
}
@ -63,7 +63,7 @@ mySetCursorPosY (0xFFFF)
////////////////////////////////////////////////////////////
/// Construct a new window
////////////////////////////////////////////////////////////
Window::Window(VideoMode Mode, const std::string& Title, unsigned long WindowStyle, const ContextSettings& Settings) :
Window::Window(VideoMode mode, const std::string& title, unsigned long style, const ContextSettings& settings) :
myWindow (NULL),
myContext (NULL),
myLastFrameTime (0.f),
@ -72,14 +72,14 @@ myFramerateLimit(0),
mySetCursorPosX (0xFFFF),
mySetCursorPosY (0xFFFF)
{
Create(Mode, Title, WindowStyle, Settings);
Create(mode, title, style, settings);
}
////////////////////////////////////////////////////////////
/// Construct the window from an existing control
////////////////////////////////////////////////////////////
Window::Window(WindowHandle Handle, const ContextSettings& Settings) :
Window::Window(WindowHandle handle, const ContextSettings& settings) :
myWindow (NULL),
myContext (NULL),
myLastFrameTime (0.f),
@ -88,7 +88,7 @@ myFramerateLimit(0),
mySetCursorPosX (0xFFFF),
mySetCursorPosY (0xFFFF)
{
Create(Handle, Settings);
Create(handle, settings);
}
@ -104,51 +104,51 @@ Window::~Window()
////////////////////////////////////////////////////////////
/// Create the window
////////////////////////////////////////////////////////////
void Window::Create(VideoMode Mode, const std::string& Title, unsigned long WindowStyle, const ContextSettings& Settings)
void Window::Create(VideoMode mode, const std::string& title, unsigned long style, const ContextSettings& settings)
{
// Destroy the previous window implementation
Close();
// Fullscreen style requires some tests
if (WindowStyle & Style::Fullscreen)
if (style & Style::Fullscreen)
{
// Make sure there's not already a fullscreen window (only one is allowed)
if (FullscreenWindow)
if (fullscreenWindow)
{
std::cerr << "Creating two fullscreen windows is not allowed, switching to windowed mode" << std::endl;
WindowStyle &= ~Style::Fullscreen;
style &= ~Style::Fullscreen;
}
else
{
// Make sure the chosen video mode is compatible
if (!Mode.IsValid())
if (!mode.IsValid())
{
std::cerr << "The requested video mode is not available, switching to a valid mode" << std::endl;
Mode = VideoMode::GetMode(0);
mode = VideoMode::GetMode(0);
}
// Update the fullscreen window
FullscreenWindow = this;
fullscreenWindow = this;
}
}
// Check validity of style
if ((WindowStyle & Style::Close) || (WindowStyle & Style::Resize))
WindowStyle |= Style::Titlebar;
if ((style & Style::Close) || (style & Style::Resize))
style |= Style::Titlebar;
// Recreate the window implementation
delete myWindow;
myWindow = priv::WindowImpl::New(Mode, Title, WindowStyle);
myWindow = priv::WindowImpl::New(mode, title, style);
{
// Make sure another context is bound, so that:
// - the context creation can request OpenGL extensions if necessary
// - myContext can safely be destroyed (it's no longer bound)
Context Ctx;
Context context;
// Recreate the context
delete myContext;
myContext = priv::ContextGL::New(myWindow, Mode.BitsPerPixel, Settings);
myContext = priv::ContextGL::New(myWindow, mode.BitsPerPixel, settings);
Initialize();
}
@ -161,21 +161,21 @@ void Window::Create(VideoMode Mode, const std::string& Title, unsigned long Wind
////////////////////////////////////////////////////////////
/// Create the window from an existing control
////////////////////////////////////////////////////////////
void Window::Create(WindowHandle Handle, const ContextSettings& Settings)
void Window::Create(WindowHandle handle, const ContextSettings& settings)
{
// Recreate the window implementation
Close();
myWindow = priv::WindowImpl::New(Handle);
myWindow = priv::WindowImpl::New(handle);
{
// Make sure another context is bound, so that:
// - the context creation can request OpenGL extensions if necessary
// - myContext can safely be destroyed (it's no longer bound)
Context Ctx;
Context context;
// Recreate the context
delete myContext;
myContext = priv::ContextGL::New(myWindow, VideoMode::GetDesktopMode().BitsPerPixel, Settings);
myContext = priv::ContextGL::New(myWindow, VideoMode::GetDesktopMode().BitsPerPixel, settings);
Initialize();
}
@ -207,8 +207,8 @@ void Window::Close()
}
// Update the fullscreen window
if (this == FullscreenWindow)
FullscreenWindow = NULL;
if (this == fullscreenWindow)
fullscreenWindow = NULL;
}
@ -246,16 +246,16 @@ unsigned int Window::GetHeight() const
////////////////////////////////////////////////////////////
const ContextSettings& Window::GetSettings() const
{
static ContextSettings EmptySettings(0, 0, 0);
static const ContextSettings empty(0, 0, 0);
return myContext ? myContext->GetSettings() : EmptySettings;
return myContext ? myContext->GetSettings() : empty;
}
////////////////////////////////////////////////////////////
/// Get the event on top of events stack, if any
////////////////////////////////////////////////////////////
bool Window::GetEvent(Event& EventReceived)
bool Window::GetEvent(Event& event)
{
// Let the window implementation process incoming events if the events queue is empty
if (myWindow && myEvents.empty())
@ -264,7 +264,7 @@ bool Window::GetEvent(Event& EventReceived)
// Pop first event of queue, if not empty
if (!myEvents.empty())
{
EventReceived = myEvents.front();
event = myEvents.front();
myEvents.pop();
return true;
@ -277,35 +277,35 @@ bool Window::GetEvent(Event& EventReceived)
////////////////////////////////////////////////////////////
/// Enable / disable vertical synchronization
////////////////////////////////////////////////////////////
void Window::UseVerticalSync(bool Enabled)
void Window::UseVerticalSync(bool enabled)
{
if (SetActive())
myContext->UseVerticalSync(Enabled);
myContext->UseVerticalSync(enabled);
}
////////////////////////////////////////////////////////////
/// Show or hide the mouse cursor
////////////////////////////////////////////////////////////
void Window::ShowMouseCursor(bool Show)
void Window::ShowMouseCursor(bool show)
{
if (myWindow)
myWindow->ShowMouseCursor(Show);
myWindow->ShowMouseCursor(show);
}
////////////////////////////////////////////////////////////
/// Change the position of the mouse cursor
////////////////////////////////////////////////////////////
void Window::SetCursorPosition(unsigned int Left, unsigned int Top)
void Window::SetCursorPosition(unsigned int left, unsigned int top)
{
if (myWindow)
{
// Keep coordinates for later checking (to reject the generated MouseMoved event)
mySetCursorPosX = Left;
mySetCursorPosY = Top;
mySetCursorPosX = left;
mySetCursorPosY = top;
myWindow->SetCursorPosition(Left, Top);
myWindow->SetCursorPosition(left, top);
}
}
@ -313,30 +313,30 @@ void Window::SetCursorPosition(unsigned int Left, unsigned int Top)
////////////////////////////////////////////////////////////
/// Change the position of the window on screen
////////////////////////////////////////////////////////////
void Window::SetPosition(int Left, int Top)
void Window::SetPosition(int left, int top)
{
if (myWindow)
myWindow->SetPosition(Left, Top);
myWindow->SetPosition(left, top);
}
////////////////////////////////////////////////////////////
/// Change the size of the rendering region of the window
////////////////////////////////////////////////////////////
void Window::SetSize(unsigned int Width, unsigned int Height)
void Window::SetSize(unsigned int width, unsigned int height)
{
if (myWindow)
myWindow->SetSize(Width, Height);
myWindow->SetSize(width, height);
}
////////////////////////////////////////////////////////////
/// Show or hide the window
////////////////////////////////////////////////////////////
void Window::Show(bool State)
void Window::Show(bool show)
{
if (myWindow)
myWindow->Show(State);
myWindow->Show(show);
}
@ -344,20 +344,20 @@ void Window::Show(bool State)
/// Enable or disable automatic key-repeat.
/// Automatic key-repeat is enabled by default
////////////////////////////////////////////////////////////
void Window::EnableKeyRepeat(bool Enabled)
void Window::EnableKeyRepeat(bool enabled)
{
if (myWindow)
myWindow->EnableKeyRepeat(Enabled);
myWindow->EnableKeyRepeat(enabled);
}
////////////////////////////////////////////////////////////
/// Change the window's icon
////////////////////////////////////////////////////////////
void Window::SetIcon(unsigned int Width, unsigned int Height, const Uint8* Pixels)
void Window::SetIcon(unsigned int width, unsigned int height, const Uint8* pixels)
{
if (myWindow)
myWindow->SetIcon(Width, Height, Pixels);
myWindow->SetIcon(width, height, pixels);
}
@ -365,11 +365,11 @@ void Window::SetIcon(unsigned int Width, unsigned int Height, const Uint8* Pixel
/// Activate or deactivate the window as the current target
/// for rendering
////////////////////////////////////////////////////////////
bool Window::SetActive(bool Active) const
bool Window::SetActive(bool active) const
{
if (myContext)
{
if (myContext->SetActive(Active))
if (myContext->SetActive(active))
{
return true;
}
@ -394,9 +394,9 @@ void Window::Display()
// Limit the framerate if needed
if (myFramerateLimit > 0)
{
float RemainingTime = 1.f / myFramerateLimit - myClock.GetElapsedTime();
if (RemainingTime > 0)
Sleep(RemainingTime);
float remainingTime = 1.f / myFramerateLimit - myClock.GetElapsedTime();
if (remainingTime > 0)
Sleep(remainingTime);
}
// Measure the time elapsed since last frame
@ -421,9 +421,9 @@ const Input& Window::GetInput() const
////////////////////////////////////////////////////////////
/// Set the framerate at a fixed frequency
////////////////////////////////////////////////////////////
void Window::SetFramerateLimit(unsigned int Limit)
void Window::SetFramerateLimit(unsigned int limit)
{
myFramerateLimit = Limit;
myFramerateLimit = limit;
}
@ -440,10 +440,10 @@ float Window::GetFrameTime() const
/// Change the joystick threshold, ie. the value below which
/// no move event will be generated
////////////////////////////////////////////////////////////
void Window::SetJoystickThreshold(float Threshold)
void Window::SetJoystickThreshold(float threshold)
{
if (myWindow)
myWindow->SetJoystickThreshold(Threshold);
myWindow->SetJoystickThreshold(threshold);
}
@ -459,19 +459,19 @@ void Window::OnCreate()
////////////////////////////////////////////////////////////
/// Receive an event from window
////////////////////////////////////////////////////////////
void Window::OnEvent(const Event& EventReceived)
void Window::OnEvent(const Event& event)
{
// Discard MouseMove events generated by SetCursorPosition
if ((EventReceived.Type == Event::MouseMoved) &&
(EventReceived.MouseMove.X == mySetCursorPosX) &&
(EventReceived.MouseMove.Y == mySetCursorPosY))
if ((event.Type == Event::MouseMoved) &&
(event.MouseMove.X == mySetCursorPosX) &&
(event.MouseMove.Y == mySetCursorPosY))
{
mySetCursorPosX = 0xFFFF;
mySetCursorPosY = 0xFFFF;
return;
}
myEvents.push(EventReceived);
myEvents.push(event);
}

View file

@ -56,18 +56,18 @@ namespace priv
////////////////////////////////////////////////////////////
/// Create a new window depending on the current OS
////////////////////////////////////////////////////////////
WindowImpl* WindowImpl::New(VideoMode Mode, const std::string& Title, unsigned long WindowStyle)
WindowImpl* WindowImpl::New(VideoMode mode, const std::string& title, unsigned long style)
{
return new WindowImplType(Mode, Title, WindowStyle);
return new WindowImplType(mode, title, style);
}
////////////////////////////////////////////////////////////
/// Create a new window depending on the current OS
////////////////////////////////////////////////////////////
WindowImpl* WindowImpl::New(WindowHandle Handle)
WindowImpl* WindowImpl::New(WindowHandle handle)
{
return new WindowImplType(Handle);
return new WindowImplType(handle);
}
@ -100,19 +100,19 @@ WindowImpl::~WindowImpl()
////////////////////////////////////////////////////////////
/// Add a listener to the window
////////////////////////////////////////////////////////////
void WindowImpl::AddListener(WindowListener* Listener)
void WindowImpl::AddListener(WindowListener* listener)
{
if (Listener)
myListeners.insert(Listener);
if (listener)
myListeners.insert(listener);
}
////////////////////////////////////////////////////////////
/// Remove a listener from the window
////////////////////////////////////////////////////////////
void WindowImpl::RemoveListener(WindowListener* Listener)
void WindowImpl::RemoveListener(WindowListener* listener)
{
myListeners.erase(Listener);
myListeners.erase(listener);
}
@ -138,9 +138,9 @@ unsigned int WindowImpl::GetHeight() const
/// Change the joystick threshold, ie. the value below which
/// no move event will be generated
////////////////////////////////////////////////////////////
void WindowImpl::SetJoystickThreshold(float Threshold)
void WindowImpl::SetJoystickThreshold(float threshold)
{
myJoyThreshold = Threshold;
myJoyThreshold = threshold;
}
@ -160,11 +160,11 @@ void WindowImpl::DoEvents()
////////////////////////////////////////////////////////////
/// Send an event to listeners
////////////////////////////////////////////////////////////
void WindowImpl::SendEvent(const Event& EventToSend)
void WindowImpl::SendEvent(const Event& event)
{
for (std::set<WindowListener*>::iterator i = myListeners.begin(); i != myListeners.end(); ++i)
{
(*i)->OnEvent(EventToSend);
(*i)->OnEvent(event);
}
}
@ -177,38 +177,38 @@ void WindowImpl::ProcessJoystickEvents()
for (unsigned int i = 0; i < JoysticksCount; ++i)
{
// Copy the previous state of the joystick and get the new one
JoystickState PreviousState = myJoyStates[i];
JoystickState previousState = myJoyStates[i];
myJoyStates[i] = myJoysticks[i].UpdateState();
// Axis
for (unsigned int j = 0; j < myJoysticks[i].GetAxesCount(); ++j)
{
float PrevPos = PreviousState.Axis[j];
float CurrPos = myJoyStates[i].Axis[j];
if (fabs(CurrPos - PrevPos) >= myJoyThreshold)
float prevPos = previousState.Axis[j];
float currPos = myJoyStates[i].Axis[j];
if (fabs(currPos - prevPos) >= myJoyThreshold)
{
Event Event;
Event.Type = Event::JoyMoved;
Event.JoyMove.JoystickId = i;
Event.JoyMove.Axis = static_cast<Joy::Axis>(j);
Event.JoyMove.Position = CurrPos;
SendEvent(Event);
Event event;
event.Type = Event::JoyMoved;
event.JoyMove.JoystickId = i;
event.JoyMove.Axis = static_cast<Joy::Axis>(j);
event.JoyMove.Position = currPos;
SendEvent(event);
}
}
// Buttons
for (unsigned int j = 0; j < myJoysticks[i].GetButtonsCount(); ++j)
{
bool PrevPressed = PreviousState.Buttons[j];
bool CurrPressed = myJoyStates[i].Buttons[j];
bool prevPressed = previousState.Buttons[j];
bool currPressed = myJoyStates[i].Buttons[j];
if ((!PrevPressed && CurrPressed) || (PrevPressed && !CurrPressed))
if ((!prevPressed && currPressed) || (prevPressed && !currPressed))
{
Event Event;
Event.Type = CurrPressed ? Event::JoyButtonPressed : Event::JoyButtonReleased;
Event.JoyButton.JoystickId = i;
Event.JoyButton.Button = j;
SendEvent(Event);
Event event;
event.Type = currPressed ? Event::JoyButtonPressed : Event::JoyButtonReleased;
event.JoyButton.JoystickId = i;
event.JoyButton.Button = j;
SendEvent(event);
}
}
}

View file

@ -54,24 +54,24 @@ public :
////////////////////////////////////////////////////////////
/// Create a new window depending on the current OS
///
/// \param Mode : Video mode to use
/// \param Title : Title of the window
/// \param WindowStyle : Window style
/// \param mode : Video mode to use
/// \param title : Title of the window
/// \param style : Window style
///
/// \return Pointer to the created window
///
////////////////////////////////////////////////////////////
static WindowImpl* New(VideoMode Mode, const std::string& Title, unsigned long WindowStyle);
static WindowImpl* New(VideoMode mode, const std::string& title, unsigned long style);
////////////////////////////////////////////////////////////
/// Create a new window depending on to the current OS
///
/// \param Handle : Platform-specific handle of the control
/// \param handle : Platform-specific handle of the control
///
/// \return Pointer to the created window
///
////////////////////////////////////////////////////////////
static WindowImpl* New(WindowHandle Handle);
static WindowImpl* New(WindowHandle handle);
public :
@ -84,18 +84,18 @@ public :
////////////////////////////////////////////////////////////
/// Add a listener to the window
///
/// \param Listener : Listener to add
/// \param listener : Listener to add
///
////////////////////////////////////////////////////////////
void AddListener(WindowListener* Listener);
void AddListener(WindowListener* listener);
////////////////////////////////////////////////////////////
/// Remove a listener from the window
///
/// \param Listener : Listener to remove
/// \param listener : Listener to remove
///
////////////////////////////////////////////////////////////
void RemoveListener(WindowListener* Listener);
void RemoveListener(WindowListener* listener);
////////////////////////////////////////////////////////////
/// Get the client width of the window
@ -117,10 +117,10 @@ public :
/// Change the joystick threshold, ie. the value below which
/// no move event will be generated
///
/// \param Threshold : New threshold, in range [0, 100]
/// \param threshold : New threshold, in range [0, 100]
///
////////////////////////////////////////////////////////////
void SetJoystickThreshold(float Threshold);
void SetJoystickThreshold(float threshold);
////////////////////////////////////////////////////////////
/// Process incoming events from operating system
@ -139,63 +139,63 @@ public :
////////////////////////////////////////////////////////////
/// Show or hide the mouse cursor
///
/// \param Show : True to show, false to hide
/// \param show : True to show, false to hide
///
////////////////////////////////////////////////////////////
virtual void ShowMouseCursor(bool Show) = 0;
virtual void ShowMouseCursor(bool show) = 0;
////////////////////////////////////////////////////////////
/// Change the position of the mouse cursor
///
/// \param Left : Left coordinate of the cursor, relative to the window
/// \param Top : Top coordinate of the cursor, relative to the window
/// \param left : Left coordinate of the cursor, relative to the window
/// \param top : Top coordinate of the cursor, relative to the window
///
////////////////////////////////////////////////////////////
virtual void SetCursorPosition(unsigned int Left, unsigned int Top) = 0;
virtual void SetCursorPosition(unsigned int left, unsigned int top) = 0;
////////////////////////////////////////////////////////////
/// Change the position of the window on screen
///
/// \param Left : Left position
/// \param Top : Top position
/// \param left : Left position
/// \param top : Top position
///
////////////////////////////////////////////////////////////
virtual void SetPosition(int Left, int Top) = 0;
virtual void SetPosition(int left, int top) = 0;
////////////////////////////////////////////////////////////
/// Change the size of the rendering region of the window
///
/// \param Width : New width
/// \param Height : New height
/// \param width : New width
/// \param height : New height
///
////////////////////////////////////////////////////////////
virtual void SetSize(unsigned int Width, unsigned int Height) = 0;
virtual void SetSize(unsigned int width, unsigned int height) = 0;
////////////////////////////////////////////////////////////
/// Show or hide the window
///
/// \param State : True to show, false to hide
/// \param show : True to show, false to hide
///
////////////////////////////////////////////////////////////
virtual void Show(bool State) = 0;
virtual void Show(bool show) = 0;
////////////////////////////////////////////////////////////
/// Enable or disable automatic key-repeat
///
/// \param Enabled : True to enable, false to disable
/// \param enabled : True to enable, false to disable
///
////////////////////////////////////////////////////////////
virtual void EnableKeyRepeat(bool Enabled) = 0;
virtual void EnableKeyRepeat(bool enabled) = 0;
////////////////////////////////////////////////////////////
/// Change the window's icon
///
/// \param Width : Icon's width, in pixels
/// \param Height : Icon's height, in pixels
/// \param Pixels : Pointer to the pixels in memory, format must be RGBA 32 bits
/// \param width : Icon's width, in pixels
/// \param height : Icon's height, in pixels
/// \param pixels : Pointer to the pixels in memory, format must be RGBA 32 bits
///
////////////////////////////////////////////////////////////
virtual void SetIcon(unsigned int Width, unsigned int Height, const Uint8* Pixels) = 0;
virtual void SetIcon(unsigned int width, unsigned int height, const Uint8* pixels) = 0;
protected :
@ -208,10 +208,10 @@ protected :
////////////////////////////////////////////////////////////
/// Send an event to listeners (for derived classes only)
///
/// \param EventToSend : Event to send
/// \param event : Event to send
///
////////////////////////////////////////////////////////////
void SendEvent(const Event& EventToSend);
void SendEvent(const Event& event);
////////////////////////////////////////////////////////////
// Member data