def __init__(self): self.ctx = mgl.create_context() self.prog = self.ctx.program( vertex_shader=''' #version 330 uniform mat4 Mvp; in vec3 in_vert; in vec3 in_norm; in vec2 in_text; out vec3 v_vert; out vec3 v_norm; out vec2 v_text; void main() { gl_Position = Mvp * vec4(in_vert, 1.0); v_vert = in_vert; v_norm = in_norm; v_text = in_text; } ''', fragment_shader=''' #version 330 uniform vec3 Light; uniform vec3 Color; uniform bool UseTexture; uniform sampler2D Texture; in vec3 v_vert; in vec3 v_norm; in vec2 v_text; out vec4 f_color; void main() { float lum = clamp(dot(normalize(Light - v_vert), normalize(v_norm)), 0.0, 1.0) * 0.8 + 0.2; if (UseTexture) { f_color = vec4(texture(Texture, v_text).rgb * lum, 1.0); } else { f_color = vec4(Color * lum, 1.0); } } ''', ) self.objects = {} for name in ['ground', 'grass', 'billboard', 'billboard-holder', 'billboard-image']: obj = Obj.open(data.find('scene-1-%s.obj' % name)) vbo = self.ctx.buffer(obj.pack('vx vy vz nx ny nz tx ty')) vao = self.ctx.simple_vertex_array(self.prog, vbo, 'in_vert', 'in_norm', 'in_text') self.objects[name] = vao img = Image.open(data.find('infographic-1.jpg')).transpose(Image.FLIP_TOP_BOTTOM).convert('RGB') self.texture = self.ctx.texture(img.size, 3, img.tobytes()) self.sampler = self.ctx.sampler(self.texture)
def __init__(self, **kwargs): super().__init__(**kwargs) self.ctx = mgl.create_context() # import gltraces # mglprocs = mgl.glprocs(self.ctx) # gltraces.glprocs[:] = mglprocs # mglprocs[:] = gltraces.gltraces self.prog = self.ctx.program( vertex_shader=''' #version 330 uniform mat4 Mvp; in vec3 in_vert; in vec3 in_norm; in vec3 in_text; out vec3 v_vert; out vec3 v_norm; out vec3 v_text; void main() { gl_Position = Mvp * vec4(in_vert, 1.0); v_vert = in_vert; v_norm = in_norm; v_text = in_text; } ''', fragment_shader=''' #version 330 uniform vec3 Light; uniform samplerCube Sampler; in vec3 v_vert; in vec3 v_norm; in vec3 v_text; out vec4 f_color; void main() { float lum = clamp(dot(normalize(Light - v_vert), normalize(v_norm)), 0.0, 1.0) * 0.8 + 0.2; f_color = vec4(texture(Sampler, normalize(v_text)).rgb * lum, 1.0); } ''', ) obj = Obj.open(data.find('texture-test-cube.obj')) self.texture = self.ctx.texture_cube((4, 4), 3, np.random.randint(128, 255, (4, 4, 3, 6), 'u1').tobytes()) self.sampler = self.ctx.sampler(self.texture, filter=mgl.LINEAR) self.vbo = self.ctx.buffer(obj.pack('vx vy vz nx ny nz tx ty tz')) self.vao = self.ctx.simple_vertex_array(self.prog, self.vbo, 'in_vert', 'in_norm', 'in_text') self.vao.scope = self.ctx.scope(mgl.DEPTH_TEST, samplers=[(self.sampler, 0)])
def __init__(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_norm; in vec2 in_text; out vec3 v_vert; out vec3 v_norm; out vec2 v_text; void main() { gl_Position = Mvp * vec4(in_vert, 1.0); v_vert = in_vert; v_norm = in_norm; v_text = in_text; } ''', fragment_shader=''' #version 330 uniform vec3 Light; uniform sampler2D Texture; in vec3 v_vert; in vec3 v_norm; in vec2 v_text; out vec4 f_color; void main() { float lum = clamp(dot(normalize(Light - v_vert), normalize(v_norm)), 0.0, 1.0) * 0.8 + 0.2; f_color = vec4(texture(Texture, v_text).rgb * lum, 1.0); } ''', ) self.mvp = self.prog['Mvp'] self.light = self.prog['Light'] obj = Obj.open(local('data', 'crate.obj')) img = Image.open(local('data', 'crate.png')).transpose(Image.FLIP_TOP_BOTTOM).convert('RGB') self.texture = self.ctx.texture(img.size, 3, img.tobytes()) self.texture.use() self.vbo = self.ctx.buffer(obj.pack('vx vy vz nx ny nz tx ty')) self.vao = self.ctx.simple_vertex_array(self.prog, self.vbo, 'in_vert', 'in_norm', 'in_text')
def __init__(self, **kwargs): super().__init__(**kwargs) self.ctx = mgl.create_context() self.prog = self.ctx.program( vertex_shader=''' #version 330 uniform mat4 Mvp; in vec3 in_vert; in vec3 in_norm; in vec2 in_text; out vec3 v_vert; out vec3 v_norm; out vec2 v_text; void main() { gl_Position = Mvp * vec4(in_vert, 1.0); v_vert = in_vert; v_norm = in_norm; v_text = in_text; } ''', fragment_shader=''' #version 330 uniform vec3 Light; uniform sampler2D Texture; in vec3 v_vert; in vec3 v_norm; in vec2 v_text; out vec4 f_color; void main() { float lum = clamp(dot(normalize(Light - v_vert), normalize(v_norm)), 0.0, 1.0) * 0.8 + 0.2; f_color = vec4(texture(Texture, v_text).rgb * lum, 1.0); } ''', ) obj = Obj.open(data.find('crate.obj')) img = Image.open(data.find('crate.png')).transpose(Image.FLIP_TOP_BOTTOM).convert('RGB') self.texture = self.ctx.texture(img.size, 3, img.tobytes()) self.sampler = self.ctx.sampler(self.texture) self.vbo = self.ctx.buffer(obj.pack('vx vy vz nx ny nz tx ty')) self.vao = self.ctx.simple_vertex_array(self.prog, self.vbo, 'in_vert', 'in_norm', 'in_text') self.vao.scope = self.ctx.scope(mgl.DEPTH_TEST, samplers=[(self.sampler, 0)])
def __init__(self, **kwargs): super().__init__(**kwargs) self.ctx = mgl.create_context() self.prog = self.ctx.program( vertex_shader=''' #version 330 uniform mat4 Mvp; in vec3 in_vert; in vec3 in_norm; in vec3 in_text; out vec3 v_vert; out vec3 v_norm; out vec3 v_text; void main() { gl_Position = Mvp * vec4(in_vert, 1.0); v_vert = in_vert; v_norm = in_norm; v_text = in_text; } ''', fragment_shader=''' #version 330 uniform vec3 Light; uniform sampler3D Sampler; in vec3 v_vert; in vec3 v_norm; in vec3 v_text; out vec4 f_color; void main() { float lum = clamp(dot(normalize(Light - v_vert), normalize(v_norm)), 0.0, 1.0) * 0.8 + 0.2; f_color = vec4(texture(Sampler, v_text).rgb * lum, 1.0); } ''', ) obj = Obj.open(data.find('texture-test-cube.obj')) self.texture = self.ctx.texture((2, 2, 2), 3, np.random.randint(128, 255, (2, 2, 2, 3), 'u1')) self.sampler = self.ctx.sampler(self.texture, wrap=mgl.REPEAT_X | mgl.REPEAT_Y | mgl.REPEAT_Z) self.vbo = self.ctx.buffer(obj.pack('vx vy vz nx ny nz tx ty tz')) self.vao = self.ctx.simple_vertex_array(self.prog, self.vbo, 'in_vert', 'in_norm', 'in_text') self.vao.scope = self.ctx.scope(mgl.DEPTH_TEST, samplers=[(self.sampler, 0)])
def loadobj(self, objfn, texfn): self.release() prog = self.ctx.program(vertex_shader=self.vert_shader, fragment_shader=self.frag_shader) prog["is_background"].value = False prog["DirLight"].value = (-1, 1, 1) prog["dir_int"].value = 0.4 prog["amb_int"].value = 1.0 self.bufs['prog'] = prog self.vs = SimpleNamespace() self.vs.proj = matrix44.create_perspective_projection( 30, 1.0, 0.1, 1000.0) self.vs.view = matrix44.create_look_at( [0, 0, 1.5], [0, 0, 0], [0, 1, 0], ) self.bufs['fbo'] = fbo fbo.use() obj = Obj.open(objfn) tmp = obj.pack('vx vy vz nx ny nz tx ty') arr = np.array(np.frombuffer(tmp, dtype='f4')).reshape((-1, 8)) # move obj center to the origin tmp = arr[:, :3] center = np.mean(tmp, axis=0) tmp -= center # scale obj to be within [-1, 1] a, b = tmp.min(), tmp.max() arr[:, :3] = tmp / (b - a) vbo = self.ctx.buffer(arr.flatten().astype("f4").tobytes()) vao = self.ctx.simple_vertex_array(self.bufs['prog'], vbo, "in_vert", "in_norm", "in_text") self.bufs['vbo'] = vbo self.bufs['vao'] = vao img = Image.open(texfn).transpose( Image.FLIP_TOP_BOTTOM).convert("RGBA") texture = self.ctx.texture(img.size, 4, img.tobytes()) texture.build_mipmaps() texture.use() self.bufs['texture'] = texture
def LoadObjFile(fullPath, rotate=False): assert sys.version_info[0] >= 3, 'only available in Python3' from objloader import Obj newFileCreated, fullPath = EnsureObjFacesInCorrectFormat(fullPath) ob = Obj.open(fullPath) verts = np.array(ob.vert) if rotate: # use this to make sure the neutral mesh aligns with 'bvhJoints_neutral' in GetMocapData.GetData() verts = verts[:,(0,2,1)] verts[:,1] *= -1 # bvhJoints_neutral = JsonToNumpyArr.MovePointsOutOfMayaCoordSystem(bvhJoints[:,:,0]) norms = np.array(ob.norm) texture = np.array(ob.text) # texture is Nx3, make Nx2 texture = texture[:,0:2] faces = ob.face if faces[0][0] == faces[0][1] and faces[0][0] == faces[0][2] or faces[0][1] is None: # faces in the file are in the format 'f 736/736/736 40/40/40 46/46/46', giving 3 entries per face. # Change it to be 1 entry of '736/40/46' faces = [face[0] for face in ob.face] numFaces = len(faces) # print('numFaces', numFaces) faces = np.array(faces) faces = np.reshape(faces, ((int(numFaces/3), 3))) # print('faces.shape', faces.shape) else: # print('else, faces[0]', faces[0]) faces = np.array(faces) faces -= 1 # start at 0 # create dict that has the same format as reading an obj, LoadObj, in Matlab obj = {} obj['vertices'] = verts obj['vertices_normal'] = norms obj['vertices_texture'] = texture objects = {} objects['type'] = 'f' data = {} data['vertices'] = faces objects['data'] = data obj['objects'] = objects return obj
def __init__(self, **kwargs): super().__init__(**kwargs) # the shader program is inherited # self.prog = self.ctx.program(...) self.prog['RenderMode'] = self.TEXTURE_WITH_LIGHT_MODE obj = Obj.open('examples/data/crate.obj') img = Image.open('examples/data/crate.png') self.texture = self.ctx.texture(img.size, 3, img.tobytes('raw', 'RGB', 0, -1)) self.sampler = self.ctx.sampler(texture=self.texture) self.vbo = self.ctx.buffer(obj.pack('vx vy vz nx ny nz tx ty')) self.vao = self.ctx.vertex_array(self.prog, self.vbo, 'in_vert', 'in_norm', 'in_text') self.vao.scope = self.ctx.scope(enable=self.ctx.DEPTH_TEST, samplers=[ self.sampler.assign(0), ])
def EnsureObjFacesInCorrectFormat(pathToObj): assert sys.version_info[0] >= 3, 'only available in Python3' from objloader import Obj ob = Obj.open(pathToObj) writeFile = True keepReading = True content = [] with open(pathToObj, 'r') as fp: line = fp.readline() cnt = 1 while line and keepReading: #print('line', line) if line[0] == 'f': splt = line.split('/') numSlashes = len(splt) -1 if numSlashes == 8: # splt eg: ['f 1931', '87', '93 1091', '88', '94 1171', '89', '95 1971', '90', '96\n'] #print('splt', splt) num1 = int(splt[0][2:]) num2_temp = int(splt[1]) if num1 == num2_temp: # the line is in the format 1/1/1 2/2/2 3/3/3 # this means we don't need to do anything to it keepReading = False writeFile = False else: a = splt[2] num2 = int(a[a.find(' ')+1:]) a = splt[4] num3 = int(a[a.find(' ')+1:]) a = splt[6] num4 = int(a[a.find(' ')+1:]) s1 = 'f %d/%d/%d %d/%d/%d %d/%d/%d\n' % (num1, num1, num1, num2, num2, num2, num3, num3, num3) s2 = 'f %d/%d/%d %d/%d/%d %d/%d/%d\n' % (num1, num1, num1, num3, num3, num3, num4, num4, num4) content.append(s1) content.append(s2) elif numSlashes == 6: # splt eg: ['f 917', '512', '797 916', '513', '798 922', '514', '799\n'] # print('splt', splt) num1 = int(splt[0][2:]) num2_temp = int(splt[1]) if num1 == num2_temp: # the line is in the format 1/1/1 2/2/2 3/3/3 # this means we don't need to do anything to it keepReading = False writeFile = False else: a = splt[2] num2 = int(a[a.find(' ')+1:]) a = splt[4] num3 = int(a[a.find(' ')+1:]) s1 = 'f %d/%d/%d %d/%d/%d %d/%d/%d\n' % (num1, num1, num1, num2, num2, num2, num3, num3, num3) content.append(s1) content.append(s2) else: # print('numSlashes', numSlashes) # print('line', line) keepReading = False writeFile = False # the file is in a correct format. Don't need to keep reading else: content.append(line) line = fp.readline() cnt += 1 newFilename = pathToObj if writeFile: oldFilename = pathToObj pathOnly = GetPathFromFullFilename(oldFilename) filenameOnly = GetFilenameFromPath(oldFilename) # extension is assumed to be '.obj' newFilename = join(pathOnly, filenameOnly + '_OLD.obj') rename(oldFilename, newFilename) with open(oldFilename, 'w') as fp: for c in content: fp.write(c) print('old file at ', newFilename) print('new file at ', oldFilename) return writeFile, newFilename
layout (location = 0) out vec4 out_color; void main() { vec3 color = vec3(1.0, 1.0, 1.0); vec3 sight = -vec3(mvp[0].w, mvp[1].w, mvp[2].w); float lum = dot(normalize(sight), normalize(in_norm)) * 0.7 + 0.3; out_color = vec4(lum, lum, lum, 1.0); } '''), vertex_format='3f 3f', vertex_count=36, bindings=[ { 'binding': 0, 'type': 'uniform_buffer', 'buffer': uniform_buffer, }, ], ) uniform_buffer.write(glnext.camera((4.0, 3.0, 2.0), (0.0, 0.0, 0.0))) pipeline.update( vertex_buffer=Obj.open('examples/cube.obj').pack('vx vy vz nx ny nz'), ) task.run() data = framebuffer.output[0].read() Image.frombuffer('RGBA', (512, 512), data, 'raw', 'RGBA', 0, -1).show()
def __init__(self, **kwargs): super().__init__(**kwargs) self.prog = self.ctx.program( vertex_shader=''' #version 330 uniform mat4 Mvp; in vec3 in_vert; in vec3 in_norm; in vec2 in_text; out vec3 v_vert; out vec3 v_norm; out vec2 v_text; void main() { gl_Position = Mvp * vec4(in_vert, 1.0); v_vert = in_vert; v_norm = in_norm; v_text = in_text; } ''', fragment_shader=''' #version 330 uniform vec3 Light; uniform vec3 Color; uniform bool UseTexture; uniform sampler2D Texture; in vec3 v_vert; in vec3 v_norm; in vec2 v_text; out vec4 f_color; void main() { float lum = clamp(dot(normalize(Light - v_vert), normalize(v_norm)), 0.0, 1.0) * 0.8 + 0.2; if (UseTexture) { f_color = vec4(texture(Texture, v_text).rgb * lum, 1.0); } else { f_color = vec4(Color * lum, 1.0); } } ''', ) self.objects = {} for name in ['ground', 'grass', 'billboard', 'billboard-holder', 'billboard-image']: obj = Obj.open(data.find('scene-1-%s.obj' % name)) vbo = self.ctx.buffer(obj.pack('vx vy vz nx ny nz tx ty')) vao = self.ctx.simple_vertex_array(self.prog, vbo, 'in_vert', 'in_norm', 'in_text') self.objects[name] = vao img = Image.open(data.find('infographic-1.jpg')).transpose(Image.FLIP_TOP_BOTTOM).convert('RGB') self.texture1 = self.ctx.texture(img.size, 3, img.tobytes()) # self.texture1.build_mipmaps() self.texture2 = self.ctx.texture(self.wnd.size, 3) depth_attachment = self.ctx.depth_renderbuffer(self.wnd.size) self.fbo = self.ctx.framebuffer(self.texture2, depth_attachment) self.sampler1 = self.ctx.sampler(self.texture1) self.sampler2 = self.ctx.sampler(self.texture2) self.scope1 = self.ctx.scope(mgl.DEPTH_TEST, self.fbo, samplers=[(self.sampler1, 0)]) self.scope2 = self.ctx.scope(mgl.DEPTH_TEST, self.ctx.screen, samplers=[(self.sampler2, 0)])
def __init__(self): self.ctx = mgl.create_context() self.canvas_prog = self.ctx.program( vertex_shader=''' #version 330 in vec2 in_vert; out vec2 v_vert; void main() { gl_Position = vec4(in_vert * 2.0 - 1.0, 0.0, 1.0); v_vert = in_vert; } ''', fragment_shader=''' #version 330 uniform sampler2D Texture; in vec2 v_vert; out vec4 f_color; void main() { f_color = texture(Texture, v_vert); } ''', ) self.prog = self.ctx.program( vertex_shader=''' #version 330 uniform mat4 Mvp; in vec3 in_vert; in vec3 in_norm; in vec2 in_text; out vec3 v_vert; out vec3 v_norm; out vec2 v_text; void main() { gl_Position = Mvp * vec4(in_vert, 1.0); v_vert = in_vert; v_norm = in_norm; v_text = in_text; } ''', fragment_shader=''' #version 330 uniform vec3 Light; uniform sampler2D Texture; in vec3 v_vert; in vec3 v_norm; in vec2 v_text; out vec4 f_color; void main() { float lum = clamp(dot(normalize(Light - v_vert), normalize(v_norm)), 0.0, 1.0) * 0.8 + 0.2; vec3 base = vec3(0.5, 0.5, 0.5) * lum; vec3 spec = vec3(1.0, 1.0, 1.0) * pow(lum, 5.7); vec4 tex = texture(Texture, v_text); f_color = vec4(base * 0.1 + tex.rgb * lum + spec, tex.a); } ''', ) self.canvas_vbo = self.ctx.buffer( np.array([0.0, 0.0, 0.0, 1.0, 1.0, 0.0, 1.0, 1.0], dtype='f4').tobytes()) self.canvas_vao = self.ctx.simple_vertex_array(self.canvas_prog, self.canvas_vbo, 'in_vert') bg_img = Image.open(data.find('mug-background.jpg')).transpose( Image.FLIP_TOP_BOTTOM).convert('RGB') self.bg_texture = self.ctx.texture(bg_img.size, 3, bg_img.tobytes()) self.bg_sampler = self.ctx.sampler(self.bg_texture) sticker_img = Image.open(data.find('mug-pymet-logo.png')).transpose( Image.FLIP_TOP_BOTTOM).convert('RGBA') self.sticker_texture = self.ctx.texture(sticker_img.size, 4, sticker_img.tobytes()) # self.sticker_texture.build_mipmaps(0, 2) self.sticker_sampler = self.ctx.sampler(self.sticker_texture) self.mug_texture = self.ctx.texture((1, 1), 3) self.mug_texture.write(struct.pack('3B', 10, 10, 10)) self.mug_sampler = self.ctx.sampler(self.mug_texture) obj = Obj.open(data.find('mug.obj')) self.mug_vbo = self.ctx.buffer(obj.pack('vx vy vz nx ny nz tx ty')) self.mug_vao = self.ctx.simple_vertex_array(self.prog, self.mug_vbo, 'in_vert', 'in_norm', 'in_text') segs = 32 radius = 29.94 bottom = 6.601 top = 57.856 left = -163.12 * np.pi / 180.0 right = 11.25 * np.pi / 180.0 lin = np.linspace(left, right, segs) sticker_vertices = np.array([ np.repeat(np.cos(lin) * radius, 2), np.repeat(np.sin(lin) * radius, 2), np.tile([bottom, top], segs), np.repeat(np.cos(lin), 2), np.repeat(np.sin(lin), 2), np.tile([0.0, 0.0], segs), np.repeat(np.linspace(0.0, 1.0, segs), 2), np.tile([0.0, 1.0], segs), ]) self.sticker_vbo = self.ctx.buffer( sticker_vertices.T.astype('f4').tobytes()) self.sticker_vao = self.ctx.simple_vertex_array( self.prog, self.sticker_vbo, 'in_vert', 'in_norm', 'in_text')
// specular vec3 viewDir = normalize(viewPos - fragPos); vec3 reflectDir = reflect(-lightDir, norm); float spec = pow(max(dot(viewDir, reflectDir), 0.0), material.shininess); vec3 specular = light.specular * spec * vec3(texture(material.specular, texCoords)); vec3 result = ambient + diffuse + specular; fragColour = vec4(result, 1.0); } ''' prog = ctx.program(vertex_shader=vs, fragment_shader=fs) glShadeModel(GL_SMOOTH) glEnable(GL_DEPTH_TEST) obj = Obj.open(Path.local('models', 'teapot.obj')) vbo = ctx.buffer(obj.pack('vx vy vz nx ny nz tx ty')) vao = ctx.simple_vertex_array(prog, vbo, 'in_vert', 'in_norm', 'in_UVs') # light properties pos = lightPos amb = Vector3([0.2, 0.2, 0.2]) diff = Vector3([0.7, 0.7, 0.7]) spec = lightCol prog['light.position'].write(pos.astype('f4').tobytes()) prog['light.ambient'].write(amb.astype('f4').tobytes()) prog['light.diffuse'].write(diff.astype('f4').tobytes()) prog['light.specular'].write(spec.astype('f4').tobytes()) # material properties img1 = Image.open(os.path.join(os.path.dirname(__file__), 'images', 'Brick_{size}x{size}.jpg'.format(size=2048))) # texture sizes: 8,16,32,64,128,256,512,1024,2048,4096
def __init__(self, **kwargs): super().__init__(**kwargs) self.obj = Obj.open( os.path.join(os.path.dirname(__file__), 'data', 'sitting_dummy.obj')) self.wood = Image.open( os.path.join(os.path.dirname(__file__), 'data', 'wood.jpg')) self.prog = self.ctx.program( vertex_shader=''' #version 330 uniform mat4 Mvp; in vec3 in_vert; in vec3 in_norm; in vec2 in_text; out vec3 v_vert; out vec3 v_norm; out vec2 v_text; void main() { v_vert = in_vert; v_norm = in_norm; v_text = in_text; gl_Position = Mvp * vec4(v_vert, 1.0); } ''', fragment_shader=''' #version 330 uniform sampler2D Texture; uniform vec4 Color; uniform vec3 Light; in vec3 v_vert; in vec3 v_norm; in vec2 v_text; out vec4 f_color; void main() { float lum = dot(normalize(v_norm), normalize(v_vert - Light)); lum = acos(lum) / 3.14159265; lum = clamp(lum, 0.0, 1.0); lum = lum * lum; lum = smoothstep(0.0, 1.0, lum); lum *= smoothstep(0.0, 80.0, v_vert.z) * 0.3 + 0.7; lum = lum * 0.8 + 0.2; vec3 color = texture(Texture, v_text).rgb; color = color * (1.0 - Color.a) + Color.rgb * Color.a; f_color = vec4(color * lum, 1.0); } ''', ) self.light = self.prog['Light'] self.color = self.prog['Color'] self.mvp = self.prog['Mvp'] self.texture = self.ctx.texture(self.wood.size, 3, self.wood.tobytes()) self.texture.build_mipmaps() self.vbo = self.ctx.buffer(self.obj.pack('vx vy vz nx ny nz tx ty')) self.vao = self.ctx.simple_vertex_array(self.prog, self.vbo, 'in_vert', 'in_norm', 'in_text')
def initGL(): ctx = moderngl.create_standalone_context() prog = ctx.program( vertex_shader=''' #version 330 uniform mat4 Mvp; in vec3 in_vert; in vec3 in_norm; in vec2 in_text; out vec3 v_vert; out vec3 v_norm; out vec2 v_text; void main() { gl_Position = Mvp * vec4(in_vert, 1.0); v_vert = in_vert; v_norm = in_norm; v_text = in_text; } ''', fragment_shader=''' #version 330 uniform vec3 Light; uniform vec3 Color; uniform bool UseTexture; uniform sampler2D Texture; in vec3 v_vert; in vec3 v_norm; in vec2 v_text; out vec4 f_color; void main() { float lum = clamp(dot(normalize(Light - v_vert), normalize(v_norm)), 0.0, 1.0) * 0.8 + 0.2; if (UseTexture) { f_color = vec4(texture(Texture, v_text).rgb * lum, 1.0); } else { f_color = vec4(Color * lum, 1.0); } } ''', ) ctx.clear(1.0, 1.0, 1.0) ctx.enable(moderngl.DEPTH_TEST) light = prog['Light'] light.value = (67.69, -8.14, 52.49) objects = {} for name in ['ground', 'grass']: obj = Obj.open('scene-1-%s.obj' % name) vbo = ctx.buffer(obj.pack('vx vy vz nx ny nz tx ty')) vao = ctx.simple_vertex_array(prog, vbo, 'in_vert', 'in_norm', 'in_text') objects[name] = vao fbo = ctx.simple_framebuffer((1280, 720)) fbo.use() return (ctx, prog, objects, fbo)
def __init__(self, **kwargs): super().__init__(**kwargs) self.prog = self.ctx.program( vertex_shader=''' #version 330 uniform mat4 Mvp; in vec3 in_vert; in vec3 in_norm; in vec2 in_text; out vec3 v_vert; out vec3 v_norm; out vec2 v_text; void main() { gl_Position = Mvp * vec4(in_vert, 1.0); v_vert = in_vert; v_norm = in_norm; v_text = in_text; } ''', fragment_shader=''' #version 330 uniform vec3 Light; uniform vec3 Color; uniform bool UseTexture; uniform sampler2D Texture; in vec3 v_vert; in vec3 v_norm; in vec2 v_text; out vec4 f_color; void main() { float lum = clamp(dot(normalize(Light - v_vert), normalize(v_norm)), 0.0, 1.0) * 0.8 + 0.2; if (UseTexture) { f_color = vec4(texture(Texture, v_text).rgb * lum, 1.0); } else { f_color = vec4(Color * lum, 1.0); } } ''', ) self.mvp = self.prog['Mvp'] self.light = self.prog['Light'] self.color = self.prog['Color'] self.use_texture = self.prog['UseTexture'] self.objects = {} for name in ['ground', 'grass', 'billboard', 'billboard-holder', 'billboard-image']: obj = Obj.open(data.find('scene-1-%s.obj' % name)) vbo = self.ctx.buffer(obj.pack('vx vy vz nx ny nz tx ty')) vao = self.ctx.simple_vertex_array(self.prog, vbo, 'in_vert', 'in_norm', 'in_text') self.objects[name] = vao figure_size = (640, 360) temp = io.BytesIO() plt.figure(0, figsize=(figure_size[0] / 72, figure_size[1] / 72)) mu, sigma = 100, 15 x = mu + sigma * np.random.randn(10000) n, bins, patches = plt.hist(x, 50, normed=1, facecolor='r', alpha=0.75) plt.axis([40, 160, 0, 0.03]) plt.grid(True) plt.show() plt.savefig(temp, format='raw', dpi=72) temp.seek(0) img = Image.frombytes('RGBA', figure_size, temp.read()).transpose(Image.FLIP_TOP_BOTTOM).convert('RGB') self.texture = self.ctx.texture(img.size, 3, img.tobytes()) self.texture.build_mipmaps()
def __init__(self, **kwargs): super().__init__(**kwargs) # import gltraces # mglprocs = mgl.glprocs(self.ctx) # gltraces.glprocs[:] = mglprocs # mglprocs[:] = gltraces.gltraces self.prog = self.ctx.program( vertex_shader=''' #version 330 uniform mat4 Mvp; in vec3 in_vert; in vec3 in_norm; out vec3 v_vert; out vec3 v_norm; void main() { gl_Position = Mvp * vec4(in_vert, 1.0); v_vert = in_vert; v_norm = in_norm; } ''', fragment_shader=''' #version 330 uniform samplerCube Sampler; uniform vec3 Eye; in vec3 v_vert; in vec3 v_norm; out vec4 f_color; void main() { f_color = texture(Sampler, reflect(v_vert - Eye, v_norm)); } ''', ) img1 = Image.new('RGB', (200, 200), '#fee') img2 = Image.new('RGB', (200, 200), '#efe') img3 = Image.new('RGB', (200, 200), '#eef') img4 = Image.new('RGB', (200, 200), '#ffe') img5 = Image.new('RGB', (200, 200), '#fef') img6 = Image.new('RGB', (200, 200), '#eff') ImageDraw.ImageDraw(img1).text((50, 30), 'i1', '#000', ImageFont.truetype('arial', 128)) ImageDraw.ImageDraw(img2).text((50, 30), 'i2', '#000', ImageFont.truetype('arial', 128)) ImageDraw.ImageDraw(img3).text((50, 30), 'i3', '#000', ImageFont.truetype('arial', 128)) ImageDraw.ImageDraw(img4).text((50, 30), 'i4', '#000', ImageFont.truetype('arial', 128)) ImageDraw.ImageDraw(img5).text((50, 30), 'i5', '#000', ImageFont.truetype('arial', 128)) ImageDraw.ImageDraw(img6).text((50, 30), 'i6', '#000', ImageFont.truetype('arial', 128)) def join(*images): return b''.join(img.tobytes('raw', 'RGB', 0, -1) for img in images) self.texture = self.ctx.texture_cube((200, 200), 3, join(img1, img2, img3, img4, img5, img6)) self.sampler = self.ctx.sampler(self.texture) self.sampler.filter = mgl.LINEAR self.sampler.use() obj = Obj.open(data.find('sitting_dummy.obj')) self.vbo = self.ctx.buffer(obj.pack('vx vy vz nx ny nz')) self.vao = self.ctx.simple_vertex_array(self.prog, self.vbo, 'in_vert', 'in_norm') self.scope = self.ctx.scope(mgl.DEPTH_TEST)
def add_drawable(model): obj = Obj.open(runner.resources.find(model)) vbo = window.ctx.buffer(obj.pack('vx vy vz nx ny nz')) vao = window.ctx.simple_vertex_array(prog, vbo, 'in_vert', 'in_norm') return {'vao': vao}
def __init__(self): self.ctx = mgl.create_context() self.prog = self.ctx.program( vertex_shader=''' #version 330 uniform mat4 Mvp; in vec3 in_vert; in vec3 in_norm; in vec3 in_color; in vec3 in_origin; in mat3 in_basis; out vec3 v_vert; out vec3 v_norm; out vec3 v_color; void main() { v_vert = in_origin + in_basis * in_vert; v_norm = in_basis * in_norm; v_color = in_color; gl_Position = Mvp * vec4(v_vert, 1.0); } ''', fragment_shader=''' #version 330 uniform vec3 Light; uniform sampler2D Texture; in vec3 v_vert; in vec3 v_norm; in vec3 v_color; out vec4 f_color; void main() { float lum = clamp(dot(normalize(Light - v_vert), normalize(v_norm)), 0.0, 1.0) * 0.8 + 0.2; f_color = vec4(v_color * lum, 1.0); } ''', ) obj = Obj.open(data.find('lowpoly_toy_car.obj')) self.vbo1 = self.ctx.buffer(obj.pack('vx vy vz nx ny nz')) self.vbo2 = self.ctx.buffer(struct.pack( '15f', 1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, ) * len(cars)) self.vao = self.ctx.vertex_array(self.prog, [ (self.vbo1, '3f 3f', 'in_vert', 'in_norm'), (self.vbo2, '3f 3f 9f/i', 'in_color', 'in_origin', 'in_basis'), ])
def __init__(self, **kwargs): super().__init__(**kwargs) self.canvas_prog = self.ctx.program( vertex_shader=''' #version 330 in vec2 in_vert; out vec2 v_vert; void main() { gl_Position = vec4(in_vert * 2.0 - 1.0, 0.0, 1.0); v_vert = in_vert; } ''', fragment_shader=''' #version 330 uniform sampler2D Texture; in vec2 v_vert; out vec4 f_color; void main() { f_color = texture(Texture, v_vert); } ''', ) self.prog = self.ctx.program( vertex_shader=''' #version 330 uniform mat4 Mvp; in vec3 in_vert; in vec3 in_norm; in vec2 in_text; out vec3 v_vert; out vec3 v_norm; out vec2 v_text; void main() { gl_Position = Mvp * vec4(in_vert, 1.0); v_vert = in_vert; v_norm = in_norm; v_text = in_text; } ''', fragment_shader=''' #version 330 uniform vec3 Light; uniform sampler2D Texture; in vec3 v_vert; in vec3 v_norm; in vec2 v_text; out vec4 f_color; void main() { float lum = clamp(dot(normalize(Light - v_vert), normalize(v_norm)), 0.0, 1.0) * 0.8 + 0.2; vec3 base = vec3(0.5, 0.5, 0.5) * lum; vec3 spec = vec3(1.0, 1.0, 1.0) * pow(lum, 5.7); vec4 tex = texture(Texture, v_text); f_color = vec4(base * 0.1 + tex.rgb * lum + spec, tex.a); } ''', ) self.canvas_vbo = self.ctx.buffer(np.array([0.0, 0.0, 0.0, 1.0, 1.0, 0.0, 1.0, 1.0], dtype='f4').tobytes()) self.canvas_vao = self.ctx.simple_vertex_array(self.canvas_prog, self.canvas_vbo, 'in_vert') bg_img = Image.open(data.find('mug-background.jpg')).transpose(Image.FLIP_TOP_BOTTOM).convert('RGB') self.bg_texture = self.ctx.texture(bg_img.size, 3, bg_img.tobytes()) self.mvp = self.prog['Mvp'] self.light = self.prog['Light'] sticker_img = Image.open(data.find('mug-pymet-logo.png')).transpose(Image.FLIP_TOP_BOTTOM).convert('RGBA') self.sticker_texture = self.ctx.texture(sticker_img.size, 4, sticker_img.tobytes()) self.sticker_texture.build_mipmaps(0, 2) self.mug_texture = self.ctx.texture((1, 1), 3) self.mug_texture.write(struct.pack('3B', 10, 10, 10)) obj = Obj.open(data.find('mug.obj')) self.mug_vbo = self.ctx.buffer(obj.pack('vx vy vz nx ny nz tx ty')) self.mug_vao = self.ctx.simple_vertex_array(self.prog, self.mug_vbo, 'in_vert', 'in_norm', 'in_text') segs = 32 radius = 29.94 bottom = 6.601 top = 57.856 left = -163.12 * np.pi / 180.0 right = 11.25 * np.pi / 180.0 lin = np.linspace(left, right, segs) sticker_vertices = np.array([ np.repeat(np.cos(lin) * radius, 2), np.repeat(np.sin(lin) * radius, 2), np.tile([bottom, top], segs), np.repeat(np.cos(lin), 2), np.repeat(np.sin(lin), 2), np.tile([0.0, 0.0], segs), np.repeat(np.linspace(0.0, 1.0, segs), 2), np.tile([0.0, 1.0], segs), ]) self.sticker_vbo = self.ctx.buffer(sticker_vertices.T.astype('f4').tobytes()) self.sticker_vao = self.ctx.simple_vertex_array(self.prog, self.sticker_vbo, 'in_vert', 'in_norm', 'in_text')
#默认的输出图片文件名 if (len(sys.argv) > 1): filename = sys.argv[1] else: filename = "output.png" #模型加载目录 obj_path = "./models/spot/" #创建一个像素着色器,用来计算具体像素的值 if (len(sys.argv) > 3): fragment_shader = Shader(sys.argv[2], obj_path + sys.argv[3]) else: fragment_shader = Shader(sys.argv[2], obj_path + "spot_texture.png") #一个数组,记录了模型的各个顶点,每个顶点的信息(分先后)为顶点坐标,法向量坐标,纹理坐标(加了一个0.扩展到三维) obj = Obj.open(obj_path + "spot_triangulated_good.obj").to_array() #用来记录键盘输入的键值 key = 0 #旋转变换的角度 angle = 140. f1 = (50 - 0.1) / 2.0 f2 = (50 + 0.1) / 2.0 #只经过了modle和view变换 mv = get_view(eye_pos).dot(get_model(angle)) #model和view变换的矩阵的逆矩阵的转置矩阵 inv_trans = np.linalg.inv(mv).T #mvp变换矩阵 mvp = get_projection(45, 1, 0.1, 50).dot(mv) points = [] for i in range(0, len(obj), 3): points.clear()
def start(self): if not glfw.init(): print("Could not initialize OpenGL context") exit(1) glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 3) glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 3) glfw.window_hint(glfw.OPENGL_FORWARD_COMPAT, True) glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE) #glfw.window_hint(glfw.RESIZABLE, self.resizable) glfw.window_hint(glfw.DOUBLEBUFFER, True) glfw.window_hint(glfw.DEPTH_BITS, 24) #glfw.window_hint(glfw.SAMPLES, 1) glfw.window_hint(glfw.DECORATED, False) monitor = None ''' if self.fullscreen: # Use the primary monitors current resolution monitor = glfw.get_primary_monitor() self.width, self.height = mode.size.width, mode.size.height mode = glfw.get_video_mode(monitor) ''' self.window = glfw.create_window(self.width, self.height, self.window_name, monitor, None) if not self.window: glfw.terminate() raise ValueError("Failed to create window") ''' if not self.cursor: glfw.set_input_mode(self.window, glfw.CURSOR, glfw.CURSOR_DISABLED) ''' glfw.set_window_pos(self.window, 40, 40) # Get the actual buffer size of the window # This is important for some displays like Apple's Retina as reported window sizes are virtual self.buffer_width, self.buffer_height = glfw.get_framebuffer_size(self.window) #print("Frame buffer size:", self.buffer_width, self.buffer_height) #print("Actual window size:", glfw.get_window_size(self.window)) glfw.make_context_current(self.window) # The number of screen updates to wait from the time glfwSwapBuffers # was called before swapping the buffers and returning if self.bVsync: glfw.swap_interval(1) glfw.set_key_callback(self.window, self.key_event_callback) #glfw.set_cursor_pos_callback(self.window, self.mouse_event_callback) #glfw.set_window_size_callback(self.window, self.window_resize_callback) # Create mederngl context from existing context self.ctx = moderngl.create_context(require=330) self.fbo = self.ctx.screen #self.ctx.viewport = self.window.viewport #self.set_default_viewport() #print("Wow ! GL_SHADING_LANGUAGE_VERSION :", gl.glGetString(gl.GL_SHADING_LANGUAGE_VERSION)) ''' self.proj = Matrix44.perspective_projection(45.0, float(self.width)/float(self.height), 0.1, 1000.0) self.lookat = Matrix44.look_at( (0.0, 0.0, 10.0), (0.0, 0.0, 0.0), (0.0, -1.0, 0.0), ) ''' left = 0 #-float(self.width) right = float(self.width) top = 0 #float(self.height) bottom = -float(self.height) near = 1.0 far = 1000.0 self.proj = Matrix44.orthogonal_projection(left, right, bottom, top, near, far) self.lookat = Matrix44.look_at( (0.0, 0.0, -10.0), (0.0, 0.0, 0.0), (0.0, -1.0, 0.0), ) self.prog = self.ctx.program( vertex_shader=''' #version 330 uniform mat4 MVP; //in vec3 in_vert; in vec2 in_vert; in vec2 in_text; out vec2 v_text; void main() { //gl_Position = MVP * vec4(in_vert, 1.0); gl_Position = MVP * vec4(in_vert, 0.0, 1.0); v_text = in_text; } ''', fragment_shader=''' #version 330 uniform sampler2D Texture; in vec2 v_text; out vec4 f_color; void main() { //f_color = vec4(0.3, 0.5, 1.0, 1.0); f_color = vec4(texture(Texture, v_text).rgb, 1.0); } ''', ) self.mvp = self.prog['MVP'] img_left = Image.open(local('assets', 'l.png')).convert('RGB') self.texture_left = self.ctx.texture(img_left.size, 3, img_left.tobytes()) #self.texture_left.build_mipmaps() #img_right = Image.open(local('assets', 'r.png')).convert('RGB') #self.texture_right = self.ctx.texture(img_right.size, 3, img_right.tobytes()) #self.texture_right.build_mipmaps() texSize = (1024,1024) self.texture_left = self.ctx.texture((1024,1024), 3) depth_attachment_left = self.ctx.depth_renderbuffer(texSize) self.fbo_left = self.ctx.framebuffer(self.texture_left, depth_attachment_left) self.texture_right = self.ctx.texture((1024,1024), 3) depth_attachment_right = self.ctx.depth_renderbuffer(texSize) self.fbo_right = self.ctx.framebuffer(self.texture_right, depth_attachment_right) vertices_left_quad = np.array([ 0.0, 0.0, 0.0,1.0, 0.0, self.height, 0.0,0.0, self.width/2, 0.0, 1.0,1.0, self.width/2, self.height, 1.0,0.0 ]) self.vbo_left_quad = self.ctx.buffer(vertices_left_quad.astype('f4').tobytes()) self.vao_left_quad = self.ctx.simple_vertex_array(self.prog, self.vbo_left_quad, 'in_vert', 'in_text') vertices_right_quad = np.array([ self.width/2, 0.0, 0.0,1.0, self.width/2, self.height, 0.0,0.0, self.width, 0.0, 1.0,1.0, self.width, self.height, 1.0,0.0 ]) self.vbo_right_quad = self.ctx.buffer(vertices_right_quad.astype('f4').tobytes()) self.vao_right_quad = self.ctx.simple_vertex_array(self.prog, self.vbo_right_quad, 'in_vert', 'in_text') ##### # Persp scene self.proj_sample = Matrix44.perspective_projection(45.0, self.width / self.height, 0.1, 1000.0) self.proj_sample_stereo = Matrix44.perspective_projection(45.0, (self.width/2) / self.height, 0.1, 1000.0) self.lookat_sample = Matrix44.look_at( (50.0, 20.0, 30.0), (0.0, 0.0, 10.0), (0.0, 0.0, 1.0), ) self.prog_sample = self.ctx.program( vertex_shader=''' #version 330 uniform mat4 MVP; in vec3 in_vert; in vec3 in_norm; in vec2 in_text; out vec3 v_vert; out vec3 v_norm; out vec2 v_text; void main() { gl_Position = MVP * vec4(in_vert, 1.0); v_vert = in_vert; v_norm = in_norm; v_text = in_text; } ''', fragment_shader=''' #version 330 uniform vec3 Light; uniform vec3 Color; uniform bool UseTexture; uniform sampler2D Texture; in vec3 v_vert; in vec3 v_norm; in vec2 v_text; out vec4 f_color; void main() { float lum = clamp(dot(normalize(Light - v_vert), normalize(v_norm)), 0.0, 1.0) * 0.8 + 0.2; if (UseTexture) { f_color = vec4(texture(Texture, v_text).rgb * lum, 1.0); } else { f_color = vec4(Color * lum, 1.0); } } ''', ) self.objects = {} for name in ['ground', 'grass', 'billboard', 'billboard-holder', 'billboard-image']: obj = Obj.open(local('assets', 'scene-1-%s.obj' % name)) vbo = self.ctx.buffer(obj.pack('vx vy vz nx ny nz tx ty')) vao = self.ctx.simple_vertex_array(self.prog_sample, vbo, 'in_vert', 'in_norm', 'in_text') self.objects[name] = vao img = Image.open(local('assets', 'infographic-1.jpg')).transpose(Image.FLIP_TOP_BOTTOM).convert('RGB') self.texture_sample = self.ctx.texture(img.size, 3, img.tobytes()) self.texture_sample.build_mipmaps() self.mvp_sample = self.prog_sample['MVP'] self.bUseTexture_sample = self.prog_sample['UseTexture'] self.light_sample = self.prog_sample['Light'] self.color_sample = self.prog_sample['Color']
def __init__(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_norm; in vec2 in_text; out vec3 v_vert; out vec3 v_norm; out vec2 v_text; void main() { gl_Position = Mvp * vec4(in_vert, 1.0); v_vert = in_vert; v_norm = in_norm; v_text = in_text; } ''', fragment_shader=''' #version 330 uniform vec3 Light; uniform vec3 Color; uniform bool UseTexture; uniform sampler2D Texture; in vec3 v_vert; in vec3 v_norm; in vec2 v_text; out vec4 f_color; void main() { float lum = clamp(dot(normalize(Light - v_vert), normalize(v_norm)), 0.0, 1.0) * 0.8 + 0.2; if (UseTexture) { f_color = vec4(texture(Texture, v_text).rgb * lum, 1.0); } else { f_color = vec4(Color * lum, 1.0); } } ''', ) self.mvp = self.prog['Mvp'] self.light = self.prog['Light'] self.color = self.prog['Color'] self.use_texture = self.prog['UseTexture'] self.objects = {} for name in [ 'ground', 'grass', 'billboard', 'billboard-holder', 'billboard-image' ]: obj = Obj.open(local('data', 'scene-1-%s.obj' % name)) vbo = self.ctx.buffer(obj.pack('vx vy vz nx ny nz tx ty')) vao = self.ctx.simple_vertex_array(self.prog, vbo, 'in_vert', 'in_norm', 'in_text') self.objects[name] = vao figure_size = (640, 360) temp = io.BytesIO() plt.figure(0, figsize=(figure_size[0] / 72, figure_size[1] / 72)) mu, sigma = 100, 15 x = mu + sigma * np.random.randn(10000) n, bins, patches = plt.hist(x, 50, normed=1, facecolor='r', alpha=0.75) plt.axis([40, 160, 0, 0.03]) plt.grid(True) plt.show() plt.savefig(temp, format='raw', dpi=72) temp.seek(0) img = Image.frombytes('RGBA', figure_size, temp.read()).transpose( Image.FLIP_TOP_BOTTOM).convert('RGB') self.texture = self.ctx.texture(img.size, 3, img.tobytes()) self.texture.build_mipmaps()
def __init__(self, **kwargs): super().__init__(**kwargs) self.prog = self.ctx.program( vertex_shader=''' #version 330 uniform mat4 Mvp; in vec3 in_vert; in vec3 in_norm; in vec2 in_text; out vec3 v_vert; out vec3 v_norm; out vec2 v_text; void main() { gl_Position = Mvp * vec4(in_vert, 1.0); v_vert = in_vert; v_norm = in_norm; v_text = in_text; } ''', fragment_shader=''' #version 330 uniform vec3 Light; uniform vec3 Color; uniform bool UseTexture; uniform sampler2D Texture; in vec3 v_vert; in vec3 v_norm; in vec2 v_text; out vec4 f_color; void main() { float lum = clamp(dot(normalize(Light - v_vert), normalize(v_norm)), 0.0, 1.0) * 0.8 + 0.2; if (UseTexture) { f_color = vec4(texture(Texture, v_text).rgb * lum, 1.0); } else { f_color = vec4(Color * lum, 1.0); } } ''', ) self.objects = {} for name in [ 'ground', 'grass', 'billboard', 'billboard-holder', 'billboard-image' ]: obj = Obj.open(data.find('scene-1-%s.obj' % name)) vbo = self.ctx.buffer(obj.pack('vx vy vz nx ny nz tx ty')) vao = self.ctx.simple_vertex_array(self.prog, vbo, 'in_vert', 'in_norm', 'in_text') self.objects[name] = vao img = Image.open(data.find('infographic-1.jpg')).transpose( Image.FLIP_TOP_BOTTOM).convert('RGB') self.texture1 = self.ctx.texture(img.size, 3, img.tobytes()) # self.texture1.build_mipmaps() self.texture2 = self.ctx.texture(self.wnd.size, 3) depth_attachment = self.ctx.depth_renderbuffer(self.wnd.size) self.fbo = self.ctx.framebuffer(self.texture2, depth_attachment) self.sampler1 = self.ctx.sampler(self.texture1) self.sampler2 = self.ctx.sampler(self.texture2) self.scope1 = self.ctx.scope(mgl.DEPTH_TEST, self.fbo, samplers=[(self.sampler1, 0)]) self.scope2 = self.ctx.scope(mgl.DEPTH_TEST, self.ctx.screen, samplers=[(self.sampler2, 0)])
def __init__(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_norm; in vec3 in_color; in vec3 in_origin; in mat3 in_basis; out vec3 v_vert; out vec3 v_norm; out vec3 v_color; void main() { v_vert = in_origin + in_basis * in_vert; v_norm = in_basis * in_norm; v_color = in_color; gl_Position = Mvp * vec4(v_vert, 1.0); } ''', fragment_shader=''' #version 330 uniform vec3 Light; uniform sampler2D Texture; in vec3 v_vert; in vec3 v_norm; in vec3 v_color; out vec4 f_color; void main() { float lum = clamp(dot(normalize(Light - v_vert), normalize(v_norm)), 0.0, 1.0) * 0.8 + 0.2; f_color = vec4(v_color * lum, 1.0); } ''', ) self.mvp = self.prog['Mvp'] self.light = self.prog['Light'] obj = Obj.open(local('data', 'lowpoly_toy_car.obj')) self.vbo1 = self.ctx.buffer(obj.pack('vx vy vz nx ny nz')) self.vbo2 = self.ctx.buffer( struct.pack( '15f', 1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, ) * len(cars)) self.vao = self.ctx.vertex_array(self.prog, [ (self.vbo1, '3f 3f', 'in_vert', 'in_norm'), (self.vbo2, '3f 3f 9f/i', 'in_color', 'in_origin', 'in_basis'), ])
def __init__(self, **kwargs): super().__init__(**kwargs) self.prog = self.ctx.program( vertex_shader=''' #version 330 uniform mat4 Mvp; in vec3 in_vert; in vec3 in_norm; in vec3 in_color; in vec2 in_text; out vec3 v_vert; out vec3 v_norm; out vec3 v_color; out vec2 v_text; void main() { gl_Position = Mvp * vec4(in_vert, 1.0); v_vert = in_vert; v_norm = in_norm; v_color = in_color; v_text = in_text; } ''', fragment_shader=''' #version 330 uniform sampler2D Texture; uniform int RenderMode; uniform vec3 Color; uniform vec3 Light; in vec3 v_vert; in vec3 v_norm; in vec3 v_color; in vec2 v_text; out vec4 f_color; void main() { float lum = 0.2 + 0.8* abs(dot(normalize(Light - v_vert), normalize(v_norm))); if (RenderMode == 0) { f_color = vec4(Color, 0.4); } else if (RenderMode == 1) { f_color = vec4(Color * lum, 0.4); } else if (RenderMode == 2) { f_color = vec4(v_color * lum, 0.4); } else if (RenderMode == 3) { f_color = texture(Texture, v_text) * vec4(lum, lum, lum, 0.4); } } ''', ) self.mvp = self.prog['Mvp'] self.light = self.prog['Light'] self.renderMode=self.prog['RenderMode'] self.color=self.prog['Color'] obj = Obj.open(r'Recorde.obj') self.vbo = self.ctx.buffer(obj.pack('vx vy vz nx ny nz')) self.vao = self.ctx.vertex_array(self.prog, self.vbo, 'in_vert','in_norm')
def __init__(self): self.ctx = mgl.create_context() self.prog = self.ctx.program( vertex_shader=''' #version 330 uniform mat4 Mvp; in vec3 in_vert; in vec3 in_norm; in vec2 in_text; out vec3 v_vert; out vec3 v_norm; out vec2 v_text; void main() { gl_Position = Mvp * vec4(in_vert, 1.0); v_vert = in_vert; v_norm = in_norm; v_text = in_text; } ''', fragment_shader=''' #version 330 uniform vec3 Light; uniform vec3 Color; uniform bool UseTexture; uniform sampler2D Texture; in vec3 v_vert; in vec3 v_norm; in vec2 v_text; out vec4 f_color; void main() { float lum = clamp(dot(normalize(Light - v_vert), normalize(v_norm)), 0.0, 1.0) * 0.8 + 0.2; if (UseTexture) { f_color = vec4(texture(Texture, v_text).rgb * lum, 1.0); } else { f_color = vec4(Color * lum, 1.0); } } ''', ) self.objects = {} for name in [ 'ground', 'grass', 'billboard', 'billboard-holder', 'billboard-image' ]: obj = Obj.open(local('data', 'scene-1-%s.obj' % name)) vbo = self.ctx.buffer(obj.pack('vx vy vz nx ny nz tx ty')) vao = self.ctx.simple_vertex_array(self.prog, vbo, 'in_vert', 'in_norm', 'in_text') self.objects[name] = vao img = Image.open(local('data', 'infographic-1.jpg')).transpose( Image.FLIP_TOP_BOTTOM).convert('RGB') self.texture = self.ctx.texture(img.size, 3, img.tobytes()) self.sampler = self.ctx.sampler(self.texture)
import glnext import numpy as np from glnext_compiler import glsl from matplotlib import pyplot as plt from objloader import Obj instance = glnext.instance() task = instance.task() framebuffer = task.framebuffer((512, 512), '1f', samples=1) vertex_size = 12 mesh = Obj.open('examples/monkey.obj').pack('vx vy vz') vertex_count = len(mesh) // vertex_size pipeline = framebuffer.render( vertex_shader=glsl(''' #version 450 #pragma shader_stage(vertex) layout (binding = 0) uniform Buffer { mat4 mvp; }; layout (location = 0) in vec3 in_vert; layout (location = 0) out float out_depth; void main() { vec4 vert = mvp * vec4(in_vert, 1.0); gl_Position = vert;
def __init__(self): self.ctx = moderngl.create_context() self.prog = self.ctx.program( vertex_shader=''' #version 330 uniform mat4 Mvp; in vec3 in_move; in vec3 in_vert; in vec3 in_norm; in vec2 in_text; out vec3 v_vert; out vec3 v_norm; out vec2 v_text; void main() { gl_Position = Mvp * vec4(in_vert + in_move, 1.0); v_vert = in_vert + in_move; v_norm = in_norm; v_text = in_text; } ''', fragment_shader=''' #version 330 uniform vec3 Light; uniform sampler2D Texture; in vec3 v_vert; in vec3 v_norm; in vec2 v_text; out vec4 f_color; void main() { float lum = clamp(dot(normalize(Light - v_vert), normalize(v_norm)), 0.0, 1.0) * 0.8 + 0.2; f_color = vec4(texture(Texture, v_text).rgb * lum, 1.0); } ''', ) self.mvp = self.prog['Mvp'] self.light = self.prog['Light'] obj = Obj.open(local('data', 'crate.obj')) img = Image.open(local('data', 'crate.png')).transpose(Image.FLIP_TOP_BOTTOM).convert('RGB') self.texture = self.ctx.texture(img.size, 3, img.tobytes()) self.texture.build_mipmaps() self.texture.use() self.vbo1 = self.ctx.buffer(obj.pack('vx vy vz nx ny nz tx ty')) self.vbo2 = self.ctx.buffer(reserve=12 * 1024) self.vao = self.ctx.vertex_array(self.prog, [ (self.vbo1, '3f 3f 2f', 'in_vert', 'in_norm', 'in_text'), (self.vbo2, '3f/i', 'in_move'), ]) self.crate_a = np.random.uniform(0.7, 0.8, 32 * 32) self.crate_b = np.random.uniform(0.0, 6.3, 32 * 32) self.crate_x = (np.tile(np.arange(32), 32) - 16) * 1.5 self.crate_y = (np.repeat(np.arange(32), 32) - 16) * 1.5 self.crate_x += np.random.uniform(-0.2, 0.2, 32 * 32) self.crate_y += np.random.uniform(-0.2, 0.2, 32 * 32)
def __init__(self, **kwargs): super().__init__(**kwargs) self.obj = Obj.open(os.path.join(os.path.dirname(__file__), 'data', 'sitting_dummy.obj')) self.wood = Image.open(os.path.join(os.path.dirname(__file__), 'data', 'wood.jpg')) self.prog = self.ctx.program( vertex_shader=''' #version 330 uniform mat4 Mvp; in vec3 in_vert; in vec3 in_norm; in vec2 in_text; out vec3 v_vert; out vec3 v_norm; out vec2 v_text; void main() { v_vert = in_vert; v_norm = in_norm; v_text = in_text; gl_Position = Mvp * vec4(v_vert, 1.0); } ''', fragment_shader=''' #version 330 uniform sampler2D Texture; uniform vec4 Color; uniform vec3 Light; in vec3 v_vert; in vec3 v_norm; in vec2 v_text; out vec4 f_color; void main() { float lum = dot(normalize(v_norm), normalize(v_vert - Light)); lum = acos(lum) / 3.14159265; lum = clamp(lum, 0.0, 1.0); lum = lum * lum; lum = smoothstep(0.0, 1.0, lum); lum *= smoothstep(0.0, 80.0, v_vert.z) * 0.3 + 0.7; lum = lum * 0.8 + 0.2; vec3 color = texture(Texture, v_text).rgb; color = color * (1.0 - Color.a) + Color.rgb * Color.a; f_color = vec4(color * lum, 1.0); } ''', ) self.light = self.prog['Light'] self.color = self.prog['Color'] self.mvp = self.prog['Mvp'] self.texture = self.ctx.texture(self.wood.size, 3, self.wood.tobytes()) self.texture.build_mipmaps() self.vbo = self.ctx.buffer(self.obj.pack('vx vy vz nx ny nz tx ty')) self.vao = self.ctx.simple_vertex_array(self.prog, self.vbo, 'in_vert', 'in_norm', 'in_text')
def __init__(self): self.ctx = mgl.create_context() # import gltraces # mglprocs = mgl.glprocs(self.ctx) # gltraces.glprocs[:] = mglprocs # mglprocs[:] = gltraces.gltraces self.prog = self.ctx.program( vertex_shader=''' #version 330 uniform mat4 Mvp; in vec3 in_vert; in vec3 in_norm; in vec2 in_text; out vec3 v_vert; out vec3 v_norm; out vec2 v_text; void main() { gl_Position = Mvp * vec4(in_vert, 1.0); v_vert = in_vert; v_norm = in_norm; v_text = in_text; } ''', fragment_shader=''' #version 330 uniform vec3 Light; uniform sampler2D Texture; in vec3 v_vert; in vec3 v_norm; in vec2 v_text; out vec4 f_color; void main() { float lum = clamp(dot(normalize(Light - v_vert), normalize(v_norm)), 0.0, 1.0) * 0.8 + 0.2; f_color = vec4(texture(Texture, v_text).rgb * lum, 1.0); } ''', ) obj1 = Obj.open(data.find('crate_left.obj')) obj2 = Obj.open(data.find('crate.obj')) obj3 = Obj.open(data.find('crate_right.obj')) img1 = Image.open(data.find('crate.png')).transpose(Image.FLIP_TOP_BOTTOM).convert('RGB') img2 = Image.open(data.find('rock.jpg')).transpose(Image.FLIP_TOP_BOTTOM).convert('RGB') self.texture1 = self.ctx.texture(img1) self.texture2 = self.ctx.texture(img2) self.sampler1 = self.ctx.sampler(self.texture1) self.sampler2 = self.ctx.sampler(self.texture2) self.vbo1 = self.ctx.buffer(obj1.pack('vx vy vz nx ny nz tx ty')) self.vbo2 = self.ctx.buffer(obj2.pack('vx vy vz nx ny nz tx ty')) self.vbo3 = self.ctx.buffer(obj3.pack('vx vy vz nx ny nz tx ty')) self.vao1 = self.ctx.simple_vertex_array(self.prog, self.vbo1, 'in_vert', 'in_norm', 'in_text') self.vao1.scope = self.ctx.scope(mgl.DEPTH_TEST, samplers=[(self.sampler2, 0)]) self.vao2 = self.ctx.simple_vertex_array(self.prog, self.vbo2, 'in_vert', 'in_norm', 'in_text') self.vao2.scope = self.ctx.scope(mgl.DEPTH_TEST, samplers=[(self.sampler1, 0)]) self.vao3 = self.ctx.simple_vertex_array(self.prog, self.vbo3, 'in_vert', 'in_norm', 'in_text') self.vao3.scope = self.ctx.scope(mgl.DEPTH_TEST, samplers=[(self.sampler2, 0)]) with self.ctx.recorder: self.ctx.clear(1.0, 1.0, 1.0) self.vao1.render() self.vao2.render() self.vao3.render() self.bytecode = self.ctx.recorder.dump() print(self.bytecode)
def __init__(self, **kwargs): super().__init__(**kwargs) # import gltraces # mglprocs = mgl.glprocs(self.ctx) # gltraces.glprocs[:] = mglprocs # mglprocs[:] = gltraces.gltraces self.prog = self.ctx.program( vertex_shader=''' #version 330 uniform mat4 Mvp; in vec3 in_vert; in vec3 in_norm; in vec2 in_text; out vec3 v_vert; out vec3 v_norm; out vec2 v_text; void main() { gl_Position = Mvp * vec4(in_vert, 1.0); v_vert = in_vert; v_norm = in_norm; v_text = in_text; } ''', fragment_shader=''' #version 330 uniform vec3 Light; uniform vec3 Color; uniform bool UseTexture; uniform sampler2D Texture; in vec3 v_vert; in vec3 v_norm; in vec2 v_text; out vec4 f_color; void main() { float lum = clamp(dot(normalize(Light - v_vert), normalize(v_norm)), 0.0, 1.0) * 0.8 + 0.2; if (UseTexture) { f_color = vec4(texture(Texture, v_text).rgb * lum, 1.0); } else { f_color = vec4(Color * lum, 1.0); } } ''', ) self.compute = self.ctx.compute_shader(''' #version 430 layout (local_size_x = 16, local_size_y = 16) in; layout(rg32f,location=0) writeonly uniform image2D destTex; uniform float time; void main() { ivec2 ij = ivec2(gl_GlobalInvocationID.xy); float localCoef = length(vec2(ivec2(gl_LocalInvocationID.xy)-8)/8.0); float globalCoef = sin(float(gl_WorkGroupID.x+gl_WorkGroupID.y)*0.1 + time)*0.5; imageStore(destTex, ij, vec4(1.0-globalCoef*localCoef, 0.0, 0.0, 0.0)); } ''') self.objects = {} for name in ['ground', 'grass', 'billboard', 'billboard-holder', 'billboard-image']: obj = Obj.open(data.find('scene-1-%s.obj' % name)) vbo = self.ctx.buffer(obj.pack('vx vy vz nx ny nz tx ty')) vao = self.ctx.simple_vertex_array(self.prog, vbo, 'in_vert', 'in_norm', 'in_text') self.objects[name] = vao img = Image.new('RGB', (512, 512)) self.texture = self.ctx.texture(img.size, 3, img.tobytes()) self.sampler = self.ctx.sampler(self.texture) self.scope = self.ctx.scope(mgl.DEPTH_TEST, self.ctx.screen, samplers=[(self.sampler, 0)])
def __init__(self, **kwargs): super().__init__(**kwargs) self.prog = self.ctx.program( vertex_shader=''' #version 330 uniform mat4 Mvp; in vec3 in_move; in vec3 in_vert; in vec3 in_norm; in vec2 in_text; out vec3 v_vert; out vec3 v_norm; out vec2 v_text; void main() { gl_Position = Mvp * vec4(in_vert + in_move, 1.0); v_vert = in_vert + in_move; v_norm = in_norm; v_text = in_text; } ''', fragment_shader=''' #version 330 uniform vec3 Light; uniform sampler2D Texture; in vec3 v_vert; in vec3 v_norm; in vec2 v_text; out vec4 f_color; void main() { float lum = clamp(dot(normalize(Light - v_vert), normalize(v_norm)), 0.0, 1.0) * 0.8 + 0.2; f_color = vec4(texture(Texture, v_text).rgb * lum, 1.0); } ''', ) self.mvp = self.prog['Mvp'] self.light = self.prog['Light'] obj = Obj.open(data.find('crate.obj')) img = Image.open(data.find('crate.png')).transpose(Image.FLIP_TOP_BOTTOM).convert('RGB') self.texture = self.ctx.texture(img.size, 3, img.tobytes()) self.texture.build_mipmaps() self.texture.use() self.vbo1 = self.ctx.buffer(obj.pack('vx vy vz nx ny nz tx ty')) self.vbo2 = self.ctx.buffer(reserve=12 * 1024) self.vao = self.ctx.vertex_array(self.prog, [ (self.vbo1, '3f 3f 2f', 'in_vert', 'in_norm', 'in_text'), (self.vbo2, '3f/i', 'in_move'), ]) self.crate_a = np.random.uniform(0.7, 0.8, 32 * 32) self.crate_b = np.random.uniform(0.0, 6.3, 32 * 32) self.crate_x = (np.tile(np.arange(32), 32) - 16) * 1.5 self.crate_y = (np.repeat(np.arange(32), 32) - 16) * 1.5 self.crate_x += np.random.uniform(-0.2, 0.2, 32 * 32) self.crate_y += np.random.uniform(-0.2, 0.2, 32 * 32)
def __init__(self): self.MODEL = Model().to(DEVICE) self.LABEL_MAP = load_imagenet_label_map() self.CTX = moderngl.create_context() self.PROG = self.CTX.program(vertex_shader=""" #version 330 uniform vec2 Pan; uniform float Zoom; uniform mat3 R; uniform mat3 L; uniform vec3 DirLight; uniform mat4 Mvp; uniform bool is_background; in vec3 in_vert; in vec3 in_norm; in vec2 in_text; out vec3 v_norm; out vec2 v_text; out vec3 v_light; void main() { if (!is_background) { gl_Position = Mvp * vec4((R * in_vert) + vec3(Pan, Zoom), 1.0); v_norm = R * in_norm; v_text = in_text; v_light = L * DirLight; } else { gl_Position = vec4(in_vert, 1.0); v_norm = in_norm; v_text = in_text; } } """, fragment_shader=""" #version 330 uniform float dir_int; uniform float amb_int; uniform sampler2D Texture; uniform bool is_background; uniform bool use_texture; in vec3 v_norm; in vec2 v_text; in vec3 v_light; out vec4 f_color; void main() { if (!is_background) { float lum = clamp(dot(v_light, v_norm), 0.0, 1.0) * dir_int + amb_int; if (use_texture) { f_color = vec4(texture(Texture, v_text).rgb * lum, texture(Texture, v_text).a); } else { f_color = vec4(vec3(1.0, 1.0, 1.0) * lum, 1.0); } } else { f_color = vec4(texture(Texture, v_text).rgba); } } """) self.CTX.enable(moderngl.DEPTH_TEST) self.CTX.enable(moderngl.BLEND) self.PROG["is_background"].value = False self.PROG["use_texture"].value = True self.USE_BACKGROUND = False self.PROG["use_texture"].value = False self.PROG["Pan"].value = (0, 0) self.PROG["Zoom"].value = 0 self.PROG["DirLight"].value = (0, 1, 0) self.PROG["dir_int"].value = 0.7 self.PROG["amb_int"].value = 0.5 self.PROG["Mvp"].write((perspective * LOOK_AT).astype("f4").tobytes()) self.R = np.eye(3) self.PROG["R"].write(self.R.astype("f4").tobytes()) self.L = np.eye(3) self.PROG["L"].write(self.L.astype("f4").tobytes()) self.CAMERA_DISTANCE = CAMERA_DISTANCE self.TOO_CLOSE = self.CAMERA_DISTANCE - 2.0 self.TOO_FAR = self.CAMERA_DISTANCE - 30.0 self.TAN_ANGLE = np.tan(VIEWING_ANGLE * np.pi / 180.0) # Load background. if BACKGROUND_F is not None: background_f = "{0}{1}".format(SCENE_DIR, BACKGROUND_F) background_img = Image.open(background_f).transpose( Image.FLIP_TOP_BOTTOM).convert("RGBA") (width, height) = (WIDTH, HEIGHT) # Resize background image to work with neural network. if height < background_img.height < background_img.width: new_height = height new_width = new_height * background_img.width // background_img.height else: new_width = width new_height = new_width * background_img.height // background_img.width background_img = background_img.resize((new_width, new_height), Image.ANTIALIAS) background_img = ImageOps.fit(background_img, (width, height), Image.ANTIALIAS) # Convert background image to ModernGL texture. self.BACKGROUND = self.CTX.texture(background_img.size, 4, background_img.tobytes()) self.BACKGROUND.build_mipmaps() # Create background 3D object consisting of two triangles forming a # rectangle. # Screen coordinates are [-1, 1]. vertices = np.array([[-1.0, -1.0, 0.0], [-1.0, 1.0, 0.0], [1.0, 1.0, 0.0], [-1.0, -1.0, 0.0], [1.0, -1.0, 0.0], [1.0, 1.0, 0.0]]) # Not used for the background, but the vertex shader expects a normal. normals = np.repeat([[0.0, 0.0, 1.0]], len(vertices), axis=0) # Image coordinates are [0, 1]. texture_coords = np.array([[0.0, 0.0], [0.0, 1.0], [1.0, 1.0], [0.0, 0.0], [1.0, 0.0], [1.0, 1.0]]) BACKGROUND_ARRAY = np.hstack((vertices, normals, texture_coords)) BACKGROUND_VBO = self.CTX.buffer( BACKGROUND_ARRAY.flatten().astype("f4").tobytes()) self.BACKGROUND_VAO = self.CTX.simple_vertex_array( self.PROG, BACKGROUND_VBO, "in_vert", "in_norm", "in_text") # Set up object. self.TRUE_CLASS = int(open("{0}{1}".format(SCENE_DIR, CLASS_F)).read()) self.TRUE_LABEL = self.LABEL_MAP[self.TRUE_CLASS] # Load textures. TEXTURES = [] for TEXTURE_F in TEXTURE_FS: texture_f = SCENE_DIR + "{1}".format(SCENE_DIR, TEXTURE_F) texture_img = Image.open(texture_f).transpose( Image.FLIP_TOP_BOTTOM).convert("RGBA") TEXTURE = self.CTX.texture(texture_img.size, 4, texture_img.tobytes()) TEXTURE.build_mipmaps() TEXTURES.append(TEXTURE) self.TEXTURES = TEXTURES # Load vertices. VAOS = [] (min_val, abs_max_val, max_val) = (None, None, None) for OBJ_F in OBJ_FS: input_obj = SCENE_DIR + OBJ_F obj = Obj.open(input_obj) packed_array = obj.to_array()[:, :-1] # Normalize vertices into a unit cube centered at zero. original_vertices = packed_array[:, :3].copy() if min_val is None: min_val = original_vertices.min(axis=0) original_vertices -= min_val if abs_max_val is None: abs_max_val = np.abs(original_vertices).max() original_vertices /= abs_max_val original_vertices *= 2 if max_val is None: max_val = original_vertices.max(axis=0) original_vertices -= max_val / 2 packed_array[:, :3] = original_vertices vbo = self.CTX.buffer( packed_array.flatten().astype("f4").tobytes()) vao = self.CTX.simple_vertex_array(self.PROG, vbo, "in_vert", "in_norm", "in_text") VAOS.append(vao) self.VAOS = VAOS
def __init__(self, **kwargs): super().__init__(**kwargs) self.ctx = mgl.create_context() # import gltraces # mglprocs = mgl.glprocs(self.ctx) # gltraces.glprocs[:] = mglprocs # mglprocs[:] = gltraces.gltraces self.prog1 = self.ctx.program( vertex_shader=''' #version 330 uniform mat4 Mvp; in vec3 in_vert; in vec3 in_norm; in vec3 in_text; out vec3 v_vert; out vec3 v_norm; out vec3 v_text; void main() { gl_Position = Mvp * vec4(in_vert, 1.0); v_vert = in_vert; v_norm = in_norm; v_text = in_text; } ''', fragment_shader=''' #version 330 uniform vec3 Light; uniform samplerCube Sampler; in vec3 v_vert; in vec3 v_norm; in vec3 v_text; out vec4 f_color; void main() { float lum = clamp(dot(normalize(Light - v_vert), normalize(v_norm)), 0.0, 1.0) * 0.8 + 0.2; f_color = vec4(texture(Sampler, normalize(v_text)).rgb * lum, 1.0); } ''', ) obj = Obj.open(data.find('texture-test-cube.obj')) self.texture1 = self.ctx.texture_cube((512, 512), 3, np.random.randint(128, 255, (512, 512, 3, 6), 'u1').tobytes()) self.depth1 = self.ctx.texture_cube((512, 512), 1, None, dtype='d3') self.sampler1 = self.ctx.sampler(self.texture1, filter=mgl.LINEAR) self.fbo1 = self.ctx.framebuffer(self.texture1, self.depth1) # exit() self.vbo1 = self.ctx.buffer(obj.pack('vx vy vz nx ny nz tx ty tz')) self.vao1 = self.ctx.simple_vertex_array(self.prog1, self.vbo1, 'in_vert', 'in_norm', 'in_text') self.vao1.scope = self.ctx.scope(mgl.DEPTH_TEST, self.ctx.screen, samplers=[(self.sampler1, 0)]) self.prog2 = self.ctx.program( vertex_shader=''' #version 330 in vec3 in_vert; in vec3 in_norm; in vec3 in_text; out vec3 v_vert; out vec3 v_norm; out vec3 v_text; void main() { v_vert = in_vert; v_norm = in_norm; v_text = in_text; } ''', geometry_shader=''' #version 330 layout(triangles) in; layout(triangle_strip, max_vertices=18) out; in vec3 v_vert[3]; in vec3 v_norm[3]; in vec3 v_text[3]; out vec3 g_vert; out vec3 g_norm; out vec3 g_text; uniform mat4 Mvp[6]; void main() { for (int layer = 0; layer < 6; ++layer) { gl_Layer = layer; for (int i = 0; i < 3; ++i) { g_vert = v_vert[i]; g_norm = v_norm[i]; g_text = v_text[i]; gl_Position = Mvp[layer] * vec4(g_vert, 1.0); EmitVertex(); } EndPrimitive(); } } ''', fragment_shader=''' #version 330 uniform sampler3D Sampler; uniform vec3 Light; in vec3 g_vert; in vec3 g_norm; in vec3 g_text; out vec4 f_color; void main() { float lum = clamp(dot(normalize(Light - g_vert), normalize(g_norm)), 0.0, 1.0) * 0.8 + 0.2; f_color = vec4(texture(Sampler, g_text).rgb * lum, 1.0); } ''', ) obj = Obj.open(data.find('test_scene.obj')) self.texture2 = self.ctx.texture((4, 4, 4), 3, np.repeat(np.random.randint(180, 220, (4, 4, 4), 'u1'), 3)) self.sampler2 = self.ctx.sampler(self.texture2, wrap=mgl.REPEAT_X | mgl.REPEAT_Y | mgl.REPEAT_Z, filter=mgl.LINEAR) self.vbo2 = self.ctx.buffer(obj.pack('vx vy vz nx ny nz vx vy vz')) self.vao2 = self.ctx.simple_vertex_array(self.prog2, self.vbo2, 'in_vert', 'in_norm', 'in_text') self.vao2.scope = self.ctx.scope(mgl.DEPTH_TEST, self.fbo1, samplers=[(self.sampler2, 0)])
def __init__(self, **kwargs): super().__init__(**kwargs) # import gltraces # mglprocs = mgl.glprocs(self.ctx) # gltraces.glprocs[:] = mglprocs # mglprocs[:] = gltraces.gltraces self.prog = self.ctx.program( vertex_shader=''' #version 330 uniform mat4 Mvp; in vec3 in_vert; in vec3 in_norm; in vec2 in_text; out vec3 v_vert; out vec3 v_norm; out vec2 v_text; void main() { gl_Position = Mvp * vec4(in_vert, 1.0); v_vert = in_vert; v_norm = in_norm; v_text = in_text; } ''', fragment_shader=''' #version 330 uniform vec3 Light; uniform vec3 Color; uniform bool UseTexture; uniform sampler2D Texture; in vec3 v_vert; in vec3 v_norm; in vec2 v_text; out vec4 f_color; void main() { float lum = clamp(dot(normalize(Light - v_vert), normalize(v_norm)), 0.0, 1.0) * 0.8 + 0.2; if (UseTexture) { f_color = vec4(texture(Texture, v_text).rgb * lum, 1.0); } else { f_color = vec4(Color * lum, 1.0); } } ''', ) self.compute = self.ctx.compute_shader(''' #version 430 layout (local_size_x = 16, local_size_y = 16) in; layout(rg32f,location=0) writeonly uniform image2D destTex; uniform float time; void main() { ivec2 ij = ivec2(gl_GlobalInvocationID.xy); float localCoef = length(vec2(ivec2(gl_LocalInvocationID.xy)-8)/8.0); float globalCoef = sin(float(gl_WorkGroupID.x+gl_WorkGroupID.y)*0.1 + time)*0.5; imageStore(destTex, ij, vec4(1.0-globalCoef*localCoef, 0.0, 0.0, 0.0)); } ''') self.objects = {} for name in [ 'ground', 'grass', 'billboard', 'billboard-holder', 'billboard-image' ]: obj = Obj.open(data.find('scene-1-%s.obj' % name)) vbo = self.ctx.buffer(obj.pack('vx vy vz nx ny nz tx ty')) vao = self.ctx.simple_vertex_array(self.prog, vbo, 'in_vert', 'in_norm', 'in_text') self.objects[name] = vao img = Image.new('RGB', (512, 512)) self.texture = self.ctx.texture(img.size, 3, img.tobytes()) self.sampler = self.ctx.sampler(self.texture) self.scope = self.ctx.scope(mgl.DEPTH_TEST, self.ctx.screen, samplers=[(self.sampler, 0)])