def reload_shaders(self):
        print("Reloading shaders..")
        self.prog_eep = self.ctx.program([
            self.ctx.vertex_shader(load_shader("exitpoints.vert")),
            self.ctx.fragment_shader(load_shader("exitpoints.frag")),
        ])

        self.prog_rc = self.ctx.program([
            self.ctx.vertex_shader(load_shader("raycasting.vert")),
            self.ctx.fragment_shader(load_shader("raycasting.frag")),
        ])

        # re-attach vertex array objects
        vbo_attributes = [
            'VerPos',
        ]
        vbo_format = ModernGL.detect_format(self.prog_eep, vbo_attributes)
        self.vao_eep = self.ctx.vertex_array(
            self.prog_eep, [(self.vbo_vertex, vbo_format, vbo_attributes)],
            self.vbo_veridx)

        vbo_format = ModernGL.detect_format(self.prog_rc, vbo_attributes)
        self.vao_rc = self.ctx.vertex_array(
            self.prog_rc, [(self.vbo_vertex, vbo_format, vbo_attributes)],
            self.vbo_veridx)

        # update handles for the uniforms
        self.unf_screensize = self.prog_rc.uniforms["ScreenSize"]
        self.unf_stepsize = self.prog_rc.uniforms["StepSize"]
        self.unf_transferfunc = self.prog_rc.uniforms["TransferFunc"]
        self.unf_exitpoints = self.prog_rc.uniforms["ExitPoints"]
        self.unf_volumetex = self.prog_rc.uniforms["VolumeTex"]
Esempio n. 2
0
    def initializeGL(self):
        try:
            GL.Init()
            GL.Viewport(0, 0, context['width'], context['height'])

            vert = GL.NewVertexShader('''
				#version 330

				in vec2 vert;
				out vec2 tex;

				void main() {
					gl_Position = vec4(vert, 0.0, 1.0);
					tex = vert / 2.0 + vec2(0.5, 0.5);
				}
			''')

            frag = GL.NewFragmentShader('''
				#version 330
				
				in vec2 tex;
				out vec4 color;

				uniform float scale;
				uniform vec2 center;
				uniform int iter;

				void main() {
					vec2 z = vec2(5.0 * (tex.x - 0.5), 3.0 * (tex.y - 0.5));
					vec2 c = vec2(1.33 * (tex.x - 0.5) * scale - center.x, (tex.y - 0.5) * scale - center.y);

					int i;
					for(i = 0; i < iter; i++) {
						vec2 v = vec2((z.x * z.x - z.y * z.y) + c.x, (z.y * z.x + z.x * z.y) + c.y);
						if (dot(v, v) > 4.0) break;
						z = v;
					}

					float cm = fract((i == iter ? 0.0 : float(i)) * 10 / iter);
					color = vec4(fract(cm + 0.0 / 3.0), fract(cm + 1.0 / 3.0), fract(cm + 2.0 / 3.0), 1.0);
				}
			''')

            prog = GL.NewProgram([vert, frag])
            context['center'] = prog['center']
            context['scale'] = prog['scale']

            vbo = GL.NewVertexBuffer(
                struct.pack('8f', -1.0, -1.0, -1.0, 1.0, 1.0, -1.0, 1.0, 1.0))
            context['vao'] = GL.NewVertexArray(prog, vbo, '2f', ['vert'])

            GL.SetUniform(prog['iter'], 100)
            GL.SetUniform(prog['scale'], 1.0)
            GL.SetUniform(prog['center'], 0.3, 0.2)

        except GL.Error as error:
            print(error)
            exit(1)
Esempio n. 3
0
 def paintGL(self):
     context['mx'] += context['dmx']
     context['my'] += context['dmy']
     context['s'] += context['ds']
     GL.Clear(240, 240, 240)
     GL.SetUniform(context['center'], context['mx'], context['my'])
     GL.SetUniform(context['scale'], 0.5**context['s'])
     GL.RenderTriangleStrip(context['vao'], 4)
     self.update()
Esempio n. 4
0
    def paintGL(self):
        z = 0.5**context['s']
        context['mx'] += context['dmx'] * z
        context['my'] += context['dmy'] * z
        context['s'] += context['ds']
        GL.Clear(240, 240, 240)

        GL.SetUniform(context['pos'], context['mx'] / z, context['my'] / z)
        GL.SetUniform(context['zoom'], z)
        GL.RenderTriangleStrip(context['vao'], 4)
        self.update()
Esempio n. 5
0
    def initializeGL(self):
        try:
            GL.Init()
            GL.Viewport(0, 0, context['width'], context['height'])

            vert = GL.NewVertexShader('''
				#version 330

				in vec2 vert;
				out vec2 tex_coord;

				uniform vec2 scale;
				uniform float rotation;

				void main() {
					mat2 rot = mat2(cos(rotation), sin(rotation), -sin(rotation), cos(rotation));
					gl_Position = vec4((rot * vert) * scale, 0.0, 1.0);
					tex_coord = vert;
				}
			''')

            frag = GL.NewFragmentShader('''
				#version 330

				uniform sampler2D texture;
				
				in vec2 tex_coord;
				out vec4 color;

				void main() {
					color = vec4(texture2D(texture, tex_coord).rgb, 1.0);
				}
			''')

            prog = GL.NewProgram([vert, frag])
            context['rotation'] = prog['rotation']

            vbo = GL.NewVertexBuffer(
                struct.pack('6f', 1.0, 0.0, -0.5, 0.86, -0.5, -0.86))
            context['vao'] = GL.NewVertexArray(prog, vbo, '2f', ['vert'])

            GL.SetUniform(prog['scale'],
                          context['height'] / context['width'] * 0.75, 0.75)

            tex = GL.NewTexture(256, 256,
                                Image.open('../DataFiles/Noise.jpg').tobytes())
            GL.UseTexture(tex)

        except GL.Error as error:
            print(error)
            exit(1)
Esempio n. 6
0
    def initializeGL(self):
        try:
            GL.Init()
            GL.Viewport(0, 0, context['width'], context['height'])

            vert = GL.NewVertexShader('''
				#version 330

				uniform vec2 pos;
				uniform float zoom;

				in vec2 vert;
				out vec2 textcoord;

				void main() {
					gl_Position = vec4(vert, 0.0, 1.0);
					textcoord = ((vert + pos) * zoom) / 2.0 + vec2(0.5, 0.5);
				}
			''')

            frag = GL.NewFragmentShader('''
				#version 330
				
				in vec2 textcoord;
				out vec4 color;

				uniform int iter;

				void main() {
					vec2 z = vec2(3.0 * (textcoord.x - 0.5), 2.0 * (textcoord.y - 0.5));
					vec2 c = vec2(0.0, 1.0);

					int i;
					for(i = 0; i < iter; i++) {
						float x = (z.x * z.x - z.y * z.y) + c.x;
						float y = (z.y * z.x + z.x * z.y) + c.y;
						if ((x * x + y * y) > 4.0) break;
						z.x = x;
						z.y = y;
					}

					float cm = fract((i == iter ? 0.0 : float(i)) * 10 / iter);
					color = vec4(fract(cm + 0.0 / 3.0), fract(cm + 1.0 / 3.0), fract(cm + 2.0 / 3.0), 1.0);
				}
			''')

            prog = GL.NewProgram([vert, frag])
            context['pos'] = prog['pos']
            context['zoom'] = prog['zoom']

            vbo = GL.NewVertexBuffer(
                struct.pack('8f', -1.0, -1.0, -1.0, 1.0, 1.0, -1.0, 1.0, 1.0))
            context['vao'] = GL.NewVertexArray(prog, vbo, '2f', ['vert'])

            GL.SetUniform(prog['iter'], 100)

        except GL.Error as error:
            print(error)
            exit(1)
Esempio n. 7
0
    def __init__(self, wnd):
        self.wnd = wnd
        self.ctx = ModernGL.create_context()

        self.prog = self.ctx.program([
            self.ctx.vertex_shader('''
                #version 330

                in vec2 in_vert;

                void main() {
                    gl_Position = vec4(in_vert, 0.0, 1.0);
                }
            '''),
            self.ctx.fragment_shader('''
                #version 330

                out vec4 f_color;

                void main() {
                    f_color = vec4(0.3, 0.5, 1.0, 1.0);
                }
            '''),
        ])

        vertices = np.array([
            0.0, 0.8,
            -0.6, -0.8,
            0.6, -0.8,
        ])

        self.vbo = self.ctx.buffer(vertices.astype('f4').tobytes())
        self.vao = self.ctx.simple_vertex_array(self.prog, self.vbo, ['in_vert'])
    def initializeGL(self):
        self.ctx = ModernGL.create_context()

        self.prog = self.ctx.program(
            vertex_shader='''
                #version 330

                uniform mat4 Mvp;

                in vec3 in_vert;
                in vec3 in_color;

                out vec3 v_color;

                void main() {
                    v_color = in_color;
                    gl_Position = Mvp * vec4(in_vert, 1.0);
                }
            '''),
            fragment_shader='''
                #version 330

                in vec3 v_color;
                out vec4 f_color;

                void main() {
                    f_color = vec4(v_color, 1.0);
                }
            '''),
Esempio n. 9
0
def main():
    '''
        Sample program to test GLWindow.
    '''

    print('GLWindow:', GLWindow.__version__)
    print('Python:', sys.version)
    print('Platform:', sys.platform)

    wnd = GLWindow.create_window((480, 480), title='GLWindow Sample')
    wnd.vsync = False

    ctx = ModernGL.create_context()

    prog = ctx.program([
        ctx.vertex_shader('''
            #version 330
            in vec2 vert;
            in vec4 vert_color;
            out vec4 frag_color;
            uniform vec2 scale;
            uniform float rotation;
            void main() {
                frag_color = vert_color;
                float r = rotation * (0.5 + gl_InstanceID * 0.05);
                mat2 rot = mat2(cos(r), sin(r), -sin(r), cos(r));
                gl_Position = vec4((rot * vert) * scale, 0.0, 1.0);
            }
        '''),
        ctx.fragment_shader('''
            #version 330
            in vec4 frag_color;
            out vec4 color;
            void main() {
                color = vec4(frag_color);
            }
        '''),
    ])

    scale = prog.uniforms['scale']
    rotation = prog.uniforms['rotation']

    vbo = ctx.buffer(struct.pack(
        '18f',
        1.0, 0.0, 1.0, 0.0, 0.0, 0.5,
        -0.5, 0.86, 0.0, 1.0, 0.0, 0.5,
        -0.5, -0.86, 0.0, 0.0, 1.0, 0.5,
    ))

    vao = ctx.simple_vertex_array(prog, vbo, ['vert', 'vert_color'])

    while wnd.update():
        wnd.clear(0.95, 0.95, 0.95)

        width, height = wnd.size
        scale.value = (height / width * 0.75, 0.75)
        ctx.viewport = wnd.viewport
        ctx.enable(ModernGL.BLEND)
        rotation.value = wnd.time
        vao.render(instances=10)
Esempio n. 10
0
    def __init__(self, wnd):
        self.wnd = wnd
        self.ctx = ModernGL.create_context()

        self.prog = self.ctx.program([
            self.ctx.vertex_shader('''
                #version 330

                uniform mat4 Mvp;

                in vec3 in_vert;

                void main() {
                    gl_Position = Mvp * vec4(in_vert, 1.0);
                }
            '''),
            self.ctx.fragment_shader('''
                #version 330

                out vec4 f_color;

                void main() {
                    f_color = vec4(0.1, 0.1, 0.1, 1.0);
                }
            '''),
        ])

        self.mvp = self.prog.uniforms['Mvp']

        self.vbo = self.ctx.buffer(grid(15, 10).astype('f4').tobytes())
        self.vao = self.ctx.simple_vertex_array(self.prog, self.vbo,
                                                ['in_vert'])
    def test_arrays(self):
        vert_src = '''
			#version %(version)s

			in %(type)s v_in[];
			out %(type)s v_out[];

			void main() {
				v_out[0] = v_in[0] * 2;
				v_out[1] = v_in[1] * 2;
			}
		'''

        for vtype in vtypes:
            try:
                prog = self.ctx.program(
                    self.ctx.vertex_shader(vert_src % vtype), ['v_out'])
            except ModernGL.Error:
                # skip when version 410 not supported
                continue

            fmt = ModernGL.detect_format(prog, ['v_in'])
            vbo1 = self.ctx.buffer(struct.pack(fmt, *(vtype['input'] * 2)))
            vbo2 = self.ctx.buffer(b'\xAA' * struct.calcsize(fmt))
            vao = self.ctx.simple_vertex_array(prog, vbo1, ['v_in'])
            vao.transform(vbo2, ModernGL.POINTS, 1)

            for a, b in zip(struct.unpack(fmt, vbo2.read()),
                            vtype['output'] * 2):
                self.assertAlmostEqual(a, b)
Esempio n. 12
0
    def __init__(self):
        self.h, self.v, self.r = 1.5, 0, 300
        self.ratio, self.dial = 1.0, 1.0
        self.pers, self.center = True, (0, 0, 0)
        self.background = 0.4, 0.4, 0.4
        self.objs = {}
        self.ctx = ModernGL.create_context()
        self.prog_suf = self.ctx.program([
            self.ctx.vertex_shader('''
                #version 330
                uniform mat4 Mvp;
                in vec3 v_vert;
                in vec3 v_norm;
                in vec3 v_color;
                out vec3 f_norm;
                out vec3 f_color;
                void main() {
                    gl_Position = Mvp * vec4(v_vert, 1);
                    f_norm = v_norm;
                    f_color = v_color;
                }
            '''),
            self.ctx.fragment_shader('''
                #version 330
                uniform vec3 light = vec3(1,1,0.8);
                uniform float blend = 1;
                in vec3 f_norm;
                in vec3 f_color;
                out vec4 color;
                void main() {
                    float d = clamp((dot(light, f_norm)+1)*0.5, 0, 1);
           			color = vec4(f_color*d, blend);
                }
			'''),
        ])
    def test_arrays(self):
        vert_src = '''
            #version %(version)s

            in %(type)s v_in[];
            out %(type)s v_out[];

            void main() {
                v_out[0] = v_in[0] + v_in[0];
                v_out[1] = v_in[1] + v_in[1];
            }
        '''

        for vtype in vtypes:
            if self.ctx.version_code < vtype['version']:
                warnings.warn('skipping version %s' % vtype['version'])
                continue

            prog = self.ctx.program(self.ctx.vertex_shader(vert_src % vtype),
                                    ['v_out'])

            if 'v_in' not in prog.attributes:
                warnings.warn('skipping %s' % vtype['type'])
                continue

            fmt = ModernGL.detect_format(prog, ['v_in'])
            vbo1 = self.ctx.buffer(struct.pack(fmt, *(vtype['input'] * 2)))
            vbo2 = self.ctx.buffer(b'\xAA' * struct.calcsize(fmt))
            vao = self.ctx.simple_vertex_array(prog, vbo1, ['v_in'])
            vao.transform(vbo2, ModernGL.POINTS, 1)

            for a, b in zip(struct.unpack(fmt, vbo2.read()),
                            vtype['output'] * 2):
                self.assertAlmostEqual(a, b)
    def __init__(self, **kwargs):
        super(CustomWidget, self).__init__(**kwargs)

        with self.canvas:
            self.ctx = ModernGL.create_context()

            self.prog = self.ctx.program(
                vertex_shader='''
                    #version 330

                    uniform mat4 Mvp;

                    in vec3 in_vert;
                    in vec3 in_color;

                    out vec3 v_color;

                    void main() {
                        v_color = in_color;
                        gl_Position = Mvp * vec4(in_vert, 1.0);
                    }
                '''),
                fragment_shader='''
                    #version 330

                    in vec3 v_color;
                    out vec4 f_color;

                    void main() {
                        f_color = vec4(v_color, 1.0);
                    }
                '''),
            ])
Esempio n. 15
0
    def setUpClass(cls):
        cls.ctx = ModernGL.create_standalone_context()

        prog = cls.ctx.program([
            cls.ctx.vertex_shader('''
                #version 330
                in vec2 vert;
                out vec2 text;
                void main() {
                    gl_Position = vec4(vert * 2.0 - 1.0, 0.0, 1.0);
                    text = vert;
                }
            '''),
            cls.ctx.fragment_shader('''
                #version 330
                uniform sampler2D Texture;
                in vec2 text;
                out vec4 color;
                void main() {
                    color = texture(Texture, text);
                }
            '''),
        ])

        vbo = cls.ctx.buffer(struct.pack('8f', 0, 0, 0, 1, 1, 0, 1, 1))
        cls.vao = cls.ctx.simple_vertex_array(prog, vbo, ['vert'])
    def initializeGL(self):
        self.ctx = ModernGL.create_context()

        prog = self.ctx.program(
            vertex_shader='''
                #version 330

                in vec2 vert;

                in vec4 vert_color;
                out vec4 frag_color;

                uniform vec2 scale;
                uniform float rotation;

                void main() {
                    frag_color = vert_color;
                    float r = rotation * (0.5 + gl_InstanceID * 0.05);
                    mat2 rot = mat2(cos(r), sin(r), -sin(r), cos(r));
                    gl_Position = vec4((rot * vert) * scale, 0.0, 1.0);
                }
            '''),
            fragment_shader='''
                #version 330

                in vec4 frag_color;
                out vec4 color;

                void main() {
                    color = vec4(frag_color);
                }
            '''),
Esempio n. 17
0
    def setUpClass(cls):
        cls.ctx = ModernGL.create_standalone_context()
        cls.vbo = cls.ctx.buffer(reserve=1024)
        cls.res = cls.ctx.buffer(reserve=1024)
        cls.vbo.clear()

        cls.shader = '''
Esempio n. 18
0
def main():
    '''
        main
    '''

    parser = argparse.ArgumentParser(prog='ModernGL')
    parser.add_argument('-v',
                        '--version',
                        action='version',
                        version='ModernGL %s' % ModernGL.__version__)
    parser.add_argument('-i', '--info', action='store_true', default=False)
    args = parser.parse_args()

    ctx = ModernGL.create_standalone_context()

    if args.info:
        print(json.dumps(ctx.info, sort_keys=True, indent=4))

    else:
        print('ModernGL:', ModernGL.__version__)
        print('Vendor:', ctx.vendor)
        print('Renderer:', ctx.renderer)
        print('Version:', ctx.version)
        print('Python:', sys.version)
        print('Platform:', sys.platform)
Esempio n. 19
0
 def initializeGL(self):
     self.ctx = ModernGL.create_context()
     self.ctx.enable(ModernGL.BLEND)
     prog = self.ctx.program([
         self.ctx.vertex_shader('''
                 #version 330
                 in vec2 vert;
                 uniform mat4 transformation;
                 uniform vec2 offset;
                 void main() {
                     vec4 tmp = transformation * vec4(vert+offset, 0, 1.0);
                     gl_Position = tmp;
                 }
         '''),
         self.ctx.fragment_shader('''
                 #version 330
                 out vec4 color;
                 void main() {
                         color = vec4(1.0, 1.0, 1.0, 0.01);
                 }
         '''),
     ])
     buf_size = self.x.nbytes + self.y.nbytes
     self.vbo = self.ctx.buffer(reserve=buf_size)
     self.win_x = 0
     self.win_y = 0
     self.win_size = 50
     self.vao = self.ctx.simple_vertex_array(prog, self.vbo, ['vert'])
     self.update_window()
     self.clear_gray = 0.9
     self.n = 0
     self.clear = False
     init_cl()
Esempio n. 20
0
    def __init__(self, **kwargs):
        super(CustomWidget, self).__init__(**kwargs)

        with self.canvas:
            self.ctx = ModernGL.create_context()

            self.prog = self.ctx.program([
                self.ctx.vertex_shader('''
                    #version 330

                    uniform vec2 WindowSize;

                    in vec2 in_vert;
                    in vec3 in_color;

                    out vec3 v_color;

                    void main() {
                        v_color = in_color;
                        gl_Position = vec4(in_vert / WindowSize * 2.0, 0.0, 1.0);
                    }
                '''),
                self.ctx.fragment_shader('''
                    #version 330

                    in vec3 v_color;
                    out vec4 f_color;

                    void main() {
                        f_color = vec4(v_color, 1.0);
                    }
                '''),
            ])

            self.window_size = self.prog.uniforms['WindowSize']

            self.vbo = self.ctx.buffer(
                struct.pack(
                    '15f',
                    0.0,
                    100.0,
                    1.0,
                    0.0,
                    0.0,
                    -86.0,
                    -50.0,
                    0.0,
                    1.0,
                    0.0,
                    86.0,
                    -50.0,
                    0.0,
                    0.0,
                    1.0,
                ))

            self.vao = self.ctx.simple_vertex_array(self.prog, self.vbo,
                                                    ['in_vert', 'in_color'])

            Callback(self.draw)
Esempio n. 21
0
    def create(cls, width, height):
        ctx = ModernGL.create_standalone_context()

        color_rbo = ctx.renderbuffer((width, height), samples=ctx.max_samples)
        fbo = ctx.framebuffer([color_rbo])
        fbo.use()

        prog = ctx.program([
            ctx.vertex_shader('''
                #version 330
                in vec3 in_vert;
                in vec4 in_color;
                out vec4 v_color;

                uniform mat4 mvp;

                void main() {
                    gl_Position = mvp * vec4(in_vert, 1.0);
                    v_color = in_color;
                }
            '''),
            ctx.fragment_shader('''
                #version 330
                in vec4 v_color;
                out vec4 f_color;
                void main() {
                    f_color = v_color;
                }
            '''),
        ])

        ctx.enable(ModernGL.BLEND)

        return cls(width, height, ctx, prog, fbo)
Esempio n. 22
0
    def setUpClass(cls):
        cls.ctx = ModernGL.create_standalone_context()

        cls.vert = cls.ctx.vertex_shader('''
            #version 330

            in vec2 in_v;
            out vec2 out_v;

            uniform Block1 {
                float x;
            };

            uniform Block2 {
                float y;
            };

            uniform Block3 {
                float z;
            };

            void main() {
                out_v = in_v * z + vec2(x, y);
            }
        ''')

        cls.prog = cls.ctx.program(cls.vert, ['out_v'])
Esempio n. 23
0
    def __init__(self, **kwargs):
        super(CustomWidget, self).__init__(**kwargs)

        with self.canvas:

            self.ctx = ModernGL.create_context()

            self.vert = vertex_shader='''
                #version 330

                in vec2 vert;

                void main() {
                    gl_Position = vec4(vert, 0.0, 1.0);
                }
            ''')

            self.frag = fragment_shader='''
                #version 330

                out vec4 color;

                void main() {
                    color = vec4(0.30, 0.50, 1.00, 1.0);
                }
            ''')

            self.prog = self.ctx.program(self.vert, self.frag])

            self.vbo = self.ctx.buffer(struct.pack('6f', 0.0, 0.8, -0.6, -0.8, 0.6, -0.8))
            self.vao = self.ctx.simple_vertex_array(self.prog, self.vbo, ['vert'])

            self.draw()

            Callback(self.draw)
Esempio n. 24
0
def main(argv=None):
    '''
        main
    '''

    parser = argparse.ArgumentParser(prog='ModernGL')
    parser.add_argument('-v',
                        '--version',
                        action='version',
                        version='ModernGL %s' % ModernGL.__version__)
    parser.add_argument('-i', '--info', action='store_true', default=False)
    args = parser.parse_args(argv)

    ctx = ModernGL.create_standalone_context()

    if args.info:
        print(json.dumps(ctx.info, sort_keys=True, indent=4))

    else:
        repo = os.path.isfile(
            os.path.join(os.path.dirname(__file__), 'README.md'))
        install = '(git repository)' if repo else '(installed)'

        print('ModernGL:', ModernGL.__version__, install)
        print('Vendor:', ctx.vendor)
        print('Renderer:', ctx.renderer)
        print('Version:', ctx.version)
        print('Python:', sys.version)
        print('Platform:', sys.platform)
Esempio n. 25
0
    def initializeGL(self):
        self.ctx = ModernGL.create_context()

        prog = self.ctx.program(
            vertex_shader='''
                #version 330

                in vec2 vert;

                in vec3 vert_color;
                out vec3 frag_color;

                uniform vec2 scale;
                uniform float rotation;

                void main() {
                    frag_color = vert_color;
                    mat2 rot = mat2(
                        cos(rotation), sin(rotation),
                        -sin(rotation), cos(rotation)
                    );
                    gl_Position = vec4((rot * vert) * scale, 0.0, 1.0);
                }
            '''),
            fragment_shader='''
                #version 330

                in vec3 frag_color;
                out vec4 color;

                void main() {
                    color = vec4(frag_color, 1.0);
                }
            '''),
Esempio n. 26
0
    def __init__(self, **kwargs):
        super(CustomWidget, self).__init__(**kwargs)

        with self.canvas:

            self.ctx = ModernGL.create_context()

            self.vert = self.ctx.vertex_shader('''
                #version 330

                in vec2 vert;

                void main() {
                    gl_Position = vec4(vert, 0.0, 1.0);
                }
            ''')

            self.frag = self.ctx.fragment_shader('''
                #version 330

                out vec4 color;

                void main() {
                    color = vec4(0.30, 0.50, 1.00, 1.0);
                }
            ''')

            self.prog = self.ctx.program([self.vert, self.frag])

            self.vbo = self.ctx.buffer(struct.pack('6f', 0.0, 0.8, -0.6, -0.8, 0.6, -0.8))
            self.vao = self.ctx.simple_vertex_array(self.prog, self.vbo, ['vert'])

            self.draw()

            Callback(self.draw)
Esempio n. 27
0
def main_loop(data_path=None,
              texture_path=None,
              vertex_path=None,
              fragment_path=None,
              object_path=None):
    global ctx

    # Loop initialization
    win = glfw_initialization()
    ctx = ModernGL.create_context()
    load_data(
        ctx,
        data_path=data_path,
        vertex_path=vertex_path,
        fragment_path=fragment_path,
        texture_path=texture_path,
        object_path=object_path,
    )

    # Display
    while not glfw.window_should_close(win):
        render_scene(win, ctx)
        glfw.swap_buffers(win)
        glfw.poll_events()

    glfw.destroy_window(win)
    glfw.terminate()
Esempio n. 28
0
def test_basic_material():
    # create context
    ctx = ModernGL.create_standalone_context()

    # create renderer
    renderer = ModernGLRenderer(ctx)

    # create scene
    scene = radiant.Scene()

    cube_geom = radiant.PlaneGeometry()
    red = radiant.MeshBasicMaterial(color=(1.0, 0.0, 0.0, 0.0))
    cube = radiant.Mesh(cube_geom, red)
    scene.append_child(cube)

    # create camera
    camera = radiant.PerspectiveCamera(position=[10, 10, 10], target=[0, 0, 0], up=[0, 1, 0])
    scene.append_child(camera)

    # create framebuffer and render into it
    fbo = ctx.framebuffer(ctx.renderbuffer((512, 512)))
    fbo.use()
    renderer.render(scene, camera)

    # read from the framebuffer and write to an image file
    data = fbo.read(components=3, alignment=1)
    img = Image.frombytes('RGB', fbo.size, data).transpose(Image.FLIP_TOP_BOTTOM)
    filename = "test_basic.png"
    with open(filename, mode="wb") as fh:
        img.save(fh)

    # complete the test
    assert os.path.exists(filename)
Esempio n. 29
0
    def initializeGL(self):
        self.ctx = ModernGL.create_context()

        prog = self.ctx.program([
            self.ctx.vertex_shader('''
                #version 330

                in vec2 vert;

                void main() {
                    gl_Position = vec4(vert, 0.0, 1.0);
                }
            '''),
            self.ctx.fragment_shader('''
                #version 330

                out vec4 color;

                void main() {
                    color = vec4(0.30, 0.50, 1.00, 1.0);
                }
            '''),
        ])

        vbo = self.ctx.buffer(
            struct.pack('6f', 0.0, 0.8, -0.6, -0.8, 0.6, -0.8))
        self.vao = self.ctx.simple_vertex_array(prog, vbo, ['vert'])
Esempio n. 30
0
    def on_ctx(self):
        self.ctx = ModernGL.create_context()
        self.prog_suf = self.ctx.program([
            self.ctx.vertex_shader('''
                #version 330
                uniform mat4 Mvp;
                in vec3 v_vert;
                in vec3 v_norm;
                in vec3 v_color;
                out vec3 f_norm;
                out vec3 f_color;
                void main() {
                    gl_Position = Mvp * vec4(v_vert, 1);
                    f_norm = v_norm;
                    f_color = v_color;
                }
            '''),
            self.ctx.fragment_shader('''
                #version 330
                uniform vec3 light = vec3(1,1,0.8);
                uniform float blend = 1;
                in vec3 f_norm;
                in vec3 f_color;
                out vec4 color;
                void main() {
                    float d = clamp((dot(light, f_norm)+1)*0.5, 0, 1);
           			color = vec4(f_color*d, blend);
                }
			'''),
        ])
        for i in self.objs.values():
            i.on_ctx(self.ctx, self.prog_suf)
Esempio n. 31
0
    def __init__(self, **kwargs):
        super(CustomWidget, self).__init__(**kwargs)

        with self.canvas:
            self.ctx = ModernGL.create_context()

            self.prog = self.ctx.program(
                vertex_shader='''
                    #version 330

                    uniform vec2 WindowSize;

                    in vec2 in_vert;
                    in vec3 in_color;

                    out vec3 v_color;

                    void main() {
                        v_color = in_color;
                        gl_Position = vec4(in_vert / WindowSize * 2.0, 0.0, 1.0);
                    }
                '''),
                fragment_shader='''
                    #version 330

                    in vec3 v_color;
                    out vec4 f_color;

                    void main() {
                        f_color = vec4(v_color, 1.0);
                    }
                '''),
            ])
Esempio n. 32
0
    def setUpClass(cls):
        cls.ctx = ModernGL.create_standalone_context()

        cls.vert = cls.ctx.vertex_shader('''
            #version 330

            in int a_in;
            in int b_in;
            in int c_in;
            in int d_in;

            out int a_out;
            out int b_out;
            out int c_out;
            out int d_out;

            void main() {
                a_out = a_in * 2;
                b_out = b_in * 2;
                c_out = c_in * 2;
                d_out = d_in * 2;
            }
        ''')

        cls.prog = cls.ctx.program(cls.vert,
                                   ['a_out', 'b_out', 'c_out', 'd_out'])
Esempio n. 33
0
def get_context() -> ModernGL.Context:
    ctx = _static.get('context')

    if ctx is None:
        ctx = ModernGL.create_standalone_context()
        _static['context'] = ctx

    return ctx
Esempio n. 34
0
 def initializeGL(self):
     self.ctx = ModernGL.create_context()
     prog = utils.create_program_from_file(self.ctx, 'shaders.json')
     pts = np.array((-0.5, -0.5, 0.0, 0.8, 0.5, -0.5)).astype(np.float32)
     self.vbo = self.ctx.buffer(pts.tobytes())
     self.vao = self.ctx.simple_vertex_array(prog, self.vbo, ['vert'])
     self.clear_gray = 0.9
     self.n = 0
Esempio n. 35
0
    def __init__(self, wnd):
        self.wnd = wnd
        self.ctx = ModernGL.create_context()

        self.prog = self.ctx.program([
            self.ctx.vertex_shader('''
                #version 330

                in vec2 in_vert;
                out vec2 v_text;

                void main() {
                    gl_Position = vec4(in_vert, 0.0, 1.0);
                    v_text = in_vert / 2.0 + 0.5;
                }
            '''),
            self.ctx.fragment_shader('''
                #version 330

                in vec2 v_text;
                out vec4 f_color;

                uniform vec2 Center;
                uniform int Iter;

                void main() {
                    vec2 z = vec2(5.0 * (v_text.x - 0.5), 3.0 * (v_text.y - 0.5));
                    vec2 c = Center;

                    int i;
                    for(i = 0; i < Iter; i++) {
                        vec2 v = vec2(
                            (z.x * z.x - z.y * z.y) + c.x,
                            (z.y * z.x + z.x * z.y) + c.y
                        );
                        if (dot(v, v) > 4.0) break;
                        z = v;
                    }

                    float cm = fract((i == Iter ? 0.0 : float(i)) * 10 / Iter);
                    f_color = vec4(
                        fract(cm + 0.0 / 3.0),
                        fract(cm + 1.0 / 3.0),
                        fract(cm + 2.0 / 3.0),
                        1.0
                    );
                }
            ''')
        ])

        self.center = self.prog.uniforms['Center']
        self.iter = self.prog.uniforms['Iter']

        vertices = np.array([-1.0, -1.0, -1.0, 1.0, 1.0, -1.0, 1.0, 1.0])

        self.vbo = self.ctx.buffer(vertices.astype('f4').tobytes())
        self.vao = self.ctx.simple_vertex_array(self.prog, self.vbo,
                                                ['in_vert'])
Esempio n. 36
0
    def run(self):
        glfw.make_context_current(self._wnd)
        self._ctx = ModernGL.create_context()

        self.initialize(self._ctx)

        while not glfw.window_should_close(self._wnd):
            width, height = self.size()
            self._ctx.viewport = (0, 0, width, height)
            self.render(self._ctx)
            glfw.swap_buffers(self._wnd)
            glfw.wait_events()
Esempio n. 37
0
    def initializeGL(self):
        self.ctx = ModernGL.create_context()

        prog = self.ctx.program(
            vertex_shader='''
                #version 330

                in vec2 vert;

                void main() {
                    gl_Position = vec4(vert, 0.0, 1.0);
                }
            '''),
            fragment_shader='''
                #version 330

                out vec4 color;

                void main() {
                    color = vec4(0.30, 0.50, 1.00, 1.0);
                }
            '''),
Esempio n. 38
0
    def initializeGL(self):
        self.ctx = ModernGL.create_context()

        img = Image.open(os.path.join(os.path.dirname(__file__), '..', 'data', 'noise.jpg'))
        texture = self.ctx.texture(img.size, 3, img.tobytes())
        texture.use()

        prog = self.ctx.program(
            vertex_shader='''
                #version 330

                in vec2 vert;
                in vec2 tex_coord;
                out vec2 v_tex_coord;

                uniform vec2 scale;
                uniform float rotation;

                void main() {
                    mat2 rot = mat2(
                        cos(rotation), sin(rotation),
                        -sin(rotation), cos(rotation)
                    );
                    gl_Position = vec4((rot * vert) * scale, 0.0, 1.0);
                    v_tex_coord = tex_coord;
                }
            '''),
            fragment_shader='''
                #version 330

                uniform sampler2D texture;

                in vec2 v_tex_coord;
                out vec4 color;

                void main() {
                    color = vec4(texture2D(texture, v_tex_coord).rgb, 1.0);
                }
            '''),
Esempio n. 39
0
def test_phong():
    # create context
    ctx = ModernGL.create_standalone_context()

    # create renderer
    renderer = ModernGLRenderer(ctx)

    # create scene
    scene = radiant.Scene()

    plane_geom = radiant.PlaneGeometry(width=2, height=2)
    red = radiant.MeshPhongMaterial(color=(0.1, 0.5, 0.3, 1.0), shininess=16.0)
    plane = radiant.Mesh(plane_geom, red)
    scene.append_child(plane)

    # create a light
    light = radiant.PointLight(position=[-0.5, -0.5, 4])
    plane.append_child(light)  # follow the plane

    # create camera
    camera = radiant.PerspectiveCamera(position=[0.5, 0.5, 2], target=[0, 0, 0], up=[0, 1, 0])
    scene.append_child(camera)

    # create framebuffer and render into it
    fbo = ctx.framebuffer(ctx.renderbuffer((512, 512)))
    fbo.use()
    renderer.render(scene, camera, light=light)

    # read from the framebuffer and write to an image file
    data = fbo.read(components=3, alignment=1)
    img = Image.frombytes('RGB', fbo.size, data).transpose(Image.FLIP_TOP_BOTTOM)
    filename = "test_phong.png"
    with open(filename, mode="wb") as fh:
        img.save(fh)

    # complete the test
    assert os.path.exists(filename)
import struct

import GLWindow
import ModernGL
from pyrr import Matrix44

wnd = GLWindow.create_window()
ctx = ModernGL.create_context()

prog = ctx.program(
    ctx.vertex_shader('''
        #version 330

        uniform mat4 Mvp;

        in vec3 in_vert;
        in vec3 in_color;

        out vec3 v_color;

        void main() {
            v_color = in_color;
            gl_Position = Mvp * vec4(in_vert, 1.0);
        }
    '''),
    ctx.fragment_shader('''
        #version 330

        in vec3 v_color;
        out vec4 f_color;
Esempio n. 41
0
import struct
import tkinter

import ModernGL
import ModernGL.tk

ctx = ModernGL.create_standalone_context()

prog = ctx.program(
    ctx.vertex_shader('''
        #version 330

        in vec2 vert;

        in vec3 vert_color;
        out vec3 frag_color;

        uniform vec2 scale;
        uniform float rotation;

        void main() {
            frag_color = vert_color;
            mat2 rot = mat2(
                cos(rotation), sin(rotation),
                -sin(rotation), cos(rotation)
            );
            gl_Position = vec4((rot * vert) * scale, 0.0, 1.0);
        }
    '''),
    ctx.fragment_shader('''
        #version 330