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))
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) glfw.window_hint(glfw.SCALE_TO_MONITOR, glfw.TRUE) monitor = None if self.fullscreen: self._set_fullscreen(True) self._window = glfw.create_window(self.width, self.height, self.title, monitor, None) self._has_focus = True if not self._window: glfw.terminate() raise ValueError("Failed to create window") self.cursor = self._cursor 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) else: glfw.swap_interval(0) glfw.set_key_callback(self._window, self.glfw_key_event_callback) glfw.set_cursor_pos_callback(self._window, self.glfw_mouse_event_callback) glfw.set_mouse_button_callback(self._window, self.glfw_mouse_button_callback) glfw.set_scroll_callback(self._window, self.glfw_mouse_scroll_callback) glfw.set_window_size_callback(self._window, self.glfw_window_resize_callback) glfw.set_char_callback(self._window, self.glfw_char_callback) glfw.set_window_focus_callback(self._window, self.glfw_window_focus) glfw.set_cursor_enter_callback(self._window, self.glfw_cursor_enter) glfw.set_window_iconify_callback(self._window, self.glfw_window_iconify) glfw.set_window_close_callback(self._window, self.glfw_window_close) self.init_mgl_context() self.set_default_viewport()
def set_callbacks(self): glfw.set_window_close_callback(self.window, self.window_close_callback) glfw.set_window_size_callback(self.window, self.window_resize_callback) glfw.set_key_callback(self.window, self.keyboard_callback) glfw.set_char_callback(self.window, self.key_typed_callback) glfw.set_mouse_button_callback(self.window, self.mouse_callback) glfw.set_scroll_callback(self.window, self.scroll_callback) glfw.set_cursor_pos_callback(self.window, self.cursor_pos_callback)
def __init__(self, win): """ Init needs a GLFW window handler 'win' to register callbacks """ super().__init__(radians=[1, .5, -.6]) self.distance = 900 self.pos2d = (0, 0) self.mouse = (0, 0) glfw.set_cursor_pos_callback(win, self.on_mouse_move) glfw.set_scroll_callback(win, self.on_scroll)
def __init__(self, win, dist): """ Init needs a GLFW window handler 'win' to register callbacks Distance to see the scene from further away """ super().__init__(distance=dist) self.mouse = (0, 0) glfw.set_cursor_pos_callback(win, self.on_mouse_move) glfw.set_scroll_callback(win, self.on_scroll)
def _register_callbacks(self, window): glfw.set_window_size_callback(window, self._on_set_window_size) glfw.set_window_pos_callback(window, self._on_set_window_pos) glfw.set_framebuffer_size_callback(window, self._on_set_frame_buffer_size) glfw.set_mouse_button_callback(window, self._on_set_mouse_button) glfw.set_cursor_pos_callback(window, self._on_set_cursor_pos) glfw.set_scroll_callback(window, self._on_set_scroll) glfw.set_window_close_callback(window, self._on_set_window_close)
def __init__(self, Name, SizeX, SizeY, MainColor, EdgeColor): if not glfw.init(): return self._mainColor = MainColor self._edgeColor = EdgeColor self.width, self.height = SizeX, SizeY ''' monitors = glfw.get_monitors() if len(monitors) > 1: monitor = monitors[1] else: monitor = glfw.get_primary_monitor() mode = glfw.get_video_mode(monitor) print(mode) glfw.window_hint(glfw.RED_BITS, mode[1][0]) glfw.window_hint(glfw.GREEN_BITS, mode[1][1]) glfw.window_hint(glfw.BLUE_BITS, mode[1][2]) glfw.window_hint(glfw.REFRESH_RATE, mode[2]) glfw.window_hint(glfw.AUTO_ICONIFY, False) #glfw.window_hint(glfw.DECORATED, False) #GLFW_DECORATED self.Window = glfw.create_window(mode[0][0], mode[0][1], Name, monitor, None) glfw.set_window_monitor(self.Window, monitor, 0, 0, mode[0][0], mode[0][1], mode[2]) #print(mode[0][0], mode[0][1], mode[2]) ''' glfw.window_hint(glfw.RESIZABLE, GL_FALSE) self.Window = glfw.create_window(self.width, self.height, Name, None, None) glfw.make_context_current(self.Window) #print(monitors, len(monitors)) if not self.Window: glfw.terminate() return self.Keys = [False] * 1024 self.KeyPressed = False self.MousePos = np.zeros([2]) self.MouseButtons = np.zeros([5]) self.MouseScroll = 0 self.LeftArrow = False self.RightArrow = False self.MouseEventFlag = False self._lastColor = None self.NewDragNDrop = False self.CurrentDragNDropPath = "Drag here" glfw.set_drop_callback(self.Window, self.drop_callback) glfw.set_window_size_callback(self.Window, self.window_resize) glfw.set_key_callback(self.Window, self.key_callback) glfw.set_mouse_button_callback(self.Window, self.mouse_button_callback) glfw.set_cursor_pos_callback(self.Window, self.cursor_pos_callback) glfw.set_scroll_callback(self.Window, self.mouse_scroll_callback) glClearColor(0.3, 0.1, 0.1, 1.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)
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)
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: monitor = glfw.get_primary_monitor() mode = glfw.get_video_mode(monitor) self._width, self._height = mode.size.width, mode.size.height 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.glfw_key_event_callback) glfw.set_cursor_pos_callback(self._window, self.glfw_mouse_event_callback) glfw.set_mouse_button_callback(self._window, self.glfw_mouse_button_callback) glfw.set_scroll_callback(self._window, self.glfw_mouse_scroll_callback) glfw.set_window_size_callback(self._window, self.glfw_window_resize_callback) glfw.set_char_callback(self._window, self.glfw_char_callback) self.init_mgl_context() self.set_default_viewport()
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) def on_key(window, key, scancode, action, mods): io = self.io if action == glfw.PRESS: io.keys_down[key] = True elif action == glfw.RELEASE: io.keys_down[key] = False io.key_ctrl = (io.keys_down[glfw.KEY_LEFT_CONTROL] or io.keys_down[glfw.KEY_RIGHT_CONTROL]) io.key_alt = (io.keys_down[glfw.KEY_LEFT_ALT] or io.keys_down[glfw.KEY_RIGHT_ALT]) io.key_shift = (io.keys_down[glfw.KEY_LEFT_SHIFT] or io.keys_down[glfw.KEY_RIGHT_SHIFT]) io.key_super = (io.keys_down[glfw.KEY_LEFT_SUPER] or io.keys_down[glfw.KEY_RIGHT_SUPER]) self.on_key(window, key, scancode, action, mods) def on_char(window, char): io = imgui.get_io() if 0 < char < 0x10000: io.add_input_character(char) 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) glfw.set_key_callback(window, on_key) glfw.set_char_callback(window, on_char)
def __init__(self, *args, **kwargs): super().__init__() global selfstatic, start_t, frame_times width = 800 height = 600 self.width = width self.height = height viewport = (width, height) width, height = 800, 600 window = glfw.create_window(width, height, "OpenGL & Python", None, None) if not window: print('error') glfw.terminate() return self.window = window #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) glfw.make_context_current(self.window) glfw.set_key_callback(self.window, self.key_event) glfw.set_cursor_pos_callback(self.window, self.handle_mouse_move) glfw.set_mouse_button_callback(self.window, self.handle_mouse_button) glfw.set_scroll_callback(self.window, self.handle_scroll) glfw.set_window_size_callback(self.window, self.onSize) frame_times = [] start_t = time.time() map = WorldMap() selected_obj = 0 zpos = 5 rotate = move = False oo = map.objs[selected_obj] storeit = None self.map = map self.selected_obj = selected_obj self.zpos = zpos self.rotate = rotate self.move = move self.oo = oo self.storeit = storeit selfstatic = self
def __init__( self, controller: BaseController, *, hint: Optional[GLContextHint] = None, title: str = 'glfw', width: int = 0, height: int = 0, is_maximized: bool = False, config: Optional[WindowConfig] = None ): width = width or (config.width if config else 1280) height = height or (config.height if config else 720) is_maximized = is_maximized or ( config.is_maximized if config else False) self.controller = controller self.mouse_x = 0 self.mouse_y = 0 if not glfw.init(): logger.error("Could not initialize OpenGL context") return if hint: # OS X supports only forward-compatible core profiles from 3.2 glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, hint.major) glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, hint.minor) if hint.core_profile: glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE) else: glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_FORWARD_COMPAT) # Create a windowed mode window and its OpenGL context self.window = glfw.create_window( width, height, title, None, None ) if not self.window: logger.error("Could not initialize Window") return if is_maximized: glfw.maximize_window(self.window) glfw.make_context_current(self.window) glfw.swap_interval(1) glfw.set_key_callback(self.window, self.keyboard_callback) glfw.set_cursor_pos_callback(self.window, self.cursor_calblack) glfw.set_mouse_button_callback(self.window, self.mouse_callback) glfw.set_window_size_callback(self.window, self.resize_callback) glfw.set_char_callback(self.window, self.char_callback) glfw.set_scroll_callback(self.window, self.scroll_callback) self.controller.onResize(width, height)
def init_input(self): self.is_drag = False self.drag_prepos = vec2(0.0, 0.0) self.camera_pos = vec3(0.0, 0.0, -120.0) view = lookAt(self.camera_pos, ZERO, UP) * vec4(0.0, 0.0, 1.0, 1.0) print(view) self.camera_rot = quat(1.0, 0.0, 0.0, 0.0) help(quat) glfw.set_mouse_button_callback(self.window, self.on_mouse_button) glfw.set_cursor_pos_callback(self.window, self.on_mouse_pos) glfw.set_window_size_callback(self.window, self.on_window_size) glfw.set_scroll_callback(self.window, self.on_scroll)
def init_window(self): glfw.init() self.window = glfw.create_window(*self.resolution, 'PyGL', None, None) glfw.make_context_current(self.window) glfw.set_window_size_callback(self.window, self.resize) glfw.set_key_callback(self.window, self.keyboard_input) glfw.set_scroll_callback(self.window, self.scroll_input) glfw.set_cursor_pos_callback(self.window, self.mouse_position_input) glClearColor(0, 0, 0, 1) self.target_frame_time = 1 / self.target_fps self.ui = UI(self) self.logger.debug('Window initialized')
def __init__(self, window): super().__init__(window) with window.context.glfw as window: glfw.set_cursor_pos_callback(window, self.__master_cursor_pos_callback) glfw.set_cursor_enter_callback(window, self.__master_cursor_enter_callback) glfw.set_mouse_button_callback(window, self.__master_mouse_button_callback) glfw.set_scroll_callback(window, self.__master_mouse_scroll_callback) self.window.append_predraw_callback(self.__set_cursor_pos_perframe) self.__pos_perframe = Vec(0, 0, 0) self.__pos_prev = Vec(0, 0, 0) self.__pos_instant = Vec(0, 0, 0) self.__accel = Vec(0, 0, 0)
def open_window(self): if not self.window: self.input = {"button": None, "mouse": (0, 0)} # get glfw started if self.run_independently: glfw.init() glfw.window_hint(glfw.SCALE_TO_MONITOR, glfw.TRUE) self.window = glfw.create_window(self.window_size[0], self.window_size[1], self.name, None, None) else: self.window = glfw.create_window( self.window_size[0], self.window_size[1], self.name, None, glfw.get_current_context(), ) self.other_window = glfw.get_current_context() glfw.make_context_current(self.window) glfw.swap_interval(0) glfw.set_window_pos(self.window, window_position_default[0], window_position_default[1]) # Register callbacks window glfw.set_framebuffer_size_callback(self.window, self.on_resize) glfw.set_window_iconify_callback(self.window, self.on_iconify) glfw.set_key_callback(self.window, self.on_window_key) glfw.set_char_callback(self.window, self.on_window_char) glfw.set_mouse_button_callback(self.window, self.on_window_mouse_button) glfw.set_cursor_pos_callback(self.window, self.on_pos) glfw.set_scroll_callback(self.window, self.on_scroll) # get glfw started if self.run_independently: glutils.init() self.basic_gl_setup() self.sphere = glutils.Sphere(20) self.glfont = fs.Context() self.glfont.add_font("opensans", get_opensans_font_path()) self.glfont.set_size(18) self.glfont.set_color_float((0.2, 0.5, 0.9, 1.0)) self.on_resize(self.window, *glfw.get_framebuffer_size(self.window)) glfw.make_context_current(self.other_window)
def open_window(self): if not self._window: monitor = None # open with same aspect ratio as surface surface_aspect_ratio = (self.surface.real_world_size["x"] / self.surface.real_world_size["y"]) win_h = 640 win_w = int(win_h / surface_aspect_ratio) self._window = glfw.create_window( win_h, win_w, "Reference Surface: " + self.surface.name, monitor, glfw.get_current_context(), ) glfw.set_window_pos( self._window, self.window_position_default[0], self.window_position_default[1], ) self.trackball = gl_utils.trackball.Trackball() self.input = {"down": False, "mouse": (0, 0)} # Register callbacks glfw.set_framebuffer_size_callback(self._window, self.on_resize) glfw.set_key_callback(self._window, self.on_window_key) glfw.set_window_close_callback(self._window, self.on_close) glfw.set_mouse_button_callback(self._window, self.on_window_mouse_button) glfw.set_cursor_pos_callback(self._window, self.on_pos) glfw.set_scroll_callback(self._window, self.on_scroll) self.on_resize(self._window, *glfw.get_framebuffer_size(self._window)) # gl_state settings active_window = glfw.get_current_context() glfw.make_context_current(self._window) gl_utils.basic_gl_setup() gl_utils.make_coord_system_norm_based() # refresh speed settings glfw.swap_interval(0) glfw.make_context_current(active_window)
def __init__(self, window, attach_callbacks=True): super(GlfwRenderer, self).__init__() self.window = window if attach_callbacks: glfw.set_key_callback(self.window, self.keyboard_callback) glfw.set_cursor_pos_callback(self.window, self.mouse_callback) glfw.set_window_size_callback(self.window, self.resize_callback) glfw.set_char_callback(self.window, self.char_callback) glfw.set_scroll_callback(self.window, self.scroll_callback) self.io.display_size = glfw.get_framebuffer_size(self.window) self._map_keys() self._gui_time = None
def __init__(self, scene): super().__init__() glfw.set_mouse_button_callback(scene.window, self.mouse_down_callback) glfw.set_scroll_callback(scene.window, self.scroll_callback) glfw.set_cursor_pos_callback(scene.window, self.mouse_move_callback) # mouse self.lastX, self.lastY = scene.width / 2, scene.height / 2 self.first_mouse = True self.is_mouse_left_down = False self.cached_mouse_move_X = 0 self.cached_mouse_move_Y = 0 self.cached_scroll_num = 0 self.transforms = []
def prepare_window(): window = glfw.create_window(SCR_WIDTH, SCR_HEIGHT, "LearnOpenGL", None, None) glfw.make_context_current(window) glfw.set_framebuffer_size_callback(window, framebuffer_size_callback) glfw.set_cursor_pos_callback(window, mouse_callback) glfw.set_scroll_callback(window, scroll_callback) # tell GLFW to capture our mouse glfw.set_input_mode(window, glfw.CURSOR, glfw.CURSOR_DISABLED) width, height = glfw.get_framebuffer_size(window) glClearColor(0.2, 0.3, 0.3, 1.) glEnable(GL_DEPTH_TEST) return window
def add_scroll_callback(viewer: MjViewerBasic, callback): assert callable(callback) import glfw def scroll_callback(window, x_offset, y_offset): mod_shift = glfw.get_key(window, glfw.KEY_LEFT_SHIFT) == glfw.PRESS or \ glfw.get_key(window, glfw.KEY_RIGHT_SHIFT) == glfw.PRESS if mod_shift: scroll_callback.pos -= 0.05 * y_offset callback(scroll_callback.pos) else: viewer._scroll_callback(window, x_offset, y_offset) scroll_callback.pos = 0.0 glfw.set_scroll_callback(viewer.window, scroll_callback)
def __init__(self, config): Display.__init__(self, config) self.key, self.mouse = config.key, config.mouse self.mouspeed = config.mouspeed self.zmspeed = config.zmspeed glfw.set_input_mode(self.window, glfw.CURSOR, glfw.CURSOR_DISABLED) glfw.set_input_mode(self.window, glfw.STICKY_KEYS, True) glfw.set_cursor_pos_callback(self.window, self.look) glfw.set_scroll_callback(self.window, self.zoom) glfw.set_mouse_button_callback(self.window, self.shoot) try: if glfw.raw_mouse_motion_supported(): glfw.set_input_mode(self.window, glfw.RAW_MOUSE_MOTION, True) except AttributeError: warn(GLFW_VER_WARN, category=RuntimeWarning)
def main(): if not glfw.init(): return window = glfw.create_window(1028, 1028, '2017030155-class1', None, None) if not window: glfw.terminate() return glfw.make_context_current(window) #glfw.set_key_callback(window, key_callback) glfw.set_mouse_button_callback(window, button_callback) glfw.set_scroll_callback(window, scroll_callback) while not glfw.window_should_close(window): glfw.poll_events() render() glfw.swap_buffers(window) glfw.terminate()
def __init__(self): # save current working directory cwd = os.getcwd() # Initialize the library if not glfw.init(): return # restore cwd os.chdir(cwd) # buffer hints glfw.window_hint(glfw.DEPTH_BITS, 32) # make a window self.width, self.height = 640, 480 self.aspect = self.width / float(self.height) self.window = glfw.create_window(self.width, self.height, "2D Graphics", None, None) if not self.window: glfw.terminate() return # Make the window's context current glfw.make_context_current(self.window) # set window callbacks glfw.set_mouse_button_callback(self.window, self.onMouseButton) glfw.set_cursor_pos_callback(self.window, self.mouseMoved) glfw.set_key_callback(self.window, self.onKeyboard) glfw.set_window_size_callback(self.window, self.onSize) glfw.set_scroll_callback(self.window, self.onScroll) # cursor position self.currentPosX = 0 self.currentPosY = 0 self.lastPosX = 0 self.lastPosY = 0 # create 3D self.scene = Scene(objFile, self.width, self.height) # exit flag self.exitNow = False
def main(): glfw_init() window = glfw_create_window() set_gl_options() print("GL version: %s" % glGetString(GL_VERSION)) # A bit hacky? global INPUT INPUT = Input(window) glfw.set_framebuffer_size_callback(window, framebuffer_size_callback) glfw.set_cursor_pos_callback(window, INPUT.mouse_callback) glfw.set_scroll_callback(window, INPUT.scroll_callback) glfw.set_key_callback(window, INPUT.key_callback) game_manager = GameManager() fps = FPSCounter() last_time = time.time() fov = 45.0 while not glfw.window_should_close(window): fps.frame() now = time.time() dt = now - last_time last_time = now t = now glfw.poll_events() game_manager.update(dt) glClearColor(0.0, 0.0, 0.0, 1.0) glClear(GL_COLOR_BUFFER_BIT) game_manager.render() glfw.swap_buffers(window) if INPUT.key_down(glfw.KEY_Q): glfw.set_window_should_close(window, True) INPUT.update_end() glfw.terminate() return
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 wire_glfw_to_imgui_events(self): def resize(window, width, height): self.gl.viewport = (0, 0, width, height) imgui.get_io().display_size = width, height def on_cursor_pos(window, x, y): imgui.get_io().mouse_pos = x, y def on_mouse_button(window, button, action, mods): imgui.get_io().mouse_down[button] = action def on_scroll(window, scroll_x, scroll_y): imgui.get_io().mouse_wheel = scroll_y glfw.set_window_size_callback(self.window, resize) glfw.set_cursor_pos_callback(self.window, on_cursor_pos) glfw.set_mouse_button_callback(self.window, on_mouse_button) glfw.set_scroll_callback(self.window, on_scroll)
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 main(): if not glfw.init(): return window = glfw.create_window(640,640,'Basic OpenGL viewer', None,None) if not window: glfw.terminate() return glfw.make_context_current(window) while not glfw.window_should_close(window): glfw.poll_events() render() glfw.set_scroll_callback(window, scroll_callback) glfw.set_mouse_button_callback(window, button_callback) glfw.set_cursor_pos_callback(window, cursor_callback) glfw.swap_buffers(window) glfw.terminate()
def main(): if not glfw.init(): return window = glfw.create_window(700,700,'2016025478', None,None) if not window: glfw.terminate() return 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) glfw.terminate()
def __init__(self, model, data): self._gui_lock = Lock() self._button_left_pressed = False self._button_right_pressed = False self._last_mouse_x = 0 self._last_mouse_y = 0 self._paused = False self._transparent = False self._contacts = False self._render_every_frame = True self._image_idx = 0 self._image_path = "/tmp/frame_%07d.png" self._time_per_render = 1 / 60.0 self._run_speed = 1.0 self._loop_count = 0 self._advance_by_one_step = False self._hide_menu = False # glfw init glfw.init() width, height = glfw.get_video_mode(glfw.get_primary_monitor()).size self.window = glfw.create_window(width // 2, height // 2, "mujoco", None, None) glfw.make_context_current(self.window) glfw.swap_interval(1) framebuffer_width, framebuffer_height = glfw.get_framebuffer_size( self.window) window_width, _ = glfw.get_window_size(self.window) self._scale = framebuffer_width * 1.0 / window_width # set callbacks 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) # get viewport self.viewport = mujoco.MjrRect(0, 0, framebuffer_width, framebuffer_height) super().__init__(model, data, offscreen=False)
def main(): if not glfw.init(): return window = glfw.create_window(800, 800, 'my_viewer', None, None) if not window: glfw.terminate() return glfw.set_key_callback(window, key_callback) glfw.set_mouse_button_callback(window, button_callback) glfw.make_context_current(window) glfw.set_scroll_callback(window, scroll_callback) glfw.set_drop_callback(window, drop_callback) while not glfw.window_should_close(window): glfw.poll_events() render() glfw.swap_buffers(window) glfw.terminate()
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)
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)
#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()
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()