Giter VIP home page Giter VIP logo

py-sdl2's Introduction

PySDL2

Tests PyPI - Python Version PyPI Version

PySDL2 is a pure Python wrapper around the SDL2, SDL2_mixer, SDL2_image, SDL2_ttf, and SDL2_gfx libraries. Instead of relying on C code, it uses the built-in ctypes module to interface with SDL2, and provides simple Python classes and wrappers for common SDL2 functionality.

Installation

PySDL2 is easy to install and integrate within your own projects. To install or update to the latest version, simply run one of the following commands in a terminal:

# Install latest stable version from PyPI
pip install -U pysdl2

# Install latest development verion from GitHub
pip install -U git+https://github.com/py-sdl/py-sdl2.git

Note: If installing on Python 3 on a computer where both Python 2 and 3 are installed, replace pip with pip3 in the above commands.

Requirements

In order for PySDL2 to work, the binaries for SDL2 (and any SDL2 addon modules you wish to use, e.g. SDL2_mixer) need to be installed on your system. On macOS, Windows, and most x86 and ARM64 distributions of Linux, the recommended way to install the SDL2 binaries is via the pysdl2-dll package using pip:

pip install pysdl2-dll

This will install pre-built binaries for all supported SDL2 libraries as a Python package, which PySDL2 will automatically load if available. On systems not supported by pysdl2-dll, you can install the SDL2 binaries using your system's package manager (which may be out of date), or alternatively build and install the latest versions yourself from source.

The current minimum supported versions for each library are listed below:

  • SDL2 >= 2.0.5
  • SDL2_mixer >= 2.0.1 (for the sdl2.sdlmixer module)
  • SDL2_ttf >= 2.0.14 (for the sdl2.sdlttf module)
  • SDL2_image >= 2.0.1 (for the sdl2.sdlimage module)
  • SDL2_gfx >= 1.0.3 (for the sdl2.sdlgfx module)

Documentation

If you just started with SDL and PySDL2, it is strongly recommended that you read through the tutorial of the documentation to learn the basics. You can find the documentation at doc/html or online at http://pysdl2.readthedocs.org.

License

This library is given to the public domain. There are no licensing restrictions. Please see doc/copying.rst for further details.

py-sdl2's People

Contributors

a-hurst avatar basak avatar benrg avatar bnavigator avatar ecsv avatar fabtjar avatar joepolak avatar johny22 avatar jvarho avatar kml27 avatar kutu avatar lecram avatar marcusva avatar maxbareiss avatar mentat51 avatar mgorny avatar mindfilleter avatar mtn avatar namelivia avatar pvallet avatar rovitotv avatar shjohnson-pi avatar smcv avatar smealum avatar stillinbeta avatar techtonik avatar theatomicoption avatar tinmarr avatar tycode avatar zmarvel avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

py-sdl2's Issues

import in try/except in examples is pointless and broken?

Originally reported by: Isaac Freeman (Bitbucket: memotype, GitHub: memotype)


I don't understand this idiom:

#!python

try:
    import something
except ImportError:
    import traceback
    traceback.print_exc()
    sys.exit(1)

Why not just do the import and let python print the exception and exit? I can't figure out any use-case where explicitly catching and printing the exception is preferable. In fact, it seems the only effect this has is to break various tools which rely on normal python exception handling, like "python --pdb ..." or ipython's prettified exception printing. I really can't figure out why all the examples use this pattern....


sdl.ext.get_events() incorrectly handles more than 10 events

Originally reported by: markhildreth (Bitbucket: markhildreth, GitHub: markhildreth)


When sdl.ext.get_events() is called, it tries to get the first 10 events off of the queue. If it does get 10 events, it tries to grab another ten. However, because it's using a pointer to the same array as the first call to store the results, any events found in the subsequent calls to SDL_PeepEvent overwrite the events found in the previous calls. Thus, if the events were numbered in the order that they are listed in the queue, you should see a list with the results of...

#!python

[1,2,3,4,5,6,7,8,9,10,11,12]

...but instead you would see..

#!python

[11,12,3,4,5,6,7,8,9,10,11,12]

This problem can be duplicated using the following code:

#!python

import sdl3 as sdl
import sdl2.ext as sdlext

sdl.SDL_Init(sdl.SDL_INIT_VIDEO)

# Clear all items from the event queue that might have happened when SDL started.
sdl.SDL_FlushEvent(sdl.SDL_FIRSTEVENT, sdl.SDL_LASTEVENT)

# Add a bunch of different events, at least 11 to duplicate issue
for x in range(12):
    event = sdl.SDL_Event()
    event.type = sdl.SDL_USEREVENT + x
    event.user = sdl.SDL_UserEvent(type=event.type, timestamp=0, windowID=0, code=0)
    sdl.SDL_PushEvent(event)
    
results = sdlext.get_events()

# This asserion should pass, as the first event we push is USEREVENT + 0, but it fails.
types_found = [x.type for x in results]
assert sdl.SDL_USEREVENT in types_found

A corrected version of get_events is shown below:

#!python

def get_events():
    """Gets all SDL events that are currently on the event queue."""
    events.SDL_PumpEvents()

    evlist = []
    SDL_PeepEvents = events.SDL_PeepEvents

    op = events.SDL_GETEVENT
    first = events.SDL_FIRSTEVENT
    last = events.SDL_LASTEVENT

    while True:
        evarray = (events.SDL_Event * 10)()
        ptr = ctypes.cast(evarray, ctypes.POINTER(events.SDL_Event))

        ret = SDL_PeepEvents(ptr, 10, op, first, last)
        if not ret:
            break

        evlist += list(evarray)[:ret]

    return evlist


SDL_GetKeyFromScancode returns always 0

Originally reported by: Anonymous


Hi,

I don't know if I am using this properly, but it seems it always returns 0:

Python 2.7.3 (default, Apr 17 2013, 00:06:22)
[GCC 4.5.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.

from SDL2 import *
SDL_GetKeyFromScancode(SDL_SCANCODE_A)
0
SDL_GetKeyFromScancode(SDL_SCANCODE_RETURN)
0

Thanks,
Milan


SpriteFactory renderer= argument

Originally reported by: Jordan F (Bitbucket: FeralBytes, GitHub: FeralBytes)


I used SpriteFactory with a Texture based renderer and encountered a small flaw in the error description while figuring out how to do so. I was trying to use a Texture renderer and in one of my attemps I left out the renderer argument and recieved this traceback:

#!python
factory = sdl2.ext.SpriteFactory(sdl2.ext.TEXTURE)
  File "/usr/local/lib/python3.3/dist-packages/sdl2/ext/sprite.py", line 374, in __init__
    raise ValueError("you have to provide a renderer= argument")
ValueError: you have to provide a renderer= argument

But I think it should say:

#!python
factory = sdl2.ext.SpriteFactory(sdl2.ext.TEXTURE)
  File "/usr/local/lib/python3.3/dist-packages/sdl2/ext/sprite.py", line 374, in __init__
    raise ValueError("you have to provide a renderer=argument")
ValueError: you have to provide a renderer=argument

The space caused slight confusion.


Improving DLL error messages

Originally reported by: Roger Flores (Bitbucket: rallant92, GitHub: rallant92)


I installed the 64 bit sdl2 DLLs for my Win 7 x64 OS. Running (draw.py) reported

ImportError: could not load any library for SDL2

After some tracking, I figured out the Python was 32 bit, which can't use 64 bit libs. Specifically, exc at dll.py:57 is "[Error 193] %1 is not a valid Win32 application", raised from CDLL().

The import feedback could be more helpful. Mentioning that a dll file was found but not usable/suitable makes it clear that path issues aren't the source of the problem. So change dll.py:61 to
raise RuntimeError("found %s but it's not usable for the libary %s" % (foundlibs, libinfo))

dll.py:50 could become:
raise RuntimeError("searched %s but could not find any library for %s" % (path, libinfo))

It would also help to mention PYSDL2_DLL_PATH when there's a problem and it's unset so that people know about it.
dll.py:101:
if os.getenv("PYSDL2_DLL_PATH") == None:
exc = exc.message + " (and PYSDL2_DLL_PATH is unset)";


The Pong Game - Improved bouncing

Originally reported by: Jordan F (Bitbucket: FeralBytes, GitHub: FeralBytes)


So it may just be me, but upon reading the tutorial I could not figure out where the last set of "if" statements for bouncing off of walls went, since they do not following the typical flow of the rest of the tutorial by filling in near some other code as a hint. I had to read the source code for the example to find where they went.
Perhaps to better follow the flow of the tutorial change:

#!python
if self.ball.sprite.y <= self.miny or \
        self.ball.sprite.y + self.ball.sprite.size[1] >= self.maxy:
    self.ball.velocity.vy = - self.ball.velocity.vy

if self.ball.sprite.x <= self.minx or \
        self.ball.sprite.x + self.ball.sprite.size[0] >= self.maxx:
    self.ball.velocity.vx = - self.ball.velocity.vx

to be:

#!python
class CollisionSystem(sdl2ext.Applicator):
    [...]

    def process(self, world, componentsets):
        [...]
        if self.ball.sprite.y <= self.miny or \
                self.ball.sprite.y + self.ball.sprite.size[1] >= self.maxy:
            self.ball.velocity.vy = - self.ball.velocity.vy

        if self.ball.sprite.x <= self.minx or \
                self.ball.sprite.x + self.ball.sprite.size[0] >= self.maxx:
            self.ball.velocity.vx = - self.ball.velocity.vx


bind_function fails if function is not found

Originally reported by: Steven Johnson (Bitbucket: shjohnson_pi, GitHub: Unknown)


Based on commit 03c0926, bind_function is called:

# sdl2/hints.py
_bind("SDL_AddHintCallback", [c_char_p, SDL_HintCallback, c_void_p])

# sdl2/dll.py (_DLL class)
def bind_function(self, funcname, args=None, returns=None, optfunc=None):
    """Binds the passed argument and return value types to the specified
    function."""
    func = getattr(self._dll, funcname, None)
    if not func:
        func = optfunc
    func.argtypes = args
    func.restype = returns
    return func

bind_function checks if the function is found, if not it uses the supplied optfunc regardless if it's none (None by default)

I'm not sure whether it should return a dummy function, raise an error, or just do nothing. But currently a non-descriptive error occurs:

>>> import sdl2
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python3.3/dist-packages/sdl2/__init__.py", line 15, in <module>
    from .hints import *
  File "/usr/local/lib/python3.3/dist-packages/sdl2/hints.py", line 45, in <module>
    SDL_AddHintCallback = _bind("SDL_AddHintCallback", [c_char_p, SDL_HintCallback, c_void_p])
  File "/usr/local/lib/python3.3/dist-packages/sdl2/dll.py", line 73, in bind_function
    func.argtypes = args
AttributeError: 'NoneType' object has no attribute 'argtypes'

Bindings autogeneration

Originally reported by: cheery (Bitbucket: cheery, GitHub: cheery)


I looked at the bindings a bit and see they are in a lot of way isomorphic with the C API.

You could automatically generate the isomorphic parts and write binding specification for the generator instead. That way there would be less pressure in keeping all the bindings updated if the API gets minor upgrades. People would spend less time writing bindings and doing something awesome instead.

https://github.com/cheery/sdl2-binding-hack


OSError: /usr/lib/libc.so: invalid ELF header

Originally reported by: Anonymous


On ArchLinux, i can't import sdl2.ext because /usr/lib/libc.so is an ASCII text file.

Traceback (most recent call last):
File "./main.py", line 6, in
import sdl2.ext as sdl2ext
File "/usr/lib/python2.7/site-packages/sdl2/init.py", line 14, in
from .audio import *
File "/usr/lib/python2.7/site-packages/sdl2/audio.py", line 6, in
from .stdinc import Uint8, Uint16, Uint32
File "/usr/lib/python2.7/site-packages/sdl2/stdinc.py", line 30, in
_libc = cdll.LoadLibrary("libc.so")
File "/usr/lib/python2.7/ctypes/init.py", line 443, in LoadLibrary
return self._dlltype(name)
File "/usr/lib/python2.7/ctypes/init.py", line 365, in init
self._handle = _dlopen(self._name, mode)
OSError: /usr/lib/libc.so: invalid ELF header

$ file /usr/lib/libc.so
/usr/lib/libc.so: ASCII text

$ file /usr/lib/libc.so.6
/usr/lib/libc.so.6: symbolic link to `libc-2.17.so'

$ cat /usr/lib/libc.so
/* GNU ld script
Use the shared library, but some functions are only in
the static library, so try that secondarily. */
OUTPUT_FORMAT(elf64-x86-64)
GROUP ( /usr/lib/libc.so.6 /usr/lib/libc_nonshared.a AS_NEEDED ( /usr/lib/ld-linux-x86-64.so.2 ) )


Upload pysdl2 to pypi

Originally reported by: Matthew Iversen (Bitbucket: Ivoz, GitHub: Ivoz)


From pip 1.5 onwards, it will not install external downloads by default. i.e:

$ pip install pysdl2
Downloading/unpacking pysdl2
  Could not find any downloads that satisfy the requirement pysdl2
  Some externally hosted files were ignored (use --allow-external pysdl2 to allow).
Cleaning up...
No distributions at all found for pysdl2
Storing debug log for failure in /home/ivo/.pip/pip.log

For this, any pip user would now have to enter:

pip install pysdl2 --allow-external pysdl2 --allow-unverified pysdl2

It is possible to fix this so pip install pysdl2 works again, simply by uploading the library to PyPI. you can do this through python setup.py sdist --formats=zip,gztar upload, or use python setup.py sdist --formats=zip,gztar and twine upload dist/* if you have the cool twine tool installed.


document surface vs texture vs buffer vs pixelview

Originally reported by: anatoly techtonik (Bitbucket: techtonik, GitHub: techtonik)


It is pretty confusing to read documentation that speaks about abstract pixels, with some vague connection to bytes in video memory, system memory and the ways Python protects people from messing with those.

I am trying to start with representation of pixel data in Python list and documentation doesn't give me a glue how can I convert it to picture. For that, I need to know:

  1. what input buffer formats of raw pixel data are used by SDL2
  2. how do these look in PySDL2 and why
  3. what is the transformation chain from Python variable to pixel on the screen
  4. how does Python hides direct access to memory (why it is slow)

Actually, the (1,3) are the two most important.


Tutorials Should Match API

Originally reported by: Jordan F (Bitbucket: FeralBytes, GitHub: FeralBytes)


Tutorials all use:
import sdl2.ext as sdl2ext

API presumably uses:
import sdl2.ext

As an example from the API "sdl2.ext.UIFactory()".

I personally see nothing wrong with the dot notation for submodules so why not use "sdl2.ext". However if you wish to dismiss this on personal taste then I understand as it is very trivial.


test_SDL_AddDelHintCallback fails with PyPy 2.2.1+dfsg-1 (amd64)

Originally reported by: Anonymous


I get following error when running the tests with PyPy from Debian sid:

#!txt
----------------------------------------------------------------------
FAILURE: test_SDL_AddDelHintCallback (sdl2.test.hints_test.SDLHintsTest)
======================================================================
Traceback (most recent call last):
  File "/home/pau/py-sdl2/sdl2/test/util/../hints_test.py", line 86, in test_SDL_AddDelHintCallback
    self.assertEqual(len(calls), 2)
AssertionError: 3 != 2


factory.from_image fails if neither SDL_image nor PIL are installed

Originally reported by: Scott Harper (Bitbucket: pahzy, GitHub: Unknown)


Neither library is listed as required (and PIL isn't mentioned at all, and isn't compatible with Python 3.x). Should there be some mention of this on the website? Should the library report an error when neither library manages to import?

----------------- original bug -----------------
Running on Windows, I am following the tutorial, and everything works great up until the following line:

sprite = factory.from_image(RESOURCES.get_path("imagename.bmp"))

Here is the traceback:

#!text

Traceback (most recent call last):
  File "main.py", line 25, in <module>
    sprite = factory.from_image(RESOURCES.get_path("Timmy.png"))
  File "C:\Python33\lib\site-packages\sdl2\ext\sprite.py", line 405, in from_image
    return self.from_surface(load_image(fname), True)
  File "C:\Python33\lib\site-packages\sdl2\ext\sprite.py", line 423, in from_surface
    s = SoftwareSprite(tsurface, free)
  File "C:\Python33\lib\site-packages\sdl2\ext\sprite.py", line 299, in __init__
    raise TypeError("surface must be a SDL_Surface")
TypeError: surface must be a SDL_Surface

I have checked that sdl2ext.load_image(...) does not fail for the same file path.


ImportError: found ['libSDL2_ttf-2.0.so.0'], but it's not usable for the libary SDL2_ttf

Originally reported by: Anonymous


This error:
ImportError: found ['libSDL2_ttf-2.0.so.0'], but it's not usable for the libary SDL2_ttf

happens as soon as I try to import the ttf library:
import sdl2.sdlttf

Is there any way to find out why the library is not usable?

I'm running Ubuntu 12.04, python3.2, and SDL2 (v2.0.1-7893) and SDL2_ttf (v2.0.12) were compiled from source


Shape Window not showing on desktop

Originally reported by: Mihail Latyshov (Bitbucket: kutu182, GitHub: Unknown)


Hello,

I try to create a "tv overlay" for racing game

If i use c with mingw from this example http://www.libsdl.org/tmp/SDL/test/testshape.c shaped window shown like this

but if i try to do the same with python, window created and shaped, but not shown on desktop

my python code is:

import sys

try:
    import sdl2
    import sdl2.ext as sdl2ext
except ImportError:
    import traceback
    traceback.print_exc()
    sys.exit(1)

from sdl2.ext import Resources
RESOURCES = Resources(__file__, "resources")

class ShapeWindow(sdl2ext.Window):
    def __init__(self, title, size, position=None, flags=None):
        if position is None:
            position = self.DEFAULTPOS
        if flags is None:
            flags = self.DEFAULTFLAGS
        window = sdl2.SDL_CreateShapedWindow(sdl2ext.compat.byteify(title, "utf-8"),
                                             position[0], position[1],
                                             size[0], size[1], flags)
        if not window:
            raise SDLError()
        self.window = window.contents
        self._renderer = None

sdl2ext.init()

# window = sdl2ext.Window("Hello World!", size=(800, 500))
window = ShapeWindow("Hello World!", size=(800, 500))
window.show()

renderer = sdl2ext.RenderContext(window)
factory = sdl2ext.SpriteFactory(sdl2ext.TEXTURE, renderer=renderer)

circle_sf = sdl2ext.load_image(RESOURCES.get_path("circle2.bmp"))
circle = factory.from_surface(circle_sf)

shape_mode = sdl2.SDL_WindowShapeMode()
shape_mode.mode = sdl2.ShapeModeColorKey
shape_mode.parameters.colorKey = (0, 0, 0, 255)
sdl2.SDL_SetWindowShape(window.window, circle_sf, shape_mode)

spriterenderer = factory.create_sprite_renderer(window)
spriterenderer.render(circle)

processor = sdl2ext.TestEventProcessor()
processor.run(window)

sdl2ext.quit()

can you point me, what i'm doing wrong?


SDL_AudioSpec.callback should be type SDL_AudioCallBack not c_void_p

Originally reported by: Michael McCandless (Bitbucket: changingbits, GitHub: Unknown)


I'm using py-sdl2 to play a sound file (see attachment), but when I try to pass my python function as a callback I hit this:

#!python
Traceback (most recent call last):
  File "playSoundSDL2.py", line 46, in <module>
    sdl2.SDL_AudioCallback(p.playNextChunk))
  File "/Library/Python/2.7/site-packages/sdl2/audio.py", line 102, in __init__
    self.callback = callback
TypeError: incompatible types, CFunctionType instance instead of c_void_p instance

With this small fix I'm able to play the sound successfully:

#!python
*** /Library/Python/2.7/site-packages/sdl2/audio.py	Tue Nov 12 12:28:39 2013
--- /Library/Python/2.7/site-packages/sdl2/audio2.py	Tue Nov 12 12:29:09 2013
***************
*** 89,95 ****
                  ("samples", Uint16),
                  ("padding", Uint16),
                  ("size", Uint32),
!                 ("callback", c_void_p),
                  ("userdata", c_void_p)
                  ]
      def __init__(self, freq, aformat, channels, samples,
--- 89,95 ----
                  ("samples", Uint16),
                  ("padding", Uint16),
                  ("size", Uint32),
!                 ("callback", SDL_AudioCallback),
                  ("userdata", c_void_p)
                  ]
      def __init__(self, freq, aformat, channels, samples,

However, I don't have much experience with SDL, py-sdl2 nor ctypes so it could be I'm doing something wrong. Here's the script I'm using to play sounds (it loads an aiff file and plays it):

import sdl2
import sys
import aifc
import threading

class ReadAIFF:
  def __init__(self, fileName):
    self.a = aifc.open(fileName)
    self.frameUpto = 0
    self.bytesPerFrame = self.a.getnchannels() * self.a.getsampwidth()
    self.numFrames = self.a.getnframes()
    self.done = threading.Event()
    
  def playNextChunk(self, unused, buf, bufSize):
    framesInBuffer = bufSize/self.bytesPerFrame
    framesToRead = min(framesInBuffer, self.numFrames-self.frameUpto)

    if self.frameUpto == self.numFrames:
      self.done.set()

    # TODO: is there a faster way to copy the string into the ctypes
    # pointer/array?
    for i, b in enumerate(self.a.readframes(framesToRead)):
      buf[i] = ord(b)

    # Play silence after:
    # TODO: is there a faster way to zero out the array?
    for i in range(self.bytesPerFrame*framesToRead, self.bytesPerFrame*framesInBuffer):
      buf[i] = 0

    self.frameUpto += framesToRead

if sdl2.SDL_Init(sdl2.SDL_INIT_AUDIO) != 0:
  raise RuntimeError('failed to init audio')

p = ReadAIFF(sys.argv[1])
spec = sdl2.SDL_AudioSpec(p.a.getframerate(),
                          sdl2.AUDIO_S16MSB,
                          p.a.getnchannels(),
                          512,
                          sdl2.SDL_AudioCallback(p.playNextChunk))

# TOOD: instead of passing None for the 4th arg, I really should pass
# anoter AudioSpec and then confirm it matched what I asked for:
devID = sdl2.SDL_OpenAudioDevice(None, 0, spec, None, 0)

# Tell audio device to start playing:
sdl2.SDL_PauseAudioDevice(devID, 0)
p.done.wait()

sdl2.SDL_CloseAudioDevice(devID)


TextureSpriteRenderer mishandles x and y for single sprites

Originally reported by: otus (Bitbucket: jvarho, GitHub: jvarho)


The docstring for TextureSpriteRenderer says x and y are used as absolute position when a single TextureSprite is passed, but the code actually renders to an empty rect (i.e. nowhere) instead.

Testcase: add x=10, y=10 to the render call in helloworld.py example and run it with the -hardware switch.

Suggested fix is here:
https://bitbucket.org/otus/py-sdl2/commits/5c5ad73975c4460a2337f081256777ec5f7ad2b9


One module per C API prefix, no C API prefixes in function names.

Originally reported by: Eric Toombs (Bitbucket: ewtoombs, GitHub: ewtoombs)


From the FAQ:
The low-level APIs for SDL2, SDL2_mixer, SDL2_ttf, ... shall represent a clean wrapping around the original C API calls. Thus, if you have to search for documentation or want to make a Python to C conversion (or C to Python), most of the code cleanly maps to the original API naming and layout and you do not have to think about whether you had to use SDL_ or TTF_ or whatever as prefix or suffix.

I'll tell you what is "clean". One module per C API prefix, just like every other python wrapper around a C API ever made. Think about it. SDL_ goes in an sdl module, TTF_ goes in a ttf module, and so on. The original C API calls can be found just as easily by searching for the function without the prefix. If two calls have the same name, except for the prefix, then just click on the one in your search results that has the prefix that goes with the module name. Function calls aren't just given a prefix for no reason after all. They are related to one another and should be put in the same module.

As for python-to-C conversion. If you really want to do a python-to-C conversion, there are so many syntax and usage differences that you're probably going to have to rewrite it anyway. The function names will be the least of your concern.

Take Cairo, for example. Every Cairo C API call is prefixed with cairo_. The python interface is a clean mapping right to the C API, and they did it without prefixing every one of their python function names with cairo_, to keep things "clean". They just put them all in a module to avoid name collisions, took off the prefixes, and were done with it.


Importing sdl2.ext fails, if SDL2_image or SDL2_ttf are not installed

Originally reported by: Anonymous


I get the following error on my system. It looks like the RuntimeError is not properly handled on importing sdl2.sdlttf or sdl2.sdlimage within sdl2.ext

c:\Python27\Lib\site-packages\sdl2\examples>python draw.py
Traceback (most recent call last):
File "draw.py", line 10, in
import sdl2.ext as sdl2ext
File "C:\Python27\lib\site-packages\sdl2\ext_init_.py", line 14, in
from .common import *
File "C:\Python27\lib\site-packages\sdl2\ext\common.py", line 8, in
from .. import sdlttf
File "C:\Python27\lib\site-packages\sdl2\sdlttf.py", line 40, in
os.getenv("PYSDL2_DLL_PATH"))
File "C:\Python27\lib\site-packages\sdl2\dll.py", line 51, in init
raise RuntimeError("could not find any library for %s" % libinfo)
RuntimeError: could not find any library for SDL2_ttf


Run gfxdrawing.py met a error "sdl2.ext.common.SDLError"

Originally reported by: zaazbb (Bitbucket: zaazbb, GitHub: zaazbb)


I build SDL2_gfx-1.0.0.tar.gz to a SDL2_gfx.dll use vs2010.
when i running the gfxdrawing.py in examples, met a error as below:

Traceback (most recent call last):
File "C:\Python33\Lib\site-packages\sdl2\examples\gfxdrawing.py", line 337, in
sys.exit(run())
File "C:\Python33\Lib\site-packages\sdl2\examples\gfxdrawing.py", line 306, in run
draw_lines(context, 800, 600)
File "C:\Python33\Lib\site-packages\sdl2\examples\gfxdrawing.py", line 22, in draw_lines
context.clear(0)
File "C:\Python33\lib\site-packages\sdl2\ext\sprite.py", line 93, in clear
tmp = self.color
File "C:\Python33\lib\site-packages\sdl2\ext\sprite.py", line 62, in color
raise SDLError()
sdl2.ext.common.SDLError: b'Invalid renderer'


How to do Sprite Clipping?

Originally reported by: Connor Petersen (Bitbucket: chisaipete, GitHub: chisaipete)


I'm trying to use PySDL2 to implement a basic tile/sprite clipping system to render sprites clipped from a tilemap, like in this SDL2 tutorial.

sdl2.ext.RenderContext.copy() would probably do what I want, but I'm trying to modify the pong example or in other words using a spritefactory and can't seem to be able to create a RenderContext properly to let me clip a part of a larger sprite (tilemap) into a new sprite to assign to a player entity to be drawn by the RenderSystem.

What am I doing wrong, and what's the best/most Pythonic/most pysdlish way to do this?


Cannot pass surface to SDL_LockTexture

Originally reported by: Mikko Ronkainen (Bitbucket: mikoro, GitHub: mikoro)


#!python

texture = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_ARGB8888, SDL_TEXTUREACCESS_STREAMING, width, height)
surface = SDL_CreateRGBSurface(0, width, height, 32, 0x00FF0000, 0x0000FF00, 0x000000FF, 0xFF000000)
SDL_LockTexture(texture, 0, ctypes.byref(surface.contents.pixels), ctypes.byref(surface.contents.pitch))

byref() argument must be a ctypes instance, not 'int'

How should the SDL_LockTexture be called? I couldn't find any examples from the tests. Do the pixels/pitch members have wrong types after SDL_CreateRGBSurface or am I just calling the function in a wrong way?


SDL_MIXER_VERSION broken

Originally reported by: arifsch (Bitbucket: arifsch, GitHub: Unknown)


I noticed a small copy & paste error in sdlmixer.
The function sdlmixer.SDL_MIXER_VERSION attempts to use values from sdlttf like SDL_TTF_MAJOR_VERSION, etc.
This fails as these values are neither defined nor imported in sdlmixer.

Instead it should assign the corresponding SDL_MIXER_* version numbers:

#!diff

--- a/sdl2/sdlmixer.py  Sat Dec 28 09:21:24 2013 +0100
+++ b/sdl2/sdlmixer.py  Sat Dec 28 15:38:00 2013 +0100
@@ -68,9 +68,9 @@
 
 
 def SDL_MIXER_VERSION(x):
-    x.major = SDL_TTF_MAJOR_VERSION
-    x.minor = SDL_TTF_MINOR_VERSION
-    x.patch = SDL_TTF_PATCHLEVEL
+    x.major = SDL_MIXER_MAJOR_VERSION
+    x.minor = SDL_MIXER_MINOR_VERSION
+    x.patch = SDL_MIXER_PATCHLEVEL
 
 MIX_MAJOR_VERSION = SDL_MIXER_MAJOR_VERSION
 MIX_MINOR_VERSION = SDL_MIXER_MINOR_VERSION

Render functions don't always work

Originally reported by: Bil Bas (Bitbucket: bil_bas, GitHub: Unknown)


Some of the render functions that are calling OpenGL underneath seem to work on about 50% of machines I've tested on. In failing, they just do nothing!

  1. Ubuntu 13.04 x64 - works (Nvidia 550 Ti)
  2. win7x32 VM (on the above Ubuntu machine) - works
  3. win7x64 - fails (Nvidia GTX560)
  4. win7x64 - fails
  5. win8x64 - works

The specific methods that fail are:

  • SDL_RenderSetViewport()
  • SDL_RenderSetClipRect()
  • setting RenderContext.color (which uses SDL_SetRenderDrawColor)

I'm creating the Window as a OPENGL, but not using any of my own OpenGL. On the machines that fail with these methods, they also fail/do nothing if I use any pyopengl function within the SDL application. However, those same machine correctly run pyopengl functions under a GLUT window.

SDL_SetRenderTarget() does work on all machines though.

Window created with: SDL_WINDOW_OPENGL|SDL_WINDOW_RESIZABLE
Renderer created with: SDL_RENDERER_ACCELERATED|SDL_RENDERER_PRESENTVSYNC

Sorry if this is my fault (or sdl2's fault rather than pysdl2's), but I can't guess what is wrong here...


Mouse module issues

Originally reported by: sp4ztique (Bitbucket: sp4ztique, GitHub: sp4ztique)


The mouse related functions i.e. SDL_GetMouseState(), aren't well documented for python, as in C they involve getting the mouse position via x and y pointers passed to the function, rather than just returning a tuple or using a class. I've had a lot of trouble getting this function to work, as I'm trying to use the mouse for unit movement, similar to diablo or RTS games, but even when I try and create pointers with ctypes, this function doesn't want to work. If I pass x and y as None, I can get it to return the mouse button states, but I can't seem to get the right ctypes pointer.

I'd really rather use this library than the dead pygame, but if I can't get the mouse co-ordinates I'm going to be forced to switch to pygame.

Also, sorry for posting this here, if you have somewhere you'd rather questions sent I'll happily switch to that platform.


TextureSpriteRenderer mishandles x and y for single sprites

Originally reported by: otus (Bitbucket: jvarho, GitHub: jvarho)


The docstring for TextureSpriteRenderer says x and y are used as absolute position when a single TextureSprite is passed, but the code actually renders to an empty rect (i.e. nowhere) instead.

Testcase: add x=10, y=10 to the render call in helloworld.py example and run it with the -hardware switch.

Suggested fix is here:
https://bitbucket.org/otus/py-sdl2/commits/5c5ad73975c4460a2337f081256777ec5f7ad2b9


Can't render to Sprite

Originally reported by: Bil Bas (Bitbucket: bil_bas, GitHub: Unknown)


Sprites can only be static or dynamic (init() passed a boolean, "static"). The problem with this is that it doesn't allow you to create the texture with the other option: SDL_TEXTUREACCESS_TARGET (which must be set to render to the texture).

I've monkey-patched Sprite/SpriteFactory in my code to replace the static option with a more sensible access=Sprite.ACCESS_STATIC, Sprite.ACCESS_STREAMING or Sprite.ACCESS_TARGET (where Sprite.ACCESS_TARGET = sdl2.SDL_TEXTUREACCESS_TARGET). Not sure if this is how you'd want it done in pysdl2 ext though.


py-sdl2 on OSX

Originally reported by: Anonymous


Hi,

When running on OSX, upon import sdl2.ext you get the following warnings.
/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/sdl2/dll.py:74: UserWarning: function 'SDL_GetBasePath' not found in <CDLL '/opt/local/lib/libSDL2.dylib', handle 7fe9384910d0 at 10c9eaa50>, using replacement
(funcname, self._dll))
/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/sdl2/dll.py:74: UserWarning: function 'SDL_GetPrefPath' not found in <CDLL '/opt/local/lib/libSDL2.dylib', handle 7fe9384910d0 at 10c9eaa50>, using replacement
(funcname, self._dll))

Everything seems to work ok, it just looks like the 2 functions don't exist in the OSX implementation of SDL2.

Cheers

Richard


examples only run from CLI

Originally reported by: Mark Schafer (Bitbucket: Neon22, GitHub: Neon22)


The gui, helloworld, and particles examples will not run unless run from the command line. (Actually I still get an error about SDL can't load but that's a diff issue.).
(I'm using Windows)

But their internal syntax makes them not possible to run from IDLE (say). I think this is a mistake.

E.g. gui.py when executed in IDLE reports:
Traceback (most recent call last):
File "C:\Python27\Lib\site-packages\sdl2\examples\gui.py", line 26, in
RESOURCES = sdl2ext.Resources(file, "resources")
NameError: name 'file' is not defined

This is because the Python Shell doesn't detect current file path in file and it's related to the filepath in the line.

Perhaps use os module to get the cwd ? I really don't know what its supposed to be doing... If its just loading a file....


FontManager - No Tutorial or Example & it is Broken

Originally reported by: Jordan F (Bitbucket: FeralBytes, GitHub: FeralBytes)


Well using py-sdl2 I was about to move on to making a menu when I suddenly realized that I had no idea how to create text. I had the API open and understand how to get a surface from the FontManager but was unable to find any further documentation or even an example.

I then proceeded to try and build a test case to see how I would go about converting the text into a surface and then into a sprite and finally into an entity. But I encountered this error while creating the FontManager:

Traceback (most recent call last):
File "test_script.py", line 34, in
font_manager = sdl2.ext.FontManager('Villa.ttf')
File "/usr/local/lib/python3.3/dist-packages/sdl2/ext/font.py", line 187, in init
"FontManager requires sdlttf support")
sdl2.ext.compat.UnsupportedError: 'FontManager requires sdlttf support'
Exception AttributeError: "'FontManager' object has no attribute 'fonts'" in <bound method FontManager.del of <sdl2.ext.font.FontManager object at 0x7fef2b3e3110>> ignored

My system is Linux Mint 16 64-bit and I have both libsdl-ttf2.0-dev (ver2.0.11-2ubuntu1) and libsdl-ttf2.0-0 (ver2.0.11-2ubuntu1) installed.


gfxdrawing example presents context in the wrong place (?)

Originally reported by: Brett Calcott (Bitbucket: bcalcott, GitHub: Unknown)


The gfxdrawing example calls context.present() every pass through the loop. This cause flashing on OSX. I changed it calls it only calls it when the drawing changes:

#!diff

diff --git a/examples/gfxdrawing.py b/examples/gfxdrawing.py
--- a/examples/gfxdrawing.py
+++ b/examples/gfxdrawing.py
@@ -304,6 +304,7 @@
     # which function to execute next.
     curindex = 0
     draw_lines(context, 800, 600)
+    context.present()
 
     # The event loop is nearly the same as we used in colorpalettes.py. If you
     # do not know, what happens here, take a look at colorpalettes.py for a
@@ -325,8 +326,8 @@
                 # function with the arguments.
                 func, args = functions[curindex]
                 func(*args)
+                context.present()
                 break
-        context.present()
     sdl2ext.quit()
     return 0
 


Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.