Example #1
0
def main():
    global gFlag, gCnt
    
    if not glfw.init():
        return

    window = glfw.create_window(1000, 1000, '2018008177', None, None)
    if not window:
        glfw.terminate()
        return

    glfw.make_context_current(window)

    glfw.set_mouse_button_callback(window, mouse_button_callback)
    glfw.set_key_callback(window, key_callback)
    glfw.set_scroll_callback(window, scroll_callback)
    glfw.set_cursor_pos_callback(window, cursor_position_callback)
    glfw.set_drop_callback(window, drop_callback)
    glfw.swap_interval(1)
    
    while not glfw.window_should_close(window):
        glfw.poll_events()
        render(gCnt)
        glfw.swap_buffers(window)
        if gFlag == 1:
            gCnt += 1
    glfw.terminate()
Example #2
0
def main():
    global gVertexArraySeparate
    global a, b, c
    if not glfw.init():
        return
    window = glfw.create_window(800, 800, "2017030482_ClassAssignment3", None,
                                None)
    if not window:
        glfw.ternminate()
        return

    glfw.make_context_current(window)
    glfw.set_mouse_button_callback(window, mouse_button_callback)
    glfw.set_scroll_callback(window, scroll_callback)
    glfw.set_drop_callback(window, drop_callback)
    glfw.set_key_callback(window, key_callback)
    glfw.make_context_current(window)

    glfw.swap_interval(1)

    while not glfw.window_should_close(window):
        glfw.poll_events()
        glfw.swap_buffers(window)
        render()

    glfw.terminate()
Example #3
0
    def __init__(self, window):
        super(Client, self).__init__()

        self.window = window
        self.width, self.height = glfw.get_window_size(window)

        self.gl = mg.create_context()
        self.compile()

        self.camerapos = vec4(0.0, 0.0, 20.0, 1.0)

        def on_modified(e):
            # restart python if python code is changed
            if e.src_path.endswith(".py"):
                glfw.set_window_should_close(window, glfw.TRUE)
                os.system(f"python {e.src_path}")

            # compile shaders if the change is not python code
            else:
                self.should_compile = True

        handler = FileSystemEventHandler()
        handler.on_modified = on_modified
        observer = Observer()
        observer.schedule(handler, "./.", True)
        observer.start()

        self.is_drag_rot_cam = False
        self.prempos = vec2(0.0, 0.0)

        # wire glfw events
        glfw.set_mouse_button_callback(window, self.on_mouse_button)
        glfw.set_cursor_pos_callback(window, self.on_cursor_pos)
        glfw.set_scroll_callback(window, self.on_scroll)
        glfw.set_window_size_callback(window, self.on_window_size)
Example #4
0
def main():
    global frame
    global animate

    if not glfw.init():
        return
    window = glfw.create_window(640, 640, "2015028077-Assingnment-3", None,
                                None)
    if not window:
        glfw.terminate()
        return

    glfw.set_cursor_pos_callback(window, cursorCallback)
    glfw.set_key_callback(window, key_callback)
    glfw.set_mouse_button_callback(window, mouseCallback)
    glfw.set_input_mode(window, glfw.STICKY_MOUSE_BUTTONS, 1)
    glfw.set_scroll_callback(window, scrollCallback)
    glfw.set_drop_callback(window, dropCallback)
    glfw.make_context_current(window)
    # if (animate < 1):
    glfw.swap_interval(1)

    while not glfw.window_should_close(window):
        #calculatePositionDiff(window)

        glfw.poll_events()
        # if(animate > 1):
        #     render()
        # if(animate<1):
        renderWrapper()
        # render(int(t*50)%frame)
        glfw.swap_buffers(window)

    glfw.terminate()
Example #5
0
def View(meshes):

    global viewer

    viewer = ViewerClass()
    viewer.W = 1024
    viewer.H = 768
    viewer.fov = 60.0
    viewer.button = 0
    viewer.meshes = meshes
    viewer.shader = None

    # calculate bounding box -> (-1,+1) ^3
    BOX = invalid_box()
    for mesh in viewer.meshes:
        box = get_bounding_box(mesh)
        add_point(BOX, box.p1)
        add_point(BOX, box.p2)
    S = BOX.p2 - BOX.p1
    maxsize = max([S.x, S.y, S.z])

    for mesh in viewer.meshes:
        mesh.T = matrix_prod(
            translate_matrix(Point3d(-1.0, -1.0, -1.0)),
            matrix_prod(
                scale_matrix(
                    Point3d(2.0 / maxsize, 2.0 / maxsize, 2.0 / maxsize)),
                translate_matrix(-BOX.p1)))

    viewer.pos = Point3d(3, 3, 3)
    viewer.dir = normalized(Point3d(0, 0, 0) - viewer.pos)
    viewer.vup = Point3d(0, 0, 1)

    maxsize = 2.0
    viewer.zNear = maxsize / 50.0
    viewer.zFar = maxsize * 10.0
    viewer.walk_speed = maxsize / 100.0
    redisplay(viewer)

    glfw.init()

    glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 3)
    glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 2)
    glfw.window_hint(glfw.OPENGL_FORWARD_COMPAT, GL_TRUE)
    glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE)

    viewer.win = glfw.create_window(viewer.W, viewer.H, "Plasm", None, None)
    glfw.make_context_current(viewer.win)

    glfw.set_window_size_callback(viewer.win, on_resize_evt)
    glfw.set_key_callback(viewer.win, on_keypress_evt)
    glfw.set_cursor_pos_callback(viewer.win, on_mousemove_evt)
    glfw.set_mouse_button_callback(viewer.win, on_mousebutton_evt)
    glfw.set_scroll_callback(viewer.win, on_mousewheel_evt)

    while not glfw.window_should_close(viewer.win):
        glRender(viewer)
        glfw.swap_buffers(viewer.win)
        glfw.poll_events()
    glfw.terminate()
Example #6
0
def main():
    if not glfw.init():
        print ('GLFW initialization failed')
        sys.exit(-1)
    width = 800
    height = 600
    window = glfw.create_window(width, height, 'COW COASTER', None, None)
    if not window:
        glfw.terminate()
        sys.exit(-1)

    glfw.make_context_current(window)
    glfw.set_key_callback(window, onKeyPress)
    glfw.set_mouse_button_callback(window, onMouseButton)
    glfw.set_cursor_pos_callback(window, onMouseDrag)
    glfw.swap_interval(1)

    mac_moved = False

    initialize(window)
    while not glfw.window_should_close(window):
        glfw.poll_events()
        display()

        glfw.swap_buffers(window)

        # TO FIX ERROR IN MAC
        # Screen does not render properly until move/resizing its window
        if not mac_moved:
            x_win, y_win = glfw.get_window_pos(window)
            x_win += 1
            glfw.set_window_pos(window, x_win, y_win)
            mac_moved = True

    glfw.terminate()
Example #7
0
    def __init__(self, window_instance):
        """ Constructor.

        Parameters:
        ===========
        * window_instance (:obj:`int`): Reference to the current window used to
          attach the keyboard event handler functions to.
        """

        # Button state collections
        self._buttons_pressed = set()
        self._buttons_held = set()
        self._buttons_released = set()
        self._mod_bitfield = 0

        # Mouse scroll wheel offsets
        self._scroll_offset_x = 0
        self._scroll_offset_y = 0

        # Mouse positioning parameters
        self._x = self._y = self._dx = self._dy = 0.0

        # Set window callback functions for mouse
        self._window = window_instance
        glfw.set_mouse_button_callback(window_instance, self.handle_button)
        glfw.set_scroll_callback(window_instance, self.handle_scroll)
Example #8
0
 def _glfw_setup(self, window):
   glfw.set_cursor_pos_callback(window, self._handle_move)
   glfw.set_mouse_button_callback(window, self._handle_button)
   glfw.set_scroll_callback(window, self._handle_scroll)
   framebuffer_width, _ = glfw.get_framebuffer_size(window)
   window_width, _ = glfw.get_window_size(window)
   return framebuffer_width, window_width
Example #9
0
def main():
    global window, frame_rate
    cwd = os.getcwd()

    if not glfw.init():
        return

    os.chdir(cwd)

    glfw.window_hint(glfw.DEPTH_BITS, 32)
    frame_rate = 144
    window = glfw.create_window(WIDTH, HEIGHT, "2D Graphics", None, None)

    if not window:
        glfw.terminate()
        return

    glfw.make_context_current(window)

    glfw.set_mouse_button_callback(window, mouse_pressed)
    glfw.set_key_callback(window, key_pressed)
    glfw.set_window_size_callback(window, resize_viewport)
    glfw.set_cursor_pos_callback(window, mouse_moved)

    create_obj_from_file()

    init_opengl()

    run()
Example #10
0
def main():
    # initialize glfw
    if not glfw.init():
        return
    window = glfw.create_window(500, 500, "Jakob", None, None)
    if not window:
        glfw.terminate()
        return
    glfw.make_context_current(window)
    glfw.set_mouse_button_callback(window, onMouseButton)
    glfw.set_key_callback(window, onKeyboard)

    # opengl init
    glViewport(0, 0, 500, 500)
    glMatrixMode(GL_PROJECTION)
    glOrtho(0, 500, 0, 500, 0.01, 1)
    glClearColor(1.0, 1.0, 1.0, 1.0)
    glLoadIdentity()

    while not glfw.window_should_close(window):

        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
        render()
        glfw.swap_buffers(window)
        glfw.poll_events()

    glfw.terminate()
Example #11
0
def main():
    #initialize the library
    if not glfw.init():
        return
    #Create a windowed mode window and its OpenGL context
    window = glfw.create_window(640, 480, "Hello World", None, None)
    if not window:
        glfw.terminate()
        return

    glfw.set_key_callback(window, key_callback)
    glfw.set_cursor_pos_callback(window, cursor_callback)
    glfw.set_mouse_button_callback(window, button_callback)
    glfw.set_scroll_callback(window, scroll_callback)

    #Make the window's context current
    glfw.make_context_current(window)

    #Loop until the user closes the window
    while not glfw.window_should_close(window):
        #Poll events
        glfw.poll_events()

        #Render here, e.g. using pyOpenGL
        render()

        #Swap front and back buffers
        glfw.swap_buffers(window)

    glfw.terminate()
Example #12
0
    def run(self):

        glfw.set_key_callback(self.window, self.key_callback)
        glfw.set_cursor_pos_callback(self.window,
                                     self.mouse_cursor_pos_callback)
        glfw.set_mouse_button_callback(self.window, self.mouse_button_callback)
        glfw.set_scroll_callback(self.window, self.mouse_scroll_callback)
        glfw.set_window_size_callback(self.window, self.window_size_callback)

        while not glfw.window_should_close(
                self.window) and not self.quit_requested:
            self.app.on_draw()

            glfw.poll_events()
            self.impl.process_inputs()

            self.app.menu()

            gl.glClearColor(0., 0., 0.2, 1)
            gl.glClear(gl.GL_COLOR_BUFFER_BIT)

            self.app.on_draw()

            imgui.render()
            self.impl.render(imgui.get_draw_data())
            glfw.swap_buffers(self.window)

        self.impl.shutdown()
        glfw.terminate()
Example #13
0
def main():
    global gToggle, count
    # Initialize the library
    if not glfw.init():
        return
    # Create a windowed mode window and its OpenGL context
    window = glfw.create_window(800, 800, "2016025105", None, None)
    if not window:
        glfw.terminate()
        return

    # Make the window's context current
    glfw.make_context_current(window)

    glfw.set_key_callback(window, key_callback)
    glfw.set_cursor_pos_callback(window, cursor_callback)
    glfw.set_mouse_button_callback(window, button_callback)
    glfw.set_scroll_callback(window, scroll_callback)
    glfw.set_drop_callback(window, drop_callback)
    glfw.swap_interval(1)

    # Loop until the user closes the window
    count = 0
    while not glfw.window_should_close(window):
        # Poll for and process events
        glfw.poll_events()
        # Render here, e.g. using pyOpenGL
        render(count)
        # Swap front and back buffers
        glfw.swap_buffers(window)
        if gToggle == True:
            count += 1

    glfw.terminate()
Example #14
0
def main():
  global mshelm, wmngr_glfw
  mshelm = dfm2.MeshElem("../test_inputs/bunny_2k.ply");
  mshelm.scaleXYZ(0.02)

  wmngr_glfw = dfm2.WindowManagerGLFW(1.0)

  glfw.init()
  win_glfw = glfw.create_window(640, 480, 'Hello World', None, None)
  glfw.make_context_current(win_glfw)

  dfm2.setSomeLighting()
  glEnable(GL_DEPTH_TEST)

  glfw.set_mouse_button_callback(win_glfw, mouseButtonCB)
  glfw.set_cursor_pos_callback(win_glfw,  mouseMoveCB)
  glfw.set_key_callback(win_glfw, keyFunCB)

  while not glfw.window_should_close(win_glfw):
    glClearColor(1, 1, 1, 1)
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
    wmngr_glfw.camera.set_gl_camera()
    render()
    glfw.swap_buffers(win_glfw)
    glfw.poll_events()
    if wmngr_glfw.isClose:
      break
  glfw.destroy_window(win_glfw)
  glfw.terminate()
  print("closed")
    def __init__(self, sim):
        super().__init__(sim)

        self._gui_lock = Lock()
        self._button_left_pressed = False
        self._button_right_pressed = False
        self._last_mouse_x = 0
        self._last_mouse_y = 0

        # debug
        self._click_cnt = 0
        self._last_click_time = 0
        self._last_button = None
        self._needselect = 0
        self.theta_discrete = 0

        framebuffer_width, _ = glfw.get_framebuffer_size(self.window)
        window_width, _ = glfw.get_window_size(self.window)
        self._scale = framebuffer_width * 1.0 / window_width

        glfw.set_cursor_pos_callback(self.window, self._cursor_pos_callback)
        glfw.set_mouse_button_callback(self.window,
                                       self._mouse_button_callback)
        glfw.set_scroll_callback(self.window, self._scroll_callback)
        glfw.set_key_callback(self.window, self.key_callback)
Example #16
0
def main():
    global KEY_SPACE
    global frame_now, frame_num
    if not glfw.init():
        return
    window = glfw.create_window(800, 800, '2014000082-class-3', None, None)
    if not window:
        glfw.terminate()
        return

    glfw.set_drop_callback(window, drop_callback)
    glfw.set_key_callback(window, key_callback)
    glfw.make_context_current(window)
    glfw.set_cursor_pos_callback(window, cursor_callback)
    glfw.set_mouse_button_callback(window, button_callback)
    glfw.set_scroll_callback(window, scroll_callback)

    glfw.swap_interval(1)
    while not glfw.window_should_close(window):
        glfw.poll_events()
        render()
        glfw.swap_buffers(window)
        if KEY_SPACE:
            frame_now += 1
            frame_now %= frame_num
    glfw.terminate()
Example #17
0
def main():
    global gVertexArraySeparate
    # Initialize the library
    if not glfw.init():
        return
    # Create a windowed mode window and its OpenGL context
    window = glfw.create_window(640, 640, "2016025887", None, None)
    if not window:
        glfw.terminate()
        return
    # Make the window's context current
    glfw.make_context_current(window)

    glfw.set_key_callback(window, key_callback)
    glfw.set_cursor_pos_callback(window, cursor_callback)
    glfw.set_mouse_button_callback(window, button_callback)
    glfw.set_scroll_callback(window, scroll_callback)

    glfw.swap_interval(1)

    obj_drop()

    # Loop until the user closes the window
    while not glfw.window_should_close(window):
        # Poll for and process events
        glfw.poll_events()
        # Render here, e.g. using pyOpenGL
        render()
        # Swap front and back buffers
        glfw.swap_buffers(window)

    glfw.terminate()
Example #18
0
def main():

    global gVertexArraySeparate
    if not glfw.init():
        return
    window = glfw.create_window(800, 800, "2016025687", None, None)

    if not window:
        glfw.terminate()
        return

    glfw.set_drop_callback(window, drop_callback)
    glfw.make_context_current(window)
    glfw.set_cursor_pos_callback(window, cursor_callback)
    glfw.set_scroll_callback(window, scroll_callback)
    glfw.set_mouse_button_callback(window, button_callback)
    glfw.set_key_callback(window, key_callback)
    glfw.swap_interval(1)
    gVertexArraySeparate = createVertexArraySeparate()
    while not glfw.window_should_close(window):
        glfw.poll_events()
        render()
        glfw.swap_buffers(window)

    glfw.terminate()
Example #19
0
    def wire_events(self, gl, window):
        """
        :param gl:
        moderngl context

        :param window:
        glfw window handle
        """
        def on_resize(window, width, height):
            gl.viewport = (0, 0, width, height)
            imgui.get_io().display_size = width, height
            self.on_resize(window, width, height)

        def on_cursor_pos(window, x, y):
            imgui.get_io().mouse_pos = x, y
            self.on_cursor_pos(window, x, y)

        def on_mouse_button(window, button, action, mods):
            imgui.get_io().mouse_down[button] = action
            self.on_mouse_button(window, button, action, mods)

        def on_scroll(window, scroll_x, scroll_y):
            imgui.get_io().mouse_wheel = scroll_y
            self.on_scroll(window, scroll_x, scroll_y)

        glfw.set_window_size_callback(window, on_resize)
        glfw.set_cursor_pos_callback(window, on_cursor_pos)
        glfw.set_mouse_button_callback(window, on_mouse_button)
        glfw.set_scroll_callback(window, on_scroll)
Example #20
0
def main():
    if not glfw.init():
        print ('GLFW initialization failed')
        sys.exit(-1)
    width = 800;
    height = 600;
    window = glfw.create_window(width, height, 'modern opengl example', None, None)
    if not window:
        glfw.terminate()
        sys.exit(-1)

    glfw.make_context_current(window)
    glfw.set_key_callback(window, onKeyPress)
    glfw.set_mouse_button_callback(window, onMouseButton)
    glfw.set_cursor_pos_callback(window, onMouseDrag)
    glfw.swap_interval(1)

    initialize(window);						
    while not glfw.window_should_close(window):
        glfw.poll_events()
        display()

        glfw.swap_buffers(window)

    glfw.terminate()
Example #21
0
def show(molecule,
         width=500,
         height=500,
         show_bonds=True,
         bonds_method='radii',
         bonds_param=None,
         camera=None,
         title='mogli'):
    """
    Interactively show the given molecule with OpenGL. By default, bonds are
    drawn, if this is undesired the show_bonds parameter can be set to False.
    For information on the bond calculation, see Molecule.calculate_bonds.
    If you pass a tuple of camera position, center of view and an up vector to
    the camera parameter, the camera will be set accordingly. Otherwise the
    molecule will be viewed in the direction of the z axis, with the y axis
    pointing upward.
    """
    global _camera
    molecule.positions -= np.mean(molecule.positions, axis=0)
    max_atom_distance = np.max(la.norm(molecule.positions, axis=1))
    if show_bonds:
        molecule.calculate_bonds(bonds_method, bonds_param)

    # If GR3 was initialized earlier, it would use a different context, so
    # it will be terminated first.
    gr3.terminate()

    # Initialize GLFW and create an OpenGL context
    glfw.init()
    glfw.window_hint(glfw.SAMPLES, 16)
    window = glfw.create_window(width, height, title, None, None)
    glfw.make_context_current(window)
    glEnable(GL_MULTISAMPLE)

    # Set up the camera (it will be changed during mouse rotation)
    if camera is None:
        camera_distance = -max_atom_distance * 2.5
        camera = ((0, 0, camera_distance), (0, 0, 0), (0, 1, 0))
    camera = np.array(camera)
    _camera = camera

    # Create the GR3 scene
    gr3.setbackgroundcolor(255, 255, 255, 0)
    _create_gr3_scene(molecule, show_bonds)
    # Configure GLFW
    glfw.set_cursor_pos_callback(window, _mouse_move_callback)
    glfw.set_mouse_button_callback(window, _mouse_click_callback)
    glfw.swap_interval(1)
    # Start the GLFW main loop
    while not glfw.window_should_close(window):
        glfw.poll_events()
        width, height = glfw.get_window_size(window)
        glViewport(0, 0, width, height)
        _set_gr3_camera()
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
        gr3.drawimage(0, width, 0, height, width, height,
                      gr3.GR3_Drawable.GR3_DRAWABLE_OPENGL)
        glfw.swap_buffers(window)
    glfw.terminate()
    gr3.terminate()
Example #22
0
def main():
    global gVertexArrayIndexed, gIndexArray

    if not glfw.init():
        return
    window = glfw.create_window(480, 480, '2016025969', None, None)
    if not window:
        glfw.terminate()
        return
    glfw.make_context_current(window)

    glfw.set_mouse_button_callback(window, mouse_button_callback)
    glfw.set_cursor_pos_callback(window, cursor_position_callback)
    glfw.set_scroll_callback(window, scroll_callback)
    glfw.set_key_callback(window, key_callback)
    glfw.set_framebuffer_size_callback(window, size_callback)
    glfw.set_drop_callback(window, drop_callback)

    glfw.swap_interval(1)
    tarr = createVertexArraySeparate()

    while not glfw.window_should_close(window):
        glfw.poll_events()
        render()
        glfw.swap_buffers(window)

    glfw.terminate()
Example #23
0
def main():
    if not glfw.init():
        raise ValueError("Failed to initialize glfw")

    glfw.window_hint(glfw.CONTEXT_CREATION_API, glfw.NATIVE_CONTEXT_API)
    glfw.window_hint(glfw.CLIENT_API, glfw.OPENGL_API)
    glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 4)
    glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 2)
    glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE)
    glfw.window_hint(glfw.OPENGL_FORWARD_COMPAT, True)
    glfw.window_hint(glfw.RESIZABLE, True)
    glfw.window_hint(glfw.DOUBLEBUFFER, True)
    glfw.window_hint(glfw.DEPTH_BITS, 24)
    glfw.window_hint(glfw.SAMPLES, 4)

    window = glfw.create_window(1260, 720, "Python GL", None, None)
    if not window:
        glfw.terminate()
        raise ValueError("Failed to create window")

    glfw.make_context_current(window)
    glfw.set_key_callback(window, key_event_callback)
    glfw.set_cursor_pos_callback(window, mouse_event_callback)
    glfw.set_mouse_button_callback(window, mouse_button_callback)
    glfw.set_window_size_callback(window, window_resize_callback)

    while not glfw.window_should_close(window):

        on_input(window)
        on_draw()
        glfw.swap_buffers(window)
        glfw.poll_events()

    glfw.terminate()
Example #24
0
    def __init__(self):
        cwd = os.getcwd()

        if not glfw.init():
            return

        os.chdir(cwd)

        glfw.window_hint(glfw.VERSION_MAJOR, 3)
        glfw.window_hint(glfw.VERSION_MINOR, 3)
        glfw.window_hint(glfw.OPENGL_FORWARD_COMPAT, GL_TRUE)
        glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE)

        self.width, self.height = 640, 480
        self.window = glfw.create_window(self.width, self.height,
                                         "Simple Window", None, None)

        glfw.make_context_current(self.window)

        glViewport(0, 0, self.width, self.height)
        glEnable(GL_DEPTH_TEST)
        glClearColor(0.5, 0.5, 0.5, 1)

        glfw.set_key_callback(self.window, self._key_press_callback)
        glfw.set_mouse_button_callback(self.window, self._mouse_press_callback)
        glfw.set_window_size_callback(self.window,
                                      self._window_resize_callback)
Example #25
0
def main():

    if not glfw.init():
        return
    window = glfw.create_window(800, 800, '2015004466', None, None)
    if not window:
        glfw.terminate()
        return
    glfw.make_context_current(window)
    glfw.set_key_callback(window, key_callback)
    glfw.set_drop_callback(window, drop_callback)
    glfw.set_mouse_button_callback(window, button_callback)
    glfw.set_cursor_pos_callback(window, cursor_callback)
    glfw.set_scroll_callback(window, scroll_callback)
    glfw.swap_interval(1)

    count = 0
    while not glfw.window_should_close(window):
        glfw.poll_events()
        ang = count % 360
        render(ang)
        count += 1
        glfw.swap_buffers(window)

    glfw.terminate()
Example #26
0
def main():
    if not glfw.init():
        return
    window = glfw.create_window(800, 800, 'ObjViewer', None, None)
    if not window:
        glfw.terminate()
        return
    glfw.make_context_current(window)
    glfw.set_key_callback(window, key_callback)
    glfw.set_scroll_callback(window, scroll_callback)
    glfw.set_cursor_pos_callback(window, cursor_callback)
    glfw.set_mouse_button_callback(window, button_callback)
    glfw.set_drop_callback(window, drop_callback)

    global varr1, dvarr1, narr1, fnarr1, svarr1, diarr1
    global varr2, dvarr2, narr2, fnarr2, svarr2, diarr2
    global varr3, dvarr3, narr3, fnarr3, svarr3, diarr3

    f = open('bone.obj', mode='r', encoding='utf-8')
    varr1, dvarr1, narr1, fnarr1, svarr1, diarr1 = parsing(f)
    f = open('hand.obj', mode='r', encoding='utf-8')
    varr2, dvarr2, narr2, fnarr2, svarr2, diarr2 = parsing(f)
    f = open('coin.obj', mode='r', encoding='utf-8')
    varr3, dvarr3, narr3, fnarr3, svarr3, diarr3 = parsing(f)

    while not glfw.window_should_close(window):
        glfw.poll_events()
        render()
        glfw.swap_buffers(window)

    glfw.terminate()
Example #27
0
 def _register(self):
     glfw.set_mouse_button_callback(self.window, self._handle_mouse_button)
     glfw.set_key_callback(self.window, self._handle_key)
     glfw.set_scroll_callback(self.window, self._handle_scroll_wheel)
     glfw.set_input_mode(self.window, glfw.CURSOR,
                         glfw.CURSOR_NORMAL)  # TODO ???
     glfw.set_cursor_pos_callback(self.window, self._handle_mouse_move)
Example #28
0
    def init(self):
        if not glfw.init():
            raise Exception('glfw failed to initialize')

        glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 3)
        glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 2)
        glfw.window_hint(glfw.OPENGL_FORWARD_COMPAT, GL.GL_TRUE)
        glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE)

        self.window = glfw.create_window(
            self.initial_width, self.initial_height,
            self.title, None, None
        )
        if not self.window:
            glfw.terminate()
            raise Exception('glfw failed to create a window')

        glfw.make_context_current(self.window)
        glfw.set_framebuffer_size_callback(self.window, self._reshape_callback)
        glfw.set_key_callback(self.window, self._key_callback)
        glfw.set_mouse_button_callback(self.window, self._mouse_button_callback)

        GL.glEnable(GL.GL_CULL_FACE)
        GL.glCullFace(GL.GL_BACK)
        GL.glFrontFace(GL.GL_CW)

        GL.glEnable(GL.GL_DEPTH_TEST)
        GL.glDepthMask(GL.GL_TRUE)
        GL.glDepthFunc(GL.GL_LEQUAL)
        GL.glDepthRange(0.0, 1.0)
        GL.glEnable(depth_clamp.GL_DEPTH_CLAMP)
Example #29
0
def main():
    # Initialize the library
    if not glfw.init():
        return
    # Create a windowed mode window and its OpenGL context
    window = glfw.create_window(720, 720, "2015005141", None, None)
    if not window:
        glfw.terminate()
        return

    # Make the window's context current
    glfw.make_context_current(window)

    glfw.set_mouse_button_callback(window, button_callback)
    glfw.set_scroll_callback(window, scroll_callback)
    glfw.set_drop_callback(window, drop_callback)
    glfw.set_key_callback(window, key_callback)

    # Loop until the user closes the window
    while not glfw.window_should_close(window):
        # Poll for and process events
        glfw.poll_events()
        render(gCamAng)
        glfw.swap_interval(1)

        # Swap front and back buffers
        glfw.swap_buffers(window)

    glfw.terminate()
def main():
    global vertices, window_height, window_width, to_redraw

    if not glfw.init():
        return

    window = glfw.create_window(400, 400, "Lab4", None, None)
    if not window:
        glfw.terminate()
        return

    glfw.make_context_current(window)
    glfw.set_key_callback(window, key_callback)
    glfw.set_framebuffer_size_callback(window, resize_callback)

    glfw.set_mouse_button_callback(window, mouse_button_callback)
    glEnable(GL_DEPTH_TEST)
    glDepthFunc(GL_LESS)
    glClearColor(0, 0, 0, 0)

    while not glfw.window_should_close(window):
        # print(vertices)
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)

        draw()

        glfw.swap_buffers(window)
        glfw.poll_events()

    glfw.destroy_window(window)
    glfw.terminate()
Example #31
0
    def draw_loop(self, nframe=-1):
        """
    Enter the draw loop

    render -- a function to render
    """
        glfw.set_mouse_button_callback(self.win, self.mouse)
        glfw.set_cursor_pos_callback(self.win, self.motion)
        glfw.set_key_callback(self.win, self.keyinput)
        #    glfw.set_window_size_callback(self.win, self.window_size)
        iframe = 0
        while not glfw.window_should_close(self.win):
            gl.glClearColor(self.color_bg[0], self.color_bg[1],
                            self.color_bg[2], 1.0)
            gl.glClear(gl.GL_COLOR_BUFFER_BIT | gl.GL_DEPTH_BUFFER_BIT)
            gl.glEnable(gl.GL_POLYGON_OFFSET_FILL)
            gl.glPolygonOffset(1.1, 4.0)
            self.wm.camera.set_gl_camera()
            for func_step_time in self.list_func_step_time:
                func_step_time()
            for draw_func in self.list_func_draw:
                draw_func()
            glfw.swap_buffers(self.win)
            glfw.poll_events()
            iframe += 1
            if nframe > 0 and iframe > nframe:
                break
            if self.wm.isClose:
                break
        self.close()
Example #32
0
    def run(self):
        self._callFn("appStarted", self)

        def sizeChanged(window, width, height):
            self.width = width
            self.height = height
            print(f'new size: {width} {height}')
            self.canvas.resize(width, height)
            self._callFn('sizeChanged', self)

        def charEvent(*args):
            self.dispatchCharEvent(*args)

        def keyEvent(*args):
            self.dispatchKeyEvent(*args)

        def mouseMoved(*args):
            self.dispatchMouseMoved(*args)

        def mouseChanged(*args):
            self.dispatchMouseChanged(*args)

        glfw.set_framebuffer_size_callback(self.window, sizeChanged)
        glfw.set_key_callback(self.window, keyEvent)
        glfw.set_char_callback(self.window, charEvent)
        glfw.set_cursor_pos_callback(self.window, mouseMoved)
        glfw.set_mouse_button_callback(self.window, mouseChanged)

        i = 0

        times = [0.0] * 20

        while not glfw.window_should_close(self.window):
            times.pop(0)

            glClearColor(0.2, 0.3, 0.3, 1.0)
            glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)  #type:ignore

            self._callFn('redrawAll', self, self.window, self.canvas)

            self.canvas.redraw()

            if time.time() - self.lastTimer > (self.timerDelay / 1000.0):
                self.lastTimer = time.time()
                self._callFn('timerFired', self)

            glfw.swap_buffers(self.window)
            glfw.poll_events()

            times.append(time.time())

            i += 1

            if i % 50 == 0:
                timeDiff = (times[-1] - times[0]) / (len(times) - 1)
                print(timeDiff)

        self._callFn('appStopped', self)

        glfw.terminate()
Example #33
0
    def __init__(self, objects=[], options={}):
        super().__init__()

        self.parseOptions(options)

        self.cameraCursor = [0.0, 0.0]
        self.cameraMove = False
        self.cameraRotate = False
        self.redisplay = True
        self.titleText = 'OpenGL 4.1 render'

        glfw.init()

        try:
            self.window = glfw.create_window(*self.viewport, self.titleText, None, None)
            glfw.make_context_current(self.window)
        except:
            print('Window initialization failed')
            glfw.terminate()
            exit()

        self.initGraphics()
        self.updateMatrix(self.viewport)

        glfw.set_key_callback(self.window, self.handleKeyEvent)
        glfw.set_mouse_button_callback(self.window, self.handleMouseButtonEvent)
        glfw.set_cursor_pos_callback(self.window, self.handleCursorMoveEvent)
        glfw.set_scroll_callback(self.window, self.handleScrollEvent)
        glfw.set_window_refresh_callback(self.window, self.handleResizeEvent)

        self.objects = set()
        self.appendRenderObjects(self.makeRenderObjects(objects))
Example #34
0
def show(molecule, width=500, height=500,
         show_bonds=True, bonds_method='radii', bonds_param=None,
         camera=None, title='mogli'):
    """
    Interactively show the given molecule with OpenGL. By default, bonds are
    drawn, if this is undesired the show_bonds parameter can be set to False.
    For information on the bond calculation, see Molecule.calculate_bonds.
    If you pass a tuple of camera position, center of view and an up vector to
    the camera parameter, the camera will be set accordingly. Otherwise the
    molecule will be viewed in the direction of the z axis, with the y axis
    pointing upward.
    """
    global _camera
    molecule.positions -= np.mean(molecule.positions, axis=0)
    max_atom_distance = np.max(la.norm(molecule.positions, axis=1))
    if show_bonds:
        molecule.calculate_bonds(bonds_method, bonds_param)

    # If GR3 was initialized earlier, it would use a different context, so
    # it will be terminated first.
    gr3.terminate()

    # Initialize GLFW and create an OpenGL context
    glfw.init()
    glfw.window_hint(glfw.SAMPLES, 16)
    window = glfw.create_window(width, height, title, None, None)
    glfw.make_context_current(window)
    glEnable(GL_MULTISAMPLE)

    # Set up the camera (it will be changed during mouse rotation)
    if camera is None:
        camera_distance = -max_atom_distance*2.5
        camera = ((0, 0, camera_distance),
                  (0, 0, 0),
                  (0, 1, 0))
    camera = np.array(camera)
    _camera = camera

    # Create the GR3 scene
    gr3.setbackgroundcolor(255, 255, 255, 0)
    _create_gr3_scene(molecule, show_bonds)
    # Configure GLFW
    glfw.set_cursor_pos_callback(window, _mouse_move_callback)
    glfw.set_mouse_button_callback(window, _mouse_click_callback)
    glfw.swap_interval(1)
    # Start the GLFW main loop
    while not glfw.window_should_close(window):
        glfw.poll_events()
        width, height = glfw.get_window_size(window)
        glViewport(0, 0, width, height)
        _set_gr3_camera()
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
        gr3.drawimage(0, width, 0, height,
                      width, height, gr3.GR3_Drawable.GR3_DRAWABLE_OPENGL)
        glfw.swap_buffers(window)
    glfw.terminate()
    gr3.terminate()
Example #35
0
    def __init__(self, **kwargs):
        super().__init__(**kwargs)

        if not glfw.init():
            raise ValueError("Failed to initialize glfw")

        # Configure the OpenGL context
        glfw.window_hint(glfw.CONTEXT_CREATION_API, glfw.NATIVE_CONTEXT_API)
        glfw.window_hint(glfw.CLIENT_API, glfw.OPENGL_API)
        glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, self.gl_version[0])
        glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, self.gl_version[1])
        glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE)
        glfw.window_hint(glfw.OPENGL_FORWARD_COMPAT, True)
        glfw.window_hint(glfw.RESIZABLE, self.resizable)
        glfw.window_hint(glfw.DOUBLEBUFFER, True)
        glfw.window_hint(glfw.DEPTH_BITS, 24)
        glfw.window_hint(glfw.SAMPLES, self.samples)

        monitor = None
        if self.fullscreen:
            # Use the primary monitors current resolution
            monitor = glfw.get_primary_monitor()
            mode = glfw.get_video_mode(monitor)
            self.width, self.height = mode.size.width, mode.size.height

            # Make sure video mode switching will not happen by
            # matching the desktops current video mode
            glfw.window_hint(glfw.RED_BITS, mode.bits.red)
            glfw.window_hint(glfw.GREEN_BITS, mode.bits.green)
            glfw.window_hint(glfw.BLUE_BITS, mode.bits.blue)
            glfw.window_hint(glfw.REFRESH_RATE, mode.refresh_rate)

        self.window = glfw.create_window(self.width, self.height, self.title, monitor, None)

        if not self.window:
            glfw.terminate()
            raise ValueError("Failed to create window")

        if not self.cursor:
            glfw.set_input_mode(self.window, glfw.CURSOR, glfw.CURSOR_DISABLED)

        self.buffer_width, self.buffer_height = glfw.get_framebuffer_size(self.window)
        glfw.make_context_current(self.window)

        if self.vsync:
            glfw.swap_interval(1)

        glfw.set_key_callback(self.window, self.key_event_callback)
        glfw.set_cursor_pos_callback(self.window, self.mouse_event_callback)
        glfw.set_mouse_button_callback(self.window, self.mouse_button_callback)
        glfw.set_window_size_callback(self.window, self.window_resize_callback)

        self.ctx = moderngl.create_context(require=self.gl_version_code)
        self.print_context_info()
        self.set_default_viewport()
Example #36
0
    def start(self):
        if not glfw.init():
            return

        glfw.window_hint(glfw.SAMPLES, 4)

        # try stereo if refresh rate is at least 100Hz
        window = None
        stereo_available = False

        _, _, refresh_rate = glfw.get_video_mode(glfw.get_primary_monitor())
        if refresh_rate >= 100:
            glfw.window_hint(glfw.STEREO, 1)
            window = glfw.create_window(500, 500, "Simulate", None, None)
            if window:
                stereo_available = True

        # no stereo: try mono
        if not window:
            glfw.window_hint(glfw.STEREO, 0)
            window = glfw.create_window(500, 500, "Simulate", None, None)

        if not window:
            glfw.terminate()
            return

        self.running = True

        # Make the window's context current
        glfw.make_context_current(window)

        width, height = glfw.get_framebuffer_size(window)
        width1, height = glfw.get_window_size(window)
        self._scale = width * 1.0 / width1

        self.window = window

        mjlib.mjv_makeObjects(byref(self.objects), 1000)

        mjlib.mjv_defaultCamera(byref(self.cam))
        mjlib.mjv_defaultOption(byref(self.vopt))
        mjlib.mjr_defaultOption(byref(self.ropt))

        mjlib.mjr_defaultContext(byref(self.con))

        if self.model:
            mjlib.mjr_makeContext(self.model.ptr, byref(self.con), 150)
            self.autoscale()
        else:
            mjlib.mjr_makeContext(None, byref(self.con), 150)

        glfw.set_cursor_pos_callback(window, self.handle_mouse_move)
        glfw.set_mouse_button_callback(window, self.handle_mouse_button)
        glfw.set_scroll_callback(window, self.handle_scroll)
Example #37
0
    def setup(self):
        # get glfw started
        glfw.init()
        self.window = glfw.create_window(self.width, self.height, "Python NanoVG Demo", None, None)
        glfw.set_window_pos(self.window, 0, 0)

        # Register callbacks window
        glfw.set_window_size_callback(self.window, self.on_resize)
        glfw.set_window_close_callback(self.window, self.on_close)
        glfw.set_key_callback(self.window, self.on_key)
        glfw.set_mouse_button_callback(self.window, self.on_button)

        self.basic_gl_setup()

        # glfwSwapInterval(0)
        glfw.make_context_current(self.window)
Example #38
0
def main():
    if not glfw.init():
        return
    window = glfw.create_window(640,640,'2015004584', None,None)
    if not window:
        glfw.terminate()
        return
    glfw.make_context_current(window)
    glfw.set_mouse_button_callback(window, button_callback)
    glfw.set_cursor_pos_callback(window, cursor_callback)

    while not glfw.window_should_close(window):
        glfw.poll_events()
        render()
        glfw.swap_buffers(window)

    glfw.terminate()
Example #39
0
    def __init__(self, sim):
        super().__init__(sim)

        self._gui_lock = Lock()
        self._button_left_pressed = False
        self._button_right_pressed = False
        self._last_mouse_x = 0
        self._last_mouse_y = 0

        framebuffer_width, _ = glfw.get_framebuffer_size(self.window)
        window_width, _ = glfw.get_window_size(self.window)
        self._scale = framebuffer_width * 1.0 / window_width

        glfw.set_cursor_pos_callback(self.window, self._cursor_pos_callback)
        glfw.set_mouse_button_callback(
            self.window, self._mouse_button_callback)
        glfw.set_scroll_callback(self.window, self._scroll_callback)
        glfw.set_key_callback(self.window, self.key_callback)
def glfw_init_routine():
    global window

    if not glfw.init():
        print("Failed to init")
        return False

    glfw.window_hint(glfw.RESIZABLE, 0)
    window = glfw.create_window(WINDOW_WIDTH, WINDOW_HEIGHT, "Hello, world!",
            None, None)
    if not window:
        print("Failed to create window")
        glfw.terminate()
        return False

    glfw.set_cursor_pos_callback(window, update_cursor)
    glfw.set_mouse_button_callback(window, update_mouse_btn)

    glfw.make_context_current(window)

    return True
Example #41
0
    def __init__(self):

        # save current working directory
        cwd = os.getcwd()

        # initialize glfw - this changes cwd
        glfw.init()

        # restore cwd
        os.chdir(cwd)

        # version hints
        glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 3)
        glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 3)
        glfw.window_hint(glfw.OPENGL_FORWARD_COMPAT, GL_TRUE)
        glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE)

        # make a window
        self.width, self.height = 640, 480
        self.aspect = self.width/float(self.height)
        self.win = glfw.create_window(self.width, self.height, "test")
        # make context current
        glfw.make_context_current(self.win)

        # initialize GL
        glViewport(0, 0, self.width, self.height)
        glEnable(GL_DEPTH_TEST)
        glClearColor(0.5, 0.5, 0.5,1.0)

        # set window callbacks
        glfw.set_mouse_button_callback(self.win, self.onMouseButton)
        glfw.set_key_callback(self.win, self.onKeyboard)
        glfw.set_window_size_callback(self.win, self.onSize)        

        # create 3D
        self.scene = Scene()

        # exit flag
        self.exitNow = False
Example #42
0
    def start(self):
        logger.info('initializing glfw@%s', glfw.get_version())

        glfw.set_error_callback(_glfw_error_callback)

        if not glfw.init():
            raise Exception('glfw failed to initialize')

        window = None
        if self.visible:
            glfw.window_hint(glfw.SAMPLES, 4)
        else:
            glfw.window_hint(glfw.VISIBLE, 0);

        # try stereo if refresh rate is at least 100Hz
        stereo_available = False

        _, _, refresh_rate = glfw.get_video_mode(glfw.get_primary_monitor())
        if refresh_rate >= 100:
            glfw.window_hint(glfw.STEREO, 1)
            window = glfw.create_window(
                self.init_width, self.init_height, "Simulate", None, None)
            if window:
                stereo_available = True

        # no stereo: try mono
        if not window:
            glfw.window_hint(glfw.STEREO, 0)
            window = glfw.create_window(
                self.init_width, self.init_height, "Simulate", None, None)

        if not window:
            glfw.terminate()
            return

        self.running = True

        # Make the window's context current
        glfw.make_context_current(window)

        self._init_framebuffer_object()

        width, height = glfw.get_framebuffer_size(window)
        width1, height = glfw.get_window_size(window)
        self._scale = width * 1.0 / width1

        self.window = window

        mjlib.mjv_makeObjects(byref(self.objects), 1000)

        mjlib.mjv_defaultCamera(byref(self.cam))
        mjlib.mjv_defaultOption(byref(self.vopt))
        mjlib.mjr_defaultOption(byref(self.ropt))

        mjlib.mjr_defaultContext(byref(self.con))

        if self.model:
            mjlib.mjr_makeContext(self.model.ptr, byref(self.con), 150)
            self.autoscale()
        else:
            mjlib.mjr_makeContext(None, byref(self.con), 150)

        glfw.set_cursor_pos_callback(window, self.handle_mouse_move)
        glfw.set_mouse_button_callback(window, self.handle_mouse_button)
        glfw.set_scroll_callback(window, self.handle_scroll)
Example #43
0
    def __init__(self, win, *args, **kwargs):
        """Set up the backend window according the params of the PsychoPy win

        Before PsychoPy 1.90.0 this code was executed in Window._setupPygame()

        Parameters
        ----------
        win : psychopy.visual.Window instance
            PsychoPy Window (usually not fully created yet).
        share : psychopy.visual.Window instance
            PsychoPy Window to share a context with
        bpc : array_like
            Bits per color (R, G, B).
        refreshHz : int
            Refresh rate in Hertz.
        depthBits : int,
            Framebuffer (back buffer) depth bits.
        swapInterval : int
            Swap interval for the current OpenGL context.
        stencilBits : int
            Framebuffer (back buffer) stencil bits.
        winTitle : str
            Optional window title string.
        *args
            Additional position arguments.
        **kwargs
            Additional keyword arguments.

        """
        BaseBackend.__init__(self, win)

        # window to share a context with
        shareWin = kwargs.get('share', None)
        if shareWin is not None:
            if shareWin.winType == 'glfw':
                shareContext = shareWin.winHandle
            else:
                logging.warning(
                    'Cannot share a context with a non-GLFW window. Disabling.')
                shareContext = None
        else:
            shareContext = None

        if sys.platform=='darwin' and not win.useRetina and pyglet.version >= "1.3":
            raise ValueError("As of PsychoPy 1.85.3 OSX windows should all be "
                             "set to useRetina=True (or remove the argument). "
                             "Pyglet 1.3 appears to be forcing "
                             "us to use retina on any retina-capable screen "
                             "so setting to False has no effect.")

        # window framebuffer configuration
        win.bpc = kwargs.get('bpc', (8, 8, 8))  # nearly all displays use 8 bpc
        win.refreshHz = int(kwargs.get('refreshHz', 60))
        win.depthBits = int(kwargs.get('depthBits', 8))
        win.stencilBits = int(kwargs.get('stencilBits', 8))
        # win.swapInterval = int(kwargs.get('swapInterval', 1))  # vsync ON if 1

        # get monitors, with GLFW the primary display is ALWAYS at index 0
        allScrs = glfw.get_monitors()
        if len(allScrs) < int(win.screen) + 1:
            logging.warn("Requested an unavailable screen number - "
                         "using first available.")
            win.screen = 0

        thisScreen = allScrs[win.screen]
        if win.autoLog:
            logging.info('configured GLFW screen %i' % win.screen)

        # find a matching video mode (can we even support this configuration?)
        isVidmodeSupported = False
        for vidmode in glfw.get_video_modes(thisScreen):
            size, bpc, hz = vidmode
            if win._isFullScr:  # size and refresh rate are ignored if windowed
                hasSize = size == tuple(win.size)
                hasHz = hz == win.refreshHz
            else:
                hasSize = hasHz = True
            hasBpc = bpc == tuple(win.bpc)
            if hasSize and hasBpc and hasHz:
                isVidmodeSupported = True
                break

        nativeVidmode = glfw.get_video_mode(thisScreen)
        if not isVidmodeSupported:
            # the requested video mode is not supported, use current

            logging.warning(
                ("The specified video mode is not supported by this display, "
                 "using native mode ..."))
            logging.warning(
                ("Overriding user video settings: size {} -> {}, bpc {} -> "
                 "{}, refreshHz {} -> {}".format(
                    tuple(win.size),
                    nativeVidmode[0],
                    tuple(win.bpc),
                    nativeVidmode[1],
                    win.refreshHz,
                    nativeVidmode[2])))

            # change the window settings
            win.size, win.bpc, win.refreshHz = nativeVidmode

        if win._isFullScr:
            useDisplay = thisScreen
        else:
            useDisplay = None

        # configure stereo
        useStereo = 0
        if win.stereo:
            # provide warning if stereo buffers are requested but unavailable
            if not glfw.extension_supported('GL_STEREO'):
                logging.warning(
                    'A stereo window was requested but the graphics '
                    'card does not appear to support GL_STEREO')
                win.stereo = False
            else:
                useStereo = 1

        # setup multisampling
        # This enables multisampling on the window backbuffer, not on other
        # framebuffers.
        msaaSamples = 0
        if win.multiSample:
            maxSamples = (GL.GLint)()
            GL.glGetIntegerv(GL.GL_MAX_SAMPLES, maxSamples)
            if (win.numSamples & (win.numSamples - 1)) != 0:
                # power of two?
                logging.warning(
                    'Invalid number of MSAA samples provided, must be '
                    'power of two. Disabling.')
            elif 0 > win.numSamples > maxSamples.value:
                # check if within range
                logging.warning(
                    'Invalid number of MSAA samples provided, outside of valid '
                    'range. Disabling.')
            else:
                msaaSamples = win.numSamples
        win.multiSample = msaaSamples > 0

        # disable stencil buffer
        if not win.allowStencil:
            win.stencilBits = 0

        # set buffer configuration hints
        glfw.window_hint(glfw.RED_BITS, win.bpc[0])
        glfw.window_hint(glfw.GREEN_BITS, win.bpc[1])
        glfw.window_hint(glfw.BLUE_BITS, win.bpc[2])
        glfw.window_hint(glfw.REFRESH_RATE, win.refreshHz)
        glfw.window_hint(glfw.STEREO, useStereo)
        glfw.window_hint(glfw.SAMPLES, msaaSamples)
        glfw.window_hint(glfw.STENCIL_BITS, win.stencilBits)
        glfw.window_hint(glfw.DEPTH_BITS, win.depthBits)
        glfw.window_hint(glfw.AUTO_ICONIFY, 0)

        # window appearance and behaviour hints
        if not win.allowGUI:
            glfw.window_hint(glfw.DECORATED, 0)

        # create the window
        self.winHandle = glfw.create_window(
            width=win.size[0],
            height=win.size[1],
            title=str(kwargs.get('winTitle', "PsychoPy (GLFW)")),
            monitor=useDisplay,
            share=shareContext)

        # The window's user pointer maps the Python Window object to its GLFW
        # representation.
        glfw.set_window_user_pointer(self.winHandle, win)
        glfw.make_context_current(self.winHandle)  # ready to use

        # set the position of the window if not fullscreen
        if not win._isFullScr:
            # if no window position is specified, centre it on-screen
            if win.pos is None:
                size, bpc, hz = nativeVidmode
                win.pos = [(size[0] - win.size[0]) / 2.0,
                           (size[1] - win.size[1]) / 2.0]

            # get the virtual position of the monitor, apply offset to the
            # window position
            px, py = glfw.get_monitor_pos(thisScreen)
            glfw.set_window_pos(self.winHandle,
                                int(win.pos[0] + px),
                                int(win.pos[1] + py))

        elif win._isFullScr and win.pos is not None:
            logging.warn("Ignoring window 'pos' in fullscreen mode.")

        # set the window icon
        glfw.set_window_icon(self.winHandle, 1, _WINDOW_ICON_)

        # set the window size to the framebuffer size
        win.size = np.array(glfw.get_framebuffer_size(self.winHandle))

        if win.useFBO:  # check for necessary extensions
            if not glfw.extension_supported('GL_EXT_framebuffer_object'):
                msg = ("Trying to use a framebuffer object but "
                       "GL_EXT_framebuffer_object is not supported. Disabled")
                logging.warn(msg)
                win.useFBO = False
            if not glfw.extension_supported('GL_ARB_texture_float'):
                msg = ("Trying to use a framebuffer object but "
                       "GL_ARB_texture_float is not supported. Disabling")
                logging.warn(msg)
                win.useFBO = False

        # Assign event callbacks, these are dispatched when 'poll_events' is
        # called.
        glfw.set_mouse_button_callback(self.winHandle, event._onGLFWMouseButton)
        glfw.set_scroll_callback(self.winHandle, event._onGLFWMouseScroll)
        glfw.set_key_callback(self.winHandle, event._onGLFWKey)
        glfw.set_char_mods_callback(self.winHandle, event._onGLFWText)

        # set swap interval to manual setting, independent of waitBlanking
        self.setSwapInterval(int(kwargs.get('swapInterval', 1)))

        # give the window class GLFW specific methods
        win.setMouseType = self.setMouseType
        if not win.allowGUI:
            self.setMouseVisibility(False)
Example #44
0
    def init_atb(self):
#         atb.init() # cannot tell what for, given by the binding author
        self.total = -233.3
        atb.TwInit(atb.TW_OPENGL, None)
        atb.TwWindowSize(self.window.width, self.window.height)
        self.extern_param_bar = atb.Bar(name="extern_param", label="evals", help="Scene atb",
                           position=(650, 10), size=(300,300), valueswidth=150)
        self.extern_param_bar.add_var("total", getter=self.get_total)
        # external defined energy terms
        self.extern_param_bar.add_separator("")
        for i, name in enumerate(self._energy_terms):
            self.extern_param_bar.add_var(name="energy_term_%d" % i, label=name, 
                    getter=self._disp_getter_closure(self._energy_terms, name))
        
        # external defined penalties
        self.extern_param_bar.add_separator("")
        for i, name in enumerate(self._extern_penalty_terms):
            self.extern_param_bar.add_var(name="extern_penalty_%d" % i, label=name,
                    getter=self._disp_getter_closure(self._extern_penalty_terms, name))
        
        # internal penalties
        self.extern_param_bar.add_separator("")
        for i, name in enumerate(self._intern_penalty_terms):
            self.extern_param_bar.add_var(name="intern_penalty_%d" % i, label=name,
                    getter=self._disp_getter_closure(self._intern_penalty_terms, name))
        atb.TwDefine("extern_param refresh=0.1")
        
        if not self.atb_controls: return
        self.control_bar = atb.Bar(name="controls", label="controls",
                                   position=(650, 320), size=(300, 300), valueswidth=150)
        def position_getter_closure(item, index):
            def getter():
                return item.position[index]
#                 return item.position[index]
            return getter   
        def position_setter_closure(item, index):
            def setter(x):
                item.position[index] = x
            return setter        
        def rotation_getter_closure(item, index):
            def getter():
                return item.orientation[index]
            return getter   
        def rotation_setter_closure(item, index):
            def setter(x):
                item.orientation[index] = x
            return setter
        def param_getter_closure(index):
            return lambda: self.get_param()[index]
        def param_setter_closure(index):
#             def setter(x):
#                 X = self.get_param()
#                 X[index] = x
#                 self.set_param()
#             return setter
            return lambda x: self.set_param_indiv(x, index)
        for i, item in enumerate(self._items):
            group = "item_%d" % i
            for j, n in enumerate('xyz'):
                name = "%s %s" % (group, n)
                self.control_bar.add_var(name=name, label=n, readonly=False, 
                                         vtype=atb.TW_TYPE_FLOAT, step=0.05,
                                         group=group,
                                         getter=position_getter_closure(item, j), 
                                         setter=position_setter_closure(item, j))
            for j, n in enumerate('abc'):
                name = "%s %s" % (group, n)
                self.control_bar.add_var(name=name, label=n, readonly=False, 
                                         vtype=atb.TW_TYPE_FLOAT, step=0.05,
                                         group=group,
                                         getter=rotation_getter_closure(item, j), 
                                         setter=rotation_setter_closure(item, j))
            self.control_bar.define("opened=false",group)
        self.control_bar.add_separator("septr2")
        param_length = 4
        for i in xrange(param_length):
            name = "param[%d]" % i
            self.control_bar.add_var(name=name, label=name, readonly=False, 
                                     vtype=atb.TW_TYPE_FLOAT, step=0.05,
                                     getter=param_getter_closure(i), 
                                     setter=param_setter_closure(i))
        
        
        def mouse_button_callback(window, button, action, mods):
            tAction = tButton = -1
            if action == glfw.RELEASE:
                tAction = atb.TW_MOUSE_RELEASED
            elif action == glfw.PRESS:
                tAction = atb.TW_MOUSE_PRESSED
            if button == glfw.MOUSE_BUTTON_LEFT:
                tButton = atb.TW_MOUSE_LEFT
            elif button == glfw.MOUSE_BUTTON_RIGHT:
                tButton = atb.TW_MOUSE_RIGHT
            elif button == glfw.MOUSE_BUTTON_MIDDLE:
                tButton = atb.TW_MOUSE_MIDDLE
            if not (tAction == -1 or tButton == -1): atb.TwMouseButton(tAction, tButton)            
        glfw.set_mouse_button_callback(self.window.handle, mouse_button_callback)
        cursor_callback = lambda w, x, y: atb.TwMouseMotion(int(x),int(y))
        glfw.set_cursor_pos_callback(self.window.handle, cursor_callback)
Example #45
0
def main():
    import os
    import sys
    os.chdir(os.path.dirname(__file__))

    import glfw
    import time
    from engine import Engine

    # Initialize the library
    if not glfw.init():
        sys.exit()

    glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 4)
    glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 3)
    glfw.window_hint(glfw.SAMPLES, 16)

    # Create a windowed mode window and its OpenGL context
    window = glfw.create_window(640, 480, "Window Name", None, None)
    if not window:
        print "Couldn't initialize OpenGL. Check that your OpenGL version >4.3."
        glfw.terminate()
        sys.exit()

    # Make the window's context current
    glfw.make_context_current(window)

    # Get window size
    width, height = glfw.get_framebuffer_size(window)

    # Create engine
    engine = Engine(window)
    engine.setWindowHeight(height)
    engine.setWindowWidth(width)

    def on_resize(window, width, height):
        engine.setWindowWidth(width)
        engine.setWindowHeight(height)

    # Install a window size handler
    glfw.set_window_size_callback(window, on_resize)

    def on_key(window, key, scancode, action, mods):
        if key == glfw.KEY_ESCAPE and action == glfw.PRESS:
            glfw.set_window_should_close(window, 1)

    # Install a key handler
    glfw.set_key_callback(window, on_key)

    def on_mouse(window, button, action, mods):
        if button == glfw.MOUSE_BUTTON_1 and action == glfw.PRESS:
            engine.shoot_on()
        if button == glfw.MOUSE_BUTTON_1 and action == glfw.RELEASE:
            engine.shoot_off()
        if button == glfw.MOUSE_BUTTON_2 and action == glfw.PRESS:
            engine.camera_switch()

    glfw.set_mouse_button_callback(window, on_mouse)

    def on_scroll(window, x, y):
        engine.camera_scroll(y)

    glfw.set_scroll_callback(window, on_scroll)

    old_time = time.time()
    elapsed_time = 0.0

    # Loop until the user closes the window
    while not glfw.window_should_close(window):
        # Calculate elapsed time
        elapsed_time = time.time() - old_time
        old_time = time.time()

        # Process
        engine.step(elapsed_time)

        # Swap front and back buffers
        glfw.swap_interval(1)
        glfw.swap_buffers(window)

        # Poll for and process events
        glfw.poll_events()

        # Don't be egoist :)
        time.sleep(0.01)

    glfw.terminate()
Example #46
0
#glfw.ext.set_icons([(icon_data, icon_width, icon_height)])
glfw.set_window_title(w, "pyglfw test")
#glfw.disable(w, glfw.AUTO_POLL_EVENTS)
#glfw.enable(w, glfw.KEY_REPEAT)

center_x = int(vm[0][0] / 2 - glfw.get_window_size(w)[0] / 2)
center_y = int(vm[0][1] / 2 - glfw.get_window_size(w)[1] / 2)
print( "new window position: {!s}, {!s}".format(center_x, center_y) )
glfw.set_window_pos(w, center_x, center_y)

glfw.set_window_size_callback(w, on_resize)
glfw.set_window_close_callback(w, on_close)
glfw.set_window_refresh_callback(w, on_refresh)
glfw.set_key_callback(w, on_key)
glfw.set_char_callback(w, on_char)
glfw.set_mouse_button_callback(w, on_button)
glfw.set_cursor_pos_callback(w, on_pos)
glfw.set_scroll_callback(w, on_scroll)

while not glfw.window_should_close(w):
    glfw.poll_events()
    
    if glfw.get_key(w, glfw.KEY_E) == glfw.PRESS:
        break
    
    glClear(GL_COLOR_BUFFER_BIT)
    glfw.swap_buffers(w)

glfw.close_window(w)
glfw.terminate()
Example #47
0
 def _init_events(self):
     glfw.set_cursor_pos_callback(self._wnd, self._cursor_pos_callback)
     glfw.set_mouse_button_callback(self._wnd, self._mouse_button_callback)
Example #48
0
    # Get window size
    width, height = glfw.get_framebuffer_size(window)

    def on_resize(window, width, height):
        gui.setWindowHeight(height)
        gui.setWindowWidth(width)
        pass

    # Install a window size handler
    glfw.set_window_size_callback(window, on_resize)

    def on_mouse(window, button, action, mods):
        pass

    glfw.set_mouse_button_callback(window, on_mouse)

    old_time = time.time()
    elapsed_time = 0.0

    # Create gui and quad object
    gui = GUI()
    gui.setWindowHeight(height)
    gui.setWindowWidth(width)
    quad = objectQuad()

    # Render function
    def render():
        # Clear screen
        gl.glClearColor(0, 0, 0, 1.0)
        gl.glClear(gl.GL_COLOR_BUFFER_BIT | gl.GL_DEPTH_BUFFER_BIT | gl.GL_STENCIL_BUFFER_BIT)