Esempio n. 1
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
Esempio n. 2
0
    async def run_async(self):
        self.running = True
        self.startup()

        def event_handler(data, event_ptr):
            if self.running:
                # SDL2 seems to re-use SDL_Event structures, so we need to make a copy.
                event = sdl2.SDL_Event()
                ctypes.pointer(event)[0] = event_ptr.contents
                self.dispatch(event)
            return 0

        watcher = sdl2.SDL_EventFilter(event_handler)
        sdl2.SDL_AddEventWatch(watcher, None)

        loop = asyncio.get_running_loop()

        fps = 60.0
        frame_time = 1.0 / fps
        last_tick = loop.time()
        while self.running:
            sdl2.SDL_PumpEvents()
            # dt here will be how much time since the last loop minus any event handling.
            dt = loop.time() - last_tick
            await asyncio.sleep(max(0, frame_time - dt))
            # dt here will be how much time since the last call to tick.
            dt = loop.time() - last_tick
            self.tick(dt)
            last_tick = loop.time()

        sdl2.SDL_DelEventWatch(watcher, None)
        self.cleanup()
        sdl2.SDL_Quit()
Esempio n. 3
0
    def main_loop(self):
        running = True

        def toggle_running(event):
            print('Quit event detected')
            nonlocal running
            running = not running

        self.event_manager.add_quit_callback(toggle_running)
        self.event_manager.add_keydown_callback(sdl2.SDLK_q, toggle_running)
        boa_gfx.gl_shader.shader_manager.shader_paths.append(
            './boa_gfx/shaders')
        boa_gfx.gl_shader.shader_manager.shader_paths.append('./shaders')
        boa_gfx.gl_texture.texture_manager.texture_paths.append(
            './source_images')

        self.windows[0].camera.position = (-0.5, 0.0, 13.0)
        self.windows[0].fullscreen = True

        background = TexturedTriangleStrip(texture_name='background.png')
        background.position = (0.0, 0.0, 0.0)
        background.scale = 13

        while running:
            self.time_keeper.update()
            self.dynamo.run()
            self.event_manager.process_events()

            for w in self.windows:
                w.render()
            sdl2.SDL_Delay(1)

        for w in self.windows:
            w.close()
        sdl2.SDL_Quit()
Esempio n. 4
0
def main():
    sdl2.sdl2_load(
        ctypes.util.find_library('SDL2'))  # '/usr/local/lib/libSDL2.dylib'

    sdl2.SDL_Init(sdl2.SDL_INIT_EVERYTHING)

    WINDOW_W = 320
    WINDOW_H = 240
    window = sdl2.SDL_CreateWindow(b"1st SDL Window via Python-SDL2", 0, 0,
                                   WINDOW_W, WINDOW_H, 0)

    fpsdelay = 100
    count = 0
    event = sdl2.SDL_Event()
    done = False
    while not done:
        while sdl2.SDL_PollEvent(ctypes.byref(event)) != 0:
            # 'type' and 'timestamp' are common members for all SDL Event structs.
            event_type = event.common.type
            event_timestamp = event.common.timestamp
            print("Event : type=0x%s, timestamp=%s" %
                  (event_type, event_timestamp))

            if event_type == sdl2.SDL_KEYDOWN:
                if event.key.keysym.sym == sdl2.SDLK_ESCAPE:
                    print("\tSPACE key pressed.")

        count += 1
        if count >= 100:
            done = True
        sdl2.SDL_Delay(fpsdelay)

    sdl2.SDL_Quit()
Esempio n. 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)
Esempio n. 6
0
def main():
    sdl2.sdl2_load(
        ctypes.util.find_library('SDL2'))  # '/usr/local/lib/libSDL2.dylib'

    sdl2.SDL_Init(sdl2.SDL_INIT_EVERYTHING)
    # sdl2.SDL_SetMainReady()

    version = sdl2.SDL_version()
    sdl2.SDL_GetVersion(ctypes.byref(version))
    print('Major, Minor and Patch: ', version.major, version.minor,
          version.patch)
    print('Revision and its Number: ', sdl2.SDL_GetRevision(),
          sdl2.SDL_GetRevisionNumber())

    print('Base Path: ', sdl2.SDL_GetBasePath())
    print('Touch Devices: ', sdl2.SDL_GetNumTouchDevices())
    print('Power State: ', sdl2.SDL_GetPowerInfo(None, None))

    print('Have AVX: ', sdl2.SDL_HasAVX())
    print('System RAM: ', sdl2.SDL_GetSystemRAM())

    print('Platform: ', sdl2.SDL_GetPlatform())

    print('Pixel Format: ',
          sdl2.SDL_GetPixelFormatName(sdl2.SDL_PIXELFORMAT_RGBA32))

    # Test features added in 2.0.10
    # Ref.: https://discourse.libsdl.org/t/sdl-2-0-10-released/26429
    print('Touch Device (0) Type: ',
          sdl2.SDL_GetTouchDeviceType(sdl2.SDL_GetTouchDevice(0)))
    print('SIMD Alignment: ', sdl2.SDL_SIMDGetAlignment())

    sdl2.SDL_Quit()
Esempio n. 7
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()
Esempio n. 8
0
    def __exit__(self, *exc):
        LOG.debug('Quitting SDL mixer')
        sdlmixer.Mix_Quit()

        LOG.debug('Quitting SDL context')
        sdl.SDL_Quit()
        return False
Esempio n. 9
0
def main():
    sdl2.sdl2_load(ctypes.util.find_library('SDL2')) # '/usr/local/lib/libSDL2.dylib'
    sdl2.SDL_Init(sdl2.SDL_INIT_EVERYTHING)

    fpsdelay = 100
    count = 0
    event = sdl2.SDL_Event()
    done = False
    while not done:
        while sdl2.SDL_PollEvent(ctypes.byref(event)) != 0:
            # 'type' and 'timestamp' are common members for all SDL Event structs.
            event_type = event.common.type
            event_timestamp = event.common.timestamp
            print("Event : type=0x%s, timestamp=%s" % (event_type, event_timestamp) )

            if event_type == sdl2.SDL_KEYDOWN:
                if event.key.keysym.sym == sdl2.SDLK_ESCAPE:
                    done = True

        count += 1
        if count >= 100:
            done = True
        sdl2.SDL_Delay(fpsdelay)

    sdl2.SDL_Quit()
Esempio n. 10
0
def run():
    sdl2.SDL_Init(sdl2.SDL_INIT_VIDEO)
    window = sdl2.SDL_CreateWindow(b"Hello World", sdl2.SDL_WINDOWPOS_CENTERED,
                                   sdl2.SDL_WINDOWPOS_CENTERED, 592, 460,
                                   sdl2.SDL_WINDOW_SHOWN)
    fname = os.path.join(os.path.dirname(os.path.abspath(__file__)),
                         "resources", "hello.bmp")
    image = sdl2.SDL_LoadBMP(fname.encode("utf-8"))
    windowsurface = sdl2.SDL_GetWindowSurface(window)
    sdl2.SDL_BlitSurface(image, None, windowsurface, None)
    sdl2.SDL_UpdateWindowSurface(window)
    sdl2.SDL_FreeSurface(image)

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

    sdl2.SDL_DestroyWindow(window)
    sdl2.SDL_Quit()
    return 0
Esempio n. 11
0
 def destroy(self):
     """
     Gracefully close the window
     """
     sdl2.SDL_GL_DeleteContext(self.context)
     sdl2.SDL_DestroyWindow(self.window)
     sdl2.SDL_Quit()
Esempio n. 12
0
def main():
    window_size = (DEFAULT_WINDOW_WIDTH, DEFAULT_WINDOW_HEIGHT)
    sdl2.SDL_Init(sdl2.SDL_INIT_VIDEO)
    window = sdl2.SDL_CreateWindow(
        b"Lab 1 - Cardioid", sdl2.SDL_WINDOWPOS_CENTERED,
        sdl2.SDL_WINDOWPOS_CENTERED, window_size[0], window_size[1],
        sdl2.SDL_WINDOW_SHOWN | sdl2.SDL_WINDOW_RESIZABLE)
    # CREATE !!!
    renderer = sdl2.SDL_CreateRenderer(window, -1,
                                       sdl2.SDL_RENDERER_ACCELERATED)

    running = True
    event = sdl2.SDL_Event()
    while running:
        while sdl2.SDL_PollEvent(ctypes.byref(event)) != 0:
            if event.type == sdl2.SDL_QUIT:
                running = False
                break
            elif event.type == sdl2.SDL_WINDOWEVENT:
                if event.window.event == sdl2.SDL_WINDOWEVENT_SIZE_CHANGED:
                    new_width = event.window.data1
                    new_height = event.window.data2
                    print("Window {} resized to {}x{}".format(
                        event.window.windowID, new_width, new_height))
                    window_size = (new_width, new_height)
            draw(renderer, window_size)
    sdl2.SDL_DestroyWindow(window)
    sdl2.SDL_Quit()
    return 0
Esempio n. 13
0
    def terminate(self):
        """Cleanup the GUI resources."""
        self._renderer.cleanup()
        if hienoi.renderer.get_info().api == GraphicsAPI.OPENGL:
            sdl2.SDL_GL_DeleteContext(self._handles.renderer.context)

        sdl2.SDL_DestroyWindow(self._handles.window)
        sdl2.SDL_Quit()
Esempio n. 14
0
def main():
    sdl2.sdl2_load(ctypes.util.find_library('SDL2'), # '/usr/local/lib/libSDL2.dylib'
                   ttf_libpath = ctypes.util.find_library('SDL2_ttf'),
                   img_libpath = ctypes.util.find_library('SDL2_image')
                   )
    sdl2.SDL_Init(sdl2.SDL_INIT_EVERYTHING)

    WINDOW_W = 640
    WINDOW_H = 360
    window = sdl2.SDL_CreateWindow(b"Minimal SDL_Image Test via python-sdl2", 0, 0, WINDOW_W, WINDOW_H, sdl2.SDL_WINDOW_OPENGL)

    renderer = sdl2.SDL_CreateRenderer(window, -1, 0)

    sdl2.IMG_Init(sdl2.IMG_INIT_JPG|sdl2.IMG_INIT_PNG|sdl2.IMG_INIT_TIF|sdl2.IMG_INIT_WEBP)

    rwops_ptr = sdl2.SDL_RWFromFile(bytes(sys.argv[1], 'utf-8'), b"rb")

    print("PNG?: %s" % ('true' if sdl2.IMG_isPNG(rwops_ptr) else 'false'))

    texture = sdl2.IMG_LoadTexture_RW(renderer, rwops_ptr, 1)

    wh = 300
    pos = sdl2.SDL_Rect()
    pos.x = int((WINDOW_W - wh) / 2)
    pos.y = int((WINDOW_H - wh) / 2)
    pos.w = wh
    pos.h = wh

    sdl2.SDL_RenderCopy(renderer, texture, None, ctypes.byref(pos))

    sdl2.SDL_RenderPresent(renderer)

    fpsdelay = 100
    count = 0
    event = sdl2.SDL_Event()
    done = False
    while not done:
        while sdl2.SDL_PollEvent(ctypes.byref(event)) != 0:
            # 'type' and 'timestamp' are common members for all SDL Event structs.
            event_type = event.common.type
            event_timestamp = event.common.timestamp
            # print("Event : type=0x%s, timestamp=%s" % (event_type, event_timestamp) )

            if event_type == sdl2.SDL_KEYDOWN:
                if event.key.keysym.sym == sdl2.SDLK_ESCAPE:
                    done = True

        sdl2.SDL_SetRenderDrawColor(renderer, 0xA0, 0xA0, 0xA0, 0xFF)
        sdl2.SDL_RenderClear(renderer)
        sdl2.SDL_RenderCopy(renderer, texture, None, ctypes.byref(pos))
        sdl2.SDL_RenderPresent(renderer)

        sdl2.SDL_Delay(fpsdelay)

    sdl2.IMG_Quit()
    sdl2.SDL_DestroyRenderer(renderer)
    sdl2.SDL_DestroyWindow(window)
    sdl2.SDL_Quit()
Esempio n. 15
0
    def __init__(self, joystick):
        self.js = joystick

        sdl2.SDL_Init(sdl2.SDL_INIT_GAMECONTROLLER)
        js = sdl2.joystick.SDL_JoystickOpen(self.js.get_id())
        guid = sdl2.joystick.SDL_JoystickGetGUID(js)
        my_guid = SDL_JoystickGetGUIDString(guid)

        self.name = self.js.get_name()
        print 'joystick name:', self.js.get_name(), my_guid

        self.buttons = {}
        self.axis = {}
        numhats = self.js.get_numhats()
        if numhats > 0:
            self.hats = 1
        else:
            self.hats = None

        path = os.path.abspath(__file__)
        path = os.path.dirname(path)
        path = os.path.join(path, 'gamecontrollerdb.txt')

        with open(path) as f:
            for l in f.readlines():
                l = l.strip()
                if l.startswith('#'):
                    continue
                # 341a3608000000000000504944564944,Afterglow PS3 Controller,a:b1,b:b2,back:b8,dpdown:h0.4,dpleft:h0.8,dpright:h0.2,dpup:h0.1,
                #    guide:b12,leftshoulder:b4,leftstick:b10,lefttrigger:b6,leftx:a0,lefty:a1,rightshoulder:b5,rightstick:b11,righttrigger:b7,rightx:a2,righty:a3,start:b9,x:b0,y:b3,platform:Windows,
                tokens = l.split(',')
                #print tokens
                guid = tokens[0]
                if guid != my_guid:
                    continue

                self.guid = guid
                self.name2 = tokens[1]

                for pair in tokens[2:]:
                    pair = pair.strip()
                    if not pair:
                        continue
                    key, val = pair.split(':')
                    if key == 'platform':
                        self.platform = val
                    else:
                        if val.startswith('a'):
                            self.axis[key] = int(val[1:])
                        elif val.startswith('b'):
                            self.buttons[key] = int(val[1:])
                        else:
                            print 'unrecognized pair: ', key, val
                break

        sdl2.SDL_Quit()

        self.dump_definition()
Esempio n. 16
0
 def run(self):
     event = sdl2.SDL_Event()
     while self.running:
         while sdl2.SDL_PollEvent(ctypes.byref(event)) != 0:
             self.onEvent(event)
         # sdl2.SDL_Delay(10)  # uncomment this if you want to save CPU resources
         self.onLoop()
     self.onCleanup()
     sdl2.SDL_Quit()
Esempio n. 17
0
 def runloop(self, world, loopFunction):
     try:
         while self.keepRunning:
             self.pump(world)
             loopFunction()
     finally:
         # TODO: make these go in a more appropriate place?
         sdl2.sdlmixer.Mix_Quit()
         sdl2.sdlttf.TTF_Quit()
         sdl2.SDL_Quit()
Esempio n. 18
0
    def quit(self):
        self.is_running = False
        # Give time for the other thread to end
        ti.sleep(0.05)

        # Destroy the SDL context
        sdl2.SDL_DestroyRenderer(self.renderer)
        sdl2.SDL_HideWindow(self.window)
        sdl2.SDL_DestroyWindow(self.window)
        sdl2.SDL_Quit()
Esempio n. 19
0
def main():
    sdl2.sdl2_load(ctypes.util.find_library('SDL2')) # '/usr/local/lib/libSDL2.dylib'

    sdl2.SDL_Init(sdl2.SDL_INIT_EVERYTHING)

    print(sdl2.SDL_HasClipboardText())
    print(sdl2.SDL_GetClipboardText())
    print(sdl2.SDL_SetClipboardText(b"Hello, world."))
    print(sdl2.SDL_HasClipboardText())
    print(sdl2.SDL_GetClipboardText())

    sdl2.SDL_Quit()
Esempio n. 20
0
def main():
    init()
    joy = sdl2.SDL_JoystickOpen(0)
    print('Name: {}'.format(sdl2.SDL_JoystickName(joy)))
    print('Axes: {}'.format(sdl2.SDL_JoystickNumAxes(joy)))

    state = ControllerState()
    evt = sdl2.SDL_Event()
    running = True
    conn = SerialConnection(
        sys.argv[1] if len(sys.argv) >= 2 else '/dev/ttyACM0')

    # set to mode 1 so it will not attack
    conn.call(MD49_MODE, (0x00, 0x34, 0x01))

    while running:
        while sdl2.SDL_PollEvent(ctypes.byref(evt)) != 0:
            if evt.type == sdl2.SDL_QUIT:
                running = False
                break
            elif evt.type == sdl2.SDL_JOYAXISMOTION:
                jaxis = evt.jaxis
                # print(state, jaxis.axis, jaxis.value)
                state.axis_state[jaxis.axis] = jaxis.value
                handle_axis_motion(conn, state, jaxis.axis, jaxis.value)
            elif evt.type == sdl2.SDL_JOYBUTTONUP:
                button = evt.jbutton
                if button.button == 0:
                    # A: toggle independent
                    state.ind = not state.ind
                    print('Independent: {}'.format(state.ind))
                elif button.button == 8:
                    # B: log encoders
                    print(conn.md49_get_encoders())
                    log_encoders(conn)
                elif button.button == 3:
                    # Y: reset encoders
                    conn.call(MD49_MODE, (
                        0x00,
                        0x35,
                    ))
                elif button.button == 4:
                    # left shoulder: reverse
                    state.r_rev = not state.r_rev
                    print('Right reverse: {}'.format(state.r_rev))
                elif button.button == 5:
                    # right shoulder: reverse
                    state.l_rev = not state.l_rev
                    print('Left reverse: {}'.format(state.l_rev))
                else:
                    print('Button', button.button)
        time.sleep(0.01)
    sdl2.SDL_Quit()
Esempio n. 21
0
 def run(self):
     
     while self.running:
         start = time.clock()
         self.refresh()
         end = time.clock()
         
         if (end-start) < 0.167:
             time.sleep(0.167 - (end-start))
     
     sdl2.SDL_Quit()
     return 0
Esempio n. 22
0
 def __del__(self):
     del self.joysticks_interface
     if self.has_sdl_gamecontroller:
         sdl2.SDL_QuitSubSystem(sdl2.SDL_INIT_GAMECONTROLLER)
     if self.has_sdl_joystick:
         sdl2.SDL_QuitSubSystem(sdl2.SDL_INIT_JOYSTICK)
     if self.has_sdl_audio:
         sdl2.SDL_CloseAudioDevice(self.audio_dev)
         sdl2.SDL_QuitSubSystem(sdl2.SDL_INIT_AUDIO)
     sdl2.SDL_DestroyTexture(self.texture)
     sdl2.SDL_DestroyRenderer(self.renderer)
     sdl2.SDL_DestroyWindow(self.screen)
     sdl2.SDL_Quit()
Esempio n. 23
0
 def __exit__(self, exc_type, exc_value, traceback):
     sdl2.SDL_DestroyTexture(self.texture_graph)
     sdl2.SDL_DestroyTexture(self.texture_text)
     sdl2.SDL_DestroyTexture(self.texture_scroll)
     sdl2.SDL_DestroyTexture(self.font_text)
     sdl2.SDL_DestroyTexture(self.font_text_inverted)
     sdl2.SDL_DestroyTexture(self.font_graph)
     sdl2.SDL_DestroyTexture(self.font_graph_inverted)
     # clean up stored picts
     for pict in list(self.picts.values()):
         sdl2.SDL_DestroyTexture(pict)
     sdl2.SDL_DestroyWindow(self.window)
     sdl2.SDL_DestroyRenderer(self.renderer)
     sdl2.SDL_Quit()
Esempio n. 24
0
    def main_loop(self):
        running = True

        def toggle_running(event):
            print('Quit event detected')
            nonlocal running
            running = not running

        #print(sdl2.SDL_GL_GetSwapInterval())

        self.event_manager.add_quit_callback(toggle_running)
        self.event_manager.add_keydown_callback(sdl2.SDLK_q, toggle_running)
        boa_gfx.gl_shader.shader_manager.shader_paths.append(
            './boa_gfx/shaders')
        boa_gfx.gl_shader.shader_manager.shader_paths.append('./shaders')
        boa_gfx.gl_texture.texture_manager.texture_paths.append('./textures')

        background = TexturedTriangleStrip(texture_name='background.png')
        background.position = (0.0, 0.0, -0.2)
        background.scale = (14.0, 13.0, 1.0)

        self.windows[0].camera.position = (-0.5, 0.0, 13.0)
        self.windows[0].fullscreen = True

        background = TexturedTriangleStrip(texture_name='background.png')
        background.position = (0.0, 0.0, 0.0)
        background.scale = (13.4, 13.0, 1.0)

        creatures = culture.creature_system()
        food = culture.food_system()
        food.position += (0.0, 0.0, -0.01)
        animations = culture.animation_system()
        animations.position += (0.0, 0.0, 0.01)

        while running:
            self.time_keeper.update()
            self.dynamo.run()
            self.event_manager.process_events()

            creatures.update_instance_data()
            food.update_instance_data()
            animations.update_instance_data()

            for w in self.windows:
                w.render()
            sdl2.SDL_Delay(1)

        for w in self.windows:
            w.close()
        sdl2.SDL_Quit()
Esempio n. 25
0
def main():
    sdl2.sdl2_load(
        ctypes.util.find_library('SDL2'))  # '/usr/local/lib/libSDL2.dylib'

    sdl2.SDL_Init(sdl2.SDL_INIT_EVERYTHING)
    # sdl2.SDL_SetMainReady()

    #rwops_ptr = sdl2.SDL_AllocRW()
    rwops_ptr = sdl2.SDL_RWFromFile(b'test_timer.py', b'rb')
    rwops = ctypes.cast(rwops_ptr, ctypes.POINTER(sdl2.SDL_RWops)).contents
    size_func = ctypes.CFUNCTYPE(ctypes.c_int64, ctypes.c_void_p)(rwops.size)
    print(sdl2.SDL_ReadU8(rwops_ptr))
    print(size_func(rwops_ptr))
    sdl2.SDL_FreeRW(rwops_ptr)

    sdl2.SDL_Quit()
Esempio n. 26
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
Esempio n. 27
0
 def close(self):
     """ Close the SDL2 interface. """
     video.VideoPlugin.close(self)
     if sdl2 and numpy:
         # free windows
         sdl2.SDL_DestroyWindow(self.display)
         # free surfaces
         for s in self.canvas:
             sdl2.SDL_FreeSurface(s)
         sdl2.SDL_FreeSurface(self.work_surface)
         sdl2.SDL_FreeSurface(self.overlay)
         # free palettes
         for p in self.show_palette:
             sdl2.SDL_FreePalette(p)
         sdl2.SDL_FreePalette(self.composite_palette)
         # close SDL2
         sdl2.SDL_Quit()
Esempio n. 28
0
def main():
    global rend

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

    x, y = 0, 0

    # window = sdl2.ext.Window("ekkek", 600,600, sdl2.SDL_WINDOW_OPENGL)
    window = sdl2.SDL_CreateWindow(TITLE, sdl2.SDL_WINDOWPOS_UNDEFINED,
                                   sdl2.SDL_WINDOWPOS_UNDEFINED, 600, 600,
                                   sdl2.SDL_WINDOW_OPENGL)
    context = sdl2.SDL_GL_CreateContext(window)
    rend = Renderer()
    time = sdl2.SDL_GetTicks()
    prev_time = sdl2.SDL_GetTicks()
    frame_time = 0
    e = ioproc(sdl2.SDL_Event())
    dt = 1000. / 60.

    #while sdl2.SDL_WaitEvent(ctypes.byref(sdl2.SDL_QUIT)):
    while e.checkEvents():
        # time = sdl2.SDL_GetTicks()
        # frame_time = time - prev_time
        # prev_time = time
        # while sdl2.SDL_PollEvent(ctypes.byref(e)) !=0:
        #     if(e.type == sdl2.SDL_QUIT):
        #         running = False

        time += dt
        frame_time = time - sdl2.SDL_GetTicks()
        if (frame_time <= 0):
            frame_time = 1
        tms.sleep(frame_time / 1000.)

        # update shit here
        # ...
        rend.doShit()
        rend.draw()
        sdl2.SDL_GL_SwapWindow(window)

    # rend.unload()     #Unload assimp imports
    sdl2.SDL_GL_DeleteContext(context)
    sdl2.SDL_Quit()
Esempio n. 29
0
def setup(title="SDL window", width=640, height=480):
    ''' creates and SDL window and context '''

    if sdl2.SDL_Init(sdl2.SDL_INIT_EVERYTHING):
        print('\x1b[0;37;41m' + sdl2.SDL_GetError() + '\x1b[0m')
        sdl2.SDL_Quit()

    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)

    window = sdl2.SDL_CreateWindow(title, sdl2.SDL_WINDOWPOS_UNDEFINED,
                                   sdl2.SDL_WINDOWPOS_UNDEFINED, width, height,
                                   sdl2.SDL_WINDOW_OPENGL)

    context = sdl2.SDL_GL_CreateContext(window)
    return window, context
Esempio n. 30
0
 def __exit__(self, type, value, traceback):
     """Close the SDL2 interface."""
     base.VideoPlugin.__exit__(self, type, value, traceback)
     if sdl2 and numpy and self._has_window:
         # free windows
         sdl2.SDL_DestroyWindow(self.display)
         # free surfaces
         for s in self.canvas:
             sdl2.SDL_FreeSurface(s)
         sdl2.SDL_FreeSurface(self.work_surface)
         sdl2.SDL_FreeSurface(self.overlay)
         # free palettes
         for p in self.show_palette:
             sdl2.SDL_FreePalette(p)
         sdl2.SDL_FreePalette(self.composite_palette)
         # close IME
         sdl2.SDL_StopTextInput()
         # close SDL2
         sdl2.SDL_Quit()