def on_draw():
    gl.glMatrixMode(gl.GL_MODELVIEW)
    gl.glLoadIdentity()

    # Gradient sky
    l, b = world_to_screen((0, 0))
    r, t = world_to_screen((W, H))
    horizon = 177 / 255.0, 202 / 255.0, 1.0
    zenith = 68 / 255.0, 0.5, 1.0
    pyglet.graphics.draw(4, gl.GL_QUADS,
        ('v2f', [l, b, l, t, r, t, r, b]),
        ('c3f', sum([horizon, zenith, zenith, horizon], ())),
    )

    cx, cy = camera
    tx, ty = world_to_screen((-cx + W * 0.5, -cy + H * 0.5))
    gl.glTranslatef(tx, ty, 0)
    batch.draw()

    # Water
    l, b = world_to_screen((0, 0))
    r, t = world_to_screen((1000, WATER_LEVEL))
    gl.glEnable(gl.GL_BLEND)
    gl.glBlendFunc(gl.GL_SRC_ALPHA, gl.GL_ONE_MINUS_SRC_ALPHA)
    pyglet.graphics.draw(4, gl.GL_QUADS,
        ('v2f', [l, b, l, t, r, t, r, b]),
        ('c4f', [0, 0.2, 0.8, 0.5] * 4),
    )
Example #2
0
def texture_from_data(internalformat, size, data_format, data_type, data):
    '''Create texture from a data buffer (whatever can be passed as pointer to ctypes)
    internalformat - GL_RGBA8 or GL_RGB8 recommended
    size - a 1-, 2- or 3-tuple describing the image sizes
    data_format - see 'format' parameter of glDrawPixels
    data_type - see 'type' parameter of glDrawPixels
    data - pointer to memory'''

    size = list(size)
    dimensions = len(size)
    binding = getattr(gl, 'GL_TEXTURE_BINDING_{0:d}D'.format(dimensions))
    target = getattr(gl,'GL_TEXTURE_{0:d}D'.format(dimensions))
    texImage = getattr(gl,'glTexImage{0:d}D'.format(dimensions))
    oldbind = ctypes.c_uint(0)
    gl.glGetIntegerv(binding, ctypes.cast(ctypes.byref(oldbind), ctypes.POINTER(ctypes.c_int)))
    texid = ctypes.c_uint(0)
    gl.glEnable(target)
    gl.glGenTextures(1, ctypes.byref(texid))
    gl.glBindTexture(target, texid)
    gl.glTexParameteri(target, gl.GL_TEXTURE_MIN_FILTER, gl.GL_LINEAR)
    gl.glTexParameteri(target, gl.GL_TEXTURE_MAG_FILTER, gl.GL_LINEAR)

    args = [target, 0, internalformat] + size + [0, data_format, data_type, data]

    texImage(*args)
    gl.glBindTexture(target, oldbind)
    return texid
Example #3
0
    def render(self, geometry):
        """ Add the sphere to the view.

        :param scene: The view to render the model into
        :type scene: pyglet_helper.objects.View
        """
        # Renders a simple sphere with the #2 level of detail.
        if self.radius == 0.0:
            return
        self.init_model(geometry)

        coverage_levels = [30, 100, 500, 5000]
        lod = self.lod_adjust(geometry, coverage_levels, self.pos, self.radius)
        gl.glPushMatrix()

        self.model_world_transform(geometry.gcf, self.scale).gl_mult()
        self.color.gl_set(self.opacity)

        if self.translucent:
            # Spheres are convex, so we don't need to sort
            gl.glEnable(gl.GL_CULL_FACE)

            # Render the back half (inside)
            gl.glCullFace(gl.GL_FRONT)
            geometry.sphere_model[lod].gl_render()

            # Render the front half (outside)
            gl.glCullFace(gl.GL_BACK)
            geometry.sphere_model[lod].gl_render()
        else:
            # Render a simple sphere.
            geometry.sphere_model[lod].gl_render()
        gl.glPopMatrix()
Example #4
0
    def draw(self):
        if self._dirty:
            self._context = Context()
            self._parts = []
            self.free()
            self.render()
            self.build_vbo()
            self._dirty = False

        # set
        gl.glEnable(self._texture.target)
        gl.glBindTexture(self._texture.target, self._texture.id)
        gl.glPushAttrib(gl.GL_COLOR_BUFFER_BIT)

        gl.glEnable(gl.GL_BLEND)
        gl.glBlendFunc(gl.GL_SRC_ALPHA, gl.GL_ONE_MINUS_SRC_ALPHA)

        gl.glPushMatrix()
        self.transform()
        # cuadric.begin()
        self._vertex_list.draw(gl.GL_TRIANGLES)
        # cuadric.end()

        # unset
        gl.glPopMatrix()
        gl.glPopAttrib()
        gl.glDisable(self._texture.target)
Example #5
0
    def draw_bounding_box(self, x, y, screen_height):
        bb = self.get_bounding_box()
        bb = [bb['min_x'], bb['min_y'], bb['max_x'], bb['max_y']]
        vertices = ()
        for _ in bb:
            vertices += (_.x,)
            vertices += (screen_height - _.y,)

        # get opengl vertices of type GLfloat
        vertices_gl = (GLfloat * len(vertices))(*vertices)

        # set the color
        glColor4ub(0, 255, 0, 255);
        glPolygonMode( GL_FRONT_AND_BACK, GL_LINE );

        # turn on blend for alpha channel
        glEnable(GL_BLEND)

        # tell open GL were passing a vertex array
        glEnableClientState(GL_VERTEX_ARRAY)

        # create a pointer to vertices_gl
        glVertexPointer(2, GL_FLOAT, 0, vertices_gl)
       
        # draw the array
        glDrawArrays(GL_POLYGON, 0, len(vertices) // 2)

        glPolygonMode( GL_FRONT_AND_BACK, GL_FILL );
Example #6
0
    def __init__(self, *args, **kwargs):
        super(VIctorApp, self).__init__(640, 400, caption="victor")

        self.set_default_options()

        self.mode = vmode.NORMAL
        self.down_action = None
        self.text_event = None

        self.batch = pyglet.graphics.Batch()

        self.setup_cursor()

        self.marks = dict()

        self.command_area = CommandArea(0, 0, 550, self.batch)
        self.keystrokes = Keystrokes(550, 0, 70, self.batch)

        self.current_multiplier = None
        self.normal_dispatcher = vnd.construct_dispatcher(self)
        self.set_ex_commands()

        self.groups = self.current_group = PathGroup()
        self.current_path = None

        self.time = time.time()
        pyglet.clock.schedule_interval(self.on_timer_fire, 0.05)

        gl.glBlendFunc(gl.GL_SRC_ALPHA, gl.GL_ONE_MINUS_SRC_ALPHA)
        gl.glEnable(gl.GL_BLEND)
Example #7
0
    def set_state(self):
        gl.glPushAttrib(gl.GL_ENABLE_BIT | gl.GL_TRANSFORM_BIT | gl.GL_CURRENT_BIT)
        gl.glEnable(gl.GL_BLEND)
        gl.glBlendFuncSeparate(gl.GL_SRC_ALPHA, gl.GL_ONE_MINUS_SRC_ALPHA, gl.GL_ONE, gl.GL_ONE_MINUS_SRC_ALPHA)
        # To Allow Normal Rendering when Buffering with FrameBufferObject
        # Without this option : problem with alpha blending when rendering buffered GUI textures
        #Also in context.glContext

        # Disable clipping planes to check culling.
        gl.glEnable(gl.GL_CLIP_PLANE0)
        gl.glEnable(gl.GL_CLIP_PLANE1)
        gl.glEnable(gl.GL_CLIP_PLANE2)
        gl.glEnable(gl.GL_CLIP_PLANE3)
        # Left
        gl.glClipPlane(gl.GL_CLIP_PLANE0, (gl.GLdouble * 4)(
                    1, 0, 0, -(self._clip_x - 1)))
        # Top
        gl.glClipPlane(gl.GL_CLIP_PLANE1, (gl.GLdouble * 4)(
                    0, -1, 0, self._clip_y))
        # Right
        gl.glClipPlane(gl.GL_CLIP_PLANE2, (gl.GLdouble * 4)(
                    -1, 0, 0, self._clip_x + self._clip_width + 1))
        # Bottom
        gl.glClipPlane(gl.GL_CLIP_PLANE3, (gl.GLdouble * 4)(
                    0, 1, 0, -(self._clip_y - self._clip_height)))
        gl.glTranslatef(self.translate_x, self.translate_y, 0)
Example #8
0
    def poll(dt):
        out = next(itr, False)
        if out is False:
            if args.pause:
                label.text = "Done. ('q' to quit)"
            else:
                pyglet.app.exit()
        elif out is not None:
            name, buf = out
            real_dt = time.time() - last_time[0]
            last_time[0] = time.time()
            if buf.dtype == np.uint8:
                fmt = gl.GL_UNSIGNED_BYTE
            elif buf.dtype == np.uint16:
                fmt = gl.GL_UNSIGNED_SHORT
            else:
                label.text = 'Unsupported format: ' + buf.dtype
                return

            h, w, ch = buf.shape
            gl.glEnable(tex.target)
            gl.glBindTexture(tex.target, tex.id)
            gl.glTexImage2D(tex.target, 0, gl.GL_RGB8, w, h, 0, gl.GL_RGBA,
                            fmt, buf.tostring())
            gl.glDisable(tex.target)
            label.text = '%s (%g fps)' % (name, 1./real_dt)
        else:
            label.text += '.'
Example #9
0
 def _draw_wireframe_display_list(self, dl):
     pgl.glPushAttrib(pgl.GL_ENABLE_BIT | pgl.GL_POLYGON_BIT)
     pgl.glPolygonMode(pgl.GL_FRONT_AND_BACK, pgl.GL_LINE)
     pgl.glEnable(pgl.GL_POLYGON_OFFSET_LINE)
     pgl.glPolygonOffset(-0.005, -50.0)
     pgl.glCallList(dl)
     pgl.glPopAttrib()
Example #10
0
    def _drawLUTtoScreen(self):
        """(private) Used to set the LUT in Bits++ mode.

        Should not be needed by user if attached to a ``psychopy.visual.Window()``
        since this will automatically draw the LUT as part of the screen refresh.
        """
        #push the projection matrix and set to orthorgaphic
        GL.glMatrixMode(GL.GL_PROJECTION)
        GL.glPushMatrix()
        GL.glLoadIdentity()
        GL.glOrtho( 0, self.win.size[0],self.win.size[1], 0, 0, 1 )    #this also sets the 0,0 to be top-left
        #but return to modelview for rendering
        GL.glMatrixMode(GL.GL_MODELVIEW)
        GL.glLoadIdentity()

        #draw the pixels
        GL.glActiveTextureARB(GL.GL_TEXTURE0_ARB)
        GL.glEnable(GL.GL_TEXTURE_2D)
        GL.glBindTexture(GL.GL_TEXTURE_2D, 0)
        GL.glActiveTextureARB(GL.GL_TEXTURE1_ARB)
        GL.glEnable(GL.GL_TEXTURE_2D)
        GL.glBindTexture(GL.GL_TEXTURE_2D, 0)
        GL.glRasterPos2i(0,1)
        GL.glPixelStorei(GL.GL_UNPACK_ALIGNMENT, 1)
        GL.glDrawPixels(len(self._HEADandLUT),1,
            GL.GL_RGB,GL.GL_UNSIGNED_BYTE,
            self._HEADandLUTstr)
        #GL.glDrawPixels(524,1, GL.GL_RGB,GL.GL_UNSIGNED_BYTE, self._HEADandLUTstr)
        #return to 3D mode (go and pop the projection matrix)
        GL.glMatrixMode( GL.GL_PROJECTION )
        GL.glPopMatrix()
        GL.glMatrixMode( GL.GL_MODELVIEW )
Example #11
0
def enable_states(gl_states):
    """Context Manager that calls glEnable and glDisable on a list of gl states."""
    for state in gl_states:
        gl.glEnable(state)
    yield
    for state in gl_states:
        gl.glDisable(state)
Example #12
0
def rect(a, b, color=(1.0,1.0,1.0), alpha=1.0):
    """
    Draws a rectangle in the plane spanned by a,b with GL_QUADS

    :param a: Point a
    :type a: 2-float tuple

    :param b: Point b
    :type b: 2-float tuple

    :param color: the color in [0..1] range
    :type color: 3-float tuple

    :param aa: Anti aliasing Flag

    :param alpha: the alpha value in [0..1] range

    """

    glDisable(GL_TEXTURE_2D)

    glBegin(GL_QUADS)
    glVertex3f(a[0], a[1], 0)
    glVertex3f(b[0], a[1], 0)
    glVertex3f(b[0], b[1], 0)
    glVertex3f(a[0], b[1], 0)

    glEnd()
    glEnable(GL_TEXTURE_2D)
    glColor4f(color+(alpha,))
Example #13
0
    def render(self, scene):
        """Add the cone to the scene.

        :param scene: The view to render the model into
        :type scene: pyglet_helper.objects.View
        """
        if self.radius == 0:
            return

        self.init_model(scene)

        coverage_levels = [10, 30, 90, 250, 450]
        lod = self.lod_adjust(scene, coverage_levels, self.pos, self.radius)

        length = self.axis.mag()
        gl.glPushMatrix()
        self.model_world_transform(scene.gcf, Vector([length, self.radius,
                                                      self.radius])).gl_mult()

        self.color.gl_set(self.opacity)
        if self.translucent:
            gl.glEnable(gl.GL_CULL_FACE)

            # Render the back half.
            gl.glCullFace(gl.GL_FRONT)
            scene.cone_model[lod].gl_render()

            # Render the front half.
            gl.glCullFace(gl.GL_BACK)
            scene.cone_model[lod].gl_render()
        else:
            scene.cone_model[lod].gl_render()
        gl.glPopMatrix()
Example #14
0
 def upload(self):
     '''
     Upload atlas data into video memory.
     '''
     glEnable( GL_TEXTURE_2D )
     if self.texid is None:
         self.texid = GLuint(0)
         glGenTextures(1,ctypes.byref(self.texid))
     glBindTexture( GL_TEXTURE_2D, self.texid )
     glTexParameteri( GL_TEXTURE_2D,
                         GL_TEXTURE_WRAP_S, GL_CLAMP )
     glTexParameteri( GL_TEXTURE_2D,
                         GL_TEXTURE_WRAP_T, GL_CLAMP )
     glTexParameteri( GL_TEXTURE_2D,
                         GL_TEXTURE_MAG_FILTER, GL_LINEAR )
     glTexParameteri( GL_TEXTURE_2D,
                         GL_TEXTURE_MIN_FILTER, GL_LINEAR )
     if self.depth == 1:
         glTexImage2D( GL_TEXTURE_2D, 0, GL_ALPHA,
                          self.width, self.height, 0,
                          GL_ALPHA, GL_UNSIGNED_BYTE, self.data.ctypes )
     elif self.depth == 3:
         glTexImage2D( GL_TEXTURE_2D, 0, GL_RGB,
                          self.width, self.height, 0,
                          GL_RGB, GL_UNSIGNED_BYTE, self.data.ctypes )
     else:
         glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA,
                          self.width, self.height, 0,
                          GL_RGBA, GL_UNSIGNED_BYTE, self.data.ctypes )
     glBindTexture( GL_TEXTURE_2D, 0 )
Example #15
0
 def on_draw(self):
     self.window.clear()
     gl.glMatrixMode(gl.GL_PROJECTION)
     gl.glPushMatrix()
     gl.glLoadIdentity()
     self.camera()
     gl.glEnable(self.grass.target)
     gl.glEnable(gl.GL_BLEND)
     gl.glBindTexture(self.grass.target, self.grass.id)
     W = 10000.
     graphics.draw(4, gl.GL_QUADS,
         ('v2f', (-W, -W, W, -W, W, W, -W, W)),
         ('t2f', (0., 0., W*5., 0., W*5., W*5., 0., W*5.))
     )
     gl.glDisable(self.grass.target)
     for lane in self.lanes:
         self.draw_lane_surface(lane)
     for lane in self.lanes:
         self.draw_lane_lines(lane)
     for obj in self.objects:
         self.draw_object(obj)
     for car in self.cars:
         if car!=self.main_car and car not in self.visible_cars:
             self.draw_car(self.anim_x[car], car.color)
     if self.heat is not None:
         self.draw_heatmap()
     for car in self.cars:
         if car==self.main_car or car in self.visible_cars:
             self.draw_car(self.anim_x[car], car.color)
     gl.glPopMatrix()
     if isinstance(self.main_car, Car):
         self.label.text = 'Speed: %.2f'%self.anim_x[self.main_car][3]
         self.label.draw()
     if self.output is not None:
         pyglet.image.get_buffer_manager().get_color_buffer().save(self.output.format(self.frame))
    def draw(self, frame):
        # The gneneral plan here is:
        #  1. Get the dots in the range of 0-255.
        #  2. Create a texture with the dots data.
        #  3. Draw the texture, scaled up with nearest-neighbor.
        #  4. Draw a mask over the dots to give them a slightly more realistic look.

        gl.glEnable(gl.GL_BLEND)
        gl.glBlendFunc(gl.GL_SRC_ALPHA, gl.GL_ONE_MINUS_SRC_ALPHA)
        gl.glLoadIdentity()

        # Draw the dots in this color:
        #gl.glColor3f(1.0, 0.5, 0.25)

        gl.glScalef(1, -1, 1)
        gl.glTranslatef(0, -DMD_SIZE[1]*DMD_SCALE, 0)

        #data = frame.get_data_mult()
        
        #this new jk_get_data will read the dots using the dmd function
        #and convert them via the map to rGB.
        data = self.jk_get_data(frame)

        image = pyglet.image.ImageData(DMD_SIZE[0], DMD_SIZE[1], 'RGB', data, pitch=DMD_SIZE[0] * 3)  

        gl.glTexParameteri(image.get_texture().target, gl.GL_TEXTURE_MAG_FILTER, gl.GL_NEAREST)
        image.blit(0, 0, width=DMD_SIZE[0]*DMD_SCALE, height=DMD_SIZE[1]*DMD_SCALE)

        del image

        gl.glScalef(DMD_SCALE/float(MASK_SIZE), DMD_SCALE/float(MASK_SIZE), 1.0)
        gl.glColor4f(1.0, 1.0, 1.0, 1.0)
        self.mask_texture.blit_tiled(x=0, y=0, z=0, width=DMD_SIZE[0]*MASK_SIZE, height=DMD_SIZE[1]*MASK_SIZE)
Example #17
0
    def after_draw(self, camera):
        """Called by CocosNode when the texture is already grabbed.
        The FrameBuffer will be unbound and the texture will be drawn

        :Parameters:
            `camera` : `Camera`
                The target's camera object.
        """

        # capture after drawing
        self.grabber.after_render(self.texture)

        # after unbinding
        # set a 3d projection
        self._set_3d_projection()

        # and center the camera
        camera.locate(force=True)

        # blit
        gl.glEnable(self.texture.target)
        gl.glBindTexture(self.texture.target, self.texture.id)

        gl.glPushAttrib(gl.GL_COLOR_BUFFER_BIT)

        self._blit()

        gl.glPopAttrib()
        gl.glDisable(self.texture.target)
Example #18
0
File: main.py Project: Tythos/hypyr
	def setupOpenGL(self):
		gl.glClearColor(0., 0., 0., 1.)
		gl.glColor4f(1.0, 0.0, 0.0, 0.5)
		gl.glEnable(gl.GL_DEPTH_TEST)
		#gl.glEnable(gl.GL_CULL_FACE)
		gl.glEnable(gl.GL_BLEND)
		gl.glBlendFunc(gl.GL_SRC_ALPHA, gl.GL_ONE_MINUS_SRC_ALPHA)
Example #19
0
 def set_state(self):
     """
     Ensure that blending is set.
     """
     gl.glPushAttrib(gl.GL_ENABLE_BIT | gl.GL_CURRENT_BIT)
     gl.glEnable(gl.GL_BLEND)
     gl.glBlendFunc(gl.GL_SRC_ALPHA, gl.GL_ONE_MINUS_SRC_ALPHA)
Example #20
0
    def set_state(self):
        gl.glPushMatrix()
        gl.glMultMatrixf(rendering.matrix_to_gl(self.transform))

        if self.texture:
            gl.glEnable(self.texture.target)
            gl.glBindTexture(self.texture.target, self.texture.id)
Example #21
0
    def __init__(self, rows, columns, n_apples, *args, **kwargs):
        super(PygletEngine, self).__init__(rows, columns, n_apples, *args, **kwargs)

        gl.glEnable(gl.GL_BLEND)
        gl.glBlendFunc(gl.GL_SRC_ALPHA, gl.GL_ONE_MINUS_SRC_ALPHA)

        pyglet.clock.schedule_interval(lambda t: self.update_snakes(), 1/30.0)
Example #22
0
    def draw(self, scale, pos):
        LINE_COLOUR = (255, 255, 255)

        # gl.glEnable(gl.GL_DEPTH_TEST);
        gl.glEnable(gl.GL_BLEND)
        gl.glBlendFunc(gl.GL_SRC_ALPHA, gl.GL_ONE_MINUS_SRC_ALPHA)
        gl.glEnable(gl.GL_LINE_SMOOTH)
        gl.glHint(gl.GL_LINE_SMOOTH_HINT, gl.GL_DONT_CARE)

        gl.glBegin(gl.GL_LINES)
        for link in self.links:
            if link.highlight:
                gl.glColor3ub(*self.colour)
                gl.glColor3ub(*self.colour)
            else:
                gl.glColor3ub(*LINE_COLOUR)
                gl.glColor3ub(*LINE_COLOUR)
            if link.highlight:
                depth = 0.5
            else:
                depth = 0.5
            gl.glVertex3f(*util.add_tup(pos, util.scale_tup(link.points[0].pos, scale)) + (depth,))
            gl.glVertex3f(*util.add_tup(pos, util.scale_tup(link.points[1].pos, scale)) + (depth,))
            print util.add_tup(pos, util.scale_tup(link.points[0].pos, scale))
        gl.glEnd()
Example #23
0
def line(a, b, color=(1.0,1.0,1.0), width=1, aa=False, alpha=1.0):
    """
    Draws a line from point *a* to point *b* using GL_LINE_STRIP optionaly with GL_LINE_SMOOTH when *aa=True*

    :param a: Point a
    :type a: 2-float tuple

    :param b: Point b
    :type b: 2-float tuple

    :param color: the color in [0..1] range
    :type color: 3-float tuple

    :param width: The with for glLineWidth()

    :param aa: Anti aliasing Flag

    :param alpha: the alpha value in [0..1] range

    """

    glLineWidth(width)
    if aa:
        glEnable(GL_LINE_SMOOTH)

    draw(2,GL_LINES,('v2f',(a[0],a[1],b[0],b[1]) ) )
Example #24
0
def circle(pos, radius, color=(1.0,1.0,1.0), alpha=1.0,segments=6):
    """
    Draws a circle with gluDisk 
    
    :param pos: center of the circle
    :type pos: 2-float tuple

    :param radius: radius of the circle
    :type radius: float

    :param color: the color in [0..1] range
    :type color: 3-float tuple

    :param alpha: the alpha value in [0..1] range

    :param segments: number of segments
    :type segments: int

    """

    glDisable(GL_TEXTURE_2D)

    c = gluNewQuadric()
    glColor4f(color[0], color[1], color[2], alpha)
    glPushMatrix()
    glTranslatef(pos[0], pos[1], 0)
    gluDisk(c, 0, radius, segments, 1)
    glPopMatrix()
    glColor4f(1.0,1.0,1.0,1.0)
    glEnable(GL_TEXTURE_2D)
Example #25
0
File: trees.py Project: Knio/miru
    def _draw(self):
        corner = c = self.octree.corner
        w = self.octree.width

        gl.glPushAttrib( gl.GL_ENABLE_BIT )
        gl.glEnable( gl.GL_COLOR_MATERIAL )

        if self.octree._child_nodes is None:
            if self.list_id:
                gl.glCallList(self.list_id)
            else:
                self.list_id = gl.glGenLists(1)
                gl.glNewList(self.list_id, gl.GL_COMPILE)

                gl.glColor3f(*self.color)
                gl.glBegin(gl.GL_LINE_LOOP)
                gl.glVertex3f(*c)
                gl.glVertex3f(*(c + (0,w,0)))
                gl.glVertex3f(*(c + (0,w,w)))
                gl.glVertex3f(*(c + (0,0,w)))
                gl.glEnd()

                c = corner + (w,0,0)

                gl.glBegin(gl.GL_LINE_LOOP)
                gl.glVertex3f(*c)
                gl.glVertex3f(*(c + (0,w,0)))
                gl.glVertex3f(*(c + (0,w,w)))
                gl.glVertex3f(*(c + (0,0,w)))
                gl.glEnd()

                gl.glBegin(gl.GL_LINES)
                gl.glVertex3f(*c)
                gl.glVertex3f(*(c - (w,0,0)))
                gl.glVertex3f(*(c + (0,w,0)))
                gl.glVertex3f(*(corner + (0,w,0)))
                gl.glVertex3f(*(c + (0,w,w)))
                gl.glVertex3f(*(corner + (0,w,w)))
                gl.glVertex3f(*(c + (0,0,w)))
                gl.glVertex3f(*(corner + (0,0,w)))
                gl.glEnd()

                gl.glEndList()

        # This could be optimized of course
        if self.octree._child_nodes is not None:
            r = self.color[0] + 0.14
            if r < 1.0:
                r = r % 1.0
            else:
                r = 1.0
            b = max((self.color[2] - 0.14), 0)
            for node in self.octree._child_nodes.values():
                if not self._cache.has_key(id(node)):
                    self._cache[id(node)] = OctreeDebug(node, color=(r,0,b))
                debugNode = self._cache[id(node)]
                debugNode._draw()
        gl.glColor3f(1,1,1)

        gl.glPopAttrib()
Example #26
0
def main():
    global gJoyStick
    global show

    gl.glClearColor(0.0, 0.0, 0.0, 0.0)
    gl.glEnable( gl.GL_BLEND)
    gl.glBlendFunc( gl.GL_SRC_ALPHA, gl.GL_ONE_MINUS_SRC_ALPHA)


    #pyglet.clock.set_fps_limit(60)
    pyglet.clock.schedule_interval(update, 1/30.)

    window.set_vsync(True)

    for x in pyglet.input.get_joysticks():
        #readStick(x)
        pass

    gJoyStick = pyglet.input.get_joysticks()[0]
    gJoyStick.open()

    for x in gJoyStick.device.get_controls():
        #print x
        pass

    if len(sys.argv) > 1 and sys.argv[1] == '-b':
        show = 'buttons'
    else:
        show = 'axes'


    pyglet.app.run()
    print ""
Example #27
0
    def __init__(self, width, height, display=None):
        display = get_display(display)

        self.width = width
        self.height = height

        self.window = pyglet.window.Window(width=width,
                                           height=height,
                                           display=display)
        self.window.on_close = self.window_closed_by_user
        self.geoms = []
        self.onetime_geoms = []
        self.transform = Transform()

        glEnable(GL_BLEND)
        # glEnable(GL_MULTISAMPLE)
        glEnable(GL_LINE_SMOOTH)
        # glHint(GL_LINE_SMOOTH_HINT, GL_DONT_CARE)
        glHint(GL_LINE_SMOOTH_HINT, GL_NICEST)
        glLineWidth(2.0)
        glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)
Example #28
0
def load_texture(tex_path):
    from pyglet import gl
    logger.debug('loading texture "%s"' % os.path.basename(tex_path))
    import pyglet
    img = pyglet.image.load(tex_path)
    tex = img.get_texture()
    gl.glEnable(tex.target)
    gl.glBindTexture(tex.target, tex.id)
    gl.glTexImage2D(
        gl.GL_TEXTURE_2D,
        0,
        gl.GL_RGB,
        img.width,
        img.height,
        0,
        gl.GL_RGBA,
        gl.GL_UNSIGNED_BYTE,
        img.get_image_data().get_data('RGBA', img.width * 4)
    )

    return tex
Example #29
0
def on_draw():
    window.clear()

    gl.glEnable(gl.GL_TEXTURE_2D)

    gl.glBindTexture(gl.GL_TEXTURE_2D, texture.id)
    gl.glTexImage2D(gl.GL_TEXTURE_2D, 0, gl.GL_RGBA, WIDTH, HEIGHT, 0,
                    gl.GL_BGRA, gl.GL_UNSIGNED_BYTE, data)

    gl.glBegin(gl.GL_QUADS)
    gl.glTexCoord2f(0.0, 1.0)
    gl.glVertex2i(0, 0)
    gl.glTexCoord2f(1.0, 1.0)
    gl.glVertex2i(WIDTH, 0)
    gl.glTexCoord2f(1.0, 0.0)
    gl.glVertex2i(WIDTH, HEIGHT)
    gl.glTexCoord2f(0.0, 0.0)
    gl.glVertex2i(0, HEIGHT)
    gl.glEnd()

    text.draw()
Example #30
0
 def draw(self):
     gl.glLineWidth(1)
     rgb = mcol.hsv_to_rgb(self.hsv)
     gl.glBlendFunc(gl.GL_SRC_ALPHA, gl.GL_ONE_MINUS_SRC_ALPHA)
     gl.glEnable(gl.GL_BLEND)
     gl.glColor4f(rgb[0], rgb[1], rgb[2], self.alpha)
     gl.glBegin(gl.GL_LINE_STRIP)
     if self.camera == None:
         for i in range(self.endPoint-self.startPoint):
             gl.glVertex2f(self.vts[0, self.startPoint+i], self.vts[1, self.startPoint+i])
         gl.glEnd()
     else:
         self.vtsC = self.camera.project(self.vts)
         for i in range(self.endPoint-self.startPoint):
             id = self.endPoint-i-1
             self.signals[id] = self.signals[max(self.startPoint, id-self.propagationVel)]
             self.color[:, id] = self.color[:, max(self.startPoint, id-self.propagationVel)]
             col = mcol.hsv_to_rgb([self.color[0, id], self.color[1, id], self.signals[id]])#self.color[2, id] + self.signal2colorV(self.signals[id])])
             gl.glColor4f(col[0], col[1], col[2], self.color[3, id])
             gl.glVertex2f(self.vtsC[0, id], self.vtsC[1, id])
         gl.glEnd()
Example #31
0
def load_sprite(name, relative_scale=1, flip_y=False, origin=(0, 0)):
    if name not in images:
        images[name] = pg.resource.image(name)

    img = images[name]

    scale = sprite_scale * relative_scale

    sprite = pg.sprite.Sprite(img)
    sprite.scale_x = scale
    sprite.scale_y = -scale if flip_y else scale

    sprite.origin = origin

    # enable nearest filtering, ugly but works
    gl.glEnable(gl.GL_TEXTURE_2D)
    gl.glBindTexture(gl.GL_TEXTURE_2D, sprite._texture.id)
    gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MAG_FILTER,
                       gl.GL_NEAREST)

    return sprite
Example #32
0
    def on_draw(self):
        self.camera.update_matrices()

        # bind textures

        gl.glActiveTexture(gl.GL_TEXTURE0)
        gl.glBindTexture(gl.GL_TEXTURE_2D_ARRAY,
                         self.world.texture_manager.texture_array)
        gl.glUniform1i(self.shader_sampler_location, 0)

        # draw stuff

        gl.glEnable(gl.GL_DEPTH_TEST)
        gl.glEnable(gl.GL_CULL_FACE)

        gl.glClearColor(0.0, 0.0, 0.0, 1.0)
        self.clear()
        self.world.draw()

        gl.glFinish(
        )  # there seems to be a bit of a bug in Pyglet which makes this call necessary
Example #33
0
    def draw(self, uniforms, text, quad, textures=(), *args, **kwargs):
        glUseProgram(self)
        glDisable(GL_DEPTH_TEST)

        quad.enable()

        self.uniforms[b'color'].load(0.3, 0.3, 0.5)

        text.get_transformation_matrix_2D(
            location=self.uniforms[b'transformation'])

        textures.enable()

        quad.draw()

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

        glDisableVertexAttribArray(0)

        glEnable(GL_DEPTH_TEST)
Example #34
0
def update_display(verts, tex_coords, texture=bird_texture):
    gl.glClearColor(0.2, 0.4, 0.5, 1.0)

    gl.glEnable(texture.target)
    gl.glBindTexture(texture.target, texture.id)

    gl.glPushAttrib(gl.GL_COLOR_BUFFER_BIT)

    gl.glEnable(gl.GL_ALPHA_TEST)
    gl.glAlphaFunc(gl.GL_GREATER, .1)
    #gl.glEnable(gl.GL_BLEND)
    #gl.glBlendFunc (gl.GL_SRC_ALPHA, gl.GL_ONE_MINUS_SRC_ALPHA)
    gl.glEnable(gl.GL_DEPTH_TEST)

    gl.glEnableClientState(gl.GL_VERTEX_ARRAY)
    gl.glEnableClientState(gl.GL_TEXTURE_COORD_ARRAY)

    n = len(verts[:])
    #TODO verts._buffer.ctypes.data is awkward
    gl.glVertexPointer(3, vert_dtype.gl, 0, verts[:].ctypes.data)
    gl.glTexCoordPointer(3, tex_dtype.gl, 0, tex_coords[:].ctypes.data)
    gl.glDrawArrays(gl.GL_TRIANGLE_STRIP, 0, n)
    #unset state
    gl.glPopAttrib()
    gl.glDisable(texture.target)
Example #35
0
    def on_draw(self):
        gl.glClearColor(0, 0.0, 0.0, 1.)
        self.clear()
        width, height = self.get_size()
        gl.glViewport(0, 0, width, height)

        K_gl = get_projector_gl_intrinsics()
        TF = get_extrinsics()
        R = np.array([[-1., 0., 0., 0.], [0., 1., 0., 0.], [0., 0., -1., 0.],
                      [0., 0., 0., 1.]])
        full_mat = np.ascontiguousarray((K_gl.dot(TF.dot(R))).astype('f4'))
        with self.prog.using():
            self.prog.uniforms.Mvp = full_mat.tolist()
            gl.glEnable(gl.GL_DEPTH_TEST)
            gl.glEnable(gl.GL_BLEND)
            gl.glBlendFunc(gl.GL_SRC_ALPHA, gl.GL_ONE_MINUS_SRC_ALPHA)
            gl.glPointSize(25.)
            distance = (0, 0, 1)
            gl.glPointParameterfv(gl.GL_POINT_DISTANCE_ATTENUATION,
                                  (gl.GLfloat * 3)(*distance))
            gl.glEnable(gl.GL_POINT_SPRITE)
            self.vertex_info.draw(gl.GL_POINTS)

        gl.glMatrixMode(gl.GL_PROJECTION)
        gl.glLoadIdentity()
        gl.glOrtho(0, width, 0, height, -1, 1)
        gl.glMatrixMode(gl.GL_MODELVIEW)
        gl.glLoadIdentity()
        gl.glMatrixMode(gl.GL_TEXTURE)
        gl.glLoadIdentity()
        gl.glDisable(gl.GL_DEPTH_TEST)
        gl.glDisable(gl.GL_BLEND)

        self.fps_display.draw()
Example #36
0
 def enable_lightning(self):
     gl.glEnable(gl.GL_LIGHTING)
     gl.glEnable(gl.GL_BLEND)
     gl.glLightf(gl.GL_LIGHT0, gl.GL_CONSTANT_ATTENUATION, 0.1)
     gl.glLightf(gl.GL_LIGHT0, gl.GL_LINEAR_ATTENUATION, 0.05)
     gl.glEnable(gl.GL_LIGHT0)
     return
Example #37
0
    def draw(self):
        """
        Draw everything in the list.
        """
        # gl.glClear(gl.GL_COLOR_BUFFER_BIT)
        gl.glEnableClientState(gl.GL_VERTEX_ARRAY)
        gl.glLoadIdentity()

        gl.glTranslatef(self.center_x, self.center_y, 0)
        if self.angle:
            gl.glRotatef(self.angle, 0, 0, 1)

        last_color = None
        last_line_width = None

        for shape in self.shape_list:
            if shape.vbo_color_id is not None:
                gl.glEnableClientState(gl.GL_COLOR_ARRAY)
            else:
                gl.glDisableClientState(gl.GL_COLOR_ARRAY)
                if last_color is None or last_color != shape.color:
                    last_color = shape.color

                    if len(shape.color) == 4:
                        gl.glColor4ub(shape.color[0], shape.color[1], shape.color[2],
                                      shape.color[3])
                        gl.glEnable(gl.GL_BLEND)
                        gl.glBlendFunc(gl.GL_SRC_ALPHA, gl.GL_ONE_MINUS_SRC_ALPHA)
                    elif len(shape.color) == 3:
                        gl.glDisable(gl.GL_BLEND)
                        gl.glColor4ub(shape.color[0], shape.color[1], shape.color[2], 255)

            if shape.line_width and last_line_width != shape.line_width:
                last_line_width = shape.line_width
                gl.glLineWidth(shape.line_width)

            if shape.vbo_color_id is None:
                stripped_render(shape)
            else:
                stripped_render_with_colors(shape)
Example #38
0
    def set_state(self):
        super().set_state()

        # enable alpha colors
        gl.glEnable(gl.GL_BLEND)
        gl.glBlendFunc(gl.GL_SRC_ALPHA, gl.GL_ONE_MINUS_SRC_ALPHA)

        # enable anti-aliasing
        gl.glEnable(gl.GL_POINT_SMOOTH)
        gl.glEnable(gl.GL_LINE_SMOOTH)
        gl.glEnable(gl.GL_POLYGON_SMOOTH)
        gl.glHint(gl.GL_POINT_SMOOTH_HINT, self.quality)
        gl.glHint(gl.GL_LINE_SMOOTH_HINT, self.quality)
        gl.glHint(gl.GL_POLYGON_SMOOTH_HINT, self.quality)
Example #39
0
    def render(self, mode='human'):
        """
        Rendering the environments state
        :type mode: Either "human" for direct to screen rendering or "rgb_array"
        """
        if self.viewer is None:
            self._padding = 10
            screen_width = 600

            world_size_x = self._world_x_max - self._world_x_min
            world_size_y = self._world_y_max - self._world_y_min
            self._scale = screen_width / world_size_x
            screen_height = int(world_size_y * self._scale)

            from gym.envs.classic_control import rendering
            from pyglet import gl
            self.viewer = rendering.Viewer(screen_width + 2 * self._padding,
                                           screen_height + 2 * self._padding)

            background = rendering.FilledPolygon([
                (0, 0), (0, screen_height + 2 * self._padding),
                (screen_width + 2 * self._padding,
                 screen_height + 2 * self._padding),
                (screen_width + 2 * self._padding, 0)
            ])
            background.set_color(*ColorScheme.background_inactive)
            self.viewer.add_geom(background)

            gl.glEnable(gl.GL_LINE_SMOOTH)
            gl.glEnable(gl.GL_POLYGON_SMOOTH)

            self._render_mvas()
            self._render_runway()
            self._render_faf()
            self._render_approach()

        self._render_airplane(self._airplane)
        self._render_reward()

        return self.viewer.render(mode == 'rgb_array')
Example #40
0
    def draw(self, win=None):
        """Draw the current frame to a particular visual.Window (or to the
        default win for this object if not specified). The current
        position in the movie will be determined automatically.

        This method should be called on every frame that the movie is
        meant to appear.
        """

        if (self.status == NOT_STARTED or
                (self.status == FINISHED and self.loop)):
            self.play()
        elif self.status == FINISHED and not self.loop:
            return
        if win is None:
            win = self.win
        self._selectWindow(win)
        self._updateFrameTexture()  # will check if it's needed

        # scale the drawing frame and get to centre of field
        GL.glPushMatrix()  # push before drawing, pop after
        # push the data for client attributes
        GL.glPushClientAttrib(GL.GL_CLIENT_ALL_ATTRIB_BITS)

        self.win.setScale('pix')
        # move to centre of stimulus and rotate
        vertsPix = self.verticesPix

        # bind textures
        GL.glActiveTexture(GL.GL_TEXTURE1)
        GL.glBindTexture(GL.GL_TEXTURE_2D, 0)
        GL.glEnable(GL.GL_TEXTURE_2D)
        GL.glActiveTexture(GL.GL_TEXTURE0)
        GL.glBindTexture(GL.GL_TEXTURE_2D, self._texID)
        GL.glEnable(GL.GL_TEXTURE_2D)

        # sets opacity (1,1,1 = RGB placeholder)
        GL.glColor4f(1, 1, 1, self.opacity)

        array = (GL.GLfloat * 32)(
            1, 1,  # texture coords
            vertsPix[0, 0], vertsPix[0, 1], 0.,  # vertex
            0, 1,
            vertsPix[1, 0], vertsPix[1, 1], 0.,
            0, 0,
            vertsPix[2, 0], vertsPix[2, 1], 0.,
            1, 0,
            vertsPix[3, 0], vertsPix[3, 1], 0.,
        )

        # 2D texture array, 3D vertex array
        GL.glInterleavedArrays(GL.GL_T2F_V3F, 0, array)
        GL.glDrawArrays(GL.GL_QUADS, 0, 4)
        GL.glPopClientAttrib()
        GL.glPopAttrib()
        GL.glPopMatrix()
        # unbind the textures
        GL.glActiveTexture(GL.GL_TEXTURE0)
        GL.glBindTexture(GL.GL_TEXTURE_2D, 0)
        GL.glEnable(GL.GL_TEXTURE_2D)  # implicitly disables 1D
Example #41
0
    def multi_draw(*args, **kwargs):
        gl.glEnable(gl.GL_BLEND)
        gl.glBlendFunc(gl.GL_ONE, gl.GL_ONE)
        gl.glEnable(gl.GL_LINE_SMOOTH)
        gl.glEnable(gl.GL_POINT_SMOOTH)
        gl.glClearColor(0, 0, 0, 0)
        gl.glColor4f(1, 1, 1, 1)

        gl.glClear(gl.GL_COLOR_BUFFER_BIT)

        if not buffers:
            buffers.append(image.get_buffer_manager())
        x, y, w, h = buffers[0].get_viewport()

        #Draw lowres version
        gl.glViewport(0, 0, 256, 256)
        func(*args, **kwargs)
        texes.append(buffers[0].get_color_buffer().texture)
        if len(texes) > num_texes:
            texes.pop(0)

        #Lay down copies of lowres version
        gl.glViewport(x, y, w, h)
        gl.glClear(gl.GL_COLOR_BUFFER_BIT)
        if texes:
            alphas = range(1, len(texes) + 1)
            alphas = [float(f) / sum(alphas) for f in alphas]
            for tex, alpha in zip(texes, alphas):
                gl.glBindTexture(tex.target, tex.id)

                gl.glEnable(gl.GL_TEXTURE_2D)
                gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MAG_FILTER,
                                   gl.GL_LINEAR)

                gl.glColor4f(1, 1, 1, alpha)
                gl.glBegin(gl.GL_QUADS)
                gl.glTexCoord2f(0, 0)
                gl.glVertex3f(0, 0, -.5)
                gl.glTexCoord2f(1, 0)
                gl.glVertex3f(w, 0, -.5)
                gl.glTexCoord2f(1, 1)
                gl.glVertex3f(w, h, -.5)
                gl.glTexCoord2f(0, 1)
                gl.glVertex3f(0, h, -.5)
                gl.glEnd()
                gl.glDisable(gl.GL_TEXTURE_2D)

        #Draw real thing
        gl.glColor4f(1, 1, 1, 1)
        func(*args, **kwargs)
Example #42
0
    def _blitEyeBuffer(self, eye):
        """Warp and blit to the appropriate eye buffer.

        Parameters
        ----------
        eye : str
            Eye buffer being used.

        """
        GL.glBindTexture(GL.GL_TEXTURE_2D,
                         self._eyeBuffers[eye]['frameTexture'])

        GL.glEnable(GL.GL_SCISSOR_TEST)
        # set the viewport and scissor rect for the buffer
        frameW, frameH = self._bufferViewports[eye][2:]

        offset = 0 if eye == 'left' else frameW
        self.viewport = self.scissor = (offset, 0, frameW, frameH)

        GL.glMatrixMode(GL.GL_PROJECTION)
        GL.glLoadIdentity()
        GL.glOrtho(-1, 1, -1, 1, -1, 1)
        GL.glMatrixMode(GL.GL_MODELVIEW)
        GL.glLoadIdentity()

        # anti-aliasing the edges of the polygon
        GL.glEnable(GL.GL_MULTISAMPLE)

        # blit the quad covering the side of the display the eye is viewing
        if self.lensCorrection:
            gt.drawVAO(self._warpVAOs[eye])
        else:
            self._renderFBO()

        GL.glDisable(GL.GL_MULTISAMPLE)

        # reset
        GL.glDisable(GL.GL_SCISSOR_TEST)
        self.viewport = self.scissor = \
            (0, 0, self.frameBufferSize[0], self.frameBufferSize[1])
Example #43
0
    def on_draw(self):
        gl.glClearColor(0.5, 0.69, 1.0, 1.0)
        gl.glClear(gl.GL_COLOR_BUFFER_BIT | gl.GL_DEPTH_BUFFER_BIT)

        self.cam.apply()

        gl.glEnable(gl.GL_DEPTH_TEST)
        gl.glEnable(gl.GL_LIGHTING)
        gl.glEnable(gl.GL_CULL_FACE)

        render_light((2, 10, -2))

        gl.glMaterialfv(gl.GL_FRONT, gl.GL_AMBIENT_AND_DIFFUSE, to_gl_float([0.7, 0.7, 0.7, 1.0]))

        check_draw_distance(self.cam.current_chunk)

        if len(meshing_list) > 0:
            chunks[meshing_list.pop(0)].mesh()

        for chunk in active_chunks:
            chunks[chunk].vbo.draw()

        self.cam.ui_mode()

        self.cam.ui.draw()

        self.cam.perspective()
        self.cam.apply()
Example #44
0
def setup():
    """ Basic OpenGL configuration.

    """
    # Set the color of "clear", i.e. the sky, in rgba.
    gl.glClearColor(0.5, 0.69, 1.0, 1)
    # Enable culling (not rendering) of back-facing facets -- facets that aren't
    # visible to you.
    gl.glEnable(gl.GL_CULL_FACE)

    #gl.glBlendFunc(gl.GL_SRC_ALPHA, gl.GL_DST_ALPHA)
    #gl.glBlendFunc(gl.GL_SRC_ALPHA, gl.GL_ONE_MINUS_SRC_ALPHA)
    gl.glBlendFunc(gl.GL_ZERO, gl.GL_SRC_COLOR)
    gl.glEnable(gl.GL_BLEND)
    gl.glAlphaFunc(gl.GL_GREATER, 0.5)
    gl.glEnable(gl.GL_ALPHA_TEST)
    # Set the texture minification/magnification function to GL_NEAREST (nearest
    # in Manhattan distance) to the specified texture coordinates. GL_NEAREST
    # "is generally faster than GL_LINEAR, but it can produce textured images
    # with sharper edges because the transition between texture elements is not
    # as smooth."
    gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MIN_FILTER,
                       gl.GL_NEAREST)
    gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MAG_FILTER,
                       gl.GL_NEAREST)
    gl.glTexEnvi(gl.GL_TEXTURE_ENV, gl.GL_TEXTURE_ENV_MODE, gl.GL_MODULATE)
    setup_fog()
Example #45
0
    def glSetup(self):
        gl.glClearColor(0.2, 0.2, 0.3, 1)
        gl.glColor3f(1, 1, 1)
        gl.glEnable(gl.GL_DEPTH_TEST)
        gl.glEnable(gl.GL_CULL_FACE)
        gl.glEnable(gl.GL_NORMALIZE)

        gl.glLightfv(gl.GL_LIGHT0, gl.GL_POSITION, vec(50, 50, 10, 0))
        gl.glLightfv(gl.GL_LIGHT0, gl.GL_SPECULAR, vec(5, 5, 10, 1))
        gl.glLightfv(gl.GL_LIGHT0, gl.GL_DIFFUSE, vec(1, 1, 1, 1))
        gl.glLightfv(gl.GL_LIGHT1, gl.GL_AMBIENT, vec(0, 0, 0, 1.0))
        gl.glLightfv(gl.GL_LIGHT1, gl.GL_SPECULAR, vec(0.6, 0.6, 0.6, 1.0))
        gl.glLightfv(gl.GL_LIGHT1, gl.GL_DIFFUSE, vec(0.8, 0.8, 0.8, 1))
        gl.glLightfv(gl.GL_LIGHT1, gl.GL_POSITION, vec(-10.0, -20.0, 20.0, 0))

        # Create a Material and Group for the Model
        diffuse = [0.5, 0.5, 0.3, 1.0]
        ambient = [0.5, 0.5, 0.3, 1.0]
        specular = [1.0, 1.0, 1.0, 1.0]
        emission = [0.0, 0.0, 0.0, 1.0]
        shininess = 50
        material = pyglet.model.Material("", diffuse, ambient, specular,
                                         emission, shininess)
        self.group = pyglet.model.MaterialGroup(material=material)

        # Create a Material and Group for the ground plane
        diffuse = [0.02, 0.02, 0.023, 1.0]
        ambient = [0.01, 0.01, 0.01, 1.0]
        specular = [0.05, 0.05, 0.07, 1.0]
        emission = [0.0, 0.0, 0.0, 1.0]
        shininess = 10
        material2 = pyglet.model.Material("ground", diffuse, ambient, specular,
                                          emission, shininess)
        self.group2 = pyglet.model.MaterialGroup(material=material2)
Example #46
0
def gl_enable_depth(z_near, z_far):
    gl.glDepthRange(z_near, z_far)
    gl.glClearDepth(1.0)
    gl.glEnable(gl.GL_DEPTH_TEST)
    gl.glEnable(gl.GL_DEPTH_TEST)
    gl.glDepthFunc(gl.GL_LEQUAL)
    gl.glEnable(gl.GL_CULL_FACE)
Example #47
0
    def _setup_3d(self):
        w, h = self.get_size()
        gl.glEnable(gl.GL_DEPTH_TEST)
        gl.glDepthFunc(gl.GL_LEQUAL)

        gl.glEnable(gl.GL_DEPTH_TEST)
        gl.glEnable(gl.GL_CULL_FACE)

        viewport = self.get_viewport_size()
        gl.glViewport(0, 0, max(1, viewport[0]), max(1, viewport[1]))

        gl.glMatrixMode(gl.GL_PROJECTION)
        gl.glLoadIdentity()
        gl.gluPerspective(*self.perspective)

        gl.glMatrixMode(gl.GL_MODELVIEW)
        gl.glLoadIdentity()
        y, x = self.rotation
        gl.glRotatef(x, 0, 1, 0)
        gl.glRotatef(-y, math.cos(math.radians(x)), 0,
                     math.sin(math.radians(x)))
        # NOTE: for GL render, its x-z plane is the ground plane,
        # so we unpack the position using `(x, z, y)` instead of `(x, y, z)`
        x, z, y = self.position
        if not self.debug_mode:
            y += self.perspective_over_drone[0]
        z += self.perspective_over_drone[1]
        gl.glTranslatef(-x, -y, -z)
Example #48
0
    def render_textured(self):
        gl.glEnable(GL_TEXTURE_2D)
        gl.glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT)
        gl.glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT)
        gl.glBindTexture(GL_TEXTURE_2D, self.texture.id)
        gl.glBegin(gl.GL_QUADS)
        gl.glColor4f(1, 1, 1, 1)
        gl.glTexCoord2f(-TEXTURE_SCALE, TEXTURE_SCALE)
        gl.glVertex3f(-PLAYFIELD, +PLAYFIELD, 0)
        gl.glTexCoord2f(TEXTURE_SCALE, TEXTURE_SCALE)
        gl.glVertex3f(+PLAYFIELD, +PLAYFIELD, 0)
        gl.glTexCoord2f(TEXTURE_SCALE, -TEXTURE_SCALE)
        gl.glVertex3f(+PLAYFIELD, -PLAYFIELD, 0)
        gl.glTexCoord2f(-TEXTURE_SCALE, -TEXTURE_SCALE)
        gl.glVertex3f(-PLAYFIELD, -PLAYFIELD, 0)

        gl.glEnd()
        gl.glDisable(GL_TEXTURE_2D)

        gl.glEnable(GL_TEXTURE_2D)
        gl.glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT)
        gl.glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT)
        gl.glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST)
        gl.glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST)
        gl.glBindTexture(GL_TEXTURE_2D, self.road_texture.id)

        gl.glBegin(gl.GL_QUADS)
        k = PLAYFIELD / 20.0
        tile_count = len(self.road_poly)
        tile_corners = ((-1, -1), (1, -1), (1, 1), (-1, 1))

        for i in range(len(self.road_poly)):
            poly, color = self.road_poly[i]
            gl.glColor4f(color[0], color[1], color[2], 1)
            for j in range(len(poly)):
                p = poly[j]
                gl.glTexCoord2f(*tile_corners[j % 4])
                gl.glVertex3f(p[0], p[1], 0)
        gl.glEnd()
        gl.glDisable(GL_TEXTURE_2D)
Example #49
0
    def __init__(self, window: pyglet.window.Window):
        self._window_ref = weakref.ref(window)
        self.limits = Limits(self)
        self._gl_version = (self.limits.MAJOR_VERSION,
                            self.limits.MINOR_VERSION)
        Context.activate(self)

        # Detect the default framebuffer
        self._screen = DefaultFrameBuffer(self)
        # Tracking active program
        self.active_program: Optional[Program] = None
        # Tracking active framebuffer. On context creation the window is the default render target
        self.active_framebuffer: Framebuffer = self._screen
        self.stats: ContextStats = ContextStats(warn_threshold=1000)

        # Hardcoded states
        # This should always be enabled
        gl.glEnable(gl.GL_TEXTURE_CUBE_MAP_SEAMLESS)
        # Set primitive restart index to -1 by default
        gl.glEnable(gl.GL_PRIMITIVE_RESTART)
        self._primitive_restart_index = -1
        self.primitive_restart_index = self._primitive_restart_index

        # We enable scissor testing by default.
        # This is always set to the same value as the viewport
        # to avoid background color affecting areas outside the viewport
        gl.glEnable(gl.GL_SCISSOR_TEST)

        # States
        self._blend_func = self.BLEND_DEFAULT
        self._point_size = 1.0
        self._flags: Set[int] = set()
Example #50
0
 def on_key_press(symbol, modifiers):
     if symbol == pyglet.window.key.UP:
         self.__cameradist *= 1.1
         if self.__cameradist > self.__maxcameradist:
             self.__cameradist = self.__maxcameradist
     elif symbol == pyglet.window.key.DOWN:
         self.__cameradist *= .90909090
         if self.__cameradist < self.__mincameradist:
             self.__cameradist = self.__mincameradist
     elif symbol == pyglet.window.key.RETURN:
         self.__cameradist = self.camerastartdist
         self.__rx = 0
         self.__ry = 0
     elif symbol == pyglet.window.key.P:
         self.__drawground = not self.__drawground
     elif symbol == pyglet.window.key.M:
         self.__legend = not self.__legend
     elif symbol == pyglet.window.key.L:
         if not (self.__light0 or self.__light1):
             self.__light0 = True
             gl.glEnable(gl.GL_LIGHT0)
             gl.glDisable(gl.GL_LIGHT1)
         elif self.__light0 and not self.__light1:
             self.__light1 = True
             gl.glEnable(gl.GL_LIGHT0)
             gl.glEnable(gl.GL_LIGHT1)
         elif self.__light0 and self.__light1:
             self.__light0 = self.__light1 = False
Example #51
0
    def _render_view(self):

        gl.glClearBufferfv(gl.GL_COLOR, 0, (gl.GLfloat * 4)(0.25, 0.25, 0.25,
                                                            1))

        if not self.view:
            return

        w, h, d = self.view.shape
        size = w, h
        window_size = self.get_size()

        ob = render_view(self)

        vm = make_view_matrix(window_size, size, self.zoom, self.offset)
        vm = (gl.GLfloat * 16)(*vm)
        gl.glViewport(0, 0, *window_size)

        self._update_border(self.view.shape)
        with self.border_vao, self.line_program:
            gl.glUniformMatrix4fv(0, 1, gl.GL_FALSE, vm)
            r, g, b, a = self.drawing.palette.colors[
                0]  # Color 0 is currently hardcoded background
            gl.glUniform3f(1, r / 256, g / 256, b / 256)
            gl.glDrawArrays(gl.GL_TRIANGLE_FAN, 0, 4)

        with self.vao, self.copy_program:
            # Draw the actual drawing
            with ob["color"]:
                gl.glEnable(gl.GL_BLEND)
                gl.glUniformMatrix4fv(0, 1, gl.GL_FALSE,
                                      (gl.GLfloat * 16)(*vm))
                gl.glDrawArrays(gl.GL_TRIANGLES, 0, 6)
            self._draw_mouse_cursor()

        with self.border_vao, self.line_program:
            gl.glUniform3f(1, 0., 0., 0.)
            gl.glLineWidth(1)
            gl.glDrawArrays(gl.GL_LINE_LOOP, 0, 4)
Example #52
0
 def on_draw(self):
     self.window.clear()
     gl.glMatrixMode(gl.GL_PROJECTION)
     gl.glPushMatrix()
     gl.glLoadIdentity()
     self.camera()
     gl.glEnable(self.grass.target)
     gl.glEnable(gl.GL_BLEND)
     gl.glBindTexture(self.grass.target, self.grass.id)
     W = 10000.
     graphics.draw(4, gl.GL_QUADS, ('v2f', (-W, -W, W, -W, W, W, -W, W)),
                   ('t2f',
                    (0., 0., W * 5., 0., W * 5., W * 5., 0., W * 5.)))
     gl.glDisable(self.grass.target)
     for lane in self.world.lanes:
         self.draw_lane_surface(lane)
     for lane in self.world.lanes:
         self.draw_lane_lines(lane)
     for obj in self.world.objects:
         self.draw_object(obj)
     for note in self.world.notices:  # Elis: added.
         self.draw_notice(note)
     #if self.heat is not None:
     self.draw_heatmap()
     for car in self.world.cars:
         # this draws the car at its current actual position (according to
         # the control loop) and doesn't take its animation position (in
         # self.anim_x[car]) into account.
         self.draw_car(car.traj.x0, car.color)
         # self.draw_car(self.anim_x[car], car.color)
     self.draw_car_plans()  # display plans generated by the main robot car
     gl.glPopMatrix()
     self.draw_labels()
     # Save current frame
     if self.save_frames and not topic_program.paused:
         pyglet.image.get_buffer_manager().get_color_buffer().save(
             '{0}{1}.png'.format(
                 self.frame_dir,
                 int(self.world.simulator.time / self.world.simulator.dt)))
Example #53
0
def rendering_window(draw, h, w):
    window = pyglet.window.Window(width=w, height=h,
                                  visible=False)

    gl.glEnable(gl.GL_BLEND)
    gl.glBlendFunc(gl.GL_SRC_ALPHA, gl.GL_ONE_MINUS_SRC_ALPHA)

    # gl.glEnable(gl.GL_LINE_SMOOTH)
    # gl.glEnable(gl.GL_POLYGON_SMOOTH)
    # gl.glHint(gl.GL_LINE_SMOOTH_HINT, gl.GL_NICEST)
    # gl.glHint(gl.GL_POLYGON_SMOOTH_HINT, gl.GL_NICEST)

    @window.event
    def on_draw():
        pyglet.clock.tick()

        window.clear()
        gl.glLoadIdentity()
        draw()

    pyglet.clock.set_fps_limit(30)
    pyglet.clock.schedule_interval(lambda dt: None, 1.0/30)
Example #54
0
 def render_skybox(self):
     import pyglet.gl as gl
     gl.glEnable(gl.GL_BLEND)
     gl.glBlendFunc(gl.GL_SRC_ALPHA, gl.GL_ONE_MINUS_SRC_ALPHA)
     tex = self.skyboxTexture
     #divide the skybox into 360 degrees horizontally and 180 vertically
     #calculate the amount of skybox to display based on FOV:
     hRat = self.camera.FOV / 2 / 360
     vRat = np.arctan(np.tan(hRat * 2 * np.pi) * self._height / self._width)
     ts =\
       (  # texture coordinates as a float,
         self.camera.theta / 2 / np.pi + hRat, -self.camera.phi / np.pi - vRat / 2,
         self.camera.theta / 2 / np.pi - hRat, -self.camera.phi / np.pi - vRat / 2,
         self.camera.theta / 2 / np.pi - hRat, -self.camera.phi / np.pi + vRat / 2,
         self.camera.theta / 2 / np.pi + hRat, -self.camera.phi / np.pi + vRat / 2,
       )
     vList = pyglet.graphics.vertex_list(4, ('v2f', self.corners),
                                         ('t2f', ts))
     gl.glEnable(gl.GL_TEXTURE_2D)
     gl.glBindTexture(gl.GL_TEXTURE_2D, tex.id)
     vList.draw(pyglet.gl.GL_QUADS)
     gl.glDisable(gl.GL_TEXTURE_2D)
Example #55
0
    def render_uds(self, dt):
        import pyglet.gl as gl
        self.parent.switch_to()
        from pyglet.gl import glEnable, glDisable, GL_TEXTURE_2D, glBindTexture
        self.camera.update_position(dt)
        self.parent.renderer.render_view(self._view)
        im = pyglet.image.ImageData(self._view.width, self._view.height,
                                    'BGRA', self._view.colourBuffer)
        tex = im.get_texture()
        #depth = pyglet.image.ImageData(self._view.width,self._view.height,'RGBA',self._view.depthBuffer)
        #TODO: add depth texture to quad
        #deptht = depth.get_texture()
        #gl.glBindRenderbuffer(gl.GL_RENDERBUFFER, deptht.id)
        #gl.glRenderbufferStorage(gl.GL_RENDERBUFFER,gl.GL_DEPTH_COMPONENT32F,self._view.width,self._view.height)
        #gl.glFramebufferRenderbuffer(gl.GL_FRAMEBUFFER,gl.GL_DEPTH_ATTACHMENT,gl.GL_RENDERBUFFER,deptht.id)
        #gl.glFramebufferTexture(gl.GL_FRAMEBUFFER, gl.GL_COLOR_ATTACHMENT0,tex.id)

        self.render_skybox()
        glEnable(GL_TEXTURE_2D)
        glBindTexture(GL_TEXTURE_2D, tex.id)
        self._vertex_list.draw(pyglet.gl.GL_QUADS)
        glDisable(GL_TEXTURE_2D)
Example #56
0
    def on_draw(self):
        # create projection matrix

        self.p_matrix.load_identity()
        self.p_matrix.perspective(90,
                                  float(self.width) / self.height, 0.1, 500)

        # create modelview matrix

        self.mv_matrix.load_identity()
        self.mv_matrix.translate(0, 0, -3)
        self.mv_matrix.rotate_2d(self.x, math.sin(self.x / 3 * 2) / 2)

        # modelviewprojection matrix

        mvp_matrix = self.p_matrix * self.mv_matrix
        self.shader.uniform_matrix(self.shader_matrix_location, mvp_matrix)

        # bind textures

        gl.glActiveTexture(
            gl.GL_TEXTURE0
        )  # set our active texture unit to the first texture unit
        gl.glBindTexture(gl.GL_TEXTURE_2D_ARRAY, self.texture_manager.
                         texture_array)  # bind our texture manager's texture
        gl.glUniform1i(
            self.shader_sampler_location, 0
        )  # tell our sampler our texture is bound to the first texture unit

        # draw stuff

        gl.glEnable(
            gl.GL_DEPTH_TEST
        )  # enable depth testing so faces are drawn in the right order
        gl.glClearColor(0.0, 0.0, 0.0, 1.0)
        self.clear()

        gl.glDrawElements(gl.GL_TRIANGLES, len(self.grass.indices),
                          gl.GL_UNSIGNED_INT, None)