コード例 #1
0
ファイル: glfw_app.py プロジェクト: DarthThomas/poolvr.py
def setup_glfw(title="poolvr.py 0.0.1",
               window_size=(800,600),
               double_buffered=False,
               multisample=4,
               fullscreen=False):
    if not glfw.Init():
        raise Exception('failed to initialize glfw')
    if not double_buffered:
        glfw.WindowHint(glfw.DOUBLEBUFFER, False)
        glfw.SwapInterval(0)
    if multisample:
        glfw.WindowHint(glfw.SAMPLES, multisample)
    width, height = window_size
    if fullscreen:
        window = glfw.CreateWindow(width, height, title, glfw.GetPrimaryMonitor())
    else:
        window = glfw.CreateWindow(width, height, title)
    if not window:
        glfw.Terminate()
        raise Exception('failed to create glfw window')
    glfw.MakeContextCurrent(window)
    _logger.info('GL_VERSION: %s', gl.glGetString(gl.GL_VERSION))
    renderer = OpenGLRenderer(window_size=(width, height), znear=0.1, zfar=1000)
    def on_resize(renderer, window, width, height):
        gl.glViewport(0, 0, width, height)
        renderer.window_size[:] = (width, height)
        renderer.update_projection_matrix()
    from functools import partial
    on_resize = partial(on_resize, renderer)
    glfw.SetWindowSizeCallback(window, on_resize)
    renderer.init_gl()
    on_resize(window, window_size[0], window_size[1])
    return window, renderer
コード例 #2
0
def setup_glfw(width=800,
               height=600,
               double_buffered=False,
               title="poolvr.py 0.0.1",
               multisample=0):
    if not glfw.Init():
        raise Exception('failed to initialize glfw')
    if not double_buffered:
        glfw.WindowHint(glfw.DOUBLEBUFFER, False)
        glfw.SwapInterval(0)
    if multisample:
        glfw.WindowHint(glfw.SAMPLES, multisample)
    window = glfw.CreateWindow(width, height, title)
    if not window:
        glfw.Terminate()
        raise Exception('failed to create glfw window')
    glfw.MakeContextCurrent(window)
    _logger.info('GL_VERSION: %s', gl.glGetString(gl.GL_VERSION))
    renderer = OpenGLRenderer(window_size=(width, height),
                              znear=0.1,
                              zfar=1000)

    def on_resize(window, width, height):
        gl.glViewport(0, 0, width, height)
        renderer.window_size = (width, height)
        renderer.update_projection_matrix()

    glfw.SetWindowSizeCallback(window, on_resize)
    return window, renderer
コード例 #3
0
ファイル: tests.py プロジェクト: timweckx/cyglfw3
    def test_window_framebuffer_resize_callback(self):
        w_called = [False]

        def w_callback(window, width, height):
            w_called[0] = True

        f_called = [False]

        def f_callback(window, width, height):
            f_called[0] = True

        glfw.SetWindowSizeCallback(self.window, w_callback)
        glfw.SetFramebufferSizeCallback(self.window, f_callback)
        glfw.SetWindowSize(self.window, 800, 600)
        glfw.PollEvents()
        glfw.SetWindowSizeCallback(self.window, None)
        glfw.SetFramebufferSizeCallback(self.window, None)
        self.assertTrue(w_called[0])
        self.assertTrue(f_called[0])
コード例 #4
0
    def _view(self, meshes=None, window_size=(800,600)):
        if meshes is None:
            meshes = []
        title = traceback.extract_stack(None, 2)[0][2]
        window, renderer = setup_glfw(width=window_size[0], height=window_size[1], double_buffered=True,
                                      title=title)
        camera_world_matrix = renderer.camera_matrix
        camera_position = camera_world_matrix[3,:3]
        gl.glViewport(0, 0, window_size[0], window_size[1])
        gl.glClearColor(*BG_COLOR)
        gl.glEnable(gl.GL_DEPTH_TEST)
        for mesh in meshes:
            mesh.init_gl(force=True)
        def on_resize(window, width, height):
            gl.glViewport(0, 0, width, height)
            renderer.window_size = (width, height)
            renderer.update_projection_matrix()
        glfw.SetWindowSizeCallback(window, on_resize)
        process_keyboard_input = init_keyboard(window)

        _logger.info('entering render loop...')
        stdout.flush()

        nframes = 0
        max_frame_time = 0.0
        lt = glfw.GetTime()
        while not glfw.WindowShouldClose(window):
            t = glfw.GetTime()
            dt = t - lt
            lt = t
            glfw.PollEvents()
            renderer.process_input()
            process_keyboard_input(dt, camera_world_matrix)
            with renderer.render(meshes=meshes):
                pass
            max_frame_time = max(max_frame_time, dt)
            if nframes == 0:
                st = glfw.GetTime()
            nframes += 1
            glfw.SwapBuffers(window)

        _logger.info('...exited render loop: average FPS: %f, maximum frame time: %f',
                     (nframes - 1) / (t - st), max_frame_time)

        renderer.shutdown()
        _logger.info('...shut down renderer')
        glfw.DestroyWindow(window)
        glfw.Terminate()
コード例 #5
0
def main():
    appName = 'First App'

    glfw.Init()
    glfw.WindowHint(glfw.CONTEXT_VERSION_MAJOR, 3)
    glfw.WindowHint(glfw.CONTEXT_VERSION_MINOR, 3)
    # glfw.WindowHint(glfw.OPENGL_FORWARD_COMPAT, GL_TRUE)
    # glfw.WindowHint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE)

    window = glfw.CreateWindow(800, 800, appName)
    glfw.SetWindowSizeCallback(window, window_size_callback)
    glfw.SetKeyCallback(window, key_callback)
    glfw.MakeContextCurrent(window)
    glfw.SwapInterval(1)

    try:
        initOpenGL()
    except Exception as e:
        print(e)
        exit(1)

    prevTime = time()
    frameCount = 0
    frameTimeSum = 0
    lastUpdateTime = prevTime
    while not glfw.WindowShouldClose(window):
        glfw.PollEvents()
        display(window)
        glfw.SwapBuffers(window)
        curTime = time()
        frameTime = (curTime - prevTime)
        # if frameTime != 0: print(1 / frameTime)
        sleep(0.016)

        if curTime - lastUpdateTime > 1:
            glfw.SetWindowTitle(
                window, '%s, FPS: %s' %
                (appName, str(round(frameCount / frameTimeSum))))
            frameCount = 0
            frameTimeSum = 0
            lastUpdateTime = curTime

        frameTimeSum += frameTime
        frameCount += 1
        prevTime = curTime

    glfw.DestroyWindow(window)
    glfw.Terminate()
コード例 #6
0
ファイル: frame3d.py プロジェクト: nesquik011/Triangulum3D
    def init(self):
        assert not self._initialized
        glfw.SetMouseButtonCallback(self._window, self._on_mouse_button)
        self._double_clicks.set_double_click_callback(
            self._on_mouse_double_click)
        glfw.SetScrollCallback(self._window, self._on_scroll)
        glfw.SetCursorPosCallback(self._window, self._on_mouse_move)
        glfw.SetKeyCallback(self._window, self._on_keyboard)
        glfw.SetDropCallback(self._window, self._on_drop)

        glfw.SetWindowSizeCallback(self._window, self._on_resize)
        glfw.SetWindowCloseCallback(self._window,
                                    lambda window: self._fps_limiter.stop())

        yield from self._gl_executor.init_gl_context()
        yield from self._renderer.init()
        self._initialized = True
コード例 #7
0
ファイル: text_renderer.py プロジェクト: jzitelli/gltfview.py
    glfw.MakeContextCurrent(window)
    gl.glClearColor(0.1, 0.1, 0.2, 0.0)
    text_drawer.init_gl()

    def on_keydown(window, key, scancode, action, mods):
        if key == glfw.KEY_ESCAPE and action == glfw.PRESS:
            glfw.SetWindowShouldClose(window, gl.GL_TRUE)

    glfw.SetKeyCallback(window, on_keydown)

    def on_resize(window, width, height):
        gl.glViewport(0, 0, width, height)
        gl.glClear(gl.GL_COLOR_BUFFER_BIT | gl.GL_DEPTH_BUFFER_BIT)
        text_drawer.set_screen_size((width, height))

    glfw.SetWindowSizeCallback(window, on_resize)
    on_resize(window, w, h)
    _logger.debug('starting render loop...')
    nframes = 0
    dt = float('inf')
    avg_fps = 0.0
    t = lt = st = glfw.GetTime()
    while not glfw.WindowShouldClose(window):
        glfw.PollEvents()
        gl.glClear(gl.GL_COLOR_BUFFER_BIT | gl.GL_DEPTH_BUFFER_BIT)
        text_drawer.draw_text('TESTING123', screen_position=(0.5, 0.5))
        text_drawer.draw_text('fps: %f' % (1.0 / dt),
                              screen_position=(abs(np.sin(0.01 * (t - st))),
                                               abs(np.sin(0.1 * (t - st)))))
        text_drawer.draw_text('avg fps: %f' % avg_fps,
                              screen_position=(abs(np.sin(0.07 * (t - st))),
コード例 #8
0
def view_gltf(gltf, uri_path, scene_name=None,
              openvr=False,
              window_size=None,
              clear_color=(0.01, 0.01, 0.013, 0.0),
              multisample=None,
              nframes=None,
              screenshot=None,
              camera_position=None, camera_rotation=None,
              zfar=1000.0, znear=0.01, yfov=0.660593,
              window_title='gltfview',
              screen_capture_prefix=None,
              display_fps=False,
              move_speed=None):
    _t0 = time.time()
    if window_size is None:
        window_size = [800, 600]
    else:
        window_size = list(window_size)
    window = setup_glfw(width=window_size[0], height=window_size[1],
                        double_buffered=not openvr, multisample=multisample,
                        window_title=window_title)

    gl.glClearColor(*clear_color)

    camera = {'type': 'perspective',
              'perspective': {"aspectRatio": window_size[0]/window_size[1],
                              "yfov": yfov, "zfar": zfar, "znear": znear}}
    projection_matrix = np.zeros((4,4), dtype=np.float32)

    def on_resize(window, width, height):
        window_size[:] = width, height
        gl.glViewport(0, 0, window_size[0], window_size[1])
        gltfu.calc_projection_matrix(camera, out=projection_matrix,
                                     aspectRatio=window_size[0] / max(5, window_size[1]))
    glfw.SetWindowSizeCallback(window, on_resize)

    scene = gltfu.init_scene(gltf, uri_path, scene_name=scene_name)
    scene_bounds = gltfu.find_scene_bounds(scene, gltf)
    _logger.debug('scene bounds:\n%s', '\n'.join(['%20s: min = %s , max = %s' % (semantic, bounds[0], bounds[1])
                                                  for semantic, bounds in scene_bounds.items()]))

    root_nodes = [gltf['nodes'][n] for n in scene.get('nodes', [])]
    nodes = gltfu.flatten_nodes(root_nodes, gltf)

    camera_node = next((node for node in nodes if 'camera' in node), None)
    if camera_node is not None:
        camera = gltf['cameras'][camera_node['camera']]
        _logger.info('found camera: %s', camera)
        camera_world_matrix = camera_node['world_matrix']
    else:
        _logger.info('no camera specified, using default')
        camera_world_matrix = np.eye(4, dtype=np.float32)

    if camera_position is not None:
        _logger.info('setting camera position to %s', camera_position)
        camera_world_matrix[3, :3] = camera_position
    camera_position = camera_world_matrix[3, :3]

    if camera_node is None and 'POSITION' in scene_bounds:
        bounds = scene_bounds['POSITION']
        centroid = 0.5 * (bounds[0] + bounds[1])
        r_max = max(np.linalg.norm(bounds[0] - centroid), np.linalg.norm(bounds[1] - centroid))
        camera_position[:] = centroid
        camera_position[2] += r_max / np.tan(0.5*camera['perspective']['yfov'])
        _logger.debug('camera_position = %s', camera_position)

    if camera_rotation is not None:
        if camera_rotation[1]:
            s, c = np.sin(camera_rotation[1]), np.cos(camera_rotation[1])
            r = np.array([[c, -s],
                          [s,  c]], dtype=np.float32)
            camera_world_matrix[:3:2,:3:2] = camera_world_matrix[:3:2,:3:2].dot(r.T)

    # sort nodes from front to back to avoid overdraw (assuming opaque objects):
    nodes = sorted(nodes, key=lambda node: np.linalg.norm(camera_world_matrix[3, :3] - node['world_matrix'][3, :3]))

    on_resize(window, window_size[0], window_size[1])

    if 'POSITION' in scene_bounds:
        bounds = scene_bounds['POSITION']
        scene_centroid = 0.5 * (bounds[0] + bounds[1])
        move_speed = 0.125 * max(np.linalg.norm(bounds[0] - scene_centroid),
                                 np.linalg.norm(bounds[1] - scene_centroid))

    process_input = setup_controls(camera_world_matrix=camera_world_matrix, window=window,
                                   screen_capture_prefix=screen_capture_prefix, move_speed=move_speed)

    text_renderer = None
    if display_fps:
        text_renderer = TextRenderer()
        text_renderer.init_gl()

    _t1 = time.time()
    _logger.info('''...INITIALIZATION COMPLETE (took %s seconds)''', _t1 - _t0);

    # BURNER FRAME:
    gltfu.num_draw_calls = 0
    process_input(0.0)
    lt = glfw.GetTime()
    render(gltf, nodes, window_size,
           camera_world_matrix=camera_world_matrix,
           projection_matrix=projection_matrix)
    num_draw_calls_per_frame = gltfu.num_draw_calls
    _logger.info("NUM DRAW CALLS PER FRAME: %d", num_draw_calls_per_frame)
    _draw_text(fps=1/(glfw.GetTime()-lt), display_fps=display_fps, text_renderer=text_renderer)
    if screenshot:
        save_screen(window, screenshot)

    _logger.info('''STARTING RENDER LOOP...''')
    if nframes:
        _logger.info(""" * * * WILL RENDER %s FRAMES * * * """, nframes)
    stdout.flush()

    import gc; gc.collect() # does it do anything?

    if openvr and OpenVRRenderer is not None:
        vr_renderer = OpenVRRenderer(multisample=multisample, poll_tracked_device_frequency=90)
        setup_vr_controls()
        render_stats = vr_render_loop(vr_renderer=vr_renderer, process_input=process_input,
                                      window=window, window_size=window_size,
                                      gltf=gltf, nodes=nodes)
        vr_renderer.shutdown()
    else:
        render_stats = render_loop(process_input=process_input,
                                   window=window, window_size=window_size,
                                   gltf=gltf, nodes=nodes,
                                   camera_world_matrix=camera_world_matrix,
                                   projection_matrix=projection_matrix,
                                   nframes=nframes,
                                   display_fps=display_fps, text_renderer=text_renderer)
    _logger.info('''QUITING...

%s
''', '\n'.join('  %21s: %s' % (k, v) for k, v in render_stats.items()))
    glfw.DestroyWindow(window)
    glfw.Terminate()
コード例 #9
0
def view_gltf(gltf, uri_path, scene_name=None, openvr=False, window_size=None):
    if scene_name is None:
        scene_name = gltf['scene']
    if window_size is None:
        window_size = [800, 600]
    window = setup_glfw(width=window_size[0], height=window_size[1],
                        double_buffered=not openvr)
    def on_resize(window, width, height):
        window_size[0], window_size[1] = width, height
    glfw.SetWindowSizeCallback(window, on_resize)
    if openvr and OpenVRRenderer is not None:
        vr_renderer = OpenVRRenderer()
    # text_drawer = TextDrawer()

    gl.glClearColor(0.01, 0.01, 0.17, 1.0);

    shader_ids = gltfu.setup_shaders(gltf, uri_path)
    gltfu.setup_programs(gltf, shader_ids)
    gltfu.setup_textures(gltf, uri_path)
    gltfu.setup_buffers(gltf, uri_path)

    scene = gltf.scenes[scene_name]
    nodes = [gltf.nodes[n] for n in scene.nodes]
    for node in nodes:
        gltfu.update_world_matrices(node, gltf)

    camera_world_matrix = np.eye(4, dtype=np.float32)
    projection_matrix = np.array(matrix44.create_perspective_projection_matrix(np.rad2deg(55), window_size[0]/window_size[1], 0.1, 1000),
                                 dtype=np.float32)

    for node in nodes:
        if 'camera' in node:
            camera = gltf['cameras'][node['camera']]
            if 'perspective' in camera:
                perspective = camera['perspective']
                projection_matrix = np.array(matrix44.create_perspective_projection_matrix(np.rad2deg(perspective['yfov']), perspective['aspectRatio'],
                                                                                           perspective['znear'], perspective['zfar']),
                                             dtype=np.float32)
            elif 'orthographic' in camera:
                raise Exception('TODO')
            camera_world_matrix = node['world_matrix']
            break
    camera_position = camera_world_matrix[3, :3]
    camera_rotation = camera_world_matrix[:3, :3]
    dposition = np.zeros(3, dtype=np.float32)
    rotation = np.eye(3, dtype=np.float32)

    key_state = defaultdict(bool)

    def on_keydown(window, key, scancode, action, mods):
        if key == glfw.KEY_ESCAPE and action == glfw.PRESS:
            glfw.SetWindowShouldClose(window, gl.GL_TRUE)
        elif action == glfw.PRESS:
            key_state[key] = True
        elif action == glfw.RELEASE:
            key_state[key] = False

    glfw.SetKeyCallback(window, on_keydown)

    def on_mousedown(window, button, action, mods):
        pass
    glfw.SetMouseButtonCallback(window, on_mousedown)

    move_speed = 2.0
    turn_speed = 0.5

    def process_input(dt):
        glfw.PollEvents()
        dposition[:] = 0.0
        if key_state[glfw.KEY_W]:
            dposition[2] -= dt * move_speed
        if key_state[glfw.KEY_S]:
            dposition[2] += dt * move_speed
        if key_state[glfw.KEY_A]:
            dposition[0] -= dt * move_speed
        if key_state[glfw.KEY_D]:
            dposition[0] += dt * move_speed
        if key_state[glfw.KEY_Q]:
            dposition[1] += dt * move_speed
        if key_state[glfw.KEY_Z]:
            dposition[1] -= dt * move_speed
        theta = 0.0
        if key_state[glfw.KEY_LEFT]:
            theta -= dt * turn_speed
        if key_state[glfw.KEY_RIGHT]:
            theta += dt * turn_speed
        rotation[0,0] = np.cos(theta)
        rotation[2,2] = rotation[0,0]
        rotation[0,2] = np.sin(theta)
        rotation[2,0] = -rotation[0,2]
        camera_rotation[...] = rotation.dot(camera_world_matrix[:3,:3])
        camera_position[:] += camera_rotation.T.dot(dposition)

    # sort nodes from front to back to avoid overdraw (assuming opaque objects):
    nodes = sorted(nodes, key=lambda node: np.linalg.norm(camera_position - node['world_matrix'][3, :3]))

    _logger.info('starting render loop...')
    sys.stdout.flush()
    gltfu.num_draw_calls = 0
    nframes = 0
    lt = glfw.GetTime()
    dt_max = 0.0
    while not glfw.WindowShouldClose(window):
        t = glfw.GetTime()
        dt = t - lt
        dt_max = max(dt, dt_max)
        lt = t
        process_input(dt)
        if openvr:
            vr_renderer.process_input()
            vr_renderer.render(gltf, nodes, window_size)
        else:
            gl.glViewport(0, 0, window_size[0], window_size[1])
            gl.glClear(gl.GL_COLOR_BUFFER_BIT | gl.GL_DEPTH_BUFFER_BIT)
            view_matrix = np.linalg.inv(camera_world_matrix)
            gltfu.set_material_state.current_material = None
            gltfu.set_technique_state.current_technique = None
            for node in nodes:
                gltfu.draw_node(node, gltf,
                                projection_matrix=projection_matrix,
                                view_matrix=view_matrix)
            # text_drawer.draw_text("%f" % dt, color=(1.0, 1.0, 0.0, 0.0),
            #                       view_matrix=view_matrix,
            #                       projection_matrix=projection_matrix)
        if nframes == 0:
            _logger.info("num draw calls per frame: %d", gltfu.num_draw_calls)
            sys.stdout.flush()
            gltfu.num_draw_calls = 0
            st = glfw.GetTime()
        nframes += 1
        glfw.SwapBuffers(window)
    _logger.info('FPS (avg): %f', ((nframes - 1) / (t - st)))
    _logger.info('MAX FRAME RENDER TIME: %f', dt_max)
    sys.stdout.flush()

    if openvr:
        vr_renderer.shutdown()
    glfw.DestroyWindow(window)
    glfw.Terminate()
コード例 #10
0
def show(game,
         title='poolvr.py   ***   GLViewer',
         window_size=(800, 600),
         gl_clear_color=(0.24, 0.18, 0.08, 0.0),
         before_frame_cb=None,
         after_frame_cb=None,
         double_buffered=True,
         playback_rate=1.0,
         screenshots_dir='',
         use_billboards=False):
    if not glfw.Init():
        raise Exception('failed to initialize glfw')
    if not double_buffered:
        glfw.WindowHint(glfw.DOUBLEBUFFER, False)
        glfw.SwapInterval(0)
    window = glfw.CreateWindow(window_size[0], window_size[1], title)
    if not window:
        raise Exception('failed to create glfw window')
    glfw.MakeContextCurrent(window)
    _logger.info('GL_VERSION: %s', gl.glGetString(gl.GL_VERSION))
    renderer = OpenGLRenderer(window_size=window_size, znear=0.1, zfar=1000)

    def on_resize(window, width, height):
        gl.glViewport(0, 0, width, height)
        renderer.window_size = (width, height)
        renderer.update_projection_matrix()

    glfw.SetWindowSizeCallback(window, on_resize)

    table = game.table
    physics = game.physics
    ball_meshes = table.setup_balls(game.ball_radius,
                                    game.ball_colors[:9],
                                    game.ball_positions,
                                    striped_balls=set(range(9,
                                                            game.num_balls)),
                                    use_bb_particles=use_billboards)
    ball_shadow_meshes = [mesh.shadow_mesh for mesh in ball_meshes]
    camera_world_matrix = renderer.camera_matrix
    camera_position = camera_world_matrix[3, :3]
    camera_position[1] = table.height + 0.19
    camera_position[2] = 0.183 * table.length
    cue = PoolCue()
    cue.position[1] = table.height + 0.1

    process_keyboard_input = init_keyboard(window)

    meshes = [table.mesh, floor_mesh, skybox_mesh] + ball_meshes  #+ [cue]
    for mesh in meshes:
        mesh.init_gl(force=True)

    ball_positions = game.ball_positions
    ball_quaternions = game.ball_quaternions
    ball_mesh_positions = [mesh.world_matrix[3, :3] for mesh in ball_meshes]
    ball_mesh_rotations = [mesh.world_matrix[:3, :3].T for mesh in ball_meshes]
    ball_shadow_mesh_positions = [
        mesh.world_matrix[3, :3] for mesh in ball_shadow_meshes
    ]
    gl.glViewport(0, 0, window_size[0], window_size[1])
    gl.glClearColor(*gl_clear_color)
    gl.glEnable(gl.GL_DEPTH_TEST)

    _logger.info('entering render loop...')
    stdout.flush()

    nframes = 0
    max_frame_time = 0.0
    lt = glfw.GetTime()
    t0 = physics.events[0].t
    t1 = physics.events[-1].t + min(2.0, physics.events[-1].T)
    pt = t0

    while not glfw.WindowShouldClose(window) and pt <= t1:

        t = glfw.GetTime()
        dt = t - lt
        lt = t
        glfw.PollEvents()
        process_keyboard_input(dt, camera_world_matrix, cue=cue)
        renderer.process_input()

        with renderer.render(meshes=meshes) as frame_data:
            camera_position = frame_data.get('camera_position',
                                             renderer.camera_position)
            physics.eval_positions(pt, out=ball_positions)
            physics.eval_quaternions(pt, out=ball_quaternions)
            ball_positions[
                ~physics.
                on_table] = camera_position  # hacky way to only show balls that are on table
            for i, pos in enumerate(ball_positions):
                ball_mesh_positions[i][:] = pos
                ball_shadow_mesh_positions[i][0::2] = pos[0::2]
            for i, quat in enumerate(ball_quaternions):
                set_matrix_from_quaternion(quat, ball_mesh_rotations[i])

        physics.step(dt)

        max_frame_time = max(max_frame_time, dt)
        if nframes == 0:
            st = glfw.GetTime()
        nframes += 1
        pt += dt * playback_rate
        glfw.SwapBuffers(window)

    _logger.info(
        '...exited render loop: average FPS: %f, maximum frame time: %f',
        (nframes - 1) / (t - st), max_frame_time)

    mWidth, mHeight = glfw.GetWindowSize(window)
    gl.glPixelStorei(gl.GL_PACK_ALIGNMENT, 1)
    pixels = gl.glReadPixels(0, 0, mWidth, mHeight, gl.GL_RGB,
                             gl.GL_UNSIGNED_BYTE)
    pil_image = PIL.Image.frombytes('RGB', (mWidth, mHeight), pixels)
    pil_image = pil_image.transpose(PIL.Image.FLIP_TOP_BOTTOM)
    filename = title.replace(' ', '_') + '-screenshot.png'
    filepath = os.path.join(screenshots_dir, filename)
    pil_image.save(filepath)
    _logger.info('..saved screen capture to "%s"', filepath)

    try:
        renderer.shutdown()
        _logger.info('...shut down renderer')
    except Exception as err:
        _logger.error(err)

    glfw.DestroyWindow(window)
    glfw.Terminate()
コード例 #11
0
ファイル: cbwindow.py プロジェクト: wuyuzaizai/car-detection
    def __init__(self, width, height, title):
        glfw.WindowHint(glfw.CONTEXT_VERSION_MAJOR, 4)
        glfw.WindowHint(glfw.CONTEXT_VERSION_MINOR, 1)
        glfw.WindowHint(glfw.OPENGL_FORWARD_COMPAT, 1)
        glfw.WindowHint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE)
        glfw.WindowHint(glfw.RESIZABLE, True)
        glfw.WindowHint(glfw.RED_BITS, 8)
        glfw.WindowHint(glfw.GREEN_BITS, 8)
        glfw.WindowHint(glfw.BLUE_BITS, 8)
        # glfw.WindowHint(glfw.ALPHA_BITS, 8)
        glfw.WindowHint(glfw.DEPTH_BITS, 24)
        glfw.WindowHint(glfw.STENCIL_BITS, 8)

        self.window = glfw.CreateWindow(width, height, title)
        self.framebufferSize = (width, height)

        f = 240
        pos = np.array([3, 3, 3])
        dir = np.array([-1, -1, -1])
        up = np.array([0, 0, 1])
        near = 0.2
        far = 100
        self.playerCamera = PlayerCamera(f, self.framebufferSize, pos, dir, up, near, far)
        self.currentCamera = self.playerCamera
        self.cameraLocked = True
        self.mainRender = None
        self.cairoSavePath = None

        def key_callback(window, key, scancode, action, mods):
            if (key == glfw.KEY_ESCAPE and action == glfw.PRESS):
                glfw.SetWindowShouldClose(window, True)

            if (action == glfw.PRESS and key == glfw.KEY_L):
                self.cameraLocked = not self.cameraLocked
                print 'cameraLocked:', self.cameraLocked

                glfw.SetInputMode(window, glfw.CURSOR, glfw.CURSOR_NORMAL if self.cameraLocked else glfw.CURSOR_DISABLED)

                # if not self.cameraLocked:
                # Ensure that locking/unlocking doesn't move the view:
                windowWidth, windowHeight = glfw.GetWindowSize(window)
                glfw.SetCursorPos(window, windowWidth / 2, windowHeight / 2)
                self.currentCamera.lastCursor = np.array(glfw.GetCursorPos(window), np.float32)
                self.currentCamera.lastUpdateTime = glfw.GetTime()

            if (action == glfw.PRESS and key == glfw.KEY_R):
                self.mainRender.renderCairo(self.playerCamera, self.cairoSavePath)

            pass
            # # print(
                # "keybrd: key=%s scancode=%s action=%s mods=%s" %
                # (key, scancode, action, mods))

        def char_callback(window, char):
            pass
            # print("unichr: char=%s" % char)

        def scroll_callback(window, off_x, off_y):
            pass
            # print("scroll: x=%s y=%s" % (off_x, off_y))

        def mouse_button_callback(window, button, action, mods):
            pass
            # print("button: button=%s action=%s mods=%s" % (button, action, mods))

        def cursor_enter_callback(window, status):
            pass
            # print("cursor: status=%s" % status)

        def cursor_pos_callback(window, pos_x, pos_y):
            pass
            # print("curpos: x=%s y=%s" % (pos_x, pos_y))

        def window_size_callback(window, wsz_w, wsz_h):
            pass
            # print("window: w=%s h=%s" % (wsz_w, wsz_h))

        def window_pos_callback(window, pos_x, pos_y):
            pass
            # print("window: x=%s y=%s" % (pos_x, pos_y))

        def window_close_callback(window):
            pass
            # print("should: %s" % self.should_close)

        def window_refresh_callback(window):
            pass
            # print("redraw")

        def window_focus_callback(window, status):
            pass
            # print("active: status=%s" % status)

        def window_iconify_callback(window, status):
            pass
            # print("hidden: status=%s" % status)

        def framebuffer_size_callback(window, fbs_x, fbs_y):
            print("buffer: x=%s y=%s" % (fbs_x, fbs_y))
            self.framebufferSize = (fbs_x, fbs_y)
            self.playerCamera.framebufferSize = (fbs_x, fbs_y)
            glViewport(0, 0, self.currentCamera.framebufferSize[0], self.currentCamera.framebufferSize[1])
            pass

        glfw.SetKeyCallback(self.window, key_callback)
        glfw.SetCharCallback(self.window, char_callback)
        glfw.SetScrollCallback(self.window, scroll_callback)
        glfw.SetMouseButtonCallback(self.window, mouse_button_callback)
        glfw.SetCursorEnterCallback(self.window, cursor_enter_callback)
        glfw.SetCursorPosCallback(self.window, cursor_pos_callback)
        glfw.SetWindowSizeCallback(self.window, window_size_callback)
        glfw.SetWindowPosCallback(self.window, window_pos_callback)
        glfw.SetWindowCloseCallback(self.window, window_close_callback)
        glfw.SetWindowRefreshCallback(self.window, window_refresh_callback)
        glfw.SetWindowFocusCallback(self.window, window_focus_callback)
        glfw.SetWindowIconifyCallback(self.window, window_iconify_callback)
        glfw.SetFramebufferSizeCallback(self.window, framebuffer_size_callback)