Пример #1
0
Файл: render.py Проект: sv3/gift
class W(pyglet.window.Window):
    def __init__(self, sprite):
        super(W, self).__init__()
        self.mouse = [0,0]
        self.sprite = sprite
        self.shader = Shader(open('pass.vert').read(), open('RGB2Lab.glsl').read())

    def on_draw(self):
        x, y = self.mouse
        # glEnable(GL_LINE_SMOOTH)
        # glHint(GL_LINE_SMOOTH_HINT, GL_NICEST)

        # glMatrixMode(GL_PROJECTION)
        # glLoadIdentity()
        # glOrtho(-1., 1., 1., -1., 0., 1.)

        # glMatrixMode(GL_MODELVIEW)
        # glLoadIdentity()

        self.shader.bind()
        self.sprite.draw()

        #self.shader.uniformf('C', *self.C)

        self.shader.unbind()

    def on_mouse_motion(self, x, y, dx, dy):
        self.mouse = [x, y]

    def on_mouse_press(self, x, y, buttons, modifiers):
        # capture window contents to buffer
        buf = pyglet.image.get_buffer_manager().get_color_buffer()
        image = pyglet_to_pil(buf)
        image.show()
Пример #2
0
class JuliaWindow(pyglet.window.Window):
	def __init__(self):
		super(JuliaWindow, self).__init__(caption = 'julia', width = 512, height = 512)

		self.C = (-0.70176, -0.3842)

		shader_path = 'julia'
		self.shader = Shader(''.join(open('%s.v.glsl' % shader_path)), ''.join(open('%s.f.glsl' % shader_path)))

	def on_mouse_motion(self, x, y, dx, dy):
		self.C = (6. * ((float(x) / window.width) - .5), 6 * ((float(y) / window.height) - .5))

	def on_draw(self):
		glMatrixMode(GL_PROJECTION)
		glLoadIdentity()
		glOrtho(-1., 1., 1., -1., 0., 1.)

		glMatrixMode(GL_MODELVIEW)
		glLoadIdentity()

		self.shader.bind()
		self.shader.uniformf('C', *self.C)

		glBegin(GL_QUADS)
		glVertex2i(-1, -1)
		glTexCoord2i(-2, -2)
		glVertex2f(1, -1)
		glTexCoord2i(2, -2)
		glVertex2i(1,  1)
		glTexCoord2i(2, 2)
		glVertex2i(-1,  1)
		glTexCoord2i(-2, 2)
		glEnd()
		self.shader.unbind()
Пример #3
0
def getShader( frag, seed ):
    with open ("shaders/basicvert.glsl", "r") as vertfile:
      vert = vertfile.read()

    with open ("shaders/noise.glsl", "r") as noisefile:
      noise = noisefile.read()

    with open ("shaders/utils.glsl", "r") as utilsfile:
      utils = utilsfile.read()

    with open ("shaders/header.glsl", "r") as headerfile:
      header = headerfile.read()

    fullfrag = header + noise + utils + frag

    with open( "Output/" + str( seed ) + "/" + str( seed ) + ".glsl", "w") as text_file:
        text_file.write( frag )

    with open( "Output/" + str( seed ) + "/" + str( seed ) + "full.glsl", "w") as text_file:
        text_file.write( fullfrag )

    shader = Shader( vert, fullfrag )
    shader.bind()
    shader.uniformf( "iResolution", x, y )
    return shader
Пример #4
0
class TestShaderBind(BaseCase):
    def setUp(self):
        self.shader = Shader(vertexCode, fragmentCode)

    def test_bind(self):
        self.shader.bind()

    def test_unbind(self):
        self.shader.unbind()
Пример #5
0
class TestShaderUniformMatrix(BaseCase):
    def setUp(self):
        self.shader = Shader(vertexCode, fragmentCode)
        self.shader.bind()

    def test_matrix(self):
        # Why not the identity matrix? ;-)
        # Needs to be a flat list, of course
        matrix = [(1.0 if x == y else 0.0) for x in range(4) for y in range(4)]
        self.shader.uniform_matrixf('', matrix)

    def tearDown(self):
        self.shader.unbind()
Пример #6
0
class uiShaderGroup(uiGroup):
    
    def __init__(self, order, window, vertex_shader, fragment_shader, **kwargs):
        super(uiShaderGroup, self).__init__(order, window, **kwargs)

        self.shader = Shader(vertex_shader, fragment_shader)

    def set_state(self):
        self.shader.bind()
        #self.shader.uniform_matrixf('projection', camera.matrix * m)
    
    def unset_state(self):
        self.shader.unbind()
Пример #7
0
def draw_gl_checkerboards(points,
                          size=60,
                          color=(1., 0.5, 0.5, .5),
                          grid=[7.0, 7.0]):
    global simple_checkerboard_shader  # we cache the shader because we only create it the first time we call this fn.
    if not simple_checkerboard_shader:
        grid = np.array(grid)
        # step = size/grid
        # in this example the step would be 10

        # we just draw single points, a VBO is much slower than this. But this is a little bit hacked.
        #someday we should replace all legacy fn with vbo's and shaders...
        # shader defines
        VERT_SHADER = """
        #version 120
        varying vec4 f_color;
        void main () {
               gl_Position = gl_ModelViewProjectionMatrix*vec4(gl_Vertex.xy,1.,1.);
               gl_PointSize = gl_Vertex.z; //this needs to be used on some hardware we cheat and use the z coord
               f_color = gl_Color;
               }
        """

        FRAG_SHADER = """
        #version 120
        varying vec4 f_color;
        uniform vec2 grid;
        void main()
        {
            // get the lowest integer value for the grid
            float total = floor(gl_PointCoord.x*grid.x) + floor(gl_PointCoord.y*grid.y);
            // make the checkerboard by alternating colors
            bool isEven = mod(total,2.0)==0.0;
            vec4 col1 = vec4(0.0,0.0,0.0,1.0);
            vec4 col2 = vec4(1.0,1.0,1.0,1.0);
            gl_FragColor = (isEven)? col1:col2;
        }
        """
        #shader link and compile
        simple_checkerboard_shader = Shader(VERT_SHADER, FRAG_SHADER)

    simple_checkerboard_shader.bind()
    simple_checkerboard_shader.uniformf('grid', *grid)
    glColor4f(*color)
    glBegin(GL_POINTS)
    for pt in points:
        glVertex3f(pt[0], pt[1], size)
    glEnd()
    simple_checkerboard_shader.unbind()
Пример #8
0
 def bind(self, texture, lut=None):
     ''' Bind the program, i.e. use it. '''
     Shader.bind(self)
     if lut is not None:
         gl.glActiveTexture(gl.GL_TEXTURE1)
         gl.glBindTexture(lut.target, lut.id)
         self.uniformi('lut', 1)
     gl.glEnable(texture.target)
     gl.glActiveTexture(gl.GL_TEXTURE0)
     gl.glBindTexture(texture.target, texture.id)
     self.uniformi('texture', 0)
     self.uniformf('elevation', self._elevation)
     self.uniformf('pixel', 1.0 / texture.width, 1.0 / texture.height)
     self.uniformf('gridsize', *self._gridsize)
     self.uniformf('gridwidth', *self._gridwidth)
     self.uniformi('lighted', self._lighted)
Пример #9
0
 def bind(self, texture, lut=None):
     ''' Bind the program, i.e. use it. '''
     Shader.bind(self)
     if lut is not None:
         gl.glActiveTexture(gl.GL_TEXTURE1)
         gl.glBindTexture(lut.target, lut.id)
         self.uniformi('lut', 1)
     gl.glEnable(texture.target)
     gl.glActiveTexture(gl.GL_TEXTURE0)
     gl.glBindTexture(texture.target, texture.id)
     self.uniformi('texture', 0)
     self.uniformf('elevation', self._elevation)
     self.uniformf('pixel', 1.0/texture.width, 1.0/texture.height)
     self.uniformf('gridsize', *self._gridsize)
     self.uniformf('gridwidth', *self._gridwidth)
     self.uniformi('lighted', self._lighted)
Пример #10
0
   def on_resize(self, width, height):
       # set the Viewport
       glViewport(0, 0, width, height)

       # using Projection mode
       glMatrixMode(GL_PROJECTION)
       glLoadIdentity()

       aspectRatio = width / height
       gluPerspective(35, aspectRatio, 1, 1000)

       glMatrixMode(GL_MODELVIEW)
       glLoadIdentity()
       glTranslatef(0, 0, -400)
       glEnable(GL_LIGHTING)
       glEnable(GL_LIGHT0)
       glEnable(GL_LIGHT1)
       light0pos = [20.0,   20.0, 20.0, 1.0] # positional light !
       light1pos = [-20.0, -20.0, 20.0, 0.0] # infinitely away light !

       glLightfv(GL_LIGHT0, GL_POSITION, vec(*light0pos))
       glLightfv(GL_LIGHT0, GL_AMBIENT, vec(0.3, 0.3, 0.3, 1.0))
       glLightfv(GL_LIGHT0, GL_DIFFUSE, vec(0.9, 0.9, 0.9, 1.0))
       glLightfv(GL_LIGHT0, GL_SPECULAR, vec(1.0, 1.0, 1.0, 1.0))

       glLightfv(GL_LIGHT1, GL_POSITION, vec(*light1pos))
       glLightfv(GL_LIGHT1, GL_DIFFUSE, vec(.6, .6, .6, 1.0))
       glLightfv(GL_LIGHT1, GL_SPECULAR, vec(1.0, 1.0, 1.0, 1.0))
       shader = Shader(['''
       varying vec2 texCoords;
       void main()
       {    
           gl_Position = ftransform();
           texCoords = gl_MultiTexCoord0.st;
       }
       '''], ['''
       uniform vec4 color;
       uniform sampler2D tex;
       varying vec2 texCoords;


       void main (void)
       {
           gl_FragColor = texture2D(tex,texCoords);
       }
       '''])
       shader.bind()
Пример #11
0
def draw_gl_checkerboards(points,size=60,color=(1.,0.5,0.5,.5), grid=[7.0,7.0]):
    global simple_checkerboard_shader # we cache the shader because we only create it the first time we call this fn.
    if not simple_checkerboard_shader:
        grid = np.array(grid)
        # step = size/grid
        # in this example the step would be 10

        # we just draw single points, a VBO is much slower than this. But this is a little bit hacked.
        #someday we should replace all legacy fn with vbo's and shaders...
        # shader defines
        VERT_SHADER = """
        #version 120
        varying vec4 f_color;
        void main () {
               gl_Position = gl_ModelViewProjectionMatrix*vec4(gl_Vertex.xy,1.,1.);
               gl_PointSize = gl_Vertex.z; //this needs to be used on some hardware we cheat and use the z coord
               f_color = gl_Color;
               }
        """

        FRAG_SHADER = """
        #version 120
        varying vec4 f_color;
        uniform vec2 grid;
        void main()
        {
            // get the lowest integer value for the grid
            float total = floor(gl_PointCoord.x*grid.x) + floor(gl_PointCoord.y*grid.y);
            // make the checkerboard by alternating colors
            bool isEven = mod(total,2.0)==0.0;
            vec4 col1 = vec4(0.0,0.0,0.0,1.0);
            vec4 col2 = vec4(1.0,1.0,1.0,1.0);
            gl_FragColor = (isEven)? col1:col2;
        }
        """
        #shader link and compile
        simple_checkerboard_shader = Shader(VERT_SHADER,FRAG_SHADER)

    simple_checkerboard_shader.bind()
    simple_checkerboard_shader.uniformf('grid', *grid)
    glColor4f(*color)
    glBegin(GL_POINTS)
    for pt in points:
        glVertex3f(pt[0],pt[1],size)
    glEnd()
    simple_checkerboard_shader.unbind()
Пример #12
0
class PlasmaWindow(pyglet.window.Window):
    def __init__(self):
        super(PlasmaWindow, self).__init__(caption='plasma',
                                           width=512,
                                           height=512)

        self.C1 = (.0, .0)
        self.C2 = (.2, .2)
        self.C3 = (-.2, -.2)

        shader_path = 'plasma'
        self.shader = Shader(''.join(open('%s.v.glsl' % shader_path)),
                             ''.join(open('%s.f.glsl' % shader_path)))

    def on_mouse_motion(self, x, y, dx, dy):
        self.C1 = ((float(x) / window.width) - .5,
                   (float(y) / window.height) - .5)

    def on_draw(self):
        glMatrixMode(GL_PROJECTION)
        glLoadIdentity()
        glOrtho(-1., 1., 1., -1., 0., 1.)

        glMatrixMode(GL_MODELVIEW)
        glLoadIdentity()

        self.shader.bind()
        self.shader.uniformf('C1', *self.C1)
        self.shader.uniformf('C2', *self.C2)
        self.shader.uniformf('C3', *self.C3)

        glBegin(GL_QUADS)
        glVertex2i(-1, -1)
        glTexCoord2f(-.5, -.5)
        glVertex2i(1, -1)
        glTexCoord2f(.5, -.5)
        glVertex2i(1, 1)
        glTexCoord2f(.5, .5)
        glVertex2i(-1, 1)
        glTexCoord2f(-.5, .5)
        glEnd()
        self.shader.unbind()
Пример #13
0
def load_shader(name, attributes = (), **defaults):
    vert = open('./shaders/%s.vert' % name, 'rb').read()
    frag = open('./shaders/%s.frag' % name, 'rb').read()
    shader = Shader([vert], [frag])
    shader.initialize()
    for (index, name) in attributes:
        glBindAttribLocationARB(shader.handle, index, name)
    shader.link()
    shader.bind()
    for k, v in defaults.iteritems():
        try:
            v = tuple(v)
        except TypeError:
            v = (v,)
        if isinstance(v[0], float):
            func = shader.uniformf
        elif isinstance(v[0], int):
            func = shader.uniformi
        func(k, *v)
    shader.unbind()
    return shader
Пример #14
0
def load_shader(name, attributes=(), **defaults):
    vert = open('./shaders/%s.vert' % name, 'rb').read()
    frag = open('./shaders/%s.frag' % name, 'rb').read()
    shader = Shader([vert], [frag])
    shader.initialize()
    for (index, name) in attributes:
        glBindAttribLocationARB(shader.handle, index, name)
    shader.link()
    shader.bind()
    for k, v in defaults.iteritems():
        try:
            v = tuple(v)
        except TypeError:
            v = (v, )
        if isinstance(v[0], float):
            func = shader.uniformf
        elif isinstance(v[0], int):
            func = shader.uniformi
        func(k, *v)
    shader.unbind()
    return shader
Пример #15
0
class TestShaderUniformInt(BaseCase):
    def setUp(self):
        self.shader = Shader(vertexCode, fragmentCode)
        self.shader.bind()

    def test_int_1(self):
        self.shader.uniformi('', *[0])

    def test_int_2(self):
        self.shader.uniformi('', *[0, 1])

    def test_int_3(self):
        self.shader.uniformi('', *[0, 1, 2])

    def test_int_4(self):
        self.shader.uniformi('', *[0, 1, 2, 3])

    def test_int_5(self):
        self.shader.uniformi('', *[0, 1, 2, 3, 4])

    def tearDown(self):
        self.shader.unbind()
Пример #16
0
class TestShaderUniformFloat(BaseCase):
    def setUp(self):
        self.shader = Shader(vertexCode, fragmentCode)
        self.shader.bind()

    def test_float_1(self):
        self.shader.uniformf('', *[0.0])

    def test_float_2(self):
        self.shader.uniformf('', *[0.0, 0.1])

    def test_float_3(self):
        self.shader.uniformf('', *[0.0, 0.1, 0.2])

    def test_float_4(self):
        self.shader.uniformf('', *[0.0, 0.1, 0.2, 0.3])

    def test_float_5(self):
        self.shader.uniformf('', *[0.0, 0.1, 0.2, 0.3, 0.4])

    def tearDown(self):
        self.shader.unbind()
Пример #17
0
class JuliaWindow(pyglet.window.Window):
    def __init__(self):
        super(JuliaWindow, self).__init__(caption='julia',
                                          width=512,
                                          height=512)

        self.C = (-0.70176, -0.3842)

        shader_path = 'julia'
        self.shader = Shader(''.join(open('%s.v.glsl' % shader_path)),
                             ''.join(open('%s.f.glsl' % shader_path)))

    def on_mouse_motion(self, x, y, dx, dy):
        self.C = (6. * ((float(x) / window.width) - .5),
                  6 * ((float(y) / window.height) - .5))

    def on_draw(self):
        glMatrixMode(GL_PROJECTION)
        glLoadIdentity()
        glOrtho(-1., 1., 1., -1., 0., 1.)

        glMatrixMode(GL_MODELVIEW)
        glLoadIdentity()

        self.shader.bind()
        self.shader.uniformf('C', *self.C)

        glBegin(GL_QUADS)
        glVertex2i(-1, -1)
        glTexCoord2i(-2, -2)
        glVertex2f(1, -1)
        glTexCoord2i(2, -2)
        glVertex2i(1, 1)
        glTexCoord2i(2, 2)
        glVertex2i(-1, 1)
        glTexCoord2i(-2, 2)
        glEnd()
        self.shader.unbind()
Пример #18
0
def draw_gl_points(points, size=20, color=(1., 0.5, 0.5, .5)):
    global simple_pt_shader  # we cache the shader because we only create it the first time we call this fn.
    if not simple_pt_shader:

        # we just draw single points, a VBO is much slower than this. But this is a little bit hacked.
        #someday we should replace all legacy fn with vbo's and shaders...
        # shader defines
        VERT_SHADER = """
        #version 120
        varying vec4 f_color;
        void main () {
               gl_Position = gl_ModelViewProjectionMatrix*vec4(gl_Vertex.xy,1.,1.);
               gl_PointSize = gl_Vertex.z; //this needs to be used on some hardware we cheat and use the z coord
               f_color = gl_Color;
               }
        """

        FRAG_SHADER = """
        #version 120
        varying vec4 f_color;
        void main()
        {
            float dist = distance(gl_PointCoord, vec2(0.5, 0.5));
            gl_FragColor = mix(f_color, vec4(f_color.rgb,0.0), smoothstep(0.35, 0.5, dist));
        }
        """
        #shader link and compile
        simple_pt_shader = Shader(VERT_SHADER, FRAG_SHADER)

    simple_pt_shader.bind()
    glColor4f(*color)
    glBegin(GL_POINTS)
    for pt in points:
        glVertex3f(pt[0], pt[1], size)
    glEnd()
    simple_pt_shader.unbind()
Пример #19
0
def draw_gl_points(points,size=20,color=(1.,0.5,0.5,.5)):
    global simple_pt_shader # we cache the shader because we only create it the first time we call this fn.
    if not simple_pt_shader:

        # we just draw single points, a VBO is much slower than this. But this is a little bit hacked.
        #someday we should replace all legacy fn with vbo's and shaders...
        # shader defines
        VERT_SHADER = """
        #version 120
        varying vec4 f_color;
        void main () {
               gl_Position = gl_ModelViewProjectionMatrix*vec4(gl_Vertex.xy,1.,1.);
               gl_PointSize = gl_Vertex.z; //this needs to be used on some hardware we cheat and use the z coord
               f_color = gl_Color;
               }
        """

        FRAG_SHADER = """
        #version 120
        varying vec4 f_color;
        void main()
        {
            float dist = distance(gl_PointCoord, vec2(0.5, 0.5));
            gl_FragColor = mix(f_color, vec4(f_color.rgb,0.0), smoothstep(0.35, 0.5, dist));
        }
        """
        #shader link and compile
        simple_pt_shader = Shader(VERT_SHADER,FRAG_SHADER)

    simple_pt_shader.bind()
    glColor4f(*color)
    glBegin(GL_POINTS)
    for pt in points:
        glVertex3f(pt[0],pt[1],size)
    glEnd()
    simple_pt_shader.unbind()
Пример #20
0
    return f.read()


#check for command lines
if len(sys.argv) > 2:
    vertSrc = load(sys.argv[1])
    fragSrc = load(sys.argv[2])
else:
    vertSrc = load("vertexshader")
    fragSrc = load("fragshader")

# create our shader
shader = Shader([vertSrc], [fragSrc])

# bind our shader
shader.bind()
# set the correct texture unit
shader.uniformi('tex0', 0)
# unbind the shader
shader.unbind()

# create the texture
texture = pyglet.image.Texture.create(window.width, window.height, GL_RGBA)

# create a fullscreen quad
batch = pyglet.graphics.Batch()
batch.add(4, GL_QUADS, None, ('v2i', (0, 0, 1, 0, 1, 1, 0, 1)),
          ('t2f', (0, 0, 1.0, 0, 1.0, 1.0, 0, 1.0)))


# utility function to copy the framebuffer into a texture
Пример #21
0
class ShaderWindow(pyglet.window.Window):
  def __init__(self, shader_path):
    self.w = 512
    self.h = 512

    # Scaling values
    self.x = -5.4
    self.y = -5.4
    self.z = 0.0
    self.zoom = 0.02
    self.octives = 9
    self.freq = 0.73

    self.windowSize = (float(self.w), float(self.h))
    super(ShaderWindow, self).__init__(caption = 'Shader', width=self.w, height=self.h)

    self.shader = Shader(
      ' '.join(open('%s.v.glsl' % shader_path)),
      ' '.join(open('%s.f.glsl' % shader_path))
    )

    self.p = []
    permutation = self.getPermutation()
    for i in range(512):
        self.p.append(permutation[i % len(permutation)])

  def on_mouse_drag(self, x, y, dx, dy, buttons, modifiers):
    self.x -= dx * self.zoom;
    self.y -= dy * self.zoom;
    
  def on_mouse_release(self, x, y, button, modifiers):
    print "x: {}, y: {}, z: {}, zoom: {}, octs: {}, freq: {}".format(self.x, self.y, self.z, self.zoom, self.octives, self.freq)

  def on_mouse_scroll(self, x, y, scroll_x, scroll_y):
    self.zoom -= scroll_y * 0.0025;
    print "x: {}, y: {}, z: {}, zoom: {}, octs: {}, freq: {}".format(self.x, self.y, self.z, self.zoom, self.octives, self.freq)

  def on_key_release(self, symbol, modifiers):
    if symbol == pyglet.window.key.F2:
      self.saveFromShader()
    elif symbol == pyglet.window.key.Q:
      self.x += 0.1;
    elif symbol == pyglet.window.key.A:
      self.x -= 0.1;
    elif symbol == pyglet.window.key.W:
      self.y += 0.1;
    elif symbol == pyglet.window.key.S:
      self.y -= 0.1;
    elif symbol == pyglet.window.key.E:
      self.z += 0.01;
    elif symbol == pyglet.window.key.D:
      self.z -= 0.01;
    elif symbol == pyglet.window.key.R:
      self.zoom += 0.0025;
    elif symbol == pyglet.window.key.F:
      self.zoom -= 0.0025;
    elif symbol == pyglet.window.key.T:
      self.octives += 1;
    elif symbol == pyglet.window.key.G:
      self.octives -= 1;
    elif symbol == pyglet.window.key.Y:
      self.freq += 0.01;
    elif symbol == pyglet.window.key.H:
      self.freq -= 0.01;
    print "x: {}, y: {}, z: {}, zoom: {}, octs: {}, freq: {}".format(self.x, self.y, self.z, self.zoom, self.octives, self.freq)
    
  def saveFromShader(self):
    a = (GLubyte * (4 * self.w * self.h))(0)
    glReadPixels(0, 0, self.w, self.h, GL_RGBA, GL_UNSIGNED_BYTE, a)
    image = pyglet.image.ImageData(self.w, self.h, 'RGBA', a)
    scriptPath = os.path.dirname(os.path.realpath(__file__))
    filePath = scriptPath + "/TESTSAVE_" + time.strftime("%Y%m%d_%H%M%S") + ".png"
    print "save to {}".format(filePath)
    image.save(filePath)

  def getPermutation(self):
    return [
      151,160,137, 91, 90, 15,131, 13,201, 95, 96, 53,194,233,  7,225,
      140, 36,103, 30, 69,142,  8, 99, 37,240, 21, 10, 23,190,  6,148,
      247,120,234, 75,  0, 26,197, 62, 94,252,219,203,117, 35, 11, 32,
       57,177, 33, 88,237,149, 56, 87,174, 20,125,136,171,168, 68,175,
       74,165, 71,134,139, 48, 27,166, 77,146,158,231, 83,111,229,122,
       60,211,133,230,220,105, 92, 41, 55, 46,245, 40,244,102,143, 54,
       65, 25, 63,161,  1,216, 80, 73,209, 76,132,187,208, 89, 18,169,
      200,196,135,130,116,188,159, 86,164,100,109,198,173,186,  3, 64,
       52,217,226,250,124,123,  5,202, 38,147,118,126,255, 82, 85,212,
      207,206, 59,227, 47, 16, 58, 17,182,189, 28, 42,223,183,170,213,
      119,248,152,  2, 44,154,163, 70,221,153,101,155,167, 43,172,  9,
      129, 22, 39,253, 19, 98,108,110, 79,113,224,232,178,185,112,104,
      218,246, 97,228,251, 34,242,193,238,210,144, 12,191,179,162,241,
       81, 51,145,235,249, 14,239,107, 49,192,214, 31,181,199,106,157,
      184, 84,204,176,115,121, 50, 45,127,  4,150,254,138,236,205, 93,
      222,114, 67, 29, 24, 72,243,141,128,195, 78, 66,215, 61,156,180,
    ]

  def on_draw(self):
    glMatrixMode(GL_PROJECTION)
    glLoadIdentity()
    glOrtho(-1., 1., 1., -1., 0., 1.)

    glMatrixMode(GL_MODELVIEW)
    glLoadIdentity()

    self.shader.bind()
    self.shader.uniformi('p', *self.p)
    self.shader.uniformf('x', *[self.x])
    self.shader.uniformf('y', *[self.y])
    self.shader.uniformf('z', *[self.z])
    self.shader.uniformf('zoom', *[self.zoom])
    self.shader.uniformi('octives', *[self.octives])
    self.shader.uniformf('freq', *[self.freq])

    glBegin(GL_QUADS)
    glVertex2i(-1, -1)
    glTexCoord2i(-2, -2)
    glVertex2f(1, -1)
    glTexCoord2i(2, -2)
    glVertex2i(1, 1)
    glTexCoord2i(2, 2)
    glVertex2i(-1, 1)
    glTexCoord2i(-2, 2)
    glEnd()

    self.shader.unbind()
Пример #22
0
class Graphics(QtOpenGL.QGLWidget):
    def __init__(self, parent, width, height, state):
        super().__init__(parent)
        self.game = state
        self.parent = parent
        self.screen_width = width
        self.screen_height = height
        self.cell_width = 0
        self.cell_height = 0
        self.shader = None

        self.field_quad = None
        self.towers = []
        self.creeps = {}
        self.attacks = {}
        self.healths = {}
        self.auras = {}
        self.magic = {}
        self.attack_timers = {}
        self.creep_timers = {}
        self.attack_deletions = []
        self.magic_deletions = []
        self.debuff_deletions = []

        self.chosen_tower = None

        self.spawn_timer = None
        self.wave_timer = None
        self.draw_timer = None
        self.count = 0
        self.multiplier = consts.DEFAULT_MULTIPLIER
        self.multiplier_index = consts.DEFAULT_MULTIPLIER_INDEX
        self.paused = False
        self.over = False

    def initializeGL(self):
        self.cell_width = (2 * self.screen_width / len(self.game.field[0]) /
                           self.screen_width)
        self.cell_height = (2 * self.screen_height / len(self.game.field) /
                            self.screen_height)

        self.shader = Shader('shader.vs', 'shader.fs')
        self.shader.save_attr_locations(['aVertexPosition', 'aVertexTexCoord'])
        self.shader.save_uniform_locations(['uTexture'])
        self.shader.bind()

        GL.glEnable(GL.GL_DEPTH_TEST)
        GL.glClearColor(255, 255, 255, 1)

        GL.glViewport(0, 0, self.screen_width, self.screen_height)
        self.setGeometry(0, 0, self.screen_width, self.screen_height)

        self.set_field()

        self.start_spawn()

        self.draw_timer = Timer(self.update, consts.REDRAW_TIME)
        self.draw_timer.start_timer()

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

    def paintGL(self):
        if self.over:
            return
        if self.game.end:
            self.game_over()

        GL.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT)

        self.field_quad.draw(self.shader.handles)

        for tower in self.towers:
            tower.draw(self.shader.handles)

        for creep in self.creeps:
            self.creeps[creep].draw(self.shader.handles)
            self.healths[creep].draw(self.shader.handles)

        for spell in self.magic:
            self.magic[spell].draw(self.shader.handles)

        for attack in self.attacks:
            self.attacks[attack].draw(self.shader.handles)

        for aura in self.auras:
            self.auras[aura].draw(self.shader.handles)

    def mousePressEvent(self, event):
        if not self.chosen_tower or self.paused:
            return
        if event.buttons() == QtCore.Qt.RightButton:
            self.parent.reset_buttons()
            self.chosen_tower = None
        if event.buttons() == QtCore.Qt.LeftButton:
            self.parent.reset_buttons()
            cell_width = math.floor(self.screen_width /
                                    len(self.game.field[0]))
            cell_height = math.floor(self.screen_height / len(self.game.field))
            cursor_pos = self.mapFromGlobal(QtGui.QCursor().pos())
            row = math.floor(cursor_pos.y() / cell_height)
            col = math.floor(cursor_pos.x() / cell_width)
            if not game_field.in_field(self.game.field, Point(row, col)):
                return
            if (not isinstance(self.game.field[row][col], game.Map) or
                (self.game.field[row][col].name != game_field.CellType.Grass)):
                return
            self.place_tower(row, col, self.chosen_tower)
            self.chosen_tower = None

    def choose_tower(self, tower_type):
        self.chosen_tower = tower_type

    def place_tower(self, row, col, tower_type):
        fail = self.game.place_unit(row, col, tower_type)
        if fail:
            return
        self.towers.append(self.get_unit(row, col, tower_type))
        self.attack(self.game.field[row][col])

    def set_field(self):
        field = Image.new('RGBA', (self.screen_width, self.screen_width))
        images = {
            'Grass': Image.open('field/Grass.png'),
            'Path': Image.open('field/Path.png'),
            'Portal': Image.open('field/Portal.png'),
            'Castle': Image.open('field/Castle.png')
        }
        width = math.floor(self.screen_width / len(self.game.field[0]))
        height = math.floor(self.screen_width / len(self.game.field))
        for k in images:
            images[k] = images[k].resize((width, height))
        for row, line in enumerate(self.game.field):
            for col, figure in enumerate(line):
                if not isinstance(figure, game.Map):
                    continue
                image = images[self.game.field[row][col].name.name]
                field.paste(image, (col * width, row * height))
        priority = 0.9
        self.field_quad = Mesh.get_quad(-1, 1, 1, -1, priority)
        self.field_quad.set_texture(field)

    def get_unit(self, row, col, unit_type):
        bias = self.cell_height * 0.025
        priority = 0.2
        quad = Mesh.get_quad(-1 + col * self.cell_width + bias,
                             1 - row * self.cell_height - bias,
                             -1 + (col + 1) * self.cell_width - bias,
                             1 - (row + 1) * self.cell_height + bias, priority)
        quad.set_texture(
            Image.open('{0}/{1}.png'.format(consts.TEXTURES_FOLDER,
                                            unit_type.__name__)))
        return quad

    def start_spawn(self):
        spawn_wave_time = consts.SPAWN_WAVE_TIME * self.multiplier
        self.spawn_timer = Timer(self.spawn_wave, spawn_wave_time)
        self.spawn_timer.start_timer()

    def spawn_wave(self):
        creep_types = [
            creeps.Peon(0, 0, self.game),
            creeps.Grunt(0, 0, self.game),
            creeps.Raider(0, 0, self.game),
            creeps.Blademaster(0, 0, self.game),
            creeps.Shaman(0, 0, self.game)
        ]
        self.count = 0
        self.spawn(random.choice(creep_types), consts.CREEPS_IN_WAVE,
                   creep_types, consts.PORTAL)

    def spawn(self, creep, amount, types, point):
        if self.count == amount or self.game.end:
            self.wave_timer.stop()
            return
        if creep.name != 'Footman':
            self.count += 1

        unit = self.game.place_unit(point.row, point.col, type(creep))
        self.creeps[unit] = self.get_unit(point.row, point.col, type(creep))
        self.move_creep(unit)

        next_type = random.choice(types)
        spawn_creep_time = consts.SPAWN_CREEP_TIME / self.multiplier
        self.wave_timer = Timer(
            lambda: self.spawn(next_type, amount, types, point),
            round(spawn_creep_time / creep.speed))
        self.wave_timer.start_timer()

    def move_creep(self, creep):
        self.creeps.pop(creep, None)
        self.creep_timers.pop(creep, None)
        stop = creep.move(self.game)
        bias = self.cell_height * 0.025
        row = creep.row
        col = creep.col
        priority = 0.2
        self.creeps[creep] = Mesh.get_quad(
            -1 + col * self.cell_width + bias,
            1 - row * self.cell_height - bias,
            -1 + (col + 1) * self.cell_width - bias,
            1 - (row + 1) * self.cell_height + bias, priority)
        if creep.name == 'Shaman':
            self.set_aura(creep)
        health = consts.MAX_HEALTH[type(creep).__name__]
        rate = creep.health / health
        self.healths[creep] = Mesh.get_line(Point(row + 0.6, col - 0.4),
                                            Point(row + 0.6,
                                                  col - 0.4 + rate), 0.15,
                                            self.cell_width, self.cell_height)
        self.creeps[creep].set_texture(
            Image.open('{0}/{1}.png'.format(consts.TEXTURES_FOLDER,
                                            type(creep).__name__)))
        if stop is True:
            self.creeps.pop(creep, None)
            self.auras.pop(creep, None)
            return
        move_creep_time = consts.MOVE_CREEP_TIME / self.multiplier
        timer = Timer(lambda: self.move_creep(creep),
                      round(move_creep_time / creep.speed))
        timer.start_timer()
        self.creep_timers[creep] = timer

    def set_aura(self, creep):
        row = creep.row + 0.5
        col = creep.col + 0.5
        priority = 0.7
        aura = Mesh.get_quad(-1 + (col + 1) * self.cell_width,
                             1 - (row - 1) * self.cell_height,
                             -1 + (col - 1) * self.cell_width,
                             1 - (row + 1) * self.cell_height, priority)
        aura.set_texture(Image.open(consts.AURA_PATH))
        self.auras[creep] = aura

    def attack(self, tower):
        enemy = tower.attack(self.game)
        if enemy and tower.name != 'BarracksTower':
            self.add_attack(tower, enemy)
        if tower.name == 'BarracksTower':
            for unit in enemy:
                self.spawn_ally(tower, unit)
        attack_delete_time = consts.ATTACK_DELETE_TIME / self.multiplier
        delete_timer = Timer(lambda: self.delete_attack(tower),
                             attack_delete_time)
        delete_timer.launch_once()
        self.attack_deletions.append(delete_timer)
        tower_attack_time = consts.TOWER_ATTACK_TIME / self.multiplier
        timer = Timer(lambda: self.attack(tower),
                      round(tower_attack_time / tower.speed))
        timer.start_timer()
        self.attack_timers[Point(tower.row, tower.col)] = timer

    def spawn_ally(self, tower, ally):
        unit = self.game.place_ally(tower, ally, creeps.Footman)
        self.creeps[unit] = self.get_unit(ally.row, ally.col, creeps.Footman)
        self.move_creep(unit)

    def add_attack(self, tower, enemy):
        if tower.name != 'CanonTower':
            point1 = tower if tower.col < enemy.col else enemy
            point2 = tower if tower.col > enemy.col else enemy
            attack = Mesh.get_line(point1, point2, 0.1, self.cell_width,
                                   self.cell_height)
            self.attacks[Point(tower.row, tower.col)] = attack
            return
        row = enemy.row + 0.5
        col = enemy.col + 0.5
        priority = 0.19
        self.attacks[Point(tower.row, tower.col)] = Mesh.get_quad(
            -1 + (col + tower.range) * self.cell_width,
            1 - (row - tower.range) * self.cell_height,
            -1 + (col - tower.range) * self.cell_width,
            1 - (row + tower.range) * self.cell_height, priority)
        self.attacks[Point(tower.row, tower.col)].set_texture(
            Image.open('{0}/{1}.png'.format(consts.TEXTURES_FOLDER, 'Wave')))

    def delete_attack(self, tower):
        self.attacks.pop(Point(tower.row, tower.col), None)

    def reset_speed(self):
        self.multiplier = consts.DEFAULT_MULTIPLIER
        self.multiplier_index = consts.DEFAULT_MULTIPLIER_INDEX

    def decrease_speed(self):
        if self.multiplier == consts.MIN_MULTIPLIER:
            return
        self.multiplier_index -= 1
        self.multiplier = consts.MULTIPLIERS[self.multiplier_index]

    def increase_speed(self):
        if self.multiplier == consts.MAX_MULTIPLIER:
            return
        self.multiplier_index += 1
        self.multiplier = consts.MULTIPLIERS[self.multiplier_index]

    def pause(self):
        if self.spawn_timer:
            self.spawn_timer.pause()
        if self.wave_timer:
            self.wave_timer.pause()
        for key in self.attack_timers:
            self.attack_timers[key].pause()
        for key in self.creep_timers:
            self.creep_timers[key].pause()
        for timer in self.attack_deletions:
            timer.pause()
        for timer in self.magic_deletions:
            timer.pause()
        for timer in self.debuff_deletions:
            timer.pause()

    def resume(self):
        if self.spawn_timer:
            self.spawn_timer.resume()
        if self.wave_timer:
            self.wave_timer.resume()
        for key in self.attack_timers:
            self.attack_timers[key].resume()
        for key in self.creep_timers:
            self.creep_timers[key].resume()
        for timer in self.attack_deletions:
            timer.resume()
        for timer in self.magic_deletions:
            timer.resume()
        for timer in self.debuff_deletions:
            timer.resume()

    def cast_fire_magic(self):
        point = self.game.cast_fire()
        if not point:
            return
        row = point.row + 0.5
        col = point.col + 0.5
        priority = 0.04
        fire = Mesh.get_quad(-1 + (col + consts.FIRE_RADIUS) * self.cell_width,
                             1 - (row - consts.FIRE_RADIUS) * self.cell_height,
                             -1 + (col - consts.FIRE_RADIUS) * self.cell_width,
                             1 - (row + consts.FIRE_RADIUS) * self.cell_height,
                             priority)
        fire.set_texture(Image.open(consts.FIRE_PATH))
        self.magic[point] = fire
        magic_delete = Timer(lambda: self.magic.pop(point, None),
                             consts.FIRE_DURATION)
        magic_delete.launch_once()
        self.magic_deletions.append(magic_delete)

    def cast_ice_magic(self):
        point = self.game.cast_ice()
        if not point:
            return
        row = point.row + 0.5
        col = point.col + 0.5
        priority = 0.8
        wind = Mesh.get_quad(-1 + (col + consts.ICE_RADIUS) * self.cell_width,
                             1 - (row - consts.ICE_RADIUS) * self.cell_height,
                             -1 + (col - consts.ICE_RADIUS) * self.cell_width,
                             1 - (row + consts.ICE_RADIUS) * self.cell_height,
                             priority)
        wind.set_texture(Image.open(consts.WIND_PATH))
        self.magic[point] = wind
        magic_delete = Timer(lambda: self.magic.pop(point, None),
                             consts.ICE_DURATION)
        magic_delete.launch_once()
        self.magic_deletions.append(magic_delete)
        debuff_delete = Timer(lambda: self.game.disable_ice_debuff(),
                              consts.ICE_DURATION)
        debuff_delete.launch_once()
        self.magic_deletions.append(debuff_delete)

    def game_over(self):
        self.over = True
        self.parent.game_over()
Пример #23
0
        current += (1.0-live) * vec3(equal(neighbours, vec3(3.0)));

        // kill if we do not have either 3 or 2 neighbours
        current *= vec3(equal(neighbours, vec3(2.0))) + vec3(equal(neighbours, vec3(3.0)));

        // fade the current pixel as it ages
        current -= vec3(greaterThan(current, vec3(0.4)))*0.05;

        // write out the pixel
        gl_FragColor = vec4(current, 1.0);
    }
}
'''])
 
# bind our shader
shader.bind()
# set the correct texture unit
shader.uniformi('tex0', 0)
# unbind the shader
shader.unbind()
 
# create the texture
# texture = pyglet.image.Texture.create(window.width, window.height, GL_RGBA) # Blank texture
texture = pyglet.image.load('game_of_life_init.png').get_texture()

# create a fullscreen quad
batch = pyglet.graphics.Batch()
batch.add(4, GL_QUADS, None, ('v2i', (0,0, 1,0, 1,1, 0,1)), ('t2f', (0,0, 1.0,0, 1.0,1.0, 0,1.0)))

# utility function to copy the framebuffer into a texture
def copyFramebuffer(tex, *size):
Пример #24
0
class ShaderWindow(pyglet.window.Window):
  def __init__(self, shader_path):
    self.w = 512
    self.h = 512
    self.permutation = self.getPermutation()

    self.windowSize = (float(self.w), float(self.h))
    self.XY = (float(self.w / 2), float(self.h / 2))
    super(ShaderWindow, self).__init__(caption = 'Shader', width=self.w, height=self.h)

    self.shader = Shader(
      ' '.join(open('%s.v.glsl' % shader_path)),
      ' '.join(open('%s.f.glsl' % shader_path))
    )

  def on_mouse_motion(self, x, y, dx, dy):
    self.XY = (float(x), float(y))
    
  def on_mouse_drag(self, x, y, dx, dy, buttons, modifiers):
    self.XY = (float(x), float(y))

  def on_mouse_press(self, x, y, button, modifiers):
    # Assign a byte buffer (int didn't appear to work - for rgb anyway)
    a = (GLubyte * (4 * self.w * self.h))(0)

    # Call the (rather slow) pixel read
    glReadPixels(0, 0, self.w, self.h, GL_RGBA, GL_UNSIGNED_BYTE, a)

    # For debugging purposes, create an image using the data
    image = pyglet.image.ImageData(self.w, self.h, 'RGBA', a)
    
    # Save the image to disk
    image.save("screenshot.png")

  def getPermutation(self):
    return [
      151,160,137, 91, 90, 15,131, 13,201, 95, 96, 53,194,233,  7,225,
      140, 36,103, 30, 69,142,  8, 99, 37,240, 21, 10, 23,190,  6,148,
      247,120,234, 75,  0, 26,197, 62, 94,252,219,203,117, 35, 11, 32,
       57,177, 33, 88,237,149, 56, 87,174, 20,125,136,171,168, 68,175,
       74,165, 71,134,139, 48, 27,166, 77,146,158,231, 83,111,229,122,
       60,211,133,230,220,105, 92, 41, 55, 46,245, 40,244,102,143, 54,
       65, 25, 63,161,  1,216, 80, 73,209, 76,132,187,208, 89, 18,169,
      200,196,135,130,116,188,159, 86,164,100,109,198,173,186,  3, 64,
       52,217,226,250,124,123,  5,202, 38,147,118,126,255, 82, 85,212,
      207,206, 59,227, 47, 16, 58, 17,182,189, 28, 42,223,183,170,213,
      119,248,152,  2, 44,154,163, 70,221,153,101,155,167, 43,172,  9,
      129, 22, 39,253, 19, 98,108,110, 79,113,224,232,178,185,112,104,
      218,246, 97,228,251, 34,242,193,238,210,144, 12,191,179,162,241,
       81, 51,145,235,249, 14,239,107, 49,192,214, 31,181,199,106,157,
      184, 84,204,176,115,121, 50, 45,127,  4,150,254,138,236,205, 93,
      222,114, 67, 29, 24, 72,243,141,128,195, 78, 66,215, 61,156,180,
    ]

  def on_draw(self):
    glMatrixMode(GL_PROJECTION)
    glLoadIdentity()
    glOrtho(-1., 1., 1., -1., 0., 1.)

    glMatrixMode(GL_MODELVIEW)
    glLoadIdentity()

    self.shader.bind()
    self.shader.uniformf('WindowSize', *self.windowSize)
    self.shader.uniformf('XY', *self.XY)
    data_loc = glGetUniformLocation(self.shader.handle, 'data')
    glUniform1iv(data_loc, 256, (gl.c_long * len(self.permutation))(*self.permutation))

    glBegin(GL_QUADS)
    glVertex2i(-1, -1)
    glTexCoord2i(-2, -2)
    glVertex2f(1, -1)
    glTexCoord2i(2, -2)
    glVertex2i(1, 1)
    glTexCoord2i(2, 2)
    glVertex2i(-1, 1)
    glTexCoord2i(-2, 2)
    glEnd()

    self.shader.unbind()
Пример #25
0
class MainView:
    def __init__(self):
        fileConfig('log.conf')
        self.logger = logging.getLogger(type(self).__name__)

        self.resolution = np.array([800, 450])
        self.target_fps = 60
        self.frame_render_time = 1 / self.target_fps

        self.init_window()
        self.get_gl_info()
        self.init_shader()
        self.init_camera()
        self.main_loop()

    def get_gl_info(self):
        self.logger.info('Vendor    : {}'.format(
            glGetString(GL_VENDOR).decode()))
        self.logger.info('Renderer  : {}'.format(
            glGetString(GL_RENDERER).decode()))
        self.logger.info('Version   : {}'.format(
            glGetString(GL_VERSION).decode()))
        self.logger.info('SL Version: {}'.format(
            glGetString(GL_SHADING_LANGUAGE_VERSION).decode()))
        #self.logger.debug('Extensions: {}'.format(glGetString(GL_EXTENSIONS).decode()))

    def get_shader_time(self):
        return os.path.getmtime('shaders/shader.frag')

    def init_shader(self):
        self.shader = Shader({
            GL_VERTEX_SHADER: 'shaders/shader.vert',
            GL_GEOMETRY_SHADER: 'shaders/shader.geom',
            GL_FRAGMENT_SHADER: 'shaders/shader.frag'
        })
        self.shader.create()
        self.shader_time = self.get_shader_time()
        self.freeze_time = False
        self.time = 0.
        self.logger.debug('Shader program initialized')

    def init_camera(self):
        self.camera = Camera(self)

    def init_window(self):
        glfw.init()
        self.window = glfw.create_window(*self.resolution, 'PyGL', None, None)
        glfw.make_context_current(self.window)
        glfw.set_window_size_callback(self.window, self.resize)
        glfw.set_key_callback(self.window, self.keyboard_input)
        glfw.set_scroll_callback(self.window, self.scroll_input)
        glfw.set_cursor_pos_callback(self.window, self.mouse_position_input)
        glClearColor(0, 0, 0, 1)
        self.target_frame_time = 1 / self.target_fps

        self.ui = UI(self)
        self.logger.debug('Window initialized')

    def resize(self, win, width, height):
        #self.logger.debug('Window resized: {}x{}'.format(width, height))
        self.resolution = np.array([width, height])
        glViewport(0, 0, *self.resolution)

    def keyboard_input(self, win, key, scancode, action, mods):
        #self.logger.debug('key: {}, scancode: {}, action: {}, mods: {}'.format(key, scancode, action, mods))
        if (key == glfw.KEY_ESCAPE
            ) or (mods == glfw.MOD_ALT
                  and key == glfw.KEY_F4) and action == glfw.PRESS:
            glfw.set_window_should_close(self.window, True)
            self.logger.info('Exiting')
        if key == glfw.KEY_H and action == glfw.PRESS:
            self.ui.toggle_visibility()
            self.logger.debug('Toggle UI')
        if key == glfw.KEY_W and action != glfw.RELEASE:
            self.camera.move_forward()
        if key == glfw.KEY_A and action != glfw.RELEASE:
            self.camera.move_left()
        if key == glfw.KEY_S and action != glfw.RELEASE:
            self.camera.move_backward()
        if key == glfw.KEY_D and action != glfw.RELEASE:
            self.camera.move_right()
        if key == glfw.KEY_Q and action != glfw.RELEASE:
            self.camera.move_up()
        if key == glfw.KEY_E and action != glfw.RELEASE:
            self.camera.move_down()
        if key == glfw.KEY_R and action == glfw.PRESS:
            self.camera.reset()
        if key == glfw.KEY_P and action == glfw.PRESS:
            self.freeze_time = not self.freeze_time
            self.logger.info('Toggle time freeze')
        if key == glfw.KEY_F and action == glfw.PRESS:
            self.camera.toggle_look_mode()
            self.logger.info('Toggle camera look mode')
        if key == glfw.KEY_T and action == glfw.PRESS:
            self.ui.toggle_composition_overlay()
            self.logger.info('Toggle composition overlay')

    def scroll_input(self, win, x, y):
        if y > 0:
            self.camera.accelerate()
        elif y < 0:
            self.camera.decelerate()

    def mouse_position_input(self, win, x, y):
        if self.camera.look_mode:
            self.camera.look(x, y)

    def wait_for_frame_end(self, frame_start_time):
        frame_render_time = glfw.get_time() - frame_start_time
        #self.logger.debug('Frame render time: {:.1f} ms ({:.1f}%)'.format(1000*frame_render_time, frame_render_time/self.target_frame_time*100))
        self.frame_render_time = frame_render_time
        sleep_time = self.target_frame_time - frame_render_time
        if sleep_time > 0:
            time.sleep(sleep_time)

    def check_for_shader_change(self):
        current_time = self.get_shader_time()
        if current_time != self.shader_time:
            self.shader_time = current_time
            self.shader.create()

    def main_loop(self):
        while not glfw.window_should_close(self.window):
            self.check_for_shader_change()
            frame_start_time = glfw.get_time()
            if not self.freeze_time:
                self.time = frame_start_time

            glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)

            # Draw scene
            self.shader.bind()
            self.shader.set_uniforms({
                'resolution':
                self.resolution,
                'time':
                self.time,
                'camera_position':
                self.camera.position,
                'camera_rotation':
                self.camera.rotation.mat3()
            })
            glDrawArrays(GL_POINTS, 0, 1)  # dummy vbo
            self.shader.unbind()

            # Draw UI
            self.ui.draw({
                'fps_label':
                '{:4.0f}/{:2.0f} FPS, {:4.1f} ms ({:3.0f}%)'.format(
                    1 / self.frame_render_time, self.target_fps,
                    self.frame_render_time * 1000,
                    self.frame_render_time / self.target_frame_time * 100),
                'time_label':
                'Time: {:4.2f} s {}'.format(self.time,
                                            '[f]' if self.freeze_time else ''),
                'camera_label':
                'Camera: [{:5.2f}, {:5.2f}, {:5.2f}] ({:3.0f}%), [{:5.1f}, {:4.1f}]'
                .format(*self.camera.position, self.camera.speed * 100,
                        np.degrees(self.camera.yaw),
                        np.degrees(self.camera.pitch))
            })

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

        glfw.terminate()
Пример #26
0
class UI:
	def __init__(self, view):
		self.logger = logging.getLogger(type(self).__name__)
		self.view = view

		self.enabled = True

		self.init_opengl()
		self.elements = {
			'time_label':Text((.01, .99)),
			'fps_label':Text((.71, .99)),
			'camera_label':Text((.01, .04))
		}

		self.composition_overlay_enabled = True
		self.overlay_shader = Shader({GL_VERTEX_SHADER:'shaders/shader.vert', GL_GEOMETRY_SHADER:'shaders/shader.geom', GL_FRAGMENT_SHADER:'shaders/composition.frag'})
		self.overlay_shader.create()
		self.logger.debug('Initialized UI')

	def init_opengl(self):
		glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE)
		glEnable(GL_BLEND)
		glEnable(GL_COLOR_MATERIAL)
		glColorMaterial(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE)
		glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)
		glEnable(GL_TEXTURE_2D)

	def toggle_visibility(self):
		self.enabled = not self.enabled

	def toggle_composition_overlay(self):
		self.composition_overlay_enabled = not self.composition_overlay_enabled

	def draw_composition_overlay(self):
		self.overlay_shader.bind()
		self.overlay_shader.set_uniforms(
			{
				'resolution':self.view.resolution,
				'time':0.,
			}
		)
		glDrawArrays(GL_POINTS, 0, 1) # dummy vbo
		self.overlay_shader.unbind()

	def draw(self, values_dict):
		if not self.enabled: return
		ar = self.view.resolution[0]/self.view.resolution[1]
		glPushMatrix()
		glTranslatef(-1,-1,0)
		glScale(2,2,1) # -> [0,1]x[0,1]

		for name, elem in self.elements.items():
			glPushMatrix()
			glTranslatef(*elem.position, 0)
			#glScale(1/self.view.resolution[0], 1/self.view.resolution[1], 1)
			glScale(1/2000, 1/2000*ar, 1)
			elem.draw(values_dict[name])
			glPopMatrix()

		if self.composition_overlay_enabled:
			self.draw_composition_overlay()

		glPopMatrix()
Пример #27
0
class Unwrapper:
    """
    This unwrapper takes an image path and a parsed frame and fulfills
    the operations required to draw the unwrapped image.

    The draw operations MUST be called inside of the "on_draw" callback
    passed to "start_unwrap_window" in order to be fulfilled.  This class
    cannot function without an OpenGL window.
    """
    def __init__(self):

        # Create the shader.
        self.shader = Shader(vertex_shader, fragment_shader)

        # Set the texture unit.
        self.shader.bind()
        self.shader.uniformi('tex0', 0)
        self.shader.unbind()

        # Create a quad geometry to fit the whole window that will be the target of our drawing.
        self.batch = pyglet.graphics.Batch()
        self.batch.add(4, GL_QUADS, None, ('v2i', (0, 0, 1, 0, 1, 1, 0, 1)),
                       ('t2f', (0, 0, 1, 0, 1, 1, 0, 1)))

    def update(self, img_path, frame):
        """
        Update the texture to the given image path, and update the shaders with the new
        frame information to unwrap the given image correctly.
        """

        # Recalculate the variables required to unwrap the new image.
        projector = PolygonProjector(frame.center_point, frame.center_vertices)
        angle_bounds = [v.angle for v in projector.vertices]
        radii = [p.center_dist for p in projector.projectors]
        angles = [p.center_angle for p in projector.projectors]

        # Load the new image, and update the size variables.
        self.texture = pyglet.image.load(img_path).get_texture()
        region_w, region_h = self.texture.width, self.texture.height
        actual_w, actual_h = self.texture.owner.width, self.texture.owner.height

        # Update the shader variables.
        self.shader.bind()
        self.shader.uniformf('region_size', region_w, region_h)
        self.shader.uniformf('actual_size', actual_w, actual_h)
        self.shader.uniformfv('angle_bounds', 1, angle_bounds)
        self.shader.uniformfv('radii', 1, radii)
        self.shader.uniformfv('angles', 1, angles)
        self.shader.uniformi('count', len(radii))
        self.shader.unbind()

    def draw(self):
        """Draw the unwrapped image to the window."""
        glBindTexture(self.texture.target, self.texture.id)
        self.shader.bind()
        self.batch.draw()
        self.shader.unbind()
        glBindTexture(self.texture.target, 0)

    def save_image(self, filename):
        """Save the current window image to the given filename."""
        pyglet.image.get_buffer_manager().get_color_buffer().save(filename)

    def get_fps(self):
        """Get the current framerate in frames per second."""
        return pyglet.clock.get_fps()
Пример #28
0
class MainWindow(pyglet.window.Window):
    def __init__(self, **kwargs):
        config = pyglet.gl.Config(sample_buffers=1, samples=4)

        pyglet.window.Window.__init__(self, width=1000, height=700,
            resizable=True, config=self.config, **kwargs)

        self.fps = pyglet.clock.ClockDisplay()
        self.shader = Shader(vertex_shader, fragment_shader)
        self.center = np.array([0.0,0.0])
        self.show_fps = False

        self.screen_size = np.array([self.width, self.height])
        self.view_size = np.array([3.0, 2.0])
        self.col_scale = 4000.0

        self.draw()

    def on_key_press(self, symbol, modifiers):
        if symbol == key.ESCAPE:
            self.has_exit = True
        elif symbol == key.F:
            self.set_fullscreen(not self.fullscreen)
            self.screen_size = np.array([self.width, self.height])
        elif symbol == key.F1:
            self.show_fps = not self.show_fps
        elif symbol == key.F2:
            pyglet.image.get_buffer_manager().get_color_buffer().save('screenshot.png')
        elif symbol == key.C:
            self.renderC()
            return
        elif symbol == key.DOWN:
            self.col_scale *= 0.9
            print self.col_scale
            self.renderC() 
            return
        elif symbol == key.UP:
            self.col_scale *= 1.1
            print self.col_scale
            self.renderC() 
            return

        self.draw()

    def on_mouse_drag(self, x, y, dx, dy, buttons, modifiers):
        delta = np.array((dx,dy))
        self.center += delta * self.view_size / self.screen_size
        self.draw()

    def on_mouse_scroll(self, x, y, scroll_x, scroll_y):
        scale = 1.1 ** scroll_y
        screen_center = np.array([self.width/2.0, self.height/2.0])
        self.center += (scale - 1.0) * (np.array([x,y]) - screen_center) * (self.view_size / self.screen_size)
        self.view_size *= scale
        self.draw()

    def on_resize(self, width, height):
        pyglet.window.Window.on_resize(self, width, height)
        self.draw()

    def draw(self):
            if self.view_size[0] < 1e-4 or self.view_size[1] < 1e-4 :
                self.renderC()
                return

            gl.glClear(gl.GL_COLOR_BUFFER_BIT)
            gl.glLoadIdentity()
            self.shader.bind()
            self.shader.uniformf("z", self.center)
            self.shader.uniformf("res", self.screen_size)
            self.shader.uniformf("view", self.view_size)

            #draw square across screen
            gl.glBegin(gl.GL_QUADS)
            gl.glVertex3f(0.0, 0.0, 0.0)
            gl.glVertex3f(0.0, self.height, 0.0)
            gl.glVertex3f(self.width, self.height, 0.0)
            gl.glVertex3f(self.width, 0.0, 0.0)
            gl.glEnd()

            self.shader.unbind()
            if self.show_fps:
                self.fps.draw()
            self.flip()

    def run(self):
        while not self.has_exit:
            pyglet.clock.tick()
            self.dispatch_events()

    def renderC(self):
        w, h, = self.width,self.height
        t = time.time()
        imagetype = c.c_byte * (w * h * 3)
        imagedata = imagetype()
        clib.mandelbrot(c.c_int(w), c.c_int(h),c.c_double(self.col_scale), vec2(self.center), vec2(self.view_size), imagedata)
        image = pyglet.image.ImageData(w, h, "RGB", imagedata, pitch = 3 * c.sizeof(c.c_char) * w)
        image.blit(0,0)
        self.flip()
        return image
Пример #29
0
    # texture_p holds pointer mask
    # ----------------------------
    D = np.ones((8,8,4),dtype=np.ubyte)*0
    #D[4:12:,4:12] = 0
    image = pyglet.image.ImageData(D.shape[1],D.shape[0],'RGBA',D.ctypes.data)
    sprite = pyglet.sprite.Sprite(image)


    # Reaction-diffusion shader
    # -------------------------
    vertex_shader   = open('./reaction-diffusion.vert').read()
    fragment_shader = open('./reaction-diffusion.frag').read()
    reaction_shader = Shader(vertex_shader, fragment_shader)

    reaction_shader.bind()
    reaction_shader.uniformi('texture', 0)
    reaction_shader.uniformi('params',  1)
    reaction_shader.uniformi('display', 2)
    reaction_shader.uniformf('dt', dt)
    reaction_shader.uniformf('dx', 1.0/width)
    reaction_shader.uniformf('dy', 1.0/height)
    reaction_shader.uniformf('dd', dd)
    reaction_shader.unbind()

    # Color shader
    # ------------
    vertex_shader   = open('./color.vert').read()
    fragment_shader = open('./color.frag').read()
    color_shader    = Shader(vertex_shader, fragment_shader)
Пример #30
0
class TextureWindow(pyglet.window.Window):
    '''
    Concrete draw window. This uses the ShaderController to load and operate the shader at the path
    passed to the constructor.
    '''

    def __init__(self, shader_path):
        '''
        Load and attempt to run the shader at shader_path.
        '''
        self.w = 512
        self.h = 512

        # Load shader code
        vspath = '%s.v.glsl' % shader_path
        fspath = '%s.f.glsl' % shader_path
        with io.open(vspath) as vstrm, io.open(fspath) as fstrm:
            vertexshader = ' '.join(vstrm)
            fragmentshader = ' '.join(fstrm)

        self.shader = Shader(vertexshader, fragmentshader)
        self.shader_controller = ShaderController(self.shader, shader_path)
        super(TextureWindow, self).__init__(caption=shader_path, width=self.w, height=self.h)

        self.create_key_help_labels()

    def create_key_help_labels(self):
        '''
        Create the help labels to display overlaying the drawn shader
        '''
        self.helpLabels = []
        y = self.height
        for labelText in self.shader_controller.get_html_help(key):
            self.helpLabels.append(pyglet.text.HTMLLabel(
                    "<font face='Courier New' color='white'>{}</font>".format(labelText),
                    x=0, y=y,
                    anchor_x='left', anchor_y='top'))
            y -= 20
    
    def updateStatusLabels(self):
        self.statusLabels = []
        y = 20
        label = 0
        for labelText in self.shader_controller.get_statuses():
            # Create a new label if we need one (suddenly)
            if label >= len(self.statusLabels):
                self.statusLabels.append(pyglet.text.HTMLLabel("",
                    x=0, y=y,
                    anchor_x='left', anchor_y='top'))
            # Modify an existing label to give it status text
            self.statusLabels[label].text = "<font face='Courier New' color='white'>{}</font>".format(labelText)
            y += 20
            label += 1

    def on_mouse_drag(self, x, y, dx, dy, buttons, modifiers):
        self.shader_controller.mouse_drag(dx, dy)

    def on_mouse_scroll(self, x, y, scroll_x, scroll_y):
        self.shader_controller.mouse_scroll_y(scroll_y)

    def on_key_release(self, symbol, modifiers):
        self.shader_controller.binding_trigger(symbol)

    def saveFromShader(self):
        a = (gl.GLubyte * (4 * self.w * self.h))(0)
        # Save without any GUI elements
        self.drawGenerated()
        gl.glReadPixels(0, 0, self.w, self.h, gl.GL_RGBA, gl.GL_UNSIGNED_BYTE, a)
        image = pyglet.image.ImageData(self.w, self.h, 'RGBA', a)
        scriptPath = os.path.dirname(os.path.realpath(__file__))
        filePath = scriptPath + "/TESTSAVE_" + time.strftime("%Y%m%d_%H%M%S") + ".png"
        print ("saved to {}".format(filePath))
        image.save(filePath)

    def on_draw(self):
        self.drawGenerated()
        self.updateStatusLabels()
        self.drawGUI()
        
    def drawGenerated(self):
        gl.glMatrixMode(gl.GL_PROJECTION)
        gl.glLoadIdentity()
        gl.glOrtho(-1., 1., 1., -1., 0., 1.)

        gl.glMatrixMode(gl.GL_MODELVIEW)
        gl.glLoadIdentity()

        self.shader.bind()

        self.shader_controller.set_uniforms()

        gl.glBegin(gl.GL_QUADS)
        gl.glVertex2i(-1, -1)
        gl.glTexCoord2i(-2, -2)
        gl.glVertex2f(1, -1)
        gl.glTexCoord2i(2, -2)
        gl.glVertex2i(1, 1)
        gl.glTexCoord2i(2, 2)
        gl.glVertex2i(-1, 1)
        gl.glTexCoord2i(-2, 2)
        gl.glEnd()

        self.shader.unbind()

    def drawGUI(self):
        gl.glMatrixMode(gl.GL_PROJECTION)
        gl.glLoadIdentity()
        gl.glOrtho(0, self.w, 0, self.h, -1, 1)

        for label in self.helpLabels:
            label.draw()
        for label in self.statusLabels:
            label.draw()
Пример #31
0
class Scene(object):
    
    PAUSED = 0
    PLAYING = 1
    
    vertex_shader = '''
    uniform mat4 modelview;
    uniform mat4 projection;
    void main() {
        gl_FrontColor = gl_Color;
        
        vec4 modelSpacePos = modelview * gl_Vertex;
        gl_Position = projection * modelSpacePos;
    }
    '''

    def __init__(self):
        self.objects = []
        self.camera = None
        
        self.playback = Parameter(default=self.PAUSED, enum=[('Play',self.PLAYING),('Pause',self.PAUSED)])
        #self.playback = self.PLAYING
        self.fps = 24.0
        self.time = 0   # in seconds?
        self.frame = Parameter(default=1, vmin=0, vmax=100, title='Frame', update=self.update_time)
        self.sframe = Parameter(default=1, vmin=0, vmax=100, title='Start Frame')
        self.eframe = Parameter(default=100, vmin=0, vmax=100, title='End Frame')

        self.ui3d_shader = Shader(self.vertex_shader)
        self.ui3d_batch = pyglet.graphics.Batch()

        self.grid = Grid(10, 10, self.ui3d_batch )
        self.axes = Axes(0.5, self.ui3d_batch )

        self.bbmin = None
        self.bbmax = None
    
    def calculate_bounds(self):
        self.bbmin = None
        self.bbmax = None

        for ob in self.objects:
            if hasattr(ob, "bbmin") and hasattr(ob, "bbmax"):
                if self.bbmin is None and self.bbmax is None:
                    self.bbmin = ob.bbmin
                    self.bbmax = ob.bbmax
                else:
                    self.bbmin.x = min(ob.bbmin.x, self.bbmin.x)
                    self.bbmin.y = min(ob.bbmin.y, self.bbmin.y)
                    self.bbmin.z = min(ob.bbmin.z, self.bbmin.z)

                    self.bbmax.x = max(ob.bbmax.x, self.bbmax.x)
                    self.bbmax.y = max(ob.bbmax.y, self.bbmax.y)
                    self.bbmax.z = max(ob.bbmax.z, self.bbmax.z)

                self.grid.delete()
                del self.grid
                diam = self.bbmax - self.bbmin
                center = self.bbmin + diam*0.5
                self.grid = Grid(10, 10, self.ui3d_batch, center=center[:])


    def on_key_press(self, symbol, modifiers):
        if symbol == pyglet.window.key.H:
            self.calculate_bounds()
            self.camera.focus(self)
        if symbol == pyglet.window.key.RIGHT:
            self.frame.value += 1
        if symbol == pyglet.window.key.LEFT:
            self.frame.value -= 1

    def on_mouse_drag(self, x, y, dx, dy, buttons, modifiers):
        if not (modifiers & pyglet.window.key.MOD_ALT or \
                modifiers & pyglet.window.key.MOD_CTRL or \
                modifiers & pyglet.window.key.MOD_SHIFT or \
                keys[pyglet.window.key.SPACE]):
            if buttons & mouse.MIDDLE:
                self.frame.value +=  dx*0.05
                return pyglet.event.EVENT_HANDLED


    def on_draw(self):
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
        
        # 3D Geometry
        for ob in self.objects:
            ob.draw(time=self.time, camera=self.camera)

        # 3D UI elements
        glEnable(GL_LINE_SMOOTH)
        glEnable(GL_BLEND);
        glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
        glHint (GL_LINE_SMOOTH_HINT, GL_NICEST);
        
        self.ui3d_shader.bind()
        self.ui3d_shader.uniform_matrixf('modelview', self.camera.matrixinv)
        self.ui3d_shader.uniform_matrixf('projection', self.camera.persp_matrix)
        self.ui3d_batch.draw()
        self.ui3d_shader.unbind()

        glDisable(GL_LINE_SMOOTH)

    def update_time(self):            
        for ob in self.objects:
            ob.update(self.time, self.frame.value)

    def update(self, dt):
        if self.playback.value == self.PLAYING:
            #self.time += dt

            # loop playback
            #frame = self.time * self.fps
            frame = self.frame.value + 1
            if frame > self.eframe.value:
                frame = self.sframe.value
            self.frame.value = frame

            self.update_time()
Пример #32
0
class Unwrapper:
    """
    This unwrapper takes an image path and a parsed frame and fulfills
    the operations required to draw the unwrapped image.

    The draw operations MUST be called inside of the "on_draw" callback
    passed to "start_unwrap_window" in order to be fulfilled.  This class
    cannot function without an OpenGL window.
    """
    def __init__(self):

        # Create the shader.
        self.shader = Shader(vertex_shader, fragment_shader)

        # Set the texture unit.
        self.shader.bind()
        self.shader.uniformi('tex0', 0)
        self.shader.unbind()

        # Create a quad geometry to fit the whole window that will be the target of our drawing.
        self.batch = pyglet.graphics.Batch()
        self.batch.add(4, GL_QUADS, None, ('v2i', (0,0, 1,0, 1,1, 0,1)), ('t2f', (0,0, 1,0, 1,1, 0,1)))

    def update(self, img_path, frame):
        """
        Update the texture to the given image path, and update the shaders with the new
        frame information to unwrap the given image correctly.
        """

        # Recalculate the variables required to unwrap the new image.
        projector = PolygonProjector(frame.center_point, frame.center_vertices)
        angle_bounds = [v.angle for v in projector.vertices]
        radii = [p.center_dist for p in projector.projectors]
        angles = [p.center_angle for p in projector.projectors]

        # Load the new image, and update the size variables.
        self.texture = pyglet.image.load(img_path).get_texture()
        region_w, region_h = self.texture.width, self.texture.height
        actual_w, actual_h = self.texture.owner.width, self.texture.owner.height

        # Update the shader variables.
        self.shader.bind()
        self.shader.uniformf('region_size', region_w, region_h)
        self.shader.uniformf('actual_size', actual_w, actual_h)
        self.shader.uniformfv('angle_bounds', 1, angle_bounds)
        self.shader.uniformfv('radii', 1, radii)
        self.shader.uniformfv('angles', 1, angles)
        self.shader.uniformi('count', len(radii))
        self.shader.unbind()

    def draw(self):
        """Draw the unwrapped image to the window."""
        glBindTexture(self.texture.target, self.texture.id)
        self.shader.bind()
        self.batch.draw()
        self.shader.unbind()
        glBindTexture(self.texture.target, 0)

    def save_image(self, filename):
        """Save the current window image to the given filename."""
        pyglet.image.get_buffer_manager().get_color_buffer().save(filename)

    def get_fps(self):
        """Get the current framerate in frames per second."""
        return pyglet.clock.get_fps()
Пример #33
0
class LineRendererDynamic:
    def __init__(self):
        self.feather = 0.4
        self.shader = Shader(['''
                              #version 120
                              attribute vec2 width;
                              varying vec4 color;
                              varying vec2 offset;

                              void main() {
                               // transform the vertex position
                               vec2 dir = gl_Normal.xy * width.xy;
                               offset = dir;
                               gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex + vec4(offset, 0.0, 0.0);
                               color = gl_Color;
                            }
                              '''],
            ['''
                #version 120
                varying vec4 color;
                varying vec2 offset;
                uniform float feather;
                uniform float width;

                void main() {
                    vec4 newColor = color;
                    //if (length(offset) >= width * 0.9) {
                    //    newColor = vec4(1.0, 0.0, 0.0, 1.0);
                    //}

                    float alpha = 1.0 - smoothstep(-width * feather, width * feather, length(offset) - width);

                    newColor = vec4(color.r * alpha, color.g * alpha, color.b * alpha, alpha);

                    gl_FragColor = newColor;
                }
             '''])
        
    def drawLineInNormalizedCoordinates(self, start, end, width):
        lineBatch = pyglet.graphics.Batch()
    
        direction = pointsSubtract(end, start)
        cross = pointNormalized(pointCross(direction))
        cross = (cross[0], cross[1] * (window.width / window.height))
        crossAlt = pointNormalized(pointCrossAlt(direction))
        crossAlt = (crossAlt[0], crossAlt[1] * (window.width / window.height))
        
        aspect = window.width / window.height
        widthVector = pointsMultiply(pointNormalized((width, width * aspect)), width)
        vertex_list = lineBatch.add(
            6,
                                    pyglet.gl.GL_TRIANGLES,
                                    None,
                                    ('v2f',
                                     (start[0], start[1], end[0], end[1], start[0], start[1],
                                      start[0], start[1], end[0], end[1], end[0], end[1])
                                    ),
                                    ('c4f',
                                     (1.0, 0.0, 0.0, 1.0,  1.0, 0.0, 0.0, 0.5,  1.0, 0.0, 0.0, 0.5,
                                      
                                      0.0, 1.0, 0.0, 1.0,  0.0, 0.0, 1.0, 1.0,  0.0, 0.0, 1.0, 1.0)
                                    ),
                                    ('n3f',
                                     (cross[0], cross[1], 1.0,  crossAlt[0], crossAlt[1], 1.0,  crossAlt[0], crossAlt[1], 1.0,
                                      cross[0], cross[1], 1.0, cross[0], cross[1], 1.0,  crossAlt[0], crossAlt[1], 1.0)
                                     )
                                    ,
                                    ('1g2f',
                                     (widthVector[0], widthVector[1],  widthVector[0], widthVector[1],  widthVector[0], widthVector[1],
                                      
                                      widthVector[0], widthVector[1],  widthVector[0], widthVector[1],  widthVector[0], widthVector[1])
                                    )
                                    )
    
        self.__drawBatch(lineBatch, widthVector[0])
        
    def drawLine(self, start, end, width):
        lineBatch = pyglet.graphics.Batch()
        
        start = pointsDivide(start, (window.width, window.height))
        end = pointsDivide(end, (window.width, window.height))
        
        direction = pointsSubtract(end, start)
        cross = pointNormalized(pointCross(direction))
        cross = (cross[0], cross[1] * (window.width / window.height))
        cross = pointNormalized(cross)
        crossAlt = pointNormalized(pointCrossAlt(direction))
        crossAlt = (crossAlt[0], crossAlt[1] * (window.width / window.height))
        crossAlt = pointNormalized(crossAlt)

        #since in veretx shader coordinates ar maped into device normalized space we do not need to divide width by half
        width = width / window.width
        
        aspect = window.width / window.height
        widthVector = (width, width) #pointMultipliedByScalar(pointNormalized((width, width * aspect)), width)
        vertex_list = lineBatch.add(
            6,
                                    pyglet.gl.GL_TRIANGLES,
                                    None,
                                    ('v2f',
                                     (start[0], start[1], end[0], end[1], start[0], start[1],
                                      start[0], start[1], end[0], end[1], end[0], end[1])
                                    ),
                                    ('c4f',
                                     (1.0, 1.0, 1.0, 1.0,  1.0, 1.0, 1.0, 1.0,  1.0, 1.0, 1.0, 1.0,
                                      
                                      1.0, 1.0, 1.0, 1.0,  1.0, 1.0, 1.0, 1.0,  1.0, 1.0, 1.0, 1.0)
                                    ),
                                    ('n3f',
                                     (cross[0], cross[1], 1.0,  crossAlt[0], crossAlt[1], 1.0,  crossAlt[0], crossAlt[1], 1.0,
                                      cross[0], cross[1], 1.0, cross[0], cross[1], 1.0,  crossAlt[0], crossAlt[1], 1.0)
                                     )
                                    ,
                                    ('1g2f',
                                     (widthVector[0], widthVector[1],  widthVector[0], widthVector[1],  widthVector[0], widthVector[1],

                                      widthVector[0], widthVector[1],  widthVector[0], widthVector[1],  widthVector[0], widthVector[1])
                                    )
                                   )
        self.__drawBatch(lineBatch, widthVector[0])

    def __drawBatch(self, batch, width):
        self.shader.bind()
        self.shader.uniformf("feather", self.feather)
        self.shader.uniformf("width", width)
        batch.draw()
        self.shader.unbind()
Пример #34
0
Файл: game.py Проект: ext/scfa
class Game(object):
    def __init__(self):
        self._running = False
        self.camera = Vector2f(0,5)

    def init(self, size, fullscreen=False):
        flags = OPENGL|DOUBLEBUF
        if fullscreen:
            flags |= FULLSCREEN

        pygame.display.set_mode(size.xy, flags)
        pygame.display.set_caption('Super Chainsaw Food Adventure')

        i = pygame.display.Info()
        self.size = Vector2i(i.current_w, i.current_h)

        glMatrixMode(GL_MODELVIEW)
        glEnable(GL_TEXTURE_2D)
        glDisable(GL_CULL_FACE)
        glEnable(GL_BLEND)
        glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA)

        self.stage = 1
        self.projection = Matrix.perspective(75, self.size, 0.1, 100)
        self.ortho = Matrix.ortho(self.size)

        v = np.array([
                0,0,0, 0,0,
                1,0,0, 1,0,
                1,1,0, 1,1,
                0,1,0, 0,1,
                ], np.float32)
        i = np.array([0,1,2,3], np.uint32)
        self.quad = VBO(GL_QUADS, v, i)

        # parallax
        self.parallax_rep = 25
        v = np.array([
                0,0,0, 0,1,
                1,0,0, self.parallax_rep, 1,
                1,1,0, self.parallax_rep,0,
                0,1,0, 0,0,
                ], np.float32)
        i = np.array([0,1,2,3], np.uint32)
        self.repquad = VBO(GL_QUADS, v, i)
        self.parallax = Image('texture/sky.png', wrap=GL_REPEAT)
        self.parallax2 = Image('texture/sky2.png', wrap=GL_REPEAT)

        self.fbo = FBO(self.size, format=GL_RGB8, depth=True)

        self.shader = Shader('derp')
        self.passthru = Shader('passtru')
        self.herp = Shader('herp')

        self.map = Map('map.json')
        self.player = Player(Vector2f(55,-9))
        self.clock = pygame.time.Clock()
        self.hud = HUD(Vector2i(500,100))
        self.hpmeter = HUD(Vector2i(20, 500))
        self.font = self.hud.create_font(size=16)
        self.font2 = self.hud.create_font(size=12)

        self.land = pygame.mixer.Sound('data/sound/land.wav')
        self.ding = pygame.mixer.Sound('data/sound/ding.wav')
        self.eat = pygame.mixer.Sound('data/sound/eat.wav')
        self.wind = pygame.mixer.Sound('data/sound/wind.wav')

        self.wind.play(loops=-1)

        self.set_stage(1)
        self.killfade = None
        self.killfade2 = 1.0 # fade amount
        self.textbuf = []
        self.texttime = -10.0
        self.message('<b>Welcome adventurer!</b>\nYou can start exploring the world but beware of wandering away too far.')
        self.message('When outside of lights your <i>HP</i> will drain and you will get lost in the woods.')
        self.message('Eat food to temporary increase your <i>HP</i>.')
        self.message('Quest started: "Find the chainsaw".')
        self.message('Quest started: "Frobnicate something".')

        with self.hud:
            self.hud.clear((0,1,1,1))

    def running(self):
        return self._running

    @event(pygame.QUIT)
    def quit(self, event=None):
        self._running = False

    @event(pygame.KEYDOWN)
    def on_keypress(self, event):
        if event.key == 113 and event.mod & KMOD_CTRL: # ctrl+q
            return self.quit()
        if event.key == 27: # esc
            return self.quit()

        if event.key == 119:
            self.player.jump()

    @event(pygame.KEYUP)
    def on_keyrelease(self, event):
        if event.key == 119:
            self.player.unjump()

    def poll(self):
        global event_table
        for event in pygame.event.get():
            func = event_table.get(event.type, None)
            if func is None:
                continue
            func(self, event)

    def update(self):
        if self.killfade is not None:
            t = pygame.time.get_ticks() / 1000.0
            s = (t - self.killfade) / 2.5
            self.killfade2 = 1.0 - s

            if s > 1.0:
                self.quit()

            # so player keeps falling
            dt = 1.0 / self.clock.tick(60)
            self.player.vel.y = 0
            self.player.update(dt, self.map)

            return

        key = pygame.key.get_pressed()

        self.player.vel.x = 0
        if key[97 ]: self.player.vel.x = -0.15
        if key[100]: self.player.vel.x =  0.15

        if key[260]: self.camera.x -= 0.1
        if key[262]: self.camera.x += 0.1
        if key[258]: self.camera.y -= 0.1
        if key[264]: self.camera.y += 0.1

        dt = 1.0 / self.clock.tick(60)
        self.player.update(dt, self.map)
        self.player.frobnicate(self.map.pickups)
        self.map.update()

    def render(self):
        glClearColor(1,0,1,1)
        glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT)

        with self.hpmeter as hud:
            hud.clear((0.3,0,0,1))
            hud.cr.identity_matrix()

            hud.rectangle(0,0, hud.width, hud.height * self.player.hp_ratio, (0,0.3,0,1))

            hud.cr.translate(18,0)
            hud.cr.rotate(math.pi*0.5)
            hud.text(' Energy: %d / %d' % (int(math.ceil(self.player.hp/10)) * 10, Player.max_hp), self.font2, color=(1,0.8,0,1))

        with self.hud:
            self.hud.clear((0,0,0,0))
            self.hud.cr.identity_matrix()

            t = pygame.time.get_ticks() / 1000.0
            s = (t - self.texttime) / 4.0

            if s > 1.0:
                if len(self.textbuf) > 0:
                    self.texttime = pygame.time.get_ticks() / 1000.0
                    self.text = self.textbuf.pop(0)
            else:
                a = min(1.0-s, 0.2) * 5
                self.hud.cr.translate(0,25)
                self.hud.text(self.text, self.font, color=(1,0.8,0,a), width=self.hud.width, alignment=ALIGN_CENTER)

        view = Matrix.lookat(
            self.player.pos.x, self.player.pos.y+7, 15,
            self.player.pos.x, self.player.pos.y+7, 0,
            0,1,0)

        with self.fbo as frame:
            frame.clear(0,0.03,0.15,1)

            Shader.upload_projection_view(self.projection, view)
            Shader.upload_player(self.player)
            self.shader.bind()

            # parallax background
            pm1 = Matrix.identity()
            pm1[3,0] = self.player.pos.x * 0.35 - 20
            pm1[3,1] = self.player.pos.y * 0.5 - 20
            pm1[0,0] = 42.0 * self.parallax_rep
            pm1[1,1] = 42.0
            self.parallax.texture_bind()
            Shader.upload_model(pm1)
            self.repquad.draw()

            Shader.upload_projection_view(self.projection, view)

            self.map.draw()

            # entities
            for obj in self.map.pickups:
                obj.draw(self.quad)
            self.player.draw()

            # parallax 2
            pm1 = Matrix.identity()
            pm1[3,0] = self.player.pos.x * -2.0 + 100
            pm1[3,1] = self.player.pos.y * 0.5 - 45 * 3 + 10
            pm1[0,0] = 45.0 * self.parallax_rep * 3
            pm1[1,1] = 45 * 3
            self.parallax2.texture_bind()
            Shader.upload_model(pm1)
            self.repquad.draw()

        mat = Matrix.identity()
        mat[0,0] = self.size.x
        mat[1,1] = self.size.y
        Shader.upload_projection_view(self.ortho, Matrix.identity())
        Shader.upload_model(mat)

        self.fbo.bind_texture()
        self.herp.bind()
        self.quad.draw()

        # messagebox
        mat = Matrix.identity()
        mat[3,0] = self.size.x / 2 - self.hud.width / 2
        mat[3,1] = self.size.y - self.hud.height
        Shader.upload_model(mat)
        self.hud.draw()

        # hpmeter
        mat = Matrix.identity()
        mat[3,1] = self.size.y / 2 - self.hpmeter.height / 2
        Shader.upload_model(mat)
        self.hpmeter.draw()

        Shader.unbind()

        pygame.display.flip()

    def run(self):
        self._running = True
        while self.running():
            self.poll()
            self.update()
            self.render()

    def message(self, text):
        self.textbuf.append(text)

    def set_stage(self, n):
        if n == 1:
            self.map.pickups.extend(self.map.obj1)
        elif n == 2:
            self.map.pickups.extend(self.map.obj2)
        elif n == 3:
            self.map.pickups.extend(self.map.obj3)

    def over(self):
        self.killfade = pygame.time.get_ticks() / 1000.0
Пример #35
0
class GLRender(object):
	
	scale = 1
	angles = [0,0,0]
	mol = None
	envTex = None
	
	def __init__(self):
		# Setup the GLSL program
		with open('molgl.vert','r') as f:
			vert = f.readlines()
		with open('molgl.frag','r') as f:
			frag = f.readlines()
		self.shader = Shader(vert=vert, frag=frag)
		
		# Some parameters
		glEnable(GL_DEPTH_TEST)
		glPolygonMode(GL_FRONT_AND_BACK, GL_FILL)
	
	def applySceneTransforms(self):
		gluLookAt(0, 0, 2*self.mol.radius, 0, 0, 0, 0, 1, 0); # Push molecule away from the origin along -Z direction.
		glScalef(self.scale,self.scale,self.scale);
		def mouse_rotate(xAngle, yAngle, zAngle):
			glRotatef(xAngle, 1.0, 0.0, 0.0);
			glRotatef(yAngle, 0.0, 1.0, 0.0);
			glRotatef(zAngle, 0.0, 0.0, 1.0);
		mouse_rotate(self.angles[0],self.angles[1],self.angles[2]);
		glTranslatef(-self.mol.x, -self.mol.y, -self.mol.z); # Bring molecue center to origin
		
	def set_molecule(self, mol):
		self.mol = mol
		
	def set_envmap(self, envmap):
		if self.envTex: glDeleteTextures(self.envTex)
		self.envTex = glGenTextures(1);
		glBindTexture(GL_TEXTURE_2D, self.envTex);
		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_NEAREST);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
		glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, envmap.shape[0], envmap.shape[1], 0, 
			GL_RGB, GL_FLOAT, envmap);
		glBindTexture(GL_TEXTURE_2D, 0);

	def render(self):
		glEnable(GL_TEXTURE_2D)
		glBindTexture(GL_TEXTURE_2D, self.envTex)
		self.applySceneTransforms()
		self.shader.bind()
		#self.shader.uniformf('scale',self.scale)
		self.shader.uniformf('scale', 1)
		self.shader.uniformi('tex', 0)
		self.shader.uniformi('envMapping', 1)

		# Draw all the sphere
		for sphere in self.mol.spheres:
			glColor3f(sphere.r, sphere.g, sphere.b);
			glPushMatrix()
			glTranslatef(sphere.x, sphere.y, sphere.z);
			q = gluNewQuadric()
			gluSphere(q, sphere.radius,20,20)
			#glutSolidSphere(sphere.radius,20,20);
			glPopMatrix()
		self.shader.unbind()
		glBindTexture(GL_TEXTURE_2D, 0)
		glDisable(GL_TEXTURE_2D)