From 6c98d270b90b86cf674f9c4cce3578c31f7bb586 Mon Sep 17 00:00:00 2001 From: laurentgom Date: Fri, 6 Feb 2009 16:27:53 +0000 Subject: [PATCH 01/22] Updated version number in makefiles git-svn-id: https://sfml.svn.sourceforge.net/svnroot/sfml/trunk@1011 4e206d99-4929-0410-ac5d-dfc041789085 --- CSFML/src/SFML/Makefile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CSFML/src/SFML/Makefile b/CSFML/src/SFML/Makefile index cd2f22e48..bcb6551eb 100644 --- a/CSFML/src/SFML/Makefile +++ b/CSFML/src/SFML/Makefile @@ -3,7 +3,7 @@ export CPP = g++ export CFLAGS = -W -Wall -pedantic -fPIC -Wno-unused -I../.. -I../../../include -DNDEBUG -DCSFML_EXPORTS -O2 export LDFLAGS = -shared export LIBPATH = ../../../lib -export VERSION = 1.4 +export VERSION = 1.5 export CP = cp export LN = ln export LNFLAGS = -s -f From 73c041cbcf015526647fb8e8ceb8a1d649fa3bea Mon Sep 17 00:00:00 2001 From: laurentgom Date: Tue, 10 Feb 2009 18:27:42 +0000 Subject: [PATCH 02/22] Added an option in Image::Copy to take into account the source transparency git-svn-id: https://sfml.svn.sourceforge.net/svnroot/sfml/trunk@1012 4e206d99-4929-0410-ac5d-dfc041789085 --- src/SFML/Graphics/Image.cpp | 36 +++++++++++++++++++++++++++++++----- 1 file changed, 31 insertions(+), 5 deletions(-) diff --git a/src/SFML/Graphics/Image.cpp b/src/SFML/Graphics/Image.cpp index 62e64a1f6..938a95941 100644 --- a/src/SFML/Graphics/Image.cpp +++ b/src/SFML/Graphics/Image.cpp @@ -267,7 +267,7 @@ void Image::CreateMaskFromColor(Color ColorKey, Uint8 Alpha) /// This function does a slow pixel copy and should only /// be used at initialization time //////////////////////////////////////////////////////////// -void Image::Copy(const Image& Source, unsigned int DestX, unsigned int DestY, const IntRect& SourceRect) +void Image::Copy(const Image& Source, unsigned int DestX, unsigned int DestY, const IntRect& SourceRect, bool ApplyAlpha) { // Make sure both images are valid if ((Source.myWidth == 0) || (Source.myHeight == 0) || (myWidth == 0) || (myHeight == 0)) @@ -313,11 +313,37 @@ void Image::Copy(const Image& Source, unsigned int DestX, unsigned int DestY, co Uint8* DstPixels = reinterpret_cast(&myPixels[0]) + (DestX + DestY * myWidth) * 4; // Copy the pixels - for (int i = 0; i < Rows; ++i) + if (ApplyAlpha) { - memcpy(DstPixels, SrcPixels, Pitch); - SrcPixels += SrcStride; - DstPixels += DstStride; + // Interpolation using alpha values, pixel by pixel (slower) + for (int i = 0; i < Rows; ++i) + { + for (int j = 0; j < Width; ++j) + { + // Get a direct pointer to the components of the current pixel + const Uint8* Src = SrcPixels + j * 4; + Uint8* Dst = DstPixels + j * 4; + + // Interpolate RGB components using the alpha value of the source pixel + Uint8 Alpha = Src[3]; + Dst[0] = (Src[0] * Alpha + Dst[0] * (255 - Alpha)) / 255; + Dst[1] = (Src[1] * Alpha + Dst[1] * (255 - Alpha)) / 255; + Dst[2] = (Src[2] * Alpha + Dst[2] * (255 - Alpha)) / 255; + } + + SrcPixels += SrcStride; + DstPixels += DstStride; + } + } + else + { + // Optimized copy ignoring alpha values, row by row (faster) + for (int i = 0; i < Rows; ++i) + { + memcpy(DstPixels, SrcPixels, Pitch); + SrcPixels += SrcStride; + DstPixels += DstStride; + } } // The texture will need an update From dd5b22b87228d8dac60f10b6baa2cbc813d725b7 Mon Sep 17 00:00:00 2001 From: laurentgom Date: Tue, 10 Feb 2009 18:31:56 +0000 Subject: [PATCH 03/22] git-svn-id: https://sfml.svn.sourceforge.net/svnroot/sfml/trunk@1013 4e206d99-4929-0410-ac5d-dfc041789085 --- include/SFML/Graphics/Image.hpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/include/SFML/Graphics/Image.hpp b/include/SFML/Graphics/Image.hpp index e950ec33b..ee136f0a7 100644 --- a/include/SFML/Graphics/Image.hpp +++ b/include/SFML/Graphics/Image.hpp @@ -161,9 +161,10 @@ public : /// \param DestX : X coordinate of the destination position /// \param DestY : Y coordinate of the destination position /// \param SourceRect : Sub-rectangle of the source image to copy (empty by default - entire image) + /// \param ApplyAlpha : Should the copy take in account the source transparency? (false by default) /// //////////////////////////////////////////////////////////// - void Copy(const Image& Source, unsigned int DestX, unsigned int DestY, const IntRect& SourceRect = IntRect(0, 0, 0, 0)); + void Copy(const Image& Source, unsigned int DestX, unsigned int DestY, const IntRect& SourceRect = IntRect(0, 0, 0, 0), bool ApplyAlpha = false); //////////////////////////////////////////////////////////// /// Create the image from the current contents of the From ebdee32601cc7747ea08278f00c5a11c1b8ab396 Mon Sep 17 00:00:00 2001 From: laurentgom Date: Sat, 14 Feb 2009 11:13:33 +0000 Subject: [PATCH 04/22] Fixed Window::SetSize not resizing to the requested size, on Windows git-svn-id: https://sfml.svn.sourceforge.net/svnroot/sfml/trunk@1016 4e206d99-4929-0410-ac5d-dfc041789085 --- src/SFML/Window/Win32/WindowImplWin32.cpp | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/src/SFML/Window/Win32/WindowImplWin32.cpp b/src/SFML/Window/Win32/WindowImplWin32.cpp index 736d5e6aa..2bd9c6d4a 100644 --- a/src/SFML/Window/Win32/WindowImplWin32.cpp +++ b/src/SFML/Window/Win32/WindowImplWin32.cpp @@ -355,6 +355,13 @@ void WindowImplWin32::SetPosition(int Left, int Top) //////////////////////////////////////////////////////////// void WindowImplWin32::SetSize(unsigned int Width, unsigned int Height) { + // SetWindowPos wants the total size of the window (including title bar and borders), + // so we have to compute it + RECT Rect = {0, 0, Width, Height}; + AdjustWindowRect(&Rect, GetWindowLong(myHandle, GWL_STYLE), false); + Width = Rect.right - Rect.left; + Height = Rect.bottom - Rect.top; + SetWindowPos(myHandle, NULL, 0, 0, Width, Height, SWP_NOMOVE | SWP_NOZORDER); } From 4a3d6b171c579c610458741f4d450e88a08982d1 Mon Sep 17 00:00:00 2001 From: remi-k Date: Sat, 14 Feb 2009 19:43:12 +0000 Subject: [PATCH 05/22] git-svn-id: https://sfml.svn.sourceforge.net/svnroot/sfml/trunk@1017 4e206d99-4929-0410-ac5d-dfc041789085 --- python/PKG-INFO | 2 +- python/setup.py | 2 +- python/src/Color.cpp | 2 +- python/src/Drawable.cpp | 6 ++++++ python/src/Drawable.hpp | 3 +++ python/src/Image.cpp | 2 +- python/src/Input.cpp | 2 +- python/src/Rect.cpp | 4 ++-- python/src/Shape.cpp | 2 +- python/src/SoundBuffer.cpp | 2 +- python/src/WindowSettings.cpp | 2 +- python/src/main.cpp | 2 +- 12 files changed, 20 insertions(+), 11 deletions(-) diff --git a/python/PKG-INFO b/python/PKG-INFO index 7d48fe13b..354c67c19 100644 --- a/python/PKG-INFO +++ b/python/PKG-INFO @@ -1,6 +1,6 @@ Metadata-Version: 1.0 Name: PySFML -Version: 1.4 +Version: 1.5 Summary: Python binding for SFML (Simple and Fast Multimedia Library) Home-page: http://sfml.sourceforge.net/ Author: Rémi Koenig diff --git a/python/setup.py b/python/setup.py index 125ed275a..bb05523f3 100644 --- a/python/setup.py +++ b/python/setup.py @@ -4,7 +4,7 @@ from distutils.core import setup, Extension setup(name='PySFML', - version='1.4', + version='1.5', description='Python binding for SFML (Simple and Fast Multimedia Library)', author='Rémi Koenig', author_email='remi.k2620@gmail.com', diff --git a/python/src/Color.cpp b/python/src/Color.cpp index 30e428ee0..1b3043299 100644 --- a/python/src/Color.cpp +++ b/python/src/Color.cpp @@ -145,7 +145,7 @@ PyTypeObject PySfColorType = { PySfColor * GetNewPySfColor() { - return PyObject_New(PySfColor, &PySfColorType); + return (PySfColor *)PySfColor_new(&PySfColorType, NULL, NULL); } void diff --git a/python/src/Drawable.cpp b/python/src/Drawable.cpp index 347e7f730..008e469a9 100644 --- a/python/src/Drawable.cpp +++ b/python/src/Drawable.cpp @@ -302,4 +302,10 @@ PyTypeObject PySfDrawableType = { PySfDrawable_new, /* tp_new */ }; +PySfDrawable * +GetNewPySfDrawable() +{ + return (PySfDrawable *)PySfDrawable_new(&PySfDrawableType, NULL, NULL); +} + diff --git a/python/src/Drawable.hpp b/python/src/Drawable.hpp index 8676d9dd8..2553b640a 100644 --- a/python/src/Drawable.hpp +++ b/python/src/Drawable.hpp @@ -50,5 +50,8 @@ typedef struct { CustomDrawable *obj; } PySfDrawable; +PySfDrawable * +GetNewPySfDrawable(); + #endif diff --git a/python/src/Image.cpp b/python/src/Image.cpp index 9991135f2..bd1f57d67 100644 --- a/python/src/Image.cpp +++ b/python/src/Image.cpp @@ -414,6 +414,6 @@ PySfImage_Copy(PySfImage* self, PyObject *args) PySfImage * GetNewPySfImage() { - return PyObject_New(PySfImage, &PySfImageType); + return (PySfImage *)PySfImage_new(&PySfImageType, NULL, NULL); } diff --git a/python/src/Input.cpp b/python/src/Input.cpp index e0162fb2b..7116731e4 100644 --- a/python/src/Input.cpp +++ b/python/src/Input.cpp @@ -162,6 +162,6 @@ PyTypeObject PySfInputType = { PySfInput * GetNewPySfInput() { - return PyObject_New(PySfInput, &PySfInputType); + return (PySfInput *)PySfInput_new(&PySfInputType, NULL, NULL); } diff --git a/python/src/Rect.cpp b/python/src/Rect.cpp index abd938ab1..46d03722b 100644 --- a/python/src/Rect.cpp +++ b/python/src/Rect.cpp @@ -425,13 +425,13 @@ PySfFloatRectUpdateSelf(PySfFloatRect *self) PySfIntRect * GetNewPySfIntRect() { - return PyObject_New(PySfIntRect, &PySfIntRectType); + return (PySfIntRect *)PySfIntRect_new(&PySfIntRectType, NULL, NULL); } PySfFloatRect * GetNewPySfFloatRect() { - return PyObject_New(PySfFloatRect, &PySfFloatRectType); + return (PySfFloatRect *)PySfFloatRect_new(&PySfFloatRectType, NULL, NULL); } diff --git a/python/src/Shape.cpp b/python/src/Shape.cpp index ad2bd5260..622e0f90e 100644 --- a/python/src/Shape.cpp +++ b/python/src/Shape.cpp @@ -391,6 +391,6 @@ PyTypeObject PySfShapeType = { PySfShape * GetNewPySfShape() { - return PyObject_New(PySfShape, &PySfShapeType); + return (PySfShape *)PySfShape_new(&PySfShapeType, NULL, NULL); } diff --git a/python/src/SoundBuffer.cpp b/python/src/SoundBuffer.cpp index cf651bde0..2d0fd5522 100644 --- a/python/src/SoundBuffer.cpp +++ b/python/src/SoundBuffer.cpp @@ -213,6 +213,6 @@ PySfSoundBuffer_init(PySfSoundBuffer *self, PyObject *args, PyObject *kwds) PySfSoundBuffer * GetNewPySfSoundBuffer() { - return PyObject_New(PySfSoundBuffer, &PySfSoundBufferType); + return (PySfSoundBuffer *)PySfSoundBuffer_new(&PySfSoundBufferType, NULL, NULL); } diff --git a/python/src/WindowSettings.cpp b/python/src/WindowSettings.cpp index f6e5be476..807e7d847 100644 --- a/python/src/WindowSettings.cpp +++ b/python/src/WindowSettings.cpp @@ -126,6 +126,6 @@ PyTypeObject PySfWindowSettingsType = { PySfWindowSettings * GetNewPySfWindowSettings() { - return PyObject_New(PySfWindowSettings, &PySfWindowSettingsType); + return (PySfWindowSettings *)PySfWindowSettings_new(&PySfWindowSettingsType, NULL, NULL); } diff --git a/python/src/main.cpp b/python/src/main.cpp index d879f4a76..86f3fae89 100644 --- a/python/src/main.cpp +++ b/python/src/main.cpp @@ -260,7 +260,7 @@ initsf(void) Py_INCREF(&PySfListenerType); PyModule_AddObject(m, "Listener", (PyObject *)&PySfListenerType); - PyModule_AddStringConstant(m, "Version", "1.4"); + PyModule_AddStringConstant(m, "Version", "1.5"); PySfColor_InitConst(); PySfKey_InitConst(); From e580c8cd63ccc97c47e17ea039e77571795ff7bb Mon Sep 17 00:00:00 2001 From: laurentgom Date: Fri, 20 Feb 2009 21:38:59 +0000 Subject: [PATCH 06/22] sf::SoundStream (and sf::Music) is now able to loop seamlessly git-svn-id: https://sfml.svn.sourceforge.net/svnroot/sfml/trunk@1018 4e206d99-4929-0410-ac5d-dfc041789085 --- samples/sound/Sound.cpp | 6 +-- src/SFML/Audio/SoundStream.cpp | 70 ++++++++++++++++++---------------- 2 files changed, 40 insertions(+), 36 deletions(-) diff --git a/samples/sound/Sound.cpp b/samples/sound/Sound.cpp index 94314d3c4..c50b0c542 100644 --- a/samples/sound/Sound.cpp +++ b/samples/sound/Sound.cpp @@ -64,11 +64,11 @@ void PlayMusic() // Loop while the music is playing while (Music.GetStatus() == sf::Music::Playing) { - // Display the playing position - std::cout << "\rPlaying... " << std::fixed << std::setprecision(2) << Music.GetPlayingOffset() << " sec "; - // Leave some CPU time for other processes sf::Sleep(0.1f); + + // Display the playing position + std::cout << "\rPlaying... " << std::fixed << std::setprecision(2) << Music.GetPlayingOffset() << " sec "; } std::cout << std::endl; } diff --git a/src/SFML/Audio/SoundStream.cpp b/src/SFML/Audio/SoundStream.cpp index 991a0bca1..f5b87c430 100644 --- a/src/SFML/Audio/SoundStream.cpp +++ b/src/SFML/Audio/SoundStream.cpp @@ -191,6 +191,7 @@ void SoundStream::Run() { // Create buffers ALCheck(alGenBuffers(BuffersCount, myBuffers)); + unsigned int EndBuffer = 0xFFFF; // Fill the queue bool RequestStop = FillQueue(); @@ -203,37 +204,15 @@ void SoundStream::Run() // The stream has been interrupted ! if (Sound::GetStatus() == Stopped) { - // User requested to stop - if (RequestStop) + if (!RequestStop) { - if (myLoop) - { - // The stream is in loop mode : restart it - if (OnStart()) - { - mySamplesProcessed = 0; - ClearQueue(); - RequestStop = FillQueue(); - Sound::Play(); - } - else - { - // Restart failed : finish the streaming loop - myIsStreaming = false; - break; - } - } - else - { - // The stream is not in loop mode : finish the streaming loop - myIsStreaming = false; - break; - } + // Just continue + Sound::Play(); } else { - // Streaming is not completed : restart the sound - Sound::Play(); + // End streaming + myIsStreaming = false; } } @@ -241,20 +220,45 @@ void SoundStream::Run() ALint NbProcessed; ALCheck(alGetSourcei(Sound::mySource, AL_BUFFERS_PROCESSED, &NbProcessed)); - while (NbProcessed-- && !RequestStop) + while (NbProcessed--) { // Pop the first unused buffer from the queue ALuint Buffer; ALCheck(alSourceUnqueueBuffers(Sound::mySource, 1, &Buffer)); // Retrieve its size and add it to the samples count - ALint Size; - ALCheck(alGetBufferi(Buffer, AL_SIZE, &Size)); - mySamplesProcessed += Size / sizeof(Int16); + if (Buffer == EndBuffer) + { + // This was the last buffer: reset the sample count + mySamplesProcessed = 0; + EndBuffer = 0xFFFF; + } + else + { + ALint Size; + ALCheck(alGetBufferi(Buffer, AL_SIZE, &Size)); + mySamplesProcessed += Size / sizeof(Int16); + } // Fill it and push it back into the playing queue - if (FillAndPushBuffer(Buffer)) - RequestStop = true; + if (!RequestStop) + { + if (FillAndPushBuffer(Buffer)) + { + // User requested to stop: check if we must loop or really stop + if (myLoop && OnStart()) + { + // Looping: mark the current buffer as the last one + // (to know when to reset the sample count) + EndBuffer = Buffer; + } + else + { + // Not looping or restart failed: request stop + RequestStop = true; + } + } + } } // Leave some time for the other threads if the stream is still playing From 49c776927343966045d2855d1e4e3c712cdfc7e0 Mon Sep 17 00:00:00 2001 From: remi-k Date: Sun, 22 Feb 2009 14:57:18 +0000 Subject: [PATCH 07/22] worm.py sample rewritten; Minor fix in sf.SoundStream; Updated sf.Image. git-svn-id: https://sfml.svn.sourceforge.net/svnroot/sfml/trunk@1019 4e206d99-4929-0410-ac5d-dfc041789085 --- python/samples/worm.py | 451 ++++++++++++++++++++----------------- python/src/Image.cpp | 16 +- python/src/SoundStream.cpp | 1 + python/src/SoundStream.hpp | 6 +- 4 files changed, 258 insertions(+), 216 deletions(-) diff --git a/python/samples/worm.py b/python/samples/worm.py index 25a1c6c38..e43a9d921 100644 --- a/python/samples/worm.py +++ b/python/samples/worm.py @@ -1,240 +1,275 @@ #!/usr/bin/python -from PySFML import * +from PySFML import sf import math import random -import sys + +class Menu: + def __init__(self, screen_width, screen_height): + self.selection = 0 + text_color = sf.Color(220, 220, 20, 255) + self.spacing = screen_height/7 + + self.title = sf.String("PyWorm!") + self.title.SetColor(text_color) + self.title.SetPosition(screen_width/2-80., self.spacing) + + levels = ["Very Easy", "Easy", "Medium", "Hard"] + x_align = [-80., -50., -70., -50.] + self.strings = [] + for i in range(0, 4): + string = sf.String(levels[i]) + string.SetColor(text_color) + string.SetPosition(screen_width/2+x_align[i], (2+i)*self.spacing+20) + self.strings.append(string) + + self.rectangle = sf.Shape.Rectangle(0, 0, screen_width, 40, sf.Color(50, 50, 10)) + + def next_frame(self, win): + self.rectangle.SetY(self.spacing*(2 + self.selection)+20) + win.Draw(self.rectangle) + win.Draw(self.title) + win.Draw(self.strings) + + def key_up(self, pressed): + if pressed: + self.selection = (self.selection - 1) % 4 + def key_down(self, pressed): + if pressed: + self.selection = (self.selection + 1) % 4 -def Game(Difficulty): - PartsPerFrame = 1 + Difficulty # Number of drawn base parts each frame - PartsSpacing = 3 # Each worm's base part is separated by PartsSpacing pixels - TurnStep = 0.15 # Turn the worm's head of 0.15 rad +class Apple(sf.Sprite): + def __init__(self): + apple_img = sf.Image() # Apple's image + if not apple_img.LoadFromFile("./data/apple.png"): + print "Could not load data/apple.png" + sf.Sprite.__init__(self, apple_img) + self.SetCenter(apple_img.GetWidth()/2, apple_img.GetHeight()/2) + self.size = apple_img.GetWidth() - PartSize = 6.0 # worm's base part size for collision - PartRealSize = 18.0 # worm's real base part size for drawing - - # Load images - Rond = sf.Image() # Image containing the base part of the worm - if not Rond.LoadFromFile("./data/rond2.png"): - print "Could not load data/rond2.png" - return - WormPart = sf.Sprite(Rond) - WormPart.SetCenter(Rond.GetWidth()/2, Rond.GetHeight()/2) - AppleImg = sf.Image() # Apple's image - if not AppleImg.LoadFromFile("./data/apple.png"): - print "Could not load data/apple.png" - return - Apple = sf.Sprite(AppleImg, 0, 0, 1, 1, 0) # Corresponding sprite - Black = sf.Color(0,0,0,255) - UglyYellow = sf.Color(220, 220, 20, 255) - - Stop = False - - Event = sf.Event() # Our events manager - - Level = 0 - ShrinkValue = 20 - - Border = 30 - ArenaTop = 20 - ArenaBottom = 520 - - RequiredLength = 300 - - ExitLeft = 350 - ExitRight = 450 - ExitImg = sf.Image(ExitRight-ExitLeft, ArenaTop, Black) - Exit = sf.Sprite(ExitImg, ExitLeft, 0, 1, 1, 0) - - Score = 0 - - HeadX, HeadY = 0, 0 - - while not Stop: - - #Initialize a new game - - Level += 1 - - ArenaLeft = ShrinkValue*Level - ArenaRight = 800-ShrinkValue*Level - ArenaImg = sf.Image(ArenaRight-ArenaLeft, ArenaBottom-ArenaTop, Black) - Arena = sf.Sprite(ArenaImg, ArenaLeft, ArenaTop, 1, 1, 0) - - AppleX, AppleY = random.randrange(ArenaLeft+Border, ArenaRight-Border), random.randrange(ArenaTop+Border, ArenaBottom-Border) - Apple.SetX(AppleX - AppleImg.GetWidth()/2) # We move the apple to somewhere else, randomly - Apple.SetY(AppleY - AppleImg.GetHeight()/2) - - Crash = False - Running = True - - LevelStr = sf.String("Level: " + str(Level)) - LevelStr.SetPosition(60., 540.) - LevelStr.SetColor(UglyYellow) - - ScoreStr = sf.String("Score: 0") - ScoreStr.SetPosition(260., 540.) - ScoreStr.SetColor(UglyYellow) - - Length = 1 - TargetedLength = 30 - - Worm = [[ArenaLeft+50., ArenaTop+50.]] - - Angle = 0 - i = 0 - Dir = 0 - - while Running: # Game main loop - while App.GetEvent(Event): # Event Handler - if Event.Type == sf.Event.Closed: - App.Close() - return - if Event.Type == sf.Event.KeyPressed: - if Event.Key.Code == sf.Key.Escape: - Running = False - Stop = True - if Event.Key.Code == sf.Key.Left: - Dir = -1 - if Event.Key.Code == sf.Key.Right: - Dir = 1 - if Crash and Length<=1: - Running = False - if Event.Type == sf.Event.KeyReleased: - if Event.Key.Code == sf.Key.Left and Dir == -1: - Dir = 0 - if Event.Key.Code == sf.Key.Right and Dir == 1: - Dir = 0 - - App.Draw(Arena) + def random_move(self, arena): + self.SetPosition( \ + random.randrange(arena.arena_left+arena.border, arena.arena_right-arena.border), \ + random.randrange(arena.arena_top+arena.border, arena.arena_bottom-arena.border) \ + ) - if not Crash: # Create new parts and check collisions if the worm hasn't crashed yet - for i in range(0, PartsPerFrame): # We create PartsPerFrame Worm's parts - Angle += Dir*TurnStep - HeadX, HeadY = Worm[Length-1][0]+PartsSpacing*math.cos(Angle), Worm[Length-1][1]+PartsSpacing*math.sin(Angle) - if TargetedLength <= RequiredLength: - if math.sqrt ( (AppleX - HeadX)**2 + (AppleY - HeadY)**2 ) < 14 + PartSize/2: # The Worm ate the apple - Score += 1 - TargetedLength += 20 # The worm gets longer - if TargetedLength <= RequiredLength: - AppleX, AppleY = random.randrange(ArenaLeft+Border, ArenaRight-Border), random.randrange(ArenaTop+Border, ArenaBottom-Border) - Apple.SetX(AppleX - AppleImg.GetWidth()/2) # We move the apple to somewhere else, randomly - Apple.SetY(AppleY - AppleImg.GetHeight()/2) - App.Draw(Apple) +class Arena(dict): + shrink_value, border, arena_top = 20, 30, 20 + def __init__(self, window_width, window_height): + self.window_width = window_width + self.arena_bottom, self.exit_left, self.exit_right = window_height-80, window_width/2 - 50, window_width/2 + 50 + self['level_str'] = sf.String() + self['level_str'].SetColor(sf.Color.White) + self['level_str'].SetPosition(60., window_height-60) + self['score_str'] = sf.String() + self['score_str'].SetColor(sf.Color.White) + self['score_str'].SetPosition(260., window_height-60) + self.exit_rect = sf.Shape.Rectangle(self.exit_left, 0, self.exit_right, self.arena_top, sf.Color.Black) + self.reset() + self.update_arena_rect() - if HeadXArenaRight-PartSize/2 or HeadYArenaBottom-PartSize/2: # Crash into a wall - if Length > RequiredLength: - if HeadYExitRight-PartSize/2: - Crash = True - elif HeadY < 0: - Length = 0 - Running = False # Level completed! - else: - Crash = True - elif Running: - Crash = True - if not Crash: - Worm.append([HeadX, HeadY]) - Length += 1 + def update_arena_rect(self): + self['arena_rect'] = sf.Shape.Rectangle(self.arena_left, self.arena_top, self.arena_right, self.arena_bottom, sf.Color.Black) + def reset(self): + self.level, self.score, self.arena_left, self.arena_right = 1, 0, self.shrink_value, self.window_width-self.shrink_value + self.update_arena_rect() + self['level_str'].SetText("Level: 1") + self['score_str'].SetText("Score: 0") - if TargetedLength > RequiredLength: - App.Draw(Exit) + def update_score(self): + self.score += 1 + self['score_str'].SetText("Score: " + str(self.score)) - if Length >= TargetedLength: - Worm[0:TargetedLength] = Worm[Length-TargetedLength:Length] - for i in range(Length, TargetedLength): - del Worm[i] - Worm[TargetedLength:Length] = [] - Length = TargetedLength + def next_level(self): + self.level += 1 + self['level_str'].SetText("Level: " + str(self.level)) + self.arena_left += self.shrink_value + self.arena_right -= self.shrink_value + self.update_arena_rect() + self.score += 4 + self.update_score() - for i in range(0, Length): - WormPart.SetPosition(Worm[i][0], Worm[i][1]) - App.Draw(WormPart) # Draw the part on screen - if i < Length - PartSize/PartsSpacing - 1: - if math.sqrt( (HeadX-Worm[i][0])**2 + (HeadY-Worm[i][1])**2 ) < PartSize and Running: # Check for collision - Crash = True +class Part(sf.Sprite): + def __init__(self, rond, x, y): + sf.Sprite.__init__(self, rond) + self.SetCenter(rond.GetWidth()/2, rond.GetHeight()/2) + self.SetPosition(x, y) - if Crash and Length>0: - TargetedLength -= PartsPerFrame +class Worm(list): + parts_spacing, turn_step, part_size, start_x, start_y, required_length, grow_length = 3, 0.15, 6.0, 50., 50., 300, 20 + def __init__(self, difficulty): + self.parts_per_frame = 1 + difficulty + self.angle = 0 + self.direction = 0 # 0, 1 or -1 according to the key pressed + self.rond = sf.Image() + self.level_completed = False + if not self.rond.LoadFromFile("./data/rond2.png"): + print "Could not load data/rond2.png" - ScoreStr.SetText("Score: " + str(Score)) + def reset(self, arena): + self.targeted_length, self.angle, self.direction = 30, 0, 0 + self[:] = [Part(self.rond, arena.arena_left+self.start_x, arena.arena_top+self.start_y)] - App.Draw(ScoreStr) - App.Draw(LevelStr) - App.Display() # Refresh Screen - App.Clear(BGColor) - - - # End of the game - if Crash: - Level = 0 - Score = 0 + def left(self, pressed): + if pressed: + self.direction = -1 + elif self.direction == -1: + self.direction = 0 + def right(self, pressed): + if pressed: + self.direction = 1 + elif self.direction == 1: + self.direction = 0 + def restart(self, arena): + if self.targeted_length == 0 and not self.level_completed: + arena.reset() + self.reset(arena) + return True else: - Score += 5 # End level bonus + return False - del Worm - del Arena - del ArenaImg + def crash(self): + self.targeted_length = 0 -def Menu(): + def move(self, arena, apple): + head_x, head_y = -1, -1 + if self.is_running(): # Create new parts and check collisions if the worm hasn't crashed yet + for i in range(self.parts_per_frame): # We create PartsPerFrame Worm's parts + self.angle += self.direction*self.turn_step + head_x, head_y = self[-1].GetPosition() + head_x += self.parts_spacing*math.cos(self.angle) + head_y += self.parts_spacing*math.sin(self.angle) + if self.is_running() and self.targeted_length <= self.required_length: # let's check if the worm ate the apple + if math.hypot(apple.GetPosition()[0] - head_x, apple.GetPosition()[1] - head_y) < apple.size/2 + self.part_size/2: # Yes it did + arena.update_score() + self.targeted_length += self.grow_length # The worm gets longer + apple.random_move(arena) + if head_xarena.arena_right-self.part_size/2 or head_yarena.arena_bottom-self.part_size/2: # Crash into a wall + if len(self) > self.required_length: + if head_yarena.exit_right-self.part_size/2: # Crash into the exit walls + self.crash() + elif head_y < 0: + self.level_completed = True + self.targeted_length = 0 + else: + self.crash() + elif self.is_running(): + self.crash() + if self.is_running(): + self.append(Part(self.rond, head_x, head_y)) + if len(self) > self.targeted_length: + if len(self) - self.targeted_length >= self.parts_per_frame: + del self[0:self.parts_per_frame] + else: + del self[0:len(self) - self.targeted_length] - Selection = 0 + if (head_x, head_y) == (-1, -1) and len(self) > 0: + head_x, head_y = self[-1].GetPosition() - TextColor = sf.Color(220, 220, 20, 255) + if len(self) > self.part_size/self.parts_spacing + 1: + for i in range(len(self)): + if i < len(self) - self.part_size/self.parts_spacing - 1: + test_x, test_y = self[i].GetPosition() + if math.hypot(head_x-test_x, head_y-test_y) < self.part_size and self.is_running(): # Check for collision + self.crash() - Running = True - Event = sf.Event() + if len(self) == 0: + if self.level_completed: + self.level_completed = False + arena.next_level() + self.reset(arena) - Title = sf.String("PyWorm!") - Title.SetX(320.) - Title.SetY(50.) - Title.SetColor(TextColor) + def is_running(self): + return (self.targeted_length > 0) and not self.level_completed + def draw_exit(self): + return self.targeted_length > self.required_length or self.level_completed - Levels = ["Very Easy", "Easy", "Medium", "Hard"] - Xs = [320., 350., 330., 350.] - Strings = [0,0,0,0] - for i in range(0, 4): - Strings[i] = sf.String(Levels[i]) - Strings[i].SetColor(TextColor) - Strings[i].SetPosition(Xs[i], 200. + 80*i) +class Game: + def __init__(self, difficulty, window_width, window_height): + self.arena = Arena(window_width, window_height) + self.worm = Worm(difficulty) + self.worm.reset(self.arena) + self.apple = Apple() + self.apple.random_move(self.arena) + self.pause = False - RectangleImg = sf.Image(ScreenWidth, 40, sf.Color(50,50,10,255)) - Rectangle = sf.Sprite(RectangleImg, 0, 350, 1, 1, 0) + def enter(self, pressed): + if pressed: + if not self.worm.restart(self.arena): + self.pause = not self.pause - while App.IsOpened(): # Game main loop - while App.GetEvent(Event): # Event Handler - if Event.Type == sf.Event.Closed: - App.Close() - if Event.Type == sf.Event.KeyPressed: - if Event.Key.Code == sf.Key.Escape: - App.Close() - elif Event.Key.Code == sf.Key.Up: - Selection = (Selection - 1) % 4 - elif Event.Key.Code == sf.Key.Down: - Selection = (Selection + 1) % 4 - elif Event.Key.Code == sf.Key.Return: - Game(Selection) - - Rectangle.SetY(200 + Selection*80) - App.Draw(Rectangle) - App.Draw(Title) - for i in range(0,4): - App.Draw(Strings[i]) - App.Display() - App.Clear(BGColor) - + def next_frame(self, win): + win.Draw(self.arena.values()) + if not self.pause: + self.worm.move(self.arena, self.apple) + if self.worm.draw_exit(): + win.Draw(self.arena.exit_rect) + elif self.worm.is_running(): + win.Draw(self.apple) + win.Draw(self.worm) -# Initialize the window -ScreenWidth, ScreenHeight = 800, 600 -App = sf.RenderWindow(sf.VideoMode(ScreenWidth,ScreenHeight,32), "PyWorm", sf.Style.Close) # Creates the window -BGColor = sf.Color(100,100,0,255) -App.SetFramerateLimit(30) -Menu() +class Main: + # Entry Point + def __init__(self): + # Initialize the window + self.win = sf.RenderWindow(sf.VideoMode(800, 600,32), "PyWorm", sf.Style.Close) # Creates the window + self.win.EnableKeyRepeat(False) + background_color = sf.Color(100, 100, 0, 255) + self.win.SetFramerateLimit(30) + event = sf.Event() + self.keys = {} # keys to watch + self.menu_begin() + + # Boucle principale + while self.win.IsOpened(): + while self.win.GetEvent(event): # Event Handler + if event.Type == sf.Event.Closed: + self.win.Close() + elif event.Type == sf.Event.KeyPressed: + for key in self.keys: + if event.Key.Code == key: + self.keys[key](True) + elif event.Type == sf.Event.KeyReleased: + for key in self.keys: + if event.Key.Code == key: + self.keys[key](False) + self.win.Display() + self.win.Clear(background_color) + self.next_frame(self.win) + + # Menu + def menu_begin(self): + self.menu = Menu(self.win.GetWidth(), self.win.GetHeight()) + self.keys = {sf.Key.Escape:self.close_window, sf.Key.Up:self.menu.key_up, sf.Key.Down:self.menu.key_down, sf.Key.Return:self.menu_end} + self.next_frame = self.menu.next_frame + + def close_window(self, pressed): + if pressed: + self.win.Close() + + def menu_end(self, pressed): + if pressed: + selection = self.menu.selection + del self.menu + self.game_begin(selection) + + # Game + def game_begin(self, selection): + self.game = Game(selection, self.win.GetWidth(), self.win.GetHeight()) + self.keys = {sf.Key.Left:self.game.worm.left, sf.Key.Right:self.game.worm.right, sf.Key.Return:self.game.enter, sf.Key.Escape:self.game_end} + self.next_frame = self.game.next_frame + + def game_end(self, pressed): + if pressed: + del self.game + self.menu_begin() + +Main() diff --git a/python/src/Image.cpp b/python/src/Image.cpp index bd1f57d67..e3ac4d8b7 100644 --- a/python/src/Image.cpp +++ b/python/src/Image.cpp @@ -293,7 +293,8 @@ Copy pixels from another image onto this one. This function does a slow pixel co Source : Source image to copy\n\ DestX : X coordinate of the destination position\n\ DestY : Y coordinate of the destination position\n\ - SourceRect : Sub-rectangle of the source image to copy (empty by default - entire image)"}, + SourceRect : Sub-rectangle of the source image to copy (empty by default - entire image)\n\ + ApplyAlpha : Should the copy take in account the source transparency? (false by default)"}, {"Create", (PyCFunction)PySfImage_Create, METH_VARARGS, "Create(Width=0, Height=0, Color=sf.Color.Black)\n\ Create an empty image.\n\ Width : Image width\n\ @@ -396,17 +397,22 @@ PySfImage_Copy(PySfImage* self, PyObject *args) { PySfIntRect *SourceRect = NULL; PySfImage *Source = NULL; - unsigned int DestX, DestY; - if (! PyArg_ParseTuple(args, "O!II|O!", &PySfImageType, &Source, &DestX, &DestY, &PySfIntRectType, &SourceRect)) + unsigned int DestX, DestY; + PyObject *PyApplyAlpha; + bool ApplyAlpha = false; + if (! PyArg_ParseTuple(args, "O!II|O!O", &PySfImageType, &Source, &DestX, &DestY, &PySfIntRectType, &SourceRect, &PyApplyAlpha)) return NULL; + if (PyObject_IsTrue(PyApplyAlpha)) + ApplyAlpha = true; + if (SourceRect) { PySfIntRectUpdateObj(SourceRect); - self->obj->Copy(*(Source->obj), DestX, DestY, *(SourceRect->obj)); + self->obj->Copy(*(Source->obj), DestX, DestY, *(SourceRect->obj), ApplyAlpha); } else - self->obj->Copy(*(Source->obj), DestX, DestY); + self->obj->Copy(*(Source->obj), DestX, DestY, sf::IntRect(0, 0, 0, 0), ApplyAlpha); Py_RETURN_NONE; } diff --git a/python/src/SoundStream.cpp b/python/src/SoundStream.cpp index 112fea03b..a52b81fc1 100644 --- a/python/src/SoundStream.cpp +++ b/python/src/SoundStream.cpp @@ -38,6 +38,7 @@ bool CustomSoundStream::OnGetData(Chunk& Data) if (PyObject_HasAttrString(SoundStream, "OnGetData")) { PyObject *PyData=NULL; + Data.NbSamples = 0; if ((PyData = PyObject_CallFunction(PyObject_GetAttrString(SoundStream, "OnGetData"), NULL))) { if (PyArg_Parse(PyData, "s#", &(Data.Samples), &(Data.NbSamples))) diff --git a/python/src/SoundStream.hpp b/python/src/SoundStream.hpp index 72ddd355a..8c7b26f4c 100644 --- a/python/src/SoundStream.hpp +++ b/python/src/SoundStream.hpp @@ -25,12 +25,12 @@ #ifndef __PYSOUNDSTREAM_HPP #define __PYSOUNDSTREAM_HPP -#include -#include - #include #include +#include +#include + class CustomSoundStream : public sf::SoundStream { public : From 60ebaa84d1f773c6ffbc0ee10ac045d1fe39f12c Mon Sep 17 00:00:00 2001 From: remi-k Date: Mon, 23 Feb 2009 19:01:41 +0000 Subject: [PATCH 08/22] * Implemented sf.RenderTarget; * Made sf.RenderWindow inherit from sf.RenderTarget and sf.Window git-svn-id: https://sfml.svn.sourceforge.net/svnroot/sfml/trunk@1020 4e206d99-4929-0410-ac5d-dfc041789085 --- python/setup.py | 4 +- python/src/RenderTarget.cpp | 190 ++++++++++++++++++++++++++++++++++++ python/src/RenderTarget.hpp | 41 ++++++++ python/src/RenderWindow.cpp | 83 ++-------------- python/src/main.cpp | 3 + 5 files changed, 244 insertions(+), 77 deletions(-) create mode 100644 python/src/RenderTarget.cpp create mode 100644 python/src/RenderTarget.hpp diff --git a/python/setup.py b/python/setup.py index bb05523f3..db8cb7cb0 100644 --- a/python/setup.py +++ b/python/setup.py @@ -12,8 +12,8 @@ setup(name='PySFML', license='zlib/png', ext_modules=[ Extension('PySFML.sf', \ ['src/Clock.cpp', 'src/Color.cpp', 'src/Drawable.cpp', \ - 'src/Event.cpp', 'src/Image.cpp', 'src/Input.cpp', 'src/Key.cpp', 'src/main.cpp', \ - 'src/Music.cpp', 'src/PostFX.cpp', 'src/Rect.cpp', 'src/RenderWindow.cpp', 'src/Sleep.cpp', \ + 'src/Event.cpp', 'src/Image.cpp', 'src/Input.cpp', 'src/Key.cpp', 'src/main.cpp', 'src/Music.cpp', \ + 'src/PostFX.cpp', 'src/Rect.cpp', 'src/RenderTarget.cpp', 'src/RenderWindow.cpp', 'src/Sleep.cpp', \ 'src/Sprite.cpp', 'src/String.cpp', 'src/VideoMode.cpp', 'src/View.cpp', 'src/Window.cpp', \ 'src/Joy.cpp', 'src/Mouse.cpp', 'src/WindowStyle.cpp', 'src/Blend.cpp', 'src/Sound.cpp', \ 'src/SoundBuffer.cpp', 'src/Listener.cpp', 'src/SoundRecorder.cpp', 'src/SoundBufferRecorder.cpp', \ diff --git a/python/src/RenderTarget.cpp b/python/src/RenderTarget.cpp new file mode 100644 index 000000000..8762cdaa9 --- /dev/null +++ b/python/src/RenderTarget.cpp @@ -0,0 +1,190 @@ +//////////////////////////////////////////////////////////// +// +// PySFML - Python binding for SFML (Simple and Fast Multimedia Library) +// Copyright (C) 2007, 2008 Rémi Koenig (remi.k2620@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. +// +//////////////////////////////////////////////////////////// + +#include "RenderTarget.hpp" +#include "Color.hpp" +#include "View.hpp" + +extern PyTypeObject PySfColorType; +extern PyTypeObject PySfViewType; + +static PyMemberDef PySfRenderTarget_members[] = { + {NULL} /* Sentinel */ +}; + + +static void +PySfRenderTarget_dealloc(PySfRenderTarget *self) +{ + delete self->obj; + self->ob_type->tp_free((PyObject*)self); +} + +static PyObject * +PySfRenderTarget_new(PyTypeObject *type, PyObject *args, PyObject *kwds) +{ + PySfRenderTarget *self; + + self = (PySfRenderTarget *)type->tp_alloc(type, 0); + + if (self != NULL) + { + } + + return (PyObject *)self; +} + +static PyObject * +PySfRenderTarget_Clear(PySfRenderTarget *self, PyObject *args) +{ + PySfColor *Color; + int size = PyTuple_Size(args); + if (size == 1) + { + if (! PyArg_ParseTuple(args, "O!", &PySfColorType, &Color)) + { + PyErr_SetString(PyExc_TypeError, "Argument is not a sf.Color"); + return NULL; + } + PySfColorUpdate(Color); + self->obj->Clear(*(Color->obj)); + } + else if (size == 0) + { + self->obj->Clear(sf::Color::Black); + } + else + { + PyErr_SetString(PyExc_TypeError, "sf.RenderTarget.Clear takes one or zero argument"); + return NULL; + } + Py_RETURN_NONE; +} + + +static PyObject * +PySfRenderTarget_GetView(PySfRenderTarget *self) +{ + PySfView *View; + + View = GetNewPySfView(); + View->obj = new sf::View(self->obj->GetView()); + + return (PyObject *)View; +} + +static PyObject * +PySfRenderTarget_PreserveOpenGLStates(PySfRenderTarget *self, PyObject *args) +{ + bool Optimize = false; + if (PyObject_IsTrue(args)) + Optimize = true; + self->obj->PreserveOpenGLStates(Optimize); + Py_RETURN_NONE; +} + +static PyObject * +PySfRenderTarget_SetView(PySfRenderTarget* self, PyObject *args) +{ + PySfView *View = (PySfView *)args; + if (! PyObject_TypeCheck(View, &PySfViewType)) + { + PyErr_SetString(PyExc_TypeError, "Argument is not a sf.View"); + return NULL; + } + self->obj->SetView( *(View->obj)); + Py_RETURN_NONE; +} + +static PyObject * +PySfRenderTarget_GetDefaultView(PySfRenderTarget *self) +{ + PySfView *View; + + View = GetNewPySfView(); + View->Owner = false; + View->obj = &(self->obj->GetDefaultView()); + + return (PyObject *)View; +} + +static PyMethodDef PySfRenderTarget_methods[] = { + {"Clear", (PyCFunction)PySfRenderTarget_Clear, METH_VARARGS, "Clear(FillColor)\n\ +Clear the entire target with a single color.\n\ + FillColor : Color to use to clear the render target."}, + {"GetDefaultView", (PyCFunction)PySfRenderTarget_GetDefaultView, METH_NOARGS, "GetDefaultView()\n\ +Get the default view of the window for read / write (returns a sf.View instance)."}, + {"GetView", (PyCFunction)PySfRenderTarget_GetView, METH_NOARGS, "GetView()\n\ +Get the current view rectangle (returns a sf.View instance)."}, + {"PreserveOpenGLStates", (PyCFunction)PySfRenderTarget_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"}, + {"SetView", (PyCFunction)PySfRenderTarget_SetView, METH_O, "SetView(View)\n\ +Change the current active view. View must be a sf.View instance."}, + {NULL} /* Sentinel */ +}; + +PyTypeObject PySfRenderTargetType = { + PyObject_HEAD_INIT(NULL) + 0, /*ob_size*/ + "RenderTarget", /*tp_name*/ + sizeof(PySfRenderTarget), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + (destructor)PySfRenderTarget_dealloc, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + 0, /*tp_compare*/ + 0, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash */ + 0, /*tp_call*/ + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/ + "Base class for all render targets (window, image, ...).", /* tp_doc */ + 0, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + PySfRenderTarget_methods, /* tp_methods */ + PySfRenderTarget_members, /* 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 */ +}; + + diff --git a/python/src/RenderTarget.hpp b/python/src/RenderTarget.hpp new file mode 100644 index 000000000..25a4ef40c --- /dev/null +++ b/python/src/RenderTarget.hpp @@ -0,0 +1,41 @@ +//////////////////////////////////////////////////////////// +// +// PySFML - Python binding for SFML (Simple and Fast Multimedia Library) +// Copyright (C) 2007, 2008 Rémi Koenig (remi.k2620@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. +// +//////////////////////////////////////////////////////////// + +#ifndef __PYRENDERTARGET_H +#define __PYRENDERTARGET_H + +#include + +#include +#include + +#include + +typedef struct { + PyObject_HEAD + sf::RenderTarget *obj; +} PySfRenderTarget; + +#endif + diff --git a/python/src/RenderWindow.cpp b/python/src/RenderWindow.cpp index a251bd822..71f293e3f 100644 --- a/python/src/RenderWindow.cpp +++ b/python/src/RenderWindow.cpp @@ -42,7 +42,9 @@ extern PyTypeObject PySfColorType; extern PyTypeObject PySfWindowType; extern PyTypeObject PySfWindowSettingsType; extern PyTypeObject PySfVideoModeType; -extern PyTypeObject PySfDrawableType; +extern PyTypeObject PySfDrawableType; + +extern PyTypeObject PySfRenderTargetType; static PyMemberDef PySfRenderWindow_members[] = { {NULL} /* Sentinel */ @@ -157,72 +159,9 @@ PySfRenderWindow_Draw(PySfRenderWindow *self, PyObject *args) } } Py_RETURN_NONE; -} - -static PyObject * -PySfRenderWindow_GetDefaultView(PySfRenderWindow *self) -{ - PySfView *View; - - View = GetNewPySfView(); - View->Owner = false; - View->obj = &(self->obj->GetDefaultView()); - - return (PyObject *)View; -} - -static PyObject * -PySfRenderWindow_GetView(PySfRenderWindow *self) -{ - PySfView *View; - - View = GetNewPySfView(); - View->obj = new sf::View(self->obj->GetView()); - - return (PyObject *)View; -} - -static PyObject * -PySfRenderWindow_PreserveOpenGLStates(PySfRenderWindow *self, PyObject *args) -{ - bool Optimize = false; - if (PyObject_IsTrue(args)) - Optimize = true; - self->obj->PreserveOpenGLStates(Optimize); - Py_RETURN_NONE; -} - -static PyObject * -PySfRenderWindow_SetView(PySfRenderWindow* self, PyObject *args) -{ - PySfView *View = (PySfView *)args; - if (! PyObject_TypeCheck(View, &PySfViewType)) - { - PyErr_SetString(PyExc_TypeError, "Argument is not a sfView"); - return NULL; - } - self->obj->SetView( *(View->obj)); - Py_RETURN_NONE; -} - -static PyObject * -PySfRenderWindow_Clear(PySfRenderWindow* self, PyObject *args) -{ - PySfColor *Color = (PySfColor *)args; - if (! PyObject_TypeCheck(Color, &PySfColorType)) - { - PyErr_SetString(PyExc_TypeError, "Argument is not a sfColor"); - return NULL; - } - PySfColorUpdate(Color); - self->obj->Clear(*(Color->obj)); - Py_RETURN_NONE; } static PyMethodDef PySfRenderWindow_methods[] = { - {"Clear", (PyCFunction)PySfRenderWindow_Clear, METH_O, "Clear(FillColor)\n\ -Clear the entire target with a single color.\n\ - FillColor : Color to use to clear the render target."}, {"Capture", (PyCFunction)PySfRenderWindow_Capture, METH_NOARGS, "Capture()\n\ 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\ @@ -232,15 +171,6 @@ Convert a point in window coordinates into view coordinates. Returns a tuple of TargetView : Target view to convert the point to (NULL by default -- uses the current view)."}, {"Draw", (PyCFunction)PySfRenderWindow_Draw, METH_O, "Draw(Drawable)\n\ Draw something on the window. The argument can be a drawable or any object supporting the iterator protocol and containing drawables (for example a tuple of drawables)."}, - {"GetDefaultView", (PyCFunction)PySfRenderWindow_GetDefaultView, METH_NOARGS, "GetDefaultView()\n\ -Get the default view of the window for read / write (returns a sf.View instance)."}, - {"GetView", (PyCFunction)PySfRenderWindow_GetView, METH_NOARGS, "GetView()\n\ -Get the current view rectangle (returns a sf.View instance)."}, - {"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"}, - {"SetView", (PyCFunction)PySfRenderWindow_SetView, METH_O, "SetView(View)\n\ -Change the current active view. View must be a sf.View instance."}, {NULL} /* Sentinel */ }; @@ -276,14 +206,17 @@ PyTypeObject PySfRenderWindowType = { PySfRenderWindow_methods, /* tp_methods */ PySfRenderWindow_members, /* tp_members */ 0, /* tp_getset */ - &PySfWindowType, /* tp_base */ + 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ (initproc)PySfRenderWindow_init, /* tp_init */ 0, /* tp_alloc */ - PySfRenderWindow_new, /* tp_new */ + PySfRenderWindow_new, /* tp_new */ + 0, /* tp_free */ + 0, /* tp_is_gc */ + Py_BuildValue("(OO)", &PySfWindowType, &PySfRenderTargetType) /* tp_bases */ }; diff --git a/python/src/main.cpp b/python/src/main.cpp index 86f3fae89..7df0428b1 100644 --- a/python/src/main.cpp +++ b/python/src/main.cpp @@ -55,6 +55,7 @@ extern PyTypeObject PySfWindowType; extern PyTypeObject PySfWindowSettingsType; extern PyTypeObject PySfStyleType; extern PyTypeObject PySfRenderWindowType; +extern PyTypeObject PySfRenderTargetType; extern PyTypeObject PySfViewType; extern PyTypeObject PySfInputType; @@ -106,6 +107,8 @@ initsf(void) return; if (PyType_Ready(&PySfStyleType) < 0) return; + if (PyType_Ready(&PySfRenderTargetType) < 0) + return; if (PyType_Ready(&PySfRenderWindowType) < 0) return; if (PyType_Ready(&PySfVideoModeType) < 0) From 79bf5c62522937b61e2cf07b79e3759debf279fb Mon Sep 17 00:00:00 2001 From: remi-k Date: Wed, 25 Feb 2009 10:40:38 +0000 Subject: [PATCH 09/22] * Began supporting python3 * Code clean-up git-svn-id: https://sfml.svn.sourceforge.net/svnroot/sfml/trunk@1021 4e206d99-4929-0410-ac5d-dfc041789085 --- python/samples/opengl.py | 10 +- python/src/Clock.cpp | 21 +-- python/src/Clock.hpp | 8 +- python/src/Color.cpp | 8 +- python/src/Color.hpp | 5 +- python/src/Drawable.cpp | 23 ++-- python/src/Drawable.hpp | 7 +- python/src/Event.cpp | 134 +++++++++---------- python/src/Event.hpp | 7 +- python/src/Image.cpp | 118 +++++++++-------- python/src/Image.hpp | 9 +- python/src/Input.cpp | 49 ++----- python/src/Input.hpp | 7 +- python/src/Key.cpp | 252 +++++++++++++++--------------------- python/src/Key.hpp | 8 ++ python/src/Music.cpp | 58 +++++---- python/src/Music.hpp | 6 +- python/src/PostFX.cpp | 90 +++++++------ python/src/PostFX.hpp | 7 +- python/src/Rect.cpp | 67 ++++------ python/src/Rect.hpp | 7 +- python/src/RenderTarget.cpp | 35 ++--- python/src/RenderTarget.hpp | 5 +- python/src/RenderWindow.cpp | 42 +++--- python/src/RenderWindow.hpp | 6 +- python/src/Sleep.hpp | 6 +- python/src/Sprite.cpp | 45 +++---- python/src/Sprite.hpp | 9 +- python/src/Window.cpp | 3 +- python/src/compat.hpp | 42 ++++++ python/src/main.cpp | 122 ++++++++++------- 31 files changed, 572 insertions(+), 644 deletions(-) create mode 100644 python/src/compat.hpp diff --git a/python/samples/opengl.py b/python/samples/opengl.py index 6442b8399..e35df9e5f 100644 --- a/python/samples/opengl.py +++ b/python/samples/opengl.py @@ -30,11 +30,7 @@ def main(): Texture = glGenTextures(1) # instead of glGenTextures(1, &Texture); glBindTexture(GL_TEXTURE_2D, Texture) # It is almost the same line there, except in C++, the last argument was Image.GetPixelsPtr(). - # With GetPixelsPtr, PySFML returns a PyCObject: "an opaque value, useful for C extension - # modules who need to pass an opaque value (as a void* pointer) through Python code to other C code". - # However, gluBuild2DMipmaps' python version takes a string as last argument (which is normally a - # pointer to pixels data). This is why Image.GetPixelsPtr is replaced by Image.GetPixelsString. - # This function (that doesn't exist in C++ SFML) returns a string that contains the pixels data. + # In python, GetPixels simply returns a string. gluBuild2DMipmaps(GL_TEXTURE_2D, GL_RGBA, Image.GetWidth(), Image.GetHeight(), GL_RGBA, GL_UNSIGNED_BYTE, Image.GetPixels()) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR) @@ -73,7 +69,7 @@ def main(): # Adjust the viewport when the window is resized if Event.Type == sf.Event.Resized: - glViewport(0, 0, Event.Size.Width, Event.Size.Height); + glViewport(0, 0, Event.Size.Width, Event.Size.Height) # Draw background App.Draw(Background) @@ -81,7 +77,7 @@ def main(): # Clear depth buffer glClear(GL_DEPTH_BUFFER_BIT) - # Apply some transf.ormations + # Apply some transformations glMatrixMode(GL_MODELVIEW) glLoadIdentity() glTranslatef(0, 0, -200) diff --git a/python/src/Clock.cpp b/python/src/Clock.cpp index 7c28c3141..714a6603a 100644 --- a/python/src/Clock.cpp +++ b/python/src/Clock.cpp @@ -24,24 +24,14 @@ #include "Clock.hpp" - -typedef struct { - PyObject_HEAD - sf::Clock *obj; -} PySfClock; - - - -static PyMemberDef PySfClock_members[] = { - {NULL} /* Sentinel */ -}; +#include "compat.hpp" static void PySfClock_dealloc(PySfClock *self) { delete self->obj; - self->ob_type->tp_free((PyObject*)self); + free_object(self); } static PyObject * @@ -86,8 +76,7 @@ static PyMethodDef PySfClock_methods[] = { }; PyTypeObject PySfClockType = { - PyObject_HEAD_INIT(NULL) - 0, /*ob_size*/ + head_init "Clock", /*tp_name*/ sizeof(PySfClock), /*tp_basicsize*/ 0, /*tp_itemsize*/ @@ -95,7 +84,7 @@ PyTypeObject PySfClockType = { 0, /*tp_print*/ 0, /*tp_getattr*/ 0, /*tp_setattr*/ - 0, /*tp_compare*/ + 0, /*tp_compare (tp_reserved in py3k)*/ 0, /*tp_repr*/ 0, /*tp_as_number*/ 0, /*tp_as_sequence*/ @@ -115,7 +104,7 @@ PyTypeObject PySfClockType = { 0, /* tp_iter */ 0, /* tp_iternext */ PySfClock_methods, /* tp_methods */ - PySfClock_members, /* tp_members */ + 0, /* tp_members */ 0, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ diff --git a/python/src/Clock.hpp b/python/src/Clock.hpp index 4b2c9d8ca..d0a32f65c 100644 --- a/python/src/Clock.hpp +++ b/python/src/Clock.hpp @@ -25,11 +25,13 @@ #ifndef __PYCLOCK_HPP #define __PYCLOCK_HPP +#include #include -#include -#include -#include +typedef struct { + PyObject_HEAD + sf::Clock *obj; +} PySfClock; #endif diff --git a/python/src/Color.cpp b/python/src/Color.cpp index 1b3043299..be8f16754 100644 --- a/python/src/Color.cpp +++ b/python/src/Color.cpp @@ -24,6 +24,9 @@ #include "Color.hpp" +#include "offsetof.hpp" +#include "compat.hpp" + static PyMemberDef PySfColor_members[] = { {(char *)"r", T_UBYTE, offsetof(PySfColor, r), 0, (char *)"Red component."}, {(char *)"g", T_UBYTE, offsetof(PySfColor, g), 0, (char *)"Green component."}, @@ -38,7 +41,7 @@ static void PySfColor_dealloc(PySfColor *self) { delete self->obj; - self->ob_type->tp_free((PyObject*)self); + free_object(self); } void @@ -101,8 +104,7 @@ static PyMethodDef PySfColor_methods[] = { PyTypeObject PySfColorType = { - PyObject_HEAD_INIT(NULL) - 0, /*ob_size*/ + head_init "Color", /*tp_name*/ sizeof(PySfColor), /*tp_basicsize*/ 0, /*tp_itemsize*/ diff --git a/python/src/Color.hpp b/python/src/Color.hpp index 19379e3bd..d86ed7f42 100644 --- a/python/src/Color.hpp +++ b/python/src/Color.hpp @@ -25,13 +25,10 @@ #ifndef __PYCOLOR_HPP #define __PYCOLOR_HPP -#include -#include - #include #include -#include "offsetof.hpp" +#include typedef struct { diff --git a/python/src/Drawable.cpp b/python/src/Drawable.cpp index 008e469a9..d0fb70042 100644 --- a/python/src/Drawable.cpp +++ b/python/src/Drawable.cpp @@ -23,6 +23,13 @@ //////////////////////////////////////////////////////////// #include "Drawable.hpp" +#include "Color.hpp" + +#include "compat.hpp" + + +extern PyTypeObject PySfColorType; + void CustomDrawable::Render (sf::RenderTarget& Target) const { @@ -30,20 +37,11 @@ void CustomDrawable::Render (sf::RenderTarget& Target) const PyObject_CallFunction(RenderFunction, (char *)"O", RenderWindow); } - -extern PyTypeObject PySfColorType; - -static PyMemberDef PySfDrawable_members[] = { - {NULL} /* Sentinel */ -}; - - - static void PySfDrawable_dealloc(PySfDrawable *self) { delete self->obj; - self->ob_type->tp_free((PyObject*)self); + free_object(self); } static PyObject * @@ -261,8 +259,7 @@ Transform a point from local coordinates into global coordinates (ie it applies }; PyTypeObject PySfDrawableType = { - PyObject_HEAD_INIT(NULL) - 0, /*ob_size*/ + head_init "Drawable", /*tp_name*/ sizeof(PySfDrawable), /*tp_basicsize*/ 0, /*tp_itemsize*/ @@ -290,7 +287,7 @@ PyTypeObject PySfDrawableType = { 0, /* tp_iter */ 0, /* tp_iternext */ PySfDrawable_methods, /* tp_methods */ - PySfDrawable_members, /* tp_members */ + 0, /* tp_members */ 0, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ diff --git a/python/src/Drawable.hpp b/python/src/Drawable.hpp index 2553b640a..6e227271a 100644 --- a/python/src/Drawable.hpp +++ b/python/src/Drawable.hpp @@ -25,13 +25,10 @@ #ifndef __PYDRAWABLE_H #define __PYDRAWABLE_H -#include -#include - #include -#include -#include "Color.hpp" +#include + #include "RenderWindow.hpp" diff --git a/python/src/Event.cpp b/python/src/Event.cpp index 954916901..e6a899c00 100644 --- a/python/src/Event.cpp +++ b/python/src/Event.cpp @@ -24,13 +24,16 @@ #include "Event.hpp" +#include + +#include "compat.hpp" //////////////////////////////// // Text Events Parameters //////////////////////////////// PyMemberDef PySfEventText_members[] = { - {(char *)"Unicode", T_USHORT, offsetof(PySfEventText, Unicode), RO, (char *)""}, + {(char *)"Unicode", T_USHORT, offsetof(PySfEventText, Unicode), READONLY, (char *)""}, {NULL} /* Sentinel */ }; @@ -57,12 +60,11 @@ PySfEventText_init(PySfEventText *self, PyObject *args, PyObject *kwds) void PySfEventText_dealloc(PySfEventText* self) { - self->ob_type->tp_free((PyObject*)self); + free_object(self); } PyTypeObject PySfEventTextType = { - PyObject_HEAD_INIT(NULL) - 0, /*ob_size*/ + head_init "Event.Text", /*tp_name*/ sizeof(PySfEventText), /*tp_basicsize*/ 0, /*tp_itemsize*/ @@ -136,20 +138,19 @@ PySfEventKey_init(PySfEventKey *self, PyObject *args, PyObject *kwds) void PySfEventKey_dealloc(PySfEventKey* self) { - self->ob_type->tp_free((PyObject*)self); + free_object(self); } PyMemberDef PySfEventKey_members[] = { - {(char *)"Alt", T_OBJECT, offsetof(PySfEventKey, Alt), RO, (char *)""}, - {(char *)"Control", T_OBJECT, offsetof(PySfEventKey, Control), RO, (char *)""}, - {(char *)"Shift", T_OBJECT, offsetof(PySfEventKey, Shift), RO, (char *)""}, - {(char *)"Code", T_UINT, offsetof(PySfEventKey, Code), RO, (char *)""}, + {(char *)"Alt", T_OBJECT, offsetof(PySfEventKey, Alt), READONLY, (char *)""}, + {(char *)"Control", T_OBJECT, offsetof(PySfEventKey, Control), READONLY, (char *)""}, + {(char *)"Shift", T_OBJECT, offsetof(PySfEventKey, Shift), READONLY, (char *)""}, + {(char *)"Code", T_UINT, offsetof(PySfEventKey, Code), READONLY, (char *)""}, {NULL} /* Sentinel */ }; PyTypeObject PySfEventKeyType = { - PyObject_HEAD_INIT(NULL) - 0, /*ob_size*/ + head_init "Event.Key", /*tp_name*/ sizeof(PySfEventKey), /*tp_basicsize*/ 0, /*tp_itemsize*/ @@ -218,19 +219,18 @@ PySfEventMouseMove_init(PySfEventMouseMove *self, PyObject *args, PyObject *kwds void PySfEventMouseMove_dealloc(PySfEventMouseMove *self) { - self->ob_type->tp_free((PyObject*)self); + free_object(self); } PyMemberDef PySfEventMouseMove_members[] = { - {(char *)"X", T_INT, offsetof(PySfEventMouseMove, X), RO, (char *)""}, - {(char *)"Y", T_INT, offsetof(PySfEventMouseMove, Y), RO, (char *)""}, + {(char *)"X", T_INT, offsetof(PySfEventMouseMove, X), READONLY, (char *)""}, + {(char *)"Y", T_INT, offsetof(PySfEventMouseMove, Y), READONLY, (char *)""}, {NULL} /* Sentinel */ }; PyTypeObject PySfEventMouseMoveType = { - PyObject_HEAD_INIT(NULL) - 0, /*ob_size*/ + head_init "Event.MouseMove", /*tp_name*/ sizeof(PySfEventMouseMove), /*tp_basicsize*/ 0, /*tp_itemsize*/ @@ -300,20 +300,19 @@ PySfEventMouseButton_init(PySfEventMouseButton *self, PyObject *args, PyObject * void PySfEventMouseButton_dealloc(PySfEventMouseButton* self) { - self->ob_type->tp_free((PyObject*)self); + free_object(self); } PyMemberDef PySfEventMouseButton_members[] = { - {(char *)"Button", T_UINT, offsetof(PySfEventMouseButton, Button), RO, (char *)""}, - {(char *)"X", T_INT, offsetof(PySfEventMouseButton, X), RO, (char *)""}, - {(char *)"Y", T_INT, offsetof(PySfEventMouseButton, Y), RO, (char *)""}, + {(char *)"Button", T_UINT, offsetof(PySfEventMouseButton, Button), READONLY, (char *)""}, + {(char *)"X", T_INT, offsetof(PySfEventMouseButton, X), READONLY, (char *)""}, + {(char *)"Y", T_INT, offsetof(PySfEventMouseButton, Y), READONLY, (char *)""}, {NULL} /* Sentinel */ }; PyTypeObject PySfEventMouseButtonType = { - PyObject_HEAD_INIT(NULL) - 0, /*ob_size*/ + head_init "Event.MouseButton", /*tp_name*/ sizeof(PySfEventMouseButton), /*tp_basicsize*/ 0, /*tp_itemsize*/ @@ -381,17 +380,16 @@ PySfEventMouseWheel_init(PySfEventMouseWheel *self, PyObject *args, PyObject *kw void PySfEventMouseWheel_dealloc(PySfEventMouseWheel* self) { - self->ob_type->tp_free((PyObject*)self); + free_object(self); } PyMemberDef PySfEventMouseWheel_members[] = { - {(char *)"Delta", T_INT, offsetof(PySfEventMouseWheel,Delta), RO, (char *)""}, + {(char *)"Delta", T_INT, offsetof(PySfEventMouseWheel,Delta), READONLY, (char *)""}, {NULL} /* Sentinel */ }; PyTypeObject PySfEventMouseWheelType = { - PyObject_HEAD_INIT(NULL) - 0, /*ob_size*/ + head_init "Event.MouseWheel", /*tp_name*/ sizeof(PySfEventMouseWheel), /*tp_basicsize*/ 0, /*tp_itemsize*/ @@ -461,20 +459,19 @@ PySfEventJoyMove_init(PySfEventJoyMove *self, PyObject *args, PyObject *kwds) void PySfEventJoyMove_dealloc(PySfEventJoyMove* self) { - self->ob_type->tp_free((PyObject*)self); + free_object(self); } PyMemberDef PySfEventJoyMove_members[] = { - {(char *)"JoystickId", T_UINT, offsetof(PySfEventJoyMove,JoystickId), RO, (char *)""}, - {(char *)"Axis", T_UINT, offsetof(PySfEventJoyMove,Axis), RO, (char *)""}, - {(char *)"Position", T_FLOAT, offsetof(PySfEventJoyMove,Position), RO, (char *)""}, + {(char *)"JoystickId", T_UINT, offsetof(PySfEventJoyMove,JoystickId), READONLY, (char *)""}, + {(char *)"Axis", T_UINT, offsetof(PySfEventJoyMove,Axis), READONLY, (char *)""}, + {(char *)"Position", T_FLOAT, offsetof(PySfEventJoyMove,Position), READONLY, (char *)""}, {NULL} /* Sentinel */ }; PyTypeObject PySfEventJoyMoveType = { - PyObject_HEAD_INIT(NULL) - 0, /*ob_size*/ + head_init "Event.JoyMove", /*tp_name*/ sizeof(PySfEventJoyMove), /*tp_basicsize*/ 0, /*tp_itemsize*/ @@ -543,19 +540,18 @@ PySfEventJoyButton_init(PySfEventJoyButton *self, PyObject *args, PyObject *kwds void PySfEventJoyButton_dealloc(PySfEventJoyButton* self) { - self->ob_type->tp_free((PyObject*)self); + free_object(self); } PyMemberDef PySfEventJoyButton_members[] = { - {(char *)"JoystickId", T_UINT, offsetof(PySfEventJoyButton, JoystickId), RO, (char *)""}, - {(char *)"Button", T_UINT, offsetof(PySfEventJoyButton, Button), RO, (char *)""}, + {(char *)"JoystickId", T_UINT, offsetof(PySfEventJoyButton, JoystickId), READONLY, (char *)""}, + {(char *)"Button", T_UINT, offsetof(PySfEventJoyButton, Button), READONLY, (char *)""}, {NULL} /* Sentinel */ }; PyTypeObject PySfEventJoyButtonType = { - PyObject_HEAD_INIT(NULL) - 0, /*ob_size*/ + head_init "Event.JoyButton", /*tp_name*/ sizeof(PySfEventJoyButton), /*tp_basicsize*/ 0, /*tp_itemsize*/ @@ -624,18 +620,17 @@ PySfEventSize_init(PySfEventSize *self, PyObject *args, PyObject *kwds) void PySfEventSize_dealloc(PySfEventSize* self) { - self->ob_type->tp_free((PyObject*)self); + free_object(self); } PyMemberDef PySfEventSize_members[] = { - {(char *)"Width", T_UINT, offsetof(PySfEventSize, Width), RO, (char *)""}, - {(char *)"Height", T_UINT, offsetof(PySfEventSize, Height), RO, (char *)""}, + {(char *)"Width", T_UINT, offsetof(PySfEventSize, Width), READONLY, (char *)""}, + {(char *)"Height", T_UINT, offsetof(PySfEventSize, Height), READONLY, (char *)""}, {NULL} /* Sentinel */ }; PyTypeObject PySfEventSizeType = { - PyObject_HEAD_INIT(NULL) - 0, /*ob_size*/ + head_init "Event.Size", /*tp_name*/ sizeof(PySfEventSize), /*tp_basicsize*/ 0, /*tp_itemsize*/ @@ -725,19 +720,19 @@ PySfEvent_dealloc(PySfEvent* self) Py_DECREF(self->JoyButton); Py_DECREF(self->Size); delete self->obj; - self->ob_type->tp_free((PyObject*)self); + free_object(self); } static PyMemberDef PySfEvent_members[] = { - {(char *)"Text", T_OBJECT, offsetof(PySfEvent, Text), RO, (char *)"Text Events Parameters"}, - {(char *)"Key", T_OBJECT, offsetof(PySfEvent, Key), RO, (char *)"Keyboard Events Parameters"}, - {(char *)"MouseMove", T_OBJECT, offsetof(PySfEvent, MouseMove), RO, (char *)"MouseMove Events Parameters"}, - {(char *)"MouseButton", T_OBJECT, offsetof(PySfEvent, MouseButton), RO, (char *)"MouseButton Events Parameters"}, - {(char *)"MouseWheel", T_OBJECT, offsetof(PySfEvent, MouseWheel), RO, (char *)"MouseWheel Events Parameters"}, - {(char *)"JoyMove", T_OBJECT, offsetof(PySfEvent, JoyMove), RO, (char *)"JoyMove Events Parameters"}, - {(char *)"JoyButton", T_OBJECT, offsetof(PySfEvent, JoyButton), RO, (char *)"JoyButton Events Parameters"}, - {(char *)"Size", T_OBJECT, offsetof(PySfEvent, Size), RO, (char *)"Size Events Parameters"}, - {(char *)"Type", T_UINT, offsetof(PySfEvent, Type), RO, (char *)"Type Events Parameters"}, + {(char *)"Text", T_OBJECT, offsetof(PySfEvent, Text), READONLY, (char *)"Text Events Parameters"}, + {(char *)"Key", T_OBJECT, offsetof(PySfEvent, Key), READONLY, (char *)"Keyboard Events Parameters"}, + {(char *)"MouseMove", T_OBJECT, offsetof(PySfEvent, MouseMove), READONLY, (char *)"MouseMove Events Parameters"}, + {(char *)"MouseButton", T_OBJECT, offsetof(PySfEvent, MouseButton), READONLY, (char *)"MouseButton Events Parameters"}, + {(char *)"MouseWheel", T_OBJECT, offsetof(PySfEvent, MouseWheel), READONLY, (char *)"MouseWheel Events Parameters"}, + {(char *)"JoyMove", T_OBJECT, offsetof(PySfEvent, JoyMove), READONLY, (char *)"JoyMove Events Parameters"}, + {(char *)"JoyButton", T_OBJECT, offsetof(PySfEvent, JoyButton), READONLY, (char *)"JoyButton Events Parameters"}, + {(char *)"Size", T_OBJECT, offsetof(PySfEvent, Size), READONLY, (char *)"Size Events Parameters"}, + {(char *)"Type", T_UINT, offsetof(PySfEvent, Type), READONLY, (char *)"Type Events Parameters"}, {NULL} /* Sentinel */ }; @@ -746,8 +741,7 @@ static PyMethodDef PySfEvent_methods[] = { }; PyTypeObject PySfEventType = { - PyObject_HEAD_INIT(NULL) - 0, /*ob_size*/ + head_init "Event", /*tp_name*/ sizeof(PySfEvent), /*tp_basicsize*/ 0, /*tp_itemsize*/ @@ -792,52 +786,52 @@ void PySfEvent_InitConst() { PyObject *obj; - obj = PyInt_FromLong(sf::Event::KeyReleased); + obj = PyLong_FromLong(sf::Event::KeyReleased); PyDict_SetItemString(PySfEventType.tp_dict, "KeyReleased", obj); Py_DECREF(obj); - obj = PyInt_FromLong(sf::Event::LostFocus); + obj = PyLong_FromLong(sf::Event::LostFocus); PyDict_SetItemString(PySfEventType.tp_dict, "LostFocus", obj); Py_DECREF(obj); - obj = PyInt_FromLong(sf::Event::GainedFocus); + obj = PyLong_FromLong(sf::Event::GainedFocus); PyDict_SetItemString(PySfEventType.tp_dict, "GainedFocus", obj); Py_DECREF(obj); - obj = PyInt_FromLong(sf::Event::KeyPressed); + obj = PyLong_FromLong(sf::Event::KeyPressed); PyDict_SetItemString(PySfEventType.tp_dict, "KeyPressed", obj); Py_DECREF(obj); - obj = PyInt_FromLong(sf::Event::MouseWheelMoved); + obj = PyLong_FromLong(sf::Event::MouseWheelMoved); PyDict_SetItemString(PySfEventType.tp_dict, "MouseWheelMoved", obj); Py_DECREF(obj); - obj = PyInt_FromLong(sf::Event::TextEntered); + obj = PyLong_FromLong(sf::Event::TextEntered); PyDict_SetItemString(PySfEventType.tp_dict, "TextEntered", obj); Py_DECREF(obj); - obj = PyInt_FromLong(sf::Event::MouseMoved); + obj = PyLong_FromLong(sf::Event::MouseMoved); PyDict_SetItemString(PySfEventType.tp_dict, "MouseMoved", obj); Py_DECREF(obj); - obj = PyInt_FromLong(sf::Event::JoyButtonPressed); + obj = PyLong_FromLong(sf::Event::JoyButtonPressed); PyDict_SetItemString(PySfEventType.tp_dict, "JoyButtonPressed", obj); Py_DECREF(obj); - obj = PyInt_FromLong(sf::Event::MouseButtonReleased); + obj = PyLong_FromLong(sf::Event::MouseButtonReleased); PyDict_SetItemString(PySfEventType.tp_dict, "MouseButtonReleased", obj); Py_DECREF(obj); - obj = PyInt_FromLong(sf::Event::Closed); + obj = PyLong_FromLong(sf::Event::Closed); PyDict_SetItemString(PySfEventType.tp_dict, "Closed", obj); Py_DECREF(obj); - obj = PyInt_FromLong(sf::Event::MouseButtonPressed); + obj = PyLong_FromLong(sf::Event::MouseButtonPressed); PyDict_SetItemString(PySfEventType.tp_dict, "MouseButtonPressed", obj); Py_DECREF(obj); - obj = PyInt_FromLong(sf::Event::JoyMoved); + obj = PyLong_FromLong(sf::Event::JoyMoved); PyDict_SetItemString(PySfEventType.tp_dict, "JoyMoved", obj); Py_DECREF(obj); - obj = PyInt_FromLong(sf::Event::JoyButtonReleased); + obj = PyLong_FromLong(sf::Event::JoyButtonReleased); PyDict_SetItemString(PySfEventType.tp_dict, "JoyButtonReleased", obj); Py_DECREF(obj); - obj = PyInt_FromLong(sf::Event::Resized); + obj = PyLong_FromLong(sf::Event::Resized); PyDict_SetItemString(PySfEventType.tp_dict, "Resized", obj); Py_DECREF(obj); - obj = PyInt_FromLong(sf::Event::MouseEntered); + obj = PyLong_FromLong(sf::Event::MouseEntered); PyDict_SetItemString(PySfEventType.tp_dict, "MouseEntered", obj); Py_DECREF(obj); - obj = PyInt_FromLong(sf::Event::MouseLeft); + obj = PyLong_FromLong(sf::Event::MouseLeft); PyDict_SetItemString(PySfEventType.tp_dict, "MouseLeft", obj); Py_DECREF(obj); } diff --git a/python/src/Event.hpp b/python/src/Event.hpp index c0f4ad896..fa8f8fa4a 100644 --- a/python/src/Event.hpp +++ b/python/src/Event.hpp @@ -25,12 +25,9 @@ #ifndef __PYEVENT_HPP #define __PYEVENT_HPP -#include -#include -#include - #include -#include + +#include typedef struct { diff --git a/python/src/Image.cpp b/python/src/Image.cpp index e3ac4d8b7..9f8abe689 100644 --- a/python/src/Image.cpp +++ b/python/src/Image.cpp @@ -24,34 +24,27 @@ #include "Image.hpp" #include "RenderWindow.hpp" +#include "Color.hpp" +#include "Rect.hpp" + +#include "compat.hpp" extern PyTypeObject PySfColorType; extern PyTypeObject PySfIntRectType; extern PyTypeObject PySfRenderWindowType; -static PyMemberDef PySfImage_members[] = { - {NULL} /* Sentinel */ -}; - - static void PySfImage_dealloc(PySfImage* self) { delete self->obj; - self->ob_type->tp_free((PyObject*)self); + free_object(self); } static PyObject * PySfImage_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { PySfImage *self; - self = (PySfImage *)type->tp_alloc(type, 0); - - if (self != NULL) - { - } - return (PyObject *)self; } @@ -64,7 +57,7 @@ PySfImage_Create(PySfImage* self, PyObject *args, PyObject *kwds) unsigned int Width=0, Height=0; const char *kwlist[] = {"Width", "Height", "Color", NULL}; - if (! PyArg_ParseTupleAndKeywords(args, kwds, "|IIO!", (char **)kwlist, &Width, &Height, &PySfColorType, &ColorTmp)) + if (! PyArg_ParseTupleAndKeywords(args, kwds, "|IIO!:Image.Create", (char **)kwlist, &Width, &Height, &PySfColorType, &ColorTmp)) return NULL; if (ColorTmp) @@ -82,12 +75,11 @@ PySfImage_Create(PySfImage* self, PyObject *args, PyObject *kwds) static PyObject * PySfImage_CopyScreen(PySfImage* self, PyObject *args) { -// bool CopyScreen(RenderWindow& Window, const IntRect& SourceRect = IntRect(0, 0, 0, 0)); PySfRenderWindow *RenderWindow; PySfIntRect *SourceRect=NULL; bool Result; - if (! PyArg_ParseTuple(args, "O!|O!", &PySfRenderWindowType, &RenderWindow, &PySfIntRectType, &SourceRect)) + if (! PyArg_ParseTuple(args, "O!|O!:Image.CopyScreen", &PySfRenderWindowType, &RenderWindow, &PySfIntRectType, &SourceRect)) return NULL; @@ -113,7 +105,7 @@ PySfImage_SetPixel(PySfImage* self, PyObject *args, PyObject *kwds) const char *kwlist[] = {"x", "y", "Color", NULL}; - if (! PyArg_ParseTupleAndKeywords(args, kwds, "II|O!", (char **)kwlist, &x, &y, &PySfColorType, &ColorTmp)) + if (!PyArg_ParseTupleAndKeywords(args, kwds, "II|O!:Image.SetPixel", (char **)kwlist, &x, &y, &PySfColorType, &ColorTmp)) return NULL; @@ -134,7 +126,7 @@ PySfImage_GetPixel(PySfImage* self, PyObject *args) unsigned int x=0, y=0; - if (! PyArg_ParseTuple(args, "II", &x, &y)) + if (!PyArg_ParseTuple(args, "II:Image.GetPixel", &x, &y)) return NULL; @@ -154,8 +146,11 @@ PySfImage_CreateMaskFromColor(PySfImage* self, PyObject *args) PySfColor *ColorTmp= (PySfColor *)args; sf::Color *Color; - if ( ! PyObject_TypeCheck(ColorTmp, &PySfColorType)) - PyErr_SetString(PyExc_ValueError, "Argument must be a sf.Color"); + if (!PyObject_TypeCheck(ColorTmp, &PySfColorType)) + { + PyErr_SetString(PyExc_TypeError, "Image.CreateMaskFromColor() Argument must be a sf.Color"); + return NULL; + } Color = ColorTmp->obj; PySfColorUpdate(ColorTmp); self->obj->CreateMaskFromColor(*Color); @@ -169,14 +164,10 @@ PySfImage_LoadFromMemory(PySfImage* self, PyObject *args) unsigned int SizeInBytes; char *Data; - if (! PyArg_ParseTuple(args, "s#", &Data, &SizeInBytes)) + if (! PyArg_ParseTuple(args, "s#:Image.LoadFromMemory", &Data, &SizeInBytes)) return NULL; - if (self->obj->LoadFromMemory(Data, (std::size_t) SizeInBytes)) - Py_RETURN_TRUE; - else - Py_RETURN_FALSE; - + return PyBool_FromLong(self->obj->LoadFromMemory(Data, (std::size_t) SizeInBytes)); } static PyObject * @@ -185,7 +176,7 @@ PySfImage_LoadFromPixels(PySfImage* self, PyObject *args) unsigned int Width, Height, Size; char *Data; - if (! PyArg_ParseTuple(args, "IIs#", &Width, &Height, &Data, &Size)) + if (! PyArg_ParseTuple(args, "IIs#:Image.LoadFromPixels", &Width, &Height, &Data, &Size)) return NULL; self->obj->LoadFromPixels(Width, Height, (sf::Uint8*) Data); @@ -195,29 +186,49 @@ PySfImage_LoadFromPixels(PySfImage* self, PyObject *args) static PyObject * PySfImage_GetPixels(PySfImage *self) { +#ifdef IS_PY3K + return PyBytes_FromStringAndSize((const char *)(self->obj->GetPixelsPtr()), self->obj->GetWidth()*self->obj->GetHeight()*4); +#else return PyString_FromStringAndSize((const char *)(self->obj->GetPixelsPtr()), self->obj->GetWidth()*self->obj->GetHeight()*4); +#endif } static PyObject * PySfImage_LoadFromFile (PySfImage *self, PyObject *args) { - char *path = PyString_AsString(args); - - if (self->obj->LoadFromFile(path)) - Py_RETURN_TRUE; - else - Py_RETURN_FALSE; + char *path; +#ifdef IS_PY3K + PyObject *string = PyUnicode_AsUTF8String(args); + if (string == NULL) + return NULL; + path = PyBytes_AsString(string); +#else + path = PyString_AsString(args); +#endif + bool result = self->obj->LoadFromFile(path); +#ifdef IS_PY3K + Py_DECREF(string); +#endif + return PyBool_FromLong(result); } static PyObject * PySfImage_SaveToFile (PySfImage *self, PyObject *args) { - char *path = PyString_AsString(args); - - if (self->obj->SaveToFile(path)) - Py_RETURN_TRUE; - else - Py_RETURN_FALSE; + char *path; +#ifdef IS_PY3K + PyObject *string = PyUnicode_AsUTF8String(args); + if (string == NULL) + return NULL; + path = PyBytes_AsString(string); +#else + path = PyString_AsString(args); +#endif + bool result = self->obj->SaveToFile(path); +#ifdef IS_PY3K + Py_DECREF(string); +#endif + return PyBool_FromLong(result); } static int @@ -233,10 +244,7 @@ PySfImage_Bind(PySfImage *self) static PyObject * PySfImage_SetSmooth (PySfImage *self, PyObject *args) { - bool arg=false; - if (PyObject_IsTrue(args)) - arg = true; - self->obj->SetSmooth(arg); + self->obj->SetSmooth(PyBool_AsBool(args)); Py_RETURN_NONE; } @@ -269,8 +277,9 @@ PySfImage_GetTexCoords(PySfImage* self, PyObject *args) if (! PyArg_ParseTuple(args, "O!|O", &PySfIntRectType, &RectArg, &AdjustObj)) return NULL; - if (PyObject_IsTrue(AdjustObj)) - Adjust = true; + if (AdjustObj) + if (PyObject_IsTrue(AdjustObj)) + Adjust = true; PySfFloatRect *Rect; @@ -326,8 +335,7 @@ Create the image from the current contents of the given window. Return True if c }; PyTypeObject PySfImageType = { - PyObject_HEAD_INIT(NULL) - 0, /*ob_size*/ + head_init "Image", /*tp_name*/ sizeof(PySfImage), /*tp_basicsize*/ 0, /*tp_itemsize*/ @@ -358,7 +366,7 @@ Copy constructor : sf.Image(Copy) where Copy is a sf.Image instance.", /* tp_doc 0, /* tp_iter */ 0, /* tp_iternext */ PySfImage_methods, /* tp_methods */ - PySfImage_members, /* tp_members */ + 0, /* tp_members */ 0, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ @@ -373,7 +381,8 @@ Copy constructor : sf.Image(Copy) where Copy is a sf.Image instance.", /* tp_doc static int PySfImage_init(PySfImage *self, PyObject *args, PyObject *kwds) { - if (PyTuple_Size(args) == 1) + int size = PyTuple_Size(args); + if (size == 1) { PySfImage *Image; if (PyArg_ParseTuple(args, "O!", &PySfImageType, &Image)) @@ -386,8 +395,12 @@ PySfImage_init(PySfImage *self, PyObject *args, PyObject *kwds) if (PyTuple_Size(args) > 0) { if (PySfImage_Create(self, args, kwds) == NULL) - if (PySfImage_LoadFromPixels(self, args) == NULL) + { + if (size != 3) return -1; + else if (PySfImage_LoadFromPixels(self, args) == NULL) + return -1; + } } return 0; } @@ -400,11 +413,12 @@ PySfImage_Copy(PySfImage* self, PyObject *args) unsigned int DestX, DestY; PyObject *PyApplyAlpha; bool ApplyAlpha = false; - if (! PyArg_ParseTuple(args, "O!II|O!O", &PySfImageType, &Source, &DestX, &DestY, &PySfIntRectType, &SourceRect, &PyApplyAlpha)) + if (! PyArg_ParseTuple(args, "O!II|O!O:Image.Copy", &PySfImageType, &Source, &DestX, &DestY, &PySfIntRectType, &SourceRect, &PyApplyAlpha)) return NULL; - if (PyObject_IsTrue(PyApplyAlpha)) - ApplyAlpha = true; + if (PyApplyAlpha) + if (PyObject_IsTrue(PyApplyAlpha)) + ApplyAlpha = true; if (SourceRect) { diff --git a/python/src/Image.hpp b/python/src/Image.hpp index 84713e0ef..ff195c7ae 100644 --- a/python/src/Image.hpp +++ b/python/src/Image.hpp @@ -25,16 +25,9 @@ #ifndef __PYIMAGE_HPP #define __PYIMAGE_HPP -#include -#include - #include -#include -#include "Color.hpp" -#include "Rect.hpp" - -#include "offsetof.hpp" +#include typedef struct { diff --git a/python/src/Input.cpp b/python/src/Input.cpp index 7116731e4..c146f69f1 100644 --- a/python/src/Input.cpp +++ b/python/src/Input.cpp @@ -24,85 +24,61 @@ #include "Input.hpp" +#include "compat.hpp" -static PyMemberDef PySfInput_members[] = { - {NULL} /* Sentinel */ -}; - - -static void -PySfInput_dealloc(PySfInput *self) -{ - self->ob_type->tp_free((PyObject*)self); -} static PyObject * PySfInput_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { PySfInput *self; - self = (PySfInput *)type->tp_alloc(type, 0); - if (self != NULL) - { - } - return (PyObject *)self; } - static int PySfInput_init(PySfInput *self, PyObject *args, PyObject *kwds) { - PyErr_SetString(PyExc_StandardError, "You can't create an Input object yourself, because an Input object must always be associated to its window.\nThe only way to get an Input is by creating a window and calling : Input = MyWindow.GetInput()."); + PyErr_SetString(PyExc_RuntimeError, "You can't create an Input object yourself, because an Input object must always be associated to its window.\nThe only way to get an Input is by creating a window and calling : Input = MyWindow.GetInput()."); return -1; } static PyObject* PySfInput_IsKeyDown(PySfInput *self, PyObject *args) { - if (self->obj->IsKeyDown( (sf::Key::Code) PyInt_AsLong(args) )) - Py_RETURN_TRUE; - else - Py_RETURN_FALSE; + return PyBool_FromLong(self->obj->IsKeyDown( (sf::Key::Code) PyLong_AsLong(args) )); } static PyObject* PySfInput_IsMouseButtonDown(PySfInput *self, PyObject *args) { - if (self->obj->IsMouseButtonDown( (sf::Mouse::Button) PyInt_AsLong(args) )) - Py_RETURN_TRUE; - else - Py_RETURN_FALSE; + return PyBool_FromLong(self->obj->IsMouseButtonDown( (sf::Mouse::Button) PyLong_AsLong(args) )); } static PyObject* PySfInput_IsJoystickButtonDown(PySfInput *self, PyObject *args) { unsigned int JoyId, Button; - if (! PyArg_ParseTuple (args, "II", &JoyId, &Button)) + if (! PyArg_ParseTuple (args, "II:Input.IsJoystickButtonDown", &JoyId, &Button)) return NULL; - if (self->obj->IsJoystickButtonDown(JoyId, Button)) - Py_RETURN_TRUE; - else - Py_RETURN_FALSE; + return PyBool_FromLong(self->obj->IsJoystickButtonDown(JoyId, Button)); } static PyObject* PySfInput_GetMouseX(PySfInput *self) { - return PyInt_FromLong(self->obj->GetMouseX()); + return PyLong_FromLong(self->obj->GetMouseX()); } static PyObject* PySfInput_GetMouseY(PySfInput *self) { - return PyInt_FromLong(self->obj->GetMouseY()); + return PyLong_FromLong(self->obj->GetMouseY()); } static PyObject* PySfInput_GetJoystickAxis(PySfInput *self, PyObject *args) { unsigned int JoyId, Axis; - if (! PyArg_ParseTuple (args, "II", &JoyId, &Axis)) + if (! PyArg_ParseTuple (args, "II:Input.GetJoystickAxis", &JoyId, &Axis)) return NULL; return PyFloat_FromDouble(self->obj->GetJoystickAxis(JoyId, (sf::Joy::Axis) Axis)); } @@ -118,12 +94,11 @@ static PyMethodDef PySfInput_methods[] = { }; PyTypeObject PySfInputType = { - PyObject_HEAD_INIT(NULL) - 0, /*ob_size*/ + head_init "Input", /*tp_name*/ sizeof(PySfInput), /*tp_basicsize*/ 0, /*tp_itemsize*/ - (destructor)PySfInput_dealloc, /*tp_dealloc*/ + 0, /*tp_dealloc*/ 0, /*tp_print*/ 0, /*tp_getattr*/ 0, /*tp_setattr*/ @@ -147,7 +122,7 @@ PyTypeObject PySfInputType = { 0, /* tp_iter */ 0, /* tp_iternext */ PySfInput_methods, /* tp_methods */ - PySfInput_members, /* tp_members */ + 0, /* tp_members */ 0, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ diff --git a/python/src/Input.hpp b/python/src/Input.hpp index ad5209e0e..73df36523 100644 --- a/python/src/Input.hpp +++ b/python/src/Input.hpp @@ -25,12 +25,9 @@ #ifndef __PYINPUT_HPP #define __PYINPUT_HPP -#include -#include -#include - #include -#include + +#include typedef struct { PyObject_HEAD diff --git a/python/src/Key.cpp b/python/src/Key.cpp index f209c376e..9b807cfa6 100644 --- a/python/src/Key.cpp +++ b/python/src/Key.cpp @@ -22,62 +22,24 @@ // //////////////////////////////////////////////////////////// -#include - -#include -#include - #include "Key.hpp" - -typedef struct { - PyObject_HEAD -} PySfKey; - - - -static PyMemberDef PySfKey_members[] = { - {NULL} /* Sentinel */ -}; - - -static void -PySfKey_dealloc(PySfKey *self) -{ - self->ob_type->tp_free((PyObject*)self); -} +#include "compat.hpp" static PyObject * PySfKey_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { PySfKey *self; - self = (PySfKey *)type->tp_alloc(type, 0); - if (self != NULL) - { - } - return (PyObject *)self; } - -static int -PySfKey_init(PySfKey *self, PyObject *args, PyObject *kwds) -{ - return 0; -} - -static PyMethodDef PySfKey_methods[] = { - {NULL} /* Sentinel */ -}; - PyTypeObject PySfKeyType = { - PyObject_HEAD_INIT(NULL) - 0, /*ob_size*/ + head_init "Key", /*tp_name*/ sizeof(PySfKey), /*tp_basicsize*/ 0, /*tp_itemsize*/ - (destructor)PySfKey_dealloc, /*tp_dealloc*/ + 0, /*tp_dealloc*/ 0, /*tp_print*/ 0, /*tp_getattr*/ 0, /*tp_setattr*/ @@ -100,15 +62,15 @@ PyTypeObject PySfKeyType = { 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ - PySfKey_methods, /* tp_methods */ - PySfKey_members, /* tp_members */ + 0, /* 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 */ - (initproc)PySfKey_init, /* tp_init */ + 0, /* tp_init */ 0, /* tp_alloc */ PySfKey_new, /* tp_new */ }; @@ -116,307 +78,307 @@ PyTypeObject PySfKeyType = { void PySfKey_InitConst() { PyObject *obj; - obj = PyInt_FromLong(sf::Key::Numpad2); + obj = PyLong_FromLong(sf::Key::Numpad2); PyDict_SetItemString(PySfKeyType.tp_dict, "Numpad2", obj); Py_DECREF(obj); - obj = PyInt_FromLong(sf::Key::Numpad3); + obj = PyLong_FromLong(sf::Key::Numpad3); PyDict_SetItemString(PySfKeyType.tp_dict, "Numpad3", obj); Py_DECREF(obj); - obj = PyInt_FromLong(sf::Key::Numpad0); + obj = PyLong_FromLong(sf::Key::Numpad0); PyDict_SetItemString(PySfKeyType.tp_dict, "Numpad0", obj); Py_DECREF(obj); - obj = PyInt_FromLong(sf::Key::Numpad1); + obj = PyLong_FromLong(sf::Key::Numpad1); PyDict_SetItemString(PySfKeyType.tp_dict, "Numpad1", obj); Py_DECREF(obj); - obj = PyInt_FromLong(sf::Key::Numpad6); + obj = PyLong_FromLong(sf::Key::Numpad6); PyDict_SetItemString(PySfKeyType.tp_dict, "Numpad6", obj); Py_DECREF(obj); - obj = PyInt_FromLong(sf::Key::Numpad7); + obj = PyLong_FromLong(sf::Key::Numpad7); PyDict_SetItemString(PySfKeyType.tp_dict, "Numpad7", obj); Py_DECREF(obj); - obj = PyInt_FromLong(sf::Key::Numpad4); + obj = PyLong_FromLong(sf::Key::Numpad4); PyDict_SetItemString(PySfKeyType.tp_dict, "Numpad4", obj); Py_DECREF(obj); - obj = PyInt_FromLong(sf::Key::Numpad5); + obj = PyLong_FromLong(sf::Key::Numpad5); PyDict_SetItemString(PySfKeyType.tp_dict, "Numpad5", obj); Py_DECREF(obj); - obj = PyInt_FromLong(sf::Key::Numpad8); + obj = PyLong_FromLong(sf::Key::Numpad8); PyDict_SetItemString(PySfKeyType.tp_dict, "Numpad8", obj); Py_DECREF(obj); - obj = PyInt_FromLong(sf::Key::Numpad9); + obj = PyLong_FromLong(sf::Key::Numpad9); PyDict_SetItemString(PySfKeyType.tp_dict, "Numpad9", obj); Py_DECREF(obj); - obj = PyInt_FromLong(sf::Key::RAlt); + obj = PyLong_FromLong(sf::Key::RAlt); PyDict_SetItemString(PySfKeyType.tp_dict, "RAlt", obj); Py_DECREF(obj); - obj = PyInt_FromLong(sf::Key::PageUp); + obj = PyLong_FromLong(sf::Key::PageUp); PyDict_SetItemString(PySfKeyType.tp_dict, "PageUp", obj); Py_DECREF(obj); - obj = PyInt_FromLong(sf::Key::Multiply); + obj = PyLong_FromLong(sf::Key::Multiply); PyDict_SetItemString(PySfKeyType.tp_dict, "Multiply", obj); Py_DECREF(obj); - obj = PyInt_FromLong(sf::Key::D); + obj = PyLong_FromLong(sf::Key::D); PyDict_SetItemString(PySfKeyType.tp_dict, "D", obj); Py_DECREF(obj); - obj = PyInt_FromLong(sf::Key::SemiColon); + obj = PyLong_FromLong(sf::Key::SemiColon); PyDict_SetItemString(PySfKeyType.tp_dict, "SemiColon", obj); Py_DECREF(obj); - obj = PyInt_FromLong(sf::Key::H); + obj = PyLong_FromLong(sf::Key::H); PyDict_SetItemString(PySfKeyType.tp_dict, "H", obj); Py_DECREF(obj); - obj = PyInt_FromLong(sf::Key::L); + obj = PyLong_FromLong(sf::Key::L); PyDict_SetItemString(PySfKeyType.tp_dict, "L", obj); Py_DECREF(obj); - obj = PyInt_FromLong(sf::Key::P); + obj = PyLong_FromLong(sf::Key::P); PyDict_SetItemString(PySfKeyType.tp_dict, "P", obj); Py_DECREF(obj); - obj = PyInt_FromLong(sf::Key::Num7); + obj = PyLong_FromLong(sf::Key::Num7); PyDict_SetItemString(PySfKeyType.tp_dict, "Num7", obj); Py_DECREF(obj); - obj = PyInt_FromLong(sf::Key::T); + obj = PyLong_FromLong(sf::Key::T); PyDict_SetItemString(PySfKeyType.tp_dict, "T", obj); Py_DECREF(obj); - obj = PyInt_FromLong(sf::Key::X); + obj = PyLong_FromLong(sf::Key::X); PyDict_SetItemString(PySfKeyType.tp_dict, "X", obj); Py_DECREF(obj); - obj = PyInt_FromLong(sf::Key::RSystem); + obj = PyLong_FromLong(sf::Key::RSystem); PyDict_SetItemString(PySfKeyType.tp_dict, "RSystem", obj); Py_DECREF(obj); - obj = PyInt_FromLong(sf::Key::F5); + obj = PyLong_FromLong(sf::Key::F5); PyDict_SetItemString(PySfKeyType.tp_dict, "F5", obj); Py_DECREF(obj); - obj = PyInt_FromLong(sf::Key::Num4); + obj = PyLong_FromLong(sf::Key::Num4); PyDict_SetItemString(PySfKeyType.tp_dict, "Num4", obj); Py_DECREF(obj); - obj = PyInt_FromLong(sf::Key::Num5); + obj = PyLong_FromLong(sf::Key::Num5); PyDict_SetItemString(PySfKeyType.tp_dict, "Num5", obj); Py_DECREF(obj); - obj = PyInt_FromLong(sf::Key::Num6); + obj = PyLong_FromLong(sf::Key::Num6); PyDict_SetItemString(PySfKeyType.tp_dict, "Num6", obj); Py_DECREF(obj); - obj = PyInt_FromLong(sf::Key::Right); + obj = PyLong_FromLong(sf::Key::Right); PyDict_SetItemString(PySfKeyType.tp_dict, "Right", obj); Py_DECREF(obj); - obj = PyInt_FromLong(sf::Key::Num0); + obj = PyLong_FromLong(sf::Key::Num0); PyDict_SetItemString(PySfKeyType.tp_dict, "Num0", obj); Py_DECREF(obj); - obj = PyInt_FromLong(sf::Key::Num1); + obj = PyLong_FromLong(sf::Key::Num1); PyDict_SetItemString(PySfKeyType.tp_dict, "Num1", obj); Py_DECREF(obj); - obj = PyInt_FromLong(sf::Key::Num2); + obj = PyLong_FromLong(sf::Key::Num2); PyDict_SetItemString(PySfKeyType.tp_dict, "Num2", obj); Py_DECREF(obj); - obj = PyInt_FromLong(sf::Key::Num3); + obj = PyLong_FromLong(sf::Key::Num3); PyDict_SetItemString(PySfKeyType.tp_dict, "Num3", obj); Py_DECREF(obj); - obj = PyInt_FromLong(sf::Key::LControl); + obj = PyLong_FromLong(sf::Key::LControl); PyDict_SetItemString(PySfKeyType.tp_dict, "LControl", obj); Py_DECREF(obj); - obj = PyInt_FromLong(sf::Key::Num8); + obj = PyLong_FromLong(sf::Key::Num8); PyDict_SetItemString(PySfKeyType.tp_dict, "Num8", obj); Py_DECREF(obj); - obj = PyInt_FromLong(sf::Key::Num9); + obj = PyLong_FromLong(sf::Key::Num9); PyDict_SetItemString(PySfKeyType.tp_dict, "Num9", obj); Py_DECREF(obj); - obj = PyInt_FromLong(sf::Key::Tab); + obj = PyLong_FromLong(sf::Key::Tab); PyDict_SetItemString(PySfKeyType.tp_dict, "Tab", obj); Py_DECREF(obj); - obj = PyInt_FromLong(sf::Key::RBracket); + obj = PyLong_FromLong(sf::Key::RBracket); PyDict_SetItemString(PySfKeyType.tp_dict, "RBracket", obj); Py_DECREF(obj); - obj = PyInt_FromLong(sf::Key::End); + obj = PyLong_FromLong(sf::Key::End); PyDict_SetItemString(PySfKeyType.tp_dict, "End", obj); Py_DECREF(obj); - obj = PyInt_FromLong(sf::Key::BackSlash); + obj = PyLong_FromLong(sf::Key::BackSlash); PyDict_SetItemString(PySfKeyType.tp_dict, "BackSlash", obj); Py_DECREF(obj); - obj = PyInt_FromLong(sf::Key::LShift); + obj = PyLong_FromLong(sf::Key::LShift); PyDict_SetItemString(PySfKeyType.tp_dict, "LShift", obj); Py_DECREF(obj); - obj = PyInt_FromLong(sf::Key::E); + obj = PyLong_FromLong(sf::Key::E); PyDict_SetItemString(PySfKeyType.tp_dict, "E", obj); Py_DECREF(obj); - obj = PyInt_FromLong(sf::Key::C); + obj = PyLong_FromLong(sf::Key::C); PyDict_SetItemString(PySfKeyType.tp_dict, "C", obj); Py_DECREF(obj); - obj = PyInt_FromLong(sf::Key::G); + obj = PyLong_FromLong(sf::Key::G); PyDict_SetItemString(PySfKeyType.tp_dict, "G", obj); Py_DECREF(obj); - obj = PyInt_FromLong(sf::Key::K); + obj = PyLong_FromLong(sf::Key::K); PyDict_SetItemString(PySfKeyType.tp_dict, "K", obj); Py_DECREF(obj); - obj = PyInt_FromLong(sf::Key::Up); + obj = PyLong_FromLong(sf::Key::Up); PyDict_SetItemString(PySfKeyType.tp_dict, "Up", obj); Py_DECREF(obj); - obj = PyInt_FromLong(sf::Key::O); + obj = PyLong_FromLong(sf::Key::O); PyDict_SetItemString(PySfKeyType.tp_dict, "O", obj); Py_DECREF(obj); - obj = PyInt_FromLong(sf::Key::S); + obj = PyLong_FromLong(sf::Key::S); PyDict_SetItemString(PySfKeyType.tp_dict, "S", obj); Py_DECREF(obj); - obj = PyInt_FromLong(sf::Key::W); + obj = PyLong_FromLong(sf::Key::W); PyDict_SetItemString(PySfKeyType.tp_dict, "W", obj); Py_DECREF(obj); - obj = PyInt_FromLong(sf::Key::F12); + obj = PyLong_FromLong(sf::Key::F12); PyDict_SetItemString(PySfKeyType.tp_dict, "F12", obj); Py_DECREF(obj); - obj = PyInt_FromLong(sf::Key::F13); + obj = PyLong_FromLong(sf::Key::F13); PyDict_SetItemString(PySfKeyType.tp_dict, "F13", obj); Py_DECREF(obj); - obj = PyInt_FromLong(sf::Key::F10); + obj = PyLong_FromLong(sf::Key::F10); PyDict_SetItemString(PySfKeyType.tp_dict, "F10", obj); Py_DECREF(obj); - obj = PyInt_FromLong(sf::Key::F11); + obj = PyLong_FromLong(sf::Key::F11); PyDict_SetItemString(PySfKeyType.tp_dict, "F11", obj); Py_DECREF(obj); - obj = PyInt_FromLong(sf::Key::F14); + obj = PyLong_FromLong(sf::Key::F14); PyDict_SetItemString(PySfKeyType.tp_dict, "F14", obj); Py_DECREF(obj); - obj = PyInt_FromLong(sf::Key::Delete); + obj = PyLong_FromLong(sf::Key::Delete); PyDict_SetItemString(PySfKeyType.tp_dict, "Delete", obj); Py_DECREF(obj); - obj = PyInt_FromLong(sf::Key::Back); + obj = PyLong_FromLong(sf::Key::Back); PyDict_SetItemString(PySfKeyType.tp_dict, "Back", obj); Py_DECREF(obj); - obj = PyInt_FromLong(sf::Key::Tilde); + obj = PyLong_FromLong(sf::Key::Tilde); PyDict_SetItemString(PySfKeyType.tp_dict, "Tilde", obj); Py_DECREF(obj); - obj = PyInt_FromLong(sf::Key::Home); + obj = PyLong_FromLong(sf::Key::Home); PyDict_SetItemString(PySfKeyType.tp_dict, "Home", obj); Py_DECREF(obj); - obj = PyInt_FromLong(sf::Key::Pause); + obj = PyLong_FromLong(sf::Key::Pause); PyDict_SetItemString(PySfKeyType.tp_dict, "Pause", obj); Py_DECREF(obj); - obj = PyInt_FromLong(sf::Key::Add); + obj = PyLong_FromLong(sf::Key::Add); PyDict_SetItemString(PySfKeyType.tp_dict, "Add", obj); Py_DECREF(obj); - obj = PyInt_FromLong(sf::Key::F15); + obj = PyLong_FromLong(sf::Key::F15); PyDict_SetItemString(PySfKeyType.tp_dict, "F15", obj); Py_DECREF(obj); - obj = PyInt_FromLong(sf::Key::Subtract); + obj = PyLong_FromLong(sf::Key::Subtract); PyDict_SetItemString(PySfKeyType.tp_dict, "Subtract", obj); Py_DECREF(obj); - obj = PyInt_FromLong(sf::Key::B); + obj = PyLong_FromLong(sf::Key::B); PyDict_SetItemString(PySfKeyType.tp_dict, "B", obj); Py_DECREF(obj); - obj = PyInt_FromLong(sf::Key::F); + obj = PyLong_FromLong(sf::Key::F); PyDict_SetItemString(PySfKeyType.tp_dict, "F", obj); Py_DECREF(obj); - obj = PyInt_FromLong(sf::Key::J); + obj = PyLong_FromLong(sf::Key::J); PyDict_SetItemString(PySfKeyType.tp_dict, "J", obj); Py_DECREF(obj); - obj = PyInt_FromLong(sf::Key::N); + obj = PyLong_FromLong(sf::Key::N); PyDict_SetItemString(PySfKeyType.tp_dict, "N", obj); Py_DECREF(obj); - obj = PyInt_FromLong(sf::Key::LBracket); + obj = PyLong_FromLong(sf::Key::LBracket); PyDict_SetItemString(PySfKeyType.tp_dict, "LBracket", obj); Py_DECREF(obj); - obj = PyInt_FromLong(sf::Key::R); + obj = PyLong_FromLong(sf::Key::R); PyDict_SetItemString(PySfKeyType.tp_dict, "R", obj); Py_DECREF(obj); - obj = PyInt_FromLong(sf::Key::V); + obj = PyLong_FromLong(sf::Key::V); PyDict_SetItemString(PySfKeyType.tp_dict, "V", obj); Py_DECREF(obj); - obj = PyInt_FromLong(sf::Key::LSystem); + obj = PyLong_FromLong(sf::Key::LSystem); PyDict_SetItemString(PySfKeyType.tp_dict, "LSystem", obj); Py_DECREF(obj); - obj = PyInt_FromLong(sf::Key::Z); + obj = PyLong_FromLong(sf::Key::Z); PyDict_SetItemString(PySfKeyType.tp_dict, "Z", obj); Py_DECREF(obj); - obj = PyInt_FromLong(sf::Key::Left); + obj = PyLong_FromLong(sf::Key::Left); PyDict_SetItemString(PySfKeyType.tp_dict, "Left", obj); Py_DECREF(obj); - obj = PyInt_FromLong(sf::Key::F1); + obj = PyLong_FromLong(sf::Key::F1); PyDict_SetItemString(PySfKeyType.tp_dict, "F1", obj); Py_DECREF(obj); - obj = PyInt_FromLong(sf::Key::F2); + obj = PyLong_FromLong(sf::Key::F2); PyDict_SetItemString(PySfKeyType.tp_dict, "F2", obj); Py_DECREF(obj); - obj = PyInt_FromLong(sf::Key::F3); + obj = PyLong_FromLong(sf::Key::F3); PyDict_SetItemString(PySfKeyType.tp_dict, "F3", obj); Py_DECREF(obj); - obj = PyInt_FromLong(sf::Key::F4); + obj = PyLong_FromLong(sf::Key::F4); PyDict_SetItemString(PySfKeyType.tp_dict, "F4", obj); Py_DECREF(obj); - obj = PyInt_FromLong(sf::Key::Divide); + obj = PyLong_FromLong(sf::Key::Divide); PyDict_SetItemString(PySfKeyType.tp_dict, "Divide", obj); Py_DECREF(obj); - obj = PyInt_FromLong(sf::Key::F6); + obj = PyLong_FromLong(sf::Key::F6); PyDict_SetItemString(PySfKeyType.tp_dict, "F6", obj); Py_DECREF(obj); - obj = PyInt_FromLong(sf::Key::F7); + obj = PyLong_FromLong(sf::Key::F7); PyDict_SetItemString(PySfKeyType.tp_dict, "F7", obj); Py_DECREF(obj); - obj = PyInt_FromLong(sf::Key::F8); + obj = PyLong_FromLong(sf::Key::F8); PyDict_SetItemString(PySfKeyType.tp_dict, "F8", obj); Py_DECREF(obj); - obj = PyInt_FromLong(sf::Key::F9); + obj = PyLong_FromLong(sf::Key::F9); PyDict_SetItemString(PySfKeyType.tp_dict, "F9", obj); Py_DECREF(obj); - obj = PyInt_FromLong(sf::Key::Period); + obj = PyLong_FromLong(sf::Key::Period); PyDict_SetItemString(PySfKeyType.tp_dict, "Period", obj); Py_DECREF(obj); - obj = PyInt_FromLong(sf::Key::Down); + obj = PyLong_FromLong(sf::Key::Down); PyDict_SetItemString(PySfKeyType.tp_dict, "Down", obj); Py_DECREF(obj); - obj = PyInt_FromLong(sf::Key::PageDown); + obj = PyLong_FromLong(sf::Key::PageDown); PyDict_SetItemString(PySfKeyType.tp_dict, "PageDown", obj); Py_DECREF(obj); - obj = PyInt_FromLong(sf::Key::Space); + obj = PyLong_FromLong(sf::Key::Space); PyDict_SetItemString(PySfKeyType.tp_dict, "Space", obj); Py_DECREF(obj); - obj = PyInt_FromLong(sf::Key::Menu); + obj = PyLong_FromLong(sf::Key::Menu); PyDict_SetItemString(PySfKeyType.tp_dict, "Menu", obj); Py_DECREF(obj); - obj = PyInt_FromLong(sf::Key::RControl); + obj = PyLong_FromLong(sf::Key::RControl); PyDict_SetItemString(PySfKeyType.tp_dict, "RControl", obj); Py_DECREF(obj); - obj = PyInt_FromLong(sf::Key::Slash); + obj = PyLong_FromLong(sf::Key::Slash); PyDict_SetItemString(PySfKeyType.tp_dict, "Slash", obj); Py_DECREF(obj); - obj = PyInt_FromLong(sf::Key::Return); + obj = PyLong_FromLong(sf::Key::Return); PyDict_SetItemString(PySfKeyType.tp_dict, "Return", obj); Py_DECREF(obj); - obj = PyInt_FromLong(sf::Key::Quote); + obj = PyLong_FromLong(sf::Key::Quote); PyDict_SetItemString(PySfKeyType.tp_dict, "Quote", obj); Py_DECREF(obj); - obj = PyInt_FromLong(sf::Key::A); + obj = PyLong_FromLong(sf::Key::A); PyDict_SetItemString(PySfKeyType.tp_dict, "A", obj); Py_DECREF(obj); - obj = PyInt_FromLong(sf::Key::Insert); + obj = PyLong_FromLong(sf::Key::Insert); PyDict_SetItemString(PySfKeyType.tp_dict, "Insert", obj); Py_DECREF(obj); - obj = PyInt_FromLong(sf::Key::RShift); + obj = PyLong_FromLong(sf::Key::RShift); PyDict_SetItemString(PySfKeyType.tp_dict, "RShift", obj); Py_DECREF(obj); - obj = PyInt_FromLong(sf::Key::I); + obj = PyLong_FromLong(sf::Key::I); PyDict_SetItemString(PySfKeyType.tp_dict, "I", obj); Py_DECREF(obj); - obj = PyInt_FromLong(sf::Key::Escape); + obj = PyLong_FromLong(sf::Key::Escape); PyDict_SetItemString(PySfKeyType.tp_dict, "Escape", obj); Py_DECREF(obj); - obj = PyInt_FromLong(sf::Key::M); + obj = PyLong_FromLong(sf::Key::M); PyDict_SetItemString(PySfKeyType.tp_dict, "M", obj); Py_DECREF(obj); - obj = PyInt_FromLong(sf::Key::Equal); + obj = PyLong_FromLong(sf::Key::Equal); PyDict_SetItemString(PySfKeyType.tp_dict, "Equal", obj); Py_DECREF(obj); - obj = PyInt_FromLong(sf::Key::Q); + obj = PyLong_FromLong(sf::Key::Q); PyDict_SetItemString(PySfKeyType.tp_dict, "Q", obj); Py_DECREF(obj); - obj = PyInt_FromLong(sf::Key::U); + obj = PyLong_FromLong(sf::Key::U); PyDict_SetItemString(PySfKeyType.tp_dict, "U", obj); Py_DECREF(obj); - obj = PyInt_FromLong(sf::Key::Y); + obj = PyLong_FromLong(sf::Key::Y); PyDict_SetItemString(PySfKeyType.tp_dict, "Y", obj); Py_DECREF(obj); - obj = PyInt_FromLong(sf::Key::Dash); + obj = PyLong_FromLong(sf::Key::Dash); PyDict_SetItemString(PySfKeyType.tp_dict, "Dash", obj); Py_DECREF(obj); - obj = PyInt_FromLong(sf::Key::Comma); + obj = PyLong_FromLong(sf::Key::Comma); PyDict_SetItemString(PySfKeyType.tp_dict, "Comma", obj); Py_DECREF(obj); - obj = PyInt_FromLong(sf::Key::LAlt); + obj = PyLong_FromLong(sf::Key::LAlt); PyDict_SetItemString(PySfKeyType.tp_dict, "LAlt", obj); Py_DECREF(obj); } diff --git a/python/src/Key.hpp b/python/src/Key.hpp index 2126ee279..1af17a218 100644 --- a/python/src/Key.hpp +++ b/python/src/Key.hpp @@ -25,6 +25,14 @@ #ifndef __PYKEY_HPP #define __PYKEY_HPP +#include + +#include + +typedef struct { + PyObject_HEAD +} PySfKey; + void PySfKey_InitConst(); diff --git a/python/src/Music.cpp b/python/src/Music.cpp index 9801262ea..ed54bf5f3 100644 --- a/python/src/Music.cpp +++ b/python/src/Music.cpp @@ -24,32 +24,24 @@ #include "Music.hpp" +#include "compat.hpp" + extern PyTypeObject PySfSoundStreamType; -static PyMemberDef PySfMusic_members[] = { - {NULL} /* Sentinel */ -}; - - static void PySfMusic_dealloc(PySfMusic *self) { delete self->obj; - self->ob_type->tp_free((PyObject*)self); + free_object(self); } static PyObject * PySfMusic_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { PySfMusic *self; - self = (PySfMusic *)type->tp_alloc(type, 0); - if (self != NULL) - { - } - return (PyObject *)self; } @@ -58,11 +50,16 @@ static int PySfMusic_init(PySfMusic *self, PyObject *args, PyObject *kwds) { unsigned int BufferSize=44100; - if (PyTuple_Size(args) == 1) + int size = PyTuple_Size(args); + if (size == 1) { - if ( !PyArg_ParseTuple(args, "I", &BufferSize)) + if ( !PyArg_ParseTuple(args, "I:Music.Init", &BufferSize)) return -1; } + else if (size > 1) + { + PyErr_SetString(PyExc_TypeError, "Music.__init__() takes at most one argument"); + } self->obj = new sf::Music(BufferSize); return 0; } @@ -73,23 +70,29 @@ PySfMusic_OpenFromMemory(PySfMusic *self, PyObject *args) unsigned int SizeInBytes; char *Data; - if (! PyArg_ParseTuple(args, "s#", &Data, &SizeInBytes)) + if (! PyArg_ParseTuple(args, "s#:Music.OpenFromMemory", &Data, &SizeInBytes)) return NULL; - if (self->obj->OpenFromMemory(Data, (std::size_t) SizeInBytes)) - Py_RETURN_TRUE; - else - Py_RETURN_FALSE; + return PyBool_FromLong(self->obj->OpenFromMemory(Data, (std::size_t) SizeInBytes)); } static PyObject* PySfMusic_OpenFromFile(PySfMusic *self, PyObject *args) { - char *path = PyString_AsString(args); - if (self->obj->OpenFromFile(path)) - Py_RETURN_TRUE; - else - Py_RETURN_FALSE; + char *path; +#ifdef IS_PY3K + PyObject *string = PyUnicode_AsUTF8String(args); + if (string == NULL) + return NULL; + path = PyBytes_AsString(string); +#else + path = PyString_AsString(args); +#endif + bool result = self->obj->OpenFromFile(path); +#ifdef IS_PY3K + Py_DECREF(string); +#endif + return PyBool_FromLong(result); } static PyObject* @@ -108,8 +111,7 @@ static PyMethodDef PySfMusic_methods[] = { PyTypeObject PySfMusicType = { - PyObject_HEAD_INIT(NULL) - 0, /*ob_size*/ + head_init "Music", /*tp_name*/ sizeof(PySfMusic), /*tp_basicsize*/ 0, /*tp_itemsize*/ @@ -129,7 +131,9 @@ PyTypeObject PySfMusicType = { 0, /*tp_setattro*/ 0, /*tp_as_buffer*/ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/ - "sf.Music defines a big sound played using streaming, so usually what we call a music :)", /* tp_doc */ + "sf.Music defines a big sound played using streaming, so usually what we call a music :).\n\ +Constructor: sf.Music(BufferSize=44100)\n\ +BufferSize : Size of the internal buffer, expressed in number of samples (ie. size taken by the music in memory) (44100 by default)", /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ @@ -137,7 +141,7 @@ PyTypeObject PySfMusicType = { 0, /* tp_iter */ 0, /* tp_iternext */ PySfMusic_methods, /* tp_methods */ - PySfMusic_members, /* tp_members */ + 0, /* tp_members */ 0, /* tp_getset */ &PySfSoundStreamType, /* tp_base */ 0, /* tp_dict */ diff --git a/python/src/Music.hpp b/python/src/Music.hpp index 9d2fba400..a69c47d17 100644 --- a/python/src/Music.hpp +++ b/python/src/Music.hpp @@ -25,13 +25,9 @@ #ifndef __PYMUSIC_HPP #define __PYMUSIC_HPP -#include -#include - #include -#include - +#include typedef struct { PyObject_HEAD diff --git a/python/src/PostFX.cpp b/python/src/PostFX.cpp index fb2f343d7..5962972a7 100644 --- a/python/src/PostFX.cpp +++ b/python/src/PostFX.cpp @@ -22,69 +22,75 @@ // //////////////////////////////////////////////////////////// -#include "PostFX.hpp" +#include "PostFX.hpp" +#include "Drawable.hpp" +#include "Image.hpp" + +#include "compat.hpp" extern PyTypeObject PySfImageType; -extern PyTypeObject PySfDrawableType; - -static PyMemberDef PySfPostFX_members[] = { - {NULL} /* Sentinel */ -}; - - +extern PyTypeObject PySfDrawableType; + static void PySfPostFX_dealloc(PySfPostFX *self) { delete self->obj; - self->ob_type->tp_free((PyObject*)self); + free_object(self); } static PyObject * PySfPostFX_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { PySfPostFX *self; - self = (PySfPostFX *)type->tp_alloc(type, 0); - - if (self != NULL) - { - } - return (PyObject *)self; } static PyObject * PySfPostFX_LoadFromFile (PySfPostFX *self, PyObject *args) -{ - if (self->obj->LoadFromFile(PyString_AsString(args))) - Py_RETURN_TRUE; - else - Py_RETURN_FALSE; +{ + char *path; +#ifdef IS_PY3K + PyObject *string = PyUnicode_AsUTF8String(args); + if (string == NULL) + return NULL; + path = PyBytes_AsString(string); +#else + path = PyString_AsString(args); +#endif + bool result = self->obj->LoadFromFile(path); +#ifdef IS_PY3K + Py_DECREF(string); +#endif + return PyBool_FromLong(result); } static PyObject * PySfPostFX_LoadFromMemory (PySfPostFX *self, PyObject *args) -{ - if (self->obj->LoadFromMemory(PyString_AsString(args))) - Py_RETURN_TRUE; - else - Py_RETURN_FALSE; +{ + char *path; +#ifdef IS_PY3K + PyObject *string = PyUnicode_AsUTF8String(args); + if (string == NULL) + return NULL; + path = PyBytes_AsString(string); +#else + path = PyString_AsString(args); +#endif + bool result = self->obj->LoadFromMemory(path); +#ifdef IS_PY3K + Py_DECREF(string); +#endif + return PyBool_FromLong(result); } static int -PySfPostFX_init(PySfPostFX *self, PyObject *args); +PySfPostFX_init(PySfPostFX *self, PyObject *args); -static PyObject * -PySfPostFX_SetParameter(PySfPostFX* self, PyObject *args) -{ - char *Name; - float X, Y, Z, W; - int size = PyTuple_Size(args); - if (! PyArg_ParseTuple(args, "sf|fff", &Name, &X, &Y, &Z, &W)) - return NULL; +static PyObject * PySfPostFX_SetParameter(PySfPostFX* self, PyObject *args) { char *Name; float X, Y, Z, W; int size = PyTuple_Size(args); if (!PyArg_ParseTuple(args, "sf|fff:PostFX.SetParameter", &Name, &X, &Y, &Z, &W)) return NULL; switch (size) { @@ -120,7 +126,7 @@ PySfPostFX_SetTexture(PySfPostFX* self, PyObject *args) { if (!PyObject_TypeCheck(Image, &PySfImageType)) { - PyErr_SetString(PyExc_TypeError, "Argument 2, if specified, must be a sf.Image instance or None."); + PyErr_SetString(PyExc_TypeError, "PostFX.SetTexture() Argument 2, if specified, must be a sf.Image instance or None."); return NULL; } self->obj->SetTexture(Name, Image->obj); @@ -131,10 +137,7 @@ PySfPostFX_SetTexture(PySfPostFX* self, PyObject *args) static PyObject * PySfPostFX_CanUsePostFX(PySfPostFX* self, PyObject *args) { - if (sf::PostFX::CanUsePostFX()) - Py_RETURN_TRUE; - else - Py_RETURN_FALSE; + return PyBool_FromLong(sf::PostFX::CanUsePostFX()); } @@ -152,8 +155,7 @@ static PyMethodDef PySfPostFX_methods[] = { }; PyTypeObject PySfPostFXType = { - PyObject_HEAD_INIT(NULL) - 0, /*ob_size*/ + head_init "PostFX", /*tp_name*/ sizeof(PySfPostFX), /*tp_basicsize*/ 0, /*tp_itemsize*/ @@ -173,7 +175,9 @@ PyTypeObject PySfPostFXType = { 0, /*tp_setattro*/ 0, /*tp_as_buffer*/ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/ - "sf.PostFX is used to apply a post effect to a window. ", /* tp_doc */ + "sf.PostFX is used to apply a post effect to a window.\n\ +Default constructor : sf.PostFX()\n\ +Copy constructor : sf.PostFX(Copy) where Copy is a sf.PostFX instance.", /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ @@ -181,7 +185,7 @@ PyTypeObject PySfPostFXType = { 0, /* tp_iter */ 0, /* tp_iternext */ PySfPostFX_methods, /* tp_methods */ - PySfPostFX_members, /* tp_members */ + 0, /* tp_members */ 0, /* tp_getset */ &PySfDrawableType, /* tp_base */ 0, /* tp_dict */ diff --git a/python/src/PostFX.hpp b/python/src/PostFX.hpp index 20541ace6..080b3a0a5 100644 --- a/python/src/PostFX.hpp +++ b/python/src/PostFX.hpp @@ -25,14 +25,9 @@ #ifndef __PYPOSTFX_HPP #define __PYPOSTFX_HPP -#include -#include - #include -#include -#include "Drawable.hpp" -#include "Image.hpp" +#include typedef struct { PyObject_HEAD diff --git a/python/src/Rect.cpp b/python/src/Rect.cpp index 46d03722b..a05583e92 100644 --- a/python/src/Rect.cpp +++ b/python/src/Rect.cpp @@ -24,6 +24,12 @@ #include "Rect.hpp" +#include + +#include "compat.hpp" +#include "offsetof.hpp" + + static PyMemberDef PySfIntRect_members[] = { {(char *)"Left", T_INT, offsetof(PySfIntRect, Left), 0, (char *)"Left coordinate of the rectangle."}, {(char *)"Top", T_INT, offsetof(PySfIntRect, Top), 0, (char *)"Top coordinate of the rectangle."}, @@ -44,26 +50,21 @@ static void PySfIntRect_dealloc(PySfIntRect* self) { delete self->obj; - self->ob_type->tp_free((PyObject*)self); + free_object(self); } static void PySfFloatRect_dealloc(PySfFloatRect* self) { delete self->obj; - self->ob_type->tp_free((PyObject*)self); + free_object(self); } static PyObject * PySfIntRect_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { PySfIntRect *self; - self = (PySfIntRect *)type->tp_alloc(type, 0); - if (self != NULL) - { - } - return (PyObject *)self; } @@ -71,12 +72,7 @@ static PyObject * PySfFloatRect_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { PySfFloatRect *self; - self = (PySfFloatRect *)type->tp_alloc(type, 0); - if (self != NULL) - { - } - return (PyObject *)self; } @@ -86,7 +82,7 @@ PySfIntRect_init(PySfIntRect *self, PyObject *args, PyObject *kwds) const char *kwlist[] = {"Left", "Top", "Right", "Bottom", NULL}; int Left, Top, Right, Bottom; - if (! PyArg_ParseTupleAndKeywords(args, kwds, "iiii", (char **)kwlist, &Left, &Top, &Right, &Bottom)) + if (!PyArg_ParseTupleAndKeywords(args, kwds, "iiii:IntRect.__init__", (char **)kwlist, &Left, &Top, &Right, &Bottom)) return -1; self->Left = Left; @@ -101,14 +97,14 @@ static PyObject * PySfIntRect_GetWidth(PySfIntRect *self) { PySfIntRectUpdateObj(self); - return PyInt_FromLong(self->obj->GetWidth()); + return PyLong_FromLong(self->obj->GetWidth()); } static PyObject * PySfIntRect_GetHeight(PySfIntRect *self) { PySfIntRectUpdateObj(self); - return PyInt_FromLong(self->obj->GetHeight()); + return PyLong_FromLong(self->obj->GetHeight()); } static PyObject * @@ -143,7 +139,7 @@ PySfFloatRect_init(PySfFloatRect *self, PyObject *args, PyObject *kwds) const char *kwlist[] = {"Left", "Top", "Right", "Bottom", NULL}; float Left, Top, Right, Bottom; - if (! PyArg_ParseTupleAndKeywords(args, kwds, "ffff", (char **)kwlist, &Left, &Top, &Right, &Bottom)) + if (!PyArg_ParseTupleAndKeywords(args, kwds, "ffff:FloatRect.__init__", (char **)kwlist, &Left, &Top, &Right, &Bottom)) return -1; self->Left = Left; @@ -160,7 +156,7 @@ PySfIntRect_Offset(PySfIntRect* self, PyObject *args) { int OffsetX, OffsetY; - if (!PyArg_ParseTuple(args, "ii", &OffsetX, &OffsetY)) + if (!PyArg_ParseTuple(args, "ii:IntRect.Offset", &OffsetX, &OffsetY)) return NULL; PySfIntRectUpdateObj(self); @@ -174,7 +170,7 @@ PySfFloatRect_Offset(PySfFloatRect* self, PyObject *args) { float OffsetX, OffsetY; - if (!PyArg_ParseTuple(args, "ff", &OffsetX, &OffsetY)) + if (!PyArg_ParseTuple(args, "ff:FloatRect.Offset", &OffsetX, &OffsetY)) return NULL; PySfFloatRectUpdateObj(self); @@ -228,8 +224,7 @@ Check intersection between two rectangles.\n\ }; PyTypeObject PySfIntRectType = { - PyObject_HEAD_INIT(NULL) - 0, /*ob_size*/ + head_init "IntRect", /*tp_name*/ sizeof(PySfIntRect), /*tp_basicsize*/ 0, /*tp_itemsize*/ @@ -271,8 +266,7 @@ PyTypeObject PySfIntRectType = { PyTypeObject PySfFloatRectType = { - PyObject_HEAD_INIT(NULL) - 0, /*ob_size*/ + head_init "FloatRect", /*tp_name*/ sizeof(PySfFloatRect), /*tp_basicsize*/ 0, /*tp_itemsize*/ @@ -318,14 +312,11 @@ PySfFloatRect_Contains(PySfFloatRect* self, PyObject *args) { float x=0, y=0; - if (! PyArg_ParseTuple(args, "ff", &x, &y)) + if (!PyArg_ParseTuple(args, "ff:FloatRect.Contains", &x, &y)) return NULL; PySfFloatRectUpdateObj(self); - if (self->obj->Contains(x,y)) - Py_RETURN_TRUE; - else - Py_RETURN_FALSE; + return PyBool_FromLong(self->obj->Contains(x,y)); } static PyObject * @@ -334,8 +325,7 @@ PySfFloatRect_Intersects(PySfFloatRect* self, PyObject *args) PySfFloatRect *Rect=NULL, *OverlappingRect=NULL; bool result; - - if (! PyArg_ParseTuple(args, "O!|O!", &PySfFloatRectType, &Rect, &PySfFloatRectType, &OverlappingRect)) + if (!PyArg_ParseTuple(args, "O!|O!:FloatRect.Intersects", &PySfFloatRectType, &Rect, &PySfFloatRectType, &OverlappingRect)) return NULL; PySfFloatRectUpdateObj(self); @@ -344,10 +334,7 @@ PySfFloatRect_Intersects(PySfFloatRect* self, PyObject *args) else result = self->obj->Intersects(*(Rect->obj)); - if (result) - Py_RETURN_TRUE; - else - Py_RETURN_FALSE; + return PyBool_FromLong(result); } @@ -357,13 +344,10 @@ PySfIntRect_Contains(PySfIntRect* self, PyObject *args) unsigned int x=0, y=0; PySfIntRectUpdateObj(self); - if (! PyArg_ParseTuple(args, "II", &x, &y)) + if (!PyArg_ParseTuple(args, "II:IntRect.Contains", &x, &y)) return NULL; - if (self->obj->Contains(x,y)) - Py_RETURN_TRUE; - else - Py_RETURN_FALSE; + return PyBool_FromLong(self->obj->Contains(x,y)); } static PyObject * @@ -373,7 +357,7 @@ PySfIntRect_Intersects(PySfIntRect* self, PyObject *args) bool result; PySfIntRectUpdateObj(self); - if (! PyArg_ParseTuple(args, "O!|O!", &PySfIntRectType, &Rect, &PySfIntRectType, &OverlappingRect)) + if (!PyArg_ParseTuple(args, "O!|O!:IntRect.Intersects", &PySfIntRectType, &Rect, &PySfIntRectType, &OverlappingRect)) return NULL; if (OverlappingRect) @@ -381,10 +365,7 @@ PySfIntRect_Intersects(PySfIntRect* self, PyObject *args) else result = self->obj->Intersects(*(Rect->obj)); - if (result) - Py_RETURN_TRUE; - else - Py_RETURN_FALSE; + return PyBool_FromLong(result); } void diff --git a/python/src/Rect.hpp b/python/src/Rect.hpp index 59856f929..4b4ae63f9 100644 --- a/python/src/Rect.hpp +++ b/python/src/Rect.hpp @@ -25,14 +25,9 @@ #ifndef __PYRECT_HPP #define __PYRECT_HPP +#include #include -#include - -#include -#include - -#include "offsetof.hpp" typedef struct { PyObject_HEAD diff --git a/python/src/RenderTarget.cpp b/python/src/RenderTarget.cpp index 8762cdaa9..5b2afe243 100644 --- a/python/src/RenderTarget.cpp +++ b/python/src/RenderTarget.cpp @@ -25,33 +25,26 @@ #include "RenderTarget.hpp" #include "Color.hpp" #include "View.hpp" + +#include "compat.hpp" + extern PyTypeObject PySfColorType; extern PyTypeObject PySfViewType; -static PyMemberDef PySfRenderTarget_members[] = { - {NULL} /* Sentinel */ -}; - static void PySfRenderTarget_dealloc(PySfRenderTarget *self) { delete self->obj; - self->ob_type->tp_free((PyObject*)self); + free_object(self); } static PyObject * PySfRenderTarget_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { PySfRenderTarget *self; - self = (PySfRenderTarget *)type->tp_alloc(type, 0); - - if (self != NULL) - { - } - return (PyObject *)self; } @@ -62,11 +55,8 @@ PySfRenderTarget_Clear(PySfRenderTarget *self, PyObject *args) int size = PyTuple_Size(args); if (size == 1) { - if (! PyArg_ParseTuple(args, "O!", &PySfColorType, &Color)) - { - PyErr_SetString(PyExc_TypeError, "Argument is not a sf.Color"); + if (!PyArg_ParseTuple(args, "O!:RenderTarget.Clear", &PySfColorType, &Color)) return NULL; - } PySfColorUpdate(Color); self->obj->Clear(*(Color->obj)); } @@ -97,9 +87,7 @@ PySfRenderTarget_GetView(PySfRenderTarget *self) static PyObject * PySfRenderTarget_PreserveOpenGLStates(PySfRenderTarget *self, PyObject *args) { - bool Optimize = false; - if (PyObject_IsTrue(args)) - Optimize = true; + bool Optimize = PyBool_AsBool(args); self->obj->PreserveOpenGLStates(Optimize); Py_RETURN_NONE; } @@ -108,9 +96,9 @@ static PyObject * PySfRenderTarget_SetView(PySfRenderTarget* self, PyObject *args) { PySfView *View = (PySfView *)args; - if (! PyObject_TypeCheck(View, &PySfViewType)) + if (!PyObject_TypeCheck(View, &PySfViewType)) { - PyErr_SetString(PyExc_TypeError, "Argument is not a sf.View"); + PyErr_SetString(PyExc_TypeError, "RenderTarget.SetView() Argument is not a sf.View"); return NULL; } self->obj->SetView( *(View->obj)); @@ -146,8 +134,7 @@ Change the current active view. View must be a sf.View instance."}, }; PyTypeObject PySfRenderTargetType = { - PyObject_HEAD_INIT(NULL) - 0, /*ob_size*/ + head_init "RenderTarget", /*tp_name*/ sizeof(PySfRenderTarget), /*tp_basicsize*/ 0, /*tp_itemsize*/ @@ -175,14 +162,14 @@ PyTypeObject PySfRenderTargetType = { 0, /* tp_iter */ 0, /* tp_iternext */ PySfRenderTarget_methods, /* tp_methods */ - PySfRenderTarget_members, /* tp_members */ + 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_init */ 0, /* tp_alloc */ PySfRenderTarget_new, /* tp_new */ }; diff --git a/python/src/RenderTarget.hpp b/python/src/RenderTarget.hpp index 25a4ef40c..e57a5a552 100644 --- a/python/src/RenderTarget.hpp +++ b/python/src/RenderTarget.hpp @@ -25,12 +25,9 @@ #ifndef __PYRENDERTARGET_H #define __PYRENDERTARGET_H -#include - #include -#include -#include +#include typedef struct { PyObject_HEAD diff --git a/python/src/RenderWindow.cpp b/python/src/RenderWindow.cpp index 71f293e3f..1e486a55f 100644 --- a/python/src/RenderWindow.cpp +++ b/python/src/RenderWindow.cpp @@ -23,7 +23,6 @@ //////////////////////////////////////////////////////////// #include "RenderWindow.hpp" - #include "Event.hpp" #include "VideoMode.hpp" #include "Drawable.hpp" @@ -31,9 +30,12 @@ #include "Rect.hpp" #include "View.hpp" #include "Image.hpp" -#include "Window.hpp" +#include "Window.hpp" +#include "WindowSettings.hpp" + +#include "compat.hpp" -#include "SFML/Window/WindowStyle.hpp" +#include extern PyTypeObject PySfEventType; @@ -43,31 +45,21 @@ extern PyTypeObject PySfWindowType; extern PyTypeObject PySfWindowSettingsType; extern PyTypeObject PySfVideoModeType; extern PyTypeObject PySfDrawableType; - extern PyTypeObject PySfRenderTargetType; -static PyMemberDef PySfRenderWindow_members[] = { - {NULL} /* Sentinel */ -}; - static void PySfRenderWindow_dealloc(PySfRenderWindow* self) { delete self->obj; - self->ob_type->tp_free((PyObject*)self); + free_object(self); } static PyObject * PySfRenderWindow_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { PySfRenderWindow *self; - self = (PySfRenderWindow *)type->tp_alloc(type, 0); - if (self != NULL) - { - } - return (PyObject *)self; } @@ -76,7 +68,8 @@ PySfRenderWindow_init(PySfRenderWindow *self, PyObject *args, PyObject *kwds) { self->obj = new sf::RenderWindow(); if (PyTuple_Size(args) > 0) - PySfWindow_Create((PySfWindow *)self, args, kwds); + if (PySfWindow_Create((PySfWindow *)self, args, kwds) == NULL) + return -1; return 0; } @@ -98,7 +91,7 @@ PySfRenderWindow_ConvertCoords(PySfRenderWindow *self, PyObject *args) sf::View *TargetView = NULL; sf::Vector2f Vect; - if (! PyArg_ParseTuple(args, "II|O!", &WindowX, &WindowY, &PySfViewType, &PyTargetView)) + if (!PyArg_ParseTuple(args, "II|O!:RenderWindow.ConvertCoords", &WindowX, &WindowY, &PySfViewType, &PyTargetView)) return NULL; if (PyTargetView) @@ -154,9 +147,8 @@ PySfRenderWindow_Draw(PySfRenderWindow *self, PyObject *args) Py_DECREF(iterator); - if (PyErr_Occurred()) { + if (PyErr_Occurred()) return NULL; - } } Py_RETURN_NONE; } @@ -175,8 +167,7 @@ Draw something on the window. The argument can be a drawable or any object suppo }; PyTypeObject PySfRenderWindowType = { - PyObject_HEAD_INIT(NULL) - 0, /*ob_size*/ + head_init "RenderWindow", /*tp_name*/ sizeof(PySfRenderWindow), /*tp_basicsize*/ 0, /*tp_itemsize*/ @@ -196,7 +187,14 @@ PyTypeObject PySfRenderWindowType = { 0, /*tp_setattro*/ 0, /*tp_as_buffer*/ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/ - "Simple wrapper for sf.Window that allows easy 2D rendering.", /* tp_doc */ + "Simple wrapper for sf.Window that allows easy 2D rendering.\n\ +Default constructor : sf.RenderWindow()\n\ +Other constructor : sf.RenderWindow(Mode, Title, Style::Resize|Style::Close, Params = WindowSettings())\n\ +Parameters:\n\ + Mode : Video mode to use\n\ + Title : Title of the window\n\ + WindowStyle : Window style (Resize | Close by default)\n\ + Params : Creation parameters (see default constructor for default values)", /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ @@ -204,7 +202,7 @@ PyTypeObject PySfRenderWindowType = { 0, /* tp_iter */ 0, /* tp_iternext */ PySfRenderWindow_methods, /* tp_methods */ - PySfRenderWindow_members, /* tp_members */ + 0, /* tp_members */ 0, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ diff --git a/python/src/RenderWindow.hpp b/python/src/RenderWindow.hpp index c484b891e..37e62afb6 100644 --- a/python/src/RenderWindow.hpp +++ b/python/src/RenderWindow.hpp @@ -25,13 +25,9 @@ #ifndef __PYRENDERWINDOW_HPP #define __PYRENDERWINDOW_HPP -#include -#include - #include -#include -#include "WindowSettings.hpp" +#include typedef struct { PyObject_HEAD diff --git a/python/src/Sleep.hpp b/python/src/Sleep.hpp index ad2b7e0e9..3c78fd733 100644 --- a/python/src/Sleep.hpp +++ b/python/src/Sleep.hpp @@ -25,11 +25,9 @@ #ifndef __PYSLEEP_HPP #define __PYSLEEP_HPP -#include -#include - #include -#include + +#include PyObject * PySFML_Sleep (PyObject *self, PyObject *args); diff --git a/python/src/Sprite.cpp b/python/src/Sprite.cpp index c783ccdd1..3070e47c8 100644 --- a/python/src/Sprite.cpp +++ b/python/src/Sprite.cpp @@ -22,7 +22,12 @@ // //////////////////////////////////////////////////////////// -#include "Sprite.hpp" +#include "Sprite.hpp" +#include "Drawable.hpp" +#include "Rect.hpp" +#include "Color.hpp" + +#include "compat.hpp" extern PyTypeObject PySfColorType; @@ -30,19 +35,16 @@ extern PyTypeObject PySfImageType; extern PyTypeObject PySfIntRectType; extern PyTypeObject PySfDrawableType; -static PyMemberDef PySfSprite_members[] = { - {NULL} /* Sentinel */ -}; - - static void PySfSprite_dealloc(PySfSprite *self) { if (self->Image != NULL) - Py_DECREF(self->Image); + { + Py_DECREF(self->Image); + } delete self->obj; - self->ob_type->tp_free((PyObject*)self); + free_object(self); } static PyObject * @@ -69,7 +71,7 @@ PySfSprite_init(PySfSprite *self, PyObject *args, PyObject *kwds) PySfImage *Image=NULL; PySfColor *Color=NULL; - if (! PyArg_ParseTupleAndKeywords(args, kwds, "O!|fffffO!", (char **)kwlist, &PySfImageType, &Image, &X, &Y, &ScaleX, &ScaleY, &Rotation, &PySfColorType, &Color)) + if (! PyArg_ParseTupleAndKeywords(args, kwds, "O!|fffffO!:Sprite.__init__", (char **)kwlist, &PySfImageType, &Image, &X, &Y, &ScaleX, &ScaleY, &Rotation, &PySfColorType, &Color)) return -1; Py_INCREF(Image); @@ -79,7 +81,6 @@ PySfSprite_init(PySfSprite *self, PyObject *args, PyObject *kwds) else self->obj = new sf::Sprite(*(Image->obj), sf::Vector2f(X, Y), sf::Vector2f(ScaleX, ScaleY), Rotation); - return 0; } @@ -91,7 +92,7 @@ PySfSprite_SetImage(PySfSprite* self, PyObject *args) PySfImage *Image = (PySfImage *)args; if (! PyObject_TypeCheck(Image, &PySfImageType)) { - PyErr_SetString(PyExc_TypeError, "Argument is not a sfImage"); + PyErr_SetString(PyExc_TypeError, "Sprite.SetImage() Argument is not a sf.Image"); return NULL; } Py_DECREF(self->Image); @@ -114,8 +115,7 @@ PySfSprite_GetPixel(PySfSprite* self, PyObject *args) PySfColor *Color; unsigned int x=0, y=0; - - if (! PyArg_ParseTuple(args, "II", &x, &y)) + if (!PyArg_ParseTuple(args, "II:Sprite.GetPixel", &x, &y)) return NULL; Color = GetNewPySfColor(); @@ -133,7 +133,7 @@ PySfSprite_Resize(PySfSprite* self, PyObject *args) { float W=0, H=0; - if (! PyArg_ParseTuple(args, "ff", &W, &H)) + if (! PyArg_ParseTuple(args, "ff:Sprite.Resize", &W, &H)) return NULL; self->obj->Resize(W,H); @@ -161,7 +161,7 @@ PySfSprite_SetSubRect(PySfSprite* self, PyObject *args) PySfIntRect *Rect = (PySfIntRect *)args; if (! PyObject_TypeCheck(Rect, &PySfIntRectType)) { - PyErr_SetString(PyExc_TypeError, "Argument is not a sf.IntRect instance"); + PyErr_SetString(PyExc_TypeError, "Sprite.SetSubRect() Argument is not a sf.IntRect instance"); return NULL; } self->obj->SetSubRect(*(Rect->obj)); @@ -171,20 +171,14 @@ PySfSprite_SetSubRect(PySfSprite* self, PyObject *args) static PyObject * PySfSprite_FlipX(PySfSprite* self, PyObject *args) { - bool Flip = false; - if (PyObject_IsTrue(args)) - Flip = true; - self->obj->FlipX(Flip); + self->obj->FlipX(PyBool_AsBool(args)); Py_RETURN_NONE; } static PyObject * PySfSprite_FlipY(PySfSprite* self, PyObject *args) { - bool Flip = false; - if (PyObject_IsTrue(args)) - Flip = true; - self->obj->FlipY(Flip); + self->obj->FlipY(PyBool_AsBool(args)); Py_RETURN_NONE; } @@ -211,8 +205,7 @@ static PyMethodDef PySfSprite_methods[] = { }; PyTypeObject PySfSpriteType = { - PyObject_HEAD_INIT(NULL) - 0, /*ob_size*/ + head_init "Sprite", /*tp_name*/ sizeof(PySfSprite), /*tp_basicsize*/ 0, /*tp_itemsize*/ @@ -240,7 +233,7 @@ PyTypeObject PySfSpriteType = { 0, /* tp_iter */ 0, /* tp_iternext */ PySfSprite_methods, /* tp_methods */ - PySfSprite_members, /* tp_members */ + 0, /* tp_members */ 0, /* tp_getset */ &PySfDrawableType, /* tp_base */ 0, /* tp_dict */ diff --git a/python/src/Sprite.hpp b/python/src/Sprite.hpp index 97cd58b2d..aaab6d635 100644 --- a/python/src/Sprite.hpp +++ b/python/src/Sprite.hpp @@ -25,16 +25,11 @@ #ifndef __PYSPRITE_HPP #define __PYSPRITE_HPP -#include -#include -#include - #include -#include -#include "Drawable.hpp" +#include + #include "Image.hpp" -#include "Rect.hpp" typedef struct { PyObject_HEAD diff --git a/python/src/Window.cpp b/python/src/Window.cpp index 1f4b17f80..791012460 100644 --- a/python/src/Window.cpp +++ b/python/src/Window.cpp @@ -169,7 +169,8 @@ PySfWindow_init(PySfWindow *self, PyObject *args, PyObject *kwds) { self->obj = new sf::Window(); if (PyTuple_Size(args) > 0) - PySfWindow_Create(self, args, kwds); + if (PySfWindow_Create(self, args, kwds) == NULL) + return -1; return 0; } diff --git a/python/src/compat.hpp b/python/src/compat.hpp new file mode 100644 index 000000000..173ab54a8 --- /dev/null +++ b/python/src/compat.hpp @@ -0,0 +1,42 @@ +//////////////////////////////////////////////////////////// +// +// PySFML - Python binding for SFML (Simple and Fast Multimedia Library) +// Copyright (C) 2007, 2008 Rémi Koenig (remi.k2620@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. +// +//////////////////////////////////////////////////////////// + +#ifndef __PYCOMPAT_HPP +#define __PYCOMPAT_HPP + +#if PY_MAJOR_VERSION >= 3 +#define IS_PY3K +#define head_init PyVarObject_HEAD_INIT(NULL, 0) +#else +#define Py_TYPE(a) a->ob_type +#define head_init PyObject_HEAD_INIT(NULL) 0, +#define PyBytes_FromStringAndSize PyString_FromStringAndSize +#endif + +#define free_object(a) Py_TYPE(a)->tp_free((PyObject*)a) + +#define PyBool_AsBool(a) ((PyObject_IsTrue(a))?true:false) + +#endif + diff --git a/python/src/main.cpp b/python/src/main.cpp index 7df0428b1..6dc7d06d8 100644 --- a/python/src/main.cpp +++ b/python/src/main.cpp @@ -33,7 +33,9 @@ #include "Blend.hpp" #include "Sound.hpp" #include "String.hpp" -#include "SoundStream.hpp" +#include "SoundStream.hpp" + +#include "compat.hpp" extern PyTypeObject PySfClockType; @@ -88,109 +90,129 @@ extern PyTypeObject PySfListenerType; static PyMethodDef module_methods[] = { {"Sleep", (PyCFunction)PySFML_Sleep, METH_O, "Sleep(Duration)\nMake the current thread sleep for a given time.\n Duration : Time to sleep, in seconds"}, {NULL} /* Sentinel */ -}; +}; +#ifdef IS_PY3K +#define INITERROR return NULL +static PyModuleDef module_def = { + PyModuleDef_HEAD_INIT, + "noddy", + "Example module that creates an extension type.", + -1, + module_methods, NULL, NULL, NULL, NULL +}; + +PyObject * +PyInit_sf(void) +#else +#define INITERROR return + #ifndef PyMODINIT_FUNC /* declarations for DLL import/export */ #define PyMODINIT_FUNC void #endif -PyMODINIT_FUNC -initsf(void) +PyMODINIT_FUNC +initsf(void) +#endif { PyObject *m; if (PyType_Ready(&PySfClockType) < 0) - return; + INITERROR; if (PyType_Ready(&PySfWindowType) < 0) - return; + INITERROR; if (PyType_Ready(&PySfWindowSettingsType) < 0) - return; + INITERROR; if (PyType_Ready(&PySfStyleType) < 0) - return; + INITERROR; if (PyType_Ready(&PySfRenderTargetType) < 0) - return; + INITERROR; if (PyType_Ready(&PySfRenderWindowType) < 0) - return; + INITERROR; if (PyType_Ready(&PySfVideoModeType) < 0) - return; + INITERROR; if (PyType_Ready(&PySfViewType) < 0) - return; + INITERROR; if (PyType_Ready(&PySfInputType) < 0) - return; + INITERROR; if (PyType_Ready(&PySfEventType) < 0) - return; + INITERROR; if (PyType_Ready(&PySfEventTextType) < 0) - return; + INITERROR; if (PyType_Ready(&PySfEventKeyType) < 0) - return; + INITERROR; if (PyType_Ready(&PySfEventMouseMoveType) < 0) - return; + INITERROR; if (PyType_Ready(&PySfEventMouseButtonType) < 0) - return; + INITERROR; if (PyType_Ready(&PySfEventMouseWheelType) < 0) - return; + INITERROR; if (PyType_Ready(&PySfEventJoyMoveType) < 0) - return; + INITERROR; if (PyType_Ready(&PySfEventJoyButtonType) < 0) - return; + INITERROR; if (PyType_Ready(&PySfEventSizeType) < 0) - return; + INITERROR; if (PyType_Ready(&PySfKeyType) < 0) - return; + INITERROR; if (PyType_Ready(&PySfJoyType) < 0) - return; + INITERROR; if (PyType_Ready(&PySfMouseType) < 0) - return; + INITERROR; if (PyType_Ready(&PySfDrawableType) < 0) - return; + INITERROR; if (PyType_Ready(&PySfBlendType) < 0) - return; + INITERROR; if (PyType_Ready(&PySfSpriteType) < 0) - return; + INITERROR; if (PyType_Ready(&PySfFontType) < 0) - return; + INITERROR; if (PyType_Ready(&PySfGlyphType) < 0) - return; + INITERROR; if (PyType_Ready(&PySfStringType) < 0) - return; + INITERROR; if (PyType_Ready(&PySfPostFXType) < 0) - return; + INITERROR; if (PyType_Ready(&PySfImageType) < 0) - return; + INITERROR; if (PyType_Ready(&PySfShapeType) < 0) - return; + INITERROR; if (PyType_Ready(&PySfColorType) < 0) - return; + INITERROR; if (PyType_Ready(&PySfIntRectType) < 0) - return; + INITERROR; if (PyType_Ready(&PySfFloatRectType) < 0) - return; + INITERROR; if (PyType_Ready(&PySfMusicType) < 0) - return; + INITERROR; if (PyType_Ready(&PySfSoundType) < 0) - return; + INITERROR; if (PyType_Ready(&PySfSoundBufferType) < 0) - return; + INITERROR; if (PyType_Ready(&PySfSoundBufferRecorderType) < 0) - return; + INITERROR; if (PyType_Ready(&PySfSoundRecorderType) < 0) - return; + INITERROR; if (PyType_Ready(&PySfSoundStreamType) < 0) - return; + INITERROR; if (PyType_Ready(&PySfListenerType) < 0) - return; - - m = Py_InitModule3("sf", module_methods, "Python binding for sfml (Simple Fast Media Library)"); + INITERROR; + +#ifdef IS_PY3K + m = PyModule_Create(&module_def); +#else + m = Py_InitModule3("sf", module_methods, "Python binding for sfml (Simple Fast Media Library)"); +#endif if (m == NULL) - return; + INITERROR; Py_INCREF(&PySfClockType); PyModule_AddObject(m, "Clock", (PyObject *)&PySfClockType); @@ -274,6 +296,10 @@ initsf(void) PySfBlend_InitConst(); PySfSound_InitConst(); PySfSoundStream_InitConst(); - PySfString_InitConst(); + PySfString_InitConst(); + +#ifdef IS_PY3K + return m; +#endif } From af3dd7c63008854cbfa2600cc2636541aa246006 Mon Sep 17 00:00:00 2001 From: remi-k Date: Thu, 26 Feb 2009 12:36:06 +0000 Subject: [PATCH 10/22] More code clean-up and python3 compliance git-svn-id: https://sfml.svn.sourceforge.net/svnroot/sfml/trunk@1022 4e206d99-4929-0410-ac5d-dfc041789085 --- python/src/Blend.cpp | 56 ++--------- python/src/Blend.hpp | 8 ++ python/src/Font.cpp | 21 ++--- python/src/Font.hpp | 6 +- python/src/Glyph.cpp | 21 ++--- python/src/Glyph.hpp | 6 +- python/src/Image.cpp | 32 +------ python/src/Joy.cpp | 62 +++--------- python/src/Joy.hpp | 8 ++ python/src/Listener.cpp | 38 ++------ python/src/Listener.hpp | 6 +- python/src/Mouse.cpp | 58 +++--------- python/src/Mouse.hpp | 8 ++ python/src/PostFX.cpp | 23 +---- python/src/Shape.cpp | 45 +++------ python/src/Shape.hpp | 6 +- python/src/Sound.cpp | 55 ++++------- python/src/Sound.hpp | 6 +- python/src/SoundBuffer.cpp | 59 +++++------- python/src/SoundBuffer.hpp | 6 +- python/src/SoundBufferRecorder.cpp | 24 ++--- python/src/SoundBufferRecorder.hpp | 6 +- python/src/SoundRecorder.cpp | 61 ++++++------ python/src/SoundRecorder.hpp | 6 +- python/src/SoundStream.cpp | 62 ++++++------ python/src/SoundStream.hpp | 3 +- python/src/String.cpp | 37 ++++---- python/src/String.hpp | 6 +- python/src/VideoMode.cpp | 20 ++-- python/src/VideoMode.hpp | 8 +- python/src/View.cpp | 24 ++--- python/src/View.hpp | 8 +- python/src/Window.cpp | 145 ++++++++--------------------- python/src/Window.hpp | 10 +- python/src/WindowSettings.cpp | 21 ++--- python/src/WindowSettings.hpp | 6 +- python/src/WindowStyle.cpp | 59 +++--------- python/src/WindowStyle.hpp | 8 ++ python/src/compat.hpp | 27 ++++++ python/src/main.cpp | 7 +- 40 files changed, 364 insertions(+), 714 deletions(-) diff --git a/python/src/Blend.cpp b/python/src/Blend.cpp index 7398e4621..dc43ca5c6 100644 --- a/python/src/Blend.cpp +++ b/python/src/Blend.cpp @@ -22,62 +22,26 @@ // //////////////////////////////////////////////////////////// -#include - -#include -#include - #include "Blend.hpp" +#include "compat.hpp" -typedef struct { - PyObject_HEAD -} PySfBlend; - - - -static PyMemberDef PySfBlend_members[] = { - {NULL} /* Sentinel */ -}; - - -static void -PySfBlend_dealloc(PySfBlend *self) -{ - self->ob_type->tp_free((PyObject*)self); -} static PyObject * PySfBlend_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { PySfBlend *self; - self = (PySfBlend *)type->tp_alloc(type, 0); - if (self != NULL) - { - } - return (PyObject *)self; } -static int -PySfBlend_init(PySfBlend *self, PyObject *args, PyObject *kwds) -{ - return 0; -} - -static PyMethodDef PySfBlend_methods[] = { - {NULL} /* Sentinel */ -}; - PyTypeObject PySfBlendType = { - PyObject_HEAD_INIT(NULL) - 0, /*ob_size*/ + head_init "Blend", /*tp_name*/ sizeof(PySfBlend), /*tp_basicsize*/ 0, /*tp_itemsize*/ - (destructor)PySfBlend_dealloc, /*tp_dealloc*/ + 0, /*tp_dealloc*/ 0, /*tp_print*/ 0, /*tp_getattr*/ 0, /*tp_setattr*/ @@ -104,15 +68,15 @@ None No blending.", /* tp_doc */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ - PySfBlend_methods, /* tp_methods */ - PySfBlend_members, /* tp_members */ + 0, /* 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 */ - (initproc)PySfBlend_init, /* tp_init */ + 0, /* tp_init */ 0, /* tp_alloc */ PySfBlend_new, /* tp_new */ }; @@ -120,16 +84,16 @@ None No blending.", /* tp_doc */ void PySfBlend_InitConst() { PyObject *obj; - obj = PyInt_FromLong(sf::Blend::Alpha); + obj = PyLong_FromLong(sf::Blend::Alpha); PyDict_SetItemString(PySfBlendType.tp_dict, "Alpha", obj); Py_DECREF(obj); - obj = PyInt_FromLong(sf::Blend::Add); + obj = PyLong_FromLong(sf::Blend::Add); PyDict_SetItemString(PySfBlendType.tp_dict, "Add", obj); Py_DECREF(obj); - obj = PyInt_FromLong(sf::Blend::Multiply); + obj = PyLong_FromLong(sf::Blend::Multiply); PyDict_SetItemString(PySfBlendType.tp_dict, "Multiply", obj); Py_DECREF(obj); - obj = PyInt_FromLong(sf::Blend::None); + obj = PyLong_FromLong(sf::Blend::None); PyDict_SetItemString(PySfBlendType.tp_dict, "None", obj); Py_DECREF(obj); } diff --git a/python/src/Blend.hpp b/python/src/Blend.hpp index e47ed9c53..f61087369 100644 --- a/python/src/Blend.hpp +++ b/python/src/Blend.hpp @@ -25,6 +25,14 @@ #ifndef __PYBLEND_HPP #define __PYBLEND_HPP +#include + +#include + +typedef struct { + PyObject_HEAD +} PySfBlend; + void PySfBlend_InitConst(); diff --git a/python/src/Font.cpp b/python/src/Font.cpp index e9abe5527..c6f49860d 100644 --- a/python/src/Font.cpp +++ b/python/src/Font.cpp @@ -25,10 +25,7 @@ #include "Font.hpp" #include "Glyph.hpp" -static PyMemberDef PySfFont_members[] = { - {NULL} /* Sentinel */ -}; - +#include "compat.hpp" static void @@ -36,21 +33,16 @@ PySfFont_dealloc(PySfFont *self) { if (self->Owner) delete self->obj; - self->ob_type->tp_free((PyObject*)self); + free_object(self); } static PyObject * PySfFont_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { PySfFont *self; - self = (PySfFont *)type->tp_alloc(type, 0); - if (self != NULL) - { self->Owner = true; - } - return (PyObject *)self; } @@ -71,7 +63,7 @@ PySfFont_LoadFromFile(PySfFont* self, PyObject *args, PyObject *kwds) int CharsetSize; bool Result; - if (! PyArg_ParseTupleAndKeywords(args, kwds, "s|Is#", (char **)kwlist, &Filename, &Charsize, &CharsetTmp, &CharsetSize)) + if (! PyArg_ParseTupleAndKeywords(args, kwds, "s|Is#:Font.LoadFromFile", (char **)kwlist, &Filename, &Charsize, &CharsetTmp, &CharsetSize)) return NULL; if (CharsetTmp) @@ -100,7 +92,7 @@ PySfFont_LoadFromMemory(PySfFont* self, PyObject *args, PyObject *kwds) int CharsetSize; bool Result; - if (! PyArg_ParseTupleAndKeywords(args, kwds, "s#|Is#", (char **)kwlist, &Data, &Size, &Charsize, &CharsetTmp, &CharsetSize)) + if (! PyArg_ParseTupleAndKeywords(args, kwds, "s#|Is#:Font.LoadFromMemory", (char **)kwlist, &Data, &Size, &Charsize, &CharsetTmp, &CharsetSize)) return NULL; if (CharsetTmp) @@ -169,8 +161,7 @@ Get the description of a glyph (character) given by its unicode value. Returns g PyTypeObject PySfFontType = { - PyObject_HEAD_INIT(NULL) - 0, /*ob_size*/ + head_init "Font", /*tp_name*/ sizeof(PySfFont), /*tp_basicsize*/ 0, /*tp_itemsize*/ @@ -198,7 +189,7 @@ PyTypeObject PySfFontType = { 0, /* tp_iter */ 0, /* tp_iternext */ PySfFont_methods, /* tp_methods */ - PySfFont_members, /* tp_members */ + 0, /* tp_members */ 0, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ diff --git a/python/src/Font.hpp b/python/src/Font.hpp index a7851a463..a8105504b 100644 --- a/python/src/Font.hpp +++ b/python/src/Font.hpp @@ -25,13 +25,9 @@ #ifndef __PYFONT_HPP #define __PYFONT_HPP -#include -#include - #include -#include -#include "offsetof.hpp" +#include typedef struct { diff --git a/python/src/Glyph.cpp b/python/src/Glyph.cpp index 21c93a344..2f82b058f 100644 --- a/python/src/Glyph.cpp +++ b/python/src/Glyph.cpp @@ -24,6 +24,12 @@ #include "Glyph.hpp" +#include + +#include "offsetof.hpp" +#include "compat.hpp" + + static PyMemberDef PySfGlyph_members[] = { {(char *)"Advance", T_INT, offsetof(PySfGlyph, Advance), 0, (char *)"Offset to move horizontically to the next character."}, {(char *)"Rectangle", T_OBJECT, offsetof(PySfGlyph, Rectangle), 0, (char *)"Bounding rectangle of the glyph, in relative coordinates."}, @@ -32,7 +38,6 @@ static PyMemberDef PySfGlyph_members[] = { }; - static void PySfGlyph_dealloc(PySfGlyph *self) { @@ -41,7 +46,7 @@ PySfGlyph_dealloc(PySfGlyph *self) self->TexCoords->obj = new sf::FloatRect(self->obj->TexCoords); Py_DECREF(self->TexCoords); delete self->obj; - self->ob_type->tp_free((PyObject*)self); + free_object(self); } void @@ -80,16 +85,13 @@ static PyObject * PySfGlyph_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { PySfGlyph *self; - self = (PySfGlyph *)type->tp_alloc(type, 0); - if (self != NULL) { self->Advance = 0; self->Rectangle = GetNewPySfIntRect(); self->TexCoords = GetNewPySfFloatRect(); } - return (PyObject *)self; } @@ -103,14 +105,9 @@ PySfGlyph_init(PySfGlyph *self, PyObject *args, PyObject *kwds) return 0; } -static PyMethodDef PySfGlyph_methods[] = { - {NULL} /* Sentinel */ -}; - PyTypeObject PySfGlyphType = { - PyObject_HEAD_INIT(NULL) - 0, /*ob_size*/ + head_init "Glyph", /*tp_name*/ sizeof(PySfGlyph), /*tp_basicsize*/ 0, /*tp_itemsize*/ @@ -137,7 +134,7 @@ PyTypeObject PySfGlyphType = { 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ - PySfGlyph_methods, /* tp_methods */ + 0, /* tp_methods */ PySfGlyph_members, /* tp_members */ 0, /* tp_getset */ 0, /* tp_base */ diff --git a/python/src/Glyph.hpp b/python/src/Glyph.hpp index 0b35a8866..5b83575d8 100644 --- a/python/src/Glyph.hpp +++ b/python/src/Glyph.hpp @@ -25,13 +25,9 @@ #ifndef __PYGLYPH_HPP #define __PYGLYPH_HPP -#include -#include - #include -#include -#include "offsetof.hpp" +#include #include "Rect.hpp" diff --git a/python/src/Image.cpp b/python/src/Image.cpp index 9f8abe689..3d8b060e7 100644 --- a/python/src/Image.cpp +++ b/python/src/Image.cpp @@ -196,39 +196,13 @@ PySfImage_GetPixels(PySfImage *self) static PyObject * PySfImage_LoadFromFile (PySfImage *self, PyObject *args) { - char *path; -#ifdef IS_PY3K - PyObject *string = PyUnicode_AsUTF8String(args); - if (string == NULL) - return NULL; - path = PyBytes_AsString(string); -#else - path = PyString_AsString(args); -#endif - bool result = self->obj->LoadFromFile(path); -#ifdef IS_PY3K - Py_DECREF(string); -#endif - return PyBool_FromLong(result); + load_from_file(self, args); } static PyObject * PySfImage_SaveToFile (PySfImage *self, PyObject *args) { - char *path; -#ifdef IS_PY3K - PyObject *string = PyUnicode_AsUTF8String(args); - if (string == NULL) - return NULL; - path = PyBytes_AsString(string); -#else - path = PyString_AsString(args); -#endif - bool result = self->obj->SaveToFile(path); -#ifdef IS_PY3K - Py_DECREF(string); -#endif - return PyBool_FromLong(result); + save_to_file(self, args); } static int @@ -390,6 +364,7 @@ PySfImage_init(PySfImage *self, PyObject *args, PyObject *kwds) self->obj = new sf::Image(*(Image->obj)); return 0; } + else PyErr_Clear(); } self->obj = new sf::Image(); if (PyTuple_Size(args) > 0) @@ -400,6 +375,7 @@ PySfImage_init(PySfImage *self, PyObject *args, PyObject *kwds) return -1; else if (PySfImage_LoadFromPixels(self, args) == NULL) return -1; + else PyErr_Clear(); } } return 0; diff --git a/python/src/Joy.cpp b/python/src/Joy.cpp index b43b29d64..7f20f68f3 100644 --- a/python/src/Joy.cpp +++ b/python/src/Joy.cpp @@ -22,62 +22,26 @@ // //////////////////////////////////////////////////////////// -#include - -#include -#include - #include "Joy.hpp" +#include "compat.hpp" -typedef struct { - PyObject_HEAD -} PySfJoy; - - - -static PyMemberDef PySfJoy_members[] = { - {NULL} /* Sentinel */ -}; - - -static void -PySfJoy_dealloc(PySfJoy *self) -{ - self->ob_type->tp_free((PyObject*)self); -} static PyObject * PySfJoy_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { PySfJoy *self; - self = (PySfJoy *)type->tp_alloc(type, 0); - if (self != NULL) - { - } - return (PyObject *)self; } -static int -PySfJoy_init(PySfJoy *self, PyObject *args, PyObject *kwds) -{ - return 0; -} - -static PyMethodDef PySfJoy_methods[] = { - {NULL} /* Sentinel */ -}; - PyTypeObject PySfJoyType = { - PyObject_HEAD_INIT(NULL) - 0, /*ob_size*/ + head_init "Joy", /*tp_name*/ sizeof(PySfJoy), /*tp_basicsize*/ 0, /*tp_itemsize*/ - (destructor)PySfJoy_dealloc, /*tp_dealloc*/ + 0, /*tp_dealloc*/ 0, /*tp_print*/ 0, /*tp_getattr*/ 0, /*tp_setattr*/ @@ -100,15 +64,15 @@ PyTypeObject PySfJoyType = { 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ - PySfJoy_methods, /* tp_methods */ - PySfJoy_members, /* tp_members */ + 0, /* 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 */ - (initproc)PySfJoy_init, /* tp_init */ + 0, /* tp_init */ 0, /* tp_alloc */ PySfJoy_new, /* tp_new */ }; @@ -116,25 +80,25 @@ PyTypeObject PySfJoyType = { void PySfJoy_InitConst() { PyObject *obj; - obj = PyInt_FromLong(sf::Joy::AxisX); + obj = PyLong_FromLong(sf::Joy::AxisX); PyDict_SetItemString(PySfJoyType.tp_dict, "AxisX", obj); Py_DECREF(obj); - obj = PyInt_FromLong(sf::Joy::AxisY); + obj = PyLong_FromLong(sf::Joy::AxisY); PyDict_SetItemString(PySfJoyType.tp_dict, "AxisY", obj); Py_DECREF(obj); - obj = PyInt_FromLong(sf::Joy::AxisZ); + obj = PyLong_FromLong(sf::Joy::AxisZ); PyDict_SetItemString(PySfJoyType.tp_dict, "AxisZ", obj); Py_DECREF(obj); - obj = PyInt_FromLong(sf::Joy::AxisR); + obj = PyLong_FromLong(sf::Joy::AxisR); PyDict_SetItemString(PySfJoyType.tp_dict, "AxisR", obj); Py_DECREF(obj); - obj = PyInt_FromLong(sf::Joy::AxisU); + obj = PyLong_FromLong(sf::Joy::AxisU); PyDict_SetItemString(PySfJoyType.tp_dict, "AxisU", obj); Py_DECREF(obj); - obj = PyInt_FromLong(sf::Joy::AxisV); + obj = PyLong_FromLong(sf::Joy::AxisV); PyDict_SetItemString(PySfJoyType.tp_dict, "AxisV", obj); Py_DECREF(obj); - obj = PyInt_FromLong(sf::Joy::AxisPOV); + obj = PyLong_FromLong(sf::Joy::AxisPOV); PyDict_SetItemString(PySfJoyType.tp_dict, "AxisPOV", obj); Py_DECREF(obj); } diff --git a/python/src/Joy.hpp b/python/src/Joy.hpp index 14805ade9..6daf4bb38 100644 --- a/python/src/Joy.hpp +++ b/python/src/Joy.hpp @@ -25,6 +25,14 @@ #ifndef __PYJOY_HPP #define __PYJOY_HPP +#include + +#include + +typedef struct { + PyObject_HEAD +} PySfJoy; + void PySfJoy_InitConst(); diff --git a/python/src/Listener.cpp b/python/src/Listener.cpp index 5a56143d2..4f2f877e0 100644 --- a/python/src/Listener.cpp +++ b/python/src/Listener.cpp @@ -24,40 +24,17 @@ #include "Listener.hpp" +#include "compat.hpp" -static PyMemberDef PySfListener_members[] = { - {NULL} /* Sentinel */ -}; - - - -static void -PySfListener_dealloc(PySfListener* self) -{ - self->ob_type->tp_free((PyObject*)self); -} static PyObject * PySfListener_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { PySfListener *self; - self = (PySfListener *)type->tp_alloc(type, 0); - - if (self != NULL) - { - } - return (PyObject *)self; } -static int -PySfListener_init(PySfListener *self, PyObject *args, PyObject *kwds) -{ - return 0; -} - - static PyObject * PySfListener_SetGlobalVolume(PySfListener* self, PyObject *args) { @@ -75,7 +52,7 @@ static PyObject * PySfListener_SetPosition(PySfListener* self, PyObject *args) { float X, Y, Z; - if (! PyArg_ParseTuple(args, "fff", &X, &Y, &Z)) + if (!PyArg_ParseTuple(args, "fff:Listener.SetPosition", &X, &Y, &Z)) return NULL; sf::Listener::SetPosition(X, Y, Z); Py_RETURN_NONE; @@ -92,7 +69,7 @@ static PyObject * PySfListener_SetTarget(PySfListener* self, PyObject *args) { float X, Y, Z; - if (! PyArg_ParseTuple(args, "fff", &X, &Y, &Z)) + if (!PyArg_ParseTuple(args, "fff:Listener.SetTarget", &X, &Y, &Z)) return NULL; sf::Listener::SetTarget(X, Y, Z); Py_RETURN_NONE; @@ -116,12 +93,11 @@ static PyMethodDef PySfListener_methods[] = { }; PyTypeObject PySfListenerType = { - PyObject_HEAD_INIT(NULL) - 0, /*ob_size*/ + head_init "Listener", /*tp_name*/ sizeof(PySfListener), /*tp_basicsize*/ 0, /*tp_itemsize*/ - (destructor)PySfListener_dealloc, /*tp_dealloc*/ + 0, /*tp_dealloc*/ 0, /*tp_print*/ 0, /*tp_getattr*/ 0, /*tp_setattr*/ @@ -145,14 +121,14 @@ PyTypeObject PySfListenerType = { 0, /* tp_iter */ 0, /* tp_iternext */ PySfListener_methods, /* tp_methods */ - PySfListener_members, /* tp_members */ + 0, /* tp_members */ 0, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ - (initproc)PySfListener_init, /* tp_init */ + 0, /* tp_init */ 0, /* tp_alloc */ PySfListener_new, /* tp_new */ }; diff --git a/python/src/Listener.hpp b/python/src/Listener.hpp index 6cd72504d..123956b6b 100644 --- a/python/src/Listener.hpp +++ b/python/src/Listener.hpp @@ -25,13 +25,9 @@ #ifndef __PYLISTENER_HPP #define __PYLISTENER_HPP -#include -#include - #include -#include -#include "offsetof.hpp" +#include typedef struct { diff --git a/python/src/Mouse.cpp b/python/src/Mouse.cpp index 490e7e3ad..d0165efc2 100644 --- a/python/src/Mouse.cpp +++ b/python/src/Mouse.cpp @@ -22,62 +22,26 @@ // //////////////////////////////////////////////////////////// -#include - -#include -#include - #include "Mouse.hpp" +#include "compat.hpp" -typedef struct { - PyObject_HEAD -} PySfMouse; - - - -static PyMemberDef PySfMouse_members[] = { - {NULL} /* Sentinel */ -}; - - -static void -PySfMouse_dealloc(PySfMouse *self) -{ - self->ob_type->tp_free((PyObject*)self); -} static PyObject * PySfMouse_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { PySfMouse *self; - self = (PySfMouse *)type->tp_alloc(type, 0); - if (self != NULL) - { - } - return (PyObject *)self; } -static int -PySfMouse_init(PySfMouse *self, PyObject *args, PyObject *kwds) -{ - return 0; -} - -static PyMethodDef PySfMouse_methods[] = { - {NULL} /* Sentinel */ -}; - PyTypeObject PySfMouseType = { - PyObject_HEAD_INIT(NULL) - 0, /*ob_size*/ + head_init "Mouse", /*tp_name*/ sizeof(PySfMouse), /*tp_basicsize*/ 0, /*tp_itemsize*/ - (destructor)PySfMouse_dealloc, /*tp_dealloc*/ + 0, /*tp_dealloc*/ 0, /*tp_print*/ 0, /*tp_getattr*/ 0, /*tp_setattr*/ @@ -100,15 +64,15 @@ PyTypeObject PySfMouseType = { 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ - PySfMouse_methods, /* tp_methods */ - PySfMouse_members, /* tp_members */ + 0, /* 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 */ - (initproc)PySfMouse_init, /* tp_init */ + 0, /* tp_init */ 0, /* tp_alloc */ PySfMouse_new, /* tp_new */ }; @@ -116,19 +80,19 @@ PyTypeObject PySfMouseType = { void PySfMouse_InitConst() { PyObject *obj; - obj = PyInt_FromLong(sf::Mouse::Left); + obj = PyLong_FromLong(sf::Mouse::Left); PyDict_SetItemString(PySfMouseType.tp_dict, "Left", obj); Py_DECREF(obj); - obj = PyInt_FromLong(sf::Mouse::Right); + obj = PyLong_FromLong(sf::Mouse::Right); PyDict_SetItemString(PySfMouseType.tp_dict, "Right", obj); Py_DECREF(obj); - obj = PyInt_FromLong(sf::Mouse::Middle); + obj = PyLong_FromLong(sf::Mouse::Middle); PyDict_SetItemString(PySfMouseType.tp_dict, "Middle", obj); Py_DECREF(obj); - obj = PyInt_FromLong(sf::Mouse::XButton1); + obj = PyLong_FromLong(sf::Mouse::XButton1); PyDict_SetItemString(PySfMouseType.tp_dict, "XButton1", obj); Py_DECREF(obj); - obj = PyInt_FromLong(sf::Mouse::XButton2); + obj = PyLong_FromLong(sf::Mouse::XButton2); PyDict_SetItemString(PySfMouseType.tp_dict, "XButton2", obj); Py_DECREF(obj); } diff --git a/python/src/Mouse.hpp b/python/src/Mouse.hpp index 0876840f9..3e0ca33a3 100644 --- a/python/src/Mouse.hpp +++ b/python/src/Mouse.hpp @@ -25,6 +25,14 @@ #ifndef __PYMOUSE_HPP #define __PYMOUSE_HPP +#include + +#include + +typedef struct { + PyObject_HEAD +} PySfMouse; + void PySfMouse_InitConst(); diff --git a/python/src/PostFX.cpp b/python/src/PostFX.cpp index 5962972a7..739920308 100644 --- a/python/src/PostFX.cpp +++ b/python/src/PostFX.cpp @@ -51,35 +51,22 @@ PySfPostFX_new(PyTypeObject *type, PyObject *args, PyObject *kwds) static PyObject * PySfPostFX_LoadFromFile (PySfPostFX *self, PyObject *args) { - char *path; -#ifdef IS_PY3K - PyObject *string = PyUnicode_AsUTF8String(args); - if (string == NULL) - return NULL; - path = PyBytes_AsString(string); -#else - path = PyString_AsString(args); -#endif - bool result = self->obj->LoadFromFile(path); -#ifdef IS_PY3K - Py_DECREF(string); -#endif - return PyBool_FromLong(result); + load_from_file(self, args); } static PyObject * PySfPostFX_LoadFromMemory (PySfPostFX *self, PyObject *args) { - char *path; + char *effect; #ifdef IS_PY3K PyObject *string = PyUnicode_AsUTF8String(args); if (string == NULL) return NULL; - path = PyBytes_AsString(string); + effect = PyBytes_AsString(string); #else - path = PyString_AsString(args); + effect = PyString_AsString(args); #endif - bool result = self->obj->LoadFromMemory(path); + bool result = self->obj->LoadFromMemory(effect); #ifdef IS_PY3K Py_DECREF(string); #endif diff --git a/python/src/Shape.cpp b/python/src/Shape.cpp index 622e0f90e..fc4142cdf 100644 --- a/python/src/Shape.cpp +++ b/python/src/Shape.cpp @@ -27,33 +27,24 @@ #include #include "Color.hpp" +#include "compat.hpp" + extern PyTypeObject PySfColorType; extern PyTypeObject PySfDrawableType; -static PyMemberDef PySfShape_members[] = { - {NULL} /* Sentinel */ -}; - - static void PySfShape_dealloc(PySfShape* self) { delete self->obj; - self->ob_type->tp_free((PyObject*)self); + free_object(self); } static PyObject * PySfShape_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { PySfShape *self; - self = (PySfShape *)type->tp_alloc(type, 0); - - if (self != NULL) - { - } - return (PyObject *)self; } @@ -64,7 +55,6 @@ PySfShape_init(PySfShape *self, PyObject *args) return 0; } - // void AddPoint(float X, float Y, const Color& Col = Color(255, 255, 255), const Color& OutlineCol = Color(0, 0, 0)); static PyObject * PySfShape_AddPoint(PySfShape* self, PyObject *args, PyObject *kwds) @@ -73,7 +63,7 @@ PySfShape_AddPoint(PySfShape* self, PyObject *args, PyObject *kwds) float X, Y; sf::Color *Col, *OutlineCol; PySfColor *ColTmp=NULL, *OutlineColTmp=NULL; - if (!PyArg_ParseTupleAndKeywords(args, kwds, "ff|O!O!", (char **)kwlist, &X, &Y, &PySfColorType, &ColTmp, &PySfColorType, &OutlineColTmp)) + if (!PyArg_ParseTupleAndKeywords(args, kwds, "ff|O!O!:Shape.AddPoint", (char **)kwlist, &X, &Y, &PySfColorType, &ColTmp, &PySfColorType, &OutlineColTmp)) return NULL; if (ColTmp) @@ -119,7 +109,7 @@ PySfShape_Line(PySfShape* self, PyObject *args, PyObject *kwds) float X0, Y0, X1, Y1, Thickness, Outline = 0.f; sf::Color *OutlineCol; PySfColor *ColTmp, *OutlineColTmp=NULL; - if (!PyArg_ParseTupleAndKeywords(args, kwds, "fffffO!|fO!", (char **)kwlist, &X0, &Y0, &X1, &Y1, &Thickness, &PySfColorType, &ColTmp, &Outline, &PySfColorType, &OutlineColTmp)) + if (!PyArg_ParseTupleAndKeywords(args, kwds, "fffffO!|fO!:Shape.Line", (char **)kwlist, &X0, &Y0, &X1, &Y1, &Thickness, &PySfColorType, &ColTmp, &Outline, &PySfColorType, &OutlineColTmp)) return NULL; if (OutlineColTmp) { @@ -143,7 +133,7 @@ PySfShape_Rectangle(PySfShape* self, PyObject *args, PyObject *kwds) float X0, Y0, X1, Y1, Outline = 0.f; sf::Color *OutlineCol; PySfColor *ColTmp, *OutlineColTmp=NULL; - if (!PyArg_ParseTupleAndKeywords(args, kwds, "ffffO!|fO!", (char **)kwlist, &X0, &Y0, &X1, &Y1, &PySfColorType, &ColTmp, &Outline, &PySfColorType, &OutlineColTmp)) + if (!PyArg_ParseTupleAndKeywords(args, kwds, "ffffO!|fO!:Shape.Rectangle", (char **)kwlist, &X0, &Y0, &X1, &Y1, &PySfColorType, &ColTmp, &Outline, &PySfColorType, &OutlineColTmp)) return NULL; if (OutlineColTmp) { @@ -167,7 +157,7 @@ PySfShape_Circle(PySfShape* self, PyObject *args, PyObject *kwds) float X, Y, Radius, Outline = 0.f; sf::Color *OutlineCol; PySfColor *ColTmp, *OutlineColTmp=NULL; - if (!PyArg_ParseTupleAndKeywords(args, kwds, "fffO!|fO!", (char **)kwlist, &X, &Y, &Radius, &PySfColorType, &ColTmp, &Outline, &PySfColorType, &OutlineColTmp)) + if (!PyArg_ParseTupleAndKeywords(args, kwds, "fffO!|fO!:Shape.Circle", (char **)kwlist, &X, &Y, &Radius, &PySfColorType, &ColTmp, &Outline, &PySfColorType, &OutlineColTmp)) return NULL; if (OutlineColTmp) { @@ -218,7 +208,7 @@ PySfShape_SetPointPosition(PySfShape* self, PyObject *args) { unsigned int Index; float X, Y; - if (!PyArg_ParseTuple(args, "Iff", &Index, &X, &Y)) + if (!PyArg_ParseTuple(args, "Iff:Shape.SetPointPosition", &Index, &X, &Y)) return NULL; self->obj->SetPointPosition(Index, X, Y); Py_RETURN_NONE; @@ -229,7 +219,7 @@ PySfShape_SetPointColor(PySfShape* self, PyObject *args) { unsigned int Index; PySfColor *Color; - if (!PyArg_ParseTuple(args, "IO!", &Index, &PySfColorType, &Color)) + if (!PyArg_ParseTuple(args, "IO!:Shape.SetPointColor", &Index, &PySfColorType, &Color)) return NULL; PySfColorUpdate(Color); self->obj->SetPointColor(Index, *(Color->obj)); @@ -241,7 +231,7 @@ PySfShape_SetPointOutlineColor(PySfShape* self, PyObject *args) { unsigned int Index; PySfColor *Color; - if (!PyArg_ParseTuple(args, "IO!", &Index, &PySfColorType, &Color)) + if (!PyArg_ParseTuple(args, "IO!:Shape:SetPointOutlineColor", &Index, &PySfColorType, &Color)) return NULL; PySfColorUpdate(Color); self->obj->SetPointOutlineColor(Index, *(Color->obj)); @@ -257,20 +247,14 @@ PySfShape_GetNbPoints(PySfShape* self, PyObject *args) static PyObject * PySfShape_EnableFill(PySfShape* self, PyObject *args) { - if (PyObject_IsTrue(args)) - self->obj->EnableFill(true); - else - self->obj->EnableFill(false); + self->obj->EnableFill(PyBool_AsBool(args)); Py_RETURN_NONE; } static PyObject * PySfShape_EnableOutline(PySfShape* self, PyObject *args) { - if (PyObject_IsTrue(args)) - self->obj->EnableOutline(true); - else - self->obj->EnableOutline(false); + self->obj->EnableOutline(PyBool_AsBool(args)); Py_RETURN_NONE; } @@ -346,8 +330,7 @@ Create a shape made of a single circle.\n\ PyTypeObject PySfShapeType = { - PyObject_HEAD_INIT(NULL) - 0, /*ob_size*/ + head_init "Shape", /*tp_name*/ sizeof(PySfShape), /*tp_basicsize*/ 0, /*tp_itemsize*/ @@ -375,7 +358,7 @@ PyTypeObject PySfShapeType = { 0, /* tp_iter */ 0, /* tp_iternext */ PySfShape_methods, /* tp_methods */ - PySfShape_members, /* tp_members */ + 0, /* tp_members */ 0, /* tp_getset */ &PySfDrawableType, /* tp_base */ 0, /* tp_dict */ diff --git a/python/src/Shape.hpp b/python/src/Shape.hpp index 05bab545b..ee2d2ce1c 100644 --- a/python/src/Shape.hpp +++ b/python/src/Shape.hpp @@ -25,13 +25,9 @@ #ifndef __PYSHAPE_HPP #define __PYSHAPE_HPP -#include -#include - #include -#include -#include "offsetof.hpp" +#include typedef struct { diff --git a/python/src/Sound.cpp b/python/src/Sound.cpp index d755d4485..494d7fb43 100644 --- a/python/src/Sound.cpp +++ b/python/src/Sound.cpp @@ -23,33 +23,26 @@ //////////////////////////////////////////////////////////// #include "Sound.hpp" - #include "SoundBuffer.hpp" -extern PyTypeObject PySfSoundBufferType; +#include "compat.hpp" -static PyMemberDef PySfSound_members[] = { - {NULL} /* Sentinel */ -}; + +extern PyTypeObject PySfSoundBufferType; static void PySfSound_dealloc(PySfSound *self) { delete self->obj; - self->ob_type->tp_free((PyObject*)self); + free_object(self); } static PyObject * PySfSound_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { PySfSound *self; - self = (PySfSound *)type->tp_alloc(type, 0); - if (self != NULL) - { - } - return (PyObject *)self; } @@ -61,21 +54,17 @@ static PyObject* PySfSound_SetBuffer(PySfSound *self, PyObject *args) { PySfSoundBuffer *Buffer = (PySfSoundBuffer *)args; - if ( ! PyObject_TypeCheck(args, &PySfSoundBufferType)) - PyErr_SetString(PyExc_TypeError, "The argument must be a sfSoundBuffer."); + if (!PyObject_TypeCheck(args, &PySfSoundBufferType)) + PyErr_SetString(PyExc_TypeError, "Sound.SetBuffer() The argument must be a sf.SoundBuffer."); self->obj->SetBuffer(*(Buffer->obj)); - Py_RETURN_NONE; } static PyObject* PySfSound_SetLoop(PySfSound *self, PyObject *args) { - if (PyObject_IsTrue(args)) - self->obj->SetLoop(true); - else - self->obj->SetLoop(false); + self->obj->SetLoop(PyBool_AsBool(args)); Py_RETURN_NONE; } @@ -147,10 +136,7 @@ PySfSound_GetPlayingOffset(PySfSound *self) static PyObject* PySfSound_GetLoop(PySfSound *self) { - if (self->obj->GetLoop()) - Py_RETURN_TRUE; - else - Py_RETURN_FALSE; + return PyBool_FromLong(self->obj->GetLoop()); } static PyObject* @@ -184,7 +170,7 @@ static PyObject* PySfSound_SetPosition(PySfSound *self, PyObject *args) { float X, Y, Z; - if (! PyArg_ParseTuple(args, "fff", &X, &Y, &Z)) + if (!PyArg_ParseTuple(args, "fff:Sound.SetPosition", &X, &Y, &Z)) return NULL; self->obj->SetPosition(X, Y, Z); Py_RETURN_NONE; @@ -233,8 +219,7 @@ static PyMethodDef PySfSound_methods[] = { }; PyTypeObject PySfSoundType = { - PyObject_HEAD_INIT(NULL) - 0, /*ob_size*/ + head_init "Sound", /*tp_name*/ sizeof(PySfSound), /*tp_basicsize*/ 0, /*tp_itemsize*/ @@ -272,7 +257,7 @@ Copy constructor : Sound(Copy) where Copy is a sf.Sound instance.", /* tp_doc */ 0, /* tp_iter */ 0, /* tp_iternext */ PySfSound_methods, /* tp_methods */ - PySfSound_members, /* tp_members */ + 0, /* tp_members */ 0, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ @@ -286,9 +271,7 @@ Copy constructor : Sound(Copy) where Copy is a sf.Sound instance.", /* tp_doc */ static int PySfSound_init(PySfSound *self, PyObject *args, PyObject *kwds) -{ -// Sound(const 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); - +{ const char *kwlist[] = {"Buffer", "Loop", "Pitch", "Volume", "X", "Y", "Z", NULL}; PySfSoundBuffer *Buffer=NULL; bool Loop=false; @@ -298,19 +281,17 @@ PySfSound_init(PySfSound *self, PyObject *args, PyObject *kwds) if (PyTuple_Size(args) == 1) { PySfSound *Copy; - if (PyArg_ParseTuple(args, "O!", &PySfSoundType, &Copy)) + if (PyArg_ParseTuple(args, "O!:Sound.__init__", &PySfSoundType, &Copy)) { self->obj = new sf::Sound(*(Copy->obj)); return 0; } - else - PyErr_Clear(); + else PyErr_Clear(); } if (PyTuple_Size(args) > 0) { - if ( !PyArg_ParseTupleAndKeywords(args, kwds, "O!|Offfff", (char **)kwlist, &PySfSoundBufferType, &Buffer, &LoopObj, &Pitch, &Volume, &X, &Y, &Z)) + if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!|Offfff:Sound.__init__", (char **)kwlist, &PySfSoundBufferType, &Buffer, &LoopObj, &Pitch, &Volume, &X, &Y, &Z)) return -1; - if (PyObject_IsTrue(LoopObj)) Loop = true; @@ -326,13 +307,13 @@ void PySfSound_InitConst() { PyObject *obj; - obj = PyInt_FromLong(sf::Sound::Stopped); + obj = PyLong_FromLong(sf::Sound::Stopped); PyDict_SetItemString(PySfSoundType.tp_dict, "Stopped", obj); Py_DECREF(obj); - obj = PyInt_FromLong(sf::Sound::Paused); + obj = PyLong_FromLong(sf::Sound::Paused); PyDict_SetItemString(PySfSoundType.tp_dict, "Paused", obj); Py_DECREF(obj); - obj = PyInt_FromLong(sf::Sound::Playing); + obj = PyLong_FromLong(sf::Sound::Playing); PyDict_SetItemString(PySfSoundType.tp_dict, "Playing", obj); Py_DECREF(obj); } diff --git a/python/src/Sound.hpp b/python/src/Sound.hpp index d0c38230a..4992a5d7f 100644 --- a/python/src/Sound.hpp +++ b/python/src/Sound.hpp @@ -25,11 +25,9 @@ #ifndef __PYSOUND_HPP #define __PYSOUND_HPP -#include -#include - #include -#include + +#include typedef struct { PyObject_HEAD diff --git a/python/src/SoundBuffer.cpp b/python/src/SoundBuffer.cpp index 2d0fd5522..e3c95238c 100644 --- a/python/src/SoundBuffer.cpp +++ b/python/src/SoundBuffer.cpp @@ -24,29 +24,21 @@ #include "SoundBuffer.hpp" - -static PyMemberDef PySfSoundBuffer_members[] = { - {NULL} /* Sentinel */ -}; +#include "compat.hpp" static void PySfSoundBuffer_dealloc(PySfSoundBuffer *self) { delete self->obj; - self->ob_type->tp_free((PyObject*)self); + free_object(self); } static PyObject * PySfSoundBuffer_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { PySfSoundBuffer *self; - self = (PySfSoundBuffer *)type->tp_alloc(type, 0); - if (self != NULL) - { - } - return (PyObject *)self; } @@ -56,11 +48,7 @@ PySfSoundBuffer_init(PySfSoundBuffer *self, PyObject *args, PyObject *kwds); static PyObject* PySfSoundBuffer_LoadFromFile(PySfSoundBuffer *self, PyObject *args) { - char *path = PyString_AsString(args); - if (self->obj->LoadFromFile(path)) - Py_RETURN_TRUE; - else - Py_RETURN_FALSE; + load_from_file(self, args); } static PyObject * @@ -69,13 +57,10 @@ PySfSoundBuffer_LoadFromMemory(PySfSoundBuffer* self, PyObject *args) unsigned int SizeInBytes; char *Data; - if (! PyArg_ParseTuple(args, "s#", &Data, &SizeInBytes)) + if (!PyArg_ParseTuple(args, "s#:SoundBuffer.LoadFromMemory", &Data, &SizeInBytes)) return NULL; - if (self->obj->LoadFromMemory(Data, (std::size_t) SizeInBytes)) - Py_RETURN_TRUE; - else - Py_RETURN_FALSE; + return PyBool_FromLong(self->obj->LoadFromMemory(Data, (std::size_t) SizeInBytes)); } static PyObject * @@ -84,29 +69,26 @@ PySfSoundBuffer_LoadFromSamples(PySfSoundBuffer* self, PyObject *args) unsigned int SizeInBytes, ChannelsCount, SampleRate; char *Data; - if (! PyArg_ParseTuple(args, "s#II", &Data, &SizeInBytes, &ChannelsCount, &SampleRate)) + if (!PyArg_ParseTuple(args, "s#II:SoundBuffer.LoadFromSamples", &Data, &SizeInBytes, &ChannelsCount, &SampleRate)) return NULL; - if (self->obj->LoadFromSamples((const sf::Int16*)Data, (std::size_t) SizeInBytes/2, ChannelsCount, SampleRate)) - Py_RETURN_TRUE; - else - Py_RETURN_FALSE; + return PyBool_FromLong(self->obj->LoadFromSamples((const sf::Int16*)Data, (std::size_t) SizeInBytes/2, ChannelsCount, SampleRate)); } static PyObject* PySfSoundBuffer_GetSamples(PySfSoundBuffer *self) { +#ifdef IS_PY3K + return PyBytes_FromStringAndSize((const char *)(self->obj->GetSamples()), self->obj->GetSamplesCount()*2); +#else return PyString_FromStringAndSize((const char *)(self->obj->GetSamples()), self->obj->GetSamplesCount()*2); +#endif } static PyObject* PySfSoundBuffer_SaveToFile(PySfSoundBuffer *self, PyObject *args) { - char *path = PyString_AsString(args); - if (self->obj->SaveToFile(path)) - Py_RETURN_TRUE; - else - Py_RETURN_FALSE; + save_to_file(self, args); } static PyObject* @@ -151,8 +133,7 @@ static PyMethodDef PySfSoundBuffer_methods[] = { }; PyTypeObject PySfSoundBufferType = { - PyObject_HEAD_INIT(NULL) - 0, /*ob_size*/ + head_init "SoundBuffer", /*tp_name*/ sizeof(PySfSoundBuffer), /*tp_basicsize*/ 0, /*tp_itemsize*/ @@ -182,7 +163,7 @@ Copy constructor : SoundBuffer(Copy) where Copy is a sf.SoundBuffer instance.", 0, /* tp_iter */ 0, /* tp_iternext */ PySfSoundBuffer_methods, /* tp_methods */ - PySfSoundBuffer_members, /* tp_members */ + 0, /* tp_members */ 0, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ @@ -197,16 +178,18 @@ Copy constructor : SoundBuffer(Copy) where Copy is a sf.SoundBuffer instance.", static int PySfSoundBuffer_init(PySfSoundBuffer *self, PyObject *args, PyObject *kwds) { - if (PyTuple_Size(args) == 1) + int size = PyTuple_Size(args); + if (size == 1) { PySfSoundBuffer *Copy; - if (PyArg_ParseTuple(args, "O!", &PySfSoundBufferType, &Copy)) - self->obj = new sf::SoundBuffer(*(Copy->obj)); - else + if (!PyArg_ParseTuple(args, "O!:SoundBuffer.__init__", &PySfSoundBufferType, &Copy)) return -1; + self->obj = new sf::SoundBuffer(*(Copy->obj)); } - else + else if (size == 0) self->obj = new sf::SoundBuffer(); + else + PyErr_SetString(PyExc_TypeError, "SoundBuffer.__init__() takes 0 or 1 argument"); return 0; } diff --git a/python/src/SoundBuffer.hpp b/python/src/SoundBuffer.hpp index 2420bf909..4a35fb3e4 100644 --- a/python/src/SoundBuffer.hpp +++ b/python/src/SoundBuffer.hpp @@ -25,11 +25,9 @@ #ifndef __PYSOUNDBUFFER_HPP #define __PYSOUNDBUFFER_HPP -#include -#include - #include -#include + +#include typedef struct { PyObject_HEAD diff --git a/python/src/SoundBufferRecorder.cpp b/python/src/SoundBufferRecorder.cpp index 37d87e8d5..5da462ae3 100644 --- a/python/src/SoundBufferRecorder.cpp +++ b/python/src/SoundBufferRecorder.cpp @@ -23,35 +23,26 @@ //////////////////////////////////////////////////////////// #include "SoundBufferRecorder.hpp" - #include "SoundBuffer.hpp" +#include "compat.hpp" + + extern PyTypeObject PySfSoundRecorderType; -static PyMemberDef PySfSoundBufferRecorder_members[] = { - {NULL} /* Sentinel */ -}; - - static void PySfSoundBufferRecorder_dealloc(PySfSoundBufferRecorder *self) { delete self->obj; - self->ob_type->tp_free((PyObject*)self); + free_object(self); } static PyObject * PySfSoundBufferRecorder_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { PySfSoundBufferRecorder *self; - self = (PySfSoundBufferRecorder *)type->tp_alloc(type, 0); - - if (self != NULL) - { - } - return (PyObject *)self; } @@ -66,7 +57,7 @@ static PyObject * PySfSoundBufferRecorder_GetBuffer(PySfSoundBufferRecorder* self) { PySfSoundBuffer *SoundBuffer = GetNewPySfSoundBuffer(); - SoundBuffer->obj = new sf::SoundBuffer( self->obj->GetBuffer() ); + SoundBuffer->obj = new sf::SoundBuffer(self->obj->GetBuffer()); return (PyObject *)SoundBuffer; } @@ -77,8 +68,7 @@ static PyMethodDef PySfSoundBufferRecorder_methods[] = { }; PyTypeObject PySfSoundBufferRecorderType = { - PyObject_HEAD_INIT(NULL) - 0, /*ob_size*/ + head_init "SoundBufferRecorder", /*tp_name*/ sizeof(PySfSoundBufferRecorder), /*tp_basicsize*/ 0, /*tp_itemsize*/ @@ -106,7 +96,7 @@ PyTypeObject PySfSoundBufferRecorderType = { 0, /* tp_iter */ 0, /* tp_iternext */ PySfSoundBufferRecorder_methods, /* tp_methods */ - PySfSoundBufferRecorder_members, /* tp_members */ + 0, /* tp_members */ 0, /* tp_getset */ &PySfSoundRecorderType, /* tp_base */ 0, /* tp_dict */ diff --git a/python/src/SoundBufferRecorder.hpp b/python/src/SoundBufferRecorder.hpp index 966243299..4feadbe38 100644 --- a/python/src/SoundBufferRecorder.hpp +++ b/python/src/SoundBufferRecorder.hpp @@ -25,13 +25,9 @@ #ifndef __PYSOUNDBUFFERRECORDER_HPP #define __PYSOUNDBUFFERRECORDER_HPP -#include -#include - #include -#include -#include "offsetof.hpp" +#include typedef struct { PyObject_HEAD diff --git a/python/src/SoundRecorder.cpp b/python/src/SoundRecorder.cpp index 887c0272e..e45ef1828 100644 --- a/python/src/SoundRecorder.cpp +++ b/python/src/SoundRecorder.cpp @@ -24,57 +24,58 @@ #include "SoundRecorder.hpp" - - -static PyMemberDef PySfSoundRecorder_members[] = { - {NULL} /* Sentinel */ -}; - +#include "compat.hpp" bool CustomSoundRecorder::OnStart() { + bool result = false; if (PyObject_HasAttrString(SoundRecorder, "OnStart")) - if (PyObject_IsTrue(PyObject_CallFunction(PyObject_GetAttrString(SoundRecorder, "OnStart"), NULL))) - return true; - return false; + { + PyObject *OnStart = PyObject_GetAttrString(SoundRecorder, "OnStart"); + PyObject *Result = PyObject_CallFunction(OnStart, NULL); + result = PyBool_AsBool(Result); + Py_DECREF(OnStart); + Py_DECREF(Result); + } + return result; } bool CustomSoundRecorder::OnProcessSamples(const sf::Int16* Samples, std::size_t SamplesCount) { + bool result = false; if (PyObject_HasAttrString(SoundRecorder, "OnGetData")) { - if (PyObject_IsTrue(PyObject_CallFunction(PyObject_GetAttrString(SoundRecorder, "OnGetData"), (char *)"#s", (char *)Samples, SamplesCount*2))) - { - return true; - } + PyObject *OnGetData = PyObject_GetAttrString(SoundRecorder, "OnGetData"); + PyObject *Result = PyObject_CallFunction(OnGetData, (char *)"#s", (char *)Samples, SamplesCount*2); + result = PyBool_AsBool(Result); + Py_DECREF(OnGetData); + Py_DECREF(Result); } - return false; + return result; } void CustomSoundRecorder::OnStop() { if (PyObject_HasAttrString(SoundRecorder, "OnStop")) - PyObject_CallFunction(PyObject_GetAttrString(SoundRecorder, "OnStop"), NULL); + { + PyObject *OnStop = PyObject_GetAttrString(SoundRecorder, "OnStop"); + PyObject_CallFunction(OnStop, NULL); + Py_DECREF(OnStop); + } } static void PySfSoundRecorder_dealloc(PySfSoundRecorder* self) { delete self->obj; - self->ob_type->tp_free((PyObject*)self); + free_object(self); } static PyObject * PySfSoundRecorder_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { PySfSoundRecorder *self; - self = (PySfSoundRecorder *)type->tp_alloc(type, 0); - - if (self != NULL) - { - } - return (PyObject *)self; } @@ -86,11 +87,10 @@ PySfSoundRecorder_init(PySfSoundRecorder *self, PyObject *args) return 0; } - static PyObject * PySfSoundRecorder_Start(PySfSoundRecorder* self, PyObject *args) { - self->obj->Start( PyInt_AsLong(args) ); + self->obj->Start(PyLong_AsLong(args)); Py_RETURN_NONE; } @@ -104,20 +104,16 @@ PySfSoundRecorder_Stop(PySfSoundRecorder* self) static PyObject * PySfSoundRecorder_GetSampleRate(PySfSoundRecorder* self) { - return PyInt_FromLong(self->obj->GetSampleRate()); + return PyLong_FromLong(self->obj->GetSampleRate()); } static PyObject * PySfSoundRecorder_CanCapture(PySfSoundRecorder* self) { - if (sf::SoundRecorder::CanCapture()) - Py_RETURN_TRUE; - else - Py_RETURN_FALSE; + return PyBool_FromLong(sf::SoundRecorder::CanCapture()); } - static PyMethodDef PySfSoundRecorder_methods[] = { {"Start", (PyCFunction)PySfSoundRecorder_Start, METH_O, "Start(SampleRate=44100)\nStart the capture. Warning : only one capture can happen at the same time.\n SampleRate : Sound frequency (the more samples, the higher the quality) (44100 by default = CD quality)."}, {"Stop", (PyCFunction)PySfSoundRecorder_Stop, METH_NOARGS, "Stop()\nStop the capture."}, @@ -128,8 +124,7 @@ static PyMethodDef PySfSoundRecorder_methods[] = { PyTypeObject PySfSoundRecorderType = { - PyObject_HEAD_INIT(NULL) - 0, /*ob_size*/ + head_init "SoundRecorder", /*tp_name*/ sizeof(PySfSoundRecorder), /*tp_basicsize*/ 0, /*tp_itemsize*/ @@ -160,7 +155,7 @@ Construct the sound recorder with a callback function for processing captured sa 0, /* tp_iter */ 0, /* tp_iternext */ PySfSoundRecorder_methods, /* tp_methods */ - PySfSoundRecorder_members, /* tp_members */ + 0, /* tp_members */ 0, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ diff --git a/python/src/SoundRecorder.hpp b/python/src/SoundRecorder.hpp index 356262d21..cc3600240 100644 --- a/python/src/SoundRecorder.hpp +++ b/python/src/SoundRecorder.hpp @@ -25,13 +25,9 @@ #ifndef __PYSOUNDRECORDER_HPP #define __PYSOUNDRECORDER_HPP -#include -#include - #include -#include -#include "offsetof.hpp" +#include class CustomSoundRecorder : public sf::SoundRecorder { diff --git a/python/src/SoundStream.cpp b/python/src/SoundStream.cpp index a52b81fc1..89b040840 100644 --- a/python/src/SoundStream.cpp +++ b/python/src/SoundStream.cpp @@ -24,32 +24,46 @@ #include "SoundStream.hpp" +#include "compat.hpp" + bool CustomSoundStream::OnStart() { + bool result = false; if (PyObject_HasAttrString(SoundStream, "OnStart")) - if (PyObject_IsTrue(PyObject_CallFunction(PyObject_GetAttrString(SoundStream, "OnStart"), NULL))) - return true; - return false; + { + PyObject *OnStart = PyObject_GetAttrString(SoundStream, "OnStart"); + PyObject *Result = PyObject_CallFunction(OnStart, NULL); + result = PyBool_AsBool(Result); + Py_DECREF(OnStart); + Py_DECREF(Result); + } + return result; } bool CustomSoundStream::OnGetData(Chunk& Data) { + bool result = false; + if (PyData != NULL) { + Py_DECREF(PyData); + } if (PyObject_HasAttrString(SoundStream, "OnGetData")) { - PyObject *PyData=NULL; + PyObject *Function = PyObject_GetAttrString(SoundStream, "OnGetData"); Data.NbSamples = 0; - if ((PyData = PyObject_CallFunction(PyObject_GetAttrString(SoundStream, "OnGetData"), NULL))) + PyData = PyObject_CallFunction(Function, NULL); + if (PyData != NULL) { if (PyArg_Parse(PyData, "s#", &(Data.Samples), &(Data.NbSamples))) { Data.NbSamples /= 2; if (Data.NbSamples > 0) - return true; + result = true; } } + Py_DECREF(Function); } - return false; + return result; } void CustomSoundStream::Init(unsigned int ChannelsCount, unsigned int SampleRate) @@ -57,16 +71,11 @@ void CustomSoundStream::Init(unsigned int ChannelsCount, unsigned int SampleRate Initialize(ChannelsCount, SampleRate); } - -static PyMemberDef PySfSoundStream_members[] = { - {NULL} /* Sentinel */ -}; - - static int PySfSoundStream_init(PySfSoundStream *self, PyObject *args, PyObject *kwds) { self->obj = new CustomSoundStream(); + self->obj->PyData = NULL; self->obj->SoundStream = (PyObject *)self; return 0; } @@ -75,7 +84,7 @@ static void PySfSoundStream_dealloc(PySfSoundStream *self) { delete self->obj; - self->ob_type->tp_free((PyObject*)self); + free_object(self); } static PyObject * @@ -90,7 +99,7 @@ static PyObject * PySfSoundStream_Initialize(PySfSoundStream *self, PyObject *args) { unsigned int ChannelsCount, SampleRate; - if (!PyArg_ParseTuple(args, "II", &ChannelsCount, &SampleRate)) + if (!PyArg_ParseTuple(args, "II:SoundStream.Initialize", &ChannelsCount, &SampleRate)) return NULL; self->obj->Init(ChannelsCount, SampleRate); Py_RETURN_NONE; @@ -192,7 +201,7 @@ static PyObject* PySfSoundStream_SetPosition(PySfSoundStream *self, PyObject *args) { float X, Y, Z; - if (! PyArg_ParseTuple(args, "fff", &X, &Y, &Z)) + if (!PyArg_ParseTuple(args, "fff:SoundStream.SetPosition", &X, &Y, &Z)) return NULL; self->obj->SetPosition(X, Y, Z); Py_RETURN_NONE; @@ -207,20 +216,14 @@ PySfSoundStream_GetStatus(PySfSoundStream *self) static PyObject* PySfSoundStream_SetLoop(PySfSoundStream *self, PyObject *args) { - if (PyObject_IsTrue(args)) - self->obj->SetLoop(true); - else - self->obj->SetLoop(false); + self->obj->SetLoop(PyBool_AsBool(args)); Py_RETURN_NONE; } static PyObject* PySfSoundStream_GetLoop(PySfSoundStream *self) { - if (self->obj->GetLoop()) - Py_RETURN_TRUE; - else - Py_RETURN_FALSE; + return PyBool_FromLong(self->obj->GetLoop()); } static PyObject* @@ -259,8 +262,7 @@ Set the audio stream parameters, you must call it before Play()\n\ PyTypeObject PySfSoundStreamType = { - PyObject_HEAD_INIT(NULL) - 0, /*ob_size*/ + head_init "SoundStream", /*tp_name*/ sizeof(PySfSoundStream), /*tp_basicsize*/ 0, /*tp_itemsize*/ @@ -291,7 +293,7 @@ or for streaming sound from the network", /* tp_doc */ 0, /* tp_iter */ 0, /* tp_iternext */ PySfSoundStream_methods, /* tp_methods */ - PySfSoundStream_members, /* tp_members */ + 0, /* tp_members */ 0, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ @@ -308,13 +310,13 @@ void PySfSoundStream_InitConst() { PyObject *obj; - obj = PyInt_FromLong(sf::SoundStream::Stopped); + obj = PyLong_FromLong(sf::SoundStream::Stopped); PyDict_SetItemString(PySfSoundStreamType.tp_dict, "Stopped", obj); Py_DECREF(obj); - obj = PyInt_FromLong(sf::SoundStream::Paused); + obj = PyLong_FromLong(sf::SoundStream::Paused); PyDict_SetItemString(PySfSoundStreamType.tp_dict, "Paused", obj); Py_DECREF(obj); - obj = PyInt_FromLong(sf::SoundStream::Playing); + obj = PyLong_FromLong(sf::SoundStream::Playing); PyDict_SetItemString(PySfSoundStreamType.tp_dict, "Playing", obj); Py_DECREF(obj); } diff --git a/python/src/SoundStream.hpp b/python/src/SoundStream.hpp index 8c7b26f4c..6569bb035 100644 --- a/python/src/SoundStream.hpp +++ b/python/src/SoundStream.hpp @@ -26,15 +26,14 @@ #define __PYSOUNDSTREAM_HPP #include -#include #include -#include class CustomSoundStream : public sf::SoundStream { public : PyObject *SoundStream; + PyObject *PyData; virtual bool OnStart(); virtual bool OnGetData(Chunk& Data); void Init(unsigned int ChannelsCount, unsigned int SampleRate); diff --git a/python/src/String.cpp b/python/src/String.cpp index 8d2fa7f2f..09b9f8d62 100644 --- a/python/src/String.cpp +++ b/python/src/String.cpp @@ -27,36 +27,27 @@ #include "Color.hpp" #include "Rect.hpp" +#include "compat.hpp" + extern PyTypeObject PySfColorType; extern PyTypeObject PySfImageType; extern PyTypeObject PySfDrawableType; extern PyTypeObject PySfFontType; -static PyMemberDef PySfString_members[] = { - {NULL} /* Sentinel */ -}; - - static void PySfString_dealloc(PySfString *self) { delete self->obj; - self->ob_type->tp_free((PyObject*)self); + free_object(self); } static PyObject * PySfString_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { PySfString *self; - self = (PySfString *)type->tp_alloc(type, 0); - - if (self != NULL) - { - } - return (PyObject *)self; } @@ -121,7 +112,7 @@ PySfString_SetFont(PySfString* self, PyObject *args) { PySfFont *Font = (PySfFont *)args; if (!PyObject_TypeCheck(Font, &PySfFontType)) - PyErr_SetString(PyExc_ValueError, "Argument must be a sf.Font"); + PyErr_SetString(PyExc_ValueError, "String.SetFont() Argument must be a sf.Font"); self->obj->SetFont(*(Font->obj)); Py_RETURN_NONE; } @@ -155,7 +146,12 @@ PySfString_GetStyle(PySfString* self) static PyObject * PySfString_GetText(PySfString* self) { - return PyString_FromString((std::string(self->obj->GetText())).c_str()); + std::string Text = (std::string(self->obj->GetText())); +#ifdef IS_PY3K + return PyUnicode_DecodeUTF8(Text.c_str(), (Py_ssize_t)Text.length(), "replace"); +#else + return PyString_FromString(Text.c_str()); +#endif } static PyObject * @@ -206,8 +202,7 @@ Return the visual position (a tuple of two floats) of the Index-th character of }; PyTypeObject PySfStringType = { - PyObject_HEAD_INIT(NULL) - 0, /*ob_size*/ + head_init "String", /*tp_name*/ sizeof(PySfString), /*tp_basicsize*/ 0, /*tp_itemsize*/ @@ -236,7 +231,7 @@ Default constructor : String ()\nConstruct the string from a utf-8 or a utf-16 s 0, /* tp_iter */ 0, /* tp_iternext */ PySfString_methods, /* tp_methods */ - PySfString_members, /* tp_members */ + 0, /* tp_members */ 0, /* tp_getset */ &PySfDrawableType, /* tp_base */ 0, /* tp_dict */ @@ -253,16 +248,16 @@ Default constructor : String ()\nConstruct the string from a utf-8 or a utf-16 s void PySfString_InitConst() { PyObject *obj; - obj = PyInt_FromLong(sf::String::Regular); + obj = PyLong_FromLong(sf::String::Regular); PyDict_SetItemString(PySfStringType.tp_dict, "Regular", obj); Py_DECREF(obj); - obj = PyInt_FromLong(sf::String::Bold); + obj = PyLong_FromLong(sf::String::Bold); PyDict_SetItemString(PySfStringType.tp_dict, "Bold", obj); Py_DECREF(obj); - obj = PyInt_FromLong(sf::String::Italic); + obj = PyLong_FromLong(sf::String::Italic); PyDict_SetItemString(PySfStringType.tp_dict, "Italic", obj); Py_DECREF(obj); - obj = PyInt_FromLong(sf::String::Underlined); + obj = PyLong_FromLong(sf::String::Underlined); PyDict_SetItemString(PySfStringType.tp_dict, "Underlined", obj); Py_DECREF(obj); } diff --git a/python/src/String.hpp b/python/src/String.hpp index 312eb4bbe..a036f8e16 100644 --- a/python/src/String.hpp +++ b/python/src/String.hpp @@ -25,11 +25,9 @@ #ifndef __PYSTRING_HPP #define __PYSTRING_HPP -#include -#include - #include -#include + +#include typedef struct { PyObject_HEAD diff --git a/python/src/VideoMode.cpp b/python/src/VideoMode.cpp index 19abe2fc8..70cefbb5c 100644 --- a/python/src/VideoMode.cpp +++ b/python/src/VideoMode.cpp @@ -22,8 +22,12 @@ // //////////////////////////////////////////////////////////// -#include "VideoMode.hpp" - +#include "VideoMode.hpp" + +#include + +#include "offsetof.hpp" +#include "compat.hpp" static PyMemberDef PySfVideoMode_members[] = { @@ -34,12 +38,11 @@ static PyMemberDef PySfVideoMode_members[] = { }; - static void PySfVideoMode_dealloc(PySfVideoMode* self) { delete self->obj; - self->ob_type->tp_free((PyObject*)self); + free_object(self); } static PyObject * @@ -72,7 +75,7 @@ PySfVideoMode_init(PySfVideoMode *self, PyObject *args, PyObject *kwds) { const char *kwlist[] = {"Width", "Height", "BitsPerPixel", NULL}; - if (! PyArg_ParseTupleAndKeywords(args, kwds, "II|I", (char **)kwlist, &self->Width, &self->Height, &self->BitsPerPixel)) + if (!PyArg_ParseTupleAndKeywords(args, kwds, "II|I:VideoMode.__init__", (char **)kwlist, &self->Width, &self->Height, &self->BitsPerPixel)) return -1; self->obj = new sf::VideoMode(self->Width, self->Height, self->BitsPerPixel); @@ -111,7 +114,7 @@ PySfVideoMode_GetMode(PySfVideoMode* self, PyObject *args) std::size_t index; PySfVideoMode *VideoMode; - index = (std::size_t)PyInt_AsLong(args); + index = (std::size_t)PyLong_AsLong(args); VideoMode = GetNewPySfVideoMode(); VideoMode->obj = new sf::VideoMode ( sf::VideoMode::GetMode(index) ); @@ -125,7 +128,7 @@ PySfVideoMode_GetMode(PySfVideoMode* self, PyObject *args) static PyObject * PySfVideoMode_GetModesCount(PySfVideoMode* self) { - return PyInt_FromLong(sf::VideoMode::GetModesCount()); + return PyLong_FromLong(sf::VideoMode::GetModesCount()); } @@ -150,8 +153,7 @@ int PySfVideoMode_Compare(PyObject *o1, PyObject *o2) PyTypeObject PySfVideoModeType = { - PyObject_HEAD_INIT(NULL) - 0, /*ob_size*/ + head_init "VideoMode", /*tp_name*/ sizeof(PySfVideoMode), /*tp_basicsize*/ 0, /*tp_itemsize*/ diff --git a/python/src/VideoMode.hpp b/python/src/VideoMode.hpp index d7a3dec6a..59e3e274e 100644 --- a/python/src/VideoMode.hpp +++ b/python/src/VideoMode.hpp @@ -25,15 +25,9 @@ #ifndef __PYVIDEOMODE_HPP #define __PYVIDEOMODE_HPP -#include -#include -#include +#include #include -#include - -#include "offsetof.hpp" - typedef struct { PyObject_HEAD diff --git a/python/src/View.cpp b/python/src/View.cpp index d2587f02f..45ffd0798 100644 --- a/python/src/View.cpp +++ b/python/src/View.cpp @@ -23,20 +23,21 @@ //////////////////////////////////////////////////////////// #include "View.hpp" +#include "Rect.hpp" + +#include "offsetof.hpp" +#include "compat.hpp" + extern PyTypeObject PySfFloatRectType; -static PyMemberDef PySfView_members[] = { - {NULL} /* Sentinel */ -}; - static void PySfView_dealloc(PySfView *self) { if (self->Owner) delete self->obj; - self->ob_type->tp_free((PyObject*)self); + free_object(self); } static PyObject * @@ -57,7 +58,7 @@ static int PySfView_init(PySfView *self, PyObject *args, PyObject *kwds) { PySfFloatRect *Rect=NULL; - if (! PyArg_ParseTuple(args, "|O!", &PySfFloatRectType, &Rect)) + if (!PyArg_ParseTuple(args, "|O!:View.__init__", &PySfFloatRectType, &Rect)) return -1; if (Rect != NULL) @@ -98,7 +99,7 @@ static PyObject * PySfView_Move(PySfView* self, PyObject *args) { float x, y; - if ( !PyArg_ParseTuple(args, "ff", &x, &y) ) + if (!PyArg_ParseTuple(args, "ff:View.Move", &x, &y) ) return NULL; self->obj->Move(x, y); Py_RETURN_NONE; @@ -108,7 +109,7 @@ static PyObject * PySfView_SetCenter(PySfView* self, PyObject *args) { float x, y; - if ( !PyArg_ParseTuple(args, "ff", &x, &y) ) + if (!PyArg_ParseTuple(args, "ff:View.SetCenter", &x, &y) ) return NULL; self->obj->SetCenter(x, y); Py_RETURN_NONE; @@ -118,7 +119,7 @@ static PyObject * PySfView_SetHalfSize(PySfView* self, PyObject *args) { float x, y; - if ( !PyArg_ParseTuple(args, "ff", &x, &y) ) + if (!PyArg_ParseTuple(args, "ff:View.SetHalfSize", &x, &y) ) return NULL; self->obj->SetHalfSize(x, y); Py_RETURN_NONE; @@ -145,8 +146,7 @@ static PyMethodDef PySfView_methods[] = { }; PyTypeObject PySfViewType = { - PyObject_HEAD_INIT(NULL) - 0, /*ob_size*/ + head_init "View", /*tp_name*/ sizeof(PySfView), /*tp_basicsize*/ 0, /*tp_itemsize*/ @@ -174,7 +174,7 @@ PyTypeObject PySfViewType = { 0, /* tp_iter */ 0, /* tp_iternext */ PySfView_methods, /* tp_methods */ - PySfView_members, /* tp_members */ + 0, /* tp_members */ 0, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ diff --git a/python/src/View.hpp b/python/src/View.hpp index af55275f9..2e8955c3a 100644 --- a/python/src/View.hpp +++ b/python/src/View.hpp @@ -25,15 +25,9 @@ #ifndef __PYVIEW_HPP #define __PYVIEW_HPP -#include -#include - -#include "Rect.hpp" - #include -#include -#include "offsetof.hpp" +#include typedef struct { PyObject_HEAD diff --git a/python/src/Window.cpp b/python/src/Window.cpp index 791012460..54da51f43 100644 --- a/python/src/Window.cpp +++ b/python/src/Window.cpp @@ -22,39 +22,38 @@ // //////////////////////////////////////////////////////////// -#include "Window.hpp" +#include "Window.hpp" + +#include "Event.hpp" +#include "VideoMode.hpp" +#include "Input.hpp" +#include "WindowSettings.hpp" -#include "SFML/Window/WindowStyle.hpp" +#include + +#include "compat.hpp" + extern PyTypeObject PySfEventType; extern PyTypeObject PySfWindowSettingsType; -extern PyTypeObject PySfVideoModeType; +extern PyTypeObject PySfVideoModeType; -static PyMemberDef PySfWindow_members[] = { - {NULL} /* Sentinel */ -}; static void PySfWindow_dealloc(PySfWindow* self) { delete self->obj; - self->ob_type->tp_free((PyObject*)self); + free_object(self); } static PyObject * PySfWindow_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { PySfWindow *self; - self = (PySfWindow *)type->tp_alloc(type, 0); - if (self != NULL) - { - } - return (PyObject *)self; } - static PyObject* PySfWindow_GetEvent(PySfWindow *self, PyObject *args) @@ -63,7 +62,7 @@ PySfWindow_GetEvent(PySfWindow *self, PyObject *args) if (! PyObject_TypeCheck(PyEvent, &PySfEventType)) { - PyErr_SetString(PyExc_TypeError, "Argument is not a sfEvent"); + PyErr_SetString(PyExc_TypeError, "Window.GetEvent() Argument is not a sfEvent"); return NULL; } @@ -71,43 +70,13 @@ PySfWindow_GetEvent(PySfWindow *self, PyObject *args) { PyEvent->Type = PyEvent->obj->Type; PyEvent->Text->Unicode = PyEvent->obj->Text.Unicode; - PyEvent->Key->Code = PyEvent->obj->Key.Code; - if (PyEvent->obj->Key.Alt && PyEvent->Key->Alt == Py_False) - { - Py_DECREF(Py_False); - Py_INCREF(Py_True); - PyEvent->Key->Alt = Py_True; - } - else if (PyEvent->Key->Alt == Py_True) - { - Py_DECREF(Py_True); - Py_INCREF(Py_False); - PyEvent->Key->Alt = Py_False; - } - if (PyEvent->obj->Key.Control && PyEvent->Key->Control == Py_False) - { - Py_DECREF(Py_False); - Py_INCREF(Py_True); - PyEvent->Key->Control = Py_True; - } - else if (PyEvent->Key->Control == Py_True) - { - Py_DECREF(Py_True); - Py_INCREF(Py_False); - PyEvent->Key->Control = Py_False; - } - if (PyEvent->obj->Key.Shift && PyEvent->Key->Shift == Py_False) - { - Py_DECREF(Py_False); - Py_INCREF(Py_True); - PyEvent->Key->Shift = Py_True; - } - else if (PyEvent->Key->Shift == Py_True) - { - Py_DECREF(Py_True); - Py_INCREF(Py_False); - PyEvent->Key->Shift = Py_False; - } + PyEvent->Key->Code = PyEvent->obj->Key.Code; + Py_DECREF(PyEvent->Key->Alt); + PyEvent->Key->Alt = PyBool_FromLong(PyEvent->obj->Key.Alt); + Py_DECREF(PyEvent->Key->Control); + PyEvent->Key->Control = PyBool_FromLong(PyEvent->obj->Key.Control); + Py_DECREF(PyEvent->Key->Shift); + PyEvent->Key->Shift = PyBool_FromLong(PyEvent->obj->Key.Shift); PyEvent->MouseButton->Button = PyEvent->obj->MouseButton.Button; PyEvent->MouseButton->X = PyEvent->obj->MouseButton.X; PyEvent->MouseButton->Y = PyEvent->obj->MouseButton.Y; @@ -136,30 +105,23 @@ PySfWindow_Create(PySfWindow* self, PyObject *args, PyObject *kwds) sf::VideoMode *VideoMode; char *Title=NULL; unsigned long WindowStyle = sf::Style::Resize | sf::Style::Close; - PySfWindowSettings *ParamsTmp=NULL; - sf::WindowSettings *Params = NULL; + PySfWindowSettings *Params=NULL; const char *kwlist[] = {"VideoMode", "Title", "WindowStyle", "Params", NULL}; - if (! PyArg_ParseTupleAndKeywords(args, kwds, "O!s|IO!", (char **)kwlist, &PySfVideoModeType, &VideoModeTmp, &Title, &WindowStyle, &PySfWindowSettingsType, &ParamsTmp)) + if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!s|IO!:Window.Create", (char **)kwlist, &PySfVideoModeType, &VideoModeTmp, &Title, &WindowStyle, &PySfWindowSettingsType, &Params)) return NULL; - if (VideoModeTmp) { - VideoMode = ((PySfVideoMode *)VideoModeTmp)->obj; - PySfVideoModeUpdate((PySfVideoMode *)VideoModeTmp); - } - else - return NULL; + VideoMode = ((PySfVideoMode *)VideoModeTmp)->obj; + PySfVideoModeUpdate((PySfVideoMode *)VideoModeTmp); - if (ParamsTmp) + if (Params) { - PySfWindowSettingsUpdate(ParamsTmp); - Params = ParamsTmp->obj; + PySfWindowSettingsUpdate(Params); + self->obj->Create(*VideoMode, Title, WindowStyle, *(Params->obj)); } - else - Params = new sf::WindowSettings(); - - self->obj->Create(*VideoMode, Title, WindowStyle, *Params); + else + self->obj->Create(*VideoMode, Title, WindowStyle); Py_RETURN_NONE; } @@ -183,10 +145,7 @@ PySfWindow_Close(PySfWindow *self) static PyObject * PySfWindow_IsOpened(PySfWindow *self) { - if (self->obj->IsOpened()) - Py_RETURN_TRUE; - else - Py_RETURN_NONE; + return PyBool_FromLong(self->obj->IsOpened()); } static PyObject * PySfWindow_GetWidth(PySfWindow *self) @@ -202,32 +161,20 @@ PySfWindow_GetHeight(PySfWindow *self) static PyObject * PySfWindow_UseVerticalSync(PySfWindow *self, PyObject *args) { - bool Enabled = false; - if (PyObject_IsTrue(args)) - Enabled = true; - self->obj->UseVerticalSync(Enabled); + self->obj->UseVerticalSync(PyBool_AsBool(args)); Py_RETURN_NONE; } static PyObject * PySfWindow_ShowMouseCursor(PySfWindow *self, PyObject *args) { - bool Show = false; - if (PyObject_IsTrue(args)) - Show = true; - self->obj->ShowMouseCursor(Show); + self->obj->ShowMouseCursor(PyBool_AsBool(args)); Py_RETURN_NONE; } static PyObject * PySfWindow_SetActive(PySfWindow *self, PyObject *args) { - bool Active = false; - if (PyObject_IsTrue(args)) - Active = true; - if (self->obj->SetActive(Active)) - Py_RETURN_TRUE; - else - Py_RETURN_FALSE; + return PyBool_FromLong(self->obj->SetActive(PyBool_AsBool(args))); } static PyObject * PySfWindow_Display(PySfWindow *self) @@ -266,9 +213,8 @@ static PyObject * PySfWindow_SetPosition(PySfWindow* self, PyObject *args) { int Left=0, Top=0; - if (! PyArg_ParseTuple(args, "ii", &Left, &Top)) + if (!PyArg_ParseTuple(args, "ii:Window.SetPosition", &Left, &Top)) return NULL; - self->obj->SetPosition(Left,Top); Py_RETURN_NONE; } @@ -283,20 +229,14 @@ PySfWindow_SetFramerateLimit(PySfWindow *self, PyObject *args) static PyObject * PySfWindow_Show(PySfWindow *self, PyObject *args) { - if (PyObject_IsTrue(args)) - self->obj->Show(true); - else - self->obj->Show(false); + self->obj->Show(PyBool_AsBool(args)); Py_RETURN_NONE; } static PyObject * PySfWindow_EnableKeyRepeat(PySfWindow *self, PyObject *args) { - if (PyObject_IsTrue(args)) - self->obj->EnableKeyRepeat(true); - else - self->obj->EnableKeyRepeat(false); + self->obj->EnableKeyRepeat(PyBool_AsBool(args)); Py_RETURN_NONE; } @@ -304,9 +244,8 @@ static PyObject * PySfWindow_SetCursorPosition(PySfWindow* self, PyObject *args) { unsigned int Left=0, Top=0; - if (! PyArg_ParseTuple(args, "II", &Left, &Top)) + if (!PyArg_ParseTuple(args, "II:Window.SetCursorPosition", &Left, &Top)) return NULL; - self->obj->SetCursorPosition(Left,Top); Py_RETURN_NONE; } @@ -315,9 +254,8 @@ static PyObject * PySfWindow_SetSize(PySfWindow* self, PyObject *args) { unsigned int Width=0, Height=0; - if (! PyArg_ParseTuple(args, "II", &Width, &Height)) + if (!PyArg_ParseTuple(args, "II:Window.SetSize", &Width, &Height)) return NULL; - self->obj->SetSize(Width, Height); Py_RETURN_NONE; } @@ -335,7 +273,7 @@ PySfWindow_SetIcon(PySfWindow* self, PyObject *args) unsigned int Width, Height, Size; char *Data; - if (! PyArg_ParseTuple(args, "IIs#", &Width, &Height, &Data, &Size)) + if (! PyArg_ParseTuple(args, "IIs#:Window.SetIcon", &Width, &Height, &Data, &Size)) return NULL; self->obj->SetIcon(Width, Height, (sf::Uint8*) Data); @@ -378,8 +316,7 @@ Change the window's icon.\n\ }; PyTypeObject PySfWindowType = { - PyObject_HEAD_INIT(NULL) - 0, /*ob_size*/ + head_init "Window", /*tp_name*/ sizeof(PySfWindow), /*tp_basicsize*/ 0, /*tp_itemsize*/ @@ -414,7 +351,7 @@ Construct a new window : sf.Window(Mode, Title, sf.Style.Resize | sf.Style.Close 0, /* tp_iter */ 0, /* tp_iternext */ PySfWindow_methods, /* tp_methods */ - PySfWindow_members, /* tp_members */ + 0, /* tp_members */ 0, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ diff --git a/python/src/Window.hpp b/python/src/Window.hpp index b42084b0b..5b26b5191 100644 --- a/python/src/Window.hpp +++ b/python/src/Window.hpp @@ -25,17 +25,9 @@ #ifndef __PYWINDOW_HPP #define __PYWINDOW_HPP -#include -#include -#include - #include -#include -#include "Event.hpp" -#include "VideoMode.hpp" -#include "Input.hpp" -#include "WindowSettings.hpp" +#include typedef struct { diff --git a/python/src/WindowSettings.cpp b/python/src/WindowSettings.cpp index 807e7d847..9a6579624 100644 --- a/python/src/WindowSettings.cpp +++ b/python/src/WindowSettings.cpp @@ -24,6 +24,11 @@ #include "WindowSettings.hpp" +#include + +#include "offsetof.hpp" +#include "compat.hpp" + static PyMemberDef PySfWindowSettings_members[] = { {(char *)"DepthBits", T_UINT, offsetof(PySfWindowSettings, DepthBits), 0, (char *)"Depth buffer bits (24 by default)"}, {(char *)"StencilBits", T_UINT, offsetof(PySfWindowSettings, StencilBits), 0, (char *)"Stencil buffer bits (8 by default)"}, @@ -36,7 +41,7 @@ static void PySfWindowSettings_dealloc(PySfWindowSettings *self) { delete self->obj; - self->ob_type->tp_free((PyObject*)self); + free_object(self); } void @@ -51,16 +56,13 @@ static PyObject * PySfWindowSettings_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { PySfWindowSettings *self; - self = (PySfWindowSettings *)type->tp_alloc(type, 0); - if (self != NULL) { self->DepthBits = 24; self->StencilBits = 8; self->AntialiasingLevel = 0; } - return (PyObject *)self; } @@ -69,21 +71,16 @@ static int PySfWindowSettings_init(PySfWindowSettings *self, PyObject *args, PyObject *kwds) { const char *kwlist[] = {"DepthBits", "StencilBits", "AntialiasingLevel", NULL}; - if (! PyArg_ParseTupleAndKeywords(args, kwds, "|III", (char **)kwlist, &(self->DepthBits), &(self->StencilBits), &(self->AntialiasingLevel))) + if (!PyArg_ParseTupleAndKeywords(args, kwds, "|III:WindowSettings.__init__", (char **)kwlist, &(self->DepthBits), &(self->StencilBits), &(self->AntialiasingLevel))) return -1; self->obj = new sf::WindowSettings(self->DepthBits, self->StencilBits, self->AntialiasingLevel); return 0; } -static PyMethodDef PySfWindowSettings_methods[] = { - {NULL} /* Sentinel */ -}; - PyTypeObject PySfWindowSettingsType = { - PyObject_HEAD_INIT(NULL) - 0, /*ob_size*/ + head_init "WindowSettings", /*tp_name*/ sizeof(PySfWindowSettings), /*tp_basicsize*/ 0, /*tp_itemsize*/ @@ -110,7 +107,7 @@ PyTypeObject PySfWindowSettingsType = { 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ - PySfWindowSettings_methods, /* tp_methods */ + 0, /* tp_methods */ PySfWindowSettings_members, /* tp_members */ 0, /* tp_getset */ 0, /* tp_base */ diff --git a/python/src/WindowSettings.hpp b/python/src/WindowSettings.hpp index ac6135619..e185084e3 100644 --- a/python/src/WindowSettings.hpp +++ b/python/src/WindowSettings.hpp @@ -25,13 +25,9 @@ #ifndef __PYWINDOWSETTINGS_HPP #define __PYWINDOWSETTINGS_HPP -#include -#include - #include -#include -#include "offsetof.hpp" +#include typedef struct { diff --git a/python/src/WindowStyle.cpp b/python/src/WindowStyle.cpp index 3846f1501..03976e500 100644 --- a/python/src/WindowStyle.cpp +++ b/python/src/WindowStyle.cpp @@ -22,62 +22,25 @@ // //////////////////////////////////////////////////////////// -#include - -#include -#include - #include "WindowStyle.hpp" +#include "compat.hpp" -typedef struct { - PyObject_HEAD -} PySfStyle; - - - -static PyMemberDef PySfStyle_members[] = { - {NULL} /* Sentinel */ -}; - - -static void -PySfStyle_dealloc(PySfStyle *self) -{ - self->ob_type->tp_free((PyObject*)self); -} static PyObject * PySfStyle_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { PySfStyle *self; - self = (PySfStyle *)type->tp_alloc(type, 0); - if (self != NULL) - { - } - return (PyObject *)self; } - -static int -PySfStyle_init(PySfStyle *self, PyObject *args, PyObject *kwds) -{ - return 0; -} - -static PyMethodDef PySfStyle_methods[] = { - {NULL} /* Sentinel */ -}; - PyTypeObject PySfStyleType = { - PyObject_HEAD_INIT(NULL) - 0, /*ob_size*/ + head_init "Style", /*tp_name*/ sizeof(PySfStyle), /*tp_basicsize*/ 0, /*tp_itemsize*/ - (destructor)PySfStyle_dealloc, /*tp_dealloc*/ + 0, /*tp_dealloc*/ 0, /*tp_print*/ 0, /*tp_getattr*/ 0, /*tp_setattr*/ @@ -105,15 +68,15 @@ Fullscreen Fullscreen mode (this flag and all others are mutually exclusive).", 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ - PySfStyle_methods, /* tp_methods */ - PySfStyle_members, /* tp_members */ + 0, /* 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 */ - (initproc)PySfStyle_init, /* tp_init */ + 0, /* tp_init */ 0, /* tp_alloc */ PySfStyle_new, /* tp_new */ }; @@ -121,19 +84,19 @@ Fullscreen Fullscreen mode (this flag and all others are mutually exclusive).", void PySfStyle_InitConst() { PyObject *obj; - obj = PyInt_FromLong(sf::Style::None); + obj = PyLong_FromLong(sf::Style::None); PyDict_SetItemString(PySfStyleType.tp_dict, "None", obj); Py_DECREF(obj); - obj = PyInt_FromLong(sf::Style::Titlebar); + obj = PyLong_FromLong(sf::Style::Titlebar); PyDict_SetItemString(PySfStyleType.tp_dict, "Titlebar", obj); Py_DECREF(obj); - obj = PyInt_FromLong(sf::Style::Resize); + obj = PyLong_FromLong(sf::Style::Resize); PyDict_SetItemString(PySfStyleType.tp_dict, "Resize", obj); Py_DECREF(obj); - obj = PyInt_FromLong(sf::Style::Close); + obj = PyLong_FromLong(sf::Style::Close); PyDict_SetItemString(PySfStyleType.tp_dict, "Close", obj); Py_DECREF(obj); - obj = PyInt_FromLong(sf::Style::Fullscreen); + obj = PyLong_FromLong(sf::Style::Fullscreen); PyDict_SetItemString(PySfStyleType.tp_dict, "Fullscreen", obj); Py_DECREF(obj); } diff --git a/python/src/WindowStyle.hpp b/python/src/WindowStyle.hpp index 042c1b83a..d93516efa 100644 --- a/python/src/WindowStyle.hpp +++ b/python/src/WindowStyle.hpp @@ -25,6 +25,14 @@ #ifndef __PYWINDOWSTYLE_HPP #define __PYWINDOWSTYLE_HPP +#include + +#include + +typedef struct { + PyObject_HEAD +} PySfStyle; + void PySfStyle_InitConst(); diff --git a/python/src/compat.hpp b/python/src/compat.hpp index 173ab54a8..8439f5891 100644 --- a/python/src/compat.hpp +++ b/python/src/compat.hpp @@ -26,17 +26,44 @@ #define __PYCOMPAT_HPP #if PY_MAJOR_VERSION >= 3 + #define IS_PY3K #define head_init PyVarObject_HEAD_INIT(NULL, 0) + +#define save_to_file(self, args) \ + PyObject *string = PyUnicode_AsUTF8String(args); \ + if (string == NULL) return NULL; \ + char *path = PyBytes_AsString(string); \ + bool result = self->obj->SaveToFile(path); \ + Py_DECREF(string); \ + return PyBool_FromLong(result) + +#define load_from_file(self, args) \ + PyObject *string = PyUnicode_AsUTF8String(args); \ + if (string == NULL) return NULL; \ + char *path = PyBytes_AsString(string); \ + bool result = self->obj->LoadFromFile(path); \ + Py_DECREF(string); \ + return PyBool_FromLong(result) + #else + +#define save_to_file(self, args) \ + return PyBool_FromLong(self->obj->SaveToFile(PyString_AsString(args))) +#define load_from_file(self, args) \ + return PyBool_FromLong(self->obj->LoadFromFile(PyString_AsString(args))) + #define Py_TYPE(a) a->ob_type #define head_init PyObject_HEAD_INIT(NULL) 0, #define PyBytes_FromStringAndSize PyString_FromStringAndSize + #endif #define free_object(a) Py_TYPE(a)->tp_free((PyObject*)a) #define PyBool_AsBool(a) ((PyObject_IsTrue(a))?true:false) + + #endif diff --git a/python/src/main.cpp b/python/src/main.cpp index 6dc7d06d8..b1d5fefa1 100644 --- a/python/src/main.cpp +++ b/python/src/main.cpp @@ -69,8 +69,7 @@ extern PyTypeObject PySfGlyphType; extern PyTypeObject PySfStringType; extern PyTypeObject PySfPostFXType; -extern PyTypeObject PySfImageType; - +extern PyTypeObject PySfImageType; extern PyTypeObject PySfColorType; extern PyTypeObject PySfShapeType; @@ -96,8 +95,8 @@ static PyMethodDef module_methods[] = { #define INITERROR return NULL static PyModuleDef module_def = { PyModuleDef_HEAD_INIT, - "noddy", - "Example module that creates an extension type.", + "sf", + "Python binding for sfml (Simple Fast Media Library)", -1, module_methods, NULL, NULL, NULL, NULL }; From 39f4805a98cf11d86faf14d5dff0e3bbd1420642 Mon Sep 17 00:00:00 2001 From: remi-k Date: Fri, 27 Feb 2009 17:57:39 +0000 Subject: [PATCH 11/22] * 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 --- python/PySFML/__init__.py | 1 - python/samples/opengl.py | 2 +- python/samples/sound_capture.py | 2 +- python/samples/sound_capture_py3.py | 67 ++++++++++++++++ python/samples/sound_stream_py3.py | 49 ++++++++++++ python/samples/worm.py | 6 +- python/src/Drawable.cpp | 34 ++++---- python/src/Drawable.hpp | 4 +- python/src/Font.cpp | 118 +++++++++++++++++++--------- python/src/RenderTarget.cpp | 30 +------ python/src/RenderWindow.cpp | 33 ++++---- python/src/String.cpp | 96 ++++++++++++++-------- python/src/Window.cpp | 2 +- python/src/main.cpp | 2 +- 14 files changed, 306 insertions(+), 140 deletions(-) create mode 100644 python/samples/sound_capture_py3.py create mode 100755 python/samples/sound_stream_py3.py diff --git a/python/PySFML/__init__.py b/python/PySFML/__init__.py index 79d6660f3..8b1378917 100644 --- a/python/PySFML/__init__.py +++ b/python/PySFML/__init__.py @@ -1,2 +1 @@ -import sf diff --git a/python/samples/opengl.py b/python/samples/opengl.py index e35df9e5f..b171a4783 100644 --- a/python/samples/opengl.py +++ b/python/samples/opengl.py @@ -1,6 +1,6 @@ #!/usr/bin/python -from PySFML import * +from PySFML import sf from OpenGL.GL import * from OpenGL.GLUT import * diff --git a/python/samples/sound_capture.py b/python/samples/sound_capture.py index bfb24d0a1..456ba59b6 100644 --- a/python/samples/sound_capture.py +++ b/python/samples/sound_capture.py @@ -1,6 +1,6 @@ #!/usr/bin/env python -from PySFML import * +from PySFML import sf def Main(): # Check that the device can capture audio diff --git a/python/samples/sound_capture_py3.py b/python/samples/sound_capture_py3.py new file mode 100644 index 000000000..2f2053da2 --- /dev/null +++ b/python/samples/sound_capture_py3.py @@ -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() diff --git a/python/samples/sound_stream_py3.py b/python/samples/sound_stream_py3.py new file mode 100755 index 000000000..9cae12797 --- /dev/null +++ b/python/samples/sound_stream_py3.py @@ -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() + diff --git a/python/samples/worm.py b/python/samples/worm.py index e43a9d921..2039f315b 100644 --- a/python/samples/worm.py +++ b/python/samples/worm.py @@ -44,7 +44,8 @@ class Apple(sf.Sprite): def __init__(self): apple_img = sf.Image() # Apple's image 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) self.SetCenter(apple_img.GetWidth()/2, apple_img.GetHeight()/2) self.size = apple_img.GetWidth() @@ -109,7 +110,8 @@ class Worm(list): self.rond = sf.Image() self.level_completed = False 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): self.targeted_length, self.angle, self.direction = 30, 0, 0 diff --git a/python/src/Drawable.cpp b/python/src/Drawable.cpp index d0fb70042..8f026c511 100644 --- a/python/src/Drawable.cpp +++ b/python/src/Drawable.cpp @@ -34,7 +34,9 @@ extern PyTypeObject PySfColorType; void CustomDrawable::Render (sf::RenderTarget& Target) const { 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 @@ -48,23 +50,19 @@ static PyObject * PySfDrawable_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { PySfDrawable *self; - self = (PySfDrawable *)type->tp_alloc(type, 0); - - if (self != NULL) - { - } - return (PyObject *)self; } - static int 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; -} +} + static PyObject * PySfDrawable_SetX(PySfDrawable* self, PyObject *args) { @@ -81,7 +79,7 @@ static PyObject * PySfDrawable_SetScale(PySfDrawable* self, PyObject *args) { float ScaleX, ScaleY; - if ( !PyArg_ParseTuple(args, "ff", &ScaleX, &ScaleY) ) + if (!PyArg_ParseTuple(args, "ff:Drawable.SetScale", &ScaleX, &ScaleY) ) return NULL; self->obj->SetScale(ScaleX, ScaleY); Py_RETURN_NONE; @@ -109,7 +107,7 @@ static PyObject * PySfDrawable_SetCenter(PySfDrawable* self, PyObject *args) { float x, y; - if ( !PyArg_ParseTuple(args, "ff", &x, &y) ) + if (!PyArg_ParseTuple(args, "ff:Drawable.SetCenter", &x, &y) ) return NULL; self->obj->SetCenter(x, y); Py_RETURN_NONE; @@ -127,7 +125,7 @@ PySfDrawable_SetColor(PySfDrawable* self, PyObject *args) PySfColor *Color = (PySfColor *)args; 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; } PySfColorUpdate(Color); @@ -170,7 +168,7 @@ static PyObject * PySfDrawable_Move(PySfDrawable* self, PyObject *args) { float x, y; - if ( !PyArg_ParseTuple(args, "ff", &x, &y) ) + if (!PyArg_ParseTuple(args, "ff:Drawable.Move", &x, &y) ) return NULL; self->obj->Move(x, y); Py_RETURN_NONE; @@ -185,7 +183,7 @@ static PyObject * PySfDrawable_Scale(PySfDrawable* self, PyObject *args) { float FactorX, FactorY; - if ( !PyArg_ParseTuple(args, "ff", &FactorX, &FactorY) ) + if (!PyArg_ParseTuple(args, "ff:Drawable.Scale", &FactorX, &FactorY) ) return NULL; self->obj->Scale(FactorX, FactorY); Py_RETURN_NONE; @@ -202,7 +200,7 @@ static PyObject * PySfDrawable_SetPosition(PySfDrawable* self, PyObject *args) { float Left, Top; - if ( !PyArg_ParseTuple(args, "ff", &Left, &Top) ) + if (!PyArg_ParseTuple(args, "ff:Drawable.SetPosition", &Left, &Top) ) return NULL; self->obj->SetPosition(Left, Top); Py_RETURN_NONE; @@ -212,7 +210,7 @@ static PyObject * PySfDrawable_TransformToLocal(PySfDrawable* self, PyObject *args) { float X, Y; - if ( !PyArg_ParseTuple(args, "ff", &X, &Y) ) + if (!PyArg_ParseTuple(args, "ff:Drawable.TransformToLocal", &X, &Y) ) return NULL; sf::Vector2f result = self->obj->TransformToLocal(sf::Vector2f(X, Y)); return Py_BuildValue("ff", result.x, result.y); @@ -222,7 +220,7 @@ static PyObject * PySfDrawable_TransformToGlobal(PySfDrawable* self, PyObject *args) { float X, Y; - if ( !PyArg_ParseTuple(args, "ff", &X, &Y) ) + if (!PyArg_ParseTuple(args, "ff:Drawable.TransformToGlobal", &X, &Y) ) return NULL; sf::Vector2f result = self->obj->TransformToGlobal(sf::Vector2f(X, Y)); return Py_BuildValue("ff", result.x, result.y); diff --git a/python/src/Drawable.hpp b/python/src/Drawable.hpp index 6e227271a..abedd8ea0 100644 --- a/python/src/Drawable.hpp +++ b/python/src/Drawable.hpp @@ -29,7 +29,7 @@ #include -#include "RenderWindow.hpp" +#include "RenderTarget.hpp" class CustomDrawable : public sf::Drawable @@ -37,7 +37,7 @@ class CustomDrawable : public sf::Drawable protected : virtual void Render(sf::RenderTarget& Target) const; public : - PySfRenderWindow *RenderWindow; + PySfRenderTarget *RenderTarget; PyObject *RenderFunction; }; diff --git a/python/src/Font.cpp b/python/src/Font.cpp index c6f49860d..1458a0bd4 100644 --- a/python/src/Font.cpp +++ b/python/src/Font.cpp @@ -59,27 +59,48 @@ PySfFont_LoadFromFile(PySfFont* self, PyObject *args, PyObject *kwds) const char *kwlist[] = {"Filename", "Charsize", "Charset", NULL}; unsigned int Charsize=30; char *Filename; - char *CharsetTmp = NULL; - int CharsetSize; - bool Result; - - if (! PyArg_ParseTupleAndKeywords(args, kwds, "s|Is#:Font.LoadFromFile", (char **)kwlist, &Filename, &Charsize, &CharsetTmp, &CharsetSize)) - return NULL; - - if (CharsetTmp) + char *Charset=NULL, *EncodingStr; + int Length; + bool result; + std::string Encoding; + if (PyArg_ParseTupleAndKeywords(args, kwds, "s|I:Font.LoadFromFile", (char **)kwlist, &Filename, &Charsize)) + result = self->obj->LoadFromFile(Filename, Charsize); + else if (PyArg_ParseTupleAndKeywords(args, kwds, "s|Iu:Font.LoadFromFile", (char **)kwlist, &Filename, &Charsize, &Charset)) { - if ((unsigned char)CharsetTmp[0] == 0xff && (unsigned char)CharsetTmp[1] == 0xfe) - Result = self->obj->LoadFromFile(Filename, Charsize, sf::Unicode::Text((const sf::Uint16 *)(CharsetTmp+2))); + PyErr_Clear(); +#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 - 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 - Result = self->obj->LoadFromFile(Filename, Charsize); - - if (Result) - Py_RETURN_TRUE; - else - Py_RETURN_FALSE; + { + PyErr_BadArgument(); + return NULL; + } + return PyBool_FromLong(result); } static PyObject * @@ -88,27 +109,48 @@ PySfFont_LoadFromMemory(PySfFont* self, PyObject *args, PyObject *kwds) const char *kwlist[] = {"Data", "Charsize", "Charset", NULL}; unsigned int Charsize=30, Size; char *Data; - char *CharsetTmp = NULL; - int CharsetSize; - bool Result; - - if (! PyArg_ParseTupleAndKeywords(args, kwds, "s#|Is#:Font.LoadFromMemory", (char **)kwlist, &Data, &Size, &Charsize, &CharsetTmp, &CharsetSize)) - return NULL; - - if (CharsetTmp) + char *Charset=NULL, *EncodingStr; + int Length; + bool result; + std::string Encoding; + if (PyArg_ParseTupleAndKeywords(args, kwds, "s#|I:Font.LoadFromMemory", (char **)kwlist, &Data, &Size, &Charsize)) + result = self->obj->LoadFromMemory(Data, Size, Charsize); + else if (PyArg_ParseTupleAndKeywords(args, kwds, "s#|Iu:Font.LoadFromMemory", (char **)kwlist, &Data, &Size, &Charsize, &Charset)) { - if ((unsigned char)CharsetTmp[0] == 0xff && (unsigned char)CharsetTmp[1] == 0xfe) - Result = self->obj->LoadFromMemory(Data, Size, Charsize, sf::Unicode::Text((const sf::Uint16 *)(CharsetTmp+2))); + PyErr_Clear(); +#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 - 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 - Result = self->obj->LoadFromMemory(Data, Size, Charsize); - - if (Result) - Py_RETURN_TRUE; - else - Py_RETURN_FALSE; + { + PyErr_BadArgument(); + return NULL; + } + return PyBool_FromLong(result); } static PyObject * @@ -139,16 +181,16 @@ PySfFont_GetGlyph(PySfFont* self, PyObject *args) } 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\ Filename : Font file to load\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])"}, - {"LoadFromMemory", (PyCFunction)PySfFont_LoadFromMemory, METH_VARARGS | METH_KEYWORDS, "LoadFromMemory(Data, CharSize, Charset)\n\ + 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, UnicodeCharset) or LoadFromMemory(Data, CharSize, Charset, Encoding='utf8')\n\ Load the font from a file in memory. Returns True if loading was successful.\n\ Data : data to load\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\ Get the SFML default built-in font (Arial)."}, {"GetCharacterSize", (PyCFunction)PySfFont_GetCharacterSize, METH_NOARGS, "GetCharacterSize()\n\ diff --git a/python/src/RenderTarget.cpp b/python/src/RenderTarget.cpp index 5b2afe243..4953f7272 100644 --- a/python/src/RenderTarget.cpp +++ b/python/src/RenderTarget.cpp @@ -33,21 +33,6 @@ extern PyTypeObject PySfColorType; 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 * PySfRenderTarget_Clear(PySfRenderTarget *self, PyObject *args) { @@ -87,8 +72,7 @@ PySfRenderTarget_GetView(PySfRenderTarget *self) static PyObject * PySfRenderTarget_PreserveOpenGLStates(PySfRenderTarget *self, PyObject *args) { - bool Optimize = PyBool_AsBool(args); - self->obj->PreserveOpenGLStates(Optimize); + self->obj->PreserveOpenGLStates(PyBool_AsBool(args)); Py_RETURN_NONE; } @@ -138,7 +122,7 @@ PyTypeObject PySfRenderTargetType = { "RenderTarget", /*tp_name*/ sizeof(PySfRenderTarget), /*tp_basicsize*/ 0, /*tp_itemsize*/ - (destructor)PySfRenderTarget_dealloc, /*tp_dealloc*/ + 0, /*tp_dealloc*/ 0, /*tp_print*/ 0, /*tp_getattr*/ 0, /*tp_setattr*/ @@ -162,16 +146,6 @@ PyTypeObject PySfRenderTargetType = { 0, /* tp_iter */ 0, /* tp_iternext */ 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 */ }; diff --git a/python/src/RenderWindow.cpp b/python/src/RenderWindow.cpp index 1e486a55f..1617c334a 100644 --- a/python/src/RenderWindow.cpp +++ b/python/src/RenderWindow.cpp @@ -38,12 +38,8 @@ #include -extern PyTypeObject PySfEventType; extern PyTypeObject PySfViewType; -extern PyTypeObject PySfColorType; extern PyTypeObject PySfWindowType; -extern PyTypeObject PySfWindowSettingsType; -extern PyTypeObject PySfVideoModeType; extern PyTypeObject PySfDrawableType; extern PyTypeObject PySfRenderTargetType; @@ -108,7 +104,9 @@ PySfRenderWindow_DrawObject(PySfRenderWindow *RenderWindow, PySfDrawable *Obj) { 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"); } RenderWindow->obj->Draw( *(Obj->obj) ); @@ -120,21 +118,18 @@ PySfRenderWindow_DrawObject(PySfRenderWindow *RenderWindow, PySfDrawable *Obj) static PyObject * PySfRenderWindow_Draw(PySfRenderWindow *self, PyObject *args) { - if (!args) + if (args == NULL) return NULL; - - if (!PySfRenderWindow_DrawObject(self, (PySfDrawable *)args)) { PyObject *iterator = PyObject_GetIter(args); PyObject *item; - + PyErr_Clear(); if (iterator == NULL) { PyErr_SetString(PyExc_TypeError, "Argument to Draw method is neither a Drawable nor an iterable."); return NULL; } - while ((item = PyIter_Next(iterator))) { if (!PySfRenderWindow_DrawObject(self, (PySfDrawable *)item)) @@ -144,16 +139,24 @@ PySfRenderWindow_Draw(PySfRenderWindow *self, PyObject *args) } Py_DECREF(item); } - 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; } 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\ 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\ diff --git a/python/src/String.cpp b/python/src/String.cpp index 09b9f8d62..b95517393 100644 --- a/python/src/String.cpp +++ b/python/src/String.cpp @@ -51,19 +51,16 @@ PySfString_new(PyTypeObject *type, PyObject *args, PyObject *kwds) return (PyObject *)self; } - static int PySfString_init(PySfString *self, PyObject *args, PyObject *kwds) { const char *kwlist[] = {"Text", "Font", "Size", NULL}; float Size = 30.f; - std::string Text = ""; - char *TextTmp = NULL; - unsigned int TextSize; + PyObject *Text=NULL; PySfFont *FontTmp = NULL; 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; if (FontTmp) @@ -71,39 +68,74 @@ PySfString_init(PySfString *self, PyObject *args, PyObject *kwds) else Font = (sf::Font *)&(sf::Font::GetDefaultFont()); - if (TextSize >= 2 && TextTmp) - if ((unsigned char)TextTmp[0] == 0xff && (unsigned char)TextTmp[1] == 0xfe) + if (Text != NULL) + { + if (PyUnicode_Check(Text)) { - self->obj = new sf::String(sf::Unicode::Text((const sf::Uint16 *)(TextTmp+2)), *Font, Size); - return 0; +#if Py_UNICODE_SIZE == 4 + 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 } - - if (TextTmp != NULL) - self->obj = new sf::String(sf::Unicode::Text((const sf::Uint8 *)(TextTmp)), *Font, Size); +#ifdef IS_PY3K + else if (PyBytes_Check(Text)) + 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 - self->obj = new sf::String(); + self->obj = new sf::String("", *Font, Size); return 0; } - - static PyObject * PySfString_SetText(PySfString* self, PyObject *args) { - char *TextTmp = NULL; - int Size; - if (!PyArg_Parse(args, "s#", &TextTmp, &Size)) - return NULL; - - if (Size >= 2) + char *Text, *EncodingStr=NULL; + int Length; + std::string Encoding; + if (PyArg_ParseTuple(args, "u:String.SetText", &Text)) { - 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))); - Py_RETURN_NONE; + Encoding.assign(EncodingStr); + 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; } @@ -146,12 +178,12 @@ PySfString_GetStyle(PySfString* self) static PyObject * PySfString_GetText(PySfString* self) { - std::string Text = (std::string(self->obj->GetText())); -#ifdef IS_PY3K - return PyUnicode_DecodeUTF8(Text.c_str(), (Py_ssize_t)Text.length(), "replace"); +#if Py_UNICODE_SIZE == 4 + sf::Unicode::UTF32String Text(self->obj->GetText()); #else - return PyString_FromString(Text.c_str()); + sf::Unicode::UTF16String Text(self->obj->GetText()); #endif + return PyUnicode_FromUnicode((const Py_UNICODE*)Text.c_str(), Text.length()); } static PyObject * @@ -189,8 +221,8 @@ static PyMethodDef PySfString_methods[] = { {"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\ 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"}, - {"GetText", (PyCFunction)PySfString_GetText, METH_NOARGS, "GetText()\nGet the 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 as an unicode string."}, {"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."}, {"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*/ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/ "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_clear */ 0, /* tp_richcompare */ diff --git a/python/src/Window.cpp b/python/src/Window.cpp index 54da51f43..9844ddf68 100644 --- a/python/src/Window.cpp +++ b/python/src/Window.cpp @@ -287,7 +287,7 @@ Create a window.\n\ Mode : Video mode to use (sf.VideoMode instance)\n\ Title : Title of the window\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."}, {"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."}, diff --git a/python/src/main.cpp b/python/src/main.cpp index b1d5fefa1..9b2a4441b 100644 --- a/python/src/main.cpp +++ b/python/src/main.cpp @@ -101,7 +101,7 @@ static PyModuleDef module_def = { module_methods, NULL, NULL, NULL, NULL }; -PyObject * +PyMODINIT_FUNC PyInit_sf(void) #else #define INITERROR return From 7e7489b34a2e964e629ccfae4f8e420054a6cc50 Mon Sep 17 00:00:00 2001 From: remi-k Date: Fri, 27 Feb 2009 23:50:02 +0000 Subject: [PATCH 12/22] Removed RenderTarget git-svn-id: https://sfml.svn.sourceforge.net/svnroot/sfml/trunk@1025 4e206d99-4929-0410-ac5d-dfc041789085 --- python/setup.py | 2 +- python/src/Drawable.cpp | 6 +- python/src/Drawable.hpp | 4 +- python/src/RenderTarget.cpp | 151 ------------------------------------ python/src/RenderTarget.hpp | 38 --------- python/src/RenderWindow.cpp | 103 +++++++++++++++++++----- python/src/main.cpp | 3 - 7 files changed, 91 insertions(+), 216 deletions(-) delete mode 100644 python/src/RenderTarget.cpp delete mode 100644 python/src/RenderTarget.hpp diff --git a/python/setup.py b/python/setup.py index db8cb7cb0..9a6813fc8 100644 --- a/python/setup.py +++ b/python/setup.py @@ -13,7 +13,7 @@ setup(name='PySFML', ext_modules=[ Extension('PySFML.sf', \ ['src/Clock.cpp', 'src/Color.cpp', 'src/Drawable.cpp', \ 'src/Event.cpp', 'src/Image.cpp', 'src/Input.cpp', 'src/Key.cpp', 'src/main.cpp', 'src/Music.cpp', \ - 'src/PostFX.cpp', 'src/Rect.cpp', 'src/RenderTarget.cpp', 'src/RenderWindow.cpp', 'src/Sleep.cpp', \ + 'src/PostFX.cpp', 'src/Rect.cpp', 'src/RenderWindow.cpp', 'src/Sleep.cpp', \ 'src/Sprite.cpp', 'src/String.cpp', 'src/VideoMode.cpp', 'src/View.cpp', 'src/Window.cpp', \ 'src/Joy.cpp', 'src/Mouse.cpp', 'src/WindowStyle.cpp', 'src/Blend.cpp', 'src/Sound.cpp', \ 'src/SoundBuffer.cpp', 'src/Listener.cpp', 'src/SoundRecorder.cpp', 'src/SoundBufferRecorder.cpp', \ diff --git a/python/src/Drawable.cpp b/python/src/Drawable.cpp index 8f026c511..4ac64df96 100644 --- a/python/src/Drawable.cpp +++ b/python/src/Drawable.cpp @@ -31,10 +31,10 @@ extern PyTypeObject PySfColorType; -void CustomDrawable::Render (sf::RenderTarget& Target) const +void CustomDrawable::Render(sf::RenderTarget& Target) const { if (RenderFunction) - PyObject_CallFunction(RenderFunction, (char *)"O", RenderTarget); + PyObject_CallFunction(RenderFunction, (char *)"O", RenderWindow); else PyErr_SetString(PyExc_RuntimeError, "Custom drawables must have a render method defined"); } @@ -59,7 +59,7 @@ PySfDrawable_init(PySfDrawable *self, PyObject *args, PyObject *kwds) { self->obj = new CustomDrawable(); self->obj->RenderFunction = NULL; - self->obj->RenderTarget = NULL; + self->obj->RenderWindow = NULL; return 0; } diff --git a/python/src/Drawable.hpp b/python/src/Drawable.hpp index abedd8ea0..6e227271a 100644 --- a/python/src/Drawable.hpp +++ b/python/src/Drawable.hpp @@ -29,7 +29,7 @@ #include -#include "RenderTarget.hpp" +#include "RenderWindow.hpp" class CustomDrawable : public sf::Drawable @@ -37,7 +37,7 @@ class CustomDrawable : public sf::Drawable protected : virtual void Render(sf::RenderTarget& Target) const; public : - PySfRenderTarget *RenderTarget; + PySfRenderWindow *RenderWindow; PyObject *RenderFunction; }; diff --git a/python/src/RenderTarget.cpp b/python/src/RenderTarget.cpp deleted file mode 100644 index 4953f7272..000000000 --- a/python/src/RenderTarget.cpp +++ /dev/null @@ -1,151 +0,0 @@ -//////////////////////////////////////////////////////////// -// -// PySFML - Python binding for SFML (Simple and Fast Multimedia Library) -// Copyright (C) 2007, 2008 Rémi Koenig (remi.k2620@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. -// -//////////////////////////////////////////////////////////// - -#include "RenderTarget.hpp" -#include "Color.hpp" -#include "View.hpp" - -#include "compat.hpp" - - -extern PyTypeObject PySfColorType; -extern PyTypeObject PySfViewType; - - -static PyObject * -PySfRenderTarget_Clear(PySfRenderTarget *self, PyObject *args) -{ - PySfColor *Color; - int size = PyTuple_Size(args); - if (size == 1) - { - if (!PyArg_ParseTuple(args, "O!:RenderTarget.Clear", &PySfColorType, &Color)) - return NULL; - PySfColorUpdate(Color); - self->obj->Clear(*(Color->obj)); - } - else if (size == 0) - { - self->obj->Clear(sf::Color::Black); - } - else - { - PyErr_SetString(PyExc_TypeError, "sf.RenderTarget.Clear takes one or zero argument"); - return NULL; - } - Py_RETURN_NONE; -} - - -static PyObject * -PySfRenderTarget_GetView(PySfRenderTarget *self) -{ - PySfView *View; - - View = GetNewPySfView(); - View->obj = new sf::View(self->obj->GetView()); - - return (PyObject *)View; -} - -static PyObject * -PySfRenderTarget_PreserveOpenGLStates(PySfRenderTarget *self, PyObject *args) -{ - self->obj->PreserveOpenGLStates(PyBool_AsBool(args)); - Py_RETURN_NONE; -} - -static PyObject * -PySfRenderTarget_SetView(PySfRenderTarget* self, PyObject *args) -{ - PySfView *View = (PySfView *)args; - if (!PyObject_TypeCheck(View, &PySfViewType)) - { - PyErr_SetString(PyExc_TypeError, "RenderTarget.SetView() Argument is not a sf.View"); - return NULL; - } - self->obj->SetView( *(View->obj)); - Py_RETURN_NONE; -} - -static PyObject * -PySfRenderTarget_GetDefaultView(PySfRenderTarget *self) -{ - PySfView *View; - - View = GetNewPySfView(); - View->Owner = false; - View->obj = &(self->obj->GetDefaultView()); - - return (PyObject *)View; -} - -static PyMethodDef PySfRenderTarget_methods[] = { - {"Clear", (PyCFunction)PySfRenderTarget_Clear, METH_VARARGS, "Clear(FillColor)\n\ -Clear the entire target with a single color.\n\ - FillColor : Color to use to clear the render target."}, - {"GetDefaultView", (PyCFunction)PySfRenderTarget_GetDefaultView, METH_NOARGS, "GetDefaultView()\n\ -Get the default view of the window for read / write (returns a sf.View instance)."}, - {"GetView", (PyCFunction)PySfRenderTarget_GetView, METH_NOARGS, "GetView()\n\ -Get the current view rectangle (returns a sf.View instance)."}, - {"PreserveOpenGLStates", (PyCFunction)PySfRenderTarget_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"}, - {"SetView", (PyCFunction)PySfRenderTarget_SetView, METH_O, "SetView(View)\n\ -Change the current active view. View must be a sf.View instance."}, - {NULL} /* Sentinel */ -}; - -PyTypeObject PySfRenderTargetType = { - head_init - "RenderTarget", /*tp_name*/ - sizeof(PySfRenderTarget), /*tp_basicsize*/ - 0, /*tp_itemsize*/ - 0, /*tp_dealloc*/ - 0, /*tp_print*/ - 0, /*tp_getattr*/ - 0, /*tp_setattr*/ - 0, /*tp_compare*/ - 0, /*tp_repr*/ - 0, /*tp_as_number*/ - 0, /*tp_as_sequence*/ - 0, /*tp_as_mapping*/ - 0, /*tp_hash */ - 0, /*tp_call*/ - 0, /*tp_str*/ - 0, /*tp_getattro*/ - 0, /*tp_setattro*/ - 0, /*tp_as_buffer*/ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/ - "Base class for all render targets (window, image, ...).", /* tp_doc */ - 0, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - PySfRenderTarget_methods, /* tp_methods */ -}; - - diff --git a/python/src/RenderTarget.hpp b/python/src/RenderTarget.hpp deleted file mode 100644 index e57a5a552..000000000 --- a/python/src/RenderTarget.hpp +++ /dev/null @@ -1,38 +0,0 @@ -//////////////////////////////////////////////////////////// -// -// PySFML - Python binding for SFML (Simple and Fast Multimedia Library) -// Copyright (C) 2007, 2008 Rémi Koenig (remi.k2620@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. -// -//////////////////////////////////////////////////////////// - -#ifndef __PYRENDERTARGET_H -#define __PYRENDERTARGET_H - -#include - -#include - -typedef struct { - PyObject_HEAD - sf::RenderTarget *obj; -} PySfRenderTarget; - -#endif - diff --git a/python/src/RenderWindow.cpp b/python/src/RenderWindow.cpp index 1617c334a..0985201e6 100644 --- a/python/src/RenderWindow.cpp +++ b/python/src/RenderWindow.cpp @@ -23,15 +23,11 @@ //////////////////////////////////////////////////////////// #include "RenderWindow.hpp" -#include "Event.hpp" -#include "VideoMode.hpp" -#include "Drawable.hpp" -#include "Color.hpp" -#include "Rect.hpp" #include "View.hpp" #include "Image.hpp" #include "Window.hpp" -#include "WindowSettings.hpp" +#include "Color.hpp" +#include "Drawable.hpp" #include "compat.hpp" @@ -40,8 +36,9 @@ extern PyTypeObject PySfViewType; extern PyTypeObject PySfWindowType; -extern PyTypeObject PySfDrawableType; -extern PyTypeObject PySfRenderTargetType; +extern PyTypeObject PySfRenderWindowType; +extern PyTypeObject PySfColorType; +extern PyTypeObject PySfDrawableType; static void @@ -104,9 +101,9 @@ PySfRenderWindow_DrawObject(PySfRenderWindow *RenderWindow, PySfDrawable *Obj) { if (PyObject_HasAttrString((PyObject *)Obj, "Render")) { - Py_DECREF(Obj->obj->RenderTarget); - Obj->obj->RenderTarget = (PySfRenderTarget *)RenderWindow; - Py_DECREF(Obj->obj->RenderFunction); + Py_XDECREF(Obj->obj->RenderWindow); + Obj->obj->RenderWindow = RenderWindow; + Py_XDECREF(Obj->obj->RenderFunction); Obj->obj->RenderFunction = PyObject_GetAttrString((PyObject *)Obj, "Render"); } RenderWindow->obj->Draw( *(Obj->obj) ); @@ -144,6 +141,42 @@ PySfRenderWindow_Draw(PySfRenderWindow *self, PyObject *args) if (PyErr_Occurred()) return NULL; Py_RETURN_NONE; +} + + +static PyObject * +PySfRenderWindow_Clear(PySfRenderWindow *self, PyObject *args) +{ + PySfColor *Color; + int size = PyTuple_Size(args); + if (size == 1) + { + if (!PyArg_ParseTuple(args, "O!:RenderWindow.Clear", &PySfColorType, &Color)) + return NULL; + PySfColorUpdate(Color); + self->obj->Clear(*(Color->obj)); + } + else if (size == 0) + { + self->obj->Clear(sf::Color::Black); + } + else + { + PyErr_SetString(PyExc_TypeError, "RenderWindow.Clear() takes one or zero argument"); + return NULL; + } + Py_RETURN_NONE; +} + +static PyObject * +PySfRenderWindow_GetView(PySfRenderWindow *self) +{ + PySfView *View; + + View = GetNewPySfView(); + View->obj = new sf::View(self->obj->GetView()); + + return (PyObject *)View; } static PyObject * @@ -151,9 +184,48 @@ PySfRenderWindow_PreserveOpenGLStates(PySfRenderWindow *self, PyObject *args) { self->obj->PreserveOpenGLStates(PyBool_AsBool(args)); Py_RETURN_NONE; +} + +static PyObject * +PySfRenderWindow_SetView(PySfRenderWindow* self, PyObject *args) +{ + PySfView *View = (PySfView *)args; + if (!PyObject_TypeCheck(View, &PySfViewType)) + { + PyErr_SetString(PyExc_TypeError, "RenderWindow.SetView() Argument is not a sf.View"); + return NULL; + } + self->obj->SetView( *(View->obj)); + Py_RETURN_NONE; +} + +static PyObject * +PySfRenderWindow_GetDefaultView(PySfRenderWindow *self) +{ + PySfView *View; + + View = GetNewPySfView(); + View->Owner = false; + View->obj = &(self->obj->GetDefaultView()); + + return (PyObject *)View; } static PyMethodDef PySfRenderWindow_methods[] = { + {"Clear", (PyCFunction)PySfRenderWindow_Clear, METH_VARARGS, "Clear(FillColor)\n\ +Clear the entire target with a single color.\n\ + FillColor : Color to use to clear the render target."}, + {"GetDefaultView", (PyCFunction)PySfRenderWindow_GetDefaultView, METH_NOARGS, "GetDefaultView()\n\ +Get the default view of the window for read / write (returns a sf.View instance)."}, + {"GetView", (PyCFunction)PySfRenderWindow_GetView, METH_NOARGS, "GetView()\n\ +Get the current view rectangle (returns a sf.View instance)."}, + {"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"}, + {"SetView", (PyCFunction)PySfRenderWindow_SetView, METH_O, "SetView(View)\n\ +Change the current active view. View must be a sf.View instance."}, + {"Draw", (PyCFunction)PySfRenderWindow_Draw, METH_O, "Draw(Drawable)\n\ +Draw something on the window. The argument can be a drawable or any object supporting the iterator protocol and containing drawables (for example a tuple of drawables)."}, {"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"}, @@ -164,8 +236,6 @@ Convert a point in window coordinates into view coordinates. Returns a tuple of WindowX : X coordinate of the point to convert, relative to the window\n\ WindowY : Y coordinate of the point to convert, relative to the window\n\ TargetView : Target view to convert the point to (NULL by default -- uses the current view)."}, - {"Draw", (PyCFunction)PySfRenderWindow_Draw, METH_O, "Draw(Drawable)\n\ -Draw something on the window. The argument can be a drawable or any object supporting the iterator protocol and containing drawables (for example a tuple of drawables)."}, {NULL} /* Sentinel */ }; @@ -207,17 +277,14 @@ Parameters:\n\ PySfRenderWindow_methods, /* tp_methods */ 0, /* tp_members */ 0, /* tp_getset */ - 0, /* tp_base */ + &PySfWindowType, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ (initproc)PySfRenderWindow_init, /* tp_init */ 0, /* tp_alloc */ - PySfRenderWindow_new, /* tp_new */ - 0, /* tp_free */ - 0, /* tp_is_gc */ - Py_BuildValue("(OO)", &PySfWindowType, &PySfRenderTargetType) /* tp_bases */ + PySfRenderWindow_new, /* tp_new */ }; diff --git a/python/src/main.cpp b/python/src/main.cpp index 9b2a4441b..517b7bdaf 100644 --- a/python/src/main.cpp +++ b/python/src/main.cpp @@ -57,7 +57,6 @@ extern PyTypeObject PySfWindowType; extern PyTypeObject PySfWindowSettingsType; extern PyTypeObject PySfStyleType; extern PyTypeObject PySfRenderWindowType; -extern PyTypeObject PySfRenderTargetType; extern PyTypeObject PySfViewType; extern PyTypeObject PySfInputType; @@ -124,8 +123,6 @@ initsf(void) INITERROR; if (PyType_Ready(&PySfStyleType) < 0) INITERROR; - if (PyType_Ready(&PySfRenderTargetType) < 0) - INITERROR; if (PyType_Ready(&PySfRenderWindowType) < 0) INITERROR; if (PyType_Ready(&PySfVideoModeType) < 0) From c68876a85858deb2303f9bdc02cc72a79ee4a2ae Mon Sep 17 00:00:00 2001 From: laurentgom Date: Sat, 28 Feb 2009 19:11:01 +0000 Subject: [PATCH 13/22] Blend::Add now uses source alpha git-svn-id: https://sfml.svn.sourceforge.net/svnroot/sfml/trunk@1026 4e206d99-4929-0410-ac5d-dfc041789085 --- src/SFML/Audio/SoundStream.cpp | 2 +- src/SFML/Graphics/Drawable.cpp | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/SFML/Audio/SoundStream.cpp b/src/SFML/Audio/SoundStream.cpp index f5b87c430..f5ff3901f 100644 --- a/src/SFML/Audio/SoundStream.cpp +++ b/src/SFML/Audio/SoundStream.cpp @@ -328,7 +328,7 @@ bool SoundStream::FillQueue() void SoundStream::ClearQueue() { // Get the number of buffers still in the queue - ALint NbQueued; + ALint NbQueued; ALCheck(alGetSourcei(Sound::mySource, AL_BUFFERS_QUEUED, &NbQueued)); // Unqueue them all diff --git a/src/SFML/Graphics/Drawable.cpp b/src/SFML/Graphics/Drawable.cpp index 04f316783..8651c9eeb 100644 --- a/src/SFML/Graphics/Drawable.cpp +++ b/src/SFML/Graphics/Drawable.cpp @@ -382,7 +382,7 @@ void Drawable::Draw(RenderTarget& Target) const switch (myBlendMode) { case Blend::Alpha : GLCheck(glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)); break; - case Blend::Add : GLCheck(glBlendFunc(GL_ONE, GL_ONE)); break; + case Blend::Add : GLCheck(glBlendFunc(GL_SRC_ALPHA, GL_ONE)); break; case Blend::Multiply : GLCheck(glBlendFunc(GL_DST_COLOR, GL_ZERO)); break; default : break; } From 5c74cc080092ee79de2ad352cd90c7051da30605 Mon Sep 17 00:00:00 2001 From: ceylo Date: Sat, 28 Feb 2009 20:38:35 +0000 Subject: [PATCH 14/22] Added working directory initializer. git-svn-id: https://sfml.svn.sourceforge.net/svnroot/sfml/trunk@1027 4e206d99-4929-0410-ac5d-dfc041789085 --- src/SFML/System/Initializer.cpp | 108 ++++++++++++++++++++++++++++++++ 1 file changed, 108 insertions(+) create mode 100644 src/SFML/System/Initializer.cpp diff --git a/src/SFML/System/Initializer.cpp b/src/SFML/System/Initializer.cpp new file mode 100644 index 000000000..acac29439 --- /dev/null +++ b/src/SFML/System/Initializer.cpp @@ -0,0 +1,108 @@ +//////////////////////////////////////////////////////////// +// +// SFML - Simple and Fast Multimedia Library +// Copyright (C) 2007-2008 Lucas Soltic (elmerod@gmail.com) and Laurent Gomila (laurent.gom@gmail.com) +// +// This software is provided 'as-is', without any express or implied warranty. +// In no event will the authors be held liable for any damages arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it freely, +// subject to the following restrictions: +// +// 1. The origin of this software must not be misrepresented; +// you must not claim that you wrote the original software. +// If you use this software in a product, an acknowledgment +// in the product documentation would be appreciated but is not required. +// +// 2. Altered source versions must be plainly marked as such, +// and must not be misrepresented as being the original software. +// +// 3. This notice may not be removed or altered from any source distribution. +// +//////////////////////////////////////////////////////////// + +//////////////////////////////////////////////////////////// +// Headers +//////////////////////////////////////////////////////////// +#include + + +#ifdef SFML_SYSTEM_MACOS + +#include +#include + +namespace +{ + +//////////////////////////////////////////////////////////// +/// Under Mac OS X, when launching an application from the Finder, +/// the default working directory is the user home directory ; +/// when launching from Xcode, the default one is the directory +/// containing the application. In order to produce a uniform behaviour +/// and simplify the use of resources, SFML sets the working directory to +/// the Resources folder of the application bundle. +/// The "constructor" attribute forces the function to be called +/// at library loading time. +//////////////////////////////////////////////////////////// + +void working_directory_initializer(void) __attribute__ ((constructor)); +void working_directory_initializer(void) +{ + char pathBuffer[4096]; + + // Get the application bundle + CFBundleRef mainBundle = CFBundleGetMainBundle(); + + if (!mainBundle) + { + std::cerr << "*** SFML: error getting the application main bundle" << std::endl; + return; + } + + // Get the resource directory URL + CFURLRef resourceDirectory = CFBundleCopyResourcesDirectoryURL(mainBundle); + + if (!resourceDirectory) + { + std::cerr << "*** SFML: error getting the resource directory of the main bundle" << std::endl; + return; + } + + // Convert it as absolute URL + CFURLRef absoluteURL = CFURLCopyAbsoluteURL(resourceDirectory); + + if (!absoluteURL) + { + std::cerr << "*** SFML: error gettint the resource directory as an absolute URL" << std::endl; + CFRelease(resourceDirectory); + return; + } + + // Get the POSIX style path + CFStringRef absolutePath = CFURLCopyFileSystemPath(absoluteURL, kCFURLPOSIXPathStyle); + + if (!absolutePath) + { + std::cerr << "*** SFML: error converting the resource directory URL as a POSIX path" << std::endl; + CFRelease(absoluteURL); + CFRelease(resourceDirectory); + return; + } + + // Get the path as C string and set it + if (CFStringGetCString(absolutePath, pathBuffer, 4096, kCFStringEncodingASCII)) + chdir(pathBuffer); + else + std::cerr << "*** SFML: error copying the resource directory path in the C buffer" << std::endl; + + CFRelease(absolutePath); + CFRelease(absoluteURL); + CFRelease(resourceDirectory); +} + +} // anonymous namespace + +#endif // SFML_SYSTEM_MACOS + From 9919e57bbdaa2365d332804230468082c633fb5c Mon Sep 17 00:00:00 2001 From: ceylo Date: Sat, 28 Feb 2009 20:41:00 +0000 Subject: [PATCH 15/22] Fixed namespace. git-svn-id: https://sfml.svn.sourceforge.net/svnroot/sfml/trunk@1028 4e206d99-4929-0410-ac5d-dfc041789085 --- src/SFML/System/Initializer.cpp | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/src/SFML/System/Initializer.cpp b/src/SFML/System/Initializer.cpp index acac29439..f5a31e499 100644 --- a/src/SFML/System/Initializer.cpp +++ b/src/SFML/System/Initializer.cpp @@ -33,7 +33,10 @@ #include #include -namespace +namespace sf +{ + +namespace priv { //////////////////////////////////////////////////////////// @@ -102,7 +105,10 @@ void working_directory_initializer(void) CFRelease(resourceDirectory); } -} // anonymous namespace +} // namespace priv + +} // namespace sf + #endif // SFML_SYSTEM_MACOS From 34ce4c00f5186217bc8d7a5785c4fe4f5753ab88 Mon Sep 17 00:00:00 2001 From: laurentgom Date: Sat, 28 Feb 2009 20:47:48 +0000 Subject: [PATCH 16/22] Fixed Initializer.cpp to use the proper naming conventions :) git-svn-id: https://sfml.svn.sourceforge.net/svnroot/sfml/trunk@1029 4e206d99-4929-0410-ac5d-dfc041789085 --- src/SFML/System/Initializer.cpp | 53 ++++++++++++++++----------------- 1 file changed, 25 insertions(+), 28 deletions(-) diff --git a/src/SFML/System/Initializer.cpp b/src/SFML/System/Initializer.cpp index f5a31e499..ad24a1ecc 100644 --- a/src/SFML/System/Initializer.cpp +++ b/src/SFML/System/Initializer.cpp @@ -1,7 +1,7 @@ //////////////////////////////////////////////////////////// // // SFML - Simple and Fast Multimedia Library -// Copyright (C) 2007-2008 Lucas Soltic (elmerod@gmail.com) and Laurent Gomila (laurent.gom@gmail.com) +// Copyright (C) 2007-2009 Lucas Soltic (elmerod@gmail.com) and Laurent Gomila (laurent.gom@gmail.com) // // This software is provided 'as-is', without any express or implied warranty. // In no event will the authors be held liable for any damages arising from the use of this software. @@ -35,10 +35,8 @@ namespace sf { - namespace priv { - //////////////////////////////////////////////////////////// /// Under Mac OS X, when launching an application from the Finder, /// the default working directory is the user home directory ; @@ -49,60 +47,59 @@ namespace priv /// The "constructor" attribute forces the function to be called /// at library loading time. //////////////////////////////////////////////////////////// - -void working_directory_initializer(void) __attribute__ ((constructor)); -void working_directory_initializer(void) +void InitializeWorkingDirectory(void) __attribute__ ((constructor)); +void InitializeWorkingDirectory(void) { - char pathBuffer[4096]; + char PathBuffer[4096]; // Get the application bundle - CFBundleRef mainBundle = CFBundleGetMainBundle(); + CFBundleRef MainBundle = CFBundleGetMainBundle(); - if (!mainBundle) + if (!MainBundle) { - std::cerr << "*** SFML: error getting the application main bundle" << std::endl; + std::cerr << "Error getting the application main bundle" << std::endl; return; } // Get the resource directory URL - CFURLRef resourceDirectory = CFBundleCopyResourcesDirectoryURL(mainBundle); + CFURLRef ResourceDirectory = CFBundleCopyResourcesDirectoryURL(MainBundle); - if (!resourceDirectory) + if (!ResourceDirectory) { - std::cerr << "*** SFML: error getting the resource directory of the main bundle" << std::endl; + std::cerr << "Error getting the resource directory of the main bundle" << std::endl; return; } // Convert it as absolute URL - CFURLRef absoluteURL = CFURLCopyAbsoluteURL(resourceDirectory); + CFURLRef AbsoluteURL = CFURLCopyAbsoluteURL(ResourceDirectory); - if (!absoluteURL) + if (!AbsoluteURL) { - std::cerr << "*** SFML: error gettint the resource directory as an absolute URL" << std::endl; - CFRelease(resourceDirectory); + std::cerr << "Error getting the resource directory as an absolute URL" << std::endl; + CFRelease(ResourceDirectory); return; } // Get the POSIX style path - CFStringRef absolutePath = CFURLCopyFileSystemPath(absoluteURL, kCFURLPOSIXPathStyle); + CFStringRef AbsolutePath = CFURLCopyFileSystemPath(AbsoluteURL, kCFURLPOSIXPathStyle); - if (!absolutePath) + if (!AbsolutePath) { - std::cerr << "*** SFML: error converting the resource directory URL as a POSIX path" << std::endl; - CFRelease(absoluteURL); - CFRelease(resourceDirectory); + std::cerr << "Error converting the resource directory URL as a POSIX path" << std::endl; + CFRelease(AbsoluteURL); + CFRelease(ResourceDirectory); return; } // Get the path as C string and set it - if (CFStringGetCString(absolutePath, pathBuffer, 4096, kCFStringEncodingASCII)) - chdir(pathBuffer); + if (CFStringGetCString(AbsolutePath, PathBuffer, 4096, kCFStringEncodingASCII)) + chdir(PathBuffer); else - std::cerr << "*** SFML: error copying the resource directory path in the C buffer" << std::endl; + std::cerr << "Error copying the resource directory path in the C buffer" << std::endl; - CFRelease(absolutePath); - CFRelease(absoluteURL); - CFRelease(resourceDirectory); + CFRelease(AbsolutePath); + CFRelease(AbsoluteURL); + CFRelease(ResourceDirectory); } } // namespace priv From 3553b83806f7a1e0c429596c5e2016af6e2e8ff2 Mon Sep 17 00:00:00 2001 From: ceylo Date: Sat, 28 Feb 2009 21:00:59 +0000 Subject: [PATCH 17/22] Using assertions instead of cerr logging. git-svn-id: https://sfml.svn.sourceforge.net/svnroot/sfml/trunk@1030 4e206d99-4929-0410-ac5d-dfc041789085 --- src/SFML/System/Initializer.cpp | 37 ++++++--------------------------- 1 file changed, 6 insertions(+), 31 deletions(-) diff --git a/src/SFML/System/Initializer.cpp b/src/SFML/System/Initializer.cpp index ad24a1ecc..8cdfdf407 100644 --- a/src/SFML/System/Initializer.cpp +++ b/src/SFML/System/Initializer.cpp @@ -54,48 +54,23 @@ void InitializeWorkingDirectory(void) // Get the application bundle CFBundleRef MainBundle = CFBundleGetMainBundle(); - - if (!MainBundle) - { - std::cerr << "Error getting the application main bundle" << std::endl; - return; - } + assert(MainBundle != NULL); // Get the resource directory URL CFURLRef ResourceDirectory = CFBundleCopyResourcesDirectoryURL(MainBundle); - - if (!ResourceDirectory) - { - std::cerr << "Error getting the resource directory of the main bundle" << std::endl; - return; - } + assert(ResourceDirectory != NULL); // Convert it as absolute URL CFURLRef AbsoluteURL = CFURLCopyAbsoluteURL(ResourceDirectory); - - if (!AbsoluteURL) - { - std::cerr << "Error getting the resource directory as an absolute URL" << std::endl; - CFRelease(ResourceDirectory); - return; - } + assert(AbsoluteURL != NULL); // Get the POSIX style path CFStringRef AbsolutePath = CFURLCopyFileSystemPath(AbsoluteURL, kCFURLPOSIXPathStyle); - - if (!AbsolutePath) - { - std::cerr << "Error converting the resource directory URL as a POSIX path" << std::endl; - CFRelease(AbsoluteURL); - CFRelease(ResourceDirectory); - return; - } + assert(AbsolutePath != NULL); // Get the path as C string and set it - if (CFStringGetCString(AbsolutePath, PathBuffer, 4096, kCFStringEncodingASCII)) - chdir(PathBuffer); - else - std::cerr << "Error copying the resource directory path in the C buffer" << std::endl; + assert(CFStringGetCString(AbsolutePath, PathBuffer, 4096, kCFStringEncodingASCII) == true); + assert(chdir(PathBuffer) == 0); CFRelease(AbsolutePath); CFRelease(AbsoluteURL); From 3664d275cbc34255010334dbd4ed258c5a8d098c Mon Sep 17 00:00:00 2001 From: laurentgom Date: Sat, 28 Feb 2009 21:20:01 +0000 Subject: [PATCH 18/22] Fixed warnings in Unicode.inl git-svn-id: https://sfml.svn.sourceforge.net/svnroot/sfml/trunk@1031 4e206d99-4929-0410-ac5d-dfc041789085 --- include/SFML/System/Unicode.hpp | 2 +- include/SFML/System/Unicode.inl | 6 +++--- src/SFML/System/Unicode.cpp | 2 +- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/include/SFML/System/Unicode.hpp b/include/SFML/System/Unicode.hpp index 6463ed8d8..c79c8748f 100644 --- a/include/SFML/System/Unicode.hpp +++ b/include/SFML/System/Unicode.hpp @@ -277,7 +277,7 @@ private : //////////////////////////////////////////////////////////// // Static member data //////////////////////////////////////////////////////////// - static const char UTF8TrailingBytes[256]; ///< Lookup table to find the length of an UTF-8 sequence + static const int UTF8TrailingBytes[256]; ///< Lookup table to find the length of an UTF-8 sequence static const Uint32 UTF8Offsets[6]; ///< Magic values to subtract during UTF-8 conversions static const Uint8 UTF8FirstBytes[7]; ///< First bytes for UTF-8 sequences }; diff --git a/include/SFML/System/Unicode.inl b/include/SFML/System/Unicode.inl index 2dbb3a253..08f055e91 100644 --- a/include/SFML/System/Unicode.inl +++ b/include/SFML/System/Unicode.inl @@ -104,7 +104,7 @@ inline Out Unicode::UTF8ToUTF16(In Begin, In End, Out Output, Uint16 Replacement while (Begin < End) { Uint32 c = 0; - int TrailingBytes = UTF8TrailingBytes[*Begin]; + int TrailingBytes = UTF8TrailingBytes[static_cast(*Begin)]; if (Begin + TrailingBytes < End) { // First decode the UTF-8 character @@ -165,7 +165,7 @@ inline Out Unicode::UTF8ToUTF32(In Begin, In End, Out Output, Uint32 Replacement while (Begin < End) { Uint32 c = 0; - int TrailingBytes = UTF8TrailingBytes[*Begin]; + int TrailingBytes = UTF8TrailingBytes[static_cast(*Begin)]; if (Begin + TrailingBytes < End) { // First decode the UTF-8 character @@ -424,7 +424,7 @@ inline std::size_t Unicode::GetUTF8Length(In Begin, In End) std::size_t Length = 0; while (Begin < End) { - int NbBytes = UTF8TrailingBytes[*Begin]; + int NbBytes = UTF8TrailingBytes[static_cast(*Begin)]; if (Begin + NbBytes < End) ++Length; diff --git a/src/SFML/System/Unicode.cpp b/src/SFML/System/Unicode.cpp index 0b5345278..f921b5001 100644 --- a/src/SFML/System/Unicode.cpp +++ b/src/SFML/System/Unicode.cpp @@ -78,7 +78,7 @@ namespace sf //////////////////////////////////////////////////////////// // Static member data //////////////////////////////////////////////////////////// -const char Unicode::UTF8TrailingBytes[256] = +const int Unicode::UTF8TrailingBytes[256] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, From f842ee3518966bb620338909f8c149d00885646a Mon Sep 17 00:00:00 2001 From: laurentgom Date: Sun, 1 Mar 2009 11:03:56 +0000 Subject: [PATCH 19/22] Fixed multi-threading issues with sf::Music git-svn-id: https://sfml.svn.sourceforge.net/svnroot/sfml/trunk@1033 4e206d99-4929-0410-ac5d-dfc041789085 --- src/SFML/Audio/Music.cpp | 28 ++++++++++++++++++++++------ 1 file changed, 22 insertions(+), 6 deletions(-) diff --git a/src/SFML/Audio/Music.cpp b/src/SFML/Audio/Music.cpp index a4d9d765e..b2cafb70b 100644 --- a/src/SFML/Audio/Music.cpp +++ b/src/SFML/Audio/Music.cpp @@ -51,6 +51,9 @@ mySamples (BufferSize) //////////////////////////////////////////////////////////// Music::~Music() { + // We must stop before destroying the file :) + Stop(); + delete myFile; } @@ -60,6 +63,9 @@ Music::~Music() //////////////////////////////////////////////////////////// bool Music::OpenFromFile(const std::string& Filename) { + // First stop the music if it was already running + Stop(); + // Create the sound file implementation, and open it in read mode delete myFile; myFile = priv::SoundFile::CreateRead(Filename); @@ -84,6 +90,9 @@ bool Music::OpenFromFile(const std::string& Filename) //////////////////////////////////////////////////////////// bool Music::OpenFromMemory(const char* Data, std::size_t SizeInBytes) { + // First stop the music if it was already running + Stop(); + // Create the sound file implementation, and open it in read mode delete myFile; myFile = priv::SoundFile::CreateRead(Data, SizeInBytes); @@ -108,7 +117,7 @@ bool Music::OpenFromMemory(const char* Data, std::size_t SizeInBytes) //////////////////////////////////////////////////////////// bool Music::OnStart() { - return myFile->Restart(); + return myFile && myFile->Restart(); } @@ -117,12 +126,19 @@ bool Music::OnStart() //////////////////////////////////////////////////////////// bool Music::OnGetData(SoundStream::Chunk& Data) { - // Fill the chunk parameters - Data.Samples = &mySamples[0]; - Data.NbSamples = myFile->Read(&mySamples[0], mySamples.size()); + if (myFile) + { + // Fill the chunk parameters + Data.Samples = &mySamples[0]; + Data.NbSamples = myFile->Read(&mySamples[0], mySamples.size()); - // Check if we have reached the end of the audio file - return Data.NbSamples == mySamples.size(); + // Check if we have reached the end of the audio file + return Data.NbSamples == mySamples.size(); + } + else + { + return false; + } } From 6f6014b5dd647d16b28bce3466f9baa44f396896 Mon Sep 17 00:00:00 2001 From: laurentgom Date: Sun, 1 Mar 2009 16:27:59 +0000 Subject: [PATCH 20/22] Removed useless include from SoundStream.cpp git-svn-id: https://sfml.svn.sourceforge.net/svnroot/sfml/trunk@1034 4e206d99-4929-0410-ac5d-dfc041789085 --- src/SFML/Audio/SoundStream.cpp | 1 - 1 file changed, 1 deletion(-) diff --git a/src/SFML/Audio/SoundStream.cpp b/src/SFML/Audio/SoundStream.cpp index f5ff3901f..0c796f8d2 100644 --- a/src/SFML/Audio/SoundStream.cpp +++ b/src/SFML/Audio/SoundStream.cpp @@ -26,7 +26,6 @@ // Headers //////////////////////////////////////////////////////////// #include -#include #include #include #include From 66681bc1ae3d4d2164fcd6a4e049945f97dfe667 Mon Sep 17 00:00:00 2001 From: ceylo Date: Sun, 1 Mar 2009 23:29:04 +0000 Subject: [PATCH 21/22] Dropped some assert() calls preventing some functions from being called. git-svn-id: https://sfml.svn.sourceforge.net/svnroot/sfml/trunk@1035 4e206d99-4929-0410-ac5d-dfc041789085 --- src/SFML/System/Initializer.cpp | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/src/SFML/System/Initializer.cpp b/src/SFML/System/Initializer.cpp index 8cdfdf407..161ae999c 100644 --- a/src/SFML/System/Initializer.cpp +++ b/src/SFML/System/Initializer.cpp @@ -32,6 +32,7 @@ #include #include +#include namespace sf { @@ -51,6 +52,7 @@ void InitializeWorkingDirectory(void) __attribute__ ((constructor)); void InitializeWorkingDirectory(void) { char PathBuffer[4096]; + bool Encoded = false; // Get the application bundle CFBundleRef MainBundle = CFBundleGetMainBundle(); @@ -64,15 +66,13 @@ void InitializeWorkingDirectory(void) CFURLRef AbsoluteURL = CFURLCopyAbsoluteURL(ResourceDirectory); assert(AbsoluteURL != NULL); - // Get the POSIX style path - CFStringRef AbsolutePath = CFURLCopyFileSystemPath(AbsoluteURL, kCFURLPOSIXPathStyle); - assert(AbsolutePath != NULL); + // Get the path as C string + Encoded = CFURLGetFileSystemRepresentation(AbsoluteURL, true, (UInt8 *)PathBuffer, 4096); + assert(Encoded); - // Get the path as C string and set it - assert(CFStringGetCString(AbsolutePath, PathBuffer, 4096, kCFStringEncodingASCII) == true); - assert(chdir(PathBuffer) == 0); + // Set the working directory + chdir(PathBuffer); - CFRelease(AbsolutePath); CFRelease(AbsoluteURL); CFRelease(ResourceDirectory); } From e28a89f902c999c3cae276d6d10d175d57827803 Mon Sep 17 00:00:00 2001 From: laurentgom Date: Mon, 2 Mar 2009 17:15:55 +0000 Subject: [PATCH 22/22] Fixed OpenAL error when stopping sound streams git-svn-id: https://sfml.svn.sourceforge.net/svnroot/sfml/trunk@1036 4e206d99-4929-0410-ac5d-dfc041789085 --- samples/sound/Sound.cpp | 6 +++--- src/SFML/Audio/SoundStream.cpp | 1 + 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/samples/sound/Sound.cpp b/samples/sound/Sound.cpp index c50b0c542..982eb99cd 100644 --- a/samples/sound/Sound.cpp +++ b/samples/sound/Sound.cpp @@ -31,11 +31,11 @@ void PlaySound() // Loop while the sound is playing while (Sound.GetStatus() == sf::Sound::Playing) { - // Display the playing position - std::cout << "\rPlaying... " << std::fixed << std::setprecision(2) << Sound.GetPlayingOffset() << " sec "; - // Leave some CPU time for other processes sf::Sleep(0.1f); + + // Display the playing position + std::cout << "\rPlaying... " << std::fixed << std::setprecision(2) << Sound.GetPlayingOffset() << " sec "; } std::cout << std::endl << std::endl; } diff --git a/src/SFML/Audio/SoundStream.cpp b/src/SFML/Audio/SoundStream.cpp index 0c796f8d2..0639a99f2 100644 --- a/src/SFML/Audio/SoundStream.cpp +++ b/src/SFML/Audio/SoundStream.cpp @@ -272,6 +272,7 @@ void SoundStream::Run() ClearQueue(); // Delete the buffers + ALCheck(alSourcei(Sound::mySource, AL_BUFFER, 0)); ALCheck(alDeleteBuffers(BuffersCount, myBuffers)); }