* PySFML now compiles and runs with python3 (and still compiles and runs

with python 2.5)
* Improved support for unicode
* Fixed a mysterious bug with the opengl sample
* Code clean up


git-svn-id: https://sfml.svn.sourceforge.net/svnroot/sfml/trunk@1024 4e206d99-4929-0410-ac5d-dfc041789085
This commit is contained in:
remi-k 2009-02-27 17:57:39 +00:00
parent af3dd7c630
commit 39f4805a98
14 changed files with 306 additions and 140 deletions

View File

@ -1,2 +1 @@
import sf

View File

@ -1,6 +1,6 @@
#!/usr/bin/python #!/usr/bin/python
from PySFML import * from PySFML import sf
from OpenGL.GL import * from OpenGL.GL import *
from OpenGL.GLUT import * from OpenGL.GLUT import *

View File

@ -1,6 +1,6 @@
#!/usr/bin/env python #!/usr/bin/env python
from PySFML import * from PySFML import sf
def Main(): def Main():
# Check that the device can capture audio # Check that the device can capture audio

View File

@ -0,0 +1,67 @@
#!/usr/bin/env python
from PySFML import sf
def Main():
# Check that the device can capture audio
if sf.SoundRecorder.CanCapture() == False:
print("Sorry, audio capture is not supported by your system")
return
# Choose the sample rate
SampleRate = int(input("Please choose the sample rate for sound capture (44100 is CD quality) : "))
# Wait for user input...
print("Press enter to start recording audio")
input()
# Here we'll use an integrated custom recorder, which saves the captured data into a sfSoundBuffer
Recorder = sf.SoundBufferRecorder()
# Audio capture is done in a separate thread, so we can block the main thread while it is capturing
Recorder.Start(SampleRate)
print("Recording... press enter to stop")
input()
Recorder.Stop()
# Get the buffer containing the captured data
Buffer = Recorder.GetBuffer()
# Display captured sound informations
print("Sound information :")
print(" " + str(Buffer.GetDuration()) + " seconds")
print(" " + str(Buffer.GetSampleRate()) + " samples / seconds")
print(" " + str(Buffer.GetChannelsCount()) + " channels")
# Choose what to do with the recorded sound data
Choice = str(input("What do you want to do with captured sound (p = play, s = save) ? "))
if Choice == 's':
# Choose the filename
Filename = str(input("Choose the file to create : "))
# Save the buffer
Buffer.SaveToFile(Filename);
else:
# Create a sound instance and play it
Sound = sf.Sound(Buffer)
Sound.Play()
# Wait until finished
while Sound.GetStatus() == sf.Sound.Playing:
# Display the playing position - I don't know how to do this in python
# std::cout << "\rPlaying... " << std::fixed << std::setprecision(2) << Sound.GetPlayingOffset() << " sec";
# Leave some CPU time for other threads
sf.Sleep(0.1)
# Finished !
print("Done !")
# Wait until the user presses 'enter' key
print("Press enter to exit...")
input()
return
Main()

View File

@ -0,0 +1,49 @@
#!/usr/bin/python
from PySFML import sf
class MyCustomStream(sf.SoundStream):
def Open(self, Filename):
# Load the sound data into a sound buffer
self.SoundData = sf.SoundBuffer()
if not self.SoundData.LoadFromFile(Filename):
return False
# Initialize the stream with the sound parameters
self.Initialize(self.SoundData.GetChannelsCount(), self.SoundData.GetSampleRate())
# Copy the audio samples into our internal array
self.myBuffer = self.SoundData.GetSamples()
return True
def OnStart(self):
self.myOffset = 0
self.myBufferSize = 80000
return True
def OnGetData(self):
# Check if there is enough data to stream
if self.myOffset > len(self.myBuffer):
# Returning something else than a string means that we want to stop playing the stream
return False
# Data contains the string of samples we will return
if self.myOffset + self.myBufferSize >= len(self.myBuffer):
print("End of audio data reached")
Data = self.myBuffer[self.myOffset:]
else:
Data = self.myBuffer[self.myOffset:self.myOffset+self.myBufferSize]
# Update the offset
self.myOffset = self.myBufferSize + self.myOffset
return Data
def Main():
Stream = MyCustomStream()
Stream.Open("./data/fart.wav")
Stream.Play()
print("Playing 5 seconds of audio data...")
sf.Sleep(5)
Stream.Stop()
print("Press enter to exit...")
input()
Main()

View File

@ -44,7 +44,8 @@ class Apple(sf.Sprite):
def __init__(self): def __init__(self):
apple_img = sf.Image() # Apple's image apple_img = sf.Image() # Apple's image
if not apple_img.LoadFromFile("./data/apple.png"): if not apple_img.LoadFromFile("./data/apple.png"):
print "Could not load data/apple.png" pass
# print "Could not load data/apple.png"
sf.Sprite.__init__(self, apple_img) sf.Sprite.__init__(self, apple_img)
self.SetCenter(apple_img.GetWidth()/2, apple_img.GetHeight()/2) self.SetCenter(apple_img.GetWidth()/2, apple_img.GetHeight()/2)
self.size = apple_img.GetWidth() self.size = apple_img.GetWidth()
@ -109,7 +110,8 @@ class Worm(list):
self.rond = sf.Image() self.rond = sf.Image()
self.level_completed = False self.level_completed = False
if not self.rond.LoadFromFile("./data/rond2.png"): if not self.rond.LoadFromFile("./data/rond2.png"):
print "Could not load data/rond2.png" pass
# print "Could not load data/rond2.png"
def reset(self, arena): def reset(self, arena):
self.targeted_length, self.angle, self.direction = 30, 0, 0 self.targeted_length, self.angle, self.direction = 30, 0, 0

View File

@ -34,7 +34,9 @@ extern PyTypeObject PySfColorType;
void CustomDrawable::Render (sf::RenderTarget& Target) const void CustomDrawable::Render (sf::RenderTarget& Target) const
{ {
if (RenderFunction) if (RenderFunction)
PyObject_CallFunction(RenderFunction, (char *)"O", RenderWindow); PyObject_CallFunction(RenderFunction, (char *)"O", RenderTarget);
else
PyErr_SetString(PyExc_RuntimeError, "Custom drawables must have a render method defined");
} }
static void static void
@ -48,23 +50,19 @@ static PyObject *
PySfDrawable_new(PyTypeObject *type, PyObject *args, PyObject *kwds) PySfDrawable_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{ {
PySfDrawable *self; PySfDrawable *self;
self = (PySfDrawable *)type->tp_alloc(type, 0); self = (PySfDrawable *)type->tp_alloc(type, 0);
if (self != NULL)
{
}
return (PyObject *)self; return (PyObject *)self;
} }
static int static int
PySfDrawable_init(PySfDrawable *self, PyObject *args, PyObject *kwds) PySfDrawable_init(PySfDrawable *self, PyObject *args, PyObject *kwds)
{ {
self->obj = new CustomDrawable(); self->obj = new CustomDrawable();
self->obj->RenderFunction = NULL;
self->obj->RenderTarget = NULL;
return 0; return 0;
} }
static PyObject * static PyObject *
PySfDrawable_SetX(PySfDrawable* self, PyObject *args) PySfDrawable_SetX(PySfDrawable* self, PyObject *args)
{ {
@ -81,7 +79,7 @@ static PyObject *
PySfDrawable_SetScale(PySfDrawable* self, PyObject *args) PySfDrawable_SetScale(PySfDrawable* self, PyObject *args)
{ {
float ScaleX, ScaleY; float ScaleX, ScaleY;
if ( !PyArg_ParseTuple(args, "ff", &ScaleX, &ScaleY) ) if (!PyArg_ParseTuple(args, "ff:Drawable.SetScale", &ScaleX, &ScaleY) )
return NULL; return NULL;
self->obj->SetScale(ScaleX, ScaleY); self->obj->SetScale(ScaleX, ScaleY);
Py_RETURN_NONE; Py_RETURN_NONE;
@ -109,7 +107,7 @@ static PyObject *
PySfDrawable_SetCenter(PySfDrawable* self, PyObject *args) PySfDrawable_SetCenter(PySfDrawable* self, PyObject *args)
{ {
float x, y; float x, y;
if ( !PyArg_ParseTuple(args, "ff", &x, &y) ) if (!PyArg_ParseTuple(args, "ff:Drawable.SetCenter", &x, &y) )
return NULL; return NULL;
self->obj->SetCenter(x, y); self->obj->SetCenter(x, y);
Py_RETURN_NONE; Py_RETURN_NONE;
@ -127,7 +125,7 @@ PySfDrawable_SetColor(PySfDrawable* self, PyObject *args)
PySfColor *Color = (PySfColor *)args; PySfColor *Color = (PySfColor *)args;
if (! PyObject_TypeCheck(args, &PySfColorType)) if (! PyObject_TypeCheck(args, &PySfColorType))
{ {
PyErr_SetString(PyExc_TypeError, "Argument is not a sfColor"); PyErr_SetString(PyExc_TypeError, "Drawable.SetColor() Argument is not a sf.Color");
return NULL; return NULL;
} }
PySfColorUpdate(Color); PySfColorUpdate(Color);
@ -170,7 +168,7 @@ static PyObject *
PySfDrawable_Move(PySfDrawable* self, PyObject *args) PySfDrawable_Move(PySfDrawable* self, PyObject *args)
{ {
float x, y; float x, y;
if ( !PyArg_ParseTuple(args, "ff", &x, &y) ) if (!PyArg_ParseTuple(args, "ff:Drawable.Move", &x, &y) )
return NULL; return NULL;
self->obj->Move(x, y); self->obj->Move(x, y);
Py_RETURN_NONE; Py_RETURN_NONE;
@ -185,7 +183,7 @@ static PyObject *
PySfDrawable_Scale(PySfDrawable* self, PyObject *args) PySfDrawable_Scale(PySfDrawable* self, PyObject *args)
{ {
float FactorX, FactorY; float FactorX, FactorY;
if ( !PyArg_ParseTuple(args, "ff", &FactorX, &FactorY) ) if (!PyArg_ParseTuple(args, "ff:Drawable.Scale", &FactorX, &FactorY) )
return NULL; return NULL;
self->obj->Scale(FactorX, FactorY); self->obj->Scale(FactorX, FactorY);
Py_RETURN_NONE; Py_RETURN_NONE;
@ -202,7 +200,7 @@ static PyObject *
PySfDrawable_SetPosition(PySfDrawable* self, PyObject *args) PySfDrawable_SetPosition(PySfDrawable* self, PyObject *args)
{ {
float Left, Top; float Left, Top;
if ( !PyArg_ParseTuple(args, "ff", &Left, &Top) ) if (!PyArg_ParseTuple(args, "ff:Drawable.SetPosition", &Left, &Top) )
return NULL; return NULL;
self->obj->SetPosition(Left, Top); self->obj->SetPosition(Left, Top);
Py_RETURN_NONE; Py_RETURN_NONE;
@ -212,7 +210,7 @@ static PyObject *
PySfDrawable_TransformToLocal(PySfDrawable* self, PyObject *args) PySfDrawable_TransformToLocal(PySfDrawable* self, PyObject *args)
{ {
float X, Y; float X, Y;
if ( !PyArg_ParseTuple(args, "ff", &X, &Y) ) if (!PyArg_ParseTuple(args, "ff:Drawable.TransformToLocal", &X, &Y) )
return NULL; return NULL;
sf::Vector2f result = self->obj->TransformToLocal(sf::Vector2f(X, Y)); sf::Vector2f result = self->obj->TransformToLocal(sf::Vector2f(X, Y));
return Py_BuildValue("ff", result.x, result.y); return Py_BuildValue("ff", result.x, result.y);
@ -222,7 +220,7 @@ static PyObject *
PySfDrawable_TransformToGlobal(PySfDrawable* self, PyObject *args) PySfDrawable_TransformToGlobal(PySfDrawable* self, PyObject *args)
{ {
float X, Y; float X, Y;
if ( !PyArg_ParseTuple(args, "ff", &X, &Y) ) if (!PyArg_ParseTuple(args, "ff:Drawable.TransformToGlobal", &X, &Y) )
return NULL; return NULL;
sf::Vector2f result = self->obj->TransformToGlobal(sf::Vector2f(X, Y)); sf::Vector2f result = self->obj->TransformToGlobal(sf::Vector2f(X, Y));
return Py_BuildValue("ff", result.x, result.y); return Py_BuildValue("ff", result.x, result.y);

View File

@ -29,7 +29,7 @@
#include <SFML/Graphics/Drawable.hpp> #include <SFML/Graphics/Drawable.hpp>
#include "RenderWindow.hpp" #include "RenderTarget.hpp"
class CustomDrawable : public sf::Drawable class CustomDrawable : public sf::Drawable
@ -37,7 +37,7 @@ class CustomDrawable : public sf::Drawable
protected : protected :
virtual void Render(sf::RenderTarget& Target) const; virtual void Render(sf::RenderTarget& Target) const;
public : public :
PySfRenderWindow *RenderWindow; PySfRenderTarget *RenderTarget;
PyObject *RenderFunction; PyObject *RenderFunction;
}; };

View File

@ -59,27 +59,48 @@ PySfFont_LoadFromFile(PySfFont* self, PyObject *args, PyObject *kwds)
const char *kwlist[] = {"Filename", "Charsize", "Charset", NULL}; const char *kwlist[] = {"Filename", "Charsize", "Charset", NULL};
unsigned int Charsize=30; unsigned int Charsize=30;
char *Filename; char *Filename;
char *CharsetTmp = NULL; char *Charset=NULL, *EncodingStr;
int CharsetSize; int Length;
bool Result; bool result;
std::string Encoding;
if (! PyArg_ParseTupleAndKeywords(args, kwds, "s|Is#:Font.LoadFromFile", (char **)kwlist, &Filename, &Charsize, &CharsetTmp, &CharsetSize)) if (PyArg_ParseTupleAndKeywords(args, kwds, "s|I:Font.LoadFromFile", (char **)kwlist, &Filename, &Charsize))
return NULL; result = self->obj->LoadFromFile(Filename, Charsize);
else if (PyArg_ParseTupleAndKeywords(args, kwds, "s|Iu:Font.LoadFromFile", (char **)kwlist, &Filename, &Charsize, &Charset))
if (CharsetTmp)
{ {
if ((unsigned char)CharsetTmp[0] == 0xff && (unsigned char)CharsetTmp[1] == 0xfe) PyErr_Clear();
Result = self->obj->LoadFromFile(Filename, Charsize, sf::Unicode::Text((const sf::Uint16 *)(CharsetTmp+2))); #if Py_UNICODE_SIZE == 4
result = self->obj->LoadFromFile(Filename, Charsize, (sf::Uint32 *)Charset);
#else
result = self->obj->LoadFromFile(Filename, Charsize, (sf::Uint16 *)Charset);
#endif
}
else if (PyArg_ParseTupleAndKeywords(args, kwds, "s|Is#s:Font.LoadFromFile", (char **)kwlist, &Filename, &Charsize, &Charset, &Length, &EncodingStr))
{
PyErr_Clear();
if (EncodingStr == NULL)
result = self->obj->LoadFromFile(Filename, Charsize, sf::Unicode::UTF8String((sf::Uint8 *)Charset));
else else
Result = self->obj->LoadFromFile(Filename, Charsize, sf::Unicode::Text((const sf::Uint8 *)CharsetTmp)); {
Encoding.assign(EncodingStr);
if (Encoding == "utf8" || Encoding == "")
result = self->obj->LoadFromFile(Filename, Charsize, sf::Unicode::UTF8String((sf::Uint8 *)Charset));
else if (Encoding == "utf16")
result = self->obj->LoadFromFile(Filename, Charsize, sf::Unicode::UTF16String((sf::Uint16 *)(Charset+2)));
else if (Encoding == "utf32")
result = self->obj->LoadFromFile(Filename, Charsize, sf::Unicode::UTF32String((sf::Uint32 *)(Charset+4)));
else
{
PyErr_Format(PyExc_TypeError, "Font.LoadFromFile() Encoding %s not supported", EncodingStr);
return NULL;
}
}
} }
else else
Result = self->obj->LoadFromFile(Filename, Charsize); {
PyErr_BadArgument();
if (Result) return NULL;
Py_RETURN_TRUE; }
else return PyBool_FromLong(result);
Py_RETURN_FALSE;
} }
static PyObject * static PyObject *
@ -88,27 +109,48 @@ PySfFont_LoadFromMemory(PySfFont* self, PyObject *args, PyObject *kwds)
const char *kwlist[] = {"Data", "Charsize", "Charset", NULL}; const char *kwlist[] = {"Data", "Charsize", "Charset", NULL};
unsigned int Charsize=30, Size; unsigned int Charsize=30, Size;
char *Data; char *Data;
char *CharsetTmp = NULL; char *Charset=NULL, *EncodingStr;
int CharsetSize; int Length;
bool Result; bool result;
std::string Encoding;
if (! PyArg_ParseTupleAndKeywords(args, kwds, "s#|Is#:Font.LoadFromMemory", (char **)kwlist, &Data, &Size, &Charsize, &CharsetTmp, &CharsetSize)) if (PyArg_ParseTupleAndKeywords(args, kwds, "s#|I:Font.LoadFromMemory", (char **)kwlist, &Data, &Size, &Charsize))
return NULL; result = self->obj->LoadFromMemory(Data, Size, Charsize);
else if (PyArg_ParseTupleAndKeywords(args, kwds, "s#|Iu:Font.LoadFromMemory", (char **)kwlist, &Data, &Size, &Charsize, &Charset))
if (CharsetTmp)
{ {
if ((unsigned char)CharsetTmp[0] == 0xff && (unsigned char)CharsetTmp[1] == 0xfe) PyErr_Clear();
Result = self->obj->LoadFromMemory(Data, Size, Charsize, sf::Unicode::Text((const sf::Uint16 *)(CharsetTmp+2))); #if Py_UNICODE_SIZE == 4
result = self->obj->LoadFromMemory(Data, Size, Charsize, (sf::Uint32 *)Charset);
#else
result = self->obj->LoadFromMemory(Data, Size, Charsize, (sf::Uint16 *)Charset);
#endif
}
else if (PyArg_ParseTupleAndKeywords(args, kwds, "s#|Is#s:Font.LoadFromMemory", (char **)kwlist, &Data, &Size, &Charsize, &Charset, &Length, &EncodingStr))
{
PyErr_Clear();
if (EncodingStr == NULL)
result = self->obj->LoadFromMemory(Data, Size, Charsize, sf::Unicode::UTF8String((sf::Uint8 *)Charset));
else else
Result = self->obj->LoadFromMemory(Data, Size, Charsize, sf::Unicode::Text((const sf::Uint8 *)CharsetTmp)); {
Encoding.assign(EncodingStr);
if (Encoding == "utf8")
result = self->obj->LoadFromMemory(Data, Size, Charsize, sf::Unicode::UTF8String((sf::Uint8 *)Charset));
else if (Encoding == "utf16")
result = self->obj->LoadFromMemory(Data, Size, Charsize, sf::Unicode::UTF16String((sf::Uint16 *)(Charset+2)));
else if (Encoding == "utf32")
result = self->obj->LoadFromMemory(Data, Size, Charsize, sf::Unicode::UTF32String((sf::Uint32 *)(Charset+4)));
else
{
PyErr_Format(PyExc_TypeError, "Font.LoadFromMemory() Encoding %s not supported", EncodingStr);
return NULL;
}
}
} }
else else
Result = self->obj->LoadFromMemory(Data, Size, Charsize); {
PyErr_BadArgument();
if (Result) return NULL;
Py_RETURN_TRUE; }
else return PyBool_FromLong(result);
Py_RETURN_FALSE;
} }
static PyObject * static PyObject *
@ -139,16 +181,16 @@ PySfFont_GetGlyph(PySfFont* self, PyObject *args)
} }
static PyMethodDef PySfFont_methods[] = { static PyMethodDef PySfFont_methods[] = {
{"LoadFromFile", (PyCFunction)PySfFont_LoadFromFile, METH_VARARGS | METH_KEYWORDS, "LoadFromFile(Filename, CharSize, Charset)\n\ {"LoadFromFile", (PyCFunction)PySfFont_LoadFromFile, METH_VARARGS | METH_KEYWORDS, "LoadFromFile(Filename, CharSize, UnicodeCharset) or LoadFromFile(Filename, CharSize, Charset, Encoding='utf8')\n\
Load the font from a file. Returns True if loading was successful.\n\ Load the font from a file. Returns True if loading was successful.\n\
Filename : Font file to load\n\ Filename : Font file to load\n\
CharSize : Size of characters in bitmap - the bigger, the higher quality (30 by default)\n\ CharSize : Size of characters in bitmap - the bigger, the higher quality (30 by default)\n\
Charset : Characters set to generate (empty by default - takes the ASCII range [31, 255])"}, Charset : Characters set to generate (by default, contains the ISO-8859-1 printable characters)"},
{"LoadFromMemory", (PyCFunction)PySfFont_LoadFromMemory, METH_VARARGS | METH_KEYWORDS, "LoadFromMemory(Data, CharSize, Charset)\n\ {"LoadFromMemory", (PyCFunction)PySfFont_LoadFromMemory, METH_VARARGS | METH_KEYWORDS, "LoadFromMemory(Data, CharSize, UnicodeCharset) or LoadFromMemory(Data, CharSize, Charset, Encoding='utf8')\n\
Load the font from a file in memory. Returns True if loading was successful.\n\ Load the font from a file in memory. Returns True if loading was successful.\n\
Data : data to load\n\ Data : data to load\n\
CharSize : Size of characters in bitmap - the bigger, the higher quality (30 by default)\n\ CharSize : Size of characters in bitmap - the bigger, the higher quality (30 by default)\n\
Charset : Characters set to generate (empty by default - takes the ASCII range [31, 255])"}, Charset : Characters set to generate (by default, contains the ISO-8859-1 printable characters)"},
{"GetDefaultFont", (PyCFunction)PySfFont_GetDefaultFont, METH_NOARGS | METH_STATIC, "GetDefaultFont()\n\ {"GetDefaultFont", (PyCFunction)PySfFont_GetDefaultFont, METH_NOARGS | METH_STATIC, "GetDefaultFont()\n\
Get the SFML default built-in font (Arial)."}, Get the SFML default built-in font (Arial)."},
{"GetCharacterSize", (PyCFunction)PySfFont_GetCharacterSize, METH_NOARGS, "GetCharacterSize()\n\ {"GetCharacterSize", (PyCFunction)PySfFont_GetCharacterSize, METH_NOARGS, "GetCharacterSize()\n\

View File

@ -33,21 +33,6 @@ extern PyTypeObject PySfColorType;
extern PyTypeObject PySfViewType; extern PyTypeObject PySfViewType;
static void
PySfRenderTarget_dealloc(PySfRenderTarget *self)
{
delete self->obj;
free_object(self);
}
static PyObject *
PySfRenderTarget_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
PySfRenderTarget *self;
self = (PySfRenderTarget *)type->tp_alloc(type, 0);
return (PyObject *)self;
}
static PyObject * static PyObject *
PySfRenderTarget_Clear(PySfRenderTarget *self, PyObject *args) PySfRenderTarget_Clear(PySfRenderTarget *self, PyObject *args)
{ {
@ -87,8 +72,7 @@ PySfRenderTarget_GetView(PySfRenderTarget *self)
static PyObject * static PyObject *
PySfRenderTarget_PreserveOpenGLStates(PySfRenderTarget *self, PyObject *args) PySfRenderTarget_PreserveOpenGLStates(PySfRenderTarget *self, PyObject *args)
{ {
bool Optimize = PyBool_AsBool(args); self->obj->PreserveOpenGLStates(PyBool_AsBool(args));
self->obj->PreserveOpenGLStates(Optimize);
Py_RETURN_NONE; Py_RETURN_NONE;
} }
@ -138,7 +122,7 @@ PyTypeObject PySfRenderTargetType = {
"RenderTarget", /*tp_name*/ "RenderTarget", /*tp_name*/
sizeof(PySfRenderTarget), /*tp_basicsize*/ sizeof(PySfRenderTarget), /*tp_basicsize*/
0, /*tp_itemsize*/ 0, /*tp_itemsize*/
(destructor)PySfRenderTarget_dealloc, /*tp_dealloc*/ 0, /*tp_dealloc*/
0, /*tp_print*/ 0, /*tp_print*/
0, /*tp_getattr*/ 0, /*tp_getattr*/
0, /*tp_setattr*/ 0, /*tp_setattr*/
@ -162,16 +146,6 @@ PyTypeObject PySfRenderTargetType = {
0, /* tp_iter */ 0, /* tp_iter */
0, /* tp_iternext */ 0, /* tp_iternext */
PySfRenderTarget_methods, /* tp_methods */ PySfRenderTarget_methods, /* tp_methods */
0, /* tp_members */
0, /* tp_getset */
0, /* tp_base */
0, /* tp_dict */
0, /* tp_descr_get */
0, /* tp_descr_set */
0, /* tp_dictoffset */
0, /* tp_init */
0, /* tp_alloc */
PySfRenderTarget_new, /* tp_new */
}; };

View File

@ -38,12 +38,8 @@
#include <SFML/Window/WindowStyle.hpp> #include <SFML/Window/WindowStyle.hpp>
extern PyTypeObject PySfEventType;
extern PyTypeObject PySfViewType; extern PyTypeObject PySfViewType;
extern PyTypeObject PySfColorType;
extern PyTypeObject PySfWindowType; extern PyTypeObject PySfWindowType;
extern PyTypeObject PySfWindowSettingsType;
extern PyTypeObject PySfVideoModeType;
extern PyTypeObject PySfDrawableType; extern PyTypeObject PySfDrawableType;
extern PyTypeObject PySfRenderTargetType; extern PyTypeObject PySfRenderTargetType;
@ -108,7 +104,9 @@ PySfRenderWindow_DrawObject(PySfRenderWindow *RenderWindow, PySfDrawable *Obj)
{ {
if (PyObject_HasAttrString((PyObject *)Obj, "Render")) if (PyObject_HasAttrString((PyObject *)Obj, "Render"))
{ {
Obj->obj->RenderWindow = RenderWindow; Py_DECREF(Obj->obj->RenderTarget);
Obj->obj->RenderTarget = (PySfRenderTarget *)RenderWindow;
Py_DECREF(Obj->obj->RenderFunction);
Obj->obj->RenderFunction = PyObject_GetAttrString((PyObject *)Obj, "Render"); Obj->obj->RenderFunction = PyObject_GetAttrString((PyObject *)Obj, "Render");
} }
RenderWindow->obj->Draw( *(Obj->obj) ); RenderWindow->obj->Draw( *(Obj->obj) );
@ -120,21 +118,18 @@ PySfRenderWindow_DrawObject(PySfRenderWindow *RenderWindow, PySfDrawable *Obj)
static PyObject * static PyObject *
PySfRenderWindow_Draw(PySfRenderWindow *self, PyObject *args) PySfRenderWindow_Draw(PySfRenderWindow *self, PyObject *args)
{ {
if (!args) if (args == NULL)
return NULL; return NULL;
if (!PySfRenderWindow_DrawObject(self, (PySfDrawable *)args)) if (!PySfRenderWindow_DrawObject(self, (PySfDrawable *)args))
{ {
PyObject *iterator = PyObject_GetIter(args); PyObject *iterator = PyObject_GetIter(args);
PyObject *item; PyObject *item;
PyErr_Clear();
if (iterator == NULL) if (iterator == NULL)
{ {
PyErr_SetString(PyExc_TypeError, "Argument to Draw method is neither a Drawable nor an iterable."); PyErr_SetString(PyExc_TypeError, "Argument to Draw method is neither a Drawable nor an iterable.");
return NULL; return NULL;
} }
while ((item = PyIter_Next(iterator))) while ((item = PyIter_Next(iterator)))
{ {
if (!PySfRenderWindow_DrawObject(self, (PySfDrawable *)item)) if (!PySfRenderWindow_DrawObject(self, (PySfDrawable *)item))
@ -144,16 +139,24 @@ PySfRenderWindow_Draw(PySfRenderWindow *self, PyObject *args)
} }
Py_DECREF(item); Py_DECREF(item);
} }
Py_DECREF(iterator); Py_DECREF(iterator);
if (PyErr_Occurred())
return NULL;
} }
if (PyErr_Occurred())
return NULL;
Py_RETURN_NONE;
}
static PyObject *
PySfRenderWindow_PreserveOpenGLStates(PySfRenderWindow *self, PyObject *args)
{
self->obj->PreserveOpenGLStates(PyBool_AsBool(args));
Py_RETURN_NONE; Py_RETURN_NONE;
} }
static PyMethodDef PySfRenderWindow_methods[] = { static PyMethodDef PySfRenderWindow_methods[] = {
{"PreserveOpenGLStates", (PyCFunction)PySfRenderWindow_PreserveOpenGLStates, METH_O, "PreserveOpenGLStates(Preserve)\n\
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\n\
Preserve : True to preserve OpenGL states, false to let SFML optimize"},
{"Capture", (PyCFunction)PySfRenderWindow_Capture, METH_NOARGS, "Capture()\n\ {"Capture", (PyCFunction)PySfRenderWindow_Capture, METH_NOARGS, "Capture()\n\
Save the content of the window to an image. Returns a sf.Image object."}, Save the content of the window to an image. Returns a sf.Image object."},
{"ConvertCoords", (PyCFunction)PySfRenderWindow_ConvertCoords, METH_VARARGS, "ConvertCoords(WindowX, WindowY, TargetView)\n\ {"ConvertCoords", (PyCFunction)PySfRenderWindow_ConvertCoords, METH_VARARGS, "ConvertCoords(WindowX, WindowY, TargetView)\n\

View File

@ -51,19 +51,16 @@ PySfString_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
return (PyObject *)self; return (PyObject *)self;
} }
static int static int
PySfString_init(PySfString *self, PyObject *args, PyObject *kwds) PySfString_init(PySfString *self, PyObject *args, PyObject *kwds)
{ {
const char *kwlist[] = {"Text", "Font", "Size", NULL}; const char *kwlist[] = {"Text", "Font", "Size", NULL};
float Size = 30.f; float Size = 30.f;
std::string Text = ""; PyObject *Text=NULL;
char *TextTmp = NULL;
unsigned int TextSize;
PySfFont *FontTmp = NULL; PySfFont *FontTmp = NULL;
sf::Font *Font; sf::Font *Font;
if (! PyArg_ParseTupleAndKeywords(args, kwds, "|s#O!f", (char **)kwlist, &TextTmp, &TextSize, &PySfFontType, &FontTmp, &Size)) if (!PyArg_ParseTupleAndKeywords(args, kwds, "|OO!f:String.__init__", (char **)kwlist, &Text, &PySfFontType, &FontTmp, &Size))
return -1; return -1;
if (FontTmp) if (FontTmp)
@ -71,39 +68,74 @@ PySfString_init(PySfString *self, PyObject *args, PyObject *kwds)
else else
Font = (sf::Font *)&(sf::Font::GetDefaultFont()); Font = (sf::Font *)&(sf::Font::GetDefaultFont());
if (TextSize >= 2 && TextTmp) if (Text != NULL)
if ((unsigned char)TextTmp[0] == 0xff && (unsigned char)TextTmp[1] == 0xfe) {
if (PyUnicode_Check(Text))
{ {
self->obj = new sf::String(sf::Unicode::Text((const sf::Uint16 *)(TextTmp+2)), *Font, Size); #if Py_UNICODE_SIZE == 4
return 0; self->obj = new sf::String((sf::Uint32 *)PyUnicode_AS_UNICODE(Text), *Font, Size);
#else
self->obj = new sf::String((sf::Uint16 *)PyUnicode_AS_UNICODE(Text), *Font, Size);
#endif
} }
#ifdef IS_PY3K
if (TextTmp != NULL) else if (PyBytes_Check(Text))
self->obj = new sf::String(sf::Unicode::Text((const sf::Uint8 *)(TextTmp)), *Font, Size); self->obj = new sf::String(sf::Unicode::UTF8String((sf::Uint8 *)PyBytes_AsString(Text)), *Font, Size);
#else
else if (PyString_Check(Text))
self->obj = new sf::String(sf::Unicode::UTF8String((sf::Uint8 *)PyString_AsString(Text)), *Font, Size);
#endif
else
{
PyErr_SetString(PyExc_TypeError, "String.__init__() first argument must be str");
return -1;
}
}
else else
self->obj = new sf::String(); self->obj = new sf::String("", *Font, Size);
return 0; return 0;
} }
static PyObject * static PyObject *
PySfString_SetText(PySfString* self, PyObject *args) PySfString_SetText(PySfString* self, PyObject *args)
{ {
char *TextTmp = NULL; char *Text, *EncodingStr=NULL;
int Size; int Length;
if (!PyArg_Parse(args, "s#", &TextTmp, &Size)) std::string Encoding;
return NULL; if (PyArg_ParseTuple(args, "u:String.SetText", &Text))
if (Size >= 2)
{ {
if ((unsigned char)TextTmp[0] == 0xff && (unsigned char)TextTmp[1] == 0xfe) #if Py_UNICODE_SIZE == 4
self->obj->SetText((sf::Uint32 *)Text);
#else
self->obj->SetText((sf::Uint16 *)Text);
#endif
}
else if (PyArg_ParseTuple(args, "s|#s:String.SetText", &Text, &Length, &EncodingStr))
{
PyErr_Clear();
if (EncodingStr == NULL)
self->obj->SetText(sf::Unicode::UTF8String((sf::Uint8 *)Text));
else
{ {
self->obj->SetText(sf::Unicode::Text((const sf::Uint16 *)(TextTmp+2))); Encoding.assign(EncodingStr);
Py_RETURN_NONE; if (Encoding == "utf8")
self->obj->SetText(sf::Unicode::UTF8String((sf::Uint8 *)Text));
else if (Encoding == "utf16")
self->obj->SetText(sf::Unicode::UTF16String((sf::Uint16 *)(Text+2)));
else if (Encoding == "utf32")
self->obj->SetText(sf::Unicode::UTF32String((sf::Uint32 *)(Text+4)));
else
{
PyErr_Format(PyExc_TypeError, "String.SetText() Encoding %s not supported", EncodingStr);
return NULL;
}
} }
} }
self->obj->SetText(sf::Unicode::Text((const sf::Uint8 *)(TextTmp))); else
{
PyErr_BadArgument();
return NULL;
}
Py_RETURN_NONE; Py_RETURN_NONE;
} }
@ -146,12 +178,12 @@ PySfString_GetStyle(PySfString* self)
static PyObject * static PyObject *
PySfString_GetText(PySfString* self) PySfString_GetText(PySfString* self)
{ {
std::string Text = (std::string(self->obj->GetText())); #if Py_UNICODE_SIZE == 4
#ifdef IS_PY3K sf::Unicode::UTF32String Text(self->obj->GetText());
return PyUnicode_DecodeUTF8(Text.c_str(), (Py_ssize_t)Text.length(), "replace");
#else #else
return PyString_FromString(Text.c_str()); sf::Unicode::UTF16String Text(self->obj->GetText());
#endif #endif
return PyUnicode_FromUnicode((const Py_UNICODE*)Text.c_str(), Text.length());
} }
static PyObject * static PyObject *
@ -189,8 +221,8 @@ static PyMethodDef PySfString_methods[] = {
{"GetCharacterPos", (PyCFunction)PySfString_GetCharacterPos, METH_O, "GetCharacterPos(Index)\n\ {"GetCharacterPos", (PyCFunction)PySfString_GetCharacterPos, METH_O, "GetCharacterPos(Index)\n\
Return the visual position (a tuple of two floats) of the Index-th character of the string, in coordinates relative to the string (note : translation, center, rotation and scale are not applied)\n\ Return the visual position (a tuple of two floats) of the Index-th character of the string, in coordinates relative to the string (note : translation, center, rotation and scale are not applied)\n\
Index : Index of the character"}, Index : Index of the character"},
{"SetText", (PyCFunction)PySfString_SetText, METH_O, "SetText(Text)\nSet the text (an utf-8 or utf-16 string).\n Text : New text"}, {"SetText", (PyCFunction)PySfString_SetText, METH_VARARGS, "SetText(UnicodeText) or SetText(Text, Encoding='utf8')\nSet the text. Valid encodings are 'utf8', 'utf16' and 'utf32'.\n Text : New text"},
{"GetText", (PyCFunction)PySfString_GetText, METH_NOARGS, "GetText()\nGet the text."}, {"GetText", (PyCFunction)PySfString_GetText, METH_NOARGS, "GetText()\nGet the text as an unicode string."},
{"SetFont", (PyCFunction)PySfString_SetFont, METH_O, "SetFont(Font)\nSet the font of the string.\n Font : font to use"}, {"SetFont", (PyCFunction)PySfString_SetFont, METH_O, "SetFont(Font)\nSet the font of the string.\n Font : font to use"},
{"GetFont", (PyCFunction)PySfString_GetFont, METH_NOARGS, "GetFont()\nGet the font used by the string."}, {"GetFont", (PyCFunction)PySfString_GetFont, METH_NOARGS, "GetFont()\nGet the font used by the string."},
{"SetSize", (PyCFunction)PySfString_SetSize, METH_O, "SetSize(Size)\nSet the size of the string.\n Size : New size, in pixels"}, {"SetSize", (PyCFunction)PySfString_SetSize, METH_O, "SetSize(Size)\nSet the size of the string.\n Size : New size, in pixels"},
@ -223,7 +255,7 @@ PyTypeObject PySfStringType = {
0, /*tp_as_buffer*/ 0, /*tp_as_buffer*/
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/
"sf.String defines a graphical 2D text, that can be drawn on screen.\n\ "sf.String defines a graphical 2D text, that can be drawn on screen.\n\
Default constructor : String ()\nConstruct the string from a utf-8 or a utf-16 string : String(Text, Font=sf.Font.GetDefaultFont(), Size=30.)\n Text : Text assigned to the string\n Font : Font used to draw the string (SFML built-in font by default)\n Size : Characters size (30 by default)", /* tp_doc */ Default constructor : String ()\nConstruct the string from an unicode or an ascii string : String(Text, Font=sf.Font.GetDefaultFont(), Size=30.)\n Text : Text assigned to the string\n Font : Font used to draw the string (SFML built-in font by default)\n Size : Characters size (30 by default)", /* tp_doc */
0, /* tp_traverse */ 0, /* tp_traverse */
0, /* tp_clear */ 0, /* tp_clear */
0, /* tp_richcompare */ 0, /* tp_richcompare */

View File

@ -287,7 +287,7 @@ Create a window.\n\
Mode : Video mode to use (sf.VideoMode instance)\n\ Mode : Video mode to use (sf.VideoMode instance)\n\
Title : Title of the window\n\ Title : Title of the window\n\
WindowStyle : Window style (Resize | Close by default)\n\ WindowStyle : Window style (Resize | Close by default)\n\
Params : Creation parameters (see default constructor for default values)\n"}, Params : Creation parameters (see default constructor for default values)"},
{"Display", (PyCFunction)PySfWindow_Display, METH_NOARGS, "Display()\nDisplay the window on screen."}, {"Display", (PyCFunction)PySfWindow_Display, METH_NOARGS, "Display()\nDisplay the window on screen."},
{"EnableKeyRepeat", (PyCFunction)PySfWindow_EnableKeyRepeat, METH_O, "EnableKeyRepeat(Enable)\nEnable or disable automatic key-repeat. Automatic key-repeat is enabled by default.\n Enabled : True to enable, false to disable"}, {"EnableKeyRepeat", (PyCFunction)PySfWindow_EnableKeyRepeat, METH_O, "EnableKeyRepeat(Enable)\nEnable or disable automatic key-repeat. Automatic key-repeat is enabled by default.\n Enabled : True to enable, false to disable"},
{"GetEvent", (PyCFunction)PySfWindow_GetEvent, METH_O, "GetEvent(Event)\nGet the event on top of events stack, if any, and pop it. Returns True if an event was returned, False if events stack was empty.\n EventReceived : Event to fill, if any."}, {"GetEvent", (PyCFunction)PySfWindow_GetEvent, METH_O, "GetEvent(Event)\nGet the event on top of events stack, if any, and pop it. Returns True if an event was returned, False if events stack was empty.\n EventReceived : Event to fill, if any."},

View File

@ -101,7 +101,7 @@ static PyModuleDef module_def = {
module_methods, NULL, NULL, NULL, NULL module_methods, NULL, NULL, NULL, NULL
}; };
PyObject * PyMODINIT_FUNC
PyInit_sf(void) PyInit_sf(void)
#else #else
#define INITERROR return #define INITERROR return