Пример #1
0
    def __init__(self, shader_programs=None, version=(3, 3)):
        if sdl2.SDL_Init(sdl2.SDL_INIT_VIDEO) != 0:
            print(sdl2.SDL_GetError())
            return -1

        self.window = sdl2.SDL_CreateWindow(b"SDL2 OpenGL Context",
                                            sdl2.SDL_WINDOWPOS_UNDEFINED,
                                            sdl2.SDL_WINDOWPOS_UNDEFINED,
                                            self.viewport[2], self.viewport[3],
                                            sdl2.SDL_WINDOW_OPENGL)
        if not self.window:
            print(sdl2.SDL_GetError())
            return -1

        # Force OpenGL 3.3 'core' context.
        # Must set *before* creating GL context!
        video.SDL_GL_SetAttribute(video.SDL_GL_CONTEXT_MAJOR_VERSION,
                                  version[0])
        video.SDL_GL_SetAttribute(video.SDL_GL_CONTEXT_MINOR_VERSION,
                                  version[1])
        video.SDL_GL_SetAttribute(video.SDL_GL_CONTEXT_PROFILE_MASK,
                                  video.SDL_GL_CONTEXT_PROFILE_CORE)
        self.context = sdl2.SDL_GL_CreateContext(self.window)

        self.update()
Пример #2
0
def _create_handles(window_title, window_position, window_size, window_flags,
                    renderer_info):
    """Create the SDL2 handles."""
    window_flags = sdl2.SDL_WINDOW_SHOWN | window_flags
    if renderer_info.api == GraphicsAPI.OPENGL:
        window_flags |= sdl2.SDL_WINDOW_OPENGL
        window = sdl2.SDL_CreateWindow(
            window_title.encode(),
            window_position.x, window_position.y,
            window_size.x, window_size.y,
            window_flags)
        if not window:
            raise RuntimeError(sdl2.SDL_GetError().decode())

        context = sdl2.SDL_GL_CreateContext(window)
        if not context:
            raise RuntimeError(sdl2.SDL_GetError().decode())

        # Try to disable the vertical synchronization. It applies to the active
        # context and thus needs to be called after `SDL_GL_CreateContext`.
        sdl2.SDL_GL_SetSwapInterval(0)

        return _Handles(
            window=window,
            renderer=_GLHandles(context=context))
Пример #3
0
    def __init__(self, width, height, title):
        self.width, self.height = width, height
        self.title = title

        if sdl2.SDL_Init(sdl2.SDL_INIT_VIDEO) != 0:
            print(sdl2.SDL_GetError())
            exit(-1)

        self.window = sdl2.SDL_CreateWindow(
            str.encode(self.title), sdl2.SDL_WINDOWPOS_CENTERED,
            sdl2.SDL_WINDOWPOS_CENTERED, self.width, self.height,
            sdl2.SDL_WINDOW_OPENGL | sdl2.SDL_WINDOW_SHOWN)
        if not self.window:
            print(sdl2.SDL_GetError())
            exit(-1)

        # Force OpenGL 4.3 'core' context. This is needed for compute shader support.
        SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 4)
        SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 3)
        SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK,
                            SDL_GL_CONTEXT_PROFILE_CORE)

        SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 8)
        SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 8)
        SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 8)
        SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, 8)
        SDL_GL_SetAttribute(SDL_GL_BUFFER_SIZE, 32)
        SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24)
        SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1)
        self._context = sdl2.SDL_GL_CreateContext(self.window)
Пример #4
0
    def __init__(self):
        self.shaderID = 0
        self.vaoID = 0

        if sdl2.SDL_Init(sdl2.SDL_INIT_VIDEO) != 0:
            print(sdl2.SDL_GetError())
            return -1
        self.window = sdl2.SDL_CreateWindow(b"OpenGL demo",
                                            sdl2.SDL_WINDOWPOS_UNDEFINED,
                                            sdl2.SDL_WINDOWPOS_UNDEFINED, 1024,
                                            720, sdl2.SDL_WINDOW_OPENGL)
        if not self.window:
            print(sdl2.SDL_GetError())
            return -1
        # Force OpenGL 4.1 'core' context.
        sdl2.video.SDL_GL_SetAttribute(sdl2.video.SDL_GL_CONTEXT_MAJOR_VERSION,
                                       4)
        sdl2.video.SDL_GL_SetAttribute(sdl2.video.SDL_GL_CONTEXT_MINOR_VERSION,
                                       1)
        sdl2.video.SDL_GL_SetAttribute(sdl2.video.SDL_GL_CONTEXT_PROFILE_MASK,
                                       sdl2.video.SDL_GL_CONTEXT_PROFILE_CORE)
        self.context = sdl2.SDL_GL_CreateContext(self.window)
        glClearColor(0.4, 0.4, 0.4, 1.0)
        glEnable(GL_DEPTH_TEST)
        glEnable(GL_MULTISAMPLE)
        self.createTriangle(0.8)
        vertex = """#version 400 core

layout (location = 0) in vec3  inPosition;
layout (location = 1) in vec3 inColour;
out vec3 vertColour;
void main()
{
  gl_Position = vec4(inPosition, 1.0);
  vertColour = inColour;
}"""
        fragment = """#version 400 core
in vec3 vertColour;
out vec4 fragColour;
void main()
{
  fragColour = vec4(vertColour,1.0);
}
"""
        self.loadShaderFromStrings(vertex, fragment)

        self.width = 1024
        self.height = 720
Пример #5
0
def init_sdl():
    global SDL_INITED
    if SDL_INITED:
        sdl2.SDL_SetHint(sdl2.SDL_HINT_JOYSTICK_ALLOW_BACKGROUND_EVENTS, b"1")
    else:
        if sdl2.SDL_Init(SDL_SUBSYSTEMS) < 0:
            sdl_e = sdl2.SDL_GetError()
            sdl_e = sdl_e.decode('utf-8') if sdl_e else 'UNKNOWN ERROR'
            sdl2.SDL_Quit()
            raise RuntimeError(
                'Failed to initialize SDL ("{}").'.format(sdl_e))
        # The following SDL_SetHint call causes SDL2 to process joystick (and game controller, as the
        # game controller subsystem is built on the joystick subsystem) events without a window created
        # and owned by SDL2 focused or even extant.  In our case, we have no SDL2 window, and
        # we do not even initialize the SDL2 video subsystem.
        sdl2.SDL_SetHint(sdl2.SDL_HINT_JOYSTICK_ALLOW_BACKGROUND_EVENTS, b"1")
        if sdl2.SDL_JoystickEventState(sdl2.SDL_QUERY) != sdl2.SDL_ENABLE:
            sdl2.SDL_JoystickEventState(sdl2.SDL_ENABLE)
        if sdl2.SDL_GameControllerEventState(
                sdl2.SDL_QUERY) != sdl2.SDL_ENABLE:
            sdl2.SDL_GameControllerEventState(sdl2.SDL_ENABLE)
        SDL_INITED = True

        def deinit_sdl():
            sdl2.SDL_QuitSubSystem(SDL_SUBSYSTEMS)
            sdl2.SDL_Quit()

        import atexit
        atexit.register(deinit_sdl)
Пример #6
0
def enumerate_devices():
    with contextlib.ExitStack() as estack:
        # We may be called from a different thread than the one that will run the SDL event loop.  In case that
        # will happen, if SDL is not already initialized, we do not leave it initialized (if we did, it would be
        # bound to our current thread, which may not be desired).
        if not SDL_INITED:
            if sdl2.SDL_Init(sdl2.SDL_INIT_JOYSTICK
                             | sdl2.SDL_INIT_GAMECONTROLLER) < 0:
                sdl_e = sdl2.SDL_GetError()
                sdl_e = sdl_e.decode('utf-8') if sdl_e else 'UNKNOWN ERROR'
                sdl2.SDL_Quit()
                raise RuntimeError(
                    'Failed to initialize SDL ("{}").'.format(sdl_e))
            estack.callback(lambda: sdl2.SDL_QuitSubSystem(
                sdl2.SDL_INIT_JOYSTICK | sdl2.SDL_INIT_GAMECONTROLLER))
            estack.callback(sdl2.SDL_Quit)
        rows = []
        for sdl_dev_idx in range(sdl2.SDL_NumJoysticks()):
            device_is_game_controller = bool(
                sdl2.SDL_IsGameController(sdl_dev_idx))
            device_type = 'game controller' if device_is_game_controller else 'joystick'
            cols = [
                sdl_dev_idx, device_type,
                sdl2.SDL_JoystickNameForIndex(sdl_dev_idx).decode('utf-8')
            ]
            if device_is_game_controller:
                cols.append(
                    sdl2.SDL_GameControllerNameForIndex(sdl_dev_idx).decode(
                        'utf-8'))
            rows.append(cols)
    return rows
Пример #7
0
    def __init__(self, Δx=1.0, Δy=1.0, m=10, n=10):
        self.Δx = Δx
        self.Δy = Δy
        self.m = m
        self.n = n
        self.width = Δx * m
        self.height = Δy * n

        if sdl2.SDL_Init(sdl2.SDL_INIT_VIDEO) != 0:
            print(sdl2.SDL_GetError())
            return

        sdl2.SDL_GL_SetAttribute(sdl2.SDL_GL_CONTEXT_MAJOR_VERSION, 3)
        sdl2.SDL_GL_SetAttribute(sdl2.SDL_GL_CONTEXT_MINOR_VERSION, 3)
        sdl2.SDL_GL_SetAttribute(sdl2.SDL_GL_CONTEXT_PROFILE_MASK,
                                 sdl2.SDL_GL_CONTEXT_PROFILE_CORE)
        self.window = sdl2.SDL_CreateWindow(
            b"Example 1", sdl2.SDL_WINDOWPOS_UNDEFINED,
            sdl2.SDL_WINDOWPOS_UNDEFINED, 640, 480,
            sdl2.SDL_WINDOW_OPENGL | sdl2.SDL_WINDOW_ALWAYS_ON_TOP)
        sdl2.SDL_SetWindowInputFocus(self.window)
        self.context = sdl2.SDL_GL_CreateContext(self.window)
        self.setupGL()
        self.prepGrid()
        self.prepBuffers()
        sdl2.SDL_RaiseWindow(self.window)
Пример #8
0
def with_sdl():
    sdl2.SDL_ClearError()
    ret = sdl2.SDL_Init(sdl2.SDL_INIT_VIDEO | sdl2.SDL_INIT_TIMER)
    assert sdl2.SDL_GetError() == b""
    assert ret == 0
    yield
    sdl2.SDL_Quit()
Пример #9
0
 def check_SDL_Error(self):
     err = sdl2.SDL_GetError()
     if (err):
         print(err)
         return True
     else:
         return False
Пример #10
0
def run():
    if sdl2.SDL_Init(sdl2.SDL_INIT_VIDEO) != 0:
        print(sdl2.SDL_GetError())
        return -1

    window = sdl2.SDL_CreateWindow(b"OpenGL demo",
                                   sdl2.SDL_WINDOWPOS_UNDEFINED,
                                   sdl2.SDL_WINDOWPOS_UNDEFINED, 800, 600,
                                   sdl2.SDL_WINDOW_OPENGL)
    if not window:
        print(sdl2.SDL_GetError())
        return -1

    context = sdl2.SDL_GL_CreateContext(window)

    GL.glMatrixMode(GL.GL_PROJECTION | GL.GL_MODELVIEW)
    GL.glLoadIdentity()
    GL.glOrtho(-400, 400, 300, -300, 0, 1)

    x = 0.0
    y = 30.0

    event = sdl2.SDL_Event()
    running = True
    while running:
        while sdl2.SDL_PollEvent(ctypes.byref(event)) != 0:
            if event.type == sdl2.SDL_QUIT:
                running = False

        GL.glClearColor(0, 0, 0, 1)
        GL.glClear(GL.GL_COLOR_BUFFER_BIT)
        GL.glRotatef(10.0, 0.0, 0.0, 1.0)
        GL.glBegin(GL.GL_TRIANGLES)
        GL.glColor3f(1.0, 0.0, 0.0)
        GL.glVertex2f(x, y + 90.0)
        GL.glColor3f(0.0, 1.0, 0.0)
        GL.glVertex2f(x + 90.0, y - 90.0)
        GL.glColor3f(0.0, 0.0, 1.0)
        GL.glVertex2f(x - 90.0, y - 90.0)
        GL.glEnd()

        sdl2.SDL_GL_SwapWindow(window)
        sdl2.SDL_Delay(10)
    sdl2.SDL_GL_DeleteContext(context)
    sdl2.SDL_DestroyWindow(window)
    sdl2.SDL_Quit()
    return 0
Пример #11
0
 def render_object_from_surface(cls, renderer: sdl2.SDL_Renderer,
                                surface: sdl2.SDL_Surface) -> RenderObject:
     texture = sdl2.SDL_CreateTextureFromSurface(renderer, surface)
     if not texture:
         raise RuntimeError(
             "Unable to create texture from surface! SDL Error: " +
             str(sdl2.SDL_GetError()))
     return RenderObject(texture)
Пример #12
0
    def __init__(self,
                 width,
                 height,
                 title='Window',
                 alpha_blending=True,
                 full_screen=False,
                 gl_major=4,
                 gl_minor=1):
        self._width = width
        self._height = height
        self._aspect_ratio = float(width) / float(height)
        self._viewport = Rect(0, 0, width, height)
        self._full_screen = full_screen

        # Create the window
        if sdl2.SDL_Init(sdl2.SDL_INIT_VIDEO) != 0:
            print(sdl2.SDL_GetError())

        self._window = sdl2.SDL_CreateWindow(str.encode(title),
                                             sdl2.SDL_WINDOWPOS_UNDEFINED,
                                             sdl2.SDL_WINDOWPOS_UNDEFINED,
                                             width, height,
                                             sdl2.SDL_WINDOW_OPENGL)

        if not self._window:
            print(sdl2.SDL_GetError())
            return

        # Set up OpenGL
        video.SDL_GL_SetAttribute(video.SDL_GL_CONTEXT_MAJOR_VERSION, gl_major)
        video.SDL_GL_SetAttribute(video.SDL_GL_CONTEXT_MINOR_VERSION, gl_minor)
        video.SDL_GL_SetAttribute(video.SDL_GL_CONTEXT_PROFILE_MASK,
                                  video.SDL_GL_CONTEXT_PROFILE_CORE)
        self._context = sdl2.SDL_GL_CreateContext(self._window)
        self._projection_matrix = self._ortho_projection()

        if alpha_blending:
            glEnable(GL_BLEND)
            glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)

        if full_screen:
            self.full_screen = True

        # Post processing steps
        self._pp_steps = []
Пример #13
0
	def __init__ (self):
		if sdl2.SDL_Init(sdl2.SDL_INIT_AUDIO) != 0:
			raise RuntimeError("Cannot initialize audio system: {}".format(sdl2.SDL_GetError()))
		fmt = sdl2.sdlmixer.MIX_DEFAULT_FORMAT
		if sdl2.sdlmixer.Mix_OpenAudio(44100, fmt, 2, 1024) != 0:
			raise RuntimeError("Cannot open mixed audio: {}".format(sdl2.sdlmixer.Mix_GetError()))
		sdl2.sdlmixer.Mix_AllocateChannels(64)
		self._bank_se = {}
		self._bgm = None
Пример #14
0
def initFont(fontFile, renderer, defaultFontSize=10):
	# Open the font
	sdl2.SDL_ClearError()
	font = sdl2.sdlttf.TTF_OpenFont(fontFile.encode('utf-8'), defaultFontSize)
	p = sdl2.SDL_GetError()
	if font is None or len(p)!=0:
		print("TTF_OpenFont error: " + str(p))
		return None
	return font
Пример #15
0
    def __init__(self, **kwargs):
        super().__init__(**kwargs)

        if sdl2.SDL_Init(sdl2.SDL_INIT_VIDEO) != 0:
            raise ValueError("Failed to initialize sdl2")

        # Configure OpenGL context
        sdl2.video.SDL_GL_SetAttribute(sdl2.SDL_GL_CONTEXT_MAJOR_VERSION,
                                       self.gl_version[0])
        sdl2.video.SDL_GL_SetAttribute(sdl2.SDL_GL_CONTEXT_MINOR_VERSION,
                                       self.gl_version[1])
        sdl2.video.SDL_GL_SetAttribute(sdl2.SDL_GL_CONTEXT_PROFILE_MASK,
                                       sdl2.SDL_GL_CONTEXT_PROFILE_CORE)
        sdl2.video.SDL_GL_SetAttribute(
            sdl2.SDL_GL_CONTEXT_FORWARD_COMPATIBLE_FLAG, 1)
        sdl2.video.SDL_GL_SetAttribute(sdl2.SDL_GL_DOUBLEBUFFER, 1)
        sdl2.video.SDL_GL_SetAttribute(sdl2.SDL_GL_DEPTH_SIZE, 24)

        # Display/hide mouse cursor
        sdl2.SDL_ShowCursor(
            sdl2.SDL_ENABLE if self.cursor else sdl2.SDL_DISABLE)

        # Configure multisampling
        if self.samples > 1:
            sdl2.video.SDL_GL_SetAttribute(sdl2.SDL_GL_MULTISAMPLEBUFFERS, 1)
            sdl2.video.SDL_GL_SetAttribute(sdl2.SDL_GL_MULTISAMPLESAMPLES,
                                           self.samples)

        # Built the window flags
        flags = sdl2.SDL_WINDOW_OPENGL
        if self.fullscreen:
            # Use primary desktop screen resolution
            flags |= sdl2.SDL_WINDOW_FULLSCREEN_DESKTOP
        else:
            if self.resizable:
                flags |= sdl2.SDL_WINDOW_RESIZABLE

        # Create the window
        self.window = sdl2.SDL_CreateWindow(
            self.title.encode(),
            sdl2.SDL_WINDOWPOS_UNDEFINED,
            sdl2.SDL_WINDOWPOS_UNDEFINED,
            self.width,
            self.height,
            flags,
        )

        if not self.window:
            raise ValueError("Failed to create window:", sdl2.SDL_GetError())

        self.context = sdl2.SDL_GL_CreateContext(self.window)
        sdl2.video.SDL_GL_SetSwapInterval(1 if self.vsync else 0)

        self.ctx = moderngl.create_context(require=self.gl_version_code)
        self.set_default_viewport()
        self.print_context_info()
Пример #16
0
    def __init__(self):
        """
        Initializes sdl2, sets up key and mouse events and
        creates a ``moderngl.Context`` using the context sdl2 createad.

        Using the sdl2 window requires sdl binaries and PySDL2.
        """
        super().__init__()
        self.window_closing = False
        self.tmp_size_x = c_int()
        self.tmp_size_y = c_int()

        print("Using sdl2 library version:", self.get_library_version())

        if sdl2.SDL_Init(sdl2.SDL_INIT_VIDEO) != 0:
            raise ValueError("Failed to initialize sdl2")

        sdl2.video.SDL_GL_SetAttribute(sdl2.SDL_GL_CONTEXT_MAJOR_VERSION,
                                       self.gl_version.major)
        sdl2.video.SDL_GL_SetAttribute(sdl2.SDL_GL_CONTEXT_MINOR_VERSION,
                                       self.gl_version.minor)
        sdl2.video.SDL_GL_SetAttribute(sdl2.SDL_GL_CONTEXT_PROFILE_MASK,
                                       sdl2.SDL_GL_CONTEXT_PROFILE_CORE)
        sdl2.video.SDL_GL_SetAttribute(
            sdl2.SDL_GL_CONTEXT_FORWARD_COMPATIBLE_FLAG, 1)
        sdl2.video.SDL_GL_SetAttribute(sdl2.SDL_GL_DOUBLEBUFFER, 1)
        sdl2.video.SDL_GL_SetAttribute(sdl2.SDL_GL_DEPTH_SIZE, 24)
        sdl2.SDL_ShowCursor(
            sdl2.SDL_ENABLE if self.cursor else sdl2.SDL_DISABLE)
        if self.samples > 1:
            sdl2.video.SDL_GL_SetAttribute(sdl2.SDL_GL_MULTISAMPLEBUFFERS, 1)
            sdl2.video.SDL_GL_SetAttribute(sdl2.SDL_GL_MULTISAMPLESAMPLES,
                                           self.samples)

        flags = sdl2.SDL_WINDOW_OPENGL
        if self.fullscreen:
            flags |= sdl2.SDL_WINDOW_FULLSCREEN_DESKTOP
        else:
            if self.resizable:
                flags |= sdl2.SDL_WINDOW_RESIZABLE

        self.window = sdl2.SDL_CreateWindow(self.title.encode(),
                                            sdl2.SDL_WINDOWPOS_UNDEFINED,
                                            sdl2.SDL_WINDOWPOS_UNDEFINED,
                                            self.width, self.height, flags)

        if not self.window:
            raise ValueError("Failed to create window:", sdl2.SDL_GetError())

        self.context = sdl2.SDL_GL_CreateContext(self.window)
        sdl2.video.SDL_GL_SetSwapInterval(1 if self.vsync else 0)

        self.ctx = moderngl.create_context(require=self.gl_version.code)
        context.WINDOW = self
        self.fbo = self.ctx.screen
        self.set_default_viewport()
Пример #17
0
def run():
    if sdl2.SDL_Init(sdl2.SDL_INIT_VIDEO) != 0:
        print(sdl2.SDL_GetError())
        return -1

    window = sdl2.SDL_CreateWindow(b"OpenGL demo",
                                   sdl2.SDL_WINDOWPOS_UNDEFINED,
                                   sdl2.SDL_WINDOWPOS_UNDEFINED, 800, 600,
                                   sdl2.SDL_WINDOW_OPENGL)
    if not window:
        print(sdl2.SDL_GetError())
        return -1

    # Force OpenGL 3.3 'core' context.
    # Must set *before* creating GL context!
    video.SDL_GL_SetAttribute(video.SDL_GL_CONTEXT_MAJOR_VERSION, 3)
    video.SDL_GL_SetAttribute(video.SDL_GL_CONTEXT_MINOR_VERSION, 3)
    video.SDL_GL_SetAttribute(video.SDL_GL_CONTEXT_PROFILE_MASK,
                              video.SDL_GL_CONTEXT_PROFILE_CORE)
    context = sdl2.SDL_GL_CreateContext(window)

    # Setup GL shaders, data, etc.
    initialize()

    event = sdl2.SDL_Event()
    running = True
    while running:
        while sdl2.SDL_PollEvent(ctypes.byref(event)) != 0:
            if event.type == sdl2.SDL_QUIT:
                running = False
            elif (event.type == sdl2.SDL_KEYDOWN
                  and event.key.keysym.sym == sdl2.SDLK_ESCAPE):
                running = False

        render()

        sdl2.SDL_GL_SwapWindow(window)
        sdl2.SDL_Delay(10)

    sdl2.SDL_GL_DeleteContext(context)
    sdl2.SDL_DestroyWindow(window)
    sdl2.SDL_Quit()
    return 0
Пример #18
0
 def _init_sound(self):
     """ Perform any necessary initialisations. """
     # init sdl audio in this thread separately
     sdl2.SDL_Init(sdl2.SDL_INIT_AUDIO)
     self.dev = sdl2.SDL_OpenAudioDevice(None, 0, self.audiospec, None, 0)
     if self.dev == 0:
         logging.warning('Could not open audio device: %s',
                         sdl2.SDL_GetError())
     # unpause the audio device
     sdl2.SDL_PauseAudioDevice(self.dev, 0)
Пример #19
0
 def __init__(self, input_queue, video_queue, **kwargs):
     """Initialise SDL2 interface."""
     if not sdl2:
         logging.debug('PySDL2 module not found.')
         raise base.InitFailed()
     if not numpy:
         logging.debug('NumPy module not found.')
         raise base.InitFailed()
     video_graphical.VideoGraphical.__init__(self, input_queue, video_queue, **kwargs)
     # display & border
     # border attribute
     self.border_attr = 0
     # palette and colours
     # composite colour artifacts
     self.composite_artifacts = False
     # update cycle
     # refresh cycle parameters
     self._cycle = 0
     self.last_cycle = 0
     self._cycle_time = 120
     self.blink_cycles = 5
     # cursor
     # current cursor location
     self.last_row = 1
     self.last_col = 1
     # cursor is visible
     self.cursor_visible = True
     # load the icon
     self.icon = kwargs['icon']
     # mouse setups
     buttons = {'left': sdl2.SDL_BUTTON_LEFT, 'middle': sdl2.SDL_BUTTON_MIDDLE,
                'right': sdl2.SDL_BUTTON_RIGHT, 'none': None}
     copy_paste = kwargs.get('copy-paste', ('left', 'middle'))
     self.mousebutton_copy = buttons[copy_paste[0]]
     self.mousebutton_paste = buttons[copy_paste[1]]
     self.mousebutton_pen = buttons[kwargs.get('pen', 'right')]
     # keyboard setup
     self.f11_active = False
     self.altgr = kwargs['altgr']
     if not self.altgr:
         scan_to_scan[sdl2.SDL_SCANCODE_RALT] = scancode.ALT
         mod_to_scan[sdl2.KMOD_RALT] = scancode.ALT
     # keep params for enter
     self.kwargs = kwargs
     # we need a set_mode call to be really up and running
     self._has_window = False
     # ensure the correct SDL2 video driver is chosen for Windows
     # since this gets messed up if we also import pygame
     if platform.system() == 'Windows':
         os.environ['SDL_VIDEODRIVER'] = 'windows'
     # initialise SDL
     if sdl2.SDL_Init(sdl2.SDL_INIT_EVERYTHING):
         # SDL not initialised correctly
         logging.error('Could not initialise SDL2: %s', sdl2.SDL_GetError())
         raise base.InitFailed()
Пример #20
0
    def __init__(self):
        super(SDLInputHandler, self).__init__()

        sdl2.SDL_InitSubSystem(sdl2.SDL_INIT_GAMECONTROLLER)
        ret = sdl2.SDL_GameControllerAddMappingsFromFile(
            os.path.join(os.path.dirname(__file__),
                         'controller_db.txt').encode('utf-8'))

        if ret == -1:
            raise InputError("Failed to load GameControllerDB, %s",
                             sdl2.SDL_GetError())
Пример #21
0
 def open(self):
     # Open the font
     sdl2.SDL_ClearError()
     self.font = (sdl2.sdlttf.TTF_OpenFont(self.path.encode('utf-8'),
                                           self.size))
     p = sdl2.SDL_GetError()
     if len(p) != 0:
         print(
             f"TTF_OpenFont error: {str(p)}\nFont file: {self.path} size: {self.size}"
         )
         return -1
Пример #22
0
    def __buildWindow(self):
        if sdl2.SDL_Init(sdl2.SDL_INIT_VIDEO) != 0:
            raise Exception(sdl2.SDL_GetError())

        sdl2.SDL_GL_SetAttribute(sdl2.SDL_GL_CONTEXT_MAJOR_VERSION, self.major)
        sdl2.SDL_GL_SetAttribute(sdl2.SDL_GL_CONTEXT_MINOR_VERSION, self.minor)

        self.window = sdl2.SDL_CreateWindow(b'ETGG2801 Example',
                                            sdl2.SDL_WINDOWPOS_UNDEFINED,
                                            sdl2.SDL_WINDOWPOS_UNDEFINED,
                                            self.size[0], self.size[1],
                                            sdl2.SDL_WINDOW_OPENGL)

        self.glcontext = sdl2.SDL_GL_CreateContext(self.window)
        if not self.glcontext:
            sdl2.SDL_DestroyWindow(self.window)
            raise Exception(sdl2.SDL_GetError())

        # keep application from receiving text input events
        sdl2.SDL_StopTextInput()
Пример #23
0
    def __buildWindow(self):
        if sdl2.SDL_Init(sdl2.SDL_INIT_VIDEO) != 0:
            raise Exception(sdl2.SDL_GetError())

        sdlimage.IMG_Init(sdlimage.IMG_INIT_PNG | sdlimage.IMG_INIT_JPG)

        sdl2.SDL_GL_SetAttribute(sdl2.SDL_GL_CONTEXT_PROFILE_MASK,
                                 sdl2.SDL_GL_CONTEXT_PROFILE_CORE)

        self.window = sdl2.SDL_CreateWindow(b'ETGG2801 Example', 0, 0,
                                            self.size[0], self.size[1],
                                            sdl2.SDL_WINDOW_OPENGL)

        self.glcontext = sdl2.SDL_GL_CreateContext(self.window)
        if not self.glcontext:
            sdl2.SDL_DestroyWindow(self.window)
            raise Exception(sdl2.SDL_GetError())

        # keep application from receiving text input events
        sdl2.SDL_StopTextInput()
Пример #24
0
    def __init__(self):
        self.dynamo = Dynamo()

        self.event_manager = EventManager()
        self.windows = []
        self.time_keeper = TimeKeeper()
        self.time_keeper.update()

        if sdl2.SDL_Init(sdl2.SDL_INIT_VIDEO) != 0:
            raise RuntimeError('SDL_Init failed: {}'.format(
                sdl2.SDL_GetError()))
Пример #25
0
def loadFontFile(fontFile, fontSize):
    # Open the font file
    sdl2.SDL_ClearError()
    font = sdl2.sdlttf.TTF_OpenFont(fontFile, int(fontSize))
    err = sdl2.SDL_GetError()

    if font is None or not err == '':
        print "TTF_OpenFont error: " + err
        return None

    return font
Пример #26
0
    def open(self, configuration):
        '''Open the SDL2 Window

        *Parameters:*

        - `configuration`: Configurations parameters from Application
        '''
        if sdl2.SDL_Init(sdl2.SDL_INIT_VIDEO) != 0:
            msg = "Can't open window: %s" % sdl2.SDL_GetError()
            logger.critical(msg)
            raise SDL2Error(msg)

        flags = 0
        if configuration.fullscreen and \
           configuration.width and configuration.height:
            flags |= sdl2.SDL_WINDOW_FULLSCREEN
        elif configuration.fullscreen:
            flags |= sdl2.SDL_WINDOW_FULLSCREEN_DESKTOP
        if not configuration.decorated:
            flags |= sdl2.SDL_WINDOW_BORDERLESS
        if configuration.resizable:
            flags |= sdl2.SDL_WINDOW_RESIZABLE
        if configuration.highdpi:
            flags |= sdl2.SDL_WINDOW_ALLOW_HIGHDPI

        self.window = sdl2.SDL_CreateWindow(configuration.name.encode('ascii'),
                                            configuration.x, configuration.y,
                                            configuration.width,
                                            configuration.height, 0)

        if not self.window:
            msg = "Can't open window: %s" % sdl2.SDL_GetError()
            logger.critical(msg)
            raise SDL2Error(msg)

        logger.debug("SDL2 window opened with configuration: %s",
                     (configuration, ))

        self.info = sdl2.SDL_SysWMinfo()
        sdl2.SDL_VERSION(self.info.version)
        sdl2.SDL_GetWindowWMInfo(self.window, ctypes.byref(self.info))
Пример #27
0
    def _no_error(self, value):
        if value != 0:
            msg = sdl2.SDL_GetError()
            msg = 'SDL error (%s): %s' % (value, msg)

            # TODO: Figure out what is the problem with PyPy and some GFX
            # functions. For now we are just ignoring errors and rendering
            # some figures improperly
            if 'PyPy' in sys.version:
                warn(msg)
            else:
                raise RuntimeError(msg)
Пример #28
0
    def __init__(self, **kwargs):
        super().__init__(**kwargs)

        if sdl2.SDL_Init(sdl2.SDL_INIT_VIDEO) != 0:
            raise ValueError("Failed to initialize sdl2")

        sdl2.video.SDL_GL_SetAttribute(sdl2.SDL_GL_CONTEXT_MAJOR_VERSION,
                                       self.gl_version[0])
        sdl2.video.SDL_GL_SetAttribute(sdl2.SDL_GL_CONTEXT_MINOR_VERSION,
                                       self.gl_version[1])
        sdl2.video.SDL_GL_SetAttribute(sdl2.SDL_GL_CONTEXT_PROFILE_MASK,
                                       sdl2.SDL_GL_CONTEXT_PROFILE_CORE)
        sdl2.video.SDL_GL_SetAttribute(
            sdl2.SDL_GL_CONTEXT_FORWARD_COMPATIBLE_FLAG, 1)
        sdl2.video.SDL_GL_SetAttribute(sdl2.SDL_GL_DOUBLEBUFFER, 1)
        sdl2.video.SDL_GL_SetAttribute(sdl2.SDL_GL_DEPTH_SIZE, 24)

        sdl2.SDL_ShowCursor(
            sdl2.SDL_ENABLE if self.cursor else sdl2.SDL_DISABLE)

        if self.samples > 1:
            sdl2.video.SDL_GL_SetAttribute(sdl2.SDL_GL_MULTISAMPLEBUFFERS, 1)
            sdl2.video.SDL_GL_SetAttribute(sdl2.SDL_GL_MULTISAMPLESAMPLES,
                                           self.samples)

        flags = sdl2.SDL_WINDOW_OPENGL
        if self.fullscreen:
            flags |= sdl2.SDL_WINDOW_FULLSCREEN_DESKTOP
        else:
            if self.resizable:
                flags |= sdl2.SDL_WINDOW_RESIZABLE

        self._window = sdl2.SDL_CreateWindow(
            self.title.encode(),
            sdl2.SDL_WINDOWPOS_UNDEFINED,
            sdl2.SDL_WINDOWPOS_UNDEFINED,
            self.width,
            self.height,
            flags,
        )

        if not self._window:
            raise ValueError("Failed to create window:", sdl2.SDL_GetError())

        self._context = sdl2.SDL_GL_CreateContext(self._window)

        sdl2.video.SDL_GL_SetSwapInterval(1 if self.vsync else 0)

        if self._create_mgl_context:
            self.init_mgl_context()

        self.set_default_viewport()
Пример #29
0
    def __init__(self, width, height, title="Pythons", borders=True):
        self.width, self.height = width, height
        self.show_borders = borders
        self.title = title.encode()
        if sdl2.SDL_Init(sdl2.SDL_INIT_VIDEO) != 0:
            print(sdl2.SDL_GetError())
            return -1
        sdl2.sdlttf.TTF_Init()
        sdl2.sdlimg.IMG_Init(sdl2img.IMG_INIT_PNG)

        self.window = sdl2.SDL_CreateWindow(self.title,
                                            sdl2.SDL_WINDOWPOS_UNDEFINED,
                                            sdl2.SDL_WINDOWPOS_UNDEFINED,
                                            self.width, self.height,
                                            sdl2.SDL_WINDOW_OPENGL)
        sdl2.SDL_SetWindowBordered(self.window, self.show_borders)
        if not self.window:
            print(sdl2.SDL_GetError())
            return -1

        self.renderer = sdl2.SDL_CreateRenderer(
            self.window, -1,
            sdl2.SDL_RENDERER_ACCELERATED | sdl2.SDL_RENDERER_PRESENTVSYNC)
Пример #30
0
    def createWindow(self):
        # Create the window context
        if sdl2.SDL_Init(sdl2.SDL_INIT_VIDEO) != 0:
            print(sdl2.SDL_GetError())
            return -1
        sdl2ttf.TTF_Init()
        sdl2img.IMG_Init(sdl2img.IMG_INIT_PNG)

        self.window = sdl2.SDL_CreateWindow(self.params["title"].encode(),
                                            sdl2.SDL_WINDOWPOS_UNDEFINED,
                                            sdl2.SDL_WINDOWPOS_UNDEFINED,
                                            self.window_width,
                                            self.window_height,
                                            sdl2.SDL_WINDOW_OPENGL)
        sdl2.SDL_SetWindowBordered(self.window, self.show_borders)
        if not self.window:
            print(sdl2.SDL_GetError())
            return -1

        # Renderer
        self.renderer = sdl2.SDL_CreateRenderer(
            self.window, -1,
            sdl2.SDL_RENDERER_ACCELERATED | sdl2.SDL_RENDERER_PRESENTVSYNC)

        # Build the GUI
        self.buildElements()

        # onStart handler
        if self.onStart is not None:
            if self.onStart[1] is None:
                self.onStart[0]()
            else:
                self.onStart[0](self.onStart[1])

        # look for events
        self._loopForEvents()