Added the trunk/branches/tags directories at repository root, and moved previous root into trunk/

git-svn-id: https://sfml.svn.sourceforge.net/svnroot/sfml/trunk@1002 4e206d99-4929-0410-ac5d-dfc041789085
This commit is contained in:
laurentgom 2009-01-28 16:18:34 +00:00
commit 2f524481c1
974 changed files with 295448 additions and 0 deletions

2
DSFML/AUTHORS Normal file
View file

@ -0,0 +1,2 @@
SirJulio (Dagorn Julien) => sirjulio13@gmail.com
Insomniak => insomniak.fr@gmail.com

18
DSFML/LICENCE Normal file
View file

@ -0,0 +1,18 @@
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.

View file

@ -0,0 +1,36 @@
/*
* DSFML - SFML Library binding in D language.
* Copyright (C) 2008 Julien Dagorn (sirjulio13@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.
*/
module dsfml.audio.all;
public import
dsfml.audio.listener,
dsfml.audio.music,
dsfml.audio.sound,
dsfml.audio.soundbuffer,
dsfml.audio.soundbufferrecorder,
dsfml.audio.soundrecorder,
dsfml.audio.soundstatus,
dsfml.audio.soundstream;

View file

@ -0,0 +1,184 @@
/*
* DSFML - SFML Library binding in D language.
* Copyright (C) 2008 Julien Dagorn (sirjulio13@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.
*/
module dsfml.audio.listener;
import dsfml.system.common;
import dsfml.system.vector3;
/**
* Listener is a global interface for defining the audio
* listener properties ; the audio listener is the point in
* the scene from where all the sounds are heard.
*
* See_Also:
* SFML Tutorial for sound spatialization example.
*/
class Listener
{
/**
* Change the global volume of all the sounds.
* The default volume is 100
*
* Params:
* volume = New global volume, in the range [0, 100]
*/
static void setGlobalVolume(float volume)
in
{
assert (volume >= 0.f && volume <= 100.f);
}
body
{
sfListener_SetGlobalVolume(volume);
}
/**
* Get the current value of the global volume of all the sounds
*
* Returns:
* Current global volume, in the range [0, 100]
*/
static float getGlobalVolume()
{
return sfListener_GetGlobalVolume();
}
/**
* Change the position of the listener.
* The default position is (0, 0, 0)
*
* Params:
* posX = X position of the listener in the world
* posY = Y position of the listener in the world
* posZ = Z position of the listener in the world
*/
static void setPosition(float posX, float posY, float posZ)
{
sfListener_SetPosition(posX, posY, posZ);
}
/**
* Change the position of the listener.
* The default position is (0, 0, 0)
*
* Params:
* position = new position
*/
static void setPosition(Vector3f position)
{
sfListener_SetPosition(position.x, position.y, position.z);
}
/**
* Get the current position of the listener
*
* Returns:
* Current position
*/
static Vector3f getPosition()
{
Vector3f ret;
sfListener_GetPosition(&ret.x, &ret.y, &ret.z);
return ret;
}
/**
* Change the orientation of the listener (the point
* he must look at).
* The default target is (0, 0, -1)
*
* Params:
* targetX = X position of the point the listener must look at
* targetY = X position of the point the listener must look at
* targetZ = X position of the point the listener must look at
*/
static void setTarget(float targetX, float targetY, float targetZ)
{
sfListener_SetTarget(targetX, targetY, targetZ);
}
/**
* Change the orientation of the listener (the point
* he must look at).
* The default target is (0, 0, -1)
*
* Params:
* target = Position of the point the listener must look at
*/
static void setTarget(Vector3f position)
{
sfListener_SetTarget(position.x, position.y, position.z);
}
/**
* Get the current orientation of the listener (the point
* he's looking at)
*
* Returns:
* Position of the point the listener is looking at
*/
static Vector3f getTarget()
{
Vector3f ret;
sfListener_GetTarget(&ret.x, &ret.y, &ret.z);
return ret;
}
private:
// External ====================================================================
extern (C)
{
typedef void function(float) pf_sfListener_SetGlobalVolume;
typedef float function() pf_sfListener_GetGlobalVolume;
typedef void function(float, float, float) pf_sfListener_SetPosition;
typedef void function(float*, float*, float*) pf_sfListener_GetPosition;
typedef void function(float, float, float) pf_sfListener_SetTarget;
typedef void function(float*, float*, float*) pf_sfListener_GetTarget;
static pf_sfListener_SetGlobalVolume sfListener_SetGlobalVolume;
static pf_sfListener_GetGlobalVolume sfListener_GetGlobalVolume;
static pf_sfListener_SetPosition sfListener_SetPosition;
static pf_sfListener_GetPosition sfListener_GetPosition;
static pf_sfListener_SetTarget sfListener_SetTarget;
static pf_sfListener_GetTarget sfListener_GetTarget;
}
static this()
{
DllLoader dll = DllLoader.load("csfml-audio");
sfListener_SetGlobalVolume = cast(pf_sfListener_SetGlobalVolume)dll.getSymbol("sfListener_SetGlobalVolume");
sfListener_GetGlobalVolume = cast(pf_sfListener_GetGlobalVolume)dll.getSymbol("sfListener_GetGlobalVolume");
sfListener_SetPosition = cast(pf_sfListener_SetPosition)dll.getSymbol("sfListener_SetPosition");
sfListener_GetPosition = cast(pf_sfListener_GetPosition)dll.getSymbol("sfListener_GetPosition");
sfListener_SetTarget = cast(pf_sfListener_SetTarget)dll.getSymbol("sfListener_SetTarget");
sfListener_GetTarget = cast(pf_sfListener_GetTarget)dll.getSymbol("sfListener_GetTarget");
}
}

View file

@ -0,0 +1,396 @@
/*
* DSFML - SFML Library binding in D language.
* Copyright (C) 2008 Julien Dagorn (sirjulio13@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.
*/
module dsfml.audio.music;
import dsfml.audio.soundstatus;
import dsfml.system.common;
import dsfml.system.exception;
import dsfml.system.stringutil;
import dsfml.system.vector3;
/**
* Music defines a big sound played using streaming,
* so usually what we call a music :)
*/
class Music : DSFMLObject
{
/**
* Open a music file (doesn't play it -- call Play for that)
*
* Params:
* filename = Path of the file to open
*
*/
this(char[] filename)
{
if (filename is null || filename.length == 0)
throw new LoadingException("LoadingException : Filename is invalid.");
super(sfMusic_CreateFromFile(toStringz(filename)));
}
/**
* Open a music file from memory (doesn't play it -- call Play() for that)
*
* Params:
* data = file data in memory
*
*/
this(byte[] data)
{
if (data is null || data.length == 0)
throw new Exception("LoadingException : Memory stream is invalid.");
super(m_ptr = sfMusic_CreateFromMemory(data.ptr, data.length));
}
override void dispose()
{
sfMusic_Destroy(m_ptr);
}
/**
* Start playing the audio stream
*/
void play()
{
sfMusic_Play(m_ptr);
}
/**
* Stop playing the audio stream
*/
void stop()
{
sfMusic_Stop(m_ptr);
}
/**
* Pause the audio stream
*/
void pause()
{
sfMusic_Pause(m_ptr);
}
/**
* Return the number of channels (1 = mono, 2 = stereo)
*
* Returns:
* Number of channels
*/
uint getChannelsCount()
{
return sfMusic_GetChannelsCount(m_ptr);
}
/**
* Get the stream sample rate
*
* Returns:
* Stream frequency (number of samples per second)
*/
uint getSampleRate()
{
return sfMusic_GetSampleRate(m_ptr);
}
/**
* Get the music duration
*
* Returns:
* Music duration, in seconds
*/
float getDuration()
{
return sfMusic_GetDuration(m_ptr);
}
/**
* Get the status of the stream (stopped, paused, playing)
*
* Returns:
* Current status of the sound
*/
SoundStatus getStatus()
{
return sfMusic_GetStatus(m_ptr);
}
/**
* Tell whether or not the music is looping
*
* Returns:
* True if the music is looping, false otherwise
*/
bool getLoop()
{
return cast(bool)sfMusic_GetLoop(m_ptr);
}
/**
* Get the pitch
*
* Returns:
* Pitch value
*/
float getPitch()
{
return sfMusic_GetPitch(m_ptr);
}
/**
* Get the volume
*
* Returns:
* Volume value (in range [1, 100])
*/
float getVolume()
{
return sfMusic_GetVolume(m_ptr);
}
/**
* Get the sound position
*
* Returns:
* Current position of the music.
*/
Vector3f getPosition()
{
Vector3f ret;
sfMusic_GetPosition(m_ptr, &ret.x, &ret.y, &ret.z);
return ret;
}
/**
* Get the minimum distance
*
* Returns:
* Minimum distance for the sound
*/
float getMinDistance()
{
return sfMusic_GetMinDistance(m_ptr);
}
/**
* Get the attenuation factor
*
* Returns:
* Attenuation factor of the sound
*
*/
float getAttenuation()
{
return sfMusic_GetAttenuation(m_ptr);
}
/**
* Set the music loop state.
* This parameter is disabled by default
*
* Params:
* loop = True to play in loop, false to play once
*/
void setLoop(bool loop)
{
sfMusic_SetLoop(m_ptr, loop);
}
/**
* Set the sound pitch.
* The default pitch is 1
*
* Params:
* pitch = New pitch
*
*/
void setPitch(float pitch)
{
sfMusic_SetPitch(m_ptr, pitch);
}
/**
* Set the sound volume.
* The default volume is 100
*
* Params:
* volume = Volume (in range [0, 100])
*
*/
void setVolume(float volume)
in
{
assert (volume >= 0.f && volume <= 100.f);
}
body
{
sfMusic_SetVolume(m_ptr, volume);
}
/**
* Set the sound position.
* The default position is (0, 0, 0)
*
* Params:
* x = X position of the sound in the world
* y = Y position of the sound in the world
* z = Z position of the sound in the world
*
*/
void setPosition(float x, float y, float z)
{
sfMusic_SetPosition(m_ptr, x, y, z);
}
/**
* Set the sound position.
* The default position is (0, 0, 0)
*
* Params:
* position = new position
*
*/
void setPosition(Vector3f position)
{
sfMusic_SetPosition(m_ptr, position.x, position.y, position.z);
}
/**
* Set the minimum distance - closer than thsi distance
* the listener will hear the sound at its maximum volume.
* The default distance is 1.0
*
* Params:
* minDistance = new minimum distance for the sound
*/
void setMinDistance(float minDistance)
{
sfMusic_SetMinDistance(m_ptr, minDistance);
}
/**
* Set the attenuation factor - the higher the attenuation, the
* more the sound will be attenuated with distance from listener.
* The default attenuation factor 1.0
*
* Params:
* attenuation = new attenuation factor for the sound
*/
void setAttenuation(float attenuation)
{
sfMusic_SetAttenuation(m_ptr, attenuation);
}
private:
// External ====================================================================
extern (C)
{
typedef void* function(char*) pf_sfMusic_CreateFromFile;
typedef void* function(byte*, size_t) pf_sfMusic_CreateFromMemory;
typedef void function(void*) pf_sfMusic_Destroy;
typedef void function(void*, int) pf_sfMusic_SetLoop;
typedef bool function(void*) pf_sfMusic_GetLoop;
typedef float function(void*) pf_sfMusic_GetDuration;
typedef void function(void*) pf_sfMusic_Play;
typedef void function(void*) pf_sfMusic_Pause;
typedef void function(void*) pf_sfMusic_Stop;
typedef uint function(void*) pf_sfMusic_GetChannelsCount;
typedef uint function(void*) pf_sfMusic_GetSampleRate;
typedef SoundStatus function(void*) pf_sfMusic_GetStatus;
typedef void function(void*, float) pf_sfMusic_SetPitch;
typedef void function(void*, float) pf_sfMusic_SetVolume;
typedef void function(void*, float, float, float) pf_sfMusic_SetPosition;
typedef float function(void*) pf_sfMusic_GetPitch;
typedef float function(void*) pf_sfMusic_GetVolume;
typedef void function(void*, float*, float*, float*) pf_sfMusic_GetPosition;
typedef float function(void*) pf_sfMusic_GetMinDistance;
typedef float function(void*) pf_sfMusic_GetAttenuation;
typedef void function(void*, float) pf_sfMusic_SetMinDistance;
typedef void function(void*, float) pf_sfMusic_SetAttenuation;
static pf_sfMusic_CreateFromFile sfMusic_CreateFromFile;
static pf_sfMusic_CreateFromMemory sfMusic_CreateFromMemory;
static pf_sfMusic_Destroy sfMusic_Destroy;
static pf_sfMusic_SetLoop sfMusic_SetLoop;
static pf_sfMusic_GetLoop sfMusic_GetLoop;
static pf_sfMusic_GetDuration sfMusic_GetDuration;
static pf_sfMusic_Play sfMusic_Play;
static pf_sfMusic_Pause sfMusic_Pause;
static pf_sfMusic_Stop sfMusic_Stop;
static pf_sfMusic_GetChannelsCount sfMusic_GetChannelsCount;
static pf_sfMusic_GetSampleRate sfMusic_GetSampleRate;
static pf_sfMusic_GetStatus sfMusic_GetStatus;
static pf_sfMusic_SetPitch sfMusic_SetPitch;
static pf_sfMusic_SetVolume sfMusic_SetVolume;
static pf_sfMusic_SetPosition sfMusic_SetPosition;
static pf_sfMusic_GetPitch sfMusic_GetPitch;
static pf_sfMusic_GetVolume sfMusic_GetVolume;
static pf_sfMusic_GetPosition sfMusic_GetPosition;
static pf_sfMusic_GetMinDistance sfMusic_GetMinDistance;
static pf_sfMusic_GetAttenuation sfMusic_GetAttenuation;
static pf_sfMusic_SetMinDistance sfMusic_SetMinDistance;
static pf_sfMusic_SetAttenuation sfMusic_SetAttenuation;
}
static this()
{
DllLoader dll = DllLoader.load("csfml-audio");
sfMusic_CreateFromFile = cast(pf_sfMusic_CreateFromFile)dll.getSymbol("sfMusic_CreateFromFile");
sfMusic_CreateFromMemory = cast(pf_sfMusic_CreateFromMemory)dll.getSymbol("sfMusic_CreateFromMemory");
sfMusic_Destroy = cast(pf_sfMusic_Destroy)dll.getSymbol("sfMusic_Destroy");
sfMusic_SetLoop = cast(pf_sfMusic_SetLoop)dll.getSymbol("sfMusic_SetLoop");
sfMusic_GetLoop = cast(pf_sfMusic_GetLoop)dll.getSymbol("sfMusic_GetLoop");
sfMusic_GetDuration = cast(pf_sfMusic_GetDuration)dll.getSymbol("sfMusic_GetDuration");
sfMusic_Play = cast(pf_sfMusic_Play)dll.getSymbol("sfMusic_Play");
sfMusic_Pause = cast(pf_sfMusic_Pause)dll.getSymbol("sfMusic_Pause");
sfMusic_Stop = cast(pf_sfMusic_Stop)dll.getSymbol("sfMusic_Stop");
sfMusic_GetChannelsCount = cast(pf_sfMusic_GetChannelsCount)dll.getSymbol("sfMusic_GetChannelsCount");
sfMusic_GetSampleRate = cast(pf_sfMusic_GetSampleRate)dll.getSymbol("sfMusic_GetSampleRate");
sfMusic_GetStatus = cast(pf_sfMusic_GetStatus)dll.getSymbol("sfMusic_GetStatus");
sfMusic_SetPitch = cast(pf_sfMusic_SetPitch)dll.getSymbol("sfMusic_SetPitch");
sfMusic_SetVolume = cast(pf_sfMusic_SetVolume)dll.getSymbol("sfMusic_SetVolume");
sfMusic_SetPosition = cast(pf_sfMusic_SetPosition)dll.getSymbol("sfMusic_SetPosition");
sfMusic_GetPitch = cast(pf_sfMusic_GetPitch)dll.getSymbol("sfMusic_GetPitch");
sfMusic_GetVolume = cast(pf_sfMusic_GetVolume)dll.getSymbol("sfMusic_GetVolume");
sfMusic_GetPosition = cast(pf_sfMusic_GetPosition)dll.getSymbol("sfMusic_GetPosition");
sfMusic_GetMinDistance = cast(pf_sfMusic_GetMinDistance)dll.getSymbol("sfMusic_GetMinDistance");
sfMusic_GetAttenuation = cast(pf_sfMusic_GetAttenuation)dll.getSymbol("sfMusic_GetAttenuation");
sfMusic_SetMinDistance = cast(pf_sfMusic_SetMinDistance)dll.getSymbol("sfMusic_SetMinDistance");
sfMusic_SetAttenuation = cast(pf_sfMusic_SetAttenuation)dll.getSymbol("sfMusic_SetAttenuation");
}
}

View file

@ -0,0 +1,415 @@
/*
* DSFML - SFML Library binding in D language.
* Copyright (C) 2008 Julien Dagorn (sirjulio13@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.
*/
module dsfml.audio.sound;
import dsfml.audio.soundbuffer;
import dsfml.audio.soundstatus;
import dsfml.system.common;
import dsfml.system.exception;
import dsfml.system.vector3;
/**
* Sound defines the properties of the sound such as position,
* volume, pitch, etc.
*/
class Sound : DSFMLObject
{
/**
* Default constructor
*/
this()
{
super(sfSound_Create());
}
/**
* Construct the sound from its parameters
*
* Params:
* buffer = Sound buffer to play
* loop = Loop flag (false by default)
* pitch = Value of the pitch (1 by default)
* volume = Volume (100 by default)
* x = X position (0 by default)
* y = Y position (0 by default)
* z = Z position (0 by default)
*
* Throws:
* NullParameterException if buffer is null
*/
this(SoundBuffer buffer, bool loop = false, float pitch = 1.f, float volume = 100.f, float x = 0.f, float y = 0.f, float z = 0.f)
{
if (buffer is null)
throw new NullParameterException("NullParameterException : SoundBuffer is null.");
super(sfSound_Create());
sfSound_SetBuffer(m_ptr, buffer.getNativePointer());
sfSound_SetLoop(m_ptr, loop);
sfSound_SetPitch(m_ptr, pitch);
sfSound_SetVolume(m_ptr, volume);
sfSound_SetPosition(m_ptr, x, y, z);
}
override void dispose()
{
sfSound_Destroy(m_ptr);
}
/**
* Play the sound
*/
void play()
{
sfSound_Play(m_ptr);
}
/**
* Pause the sound
*/
void pause()
{
sfSound_Pause(m_ptr);
}
/**
* Stop the sound
*/
void stop()
{
sfSound_Stop(m_ptr);
}
/**
* Set the source buffer
*
* Params:
* buffer = New sound buffer to bind to the sound
*/
void setBuffer(SoundBuffer buffer)
{
if (buffer is null)
throw new NullParameterException("NullParameterException : SoundBuffer is null.");
m_buffer = buffer;
sfSound_SetBuffer(m_ptr, buffer.getNativePointer);
}
/**
* Set the sound loop state.
* This parameter is disabled by default
*
* Params:
* loop = True to play in loop, false to play once
*/
void setLoop(bool loop)
{
sfSound_SetLoop(m_ptr, loop);
}
/**
* Set the sound pitch.
* The default pitch is 1
*
* Params:
* pitch = New pitch
*/
void setPitch(float pitch)
{
sfSound_SetPitch(m_ptr, pitch);
}
/**
* Set the sound volume.
* The default volume is 100
*
* Params:
* volume = Volume (in range [0, 100])
*/
void setVolume(float volume)
in
{
assert(volume >= 0 && volume <= 100);
}
body
{
sfSound_SetVolume(m_ptr, volume);
}
/**
* Set the sound position.
* The default position is (0, 0, 0)
*
* Params:
* x = X position of the sound in the world
* y = Y position of the sound in the world
* z = Z position of the sound in the world
*/
void setPosition(float x, float y, float z)
{
sfSound_SetPosition(m_ptr, x, y, z);
}
/**
* Set the sound position.
* The default position is (0, 0, 0)
*
* Params :
* position = new position
*/
void setPosition(Vector3f position)
{
sfSound_SetPosition(m_ptr, position.x, position.y, position.z);
}
/**
* Set the minimum distance - closer than this distance
* the listener will hear the sound at its maximum volume.
* The default distance is 1.0
*
* Params:
* minDistance = new minimum distance for the sound
*/
void setMinDistance(float minDistance)
{
sfSound_SetMinDistance(m_ptr, minDistance);
}
/**
* Set the attenuation factor - the higher the attenuation, the
* more the sound will be attenuated with distance from listener.
* The default attenuation factor 1.0
*
* Params:
* attenuation = new attenuation factor for the sound
*/
void setAttenuation(float attenuation)
{
sfSound_SetAttenuation(m_ptr, attenuation);
}
/**
* Set the current playing offset of a sound
*
* Params:
* offset = new playing position, expressed in seconds
*/
void setPlayingOffset(float offset)
{
sfSound_SetPlayingOffset(m_ptr, offset);
}
/**
* Get the source buffer
*
* Returns:
* Sound buffer bound to the sound (can be NULL)
*/
SoundBuffer getBuffer()
{
return m_buffer;
}
/**
* Tell whether or not the sound is looping
*
* Returns:
* True if the sound is looping, false otherwise
*/
bool getLoop()
{
return cast(bool)(sfSound_GetLoop(m_ptr));
}
/**
* Get the pitch
*
* Returns:
* Pitch value
*/
float getPitch()
{
return sfSound_GetPitch(m_ptr);
}
/**
* Get the volume
*
* Returns:
* Volume value (in range [1, 100])
*/
float getVolume()
{
return sfSound_GetVolume(m_ptr);
}
/**
* Get the sound position
*
* Params:
* x = X position of the sound in the world
* y = Y position of the sound in the world
* z = Z position of the sound in the world
*/
Vector3f getPosition()
{
Vector3f ret;
sfSound_GetPosition(m_ptr, &ret.x, &ret.y, &ret.z);
return ret;
}
/**
* Get the minimum distance
*
* Returns:
* Minimum distance for the sound
*/
float getMinDistance()
{
return sfSound_GetMinDistance(m_ptr);
}
/**
* Get the attenuation factor
*
* Returns:
* Attenuation factor of the sound
*
*/
float getAttenuation()
{
return sfSound_GetAttenuation(m_ptr);
}
/**
* Get the status of the sound (stopped, paused, playing)
*
* Returns:
* Current status of the sound
*/
SoundStatus getStatus()
{
return sfSound_GetStatus(m_ptr);
}
/**
* Get the current playing position of the sound
*
* Returns:
* Current playing position, expressed in seconds
*/
float getPlayingOffset()
{
return sfSound_GetPlayingOffset(m_ptr);
}
private:
SoundBuffer m_buffer;
// External ====================================================================
extern (C)
{
typedef void* function() pf_sfSound_Create;
typedef void function(void*) pf_sfSound_Destroy;
typedef void function(void*) pf_sfSound_Play;
typedef void function(void*) pf_sfSound_Pause;
typedef void function(void*) pf_sfSound_Stop;
typedef void function(void*, void*) pf_sfSound_SetBuffer;
typedef void* function(void*) pf_sfSound_GetBuffer;
typedef void function(void*, int) pf_sfSound_SetLoop;
typedef int function(void*) pf_sfSound_GetLoop;
typedef SoundStatus function(void*) pf_sfSound_GetStatus;
typedef void function(void*, float) pf_sfSound_SetPitch;
typedef void function(void*, float) pf_sfSound_SetVolume;
typedef void function(void*, float, float, float) pf_sfSound_SetPosition;
typedef float function(void*) pf_sfSound_GetPitch;
typedef float function(void*) pf_sfSound_GetVolume;
typedef void function(void*, float*, float*, float*) pf_sfSound_GetPosition;
typedef float function(void*) pf_sfSound_GetPlayingOffset;
typedef float function(void*) pf_sfSound_GetMinDistance;
typedef float function(void*) pf_sfSound_GetAttenuation;
typedef void function(void*, float) pf_sfSound_SetMinDistance;
typedef void function(void*, float) pf_sfSound_SetAttenuation;
typedef void function(void*, float) pf_sfSound_SetPlayingOffset;
static pf_sfSound_Create sfSound_Create;
static pf_sfSound_Destroy sfSound_Destroy;
static pf_sfSound_Play sfSound_Play;
static pf_sfSound_Pause sfSound_Pause;
static pf_sfSound_Stop sfSound_Stop;
static pf_sfSound_SetBuffer sfSound_SetBuffer;
static pf_sfSound_GetBuffer sfSound_GetBuffer;
static pf_sfSound_SetLoop sfSound_SetLoop;
static pf_sfSound_GetLoop sfSound_GetLoop;
static pf_sfSound_GetStatus sfSound_GetStatus;
static pf_sfSound_SetPitch sfSound_SetPitch;
static pf_sfSound_SetVolume sfSound_SetVolume;
static pf_sfSound_SetPosition sfSound_SetPosition;
static pf_sfSound_GetPitch sfSound_GetPitch;
static pf_sfSound_GetVolume sfSound_GetVolume;
static pf_sfSound_GetPosition sfSound_GetPosition;
static pf_sfSound_GetPlayingOffset sfSound_GetPlayingOffset;
static pf_sfSound_GetMinDistance sfSound_GetMinDistance;
static pf_sfSound_GetAttenuation sfSound_GetAttenuation;
static pf_sfSound_SetMinDistance sfSound_SetMinDistance;
static pf_sfSound_SetAttenuation sfSound_SetAttenuation;
static pf_sfSound_SetPlayingOffset sfSound_SetPlayingOffset;
}
static this()
{
DllLoader dll = DllLoader.load("csfml-audio");
sfSound_Create = cast(pf_sfSound_Create)dll.getSymbol("sfSound_Create");
sfSound_Destroy = cast(pf_sfSound_Destroy)dll.getSymbol("sfSound_Destroy");
sfSound_Play = cast(pf_sfSound_Play)dll.getSymbol("sfSound_Play");
sfSound_Pause = cast(pf_sfSound_Pause)dll.getSymbol("sfSound_Pause");
sfSound_Stop = cast(pf_sfSound_Stop)dll.getSymbol("sfSound_Stop");
sfSound_SetBuffer = cast(pf_sfSound_SetBuffer)dll.getSymbol("sfSound_SetBuffer");
sfSound_GetBuffer = cast(pf_sfSound_GetBuffer)dll.getSymbol("sfSound_GetBuffer");
sfSound_SetLoop = cast(pf_sfSound_SetLoop)dll.getSymbol("sfSound_SetLoop");
sfSound_GetLoop = cast(pf_sfSound_GetLoop)dll.getSymbol("sfSound_GetLoop");
sfSound_GetStatus = cast(pf_sfSound_GetStatus)dll.getSymbol("sfSound_GetStatus");
sfSound_SetPitch = cast(pf_sfSound_SetPitch)dll.getSymbol("sfSound_SetPitch");
sfSound_SetVolume = cast(pf_sfSound_SetVolume)dll.getSymbol("sfSound_SetVolume");
sfSound_SetPosition = cast(pf_sfSound_SetPosition)dll.getSymbol("sfSound_SetPosition");
sfSound_GetPitch = cast(pf_sfSound_GetPitch)dll.getSymbol("sfSound_GetPitch");
sfSound_GetVolume = cast(pf_sfSound_GetVolume)dll.getSymbol("sfSound_GetVolume");
sfSound_GetPosition = cast(pf_sfSound_GetPosition)dll.getSymbol("sfSound_GetPosition");
sfSound_GetPlayingOffset = cast(pf_sfSound_GetPlayingOffset)dll.getSymbol("sfSound_GetPlayingOffset");
sfSound_GetMinDistance = cast(pf_sfSound_GetMinDistance)dll.getSymbol("sfSound_GetMinDistance");
sfSound_GetAttenuation = cast(pf_sfSound_GetAttenuation)dll.getSymbol("sfSound_GetAttenuation");
sfSound_SetMinDistance = cast(pf_sfSound_SetMinDistance)dll.getSymbol("sfSound_SetMinDistance");
sfSound_SetAttenuation = cast(pf_sfSound_SetAttenuation)dll.getSymbol("sfSound_SetAttenuation");
sfSound_SetPlayingOffset = cast(pf_sfSound_SetPlayingOffset)dll.getSymbol("sfSound_SetPlayingOffset");
}
}

View file

@ -0,0 +1,226 @@
/*
* DSFML - SFML Library binding in D language.
* Copyright (C) 2008 Julien Dagorn (sirjulio13@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.
*/
module dsfml.audio.soundbuffer;
import dsfml.system.common;
import dsfml.system.exception;
import dsfml.system.stringutil;
/**
* SoundBuffer is the low-level for loading and manipulating
* sound buffers
*/
class SoundBuffer : DSFMLObject
{
/**
* Load the sound buffer from a file
*
* Params:
* filename = Path of the sound file to load
*
* Throws:
* LoadingException on failure
*/
this(char[] filename)
{
if (filename is null || filename.length == 0)
throw new LoadingException("LoadingException : Filename is invalid.");
super(sfSoundBuffer_CreateFromFile(toStringz(filename)));
}
/**
* Load the sound buffer from a file in memory
*
* Params:
* data = Array of file data in memory
*
* Throws:
* LoadingException on failure
*/
this(byte[] data)
{
if (data is null || data.length == 0)
throw new Exception("LoadingException : Memory stream is invalid.");
super(sfSoundBuffer_CreateFromMemory(data.ptr, data.length));
}
/**
* Load the sound buffer from an array of samples - assumed format for
* samples is 16 bits signed integer
*
* Params:
* samples = Array of samples in memory
* channelsCount = Number of channels (1 = mono, 2 = stereo, ...)
* sampleRate = Frequency (number of samples to play per second)
*
* Throws:
* LoadingException on failure
*/
this(short[] samples, uint channelsCount, uint sampleRate)
{
if (samples is null || samples.length == 0)
throw new Exception("LoadingException : Samples array is invalid.");
super(sfSoundBuffer_CreateFromSamples(samples.ptr, samples.length, channelsCount, sampleRate));
}
override void dispose()
{
sfSoundBuffer_Destroy(m_ptr);
}
/**
* Save the sound buffer to a file
*
* Params:
* filename = Path of the sound file to write
*
* Returns:
* True if saving has been successful
*/
bool saveToFile(char[] filename)
{
if (filename !is null && filename.length > 0 )
{
return cast(bool)sfSoundBuffer_SaveToFile(m_ptr, toStringz(filename));
}
return false;
}
/**
* Return the sound samples
*
* Returns:
* Array of sound samples, in 16 bits signed integer format
*/
short[] getSamples()
{
short* temp = null;
temp = sfSoundBuffer_GetSamples(m_ptr);
return temp is null ? null : temp[0..getSamplesCount];
}
/**
* Return the samples count
*
* Returns:
* Number of samples
*/
size_t getSamplesCount()
{
return sfSoundBuffer_GetSamplesCount(m_ptr);
}
/**
* Get the sample rate
*
* Returns:
* Sound frequency (number of samples per second)
*/
uint getSampleRate()
{
return sfSoundBuffer_GetSampleRate(m_ptr);
}
/**
* Return the number of channels (1 = mono, 2 = stereo, ...)
*
* Returns:
* Number of channels
*/
uint getChannelsCount()
{
return sfSoundBuffer_GetChannelsCount(m_ptr);
}
/**
* Get the sound duration
*
* Returns:
* Sound duration, in seconds
*/
float getDuration()
{
return sfSoundBuffer_GetDuration(m_ptr);
}
package:
this(void* ptr)
{
super(ptr, true);
}
private:
// External ====================================================================
extern (C)
{
typedef void* function(char*) pf_sfSoundBuffer_CreateFromFile;
typedef void* function(byte*, size_t) pf_sfSoundBuffer_CreateFromMemory;
typedef void* function(short*, size_t, uint, uint) pf_sfSoundBuffer_CreateFromSamples;
typedef void function(void*) pf_sfSoundBuffer_Destroy;
typedef int function(void*, char*) pf_sfSoundBuffer_SaveToFile;
typedef short* function(void*) pf_sfSoundBuffer_GetSamples;
typedef size_t function(void*) pf_sfSoundBuffer_GetSamplesCount;
typedef uint function(void*) pf_sfSoundBuffer_GetSampleRate;
typedef uint function(void*) pf_sfSoundBuffer_GetChannelsCount;
typedef float function(void*) pf_sfSoundBuffer_GetDuration;
static pf_sfSoundBuffer_CreateFromFile sfSoundBuffer_CreateFromFile;
static pf_sfSoundBuffer_CreateFromMemory sfSoundBuffer_CreateFromMemory;
static pf_sfSoundBuffer_CreateFromSamples sfSoundBuffer_CreateFromSamples;
static pf_sfSoundBuffer_Destroy sfSoundBuffer_Destroy;
static pf_sfSoundBuffer_SaveToFile sfSoundBuffer_SaveToFile;
static pf_sfSoundBuffer_GetSamples sfSoundBuffer_GetSamples;
static pf_sfSoundBuffer_GetSamplesCount sfSoundBuffer_GetSamplesCount;
static pf_sfSoundBuffer_GetSampleRate sfSoundBuffer_GetSampleRate;
static pf_sfSoundBuffer_GetChannelsCount sfSoundBuffer_GetChannelsCount;
static pf_sfSoundBuffer_GetDuration sfSoundBuffer_GetDuration;
}
static this()
{
DllLoader dll = DllLoader.load("csfml-audio");
sfSoundBuffer_CreateFromFile = cast(pf_sfSoundBuffer_CreateFromFile)dll.getSymbol("sfSoundBuffer_CreateFromFile");
sfSoundBuffer_CreateFromMemory = cast(pf_sfSoundBuffer_CreateFromMemory)dll.getSymbol("sfSoundBuffer_CreateFromMemory");
sfSoundBuffer_CreateFromSamples = cast(pf_sfSoundBuffer_CreateFromSamples)dll.getSymbol("sfSoundBuffer_CreateFromSamples");
sfSoundBuffer_Destroy = cast(pf_sfSoundBuffer_Destroy)dll.getSymbol("sfSoundBuffer_Destroy");
sfSoundBuffer_SaveToFile = cast(pf_sfSoundBuffer_SaveToFile)dll.getSymbol("sfSoundBuffer_SaveToFile");
sfSoundBuffer_GetSamples = cast(pf_sfSoundBuffer_GetSamples)dll.getSymbol("sfSoundBuffer_GetSamples");
sfSoundBuffer_GetSamplesCount = cast(pf_sfSoundBuffer_GetSamplesCount)dll.getSymbol("sfSoundBuffer_GetSamplesCount");
sfSoundBuffer_GetSampleRate = cast(pf_sfSoundBuffer_GetSampleRate)dll.getSymbol("sfSoundBuffer_GetSampleRate");
sfSoundBuffer_GetChannelsCount = cast(pf_sfSoundBuffer_GetChannelsCount)dll.getSymbol("sfSoundBuffer_GetChannelsCount");
sfSoundBuffer_GetDuration = cast(pf_sfSoundBuffer_GetDuration)dll.getSymbol("sfSoundBuffer_GetDuration");
}
}

View file

@ -0,0 +1,105 @@
/*
* DSFML - SFML Library binding in D language.
* Copyright (C) 2008 Julien Dagorn (sirjulio13@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.
*/
module dsfml.audio.soundbufferrecorder;
import dsfml.system.common;
import dsfml.audio.soundbuffer;
import dsfml.audio.soundrecorder;
/**
* Specialized sfSoundRecorder which saves the captured
* audio data into a sound buffer
*/
class SoundBufferRecorder : SoundRecorder
{
/**
* Constructor
*/
this()
{
super(sfSoundBufferRecorder_Create());
}
override void dispose()
{
sfSoundBufferRecorder_Destroy(m_ptr);
}
/**
* Get the sound buffer containing the captured audio data
*
* Returns:
* SoundBuffer containing the captured audio data
*
*/
SoundBuffer getBuffer()
{
return new SoundBuffer(sfSoundBufferRecorder_GetBuffer(m_ptr));
}
protected:
override bool onStart()
{
return true;
}
override bool onProcessSamples(short[] s)
{
return true;
}
override void onStop()
{
}
private:
// External ====================================================================
extern (C)
{
typedef void* function() pf_sfSoundBufferRecorder_Create;
typedef void function(void*) pf_sfSoundBufferRecorder_Destroy;
typedef void* function(void*) pf_sfSoundBufferRecorder_GetBuffer;
static pf_sfSoundBufferRecorder_Create sfSoundBufferRecorder_Create;
static pf_sfSoundBufferRecorder_Destroy sfSoundBufferRecorder_Destroy;
static pf_sfSoundBufferRecorder_GetBuffer sfSoundBufferRecorder_GetBuffer;
}
static this()
{
DllLoader dll = DllLoader.load("csfml-audio");
sfSoundBufferRecorder_Create = cast(pf_sfSoundBufferRecorder_Create)dll.getSymbol("sfSoundBufferRecorder_Create");
sfSoundBufferRecorder_Destroy = cast(pf_sfSoundBufferRecorder_Destroy)dll.getSymbol("sfSoundBufferRecorder_Destroy");
sfSoundBufferRecorder_GetBuffer = cast(pf_sfSoundBufferRecorder_GetBuffer)dll.getSymbol("sfSoundBufferRecorder_GetBuffer");
}
}

View file

@ -0,0 +1,332 @@
/*
* DSFML - SFML Library binding in D language.
* Copyright (C) 2008 Julien Dagorn (sirjulio13@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.
*/
module dsfml.audio.soundrecorder;
import dsfml.audio.soundbuffer;
import dsfml.system.alloc;
import dsfml.system.common;
import dsfml.system.sleep;
import dsfml.system.linkedlist;
import dsfml.system.mutex;
import dsfml.system.lock;
import dsfml.system.thread;
/**
* SoundRecorder is an interface for capturing sound data.
*
* $(B onProcessSamples and onStop will be called by a different thread, take care of synchronization issues.)
*
* Examples:
* -------
* class MySoundRecorder : SoundRecorder
* {
* this()
* {
*
* }
*
* protected bool onStart()
* {
* return true;
* }
*
* protected void onStop()
* {
*
* }
*
* protected bool onProcessSamples(out short[])
* {
* // Process data here
*
* return true; //return true to continue capture, else return false
* }
* }
* -------
*/
abstract class SoundRecorder : DSFMLObject
{
override void dispose()
{
if (m_flag)
stop();
m_instances.remove(m_id);
sfSoundRecorder_Destroy(m_ptr);
}
/**
* Start the capture.
*
* Only one capture can happen at the same time
*
* Params:
* sampleRate : Sound frequency (the more samples, the higher the quality)
* (44100 by default = CD quality)
*/
void start(uint sampleRate = 44100)
{
sfSoundRecorder_Start(m_ptr, sampleRate);
m_t = new Thread(&threadPoll);
m_t.launch();
}
/**
* Stop the capture
*/
void stop()
{
sfSoundRecorder_Stop(m_ptr);
m_flag = false;
m_t.wait();
m_t = null;
}
/**
* Get the sample rate
*
* Returns:
* Frequency, in samples per second
*/
uint getSampleRate()
{
return sfSoundRecorder_GetSampleRate(m_ptr);
}
/**
* Tell if the system supports sound capture.
* If not, this class won't be usable
*
* Returns:
* True if audio capture is supported
*
*/
static bool canCapture()
{
return cast(bool)sfSoundRecorder_CanCapture();
}
protected:
/**
* Protected constructor
*/
this()
{
m_id = ++seed;
m_instances[m_id] = this;
super(sfSoundRecorder_Create(&internalOnStart, &internalCallback, &internalOnStop, &m_id));
init(true);
}
this(void* ptr)
{
super(ptr);
init(false);
}
/**
* Start recording audio data
*
* Returns:
* False to abort recording audio data, true to start
*/
abstract bool onStart();
/**
* Stop recording audio data
*/
abstract void onStop();
/**
* callback function
*
* Parameters:
* samples = Array of samples
*
* Returns:
* true to continue recording, false to stop.
*/
abstract bool onProcessSamples(short[] samples);
bool m_disposed;
private:
/*
* an init function to initialize id of the object.
*/
void init(bool flag)
{
if (flag)
{
m_list = new LinkedList!(Samples)();
m_flag = true;
m_continue = true;
m_mutex = new Mutex();
}
}
void* m_userData;
int m_id;
static int seed = 0;
static SoundRecorder[int] m_instances;
/*
* Extern C callback function
*
* This function must be static for C interop. To retrieve the current
* instance, we retrieve id of the sender in the user data, and search associated instance
* in the associative array.
*
* We don't call delegate or derived class on that thread because GC is not aware of this thread
* instead we enqueue data informations in a queue and poll this queue with a managed thread.
*/
extern(C) static int internalCallback(short* s, size_t size, void* user)
{
int id;
// retrieve instance
if ((id = *cast(int*)(user)) in m_instances)
{
SoundRecorder temp = m_instances[id];
scope Lock l = new Lock(temp.m_mutex);
if (temp.m_continue)
// this new is allowed because Samples is an custom alloc class.
temp.m_list.enqueue(new Samples(s, size));
return temp.m_continue;
}
return false;
}
extern(C) static int internalOnStart(void* user)
{
int id;
bool ret = false;
if ((id = *cast(int*)(user)) in m_instances)
{
SoundRecorder temp = m_instances[id];
ret = temp.onStart();
}
return ret;
}
extern(C) static void internalOnStop(void* user)
{
// Nothing to do
}
/*
* Managed thread loop
*/
void threadPoll(void* user)
{
while (m_flag)
{
sleep(0.05f);
// if samples are available
if (!m_list.empty)
{
// Lock ressources
scope Lock l = new Lock(m_mutex);
Samples s = m_list.dequeue;
m_continue = this.onProcessSamples(s.data[0..s.length].dup);
delete s;
if (!m_continue)
{
// delete all samples left
foreach(Samples dummy; m_list)
delete dummy;
break;
}
}
}
onStop();
}
Mutex m_mutex;
bool m_flag;
bool m_continue = true;
LinkedList!(Samples) m_list;
Thread m_t;
// External ====================================================================
extern (C)
{
typedef void* function(int function(void*), int function(short*, size_t, void*), void function(void*), void*) pf_sfSoundRecorder_Create;
typedef void function(void*) pf_sfSoundRecorder_Destroy;
typedef void function(void*, uint SampleRate) pf_sfSoundRecorder_Start;
typedef void function(void*) pf_sfSoundRecorder_Stop;
typedef uint function(void*) pf_sfSoundRecorder_GetSampleRate;
typedef int function() pf_sfSoundRecorder_CanCapture;
static pf_sfSoundRecorder_Create sfSoundRecorder_Create;
static pf_sfSoundRecorder_Destroy sfSoundRecorder_Destroy;
static pf_sfSoundRecorder_Start sfSoundRecorder_Start;
static pf_sfSoundRecorder_Stop sfSoundRecorder_Stop;
static pf_sfSoundRecorder_GetSampleRate sfSoundRecorder_GetSampleRate;
static pf_sfSoundRecorder_CanCapture sfSoundRecorder_CanCapture;
}
static this()
{
DllLoader dll = DllLoader.load("csfml-audio");
sfSoundRecorder_Create = cast(pf_sfSoundRecorder_Create)dll.getSymbol("sfSoundRecorder_Create");
sfSoundRecorder_Destroy = cast(pf_sfSoundRecorder_Destroy)dll.getSymbol("sfSoundRecorder_Destroy");
sfSoundRecorder_Start = cast(pf_sfSoundRecorder_Start)dll.getSymbol("sfSoundRecorder_Start");
sfSoundRecorder_Stop = cast(pf_sfSoundRecorder_Stop)dll.getSymbol("sfSoundRecorder_Stop");
sfSoundRecorder_GetSampleRate = cast(pf_sfSoundRecorder_GetSampleRate)dll.getSymbol("sfSoundRecorder_GetSampleRate");
sfSoundRecorder_CanCapture = cast(pf_sfSoundRecorder_CanCapture)dll.getSymbol("sfSoundRecorder_CanCapture");
}
}
// Use explicit alloc to allow instaciation by C thread
private class Samples
{
mixin Alloc;
this(short* data, size_t length)
{
this.data = data;
this.length = length;
}
public short* data;
public size_t length;
}

View file

@ -0,0 +1,34 @@
/*
* DSFML - SFML Library binding in D language.
* Copyright (C) 2008 Julien Dagorn (sirjulio13@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.
*/
module dsfml.audio.soundstatus;
/// Enumeration of the sound states
enum SoundStatus
{
STOPPED, /// Sound / music is not playing
PAUSED, /// Sound / music is paused
PLAYING /// Sound / music is playing
}

View file

@ -0,0 +1,550 @@
/*
* DSFML - SFML Library binding in D language.
* Copyright (C) 2008 Julien Dagorn (sirjulio13@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.
*/
module dsfml.audio.soundstream;
import dsfml.system.alloc;
import dsfml.system.common;
import dsfml.system.vector3;
import dsfml.system.linkedlist;
import dsfml.system.lock;
import dsfml.system.mutex;
import dsfml.system.sleep;
import dsfml.system.thread;
import dsfml.audio.sound;
import dsfml.audio.soundstatus;
/**
* SoundStream is a streamed sound, ie samples are acquired
* while the sound is playing. Use it for big sounds that would
* require hundreds of MB in memory, or for streaming sound from the network.
*
* SoundStream is a base class and cannot be instanciated directly.
*
* $(B onGetData override will be called by a different thread, take care of synchronization issues.) onStart is called by the thread which called .play().
*
* ------------------------
* class MySoundStream : SoundStream
* {
* this()
* {
* super(2, 44100); // you need to initialize the base class before any operation.
* }
* protected bool onGetData(out short[] data)
* {
* //You need to fill data array with some samples
*
* return true; //or false if you want to stop playback
* }
*
* protected bool onStart()
* {
* return true;
* }
* }
* ------------------------
*/
abstract class SoundStream : DSFMLObject
{
override void dispose()
{
stop();
sfSoundStream_Destroy(m_ptr);
s_instances.remove(m_id);
}
/**
* Start playing the stream
*/
void play()
{
m_flag = true;
sfSoundStream_Play(m_ptr);
if (getStatus() != SoundStatus.PAUSED)
{
m_t = new Thread(&threadPoll);
m_t.launch();
}
}
/**
* Pause the stream
*/
void pause()
{
sfSoundStream_Pause(m_ptr);
}
/**
* Stop the stream
*/
void stop()
{
m_flag = false;
sfSoundStream_Stop(m_ptr);
m_t.wait();
if (m_dummy !is null)
delete m_dummy;
}
/**
* Get number of channels of the stream
*
* Returns:
* number of channels
*/
uint getChannelsCount()
{
return m_channelsCount;
}
/**
* Get the sample rate of the stream
*
* Returns:
* sample rate
*/
uint getSampleRate()
{
return m_sampleRate;
}
/**
* Get the current status of the stream
*
* Returns:
* Current stream status
*/
SoundStatus getStatus()
{
return sfSoundStream_GetStatus(m_ptr);
}
/**
* Set the sound pitch.
* The default pitch is 1
*
* Params:
* pitch = New pitch
*/
void setPitch(float pitch)
{
sfSoundStream_SetPitch(m_ptr, pitch);
}
/**
* Set the sound volume.
* The default volume is 100
*
* Params:
* volume = Volume (in range [0, 100])
*/
void setVolume(float volume)
in
{
assert(volume >= 0.f && volume <= 100.f);
}
body
{
sfSoundStream_SetVolume(m_ptr, volume);
}
/*
* Set the sound position (take 3 values).
* The default position is (0, 0, 0)
*
* Params:
* x, y, z = Position of the sound in the world
*/
void setPosition(float x, float y, float z)
{
sfSoundStream_SetPosition(m_ptr, x, y, z);
}
/**
* Set the sound position (take 3 values).
* The default position is (0, 0, 0)
*
* Params:
* vec = Position of the sound in the world
*
*/
void setPosition(Vector3f vec)
{
sfSoundStream_SetPosition(m_ptr, vec.x, vec.y, vec.z);
}
/**
* Set the minimum distance - closer than this distance,
* the listener will hear the sound at its maximum volume.
* The default minimum distance is 1.0
*
* Params:
* minDistance = New minimum distance for the sound
*/
void setMinDistance(float minDistance)
{
sfSoundStream_SetMinDistance(m_ptr, minDistance);
}
/**
* Set the attenuation factor - the higher the attenuation, the
* more the sound will be attenuated with distance from listener.
* The default attenuation factor 1.0
*
* Params:
* attenuation = New attenuation factor for the sound
*
*/
void setAttenuation(float attenuation)
{
sfSoundStream_SetAttenuation(m_ptr, attenuation);
}
/**
* Get the pitch
*
* Returns:
* Pitch value
*/
float getPitch()
{
return sfSoundStream_GetPitch(m_ptr);
}
/**
* Get the volume
*
* Returns:
* Volume value (in range [1, 100])
*
*/
float getVolume()
{
return sfSoundStream_GetVolume(m_ptr);
}
/**
* Get the sound position
*
* Returns:
* Sound position
*/
Vector3f getPosition()
{
Vector3f vec;
sfSoundStream_GetPosition(m_ptr, &vec.x, &vec.y, &vec.z);
return vec;
}
/**
* Get the minimum distance
*
* Returns:
* Get the minimum distance of the sound
*/
float getMinDistance()
{
return sfSoundStream_GetMinDistance(m_ptr);
}
/**
* Get the attenuation
*
* Returns:
* Get the attenuation of the sound
*/
float getAttenuation()
{
return sfSoundStream_GetAttenuation(m_ptr);
}
/**
* Get the current playing offset of the stream
*
* Returns:
* current playing offset, in seconds.
*/
float getPlayingOffset()
{
return sfSoundStream_GetPlayingOffset(m_ptr);
}
/**
* Tell whether or not the stream is looping
*
* Returns:
* True if the music is looping, false otherwise
*/
bool getLoop()
{
if (m_ptr !is null)
return cast(bool)sfSoundStream_GetLoop(m_ptr);
return false;
}
/**
* Set the stream loop state.
*
* Disabled by default.
*
* Params:
* loop = true to play in loop, false to play once
*/
void setLoop(bool loop)
{
if (m_ptr !is null)
sfSoundStream_SetLoop(m_ptr, loop);
}
protected:
/**
* Protected constructor
*
* Params:
* channelsCount = number of channel
* sampleRate = sample rate of the stream
*
*/
this(uint channelsCount, uint sampleRate)
{
m_channelsCount = channelsCount;
m_sampleRate = sampleRate;
super(sfSoundStream_Create(&externalOnStart, &externalOnGetData, channelsCount, sampleRate, &m_id));
m_mutex = new Mutex();
m_samples = new LinkedList!(Data);
m_t = new Thread(&this.threadPoll);
m_id = ++s_seed;
s_instances[m_id] = this;
}
/**
* Called each time the stream restart
*
* Returns:
* false to abort the playback
*/
abstract bool onStart();
/**
* Called each time the stream needs new data.
* This method will be call by an other thread, take care of possible synchronisation issues.
*
* Params:
* data = array of samples to stream
*
* Returns:
* true to continue streaming, false to stop
*/
abstract bool onGetData(out short[] data);
private:
// Called sync when user calling play()
extern(C) static int externalOnStart(void* user)
{
int id;
if ((id = *cast(int*) user) in s_instances)
{
SoundStream temp = s_instances[id];
return (temp.m_flag = temp.onStart());
}
return true;
}
// C Thread callback (no allocation can be done)
extern (C) static int externalOnGetData(sfSoundStreamChunk* data, void* user)
{
int id, flag = false;
// Get calling soundStream
if ((id = *cast(int*) user) in s_instances)
{
SoundStream temp = s_instances[id];
//if no samples are available but streaming is not stopped, we sleep the thread
while (temp.m_samples.empty && temp.m_flag)
sleep(0.01f);
scope Lock l = new Lock(temp.m_mutex);
if (!temp.m_samples.empty)
{
if (temp.m_dummy !is null)
delete temp.m_dummy;
temp.m_dummy = temp.m_samples.dequeue;
if ((flag = temp.m_dummy.Flag) == true)
{
data.Samples = temp.m_dummy.Samples.ptr;
data.NbSamples = temp.m_dummy.Samples.length;
}
else
{
data.Samples = null;
data.NbSamples = 0;
}
}
}
return flag;
}
// Managed thread loop
void threadPoll(void* dummy)
{
short[] data;
bool ret = true;
// while streaming is active ...
while (ret && m_flag)
{
{
scope Lock l = new Lock(m_mutex);
// see how many samples are available (keep always 2 samples ready)
if (m_samples.getCount < 2)
{
// if we need new samples, lock and call derived class
ret = onGetData(data);
m_samples.enqueue(new Data(data, ret));
}
}
sleep(0.1f);
}
}
private class Data
{
short[] Samples;
bool Flag;
mixin Alloc;
this (short[] samples, bool flag)
{
this.Samples = samples;
this.Flag = flag;
}
}
Thread m_t;
Mutex m_mutex;
LinkedList!(Data) m_samples;
Data m_dummy;
bool m_flag;
uint m_channelsCount;
uint m_sampleRate;
int m_id;
static SoundStream[int] s_instances;
static int s_seed = 0;
// External ====================================================================
extern (C)
{
struct sfSoundStreamChunk{ short* Samples; uint NbSamples; }
alias int function(void*) sfSoundStreamStartCallback;
alias int function (sfSoundStreamChunk*, void*) sfSoundStreamGetDataCallback;
typedef void* function(sfSoundStreamStartCallback, sfSoundStreamGetDataCallback, uint, uint, void*) pf_sfSoundStream_Create;
typedef void function(void*) pf_sfSoundStream_Destroy;
typedef void function(void*) pf_sfSoundStream_Play;
typedef void function(void*) pf_sfSoundStream_Pause;
typedef void function(void*) pf_sfSoundStream_Stop;
typedef SoundStatus function(void*) pf_sfSoundStream_GetStatus;
typedef uint function(void*) pf_sfSoundStream_GetChannelsCount;
typedef uint function(void*) pf_sfSoundStream_GetSampleRate;
typedef void function(void*, float) pf_sfSoundStream_SetPitch;
typedef void function(void*, float) pf_sfSoundStream_SetVolume;
typedef void function(void*, float, float, float) pf_sfSoundStream_SetPosition;
typedef void function(void*, float) pf_sfSoundStream_SetMinDistance;
typedef void function(void*, float) pf_sfSoundStream_SetAttenuation;
typedef float function(void*) pf_sfSoundStream_GetPitch;
typedef float function(void*) pf_sfSoundStream_GetVolume;
typedef void function(void*, float*, float*, float*) pf_sfSoundStream_GetPosition;
typedef float function(void*) pf_sfSoundStream_GetMinDistance;
typedef float function(void*) pf_sfSoundStream_GetAttenuation;
typedef float function(void*) pf_sfSoundStream_GetPlayingOffset;
typedef int function(void*) pf_sfSoundStream_GetLoop;
typedef void function(void*, int) pf_sfSoundStream_SetLoop;
static pf_sfSoundStream_Create sfSoundStream_Create;
static pf_sfSoundStream_Destroy sfSoundStream_Destroy;
static pf_sfSoundStream_Play sfSoundStream_Play;
static pf_sfSoundStream_Pause sfSoundStream_Pause;
static pf_sfSoundStream_Stop sfSoundStream_Stop;
static pf_sfSoundStream_GetStatus sfSoundStream_GetStatus;
static pf_sfSoundStream_GetChannelsCount sfSoundStream_GetChannelsCount;
static pf_sfSoundStream_GetSampleRate sfSoundStream_GetSampleRate;
static pf_sfSoundStream_SetPitch sfSoundStream_SetPitch;
static pf_sfSoundStream_SetVolume sfSoundStream_SetVolume;
static pf_sfSoundStream_SetPosition sfSoundStream_SetPosition;
static pf_sfSoundStream_SetMinDistance sfSoundStream_SetMinDistance;
static pf_sfSoundStream_SetAttenuation sfSoundStream_SetAttenuation;
static pf_sfSoundStream_GetPitch sfSoundStream_GetPitch;
static pf_sfSoundStream_GetVolume sfSoundStream_GetVolume;
static pf_sfSoundStream_GetPosition sfSoundStream_GetPosition;
static pf_sfSoundStream_GetMinDistance sfSoundStream_GetMinDistance;
static pf_sfSoundStream_GetAttenuation sfSoundStream_GetAttenuation;
static pf_sfSoundStream_GetPlayingOffset sfSoundStream_GetPlayingOffset;
static pf_sfSoundStream_GetLoop sfSoundStream_GetLoop;
static pf_sfSoundStream_SetLoop sfSoundStream_SetLoop;
}
static this()
{
DllLoader dll = DllLoader.load("csfml-audio");
sfSoundStream_Create = cast(pf_sfSoundStream_Create)dll.getSymbol("sfSoundStream_Create");
sfSoundStream_Destroy = cast(pf_sfSoundStream_Destroy)dll.getSymbol("sfSoundStream_Destroy");
sfSoundStream_Play = cast(pf_sfSoundStream_Play)dll.getSymbol("sfSoundStream_Play");
sfSoundStream_Pause = cast(pf_sfSoundStream_Pause)dll.getSymbol("sfSoundStream_Pause");
sfSoundStream_Stop = cast(pf_sfSoundStream_Stop)dll.getSymbol("sfSoundStream_Stop");
sfSoundStream_GetStatus = cast(pf_sfSoundStream_GetStatus)dll.getSymbol("sfSoundStream_GetStatus");
sfSoundStream_GetChannelsCount = cast(pf_sfSoundStream_GetChannelsCount)dll.getSymbol("sfSoundStream_GetChannelsCount");
sfSoundStream_GetSampleRate = cast(pf_sfSoundStream_GetSampleRate)dll.getSymbol("sfSoundStream_GetSampleRate");
sfSoundStream_SetPitch = cast(pf_sfSoundStream_SetPitch)dll.getSymbol("sfSoundStream_SetPitch");
sfSoundStream_SetVolume = cast(pf_sfSoundStream_SetVolume)dll.getSymbol("sfSoundStream_SetVolume");
sfSoundStream_SetPosition = cast(pf_sfSoundStream_SetPosition)dll.getSymbol("sfSoundStream_SetPosition");
sfSoundStream_SetMinDistance = cast(pf_sfSoundStream_SetMinDistance)dll.getSymbol("sfSoundStream_SetMinDistance");
sfSoundStream_SetAttenuation = cast(pf_sfSoundStream_SetAttenuation)dll.getSymbol("sfSoundStream_SetAttenuation");
sfSoundStream_GetPitch = cast(pf_sfSoundStream_GetPitch)dll.getSymbol("sfSoundStream_GetPitch");
sfSoundStream_GetVolume = cast(pf_sfSoundStream_GetVolume)dll.getSymbol("sfSoundStream_GetVolume");
sfSoundStream_GetPosition = cast(pf_sfSoundStream_GetPosition)dll.getSymbol("sfSoundStream_GetPosition");
sfSoundStream_GetMinDistance = cast(pf_sfSoundStream_GetMinDistance)dll.getSymbol("sfSoundStream_GetMinDistance");
sfSoundStream_GetAttenuation = cast(pf_sfSoundStream_GetAttenuation)dll.getSymbol("sfSoundStream_GetAttenuation");
sfSoundStream_GetPlayingOffset = cast(pf_sfSoundStream_GetPlayingOffset)dll.getSymbol("sfSoundStream_GetPlayingOffset");
sfSoundStream_GetLoop = cast(pf_sfSoundStream_GetLoop)dll.getSymbol("sfSoundStream_GetLoop");
sfSoundStream_SetLoop = cast(pf_sfSoundStream_SetLoop)dll.getSymbol("sfSoundStream_SetLoop");
}
}

View file

@ -0,0 +1,41 @@
/*
* DSFML - SFML Library binding in D language.
* Copyright (C) 2008 Julien Dagorn (sirjulio13@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.
*/
module dsfml.graphics.all;
public import
dsfml.graphics.blendmode,
dsfml.graphics.color,
dsfml.graphics.font,
dsfml.graphics.idrawable,
dsfml.graphics.image,
dsfml.graphics.postfx,
dsfml.graphics.rect,
dsfml.graphics.renderwindow,
dsfml.graphics.shape,
dsfml.graphics.sprite,
dsfml.graphics.string,
dsfml.graphics.textstyle,
dsfml.graphics.view;

View file

@ -0,0 +1,37 @@
/*
* DSFML - SFML Library binding in D language.
* Copyright (C) 2008 Julien Dagorn (sirjulio13@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.
*/
module dsfml.graphics.blendmode;
/**
* Enumerate the blending modes for drawable objects.
*/
enum BlendMode
{
ALPHA, /// Pixel = Src * a + Dest * (1 - a)
ADD, /// Pixel = Src + Dest
MULTIPLY, /// Pixel = Src * Dest
NONE /// No blending
}

View file

@ -0,0 +1,130 @@
/*
* DSFML - SFML Library binding in D language.
* Copyright (C) 2008 Julien Dagorn (sirjulio13@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.
*/
module dsfml.graphics.color;
/**
* Color is an utility structure for manipulating colors
*/
struct Color
{
/**
* Construct the color from its 4 RGBA components
*
* Params:
* r = Red component (0 .. 255)
* g = Green component (0 .. 255)
* b = Blue component (0 .. 255)
* a = Alpha component (0 .. 255) (255 by default)
*/
static Color opCall(ubyte r, ubyte g, ubyte b, ubyte a = 255)
{
Color c;
c.r = r;
c.g = g;
c.b = b;
c.a = a;
return c;
}
/**
* Operator == and != overload to compare two colors
*/
int opEquals(Color color2)
{
return
(r == color2.r)
&& (g == color2.g)
&& (b == color2.b)
&& (a == color2.a);
}
/**
* Operator + overload to add two colors
*/
Color opAdd(Color color2)
{
ubyte r = this.r + color2.r > 255 ? 255 : this.r + color2.r;
ubyte g = this.g + color2.g > 255 ? 255 : this.g + color2.g;
ubyte b = this.b + color2.b > 255 ? 255 : this.b + color2.b;
ubyte a = this.a + color2.a > 255 ? 255 : this.a + color2.a;
return Color(r, g, b, a);
}
/**
* Operator += overload
*/
Color opAddAssign(Color color2)
{
this.r = this.r + color2.r > 255 ? 255 : this.r + color2.r;
this.g = this.g + color2.g > 255 ? 255 : this.g + color2.g;
this.b = this.b + color2.b > 255 ? 255 : this.b + color2.b;
this.a = this.a + color2.a > 255 ? 255 : this.a + color2.a;
return *this;
}
/**
* Operator * overload to modulate colors
*/
Color opMul(Color color2)
{
ubyte r = this.r * color2.r / 255;
ubyte g = this.g * color2.g / 255;
ubyte b = this.b * color2.b / 255;
ubyte a = this.a * color2.a / 255;
return Color(r, g, b, a);
}
/**
* Operator *= overload
*/
Color opMulAssign(Color color2)
{
this.r = this.r * color2.r / 255;
this.g = this.g * color2.g / 255;
this.b = this.b * color2.b / 255;
this.a = this.a * color2.a / 255;
return *this;
}
ubyte r; /// Red component
ubyte g; /// Green component
ubyte b; /// Blue component
ubyte a = 255; /// Alpha (transparency) component
static const Color BLACK = {0, 0, 0}; /// Black predefined color
static const Color WHITE = {255, 255, 255}; /// White predefined color
static const Color RED = {255, 0, 0}; /// Red predefined color
static const Color GREEN = {0, 255, 0}; /// Green predefined color
static const Color BLUE = {0, 0, 255}; /// Blue predefined color
static const Color YELLOW = {255, 0, 255}; /// Yellow predefined color
static const Color MAGENTA = {255, 0, 255}; /// Magenta predefined color
static const Color CYAN = {0, 255, 255}; /// Cyan predefined color
}

View file

@ -0,0 +1,320 @@
/*
* DSFML - SFML Library binding in D language.
* Copyright (C) 2008 Julien Dagorn (sirjulio13@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.
*/
module dsfml.graphics.drawableimpl;
public import dsfml.system.common;
import dsfml.system.vector2;
import dsfml.graphics.idrawable;
import dsfml.graphics.color;
import dsfml.graphics.blendmode;
import dsfml.graphics.renderwindow;
package
{
struct sfSprite{};
struct sfShape{};
struct sfString{};
}
/*
* Package base class of all drawable.
* Provide implementation of IDrawable and functions aliases.
*/
package class Drawableimpl(T) : DSFMLObject, IDrawable
{
void setX(float x)
{
sfDrawable_SetX(m_ptr, x);
}
void setY(float y)
{
sfDrawable_SetY(m_ptr, y);
}
void setPosition(float x, float y)
{
sfDrawable_SetPosition(m_ptr, x, y);
}
void setPosition(Vector2f vec)
{
sfDrawable_SetPosition(m_ptr, vec.x, vec.y);
}
void setScaleX(float scale)
{
if (scale > 0)
sfDrawable_SetScaleX(m_ptr, scale);
}
void setScaleY(float scale)
{
if (scale > 0)
sfDrawable_SetScaleY(m_ptr, scale);
}
void setScale(float scaleX, float scaleY)
{
if (scaleX > 0 && scaleY > 0)
sfDrawable_SetScale(m_ptr, scaleX, scaleY);
}
void setScale(Vector2f scale)
{
if (scale.x > 0 && scale.y > 0)
sfDrawable_SetScale(m_ptr, scale.x, scale.y);
}
void setCenter(float centerX, float centerY)
{
sfDrawable_SetCenter(m_ptr, centerX, centerY);
}
void setCenter(Vector2f center)
{
sfDrawable_SetCenter(m_ptr, center.x, center.y);
}
void setRotation(float angle)
{
sfDrawable_SetRotation(m_ptr, angle);
}
void setColor(Color c)
{
sfDrawable_SetColor(m_ptr, c);
}
void setBlendMode(BlendMode mode)
{
sfDrawable_SetBlendMode(m_ptr, mode);
}
Vector2f getPosition()
{
return Vector2f(sfDrawable_GetX(m_ptr), sfDrawable_GetY(m_ptr));
}
Vector2f getScale()
{
return Vector2f(sfDrawable_GetScaleX(m_ptr), sfDrawable_GetScaleY(m_ptr));
}
Vector2f getCenter()
{
return Vector2f(sfDrawable_GetCenterX(m_ptr), sfDrawable_GetCenterY(m_ptr));
}
float getRotation()
{
return sfDrawable_GetRotation(m_ptr);
}
Color getColor()
{
return sfDrawable_GetColor(m_ptr);
}
BlendMode getBlendMode()
{
return cast(BlendMode)(sfDrawable_GetBlendMode(m_ptr));
}
void rotate(float angle)
{
sfDrawable_Rotate(m_ptr, angle);
}
void move(float offsetX, float offsetY)
{
sfDrawable_Move(m_ptr, offsetX, offsetY);
}
void move(Vector2f offset)
{
sfDrawable_Move(m_ptr, offset.x, offset.y);
}
void scale(float scaleX, float scaleY)
{
if (scaleX > 0 && scaleY > 0)
sfDrawable_SetScale(m_ptr, scaleX, scaleY);
}
void scale(Vector2f scale)
{
if (scale.x > 0 && scale.y > 0)
sfDrawable_SetScale(m_ptr, scale.x, scale.y);
}
Vector2f tranformToLocal(Vector2f point)
{
Vector2f ret;
sfDrawable_TransformToLocal(m_ptr, point.x, point.y, &ret.x, &ret.y);
return ret;
}
Vector2f tranformToGlobal(Vector2f point)
{
Vector2f ret;
sfDrawable_TransformToLocal(m_ptr, point.x, point.y, &ret.x, &ret.y);
return ret;
}
void render(RenderWindow window)
{
sfRenderWindow_DrawThis(window.getNativePointer, m_ptr);
}
override void dispose()
{
sfDrawable_Destroy(m_ptr);
}
protected:
this()
{
super(sfDrawable_Create());
}
this(void* ptr)
{
super(ptr);
}
private:
extern (C)
{
typedef void* function() pf_sfDrawable_Create;
typedef void function(void*) pf_sfDrawable_Destroy;
typedef void function(void*, float) pf_sfDrawable_SetX;
typedef void function(void*, float) pf_sfDrawable_SetY;
typedef void function(void*, float, float) pf_sfDrawable_SetPosition;
typedef void function(void*, float) pf_sfDrawable_SetScaleX;
typedef void function(void*, float) pf_sfDrawable_SetScaleY;
typedef void function(void*, float, float) pf_sfDrawable_SetScale;
typedef void function(void*, float) pf_sfDrawable_SetRotation;
typedef void function(void*, float, float) pf_sfDrawable_SetCenter;
typedef void function(void*, Color) pf_sfDrawable_SetColor;
typedef void function(void*, BlendMode) pf_sfDrawable_SetBlendMode;
typedef float function(void*) pf_sfDrawable_GetX;
typedef float function(void*) pf_sfDrawable_GetY;
typedef float function(void*) pf_sfDrawable_GetScaleX;
typedef float function(void*) pf_sfDrawable_GetScaleY;
typedef float function(void*) pf_sfDrawable_GetRotation;
typedef float function(void*) pf_sfDrawable_GetCenterX;
typedef float function(void*) pf_sfDrawable_GetCenterY;
typedef Color function(void*) pf_sfDrawable_GetColor;
typedef BlendMode function(void*) pf_sfDrawable_GetBlendMode;
typedef void function(void*, float, float) pf_sfDrawable_Move;
typedef void function(void*, float, float) pf_sfDrawable_Scale;
typedef void function(void*, float) pf_sfDrawable_Rotate;
typedef void function(void*, float, float, float*, float*) pf_sfDrawable_TransformToLocal;
typedef void function(void*, float, float, float*, float*) pf_sfDrawable_TransformToGlobal;
typedef void function(void*, void*) pf_sfRenderWindow_DrawThis;
static pf_sfDrawable_Create sfDrawable_Create;
static pf_sfDrawable_Destroy sfDrawable_Destroy;
static pf_sfDrawable_SetX sfDrawable_SetX;
static pf_sfDrawable_SetY sfDrawable_SetY;
static pf_sfDrawable_SetPosition sfDrawable_SetPosition;
static pf_sfDrawable_SetScaleX sfDrawable_SetScaleX;
static pf_sfDrawable_SetScaleY sfDrawable_SetScaleY;
static pf_sfDrawable_SetScale sfDrawable_SetScale;
static pf_sfDrawable_SetRotation sfDrawable_SetRotation;
static pf_sfDrawable_SetCenter sfDrawable_SetCenter;
static pf_sfDrawable_SetColor sfDrawable_SetColor;
static pf_sfDrawable_SetBlendMode sfDrawable_SetBlendMode;
static pf_sfDrawable_GetX sfDrawable_GetX;
static pf_sfDrawable_GetY sfDrawable_GetY;
static pf_sfDrawable_GetScaleX sfDrawable_GetScaleX;
static pf_sfDrawable_GetScaleY sfDrawable_GetScaleY;
static pf_sfDrawable_GetRotation sfDrawable_GetRotation;
static pf_sfDrawable_GetCenterX sfDrawable_GetCenterX;
static pf_sfDrawable_GetCenterY sfDrawable_GetCenterY;
static pf_sfDrawable_GetColor sfDrawable_GetColor;
static pf_sfDrawable_GetBlendMode sfDrawable_GetBlendMode;
static pf_sfDrawable_Move sfDrawable_Move;
static pf_sfDrawable_Scale sfDrawable_Scale;
static pf_sfDrawable_Rotate sfDrawable_Rotate;
static pf_sfDrawable_TransformToLocal sfDrawable_TransformToLocal;
static pf_sfDrawable_TransformToGlobal sfDrawable_TransformToGlobal;
static pf_sfRenderWindow_DrawThis sfRenderWindow_DrawThis;
}
static this()
{
DllLoader dll = DllLoader.load("csfml-graphics");
static if (is (T : sfSprite))
{
char[] symbol = "sfSprite";
}
else static if (is (T : sfString))
{
char[] symbol = "sfString";
}
else static if (is (T : sfShape))
{
char[] symbol = "sfShape";
}
sfDrawable_Create = cast(pf_sfDrawable_Create)dll.getSymbol(symbol ~ "_Create");
sfDrawable_Destroy = cast(pf_sfDrawable_Destroy)dll.getSymbol(symbol ~ "_Destroy");
sfDrawable_SetX = cast(pf_sfDrawable_SetX)dll.getSymbol(symbol ~ "_SetX");
sfDrawable_SetY = cast(pf_sfDrawable_SetY)dll.getSymbol(symbol ~ "_SetY");
sfDrawable_SetPosition = cast(pf_sfDrawable_SetPosition)dll.getSymbol(symbol ~ "_SetPosition");
sfDrawable_SetScaleX = cast(pf_sfDrawable_SetScaleX)dll.getSymbol(symbol ~ "_SetScaleX");
sfDrawable_SetScaleY = cast(pf_sfDrawable_SetScaleY)dll.getSymbol(symbol ~ "_SetScaleY");
sfDrawable_SetScale = cast(pf_sfDrawable_SetScale)dll.getSymbol(symbol ~ "_SetScale");
sfDrawable_SetRotation = cast(pf_sfDrawable_SetRotation)dll.getSymbol(symbol ~ "_SetRotation");
sfDrawable_SetCenter = cast(pf_sfDrawable_SetCenter)dll.getSymbol(symbol ~ "_SetCenter");
sfDrawable_SetColor = cast(pf_sfDrawable_SetColor)dll.getSymbol(symbol ~ "_SetColor");
sfDrawable_SetBlendMode = cast(pf_sfDrawable_SetBlendMode)dll.getSymbol(symbol ~ "_SetBlendMode");
sfDrawable_GetX = cast(pf_sfDrawable_GetX)dll.getSymbol(symbol ~ "_GetX");
sfDrawable_GetY = cast(pf_sfDrawable_GetY)dll.getSymbol(symbol ~ "_GetY");
sfDrawable_GetScaleX = cast(pf_sfDrawable_GetScaleX)dll.getSymbol(symbol ~ "_GetScaleX");
sfDrawable_GetScaleY = cast(pf_sfDrawable_GetScaleY)dll.getSymbol(symbol ~ "_GetScaleX");
sfDrawable_GetRotation = cast(pf_sfDrawable_GetRotation)dll.getSymbol(symbol ~ "_GetRotation");
sfDrawable_GetCenterX = cast(pf_sfDrawable_GetCenterX)dll.getSymbol(symbol ~ "_GetCenterX");
sfDrawable_GetCenterY = cast(pf_sfDrawable_GetCenterY)dll.getSymbol(symbol ~ "_GetCenterY");
sfDrawable_GetColor = cast(pf_sfDrawable_GetColor)dll.getSymbol(symbol ~ "_GetColor");
sfDrawable_GetBlendMode = cast(pf_sfDrawable_GetBlendMode)dll.getSymbol(symbol ~ "_GetBlendMode");
sfDrawable_Move = cast(pf_sfDrawable_Move)dll.getSymbol(symbol ~ "_Move");
sfDrawable_Scale = cast(pf_sfDrawable_Scale)dll.getSymbol(symbol ~ "_Scale");
sfDrawable_Rotate = cast(pf_sfDrawable_Rotate)dll.getSymbol(symbol ~ "_Rotate");
sfDrawable_TransformToLocal = cast(pf_sfDrawable_TransformToLocal)dll.getSymbol(symbol ~ "_TransformToLocal");
sfDrawable_TransformToGlobal = cast(pf_sfDrawable_TransformToGlobal)dll.getSymbol(symbol ~ "_TransformToGlobal");
sfRenderWindow_DrawThis = cast(pf_sfRenderWindow_DrawThis)dll.getSymbol("sfRenderWindow_Draw" ~ symbol[2..$]);
}
}

View file

@ -0,0 +1,123 @@
/*
* DSFML - SFML Library binding in D language.
* Copyright (C) 2008 Julien Dagorn (sirjulio13@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.
*/
module dsfml.graphics.font;
import dsfml.system.common;
import dsfml.system.exception;
import dsfml.system.stringutil;
/**
* Font is the low-level class for loading and
* manipulating character fonts.
*/
class Font : DSFMLObject
{
/**
* Get SFML default built-in font (Arial)
*/
static Font getDefaultFont()
{
if (s_default is null)
s_default = new Font(sfFont_GetDefaultFont());
return s_default;
}
/**
* construct the Font from a file
*
* Params:
* filename = font file to load
* charSize = size of characters (30 by default)
* charset = characters set to generate (empty by default - takes the ASCII range [31, 255])
*/
this(char[] filename, uint charSize = 30, dchar[] charset = null)
{
if (filename is null || filename.length == 0)
throw new LoadingException("LoadingException : Filename is invalid.");
super(sfFont_CreateFromFile(toStringz(filename), charSize, toStringz(charset)));
}
/**
* construct the Font from a file in memory
*
* Params:
* data = data to load
* charSize = size of characters (30 by default)
* charset = characters set to generate (empty by default - takes the ASCII range [31, 255])
*/
this(byte[] data, uint charSize = 30, dchar[] charset = null)
{
if (data is null || data.length == 0)
throw new Exception("LoadingException : Memory stream is invalid.");
super(sfFont_CreateFromMemory(data.ptr, data.length, charSize, toStringz(charset)));
}
override void dispose()
{
sfFont_Destroy(m_ptr);
}
package:
this(void* ptr)
{
super(ptr, true);
}
private:
static Font s_default;
extern (C)
{
typedef void* function() pf_sfFont_Create;
typedef void* function(char*, uint, dchar*) pf_sfFont_CreateFromFile;
typedef void* function(byte*, size_t, uint, dchar*) pf_sfFont_CreateFromMemory;
typedef void function(void*) pf_sfFont_Destroy;
typedef void* function() pf_sfFont_GetDefaultFont;
static pf_sfFont_Create sfFont_Create;
static pf_sfFont_CreateFromFile sfFont_CreateFromFile;
static pf_sfFont_CreateFromMemory sfFont_CreateFromMemory;
static pf_sfFont_Destroy sfFont_Destroy;
static pf_sfFont_GetDefaultFont sfFont_GetDefaultFont;
}
static this()
{
DllLoader dll = DllLoader.load("csfml-graphics");
sfFont_Create = cast(pf_sfFont_Create) dll.getSymbol("sfFont_Create");
sfFont_CreateFromFile = cast(pf_sfFont_CreateFromFile) dll.getSymbol("sfFont_CreateFromFile");
sfFont_CreateFromMemory = cast(pf_sfFont_CreateFromMemory) dll.getSymbol("sfFont_CreateFromMemory");
sfFont_Destroy = cast(pf_sfFont_Destroy) dll.getSymbol("sfFont_Destroy");
sfFont_GetDefaultFont = cast(pf_sfFont_GetDefaultFont) dll.getSymbol("sfFont_GetDefaultFont");
}
}

View file

@ -0,0 +1,284 @@
/*
* DSFML - SFML Library binding in D language.
* Copyright (C) 2008 Julien Dagorn (sirjulio13@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.
*/
module dsfml.graphics.idrawable;
import dsfml.system.vector2;
import dsfml.graphics.color;
import dsfml.graphics.blendmode;
import dsfml.graphics.renderwindow;
/**
* Interface for drawable object
*
* Shape, String and Sprite implement IDrawable
*/
interface IDrawable
{
/**
* Set the left position of the object
*
* Params:
* x = New left coordinate
*/
void setX(float x);
/**
* Set the top position of the object
*
* Params:
* y = New top coordinate
*/
void setY(float y);
/**
* Set the position of the object
*
* Params:
* x = New left coordinate
* y = New top coordinate
*/
void setPosition(float x, float y);
/**
* Set the position of the object
*
* Params:
* vec = new position
*/
void setPosition(Vector2f vec);
/**
* Set the horizontal scale of the object
*
* Params:
* scale = New horizontal scale (Strictly positive)
*/
void setScaleX(float scale);
/**
* Set the vertical scale of the object
*
* Params:
* scale = New vertical scale (Strictly positive)
*/
void setScaleY(float scale);
/**
* Set the scale of the object
*
* Params:
* scaleX = New horizontal scale
* scaleY = New vertical scale
*/
void setScale(float scaleX, float scaleY);
/**
* Set the scale of the object
*
* Params:
* scale = new scale
*/
void setScale(Vector2f scale);
/**
* Set the center of the object, in coordinates relative to the
* top-left of the object (take 2 values).
* The default center is (0, 0)
*
* Params:
* centerX : X coordinate of the center
* centerY : Y coordinate of the center
*/
void setCenter(float centerX, float centerY);
/**
* Set the center of the object, in coordinates relative to the
* top-left of the object (take a 2D vector).
* The default center is (0, 0)
*
* Params:
* center : New center
*/
void setCenter(Vector2f center);
/**
* Set the rotation of the object
*
* Params:
* angle = Angle of rotation, in degree
*/
void setRotation(float angle);
/**
* Set the color
*
* Params:
* c = New color
*/
void setColor(Color c);
/**
* Set the blending mode for the object.
* The default blend mode is Blend.Alpha
*
* Params:
* mode = New blending mode
*/
void setBlendMode(BlendMode mode);
/**
* Get the position of the object
*
* Returns:
* Current position
*
*/
Vector2f getPosition();
/**
* Get the current scale of the object
*
* Returns:
* Current scale
*/
Vector2f getScale();
/**
* Get the center of the object
*
* Returns:
* Current position of the center
*
*/
Vector2f getCenter();
/**
* Get the rotation angle of the object
*
* Returns:
* Angle of rotation, in degree
*/
float getRotation();
/**
* Get the color of the string
*
* Returns:
* Current color
*/
Color getColor();
/**
* Get the current blending mode
*
* Returns:
* Current blending mode
*/
BlendMode getBlendMode();
/**
* Rotate the object
* Angle is added to the current orientation of the objet
*
* Params:
* angle = Angle of rotation in degree
*/
void rotate(float angle);
/**
* Move the object
* New offset is added to object current position
*
* Params:
* offsetX = Offset on the X axis
* offsetY = Offset on the Y axis
*/
void move(float offsetX, float offsetY);
/**
* Move the object
* New offset is added to object current position
*
* Params:
* offset = Amount of units to move the object of
*/
void move(Vector2f offset);
/**
* Set the scale of the object
*
* Params:
* scaleX = New horizontal scale (Strictly positive)
* scaleY = New vertical scale (Strictly positive)
*/
void scale(float scaleX, float scaleY);
/**
* Scale the object (take a 2D vector)
*
* Params:
* factor = Scaling factors (both values must be strictly positive)
*/
void scale(Vector2f factor);
/**
* Transform a point from global coordinates into local coordinates
* (ie it applies the inverse of object's center, translation, rotation and scale to the point)
*
* Params:
* point = Point to transform
*
* Returns:
* Transformed point
*/
Vector2f tranformToLocal(Vector2f point);
/**
* Transform a point from local coordinates into global coordinates
* (ie it applies the inverse of object's center, translation, rotation and scale to the point)
*
* Params:
* point = Point to transform
*
* Returns:
* Transformed point
*/
Vector2f tranformToGlobal(Vector2f point);
/**
* Render the specific geometry of the object
*
* Params:
* window = Target into which render the object
*/
void render(RenderWindow window);
}

View file

@ -0,0 +1,366 @@
/*
* DSFML - SFML Library binding in D language.
* Copyright (C) 2008 Julien Dagorn (sirjulio13@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.
*/
/*
* TODO : FIX circular dependency with render window
*/
module dsfml.graphics.image;
import dsfml.graphics.color;
import dsfml.graphics.rect;
import dsfml.system.common;
import dsfml.system.exception;
import dsfml.system.stringutil;
/**
* Image is the low-level class for loading and
* manipulating images
*/
class Image : DSFMLObject
{
/**
* Default constructor
*/
this()
{
super(sfImage_Create());
}
/**
* Construct an empty image
*
* Params:
* width = Image width
* height = Image height
* col = Image color (black by default)
*/
this(uint width, uint height, Color col = Color.BLACK)
{
super(sfImage_CreateFromColor(width, height, col));
}
/**
* Construct the image from a file
*
* Params:
* filename = Path of the image file to load
*
* Throws:
* LoadingException if filename is empty or null.
*/
this(char[] filename)
{
if (filename is null || filename.length == 0)
throw new LoadingException("LoadingException : Filename is invalid.");
super(sfImage_CreateFromFile(toStringz(filename)));
}
/**
* Construct the image from a file in memory
*
* Params:
* data = array of data in memory
* Throws:
* LoadingException if data is empty or null.
*/
this(byte[] data)
{
if (data is null || data.length == 0)
throw new LoadingException("LoadingException : Memory stream is invalid.");
super(sfImage_CreateFromMemory(data.ptr, data.length));
}
/**
* Construct the image directly from an array of pixels
*
* Params:
* width = Image width
* height = Image height
* data = array of pixels in memory (assumed format is RGBA)
*
* Throws:
* LoadingException if data length doesn't match Width * Height * 4
*/
this(uint width, uint height, ubyte[] data)
{
if (width * height * 4 != data.length)
throw new LoadingException("LoadingException : Pixels array length doesn't match the specified size.");
super(sfImage_CreateFromPixels(width, height, data.ptr));
}
override void dispose()
{
sfImage_Destroy(m_ptr);
}
/**
* Save the content of the image to a file
*
* Params:
* filename = Path of the file to save (overwritten if already exist)
*
* Returns:
* True if saving was successful
*/
bool saveToFile(char[] filename)
{
return cast(bool)sfImage_SaveToFile(m_ptr, toStringz(filename));
}
/**
* Create an empty image
*
* Params:
* width = Image width
* height = Image height
* col = Image color (black by default)
*
* Returns:
* True if creation was successful
*/
bool create(uint width, uint height, Color col = Color.BLACK)
{
m_ptr = sfImage_CreateFromColor(width, height, col);
return (m_ptr !is null);
}
/**
* Create transparency mask from a specified colorkey
*
* Params:
* colorKey = Color to become transparent
* alpha = Alpha value to use for transparent pixels (0 by default)
*/
void createMaskFromColor(Color colorKey, ubyte alpha = 0)
{
sfImage_CreateMaskFromColor(m_ptr, colorKey, alpha);
}
// /**
// * Create the image from the current contents of the
// * given window
// *
// * Params:
// * window = Window to capture
// * sourceRect = Sub-rectangle of the screen to copy (empty by default - entire image)
// *
// * Returns:
// * True if copy was successful
// */
// void copyScreen(RenderWindow window, IntRect sourceRect = new IntRect())
// {
// return cast(bool)sfImage_CopyScreen(m_ptr, window.getNativePointer, sourceRect.toCIntRect());
// }
/**
* Copy pixels from another image onto this one.
* This function does a slow pixel copy and should only
* be used at initialization time
*
* Params:
* source = Source image to copy
* destX = X coordinate of the destination position
* destY = Y coordinate of the destination position
* sourceRect = Sub-rectangle of the source image to copy
*/
void copy(Image source, uint destX, uint destY, IntRect sourceRect = new IntRect())
{
sfImage_Copy(m_ptr, source.getNativePointer, destX, destY, sourceRect.toCIntRect());
}
/**
* Change the color of a pixel
* Don't forget to call Update when you end modifying pixels
*
* Params:
* x = X coordinate of pixel in the image
* y = Y coordinate of pixel in the image
* col = New color for pixel (X, Y)
*/
void setPixel(uint x, uint y, Color col)
{
sfImage_SetPixel(m_ptr, x, y, col);
}
/**
* Get a pixel from the image
*
* Params:
* x = X coordinate of pixel in the image
* y = Y coordinate of pixel in the image
*
* Returns:
* Color of pixel (x, y)
*/
Color getPixel(uint x, uint y)
{
return sfImage_GetPixel(m_ptr, x, y);
}
/**
* Get an array of pixels (8 bits integers RGBA)
* Array size is GetWidth() x GetHeight() x 4
* This array becomes invalid if you reload or resize the image
*
* Returns:
* array of pixels
*/
ubyte[] getPixelsArray()
{
return sfImage_GetPixelsPtr(m_ptr)[0..getWidth() * getHeight() * 4];
}
/**
* Bind the image for rendering
*/
void bind()
{
sfImage_Bind(m_ptr);
}
/**
* Enable or disable image smooth filter.
* This parameter is enabled by default
*
* Params:
* smooth = True to enable smoothing filter, false to disable it
*/
void setSmooth(bool smooth)
{
sfImage_SetSmooth(m_ptr, smooth);
}
/**
* Return the width of the image
*
* Returns:
* Width in pixels
*/
uint getWidth()
{
return sfImage_GetWidth(m_ptr);
}
/**
* Return the height of the image
*
* Returns:
* Height in pixels
*/
uint getHeight()
{
return sfImage_GetHeight(m_ptr);
}
/**
* Tells whether the smooth filtering is enabled or not
*
* Returns:
* True if image smoothing is enabled
*/
bool isSmooth()
{
return cast(bool)sfImage_IsSmooth(m_ptr);
}
package:
this(void* ptr)
{
super(ptr);
}
private:
extern (C)
{
typedef void* function() pf_sfImage_Create;
typedef void* function(uint, uint, Color) pf_sfImage_CreateFromColor;
typedef void* function(uint, uint, ubyte*) pf_sfImage_CreateFromPixels;
typedef void* function(char*) pf_sfImage_CreateFromFile;
typedef void* function(byte* ,size_t) pf_sfImage_CreateFromMemory;
typedef void function(void*) pf_sfImage_Destroy;
typedef int function(void*, char*) pf_sfImage_SaveToFile;
typedef void function(void*, Color, ubyte) pf_sfImage_CreateMaskFromColor;
typedef int function(void*, void*, sfIntRect) pf_sfImage_CopyScreen;
typedef void function(void*, void*, uint, uint, sfIntRect) pf_sfImage_Copy;
typedef void function(void*, uint, uint, Color) pf_sfImage_SetPixel;
typedef Color function(void*, uint, uint) pf_sfImage_GetPixel;
typedef ubyte* function(void*) pf_sfImage_GetPixelsPtr;
typedef void function(void*) pf_sfImage_Bind;
typedef void function(void*, int) pf_sfImage_SetSmooth;
typedef uint function(void*) pf_sfImage_GetWidth;
typedef uint function(void*) pf_sfImage_GetHeight;
typedef int function(void*) pf_sfImage_IsSmooth;
static pf_sfImage_Create sfImage_Create;
static pf_sfImage_CreateFromColor sfImage_CreateFromColor;
static pf_sfImage_CreateFromPixels sfImage_CreateFromPixels;
static pf_sfImage_CreateFromFile sfImage_CreateFromFile;
static pf_sfImage_CreateFromMemory sfImage_CreateFromMemory;
static pf_sfImage_Destroy sfImage_Destroy;
static pf_sfImage_SaveToFile sfImage_SaveToFile;
static pf_sfImage_CreateMaskFromColor sfImage_CreateMaskFromColor;
static pf_sfImage_CopyScreen sfImage_CopyScreen;
static pf_sfImage_Copy sfImage_Copy;
static pf_sfImage_SetPixel sfImage_SetPixel;
static pf_sfImage_GetPixel sfImage_GetPixel;
static pf_sfImage_GetPixelsPtr sfImage_GetPixelsPtr;
static pf_sfImage_Bind sfImage_Bind;
static pf_sfImage_SetSmooth sfImage_SetSmooth;
static pf_sfImage_GetWidth sfImage_GetWidth;
static pf_sfImage_GetHeight sfImage_GetHeight;
static pf_sfImage_IsSmooth sfImage_IsSmooth;
}
static this()
{
DllLoader dll = DllLoader.load("csfml-graphics");
sfImage_Create = cast(pf_sfImage_Create)dll.getSymbol("sfImage_Create");
sfImage_CreateFromColor = cast(pf_sfImage_CreateFromColor)dll.getSymbol("sfImage_CreateFromColor");
sfImage_CreateFromPixels = cast(pf_sfImage_CreateFromPixels)dll.getSymbol("sfImage_CreateFromPixels");
sfImage_CreateFromFile = cast(pf_sfImage_CreateFromFile)dll.getSymbol("sfImage_CreateFromFile");
sfImage_CreateFromMemory = cast(pf_sfImage_CreateFromMemory)dll.getSymbol("sfImage_CreateFromMemory");
sfImage_Destroy = cast(pf_sfImage_Destroy)dll.getSymbol("sfImage_Destroy");
sfImage_SaveToFile = cast(pf_sfImage_SaveToFile)dll.getSymbol("sfImage_SaveToFile");
sfImage_CreateMaskFromColor = cast(pf_sfImage_CreateMaskFromColor)dll.getSymbol("sfImage_CreateMaskFromColor");
sfImage_CopyScreen = cast(pf_sfImage_CopyScreen)dll.getSymbol("sfImage_CopyScreen");
sfImage_Copy = cast(pf_sfImage_Copy)dll.getSymbol("sfImage_Copy");
sfImage_SetPixel = cast(pf_sfImage_SetPixel)dll.getSymbol("sfImage_SetPixel");
sfImage_GetPixel = cast(pf_sfImage_GetPixel)dll.getSymbol("sfImage_GetPixel");
sfImage_GetPixelsPtr = cast(pf_sfImage_GetPixelsPtr)dll.getSymbol("sfImage_GetPixelsPtr");
sfImage_Bind = cast(pf_sfImage_Bind)dll.getSymbol("sfImage_Bind");
sfImage_SetSmooth = cast(pf_sfImage_SetSmooth)dll.getSymbol("sfImage_SetSmooth");
sfImage_GetWidth = cast(pf_sfImage_GetWidth)dll.getSymbol("sfImage_GetWidth");
sfImage_GetHeight = cast(pf_sfImage_GetHeight)dll.getSymbol("sfImage_GetHeight");
sfImage_IsSmooth = cast(pf_sfImage_IsSmooth)dll.getSymbol("sfImage_IsSmooth");
}
}

View file

@ -0,0 +1,175 @@
/*
* DSFML - SFML Library binding in D language.
* Copyright (C) 2008 Julien Dagorn (sirjulio13@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.
*/
module dsfml.graphics.postfx;
import dsfml.graphics.image;
import dsfml.system.common;
import dsfml.system.exception;
import dsfml.system.stringutil;
/**
* Define loading methods for effect
*/
enum LoadingType
{
FROMFILE, /// string represents a file path
FROMSTRING /// string represents effect code
}
/**
* PostFX is used to apply a post effect to a window
*
* See_Also:
* $(LINK2 http://www.sfml-dev.org/tutorials/graphics-postfx.php, SFML post FX tutorial) from more informations about Post effects and GLSL fragment shaders syntax.
*/
class PostFX : DSFMLObject
{
/**
* construct the effect
*
* Params:
* effect = Path of a file or string containing the effect.
* type = type of the effect (default is FROMFILE)
*/
this(char[] effect, LoadingType type = LoadingType.FROMFILE)
{
if (effect is null || effect.length == 0)
throw new LoadingException("LoadingException : Effect is invalid.");
if (type == LoadingType.FROMFILE)
super(sfPostFX_CreateFromFile(toStringz(effect)));
else
super(sfPostFX_CreateFromMemory(toStringz(effect)));
}
override void dispose()
{
sfPostFX_Destroy(m_ptr);
}
/**
* Change parameters of the effect
*
* Params:
* name = Parameter name in the effect
*/
void setParameter(char[] name, float x)
{
sfPostFX_SetParameter1(m_ptr, toStringz(name), x);
}
/**
* ditto
*/
void setParameter(char[] name, float x, float y)
{
sfPostFX_SetParameter2(m_ptr, toStringz(name), x, y);
}
/**
* ditto
*/
void setParameter(char[] name, float x, float y, float z)
{
sfPostFX_SetParameter3(m_ptr, toStringz(name), x, y, z);
}
/**
* ditto
*/
void setParameter(char[] name, float x, float y, float z, float w)
{
sfPostFX_SetParameter4(m_ptr, toStringz(name), x, y, z, w);
}
/**
* Set a texture parameter
*
* Params:
* name = Texture name in the effect
* texture = Image to set (pass NULL to use content of current framebuffer)
*/
void setTexture(char[] name, Image texture)
{
m_texture = texture;
sfPostFX_SetTexture(m_ptr, toStringz(name), texture is null ? null : texture.getNativePointer);
}
/**
* Tell whether or not the system supports post-effects
*
* Returns:
* True if the system can use post-effects
*/
static bool canUsePostFX()
{
return cast(bool)sfPostFX_CanUsePostFX();
}
private:
Image m_texture;
extern (C)
{
typedef void* function(char*) pf_sfPostFX_CreateFromFile;
typedef void* function(char*) pf_sfPostFX_CreateFromMemory;
typedef void function(void*) pf_sfPostFX_Destroy;
typedef void function(void*, char*, float) pf_sfPostFX_SetParameter1;
typedef void function(void*, char*, float, float) pf_sfPostFX_SetParameter2;
typedef void function(void*, char*, float, float, float) pf_sfPostFX_SetParameter3;
typedef void function(void*, char*, float, float, float, float) pf_sfPostFX_SetParameter4;
typedef void function(void*, char*, void*) pf_sfPostFX_SetTexture;
typedef int function() pf_sfPostFX_CanUsePostFX;
static pf_sfPostFX_CreateFromFile sfPostFX_CreateFromFile;
static pf_sfPostFX_CreateFromMemory sfPostFX_CreateFromMemory;
static pf_sfPostFX_Destroy sfPostFX_Destroy;
static pf_sfPostFX_SetParameter1 sfPostFX_SetParameter1;
static pf_sfPostFX_SetParameter2 sfPostFX_SetParameter2;
static pf_sfPostFX_SetParameter3 sfPostFX_SetParameter3;
static pf_sfPostFX_SetParameter4 sfPostFX_SetParameter4;
static pf_sfPostFX_SetTexture sfPostFX_SetTexture;
static pf_sfPostFX_CanUsePostFX sfPostFX_CanUsePostFX;
}
static this()
{
DllLoader dll = DllLoader.load("csfml-graphics");
sfPostFX_CreateFromFile = cast(pf_sfPostFX_CreateFromFile)dll.getSymbol("sfPostFX_CreateFromFile");
sfPostFX_CreateFromMemory = cast(pf_sfPostFX_CreateFromMemory)dll.getSymbol("sfPostFX_CreateFromMemory");
sfPostFX_Destroy = cast(pf_sfPostFX_Destroy)dll.getSymbol("sfPostFX_Destroy");
sfPostFX_SetParameter1 = cast(pf_sfPostFX_SetParameter1)dll.getSymbol("sfPostFX_SetParameter1");
sfPostFX_SetParameter2 = cast(pf_sfPostFX_SetParameter2)dll.getSymbol("sfPostFX_SetParameter2");
sfPostFX_SetParameter3 = cast(pf_sfPostFX_SetParameter3)dll.getSymbol("sfPostFX_SetParameter3");
sfPostFX_SetParameter4 = cast(pf_sfPostFX_SetParameter4)dll.getSymbol("sfPostFX_SetParameter4");
sfPostFX_SetTexture = cast(pf_sfPostFX_SetTexture)dll.getSymbol("sfPostFX_SetTexture");
sfPostFX_CanUsePostFX = cast(pf_sfPostFX_CanUsePostFX)dll.getSymbol("sfPostFX_CanUsePostFX");
}
}

View file

@ -0,0 +1,291 @@
/*
* DSFML - SFML Library binding in D language.
* Copyright (C) 2008 Julien Dagorn (sirjulio13@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.
*/
module dsfml.graphics.rect;
struct sfFloatRect
{
float Left;
float Top;
float Right;
float Bottom;
}
struct sfIntRect
{
int Left;
int Top;
int Right;
int Bottom;
}
version (Tango)
{
import tango.core.Traits;
}
else
{
template isIntegerType(T)
{
const bool isIntegerType =
is (T == byte) ||
is (T == short) ||
is (T == int) ||
is (T == long);
}
template isRealType(T)
{
const bool isRealType =
is (T == float) ||
is (T == double) ||
is (T == real);
}
}
/**
* Rect is an utility class for manipulating rectangles.
* Template parameter defines the type of coordinates (integer float, ...)
*/
class Rect (T)
{
static if (!isIntegerType!(T) && !isRealType!(T))
{
static assert (0, "This type is not supported by Rectangle");
}
T min(T)(T i, T j)
{
return i < j ? i : j;
}
T max(T)(T i, T j)
{
return i > j ? i : j;
}
/**
* Default constructor
*/
this()
{
m_Left = 0;
m_Top = 0;
m_Right = 0;
m_Bottom = 0;
}
/**
* Construct the rectangle from its coordinates
*
* Params:
* leftCoord = Left coordinate of the rectangle
* topCoord = Top coordinate of the rectangle
* rightCoord = Right coordinate of the rectangle
* bottomCoord = Bottom coordinate of the rectangle
*/
this(T leftCoord, T topCoord, T rightCoord, T bottomCoord)
{
m_Left = leftCoord;
m_Top = topCoord;
m_Right = rightCoord;
m_Bottom = bottomCoord;
}
/**
* Get the width of the rectangle
*
* Returns:
* Width of rectangle
*/
T getWidth()
{
return m_Right - m_Left;
}
/**
* Get the height of the rectangle
*
* Returns:
* Height of rectangle
*/
T getHeight()
{
return m_Bottom - m_Top;
}
/**
* Move the whole rectangle by the given offset
*
* Params:
* offsetX = Horizontal offset
* offsetY = Vertical offset
*/
void offset(T offsetX, T offsetY)
{
m_Left += offsetX;
m_Right += offsetX;
m_Top += offsetY;
m_Bottom += offsetY;
}
/**
* Check if a point is inside the rectangle's area
*
* Params:
* x = X coordinate of the point to test
* y = Y coordinate of the point to test
*
* Returns:
* True if the point is inside
*/
bool contains(T x, T y)
{
return (x >= m_Left) && (x <= m_Right) && (y >= m_Top) && (y <= m_Bottom);
}
/**
* Check intersection between two rectangles
*
* Params:
* rectangle = Rectangle to test
* overlappingRect = Rectangle to be filled with overlapping rect (NULL by default)
*
* Returns:
* True if rectangles overlap
*/
bool intersects(Rect!(T) rectangle, out Rect!(T) overlappingRect = null)
{
// Compute overlapping rect
Rect!(T) overlapping = new Rect!(T)(
max(m_Left, rectangle.getLeft),
max(m_Top, rectangle.getTop),
min(m_Right, rectangle.getRight),
min(m_Bottom, rectangle.getBottom)
);
// If overlapping rect is valid, then there is intersection
if ((overlapping.getLeft() < overlapping.getRight() ) && (overlapping.getTop() < overlapping.getBottom()))
{
overlappingRect = overlapping;
return true;
}
else
{
overlappingRect = new Rect!(T)();
return false;
}
}
/**
* Set left Coordinate
*/
void setLeft(T left)
{
m_Left = left;
}
/**
* Set top Coordinate
*/
void setTop(T top)
{
m_Top = top;
}
/**
* Set right Coordinate
*/
void setRight(T right)
{
m_Right = right;
}
/**
* Set bottom Coordinate
*/
void setBottom(T bottom)
{
m_Bottom = bottom;
}
/**
* Get left Coordinate
*/
T getLeft()
{
return m_Left;
}
/**
* Get top Coordinate
*/
T getTop()
{
return m_Top;
}
/**
* Get right Coordinate
*/
T getRight()
{
return m_Right;
}
/**
* Get bottom Coordinate
*/
T getBottom()
{
return m_Bottom;
}
package:
sfFloatRect toCFloatRect()
{
return sfFloatRect(m_Left, m_Top, m_Right, m_Bottom);
}
sfIntRect toCIntRect()
{
return sfIntRect(cast(int)m_Left, cast(int)m_Top, cast(int)m_Right, cast(int)m_Bottom);
}
private:
T m_Left; // Left coordinate of the rectangle
T m_Top; // Top coordinate of the rectangle
T m_Right; // Right coordinate of the rectangle
T m_Bottom; // Bottom coordinate of the rectangle
}
///Alias
alias Rect!(int) IntRect;
///ditto
alias Rect!(float) FloatRect;

View file

@ -0,0 +1,306 @@
/*
* DSFML - SFML Library binding in D language.
* Copyright (C) 2008 Julien Dagorn (sirjulio13@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.
*/
module dsfml.graphics.renderwindow;
import dsfml.graphics.color;
import dsfml.graphics.idrawable;
import dsfml.graphics.image;
import dsfml.graphics.rect;
import dsfml.graphics.postfx;
import dsfml.graphics.view;
import dsfml.window.event;
import dsfml.window.input;
import dsfml.window.videomode;
import dsfml.window.window;
import dsfml.window.windowhandle;
import dsfml.window.windowsettings;
import dsfml.window.windowstyle;
import dsfml.system.common;
import dsfml.system.stringutil;
import dsfml.system.vector2;
/**
* Simple wrapper for Window that allows easy 2D rendering.
*/
class RenderWindow : Window
{
/**
* Construct the window
*
* Params:
* mode = Video mode to use
* title = Title of the window
* windowStyle = Window style (Resize | Close by default)
* settings = Window settings (default is default WindowSettings values)
*/
this(VideoMode mode, in char[] title, ulong windowStyle = Style.RESIZE | Style.CLOSE, WindowSettings settings = WindowSettings())
{
super(sfRenderWindow_Create(mode, toStringz(title), windowStyle, settings));
m_input = new Input(sfRenderWindow_GetInput(m_ptr));
}
/**
* Construct the window from an existing control
*
* Params:
* handle = Platform-specific handle of the control
* settings = Window settings (default is default WindowSettings values)
*/
this(WindowHandle handle, WindowSettings settings = WindowSettings())
{
super(sfRenderWindow_CreateFromHandle(handle, settings));
m_input = new Input(sfRenderWindow_GetInput(m_ptr));
}
override void dispose()
{
sfRenderWindow_Destroy(m_ptr);
}
/**
* Create (or recreate) the window
*
* Input created with getInput will become invalid.
*
* Params:
* mode = Video mode to use
* title = Title of the window
* windowStyle = Window style (Resize | Close by default)
* settings = Window settings (default is default WindowSettings values)
*
*/
void create(VideoMode mode, char[] title, ulong windowStyle = Style.RESIZE | Style.CLOSE, WindowSettings settings = WindowSettings())
{
if (m_ptr !is null)
dispose();
m_ptr = sfRenderWindow_Create(mode, toStringz(title), windowStyle, settings);
m_input = new Input(sfRenderWindow_GetInput(m_ptr));
}
/**
* Create (or recreate) the window from an existing control
*
* Input created with getInput become invalid.
*
* Params:
* handle = Platform-specific handle of the control
* settings = Window settings (default is default WindowSettings values)
*
*/
void create(WindowHandle handle, WindowSettings settings = WindowSettings())
{
if (m_ptr !is null)
dispose();
m_ptr = sfRenderWindow_CreateFromHandle(handle, settings);
m_input = new Input(sfRenderWindow_GetInput(m_ptr));
}
/**
* Draw a PostFX on the window
*
* Params:
* postFX = PostFX to draw
*/
void draw(PostFX postFX)
{
sfRenderWindow_DrawPostFX(m_ptr, postFX.getNativePointer);
}
/**
* Draw a Sprite or a String
*
* Params:
* obj = IDrawable object to draw
*/
void draw(IDrawable obj)
{
obj.render(this);
}
/**
* Save the content of the window to an image
*
* Returns:
* Image instance containing the contents of the screen
*/
Image capture()
{
return new Image(sfRenderWindow_Capture(m_ptr));
}
/**
* Clear the screen with the given color.
*
* Params:
* col = Fill color
*/
void clear(Color col = Color.BLACK)
{
sfRenderWindow_Clear(m_ptr, col);
}
/**
* Change the current active view.
* The current view is defined with the initial size of the window
*
* Params:
* newView = Pointer to the new view (pass getDefaultView to set the default view)
*/
void setView(View newView)
{
if (m_view !is null)
{
m_view.setHandled(false);
}
sfRenderWindow_SetView(m_ptr, newView.getNativePointer);
m_view = newView;
m_view.setHandled(true);
}
/**
* Get the current view rectangle
*
* Returns:
* current view rectangle, in global coordinates
*/
View getView()
{
if (m_view is null)
{
void* cView = sfRenderWindow_GetView(m_ptr);
m_view = new View(cView, true);
}
return m_view;
}
/**
* Get the default view
*
* Returns:
* default view
*/
View getDefaultView()
{
if (m_defaultView is null)
{
void* cView = sfRenderWindow_GetDefaultView(m_ptr);
m_defaultView = new View(cView, true);
}
return m_defaultView;
}
/**
* Convert a point in window coordinates into view coordinates
*
* Params:
* windowX = X coordinate of the point to convert, relative to the window
* windowY = Y coordinate of the point to convert, relative to the window
* targetView = Target view to convert the point to (pass NULL to use the current view)
*
* Returns:
* Converted point
*/
Vector2f convertCoords(uint windowX, uint windowY, View targetView = null)
{
Vector2f vec;
sfRenderWindow_ConvertCoords(m_ptr, windowX, windowY, &vec.x, &vec.y, targetView is null ? null : targetView.getNativePointer);
return vec;
}
/**
* Tell SFML to preserve external OpenGL states, at the expense of
* more CPU charge. Use this function if you don't want SFML
* to mess up your own OpenGL states (if any).
* Don't enable state preservation if not needed, as it will allow
* SFML to do internal optimizations and improve performances.
* This parameter is false by default
*
* Params:
* preserve = True to preserve OpenGL states, false to let SFML optimize
*
*/
void preserveOpenGLStates(bool preserve)
{
sfRenderWindow_PreserveOpenGLStates(m_ptr, preserve);
}
private:
View m_view = null;
View m_defaultView = null;
extern (C)
{
typedef void* function(VideoMode, char*, uint, WindowSettings) pf_sfRenderWindow_Create;
typedef void* function(WindowHandle, WindowSettings) pf_sfRenderWindow_CreateFromHandle;
typedef void function(void*) pf_sfRenderWindow_Destroy;
typedef void* function(void*) pf_sfRenderWindow_GetInput;
typedef void function(void*, void*) pf_sfRenderWindow_DrawPostFX;
typedef void* function(void*) pf_sfRenderWindow_Capture;
typedef void function(void*, Color) pf_sfRenderWindow_Clear;
typedef void function(void*, void*) pf_sfRenderWindow_SetView;
typedef void* function(void*) pf_sfRenderWindow_GetView;
typedef void* function (void*) pf_sfRenderWindow_GetDefaultView;
typedef void function(void*, uint, uint, float*, float*, void*) pf_sfRenderWindow_ConvertCoords;
typedef void function(void*, int) pf_sfRenderWindow_PreserveOpenGLStates;
static pf_sfRenderWindow_Create sfRenderWindow_Create;
static pf_sfRenderWindow_CreateFromHandle sfRenderWindow_CreateFromHandle;
static pf_sfRenderWindow_Destroy sfRenderWindow_Destroy;
static pf_sfRenderWindow_GetInput sfRenderWindow_GetInput;
static pf_sfRenderWindow_DrawPostFX sfRenderWindow_DrawPostFX;
static pf_sfRenderWindow_Capture sfRenderWindow_Capture;
static pf_sfRenderWindow_Clear sfRenderWindow_Clear;
static pf_sfRenderWindow_SetView sfRenderWindow_SetView;
static pf_sfRenderWindow_GetView sfRenderWindow_GetView;
static pf_sfRenderWindow_GetDefaultView sfRenderWindow_GetDefaultView;
static pf_sfRenderWindow_ConvertCoords sfRenderWindow_ConvertCoords;
static pf_sfRenderWindow_PreserveOpenGLStates sfRenderWindow_PreserveOpenGLStates;
}
static this()
{
DllLoader dll = DllLoader.load("csfml-graphics");
sfRenderWindow_Create = cast(pf_sfRenderWindow_Create)dll.getSymbol("sfRenderWindow_Create");
sfRenderWindow_CreateFromHandle = cast(pf_sfRenderWindow_CreateFromHandle)dll.getSymbol("sfRenderWindow_CreateFromHandle");
sfRenderWindow_Destroy = cast(pf_sfRenderWindow_Destroy)dll.getSymbol("sfRenderWindow_Destroy");
sfRenderWindow_GetInput = cast(pf_sfRenderWindow_GetInput)dll.getSymbol("sfRenderWindow_GetInput");
sfRenderWindow_DrawPostFX = cast(pf_sfRenderWindow_DrawPostFX)dll.getSymbol("sfRenderWindow_DrawPostFX");
sfRenderWindow_Capture = cast(pf_sfRenderWindow_Capture)dll.getSymbol("sfRenderWindow_Capture");
sfRenderWindow_Clear = cast(pf_sfRenderWindow_Clear)dll.getSymbol("sfRenderWindow_Clear");
sfRenderWindow_SetView = cast(pf_sfRenderWindow_SetView)dll.getSymbol("sfRenderWindow_SetView");
sfRenderWindow_GetView = cast(pf_sfRenderWindow_GetView)dll.getSymbol("sfRenderWindow_GetView");
sfRenderWindow_GetDefaultView = cast(pf_sfRenderWindow_GetDefaultView)dll.getSymbol("sfRenderWindow_GetDefaultView");
sfRenderWindow_ConvertCoords = cast(pf_sfRenderWindow_ConvertCoords)dll.getSymbol("sfRenderWindow_ConvertCoords");
sfRenderWindow_PreserveOpenGLStates = cast(pf_sfRenderWindow_PreserveOpenGLStates)dll.getSymbol("sfRenderWindow_PreserveOpenGLStates");
}
}

View file

@ -0,0 +1,333 @@
/*
* DSFML - SFML Library binding in D language.
* Copyright (C) 2008 Julien Dagorn (sirjulio13@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.
*/
module dsfml.graphics.shape;
import dsfml.system.vector2;
import dsfml.graphics.blendmode;
import dsfml.graphics.color;
import dsfml.graphics.drawableimpl;
/**
* Shape defines a drawable convex shape ; it also defines
* helper functions to draw simple shapes like
* lines, rectangles, circles, etc.
*/
class Shape : Drawableimpl!(sfShape)
{
this()
{
super();
}
/**
* Add a point to the shape
*
* Params:
* x = X position of the point
* y = Y position of the point
* col = Color of the point (white by default)
* outlineCol = Outline color of the point (black by default)
*/
void addPoint(float x, float y, Color col = Color.WHITE, Color outlineCol = Color.BLACK)
{
sfShape_AddPoint(m_ptr, x, y, col, outlineCol);
}
/**
* Add a point to the shape
*
* Params:
* position = position of the point
* col = Color of the point (white by default)
* outlineCol = Outline color of the point (black by default)
*/
void addPoint(Vector2f position, Color col = Color.WHITE, Color outlineCol = Color.BLACK)
{
sfShape_AddPoint(m_ptr, position.x, position.x, col, outlineCol);
}
/**
* Enable or disable filling the shape.
* Fill is enabled by default.
*
* Params:
* enable = True to enable, false to disable
*/
void enableFill(bool enable)
{
sfShape_EnableFill(m_ptr, enable);
}
/**
* Enable or disable drawing a shape outline.
* Outline is enabled by default
*
* Params:
* enable = True to enable, false to disable
*/
void enableOutline(bool enable)
{
sfShape_EnableOutline(m_ptr, enable);
}
/**
* Change the width of a shape outline
*
* Params:
* width = New width
*/
void setOutlineWidth(float width)
{
sfShape_SetOutlineWidth(m_ptr, width);
}
/**
* Get the width of the shape outline
*
* Returns:
* Current outline width
*
*/
float getOutlineWidth()
{
return sfShape_GetOutlineWidth(m_ptr);
}
/**
* Get the number of points composing a shape
*
* Returns:
* Total number of points
*/
uint getNbPoints()
{
return sfShape_GetNbPoints(m_ptr);
}
/**
* Get a point of the shape
*
* Params:
* index = Index of the point
*
* Returns:
* position of the point
*/
Vector2f getPointPosition(uint index)
{
float x, y;
sfShape_GetPointPosition(m_ptr, index, &x, &y);
return Vector2f(x, y);
}
/**
* Set the position of a shape point
*
* Params:
* index = Index of the point
* position = New position of the point
*/
void setPointPosition(uint index, Vector2f position)
{
sfShape_SetPointPosition(m_ptr, index, position.x, position.y);
}
/**
* Get the color of a shape's point
*
* Params:
* index = Index of the point
*
* Returns:
* Color of the point
*/
Color getPointColor(uint index)
{
return sfShape_GetPointColor(m_ptr, index);
}
/**
* Set the color of a shape's point
*
* Params:
* index = Index of the point
* color = new color of the point
*/
void setPointColor(uint index, Color color)
{
sfShape_SetPointColor(m_ptr, index, color);
}
/**
* Get the outline color of a shape's point
*
* Params:
* index = Index of the point
*
* Returns:
* Color of the outline
*/
Color getPointOutlineColor(uint index)
{
return sfShape_GetPointOutlineColor(m_ptr, index);
}
/**
* Set the outline color of a shape's point
*
* Params:
* index = Index of the point
* color = new color of the point
*/
void setPointOutlineColor(uint index, Color color)
{
sfShape_SetPointOutlineColor(m_ptr, index, color);
}
/**
* Create a shape made of a single line
*
* Params:
* p1X, p1Y = Position of the first point
* p2X, p2Y = Position second point
* thickness = Line thickness
* col = Color used to draw the line
* outline = Outline width (0 by default)
* outlineCol = Color used to draw the outline (black by default)
*
* Returns:
* New line shape
*/
static Shape line(float p1X, float p1Y, float p2X, float p2Y, float thickness, Color col, float outline = 0.f, Color outlineCol = Color.BLACK)
{
return new Shape(sfShape_CreateLine(p1X, p1Y, p2X, p2Y, thickness, col, outline, outlineCol));
}
/**
* Create a shape made of a single rectangle
*
* Params:
* p1X = X position of the first point
* p1Y = Y position of the first point
* p2X = X position second point
* p2Y = Y position second point
* col = Color used to fill the rectangle
* outline = Outline width (0 by default)
* outlineCol = Color used to draw the outline (black by default)
*
* Returns:
* new rectangle shape
*/
static Shape rectangle(float p1X, float p1Y, float p2X, float p2Y, Color col, float outline = 0.f, Color outlineCol = Color.BLACK)
{
return new Shape(sfShape_CreateRectangle(p1X, p1Y, p2X, p2Y, col, outline, outlineCol));
}
/**
* Create a shape made of a single circle
*
* Params:
* x = X position of the center
* y = Y position of the center
* radius = Radius
* col = Color used to fill the circle
* outline = Outline width (0 by default)
* outlineCol = Color used to draw the outline (black by default)
*
* Returns:
* new circle shape
*/
static Shape circle(float x, float y, float radius, Color col, float outline = 0.f, Color outlineCol = Color.BLACK)
{
return new Shape(sfShape_CreateCircle(x, y, radius, col, outline, outlineCol));
}
private:
this (void* ptr)
{
super(ptr);
}
extern (C)
{
typedef void* function(float, float, float, float, float, Color, float, Color) pf_sfShape_CreateLine;
typedef void* function(float, float, float, float, Color, float, Color) pf_sfShape_CreateRectangle;
typedef void* function(float, float, float, Color, float, Color) pf_sfShape_CreateCircle;
typedef void function(void* Shape, float, float, Color, Color) pf_sfShape_AddPoint;
typedef void function(void* Shape, int) pf_sfShape_EnableFill;
typedef void function(void* Shape, int) pf_sfShape_EnableOutline;
typedef void function (void* Shape, float Width) pf_sfShape_SetOutlineWidth;
typedef float function (void* Shape) pf_sfShape_GetOutlineWidth;
typedef uint function (void* Shape) pf_sfShape_GetNbPoints;
typedef void function (void* Shape, uint Index, float* X, float* Y) pf_sfShape_GetPointPosition;
typedef void function (void* Shape, uint Index, float X, float Y) pf_sfShape_SetPointPosition;
typedef Color function (void* Shape, uint index) pf_sfShape_GetPointColor;
typedef void function (void* Shape, uint index, Color color) pf_sfShape_SetPointColor;
typedef Color function (void* Shape, uint index) pf_sfShape_GetPointOutlineColor;
typedef void function (void* Shape, uint index, Color color) pf_sfShape_SetPointOutlineColor;
static pf_sfShape_CreateLine sfShape_CreateLine;
static pf_sfShape_CreateRectangle sfShape_CreateRectangle;
static pf_sfShape_CreateCircle sfShape_CreateCircle;
static pf_sfShape_AddPoint sfShape_AddPoint;
static pf_sfShape_EnableFill sfShape_EnableFill;
static pf_sfShape_EnableOutline sfShape_EnableOutline;
static pf_sfShape_SetOutlineWidth sfShape_SetOutlineWidth;
static pf_sfShape_GetOutlineWidth sfShape_GetOutlineWidth;
static pf_sfShape_GetNbPoints sfShape_GetNbPoints;
static pf_sfShape_GetPointPosition sfShape_GetPointPosition;
static pf_sfShape_SetPointPosition sfShape_SetPointPosition;
static pf_sfShape_GetPointColor sfShape_GetPointColor;
static pf_sfShape_SetPointColor sfShape_SetPointColor;
static pf_sfShape_GetPointOutlineColor sfShape_GetPointOutlineColor;
static pf_sfShape_SetPointOutlineColor sfShape_SetPointOutlineColor;
}
static this()
{
DllLoader dll = DllLoader.load("csfml-graphics");
sfShape_CreateLine = cast(pf_sfShape_CreateLine)dll.getSymbol("sfShape_CreateLine");
sfShape_CreateRectangle = cast(pf_sfShape_CreateRectangle)dll.getSymbol("sfShape_CreateRectangle");
sfShape_CreateCircle = cast(pf_sfShape_CreateCircle)dll.getSymbol("sfShape_CreateCircle");
sfShape_AddPoint = cast(pf_sfShape_AddPoint)dll.getSymbol("sfShape_AddPoint");
sfShape_EnableFill = cast(pf_sfShape_EnableFill)dll.getSymbol("sfShape_EnableFill");
sfShape_EnableOutline = cast(pf_sfShape_EnableOutline)dll.getSymbol("sfShape_EnableOutline");
sfShape_SetOutlineWidth = cast(pf_sfShape_SetOutlineWidth)dll.getSymbol("sfShape_SetOutlineWidth");
sfShape_GetOutlineWidth = cast(pf_sfShape_GetOutlineWidth)dll.getSymbol("sfShape_GetOutlineWidth");
sfShape_GetNbPoints = cast(pf_sfShape_GetNbPoints)dll.getSymbol("sfShape_GetNbPoints");
sfShape_GetPointPosition = cast(pf_sfShape_GetPointPosition)dll.getSymbol("sfShape_GetPointPosition");
sfShape_SetPointPosition = cast(pf_sfShape_SetPointPosition)dll.getSymbol("sfShape_SetPointPosition");
sfShape_GetPointColor = cast (pf_sfShape_GetPointColor)dll.getSymbol("sfShape_GetPointColor");
sfShape_SetPointColor = cast (pf_sfShape_SetPointColor)dll.getSymbol("sfShape_SetPointColor");
sfShape_GetPointOutlineColor = cast(pf_sfShape_GetPointOutlineColor)dll.getSymbol("sfShape_GetPointOutlineColor");
sfShape_SetPointOutlineColor = cast(pf_sfShape_SetPointOutlineColor)dll.getSymbol("sfShape_SetPointOutlineColor");
}
}

View file

@ -0,0 +1,248 @@
/*
* DSFML - SFML Library binding in D language.
* Copyright (C) 2008 Julien Dagorn (sirjulio13@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.
*/
module dsfml.graphics.sprite;
import dsfml.graphics.blendmode;
import dsfml.graphics.color;
import dsfml.graphics.drawableimpl;
import dsfml.graphics.image;
import dsfml.graphics.rect;
import dsfml.system.vector2;
/**
* Sprite defines a sprite : texture, transformations,
* color, and draw on screen
* See_Also:
* IDrawable
*/
class Sprite : Drawableimpl!(sfSprite)
{
/**
* Default constructor
*/
this()
{
}
/**
* Construct the sprite from a source image
*
* Params:
* img = Image of the sprite
* left = Left coordinate of the sprite (0 by default)
* top = Top coordinate of the sprite (0 by default)
* scaleX = Horizontal scale (1 by default)
* scaleY= Vertical scale (1 by default)
* rotation = Orientation, in degrees (0 by default)
* col = Color of the sprite (white by default)
*/
this(Image img, float left = 0.f, float top = 0.f, float scaleX = 1.f, float scaleY = 1.f, float rotation = 0.f, Color col = Color.WHITE)
{
m_image = img;
sfSprite_SetImage(m_ptr, img.getNativePointer);
setX(left);
setY(top);
setScaleX(scaleX);
setScaleY(scaleY);
setRotation(rotation);
setColor(col);
}
/**
* Change the image of the sprite
*
* Params:
* img = New image
*/
void setImage(Image img)
{
assert(img !is null, "Trying to set a null image.");
sfSprite_SetImage(m_ptr, img.getNativePointer);
m_image = img;
}
/**
* Set the sub-rectangle of a sprite inside the source image.
*
* Params:
* rect = New sub-rectangle
*/
void setSubRect(IntRect rect)
{
sfIntRect r = rect.toCIntRect();
sfSprite_SetSubRect(m_ptr, &r);
m_subRect = rect;
}
/**
* Resize the sprite (by changing its scale factors).
* The default size is defined by the subrect
*
* Params:
* width = New width (must be strictly positive)
* height = New height (must be strictly positive)
*/
void resize(float width, float height)
{
if (width > 0 && height > 0)
sfSprite_Resize(m_ptr, width, height);
}
/**
* Resize the sprite (by changing its scale factors).
* The default size is defined by the subrect
*
* Params:
* size = New size (both coordinates must be strictly positive)
*/
void resize(Vector2f size)
{
if (size.x > 0 && size.y > 0)
sfSprite_Resize(m_ptr, size.x, size.y);
}
/**
* Flip the sprite horizontally
*
* Params:
* flipped = True to flip the sprite
*/
void flipX(bool flipped)
{
sfSprite_FlipX(m_ptr, flipped);
}
/**
* Flip the sprite vertically
*
* Params:
* flipped = True to flip the sprite
*/
void flipY(bool flipped)
{
sfSprite_FlipY(m_ptr, flipped);
}
/**
* Get the source image of the sprite
*
* Returns:
* Pointer to the image (can be NULL)
*/
Image getImage()
{
return m_image;
}
/**
* Get the sub-rectangle of the sprite inside the source image
*
* Returns:
* Sub-rectangle
*/
IntRect getSubRect()
{
if (m_subRect is null)
m_subRect = new IntRect(0, 0, m_image.getWidth(), m_image.getHeight());
return m_subRect;
}
/**
* Get the sprite size
*
* Returns:
* Size of the sprite
*/
Vector2f getSize()
{
return Vector2f(sfSprite_GetWidth(m_ptr), sfSprite_GetHeight(m_ptr));
}
/**
* Get the color of a given pixel in the sprite
*
* Params:
* x = X coordinate
* y = Y coordinate
*
* Returns:
* Color of pixel
*/
Color getPixel(uint x, uint y)
{
return sfSprite_GetPixel(m_ptr, x, y);
}
private:
Image m_image; //< Image used to draw the sprite
IntRect m_subRect; //< Sub-rectangle of source image to assign to the sprite
extern (C)
{
typedef void function(void*, void*) pf_sfSprite_SetImage;
typedef void function(void*, sfIntRect*) pf_sfSprite_SetSubRect;
typedef void function(void*, float, float) pf_sfSprite_Resize;
typedef void function(void*, int) pf_sfSprite_FlipX;
typedef void function(void*, int) pf_sfSprite_FlipY;
typedef void* function(void*) pf_sfSprite_GetImage;
typedef void* function(void*) pf_sfSprite_GetSubRect;
typedef float function(void*) pf_sfSprite_GetWidth;
typedef float function(void*) pf_sfSprite_GetHeight;
typedef Color function(void*, uint, uint) pf_sfSprite_GetPixel;
static pf_sfSprite_SetImage sfSprite_SetImage;
static pf_sfSprite_SetSubRect sfSprite_SetSubRect;
static pf_sfSprite_Resize sfSprite_Resize;
static pf_sfSprite_FlipX sfSprite_FlipX;
static pf_sfSprite_FlipY sfSprite_FlipY;
static pf_sfSprite_GetImage sfSprite_GetImage;
static pf_sfSprite_GetSubRect sfSprite_GetSubRect;
static pf_sfSprite_GetWidth sfSprite_GetWidth;
static pf_sfSprite_GetHeight sfSprite_GetHeight;
static pf_sfSprite_GetPixel sfSprite_GetPixel;
}
static this()
{
DllLoader dll = DllLoader.load("csfml-graphics");
sfSprite_SetImage = cast(pf_sfSprite_SetImage)dll.getSymbol("sfSprite_SetImage");
sfSprite_SetSubRect = cast(pf_sfSprite_SetSubRect)dll.getSymbol("sfSprite_SetSubRect");
sfSprite_Resize = cast(pf_sfSprite_Resize)dll.getSymbol("sfSprite_Resize");
sfSprite_FlipX = cast(pf_sfSprite_FlipX)dll.getSymbol("sfSprite_FlipX");
sfSprite_FlipY = cast(pf_sfSprite_FlipY)dll.getSymbol("sfSprite_FlipY");
sfSprite_GetImage = cast(pf_sfSprite_GetImage)dll.getSymbol("sfSprite_GetImage");
sfSprite_GetSubRect = cast(pf_sfSprite_GetSubRect)dll.getSymbol("sfSprite_GetSubRect");
sfSprite_GetWidth = cast(pf_sfSprite_GetWidth)dll.getSymbol("sfSprite_GetWidth");
sfSprite_GetHeight = cast(pf_sfSprite_GetHeight)dll.getSymbol("sfSprite_GetHeight");
sfSprite_GetPixel = cast(pf_sfSprite_GetPixel)dll.getSymbol("sfSprite_GetPixel");
}
}

View file

@ -0,0 +1,290 @@
/*
* DSFML - SFML Library binding in D language.
* Copyright (C) 2008 Julien Dagorn (sirjulio13@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.
*/
module dsfml.graphics.string;
import dsfml.graphics.blendmode;
import dsfml.graphics.color;
import dsfml.graphics.font;
import dsfml.graphics.textstyle;
import dsfml.graphics.drawableimpl;
import dsfml.graphics.rect;
import dsfml.system.stringutil;
import dsfml.system.vector2;
/**
* String defines a graphical 2D text, that can be drawn on screen
*
* All string litterals used must be prefixed with c for utf-8
* and d for utf-32 string.
*
* Examples :
* ---------------------------------------------------------------
* String s = new String("Hello"c);
* //this(char[], Font, float)
* s = new String("Hello"d);
* //this(dchar[], Font, float)
* ---------------------------------------------------------------
*
* See_Also:
* IDrawable
*/
class String : Drawableimpl!(sfString)
{
/**
* Construct the string from a text
*
* Prefixs string litterals with c
*
* Params:
* text = Text assigned to the string
* font = Font used to draw the string (use default font)
* size = Characters size, in pixels (32 by default)
*/
this(char[] text, Font font = Font.getDefaultFont(), float size = 30.f)
{
super();
m_font = font;
setFont(font);
setText(text);
setSize(size);
}
/**
* Construct the string from a unicode text
*
* Prefixs string litterals with d
*
* Params:
* text = Text assigned to the string
* font = Font used to draw the string (use default font)
* size = Characters size, in pixels (32 by default)
*/
this(dchar[] text, Font font = Font.getDefaultFont(), float size = 30.f)
{
super();
m_font = font;
setFont(font);
setText(text);
setSize(size);
}
/**
* Set the text (from a multibyte string)
*
* Params:
* text = New text
*
*/
void setText(char[] text)
{
sfString_SetText(m_ptr,toStringz(text));
}
/**
* Set the text (from a unicode string)
*
* Params:
* text = New text
*/
void setText(dchar[] text)
{
sfString_SetUnicodeText(m_ptr, toStringz(text));
}
/**
* Set the font of the string
*
* Params:
* font = Font filename
*/
void setFont(Font font)
{
m_font = font;
sfString_SetFont(m_ptr, font.getNativePointer);
}
/**
* Set the size of the string
*
* Params:
* size = New size, in pixels
*/
void setSize(float size)
{
sfString_SetSize(m_ptr, size);
}
/**
* Set the style of the text
* The default style is Regular
*
* Params:
* TextStyle = New text style, (combination of Style enum values)
*
*/
void setStyle(TextStyle style)
{
sfString_SetStyle(m_ptr, style);
}
/**
* Get the text (returns a unicode string)
*
* Returns:
* Text
*/
dchar[] getUnicodeText()
{
return fromStringz(sfString_GetUnicodeText(m_ptr));
}
/**
* Get the text (returns a multibyte string)
*
* Returns:
* Text
*/
char[] getText()
{
return fromStringz(sfString_GetText(m_ptr));
}
/**
* Get the font used by the string
*
* Returns:
* Font name
*/
Font getFont()
{
return m_font;
}
/**
* Get the size of the characters
*
* Returns:
* Size of the characters
*/
float getSize()
{
return sfString_GetSize(m_ptr);
}
/**
* Get the current font style
*
* Returns:
* Font style
*/
TextStyle getStyle()
{
return sfString_GetStyle(m_ptr);
}
/**
* Return the visual position of the Index-th character of the string,
* in coordinates relative to the string
* (note : translation, center, rotation and scale are not applied)
*
* Params:
* index = Index of the character
*
* Returns:
* Position of the Index-th character (end of string of Index is out of range)
*/
Vector2f getCharacterPos(size_t index)
{
Vector2f ret;
sfString_GetCharacterPos(m_ptr, index, &ret.x, &ret.y);
return ret;
}
/**
* Get the string rectangle on screen
*
* Returns:
* Rectangle contaning the string in screen coordinates
*/
FloatRect getRect()
{
sfFloatRect sfRect = sfString_GetRect(m_ptr);
return new Rect!(float)(sfRect.Left, sfRect.Top, sfRect.Right, sfRect.Bottom);
}
private:
Font m_font;
extern (C)
{
typedef void function(void*, char*) pf_sfString_SetText;
typedef void function(void*, dchar*) pf_sfString_SetUnicodeText;
typedef void function(void*, void*) pf_sfString_SetFont;
typedef void function(void*, float) pf_sfString_SetSize;
typedef void function(void*, TextStyle) pf_sfString_SetStyle;
typedef dchar* function(void*) pf_sfString_GetUnicodeText;
typedef char* function(void*) pf_sfString_GetText;
typedef void* function(void*) pf_sfString_GetFont;
typedef float function(void*) pf_sfString_GetSize;
typedef TextStyle function (void*) pf_sfString_GetStyle;
typedef void function(void*, size_t, float*, float*) pf_sfString_GetCharacterPos;
typedef sfFloatRect function(void*) pf_sfString_GetRect;
static pf_sfString_SetText sfString_SetText;
static pf_sfString_SetUnicodeText sfString_SetUnicodeText;
static pf_sfString_SetFont sfString_SetFont;
static pf_sfString_SetSize sfString_SetSize;
static pf_sfString_SetStyle sfString_SetStyle;
static pf_sfString_GetUnicodeText sfString_GetUnicodeText;
static pf_sfString_GetText sfString_GetText;
static pf_sfString_GetFont sfString_GetFont;
static pf_sfString_GetSize sfString_GetSize;
static pf_sfString_GetStyle sfString_GetStyle;
static pf_sfString_GetCharacterPos sfString_GetCharacterPos;
static pf_sfString_GetRect sfString_GetRect;
}
static this()
{
DllLoader dll = DllLoader.load("csfml-graphics");
sfString_SetText = cast(pf_sfString_SetText)dll.getSymbol("sfString_SetText");
sfString_SetUnicodeText = cast(pf_sfString_SetUnicodeText)dll.getSymbol("sfString_SetUnicodeText");
sfString_SetFont = cast(pf_sfString_SetFont)dll.getSymbol("sfString_SetFont");
sfString_SetSize = cast(pf_sfString_SetSize)dll.getSymbol("sfString_SetSize");
sfString_SetStyle = cast(pf_sfString_SetStyle)dll.getSymbol("sfString_SetStyle");
sfString_GetUnicodeText = cast(pf_sfString_GetUnicodeText)dll.getSymbol("sfString_GetUnicodeText");
sfString_GetText = cast(pf_sfString_GetText)dll.getSymbol("sfString_GetText");
sfString_GetFont = cast(pf_sfString_GetFont)dll.getSymbol("sfString_GetFont");
sfString_GetSize = cast(pf_sfString_GetSize)dll.getSymbol("sfString_GetSize");
sfString_GetStyle = cast(pf_sfString_GetStyle)dll.getSymbol("sfString_GetStyle");
sfString_GetCharacterPos = cast(pf_sfString_GetCharacterPos)dll.getSymbol("sfString_GetCharacterPos");
sfString_GetRect = cast(pf_sfString_GetRect)dll.getSymbol("sfString_GetRect");
}
}

View file

@ -0,0 +1,37 @@
/*
* DSFML - SFML Library binding in D language.
* Copyright (C) 2008 Julien Dagorn (sirjulio13@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.
*/
module dsfml.graphics.textstyle;
/**
* Enumerate the string drawing styles
*/
enum TextStyle
{
REGULAR = 0, /// Regular characters, no style
BOLD = 1 << 0, /// Characters are bold
ITALIC = 1 << 1, /// Characters are in italic
UNDERLINED = 1 << 2 /// Characters are underlined
}

View file

@ -0,0 +1,274 @@
/*
* DSFML - SFML Library binding in D language.
* Copyright (C) 2008 Julien Dagorn (sirjulio13@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.
*/
module dsfml.graphics.view;
import dsfml.graphics.rect;
import dsfml.system.common;
import dsfml.system.vector2;
/**
* This class defines a view (position, size and zoom) ;
* you can consider it as a camera
*/
class View : DSFMLObject
{
/**
* Constructor
*
* Default view (1000 x 1000)
*/
this()
{
super(sfView_Create());
}
/**
* Constructor
*
* Params:
* center = center of the view
* halfsize = Half-size of the view (from center to corner)
*/
this(Vector2f center, Vector2f halfsize)
{
super(sfView_CreateFromRect(sfFloatRect(center.x - halfsize.x, center.y - halfsize.y, center.x + halfsize.x, center.y + halfsize.y) ));
}
/**
* Constructor
*
* Params:
* rect = Rectangle defining the position and size of the view
*/
this(FloatRect rect)
{
super(sfView_CreateFromRect(rect.toCFloatRect()));
}
override void dispose()
{
sfView_Destroy(m_ptr);
}
/**
* Change the center of the view
*
* Params:
* x = X coordinates of the new center
* y = Y coordinates of the new center
*/
void setCenter(float x, float y)
{
sfView_SetCenter(m_ptr, x, y);
m_isModified = true;
}
/**
* Change the center of the view
*
* Params:
* center = New center
*/
void setCenter(Vector2f center)
{
sfView_SetCenter(m_ptr, center.x, center.y);
m_isModified = true;
}
/**
* Change the half-size of the view (take 2 values)
*
* Params:
* halfWidth = New half-width
* halfHeight = New half-height
*/
void setHalfSize(float halfWidth, float HalfHeight)
{
sfView_SetHalfSize(m_ptr, halfWidth, HalfHeight);
m_isModified = true;
}
/**
* Change the half-size of the view (take 2 values)
*
* Params:
* helfSize = New halfsize
*/
void setHalfSize(Vector2f halfSize)
{
sfView_SetHalfSize(m_ptr, halfSize.x, halfSize.y);
m_isModified = true;
}
/**
* Rebuild the view from a rectangle
*
* Params:
* viewRect : Rectangle defining the position and size of the view
*/
void setFromRect(FloatRect viewRect)
{
sfView_SetFromRect(m_ptr, viewRect.toCFloatRect());
m_rect = viewRect;
}
/**
* Get the center of the view
*
* Returns:
* Center of the view
*/
Vector2f GetCenter()
{
return Vector2f(sfView_GetCenterX(m_ptr), sfView_GetCenterY(m_ptr));
}
/**
* Get the halfsize of the view
*
* Returns:
* Halfsize of the view
*/
Vector2f GetHalfSize()
{
return Vector2f(sfView_GetHalfSizeX(m_ptr), sfView_GetHalfSizeY(m_ptr));
}
/**
* Get the bounding retangle of the view
*/
FloatRect getRect()
{
if (m_isModified)
{
m_isModified = false;
sfFloatRect cRect = sfView_GetRect(m_ptr);
m_rect = new FloatRect(cRect.Left, cRect.Top, cRect.Right, cRect.Bottom);
}
return m_rect;
}
/**
* Move the view
*
* Params:
* offsetX = Offset to move the view, on X axis
* offsetY = Offset to move the view, on Y axis
*/
void move(float offsetX, float offsetY)
{
sfView_Move(m_ptr, offsetX, offsetY);
m_isModified = true;
}
/**
* Move the view
*
* Params:
* offset = offsetto move the view
*/
void move(Vector2f offset)
{
sfView_Move(m_ptr, offset.x, offset.y);
m_isModified = true;
}
/**
* Resize the view rectangle to simulate a zoom / unzoom effect
*
* Params:
* factor = Zoom factor to apply, relative to the current zoom
*/
void zoom(float factor)
{
sfView_Zoom(m_ptr, factor);
m_isModified = true;
}
package:
this(void* ptr, bool preventDelete)
{
super(ptr, preventDelete);
}
private:
FloatRect m_rect;
bool m_isModified = true;
extern (C)
{
typedef void* function() pf_sfView_Create;
typedef void* function(sfFloatRect) pf_sfView_CreateFromRect;
typedef void function(void*) pf_sfView_Destroy;
typedef void function(void*, float, float) pf_sfView_SetCenter;
typedef void function(void*, float, float) pf_sfView_SetHalfSize;
typedef void function(void*, sfFloatRect ViewRect) pf_sfView_SetFromRect;
typedef float function(void*) pf_sfView_GetCenterX;
typedef float function(void*) pf_sfView_GetCenterY;
typedef float function(void*) pf_sfView_GetHalfSizeX;
typedef float function(void*) pf_sfView_GetHalfSizeY;
typedef sfFloatRect function(void*) pf_sfView_GetRect;
typedef void function(void*, float, float) pf_sfView_Move;
typedef void function(void*, float) pf_sfView_Zoom;
static pf_sfView_Create sfView_Create;
static pf_sfView_CreateFromRect sfView_CreateFromRect;
static pf_sfView_Destroy sfView_Destroy;
static pf_sfView_SetCenter sfView_SetCenter;
static pf_sfView_SetHalfSize sfView_SetHalfSize;
static pf_sfView_SetFromRect sfView_SetFromRect;
static pf_sfView_GetCenterX sfView_GetCenterX;
static pf_sfView_GetCenterY sfView_GetCenterY;
static pf_sfView_GetHalfSizeX sfView_GetHalfSizeX;
static pf_sfView_GetHalfSizeY sfView_GetHalfSizeY;
static pf_sfView_GetRect sfView_GetRect;
static pf_sfView_Move sfView_Move;
static pf_sfView_Zoom sfView_Zoom;
}
static this()
{
DllLoader dll = DllLoader.load("csfml-graphics");
sfView_Create = cast(pf_sfView_Create) dll.getSymbol("sfView_Create");
sfView_CreateFromRect = cast(pf_sfView_CreateFromRect) dll.getSymbol("sfView_CreateFromRect");
sfView_Destroy = cast(pf_sfView_Destroy) dll.getSymbol("sfView_Destroy");
sfView_SetCenter = cast(pf_sfView_SetCenter) dll.getSymbol("sfView_SetCenter");
sfView_SetHalfSize = cast(pf_sfView_SetHalfSize) dll.getSymbol("sfView_SetHalfSize");
sfView_SetFromRect = cast(pf_sfView_SetFromRect) dll.getSymbol("sfView_SetFromRect");
sfView_GetCenterX = cast(pf_sfView_GetCenterX) dll.getSymbol("sfView_GetCenterX");
sfView_GetCenterY = cast(pf_sfView_GetCenterY) dll.getSymbol("sfView_GetCenterY");
sfView_GetHalfSizeX = cast(pf_sfView_GetHalfSizeX) dll.getSymbol("sfView_GetHalfSizeX");
sfView_GetHalfSizeY = cast(pf_sfView_GetHalfSizeY) dll.getSymbol("sfView_GetHalfSizeY");
sfView_GetRect = cast(pf_sfView_GetRect) dll.getSymbol("sfView_GetRect");
sfView_Move = cast(pf_sfView_Move) dll.getSymbol("sfView_Move");
sfView_Zoom = cast(pf_sfView_Zoom) dll.getSymbol("sfView_Zoom");
}
}

View file

@ -0,0 +1,36 @@
/*
* DSFML - SFML Library binding in D language.
* Copyright (C) 2008 Julien Dagorn (sirjulio13@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.
*/
module dsfml.network.all;
public import
dsfml.network.ftp,
dsfml.network.http,
dsfml.network.ipaddress,
dsfml.network.packet,
dsfml.network.selector,
dsfml.network.socketstatus,
dsfml.network.sockettcp,
dsfml.network.socketudp;

View file

@ -0,0 +1,598 @@
/*
* DSFML - SFML Library binding in D language.
* Copyright (C) 2008 Julien Dagorn (sirjulio13@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.
*/
module dsfml.network.ftp;
import dsfml.system.common;
import dsfml.system.stringutil;
import dsfml.network.ipaddress;
/**
* Enumeration of transfer mode
*/
enum FtpTransferMode
{
BINARY, ///< Binary mode (file is transfered as a sequence of bytes)
ASCII, ///< Text mode using ASCII encoding
EBCDIC ///< Text mode using EBCDIC encoding
}
/**
* Enumerate all the valid status codes returned in
* a FTP response
*/
enum FtpStatus
{
// 1xx: the requested action is being initiated,
// expect another reply before proceeding with a new command
RESTARTMARKERREPLY = 110, ///< Restart marker reply
SERVICEREADYSOON = 120, ///< Service ready in N minutes
DATACONNECTIONALREADYOPENED = 125, ///< Data connection already opened, transfer starting
OPENINGDATACONNECTION = 150, ///< File status ok, about to open data connection
// 2xx: the requested action has been successfully completed
OK = 200, ///< Command ok
POINTLESSCOMMAND = 202, ///< Command not implemented
SYSTEMSTATUS = 211, ///< System status, or system help reply
DIRECTORYSTATUS = 212, ///< Directory status
FILESTATUS = 213, ///< File status
HELPMESSAGE = 214, ///< Help message
SYSTEMTYPE = 215, ///< NAME system type, where NAME is an official system name from the list in the Assigned Numbers document
SERVICEREADY = 220, ///< Service ready for new user
CLOSINGCONNECTION = 221, ///< Service closing control connection
DATACONNECTIONOPENED = 225, ///< Data connection open, no transfer in progress
CLOSINGDATACONNECTION = 226, ///< Closing data connection, requested file action successful
ENTERINGPASSIVEMODE = 227, ///< Entering passive mode
LOGGEDIN = 230, ///< User logged in, proceed. Logged out if appropriate
FILEACTIONOK = 250, ///< Requested file action ok
DIRECTORYOK = 257, ///< PATHNAME created
// 3xx: the command has been accepted, but the requested action
// is dormant, pending receipt of further information
NEEDPASSWORD = 331, ///< User name ok, need password
NEEDACCOUNTTOLOGIN = 332, ///< Need account for login
NEEDINFORMATION = 350, ///< Requested file action pending further information
// 4xx: the command was not accepted and the requested action did not take place,
// but the error condition is temporary and the action may be requested again
SERVICEUNAVAILABLE = 421, ///< Service not available, closing control connection
DATACONNECTIONUNAVAILABLE = 425, ///< Can't open data connection
TRANSFERABORTED = 426, ///< Connection closed, transfer aborted
FILEACTIONABORTED = 450, ///< Requested file action not taken
LOCALERROR = 451, ///< Requested action aborted, local error in processing
INSUFFICIENTSTORAGESPACE = 452, ///< Requested action not taken; insufficient storage space in system, file unavailable
// 5xx: the command was not accepted and
// the requested action did not take place
COMMANDUNKNOWN = 500, ///< Syntax error, command unrecognized
PARAMETERSUNKNOWN = 501, ///< Syntax error in parameters or arguments
COMMANDNOTIMPLEMENTED = 502, ///< Command not implemented
BADCOMMANDSEQUENCE = 503, ///< Bad sequence of commands
PARAMETERNOTIMPLEMENTED = 504, ///< Command not implemented for that parameter
NOTLOGGEDIN = 530, ///< Not logged in
NEEDACCOUNTTOSTORE = 532, ///< Need account for storing files
FILEUNAVAILABLE = 550, ///< Requested action not taken, file unavailable
PAGETYPEUNKNOWN = 551, ///< Requested action aborted, page type unknown
NOTENOUGHMEMORY = 552, ///< Requested file action aborted, exceeded storage allocation
FILENAMENOTALLOWED = 553, ///< Requested action not taken, file name not allowed
// 10xx: SFML custom codes
INVALIDRESPONSE = 1000, ///< Response is not a valid FTP one
CONNECTIONFAILED = 1001, ///< Connection with server failed
CONNECTIONCLOSED = 1002, ///< Connection with server closed
INVALIDFILE = 1003 ///< Invalid file to upload / download
}
/**
* This class provides methods for manipulating the FTP protocol (described in RFC 959).
* It provides easy access and transfers to remote directories and files on a FTP server.
*/
class Ftp : DSFMLObject
{
/**
* This class wraps a FTP response, which is basically :
* - a status code
* - a message
*/
static class FtpResponse : DSFMLObject
{
override void dispose()
{
sfFtpResponse_Destroy(m_ptr);
}
/**
* Convenience function to check if the response status code
* means a success
*
* Returns:
* True if status is success (code < 400)
*/
bool isOk()
{
return cast(bool)sfFtpResponse_IsOk(m_ptr);
}
/**
* Get the response status code
*
* Returns:
* Status code
*/
FtpStatus getStatus()
{
return sfFtpResponse_GetStatus(m_ptr);
}
/**
* Get the full message contained in the response
*
* Returns:
* The response message
*/
char[] getMessage()
{
return fromStringz(sfFtpResponse_GetMessage(m_ptr));
}
private:
this(void* ptr)
{
super(ptr);
}
// External ================================================================
extern (C)
{
typedef void function(void*) pf_sfFtpResponse_Destroy;
typedef int function(void*) pf_sfFtpResponse_IsOk;
typedef FtpStatus function(void*) pf_sfFtpResponse_GetStatus;
typedef char* function(void*) pf_sfFtpResponse_GetMessage;
static pf_sfFtpResponse_Destroy sfFtpResponse_Destroy;
static pf_sfFtpResponse_IsOk sfFtpResponse_IsOk;
static pf_sfFtpResponse_GetStatus sfFtpResponse_GetStatus;
static pf_sfFtpResponse_GetMessage sfFtpResponse_GetMessage;
}
static this()
{
DllLoader dll = DllLoader.load("csfml-network");
sfFtpResponse_Destroy = cast(pf_sfFtpResponse_Destroy)dll.getSymbol("sfFtpResponse_Destroy");
sfFtpResponse_IsOk = cast(pf_sfFtpResponse_IsOk)dll.getSymbol("sfFtpResponse_IsOk");
sfFtpResponse_GetStatus = cast(pf_sfFtpResponse_GetStatus)dll.getSymbol("sfFtpResponse_GetStatus");
sfFtpResponse_GetMessage = cast(pf_sfFtpResponse_GetMessage)dll.getSymbol("sfFtpResponse_GetMessage");
}
}
/**
* Specialization of FTP response returning a directory
*/
static class FtpDirectoryResponse : FtpResponse
{
override void dispose()
{
sfFtpDirectoryResponse_Destroy(m_ptr);
}
/**
* Get the directory returned in the response.
*
* Returns:
* Directory name
*/
char[] getDirectory()
{
return fromStringz(sfFtpDirectoryResponse_GetDirectory(m_ptr));
}
private:
this(void* ptr)
{
super(ptr);
}
// External ================================================================
extern (C)
{
typedef void function(void*) pf_sfFtpDirectoryResponse_Destroy;
typedef char* function(void*) pf_sfFtpDirectoryResponse_GetDirectory;
static pf_sfFtpDirectoryResponse_Destroy sfFtpDirectoryResponse_Destroy;
static pf_sfFtpDirectoryResponse_GetDirectory sfFtpDirectoryResponse_GetDirectory;
}
static this()
{
DllLoader dll = DllLoader.load("csfml-network");
sfFtpDirectoryResponse_Destroy = cast(pf_sfFtpDirectoryResponse_Destroy)dll.getSymbol("sfFtpDirectoryResponse_Destroy");
sfFtpDirectoryResponse_GetDirectory = cast(pf_sfFtpDirectoryResponse_GetDirectory)dll.getSymbol("sfFtpDirectoryResponse_GetDirectory");
}
}
/**
* Specialization of FTP response returning a filename listing.
*/
static class FtpListingResponse : FtpResponse
{
override void dispose()
{
sfFtpListingResponse_Destroy(m_ptr);
}
/**
* Get the number of files in the listing
*
* Returns:
* Total number of files
*/
size_t getCount()
{
return sfFtpListingResponse_GetCount(m_ptr);
}
/**
* Get the index-th filename in the directory
*
* Params:
* index = Index of the filename to get
*
* Returns:
* Filename
*/
char[] opIndex(size_t index)
{
return fromStringz(sfFtpListingResponse_GetFilename(m_ptr, index));
}
/**
* Foreach implementation
*/
int opApply(int delegate(char[]) dg)
{
size_t count = getCount();
int result;
for(int i = 0; i < count; i++)
{
result = dg(this[i]);
if (result)
break;
}
return result;
}
private:
this(void* ptr)
{
super(ptr);
}
// External ================================================================
extern (C)
{
typedef void function(void*) pf_sfFtpListingResponse_Destroy;
typedef size_t function(void*) pf_sfFtpListingResponse_GetCount;
typedef char* function(void*, size_t) pf_sfFtpListingResponse_GetFilename;
static pf_sfFtpListingResponse_Destroy sfFtpListingResponse_Destroy;
static pf_sfFtpListingResponse_GetCount sfFtpListingResponse_GetCount;
static pf_sfFtpListingResponse_GetFilename sfFtpListingResponse_GetFilename;
}
static this()
{
DllLoader dll = DllLoader.load("csfml-network");
sfFtpListingResponse_Destroy = cast(pf_sfFtpListingResponse_Destroy)dll.getSymbol("sfFtpListingResponse_Destroy");
sfFtpListingResponse_GetCount = cast(pf_sfFtpListingResponse_GetCount)dll.getSymbol("sfFtpListingResponse_GetCount");
sfFtpListingResponse_GetFilename = cast(pf_sfFtpListingResponse_GetFilename)dll.getSymbol("sfFtpListingResponse_GetFilename");
}
}
/**
* Default constructor
*/
this()
{
super(sfFtp_Create());
}
override void dispose()
{
sfFtp_Destroy(m_ptr);
}
/**
* Connect to the specified FTP server
*
* Params:
* server = FTP server to connect to
* port = Port used for connection (21 by default, standard FTP port)
* timeout = Maximum time to wait, in seconds (0 by default, means no timeout)
*
* Returns:
* Server response to the request
*/
FtpResponse connect(IPAddress server, ushort port = 21, float timeout = 0.f)
{
return new FtpResponse(sfFtp_Connect(m_ptr, server, port, timeout));
}
/**
* Log in using anonymous account
*
* Returns:
* Server response to the request
*/
FtpResponse login()
{
return new FtpResponse(sfFtp_LoginAnonymous(m_ptr));
}
/**
* Log in using a username and a password
*
* Params:
* username = User name
* password = password
*
* Returns:
* Server response to the request
*/
FtpResponse login(char[] username, char[] password)
{
return new FtpResponse(sfFtp_Login(m_ptr, toStringz(username), toStringz(password)));
}
/**
* Close the connection with FTP server
*
* Returns:
* Server response to the request
*/
FtpResponse disconnect()
{
return new FtpResponse(sfFtp_Disconnect(m_ptr));
}
/**
* Send a null command to prevent from being disconnected.
*
* Returns:
* Server response to the request
*/
FtpResponse keepAlive()
{
return new FtpResponse(sfFtp_KeepAlive(m_ptr));
}
/**
* Get the current working directory
*
* Returns:
* Server response to the request
*/
FtpDirectoryResponse getWorkingDirectory()
{
return new FtpDirectoryResponse(sfFtp_GetWorkingDirectory(m_ptr));
}
/**
* Get the content of the given directory (subdirectories and files).
*
* Params:
* directory = directory to list (null by default, the current one)
*
* Returns:
* Server response to the request
*/
FtpListingResponse getDirectoryListing(char[] directory = null)
{
return new FtpListingResponse(sfFtp_GetDirectoryListing(m_ptr, toStringz(directory)));
}
/**
* Change the current working directory
*
* Params:
* directory = New directory, relative to the current one.
*
* Returns:
* Server response to the request
*/
FtpResponse changeDirectory(char[] directory)
{
return new FtpResponse(sfFtp_ChangeDirectory(m_ptr, toStringz(directory)));
}
/**
* Go to the parent directory of the current one
*
* Returns:
* Server response to the request
*/
FtpResponse parentDirectory()
{
return new FtpResponse(sfFtp_ParentDirectory(m_ptr));
}
/**
* Create a new directory
*
* Params:
* name = name of the directory to create
*
* Returns:
* Server response to the request
*/
FtpResponse makeDirectory(char[] name)
{
return new FtpResponse(sfFtp_MakeDirectory(m_ptr, toStringz(name)));
}
/**
* remove an existing directory
*
* Params:
* name = name of the directory to remove
*
* Returns:
* Server response to the request
*/
FtpResponse deleteDirectory(char[] name)
{
return new FtpResponse(sfFtp_DeleteDirectory(m_ptr, toStringz(name)));
}
/**
* Rename a file
*
* Params:
* name = file to rename
* newName = new name
*
* Returns:
* Server response to the request
*/
FtpResponse renameFile(char[] name, char[] newName)
{
return new FtpResponse(sfFtp_RenameFile(m_ptr, toStringz(name), toStringz(newName)));
}
/**
* Remove an existing file
*
* Params:
* name = file to remove
*
* Returns:
* Server response to the request
*/
FtpResponse deleteFile(char[] name)
{
return new FtpResponse(sfFtp_DeleteFile(m_ptr, toStringz(name)));
}
/**
* Download a file from the server
*
* Params:
* distantFile = Path of the distant file to download
* destFile = Where to put the file on the local computer
* mode = transfer mode (binary by default)
*
* Returns:
* Server response to the request
*/
FtpResponse download(char[] distantFile, char[] destFile, FtpTransferMode mode = FtpTransferMode.BINARY)
{
return new FtpResponse(sfFtp_Download(m_ptr, toStringz(distantFile), toStringz(destFile), mode));
}
/**
* Upload a file to the server
*
* Params:
* localFile = Path of the local file to upload
* destPath = Where to put the file on the server
* mode = transfer mode (binary by default)
* Returns:
* Server response to the request
*/
FtpResponse upload(char[] localFile, char[] destFile, FtpTransferMode mode = FtpTransferMode.BINARY)
{
return new FtpResponse(sfFtp_Upload(m_ptr, toStringz(localFile), toStringz(destFile), mode));
}
private:
// External ====================================================================
extern (C)
{
typedef void* function() pf_sfFtp_Create;
typedef void function(void*) pf_sfFtp_Destroy;
typedef void* function(void*, IPAddress, ushort, float) pf_sfFtp_Connect;
typedef void* function(void*) pf_sfFtp_LoginAnonymous;
typedef void* function(void*, char*, char*) pf_sfFtp_Login;
typedef void* function(void*) pf_sfFtp_Disconnect;
typedef void* function(void*) pf_sfFtp_KeepAlive;
typedef void* function(void*) pf_sfFtp_GetWorkingDirectory;
typedef void* function(void*, char*) pf_sfFtp_GetDirectoryListing;
typedef void* function(void*, char*) pf_sfFtp_ChangeDirectory;
typedef void* function(void*) pf_sfFtp_ParentDirectory;
typedef void* function(void*, char*) pf_sfFtp_MakeDirectory;
typedef void* function(void*, char*) pf_sfFtp_DeleteDirectory;
typedef void* function(void*, char*, char*) pf_sfFtp_RenameFile;
typedef void* function(void*, char*) pf_sfFtp_DeleteFile;
typedef void* function(void*, char*, char*, FtpTransferMode) pf_sfFtp_Download;
typedef void* function(void*, char*, char*, FtpTransferMode) pf_sfFtp_Upload;
static pf_sfFtp_Create sfFtp_Create;
static pf_sfFtp_Destroy sfFtp_Destroy;
static pf_sfFtp_Connect sfFtp_Connect;
static pf_sfFtp_LoginAnonymous sfFtp_LoginAnonymous;
static pf_sfFtp_Login sfFtp_Login;
static pf_sfFtp_Disconnect sfFtp_Disconnect;
static pf_sfFtp_KeepAlive sfFtp_KeepAlive;
static pf_sfFtp_GetWorkingDirectory sfFtp_GetWorkingDirectory;
static pf_sfFtp_GetDirectoryListing sfFtp_GetDirectoryListing;
static pf_sfFtp_ChangeDirectory sfFtp_ChangeDirectory;
static pf_sfFtp_ParentDirectory sfFtp_ParentDirectory;
static pf_sfFtp_MakeDirectory sfFtp_MakeDirectory;
static pf_sfFtp_DeleteDirectory sfFtp_DeleteDirectory;
static pf_sfFtp_RenameFile sfFtp_RenameFile;
static pf_sfFtp_DeleteFile sfFtp_DeleteFile;
static pf_sfFtp_Download sfFtp_Download;
static pf_sfFtp_Upload sfFtp_Upload;
}
static this()
{
DllLoader dll = DllLoader.load("csfml-network");
sfFtp_Create = cast(pf_sfFtp_Create)dll.getSymbol("sfFtp_Create");
sfFtp_Destroy = cast(pf_sfFtp_Destroy)dll.getSymbol("sfFtp_Destroy");
sfFtp_Connect = cast(pf_sfFtp_Connect)dll.getSymbol("sfFtp_Connect");
sfFtp_LoginAnonymous = cast(pf_sfFtp_LoginAnonymous)dll.getSymbol("sfFtp_LoginAnonymous");
sfFtp_Login = cast(pf_sfFtp_Login)dll.getSymbol("sfFtp_Login");
sfFtp_Disconnect = cast(pf_sfFtp_Disconnect)dll.getSymbol("sfFtp_Disconnect");
sfFtp_KeepAlive = cast(pf_sfFtp_KeepAlive)dll.getSymbol("sfFtp_KeepAlive");
sfFtp_GetWorkingDirectory = cast(pf_sfFtp_GetWorkingDirectory)dll.getSymbol("sfFtp_GetWorkingDirectory");
sfFtp_GetDirectoryListing = cast(pf_sfFtp_GetDirectoryListing)dll.getSymbol("sfFtp_GetDirectoryListing");
sfFtp_ChangeDirectory = cast(pf_sfFtp_ChangeDirectory)dll.getSymbol("sfFtp_ChangeDirectory");
sfFtp_ParentDirectory = cast(pf_sfFtp_ParentDirectory)dll.getSymbol("sfFtp_ParentDirectory");
sfFtp_MakeDirectory = cast(pf_sfFtp_MakeDirectory)dll.getSymbol("sfFtp_MakeDirectory");
sfFtp_DeleteDirectory = cast(pf_sfFtp_DeleteDirectory)dll.getSymbol("sfFtp_DeleteDirectory");
sfFtp_RenameFile = cast(pf_sfFtp_RenameFile)dll.getSymbol("sfFtp_RenameFile");
sfFtp_DeleteFile = cast(pf_sfFtp_DeleteFile)dll.getSymbol("sfFtp_DeleteFile");
sfFtp_Download = cast(pf_sfFtp_Download)dll.getSymbol("sfFtp_Download");
sfFtp_Upload = cast(pf_sfFtp_Upload)dll.getSymbol("sfFtp_Upload");
}
}

View file

@ -0,0 +1,394 @@
/*
* DSFML - SFML Library binding in D language.
* Copyright (C) 2008 Julien Dagorn (sirjulio13@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.
*/
module dsfml.network.http;
import dsfml.system.stringutil;
import dsfml.system.common;
/**
* HTTP methods enumeration
*/
enum HttpMethod
{
GET, ///< Request in get mode, standard method to retrieve a page
POST, ///< Request in post mode, usually to send data to a page
HEAD ///< Request a page's header only
}
/**
* HTTP response status code
*/
enum HttpStatus
{
// 2xx: success
OK = 200, ///< Most common code returned when operation was successful
CREATED = 201, ///< The resource has successfully been created
ACCEPTED = 202, ///< The request has been accepted, but will be processed later by the server
NOCONTENT = 204, ///< Sent when the server didn't send any data in return
// 3xx: redirection
MULTIPLECHOICES = 300, ///< The requested page can be accessed from several locations
MOVEDPERMANENTLY = 301, ///< The requested page has permanently moved to a new location
MOVEDTEMPORARILY = 302, ///< The requested page has temporarily moved to a new location
NOTMODIFIED = 304, ///< For conditionnal requests, means the requested page hasn't changed and doesn't need to be refreshed
// 4xx: client error
BADREQUEST = 400, ///< The server couldn't understand the request (syntax error)
UNAUTHORIZED = 401, ///< The requested page needs an authentification to be accessed
FORBIDDEN = 403, ///< The requested page cannot be accessed at all, even with authentification
NOTFOUND = 404, ///< The requested page doesn't exist
// 5xx: server error
INTERNALSERVERERROR = 500, ///< The server encountered an unexpected error
NOTIMPLEMENTED = 501, ///< The server doesn't implement a requested feature
BADGATEWAY = 502, ///< The gateway server has received an error from the source server
SERVICENOTAVAILABLE = 503, ///< The server is temporarily unavailable (overloaded, in maintenance, ...)
// 10xx: SFML custom codes
INVALIDRESPONSE = 1000, ///< Response is not a valid HTTP one
CONNECTIONFAILED = 1001 ///< Connection with server failed
}
/**
* This class provides methods for manipulating the HTTP protocol (described in
* RFC 1945).
* It can connect to a website, get files, send requests
*/
class Http : DSFMLObject
{
/**
* Wrapper for a http request, which is basically :
* - a header with a method, a target URI and a set of field/value pairs
* - an optional body (for POST requests)
*/
static class Response : DSFMLObject
{
override void dispose()
{
sfHttpResponse_Destroy(m_ptr);
}
/**
* Get the value of a field
*
* Params:
* field = Name of the field to get (case-insensitive)
* Returns:
* Value of the field, or enpty string if not found
*/
char[] getField(char[] field)
{
return fromStringz(sfHttpResponse_GetField(m_ptr, toStringz(field)));
}
/**
* Get the header status code
*
* Returns:
* header status code
*/
HttpStatus getStatus()
{
return sfHttpResponse_GetStatus(m_ptr);
}
/**
* Get the major HTTP version number of the response
*
* Returns:
* Major version number
*/
uint getMajorHTTPVersion()
{
return sfHttpResponse_GetMajorVersion(m_ptr);
}
/**
* Get the minor HTTP version number of the response
*
* Returns:
* Minor version number
*/
uint getMinorHTTPVersion()
{
return sfHttpResponse_GetMinorVersion(m_ptr);
}
/**
* Get the body of the response. The body can contain :
* - the requested page (for GET requests)
* - a response from the server (for POST requests)
* - nothing (for HEAD requests)
* - an error message (in case of an error)
*
* Returns:
* the response body
*/
char[] getBody()
{
return fromStringz(sfHttpResponse_GetBody(m_ptr));
}
private:
this(void* ptr)
{
super(ptr);
}
// External ================================================================
extern (C)
{
typedef void function(void*) pf_sfHttpResponse_Destroy;
typedef char* function(void*, char*) pf_sfHttpResponse_GetField;
typedef HttpStatus function(void*) pf_sfHttpResponse_GetStatus;
typedef uint function(void*) pf_sfHttpResponse_GetMajorVersion;
typedef uint function(void*) pf_sfHttpResponse_GetMinorVersion;
typedef char* function(void*) pf_sfHttpResponse_GetBody;
static pf_sfHttpResponse_Destroy sfHttpResponse_Destroy;
static pf_sfHttpResponse_GetField sfHttpResponse_GetField;
static pf_sfHttpResponse_GetStatus sfHttpResponse_GetStatus;
static pf_sfHttpResponse_GetMajorVersion sfHttpResponse_GetMajorVersion;
static pf_sfHttpResponse_GetMinorVersion sfHttpResponse_GetMinorVersion;
static pf_sfHttpResponse_GetBody sfHttpResponse_GetBody;
}
static this()
{
DllLoader dll = DllLoader.load("csfml-network");
sfHttpResponse_Destroy = cast(pf_sfHttpResponse_Destroy)dll.getSymbol("sfHttpResponse_Destroy");
sfHttpResponse_GetField = cast(pf_sfHttpResponse_GetField)dll.getSymbol("sfHttpResponse_GetField");
sfHttpResponse_GetStatus = cast(pf_sfHttpResponse_GetStatus)dll.getSymbol("sfHttpResponse_GetStatus");
sfHttpResponse_GetMajorVersion = cast(pf_sfHttpResponse_GetMajorVersion)dll.getSymbol("sfHttpResponse_GetMajorVersion");
sfHttpResponse_GetMinorVersion = cast(pf_sfHttpResponse_GetMinorVersion)dll.getSymbol("sfHttpResponse_GetMinorVersion");
sfHttpResponse_GetBody = cast(pf_sfHttpResponse_GetBody)dll.getSymbol("sfHttpResponse_GetBody");
}
}
/**
* Wrapper for a HTTP response which is basically :
* - a header with a status code and a set of field/value pairs
* - a body (the content of the requested resource)
*/
static class Request : DSFMLObject
{
/**
* Constructor
*
* Params:
* requestMethod = Method to use for the request (Get by default)
* uri = Target URI ("/" by default -- index page)
* requestBody = Content of the request's body (empty by default)
*/
this(HttpMethod requestMethod = HttpMethod.GET, char[] uri = "/", char[] requestBody = "")
{
super(sfHttpRequest_Create());
sfHttpRequest_SetMethod(m_ptr, requestMethod);
sfHttpRequest_SetURI(m_ptr, toStringz(uri));
sfHttpRequest_SetBody(m_ptr, toStringz(requestBody));
}
/**
* Set the value of a field. Field is created if it doesn't exists.
*
* Params:
* field = name of the field to set (case-insensitive)
* value = value of the field
*/
void setField(char[] field, char[] value)
{
sfHttpRequest_SetField(m_ptr, toStringz(field), toStringz(value));
}
/**
* Set the request method.
*
* Params:
* requestMethod = Method to use for the request.
*/
void setMethod(HttpMethod requestMethod)
{
sfHttpRequest_SetMethod(m_ptr, requestMethod);
}
/**
* Set the target URI of the request.
*
* Params:
* uri = URI to request, local to the host.
* Returns:
*/
void setURI(char[] uri)
{
sfHttpRequest_SetURI(m_ptr, toStringz(uri));
}
/**
* Set the HTTP version of the request.
*
* Params:
* major = Major version number
* minor = Minor version number
*/
void setHttpVersion(uint major, uint minor)
{
sfHttpRequest_SetHttpVersion(m_ptr, major, minor);
}
/**
* Set the body of the request. This parameter is optionnal and make sense
* only for POST requests.
*
* Params:
* requestBody = Content of the request body.
*/
void setBody(char[] requestBody)
{
sfHttpRequest_SetBody(m_ptr, toStringz(requestBody));
}
private:
// External ================================================================
extern (C)
{
typedef void* function() pf_sfHttpRequest_Create;
typedef void function(void*) pf_sfHttpRequest_Destroy;
typedef void function(void*, char*, char*) pf_sfHttpRequest_SetField;
typedef void function(void*, HttpMethod) pf_sfHttpRequest_SetMethod;
typedef void function(void*, char*) pf_sfHttpRequest_SetURI;
typedef void function(void*, uint, uint) pf_sfHttpRequest_SetHttpVersion;
typedef void function(void*, char*) pf_sfHttpRequest_SetBody;
static pf_sfHttpRequest_Create sfHttpRequest_Create;
static pf_sfHttpRequest_Destroy sfHttpRequest_Destroy;
static pf_sfHttpRequest_SetField sfHttpRequest_SetField;
static pf_sfHttpRequest_SetMethod sfHttpRequest_SetMethod;
static pf_sfHttpRequest_SetURI sfHttpRequest_SetURI;
static pf_sfHttpRequest_SetHttpVersion sfHttpRequest_SetHttpVersion;
static pf_sfHttpRequest_SetBody sfHttpRequest_SetBody;
}
static this()
{
DllLoader dll = DllLoader.load("csfml-network");
sfHttpRequest_Create = cast(pf_sfHttpRequest_Create)dll.getSymbol("sfHttpRequest_Create");
sfHttpRequest_Destroy = cast(pf_sfHttpRequest_Destroy)dll.getSymbol("sfHttpRequest_Destroy");
sfHttpRequest_SetField = cast(pf_sfHttpRequest_SetField)dll.getSymbol("sfHttpRequest_SetField");
sfHttpRequest_SetMethod = cast(pf_sfHttpRequest_SetMethod)dll.getSymbol("sfHttpRequest_SetMethod");
sfHttpRequest_SetURI = cast(pf_sfHttpRequest_SetURI)dll.getSymbol("sfHttpRequest_SetURI");
sfHttpRequest_SetHttpVersion = cast(pf_sfHttpRequest_SetHttpVersion)dll.getSymbol("sfHttpRequest_SetHttpVersion");
sfHttpRequest_SetBody = cast(pf_sfHttpRequest_SetBody)dll.getSymbol("sfHttpRequest_SetBody");
}
}
/**
* Constructor
*/
this()
{
super(sfHttp_Create());
}
/**
* Constructor
*
* Params:
* host = Web server to connect to
* port = port to use for connection (0 by default -- use the standard port of the protocol)
*/
this(char[] host, ushort port = 0)
{
super(sfHttp_Create());
sfHttp_SetHost(m_ptr, toStringz(host), port);
}
override void dispose()
{
sfHttp_Destroy(m_ptr);
}
/**
* Set the target host.
*
* Params:
* host = Web server to connect to
* port = port to use for connection (0 by default -- use the standard port of the protocol)
*/
void setHost(char[] host, ushort port = 0)
{
sfHttp_SetHost(m_ptr, toStringz(host), port);
}
/**
* Send a HTTP request and return the server's response.
* You must be connected to a host before sending requests.
* Any missing mandatory header field will be added with an appropriate value.
*
* Warning : this function waits for the server's response and may
* not return instantly; use a thread if you don't want to block your
* application.
*
* Params:
* req = Request to send
*
* Returns:
* Server's response
*/
Response sendRequest(Request req)
{
return new Response( sfHttp_SendRequest(m_ptr, req.getNativePointer) );
}
private:
// External ====================================================================
extern (C)
{
typedef void* function() pf_sfHttp_Create;
typedef void function(void*) pf_sfHttp_Destroy;
typedef void function(void*, char*, ushort) pf_sfHttp_SetHost;
typedef void* function(void*, void*) pf_sfHttp_SendRequest;
static pf_sfHttp_Create sfHttp_Create;
static pf_sfHttp_Destroy sfHttp_Destroy;
static pf_sfHttp_SetHost sfHttp_SetHost;
static pf_sfHttp_SendRequest sfHttp_SendRequest;
}
static this()
{
DllLoader dll = DllLoader.load("csfml-network");
sfHttp_Create = cast(pf_sfHttp_Create)dll.getSymbol("sfHttp_Create");
sfHttp_Destroy = cast(pf_sfHttp_Destroy)dll.getSymbol("sfHttp_Destroy");
sfHttp_SetHost = cast(pf_sfHttp_SetHost)dll.getSymbol("sfHttp_SetHost");
sfHttp_SendRequest = cast(pf_sfHttp_SendRequest)dll.getSymbol("sfHttp_SendRequest");
}
}

View file

@ -0,0 +1,164 @@
/*
* DSFML - SFML Library binding in D language.
* Copyright (C) 2008 Julien Dagorn (sirjulio13@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.
*/
module dsfml.network.ipaddress;
import dsfml.system.common;
import dsfml.system.stringutil;
/**
* IPAddress provides easy manipulation of IP v4 addresses
*/
struct IPAddress
{
/**
* Construct the address from a string
*
* Params:
* address = IP address ("xxx.xxx.xxx.xxx") or network name
*
*/
static IPAddress opCall(char[] address)
{
return sfIPAddress_FromString(toStringz(address));
}
/**
* Construct the address from 4 bytes
*
* Params:
* byte0 = First byte of the address
* byte1 = Second byte of the address
* byte2 = Third byte of the address
* byte3 = Fourth byte of the address
*
*/
static IPAddress opCall(ubyte byte0, ubyte byte1, ubyte byte2, ubyte byte3)
{
return sfIPAddress_FromBytes(byte0, byte1, byte2, byte3);
}
/**
* Construct the address from a 32 bits integer
*
* Params:
* address = 4 bytes of the address packed into a 32 bits integer
*
*/
static IPAddress opCall(uint address)
{
return sfIPAddress_FromInteger(address);
}
/**
* Tell if the address is a valid one
*
* Returns:
* True if address has a valid syntax
*
*/
bool isValid()
{
return cast(bool)sfIPAddress_IsValid(*this);
}
/**
* Get the computer's local IP address (from the LAN point of view)
*
* Returns:
* Local IP address
*
*/
static IPAddress getLocalAddress()
{
return sfIPAddress_GetLocalAddress();
}
/**
* Get the computer's public IP address (from the web point of view).
* The only way to get a public address is to ask it to a
* distant website ; as a consequence, this function may be
* very slow -- use it as few as possible !
*
* Returns:
* Public IP address
*
*/
static IPAddress getPublicAddress()
{
return sfIPAddress_GetPublicAddress();
}
bool opEqual(IPAddress other)
{
return Address == other.Address;
}
/**
* Local host address (to connect to the same computer).
*/
static IPAddress LOCALHOST()
{
return sfIPAddress_LocalHost();
}
byte[16] Address;
}
private:
extern (C)
{
typedef IPAddress function(char*) pf_sfIPAddress_FromString;
typedef IPAddress function(ubyte, ubyte, ubyte, ubyte) pf_sfIPAddress_FromBytes;
typedef IPAddress function(uint) pf_sfIPAddress_FromInteger;
typedef int function(IPAddress) pf_sfIPAddress_IsValid;
typedef IPAddress function() pf_sfIPAddress_GetLocalAddress;
typedef IPAddress function() pf_sfIPAddress_GetPublicAddress;
typedef IPAddress function() pf_sfIPAddress_LocalHost;
static pf_sfIPAddress_FromString sfIPAddress_FromString;
static pf_sfIPAddress_FromBytes sfIPAddress_FromBytes;
static pf_sfIPAddress_FromInteger sfIPAddress_FromInteger;
static pf_sfIPAddress_IsValid sfIPAddress_IsValid;
static pf_sfIPAddress_GetLocalAddress sfIPAddress_GetLocalAddress;
static pf_sfIPAddress_GetPublicAddress sfIPAddress_GetPublicAddress;
static pf_sfIPAddress_LocalHost sfIPAddress_LocalHost;
}
static this()
{
DllLoader dll = DllLoader.load("csfml-network");
sfIPAddress_FromBytes = cast(pf_sfIPAddress_FromBytes)dll.getSymbol("sfIPAddress_FromBytes");
sfIPAddress_FromString = cast(pf_sfIPAddress_FromString)dll.getSymbol("sfIPAddress_FromString");
sfIPAddress_FromInteger = cast(pf_sfIPAddress_FromInteger)dll.getSymbol("sfIPAddress_FromInteger");
sfIPAddress_GetLocalAddress = cast(pf_sfIPAddress_GetLocalAddress)dll.getSymbol("sfIPAddress_GetLocalAddress");
sfIPAddress_GetPublicAddress = cast(pf_sfIPAddress_GetPublicAddress)dll.getSymbol("sfIPAddress_GetPublicAddress");
sfIPAddress_IsValid = cast(pf_sfIPAddress_IsValid)dll.getSymbol("sfIPAddress_IsValid");
sfIPAddress_LocalHost = cast(pf_sfIPAddress_LocalHost)dll.getSymbol("sfIPAddress_LocalHost");
}

View file

@ -0,0 +1,413 @@
/*
* DSFML - SFML Library binding in D language.
* Copyright (C) 2008 Julien Dagorn (sirjulio13@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.
*/
module dsfml.network.packet;
import dsfml.system.common;
import dsfml.system.stringutil;
/**
* Packet wraps data to send / to receive through the network
*
* The order of insertion and extraction must be the same.
*
* You can derive from Packet and override onSend and onReceive to do custom operations before send or after reception.
*
* Litterals integer are promoted to int.
* Litterals floating point are promoted to float.
*
* Extraction or insertion can be specified with explicit template.
* Examples:
* ------------------------------------------------------------
* Packet p = new Packet();
*
* int i = 32, j = 42;
* char[] k = hello;
*
* p.set(i, k, j); //Set the data in the packet
*
* int a, b;
* char[] c;
* p.get(a, c, b); //Get data from the packet
*
* //...
*
* Packet p = new Packet();
* p.set!(byte)(5); // Litteral are inserted with byte type
* ------------------------------------------------------------
*
* See_Also:
* $(LINK2 http://www.digitalmars.com/d/1.0/lex.html, D litterals Specification) for more informations.
*/
class Packet : DSFMLObject
{
/**
* Default constructor
*
*/
this()
{
super(sfPacket_Create());
}
override void dispose()
{
sfPacket_Destroy(m_ptr);
}
/**
* Append data to the end of the packet.
*
* Params:
* data = Array of data to append
*
*/
void append(byte[] data)
{
if (data !is null)
sfPacket_Append(m_ptr, data.ptr, data.length);
}
/**
* Clear the packet data
*
*/
void clear()
{
sfPacket_Clear(m_ptr);
}
/**
* Get an array to the data contained in the packet
* $(B the returned array may be invalid after you
* append data to the packet)
*
* Returns:
* array of data
*
* Remarks:
* return an array of $(B all) data in the packet.
*
* ----------
* Packet p = new Packet();
*
* char[] str1 = "Hi";
* char[] str2 = "Hello";
*
* p.set(str1, str2);
*
* // Retrieve str1 from packet
* char[] str3;
* p.get(str3);
*
* // Returns an array containing str1 and str2.
* byte[] ptr = p.getData();
* ----------
*/
byte[] getData()
{
if (canRead)
return sfPacket_GetData(m_ptr)[0..getDataSize];
}
/**
* Get the size of the data contained in the packet
*
* Returns:
* Data size, in bytes
*/
uint getDataSize()
{
return sfPacket_GetDataSize(m_ptr);
}
/**
* Tell if the reading position has reached the end of the packet
*
* Returns:
* true if all data have been read.
*/
bool endOfPacket()
{
return cast(bool)sfPacket_EndOfPacket(m_ptr);
}
/**
* Tell if the packet is valid for reading
*
* Returns:
* True if data can be extracted from the packet
*
*/
bool canRead()
{
return cast(bool)sfPacket_CanRead(m_ptr);
}
/**
* Add new variables to the packet
* Accept (u)byte, (u)short, (u)int, float, double, char[] and wchar[] types
*/
Packet set(T...)(T t)
{
foreach (v; t)
internalSet(t);
return this;
}
/**
* Retrieve data from the packet
* Accept (u)byte, (u)short, (u)int, float, double, char[] and wchar[] types
*/
Packet get(T...)(ref T t)
{
foreach (v; t)
internalGet(t);
return this;
}
/**
* Called before packet is send
*
* Params:
* size = Variable to fill with the size of the data to send
* Returns:
* Array of byte to send
*/
byte[] onSend()
{
return getData();
}
/**
* Called after a packet has been received
*
* Params:
* data = Array of byte received
*/
void onReceive(byte[] data)
{
append(data);
}
private:
void internalGet(ref bool data)
{
data = cast(bool)sfPacket_ReadInt32(m_ptr);
}
void internalGet(ref byte data)
{
data = sfPacket_ReadInt8(m_ptr);
}
void internalGet(ref ubyte data)
{
data = sfPacket_ReadUint8(m_ptr);
}
void internalGet(ref short data)
{
data = sfPacket_ReadInt16(m_ptr);
}
void internalGet(ref ushort data)
{
data = sfPacket_ReadUint16(m_ptr);
}
void internalGet(ref int data)
{
data = sfPacket_ReadInt32(m_ptr);
}
void internalGet(ref uint data)
{
data = sfPacket_ReadUint32(m_ptr);
}
void internalGet(ref float data)
{
data = sfPacket_ReadFloat(m_ptr);
}
void internalGet(ref double data)
{
data = sfPacket_ReadDouble(m_ptr);
}
void internalGet(ref char[] data)
{
scope char[] temp = new char[sfPacket_GetDataSize(m_ptr)];
sfPacket_ReadString(m_ptr, temp.ptr);
size_t l = fromStringz(temp.ptr).length;
data = new char[l];
data[] = temp[0 .. l];
}
void internalGet(ref wchar[] data)
{
scope wchar[] temp = new wchar[sfPacket_GetDataSize(m_ptr)];
sfPacket_ReadWideString(m_ptr, temp.ptr);
size_t l = fromStringz(temp.ptr).length;
data = new wchar[l];
data[] = temp[0 .. l];
}
void internalSet(bool data)
{
sfPacket_WriteInt32(m_ptr, cast(int)data);
}
void internalSet(byte data)
{
sfPacket_WriteInt8(m_ptr, data);
}
void internalSet(ubyte data)
{
sfPacket_WriteUint8(m_ptr, data);
}
void internalSet(short data)
{
sfPacket_WriteInt16(m_ptr, data);
}
void internalSet(ushort data)
{
sfPacket_WriteUint16(m_ptr, data);
}
void internalSet(int data)
{
sfPacket_WriteInt32(m_ptr, data);
}
void internalSet(uint data)
{
sfPacket_WriteUint32(m_ptr, data);
}
void internalSet(float data)
{
sfPacket_WriteFloat(m_ptr, data);
}
void internalSet(double data)
{
sfPacket_WriteDouble(m_ptr, data);
}
void internalSet(char[] data)
{
sfPacket_WriteString(m_ptr, toStringz(data));
}
void internalSet(wchar[] data)
{
sfPacket_WriteWideString(m_ptr, toStringz(data));
}
// External ====================================================================
extern (C)
{
typedef void* function() pf_sfPacket_Create;
typedef void function(void*) pf_sfPacket_Destroy;
typedef void function(void*, void*, size_t) pf_sfPacket_Append;
typedef void function(void*) pf_sfPacket_Clear;
typedef byte* function(void*) pf_sfPacket_GetData;
typedef uint function(void*) pf_sfPacket_GetDataSize;
typedef int function(void*) pf_sfPacket_EndOfPacket;
typedef int function(void*) pf_sfPacket_CanRead;
typedef byte function(void*) pf_sfPacket_ReadInt8;
typedef ubyte function(void*) pf_sfPacket_ReadUint8;
typedef short function(void*) pf_sfPacket_ReadInt16;
typedef ushort function(void*) pf_sfPacket_ReadUint16;
typedef int function(void*) pf_sfPacket_ReadInt32;
typedef uint function(void*) pf_sfPacket_ReadUint32;
typedef float function(void*) pf_sfPacket_ReadFloat;
typedef double function(void*) pf_sfPacket_ReadDouble;
typedef void function(void*, char*) pf_sfPacket_ReadString;
typedef void function(void*, wchar*) pf_sfPacket_ReadWideString;
typedef void function(void*, byte) pf_sfPacket_WriteInt8;
typedef void function(void*, ubyte) pf_sfPacket_WriteUint8;
typedef void function(void*, short) pf_sfPacket_WriteInt16;
typedef void function(void*, ushort) pf_sfPacket_WriteUint16;
typedef void function(void*, int) pf_sfPacket_WriteInt32;
typedef void function(void*, uint) pf_sfPacket_WriteUint32;
typedef void function(void*, float) pf_sfPacket_WriteFloat;
typedef void function(void*, double) pf_sfPacket_WriteDouble;
typedef void function(void*, char*) pf_sfPacket_WriteString;
typedef void function(void*, wchar*) pf_sfPacket_WriteWideString;
static pf_sfPacket_Create sfPacket_Create;
static pf_sfPacket_Destroy sfPacket_Destroy;
static pf_sfPacket_Append sfPacket_Append;
static pf_sfPacket_Clear sfPacket_Clear;
static pf_sfPacket_GetData sfPacket_GetData;
static pf_sfPacket_GetDataSize sfPacket_GetDataSize;
static pf_sfPacket_EndOfPacket sfPacket_EndOfPacket;
static pf_sfPacket_CanRead sfPacket_CanRead;
static pf_sfPacket_ReadInt8 sfPacket_ReadInt8;
static pf_sfPacket_ReadUint8 sfPacket_ReadUint8;
static pf_sfPacket_ReadInt16 sfPacket_ReadInt16;
static pf_sfPacket_ReadUint16 sfPacket_ReadUint16;
static pf_sfPacket_ReadInt32 sfPacket_ReadInt32;
static pf_sfPacket_ReadUint32 sfPacket_ReadUint32;
static pf_sfPacket_ReadFloat sfPacket_ReadFloat;
static pf_sfPacket_ReadDouble sfPacket_ReadDouble;
static pf_sfPacket_ReadString sfPacket_ReadString;
static pf_sfPacket_ReadWideString sfPacket_ReadWideString;
static pf_sfPacket_WriteInt8 sfPacket_WriteInt8;
static pf_sfPacket_WriteUint8 sfPacket_WriteUint8;
static pf_sfPacket_WriteInt16 sfPacket_WriteInt16;
static pf_sfPacket_WriteUint16 sfPacket_WriteUint16;
static pf_sfPacket_WriteInt32 sfPacket_WriteInt32;
static pf_sfPacket_WriteUint32 sfPacket_WriteUint32;
static pf_sfPacket_WriteFloat sfPacket_WriteFloat;
static pf_sfPacket_WriteDouble sfPacket_WriteDouble;
static pf_sfPacket_WriteString sfPacket_WriteString;
static pf_sfPacket_WriteWideString sfPacket_WriteWideString;
}
static this()
{
DllLoader dll = DllLoader.load("csfml-network");
sfPacket_Append = cast(pf_sfPacket_Append)dll.getSymbol("sfPacket_Append");
sfPacket_CanRead = cast(pf_sfPacket_CanRead)dll.getSymbol("sfPacket_CanRead");
sfPacket_Clear = cast(pf_sfPacket_Clear)dll.getSymbol("sfPacket_Clear");
sfPacket_Create = cast(pf_sfPacket_Create)dll.getSymbol("sfPacket_Create");
sfPacket_Destroy = cast(pf_sfPacket_Destroy)dll.getSymbol("sfPacket_Destroy");
sfPacket_EndOfPacket = cast(pf_sfPacket_EndOfPacket)dll.getSymbol("sfPacket_EndOfPacket");
sfPacket_GetData = cast(pf_sfPacket_GetData)dll.getSymbol("sfPacket_GetData");
sfPacket_GetDataSize = cast(pf_sfPacket_GetDataSize)dll.getSymbol("sfPacket_GetDataSize");
sfPacket_ReadDouble = cast(pf_sfPacket_ReadDouble)dll.getSymbol("sfPacket_ReadDouble");
sfPacket_ReadFloat = cast(pf_sfPacket_ReadFloat)dll.getSymbol("sfPacket_ReadFloat");
sfPacket_ReadInt16 = cast(pf_sfPacket_ReadInt16)dll.getSymbol("sfPacket_ReadInt16");
sfPacket_ReadInt32 = cast(pf_sfPacket_ReadInt32)dll.getSymbol("sfPacket_ReadInt32");
sfPacket_ReadInt8 = cast(pf_sfPacket_ReadInt8)dll.getSymbol("sfPacket_ReadInt8");
sfPacket_ReadString = cast(pf_sfPacket_ReadString)dll.getSymbol("sfPacket_ReadString");
sfPacket_ReadWideString = cast(pf_sfPacket_ReadWideString)dll.getSymbol("sfPacket_ReadWideString");
sfPacket_ReadUint16 = cast(pf_sfPacket_ReadUint16)dll.getSymbol("sfPacket_ReadUint16");
sfPacket_ReadUint32 = cast(pf_sfPacket_ReadUint32)dll.getSymbol("sfPacket_ReadUint32");
sfPacket_ReadUint8 = cast(pf_sfPacket_ReadUint8)dll.getSymbol("sfPacket_ReadUint8");
sfPacket_WriteDouble = cast(pf_sfPacket_WriteDouble)dll.getSymbol("sfPacket_WriteDouble");
sfPacket_WriteFloat = cast(pf_sfPacket_WriteFloat)dll.getSymbol("sfPacket_WriteFloat");
sfPacket_WriteInt16 = cast(pf_sfPacket_WriteInt16)dll.getSymbol("sfPacket_WriteInt16");
sfPacket_WriteInt32 = cast(pf_sfPacket_WriteInt32)dll.getSymbol("sfPacket_WriteInt32");
sfPacket_WriteInt8 = cast(pf_sfPacket_WriteInt8)dll.getSymbol("sfPacket_WriteInt8");
sfPacket_WriteString = cast(pf_sfPacket_WriteString)dll.getSymbol("sfPacket_WriteString");
sfPacket_WriteWideString = cast(pf_sfPacket_WriteWideString)dll.getSymbol("sfPacket_WriteWideString");
sfPacket_WriteUint16 = cast(pf_sfPacket_WriteUint16)dll.getSymbol("sfPacket_WriteUint16");
sfPacket_WriteUint32 = cast(pf_sfPacket_WriteUint32)dll.getSymbol("sfPacket_WriteUint32");
sfPacket_WriteUint8 = cast(pf_sfPacket_WriteUint8)dll.getSymbol("sfPacket_WriteUint8");
}
}

View file

@ -0,0 +1,187 @@
/*
* DSFML - SFML Library binding in D language.
* Copyright (C) 2008 Julien Dagorn (sirjulio13@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.
*/
module dsfml.network.selector;
import dsfml.network.sockettcp;
import dsfml.network.socketudp;
import dsfml.system.common;
/**
* Selector TCP allow reading from multiple sockets
* without blocking. It's a kind of multiplexer. Use SocketTCP or
* SocketUDP aliases.
*/
class Selector(T) : DSFMLObject
{
//Ensure type is correct
static if (!is(T : SocketTCP) && !is(T : SocketUDP))
static assert("Only SocketTCP and SocketUDP are valid for Selector.");
/**
* Default constructor
*/
this()
{
super(sfSelector_Create());
}
override void dispose()
{
sfSelector_Destroy(m_ptr);
}
/**
* Add a socket to watch
*
* Params:
* socket = A tcp or udp socket
*/
void add(T socket)
{
if (!(socket.getNativePointer in m_watchedSockets))
{
sfSelector_Add(m_ptr, socket.getNativePointer);
m_watchedSockets[socket.getNativePointer] = socket;
m_numSocketsWatched++;
}
}
/**
* Remove a previously added socket
*
* Params:
* socket = A tcp or udp socket
*/
void remove(T socket)
{
if (socket.getNativePointer in m_watchedSockets)
{
sfSelector_Remove(m_ptr, socket.getNativePointer);
m_watchedSockets.remove(socket.getNativePointer);
m_numSocketsWatched--;
}
}
/**
* Clear all sockets being watched
*/
void clear()
{
sfSelector_Clear(m_ptr);
foreach(key; m_watchedSockets.keys)
m_watchedSockets.remove(key);
m_numSocketsWatched = 0;
}
/**
* Wait and collect sockets which are ready for reading.
* This functions will return either when at least one socket
* is ready, or when the given time is out
*
* Params:
* timeout = Maximum time to wait, in seconds (0 to disable timeout)
*
* Returns:
* Number of sockets ready
*/
uint wait(float timeout = 0.f)
{
return sfSelector_Wait(m_ptr, timeout);
}
/**
* After a call to Wait(), get the Index-th socket which is
* ready for reading. The total number of sockets ready
* is the integer returned by the previous call to Wait()
*
* Params:
* index = Index of the socket to get
*
* Returns:
* The Index-th socket
*/
T GetSocketsReady(uint index)
{
return m_watchedSockets[sfSelector_GetSocketReady(m_ptr, index)];
}
private:
size_t m_numSocketsWatched;
T[void*] m_watchedSockets;
// External ====================================================================
extern (C)
{
typedef void* function() pf_sfSelector_Create;
typedef void function(void*) pf_sfSelector_Destroy;
typedef void function(void*, void*) pf_sfSelector_Add;
typedef void function(void*, void*) pf_sfSelector_Remove;
typedef void function(void*) pf_sfSelector_Clear;
typedef uint function(void*, float) pf_sfSelector_Wait;
typedef void* function(void*, uint) pf_sfSelector_GetSocketReady;
static pf_sfSelector_Create sfSelector_Create;
static pf_sfSelector_Destroy sfSelector_Destroy;
static pf_sfSelector_Add sfSelector_Add;
static pf_sfSelector_Remove sfSelector_Remove;
static pf_sfSelector_Clear sfSelector_Clear;
static pf_sfSelector_Wait sfSelector_Wait;
static pf_sfSelector_GetSocketReady sfSelector_GetSocketReady;
}
static this()
{
DllLoader dll = DllLoader.load("csfml-network");
static if (is (T : SocketTCP))
{
char[] symbol = "sfSelectorTCP";
}
else static if (is (T : SocketUDP))
{
char[] symbol = "sfSelectorUDP";
}
sfSelector_Add = cast(pf_sfSelector_Add)dll.getSymbol(symbol ~ "_Add");
sfSelector_Clear = cast(pf_sfSelector_Clear)dll.getSymbol(symbol ~ "_Clear");
sfSelector_Create = cast(pf_sfSelector_Create)dll.getSymbol(symbol ~ "_Create");
sfSelector_Destroy = cast(pf_sfSelector_Destroy)dll.getSymbol(symbol ~ "_Destroy");
sfSelector_GetSocketReady = cast(pf_sfSelector_GetSocketReady)dll.getSymbol(symbol ~ "_GetSocketReady");
sfSelector_Wait = cast(pf_sfSelector_Wait)dll.getSymbol(symbol ~ "_Wait");
sfSelector_Remove = cast(pf_sfSelector_Remove)dll.getSymbol(symbol ~ "_Remove");
}
}
/**
* alias of selector for TCP or UDP Socket.
*/
alias Selector!(SocketTCP) SelectorTCP;
/// ditto
alias Selector!(SocketUDP) SelectorUDP;

View file

@ -0,0 +1,37 @@
/*
* DSFML - SFML Library binding in D language.
* Copyright (C) 2008 Julien Dagorn (sirjulio13@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.
*/
module dsfml.network.socketstatus;
/**
* Enumeration of status returned by socket functions
*/
enum SocketStatus
{
DONE, ///
NOTREADY, ///
DISCONNECTED, ///
UNEXPECTEDERROR ///
}

View file

@ -0,0 +1,268 @@
/*
* DSFML - SFML Library binding in D language.
* Copyright (C) 2008 Julien Dagorn (sirjulio13@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.
*/
module dsfml.network.sockettcp;
import dsfml.network.ipaddress;
import dsfml.network.packet;
import dsfml.network.socketstatus;
import dsfml.system.common;
/**
* SocketTCP wraps a socket using TCP protocol to send data safely (but a bit slower)
*/
class SocketTCP : DSFMLObject
{
/**
* Default constructor
*/
this()
{
super(sfSocketTCP_Create());
m_intermediatePacket = new Packet();
}
override void dispose()
{
sfSocketTCP_Destroy(m_ptr);
}
/**
* Connect to another computer on a specified port
*
* Params:
* port = Port to use for transfers (warning : ports < 1024 are reserved)
* hostAddress = IP Address of the host to connect to
* timeout = Maximum time to wait in seconds (0 by default : no timeout)
*
* Returns:
* True if operation has been successful
*/
bool connect(ushort port, IPAddress hostAddress, float timeout = 0.f)
{
return cast(bool) !sfSocketTCP_Connect(m_ptr, port, hostAddress, timeout);
}
/**
* Listen to a specified port for incoming data or connections
*
* Params:
* port = Port to listen to
*
* Returns:
* True if operation has been successful
*/
bool listen(ushort port)
{
return cast(bool)sfSocketTCP_Listen(m_ptr, port);
}
/**
* Wait for a connection (must be listening to a port).
* This function is blocking.
*
* Params:
* connected = Socket containing the connection with the connected client
*
* Returns:
* Status code
*/
SocketStatus accept(SocketTCP connected)
{
void* temp = null;
SocketStatus ret = sfSocketTCP_Accept(m_ptr, &temp, null);
connected.m_ptr = temp;
return ret;
}
/**
* Wait for a connection (must be listening to a port).
* This function is blocking.
*
* Params:
* connected = Socket containing the connection with the connected client
* address = Pointer to an address to fill with client infos
*
* Returns:
* Status code
*/
SocketStatus accept(SocketTCP connected, out IPAddress address)
{
void* temp = null;
SocketStatus ret = sfSocketTCP_Accept(m_ptr, &temp, &address);
connected.m_ptr = temp;
return ret;
}
/**
* Send an array of bytes to the host (must be connected first)
*
* Params:
* data = array of bytes to send
*
* Returns:
* Status code
*/
SocketStatus send(byte[] data)
{
if (data && data.length > 0)
return cast(SocketStatus)sfSocketTCP_Send(m_ptr, data.ptr, data.length);
}
/**
* Receive an array of bytes from the host (must be connected first).
* This function will block until a connection was accepted
*
* Params:
* data = array to fill (make sure it is big enough)
* sizeReceived = Number of bytes received
*
* Returns:
* Status code
*
* Remarks:
* Assert if data is null or length == 0
*
*/
SocketStatus receive(byte[] data, out size_t sizeReceived)
{
if (data && data.length > 0)
return cast(SocketStatus)sfSocketTCP_Receive(m_ptr, data.ptr, data.length, &sizeReceived);
}
/**
* Send a packet of data to the host (must be connected first)
*
* Params:
* packetToSend = Packet to send
*
* Returns:
* Status code
*
*/
SocketStatus send(Packet packetToSend)
{
byte[] dataArray = packetToSend.onSend();
m_intermediatePacket.append(dataArray);
SocketStatus stat = cast(SocketStatus)sfSocketTCP_SendPacket(m_ptr, m_intermediatePacket.getNativePointer);
m_intermediatePacket.clear();
return stat;
}
/**
* Receive a packet from the host (must be connected first).
* This function will block if the socket is blocking
*
* Params:
* packetToReceive = Packet to fill with received data
*
* Returns:
* Status code
*
*/
SocketStatus receive(Packet packetToReceive)
{
SocketStatus stat = cast(SocketStatus)sfSocketTCP_ReceivePacket(m_ptr, m_intermediatePacket.getNativePointer);
packetToReceive.onReceive(m_intermediatePacket.getData);
m_intermediatePacket.clear();
return stat;
}
/**
* Check if the socket is in a valid state ; this function
* can be called any time to check if the socket is OK
*
* Returns:
* True if the socket is valid
*
*/
bool isValid()
{
return cast(bool)sfSocketTCP_IsValid(m_ptr);
}
///
bool opEquals(SocketTCP other)
{
return (other.getNativePointer == this.getNativePointer);
}
package:
this (void* ptr)
{
super(ptr);
m_intermediatePacket = new Packet();
}
private:
Packet m_intermediatePacket;
// External ====================================================================
extern (C)
{
typedef void* function() pf_sfSocketTCP_Create;
typedef void function(void*) pf_sfSocketTCP_Destroy;
typedef int function(void*, ushort, IPAddress, float) pf_sfSocketTCP_Connect;
typedef int function(void*, ushort) pf_sfSocketTCP_Listen;
typedef SocketStatus function(void*, void**, IPAddress*) pf_sfSocketTCP_Accept;
typedef SocketStatus function(void*, byte*, size_t) pf_sfSocketTCP_Send;
typedef SocketStatus function(void*, byte*, size_t, size_t*) pf_sfSocketTCP_Receive;
typedef SocketStatus function(void*, void*) pf_sfSocketTCP_SendPacket;
typedef SocketStatus function(void*, void*) pf_sfSocketTCP_ReceivePacket;
typedef int function(void*) pf_sfSocketTCP_IsValid;
static pf_sfSocketTCP_Create sfSocketTCP_Create;
static pf_sfSocketTCP_Destroy sfSocketTCP_Destroy;
static pf_sfSocketTCP_Connect sfSocketTCP_Connect;
static pf_sfSocketTCP_Listen sfSocketTCP_Listen;
static pf_sfSocketTCP_Accept sfSocketTCP_Accept;
static pf_sfSocketTCP_Send sfSocketTCP_Send;
static pf_sfSocketTCP_Receive sfSocketTCP_Receive;
static pf_sfSocketTCP_SendPacket sfSocketTCP_SendPacket;
static pf_sfSocketTCP_ReceivePacket sfSocketTCP_ReceivePacket;
static pf_sfSocketTCP_IsValid sfSocketTCP_IsValid;
}
static this()
{
DllLoader dll = DllLoader.load("csfml-network");
sfSocketTCP_Accept = cast(pf_sfSocketTCP_Accept)dll.getSymbol("sfSocketTCP_Accept");
sfSocketTCP_Connect = cast(pf_sfSocketTCP_Connect)dll.getSymbol("sfSocketTCP_Connect");
sfSocketTCP_Create = cast(pf_sfSocketTCP_Create)dll.getSymbol("sfSocketTCP_Create");
sfSocketTCP_Destroy = cast(pf_sfSocketTCP_Destroy)dll.getSymbol("sfSocketTCP_Destroy");
sfSocketTCP_IsValid = cast(pf_sfSocketTCP_IsValid)dll.getSymbol("sfSocketTCP_IsValid");
sfSocketTCP_Listen = cast(pf_sfSocketTCP_Listen)dll.getSymbol("sfSocketTCP_Listen");
sfSocketTCP_Receive = cast(pf_sfSocketTCP_Receive)dll.getSymbol("sfSocketTCP_Receive");
sfSocketTCP_ReceivePacket = cast(pf_sfSocketTCP_ReceivePacket)dll.getSymbol("sfSocketTCP_ReceivePacket");
sfSocketTCP_Send = cast(pf_sfSocketTCP_Send)dll.getSymbol("sfSocketTCP_Send");
sfSocketTCP_SendPacket = cast(pf_sfSocketTCP_SendPacket)dll.getSymbol("sfSocketTCP_SendPacket");
}
}

View file

@ -0,0 +1,243 @@
/*
* DSFML - SFML Library binding in D language.
* Copyright (C) 2008 Julien Dagorn (sirjulio13@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.
*/
module dsfml.network.socketudp;
import dsfml.network.ipaddress;
import dsfml.network.packet;
import dsfml.network.socketstatus;
import dsfml.system.common;
/**
* SocketUDP wraps a socket using UDP protocol to
* send data fastly (but with less safety)
*/
class SocketUDP : DSFMLObject
{
/**
* Default constructor
*/
this()
{
super(sfSocketUDP_Create());
m_intermediatePacket = new Packet();
}
override void dispose()
{
sfSocketUDP_Destroy(m_ptr);
}
/**
* Bind the socket to a specific port
*
* Params:
* port = Port to bind the socket to
*
* Returns:
* True if operation has been successful
*
*/
bool bind(ushort port)
{
m_port = port;
return cast(bool)sfSocketUDP_Bind(m_ptr, port);
}
/**
* Unbind the socket from its previous port, if any
*
* Returns: True if operation has been successful
*
*/
bool unbind()
{
m_port = 0;
return cast(bool)sfSocketUDP_Unbind(m_ptr, m_port);
}
/**
* Send an array of bytes
*
* Params:
* data = bytes array to send
* address = Address of the computer to send the packet to
* port = Port to send the data to
*
* Returns:
* Status code
*
*/
SocketStatus send(byte[] data, IPAddress address, ushort port)
{
return cast(SocketStatus) sfSocketUDP_Send(m_ptr, data.ptr, data.length, address, port);
}
/**
* Receive an array of bytes.
* This function is blocking.
*
* Params:
* data = Pointer to a byte array to fill (make sure it is big enough)
* sizeReceived = Number of bytes received
* address = Address of the computer which sent the data
*
* Returns:
* Status code
*
* Remarks:
* Assert if data is null or length == 0
*
*/
SocketStatus receive(byte[] data, out size_t sizeReceived, out IPAddress address)
{
SocketStatus ret = sfSocketUDP_Receive(m_ptr, data.ptr, data.length, &sizeReceived, &address);
return ret;
}
/**
* Send a packet of data
*
* Params:
* packetToSend = Packet to send
* address = Address of the computer to send the packet to
* port = Port to send the data to
*
* Returns:
* Status code
*
*/
SocketStatus send(Packet packetToSend, IPAddress address, ushort port)
{
byte[] dataArray = packetToSend.onSend();
m_intermediatePacket.append(dataArray);
SocketStatus stat = cast(SocketStatus)sfSocketUDP_SendPacket(m_ptr, m_intermediatePacket.getNativePointer, address, port);
m_intermediatePacket.clear();
return stat;
}
/**
* Receive a packet.
* This function is blocking.
*
* Params:
* packetToReceive = Packet to fill with received data
* address = Address of the computer which sent the packet
*
* Returns:
* Status code
*
*/
SocketStatus receive(Packet packetToReceive, out IPAddress address)
{
SocketStatus ret = sfSocketUDP_ReceivePacket(m_ptr, m_intermediatePacket.getNativePointer, &address);
packetToReceive.onReceive(m_intermediatePacket.getData);
m_intermediatePacket.clear();
return ret;
}
/**
* Check if the socket is in a valid state ; this function
* can be called any time to check if the socket is OK
*
* Returns:
* True if the socket is valid
*
*/
bool isValid()
{
return cast(bool)sfSocketUDP_IsValid(m_ptr);
}
/**
* Get the port the socket is currently bound to
*
* Returns:
* Current port (0 means the socket is not bound)
*/
ushort getPort()
{
return m_port;
}
///
bool opEquals(SocketUDP other)
{
return (other.getNativePointer == this.getNativePointer);
}
package:
this (void* ptr)
{
super(ptr);
m_intermediatePacket = new Packet();
}
private:
Packet m_intermediatePacket;
ushort m_port;
// External ====================================================================
extern (C)
{
typedef void* function() pf_sfSocketUDP_Create;
typedef void function(void*) pf_sfSocketUDP_Destroy;
typedef int function(void*, ushort) pf_sfSocketUDP_Bind;
typedef int function(void*, ushort) pf_sfSocketUDP_Unbind;
typedef SocketStatus function(void*, byte*, size_t, IPAddress, ushort) pf_sfSocketUDP_Send;
typedef SocketStatus function(void*, byte*, size_t, size_t*, IPAddress*) pf_sfSocketUDP_Receive;
typedef SocketStatus function(void*, void*, IPAddress, ushort) pf_sfSocketUDP_SendPacket;
typedef SocketStatus function(void*, void*, IPAddress*) pf_sfSocketUDP_ReceivePacket;
typedef int function(void*) pf_sfSocketUDP_IsValid;
static pf_sfSocketUDP_Create sfSocketUDP_Create;
static pf_sfSocketUDP_Destroy sfSocketUDP_Destroy;
static pf_sfSocketUDP_Bind sfSocketUDP_Bind;
static pf_sfSocketUDP_Unbind sfSocketUDP_Unbind;
static pf_sfSocketUDP_Send sfSocketUDP_Send;
static pf_sfSocketUDP_Receive sfSocketUDP_Receive;
static pf_sfSocketUDP_SendPacket sfSocketUDP_SendPacket;
static pf_sfSocketUDP_ReceivePacket sfSocketUDP_ReceivePacket;
static pf_sfSocketUDP_IsValid sfSocketUDP_IsValid;
}
static this()
{
DllLoader dll = DllLoader.load("csfml-network");
sfSocketUDP_Bind = cast(pf_sfSocketUDP_Bind)dll.getSymbol("sfSocketUDP_Bind");
sfSocketUDP_Create = cast(pf_sfSocketUDP_Create)dll.getSymbol("sfSocketUDP_Create");
sfSocketUDP_Destroy = cast(pf_sfSocketUDP_Destroy)dll.getSymbol("sfSocketUDP_Destroy");
sfSocketUDP_IsValid = cast(pf_sfSocketUDP_IsValid)dll.getSymbol("sfSocketUDP_IsValid");
sfSocketUDP_Receive = cast(pf_sfSocketUDP_Receive)dll.getSymbol("sfSocketUDP_Receive");
sfSocketUDP_ReceivePacket = cast(pf_sfSocketUDP_ReceivePacket)dll.getSymbol("sfSocketUDP_ReceivePacket");
sfSocketUDP_Send = cast(pf_sfSocketUDP_Send)dll.getSymbol("sfSocketUDP_Send");
sfSocketUDP_SendPacket = cast(pf_sfSocketUDP_SendPacket)dll.getSymbol("sfSocketUDP_SendPacket");
sfSocketUDP_Unbind = cast(pf_sfSocketUDP_Unbind)dll.getSymbol("sfSocketUDP_Unbind");
}
}

View file

@ -0,0 +1,45 @@
/*
* DSFML - SFML Library binding in D language.
* Copyright (C) 2008 Julien Dagorn (sirjulio13@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.
*/
module dsfml.system.all;
version (linux)
{
version (build)
{
pragma(link, "dl"); //Link libdl.so (dlopen, dlsym)
}
}
public import
dsfml.system.clock,
dsfml.system.lock,
dsfml.system.mutex,
dsfml.system.randomizer,
dsfml.system.sleep,
dsfml.system.thread,
dsfml.system.vector2,
dsfml.system.vector3;

View file

@ -0,0 +1,81 @@
/*
* DSFML - SFML Library binding in D language.
* Copyright (C) 2008 Julien Dagorn (sirjulio13@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.
*/
module dsfml.system.alloc;
version (Tango)
{
public import tango.core.Memory;
}
else
{
import std.c.stdlib;
import std.gc;
struct GC
{
static void* malloc(uint size)
{
return std.c.stdlib.malloc(size);
}
static void free(void* ptr)
{
std.c.stdlib.free(ptr);
}
static void addRange(void* ptr, uint size)
{
std.gc.addRange(ptr, ptr + size);
}
static void removeRange(void* ptr)
{
std.gc.removeRange(ptr);
}
}
}
/*
* Template for native non-GCed allocation for interaction between C and D threads.
*/
template Alloc()
{
new (uint size)
{
void* p = GC.malloc(size);
if (!p)
assert(0, "Memory allocation failed");
GC.addRange(p, size);
return p;
}
delete(void* p)
{
GC.removeRange(p);
GC.free(p);
}
}

View file

@ -0,0 +1,97 @@
/*
* DSFML - SFML Library binding in D language.
* Copyright (C) 2008 Julien Dagorn (sirjulio13@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.
*/
module dsfml.system.clock;
import dsfml.system.common;
/**
* Utility class for manipulating time
*/
class Clock : DSFMLObject
{
/**
* Default constructor
*/
this()
{
super(sfClock_Create());
}
/**
* Destructor
*/
override void dispose()
{
sfClock_Destroy(m_ptr);
}
/**
* Return the time elapsed since the last reset
* Returns:
* Elapsed Time in seconds
*/
float getElapsedTime()
{
return sfClock_GetTime(m_ptr);
}
/**
* Restart the timer
*/
void reset()
{
sfClock_Reset(m_ptr);
}
private:
// External ====================================================================
extern (C)
{
typedef void* function() pf_sfClock_Create;
typedef void function(void*) pf_sfClock_Destroy;
typedef float function(void*) pf_sfClock_GetTime;
typedef void function(void*) pf_sfClock_Reset;
static pf_sfClock_Create sfClock_Create;
static pf_sfClock_Destroy sfClock_Destroy;
static pf_sfClock_GetTime sfClock_GetTime;
static pf_sfClock_Reset sfClock_Reset;
static this()
{
DllLoader dll = DllLoader.load("csfml-system");
sfClock_Create = cast(pf_sfClock_Create)dll.getSymbol("sfClock_Create");
sfClock_Destroy = cast(pf_sfClock_Destroy)dll.getSymbol("sfClock_Destroy");
sfClock_GetTime = cast(pf_sfClock_GetTime)dll.getSymbol("sfClock_GetTime");
sfClock_Reset = cast(pf_sfClock_Reset)dll.getSymbol("sfClock_Reset");
}
}
}

View file

@ -0,0 +1,70 @@
/*
* DSFML - SFML Library binding in D language.
* Copyright (C) 2008 Julien Dagorn (sirjulio13@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.
*/
module dsfml.system.common;
public import dsfml.system.dllloader;
/**
* Base class for all DSFML classes.
*/
class DSFMLObject
{
this(void* ptr, bool preventDelete = false)
{
m_ptr = ptr;
}
~this()
{
if (!m_preventDelete)
dispose();
m_ptr = m_ptr.init;
}
abstract void dispose();
void* getNativePointer()
{
return m_ptr;
}
void setHandled(bool handled)
{
m_preventDelete = handled;
}
protected invariant()
{
assert(m_ptr !is null, "Problem occurs with a null pointer in " ~ this.toString);
}
protected:
void* m_ptr;
private:
bool m_preventDelete;
}

View file

@ -0,0 +1,189 @@
/*
* DSFML - SFML Library binding in D language.
* Copyright (C) 2008 Julien Dagorn (sirjulio13@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.
*/
module dsfml.system.dllloader;
import dsfml.system.stringutil;
version (Tango)
{
import tango.io.Console;
import tango.sys.SharedLib;
}
else
{
import std.stdio;
version (Windows)
{
import std.c.windows.windows;
alias HMODULE MODULEHANDLE;
}
version (linux)
{
import std.c.linux.linux;
alias void* MODULEHANDLE;
const int RTLD_NOW = 0x00002;
const int RTLD_GLOBAL = 0x00100;
}
}
static this()
{
version (Tango)
{
SharedLib.throwExceptions = false;
}
}
private void report(char[] msg, char[] lib, char[] symb)
{
char[] str = "Loading error. Reason : " ~ msg ~ " (library : " ~ lib ~ ", symbol : " ~ symb ~ ")";
version (Tango)
{
Cerr(str).newline;
}
else
{
fwritefln(stderr, str);
}
}
/**
* Simple Dll loader.
*/
class DllLoader
{
static DllLoader load(char[] library)
{
version (Windows)
{
char[] libraryName = library ~ ".dll";
}
version (linux)
{
char[] libraryName = "lib" ~ library ~ ".so";
}
if (libraryName in alreadyLoaded)
{
return alreadyLoaded[libraryName];
}
else
{
DllLoader temp = new DllLoader(libraryName);
alreadyLoaded[libraryName] = temp;
return temp;
}
}
~this()
{
close();
}
void* getSymbol(char[] symbolName)
{
void* symb;
version (Tango)
{
symb = m_lib.getSymbol(toStringz(symbolName));
}
else
{
version (Windows)
{
symb = GetProcAddress(m_lib, toStringz(symbolName));
}
version (linux)
{
symb = dlsym(m_lib, toStringz(symbolName));
}
}
if (symb is null)
report( "Symbol cannot be found in specified library", m_libPath, symbolName);
return symb;
}
void close()
{
version (Tango)
{
m_lib.unload();
}
else
{
version (Windows)
{
FreeLibrary(m_lib);
}
version (linux)
{
dlclose(m_lib);
}
alreadyLoaded.remove(this.m_libPath);
}
}
private:
this(char[] libraryPath)
{
m_libPath = libraryPath;
version (Tango)
{
m_lib = SharedLib.load(libraryPath);
}
else
{
version (Windows)
{
m_lib = LoadLibraryA(toStringz(libraryPath));
}
version (linux)
{
m_lib = dlopen(toStringz(libraryPath), RTLD_NOW | RTLD_GLOBAL);
}
}
if (m_lib is null)
report("Cannot open library", m_libPath, null);
}
version (Tango)
{
SharedLib m_lib;
}
else
{
MODULEHANDLE m_lib;
}
static DllLoader[char[]] alreadyLoaded;
char[] m_libPath;
}

View file

@ -0,0 +1,42 @@
/*
* DSFML - SFML Library binding in D language.
* Copyright (C) 2008 Julien Dagorn (sirjulio13@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.
*/
module dsfml.system.exception;
class LoadingException : Exception
{
this(char[] msg)
{
super(msg);
}
}
class NullParameterException : Exception
{
this(char[] msg)
{
super(msg);
}
}

View file

@ -0,0 +1,102 @@
/*
* DSFML - SFML Library binding in D language.
* Copyright (C) 2008 Julien Dagorn (sirjulio13@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.
*/
module dsfml.system.linkedlist;
/*
* Trivial implementation of Queue linked list (for internal use)
*/
class LinkedList(T)
{
Node!(T) head;
Node!(T) tail;
private size_t m_count;
void enqueue(T object)
{
if (empty)
head = tail = new Node!(T)(object);
else
{
tail.Next = new Node!(T)(object);
tail = tail.Next;
}
m_count++;
}
T dequeue()
{
T o;
if (empty)
o = T.init;
else
{
o = head.Data;
head = head.Next;
m_count--;
}
return o;
}
bool empty()
{
return (head is null);
}
size_t getCount()
{
return m_count;
}
void clear()
{
T data;
while ((data = dequeue()) !is T.init) {}
}
int opApply(int delegate(ref T) dg)
{
T data;
int result;
while ((data = dequeue) !is T.init)
{
if ((result = dg(data)) != 0)
break;
}
return result;
}
}
private class Node(T)
{
Node Next;
T Data;
this(T data)
{
Data = data;
}
}

View file

@ -0,0 +1,65 @@
/*
* DSFML - SFML Library binding in D language.
* Copyright (C) 2008 Julien Dagorn (sirjulio13@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.
*/
module dsfml.system.lock;
import dsfml.system.mutex;
/**
* Encapsulation of an critical section. Unlocking is guaranteed when the Lock goes out of scope, even on exception.
*
* Remarks:
* Lock is a scope class, you need to mark Lock object as scope :
*
* -----------------
* Mutex m = new Mutex;
* //..
* {
* scope Lock l = new Lock(m);
* // Critical section
* } // End of critical (Destructor called and mutex unlocked)
* //..
*
* -----------------
*/
scope class Lock
{
/**
* Construct the lock and lock the mutex
*/
this(Mutex m)
{
m_mutex = m;
m_mutex.lock();
}
~this()
{
m_mutex.unlock();
}
private:
Mutex m_mutex;
}

View file

@ -0,0 +1,94 @@
/*
* DSFML - SFML Library binding in D language.
* Copyright (C) 2008 Julien Dagorn (sirjulio13@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.
*/
module dsfml.system.mutex;
import dsfml.system.common;
/**
* Provide portable implementation of Mutual Exclusion object.
*
* Uses CriticalSection on Windows and pthread mutexes on linux.
*/
final class Mutex : DSFMLObject
{
/**
* Constructor
*/
this()
{
super(sfMutex_Create());
}
override void dispose()
{
sfMutex_Destroy(m_ptr);
}
/**
* Lock the mutex
*
* Can be called multiples times, but each lock must be unlocked with unlock()
*/
void lock()
{
sfMutex_Lock(m_ptr);
}
/**
* Unlock the mutex
*/
void unlock()
{
sfMutex_Unlock(m_ptr);
}
private:
// External ====================================================================
extern (C)
{
typedef void* function() pf_sfMutex_Create;
typedef void function(void*) pf_sfMutex_Destroy;
typedef void function(void*) pf_sfMutex_Lock;
typedef void function(void*) pf_sfMutex_Unlock;
static pf_sfMutex_Create sfMutex_Create;
static pf_sfMutex_Destroy sfMutex_Destroy;
static pf_sfMutex_Lock sfMutex_Lock;
static pf_sfMutex_Unlock sfMutex_Unlock;
}
static this()
{
DllLoader dll = DllLoader.load("csfml-system");
sfMutex_Create = cast(pf_sfMutex_Create)dll.getSymbol("sfMutex_Create");
sfMutex_Destroy = cast(pf_sfMutex_Destroy)dll.getSymbol("sfMutex_Destroy");
sfMutex_Lock = cast(pf_sfMutex_Lock)dll.getSymbol("sfMutex_Lock");
sfMutex_Unlock = cast(pf_sfMutex_Unlock)dll.getSymbol("sfMutex_Unlock");
}
}

View file

@ -0,0 +1,130 @@
/*
* DSFML - SFML Library binding in D language.
* Copyright (C) 2008 Julien Dagorn (sirjulio13@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.
*/
module dsfml.system.randomizer;
import dsfml.system.common;
/**
* Randomizer is an utility class for generating pseudo-random
* numbers
*
* Examples:
* -----------------------------------------------------------
* int randI = Randomizer.Random(1, 100);
* float randF = Randomizer.Random(1.0, 10.0)
* -----------------------------------------------------------
*/
class Randomizer
{
/**
* Set the seed for the generator. Using a known seed
* allows you to reproduce the same sequence of random number
*
* Params:
* seed = Number to use as the seed
*
*/
static void setSeed(uint seed)
{
sfRandom_SetSeed(seed);
}
/**
* Get the seed used to generate random numbers the generator.
*
* Returns:
* Current seed
*/
static uint getSeed()
{
return sfRandom_GetSeed();
}
/**
* Get a random float number in a given range
*
* Params:
* begin = Start of the range
* end = End of the range
* Returns:
* Random number in [Begin, End]
*/
static float random(float begin, float end)
{
return sfRandom_Float(begin, end);
}
/**
* Get a random integral number in a given range
*
* Params:
* begin = Start of the range
* end = End of the range
* Returns:
* Random number in [Begin, End]
*/
static int random(int begin, int end)
{
return sfRandom_Int(begin, end);
}
private:
/*
* Prevent instanciation
*/
this()
{
}
// External ====================================================================
extern (C)
{
typedef void function(uint) pf_sfRandom_SetSeed;
typedef uint function() pf_sfRandom_GetSeed;
typedef float function(float, float) pf_sfRandom_Float;
typedef int function(int, int) pf_sfRandom_Int;
static pf_sfRandom_SetSeed sfRandom_SetSeed;
static pf_sfRandom_GetSeed sfRandom_GetSeed;
static pf_sfRandom_Float sfRandom_Float;
static pf_sfRandom_Int sfRandom_Int;
}
static this()
{
DllLoader dll = DllLoader.load("csfml-system");
sfRandom_SetSeed = cast(pf_sfRandom_SetSeed)dll.getSymbol("sfRandom_SetSeed");
sfRandom_GetSeed = cast(pf_sfRandom_GetSeed)dll.getSymbol("sfRandom_GetSeed");
sfRandom_Float = cast(pf_sfRandom_Float)dll.getSymbol("sfRandom_Float");
sfRandom_Int = cast(pf_sfRandom_Int)dll.getSymbol("sfRandom_Int");
}
}

View file

@ -0,0 +1,53 @@
/*
* DSFML - SFML Library binding in D language.
* Copyright (C) 2008 Julien Dagorn (sirjulio13@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.
*/
module dsfml.system.sleep;
import dsfml.system.common;
extern(C)
{
typedef void function(float) pf_sfSleep;
private static pf_sfSleep sfSleep;
}
static this()
{
DllLoader dll = DllLoader.load("csfml-system");
sfSleep = cast(pf_sfSleep)dll.getSymbol("sfSleep");
}
/**
* Make the current thread sleep for a given time
*
* Params:
* duration = Time to sleep, in seconds
*/
void sleep(float duration)
{
sfSleep(duration);
}

View file

@ -0,0 +1,169 @@
/*
* DSFML - SFML Library binding in D language.
* Copyright (C) 2008 Julien Dagorn (sirjulio13@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.
*/
module dsfml.system.stringutil;
// version (Tango)
// {
// public import tango.stdc.stringz;
// }
// else
// {
T* toStringz(T)(T[] str)
{
if (str is null)
return null;
else if (str.length && str[$ - 1] is T.init)
return str.ptr;
T[] ret = new T[str.length + 1];
ret[0 .. str.length] = str[0 .. $];
ret[str.length] = 0;
return ret.ptr;
}
size_t stringLength(T)(T* p)
{
if (p is null || *p == T.init)
return 0;
size_t length;
while (*(p + length))
{
length++;
}
return length;
}
T[] fromStringz(T)(T* ptr)
{
T[] ret = new T[stringLength(ptr)];
ret[0..$] = ptr[0..ret.length];
return ret;
}
// /*
// * Tango equivalent functions
// *
// * Author : Keinfarbton
// * Licence : BSD style
// */
// char* toStringz(char[] s)
// {
// if (s.ptr)
// if (!(s.length && s[$-1] is 0))
// s = s ~ '\0';
// return s.ptr;
// }
//
// char[] fromStringz (char* s)
// {
// size_t i;
//
// if (s)
// while (*(s+i))
// ++i;
//
// return s ? s[0 .. i] : null;
// }
//
// wchar* toString16z(wchar[] s)
// {
// if (s.ptr)
// if (!(s.length && s[$-1] is 0))
// s = s ~ '\0';
// return s.ptr;
// }
//
// wchar[] fromString16z (wchar* s)
// {
// size_t i;
//
// if (s)
// while (*(s+i))
// ++i;
//
// return s ? s[0 .. i] : null;
// }
//
// dchar* toString32z (dchar[] s)
// {
// if (s.ptr)
// if (!(s.length && s[$-1] is 0))
// s = s ~ "\0"d;
// return s.ptr;
// }
//
//
// dchar[] fromString32z (dchar* s)
// {
// size_t i;
//
// if (s)
// while (*(s+i))
// ++i;
//
// return s ? s[0 .. i] : null;
// }
// }
version (UnitTest)
{
void main()
{
}
unittest
{
char[] str = "Test";
char[] espaceStr = "string with espace";
dchar[] strW = "Test"d;
dchar[] espaceStrW = "string with espace"d;
char[] empty = "";
dchar[] emptyW = ""d;
char[] nullStr = null;
dchar[] nullStrW = null;
assert(fromStringz(toStringz(str)) == str);
assert(fromStringz(toStringz(espaceStr)) == espaceStr);
assert(fromStringz(toStringz(strW)) == strW);
assert(fromStringz(toStringz(espaceStrW)) == espaceStrW);
assert(fromStringz(toStringz(empty)) == empty);
assert(fromStringz(toStringz(emptyW)) == emptyW);
assert(fromStringz(toStringz(nullStr)) == nullStr);
assert(fromStringz(toStringz(nullStrW)) == nullStrW);
}
}

View file

@ -0,0 +1,216 @@
/*
* DSFML - SFML Library binding in D language.
* Copyright (C) 2008 Julien Dagorn (sirjulio13@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.
*/
module dsfml.system.thread;
version(Tango)
{
static import tango.core.Thread;
alias tango.core.Thread.Thread DThread;
}
else
{
static import std.thread;
alias std.thread.Thread DThread;
}
/**
* Thread defines a simple thread abstraction.
*
* Examples:
* Can be a base class (you need to override void run(void) method) :
* --------------------
* class MyThread : Thread
* {
* void function()
* {
* this.launch();
* }
*
* //Thread entry point
* protected void run()
* {
* }
* }
* --------------------
*
* or
*
* --------------------
* void main()
* {
* Thread t = new Thread(&threadStart);
* t.launch();
* t.wait(); //Wait the end of t thread
* }
*
* //Thread entry point
* void threadStart (void* userData)
* {
*
* }
* --------------------
*
* or
*
* --------------------
* void main()
* {
* MyObject foo = new MyObject();
* Thread t = new Thread(&foo.bar);
* t.launch();
* t.wait(); //Wait the end of t thread
* }
*
* class MyObject
* {
* void bar(void* user)
* {
* //...
* }
* }
* --------------------
*/
class Thread
{
/**
* Construct the thread from a function pointer.
*
* Params:
* func = Entry point of the thread
* userData = Data to pass to the thread function (NULL by default)
*
*/
this(void function(void*) func, void* userData = null)
{
m_t = new DThread(&threadStart);
m_func = func;
m_userData = userData;
}
/**
* Construct the thread from a delegate.
*
* Params:
* dg = Entry point of the thread
* userData = Data to pass to the thread function (NULL by default)
*
*/
this(void delegate(void*) dg, void* userData = null)
{
m_t = new DThread(&threadStart);
m_dg = dg;
m_userData = userData;
m_isDelegate = true;
}
/**
* Run the thread
*/
final void launch()
{
if (!m_running)
{
m_t.start();
m_running = true;
}
}
/**
* Wait until the thread finishes
*/
final void wait()
{
if(m_running)
{
version (Tango)
{
m_t.join();
}
else
{
m_t.wait();
}
}
}
protected:
/**
* Protected constructor
*/
this()
{
m_t = new DThread(&threadStart);
}
/**
* Override this method in class derived from Thread.
*/
void run()
{
if (m_isDelegate)
this.m_dg(this.m_userData);
else
this.m_func(this.m_userData);
}
private:
DThread m_t;
bool m_isDelegate;
bool m_running;
union
{
void function(void*) m_func;
void delegate(void*) m_dg;
}
void* m_userData;
/*
* Thread entry point
*/
version (Tango)
{
final void threadStart()
{
run();
m_running = false;
}
}
else
{
final int threadStart()
{
run();
m_running = false;
return 0;
}
}
}

View file

@ -0,0 +1,160 @@
/*
* DSFML - SFML Library binding in D language.
* Copyright (C) 2008 Julien Dagorn (sirjulio13@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.
*/
module dsfml.system.vector2;
/**
* Vector2 is an utility class for manipulating 2 dimensional
* vectors. Template parameter defines the type of coordinates
* (integer, float, ...)
*/
struct Vector2(T)
{
T x;
T y;
static Vector2 opCall(T x, T y)
{
Vector2!(T) ret;
ret.x = x;
ret.y = y;
return ret;
}
/// unary (-) overload
Vector2 opNeg()
{
return Vector2!(T)(-x, -y);
}
/// (+=) overload
Vector2 opAddAssign(Vector2 other)
{
x += other.x;
y += other.y;
return *this;
}
/// (-=) overload
Vector2 opSubAssign(Vector2 other)
{
x -= other.x;
y -= other.y;
return *this;
}
/// (+) overload
Vector2 opAdd(Vector2 other)
{
return Vector2!(T)( (x + other.x), (y + other.y) );
}
/// (-) overload
Vector2 opSub(Vector2 other)
{
return Vector2!(T) ( (x - other.x), (y - other.y) );
}
/// (*) overload
Vector2 opMul(int i)
{
return Vector2!(T) ( (x * i), (y * i) );
}
/// (*=) overload
Vector2 opMulAssign(int i)
{
x *= i;
y *= i;
return *this;
}
/// (/) overload
Vector2 opDiv(int i)
{
return Vector2!(T) ( (x / i), (y / i));
}
/// (/=) overload
Vector2 opDivAssign(int i)
{
x /= i;
y /= i;
return *this;
}
///
int opEquals(Vector2 other)
{
return (x == other.x) && (y == other.y);
}
}
version (UnitTest)
{
unittest
{
Vector2f main = Vector2f(10f, 10f);
Vector2f other = Vector2f(10f, 10f);
Vector2f result;
result = -main;
assert (result == Vector2f(-10.f, -10.f) );
result = main;
result += other;
assert (result == Vector2f(20.f, 20.f));
result = main;
result -= other;
assert (result == Vector2f(0.f, 0.f));
result = main + other;
assert (result == Vector2f(20.f, 20.f));
result = main - other;
assert (result == Vector2f(0.f, 0.f));
result = main * 10;
assert (result == Vector2f(100.f, 100.f));
result *= 2;
assert (result == Vector2f(200.f, 200.f));
result = main / 2;
assert (result == Vector2f(5.f, 5.f));
result = main;
result /= 2;
assert (result == Vector2f(5.f, 5.f));
}
}
/// Aliases
alias Vector2!(float) Vector2f;
/// ditto
alias Vector2!(int) Vector2i;

View file

@ -0,0 +1,166 @@
/*
* DSFML - SFML Library binding in D language.
* Copyright (C) 2008 Julien Dagorn (sirjulio13@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.
*/
module dsfml.system.vector3;
/**
* Vector3 is an utility class for manipulating 3 dimensional
* vectors. Template parameter defines the type of coordinates
* (integer, float, ...)
*/
struct Vector3(T)
{
T x;
T y;
T z;
static Vector3 opCall(T x, T y, T z)
{
Vector3!(T) ret;
ret.x = x;
ret.y = y;
ret.z = z;
return ret;
}
/// unary (-) overload
Vector3 opNeg()
{
return Vector3!(T)(-x, -y, -z);
}
/// (+=) overload
Vector3 opAddAssign(Vector3 other)
{
x += other.x;
y += other.y;
z += other.z;
return *this;
}
/// (-=) overload
Vector3 opSubAssign(Vector3 other)
{
x -= other.x;
y -= other.y;
z -= other.z;
return *this;
}
/// (+) overload
Vector3 opAdd(Vector3 other)
{
return Vector3!(T)( (x + other.x), (y + other.y), (z + other.z) );
}
/// (-) overload
Vector3 opSub(Vector3 other)
{
return Vector3!(T) ( (x - other.x), (y - other.y), (z - other.z) );
}
/// (*) overload
Vector3 opMul(int i)
{
return Vector3!(T) ( (x * i), (y * i), (z * i) );
}
/// (*=) overload
Vector3 opMulAssign(int i)
{
x *= i;
y *= i;
z *= i;
return *this;
}
/// (/) overload
Vector3 opDiv(int i)
{
return Vector3!(T) ( (x / i), (y / i), (z / i) );
}
/// (/=) overload
Vector3 opDivAssign(int i)
{
x /= i;
y /= i;
z /= i;
return *this;
}
///
int opEquals(Vector3 other)
{
return (x == other.x) && (y == other.y) && (z == other.z) ;
}
}
version (UnitTest)
{
unittest
{
Vector3f main = Vector3f(10f, 10f, 10.f);
Vector3f other = Vector3f(10f, 10f, 10.f);
Vector3f result;
result = -main;
assert (result == Vector3f(-10.f, -10.f, -10.f) );
result = main;
result += other;
assert (result == Vector3f(20.f, 20.f, 20.f));
result = main;
result -= other;
assert (result == Vector3f(0.f, 0.f, 0.f));
result = main + other;
assert (result == Vector3f(20.f, 20.f, 20.f));
result = main - other;
assert (result == Vector3f(0.f, 0.f, 0.f));
result = main * 10;
assert (result == Vector3f(100.f, 100.f, 100.f));
result *= 2;
assert (result == Vector3f(200.f, 200.f, 200.f));
result = main / 2;
assert (result == Vector3f(5.f, 5.f, 5.f));
result = main;
result /= 2;
assert (result == Vector3f(5.f, 5.f, 5.f));
}
}
/// Aliases
alias Vector3!(float) Vector3f;
/// ditto
alias Vector3!(int) Vector3i;

View file

@ -0,0 +1,35 @@
/*
* DSFML - SFML Library binding in D language.
* Copyright (C) 2008 Julien Dagorn (sirjulio13@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.
*/
module dsfml.window.all;
public import
dsfml.window.event,
dsfml.window.input,
dsfml.window.videomode,
dsfml.window.window,
dsfml.window.windowhandle,
dsfml.window.windowsettings,
dsfml.window.windowstyle;

View file

@ -0,0 +1,329 @@
/*
* DSFML - SFML Library binding in D language.
* Copyright (C) 2008 Julien Dagorn (sirjulio13@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.
*/
module dsfml.window.event;
/**
* Definition of key codes for keyboard events
*
* $(B Possibles values:)$(BR)
* Except letters and numbers, you can use :$(BR)
* * LCONTROL, LSHIFT, LALT, LSYSTEM, RCONTROL, RSHIFT, RALT, RSYSTEM.$(BR)
* * LBRACKET, RBRACKET, SEMICOLON, COMMA, PERIOD, QUOTE, SLASH, BACKSLASH, TILDE, EQUAL, DASH.$(BR)
* * SPACE, RETURN, BACK, TAB, PAGEUP, PAGEDOWN, END, HOME, INSERT, DELETE.$(BR)
* * ADD, SUBTRACT, MULTIPLY, DIVIDE, LEFT, RIGHT, UP, DOWN.$(BR)
* * NUMPAD0, NUMPAD1, NUMPAD2, NUMPAD3, NUMPAD4, NUMPAD5, NUMPAD6, NUMPAD7, NUMPAD8, NUMPAD9.$(BR)
* * F1, F2, F3, F4, F5, F6, F7, F8, F9, F10, F11, F12, F13, F14, F15.$(BR)
*/
enum KeyCode
{
A = 'a',
B = 'b',
C = 'c',
D = 'd',
E = 'e',
F = 'f',
G = 'g',
H = 'h',
I = 'i',
J = 'j',
K = 'k',
L = 'l',
M = 'm',
N = 'n',
O = 'o',
P = 'p',
Q = 'q',
R = 'r',
S = 's',
T = 't',
U = 'u',
V = 'v',
W = 'w',
X = 'x',
Y = 'y',
Z = 'z',
NUM0 = '0',
NUM1 = '1',
NUM2 = '2',
NUM3 = '3',
NUM4 = '4',
NUM5 = '5',
NUM6 = '6',
NUM7 = '7',
NUM8 = '8',
NUM9 = '9',
ESCAPE = 256,
LCONTROL,
LSHIFT,
LALT,
LSYSTEM,
RCONTROL,
RSHIFT,
RALT,
RSYSTEM,
MENU,
LBRACKET,
RBRACKET,
SEMICOLON,
COMMA,
PERIOD,
QUOTE,
SLASH,
BACKSLASH,
TILDE,
EQUAL,
DASH,
SPACE,
RETURN,
BACK,
TAB,
PAGEUP,
PAGEDOWN,
END,
HOME,
INSERT,
DELETE,
ADD,
SUBTRACT,
MULTIPLY,
DIVIDE,
LEFT,
RIGHT,
UP,
DOWN,
NUMPAD0,
NUMPAD1,
NUMPAD2,
NUMPAD3,
NUMPAD4,
NUMPAD5,
NUMPAD6,
NUMPAD7,
NUMPAD8,
NUMPAD9,
F1,
F2,
F3,
F4,
F5,
F6,
F7,
F8,
F9,
F10,
F11,
F12,
F13,
F14,
F15,
PAUSE,
}
/**
* Definition of button codes for mouse events
*/
enum MouseButtons
{
LEFT, ///
RIGHT, ///
MIDDLE, ///
XBUTTON1, ///
XBUTTON2 ///
}
/**
* Definition of joystick axis for joystick events
*/
enum JoyAxis
{
AXISX, ///
AXISY, ///
AXISZ, ///
AXISR, ///
AXISU, ///
AXISV, ///
AXISPOV ///
}
/**
* Event defines a system event and its parameters
*/
align(1) struct Event
{
enum EventType
{
CLOSED,
RESIZED,
LOSTFOCUS,
GAINEDFOCUS,
TEXTENTERED,
KEYPRESSED,
KEYRELEASED,
MOUSEWHEELMOVED,
MOUSEBUTTONPRESSED,
MOUSEBUTTONRELEASED,
MOUSEMOVED,
MOUSEENTERED,
MOUSELEFT,
JOYBUTTONPRESSED,
JOYBUTTONRELEASED,
JOYMOVED
}
/**
* Enumeration of the different types of events. Accessing a value of another event that the one received (e.g. Event.Size.Width when receiving an KEYPRESSED event) will result in undefined behavior.
* $(UL
* $(LI CLOSED)
* $(LI LOSTFOCUS)
* $(LI GAINEDFOCUS)
* $(LI RESIZED
* $(UL
* $(LI Event.Size.Width : new Width, in pixels.)
* $(LI Event.Size.Height : new height, in pixels.)
* )
* )
* $(LI TEXTENTERED
* $(UL
* $(LI Event.Text.Unicode : dchar entered.)
* )
* )
* $(LI KEYPRESSED, KEYRELEASED
* $(UL
* $(LI Event.Key.Code : Key code of the key.)
* $(LI Event.Key.Alt : Alt pressed ?)
* $(LI Event.Key.Control : Control pressed ?)
* $(LI Event.Key.Shift : Shift pressed ?)
* )
* )
* $(LI MOUSEWHEELMOVED
* $(UL
* $(LI Event.MouseWheel.Delta : Wheel move (positive if forward, negative else.) )
* )
* )
* $(LI MOUSEBUTTONPRESSED, MOUSEBUTTONRELEASED
* $(UL
* $(LI Event.MouseButton.Button : Mouse button pressed.)
* $(LI Event.MouseButton.X : Cursor X position.)
* $(LI Event.MouseButton.Y : Cursor X position.)
* )
* )
* $(LI MOUSEMOVED
* $(UL
* $(LI Event.MouseMove.X : Cursor X position. Local coordinates.)
* $(LI Event.MouseMove.Y : Cursor Y position. Local coordinates.)
* )
* )
* $(LI MOUSEENTERED)
* $(LI MOUSELEFT)
* $(LI JOYBUTTONPRESSED, JOYBUTTONRELEASED
* $(UL
* $(LI Event.JoyButton.JoystickId : Id of the joystick.)
* $(LI Event.JoyButton.Button : Joystick button pressed.)
* )
* )
* $(LI JOYMOVED
* $(UL
* $(LI Event.JoyMove.JoystickId : Id of the joystick.)
* $(LI Event.JoyMove.Axis : Moved axis.)
* $(LI Event.JoyMove.Position : Actual position of the axis [-100, 100], except for POV [0, 360].)
* )
* )
* )
*/
EventType Type;
union
{
struct SText
{
dchar Unicode;
}
SText Text;
struct SKey
{
KeyCode Code;
bool Alt;
byte[3] Filler1;
bool Control;
byte[3] Filler2;
bool Shift;
byte[3] Filler3;
}
SKey Key;
struct SMouseMove
{
int X;
int Y;
}
SMouseMove MouseMove;
struct SMouseButton
{
MouseButtons Button;
int X;
int Y;
}
SMouseButton MouseButton;
struct SMouseWheel
{
int Delta;
}
SMouseWheel MouseWheel;
struct SJoyMove
{
uint JoystickId;
JoyAxis Axis;
float Position;
}
SJoyMove JoyMove;
struct SJoyButton
{
uint JoystickId;
uint Button;
}
SJoyButton JoyButton;
struct SSize
{
uint Width;
uint Height;
}
SSize Size;
}
}

View file

@ -0,0 +1,162 @@
/*
* DSFML - SFML Library binding in D language.
* Copyright (C) 2008 Julien Dagorn (sirjulio13@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.
*/
module dsfml.window.input;
import dsfml.system.common;
import dsfml.window.event;
/**
* Input handles real-time input from keyboard and mouse.
* Use it instead of events to handle continuous moves and more
* game-friendly inputs
*/
class Input : DSFMLObject
{
/**
* Get the state of a key
*
* Params:
* key = Key to check
*
* Returns:
* True if key is down, false if key is up
*/
bool isKeyDown(KeyCode key)
{
return cast(bool)sfInput_IsKeyDown(m_ptr, key);
}
/**
* Get the state of a mouse button
*
* Params:
* button = Button to check
*
* Returns:
* True if button is down, false if button is up
*/
bool isMouseButtonDown(MouseButtons button)
{
return cast(bool)sfInput_IsMouseButtonDown(m_ptr, button);
}
/**
* Get the state of a joystick button
*
* Params:
* joyId = Identifier of the joystick to check (0 or 1)
* button = Button to check
*
* Returns:
* True if button is down, false if button is up
*/
bool isJoystickButtonDown(uint joyId, uint button)
{
return cast(bool)sfInput_IsJoystickButtonDown(m_ptr, joyId, button);
}
/*
* Get the mouse X position
*
* Returns:
* Current mouse left position, relative to owner window
*/
int getMouseX()
{
return sfInput_GetMouseX(m_ptr);
}
/**
* Get the mouse Y position
*
* Returns:
* Current mouse top position, relative to owner window
*
*/
int getMouseY()
{
return sfInput_GetMouseY(m_ptr);
}
/**
* Get a joystick axis position
*
* Params:
* joyId = Identifier of the joystick to check (0 or 1)
* axis = Axis to get
*
* Returns:
* Current axis position, in the range [-100, 100] (except for POV, which is [0, 360])
*/
float getJoystickAxis(uint joyId, JoyAxis axis)
{
return sfInput_GetJoystickAxis(m_ptr, joyId, axis);
}
this(void* input)
{
super(input, true);
}
override void dispose()
{
// nothing to do
}
private:
// External ====================================================================
extern (C)
{
typedef int function(void*, KeyCode) pf_sfInput_IsKeyDown;
typedef int function(void*, MouseButtons) pf_sfInput_IsMouseButtonDown;
typedef int function(void*, uint, uint) pf_sfInput_IsJoystickButtonDown;
typedef uint function (void*) pf_sfInput_GetMouseX;
typedef uint function(void*) pf_sfInput_GetMouseY;
typedef float function(void*, uint, JoyAxis) pf_sfInput_GetJoystickAxis;
static pf_sfInput_IsKeyDown sfInput_IsKeyDown;
static pf_sfInput_IsMouseButtonDown sfInput_IsMouseButtonDown;
static pf_sfInput_IsJoystickButtonDown sfInput_IsJoystickButtonDown;
static pf_sfInput_GetMouseX sfInput_GetMouseX;
static pf_sfInput_GetMouseY sfInput_GetMouseY;
static pf_sfInput_GetJoystickAxis sfInput_GetJoystickAxis;
}
static this()
{
DllLoader dll = DllLoader.load("csfml-window");
sfInput_IsKeyDown = cast(pf_sfInput_IsKeyDown)dll.getSymbol("sfInput_IsKeyDown");
sfInput_IsMouseButtonDown = cast(pf_sfInput_IsMouseButtonDown)dll.getSymbol("sfInput_IsMouseButtonDown");
sfInput_IsJoystickButtonDown = cast(pf_sfInput_IsJoystickButtonDown)dll.getSymbol("sfInput_IsJoystickButtonDown");
sfInput_GetMouseX = cast(pf_sfInput_GetMouseX)dll.getSymbol("sfInput_GetMouseX");
sfInput_GetMouseY = cast(pf_sfInput_GetMouseY)dll.getSymbol("sfInput_GetMouseY");
sfInput_GetJoystickAxis = cast(pf_sfInput_GetJoystickAxis)dll.getSymbol("sfInput_GetJoystickAxis");
}
}

View file

@ -0,0 +1,136 @@
/*
* DSFML - SFML Library binding in D language.
* Copyright (C) 2008 Julien Dagorn (sirjulio13@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.
*/
module dsfml.window.videomode;
import dsfml.system.common;
/**
* VideoMode defines a video mode (width, height, bpp, frequency)
* and provides static functions for getting modes supported
* by the display device
*/
align(1) struct VideoMode
{
static VideoMode opCall(uint width, uint height, uint bitsPerPixel = 32)
{
VideoMode mode;
mode.Width = width;
mode.Height = height;
mode.BitsPerPixel = bitsPerPixel;
return mode;
}
/**
* Get the current desktop video mode
*
* Returns:
* Current desktop video mode
*/
static VideoMode getDesktopMode()
{
return sfVideoMode_GetDesktopMode();
}
/**
* Get a valid video mode
* Index must be in range [0, GetModesCount()[
* Modes are sorted from best to worst
*
* Params:
* index = Index of video mode to get
*
* Returns:
* Corresponding video mode (invalid mode if index is out of range)
*/
static VideoMode getMode(size_t index)
{
return sfVideoMode_GetMode(index);
}
/**
* Get valid video modes count
*
* Returns:
* Number of valid video modes available
*/
static size_t getModesCount()
{
return sfVideoMode_GetModesCount();
}
/**
* Tell whether or not the video mode is supported
*
* Returns:
* True if video mode is supported, false otherwise
*/
bool isValid()
{
return cast(bool)sfVideoMode_IsValid(*this);
}
/**
* Comparison operator overload -- tell if two video modes are equal
*
* Params:
* Other : Video mode to compare
*
* Returns:
* True if modes are equal
*/
bool opEquals(VideoMode other)
{
return ((other.Width == Width) && (other.Height == Height) && (other.BitsPerPixel == BitsPerPixel));
}
uint Width; /// Video mode width, in pixels
uint Height; /// Video mode height, in pixels
uint BitsPerPixel; /// Video mode pixel depth, in bits per pixels
}
extern (C)
{
typedef VideoMode function() pf_sfVideoMode_GetDesktopMode;
typedef VideoMode function(size_t) pf_sfVideoMode_GetMode;
typedef size_t function() pf_sfVideoMode_GetModesCount;
typedef int function(VideoMode) pf_sfVideoMode_IsValid;
pf_sfVideoMode_GetDesktopMode sfVideoMode_GetDesktopMode;
pf_sfVideoMode_GetMode sfVideoMode_GetMode;
pf_sfVideoMode_GetModesCount sfVideoMode_GetModesCount;
pf_sfVideoMode_IsValid sfVideoMode_IsValid;
}
static this()
{
DllLoader dll = DllLoader.load("csfml-window");
sfVideoMode_GetDesktopMode = cast(pf_sfVideoMode_GetDesktopMode)dll.getSymbol("sfVideoMode_GetDesktopMode");
sfVideoMode_GetMode = cast(pf_sfVideoMode_GetMode)dll.getSymbol("sfVideoMode_GetMode");
sfVideoMode_GetModesCount = cast(pf_sfVideoMode_GetModesCount)dll.getSymbol("sfVideoMode_GetModesCount");
sfVideoMode_IsValid = cast(pf_sfVideoMode_IsValid)dll.getSymbol("sfVideoMode_IsValid");
}

View file

@ -0,0 +1,435 @@
/*
* DSFML - SFML Library binding in D language.
* Copyright (C) 2008 Julien Dagorn (sirjulio13@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.
*/
module dsfml.window.window;
import dsfml.window.event;
import dsfml.window.input;
import dsfml.window.videomode;
import dsfml.window.windowhandle;
import dsfml.window.windowsettings;
import dsfml.window.windowstyle;
import dsfml.system.common;
import dsfml.system.stringutil;
/**
* Window is a rendering window ; it can create a new window
* or connect to an existing one
*/
class Window : DSFMLObject
{
/**
* Construct a new window
*
* Params:
* mode = Video mode to use
* title = Title of the window
* windowStyle = Window style (Resize | Close by default)
* settings = Window settings (default is default WindowSettings values)
*/
this(VideoMode mode, char[] title, Style windowStyle = Style.RESIZE | Style.CLOSE, WindowSettings settings = WindowSettings())
{
super(sfWindow_Create(mode, toStringz(title), windowStyle, settings));
}
/**
* Construct the window from an existing control
*
* Params:
* handle = Platform-specific handle of the control
* settings = Window settings (default is default WindowSettings values)
*/
this(WindowHandle handle, WindowSettings settings = WindowSettings())
{
super(sfWindow_CreateFromHandle(handle, settings));
}
override void dispose()
{
m_input = null;
sfWindow_Destroy(m_ptr);
}
/**
* Create (or recreate) the window
*
* Input created with getInput becomes invalid.
*
* Params:
* mode = Video mode to use
* title = Title of the window
* windowStyle = Window style (Resize | Close by default)
* settings = Window settings (default is default WindowSettings values)
*/
void create(VideoMode mode, char[] title, Style windowStyle = Style.RESIZE | Style.CLOSE, WindowSettings settings = WindowSettings())
{
if (m_ptr !is null)
dispose();
m_ptr = sfWindow_Create(mode, toStringz(title), windowStyle, settings);
}
/**
* Create (or recreate) the window from an existing control
*
* Input created with getInput becomes invalid.
*
* Params:
* handle = Platform-specific handle of the control
* settings = Window settings (default is default WindowSettings values)
*/
void create(WindowHandle handle, WindowSettings settings = WindowSettings())
{
if (m_ptr !is null)
dispose();
m_ptr = sfWindow_CreateFromHandle(handle, settings);
}
/**
* Close (destroy) the window.
* You can call create to recreate a valid window
*/
void close()
{
sfWindow_Close(m_ptr);
}
/**
* Tell whether or not a window is opened
*
* Returns:
* True if window is currently open.
*/
bool isOpened()
{
return cast(bool)sfWindow_IsOpened(m_ptr);
}
/**
* Get the width of the rendering region of the window
*
* Returns:
* Width in pixels
*/
uint getWidth()
{
return sfWindow_GetWidth(m_ptr);
}
/**
* Get the height of the rendering region of the window
*
* Returns:
* Height in pixels
*/
uint getHeight()
{
return sfWindow_GetHeight(m_ptr);
}
/**
* Get the creation settings of a window
*
* Returns:
* Settings used to create the window
*/
WindowSettings getSettings()
{
return sfWindow_GetSettings(m_ptr);
}
/**
* Get the event on top of events stack, if any, and pop it
*
* Params:
* eventReceived = Event to fill, if any
*
* Returns:
* True if an event was returned, false if events stack was empty
*/
bool getEvent(ref Event eventReceived)
{
return cast(bool)sfWindow_GetEvent(m_ptr, &eventReceived);
}
/**
* Enable / disable vertical synchronization
*
* Params:
* enabled : True to enable v-sync, false to deactivate
*/
void useVerticalSync(bool enabled)
{
sfWindow_UseVerticalSync(m_ptr, enabled);
}
/**
* Show or hide the mouse cursor
*
* Params:
* show : True to show, false to hide
*/
void showMouseCursor(bool show)
{
sfWindow_ShowMouseCursor(m_ptr, show);
}
/**
* Change the position of the mouse cursor
*
* Params:
* left = Left coordinate of the cursor, relative to the window
* top = Top coordinate of the cursor, relative to the window
*/
void setCursorPosition(uint left, uint top)
{
sfWindow_SetCursorPosition(m_ptr, left, top);
}
/**
* Change the position of the window on screen.
* Only works for top-level windows
*
* Params:
* left = Left position
* top = Top position
*/
void setPosition(int left, int top)
{
sfWindow_SetPosition(m_ptr, left, top);
}
/**
* change the size of the rendering region of the window
*
* Params:
* width : new width
* height : new height
*/
void setSize(uint width, uint height)
{
sfWindow_SetSize(m_ptr, width, height);
}
/**
* Show or hide the window
*
* Params:
* state = True to show, false to hide
*
*/
void show(bool state)
{
sfWindow_Show(m_ptr, state);
}
/**
* Enable or disable automatic key-repeat for keydown events.
* Automatic key-repeat is enabled by default.
*
* Params:
* enabled = true to enable, false to disable
*/
void enableKeyRepeat(bool enabled)
{
sfWindow_EnableKeyRepeat(m_ptr, enabled);
}
/**
* Change the window's icon
*
* Params:
* width = Icon's width, in pixels
* height = Icon's height, in pixels
* data = array of pixels in memory, format must be RGBA 32 bits
*
*/
void setIcon(size_t width, size_t height, ubyte[] data)
{
sfWindow_SetIcon(m_ptr, width, height, data.ptr);
}
/**
* Set the window as the current target for rendering
*
* Params:
* active = True to activate, false to deactivate
* Returns:
* True if operation was successful, false otherwise
*/
bool setActive(bool active = true)
{
return cast(bool)sfWindow_SetActive(m_ptr, active);
}
/**
* Display the window on screen
*/
void display()
{
sfWindow_Display(m_ptr);
}
/**
* Get the input manager of the window
*
* Returns:
* An input manager
* See_Also :
* Input
*/
Input getInput()
{
if (m_input is null)
m_input = new Input(sfWindow_GetInput(m_ptr));
return m_input;
}
/**
* Limit the framerate to a maximum fixed frequency
*
* Params:
* limit : Framerate limit, in frames per seconds (use 0 to disable limit)
*/
void setFramerateLimit(uint limit)
{
sfWindow_SetFramerateLimit(m_ptr, limit);
}
/**
* Get time elapsed since last frame
*
* Returns:
* Time elapsed, in seconds
*/
float getFrameTime()
{
return sfWindow_GetFrameTime(m_ptr);
}
/**
* Change the joystick threshold, ie. the value below which
* no move event will be generated
*
* Params:
* threshold : New threshold, in range [0, 100]
*/
void setJoystickThreshold(float threshold)
{
sfWindow_SetJoystickThreshold(m_ptr, threshold);
}
protected:
this(void* ptr)
{
super(ptr);
}
Input m_input;
private:
// External ====================================================================
extern (C)
{
typedef void* function(VideoMode, char*, uint, WindowSettings) pf_sfWindow_Create;
typedef void* function(WindowHandle, WindowSettings) pf_sfWindow_CreateFromHandle;
typedef void function(void*) pf_sfWindow_Destroy;
typedef void function(void*) pf_sfWindow_Close;
typedef int function(void*) pf_sfWindow_IsOpened;
typedef uint function(void*) pf_sfWindow_GetWidth;
typedef uint function(void*) pf_sfWindow_GetHeight;
typedef WindowSettings function(void* Window) pf_sfWindow_GetSettings;
typedef int function(void*, Event*) pf_sfWindow_GetEvent;
typedef void function(void*, int) pf_sfWindow_UseVerticalSync;
typedef void function(void*, int) pf_sfWindow_ShowMouseCursor;
typedef void function(void*, uint, uint) pf_sfWindow_SetCursorPosition;
typedef void function(void*, int, int) pf_sfWindow_SetPosition;
typedef void function(void*, uint, uint) pf_sfWindow_SetSize;
typedef void function(void*, int) pf_sfWindow_Show;
typedef void function(void*, int) pf_sfWindow_EnableKeyRepeat;
typedef void function(void*, size_t, size_t, ubyte*) pf_sfWindow_SetIcon;
typedef int function(void*, int) pf_sfWindow_SetActive;
typedef void function(void*) pf_sfWindow_Display;
typedef void* function(void*) pf_sfWindow_GetInput;
typedef void function(void*, uint) pf_sfWindow_SetFramerateLimit;
typedef float function(void*) pf_sfWindow_GetFrameTime;
typedef void function(void*, float) pf_sfWindow_SetJoystickThreshold;
static pf_sfWindow_Create sfWindow_Create;
static pf_sfWindow_CreateFromHandle sfWindow_CreateFromHandle;
static pf_sfWindow_Destroy sfWindow_Destroy;
static pf_sfWindow_Close sfWindow_Close;
static pf_sfWindow_IsOpened sfWindow_IsOpened;
static pf_sfWindow_GetWidth sfWindow_GetWidth;
static pf_sfWindow_GetHeight sfWindow_GetHeight;
static pf_sfWindow_GetSettings sfWindow_GetSettings;
static pf_sfWindow_GetEvent sfWindow_GetEvent;
static pf_sfWindow_UseVerticalSync sfWindow_UseVerticalSync;
static pf_sfWindow_ShowMouseCursor sfWindow_ShowMouseCursor;
static pf_sfWindow_SetCursorPosition sfWindow_SetCursorPosition;
static pf_sfWindow_SetPosition sfWindow_SetPosition;
static pf_sfWindow_SetSize sfWindow_SetSize;
static pf_sfWindow_Show sfWindow_Show;
static pf_sfWindow_EnableKeyRepeat sfWindow_EnableKeyRepeat;
static pf_sfWindow_SetIcon sfWindow_SetIcon;
static pf_sfWindow_SetActive sfWindow_SetActive;
static pf_sfWindow_Display sfWindow_Display;
static pf_sfWindow_GetInput sfWindow_GetInput;
static pf_sfWindow_SetFramerateLimit sfWindow_SetFramerateLimit;
static pf_sfWindow_GetFrameTime sfWindow_GetFrameTime;
static pf_sfWindow_SetJoystickThreshold sfWindow_SetJoystickThreshold;
}
static this()
{
DllLoader dll = DllLoader.load("csfml-window");
sfWindow_Create = cast(pf_sfWindow_Create)dll.getSymbol("sfWindow_Create");
sfWindow_CreateFromHandle = cast(pf_sfWindow_CreateFromHandle)dll.getSymbol("sfWindow_CreateFromHandle");
sfWindow_Destroy = cast(pf_sfWindow_Destroy)dll.getSymbol("sfWindow_Destroy");
sfWindow_Close = cast(pf_sfWindow_Close)dll.getSymbol("sfWindow_Close");
sfWindow_IsOpened = cast(pf_sfWindow_IsOpened)dll.getSymbol("sfWindow_IsOpened");
sfWindow_GetWidth = cast(pf_sfWindow_GetWidth)dll.getSymbol("sfWindow_GetWidth");
sfWindow_GetHeight = cast(pf_sfWindow_GetHeight)dll.getSymbol("sfWindow_GetHeight");
sfWindow_GetSettings = cast(pf_sfWindow_GetSettings)dll.getSymbol("sfWindow_GetSettings");
sfWindow_GetEvent = cast(pf_sfWindow_GetEvent)dll.getSymbol("sfWindow_GetEvent");
sfWindow_UseVerticalSync = cast(pf_sfWindow_UseVerticalSync)dll.getSymbol("sfWindow_UseVerticalSync");
sfWindow_ShowMouseCursor = cast(pf_sfWindow_ShowMouseCursor)dll.getSymbol("sfWindow_ShowMouseCursor");
sfWindow_SetCursorPosition = cast(pf_sfWindow_SetCursorPosition)dll.getSymbol("sfWindow_SetCursorPosition");
sfWindow_SetPosition = cast(pf_sfWindow_SetPosition)dll.getSymbol("sfWindow_SetPosition");
sfWindow_SetSize = cast(pf_sfWindow_SetSize)dll.getSymbol("sfWindow_SetSize");
sfWindow_Show = cast(pf_sfWindow_Show)dll.getSymbol("sfWindow_Show");
sfWindow_EnableKeyRepeat = cast(pf_sfWindow_EnableKeyRepeat)dll.getSymbol("sfWindow_EnableKeyRepeat");
sfWindow_SetIcon = cast(pf_sfWindow_SetIcon)dll.getSymbol("sfWindow_SetIcon");
sfWindow_SetActive = cast(pf_sfWindow_SetActive)dll.getSymbol("sfWindow_SetActive");
sfWindow_Display = cast(pf_sfWindow_Display)dll.getSymbol("sfWindow_Display");
sfWindow_GetInput = cast(pf_sfWindow_GetInput)dll.getSymbol("sfWindow_GetInput");
sfWindow_SetFramerateLimit = cast(pf_sfWindow_SetFramerateLimit)dll.getSymbol("sfWindow_SetFramerateLimit");
sfWindow_GetFrameTime = cast(pf_sfWindow_GetFrameTime)dll.getSymbol("sfWindow_GetFrameTime");
sfWindow_SetJoystickThreshold = cast(pf_sfWindow_SetJoystickThreshold)dll.getSymbol("sfWindow_SetJoystickThreshold");
}
}

View file

@ -0,0 +1,42 @@
/*
* DSFML - SFML Library binding in D language.
* Copyright (C) 2008 Julien Dagorn (sirjulio13@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.
*/
module dsfml.window.windowhandle;
/**
* Define a low-level window handle type, specific to
* each platform
*/
version(Windows)
{
// Windows defines a void* handle (HWND)
typedef void* WindowHandle;
}
else version(linux)
{
// Unix - X11 defines an unsigned integer handle (Window)
typedef ulong WindowHandle;
}

View file

@ -0,0 +1,48 @@
/*
* DSFML - SFML Library binding in D language.
* Copyright (C) 2008 Julien Dagorn (sirjulio13@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.
*/
module dsfml.window.windowsettings;
/**
* Structure defining the creation settings of windows
*/
struct WindowSettings
{
///
static WindowSettings opCall(uint depth = 24, uint stencil = 8, uint antialiasing = 0)
{
WindowSettings ret;
ret.DepthBits = depth;
ret.StencilBits = stencil;
ret.AntialiasingLevel = antialiasing;
return ret;
}
uint DepthBits; /// Bits of the depth buffer
uint StencilBits; /// Bits of the stencil buffer
uint AntialiasingLevel; /// Level of antialiasing
}

View file

@ -0,0 +1,38 @@
/*
* DSFML - SFML Library binding in D language.
* Copyright (C) 2008 Julien Dagorn (sirjulio13@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.
*/
module dsfml.window.windowstyle;
/**
* Window style
*/
enum Style
{
NONE = 0, /// No border / title bar (this flag and all others are mutually exclusive)
TITLEBAR = 1 << 0, /// Title bar + fixed border
RESIZE = 1 << 1, /// Titlebar + resizable border + maximize button
CLOSE = 1 << 2, /// Titlebar + close button
FULLSCREEN = 1 << 3 /// Fullscreen mode (this flag and all others are mutually exclusive)
}

46
DSFML/import/dsss.conf Normal file
View file

@ -0,0 +1,46 @@
name=dsfml
[dsfml/audio]
type = library
target = dsfml-audio
version (Windows){
postbuild += copy "dsfml-audio.lib" "../lib/dsfml-audio.lib"
} else version (linux){
postbuild += cp -f "libdsfml-audio.a" "../lib/libdsfml-audio.a"
}
[dsfml/network]
type = library
target = dsfml-network
version (Windows){
postbuild += copy "dsfml-network.lib" "../lib/dsfml-network.lib"
} else version (linux){
postbuild += cp -f "libdsfml-network.a" "../lib/libdsfml-network.a"
}
[dsfml/graphics]
type = library
target = dsfml-graphics
version (Windows){
postbuild += copy "dsfml-graphics.lib" "../lib/dsfml-graphics.lib"
} else version (linux){
postbuild += cp -f "libdsfml-graphics.a" "../lib/libdsfml-graphics.a"
}
[dsfml/system]
type = library
target = dsfml-system
version (Windows){
postbuild += copy "dsfml-system.lib" "../lib/dsfml-system.lib"
} else version (linux){
postbuild += cp -f "libdsfml-system.a" "../lib/libdsfml-system.a"
}
[dsfml/window]
type = library
target = dsfml-window
version (Windows){
postbuild += copy "dsfml-window.lib" "../lib/dsfml-window.lib"
} else version (linux){
postbuild += cp -f "libdsfml-window.a" "../lib/libdsfml-window.a"
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 154 KiB

Binary file not shown.

Binary file not shown.

Binary file not shown.

After

Width:  |  Height:  |  Size: 27 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 27 KiB

View file

@ -0,0 +1,16 @@
texture framebuffer
float offset
effect
{
vec2 offx = vec2(offset, 0.0);
vec2 offy = vec2(0.0, offset);
vec4 c0 = framebuffer(_in);
vec4 c1 = framebuffer(_in - offy);
vec4 c2 = framebuffer(_in + offy);
vec4 c3 = framebuffer(_in - offx);
vec4 c4 = framebuffer(_in + offx);
_out = c0 * 0.2 + c1 * 0.2 + c2 * 0.2 + c3 * 0.2 + c4 * 0.2;
}

Binary file not shown.

Binary file not shown.

View file

@ -0,0 +1,10 @@
texture framebuffer
vec3 color
effect
{
vec4 pixel = framebuffer(_in);
float gray = pixel.r * 0.39 + pixel.g * 0.50 + pixel.b * 0.11;
_out = vec4(gray * color, 1.0) * 0.6 + pixel * 0.4;
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.1 KiB

Binary file not shown.

View file

@ -0,0 +1,12 @@
texture framebuffer
vec2 mouse
effect
{
float len = distance(_in, mouse) * 7.0;
if (len < 1.0)
_out = framebuffer(_in + (_in - mouse) * len);
else
_out = framebuffer(_in);
}

View file

@ -0,0 +1,6 @@
texture framebuffer
effect
{
_out = framebuffer(_in);
}

Binary file not shown.

Binary file not shown.

After

Width:  |  Height:  |  Size: 23 KiB

View file

@ -0,0 +1,12 @@
texture framebuffer
texture wave
vec2 offset
effect
{
vec2 texoffset = wave(_in * offset).xy;
texoffset -= vec2(0.5, 0.5);
texoffset *= 0.05;
_out = framebuffer(_in + texoffset);
}

Binary file not shown.

Binary file not shown.

View file

@ -0,0 +1,230 @@
module dflsample;
import dsfml.system.all;
import dsfml.window.all;
// DFL and Derelict must be present.
import dfl.all;
import Derelict.opengl.gl;
import Derelict.opengl.glu;
// An enum for each controls methods
enum ControlMethod
{
MOUSE,
KEYBOARD
}
void main()
{
DerelictGL.load();
DerelictGLU.load();
//Start the message loop
Application.run(new MyForm());
}
//A simple form with a groupbox to choose input method and the openGL control
class MyForm : Form
{
GLControl m_gl;
GroupBox m_gbx;
RadioButton m_rb1;
RadioButton m_rb2;
this()
{
m_gbx = new GroupBox();
m_gbx.dock = DockStyle.TOP;
m_gbx.height = 40;
m_gbx.text = "Choose your input";
this.controls.add(m_gbx);
m_rb1 = new RadioButton();
m_rb1.text = "Mouse";
m_rb1.location = Point(10, 15);
m_rb1.checked = true;
m_rb1.click ~= &radioButtonClick;
m_gbx.controls.add(m_rb1);
m_rb2 = new RadioButton();
m_rb2.text = "Keyboard";
m_rb2.location = Point(m_rb1.width + 10, 15);
m_rb2.click ~= &radioButtonClick;
m_gbx.controls.add(m_rb2);
m_gl = new GLControl();
m_gl.dock = DockStyle.FILL;
m_gl.controlMethod = ControlMethod.MOUSE;
this.controls.add(m_gl);
this.text = "DFL Opengl Integration Sample";
}
private void radioButtonClick(Control c, EventArgs ea)
{
m_gl.controlMethod(c.text == "Mouse" ? ControlMethod.MOUSE : ControlMethod.KEYBOARD);
m_gl.focus();
}
}
//Our OpenGL control
class GLControl : Control
{
Window m_win;
Input i;
Timer m_timer;
GLfloat rotx = 0.f, roty = 0.f;
ControlMethod m_method = ControlMethod.MOUSE;
this ()
{
super();
this.setStyle(ControlStyles.SELECTABLE | ControlStyles.ALL_PAINTING_IN_WM_PAINT | ControlStyles.WANT_ALL_KEYS, true);
//We set a timer to ensure periodic refresh of the window
m_timer = new Timer();
m_timer.interval(10);
m_timer.tick ~= &this.onTick;
}
public void controlMethod(ControlMethod m)
{
m_method = m;
}
//Override of the onHandleCreated method of Control
//integration of DSFML window in a control need a valid handle
protected void onHandleCreated(EventArgs ea)
{
super.onHandleCreated(ea);
//Construction of the window
m_win = new Window(cast(WindowHandle)this.handle);
//Get the input for further use
i = m_win.getInput();
//Now that the Window is instanciated, we can start the timer.
m_timer.start();
//Some opengl initializations functions
glClearDepth(1.f);
glClearColor(0.f, 0.f, 0.f, 0.f);
glEnable(GL_DEPTH_TEST);
glDepthMask(GL_TRUE);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(90.f, 1.f, 1.f, 500.f);
}
//We handle Mouse leaving and entering the control to hide or show the cursor
protected void onMouseEnter(MouseEventArgs mea)
{
super.onMouseEnter(mea);
Cursor.current.hide();
}
protected void onMouseLeave(MouseEventArgs mea)
{
super.onMouseLeave(mea);
Cursor.current.show();
}
//If the window is resize, we need to modify openGL view
protected void onResize(EventArgs ea)
{
super.onResize(ea);
glViewport(0, 0, this.width, this.height);
}
protected void onTick(Timer t, EventArgs ea)
{
draw();
}
protected void onPaint(PaintEventArgs pea)
{
super.onPaint(pea);
draw();
}
private void handleKeys()
{
if (i.isKeyDown(KeyCode.UP))
rotx += 1.f;
if (i.isKeyDown(KeyCode.DOWN))
rotx += -1.f;
if (i.isKeyDown(KeyCode.LEFT))
roty += -1.f;
if (i.isKeyDown(KeyCode.RIGHT))
roty += 1.f;
}
private void handleMousePos()
{
rotx = i.getMouseY() - (this.height / 2.0);
roty = i.getMouseX() - (this.width / 2.0);
}
private void draw()
{
if (m_method == ControlMethod.KEYBOARD)
handleKeys();
else
handleMousePos();
m_win.setActive(true);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glTranslatef(0.f, 0.f, -200.f);
glRotatef(rotx, 1.f, 0.f, 0.f);
glRotatef(roty, 0.f, 1.f, 0.f);
glBegin(GL_QUADS);
glColor3f(1.f, 0.f, 0.f);
glVertex3f(-50.f, -50.f, -50.f);
glVertex3f(-50.f, 50.f, -50.f);
glVertex3f( 50.f, 50.f, -50.f);
glVertex3f( 50.f, -50.f, -50.f);
glColor3f(0.f, 1.f, 0.f);
glVertex3f(-50.f, -50.f, 50.f);
glVertex3f(-50.f, 50.f, 50.f);
glVertex3f( 50.f, 50.f, 50.f);
glVertex3f( 50.f, -50.f, 50.f);
glColor3f(0.f, 0.f, 1.f);
glVertex3f(-50.f, -50.f, -50.f);
glVertex3f(-50.f, 50.f, -50.f);
glVertex3f(-50.f, 50.f, 50.f);
glVertex3f(-50.f, -50.f, 50.f);
glColor3f(1.f, 1.f, 0.f);
glVertex3f(50.f, -50.f, -50.f);
glVertex3f(50.f, 50.f, -50.f);
glVertex3f(50.f, 50.f, 50.f);
glVertex3f(50.f, -50.f, 50.f);
glColor3f(1.f, 0.f, 1.f);
glVertex3f(-50.f, -50.f, 50.f);
glVertex3f(-50.f, -50.f, -50.f);
glVertex3f( 50.f, -50.f, -50.f);
glVertex3f( 50.f, -50.f, 50.f);
glColor3f(0.f, 1.f, 1.f);
glVertex3f(-50.f, 50.f, 50.f);
glVertex3f(-50.f, 50.f, -50.f);
glVertex3f( 50.f, 50.f, -50.f);
glVertex3f( 50.f, 50.f, 50.f);
glEnd();
m_win.display();
}
}

View file

@ -0,0 +1,33 @@
[*]
buildflags += -I../../import -Ivoip
[pong/pong.d]
target = bin/pong
[postFX/postFX.d]
target = bin/postFX
[socket/socketclient.d]
target = bin/client
[socket/socketserver.d]
target = bin/server
[sound3d/sound3d.d]
target = bin/sound3d
[soundstream/soundstream.d]
target = bin/soundstream
[view/view.d]
target = bin/view
[voip/entry.d]
target = bin/voip
version (Windows){
version (DFL){
[dfl/dflsample.d]
target = bin/dflSample
}
}

View file

@ -0,0 +1,183 @@
module pong;
import dsfml.system.all;
import dsfml.audio.all;
import dsfml.window.all;
import dsfml.graphics.all;
version (Tango)
{
import tango.io.Stdout;
import tango.math.Math;
}
else
{
import std.math;
}
void main()
{
// Defines PI
const float PI = 3.14159f;
// Create the window of the application
RenderWindow app = new RenderWindow(VideoMode(800, 600, 32), "SFML Pong");
app.useVerticalSync(true);
Input i = app.getInput();
// Load the sounds used in the game
Sound BallSound = new Sound(new SoundBuffer("Data/ball.wav"));
// Load the images used in the game
Image PaddleImage = new Image("Data/paddle.tga");
Image BallImage = new Image("Data/ball.tga");
// Initialize the end text
String End = new String(""c);
Font font = new Font("Data/cheeseburger.ttf");
End.setFont(font);
End.setSize(60.f);
End.move(150.f, 200.f);
End.setColor(Color(50, 50, 250));
// Create the sprites of the background, the paddles and the ball
Sprite LeftPaddle = new Sprite(PaddleImage);
Sprite RightPaddle = new Sprite(PaddleImage);
Sprite Ball = new Sprite(BallImage);
LeftPaddle.move(10, (app.getView().getRect().getHeight() - LeftPaddle.getSize().y) / 2);
RightPaddle.move(app.getView().getRect().getWidth() - RightPaddle.getSize().x - 10, (app.getView().getRect().getHeight() - RightPaddle.getSize().y) / 2);
Ball.move((app.getView().getRect().getWidth() - Ball.getSize().x) / 2, (app.getView().getRect().getHeight() - Ball.getSize().y) / 2);
// Define the paddles properties
Clock AITimer = new Clock();
const float AITime = 0.1f;
float LeftPaddleSpeed = 400.f;
float RightPaddleSpeed = 400.f;
// Define the ball properties
float BallSpeed = 400.f;
float BallAngle = 0.f;
do
{
// Make sure the ball initial angle is not too much vertical
BallAngle = Randomizer.random(0.f, 2 * PI);
} while (abs(cos(BallAngle)) < 0.7f);
bool IsPlaying = true;
Event evt;
while (app.isOpened())
{
app.clear(Color(255, 255, 255, 255));
// Handle events
while (app.getEvent(evt))
{
// Window closed or escape key pressed : exit
if ((evt.Type == Event.EventType.CLOSED) ||
((evt.Type == Event.EventType.KEYPRESSED) && (evt.Key.Code == KeyCode.ESCAPE)))
{
app.close();
break;
}
}
if (IsPlaying)
{
// Move the player's paddle
if (i.isKeyDown(KeyCode.UP) && (LeftPaddle.getPosition().y > 5.f))
LeftPaddle.move(0.f, -LeftPaddleSpeed * app.getFrameTime());
if (i.isKeyDown(KeyCode.DOWN) && (LeftPaddle.getPosition().y < app.getView().getRect().getHeight() - LeftPaddle.getSize().y - 5.f))
LeftPaddle.move(0.f, LeftPaddleSpeed * app.getFrameTime());
// Move the computer's paddle
if (((RightPaddleSpeed < 0.f) && (RightPaddle.getPosition().y > 5.f)) ||
((RightPaddleSpeed > 0.f) && (RightPaddle.getPosition().y < app.getView().getRect().getHeight() - RightPaddle.getSize().y - 5.f)))
{
RightPaddle.move(0.f, RightPaddleSpeed * app.getFrameTime());
}
// Update the computer's paddle direction according to the ball position
if (AITimer.getElapsedTime() > AITime)
{
AITimer.reset();
if ((RightPaddleSpeed < 0) && (Ball.getPosition().y + Ball.getSize().y > RightPaddle.getPosition().y + RightPaddle.getSize().y))
RightPaddleSpeed = -RightPaddleSpeed;
if ((RightPaddleSpeed > 0) && (Ball.getPosition().y < RightPaddle.getPosition().y))
RightPaddleSpeed = -RightPaddleSpeed;
}
// Move the ball
float Factor = BallSpeed * app.getFrameTime();
Ball.move(cos(BallAngle) * Factor, sin(BallAngle) * Factor);
// Check collisions between the ball and the screen
if (Ball.getPosition().x < 0.f)
{
IsPlaying = false;
End.setText("You lost !\n(press escape to exit)"c);
}
if (Ball.getPosition().x + Ball.getSize().x > app.getView().getRect().getWidth())
{
IsPlaying = false;
End.setText("You won !\n(press escape to exit)"c);
}
if (Ball.getPosition().y < 0.f)
{
BallSound.play();
BallAngle = -BallAngle;
Ball.setY(0.1f);
}
if (Ball.getPosition().y + Ball.getSize().y > app.getView().getRect().getHeight())
{
BallSound.play();
BallAngle = -BallAngle;
Ball.setY(app.getView().getRect().getHeight() - Ball.getSize().y - 0.1f);
}
// Check the collisions between the ball and the paddles
// Left Paddle
if (Ball.getPosition().x < LeftPaddle.getPosition().x + LeftPaddle.getSize().x &&
Ball.getPosition().x > LeftPaddle.getPosition().x + (LeftPaddle.getSize().x / 2.0f) &&
Ball.getPosition().y + Ball.getSize().y >= LeftPaddle.getPosition().y &&
Ball.getPosition().y <= LeftPaddle.getPosition().y + LeftPaddle.getSize().y)
{
BallSound.play();
BallAngle = PI - BallAngle;
Ball.setX(LeftPaddle.getPosition().x + LeftPaddle.getSize().x + 0.1f);
}
// Right Paddle
if (Ball.getPosition().x + Ball.getSize().x > RightPaddle.getPosition().x &&
Ball.getPosition().x + Ball.getSize().x < RightPaddle.getPosition().x + (RightPaddle.getSize().x / 2.0f) &&
Ball.getPosition().y + Ball.getSize().y >= RightPaddle.getPosition().y &&
Ball.getPosition().y <= RightPaddle.getPosition().y + RightPaddle.getSize().y)
{
BallSound.play();
BallAngle = PI - BallAngle;
Ball.setX(RightPaddle.getPosition().x - Ball.getSize().x - 0.1f);
}
}
// Draw the background, paddles and ball sprites
app.draw(LeftPaddle);
app.draw(RightPaddle);
app.draw(Ball);
// If the game is over, display the end message
if (!IsPlaying)
app.draw(End);
// Display things on screen
app.display();
}
}

View file

@ -0,0 +1,117 @@
module postfx;
import dsfml.graphics.all;
import dsfml.system.all;
import dsfml.window.all;
const char[][5] EFFECTS = ["nothing", "blur", "colorize", "fisheye", "wave"];
void main()
{
int actualIndex;
// Check that the system can use post effects
if (PostFX.canUsePostFX() == false)
assert(0, "Your system doesn't support Post Effects.");
// Create the main window
RenderWindow app = new RenderWindow(VideoMode(800, 600), "SFML PostFX");
app.setFramerateLimit(100);
// Load a cute background image to display :)
Sprite background = new Sprite(new Image("Data/background.jpg"));
// Load the image needed for the wave effect
Image WaveImage = new Image("Data/wave.jpg");
// Load all effects
PostFX[char[]] Effects;
foreach(char[] c; EFFECTS)
{
Effects[c] = new PostFX("Data/" ~ c ~ ".sfx");
}
PostFX currentEffect = Effects[EFFECTS[actualIndex]];
// Do specific initializations
Effects["nothing"].setTexture("framebuffer", null);
Effects["blur"].setTexture("framebuffer", null);
Effects["blur"].setParameter("offset", 0.f);
Effects["colorize"].setTexture("framebuffer", null);
Effects["colorize"].setParameter("color", 1.f, 1.f, 1.f);
Effects["fisheye"].setTexture("framebuffer", null);
Effects["wave"].setTexture("framebuffer", null);
Effects["wave"].setTexture("wave", WaveImage);
Font f = new Font("Data/cheeseburger.ttf");
// Define a string for displaying current effect description
String curFXStr = new String("Current effect is " ~ EFFECTS[actualIndex]);
curFXStr.setFont(f);
curFXStr.setPosition(20.f, 0.f);
// Define a string for displaying help
String infoStr = new String("Move your mouse to change the effect parameters\nPress numpad + and - to change effect\nWarning : some effects may not work\ndepending on your graphics card"c);
infoStr.setFont(f);
infoStr.setPosition(20.f, 460.f);
infoStr.setColor(Color(200, 100, 150));
// Start the game loop
while (app.isOpened())
{
// Process events
Event evt;
while (app.getEvent(evt))
{
// Close window : exit
if (evt.Type == Event.EventType.CLOSED ||
evt.Type == Event.EventType.KEYPRESSED && evt.Key.Code == KeyCode.ESCAPE)
app.close();
if (evt.Type == Event.EventType.KEYPRESSED)
{
// Add key : next effect
if (evt.Key.Code == KeyCode.ADD)
{
if (actualIndex == 4)
actualIndex = 0;
else
actualIndex++;
currentEffect = Effects[EFFECTS[actualIndex]];
curFXStr.setText("Current effect is " ~ EFFECTS[actualIndex]);
}
// Subtract key : previous effect
if (evt.Key.Code == KeyCode.SUBTRACT)
{
if (actualIndex == 0)
actualIndex = 4;
else
actualIndex--;
currentEffect = Effects[EFFECTS[actualIndex]];
curFXStr.setText("Current effect is " ~ EFFECTS[actualIndex]);
}
}
}
// Get the mouse position in the range [0, 1]
float X = app.getInput().getMouseX() / cast(float) app.getWidth();
float Y = app.getInput().getMouseY() / cast(float) app.getHeight();
// Update the current effect
if (EFFECTS[actualIndex] == "blur") currentEffect.setParameter("offset", X * Y * 0.1f);
else if (EFFECTS[actualIndex] == "colorize") currentEffect.setParameter("color", 0.3f, X, Y);
else if (EFFECTS[actualIndex] == "fisheye") currentEffect.setParameter("mouse", X, 1.f - Y);
else if (EFFECTS[actualIndex] == "wave") currentEffect.setParameter("offset", X, Y);
// Draw background and apply the post-fx
app.draw(background);
app.draw(currentEffect);
// Draw interface strings
app.draw(curFXStr);
app.draw(infoStr);
// Finally, display the rendered frame on screen
app.display();
}
}

View file

@ -0,0 +1,66 @@
module socketclient;
import dsfml.system.all;
import dsfml.network.all;
version (Tango)
{
import tango.io.Console;
import tango.io.Stdout;
}
else
{
import std.stdio;
}
void main()
{
//The TCP socket
SocketTCP client = new SocketTCP();
//Try to connect to server (on localhost for this sample)
client.connect(9000, IPAddress.LOCALHOST);
display("Connected to server."w);
//Prepare a packet with a string
Packet p = new Packet();
p.set("Hello from the client !"w);
if (client.send(p) != SocketStatus.DONE) // Assert on error
assert(0);
//Clear the packet
p.clear();
//Wait for the response of the server and display it
if (client.receive(p) != SocketStatus.DONE)
assert(0);
wchar[] c;
p.get(c);
display("Packet received : "w ~ c);
read();
}
void display(wchar[] c)
{
version (Tango)
{
Stdout(c).newline;
}
else
{
writefln("%s", c);
}
}
void read()
{
version (Tango)
{
Cin.get();
}
else
{
readln();
}
}

View file

@ -0,0 +1,83 @@
module socketserver;
import dsfml.system.all;
import dsfml.network.all;
version (Tango)
{
import tango.io.Console;
import tango.io.Stdout;
}
else
{
import std.stdio;
}
void main()
{
//We create a TCP socket for listening incomming client
SocketTCP listener = new SocketTCP();
//Set a random port for the listener
if (!listener.listen(9000))
assert(0);
//Creation of TCP socket
SocketTCP client = new SocketTCP();
IPAddress ipClient;
display("Waiting for client."w);
if (listener.accept(client, ipClient) == SocketStatus.DONE) //This call blocks until client connection
{
display("New client connected."w);
//The packet for retrieving the client message
Packet p = new Packet();
display("Waiting for data"w);
if (client.receive(p) != SocketStatus.DONE) //Assert on reception error
assert(0);
//Display the string send by the client
wchar[] c;
p.get(c);
display("Packet received : "w ~ c);
//Clear the packet (We could use a new one)
p.clear();
//and send response to client
client.send(p.set("Hello from the server !"w));
}
read();
}
/**
* Multilib string display
*/
void display(wchar[] c)
{
version (Tango)
{
Stdout(c).newline;
}
else
{
writefln("%s", c);
}
}
/**
* Dummy function to prevent console closing on windows
*/
void read()
{
version (Tango)
{
Cin.get();
}
else
{
readln();
}
}

View file

@ -0,0 +1,190 @@
module sound3d;
import dsfml.system.all;
import dsfml.window.all;
import dsfml.graphics.all;
import dsfml.audio.all;
void main()
{
//We create our window with a limit of 100 and a white backcolor.
RenderWindow app = new RenderWindow (VideoMode(800, 600, 32), "Sound Spatialization Sample");
app.useVerticalSync(true);
Font f = new Font("Data/cheeseburger.ttf", 34);
//Some instructions
String s = new String("Click anywhere on screen to change listener position.\nPress + or - to modify the speed of the car."c, f);
s.setPosition(20, 30);
s.setColor(Color.BLACK);
//We prepare our images and the sound
char[][2] images = ["Data/bluerallyecarleft.bmp", "Data/bluerallyecarright.bmp"];
Car c = new Car(images, "Data/car_idle.wav");
int carSpeed = 100;
//Set default position for the car and the listener
c.setPosition(Vector2f(0, 300));
SoundListener.setPosition(Vector2f(400, 300));
c.startPlaying();
//Start the main loop
while (app.isOpened())
{
app.clear(Color.WHITE);
Event evt;
//The event loop
while (app.getEvent(evt))
{
// if the window is closed, we can leave the game loop
if (evt.Type == Event.EventType.CLOSED)
app.close();
// we handle the click event to change listener position
else if (evt.Type == Event.EventType.MOUSEBUTTONPRESSED && evt.MouseButton.Button == MouseButtons.LEFT)
{
Input i = app.getInput();
SoundListener.setPosition(Vector2f(i.getMouseX(), i.getMouseY()));
}
// and eventual keys press
else if (evt.Type == Event.EventType.KEYPRESSED)
{
//Change the car speed
if (evt.Key.Code == KeyCode.ADD)
{
carSpeed += 25;
}
else if (evt.Key.Code == KeyCode.SUBTRACT)
{
carSpeed -= 25;
}
}
}
//We move constantly our car.
c.move(Vector2f(app.getFrameTime() * carSpeed, 0));
//Draw all the sprite and string on render window
app.draw(s);
app.draw(c.getSprite());
app.draw(SoundListener.getSprite());
//And finally display the window
app.display();
}
}
// Encapsulate the listener position and the visor sprite.
// There is only one listener so all the methods are statics.
class SoundListener
{
static Sprite s_crosshair;
static Vector2f s_p;
static this()
{
Image crosshairImg = new Image("Data/crosshair.tga");
crosshairImg.createMaskFromColor(Color.WHITE);
s_crosshair = new Sprite(crosshairImg);
s_crosshair.setCenter(Vector2f(s_crosshair.getSize().x / 2, s_crosshair.getSize().y / 2));
//Listener.setTarget(1.f, 0.f, 0.f);
}
// Adjust position of the listener
static void setPosition(Vector2f p)
{
Listener.setPosition(p.x, p.y, 5.f);
s_crosshair.setPosition(p);
}
static Sprite getSprite()
{
return s_crosshair;
}
}
// Class encapsulating all data for our car
class Car
{
Vector2f m_actual;
Sprite m_sprite;
Sound m_sound;
bool reverse;
Image[2] imgs;
//Constructor with with a fixed size string array of image path, and a string for the sound path
this (char[][2] images, char[] soundFilename)
{
//load images and create filter
imgs[0] = new Image(images[0]); imgs[1] = new Image(images[1]);
foreach(img; imgs)
img.createMaskFromColor(Color(97, 68, 43));
m_sprite = new Sprite(imgs[0]);
m_sprite.setCenter(Vector2f(m_sprite.getSize().x / 2, m_sprite.getSize().y / 2));
SoundBuffer buff = new SoundBuffer(soundFilename);
//load our sound with loop enabled
m_sound = new Sound(buff, true);
m_sound.setAttenuation(.05f);
}
// Begin the sound play
void startPlaying()
{
m_sound.play();
}
// Set the position of the car on the window
// Used to setup the begin car window and sound location
void setPosition(Vector2f p)
{
m_sprite.setPosition(p);
m_sound.setPosition(p.x, 0, p.y);
}
//Move the car (visual and sound position)
//If the car leave the screen, we change the sprite image and reverse moving
void move(Vector2f vec)
{
// if the car is beyond the right screen limit
if (!reverse && m_sprite.getPosition().x > 850)
{
m_sprite.setImage(imgs[1]);
reverse = true;
}
// same as above but for left limit
else if (reverse && vec.x + m_sprite.getPosition().x < -50)
{
m_sprite.setImage(imgs[0]);
reverse = false;
}
if (reverse)
vec = -vec;
m_sprite.move(vec);
Vector2f pos = m_sprite.getPosition();
m_sound.setPosition(pos.x , pos.y, 0);
}
Sprite getSprite()
{
return m_sprite;
}
}

View file

@ -0,0 +1,91 @@
module soundstream;
import dsfml.system.all;
import dsfml.audio.all;
version (Tango)
{
import tango.io.Console;
import tango.io.Stdout;
}
else
{
import std.stdio;
}
// SoundStream is an abstract class.
// You need to implement onStart() and onGetData()
// Don't forget to call initialize() before any usage or playback will fail.
class MySoundStream : SoundStream
{
SoundBuffer m_buff;
short[] m_data;
size_t m_cursor;
this()
{
// We initialize the stream with some sound informations
super(1, 11025);
// We create a sound buffer to load samples from files
m_buff = new SoundBuffer("Data/car_idle.wav");
m_data = m_buff.getSamples[0..m_buff.getSamplesCount];
}
protected:
bool onStart()
{
// No specifics things to do, just return true.
return true;
}
bool onGetData(out short[] data)
{
// We ensure that we have enough data to send
if (m_cursor + this.getSampleRate > m_data.length)
return false;
// Assign data in the buffer ...
data = m_data[m_cursor..m_cursor + this.getSampleRate];
// ... and increment the cursor
m_cursor += this.getSampleRate;
return true;
}
}
void main()
{
MySoundStream stream = new MySoundStream();
display("Playing sound !\n Press enter to stop playback.");
stream.play();
read();
stream.stop();
}
void display(char[] c)
{
version (Tango)
{
Stdout(c).newline;
}
else
{
writefln("%s", c);
}
}
/**
* Dummy function to prevent console closing on windows
*/
void read()
{
version (Tango)
{
Cin.get();
}
else
{
readln();
}
}

View file

@ -0,0 +1,69 @@
module view;
import dsfml.system.all;
import dsfml.window.all;
import dsfml.graphics.all;
void main()
{
RenderWindow window = new RenderWindow(VideoMode(800, 600), "View sample");
window.setFramerateLimit(100);
Input input = window.getInput();
Vector2f top;
Rect!(float) bound;
Shape s;
bool mousePressed;
Sprite background = new Sprite(new Image("Data/background.jpg"));
Font f = new Font("Data/cheeseburger.ttf");
String str = new String("Create a selection of the background with your mouse.\nPress Enter to zoom to this selection.\nPress Escape to return to the default view."c, f);
while (window.isOpened())
{
Event evt;
while (window.getEvent(evt))
{
if ( evt.Type == Event.EventType.MOUSEBUTTONPRESSED &&
evt.MouseButton.Button == MouseButtons.LEFT)
{
top = window.convertCoords(input.getMouseX(), input.getMouseY());
mousePressed = true;
}
else if ( evt.Type == Event.EventType.MOUSEBUTTONRELEASED &&
evt.MouseButton.Button == MouseButtons.LEFT)
{
mousePressed = false;
}
else if ( evt.Type == Event.EventType.MOUSEMOVED &&
mousePressed)
{
Vector2f bottom = window.convertCoords(input.getMouseX(), input.getMouseY());
bound = new Rect!(float)(top.x, top.y, bottom.x, bottom.y);
s = Shape.rectangle(top.x, top.y, bottom.x, bottom.y, Color(0, 0, 0, 0), 1, Color.BLACK);
}
else if ( evt.Type == Event.EventType.KEYPRESSED &&
evt.Key.Code == KeyCode.RETURN)
{
if (bound !is null)
window.setView(new View(bound));
s = null;
}
else if ( evt.Type == Event.EventType.KEYPRESSED &&
evt.Key.Code == KeyCode.ESCAPE)
{
window.setView(window.getDefaultView());
}
else if ( evt.Type == Event.EventType.CLOSED)
window.close();
}
window.draw(background);
window.draw(str);
if (s !is null) window.draw(s);
window.display();
}
}

View file

@ -0,0 +1,72 @@
module client;
import util;
// Specialization of audio recorder for sending recorded audio
// data through the network
class NetworkRecorder : SoundRecorder
{
public:
// Constructor
this(SocketTCP Socket)
{
mySocket = Socket;
}
~this()
{
delete mySocket;
}
protected:
override bool onStart()
{
return true;
}
override void onStop()
{
}
override bool onProcessSamples(short[] samples)
{
// Pack the audio samples into a network packet
Packet PacketOut = new Packet();
PacketOut.set(AudioData);
PacketOut.append((cast(byte*)samples.ptr)[0..samples.length * short.sizeof]);
// Send the audio packet to the server
return mySocket.send(PacketOut) == SocketStatus.DONE;
}
SocketTCP mySocket; ///< Socket used to communicate with the server
}
void runClient(IPAddress adr, int port)
{
// Create a TCP socket for communicating with server
SocketTCP Socket = new SocketTCP();
// Connect to the specified server
if (!Socket.connect(port, adr))
return;
// Wait for user input...
Cout("Press enter to start recording audio").newline;
Cin.get();
// Create a instance of our custom recorder
NetworkRecorder Recorder = new NetworkRecorder(Socket);
// Start capturing audio data
Recorder.start(44100);
Cout("Press enter to stop recording audio").newline;
Cin.get();
Recorder.stop();
// Send a "end-of-stream" packet
Packet PacketOut = new Packet();
PacketOut.set(EndOfStream);
Socket.send(PacketOut);
}

View file

@ -0,0 +1,46 @@
module entry;
import util;
import server;
import client;
int main(char[][] args)
{
char[][] argc = args.dup;
if (argc.length > 1)
{
if ( argc[1] == "-c" &&
argc.length == 4)
{
IPAddress adr = IPAddress(argc[2]);
if (adr.isValid() &&
parse(argc[3]) <= 60000 &&
parse(argc[3]) >= 1000)
{
runClient(adr, parse(argc[3]));
}
else
printUsage();
}
else if ( argc[1] == "-s" &&
argc.length == 3 &&
parse(argc[2]) <= 60000 &&
parse(argc[2]) >= 1000)
{
runServer(parse(argc[2]));
}
else
printUsage();
}
else
printUsage();
return 0;
}
void printUsage()
{
Cout("Usage :\n voip.exe [-c [ip address] | -s] [port] \n -c = run as client\n -s = run as server\n ip address = address of the server\n port = port between 1000 and 65000\n").newline;
}

View file

@ -0,0 +1,162 @@
module server;
import util;
class NetworkAudioStream : SoundStream
{
public:
static this()
{
s_sync = new Object();
}
// Default constructor
this()
{
myListener = new SocketTCP();
myClient = new SocketTCP();
// Set the sound parameters
super(1, 44100);
}
// Destructor
~this()
{
// Close the sockets
delete myClient;
delete myListener;
}
// Run the server, stream audio data from the client
void start(int Port)
{
if (!myHasFinished)
{
// Listen to the given port for incoming connections
if (!myListener.listen(Port))
return;
Cout("Listening").newline;
myListener.accept(myClient);
Cout("New Client").newline;
// Start playback
play();
// Start receiving audio data
receiveLoop();
}
else
{
// Start playback
play();
}
}
protected:
override bool onStart()
{
// Reset the playing offset
myOffset = 0;
return true;
}
override bool onGetData(out short[] data)
{
// We have reached the end of the buffer and all audio data have been played : we can stop playback
if ((myOffset == mySamples.length) && myHasFinished)
return false;
// No new data has arrived since last update : wait until we get some
while (myOffset == mySamples.length && !myHasFinished)
sleep(0.01f);
synchronized(s_sync)
{
myTempBuffer = mySamples[myOffset..mySamples.length];
// Update the playing offset
myOffset += myTempBuffer.length;
}
data = myTempBuffer;
return true;
}
private:
void receiveLoop()
{
while (!myHasFinished)
{
// Get waiting audio data from the network
Packet PacketIn = new Packet();
if (myClient.receive(PacketIn) != SocketStatus.DONE)
break;
// Extract the message ID
ubyte Id;
PacketIn.get(Id);
if (Id == AudioData)
{
// Extract audio samples from the packet, and append it to our samples buffer
synchronized(s_sync)
{
byte* temp = PacketIn.getData().ptr;
temp++;
mySamples ~= (cast(short*)temp)[0..(PacketIn.getDataSize - byte.sizeof ) / short.sizeof];
}
}
else if (Id == EndOfStream)
{
// End of stream reached : we stop receiving audio data
myHasFinished = true;
}
else
{
// Something's wrong...
myHasFinished = true;
}
}
}
SocketTCP myListener;
SocketTCP myClient;
short[] mySamples;
short[] myTempBuffer;
size_t myOffset;
bool myHasFinished;
static Object s_sync;
};
// Launch a server and wait for incoming audio data from
// a connected client
void runServer(int Port)
{
// Build an audio stream to play sound data as it is received through the network
NetworkAudioStream audioStream = new NetworkAudioStream;
audioStream.start(Port);
// Loop until the sound playback is finished
while (audioStream.getStatus() != SoundStatus.STOPPED)
{
// Leave some CPU time for other threads
sleep(0.1f);
}
Cout("Enter to replay").newline;
Cin.get();
// Replay the sound (just to make sure replaying the received data is OK)
audioStream.play();
// Loop until the sound playback is finished
while (audioStream.getStatus() != SoundStatus.STOPPED)
{
// Leave some CPU time for other threads
sleep(0.1f);
}
}

View file

@ -0,0 +1,49 @@
module util;
const ubyte AudioData = 1;
const ubyte EndOfStream = 2;
public import dsfml.system.all;
public import dsfml.audio.all;
public import dsfml.network.all;
version(Tango)
{
public import tango.io.Console;
public import tango.text.convert.Integer;
}
else
{
public import std.stdio;
//simple abstraction of Cout & Cin for phobos
class Cout
{
static Cout s_c;
static this()
{
s_c = new Cout();
}
static Cout opCall(char[] str)
{
writefln("%s", str);
return s_c;
}
void newline()
{
}
}
class Cin
{
static char[] get()
{
return readln();
}
}
public import std.string : atoi;
alias atoi parse;
}