def opengl_init(): global window # Initialize the library if not glfw.init(): print("Failed to initialize GLFW\n",file=sys.stderr) return False glfw.window_hint(glfw.SAMPLES, 4) 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) # Open Window and create its OpenGL context window = glfw.create_window(1024, 768, "Tutorial 04", None, None) #(in the accompanying source code this variable will be global) if not window: print("Failed to open GLFW window. If you have an Intel GPU, they are not 3.3 compatible. Try the 2.1 version of the tutorials.\n",file=sys.stderr) glfw.terminate() return False # Initialize GLEW glfw.make_context_current(window) glewExperimental = True # GLEW is a framework for testing extension availability. Please see tutorial notes for # more information including why can remove this code. if glewInit() != GLEW_OK: print("Failed to initialize GLEW\n",file=sys.stderr); return False return True
def opengl_init(): global window # Initialize the library if not glfw.init(): print("Failed to initialize GLFW\n",file=sys.stderr) return False # Open Window and create its OpenGL context window = glfw.create_window(1024, 768, "VAO Test", None, None) #(in the accompanying source code this variable will be global) glfw.window_hint(glfw.SAMPLES, 4) 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) if not window: print("Failed to open GLFW window. If you have an Intel GPU, they are not 3.3 compatible. Try the 2.1 version of the tutorials.\n",file=sys.stderr) glfw.terminate() return False # Initialize GLEW glfw.make_context_current(window) glewExperimental = True # !!NOTE: The most recent GLEW package for python is 8 years old, ARB functionality # is available in Pyopengl natively. if glewInit() != GLEW_OK: print("Failed to initialize GLEW\n",file=sys.stderr); return False return True
def draw_a_triangle(): if not glfw.init(): return -1; # Create a windowed mode window and its OpenGL context glfw.window_hint(glfw.SAMPLES, 4) 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) window = glfw.create_window(1024, 768, "Triangle", None, None); if window == None: glfw.terminate() return -1 # Make the window's context current glfw.make_context_current(window) # glfw.Experimental = True glClearColor(0.0, 0.1, 0.2, 1.0) flatten = lambda l: [u for t in l for u in t] vertices = [(-1.0, -1.0, 0.0), (1.0, -1.0, 0.0), (0.0, 1.0, 0.0)] indices = range(3) vao_handle = glGenVertexArrays(1) glBindVertexArray(vao_handle) program_handle = tools.load_program("../shader/simple.v.glsl", "../shader/simple.f.glsl") f_vertices = flatten(vertices) c_vertices = (c_float*len(f_vertices))(*f_vertices) v_buffer = glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, v_buffer) glBufferData(GL_ARRAY_BUFFER, c_vertices, GL_STATIC_DRAW) glEnableVertexAttribArray(0) glBindBuffer(GL_ARRAY_BUFFER, v_buffer) glVertexAttribPointer(0, #glGetAttribLocation(program_handle, "vertexPosition_modelspace"), 3, GL_FLOAT, False, 0, None) # Loop until the user closes the window while not glfw.window_should_close(window): # Render here glClear(GL_COLOR_BUFFER_BIT) glUseProgram(program_handle) glDrawArrays(GL_TRIANGLES, 0, 3) glDisableVertexAttribArray(vao_handle) # Swap front and back buffers glfw.swap_buffers(window) # Poll for and process events glfw.poll_events() glfw.terminate(); pass
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()
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)
def main(): # Initialize the library if not glfw.init(): return # Open Window and create its OpenGL context window = glfw.create_window(1024, 768, "Tutorial 01", None, None) # glfw.window_hint(glfw.SAMPLES, 4) 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) if not window: print("Failed to open GLFW window. If you have an Intel GPU, they are not 3.3 compatible. Try the 2.1 version of the tutorials.\n",file=sys.stderr) glfw.terminate() return # Initialize GLEW glfw.make_context_current(window) glewExperimental = True # GLEW is a framework for testing extension availability. Please see tutorial notes for # more information including why can remove this code. if glewInit() != GLEW_OK: print("Failed to initialize GLEW\n",file=sys.stderr); return glfw.set_input_mode(window,glfw.STICKY_KEYS,True) # Loop until the user closes the window #while not glfw.window_should_close(window): while glfw.get_key(window,glfw.KEY_ESCAPE) != glfw.PRESS and not glfw.window_should_close(window): # Draw nothing sucker # Swap front and back buffers glfw.swap_buffers(window) # Poll for and process events glfw.poll_events() glfw.terminate()
def __init__(self, width=800, height=600, title="aiv"): glfw.init() glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 3) glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 3) glfw.window_hint(glfw.OPENGL_FORWARD_COMPAT, 1) glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE) self.window = glfw.create_window(width, height, title, None, None) glfw.make_context_current(self.window) glfw.swap_interval(1) self.time = glfw.get_time() self.delta_time = 0 self.aspect_ratio = float(width) / float(height)
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
def init(): version_string = glfw.get_version_string() cwd = os.getcwd() print("Starting GLFW") print(version_string) # Initialize the library if not glfw.init(): print("fail glfw") return os.chdir(cwd) # make a window # glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE) 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)
def setup(): import glfw import pyngl if not glfw.init(): print "error with glfw init" sys.exit() glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 4) glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 1) glfw.window_hint(glfw.OPENGL_FORWARD_COMPAT, True) glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE) window = glfw.create_window(640, 480, "", None, None) if not window: glfw.terminate() return # Make the window's context current glfw.make_context_current(window) pyngl.NGLInit.instance().setCommunicationMode(pyngl.CommunicationMode.STDOUT);
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, size, title, gl_version): if not glfw.init(): raise WindowError('glfw.init failed') glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, gl_version[0]) glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, gl_version[1]) glfw.window_hint(glfw.DOUBLEBUFFER, True) self._wnd = glfw.create_window(*size, title, None, None) if not self._wnd: raise WindowError('glfw.create_window failed') self._init_events() self._ctx = None
def init_window(): # Initialize the library if not glfw.init(): return None glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 3) glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 3) glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE) glfw.window_hint(glfw.RESIZABLE, False) # Create a windowed mode window and its OpenGL context window = glfw.create_window(WINDOW_WIDTH, WINDOW_HEIGHT, "OpenGL Example", None, None) if not window: glfw.terminate() return None # Make the window's context current glfw.make_context_current(window) glfw.set_key_callback(window, key_cb) return window
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
def init_gl(self): if self._is_initialized: return # only initialize once if not glfw.init(): raise Exception("GLFW Initialization error") # Get OpenGL 4.1 context glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 4) glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 1) glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE) # Double buffered screen mirror stalls VR headset rendering, # So use single-buffering glfw.window_hint(glfw.DOUBLEBUFFER, False) glfw.swap_interval(0) self.window = glfw.create_window(self.renderer.window_size[0], self.renderer.window_size[1], self.title, None, None) if self.window is None: glfw.terminate() raise Exception("GLFW window creation error") glfw.set_key_callback(self.window, self.key_callback) glfw.make_context_current(self.window) if self.renderer is not None: self.renderer.init_gl() self._is_initialized = True
def __init__(self, renderer, title="GLFW test"): "Creates an OpenGL context and a window, and acquires OpenGL resources" self.renderer = renderer self.title = title self._is_initialized = False # keep track of whether self.init_gl() has been called if not glfw.init(): raise Exception("GLFW Initialization error") # Get OpenGL 4.1 context glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 4) glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 1) glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE) # Double buffered screen mirror stalls VR headset rendering, # So use single-buffering glfw.window_hint(glfw.DOUBLEBUFFER, False) self.window = glfw.create_window(self.renderer.window_size[0], self.renderer.window_size[1], self.title, None, None) if self.window is None: glfw.terminate() raise Exception("GLFW window creation error") glfw.set_key_callback(self.window, self.key_callback) glfw.make_context_current(self.window) glfw.swap_interval(0)
def main(): # init glfw glfw.init() # make a window glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE) glfw.window_hint(glfw.OPENGL_VERSION_MAJOR, 3) glfw.window_hint(glfw.OPENGL_VERSION_MINOR, 3) glfw.open_window(640, 480, 8, 8, 8, 8, 0, 0, glfw.WINDOW) initialize() while glfw.GetWindowParam(glfw.OPENED): render() glfw.Terminate()
def initMuJoCo(filename, width2, height): ''' load model, init simulation and rendering ''' global window, sim, ctx assert glfw.init(), 'Could not initialize GLFW' glfw.window_hint(glfw.SAMPLES, 0) glfw.window_hint(glfw.DOUBLEBUFFER, True) glfw.window_hint(glfw.RESIZABLE, 0) window = glfw.create_window(width2 // 4, height // 2, "mjvive.py", None, None) assert window, "Could not create GLFW window" glfw.make_context_current(window) glfw.swap_interval(0) # GLEW init required in C++, not in Python sim = MjSim(load_model_from_xml(open(filename).read())) sim.forward() sim.model.vis.global_.offwidth = width2 sim.model.vis.global_.offheight = height sim.model.vis.quality.offsamples = 8 ctx = MjRenderContext(sim) ctx.scn.enabletransform = 1 ctx.scn.translate[1:3] = -0.5 ctx.scn.rotate[0:2] = math.cos(-0.25 * math.pi), math.sin(-0.25 * math.pi) ctx.scn.scale = 1 ctx.scn.stereo = STEREO_SIDEBYSIDE
def render_snippet( source, file_path, title="", width=200, height=200, auto_layout=False, output_dir='.', click=None, ): _patch_imgui() # Little shim that filters out the new_frame and render commands # so we can use them in code examples. It's simply a hoax. lines = [ line if all([ "imgui.new_frame()" not in line, "imgui.render()" not in line, "imgui.end_frame()" not in line ]) else "" for line in source.split('\n') ] source = "\n".join(lines) code = compile(source, '<str>', 'exec') window_name = "minimal ImGui/GLFW3 example" if not glfw.init(): print("Could not initialize OpenGL context") exit(1) # OS X supports only forward-compatible core profiles from 3.2 glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 3) glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 3) glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE) glfw.window_hint(glfw.OPENGL_FORWARD_COMPAT, gl.GL_TRUE) # note: creating context without window is tricky so made window invisible glfw.window_hint(glfw.VISIBLE, False) window = glfw.create_window(int(width), int(height), window_name, None, None) glfw.make_context_current(window) if not window: glfw.terminate() print("Could not initialize Window") exit(1) impl = GlfwRenderer(window) glfw.poll_events() # render target for framebuffer texture = gl.glGenTextures(1) gl.glBindTexture(gl.GL_TEXTURE_2D, texture) gl.glTexImage2D(gl.GL_TEXTURE_2D, 0, gl.GL_RGBA, width, height, 0, gl.GL_RGB, gl.GL_UNSIGNED_BYTE, None) gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MAG_FILTER, gl.GL_NEAREST) gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MIN_FILTER, gl.GL_NEAREST) # create new framebuffer offscreen_fb = gl.glGenFramebuffers(1) gl.glBindFramebuffer(gl.GL_FRAMEBUFFER, offscreen_fb) # attach texture to framebuffer gl.glFramebufferTexture2D(gl.GL_FRAMEBUFFER, gl.GL_COLOR_ATTACHMENT0, gl.GL_TEXTURE_2D, texture, 0) # note: Clicking simulation is hacky as f**k and it # requires at least three frames to be rendered: # * 1st with mouse in position but without button pressed. # * 2nd in roughly same posiotion of mouse to turn on hover # mouse button starts to press but still does not trigger click. # * 3rd in the same position with button pressed still to finally # trigger the "clicked" state. # note: If clicking simulation is not required we draw only one frame. for m_state in ([None] if not click else [False, True, True]): # note: Mouse click MUST be simulated before new_frame call! if click: impl.io.mouse_draw_cursor = True simulate_click(click[0], click[1], m_state) else: # just make sure mouse state is clear _clear_mouse() impl.process_inputs() imgui.new_frame() with imgui.styled(imgui.STYLE_ALPHA, 1): imgui.core.set_next_window_size(0, 0) if auto_layout: imgui.set_next_window_size(width - 10, height - 10) imgui.set_next_window_position(impl.io.DisplaySize.x * 0.5, implio.DisplaySize.y * 0.5, 1, pivot_x=0.5, pivot_y=0.5) exec(code, locals(), globals()) gl.glBindFramebuffer(gl.GL_FRAMEBUFFER, offscreen_fb) gl.glClearColor(1, 1, 1, 0) gl.glClear(gl.GL_COLOR_BUFFER_BIT) imgui.render() # retrieve pixels from framebuffer and write to file pixels = gl.glReadPixels(0, 0, width, height, gl.GL_RGBA, gl.GL_UNSIGNED_BYTE) image = Image.frombytes('RGBA', (width, height), pixels) # note: glReadPixels returns lines "bottom to top" but PIL reads bytes # top to bottom image = image.transpose(Image.FLIP_TOP_BOTTOM) image.save(os.path.join(output_dir, file_path)) glfw.terminate()
def 超融合(): glfw.window_hint(glfw.DECORATED, False) glfw.window_hint(glfw.TRANSPARENT_FRAMEBUFFER, True) glfw.window_hint(glfw.FLOATING, True)
def player(rec_dir, ipc_pub_url, ipc_sub_url, ipc_push_url, user_dir, app_version, debug): # general imports from time import sleep import logging from glob import glob from time import time, strftime, localtime # networking import zmq import zmq_tools import numpy as np # zmq ipc setup zmq_ctx = zmq.Context() ipc_pub = zmq_tools.Msg_Dispatcher(zmq_ctx, ipc_push_url) notify_sub = zmq_tools.Msg_Receiver(zmq_ctx, ipc_sub_url, topics=("notify", )) # log setup logging.getLogger("OpenGL").setLevel(logging.ERROR) logger = logging.getLogger() logger.handlers = [] logger.setLevel(logging.NOTSET) logger.addHandler(zmq_tools.ZMQ_handler(zmq_ctx, ipc_push_url)) # create logger for the context of this function logger = logging.getLogger(__name__) try: from background_helper import IPC_Logging_Task_Proxy IPC_Logging_Task_Proxy.push_url = ipc_push_url from tasklib.background.patches import IPCLoggingPatch IPCLoggingPatch.ipc_push_url = ipc_push_url # imports from file_methods import Persistent_Dict, next_export_sub_dir from OpenGL.GL import GL_COLOR_BUFFER_BIT # display import glfw from gl_utils import GLFWErrorReporting GLFWErrorReporting.set_default() # check versions for our own depedencies as they are fast-changing from pyglui import __version__ as pyglui_version from pyglui import ui, cygl from pyglui.cygl.utils import Named_Texture, RGBA import gl_utils # capture from video_capture import File_Source # helpers/utils from version_utils import parse_version from methods import normalize, denormalize, delta_t, get_system_info import player_methods as pm from pupil_recording import PupilRecording from csv_utils import write_key_value_file from hotkey import Hotkey # Plug-ins from plugin import Plugin, Plugin_List, import_runtime_plugins from plugin_manager import Plugin_Manager from vis_circle import Vis_Circle from vis_cross import Vis_Cross from vis_polyline import Vis_Polyline from vis_light_points import Vis_Light_Points from vis_watermark import Vis_Watermark from vis_fixation import Vis_Fixation from seek_control import Seek_Control from surface_tracker import Surface_Tracker_Offline # from marker_auto_trim_marks import Marker_Auto_Trim_Marks from fixation_detector import Offline_Fixation_Detector from log_display import Log_Display from annotations import Annotation_Player from raw_data_exporter import Raw_Data_Exporter from log_history import Log_History from pupil_producers import ( DisabledPupilProducer, Pupil_From_Recording, Offline_Pupil_Detection, ) from gaze_producer.gaze_from_recording import GazeFromRecording from gaze_producer.gaze_from_offline_calibration import ( GazeFromOfflineCalibration, ) from pupil_detector_plugins.detector_base_plugin import PupilDetectorPlugin from system_graphs import System_Graphs from system_timelines import System_Timelines from blink_detection import Offline_Blink_Detection from audio_playback import Audio_Playback from video_export.plugins.imotions_exporter import iMotions_Exporter from video_export.plugins.eye_video_exporter import Eye_Video_Exporter from video_export.plugins.world_video_exporter import World_Video_Exporter from head_pose_tracker.offline_head_pose_tracker import ( Offline_Head_Pose_Tracker, ) from video_capture import File_Source from video_overlay.plugins import Video_Overlay, Eye_Overlay from pupil_recording import ( assert_valid_recording_type, InvalidRecordingException, ) assert parse_version(pyglui_version) >= parse_version( "1.29"), "pyglui out of date, please upgrade to newest version" process_was_interrupted = False def interrupt_handler(sig, frame): import traceback trace = traceback.format_stack(f=frame) logger.debug(f"Caught signal {sig} in:\n" + "".join(trace)) nonlocal process_was_interrupted process_was_interrupted = True signal.signal(signal.SIGINT, interrupt_handler) runtime_plugins = import_runtime_plugins( os.path.join(user_dir, "plugins")) runtime_plugins = [ p for p in runtime_plugins if not issubclass(p, PupilDetectorPlugin) ] system_plugins = [ Log_Display, Seek_Control, Plugin_Manager, System_Graphs, System_Timelines, Audio_Playback, ] user_plugins = [ Vis_Circle, Vis_Fixation, Vis_Polyline, Vis_Light_Points, Vis_Cross, Vis_Watermark, Eye_Overlay, Video_Overlay, Offline_Fixation_Detector, Offline_Blink_Detection, Surface_Tracker_Offline, Raw_Data_Exporter, Annotation_Player, Log_History, DisabledPupilProducer, Pupil_From_Recording, Offline_Pupil_Detection, GazeFromRecording, GazeFromOfflineCalibration, World_Video_Exporter, iMotions_Exporter, Eye_Video_Exporter, Offline_Head_Pose_Tracker, ] + runtime_plugins plugins = system_plugins + user_plugins def consume_events_and_render_buffer(): gl_utils.glViewport(0, 0, *g_pool.camera_render_size) g_pool.capture.gl_display() for p in g_pool.plugins: p.gl_display() gl_utils.glViewport(0, 0, *window_size) try: clipboard = glfw.get_clipboard_string(main_window).decode() except (AttributeError, glfw.GLFWError): # clipbaord is None, might happen on startup clipboard = "" g_pool.gui.update_clipboard(clipboard) user_input = g_pool.gui.update() if user_input.clipboard and user_input.clipboard != clipboard: # only write to clipboard if content changed glfw.set_clipboard_string(main_window, user_input.clipboard) for b in user_input.buttons: button, action, mods = b x, y = glfw.get_cursor_pos(main_window) pos = gl_utils.window_coordinate_to_framebuffer_coordinate( main_window, x, y, cached_scale=None) pos = normalize(pos, g_pool.camera_render_size) pos = denormalize(pos, g_pool.capture.frame_size) for plugin in g_pool.plugins: if plugin.on_click(pos, button, action): break for key, scancode, action, mods in user_input.keys: for plugin in g_pool.plugins: if plugin.on_key(key, scancode, action, mods): break for char_ in user_input.chars: for plugin in g_pool.plugins: if plugin.on_char(char_): break glfw.swap_buffers(main_window) # Callback functions def on_resize(window, w, h): nonlocal window_size nonlocal content_scale if w == 0 or h == 0: return # Always clear buffers on resize to make sure that there are no overlapping # artifacts from previous frames. gl_utils.glClear(GL_COLOR_BUFFER_BIT) gl_utils.glClearColor(0, 0, 0, 1) content_scale = gl_utils.get_content_scale(window) framebuffer_scale = gl_utils.get_framebuffer_scale(window) g_pool.gui.scale = content_scale window_size = w, h g_pool.camera_render_size = w - int( icon_bar_width * g_pool.gui.scale), h g_pool.gui.update_window(*window_size) g_pool.gui.collect_menus() for p in g_pool.plugins: p.on_window_resize(window, *g_pool.camera_render_size) # Minimum window size required, otherwise parts of the UI can cause openGL # issues with permanent effects. Depends on the content scale, which can # potentially be dynamically modified, so we re-adjust the size limits every # time here. min_size = int(2 * icon_bar_width * g_pool.gui.scale / framebuffer_scale) glfw.set_window_size_limits( window, min_size, min_size, glfw.DONT_CARE, glfw.DONT_CARE, ) # Needed, to update the window buffer while resizing consume_events_and_render_buffer() def on_window_key(window, key, scancode, action, mods): g_pool.gui.update_key(key, scancode, action, mods) def on_window_char(window, char): g_pool.gui.update_char(char) def on_window_mouse_button(window, button, action, mods): g_pool.gui.update_button(button, action, mods) def on_pos(window, x, y): x, y = gl_utils.window_coordinate_to_framebuffer_coordinate( window, x, y, cached_scale=None) g_pool.gui.update_mouse(x, y) pos = x, y pos = normalize(pos, g_pool.camera_render_size) # Position in img pixels pos = denormalize(pos, g_pool.capture.frame_size) for p in g_pool.plugins: p.on_pos(pos) def on_scroll(window, x, y): g_pool.gui.update_scroll(x, y * scroll_factor) def on_drop(window, paths): for path in paths: try: assert_valid_recording_type(path) _restart_with_recording(path) return except InvalidRecordingException as err: logger.debug(str(err)) for plugin in g_pool.plugins: if plugin.on_drop(paths): break def _restart_with_recording(rec_dir): logger.debug("Starting new session with '{}'".format(rec_dir)) ipc_pub.notify({ "subject": "player_drop_process.should_start", "rec_dir": rec_dir }) glfw.set_window_should_close(g_pool.main_window, True) tick = delta_t() def get_dt(): return next(tick) recording = PupilRecording(rec_dir) meta_info = recording.meta_info # log info about Pupil Platform and Platform in player.log logger.info("Application Version: {}".format(app_version)) logger.info("System Info: {}".format(get_system_info())) logger.debug(f"Debug flag: {debug}") icon_bar_width = 50 window_size = None content_scale = 1.0 # create container for globally scoped vars g_pool = SimpleNamespace() g_pool.app = "player" g_pool.process = "player" g_pool.zmq_ctx = zmq_ctx g_pool.ipc_pub = ipc_pub g_pool.ipc_pub_url = ipc_pub_url g_pool.ipc_sub_url = ipc_sub_url g_pool.ipc_push_url = ipc_push_url g_pool.plugin_by_name = {p.__name__: p for p in plugins} g_pool.camera_render_size = None video_path = recording.files().core().world().videos()[0].resolve() File_Source( g_pool, timing="external", source_path=video_path, buffered_decoding=True, fill_gaps=True, ) # load session persistent settings session_settings = Persistent_Dict( os.path.join(user_dir, "user_settings_player")) if parse_version(session_settings.get("version", "0.0")) != app_version: logger.info( "Session setting are a different version of this app. I will not use those." ) session_settings.clear() width, height = g_pool.capture.frame_size width += icon_bar_width width, height = session_settings.get("window_size", (width, height)) window_name = f"Pupil Player: {meta_info.recording_name} - {rec_dir}" glfw.init() glfw.window_hint(glfw.SCALE_TO_MONITOR, glfw.TRUE) main_window = glfw.create_window(width, height, window_name, None, None) window_position_manager = gl_utils.WindowPositionManager() window_pos = window_position_manager.new_window_position( window=main_window, default_position=window_position_default, previous_position=session_settings.get("window_position", None), ) glfw.set_window_pos(main_window, window_pos[0], window_pos[1]) glfw.make_context_current(main_window) cygl.utils.init() g_pool.main_window = main_window g_pool.version = app_version g_pool.timestamps = g_pool.capture.timestamps g_pool.get_timestamp = lambda: 0.0 g_pool.user_dir = user_dir g_pool.rec_dir = rec_dir g_pool.meta_info = meta_info g_pool.min_data_confidence = session_settings.get( "min_data_confidence", MIN_DATA_CONFIDENCE_DEFAULT) g_pool.min_calibration_confidence = session_settings.get( "min_calibration_confidence", MIN_CALIBRATION_CONFIDENCE_DEFAULT) # populated by producers g_pool.pupil_positions = pm.PupilDataBisector() g_pool.gaze_positions = pm.Bisector() g_pool.fixations = pm.Affiliator() g_pool.eye_movements = pm.Affiliator() def set_data_confidence(new_confidence): g_pool.min_data_confidence = new_confidence notification = {"subject": "min_data_confidence_changed"} notification["_notify_time_"] = time() + 0.8 g_pool.ipc_pub.notify(notification) def do_export(_): left_idx = g_pool.seek_control.trim_left right_idx = g_pool.seek_control.trim_right export_range = left_idx, right_idx + 1 # exclusive range.stop export_ts_window = pm.exact_window(g_pool.timestamps, (left_idx, right_idx)) export_dir = os.path.join(g_pool.rec_dir, "exports") export_dir = next_export_sub_dir(export_dir) os.makedirs(export_dir) logger.info('Created export dir at "{}"'.format(export_dir)) export_info = { "Player Software Version": str(g_pool.version), "Data Format Version": meta_info.min_player_version, "Export Date": strftime("%d.%m.%Y", localtime()), "Export Time": strftime("%H:%M:%S", localtime()), "Frame Index Range:": g_pool.seek_control.get_frame_index_trim_range_string(), "Relative Time Range": g_pool.seek_control.get_rel_time_trim_range_string(), "Absolute Time Range": g_pool.seek_control.get_abs_time_trim_range_string(), } with open(os.path.join(export_dir, "export_info.csv"), "w") as csv: write_key_value_file(csv, export_info) notification = { "subject": "should_export", "range": export_range, "ts_window": export_ts_window, "export_dir": export_dir, } g_pool.ipc_pub.notify(notification) def reset_restart(): logger.warning("Resetting all settings and restarting Player.") glfw.set_window_should_close(main_window, True) ipc_pub.notify({"subject": "clear_settings_process.should_start"}) ipc_pub.notify({ "subject": "player_process.should_start", "rec_dir": rec_dir, "delay": 2.0, }) def toggle_general_settings(collapsed): # this is the menu toggle logic. # Only one menu can be open. # If no menu is open the menubar should collapse. g_pool.menubar.collapsed = collapsed for m in g_pool.menubar.elements: m.collapsed = True general_settings.collapsed = collapsed g_pool.gui = ui.UI() g_pool.menubar = ui.Scrolling_Menu("Settings", pos=(-500, 0), size=(-icon_bar_width, 0), header_pos="left") g_pool.iconbar = ui.Scrolling_Menu("Icons", pos=(-icon_bar_width, 0), size=(0, 0), header_pos="hidden") g_pool.timelines = ui.Container((0, 0), (0, 0), (0, 0)) g_pool.timelines.horizontal_constraint = g_pool.menubar g_pool.user_timelines = ui.Timeline_Menu("User Timelines", pos=(0.0, -150.0), size=(0.0, 0.0), header_pos="headline") g_pool.user_timelines.color = RGBA(a=0.0) g_pool.user_timelines.collapsed = True # add container that constaints itself to the seekbar height vert_constr = ui.Container((0, 0), (0, -50.0), (0, 0)) vert_constr.append(g_pool.user_timelines) g_pool.timelines.append(vert_constr) def set_window_size(): # Get current capture frame size f_width, f_height = g_pool.capture.frame_size # Get current display scale factor content_scale = gl_utils.get_content_scale(main_window) framebuffer_scale = gl_utils.get_framebuffer_scale(main_window) display_scale_factor = content_scale / framebuffer_scale # Scale the capture frame size by display scale factor f_width *= display_scale_factor f_height *= display_scale_factor # Increas the width to account for the added scaled icon bar width f_width += icon_bar_width * display_scale_factor # Set the newly calculated size (scaled capture frame size + scaled icon bar width) glfw.set_window_size(main_window, int(f_width), int(f_height)) general_settings = ui.Growing_Menu("General", header_pos="headline") general_settings.append(ui.Button("Reset window size", set_window_size)) general_settings.append( ui.Info_Text( f"Minimum Player Version: {meta_info.min_player_version}")) general_settings.append( ui.Info_Text(f"Player Version: {g_pool.version}")) general_settings.append( ui.Info_Text( f"Recording Software: {meta_info.recording_software_name}")) general_settings.append( ui.Info_Text( f"Recording Software Version: {meta_info.recording_software_version}" )) general_settings.append( ui.Info_Text( "High level data, e.g. fixations, or visualizations only consider gaze data that has an equal or higher confidence than the minimum data confidence." )) general_settings.append( ui.Slider( "min_data_confidence", g_pool, setter=set_data_confidence, step=0.05, min=0.0, max=1.0, label="Minimum data confidence", )) general_settings.append( ui.Button("Restart with default settings", reset_restart)) g_pool.menubar.append(general_settings) icon = ui.Icon( "collapsed", general_settings, label=chr(0xE8B8), on_val=False, off_val=True, setter=toggle_general_settings, label_font="pupil_icons", ) icon.tooltip = "General Settings" g_pool.iconbar.append(icon) user_plugin_separator = ui.Separator() user_plugin_separator.order = 0.35 g_pool.iconbar.append(user_plugin_separator) g_pool.quickbar = ui.Stretching_Menu("Quick Bar", (0, 100), (100, -100)) g_pool.export_button = ui.Thumb( "export", label=chr(0xE2C5), getter=lambda: False, setter=do_export, hotkey=Hotkey.EXPORT_START_PLAYER_HOTKEY(), label_font="pupil_icons", ) g_pool.quickbar.extend([g_pool.export_button]) g_pool.gui.append(g_pool.menubar) g_pool.gui.append(g_pool.timelines) g_pool.gui.append(g_pool.iconbar) g_pool.gui.append(g_pool.quickbar) # we always load these plugins _pupil_producer_plugins = [ # In priority order (first is default) ("Pupil_From_Recording", {}), ("Offline_Pupil_Detection", {}), ("DisabledPupilProducer", {}), ] _pupil_producer_plugins = list(reversed(_pupil_producer_plugins)) _gaze_producer_plugins = [ # In priority order (first is default) ("GazeFromRecording", {}), ("GazeFromOfflineCalibration", {}), ] _gaze_producer_plugins = list(reversed(_gaze_producer_plugins)) default_plugins = [ ("Plugin_Manager", {}), ("Seek_Control", {}), ("Log_Display", {}), ("Raw_Data_Exporter", {}), ("Vis_Polyline", {}), ("Vis_Circle", {}), ("System_Graphs", {}), ("System_Timelines", {}), ("World_Video_Exporter", {}), *_pupil_producer_plugins, *_gaze_producer_plugins, ("Audio_Playback", {}), ] _plugins_to_load = session_settings.get("loaded_plugins", None) if _plugins_to_load is None: # If no plugins are available from a previous session, # then use the default plugin list _plugins_to_load = default_plugins else: # If there are plugins available from a previous session, # then prepend plugins that are required, but might have not been available before _plugins_to_load = [ *_pupil_producer_plugins, *_gaze_producer_plugins, *_plugins_to_load, ] g_pool.plugins = Plugin_List(g_pool, _plugins_to_load) # Manually add g_pool.capture to the plugin list g_pool.plugins._plugins.append(g_pool.capture) g_pool.plugins._plugins.sort(key=lambda p: p.order) g_pool.capture.init_ui() general_settings.insert( -1, ui.Text_Input( "rel_time_trim_section", getter=g_pool.seek_control.get_rel_time_trim_range_string, setter=g_pool.seek_control.set_rel_time_trim_range_string, label="Relative time range to export", ), ) general_settings.insert( -1, ui.Text_Input( "frame_idx_trim_section", getter=g_pool.seek_control.get_frame_index_trim_range_string, setter=g_pool.seek_control.set_frame_index_trim_range_string, label="Frame index range to export", ), ) # Register callbacks main_window glfw.set_framebuffer_size_callback(main_window, on_resize) glfw.set_key_callback(main_window, on_window_key) glfw.set_char_callback(main_window, on_window_char) glfw.set_mouse_button_callback(main_window, on_window_mouse_button) glfw.set_cursor_pos_callback(main_window, on_pos) glfw.set_scroll_callback(main_window, on_scroll) glfw.set_drop_callback(main_window, on_drop) toggle_general_settings(True) g_pool.gui.configuration = session_settings.get("ui_config", {}) # If previously selected plugin was not loaded this time, we will have an # expanded menubar without any menu selected. We need to ensure the menubar is # collapsed in this case. if all(submenu.collapsed for submenu in g_pool.menubar.elements): g_pool.menubar.collapsed = True # gl_state settings gl_utils.basic_gl_setup() g_pool.image_tex = Named_Texture() # trigger on_resize on_resize(main_window, *glfw.get_framebuffer_size(main_window)) def handle_notifications(n): subject = n["subject"] if subject == "start_plugin": g_pool.plugins.add(g_pool.plugin_by_name[n["name"]], args=n.get("args", {})) elif subject.startswith("meta.should_doc"): ipc_pub.notify({ "subject": "meta.doc", "actor": g_pool.app, "doc": player.__doc__ }) for p in g_pool.plugins: if (p.on_notify.__doc__ and p.__class__.on_notify != Plugin.on_notify): ipc_pub.notify({ "subject": "meta.doc", "actor": p.class_name, "doc": p.on_notify.__doc__, }) while not glfw.window_should_close( main_window) and not process_was_interrupted: # fetch newest notifications new_notifications = [] while notify_sub.new_data: t, n = notify_sub.recv() new_notifications.append(n) # notify each plugin if there are new notifications: for n in new_notifications: handle_notifications(n) for p in g_pool.plugins: p.on_notify(n) events = {} # report time between now and the last loop interation events["dt"] = get_dt() # pupil and gaze positions are added by their respective producer plugins events["pupil"] = [] events["gaze"] = [] # allow each Plugin to do its work. for p in g_pool.plugins: p.recent_events(events) # check if a plugin need to be destroyed g_pool.plugins.clean() glfw.make_context_current(main_window) glfw.poll_events() # render visual feedback from loaded plugins if gl_utils.is_window_visible(main_window): gl_utils.glViewport(0, 0, *g_pool.camera_render_size) g_pool.capture.gl_display() for p in g_pool.plugins: p.gl_display() gl_utils.glViewport(0, 0, *window_size) try: clipboard = glfw.get_clipboard_string(main_window).decode() except (AttributeError, glfw.GLFWError): # clipbaord is None, might happen on startup clipboard = "" g_pool.gui.update_clipboard(clipboard) user_input = g_pool.gui.update() if user_input.clipboard and user_input.clipboard != clipboard: # only write to clipboard if content changed glfw.set_clipboard_string(main_window, user_input.clipboard) for b in user_input.buttons: button, action, mods = b x, y = glfw.get_cursor_pos(main_window) pos = gl_utils.window_coordinate_to_framebuffer_coordinate( main_window, x, y, cached_scale=None) pos = normalize(pos, g_pool.camera_render_size) pos = denormalize(pos, g_pool.capture.frame_size) for plugin in g_pool.plugins: if plugin.on_click(pos, button, action): break for key, scancode, action, mods in user_input.keys: for plugin in g_pool.plugins: if plugin.on_key(key, scancode, action, mods): break for char_ in user_input.chars: for plugin in g_pool.plugins: if plugin.on_char(char_): break # present frames at appropriate speed g_pool.seek_control.wait(events["frame"].timestamp) glfw.swap_buffers(main_window) session_settings["loaded_plugins"] = g_pool.plugins.get_initializers() session_settings["min_data_confidence"] = g_pool.min_data_confidence session_settings[ "min_calibration_confidence"] = g_pool.min_calibration_confidence session_settings["ui_config"] = g_pool.gui.configuration session_settings["window_position"] = glfw.get_window_pos(main_window) session_settings["version"] = str(g_pool.version) session_window_size = glfw.get_window_size(main_window) if 0 not in session_window_size: f_width, f_height = session_window_size if platform.system() in ("Windows", "Linux"): f_width, f_height = ( f_width / content_scale, f_height / content_scale, ) session_settings["window_size"] = int(f_width), int(f_height) session_settings.close() # de-init all running plugins for p in g_pool.plugins: p.alive = False g_pool.plugins.clean() g_pool.gui.terminate() glfw.destroy_window(main_window) except Exception: import traceback trace = traceback.format_exc() logger.error("Process Player crashed with trace:\n{}".format(trace)) finally: logger.info("Process shutting down.") ipc_pub.notify({"subject": "player_process.stopped"}) sleep(1.0)
import pyMatrixStack as ms import atexit if not glfw.init(): sys.exit() # NEW - for shader location pwd = os.path.dirname(os.path.abspath(__file__)) # NEW - for shaders glfloat_size = 4 floatsPerVertex = 3 floatsPerColor = 3 glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 3) glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 3) # CORE profile means no fixed functions. # compatibility profile would mean access to legacy fixed functions # compatibility mode isn't supported by every graphics driver, # particulary on laptops which switch between integrated graphics # and a discrete card over time based off of usage. glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE) # for osx glfw.window_hint(glfw.OPENGL_FORWARD_COMPAT, GL_TRUE) window = glfw.create_window(500, 500, "ModelViewProjection Demo 21", None, None)
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()
def main(): global lastFrame, deltaTime glfw.init() glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 3) glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 3) glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE) window = glfw.create_window(screenWidth, screenHeight, "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) glEnable(GL_DEPTH_TEST) lighting_shader_program = ShaderProgram("shaders/c05_materials.vs", "shaders/c05_materials.fs") lighting_shader = lighting_shader_program.program_id lightcube_shader_program = ShaderProgram("shaders/c05_lightcube.vs", "shaders/c05_lightcube.fs") lightcube_shader = lightcube_shader_program.program_id texture_floor_shader = ShaderProgram("shaders/c06_floor.vs", "shaders/c06_floor.fs") vertices = np.array([ -0.5, -0.5, -0.5, 0.0, 0.0, -1.0, 0.5, -0.5, -0.5, 0.0, 0.0, -1.0, 0.5, 0.5, -0.5, 0.0, 0.0, -1.0, 0.5, 0.5, -0.5, 0.0, 0.0, -1.0, -0.5, 0.5, -0.5, 0.0, 0.0, -1.0, -0.5, -0.5, -0.5, 0.0, 0.0, -1.0, -0.5, -0.5, 0.5, 0.0, 0.0, 1.0, 0.5, -0.5, 0.5, 0.0, 0.0, 1.0, 0.5, 0.5, 0.5, 0.0, 0.0, 1.0, 0.5, 0.5, 0.5, 0.0, 0.0, 1.0, -0.5, 0.5, 0.5, 0.0, 0.0, 1.0, -0.5, -0.5, 0.5, 0.0, 0.0, 1.0, -0.5, 0.5, 0.5, -1.0, 0.0, 0.0, -0.5, 0.5, -0.5, -1.0, 0.0, 0.0, -0.5, -0.5, -0.5, -1.0, 0.0, 0.0, -0.5, -0.5, -0.5, -1.0, 0.0, 0.0, -0.5, -0.5, 0.5, -1.0, 0.0, 0.0, -0.5, 0.5, 0.5, -1.0, 0.0, 0.0, 0.5, 0.5, 0.5, 1.0, 0.0, 0.0, 0.5, 0.5, -0.5, 1.0, 0.0, 0.0, 0.5, -0.5, -0.5, 1.0, 0.0, 0.0, 0.5, -0.5, -0.5, 1.0, 0.0, 0.0, 0.5, -0.5, 0.5, 1.0, 0.0, 0.0, 0.5, 0.5, 0.5, 1.0, 0.0, 0.0, -0.5, -0.5, -0.5, 0.0, -1.0, 0.0, 0.5, -0.5, -0.5, 0.0, -1.0, 0.0, 0.5, -0.5, 0.5, 0.0, -1.0, 0.0, 0.5, -0.5, 0.5, 0.0, -1.0, 0.0, -0.5, -0.5, 0.5, 0.0, -1.0, 0.0, -0.5, -0.5, -0.5, 0.0, -1.0, 0.0, -0.5, 0.5, -0.5, 0.0, 1.0, 0.0, 0.5, 0.5, -0.5, 0.0, 1.0, 0.0, 0.5, 0.5, 0.5, 0.0, 1.0, 0.0, 0.5, 0.5, 0.5, 0.0, 1.0, 0.0, -0.5, 0.5, 0.5, 0.0, 1.0, 0.0, -0.5, 0.5, -0.5, 0.0, 1.0, 0.0, ], dtype=np.float32) indices = np.array([0, 1, 3, 1, 2, 3], dtype=np.int32) bar_indices, bar_buffer = ObjLoader.load_model("models/bar.obj") floor_indices, floor_buffer = ObjLoader.load_model("models/floor.obj") ''' What is a VAO? when configuring vertex attribute, you only need to run those once. ''' cubeVAO = glGenVertexArrays(1) VBO = glGenBuffers(1) # EBO = glGenBuffers(1) glBindVertexArray(cubeVAO) # copy vertex info mation to buffer glBindBuffer(GL_ARRAY_BUFFER, VBO) glBufferData(GL_ARRAY_BUFFER, size_of(bar_buffer), bar_buffer, GL_STATIC_DRAW) # glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO) # glBufferData(GL_ELEMENT_ARRAY_BUFFER, size_of(indices), indices, GL_STATIC_DRAW) # set vertex attribute pointer # the fifth param is STRIDE: 3*size of float f_size = bar_buffer.itemsize glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 8 * f_size, c_void_p(0)) glEnableVertexAttribArray(0) glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 8 * f_size, c_void_p(3 * f_size)) glEnableVertexAttribArray(1) glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, 8 * f_size, c_void_p(5 * f_size)) glEnableVertexAttribArray(2) # set cube vbo lightCubeVAO = glGenVertexArrays(1) lightCubeVBO = glGenBuffers(1) glBindVertexArray(lightCubeVAO) glBindBuffer(GL_ARRAY_BUFFER, lightCubeVBO) glBufferData(GL_ARRAY_BUFFER, size_of(vertices), vertices, GL_STATIC_DRAW) glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 6 * f_size, c_void_p(0)) glEnableVertexAttribArray(0) # set floor floorVAO = glGenVertexArrays(1) floorVBO = glGenBuffers(1) glBindVertexArray(floorVAO) glBindBuffer(GL_ARRAY_BUFFER, floorVBO) glBufferData(GL_ARRAY_BUFFER, size_of(floor_buffer), floor_buffer, GL_STATIC_DRAW) f_size = bar_buffer.itemsize glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 8 * f_size, c_void_p(0)) glEnableVertexAttribArray(0) glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 8 * f_size, c_void_p(3 * f_size)) glEnableVertexAttribArray(1) glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, 8 * f_size, c_void_p(5 * f_size)) glEnableVertexAttribArray(2) floor_texture = load_texture("resources/textures/floor.jpg") #glPolygonMode(GL_FRONT_AND_BACK, GL_LINE) # polygon mode while not glfw.window_should_close(window): # per-frame time logit current_frame = glfw.get_time() deltaTime = current_frame - lastFrame lastFrame = current_frame process_input(window) glClearColor(0.9, 0.9, 0.9, 1.0) glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) lighting_shader_program.use() lighting_shader_program.setVec3("light.position", lightPos) lighting_shader_program.setVec3("viewPos", camera.Position) lightColor = glm.vec3() lightColor.x = glm.sin(glfw.get_time() * 2.0) lightColor.y = glm.sin(glfw.get_time() * 0.7) lightColor.z = glm.sin(glfw.get_time() * 1.3) lightColor = glm.vec3(0.9, 0.8, 0.1) diffuseColor = lightColor * glm.vec3(0.5) ambientColor = diffuseColor * glm.vec3(0.2) lighting_shader_program.setVec3("light.ambient", ambientColor) lighting_shader_program.setVec3("light.diffuse", diffuseColor) lighting_shader_program.setVec3("light.specular", glm.vec3(1.0, 1.0, 1.0)) lighting_shader_program.setVec3("material.ambient", glm.vec3(1.0, 0.5, 3.1)) lighting_shader_program.setVec3("material.diffuse", glm.vec3(1.0, 0.5, 3.1)) lighting_shader_program.setVec3("material.specular", glm.vec3(0.5, 0.5, 0.5)) lighting_shader_program.setFloat("material.shininess", 8.0) projection = glm.perspective(glm.radians(camera.Zoom), float(screenWidth / screenHeight), 0.1, 100) view = camera.getViewMatrix() lighting_shader_program.setMat4("projection", projection) lighting_shader_program.setMat4("view", view) model = glm.mat4(1.0) lighting_shader_program.setMat4("model", model) # render the cube glBindVertexArray(cubeVAO) glDrawArrays(GL_TRIANGLES, 0, len(bar_indices)) # glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, None) # glDrawArrays(GL_TRIANGLES, 0, 3) texture_floor_shader.use() texture_floor_shader.setMat4("projection", projection) texture_floor_shader.setMat4("view", view) texture_floor_shader.setMat4("model", model) glBindVertexArray(floorVAO) glBindTexture(GL_TEXTURE_2D, floor_texture) glDrawArrays(GL_TRIANGLES, 0, len(floor_indices)) # also draw the lamp object lightcube_shader_program.use() lightcube_shader_program.setMat4("projection", projection) lightcube_shader_program.setMat4("view", view) model = glm.mat4(1.0) model = glm.translate(model, lightPos) model = glm.scale(model, glm.vec3(0.2)) lightcube_shader_program.setMat4("model", model) glBindVertexArray(lightCubeVAO) glDrawArrays(GL_TRIANGLES, 0, 36) glfw.swap_buffers(window) glfw.poll_events() glfw.terminate() return
def __init__(self, w: int, h: int, title: str): self.title = title self.screenSize = vec2(w, h) if not glfw.init(): return self.api = API() glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 3) glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 3) glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE) glfw.window_hint(glfw.RESIZABLE, glfw.TRUE) self.window = glfw.create_window(w, h, title, None, None) if not self.window: glfw.terminate() return glfw.make_context_current(self.window) glfw.swap_interval(1) value = [0] MaxTextures = glGetInteger(GL_MAX_TEXTURE_UNITS, value) self.render = Render2D(VertexShader(), FragmentShader(MaxTextures), MaxTextures) self.text_render = Render2D(VertexShaderText(), FragmentShaderText(MaxTextures), MaxTextures) self.game = Game() self.game.screenSize = self.screenSize self.game.api = self.api #callback functions def resize_callback(window, w, h): self.screenSize = vec2(w, h) glViewport(w // 2 - int(self.screenSize.x // 2), h // 2 - int(self.screenSize.y // 2), int(self.screenSize.x), int(self.screenSize.y)) self.game.on_resize(w, h) self.render.shader.SetUniMat4( "u_ViewProj", identity(mat4)) #Camera projection here self.render.shader.SetUniMat4( "u_Transform", ortho(0.0, self.screenSize.x, 0.0, self.screenSize.y, -1.0, 1.0)) self.text_render.shader.SetUniMat4("u_ViewProj", identity(mat4)) self.text_render.shader.SetUniMat4( "u_Transform", ortho(0.0, self.screenSize.x, 0.0, self.screenSize.y, 0.0, 1.0)) #TODO: Maybe pass the Mouse and Keyboard to Game, maybe def on_mouse_scroll_callback(window, xOffSet, yOffSet): Mouse.handleScroll(window, xOffSet, yOffSet) self.game.on_mouse_scroll(xOffSet, yOffSet) def on_cursor_move_callback(window, xpos, ypos): ypos = -(ypos - self.screenSize.y) # adjust to the OpenGL viewport Mouse.handleMove(window, xpos, ypos) self.game.on_cursor_move(xpos, ypos) def on_mouse_button_callback(window, key, action, mods): Mouse.handleClicks(window, key, action, mods) self.game.on_mouse_click(key, action, mods) def on_keyboard_click_callback(window, key, scancode, action, mods): Keyboard.handleClicks(window, key, scancode, action, mods) self.game.on_keyboard_click(key, scancode, action, mods) #Set callbacks from glfw glfw.set_window_size_callback(self.window, resize_callback) glfw.set_scroll_callback(self.window, on_mouse_scroll_callback) glfw.set_cursor_pos_callback(self.window, on_cursor_move_callback) glfw.set_mouse_button_callback(self.window, on_mouse_button_callback) glfw.set_key_callback(self.window, on_keyboard_click_callback)
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)
import glfw from OpenGL.GL import * import pyglet.gl from OpenGL.GL import shaders from OpenGL.arrays import vbo from OpenGLContext.arrays import * import numpy as np import ctypes 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); window = glfw.create_window(256, 240, "Hello World", None, None) assert (glfw.get_window_attrib(window, glfw.CONTEXT_VERSION_MAJOR) >= 3) print (glfw.get_window_attrib(window, glfw.CONTEXT_VERSION_MAJOR), glfw.get_window_attrib(window, glfw.CONTEXT_VERSION_MINOR)) vao_id = GLuint(0) # I hate python gl bindings pyglet.gl.glGenVertexArrays(1, ctypes.byref(vao_id)) pyglet.gl.glBindVertexArray(vao_id.value) vertexShaderSrc = """#version 150
ll = [] draw_lattice(our_x - WINDOW_WIDTH / 2, our_y - WINDOW_HEIGHT / 2) draw_players((our_x - WINDOW_WIDTH / 2, our_y - WINDOW_HEIGHT / 2), ll) config_file = open('config.txt', 'r') ip, port, = open('config.txt', 'r').readline().split() player_id = registerMe('OpenGL') t1 = threading.Thread(target=asking, daemon=True).start() t2 = threading.Thread(target=sending, daemon=True).start() if not glfw.init(): exit(0) glfw.window_hint(glfw.RESIZABLE, GL_FALSE) glfw.window_hint(glfw.SAMPLES, 8) window = glfw.create_window(WINDOW_WIDTH, WINDOW_HEIGHT, 'agar.io', None, None) w, h = glfw.get_video_mode(glfw.get_primary_monitor())[0] glfw.set_window_pos(window, (w - WINDOW_WIDTH) // 2, (h - WINDOW_HEIGHT) // 2) glfw.set_cursor_pos_callback(window, on_motion) if not window: glfw.terminate() exit(0) glfw.make_context_current(window) glfw.swap_interval(1) glClearColor(1., 1., 1., 1.) glViewport(0, 0, WINDOW_WIDTH, WINDOW_HEIGHT)
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()
def glfw_init(): glfw.init() glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 3) glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 3) glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE) glfw.window_hint(glfw.RESIZABLE, GL_FALSE)
sys.path.insert(0, ".") if __name__ == "__main__": import glfw import time from gui import * from glutils import * from objectquad import * import OpenGL.GL as gl # 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) # Create a windowed mode window and its OpenGL context window = glfw.create_window(500, 500, "Scene 1", None, None) if not window: 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) def on_resize(window, width, height):
nusp: 3672382 30/03/2020 Exercicio prático: Desenhar cilindro e aplicar as transformações geométricas vinculadas a eventos de teclado """ import glfw from OpenGL.GL import * import OpenGL.GL.shaders import numpy as np import math glfw.init() glfw.window_hint(glfw.VISIBLE, glfw.FALSE) window = glfw.create_window(700, 700, "Esfera - 3672382", None, None) glfw.make_context_current(window) vertex_code = """ attribute vec3 position; uniform mat4 mat_transformation; void main(){ gl_Position = mat_transformation * vec4(position,1.0); } """ fragment_code = """ uniform vec4 color; void main(){ gl_FragColor = color; }
def __init__(self, width=640, height=480, fullscreen=False, aspect=None): self.gl = gl if not glfw.init(): raise Exception("GLFW init failed") glfw.window_hint(glfw.CLIENT_API, glfw.OPENGL_ES_API) glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 2) glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 0) glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 0) glfw.window_hint(glfw.DOUBLEBUFFER, True) glfw.window_hint(glfw.DEPTH_BITS, 24) glfw.window_hint(glfw.ALPHA_BITS, 0) if platform.system() == "Linux": try: glfw.window_hint(GLFW_CONTEXT_CREATION_API, GLFW_EGL_CONTEXT_API) except: pass monitor = glfw.get_primary_monitor() if fullscreen else None self.window = glfw.create_window(width, height, "BlitzLoop Karaoke", monitor, None) self.x = 0 self.y = 0 glfw.make_context_current(self.window) BaseDisplay.__init__(self, width, height, fullscreen, aspect) self._on_reshape(self.window, width, height) if fullscreen: self.saved_size = (0, 0, width, height) glfw.set_input_mode(self.window, glfw.CURSOR, glfw.CURSOR_HIDDEN) glfw.set_key_callback(self.window, self._on_keyboard) glfw.set_window_pos_callback(self.window, self._on_move) glfw.set_window_size_callback(self.window, self._on_reshape) self._initialize()
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) # define desired frame rate self.frame_rate = 100 # 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 self.mouseX = None self.mouseY = None self.doRotation = False self.doZoom = False self.doTranslate = False self.colors = { "black": (0.0, 0.0, 0.0, 0.0), "white": (1.0, 1.0, 1.0, 0.0), "red": (1.0, 0.0, 0.0, 0.0), "blue": (0.0, 0.0, 1.0, 0.0), "yellow": (1.0, 1.0, 0.0, 0.0) } self.color = self.colors["yellow"] self.projections = "ortho" # Make the window's context current glfw.make_context_current(self.window) # create 3D self.scene = Scene(self.width, self.height) # initialize GL glViewport(0, 0, self.width, self.height) glEnable(GL_DEPTH_TEST) glClearColor(*self.color) glMatrixMode(GL_PROJECTION) glOrtho(-3.5, 3.5, -3.5, 3.5, -3.5, 3.5) # glOrtho(-self.width/2,self.width/2,-self.height/2,self.height/2,-2,2) glEnable(GL_DEPTH_TEST) glEnable(GL_NORMALIZE) # set window callbacks glfw.set_mouse_button_callback(self.window, self.onMouseButton) glfw.set_key_callback(self.window, self.onKeyboard) glfw.set_window_size_callback(self.window, self.onSize) glfw.set_cursor_pos_callback(self.window, self.mouse_moved) # exit flag self.exitNow = False # animation flag self.animation = True
def init(self): # Initialize the renderer, set up the Window. glfw.init() glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 3) glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 3) glfw.window_hint(glfw.OPENGL_FORWARD_COMPAT, gl.GL_TRUE) glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE) glfw.window_hint(glfw.DECORATED, gl.GL_TRUE) glfw.window_hint(glfw.DECORATED, gl.GL_TRUE) glfw.window_hint(glfw.RESIZABLE, gl.GL_FALSE) width = Config.windowWidth height = Config.windowHeight self.aspect = width/height # Initialize the window self.window = glfw.create_window(width, height, "Magic", None, None) glfw.make_context_current(self.window) self.renderer = Renderer() self.quad = [] self.text = [] # Set up camera self.viewMatrix = Matrix.identity() # Set up view transform. View is always 16 units high, and 16 * aspect units # wide. The extra space outside of a 4:3 ratio is unused, to make sure that # all the cards always fit in a 4:3 aspect monitor. vHeight = 2 vWidth = vHeight * self.aspect self.projectionMatrix = Matrix.ortho(-vWidth/2, vWidth/2, vHeight/2, -vHeight/2, -1, 1) self.viewProjectionMatrix = self.projectionMatrix * self.viewMatrix # Set up viewport fbWidth, fbHeight = glfw.get_framebuffer_size(self.window) gl.glViewport(0, 0, fbWidth, fbHeight) q = Quad(Texture('Images/Sen Triplets.jpg')) # Natural resolution of cards is 480x680 cardAspect = 480/680 q.x = 0 q.y = 0 q.height = .8 q.width = q.height * cardAspect self.quad.append(q)
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)
def render_snippet( source, file_path, title="", width=200, height=200, auto_window=False, auto_layout=False, output_dir='.', ): code = compile(source, '<str>', 'exec') window_name = "minimal ImGui/GLFW3 example" if not glfw.init(): print("Could not initialize OpenGL context") exit(1) # OS X supports only forward-compatible core profiles from 3.2 glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 3) glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 3) glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE) glfw.window_hint(glfw.OPENGL_FORWARD_COMPAT, gl.GL_TRUE) # note: creating context without window is tricky so made window invisible glfw.window_hint(glfw.VISIBLE, False) window = glfw.create_window(int(width), int(height), window_name, None, None) glfw.make_context_current(window) if not window: glfw.terminate() print("Could not initialize Window") exit(1) imgui_ctx = GlfwImpl(window) imgui_ctx.enable() glfw.poll_events() # render target for framebuffer texture = gl.glGenTextures(1) gl.glBindTexture(gl.GL_TEXTURE_2D, texture) gl.glTexImage2D(gl.GL_TEXTURE_2D, 0, gl.GL_RGBA, width, height, 0, gl.GL_RGB, gl.GL_UNSIGNED_BYTE, None) gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MAG_FILTER, gl.GL_NEAREST) gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MIN_FILTER, gl.GL_NEAREST) # create new framebuffer offscreen_fb = gl.glGenFramebuffers(1) gl.glBindFramebuffer(gl.GL_FRAMEBUFFER, offscreen_fb) # attach texture to framebuffer gl.glFramebufferTexture2D(gl.GL_FRAMEBUFFER, gl.GL_COLOR_ATTACHMENT0, gl.GL_TEXTURE_2D, texture, 0) imgui_ctx.new_frame() with imgui.styled(imgui.STYLE_ALPHA, 1): imgui.core.set_next_window_size(0, 0) if auto_layout: imgui.set_next_window_size(width - 10, height - 10) imgui.set_next_window_centered() if auto_window: imgui.set_next_window_size(width - 10, height - 10) imgui.set_next_window_centered() imgui.begin("Example: %s" % title) exec(code, locals(), globals()) if auto_window: imgui.end() gl.glBindFramebuffer(gl.GL_FRAMEBUFFER, offscreen_fb) gl.glClearColor(1, 1, 1, 0) gl.glClear(gl.GL_COLOR_BUFFER_BIT) imgui.render() # retrieve pixels from framebuffer and write to file pixels = gl.glReadPixels(0, 0, width, height, gl.GL_RGBA, gl.GL_UNSIGNED_BYTE) image = Image.frombytes('RGBA', (width, height), pixels) # note: glReadPixels returns lines "bottom to top" but PIL reads bytes # top to bottom image = image.transpose(Image.FLIP_TOP_BOTTOM) image.save(os.path.join(output_dir, file_path)) glfw.terminate()
def demo(): # Initialize the library if not glfw.init(): sys.exit() glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 3) glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 3) glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE) # for osx glfw.window_hint(glfw.OPENGL_FORWARD_COMPAT, gl.GL_TRUE) # Create a windowed mode window and its OpenGL context window = glfw.create_window(1000, 1000, "pyNuklear demo - GLFW OpenGL3", None, None) if not window: glfw.terminate() sys.exit() # Make the window's context current glfw.make_context_current(window) ctx = nkglfw3.glfw3_init(window, nkglfw3.GLFW3_INSTALL_CALLBACKS) nuklear = nk.NuklearContext(ctx) fontAtlas = nkglfw3.FontAtlas() nkglfw3.glfw3_font_stash_begin(ctypes.byref(fontAtlas)) nkglfw3.glfw3_font_stash_end() # Install a key handler def on_key(window, key, scancode, action, mods): if key == glfw.KEY_ESCAPE and action == glfw.PRESS: glfwSetWindowShouldClose(window, 1) glfw.set_key_callback(window, on_key) gl.glClearColor(0.1, 0.18, 0.24, 1.0) gl.glEnable(gl.GL_DEPTH_TEST) gl.glClearDepth(1.0) gl.glDepthFunc(gl.GL_LEQUAL) class Camera: def __init__(self): self.x = 0.0 self.y = 0.0 self.z = 10.0 self.rotationX = 0.0 self.rotationY = 0.0 camera = Camera() triangle = Triangle() triangle.prepareToRender() # does python have static local variables? this declaration is way too far away from use #property = ctypes.c_int(20) # Loop until the user closes the window while not glfw.window_should_close(window): # Render here # Poll for and process events glfw.poll_events() nkglfw3.glfw3_new_frame() width, height = glfw.get_framebuffer_size(window) gl.glViewport(0, 0, width, height) gl.glClear(gl.GL_COLOR_BUFFER_BIT | gl.GL_DEPTH_BUFFER_BIT) ms.setToIdentityMatrix(ms.MatrixStack.model) ms.setToIdentityMatrix(ms.MatrixStack.view) ms.setToIdentityMatrix(ms.MatrixStack.projection) # set the projection matrix to be perspective ms.perspective(fov=45.0, aspectRatio=width / height, nearZ=0.1, farZ=10000.0) # get input from keyboard for camera movement if not nuklear.item_is_any_active(): # set up Camera if glfw.get_key(window, glfw.KEY_RIGHT) == glfw.PRESS: camera.rotationY -= 0.03 if glfw.get_key(window, glfw.KEY_LEFT) == glfw.PRESS: camera.rotationY += 0.03 if glfw.get_key(window, glfw.KEY_UP) == glfw.PRESS: camera.x -= math.sin(camera.rotationY) camera.z -= math.cos(camera.rotationY) if glfw.get_key(window, glfw.KEY_DOWN) == glfw.PRESS: camera.x += math.sin(camera.rotationY) camera.z += math.cos(camera.rotationY) # move the camera to the correct position, which means # updating the view stack ms.rotateX(ms.MatrixStack.view, camera.rotationX) ms.rotateY(ms.MatrixStack.view, -camera.rotationY) ms.translate(ms.MatrixStack.view, -camera.x, -camera.y, -camera.z) # render the models triangle.render() MAX_VERTEX_BUFFER = 512 * 1024 MAX_ELEMENT_BUFFER = 128 * 1024 if (nuklear.begin(title="Demonstration", bounds=nk.Rect(10.0, 10.0, 230.0, 250.0), flags=nk.PanelFlags.WINDOW_BORDER.value | nk.PanelFlags.WINDOW_MOVABLE.value | nk.PanelFlags.WINDOW_SCALABLE.value | nk.PanelFlags.WINDOW_MINIMIZABLE.value | nk.PanelFlags.WINDOW_TITLE.value)): nuklear.layout_row_static(height=30.0, item_width=80, columns=5) if nuklear.button_label(title="button"): print('button pressed') nuklear.layout_row_dynamic(height=30.0, columns=2) try: op except Exception: op = 0 if nuklear.option_label(label="easy", active=op == 0): op = 0 if nuklear.option_label(label="hard", active=op == 1): op = 1 nuklear.layout_row_dynamic(height=25.0, columns=1) try: prop except Exception: prop = 20 prop = nuklear.property_int(name="Compression:", minV=0, val=prop, maxV=100, step=10, inc_per_pixel=1) nuklear.layout_row_dynamic(height=20.0, columns=1) nuklear.label(text="background:", alignment=nk.TextAlign.TEXT_LEFT) try: background except Exception: background = nk.ColorF(r=0.10, g=0.18, b=0.24, a=1.0) nuklear.layout_row_dynamic(height=25.0, columns=1) if nuklear.combo_begin_color(color=nuklear.rgb_cf(background), size=nk.Vec2(nuklear.widget_width(), 400)): nuklear.layout_row_dynamic(height=120.0, columns=1) background = nuklear.color_picker(color=background, format=nk.ColorFormat.RGBA) nuklear.layout_row_dynamic(height=25.0, columns=1) background.r = nuklear.propertyf(name="#R:", minVal=0.0, val=background.r, maxVal=1.0, step=0.01, inc_per_pixel=0.005) background.g = nuklear.propertyf(name="#G:", minVal=0.0, val=background.g, maxVal=1.0, step=0.01, inc_per_pixel=0.005) background.b = nuklear.propertyf(name="#B:", minVal=0.0, val=background.b, maxVal=1.0, step=0.01, inc_per_pixel=0.005) background.a = nuklear.propertyf(name="#A:", minVal=0.0, val=background.a, maxVal=1.0, step=0.01, inc_per_pixel=0.005) gl.glClearColor(background.r, background.g, background.b, background.a) nuklear.combo_end() nuklear.end() overview(nuklear) nkglfw3.glfw3_render(nk.AntiAliasing.ON.value, MAX_VERTEX_BUFFER, MAX_ELEMENT_BUFFER) # done with frame, flush and swap buffers # Swap front and back buffers glfw.swap_buffers(window) glfw.terminate()
loadBlenderSceneFile = True groundTruthBlender = False useCycles = True unpackModelsFromBlender = False unpackSceneFromBlender = False loadSavedSH = False glModes = ['glfw','mesa'] glMode = glModes[0] width, height = (150, 150) win = -1 if glMode == 'glfw': #Initialize base GLFW context for the Demo and to share context among all renderers. glfw.init() glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 3) glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 3) # glfw.window_hint(glfw.OPENGL_FORWARD_COMPAT, GL.GL_TRUE) glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE) glfw.window_hint(glfw.DEPTH_BITS,32) glfw.window_hint(glfw.VISIBLE, GL.GL_FALSE) # win = glfw.create_window(width, height, "Demo", None, None) # glfw.make_context_current(win) angle = 60 * 180 / numpy.pi clip_start = 0.01 clip_end = 10 frustum = {'near': clip_start, 'far': clip_end, 'width': width, 'height': height} camDistance = 0.4 teapots = [line.strip() for line in open('teapots.txt')]
def main(): if not glfw.init(): return window = glfw.create_window(WIDTH, HEIGHT, "Hello World", None, None) glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 3) glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 3) glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE) glfw.window_hint(glfw.RESIZABLE, GL_FALSE) if not window: glfw.terminate() return -1 glfw.make_context_current(window) (width, height) = glfw.get_framebuffer_size(window) glViewport(0, 0, width, height) glfw.set_key_callback(window, key_callback) glClearColor(0.2, 0.3, 0.2, 1.0) quad = [ # coords # colors # texture -0.4, -0.5, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.4, -0.5, 0.0, 0.0, 1.0, 0.0, 1.0, 0.0, 0.4, 0.5, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, -0.4, 0.5, 0.0, 1.0, 1.0, 1.0, 0.0, 1.0 ] quad = numpy.array(quad, dtype=numpy.float32) indexes = [0, 1, 2, 0, 2, 3] indexes = numpy.array(indexes, dtype=numpy.uint32) ourShader = Shader('vertex_shader.vs', 'fragment_shader.frag') VAO = glGenVertexArrays(1) VBO = glGenBuffers(1) EBO = glGenBuffers(1) glBindVertexArray(VAO) glBindBuffer(GL_ARRAY_BUFFER, VBO) glBufferData(GL_ARRAY_BUFFER, quad.itemsize * len(quad), quad, GL_STATIC_DRAW) glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO) glBufferData(GL_ELEMENT_ARRAY_BUFFER, indexes.itemsize * len(indexes), indexes, GL_STATIC_DRAW) glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 32, ctypes.c_void_p(0)) glEnableVertexAttribArray(0) glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 32, ctypes.c_void_p(12)) glEnableVertexAttribArray(1) glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 32, ctypes.c_void_p(24)) glEnableVertexAttribArray(2) glBindVertexArray(0) texture1 = glGenTextures(1) glBindTexture(GL_TEXTURE_2D, texture1) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR) image = Image.open('../textures/wall.jpg') img_data = numpy.array(list(image.getdata()), numpy.uint8) glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 512, 512, 0, GL_RGB, GL_UNSIGNED_BYTE, img_data) glGenerateMipmap(GL_TEXTURE_2D) glBindTexture(GL_TEXTURE_2D, 0) texture2 = glGenTextures(1) glBindTexture(GL_TEXTURE_2D, texture2) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR) image = Image.open('../textures/container.jpg') img_data = numpy.array(list(image.getdata()), numpy.uint8) glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 512, 512, 0, GL_RGB, GL_UNSIGNED_BYTE, img_data) glGenerateMipmap(GL_TEXTURE_2D) glBindTexture(GL_TEXTURE_2D, 0) while not glfw.window_should_close(window): glfw.poll_events() glClear(GL_COLOR_BUFFER_BIT) ourShader.Use() dxLoc = glGetUniformLocation(ourShader.shader, "dx") glUniform1f(dxLoc, -0.5) glActiveTexture(GL_TEXTURE0) glBindTexture(GL_TEXTURE_2D, texture1) glBindVertexArray(VAO) glDrawElements(GL_TRIANGLES, len(indexes), GL_UNSIGNED_INT, None) glBindVertexArray(0) glUniform1f(dxLoc, 0.5) glActiveTexture(GL_TEXTURE0) glBindTexture(GL_TEXTURE_2D, texture2) glBindVertexArray(VAO) glDrawElements(GL_TRIANGLES, len(indexes), GL_UNSIGNED_INT, None) glBindVertexArray(0) glfw.swap_buffers(window) glfw.terminate()
def setGLFWOptions(win): glfw.make_context_current(win) glfw.window_hint(glfw.SAMPLES,4) glfw.set_key_callback(win, key_callback); glfw.set_cursor_pos_callback(win, cursor_callback); glfw.set_window_size_callback(win, WindowSizeCallback);
def player_drop(rec_dir, ipc_pub_url, ipc_sub_url, ipc_push_url, user_dir, app_version, debug): # general imports import logging # networking import zmq import zmq_tools from time import sleep # zmq ipc setup zmq_ctx = zmq.Context() ipc_pub = zmq_tools.Msg_Dispatcher(zmq_ctx, ipc_push_url) # log setup logging.getLogger("OpenGL").setLevel(logging.ERROR) logger = logging.getLogger() logger.handlers = [] logger.setLevel(logging.INFO) logger.addHandler(zmq_tools.ZMQ_handler(zmq_ctx, ipc_push_url)) # create logger for the context of this function logger = logging.getLogger(__name__) try: import glfw from gl_utils import GLFWErrorReporting GLFWErrorReporting.set_default() import gl_utils from OpenGL.GL import glClearColor from version_utils import parse_version from file_methods import Persistent_Dict from pyglui.pyfontstash import fontstash from pyglui.ui import get_roboto_font_path import player_methods as pm from pupil_recording import ( assert_valid_recording_type, InvalidRecordingException, ) from pupil_recording.update import update_recording process_was_interrupted = False def interrupt_handler(sig, frame): import traceback trace = traceback.format_stack(f=frame) logger.debug(f"Caught signal {sig} in:\n" + "".join(trace)) nonlocal process_was_interrupted process_was_interrupted = True signal.signal(signal.SIGINT, interrupt_handler) def on_drop(window, paths): nonlocal rec_dir rec_dir = paths[0] if rec_dir: try: assert_valid_recording_type(rec_dir) except InvalidRecordingException as err: logger.error(str(err)) rec_dir = None # load session persistent settings session_settings = Persistent_Dict( os.path.join(user_dir, "user_settings_player")) if parse_version(session_settings.get("version", "0.0")) != app_version: logger.info( "Session setting are from a different version of this app. I will not use those." ) session_settings.clear() w, h = session_settings.get("window_size", (1280, 720)) glfw.init() glfw.window_hint(glfw.SCALE_TO_MONITOR, glfw.TRUE) glfw.window_hint(glfw.RESIZABLE, 0) window = glfw.create_window(w, h, "Pupil Player", None, None) glfw.window_hint(glfw.RESIZABLE, 1) glfw.make_context_current(window) window_position_manager = gl_utils.WindowPositionManager() window_pos = window_position_manager.new_window_position( window=window, default_position=window_position_default, previous_position=session_settings.get("window_position", None), ) glfw.set_window_pos(window, window_pos[0], window_pos[1]) glfw.set_drop_callback(window, on_drop) glfont = fontstash.Context() glfont.add_font("roboto", get_roboto_font_path()) glfont.set_align_string(v_align="center", h_align="middle") glfont.set_color_float((0.2, 0.2, 0.2, 0.9)) gl_utils.basic_gl_setup() glClearColor(0.5, 0.5, 0.5, 0.0) text = "Drop a recording directory onto this window." tip = "(Tip: You can drop a recording directory onto the app icon.)" # text = "Please supply a Pupil recording directory as first arg when calling Pupil Player." def display_string(string, font_size, center_y): x = w / 2 * content_scale y = center_y * content_scale glfont.set_size(font_size * content_scale) glfont.set_blur(10.5) glfont.set_color_float((0.0, 0.0, 0.0, 1.0)) glfont.draw_text(x, y, string) glfont.set_blur(0.96) glfont.set_color_float((1.0, 1.0, 1.0, 1.0)) glfont.draw_text(x, y, string) while not glfw.window_should_close( window) and not process_was_interrupted: fb_size = glfw.get_framebuffer_size(window) content_scale = gl_utils.get_content_scale(window) gl_utils.adjust_gl_view(*fb_size) if rec_dir: try: assert_valid_recording_type(rec_dir) logger.info( "Starting new session with '{}'".format(rec_dir)) text = "Updating recording format." tip = "This may take a while!" except InvalidRecordingException as err: logger.error(str(err)) if err.recovery: text = err.reason tip = err.recovery else: text = "Invalid recording" tip = err.reason rec_dir = None gl_utils.clear_gl_screen() display_string(text, font_size=51, center_y=216) for idx, line in enumerate(tip.split("\n")): tip_font_size = 42 center_y = 288 + tip_font_size * idx * 1.2 display_string(line, font_size=tip_font_size, center_y=center_y) glfw.swap_buffers(window) if rec_dir: try: update_recording(rec_dir) except AssertionError as err: logger.error(str(err)) tip = "Oops! There was an error updating the recording." rec_dir = None except InvalidRecordingException as err: logger.error(str(err)) if err.recovery: text = err.reason tip = err.recovery else: text = "Invalid recording" tip = err.reason rec_dir = None else: glfw.set_window_should_close(window, True) glfw.poll_events() session_settings["window_position"] = glfw.get_window_pos(window) session_settings.close() glfw.destroy_window(window) if rec_dir: ipc_pub.notify({ "subject": "player_process.should_start", "rec_dir": rec_dir }) except Exception: import traceback trace = traceback.format_exc() logger.error( "Process player_drop crashed with trace:\n{}".format(trace)) finally: sleep(1.0)
def main_rect(): glfw.init() glfw.window_hint(glfw.RESIZABLE, False) glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 4) glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 6) window = glfw.create_window(800, 600, 'Window Title', None, None) glfw.make_context_current(window) glViewport(0, 0, 800, 600) shaderProgram = make_shader_program() glUseProgram(shaderProgram) projection.set_uniform(shaderProgram, 'projection') projection.ortho(0, 800, 0, 600, 0, 1) # setup vao vao = glGenVertexArrays(1) glBindVertexArray(vao) # setup vbo for rectangle vertices rect_vbo = glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, rect_vbo) w, h = 100, 100 vertices = Vec(w, h), Vec(w, 0), Vec(0, 0), Vec(0, h) vertices = Vec(*vertices) glBufferData(GL_ARRAY_BUFFER, vertices.size, vertices.buffer, GL_STATIC_DRAW) glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, ctypes.c_void_p(0)) glEnableVertexAttribArray(0) glBindBuffer(GL_ARRAY_BUFFER, 0) # set vbo for tex coordinates rect_tex_coords = glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, rect_tex_coords) coords = Vec(1.0, 1.0), Vec(1.0, 0.0), Vec(0.0, 0.0), Vec(0.0, 1.0) coords = Vec(*coords) glBufferData(GL_ARRAY_BUFFER, coords.size, coords.buffer, GL_STATIC_DRAW) glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 0, ctypes.c_void_p(0)) glEnableVertexAttribArray(1) glBindBuffer(GL_ARRAY_BUFFER, 0) glBindVertexArray(0) # unbind vao texture = load_texture() while not glfw.window_should_close(window): glClearColor(0.0, 0.0, 0.0, 1.0) glClear(GL_COLOR_BUFFER_BIT) glBindVertexArray(vao) glBindTexture(GL_TEXTURE_2D, texture) glDrawArrays(GL_TRIANGLE_FAN, 0, 4) glBindTexture(GL_TEXTURE_2D, 0) glBindVertexArray(0) glfw.swap_buffers(window) glfw.poll_events() glDeleteVertexArrays(1, vao) glDeleteBuffers(1, rect_vbo) glDeleteBuffers(1, rect_ebo) glDeleteProgram(shaderProgram) glfw.terminate()
def main(): glfw.init() # Common window hints and their defaults glfw.window_hint(glfw.FOCUS_ON_SHOW, True) # for windowed windows glfw.window_hint(glfw.RESIZABLE, True) glfw.window_hint(glfw.VISIBLE, True) glfw.window_hint(glfw.DECORATED, True) glfw.window_hint(glfw.FOCUSED, True) glfw.window_hint(glfw.FLOATING, False) glfw.window_hint(glfw.MAXIMIZED, False) # for full screen windows # To make full screen, pass a monitor as the 5th argument to glfw.create_window, # or use glfw.set_window_monitor(w,mon). # Auto_iconify means to minimize when focus lost. glfw.window_hint(glfw.AUTO_ICONIFY, True) glfw.window_hint(glfw.CENTER_CURSOR, True) # opengl options glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 4) glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 6) glfw.window_hint(glfw.DEPTH_BITS, 24) glfw.window_hint(glfw.STENCIL_BITS, 8) # transparency glfw.window_hint(glfw.TRANSPARENT_FRAMEBUFFER, False) # later call glfw.set_window_opacity(w, 0.5) # and use glfw.get_window_opacity(w) # for X11 glfw.window_hint_string(glfw.X11_CLASS_NAME, "") glfw.window_hint_string(glfw.X11_INSTANCE_NAME, "") ##################### global w w = glfw.create_window(800, 600, 'Window Title', None, None) glfw.make_context_current(w) # glfw.set_window_title(w, "Window Title") # controlling window size # get/set interchangable # glfw.set_window_pos(w, x, y) # glfw.set_window_size(w, width, height) # glfw.set_window_size_limits(w, minW, minH, maxW, maxH) # glfw.set_window_aspect_ratio(w, 16, 9) # get only # glfw.get_window_frame_size(w) # with borders and all, get only # glfw.get_framebuffer_size(w) # get only # window status # glfw.iconify_window(w) / glfw.restore_window(w) # glfw.get_window_attrib(w, glfw.ICONIFIED) # glfw.maximize_window(w) / glfw.restore_window(w) # glfw.get_window_attrib(w, glfw.MAXIMIZED) # glfw.hide_window / glfw.show_window # glfw.get_window_attrib(w, glfw.VISIBLE) # glfw.focus_window(w) or glfw.request_window_attention(w) # glfw.get_window_attrib(w, glfw.FOCUSED) # glfw.set_window_should_close(w, False) # clipboard # glfw.get_clipboard_string(w) # glfw.set_clipboard_string(w, "hello") def clock(): while True: dt = yield from listen.wait(0.2) listen.launch(clock()) #################### shaderProgram = make_shader_program() glUseProgram(shaderProgram) vao = glGenVertexArrays(1) glBindVertexArray(vao) tri_vbo = glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, tri_vbo) v1, v2, v3 = Vec(0, 0, 0), Vec(1, 1, 0), Vec(1, 0, 0) vertices = Vec(v1, v2, v3) glBufferData(GL_ARRAY_BUFFER, vertices.size, vertices.buffer, GL_STATIC_DRAW) glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, ctypes.c_void_p(0)) glEnableVertexAttribArray(0) ################### def fbresize(): x = None while True: if x is None: x, y = glfw.get_framebuffer_size(w) else: _, x, y = yield from listen.on_framebuffer_size(w) # adjust viewport glViewport(0, 0, x, y) # adjust projection projection.set_uniform(shaderProgram, "projection") projection.clear() projection.ortho(0, x, 0, y, 0, 100) listen.launch(fbresize()) import time, math t0 = time.time() while not glfw.window_should_close(w): glClearColor(0.0, 0.0, 0.0, 1.0) glClear(GL_COLOR_BUFFER_BIT) projection.set_uniform(shaderProgram, "modelview") projection.push() theta = 10 * (time.time() - t0) projection.translate(100, 100, 0.0) projection.translate(10 * math.sin(theta), 10 * math.cos(theta), 0.0) projection.scale(100, 100, 1) glDrawArrays(GL_TRIANGLES, 0, 3) projection.pop() glfw.swap_buffers(w) # glfw.poll_events() # non-blocking # glfw.wait_events() # blocks until an event is received # glfw.wait_events_timeout(0.4) # blocks until event or timeout # To unblock the main thread from wait_events(), use glfw.post_empty_event() glfw.wait_events_timeout(0.01) # 100 fps listen.trigger_timers() glfw.terminate()
def main(): if not glfw.init(): return glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 4) glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 1) glfw.window_hint(glfw.OPENGL_FORWARD_COMPAT, 1) glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE) window = glfw.create_window(800, 600, "MY OPENGL", None, None) if not window: glfw.terminate() return glfw.make_context_current(window) #adding colors # x, y, z, r, g, b triangle = [ -.5, -.5, 0.0, 1.0, 0.0, 0.0, .5, -.5, 0.0, 0.0, 1.0, 0.0, 0.0, 0.5, 0.0, 0.0, 0.0, 1.0 ] triangle = numpy.array(triangle, dtype=numpy.float32) vertex_shader = """ #version 410 core in vec3 position; in vec3 color; out vec3 newColor; void main() { gl_Position = vec4(position, 1.0f); newColor = color; } """ fragment_shader = """ #version 410 core in vec3 newColor; out vec4 outColor; void main() { outColor = vec4(newColor, 1.0f); } """ VAO = glGenVertexArrays(1) glBindVertexArray(VAO) shader = OpenGL.GL.shaders.compileProgram( OpenGL.GL.shaders.compileShader(vertex_shader, GL_VERTEX_SHADER), OpenGL.GL.shaders.compileShader(fragment_shader, GL_FRAGMENT_SHADER)) VBO = glGenBuffers(1) # vertex buffer object for GPU glBindBuffer(GL_ARRAY_BUFFER, VBO) #upload data to array buffer glBufferData(GL_ARRAY_BUFFER, 72, triangle, GL_STATIC_DRAW) #get position from vertex_shader variable position = glGetAttribLocation(shader, "position") glVertexAttribPointer(position, 3, GL_FLOAT, GL_FALSE, 24, ctypes.c_void_p(0)) glEnableVertexAttribArray(position) #get color from vertex_shader program variable color = glGetAttribLocation(shader, "color") glVertexAttribPointer(color, 3, GL_FLOAT, GL_FALSE, 24, ctypes.c_void_p(12)) glEnableVertexAttribArray(color) glUseProgram(shader) glClearColor(.2, .3, .2, 1.0) while not glfw.window_should_close(window): glfw.poll_events() glClear(GL_COLOR_BUFFER_BIT) glDrawArrays(GL_TRIANGLES, 0, 3) glfw.swap_buffers(window) glfw.terminate()
def initGlFwAndResources(title, startWidth, startHeight, initResources): global g_simpleShader global g_vertexArrayObject global g_vertexDataBuffer global g_mousePos global g_coordinateSystemModel global g_numMsaaSamples global g_currentMsaaSamples #glfw.window_hint(glfw.OPENGL_DEBUG_CONTEXT, 1) glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 3) glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 3) glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE) glfw.window_hint(glfw.SRGB_CAPABLE, 1) glfw.window_hint(glfw.OPENGL_FORWARD_COMPAT, GL_TRUE) #glfw.window_hint(glfw.SAMPLES, g_currentMsaaSamples) window = glfw.create_window(startWidth, startHeight, title, None, None) if not window: glfw.terminate() sys.exit(1) glfw.make_context_current(window) print( "--------------------------------------\nOpenGL\n Vendor: %s\n Renderer: %s\n Version: %s\n--------------------------------------\n" % (glGetString(GL_VENDOR).decode("utf8"), glGetString(GL_RENDERER).decode("utf8"), glGetString(GL_VERSION).decode("utf8")), flush=True) impl = ImGuiGlfwRenderer(window) #glDebugMessageCallback(GLDEBUGPROC(debugMessageCallback), None) # (although this glEnable(GL_DEBUG_OUTPUT) should not have been needed when # using the GLUT_DEBUG flag above...) #glEnable(GL_DEBUG_OUTPUT) # This ensures that the callback is done in the context of the calling # function, which means it will be on the stack in the debugger, which makes it # a lot easier to figure out why it happened. #glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS) g_simpleShader = buildBasicShader( """ #version 330 in vec3 positionIn; void main() { gl_Position = vec4(positionIn, 1.0); } """, """ #version 330 out vec4 fragmentColor; void main() { fragmentColor = vec4(1.0); } """) # Create Vertex array object and buffer with dummy data for now, we'll fill it later when rendering the frame (g_vertexDataBuffer, g_vertexArrayObject) = createVertexArrayObject([[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]]) glDisable(GL_CULL_FACE) glEnable(GL_DEPTH_TEST) glDepthFunc(GL_LEQUAL) #glEnable(GL_DEPTH_CLAMP) if initResources: initResources() g_coordinateSystemModel = None #ObjModel("data/coordinate_system.obj"); return window, impl
def main(): glfw.init() # for windowed windows glfw.window_hint(glfw.RESIZABLE, True) # opengl options glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 4) glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 6) global w w = glfw.create_window(800, 600, 'Window Title', None, None) glfw.make_context_current(w) #################### shaderProgram = make_shader_program() glUseProgram(shaderProgram) vao = glGenVertexArrays(1) glBindVertexArray(vao) tri_vbo = glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, tri_vbo) vertices = Vec(0, 0), Vec(0, 1), Vec(1, 1), Vec(1, 0) vertices = Vec(*vertices) glBufferData(GL_ARRAY_BUFFER, vertices.size, vertices.buffer, GL_STATIC_DRAW) glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, ctypes.c_void_p(0)) glEnableVertexAttribArray(0) colorUniform = glGetUniformLocation(shaderProgram, "color") glUniform4f(colorUniform, 1, 1, 1, 1) ################### node = PaddingNode( vertical="*", children=[ RowsNode(children=[ RowsNode(children=[ HintedNode(width=100, height=300, key="node1"), HintedNode(width=200, height=100, key="node2"), HintedNode(width=150, height=200, key="node3"), ]) ]) ]) def fbresize(): x = None while True: if x is None: x, y = glfw.get_framebuffer_size(w) else: _, x, y = yield from listen.on_framebuffer_size(w) # adjust viewport glViewport(0, 0, x, y) # adjust projection projection.set_uniform(shaderProgram, 'projection') projection.clear() projection.ortho(0, x, 0, y, 0, 100) # adjust node node_window_fit(node, w) listen.launch(fbresize()) def rectnode(node, color): while True: yield from node.on_draw() colorUniform = glGetUniformLocation(shaderProgram, "color") glUniform4f(colorUniform, color.x, color.y, color.z, color.w) projection.set_uniform(shaderProgram, 'modelview') projection.push() projection.translate(node.x, node.y, 0.0) projection.scale(node.width, node.height, 1) glDrawArrays(GL_TRIANGLE_FAN, 0, 4) projection.pop() listen.launch(rectnode(node["node1"], Vec(1, 0, 0, 1))) listen.launch(rectnode(node["node2"], Vec(0, 1, 0, 1))) listen.launch(rectnode(node["node3"], Vec(0, 0, 1, 1))) listen.launch(rectnode(node, Vec(0.2, 0.4, 0.3, 1))) while not glfw.window_should_close(w): glClearColor(0.0, 0.0, 0.0, 1.0) glClear(GL_COLOR_BUFFER_BIT) node.draw() glfw.swap_buffers(w) glfw.wait_events_timeout(0.01) # 100 fps listen.trigger_timers() glfw.terminate()
def main(): # Initialize the library if not glfw.init(): return # Set some window 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.GL_TRUE); glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE); glfw.window_hint(glfw.SAMPLES, 16) # This works as expected glfw.window_hint(glfw.RESIZABLE, 0) # These should work, but don't :( # could control focus w/ http://crunchbang.org/forums/viewtopic.php?id=22226 # ended up using xdotool, see run.py glfw.window_hint(glfw.FOCUSED, 0) # I've set 'shader-*' to raise in openbox-rc as workaround # Looking at the code and confirming version 3.1.2 and it should work glfw.window_hint(glfw.FLOATING, 1) # Create a windowed mode window and its OpenGL context window = glfw.create_window(300, 300, "shader-test", None, None) if not window: glfw.terminate() return # Move Window glfw.set_window_pos(window, 1600, 50) # Make the window's context current glfw.make_context_current(window) # vsync glfw.swap_interval(1) # Setup GL shaders, data, etc. initialize() # Loop until the user closes the window while not glfw.window_should_close(window): # Render here, e.g. using pyOpenGL render() # Swap front and back buffers glfw.swap_buffers(window) # Poll for and process events glfw.poll_events() glfw.terminate()
def main(): global delta_time global last_frame global cameraPos # global cameraFront if not glfw.init(): return w_width = 1920 w_height = 1080 glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 4) glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 1) glfw.window_hint(glfw.OPENGL_FORWARD_COMPAT, 1) glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE) glfw.window_hint(glfw.RESIZABLE, GL_TRUE) window = glfw.create_window(w_width, w_height, "MY OPENGL", None, None) if not window: glfw.terminate() return glfw.make_context_current(window) # Enable key events glfw.set_input_mode(window, glfw.STICKY_KEYS, GL_TRUE) # Enable key event callback # if glfw. MotionSupported(): # glfw.set_input_mode(window, glfw.GLFW_RAW_MOUSE_MOTION, glfw.TRUE) glfw.set_input_mode(window, glfw.CURSOR, glfw.CURSOR_DISABLED) glfw.set_key_callback(window, key_event) glfw.set_cursor_pos_callback(window, mouse_callback) glfw.set_scroll_callback(window, scroll_callback) #when window resize # glfw.set_window_size_callback(window, window_resize) #adding colors # x, y, z, r, g, b tx ty cube = [ -0.5, -0.5, -0.5, 0.0, 0.0, 0.5, -0.5, -0.5, 1.0, 0.0, 0.5, 0.5, -0.5, 1.0, 1.0, 0.5, 0.5, -0.5, 1.0, 1.0, -0.5, 0.5, -0.5, 0.0, 1.0, -0.5, -0.5, -0.5, 0.0, 0.0, -0.5, -0.5, 0.5, 0.0, 0.0, 0.5, -0.5, 0.5, 1.0, 0.0, 0.5, 0.5, 0.5, 1.0, 1.0, 0.5, 0.5, 0.5, 1.0, 1.0, -0.5, 0.5, 0.5, 0.0, 1.0, -0.5, -0.5, 0.5, 0.0, 0.0, -0.5, 0.5, 0.5, 1.0, 0.0, -0.5, 0.5, -0.5, 1.0, 1.0, -0.5, -0.5, -0.5, 0.0, 1.0, -0.5, -0.5, -0.5, 0.0, 1.0, -0.5, -0.5, 0.5, 0.0, 0.0, -0.5, 0.5, 0.5, 1.0, 0.0, 0.5, 0.5, 0.5, 1.0, 0.0, 0.5, 0.5, -0.5, 1.0, 1.0, 0.5, -0.5, -0.5, 0.0, 1.0, 0.5, -0.5, -0.5, 0.0, 1.0, 0.5, -0.5, 0.5, 0.0, 0.0, 0.5, 0.5, 0.5, 1.0, 0.0, -0.5, -0.5, -0.5, 0.0, 1.0, 0.5, -0.5, -0.5, 1.0, 1.0, 0.5, -0.5, 0.5, 1.0, 0.0, 0.5, -0.5, 0.5, 1.0, 0.0, -0.5, -0.5, 0.5, 0.0, 0.0, -0.5, -0.5, -0.5, 0.0, 1.0, -0.5, 0.5, -0.5, 0.0, 1.0, 0.5, 0.5, -0.5, 1.0, 1.0, 0.5, 0.5, 0.5, 1.0, 0.0, 0.5, 0.5, 0.5, 1.0, 0.0, -0.5, 0.5, 0.5, 0.0, 0.0, -0.5, 0.5, -0.5, 0.0, 1.0, #ground -10, -1.1, 20, 0.0, 0.0, 10, -1.1, 20, 0.0, 1.0, -10, -1.1, -300, 1.0, 1.0, 10, -1.1, -300, 1.0, 0.0 ] # Positions # Texture Coords # cube = [ 0.5, 0.5, 0.0, 1.0, 1.0, # Top Right # 0.5, -0.5, 0.0, 1.0, 0.0, # Bottom Right # -0.5, -0.5, 0.0, 0.0, 0.0, # Bottom Let # -0.5, 0.5, 0.0, 0.0, 1.0] # Top Left cube = numpy.array(cube, dtype=numpy.float32) # indices = [ # 0, 1, 2, 2, 3, 0, # 4, 5, 6, 6, 7, 4, # 8, 9, 10, 10, 11, 8, # 12, 13, 14, 14, 15, 12, # 16, 17, 18, 18, 19, 16, # 20, 21, 22, 22, 23, 20 # ] # indices = [ # 0, 1, 3, # 1, 2, 3 # ] global cube_positions cube_positions = [ pyrr.Vector3([ 0.0, 0.0, 0.0]), pyrr.Vector3([ 2.0,5.0, -15.0]), pyrr.Vector3([-1.5, -2.2, -2.5]), pyrr.Vector3([-3.8, -2.0, -12.3]), pyrr.Vector3([ 2.4, -0.4, -3.5]), pyrr.Vector3([-1.7,3.0, -7.5]), pyrr.Vector3([ 1.3, -2.0, -2.5]), pyrr.Vector3([ 1.5,2.0, -2.5]), pyrr.Vector3([ 1.5,0.2, -1.5]), pyrr.Vector3([-1.3,1.0, -1.5]), ] # ground_vertices = [ # -10, -1.1, 20, # 10, -1.1, 20, # -10, -1.1, -300, # 10, -1.1, -300, # ] # indices = numpy.arraypyrr.Vector3([indices, dtype=numpy.uint32) VAO = glGenVertexArrays(1) glBindVertexArray(VAO) shader = shaderLoader.compile_shader("./shaders/vertex_shader1.vs", "./shaders/fragment_shader1.fs") VBO = glGenBuffers(1) # vertex buffer object for GPU glBindBuffer(GL_ARRAY_BUFFER, VBO) #upload data to array buffer # buf type byte point type glBufferData(GL_ARRAY_BUFFER, cube.itemsize * len(cube), cube, GL_STATIC_DRAW) #get position from vertex_shader variable position = glGetAttribLocation(shader, "position") glVertexAttribPointer(position, 3, GL_FLOAT, GL_FALSE, 20, ctypes.c_void_p(0)) glEnableVertexAttribArray(position) #get color from vertex_shader program variable # color = glGetAttribLocation(shader, "color") # glVertexAttribPointer(color, 3, GL_FLOAT, GL_FALSE, 32, ctypes.c_void_p(12)) # glEnableVertexAttribArray(color) texture_cords = glGetAttribLocation(shader, "inTexCords") glVertexAttribPointer(texture_cords, 2, GL_FLOAT, GL_FALSE, 20, ctypes.c_void_p(12)) glEnableVertexAttribArray(texture_cords) #load texture texture = glGenTextures(1) glBindTexture(GL_TEXTURE_2D, texture) # texture wrapping parametr glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT) #texture filtering parametr glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR) image = Image.open("./res/block.jpg") flipped_image = image.transpose(Image.FLIP_TOP_BOTTOM) image_data = numpy.array(list(flipped_image.getdata()), numpy.uint8) glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, image.width, image.height, 0, GL_RGB, GL_UNSIGNED_BYTE, image_data) glUseProgram(shader) # glClearColor(.2, .3, .2, 1.0) glEnable(GL_DEPTH_TEST) # glPolygonMode(GL_FRONT_AND_BACK, GL_LINE) #perspective part # view matrix # view = pyrr.matrix44.create_from_translation(pyrr.Vector3([.0, .0, -3.0])) # global view # projection matrix projection = pyrr.matrix44.create_perspective_projection(45.0, w_width / w_height, 0.1, 100.0) print("[PROJECTION MATRIX]") print(projection) view_location = glGetUniformLocation(shader, "view") projection_location = glGetUniformLocation(shader, "projection") model_location = glGetUniformLocation(shader, "model") # glUniformMatrix4fv(view_location, 1, GL_FALSE, view) glUniformMatrix4fv(projection_location, 1, GL_FALSE, projection) # rot_x = pyrr.matrix44.create_from_x_rotation(sin(glfw.get_time()) * 2) while not glfw.window_should_close(window): w = 0 glfw.poll_events() do_movement() glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) current_frame = glfw.get_time() delta_time = current_frame - last_frame last_frame = current_frame # pyrr.matrix44.create_look_at(eye, target, up, dtype=None) # radius = 10.0 # camX = sin(glfw.get_time()) * radius # camZ = cos(glfw.get_time()) * radius # view = pyrr.matrix44.create_look_at(pyrr.Vector3([camX, 0.0, camZ]), pyrr.Vector3([0.0, 0.0, 0.0]), pyrr.Vector3([0.0, 1.0, 0.0])) global view # cameraPos.y = 0.5 view = pyrr.Matrix44.look_at(cameraPos, cameraPos + cameraFront, cameraUp) glUniformMatrix4fv(view_location, 1, GL_FALSE, view) # model = pyrr.matrix44.create_from_translation(pyrr.Vector3([0.0, 0.0, 0.0])) # glUniformMatrix4fv(model_location, 1, GL_FALSE, model) # for i in range(len(cube_positions)): # if int(cameraPos.x) == int(cube_positions[i][0]) and \ # int(cameraPos.y) == int(cube_positions[i][1]) and \ # int(cameraPos.z) == int(cube_positions[i][2]): # w = 1 # if w: # w = 0 # continue # glDrawArrays(GL_TRIANGLES, 36, 39) # cube_positions_len = len(cube_positions) - 20w # print(cameraPos.z) # for i in range(len(cube_positions)): # if int(cube_positions[i][2]) >= int(cameraPos.z): # return # rangeIntersect: function(min0, max0, min1, max1) { # return Math.max(min0, max0) >= Math.min(min1, max1) && # Math.min(min0, max0) <= Math.max(min1, max1); # }, # rectIntersect: function(r0, r1) { # return utils.rangeIntersect(r0.x, r0.x + r0.width, r1.x, r1.x + r1.width) && # utils.rangeIntersect(r0.y, r0.y + r0.height, r1.y, r1.y + r1.height); # } rot_x = pyrr.matrix44.create_from_x_rotation(sin(glfw.get_time()) * 2) for i in range(len(cube_positions)): model = pyrr.matrix44.create_from_translation(cube_positions[i]) # print(model) angle = 0 # # angle = i # if i % 3 == 0: # angle = glfw.get_time() * 180 # angle = sin(radians(angle)) * cos(radians(angle)) # # if i % 4 == 0: # # angle = sin(glfw.get_time()) * 50 # if i == 8: # # angle = 0 # angle = sin(glfw.get_time()) * 50 # if i % 3 == 0: # rot = # model = pyrr.matrix44.multiply(rot_x, model) # if w == 0: # print(model) if i == 0: # radius = 100 # for angle in range(0, 361): # theta = math.radians(angle) # x = radius*math.cos(theta) # y = radius*math.sin(theta) # print(x, y) # rot = pyrr.matrix44.create_from_axis_rotation(cameraFront, 1) # rot = pyrr.matrix44.create_from_translation(cameraFront + camera) # pyrr.matrix44.create_from_x_rotation() radius = 4 theta = radians(glfw.get_time() * 100) rot_y = pyrr.matrix44.create_from_y_rotation(glfw.get_time() * 0.5) # X := originX + cos(angle)*radius; # Y := originY + sin(angle)*radius; cube_positions[0][0] = cameraPos.x + cos(theta) * radius cube_positions[0][1] = cameraPos.y cube_positions[0][2] = cameraPos.z + sin(theta) * radius model = pyrr.matrix44.multiply(rot_y, model) # model = pyrr.matrix44.create_from_translation(cube_positions[0]) # model = pyrr.matrix44.multiply(cube_positions[i]), model) # model = pyrr.Matrix44.look_at(cube_positions[i], cube_positions[i] + cameraFront, cameraUp) # model = pyrr.matrix44.inverse(model) # rot = pyrr.matrix44.create_from_axis_rotation(pyrr.Vector3([]), angle) glUniformMatrix4fv(model_location, 1, GL_FALSE, model) glDrawArrays(GL_TRIANGLES, 0, 36) # w = 1 # glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, None) glfw.swap_buffers(window) glfw.terminate()
def initglfw(self): glfw.init() # TODO: Check if init successful, exit otherwise glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 4) glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 5) glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE) glfw.window_hint(glfw.SAMPLES, 4) glfw.window_hint(glfw.AUTO_ICONIFY, False) glfw.window_hint(glfw.DECORATED, False)
def main(): global delta_time, last_frame glfw.init() glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 3) glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 3) glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE) window = glfw.create_window(SRC_WIDTH, SRC_HEIGHT, "learnOpenGL", None, None) if not window: glfw.terminate() raise ValueError("Failed to create window") 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) glfw.set_input_mode(window, glfw.CURSOR, glfw.CURSOR_DISABLED) gl.glEnable(gl.GL_DEPTH_TEST) lamp_shader = Shader(CURDIR / "shaders/1.lamp.vs", CURDIR / "shaders/6.1.lamp.fs") lighting_shader = Shader(CURDIR / "shaders/6.multiple_lights.vs", CURDIR / "shaders/6.multiple_lights.fs") vertices = [ # positions normals texture coords -0.5, -0.5, -0.5, 0.0, 0.0, -1.0, 0.0, 0.0, 0.5, -0.5, -0.5, 0.0, 0.0, -1.0, 1.0, 0.0, 0.5, 0.5, -0.5, 0.0, 0.0, -1.0, 1.0, 1.0, 0.5, 0.5, -0.5, 0.0, 0.0, -1.0, 1.0, 1.0, -0.5, 0.5, -0.5, 0.0, 0.0, -1.0, 0.0, 1.0, -0.5, -0.5, -0.5, 0.0, 0.0, -1.0, 0.0, 0.0, -0.5, -0.5, 0.5, 0.0, 0.0, 1.0, 0.0, 0.0, 0.5, -0.5, 0.5, 0.0, 0.0, 1.0, 1.0, 0.0, 0.5, 0.5, 0.5, 0.0, 0.0, 1.0, 1.0, 1.0, 0.5, 0.5, 0.5, 0.0, 0.0, 1.0, 1.0, 1.0, -0.5, 0.5, 0.5, 0.0, 0.0, 1.0, 0.0, 1.0, -0.5, -0.5, 0.5, 0.0, 0.0, 1.0, 0.0, 0.0, -0.5, 0.5, 0.5, -1.0, 0.0, 0.0, 1.0, 0.0, -0.5, 0.5, -0.5, -1.0, 0.0, 0.0, 1.0, 1.0, -0.5, -0.5, -0.5, -1.0, 0.0, 0.0, 0.0, 1.0, -0.5, -0.5, -0.5, -1.0, 0.0, 0.0, 0.0, 1.0, -0.5, -0.5, 0.5, -1.0, 0.0, 0.0, 0.0, 0.0, -0.5, 0.5, 0.5, -1.0, 0.0, 0.0, 1.0, 0.0, 0.5, 0.5, 0.5, 1.0, 0.0, 0.0, 1.0, 0.0, 0.5, 0.5, -0.5, 1.0, 0.0, 0.0, 1.0, 1.0, 0.5, -0.5, -0.5, 1.0, 0.0, 0.0, 0.0, 1.0, 0.5, -0.5, -0.5, 1.0, 0.0, 0.0, 0.0, 1.0, 0.5, -0.5, 0.5, 1.0, 0.0, 0.0, 0.0, 0.0, 0.5, 0.5, 0.5, 1.0, 0.0, 0.0, 1.0, 0.0, -0.5, -0.5, -0.5, 0.0, -1.0, 0.0, 0.0, 1.0, 0.5, -0.5, -0.5, 0.0, -1.0, 0.0, 1.0, 1.0, 0.5, -0.5, 0.5, 0.0, -1.0, 0.0, 1.0, 0.0, 0.5, -0.5, 0.5, 0.0, -1.0, 0.0, 1.0, 0.0, -0.5, -0.5, 0.5, 0.0, -1.0, 0.0, 0.0, 0.0, -0.5, -0.5, -0.5, 0.0, -1.0, 0.0, 0.0, 1.0, -0.5, 0.5, -0.5, 0.0, 1.0, 0.0, 0.0, 1.0, 0.5, 0.5, -0.5, 0.0, 1.0, 0.0, 1.0, 1.0, 0.5, 0.5, 0.5, 0.0, 1.0, 0.0, 1.0, 0.0, 0.5, 0.5, 0.5, 0.0, 1.0, 0.0, 1.0, 0.0, -0.5, 0.5, 0.5, 0.0, 1.0, 0.0, 0.0, 0.0, -0.5, 0.5, -0.5, 0.0, 1.0, 0.0, 0.0, 1.0 ] vertices = (c_float * len(vertices))(*vertices) cube_positions = [(0.0, 0.0, 0.0), (2.0, 5.0, -15.0), (-1.5, -2.2, -2.5), (-3.8, -2.0, -12.3), (2.4, -0.4, -3.5), (-1.7, 3.0, -7.5), (1.3, -2.0, -2.5), (1.5, 2.0, -2.5), (1.5, 0.2, -1.5), (-1.3, 1.0, -1.5)] point_light_positions = [ (0.7, 0.2, 2.0), (2.3, -3.3, -4.0), (-4.0, 2.0, -12.0), (0.0, 0.0, -3.0), ] light_settings = { "desert": { "clear_color": (.75, .52, .30, 1.0), "direction_color": (.4, .4, .4), "spot_color": (.2, .2, .2), "point_colors": [(1.0, 0.0, 0.0), (1.0, 0.6, 0.0), (1.0, 0.0, 0.0), (1.0, 0.6, 0.0)] }, "factory": { "clear_color": (0.01, 0.01, 0.01, 1.0), "direction_color": (.4, .4, .4), "spot_color": (.2, .2, .2), "point_colors": [(.17, .17, .49), (.17, .17, .49), (.17, .17, .49), (.17, .17, .49)] }, "horror": { "clear_color": (0.0, 0.0, 0.0, 1.0), "direction_color": (.01, .01, .01), "spot_color": (.2, .2, .2), "point_colors": [(.3, .1, .1), (.3, .1, .1), (.3, .1, .1), (.3, .1, .1)] }, "biochemical_lab": { "clear_color": (0.9, 0.9, 0.9, 1.0), "direction_color": (.4, .4, .4), "spot_color": (.2, .2, .2), "point_colors": [(0.4, 0.7, 0.1), (0.4, 0.7, 0.1), (0.4, 0.7, 0.1), (0.4, 0.7, 0.1)] }, } cube_vao = gl.glGenVertexArrays(1) vbo = gl.glGenBuffers(1) gl.glBindBuffer(gl.GL_ARRAY_BUFFER, vbo) gl.glBufferData(gl.GL_ARRAY_BUFFER, sizeof(vertices), vertices, gl.GL_STATIC_DRAW) gl.glBindVertexArray(cube_vao) # -- position attribute gl.glVertexAttribPointer(0, 3, gl.GL_FLOAT, gl.GL_FALSE, 8 * sizeof(c_float), c_void_p(0)) gl.glEnableVertexAttribArray(0) # -- normal attribute gl.glVertexAttribPointer(1, 3, gl.GL_FLOAT, gl.GL_FALSE, 8 * sizeof(c_float), c_void_p(3 * sizeof(c_float))) gl.glEnableVertexAttribArray(1) # -- texture coordinate gl.glVertexAttribPointer(2, 2, gl.GL_FLOAT, gl.GL_FALSE, 8 * sizeof(c_float), c_void_p(6 * sizeof(c_float))) gl.glEnableVertexAttribArray(2) # -- second configure light vao (vbo is the same) light_vao = gl.glGenVertexArrays(1) gl.glBindVertexArray(light_vao) gl.glBindBuffer(gl.GL_ARRAY_BUFFER, vbo) gl.glVertexAttribPointer(0, 3, gl.GL_FLOAT, gl.GL_FALSE, 8 * sizeof(c_float), c_void_p(0)) gl.glEnableVertexAttribArray(0) # -- load texture diffuse_map = load_texture("container2.png") specular_map = load_texture("container2_specular.png") # -- shader configuration lighting_shader.use() lighting_shader.set_int("material.diffuse", 0) lighting_shader.set_int("material.specular", 1) LIGHTS = light_settings.get("horror") while not glfw.window_should_close(window): # -- time logic current_frame = glfw.get_time() delta_time = current_frame - last_frame last_frame = current_frame # -- input process_input(window) # -- render gl.glClearColor(*LIGHTS.get("clear_color")) gl.glClear(gl.GL_COLOR_BUFFER_BIT | gl.GL_DEPTH_BUFFER_BIT) lighting_shader.use() lighting_shader.set_vec3("viewPos", camera.position) lighting_shader.set_float("material.shininess", 32.0) # -- directional light lighting_shader.set_vec3("dirLight.direction", [-0.2, -1.0, -0.3]) lighting_shader.set_vec3("dirLight.ambient", [0.05, 0.05, 0.05]) lighting_shader.set_vec3("dirLight.diffuse", LIGHTS.get("direction_color")) lighting_shader.set_vec3("dirLight.specular", [0.5, 0.5, 0.5]) # -- point light 1 lighting_shader.set_vec3("pointLights[0].position", point_light_positions[0]) lighting_shader.set_vec3("pointLights[0].ambient", [0.05, 0.05, 0.05]) lighting_shader.set_vec3("pointLights[0].diffuse", LIGHTS.get("point_colors")[0]) lighting_shader.set_vec3("pointLights[0].specular", [1.0, 1.0, 1.0]) lighting_shader.set_float("pointLights[0].constant", 1.0) lighting_shader.set_float("pointLights[0].linear", 0.09) lighting_shader.set_float("pointLights[0].quadratic", 0.032) # -- point light 2 lighting_shader.set_vec3("pointLights[1].position", point_light_positions[1]) lighting_shader.set_vec3("pointLights[1].ambient", [0.05, 0.05, 0.05]) lighting_shader.set_vec3("pointLights[1].diffuse", LIGHTS.get("point_colors")[1]) lighting_shader.set_vec3("pointLights[1].specular", [1.0, 1.0, 1.0]) lighting_shader.set_float("pointLights[1].constant", 1.0) lighting_shader.set_float("pointLights[1].linear", 0.09) lighting_shader.set_float("pointLights[1].quadratic", 0.032) # -- point light 3 lighting_shader.set_vec3("pointLights[2].position", point_light_positions[2]) lighting_shader.set_vec3("pointLights[2].ambient", [0.05, 0.05, 0.05]) lighting_shader.set_vec3("pointLights[2].diffuse", LIGHTS.get("point_colors")[2]) lighting_shader.set_vec3("pointLights[2].specular", [1.0, 1.0, 1.0]) lighting_shader.set_float("pointLights[2].constant", 1.0) lighting_shader.set_float("pointLights[2].linear", 0.09) lighting_shader.set_float("pointLights[2].quadratic", 0.032) # -- point light 4 lighting_shader.set_vec3("pointLights[3].position", point_light_positions[3]) lighting_shader.set_vec3("pointLights[3].ambient", [0.05, 0.05, 0.05]) lighting_shader.set_vec3("pointLights[3].diffuse", LIGHTS.get("point_colors")[3]) lighting_shader.set_vec3("pointLights[3].specular", [1.0, 1.0, 1.0]) lighting_shader.set_float("pointLights[3].constant", 1.0) lighting_shader.set_float("pointLights[3].linear", 0.09) lighting_shader.set_float("pointLights[3].quadratic", 0.032) # -- spotLight lighting_shader.set_vec3("spotLight.position", camera.position) lighting_shader.set_vec3("spotLight.direction", camera.front) lighting_shader.set_vec3("spotLight.ambient", [0.0, 0.0, 0.0]) lighting_shader.set_vec3("spotLight.diffuse", LIGHTS.get("spot_color")) lighting_shader.set_vec3("spotLight.specular", [1.0, 1.0, 1.0]) lighting_shader.set_float("spotLight.constant", 1.0) lighting_shader.set_float("spotLight.linear", 0.09) lighting_shader.set_float("spotLight.quadratic", 0.032) lighting_shader.set_float("spotLight.cutOff", math.cos(math.radians(12.5))) lighting_shader.set_float("spotLight.outerCutOff", math.cos(math.radians(15.0))) # -- view.projection transformations projection = Matrix44.perspective_projection(camera.zoom, SRC_WIDTH / SRC_HEIGHT, 0.1, 100.0) view = camera.get_view_matrix() lighting_shader.set_mat4("projection", projection) lighting_shader.set_mat4("view", view) # -- world transformation model = Matrix44.identity() lighting_shader.set_mat4("model", model) # -- bind diffuse map gl.glActiveTexture(gl.GL_TEXTURE0) gl.glBindTexture(gl.GL_TEXTURE_2D, diffuse_map) # -- bind specular map gl.glActiveTexture(gl.GL_TEXTURE1) gl.glBindTexture(gl.GL_TEXTURE_2D, specular_map) # -- render continers gl.glBindVertexArray(cube_vao) for idx, position in enumerate(cube_positions): angle = 20.0 * idx rotation = matrix44.create_from_axis_rotation([1.0, 0.3, 0.5], math.radians(angle)) translation = Matrix44.from_translation(position) model = translation * rotation lighting_shader.set_mat4('model', model) gl.glDrawArrays(gl.GL_TRIANGLES, 0, 36) # -- draw lamp object(s) lamp_shader.use() lamp_shader.set_mat4("projection", projection) lamp_shader.set_mat4("view", view) gl.glBindVertexArray(light_vao) for idx, pos in enumerate(point_light_positions): model = Matrix44.identity() model *= Matrix44.from_translation(pos) model *= Matrix44.from_scale(Vector3([.2, .2, .2])) lamp_shader.set_mat4("model", model) lamp_shader.set_vec3("color", LIGHTS.get("point_colors")[idx]) gl.glDrawArrays(gl.GL_TRIANGLES, 0, 36) glfw.swap_buffers(window) glfw.poll_events() gl.glDeleteVertexArrays(1, id(cube_vao)) gl.glDeleteVertexArrays(1, id(light_vao)) gl.glDeleteBuffers(1, id(vbo)) glfw.terminate()
from __future__ import annotations # to appease Python 3.7-3.9 import sys import os import numpy as np import math from OpenGL.GL import * import glfw from dataclasses import dataclass if not glfw.init(): sys.exit() glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 1) glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 4) window = glfw.create_window(500, 500, "ModelViewProjection Demo 17", None, None) if not window: glfw.terminate() sys.exit() glfw.make_context_current(window) def on_key(window, key, scancode, action, mods): if key == glfw.KEY_ESCAPE and action == glfw.PRESS: glfw.set_window_should_close(window, 1)
def main(): global shader vertex_src = """ # version 330 layout(location = 0) in vec3 a_position; layout(location = 1) in vec2 a_texture; layout(location = 2) in vec3 a_normal; uniform mat4 model; uniform mat4 projection; uniform mat4 view; out vec2 v_texture; void main() { gl_Position = projection * view * model * vec4(a_position, 1.0); v_texture = a_texture; } """ fragment_src = """ # version 330 in vec2 v_texture; out vec4 out_color; uniform sampler2D s_texture; void main() { out_color = texture(s_texture, v_texture); } """ # initializing glfw library if not glfw.init(): raise Exception("glfw can not be initialized!") if "Windows" in pltf.platform(): glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 4) glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 6) glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE) glfw.window_hint(glfw.OPENGL_FORWARD_COMPAT, True) else: glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 4) glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 1) glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE) glfw.window_hint(glfw.OPENGL_FORWARD_COMPAT, True) # creating the window window = glfw.create_window(WIDTH, HEIGHT, "My OpenGL window", None, None) # check if window was created if not window: glfw.terminate() raise Exception("glfw window can not be created!") # set window's position glfw.set_window_pos(window, 100, 100) # set the callback function for window resize glfw.set_window_size_callback(window, window_resize_clb) # set the mouse position callback glfw.set_cursor_pos_callback(window, mouse_look_clb) # set the keyboard input callback glfw.set_key_callback(window, key_input_clb) # capture the mouse cursor glfw.set_input_mode(window, glfw.CURSOR, glfw.CURSOR_DISABLED) # make the context current glfw.make_context_current(window) # load here the 3d meshes cube_indices, cube_buffer = ObjLoader.load_model("meshes/cube.obj") monkey_indices, monkey_buffer = ObjLoader.load_model("meshes/monkey.obj") floor_indices, floor_buffer = ObjLoader.load_model("meshes/floor.obj") # VAO and VBO VAO = glGenVertexArrays(3) VBO = glGenBuffers(3) # cube VAO glBindVertexArray(VAO[0]) shader = compileProgram(compileShader(vertex_src, GL_VERTEX_SHADER), compileShader(fragment_src, GL_FRAGMENT_SHADER)) # cube Vertex Buffer Object glBindBuffer(GL_ARRAY_BUFFER, VBO[0]) glBufferData(GL_ARRAY_BUFFER, cube_buffer.nbytes, cube_buffer, GL_STATIC_DRAW) # cube vertices glEnableVertexAttribArray(0) glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, cube_buffer.itemsize * 8, ctypes.c_void_p(0)) # cube textures glEnableVertexAttribArray(1) glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, cube_buffer.itemsize * 8, ctypes.c_void_p(12)) # cube normals glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, cube_buffer.itemsize * 8, ctypes.c_void_p(20)) glEnableVertexAttribArray(2) # monkey VAO glBindVertexArray(VAO[1]) # monkey Vertex Buffer Object glBindBuffer(GL_ARRAY_BUFFER, VBO[1]) glBufferData(GL_ARRAY_BUFFER, monkey_buffer.nbytes, monkey_buffer, GL_STATIC_DRAW) # monkey vertices glEnableVertexAttribArray(0) glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, monkey_buffer.itemsize * 8, ctypes.c_void_p(0)) # monkey textures glEnableVertexAttribArray(1) glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, monkey_buffer.itemsize * 8, ctypes.c_void_p(12)) # monkey normals glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, monkey_buffer.itemsize * 8, ctypes.c_void_p(20)) glEnableVertexAttribArray(2) # floor VAO glBindVertexArray(VAO[2]) # floor Vertex Buffer Object glBindBuffer(GL_ARRAY_BUFFER, VBO[2]) glBufferData(GL_ARRAY_BUFFER, floor_buffer.nbytes, floor_buffer, GL_STATIC_DRAW) # floor vertices glEnableVertexAttribArray(0) glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, floor_buffer.itemsize * 8, ctypes.c_void_p(0)) # floor textures glEnableVertexAttribArray(1) glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, floor_buffer.itemsize * 8, ctypes.c_void_p(12)) # floor normals glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, floor_buffer.itemsize * 8, ctypes.c_void_p(20)) glEnableVertexAttribArray(2) textures = glGenTextures(3) load_texture("meshes/cube.jpg", textures[0]) load_texture("meshes/monkey.jpg", textures[1]) load_texture("meshes/floor.jpg", textures[2]) glUseProgram(shader) glClearColor(0, 0.1, 0.1, 1) glEnable(GL_DEPTH_TEST) glEnable(GL_BLEND) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) projection = pyrr.matrix44.create_perspective_projection_matrix(45, WIDTH / HEIGHT, 0.1, 100) cube_pos = pyrr.matrix44.create_from_translation(pyrr.Vector3([6, 4, 0])) monkey_pos = pyrr.matrix44.create_from_translation(pyrr.Vector3([-4, 4, -4])) floor_pos = pyrr.matrix44.create_from_translation(pyrr.Vector3([0, 0, 0])) model_loc = glGetUniformLocation(shader, "model") proj_loc = glGetUniformLocation(shader, "projection") view_loc = glGetUniformLocation(shader, "view") glUniformMatrix4fv(proj_loc, 1, GL_FALSE, projection) glUseProgram(0) # the main application loop while not glfw.window_should_close(window): glfw.poll_events() glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) view = cam.get_view_matrix() glUseProgram(shader) glUniformMatrix4fv(view_loc, 1, GL_FALSE, view) rot_y = pyrr.Matrix44.from_y_rotation(0.8 * glfw.get_time()) model = pyrr.matrix44.multiply(rot_y, cube_pos) # draw the cube glBindVertexArray(VAO[0]) glBindTexture(GL_TEXTURE_2D, textures[0]) glUniformMatrix4fv(model_loc, 1, GL_FALSE, model) glDrawArrays(GL_TRIANGLES, 0, len(monkey_indices)) # draw the monkey glBindVertexArray(VAO[1]) glBindTexture(GL_TEXTURE_2D, textures[1]) glUniformMatrix4fv(model_loc, 1, GL_FALSE, monkey_pos) glDrawArrays(GL_TRIANGLES, 0, len(monkey_indices)) # draw the floor glBindVertexArray(VAO[2]) glBindTexture(GL_TEXTURE_2D, textures[2]) glUniformMatrix4fv(model_loc, 1, GL_FALSE, floor_pos) glDrawArrays(GL_TRIANGLES, 0, len(floor_indices)) glUseProgram(0) glfw.swap_buffers(window) # terminate glfw, free up allocated resources glfw.terminate()
def __init__(self, width=800, height=600, title="QLibs window", swap_interval=1, hint_conf=default_hint_conf, resizable=True, fullscreen=False, transparent=False): self.width = width self.height = height self.resize_callback = None self.mouse_motion_callback = None self.mouse_button_callback = None self.scroll_callback = None self.key_callback = None self.spec_key_callback = None self.flip_mouse_y = False #flipped relatively to usual math-y representation glfw.init() glfw.window_hint(glfw.RESIZABLE, resizable and not fullscreen) glfw.window_hint(glfw.TRANSPARENT_FRAMEBUFFER, transparent) for k, v in hint_conf.items(): glfw.window_hint(k, v) monitor = None if fullscreen: monitor = glfw.get_primary_monitor() mode = glfw.get_video_mode(monitor) width = mode.size.width height = mode.size.height #width = 1920 #height = 1080 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) try: self.window = glfw.create_window(width, height, title, monitor, None) except glfw.GLFWError: logger.warn( "Provided config is unavailable, using fallback config") glfw.default_window_hints() for k, v in fallback_hint_conf.items(): glfw.window_hint(k, v) self.window = glfw.create_window(width, height, title, None, None) if fullscreen: self.width, self.height = glfw.get_framebuffer_size( self.window) #Required on windows glfw.set_window_user_pointer(self.window, id(self.window)) glfw.make_context_current(self.window) glfw.swap_interval(swap_interval) #callbacks glfw.set_window_size_callback(self.window, self._on_resize) glfw.set_framebuffer_size_callback(self.window, self._update_viewport) glfw.set_cursor_pos_callback(self.window, self._on_mouse_motion) glfw.set_mouse_button_callback(self.window, self._on_mouse_button) glfw.set_char_mods_callback(self.window, self._on_key_press) glfw.set_key_callback(self.window, self._on_spec_key_press) glfw.set_scroll_callback(self.window, self._on_scroll) try: self.ctx = moderngl.create_context() except: self.ctx = moderngl.create_context(libgl='libGL.so.1')
def __init__(self, win, backendConf=None): """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). backendConf : `dict` or `None` Backend configuration options. Options are specified as a dictionary where keys are option names and values are settings. For this backend the following options are available: * `share` (`psychopy.visual.Window instance`) PsychoPy Window to share a context with. * `refreshHz` (`int`) Refresh rate in Hertz. * `bpc` (`array_like`) Bits per color (R, G, B). * `swapInterval` (`int`) Swap interval for the current OpenGL context. * `depthBits` (`int`) Framebuffer (back buffer) depth bits. * `stencilBits` (`int`) Framebuffer (back buffer) stencil bits. * `winTitle` (`str`) Optional window title string. Examples -------- Create a window using the GLFW backend and specify custom options:: import psychopy.visual as visual options = {'bpc': (8, 8, 8), 'depthBits': 24, 'stencilBits': 8} win = visual.Window(winType='glfw', backendOptions=options) """ BaseBackend.__init__(self, win) # if `None`, change to `dict` to extract options backendConf = backendConf if backendConf is not None else {} if not isinstance(backendConf, dict): # type check on options raise TypeError( 'Object passed to `backendConf` must be type `dict`.') # window to share a context with shareWin = backendConf.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 bpc = backendConf.get('bpc', (8, 8, 8)) if isinstance(bpc, int): win.bpc = (bpc, bpc, bpc) else: win.bpc = bpc win.refreshHz = int(backendConf.get('refreshHz', 60)) win.depthBits = int(backendConf.get('depthBits', 8)) win.stencilBits = int(backendConf.get('stencilBits', 8)) # win.swapInterval = int(backendConf.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 ...")) actualWidth, actualHeight = nativeVidmode.size redBits, greenBits, blueBits = nativeVidmode.bits # change the window settings if win._isFullScr: logging.warning( ("Overriding user video settings: size {} -> {}, bpc {} -> " "{}, refreshHz {} -> {}".format( tuple(win.size), (actualWidth, actualHeight), tuple(win.bpc), (redBits, greenBits, blueBits), win.refreshHz, nativeVidmode.refresh_rate))) win.clientSize = np.array((actualWidth, actualHeight), int) else: logging.warning( ("Overriding user video settings: bpc {} -> " "{}, refreshHz {} -> {}".format( tuple(win.bpc), (redBits, greenBits, blueBits), win.refreshHz, nativeVidmode.refresh_rate))) win.bpc = (redBits, greenBits, blueBits) win.refreshHz = nativeVidmode.refresh_rate 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.clientSize[0], height=win.clientSize[1], title=str(backendConf.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.clientSize[0]) / 2.0, (size[1] - win.clientSize[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 if hasattr(glfw, 'set_window_icon'): glfw.set_window_icon(self.winHandle, 1, _WINDOW_ICON_) # set the window size to the framebuffer size self._frameBufferSize = 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, self.onMouseButton) glfw.set_cursor_pos_callback(self.winHandle, self.onMouseMove) glfw.set_cursor_enter_callback(self.winHandle, self.onMouseEnter) glfw.set_scroll_callback(self.winHandle, self.onMouseScroll) 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(backendConf.get('swapInterval', 1))) # give the window class GLFW specific methods win.setMouseType = self.setMouseType if not win.allowGUI: self.setMouseVisibility(False)
def main(): if not glfw.init(): return glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 4) glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 1) glfw.window_hint(glfw.OPENGL_FORWARD_COMPAT, GL_TRUE) glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE) w_width, w_height = 1440, 900 window = glfw.create_window(w_width, w_height, "My OpenGL Window", None, None) #window = glfw.create_window(w_width,w_height,"My OpenGL Window", glfw.get_primary_monitor(), None) if not window: glfw.terminate() return glfw.make_context_current(window) glfw.set_key_callback(window, key_callback) glfw.set_cursor_pos_callback(window, mouse_callback) glfw.set_input_mode(window, glfw.CURSOR, glfw.CURSOR_DISABLED) monkey_obj = ObjLoader() monkey_obj.load_model('monkey.obj') monkey_tex = TextureLoader.load_texture("res/monkey.png") monkey_tex_offset = len(monkey_obj.vertex_index) * 12 monkey_norm_offset = (monkey_tex_offset + len(monkey_obj.texture_index) * 8) sphere_obj = ObjLoader() sphere_obj.load_model('sphere2.obj') sphere_tex = TextureLoader.load_texture("res/yellow.png") sphere_tex_offset = len(sphere_obj.vertex_index) * 12 sphere_norm_offset = (sphere_tex_offset + len(sphere_obj.texture_index) * 8) shader = ShaderLoader.compile_shader("Shaders/vert.vs", "Shaders/frag.fs") sphere_vao = glGenVertexArrays(1) glBindVertexArray(sphere_vao) sphere_VBO = glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, sphere_VBO) glBufferData(GL_ARRAY_BUFFER, sphere_obj.model.itemsize * len(sphere_obj.model), sphere_obj.model, GL_STATIC_DRAW) #Position glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sphere_obj.model.itemsize * 3, ctypes.c_void_p(0)) glEnableVertexAttribArray(0) #TextureCoords glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, sphere_obj.model.itemsize * 2, ctypes.c_void_p(sphere_tex_offset)) glEnableVertexAttribArray(1) #Normals glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, sphere_obj.model.itemsize * 3, ctypes.c_void_p(sphere_norm_offset)) glEnableVertexAttribArray(2) glBindVertexArray(0) monkey_vao = glGenVertexArrays(1) glBindVertexArray(monkey_vao) monkey_VBO = glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER, monkey_VBO) glBufferData(GL_ARRAY_BUFFER, monkey_obj.model.itemsize * len(monkey_obj.model), monkey_obj.model, GL_STATIC_DRAW) #Position glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, monkey_obj.model.itemsize * 3, ctypes.c_void_p(0)) glEnableVertexAttribArray(0) #TextureCoords glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, monkey_obj.model.itemsize * 2, ctypes.c_void_p(monkey_tex_offset)) glEnableVertexAttribArray(1) #Normals glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, monkey_obj.model.itemsize * 3, ctypes.c_void_p(monkey_norm_offset)) glEnableVertexAttribArray(2) glBindVertexArray(0) glClearColor(0.2, 0.3, 0.2, 1.0) glEnable(GL_DEPTH_TEST) projection = pyrr.matrix44.create_perspective_projection_matrix( 60.0, w_width / w_height, 0.1, 100.0) sphere_model = matrix44.create_from_translation(Vector3([-4.0, 0.0, -3.0])) monkey_model = matrix44.create_from_translation(Vector3([0.0, 0.0, -3.0])) glUseProgram(shader) model_loc = glGetUniformLocation(shader, "model") view_loc = glGetUniformLocation(shader, "view") proj_loc = glGetUniformLocation(shader, "proj") light_loc = glGetUniformLocation(shader, "light") glUniformMatrix4fv(proj_loc, 1, GL_FALSE, projection) while not glfw.window_should_close(window): glfw.poll_events() do_movement() glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) view = cam.get_view_matrix() glUniformMatrix4fv(view_loc, 1, GL_FALSE, view) light_y = Matrix44.from_y_rotation(0.5) rot_y = Matrix44.from_y_rotation(glfw.get_time() * 0.5) glUniformMatrix4fv(light_loc, 1, GL_FALSE, light_y) glBindVertexArray(sphere_vao) glBindTexture(GL_TEXTURE_2D, sphere_tex) glUniformMatrix4fv(model_loc, 1, GL_FALSE, Matrix44(sphere_model) * rot_y) glDrawArrays(GL_TRIANGLES, 0, len(sphere_obj.vertex_index)) glBindVertexArray(0) glBindVertexArray(monkey_vao) glBindTexture(GL_TEXTURE_2D, monkey_tex) glUniformMatrix4fv(model_loc, 1, GL_FALSE, monkey_model) glDrawArrays(GL_TRIANGLES, 0, len(monkey_obj.vertex_index)) glBindVertexArray(0) glfw.swap_buffers(window) glfw.terminate()
def _platform_init(self, width, height): glfw.window_hint(glfw.SAMPLES, 4) glfw.window_hint(glfw.VISIBLE, 1) glfw.window_hint(glfw.DOUBLEBUFFER, 1) self._context = glfw.create_window(width, height, self._title, None, None) self._destroy_window = glfw.destroy_window
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_window_size_callback(self._window, self.glfw_window_resize_callback) if self._create_mgl_context: self.init_mgl_context() self.set_default_viewport()
def run(self): # Initialize the library if not glfw.init(): return # Set some window 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.GL_TRUE); glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE); glfw.window_hint(glfw.SAMPLES, 16) # This works as expected # glfw.window_hint(glfw.RESIZABLE, 0) # These should work, but don't :( # could control focus w/ http://crunchbang.org/forums/viewtopic.php?id=22226 # ended up using xdotool, see run.py glfw.window_hint(glfw.FOCUSED, 0) # I've set 'shader-*' to raise in openbox-rc as workaround # Looking at the code and confirming version 3.1.2 and it should work glfw.window_hint(glfw.FLOATING, 1) # Create a windowed mode window and its OpenGL context self.w = glfw.create_window(500, 500, "shader-test", None, None) if not self.w: glfw.terminate() return # Move Window glfw.set_window_pos(self.w, 1400, 50) # Callbacks glfw.set_key_callback(self.w, self.on_key) glfw.set_framebuffer_size_callback(self.w, self.on_resize); # Make the window's context current glfw.make_context_current(self.w) # vsync glfw.swap_interval(1) # Setup GL shaders, data, etc. self.initialize() # Loop until the user closes the window while not glfw.window_should_close(self.w): # print difference in time since start # this should always be 16.6-16.7 @ 60fps # print('%0.1fms' % (1000 * (time.time()-self.lastframe))) # start of the frame self.lastframe = time.time() # Render here, e.g. using pyOpenGL self.render() # Swap front and back buffers glfw.swap_buffers(self.w) # Poll for and process events glfw.poll_events() glfw.terminate()