Commits

Marcus von Appen committed 5f5a42e

- added new sdl2.ext.UIFactory.from_color() method for creating UI sprites from
colors.
- removed size argument defaults from sdl2.ext.SpriteFactory methods
- minor example improvements

  • Participants
  • Parent commits cc23b28

Comments (0)

Files changed (12)

doc/modules/images/uiprocessing.dia

Binary file added.

doc/modules/images/uiprocessing.png

Added
New image

doc/modules/sdl2ext_gui.rst

 delegating input events, such as mouse movements, clicks and keyboard input,
 to the correct UI element.
 
-Depending on the event type (e.g. moving the mouse cursor), the UIProcessor
-will execute its matching method (e.g. ``mousemotion()``) with only those UI
+Depending on the event type (e.g. pressing a mouse button), the UIProcessor
+will execute its matching method (e.g. ``mousdown()``) with only those UI
 elements, which support the event type.
 
-TODO
+.. image:: images/uiprocessing.png
 
 .. _ui-elem-types:
 
       construction and can vary depending on the sprite type.
       See :meth:`SpriteFactory.create_sprite()` for further details.
 
+   .. method:: from_color(color : object , size) -> Sprite
+
+      Creates a UI element with a specific color.
+
+      *uitype* must be one of the supported :ref:`ui-elem-types` classifying
+      the type of UI element to be created.
+
    .. method:: from_image(uitype : int, fname : str) -> Sprite
 
       Creates a UI element from an image file. The image must be

doc/modules/sdl2ext_sprite.rst

 
       The default arguments to use for creating new sprites.
 
-   .. method:: create_software_sprite(size=(0, 0), bpp=32, masks=None) -> SoftwareSprite
+   .. method:: create_software_sprite(size, bpp=32, masks=None) -> SoftwareSprite
 
       Creates a software sprite. A *size* tuple containing the width and
       height of the sprite and a *bpp* value, indicating the bits per
       Otherwise a :class:`SoftwareSpriteRenderer` is created and *args*
       and *kwargs* are passed to it.
 
-   .. method:: create_texture_sprite(renderer : object, size=(0, 0), pformat=sdl2.SDL_PIXELFORMAT_RGBA8888, static=True) -> TextureSprite
+   .. method:: create_texture_sprite(renderer : object, size, pformat=sdl2.SDL_PIXELFORMAT_RGBA8888, static=True) -> TextureSprite
 
       Creates a texture sprite. A *size* tuple containing the width and
       height of the sprite needs to be provided.
       data frequently, *static* can be set to ``False`` to allow a
       streaming access on the underlying texture pixel buffer.
 
-   .. method:: from_color(color : object , size=(0, 0), bpp=32, masks=None) -> Sprite
+   .. method:: from_color(color : object , size, bpp=32, masks=None) -> Sprite
 
       Creates a :class:`Sprite` with a certain color.
 
 
 * new :mod:`sdl2.sdlgfx` module, which provides access to the SDL2_gfx library
 * fixed color argument bugs in :class:`sdl2.ext.RenderContext` methods
+* new :mod:`sdl2.ext.UIFactory.from_color` method; it creates UI-supportive
+  sprite from a color
 
 0.2.0
 -----

examples/gfxdrawing.py

     window = sdl2ext.Window("sdlgfx drawing examples", size=(800, 600))
     window.show()
 
-    # Create a rendering context for the window. The sdlgfx module require it.
+    # Create a rendering context for the window. The sdlgfx module requires it.
     context = sdl2ext.RenderContext(window)
 
     # We implement the functionality as it was done in colorpalettes.py and
 # Define some global color constants
 WHITE = sdl2ext.Color(255, 255, 255)
 GREY = sdl2ext.Color(200, 200, 200)
+RED = sdl2ext.Color(255, 0, 0)
+GREEN = sdl2ext.Color(0, 255, 0)
 
 # Create a resource, so we have easy access to the example images.
 RESOURCES = sdl2ext.Resources(__file__, "resources")
           (event.text.text, event.text.start, event.text.length))
 
 
+def oncheck(button, event):
+    if button.checked:
+        color = GREEN
+    else:
+        color = RED
+    if button.factory.sprite_type == sdl2ext.SOFTWARE:
+        sdl2ext.fill(button.surface, color)
+    else:
+        # SDL textures do not support color manipulation operation as easy
+        # as software surface (since the texture is ideally stored somwhere
+        # on the GPU memory in a GPU-specific layout [or not]). To circumvent
+        # this, we create a temporary sprite (texture) and exchange the button
+        # texture with it.
+        tmpsprite = button.factory.from_color(color, button.size)
+        button.texture, tmpsprite.texture = tmpsprite.texture, button.texture
+        del tmpsprite
+
+
 def run():
     # You know those from the helloworld.py example.
     # Initialize the video subsystem, create a window and make it visible.
     window = sdl2ext.Window("UI Elements", size=(800, 600))
     window.show()
 
-    spritefactory = sdl2ext.SpriteFactory(sdl2ext.SOFTWARE)
-    # If you want hardware-accelerated rendering, use video.TEXTURE instead
-    # and pass a renderer along:
-    #
-    # renderer = video.RenderContext(window)
-    # factory = video.SpriteFactory(video.TEXTURE, renderer=renderer)
-    #
+    # Create a sprite factory that allows us to create visible 2D elements
+    # easily. Depending on what the user chosses, we either create a factory
+    # that supports hardware-accelerated sprites or software-based ones.
+    # The hardware-accelerated SpriteFactory requres a rendering context
+    # (or SDL_Renderer), which will create the underlying textures for us.
+    if "-hardware" in sys.argv:
+        print("Using hardware acceleration")
+        renderer = sdl2ext.RenderContext(window)
+        factory = sdl2ext.SpriteFactory(sdl2ext.TEXTURE, renderer=renderer)
+    else:
+        print("Using software rendering")
+        factory = sdl2ext.SpriteFactory(sdl2ext.SOFTWARE)
 
     # Create a UI factory, which will handle several defaults for
     # us. Also, the UIFactory can utilises software-based UI elements as
     # well as hardware-accelerated ones; this allows us to keep the UI
     # creation code clean.
-    uifactory = sdl2ext.UIFactory(spritefactory)
+    uifactory = sdl2ext.UIFactory(factory)
 
     # Create a simple Button sprite, which reacts on mouse movements and
     # button presses and fill it with a white color. All UI elements
     # inherit directly from the TextureSprite (for TEXTURE) or SoftwareSprite
     # (for SOFTWARE), so everything you can do with those classes is also
     # possible for the UI elements.
-    button = uifactory.from_image \
-        (sdl2ext.BUTTON, RESOURCES.get_path("button.bmp"))
+    button = uifactory.from_image(sdl2ext.BUTTON,
+                                   RESOURCES.get_path("button.bmp"))
     button.position = 50, 50
 
     # Create a TextEntry sprite, which reacts on keyboard presses and
     # text input.
-    entry = uifactory.from_image \
-        (sdl2ext.TEXTENTRY, RESOURCES.get_path("textentry.bmp"))
+    entry = uifactory.from_image(sdl2ext.TEXTENTRY,
+                                 RESOURCES.get_path("textentry.bmp"))
     entry.position = 50, 200
 
     # Create a CheckButton sprite. The CheckButton is a specialised
     # Button, which can switch its state, identified by the 'checked'
     # attribute by clicking.
-    checkbutton = uifactory.from_image \
-        (sdl2ext.CHECKBUTTON, RESOURCES.get_path("button.bmp"))
+    checkbutton = uifactory.from_color(sdl2ext.CHECKBUTTON, RED, size=(50, 50))
     checkbutton.position = 200, 50
 
     # Bind some actions to the button's event handlers. Whenever a click
     entry.input += oninput
     entry.editing += onedit
 
+    checkbutton.click += oncheck
+    checkbutton.factory = factory
+
     # Since all gui elements are sprites, we can use the
     # SpriteRenderer class, we learned about in helloworld.py, to
     # draw them on the Window.
-    spriterenderer = spritefactory.create_sprite_renderer(window)
+    spriterenderer = factory.create_sprite_renderer(window)
 
     # Create a new UIProcessor, which will handle the user input events
     # and pass them on to the relevant user interface elements.

examples/helloworld.py

     # after creation. Thus we need to tell it to be shown now.
     window.show()
 
+    # Create a sprite factory that allows us to create visible 2D elements
+    # easily. Depending on what the user chosses, we either create a factory
+    # that supports hardware-accelerated sprites or software-based ones.
+    # The hardware-accelerated SpriteFactory requres a rendering context
+    # (or SDL_Renderer), which will create the underlying textures for us.
     if "-hardware" in sys.argv:
         print("Using hardware acceleration")
         renderer = sdl2ext.RenderContext(window)

examples/particles.py

     window = sdl2ext.Window("Particles", size=(800, 600))
     window.show()
 
+    # Create a hardware-accelerated sprite factory. The sprite factory requires
+    # a rendering context, which enables it to create the underlying textures
+    # that serve as the visual parts for the sprites.
     renderer = sdl2ext.RenderContext(window)
     factory = sdl2ext.SpriteFactory(sdl2ext.TEXTURE, renderer=renderer)
 

examples/sdl2hello.py

 
 from sdl2 import *
 
+
 def run():
     SDL_Init(SDL_INIT_VIDEO)
     window = SDL_CreateWindow(b"Hello World",
     SDL_Quit()
     return 0
 
+
 if __name__ == "__main__":
     sys.exit(run())
         elif uitype == TEXTENTRY:
             _compose_textentry(sprite)
         else:
+            del sprite
             raise ValueError("uitype must be a valid UI type identifier")
         return sprite
 
         elif uitype == TEXTENTRY:
             _compose_textentry(sprite)
         else:
+            del sprite
             raise ValueError("uitype must be a valid UI type identifier")
         return sprite
 
         elif uitype == TEXTENTRY:
             _compose_textentry(sprite)
         else:
+            del sprite
+            raise ValueError("uitype must be a valid UI type identifier")
+        return sprite
+
+    def from_color(self, uitype, color, size):
+        """Creates a new UI element using a certain color."""
+        sprite = self.spritefactory.from_color(color, size)
+        if uitype == BUTTON:
+            _compose_button(sprite)
+        elif uitype == CHECKBUTTON:
+            _compose_checkbutton(sprite)
+        elif uitype == TEXTENTRY:
+            _compose_textentry(sprite)
+        else:
+            del sprite
             raise ValueError("uitype must be a valid UI type identifier")
         return sprite
 

sdl2/ext/sprite.py

             s = SoftwareSprite(imgsurface.contents, True)
         return s
 
-    def from_color(self, color, size=(0, 0), bpp=32, masks=None):
+    def from_color(self, color, size, bpp=32, masks=None):
         """Creates a sprite with a certain color.
         """
         color = convert_to_color(color)
         else:
             return self.create_software_sprite(**args)
 
-    def create_software_sprite(self, size=(0, 0), bpp=32, masks=None):
+    def create_software_sprite(self, size, bpp=32, masks=None):
         """Creates a software sprite.
 
         A size tuple containing the width and height of the sprite and a
             raise SDLError()
         return SoftwareSprite(imgsurface.contents, True)
 
-    def create_texture_sprite(self, renderer, size=(0, 0),
+    def create_texture_sprite(self, renderer, size,
                                pformat=pixels.SDL_PIXELFORMAT_RGBA8888,
                                static=True):
         """Creates a texture sprite.