예제 #1
0
    def start(self):
        if not glfw.init():
            return

        glfw.window_hint(glfw.SAMPLES, 4)

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

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

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

        if not window:
            glfw.terminate()
            return

        self.running = True

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

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

        self.window = window

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

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

        mjlib.mjr_defaultContext(byref(self.con))

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

        glfw.set_cursor_pos_callback(window, self.handle_mouse_move)
        glfw.set_mouse_button_callback(window, self.handle_mouse_button)
        glfw.set_scroll_callback(window, self.handle_scroll)
예제 #2
0
def main():
    # Initialize the library
    if not glfw.init():
        return
    # Create a windowed mode window and its OpenGL context
    window = glfw.create_window(window_width, window_height, "Hello World", None, None)
    if not window:
        glfw.terminate()
        return

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

    initGL(window)
    # Loop until the user closes the window
    while not glfw.window_should_close(window):
        # Render here, e.g. using pyOpenGL
        display()

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

        # Poll for and process events
        glfw.poll_events()

    glfw.terminate()
예제 #3
0
 def run(self):
     # Initialize the library
     if not glfw.init():
         return
     # Create a windowed mode window and its OpenGL context
     self.window = glfw.create_window(640, 480, "Hello World", None, None)
     if not self.window:
         glfw.terminate()
         return
 
     renderer = RiftGLRendererCompatibility()
     # Paint a triangle in the center of the screen
     renderer.append(TriangleDrawerCompatibility())
 
     # Make the window's context current
     glfw.make_context_current(self.window)
 
     # Initialize Oculus Rift
     renderer.init_gl()
     renderer.rift.recenter_pose()
     
     glfw.set_key_callback(self.window, self.key_callback)
 
     # Loop until the user closes the window
     while not glfw.window_should_close(self.window):
         # Render here, e.g. using pyOpenGL
         renderer.display_rift_gl()
 
         # Swap front and back buffers
         glfw.swap_buffers(self.window)
 
         # Poll for and process events
         glfw.poll_events()
 
     glfw.terminate()
예제 #4
0
파일: Lab23.py 프로젝트: ROOOOO/Study
def main():
    global angles, angley, anglez, scale, carcass, sphere
    if not glfw.init():
        return
    window = glfw.create_window(640, 640, "Lab2", None, None)
    if not window:
        glfw.terminate()
        return
    glfw.make_context_current(window)
    glfw.set_key_callback(window, key_callback)
    glfw.set_framebuffer_size_callback(window, resize_callback)
    glfw.set_window_pos_callback(window, drag_callback)
    l_cube = Cube(0, 0, 0, 1)
    # r_cube = Cube(0, 0, 0, 1)
    sphere.recount(parts)
    while not glfw.window_should_close(window):
        glEnable(GL_DEPTH_TEST)
        glDepthFunc(GL_LESS)
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
        set_projection()
        glLoadIdentity()
        sphere.draw(scale, angles, [0.3, 0.0, 0.4], carcass)
        # r_cube.draw(scale, angles, [0.3, 0.2, 0.4], carcass)
        l_cube.draw(0.5, [0, 0, 0], [-0.5, 0.0, -0.25], False)
        glfw.swap_buffers(window)
        glfw.poll_events()
    glfw.destroy_window(window)
    glfw.terminate()
예제 #5
0
def main():
	# Initialize the library
	if not glfw.init():
		return
	
	glfw.set_error_callback(error_callback)

	# Create a windowed mode window and its OpenGL context
	window = glfw.create_window(640, 480, "Hello World", None, None)
	if not window:
		glfw.terminate()
		return

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

	program = common2d.init_shader_program()

	# Loop until the user closes the window
	while not glfw.window_should_close(window):
		# Render here
		common2d.display(program)

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

		# Poll for and process events
		glfw.poll_events()

	glfw.terminate()
예제 #6
0
def main():
    if not glfw.init():
        return
    window = glfw.create_window(640, 480, "ラララ", None, None)
    if not window:
        glfw.terminate()
        return

    #init
    glfw.make_context_current(window)
    gluOrtho2D(0.0, 640, 0.0, 480) #where is this in glfw?

    # loop
    while not glfw.window_should_close(window):

        glClear(GL_COLOR_BUFFER_BIT)
        randomWidth()
    
        drawLine(100.0, 400.0, 200.0, 400.0)
        drawLine(440.0, 400.0, 540.0, 400.0)
        drawLine(320.0, 350.0, 320.0, 330.0)
        drawLine(100.0, 400.0, 200.0, 400.0)
        drawLine(300.0, 200.0, 340.0, 200.0)
        
        glfw.swap_buffers(window)
        glfw.poll_events()
        glfw.swap_interval(2)
    glfw.terminate()
예제 #7
0
파일: main.py 프로젝트: MaybeS/CSE4020
def main():
    global R, T
    if not glfw.init(): return
    window = glfw.create_window(480, 480, "2015004584", None, None)

    if not window:
        glfw.terminate()
        return

    glfw.set_key_callback(window, key_callback)
    glfw.make_context_current(window)
    glfw.swap_interval(0)

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

        clear()
        axis()

        glMultMatrixf(R.T)
        glMultMatrixf(T.T)
        render()

        glfw.swap_buffers(window)

    glfw.terminate()
예제 #8
0
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
예제 #9
0
    def __init__(self, objects=[], options={}):
        super().__init__()

        self.parseOptions(options)

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

        glfw.init()

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

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

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

        self.objects = set()
        self.appendRenderObjects(self.makeRenderObjects(objects))
예제 #10
0
def main():
    global vertices, window_height, window_width, to_redraw

    if not glfw.init():
        return

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

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

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

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

        draw()

        glfw.swap_buffers(window)
        glfw.poll_events()

    glfw.destroy_window(window)
    glfw.terminate()
예제 #11
0
파일: main.py 프로젝트: Tofs/Pygel
def main():
    global window
    initLogger()
    Utils.init()

    # Create a windowed mode window and its OpenGL context
    window = glfw.create_window(640, 480, "Hello World", None, None)
    if not window:
        glfw.terminate()
        print("fail Window")
        return
    # Make the window's context current
    glfw.make_context_current(window)

    vertexPos, vertexColor, triangle = tmf.load("testData.tmf")

    #define input
    inputHandler.addEvent(KillProgram, "Esc")
    inputHandler.addEvent(Culling, "c")

    print vertexPos
    VAO, VertexSize, indexs = Utils.createVAO(vertexPos, vertexColor, triangle, 4)
    shaderProgram = ShaderM.compileShaderFromFile("shaders/basic.vert", "shaders/basic.frag")

    objectToRender = { "Indexs" : indexs, "VAO" : VAO, "VertexCount" : VertexSize, "ShaderProgram" : shaderProgram}

    mainLoop(objectToRender,window)
    glfw.terminate()
예제 #12
0
파일: main.py 프로젝트: ronhandler/gitroot
    def __init__(self):

        self.dir = Dir.empty
        self.run = True
        self.snake = Player()

        if not glfw.init():
            return
        self.window = glfw.create_window(400, 300, "Hello, World!", None, None)
        if not self.window:
            glfw.terminate()
            return
        glfw.make_context_current(self.window)
        glfw.set_key_callback(self.window, self.key_callback)

        while self.run and not glfw.window_should_close(self.window):

            # Update player's position
            self.snake.play(self.dir)
            sleep(0.075)

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

            if self.snake.alive is False:
                sleep(1.075)
                self.run = False
                
        glfw.terminate()
예제 #13
0
def main():
    init()

    window = create_window(500, 500, "Hi", None, None)
    make_context_current(window)
    initial_setup()
    colors = {
        "front": (1, 0, 0),
        "back": (0, 1, 0),
        "left": (1, 1, 0),
        "right": (1, 0, 1),
        "up": (0, 0, 1),
        "down": (0, 1, 1),
    }
    glClearColor(1, 1, 1, 1)
    glEnable(GL_DEPTH_TEST)
    set_lightning()
    while not window_should_close(window):
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
        glRotate(1, 0, 1, 0)
        draw_cube(0, 0, 0, 5, colors)
        swap_buffers(window)
        poll_events()

    terminate()
예제 #14
0
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
예제 #15
0
    def init(self):
        if not glfw.init():
            raise Exception('glfw failed to initialize')

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

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

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

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

        GL.glEnable(GL.GL_DEPTH_TEST)
        GL.glDepthMask(GL.GL_TRUE)
        GL.glDepthFunc(GL.GL_LEQUAL)
        GL.glDepthRange(0.0, 1.0)
        GL.glEnable(depth_clamp.GL_DEPTH_CLAMP)
예제 #16
0
파일: glfw.py 프로젝트: marcan/blitzloop
    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()
예제 #17
0
파일: demo.py 프로젝트: Olovan/PythonOpenGL
 def init(this):
     if not glfw.init():
         return
     this.windowID = glfw.create_window(640, 480, "Test", None, None)
     glfw.show_window(this.windowID)
     glfw.make_context_current(this.windowID)
     glfw.swap_interval(1)
     glClearColor(0, 0, 0, 1);
예제 #18
0
파일: entrance.py 프로젝트: chxzh/shadyn
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
예제 #19
0
 def initGL(self):
     if not glfw.init():
         sys.exit(1)
     self.window = glfw.create_window(640, 480, "Hello", None, None)
     print self.window
     glfw.make_context_current(self.window)
     glfw.swap_interval(1)
     glfw.set_key_callback(self.window, self.key_callback)
     glClearColor(0.5, 0.5, 0.5, 1)
예제 #20
0
파일: mogli.py 프로젝트: FlorianRhiem/mogli
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()
예제 #21
0
def main():
    # Initialize the library
    if not glfw.init():
        return
    # Create a windowed mode window and its OpenGL context
    window = glfw.create_window(640, 480, "Hello World", None, None)
    if not window:
        glfw.terminate()
        return

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

    # Loop until the user closes the window
    while not glfw.window_should_close(window):
        # Render here, e.g. using pyOpenGL

        # Swap front and back buffers
        glfw.swap_buffers(window)
        
        gl_begin( GL_TRIANGLES )
        glColor3f( 1.0, 0.0, 0.0 )
        glVertex3f( 0.0, 1.0, 0.0 )
        glColor3f( 0.0, 1.0, 0.0 ) 
        glVertex3f( -1.0, -1.0, 1.0 )
        glColor3f( 0.0, 0.0, 1.0 ) 
        glVertex3f( 1.0, -1.0, 1.0)
        
        glColor3f( 1.0, 0.0, 0.0 ) 
        glVertex3f( 0.0, 1.0, 0.0)
        glColor3f( 0.0, 1.0, 0.0 ) 
        glVertex3f( -1.0, -1.0, 1.0)
        glColor3f( 0.0, 0.0, 1.0 )
        glVertex3f( 0.0, -1.0, -1.0)
        
        #glColor3f( 1.0f, 0.0f, 0.0f ) 
        #glVertex3f( 0.0f, 1.0f, 0.0f)
        #glColor3f( 0.0f, 1.0f, 0.0f ) 
        #glVertex3f( 0.0f, -1.0f, -1.0f)
        #glColor3f( 0.0f, 0.0f, 1.0f ) 
        #glVertex3f( 1.0f, -1.0f, 1.0f)
        
        
        #glColor3f( 1.0f, 0.0f, 0.0f )
        #glVertex3f( -1.0f, -1.0f, 1.0f)
        #glColor3f( 0.0f, 1.0f, 0.0f )
        #glVertex3f( 0.0f, -1.0f, -1.0f)
        #glColor3f( 0.0f, 0.0f, 1.0f )
        #glVertex3f( 1.0f, -1.0f, 1.0f)
        
        glEnd()

        # Poll for and process events
        glfw.poll_events()

    glfw.terminate()
예제 #22
0
    def __init__(self, **kwargs):
        super().__init__(**kwargs)

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

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

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

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

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

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

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

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

        if self.vsync:
            glfw.swap_interval(1)

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

        self.ctx = moderngl.create_context(require=self.gl_version_code)
        self.print_context_info()
        self.set_default_viewport()
예제 #23
0
 def __init__(self, name, width, height, fullscreen=False):
     if not glfw.init():
         raise GlfwError("Could not initialize GLFW")
     monitor = glfw.get_primary_monitor() if fullscreen else None
     self.win = glfw.create_window(width, height, name, monitor, None)
     if not self.win:
         glfw.terminate()
         raise GlfwError("Could not create GLFW window")
     glfw.make_context_current(self.win)
     glfw.set_key_callback(self.win, self.key_cb)
     self.key_callbacks = []
예제 #24
0
파일: 003-ebo.py 프로젝트: lhl/vrdev
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()
예제 #25
0
파일: window.py 프로젝트: aiv01/aiv-python
 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)
예제 #26
0
    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
예제 #27
0
파일: OpenGLUtils.py 프로젝트: Tofs/Pygel
def createWindow(keyboardCallBackFunction=None):
    # Create a windowed mode window and its OpenGL context
    window = glfw.create_window(640, 480, "Hello World", None, None)
    if not window:
        glfw.terminate()
        print("fail Window")
        return
    # Make the window's context current
    glfw.make_context_current(window)

    if not keyboardCallBackFunction == None:
        # keyboard callback function
        glfw.set_key_callback(window, keyboardCallBackFunction)
    return window
예제 #28
0
파일: cubes.py 프로젝트: kossem/python
def main():
    if not glfw.init():
        return
    window = glfw.create_window(640, 480, "Lab2", None, None)
    if not window:
        glfw.terminate()
        return
    glfw.make_context_current(window)
    glfw.set_key_callback(window, key_callback)
    while not glfw.window_should_close(window) and not ex:
        draw()
        glfw.swap_buffers(window)
        glfw.poll_events()
    glfw.terminate()
예제 #29
0
파일: Lab1.py 프로젝트: ROOOOO/Study
def main():
    global delta
    global angle
    # Initialize the library
    if not glfw.init():
        return
    # Create a windowed mode window and its OpenGL context
    window = glfw.create_window(640, 640, "Lab1", None, None)
    if not window:
        glfw.terminate()
        return
    # Make the window's context current
    glfw.make_context_current(window)
    glfw.set_key_callback(window, key_callback)
    # Loop until the user closes the window
    while not glfw.window_should_close(window):
        # Render here, e.g. using pyOpenGL

        glClear(GL_COLOR_BUFFER_BIT)
        glLoadIdentity()
        glClearColor(1.0, 1.0, 1.0, 1.0)
        glPushMatrix()

        glRotatef(angle, 0, 0, 1)

        glBegin(GL_QUADS)

        glColor3f(0.0,0.0,0.0)
        glVertex3f( 0.5, 0.5, 0.0)
        glColor3f(1.0,0.0,0.0)
        glVertex3f(-0.5, 0.5, 0.0)
        glColor3f(0.0,0.0,1.0)
        glVertex3f(-0.5, -0.5, 0.0)
        glColor3f(1.0,0.0,1.0)
        glVertex3f( 0.5, -0.5, 0.0)


        glEnd()

        glPopMatrix()
        angle += delta

        # Swap front and back buffers
        glfw.swap_buffers(window)
        # Poll for and process events
        glfw.poll_events()
    glfw.destroy_window(window)
    glfw.terminate()
예제 #30
0
파일: main.py 프로젝트: MaybeS/CSE4020
def main():
   if not glfw.init(): return
   window = glfw.create_window(640,640,'2015004584', None,None)
   if not window: 
      glfw.terminate()
      return
   
   glfw.make_context_current(window)
   glfw.set_key_callback(window, key_callback)
   
   while not glfw.window_should_close(window): 
      glfw.poll_events()
      render(gCamAng)
      glfw.swap_buffers(window)
   
   glfw.terminate()
예제 #31
0
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

        glfw.ERROR_REPORTING = "raise"

        # 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

        # 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 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.28"
        ), "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,
            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.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="e",
            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
        default_plugins = [
            ("Plugin_Manager", {}),
            ("Seek_Control", {}),
            ("Log_Display", {}),
            ("Raw_Data_Exporter", {}),
            ("Vis_Polyline", {}),
            ("Vis_Circle", {}),
            ("System_Graphs", {}),
            ("System_Timelines", {}),
            ("World_Video_Exporter", {}),
            ("Pupil_From_Recording", {}),
            ("GazeFromRecording", {}),
            ("Audio_Playback", {}),
        ]

        g_pool.plugins = Plugin_List(
            g_pool, session_settings.get("loaded_plugins", default_plugins)
        )

        # 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)
예제 #32
0
def main():

    # initialize glfw
    if not glfw.init():
        return

    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, True)

    w_width, w_height = 800, 600

    window = glfw.create_window(w_width, w_height, "My OpenGL window", None,
                                None)

    if not window:
        glfw.terminate()
        return

    glfw.make_context_current(window)
    glfw.set_window_size_callback(window, window_resize)

    #        positions         colors          texture coords
    cube = [
        -0.5, -0.5, 0.5, 1.0, 0.0, 0.0, 0.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, 0.0, 1.0, 1.0, 1.0, -0.5, 0.5, 0.5,
        1.0, 1.0, 1.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, 0.0, 1.0, 0.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, 1.0, 1.0, 1.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, 0.0, 1.0, 0.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, 1.0, 1.0, 1.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,
        0.0, 1.0, 0.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, 1.0, 1.0, 1.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, 0.0, 1.0, 0.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, 1.0, 1.0, 1.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, 0.0, 1.0,
        0.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,
        1.0, 1.0, 1.0, 0.0, 1.0
    ]

    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 = numpy.array(indices, dtype=numpy.uint32)

    vertex_shader = """
    #version 330
    layout(location = 0) in vec3 position;
    layout(location = 1) in vec3 color;
    layout(location = 2) in vec2 textureCoords;
    uniform mat4 transform;
    out vec3 newColor;
    out vec2 newTexture;
    void main()
    {
        gl_Position = transform * vec4(position, 1.0f);
        newColor = color;
        newTexture = textureCoords;
    }
    """

    fragment_shader = """
    #version 330
    in vec3 newColor;
    in vec2 newTexture;

    out vec4 outColor;
    uniform sampler2D samplerTexture;
    void main()
    {
        outColor = texture(samplerTexture, newTexture) * 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)
    glBindBuffer(GL_ARRAY_BUFFER, VBO)
    glBufferData(GL_ARRAY_BUFFER, cube.itemsize * len(cube), cube,
                 GL_STATIC_DRAW)

    EBO = glGenBuffers(1)
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO)
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.itemsize * len(indices),
                 indices, GL_STATIC_DRAW)

    #position
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, cube.itemsize * 8,
                          ctypes.c_void_p(0))
    glEnableVertexAttribArray(0)
    #color
    glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, cube.itemsize * 8,
                          ctypes.c_void_p(12))
    glEnableVertexAttribArray(1)
    #texture
    glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, cube.itemsize * 8,
                          ctypes.c_void_p(24))
    glEnableVertexAttribArray(2)

    glBindVertexArray(0)
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0)
    glBindBuffer(GL_ARRAY_BUFFER, 0)

    texture = glGenTextures(1)
    glBindTexture(GL_TEXTURE_2D, texture)
    # Set the texture wrapping parameters
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT)
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT)
    # Set texture filtering parameters
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR)
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)
    # load image
    image = Image.open("res/crate.jpg")
    img_data = numpy.array(list(image.getdata()), numpy.uint8)
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, image.width, image.height, 0,
                 GL_RGB, GL_UNSIGNED_BYTE, img_data)

    glClearColor(0.2, 0.3, 0.2, 1.0)
    glEnable(GL_DEPTH_TEST)
    #glPolygonMode(GL_FRONT_AND_BACK, GL_LINE)

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

        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)

        rot_x = pyrr.Matrix44.from_x_rotation(0.5 * glfw.get_time())
        rot_y = pyrr.Matrix44.from_y_rotation(0.8 * glfw.get_time())

        glUseProgram(shader)
        transformLoc = glGetUniformLocation(shader, "transform")
        glUniformMatrix4fv(transformLoc, 1, GL_FALSE, rot_x * rot_y)
        glBindVertexArray(VAO)
        glDrawElements(GL_TRIANGLES, len(indices), GL_UNSIGNED_INT, None)
        glBindVertexArray(0)
        glUseProgram(0)

        glfw.swap_buffers(window)

    glDeleteProgram(shader)
    glDeleteVertexArrays(1, [VAO])
    glDeleteBuffers(2, [VBO, EBO])

    glfw.terminate()
예제 #33
0
    glEnableClientState(GL_VERTEX_ARRAY)
    glVertexPointer(2, GL_FLOAT, 0, None)

    while not end_trhead and not glfw.window_should_close(window2):

        glClear(GL_COLOR_BUFFER_BIT)

        glColor3f(0, 1, 0)
        glDrawArrays(GL_TRIANGLES, 0, 3)

        glfw.swap_buffers(window2)
        glfw.poll_events()
        time.sleep(0.001)


window = glfw.create_window(400, 400, "Window 1", None, None)
glfw.make_context_current(window)

r = 1 / math.sqrt(3)
px, py = r * math.cos(math.radians(30)), r * math.sin(math.radians(30))
vertices = [-px, -py, px, -py, 0, r]

vbo = glGenBuffers(1)
glBindBuffer(GL_ARRAY_BUFFER, vbo)
glBufferData(GL_ARRAY_BUFFER, (GLfloat * 12)(*vertices), GL_STATIC_DRAW)

glfw.make_context_current(None)
thread = threading.Thread(target=shard_context, args=[window, vbo])
thread.start()
event.wait()
glfw.make_context_current(window)
예제 #34
0
def main():
    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(800, 600, "LearnOpenGL", None, None)
    if not window:
        print("Window Creation failed!")
        glfw.terminate()

    glfw.make_context_current(window)
    glfw.set_window_size_callback(window, on_resize)

    shader = shaders.compileProgram(
        shaders.compileShader(vertex_shader, gl.GL_VERTEX_SHADER),
        shaders.compileShader(fragment_shader, gl.GL_FRAGMENT_SHADER),
    )

    vertices_tria_a = [
        # first triangle
        -0.9,
        -0.5,
        0.0,  # left
        -0.0,
        -0.5,
        0.0,  # right
        -0.45,
        0.5,
        0.0,  # top
    ]
    vertices_tria_a = (c_float * len(vertices_tria_a))(*vertices_tria_a)

    vertices_tria_b = [
        # second triangle
        0.0,
        -0.5,
        0.0,  # left
        0.9,
        -0.5,
        0.0,  # right
        0.45,
        0.5,
        0.0  # top
    ]
    vertices_tria_b = (c_float * len(vertices_tria_b))(*vertices_tria_b)

    vaos = gl.glGenVertexArrays(2)
    vbos = gl.glGenBuffers(2)

    gl.glBindVertexArray(vaos[0])
    gl.glBindBuffer(gl.GL_ARRAY_BUFFER, vbos[0])
    gl.glBufferData(gl.GL_ARRAY_BUFFER, sizeof(vertices_tria_a),
                    vertices_tria_a, gl.GL_STATIC_DRAW)
    gl.glVertexAttribPointer(0, 3, gl.GL_FLOAT, gl.GL_FALSE,
                             3 * sizeof(c_float), c_void_p(0))
    gl.glEnableVertexAttribArray(0)

    gl.glBindVertexArray(vaos[1])
    gl.glBindBuffer(gl.GL_ARRAY_BUFFER, vbos[1])
    gl.glBufferData(gl.GL_ARRAY_BUFFER, sizeof(vertices_tria_b),
                    vertices_tria_b, gl.GL_STATIC_DRAW)
    gl.glVertexAttribPointer(0, 3, gl.GL_FLOAT, gl.GL_FALSE,
                             3 * sizeof(c_float), c_void_p(0))
    gl.glEnableVertexAttribArray(0)

    while not glfw.window_should_close(window):
        process_input(window)

        gl.glClearColor(.2, .3, .3, 1.0)
        gl.glClear(gl.GL_COLOR_BUFFER_BIT)

        gl.glUseProgram(shader)
        gl.glBindVertexArray(vaos[0])
        gl.glDrawArrays(gl.GL_TRIANGLES, 0, 3)

        gl.glBindVertexArray(vaos[1])
        gl.glDrawArrays(gl.GL_TRIANGLES, 0, 3)

        glfw.poll_events()
        glfw.swap_buffers(window)

    gl.glDeleteVertexArrays(2, id(vaos))
    gl.glDeleteBuffers(2, id(vbos))
    glfw.terminate()
예제 #35
0
def main():
    if not glfw.init():
        return

    w_width, w_height = 1280, 720
    aspect_ratio = w_width / w_height

    window = glfw.create_window(w_width, w_height, "My OpenGL window", None,
                                None)

    if not window:
        glfw.terminate()
        return

    glfw.make_context_current(window)
    glfw.set_window_size_callback(window, window_resize)

    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, 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, 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, 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, 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,
        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
    ]

    cube = numpy.array(cube, dtype=numpy.float32)

    cube_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
    ]

    cube_indices = numpy.array(cube_indices, dtype=numpy.uint32)

    plane = [
        -0.5, -0.5, 0.0, 0.0, 0.0, 2.0, -0.5, 0.0, 1.0, 0.0, 2.0, 1.0, 0.0,
        1.0, 1.0, -0.5, 1.0, 0.0, 0.0, 1.0
    ]

    plane = numpy.array(plane, dtype=numpy.float32)

    plane_indices = [0, 1, 2, 2, 3, 0]
    plane_indices = numpy.array(plane_indices, dtype=numpy.uint32)

    vertex_shader = """
    #version 330
    in layout(location = 0) vec3 position;
    in layout(location = 1) vec2 textCoords;
    uniform mat4 vp;
    uniform mat4 model;
    out vec2 outText;
    void main()
    {
        gl_Position =  vp * model * vec4(position, 1.0f);
        outText = textCoords;
    }
    """

    fragment_shader = """
    #version 330
    in vec2 outText;
    out vec4 outColor;
    uniform sampler2D renderedTexture;
    void main()
    {
        outColor = texture(renderedTexture, outText);
    }
    """

    shader = OpenGL.GL.shaders.compileProgram(
        OpenGL.GL.shaders.compileShader(vertex_shader, GL_VERTEX_SHADER),
        OpenGL.GL.shaders.compileShader(fragment_shader, GL_FRAGMENT_SHADER))

    # cube VAO
    cube_vao = glGenVertexArrays(1)
    glBindVertexArray(cube_vao)
    cube_VBO = glGenBuffers(1)
    glBindBuffer(GL_ARRAY_BUFFER, cube_VBO)
    glBufferData(GL_ARRAY_BUFFER, cube.itemsize * len(cube), cube,
                 GL_STATIC_DRAW)
    cube_EBO = glGenBuffers(1)
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, cube_EBO)
    glBufferData(GL_ELEMENT_ARRAY_BUFFER,
                 cube_indices.itemsize * len(cube_indices), cube_indices,
                 GL_STATIC_DRAW)
    # position
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, cube.itemsize * 5,
                          ctypes.c_void_p(0))
    glEnableVertexAttribArray(0)
    # textures
    glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, cube.itemsize * 5,
                          ctypes.c_void_p(12))
    glEnableVertexAttribArray(1)
    glBindVertexArray(0)

    # plane VAO
    plane_vao = glGenVertexArrays(1)
    glBindVertexArray(plane_vao)
    plane_VBO = glGenBuffers(1)
    glBindBuffer(GL_ARRAY_BUFFER, plane_VBO)
    glBufferData(GL_ARRAY_BUFFER, plane.itemsize * len(plane), plane,
                 GL_STATIC_DRAW)
    plane_EBO = glGenBuffers(1)
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, plane_EBO)
    glBufferData(GL_ELEMENT_ARRAY_BUFFER,
                 plane_indices.itemsize * len(plane_indices), plane_indices,
                 GL_STATIC_DRAW)
    # position
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, plane.itemsize * 5,
                          ctypes.c_void_p(0))
    glEnableVertexAttribArray(0)
    # textures
    glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, plane.itemsize * 5,
                          ctypes.c_void_p(12))
    glEnableVertexAttribArray(1)
    glBindVertexArray(0)

    ###########################################################################################

    plane_texture = glGenTextures(1)
    glBindTexture(GL_TEXTURE_2D, plane_texture)
    # texture wrapping params
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT)
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT)
    # texture filtering params
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR)
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w_width, w_height, 0, GL_RGBA,
                 GL_UNSIGNED_BYTE, None)
    glBindTexture(GL_TEXTURE_2D, 0)

    depth_buff = glGenRenderbuffers(1)
    glBindRenderbuffer(GL_RENDERBUFFER, depth_buff)
    glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT, w_width,
                          w_height)

    FBO = glGenFramebuffers(1)
    glBindFramebuffer(GL_FRAMEBUFFER, FBO)
    glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D,
                           plane_texture, 0)
    glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT,
                              GL_RENDERBUFFER, depth_buff)
    glBindFramebuffer(GL_FRAMEBUFFER, 0)

    ###########################################################################################
    crate_texture = glGenTextures(1)
    glBindTexture(GL_TEXTURE_2D, crate_texture)
    # Set the texture wrapping parameters
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT)
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT)
    # Set texture filtering parameters
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR)
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)
    # load image
    image = Image.open("resources/images/planks_brown_10_diff_1k.jpg")
    img_data = numpy.array(list(image.getdata()), numpy.uint8)
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, image.width, image.height, 0,
                 GL_RGB, GL_UNSIGNED_BYTE, img_data)
    glBindTexture(GL_TEXTURE_2D, 0)
    ###########################################################################################

    glEnable(GL_DEPTH_TEST)

    view = matrix44.create_from_translation(Vector3([0.0, 0.0, -5.0]))
    projection = matrix44.create_perspective_projection_matrix(
        45.0, aspect_ratio, 0.1, 100.0)

    vp = matrix44.multiply(view, projection)

    glUseProgram(shader)
    vp_loc = glGetUniformLocation(shader, "vp")
    model_loc = glGetUniformLocation(shader, "model")
    glUniformMatrix4fv(vp_loc, 1, GL_FALSE, vp)

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

        glClearColor(0.2, 0.25, 0.27, 1.0)
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)

        rot_y = pyrr.Matrix44.from_y_rotation(glfw.get_time() * 2)

        # draw to the default frame buffer
        glBindVertexArray(cube_vao)
        glBindTexture(GL_TEXTURE_2D, crate_texture)
        for i in range(len(cube_positions)):
            model = matrix44.create_from_translation(cube_positions[i])
            if i == 0:
                glUniformMatrix4fv(model_loc, 1, GL_FALSE, rot_y * model)
            elif i == 1:
                glUniformMatrix4fv(model_loc, 1, GL_FALSE, model)
            else:
                glUniformMatrix4fv(model_loc, 1, GL_FALSE, model)

            glDrawElements(GL_TRIANGLES, len(cube_indices), GL_UNSIGNED_INT,
                           None)

        # draw to the custom frame buffer
        glBindFramebuffer(GL_FRAMEBUFFER, FBO)
        glClearColor(0.0, 0.0, 0.0, 1.0)
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)

        for i in range(len(cube_positions)):
            model = matrix44.create_from_translation(cube_positions[i])
            if i == 0:
                glUniformMatrix4fv(model_loc, 1, GL_FALSE, rot_y * model)
            elif i == 1:
                glUniformMatrix4fv(model_loc, 1, GL_FALSE, model)
            else:
                glUniformMatrix4fv(model_loc, 1, GL_FALSE, model)

            glDrawElements(GL_TRIANGLES, len(cube_indices), GL_UNSIGNED_INT,
                           None)
        glBindVertexArray(0)
        glBindFramebuffer(GL_FRAMEBUFFER, 0)

        # draw the plane
        glBindVertexArray(plane_vao)
        glBindTexture(GL_TEXTURE_2D, plane_texture)
        glUniformMatrix4fv(model_loc, 1, GL_FALSE, plane_position)
        glDrawElements(GL_TRIANGLES, len(plane_indices), GL_UNSIGNED_INT, None)
        glBindVertexArray(0)

        glfw.swap_buffers(window)

    glfw.terminate()
예제 #36
0
def main():
    if not glfw.init():
        return 0

    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)

    screenWidth = 800
    screenHeight = 600

    window = glfw.create_window(screenWidth, screenHeight,
                                "OPENGL_TextureExample", None, None)

    if not window:
        print("Window Creation Failed")
        glfw.terminate()
        return 0

    glfw.make_context_current(window)
    glfw.set_framebuffer_size_callback(window, framebuffer_size_callback)
    glfw.set_key_callback(window, key_callback)
    h = 300
    w = 300

    #                       position      color          tex coords
    vertices = numpy.array([
        0.0, h, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0,
        1.0, 1.0, w, h, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0,
        0.0, 1.0, 1.0, w, h, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, w, 0.0, 0.0, 1.0,
        1.0, 0.0, 0.0, 1.0
    ],
                           dtype="f")
    myShader.Compile()

    VBO = GLuint(0)
    VAO = GLuint(0)
    VAO = glGenVertexArrays(1)
    VBO = myRenderer.GenBuffer(1)

    glBindVertexArray(VAO)
    myRenderer.BindBuffer(GL_ARRAY_BUFFER, VBO)
    myRenderer.BufferData(GL_ARRAY_BUFFER, 4 * (numpy.size(vertices)),
                          vertices, GL_STATIC_DRAW)

    # Get vertex position
    # position = myRenderer.GetAttribLocation(myShader.ID, "aPos")
    myRenderer.VertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 32,
                                   ctypes.c_void_p(0))
    myRenderer.EnableVertexArribArray(0)

    # get color
    # Color = myRenderer.GetAttribLocation(myShader.ID, "aColor")
    myRenderer.VertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 32,
                                   ctypes.c_void_p(12))
    myRenderer.EnableVertexArribArray(1)

    # get tex coords
    # TexCoords = myRenderer.GetAttribLocation(myShader.ID, "aTexCoord")
    myRenderer.VertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 32,
                                   ctypes.c_void_p(24))
    myRenderer.EnableVertexArribArray(2)

    # load and create Texture
    Texture = glGenTextures(1)
    glBindTexture(GL_TEXTURE_2D, Texture)

    # set texture wrapping parameters
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE)
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE)
    # texture filtering parameters
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR)
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)

    # glEnable(GL_DEPTH_TEST)
    # glEnable(GL_BLEND)
    # glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)
    # load image
    ImgSource = Image.open(IMAGEPATH)
    if not ImgSource:
        print("IMAGE NOT FOUND")
        return 0
    imgWidth, imgHeight = ImgSource.size

    ImgSource = ImgSource.convert("RGBA")
    ImgArray = ImgSource.tobytes()
    print(ImgArray)
    if not ImgArray:
        print("ERROR CONVERTING IMAGE tobytes()")
        return 0
    glPixelStorei(GL_UNPACK_ALIGNMENT, 1)
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, imgWidth, imgHeight, 0, GL_RGBA,
                 GL_UNSIGNED_BYTE, ImgArray)
    glGenerateMipmap(GL_TEXTURE_2D)

    myShader.UseProgram()

    # using glm for view frustum // perspective(fov, aspect ratio, near clipping plane, far clipping plane)
    # projection = glm.perspective(45.0, screenWidth / screenHeight, 0.1, 1000.0)

    # scale = glm.fmat4(1)
    # rot = glm.fmat4(1)
    MVP_loc = glGetUniformLocation(myShader.ID, 'MVP')

    glUniformMatrix4fv(MVP_loc, 1, GL_FALSE, glm.value_ptr(MVP))
    glUniform1i(glGetUniformLocation(myShader.ID, "Texture"), 0)

    while not glfw.window_should_close(window):
        myRenderer.ClearColor(0.2, 0.2, 0.4, 1.0)
        myRenderer.Clear()

        glDrawArrays(GL_TRIANGLES, 0, 6)

        glfw.poll_events()
        glfw.swap_buffers(window)

    glfw.terminate()
    return 0
예제 #37
0
def main():

    # initialize glfw
    if not glfw.init():
        return

    w_width, w_height = 1280, 720
    aspect_ratio = w_width / w_height

    window = glfw.create_window(w_width, w_height, "My OpenGL window", None,
                                None)

    if not window:
        glfw.terminate()
        return

    glfw.make_context_current(window)
    glfw.set_window_size_callback(window, window_resize)

    #        positions        texture_coords
    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, 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, 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, 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, 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,
        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
    ]

    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 = numpy.array(indices, dtype=numpy.uint32)

    vertex_shader = """
    #version 330
    in layout(location = 0) vec3 position;
    in layout(location = 1) vec2 texture_cords;
    in layout(location = 2) vec3 offset;

    uniform mat4 mvp;

    out vec2 textures;

    void main()
    {
        vec3 final_pos = vec3(position.x + offset.x, position.y + offset.y, position.z + offset.z);
        gl_Position =  mvp * vec4(final_pos, 1.0f);
        textures = texture_cords;
    }
    """

    fragment_shader = """
    #version 330
    in vec2 textures;

    out vec4 color;
    uniform sampler2D tex_sampler;

    void main()
    {
        color = texture(tex_sampler, textures);
    }
    """
    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)
    glBindBuffer(GL_ARRAY_BUFFER, VBO)
    glBufferData(GL_ARRAY_BUFFER, cube.itemsize * len(cube), cube,
                 GL_STATIC_DRAW)

    EBO = glGenBuffers(1)
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO)
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.itemsize * len(indices),
                 indices, GL_STATIC_DRAW)

    #position
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, cube.itemsize * 5,
                          ctypes.c_void_p(0))
    glEnableVertexAttribArray(0)

    #textures
    glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, cube.itemsize * 5,
                          ctypes.c_void_p(12))
    glEnableVertexAttribArray(1)

    #instances
    instance_array = []
    offset = 1

    for z in range(0, 100, 2):
        for y in range(0, 100, 2):
            for x in range(0, 100, 2):
                translation = Vector3([0.0, 0.0, 0.0])
                translation.x = x + offset
                translation.y = y + offset
                translation.z = z + offset
                instance_array.append(translation)

    instance_array = numpy.array(instance_array, numpy.float32).flatten()

    instanceVBO = glGenBuffers(1)
    glBindBuffer(GL_ARRAY_BUFFER, instanceVBO)
    glBufferData(GL_ARRAY_BUFFER,
                 instance_array.itemsize * len(instance_array), instance_array,
                 GL_STATIC_DRAW)

    glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, 0, ctypes.c_void_p(0))
    glEnableVertexAttribArray(2)
    glVertexAttribDivisor(2, 1)

    texture = TextureLoader.load_texture("res/crate.jpg")

    glUseProgram(shader)

    glClearColor(0.2, 0.3, 0.2, 1.0)
    glEnable(GL_DEPTH_TEST)

    model = matrix44.create_from_translation(Vector3([-14.0, -8.0, 0.0]))
    view = matrix44.create_from_translation(Vector3([0.0, 0.0, -50.0]))
    projection = matrix44.create_perspective_projection_matrix(
        45.0, aspect_ratio, 0.1, 100.0)

    mv = matrix44.multiply(model, view)
    mvp = matrix44.multiply(mv, projection)

    mvp_loc = glGetUniformLocation(shader, "mvp")
    glUniformMatrix4fv(mvp_loc, 1, GL_FALSE, mvp)

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

        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)

        glDrawElementsInstanced(GL_TRIANGLES, len(indices), GL_UNSIGNED_INT,
                                None, 125000)

        glfw.swap_buffers(window)

    glfw.terminate()
예제 #38
0
def main():

    # initialize glfw
    if not glfw.init():
        return

    window = glfw.create_window(800, 600, "My OpenGL window", None, None)

    if not window:
        glfw.terminate()
        return

    glfw.make_context_current(window)
    #            positions        colors
    triangle = [
        -0.5, -0.5, 0.0, 1.0, 0.0, 0.0, 0.5, -0.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 330
    in vec3 position;
    in vec3 color;

    out vec3 newColor;
    void main()
    {
        gl_Position = vec4(position, 1.0f);
        newColor = color;
    }
    """

    fragment_shader = """
    #version 330
    in vec3 newColor;

    out vec4 outColor;
    void main()
    {
        outColor = vec4(newColor, 1.0f);
    }
    """
    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)
    glBindBuffer(GL_ARRAY_BUFFER, VBO)
    glBufferData(GL_ARRAY_BUFFER, 72, triangle, GL_STATIC_DRAW)

    position = glGetAttribLocation(shader, "position")
    glVertexAttribPointer(position, 3, GL_FLOAT, GL_FALSE, 24,
                          ctypes.c_void_p(0))
    glEnableVertexAttribArray(position)

    color = glGetAttribLocation(shader, "color")
    glVertexAttribPointer(color, 3, GL_FLOAT, GL_FALSE, 24,
                          ctypes.c_void_p(12))
    glEnableVertexAttribArray(color)

    glUseProgram(shader)

    glClearColor(0.2, 0.3, 0.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()
예제 #39
0
def main():
    # inicia glfw
    if not glfw.init():
        return

    # crea la ventana,
    # independientemente del SO que usemos
    window = glfw.create_window(800, 800, "Mi ventana", None, None)

    # Configuramos OpenGL
    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)

    # Validamos que se cree la ventana
    if not window:
        glfw.terminate()
        return
    # Establecemos el contexto
    glfw.make_context_current(window)

    # Activamos la validación de
    # funciones modernas de OpenGL
    glewExperimental = True

    # Inicializar GLEW
    if glewInit() != GLEW_OK:
        print("No se pudo inicializar GLEW")
        return

    # Obtenemos versiones de OpenGL y Shaders
    version = glGetString(GL_VERSION)
    print(version)

    version_shaders = glGetString(GL_SHADING_LANGUAGE_VERSION)
    print(version_shaders)

    while not glfw.window_should_close(window):
        # Establece regiond e dibujo
        glViewport(0, 0, 800, 800)
        # Establece color de borrado
        glClearColor(0.4, 0.8, 0.1, 1)
        # Borra el contenido de la ventana
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)

        # Dibujar

        dibujar()

        # Preguntar si hubo entradas de perifericos
        # (Teclado, mouse, game pad, etc.)
        glfw.poll_events()
        # Intercambia los buffers
        glfw.swap_buffers(window)

    # Se destruye la ventana para liberar memoria
    glfw.destroy_window(window)
    # Termina los procesos que inició glfw.init
    glfw.terminate()
예제 #40
0
    def open(
        self,
        gui_monitor: GUIMonitor,
        title: str,
        is_fullscreen: bool = False,
        size: T.Tuple[int, int] = None,
        position: T.Tuple[int, int] = None,
    ):
        if self.is_open:
            # TODO: Warn that the window is already open
            return

        if not gui_monitor.is_available:
            raise ValueError(f"Window requires an available monitor.")

        has_fixed_size = ((size is not None) and (len(size) == 2)
                          and (size[0] > 0) and (size[1] > 0))
        if is_fullscreen and has_fixed_size:
            raise ValueError(
                f"Fullscreen is mutually exclusive to having a fixed size.")

        if position is None:
            if platform.system() == "Windows":
                position = (8, 90)
            else:
                position = (0, 0)

        if is_fullscreen:
            size = gui_monitor.size

        # NOTE: Always creating windowed window here, even if in fullscreen mode. On
        # windows you might experience a black screen for up to 1 sec when creating
        # a blank window directly in fullscreen mode. By creating it windowed and
        # then switching to fullscreen it will stay white the entire time.
        self.__gl_handle = glfw.create_window(*size, title, None,
                                              glfw.get_current_context())

        if not is_fullscreen:
            glfw.set_window_pos(self.__gl_handle, *position)

        # Register callbacks
        glfw.set_framebuffer_size_callback(self.__gl_handle, self.on_resize)
        glfw.set_key_callback(self.__gl_handle, self.on_key)
        glfw.set_mouse_button_callback(self.__gl_handle, self.on_mouse_button)
        self.on_resize(self.__gl_handle,
                       *glfw.get_framebuffer_size(self.__gl_handle))

        # gl_state settings
        with self._switch_to_current_context():
            gl_utils.basic_gl_setup()
            glfw.swap_interval(0)

        if is_fullscreen:
            # Switch to full screen here. See NOTE above at glfw.create_window().
            glfw.set_window_monitor(
                self.__gl_handle,
                gui_monitor.unsafe_handle,
                0,
                0,
                *gui_monitor.size,
                gui_monitor.refresh_rate,
            )
예제 #41
0
import glfw
from OpenGL.GL import *
import numpy as np

if not glfw.init():
    raise Exception('glfw con not be initialized')

window = glfw.create_window(1280, 720, 'My OpenGL window', None, None)

if not window:
    glfw.terminate()
    raise Exception('glfw window can not be created')

glfw.set_window_pos(window, 3400, 200)
glfw.make_context_current(window)

vertices = [-0.5, -0.5, 0.0,
             0.5, -0.5, 0.0,
             0.0,  0.5, 0.0]

colors = [
    1.0, 0.0, 0.0,
    0.0, 1.0, 0.0,
    0.0, 0.0, 1.0,
]

vertices = np.array(vertices, dtype=np.float32)
colors = np.array(colors, dtype=np.float32)

glEnableClientState(GL_VERTEX_ARRAY)
glVertexPointer(3, GL_FLOAT, 0, vertices)
예제 #42
0
    def __init__(self, **kwargs):
        super().__init__(**kwargs)

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

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

        monitor = None
        if self.fullscreen:
            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)
        self._has_focus = True

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

        self.cursor = self._cursor

        self._buffer_width, self._buffer_height = glfw.get_framebuffer_size(
            self._window)
        glfw.make_context_current(self._window)

        if self.vsync:
            glfw.swap_interval(1)
        else:
            glfw.swap_interval(0)

        glfw.set_key_callback(self._window, self.glfw_key_event_callback)
        glfw.set_cursor_pos_callback(self._window,
                                     self.glfw_mouse_event_callback)
        glfw.set_mouse_button_callback(self._window,
                                       self.glfw_mouse_button_callback)
        glfw.set_scroll_callback(self._window, self.glfw_mouse_scroll_callback)
        glfw.set_window_size_callback(self._window,
                                      self.glfw_window_resize_callback)
        glfw.set_char_callback(self._window, self.glfw_char_callback)
        glfw.set_window_focus_callback(self._window, self.glfw_window_focus)
        glfw.set_cursor_enter_callback(self._window, self.glfw_cursor_enter)
        glfw.set_window_iconify_callback(self._window,
                                         self.glfw_window_iconify)

        self.init_mgl_context()
        self.set_default_viewport()
예제 #43
0
파일: tp3.py 프로젝트: renato-lopes/CG-DCC
                        default=0,
                        type=int,
                        help="Choose the animation to be played.",
                        choices=range(21))
    args = parser.parse_args()

    # Load Model
    model = load_model(args.filename)
    current_anim = args.animation
    model.SetAnim(current_anim)

    # initialize glfw
    if not glfw.init():
        exit()

    window = glfw.create_window(800, 600, "MD2 Loader", None, None)

    if not window:
        glfw.terminate()
        exit()

    glfw.make_context_current(window)
    glfw.set_key_callback(window, key_event)

    shader = OpenGL.GL.shaders.compileProgram(
        OpenGL.GL.shaders.compileShader(phong_vertex_shader, GL_VERTEX_SHADER),
        OpenGL.GL.shaders.compileShader(phong_fragment_shader,
                                        GL_FRAGMENT_SHADER))

    glUseProgram(shader)
예제 #44
0
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

        glfw.ERROR_REPORTING = "raise"

        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)
예제 #45
0
# in all chapters. "draw_in_square_viewport" is a function.

import sys
import os
import numpy as np
import math
from OpenGL.GL import *
import glfw

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 3", None, None)
if not window:
    glfw.terminate()
    sys.exit()

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


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


glfw.set_key_callback(window, on_key)
예제 #46
0
def main():
    if not glfw.init():
        print('Failed to initialize GLFW.')
        return
    
    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_TRUE)
    glfw.window_hint(glfw.SAMPLES, config['sampling_level'])
    
    if config['fullscreen']:
        global width, height
        mode = glfw.get_video_mode(glfw.get_primary_monitor())
        width, height = mode.size.width, mode.size.height
        window = glfw.create_window(mode.size.width, mode.size.height, config['app_name'], glfw.get_primary_monitor(), None)
    else:
        window = glfw.create_window(width, height, config['app_name'], None, None)
    if not window:
        print('Failed to create GLFW Window.')
        glfw.terminate()
        return

    # подключаем наши функции для эвентов 
    #
    glfw.make_context_current(window)
    glfw.set_framebuffer_size_callback(window, ResizeCallback)
    glfw.set_cursor_pos_callback(window, MouseLookCallback)
    glfw.set_key_callback(window, KeyInputCallback) 
    glfw.set_input_mode(window, glfw.CURSOR, glfw.CURSOR_DISABLED)

    glEnable(GL_DEPTH_TEST)
    glEnable(GL_CULL_FACE)
    
    # подключаем фрагментный и вершинный шейдеры
    #
    program = Program()
    program.attachShader(Shader('resources/shaders/vert.vs', GL_VERTEX_SHADER))
    program.attachShader(Shader('resources/shaders/frag.fs', GL_FRAGMENT_SHADER))
    program.link()
    
    # подключаем шейдер для создания карты теней
    #  
    depthProgram = Program()
    depthProgram.attachShader(Shader('resources/shaders/depth.vs', GL_VERTEX_SHADER))
    depthProgram.attachShader(Shader('resources/shaders/depth.fs', GL_FRAGMENT_SHADER))
    depthProgram.attachShader(Shader('resources/shaders/depth.gs', GL_GEOMETRY_SHADER))
    depthProgram.link()

    # создаем depthBuffer и frameBuffer
    #
    shadow = Shadow(config['near_plane_depth'], config['far_plane_depth'])
    shadow.create(config['shadow_width'], config['shadow_height'])

    program.use()
    program.setInt("diffuseTexture", 0)
    program.setInt("depthMap", 1)

    # позиция источника света
    #
    lightPos = glm.vec3(0.0, 2.35, 0.0)
    
    # загрузка всех объектов сцены
    #
    room = Model('resources/models/dinning_room.json')
    
    # цикл обработки
    #
    while not glfw.window_should_close(window):
        if config['debug_mode']:
            print(glGetError())

        # обработка нажатий клавиатуры для камеры
        #
        DoMovement()
        
        # движение источника света
        #
        if light_movement:
            lightPos.z = math.sin(glfw.get_time() * 0.5) * 3.0

        glClearColor(0.1, 0.1, 0.1, 1.0)
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
        
        # обработка с помощью depthProgram - карта теней
        #
        shadow.castShadow(depthProgram, lightPos)
        room.draw(depthProgram)
        shadow.endCastShadow(program)

        
        glViewport(0, 0, width, height)
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)

        # обработка с помощью program - на основе полученной карты теней
        #
        program.use()
        view = cam.get_view_matrix()
        viewPos = glm.vec3(cam.camera_pos[0],cam.camera_pos[1],cam.camera_pos[2])
        perspective = glm.perspective(45, width / height, config['near_plane'], config['far_plane'])
        program.setMat4('projection', perspective)
        program.setMat4('view', view)
        program.setVec3('lightPos', lightPos)
        program.setVec3('viewPos', viewPos)
        program.setInt('shadows', True)
        program.setFloat("far_plane", config["far_plane_depth"])
        glActiveTexture(GL_TEXTURE1)
        glBindTexture(GL_TEXTURE_CUBE_MAP, shadow.depthbuffer.texture)
        room.draw(program)

        glfw.swap_buffers(window)
        glfw.poll_events()
        

    glfw.terminate()
예제 #47
0
import glfw
from OpenGL.GL import *
import numpy as np

# initializing glfw
glfw.init()

# creating a window with 800 width and 600 height
window = glfw.create_window(800, 600, "PyOpenGL Triangle", None, None)
glfw.set_window_pos(window, 400, 200)
glfw.make_context_current(window)

vertices = [-0.5, -0.5, 0.0, 0.5, -0.5, 0.0, 0.0, 0.5, 0.0]

v = np.array(vertices, dtype=np.float32)

# for drawing a colorless triangle
glEnableClientState(GL_VERTEX_ARRAY)
glVertexPointer(3, GL_FLOAT, 0, v)

# setting color for background
glClearColor(0, 0, 0, 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()
예제 #48
0
    def __init__(
        self,
        module,
        width,
        height,
        caption,
        scale,
        palette,
        fps,
        border_width,
        border_color,
    ):
        if glfw.get_version() < tuple(map(int, GLFW_VERSION.split("."))):
            raise RuntimeError(
                "glfw version is lower than {}".format(GLFW_VERSION))

        if width > APP_SCREEN_MAX_SIZE or height > APP_SCREEN_MAX_SIZE:
            raise ValueError("screen size is larger than {}x{}".format(
                APP_SCREEN_MAX_SIZE, APP_SCREEN_MAX_SIZE))

        global pyxel
        pyxel = module

        self._palette = palette[:]
        self._fps = fps
        self._border_width = border_width
        self._border_color = border_color
        self._next_update_time = 0
        self._one_frame_time = 1 / fps
        self._key_state = {}
        self._is_mouse_visible = False
        self._update = None
        self._draw = None
        self._capture_start = 0
        self._capture_count = 0
        self._capture_images = [None] * APP_GIF_CAPTURE_COUNT

        self._perf_monitor_is_enabled = False
        self._perf_fps_count = 0
        self._perf_fps_start_time = 0
        self._perf_fps = 0
        self._perf_update_count = 0
        self._perf_update_total_time = 0
        self._perf_update_time = 0
        self._perf_draw_count = 0
        self._perf_draw_total_time = 0
        self._perf_draw_time = 0

        # exports variables
        pyxel._app = self
        pyxel.width = width
        pyxel.height = height
        pyxel.mouse_x = 0
        pyxel.mouse_y = 0
        pyxel.frame_count = 0

        # initialize window
        if not glfw.init():
            exit()

        monitor = glfw.get_primary_monitor()
        display_width, display_height = glfw.get_video_mode(monitor)[0]

        if scale == 0:
            scale = max(
                min(
                    (display_width // width) - APP_SCREEN_SCALE_CUTDOWN,
                    (display_height // height) - APP_SCREEN_SCALE_CUTDOWN,
                ),
                APP_SCREEN_SCALE_MINIMUM,
            )

        window_width = width * scale + border_width
        window_height = height * scale + border_width
        self._window = glfw.create_window(window_width, window_height, caption,
                                          None, None)

        if not self._window:
            glfw.terminate()
            exit()

        glfw.set_window_pos(
            self._window,
            (display_width - window_width) // 2,
            (display_height - window_height) // 2,
        )

        glfw.make_context_current(self._window)
        glfw.set_window_size_limits(self._window, width, height,
                                    glfw.DONT_CARE, glfw.DONT_CARE)
        self._hidpi_scale = (glfw.get_framebuffer_size(self._window)[0] /
                             glfw.get_window_size(self._window)[0])
        self._update_viewport()

        glfw.set_key_callback(self._window, self._key_callback)
        glfw.set_mouse_button_callback(self._window,
                                       self._mouse_button_callback)

        glfw.set_window_icon(self._window, 1, [get_icon_image()])
        glfw.set_input_mode(self._window, glfw.CURSOR, glfw.CURSOR_HIDDEN)

        # initialize renderer
        self._renderer = Renderer(width, height)

        # initialize audio player
        self._audio_player = AudioPlayer()

        # export module functions
        pyxel.btn = self.btn
        pyxel.btnp = self.btnp
        pyxel.btnr = self.btnr
        pyxel.mouse = self.mouse
        pyxel.run = self.run
        pyxel.run_with_profiler = self.run_with_profiler
        pyxel.quit = self.quit
        pyxel.save = self.save
        pyxel.load = self.load
        pyxel.image = self._renderer.image
        pyxel.tilemap = self._renderer.tilemap
        pyxel.clip = self._renderer.draw_command.clip
        pyxel.pal = self._renderer.draw_command.pal
        pyxel.cls = self._renderer.draw_command.cls
        pyxel.pix = self._renderer.draw_command.pix
        pyxel.line = self._renderer.draw_command.line
        pyxel.rect = self._renderer.draw_command.rect
        pyxel.rectb = self._renderer.draw_command.rectb
        pyxel.circ = self._renderer.draw_command.circ
        pyxel.circb = self._renderer.draw_command.circb
        pyxel.blt = self._renderer.draw_command.blt
        pyxel.bltm = self._renderer.draw_command.bltm
        pyxel.text = self._renderer.draw_command.text
        pyxel.sound = self._audio_player.sound
        pyxel.music = self._audio_player.music
        pyxel.play = self._audio_player.play
        pyxel.playm = self._audio_player.playm
        pyxel.stop = self._audio_player.stop

        # initialize mouse cursor
        pyxel.image(3,
                    system=True).set(MOUSE_CURSOR_IMAGE_X,
                                     MOUSE_CURSOR_IMAGE_Y, MOUSE_CURSOR_DATA)
예제 #49
0
# noinspection PyUnusedLocal,PyShadowingNames
def scroll_callback(window, _x, _y):
    print('Mouse scroll:', _x, _y)


if __name__ == '__main__':

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

    width = 600
    height = 600

    window = glfw.create_window(width, height, 'Handling mouse events', None,
                                None)

    if not window:
        glfw.terminate()
        sys.exit()

    glfw.make_context_current(window)

    # Connecting the callback function 'on_key' to handle keyboard events
    glfw.set_key_callback(window, on_key)

    # Connecting callback functions to handle mouse events:
    # - Cursor moving over the window
    # - Mouse buttons input
    # - Mouse scroll
    glfw.set_cursor_pos_callback(window, cursor_pos_callback)
"""


# glfw callback functions
def window_resize(window, width, height):
    glViewport(0, 0, width, height)
    projection = pyrr.matrix44.create_perspective_projection_matrix(45, width / height, 0.1, 100)
    glUniformMatrix4fv(proj_loc, 1, GL_FALSE, projection)


# initializing glfw library
if not glfw.init():
    raise Exception("glfw can not be initialized!")

# creating the window
window = glfw.create_window(1280, 720, "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, 400, 200)
glfw.set_window_pos(window, 10, 20)

# set the callback function for window resize
glfw.set_window_size_callback(window, window_resize)
# set the mouse position callback
glfw.set_cursor_pos_callback(window, mouse_look_clb)
# set the keyboard input callback
예제 #51
0
    def __init__(self, win, *args, **kwargs):
        """Set up the backend window according the params of the PsychoPy win

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

        Parameters
        ----------
        win : psychopy.visual.Window instance
            PsychoPy Window (usually not fully created yet).
        share : psychopy.visual.Window instance
            PsychoPy Window to share a context with
        bpc : array_like
            Bits per color (R, G, B).
        refreshHz : int
            Refresh rate in Hertz.
        depthBits : int,
            Framebuffer (back buffer) depth bits.
        stencilBits : int
            Framebuffer (back buffer) stencil bits.
        swapInterval : int
            Screen updates before swapping buffers.
        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))

        # TODO - make waitBlanking set this too, independent right now
        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)

        # Enable vsync, GLFW has additional setting for this that might be
        # useful.
        glfw.swap_interval(win.swapInterval)

        # give the window class GLFW specific methods
        win.setMouseType = self.setMouseType
        if not win.allowGUI:
            self.setMouseVisibility(False)
예제 #52
0
def main():

    if not glfw.init():
        return

    glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 4)
    glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 3)
    glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE)
    window = glfw.create_window(800, 800, "Hello World", None, None)
    if not window:
        glfw.terminate()
        return

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

    # Enable VSync
    glfw.swap_interval(1)

    # World
    world = World.Resources()
    world.initialize()

    ray = Ray.Resources()
    ray.initialize()

    random = Random.Resources()
    random.initialize()

    # OpenGL
    glClearColor(0.2, 0.2, 0.2, 0)

    # Pan and zoom
    last_mouse_left = 0
    last_mouse_right = 0
    last_cursor = None
    transform_view = mat3(1.0)
    last_view = mat3(1.0)

    while not glfw.window_should_close(window):

        window_width, window_height = glfw.get_window_size(window)

        projection = mat_projection(window_width, window_height)

        # Pan and zoom
        last_inv_view_projection_viewport = inverse(
            mat_viewport(window_width, window_height) * projection * last_view)
        next_cursor = (last_inv_view_projection_viewport *
                       vec3(*glfw.get_cursor_pos(window), 1.0)).xy

        next_mouse_left = glfw.get_mouse_button(window, 0)
        if last_mouse_left != next_mouse_left:
            if next_mouse_left:
                last_cursor = next_cursor
            else:
                last_view = current_view
                transform_view = mat3(1.0)
            last_mouse_left = next_mouse_left
        else:
            if next_mouse_left:
                delta_cursor = next_cursor - last_cursor
                transform_view = mat3(1.0, 0.0, 0.0, 0.0, 1.0, 0.0,
                                      delta_cursor.x, delta_cursor.y, 1.0)

        if not next_mouse_left:
            next_mouse_right = glfw.get_mouse_button(window, 1)
            if last_mouse_right != next_mouse_right:
                if next_mouse_right:
                    last_cursor = next_cursor
                else:
                    last_view = current_view
                    transform_view = mat3(1.0)
                last_mouse_right = next_mouse_right
            else:
                if next_mouse_right:
                    current_view_zoom = max(
                        1.0 + max_abs(next_cursor - last_cursor), 1e-4)
                    pivot = mat3(1.0, 0.0, 0.0, 0.0, 1.0, 0.0, last_cursor.x,
                                 last_cursor.y, 1.0)
                    inv_pivot = mat3(1.0, 0.0, 0.0, 0.0, 1.0, 0.0,
                                     -last_cursor.x, -last_cursor.y, 1.0)
                    transform_view = pivot * mat3(current_view_zoom, 0.0, 0.0,
                                                  0.0, current_view_zoom, 0.0,
                                                  0.0, 0.0, 1.0) * inv_pivot

        # Setup view and projection
        current_view = last_view * transform_view
        current_view_projection = projection * current_view

        # Keep random stable through frames
        Random.init(random)

        # Display rays
        glViewport(0, 0, window_width, window_height)
        glClear(GL_COLOR_BUFFER_BIT)

        World.display(world, current_view_projection)

        for iteration in range(10):
            Ray.trace(ray, iteration, world.display_buffer, random.seed_buffer)
            Ray.display_lines(ray, current_view_projection, iteration)

        Ray.display_directions(ray, iteration)

        # Done !
        glfw.swap_buffers(window)
        glfw.poll_events()

    glfw.terminate()
예제 #53
0
    if glfw.get_key(window, glfw.KEY_A) == glfw.PRESS:
        camera.strafe_left()
    if glfw.get_key(window, glfw.KEY_R) == glfw.PRESS:
        camera.move_up()
    if glfw.get_key(window, glfw.KEY_F) == glfw.PRESS:
        camera.move_down()


def cursor_position_callback(window, xpos, ypos):
    camera.mouth_update(xpos, ypos)


if not glfw.init():
    raise Exception('glfw con not be initialized')

window = glfw.create_window(SCR_WIDTH, SCR_HEIGHT, 'My OpenGL window', None,
                            None)

if not window:
    glfw.terminate()
    raise Exception('glfw window can not be created')

glfw.set_window_pos(window, 4000, 200)
glfw.set_cursor_pos(window, SCR_WIDTH / 2, SCR_HEIGHT / 2)
glfw.set_window_size_callback(window, window_resize)
glfw.set_cursor_pos_callback(window, cursor_position_callback)
glfw.make_context_current(window)

# ============================================================ #
#                   Loading shaders                            #
# ============================================================ #
shader = ShaderLoader('lightning_test/shaders/cube.vs',
예제 #54
0
def main():
    width, height = 1280, 720
    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)

    # Create a windowed mode window and its OpenGL context
    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()

    opened = True

    style = imgui.GuiStyle()

    while not glfw.window_should_close(window):
        glfw.poll_events()
        imgui_ctx.new_frame()

        imgui.show_user_guide()
        imgui.show_test_window()

        if opened:
            expanded, opened = imgui.begin("fooo", True)
            imgui.text("Bar")
            imgui.text_colored("Eggs", 0.2, 1., 0.)
            imgui.end()

        with imgui.styled(imgui.STYLE_ALPHA, 1):
            imgui.show_metrics_window()

        imgui.show_style_editor(style)

        # note: this is redundant
        width, height = glfw.get_framebuffer_size(window)
        gl.glViewport(0, 0, int(width / 2), int(height))

        gl.glClearColor(114 / 255., 144 / 255., 154 / 255., 1)
        gl.glClear(gl.GL_COLOR_BUFFER_BIT)

        imgui.render()
        glfw.swap_buffers(window)

    glfw.terminate()
예제 #55
0
import glfw
from OpenGL.GL import *
import numpy as np
import random
from math import sin, cos
if not glfw.init():
    raise Exception('Glfw not initialized !')

window = glfw.create_window(512, 512, 'Triangle', None, None)
glfw.set_window_pos(window, 200, 400)
if not window:
    glfw.terminate()
    raise Exception('window not created !')
glfw.make_context_current(window)
glClearColor(0.5, 0.8, 0.9, 1)
ver = [-0.5, -0.5, 0, 0.5, -0.5, 0, 0.0, 0.5, 0.0]
col = [0.8, 0.0, 0.0, 0.6, 1.0, 1.0, 0.0, 0.0, 0.3]

ver = np.array(ver, dtype=np.float32)
col = np.array(col, dtype=np.float32)

glEnableClientState(GL_VERTEX_ARRAY)
glVertexPointer(3, GL_FLOAT, 0, ver)
glEnableClientState(GL_COLOR_ARRAY)
glColorPointer(3, GL_FLOAT, 0, col)

while not glfw.window_should_close(window):
    ct = glfw.get_time()
    glfw.poll_events()
    glClear(GL_COLOR_BUFFER_BIT)
    glDrawArrays(GL_TRIANGLES, 0, 3)
예제 #56
0
frustum = {
    'near': clip_start,
    'far': clip_end,
    'width': width,
    'height': height
}

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_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)

else:
    from OpenGL.raw.osmesa._types import *
    from OpenGL.raw.osmesa import mesa

winShared = None

gtCamElevation = np.pi / 3
gtCamHeight = 0.4  #meters

chLightAzimuthGT = ch.Ch([0])
chLightElevationGT = ch.Ch([np.pi / 3])
chLightIntensityGT = ch.Ch([1])
chGlobalConstantGT = ch.Ch([0.5])
    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)
glMatrixMode(GL_PROJECTION)
glLoadIdentity()
def main():

    # initialize glfw
    if not glfw.init():
        return
    
    #creating the window
    window = glfw.create_window(800, 600, "My OpenGL window", None, None)

    if not window:
        glfw.terminate()
        return

    glfw.make_context_current(window)
    #           positions        colors          texture coords
    quad = [   -0.5, -0.5, 0.0,  1.0, 0.0, 0.0,  0.0, 0.0,
                0.5, -0.5, 0.0,  0.0, 1.0, 0.0,  1.0, 0.0,
                0.5,  0.5, 0.0,  0.0, 0.0, 1.0,  1.0, 1.0,
               -0.5,  0.5, 0.0,  1.0, 1.0, 1.0,  0.0, 1.0]

    quad = numpy.array(quad, dtype = numpy.float32)

    indices = [0, 1, 2,
               2, 3, 0]

    indices = numpy.array(indices, dtype= numpy.uint32)

    vertex_shader = """
    #version 330
    in layout(location = 0) vec3 position;
    in layout(location = 1) vec3 color;
    in layout(location = 2) vec2 inTexCoords;

    out vec3 newColor;
    out vec2 outTexCoords;
    void main()
    {
        gl_Position = vec4(position, 1.0f);
        newColor = color;
        outTexCoords = inTexCoords;
    }
    """

    fragment_shader = """
    #version 330
    in vec3 newColor;
    in vec2 outTexCoords;

    out vec4 outColor;
    uniform sampler2D samplerTex;
    void main()
    {
        outColor = texture(samplerTex, outTexCoords);
    }
    """
    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)
    glBindBuffer(GL_ARRAY_BUFFER, VBO)
    glBufferData(GL_ARRAY_BUFFER, 128, quad, GL_STATIC_DRAW)

    EBO = glGenBuffers(1)
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO)
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, 24, indices, GL_STATIC_DRAW)

    #position = glGetAttribLocation(shader, "position")
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 32, ctypes.c_void_p(0))
    glEnableVertexAttribArray(0)

    #color = glGetAttribLocation(shader, "color")
    glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 32, ctypes.c_void_p(12))
    glEnableVertexAttribArray(1)

    #texCoords = glGetAttribLocation(shader, "inTexCoords")
    glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 32, ctypes.c_void_p(24))
    glEnableVertexAttribArray(2)



    texture = glGenTextures(1)
    glBindTexture(GL_TEXTURE_2D, texture)
    #texture wrapping params
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT)
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT)
    #texture filtering params
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR)
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)

    image = Image.open("res/crate.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)




    glUseProgram(shader)

    glClearColor(0.2, 0.3, 0.2, 1.0)

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

        glClear(GL_COLOR_BUFFER_BIT)

        glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, None)

        glfw.swap_buffers(window)

    glfw.terminate()
예제 #59
0
uniform sampler2D s_texture;

void main(){
    out_color = texture(s_texture, v_texture);
}
"""


def window_resize(wind, width, height):
    glViewport(0, 0, width, height)


if not glfw.init():
    raise Exception('AAAAAA')

window = glfw.create_window(1024, 768, 'XXXXXDDDD', None, None)

if not window:
    glfw.terminate()
    raise Exception('AAAAA')

glfw.set_window_pos(window, 100, 100)
glfw.set_window_size_callback(window, window_resize)

glfw.make_context_current(window)

vertices = np.array([
    -0.5, -0.5, 0.5, 1.0, 0.0, 0.0, 0.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, 0.0, 1.0, 1.0, 1.0, -0.5, 0.5, 0.5, 1.0, 1.0,
    1.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,
    0.0, 1.0, 0.0, 1.0, 0.0, 0.5, 0.5, -0.5, 0.0, 0.0, 1.0, 1.0, 1.0, -0.5,
예제 #60
0
out vec4 FragColor;

uniform sampler2D s_texture;

void main()
{  FragColor=texture(s_texture,v_texture);
}
"""

def window_resize(window, width, height):
    glViewport(0, 0, width, height)

if not glfw.init():
    raise Exception("HOGE")

window=glfw.create_window(1280,720,"BOX",None,None)
if not window:
    glfw.terminate()
    raise Exception("glfw window cannot be crated")


glfw.set_window_pos(window,200,200)
glfw.set_window_size_callback(window, window_resize)
glfw.make_context_current(window)

x=0.225
y=0.325
z=0.1

frontpicx1=895/1377
frontpicy1=87/567