def __init__(self, **args): super().__init__(**args) # create world self.world = world.World() # create shader self.shader = shader.Shader("vert.glsl", "frag.glsl") self.shader_sampler_location = self.shader.find_uniform( b"texture_array_sampler") self.shader.use() # pyglet stuff pyglet.clock.schedule_interval(self.update, 1.0 / 10000) self.mouse_captured = False # camera stuff self.camera = camera.Camera(self.shader, self.width, self.height) # misc stuff self.holding = 7
def generateImg(file,width,length,cam_pos,cam_ori): files = [f for f in os.listdir(dir) if os.path.isfile(os.path.join(dir,f))] count = 0 previous_img = cv2.imread(skyDir,cv2.CV_LOAD_IMAGE_COLOR) for x in range(len(files)-1): filename = os.path.join(dir,"model_"+str(x)+".dat") print filename if x==0: continue points, rgb_values = file.importPointsWithRGB(filename) #STORE EACH FOUR PONITS INTO A MESH cam = camera.Camera(points, camera_pos, camera_ori, 1) start = timeit.default_timer() x_cords, y_cords ,z_cords = cam.getProjectedPts(height, width) #x_cords, y_cords ,z_cords = cam.getOrthProjectPts(height, width) shader = pts_shader.Shader( width, height,previous_img) print "----projected poitns generated-----" out_img = shader.shading(x_cords,y_cords,rgb_values) print "Processing Time:", timeit.default_timer()-start,"s" print "-----points shaded------------------" cv2.imwrite(os.path.join(outDir,"img_"+str(x)+".png"),out_img) #out_points = shader.plotPoints(x_cords, y_cords,rgb_values) #cv2.imwrite(os.path.join(outDir,"points_"+str(x)+".png"),out_points) print "---img_"+str(x)+".png created!" previous_img = out_img cv2.imwrite(os.path.join(outDir,"result.png"),previous_img)
def main(): if not glfw.init(): raise ValueError("Failed to initialize glfw") glfw.window_hint(glfw.CONTEXT_CREATION_API, glfw.NATIVE_CONTEXT_API) glfw.window_hint(glfw.CLIENT_API, glfw.OPENGL_API) glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 4) glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 2) glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE) glfw.window_hint(glfw.OPENGL_FORWARD_COMPAT, True) glfw.window_hint(glfw.RESIZABLE, True) glfw.window_hint(glfw.DOUBLEBUFFER, True) glfw.window_hint(glfw.DEPTH_BITS, 24) glfw.window_hint(glfw.SAMPLES, 4) window = glfw.create_window(SCR_WIDTH, SCR_HEIGHT, "Python Compute Shader Demo", None, None) if not window: glfw.terminate() raise ValueError("Failed to create window") glfw.make_context_current(window) glfw.set_key_callback(window, key_event_callback) glfw.set_cursor_pos_callback(window, mouse_event_callback) glfw.set_mouse_button_callback(window, mouse_button_callback) glfw.set_window_size_callback(window, window_resize_callback) CSG = shader.ComputeShader(RES("splat.glsl")) SplatProgram = shader.Shader(RES("splat.vert"), RES("splat.frag")) some_UAV = gl.glGenTextures(1) gl.glActiveTexture(gl.GL_TEXTURE0) gl.glBindTexture(gl.GL_TEXTURE_2D, some_UAV) gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_WRAP_S, gl.GL_CLAMP_TO_EDGE) gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_WRAP_T, gl.GL_CLAMP_TO_EDGE) gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MAG_FILTER, gl.GL_NEAREST) gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MIN_FILTER, gl.GL_NEAREST) gl.glTexImage2D(gl.GL_TEXTURE_2D, 0, gl.GL_RGBA32F, SCR_WIDTH, SCR_HEIGHT, 0, gl.GL_RGBA, gl.GL_FLOAT, None) gl.glBindImageTexture(0, some_UAV, 0, gl.GL_FALSE, 0, gl.GL_READ_WRITE, gl.GL_RGBA32F) vao = gl.glGenVertexArrays(1) gl.glBindVertexArray(vao) gl.glDisable(gl.GL_CULL_FACE) gl.glDisable(gl.GL_DEPTH_TEST) while not glfw.window_should_close(window): CSG.use() gl.glDispatchCompute(SCR_WIDTH // 8, SCR_HEIGHT // 8, 1) gl.glMemoryBarrier(gl.GL_SHADER_IMAGE_ACCESS_BARRIER_BIT) SplatProgram.use() SplatProgram.set_int("Whatever", 0) gl.glDrawArrays(gl.GL_TRIANGLES, 0, 3) glfw.swap_buffers(window) glfw.poll_events() glfw.terminate()
def __init__(self, width, height, scr_width, scr_height, vert_shader, frag_shader): self.width = width self.height = height self.scr_width = scr_width self.scr_height = scr_height self.light_pos = [] self.gen_buffers() self.shader_program = shader.Shader(vert_shader, frag_shader)
def do_live_demo(filename='demodata.npy', sealevel=7.0, steps=42, fps=30, save_fig=False): import string fps_clock = pygame.time.Clock() screen = pygame.display.set_mode(RESOLUTION, pygame.DOUBLEBUF) scene = m.Map(filename, sealevel, True) look_at = np.array([31, 33, 21]) cam = c.Camera(position=np.array([ scene.positions[:, 0].mean(), -2 * np.ceil(scene.positions[:, 2].max()) - 9.0, 2 * np.ceil(scene.positions[:, 2].max()) + 6.0 ]), screen=c.Screen(resolution=np.array(RESOLUTION))) shader = s.Shader(cam) angles = np.linspace(0, 2 * np.pi, steps + 1) R = np.linalg.norm(cam.position[:2] - look_at[:2]) for N, a in enumerate(angles): screen.fill((0, 0, 0)) cam.position = np.array([np.sin(a) * R + 31, np.cos(a) * R + 33, 42]) cam.look_at_point(look_at) # pixels = cam.get_screen_coordinates(scene.positions) colours = shader.apply_lighting(scene.positions, scene.normals, scene.colours.copy()) patches, depth = cam.get_screen_coordinates(scene.patches) order = np.argsort(-((scene.positions - cam.position)**2).mean(-1)) for n in order: # Use this to render point cloud in uniform colour: # screen.set_at(np.round(pixels[n]).astype(np.int), (204, 0, 0)) # Use this to render point cloud in shaded colours (not pretty): # screen.set_at(np.round(pixels[n]).astype(np.int), colours[n, :]) # Use this to render patches: pygame.draw.polygon(screen, colours[n], patches[n]) pygame.display.flip() if save_fig: pygame.image.save(screen, 'out/{0}.png'.format(string.zfill(str(N), 2))) fps_clock.tick(fps)
def __init__(self, **args): super().__init__(**args) # create vertex array object self.vao = gl.GLuint(0) gl.glGenVertexArrays(1, ctypes.byref(self.vao)) gl.glBindVertexArray(self.vao) # create vertex buffer object self.vbo = gl.GLuint(0) gl.glGenBuffers(1, ctypes.byref(self.vbo)) gl.glBindBuffer(gl.GL_ARRAY_BUFFER, self.vbo) gl.glBufferData(gl.GL_ARRAY_BUFFER, ctypes.sizeof(gl.GLfloat * len(vertex_positions)), (gl.GLfloat * len(vertex_positions))(*vertex_positions), gl.GL_STATIC_DRAW) gl.glVertexAttribPointer(0, 3, gl.GL_FLOAT, gl.GL_FALSE, 0, 0) gl.glEnableVertexAttribArray(0) # create index buffer object self.ibo = gl.GLuint(0) gl.glGenBuffers(1, self.ibo) gl.glBindBuffer(gl.GL_ELEMENT_ARRAY_BUFFER, self.ibo) gl.glBufferData(gl.GL_ELEMENT_ARRAY_BUFFER, ctypes.sizeof(gl.GLuint * len(indices)), (gl.GLuint * len(indices))(*indices), gl.GL_STATIC_DRAW) # create shader self.shader = shader.Shader("vert.glsl", "frag.glsl") self.shader_matrix_location = self.shader.find_uniform( b"matrix") # get the shader matrix uniform location self.shader.use() # create matrices self.mv_matrix = matrix.Matrix() # modelview self.p_matrix = matrix.Matrix() # projection self.x = 0 # temporary variable pyglet.clock.schedule_interval( self.update, 1.0 / 60) # call update function every 60th of a second
def __init__(self): glutInit(len(sys.argv), sys.argv) glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE) glutInitWindowSize(800, 600) glutCreateWindow('Dynamic Skybox') glutDisplayFunc(self.draw) glutMotionFunc(self.mouse_drag) glutKeyboardFunc(self.keyboard) glutMouseFunc(self.mouse_press) glutReshapeFunc(self.reshape) glutIdleFunc(self.idle) self.time = time.clock() self.screen_width = 1.0 self.shader = shader.Shader("./shaders/skybox.vert", "./shaders/skybox.frag") self.seed = random.uniform(0, 5000)
def __init__(self): glutInit(len(sys.argv), sys.argv) glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE) glutInitWindowSize(800, 600) glutCreateWindow('Dynamic FBM Warping') #glutFullScreen() glutDisplayFunc(self.draw) glutMotionFunc(self.mouse_drag) glutKeyboardFunc(self.keyboard) glutMouseFunc(self.mouse_press) glutReshapeFunc(self.reshape) glutIdleFunc(self.idle) print glGetString(GL_VERSION) glClearColor(0.0, 0.0, 0.0, 1.0) self.time = time.clock() self.aspect_ratio = 1.0 self.width = 800 self.height = 600 self.fps = 120 self.idle_tick = 1.0 / self.fps self.paused = False self.quad = quad.Quad() self.high_quality = True self.frames_drawn = 0 self.second_timer = 0 self.fullscreen = False self.scr_width = 800 self.scr_height = 600 self.current_shader_index = 3 self.shaders = [] self.offset = [0, 0] self.last_pos = [0, 0] self.mouse_pressed = False self.fragfiles = [ item for item in os.listdir("./shaders") if item.endswith("frag") ] for shaderfile in self.fragfiles: print "Loading shader:", shaderfile self.shaders.append( shader.Shader("./shaders/warping.vert", "./shaders/" + shaderfile))
def __init__(self): glutInit(len(sys.argv), sys.argv) glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE) glutInitWindowSize(800, 600) glutCreateWindow('Dynamic Skybox') glutFullScreen() glutDisplayFunc(self.draw) glutMotionFunc(self.mouse_drag) glutKeyboardFunc(self.keyboard) glutMouseFunc(self.mouse_press) glutReshapeFunc(self.reshape) glutIdleFunc(self.idle) glClearColor(0.1, 0.2, 0.5, 1.0) glEnable(GL_DEPTH_TEST) glEnable(GL_BLEND) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) glShadeModel(GL_SMOOTH) glEnable(GL_NORMALIZE) glEnable(GL_LIGHTING) glColorMaterial(GL_FRONT, GL_AMBIENT_AND_DIFFUSE) glEnable(GL_COLOR_MATERIAL) self.time = time.clock() self.screen_width = 1.0 self.shader = shader.Shader("./shaders/plain.vert", "./shaders/plain.frag") self.seed = random.uniform(0, 5000) self.last_mouse_pos = 0, 0 self.x_rotation = 0 self.y_rotation = 0 self.scene = scene.Scene() self.zoom = 0 self.fps = 60 self.idle_tick = 1.0 / self.fps self.scr_width = glutGet(GLUT_WINDOW_WIDTH) self.scr_height = glutGet(GLUT_WINDOW_HEIGHT) self.first_pass = postprocessing.PostProcessor( 1, 1, self.scr_width, self.scr_height, "./shaders/god_rays.vert", "./shaders/god_rays.frag") self.using_pp = False self.paused = False
def __init__(self, **args): super().__init__(**args) # create vertex array object self.vao = gl.GLuint(0) gl.glGenVertexArrays(1, ctypes.byref(self.vao)) gl.glBindVertexArray(self.vao) # create vertex buffer object self.vbo = gl.GLuint(0) gl.glGenBuffers(1, ctypes.byref(self.vbo)) gl.glBindBuffer(gl.GL_ARRAY_BUFFER, self.vbo) gl.glBufferData(gl.GL_ARRAY_BUFFER, ctypes.sizeof(gl.GLfloat * len(vertex_positions)), (gl.GLfloat * len(vertex_positions))(*vertex_positions), gl.GL_STATIC_DRAW) gl.glVertexAttribPointer(0, 3, gl.GL_FLOAT, gl.GL_FALSE, 0, 0) gl.glEnableVertexAttribArray(0) # create index buffer object self.ibo = gl.GLuint(0) gl.glGenBuffers(1, self.ibo) gl.glBindBuffer(gl.GL_ELEMENT_ARRAY_BUFFER, self.ibo) gl.glBufferData(gl.GL_ELEMENT_ARRAY_BUFFER, ctypes.sizeof(gl.GLuint * len(indices)), (gl.GLuint * len(indices))(*indices), gl.GL_STATIC_DRAW) # create shader self.shader = shader.Shader("vert.glsl", "frag.glsl") self.shader.use()
def do_demo(filename='demodata.npy', cam=None, look_at=None, sealevel=0): screen = pygame.display.set_mode(RESOLUTION, pygame.DOUBLEBUF) scene = m.Map(filename, sealevel) if cam is None: cam = c.Camera(position=np.array([ scene.positions[:, 0].mean(), -2 * np.ceil(scene.positions[:, 2].max()) - 9.0, 2 * np.ceil(scene.positions[:, 2].max()) + 6.0 ]), screen=c.Screen(resolution=np.array(RESOLUTION))) shader = s.Shader(cam) if look_at is not None: cam.look_at_point(look_at) # pixels = cam.get_screen_coordinates(scene.positions) colours = shader.apply_lighting(scene.positions, scene.normals, scene.colours.copy()) patches, depth = cam.get_screen_coordinates(scene.patches) order = np.argsort(-((scene.positions - cam.position)**2).mean(-1)) for n in order: # Use this to render point cloud in uniform colour: # screen.set_at(np.round(pixels[n]).astype(np.int), (204, 0, 0)) # Use this to render point cloud in shaded colours (not pretty): # screen.set_at(np.round(pixels[n]).astype(np.int), colours[n, :]) # Use this to render patches: pygame.draw.polygon(screen, colours[n], patches[n]) pygame.display.flip() return scene, cam
def main(): global delta_time, last_frame, frames if not glfw.init(): raise ValueError("Failed to initialize glfw") glfw.window_hint(glfw.CONTEXT_CREATION_API, glfw.NATIVE_CONTEXT_API) glfw.window_hint(glfw.CLIENT_API, glfw.OPENGL_API) glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 4) glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 2) glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE) glfw.window_hint(glfw.OPENGL_FORWARD_COMPAT, True) glfw.window_hint(glfw.DOUBLEBUFFER, True) glfw.window_hint(glfw.DEPTH_BITS, 24) glfw.window_hint(glfw.SAMPLES, 4) window = glfw.create_window( SCR_WIDTH, SCR_HEIGHT, "Python Compute Shader Demo: Pathtracer", None, None ) if not window: glfw.terminate() raise ValueError("Failed to create window") glfw.make_context_current(window) glfw.set_framebuffer_size_callback(window, framebuffer_size_callback) glfw.set_cursor_pos_callback(window, mouse_callback) glfw.set_scroll_callback(window, scroll_callback) glfw.set_input_mode(window, glfw.CURSOR, glfw.CURSOR_DISABLED) # -- setup shaders compute_program = shader.ComputeShader(RES(f"tracer_cs.glsl")) quad_program = shader.Shader(RES("tracer_vs.glsl"), RES("tracer_fs.glsl")) # -- create vao with full screen quad quad_verts = [ -1, -1, 1, -1, 1, 1, 1, 1, -1, 1, -1, -1, ] quad_verts = (c_byte * len(quad_verts))(*quad_verts) vao = gl.glGenVertexArrays(1) vbo = gl.glGenBuffers(1) gl.glBindVertexArray(vao) gl.glBindBuffer(gl.GL_ARRAY_BUFFER, vbo) gl.glBufferData(gl.GL_ARRAY_BUFFER, sizeof(quad_verts), quad_verts, gl.GL_STATIC_DRAW) gl.glVertexAttribPointer(0, 2, gl.GL_BYTE, gl.GL_FALSE, 2 * sizeof(c_byte), c_void_p(0)) gl.glEnableVertexAttribArray(0) gl.glBindVertexArray(0) trace_tex = gl.glGenTextures(1) gl.glBindTexture(gl.GL_TEXTURE_2D, trace_tex) gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MAG_FILTER, gl.GL_LINEAR) gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MIN_FILTER, gl.GL_LINEAR) gl.glTexImage2D(gl.GL_TEXTURE_2D, 0, gl.GL_RGBA32F, SCR_WIDTH, SCR_HEIGHT, 0, gl.GL_RGBA, gl.GL_FLOAT, None) gl.glBindTexture(gl.GL_TEXTURE_2D, 0) # -- initialize quad program uniforms quad_program.use() quad_program.set_int("trace_tex", 0) while not glfw.window_should_close(window): projection = Matrix44.perspective_projection(camera.zoom, SCR_WIDTH / SCR_HEIGHT, 1.0, 2.0) # -- time logic current_frame = glfw.get_time() delta_time = current_frame - last_frame last_frame = current_frame # -- input process_input(window) compute_program.use() compute_program.set_int("u_NumFrames", frames) compute_program.set_float("u_Accum", frames / (frames+1)) compute_program.set_mat4("u_InvProjectionMat", projection.inverse) compute_program.set_mat4("u_InvViewMat", camera.get_view_matrix().inverse) gl.glBindImageTexture(0, trace_tex, 0, gl.GL_FALSE, 0, gl.GL_WRITE_ONLY, gl.GL_RGBA32F) gl.glDispatchCompute(SCR_WIDTH // 8, SCR_HEIGHT // 8, 1) gl.glBindImageTexture(0, 0, 0, gl.GL_FALSE, 0, gl.GL_READ_WRITE, gl.GL_RGBA32F) gl.glMemoryBarrier(gl.GL_SHADER_IMAGE_ACCESS_BARRIER_BIT) frames += 1 quad_program.use() gl.glBindFramebuffer(gl.GL_FRAMEBUFFER, 0) gl.glClearColor(0.0, 0.0, 0.0, 1.0) gl.glClear(gl.GL_COLOR_BUFFER_BIT | gl.GL_DEPTH_BUFFER_BIT) gl.glBindVertexArray(vao) gl.glActiveTexture(gl.GL_TEXTURE0) gl.glBindTexture(gl.GL_TEXTURE_2D, trace_tex) gl.glDrawArrays(gl.GL_TRIANGLES, 0, 6) glfw.swap_buffers(window) glfw.poll_events() glfw.terminate()
for index in range(len(sorted_models)): fileindex = sorted_models[index] filename = os.path.join(dir,"model_"+str(fileindex)+".dat") print "----------get projected points ",filename,"-------------" points, rgb_values = file.importPointsWithRGB(filename) start = timeit.default_timer() #sort the points based on meshes points, rgb_values = sortMeshes(points,rgb_values,cam_pos[t]) #create the camera cam = camera.Camera(points, cam_pos[t], cam_ori[t], 1) print "----------get projected points-------------" x_cords, y_cords ,z_cords = cam.getProjectedPts(height, width) #shading the projected points shader = pts_shader.Shader(width, height,previous_img[t]) print "----projected poitns generated-----" out_img = shader.shading(x_cords,y_cords,rgb_values,mode) print "Processing Time:", timeit.default_timer()-start,"s" print "-----points shaded------------------" #write all the middle frames cv2.imwrite(os.path.join(outDir,"frame_"+str(t)+"_img_"+str(index)+".png"),out_img) print "---img_"+str(t)+"_frame_"+str(index)+".png created!" previous_img[t] = out_img #this main file is used to create the middle frames, for creating a video, please use makingVideoMain for i in range(init,end): cv2.imwrite(os.path.join(outDir,"result_"+str(i)+".png"),previous_img[i]) print "------------Main Phase Finished------------"
def do_brand_demo(filename='zdata.npy', sealevel=0.0, steps=42, fps=30, save_fig=False, frames=None): import string fps_clock = pygame.time.Clock() screen = pygame.display.set_mode(RESOLUTION, pygame.DOUBLEBUF) scene = m.Map(filename, sealevel, True) look_at = np.array([63.5, 63.5, 6.0]) cam = c.Camera(position=np.array([54.5, 63.5, 6.0]), screen=c.Screen(resolution=np.array(RESOLUTION))) shader = s.Shader(cam) fighter = o.FireFighter() fighter.position = np.array([63.5, 63.5, 6.0]) house = o.House() house.position = np.array([58.5, 67, 2.23]) house.yaw = np.pi / 8 angles = np.linspace(0, 2 * np.pi, steps + 1) R = np.linalg.norm(cam.position[:2] - look_at[:2]) for N, a in enumerate(angles): screen.fill((0, 0, 0)) cam.position = np.array( [np.sin(a) * R + 63.5, np.cos(a) * R + 63.5, 6.0]) cam.look_at_point(look_at) colours = shader.apply_lighting(scene.positions, scene.normals, scene.colours.copy()) patches, depth = cam.get_screen_coordinates(scene.patches) order = np.argsort(-((scene.positions - cam.position)**2).mean(-1)) for n in order: if ((depth[n].mean() > 0 and patches[n] >= 0).any() and (patches[n, :, 0] < RESOLUTION[0]).any() and (patches[n, :, 1] < RESOLUTION[1]).any()): pygame.draw.polygon(screen, colours[n], patches[n]) fighter.yaw = a fighter.pitch = a fighter.roll = a colours = shader.apply_lighting(fighter.positions, fighter.normals, fighter.colours.copy()) patches, depth = cam.get_screen_coordinates(fighter.patches) order = np.argsort(-((fighter.positions - cam.position)**2).mean(-1)) for n in order: if (colours[n, 3] and depth[n].mean() > 0 and (patches[n] >= 0).any() and (patches[n, :, 0] < RESOLUTION[0]).any() and (patches[n, :, 1] < RESOLUTION[1]).any()): pygame.draw.polygon(screen, colours[n], patches[n]) colours = shader.apply_lighting(house.positions, house.normals, house.colours.copy()) patches, depth = cam.get_screen_coordinates(house.patches) order = np.argsort(-((house.positions - cam.position)**2).mean(-1)) for n in order: if (colours[n, 3] and depth[n].mean() > 0 and (patches[n] >= 0).any() and (patches[n, :, 0] < RESOLUTION[0]).any() and (patches[n, :, 1] < RESOLUTION[1]).any()): pygame.draw.polygon(screen, colours[n], patches[n]) pygame.display.flip() if save_fig: pygame.image.save(screen, 'out/{0}.png'.format(string.zfill(str(N), 2))) the_tick = fps_clock.tick(fps) print "Frame update time: {0} ms".format(the_tick) if frames is not None: frames.append(the_tick / 1000.0)
def setUp(self): pygame.init() window = pygame.display.set_mode( (640, 480), pygame.HWSURFACE | pygame.OPENGL | pygame.DOUBLEBUF) self.texture = shader.Texture(window) self.shader = shader.Shader(self.texture)
glEnable(GL_BLEND) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) window = pyglet.window.Window() image = pyglet.resource.image('seamlessleaft.jpg') sprite = pyglet.sprite.Sprite(img=image, x=0, y=0) shader = shader.Shader(vert = [''' /* passthrough vertex stage */ void main() { gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex; } '''], frag=[''' /* passthrough fragment stage */ void main() { gl_FragColor = gl_Color; } ''']) text = pyglet.text.Label('Hello, world', font_name='Times New Roman', font_size=36, x=10, y=10)
def __init__(self, **args): super().__init__(**args) # create blocks self.texture_manager = texture_manager.Texture_manager( 16, 16, 256 ) # create our texture manager (256 textures that are 16 x 16 pixels each) self.cobblestone = block_type.Block_type( self.texture_manager, "cobblestone", {"all": "cobblestone"} ) # create each one of our blocks with the texture manager and a list of textures per face self.grass = block_type.Block_type(self.texture_manager, "grass", { "top": "grass", "bottom": "dirt", "sides": "grass_side" }) self.dirt = block_type.Block_type(self.texture_manager, "dirt", {"all": "dirt"}) self.stone = block_type.Block_type(self.texture_manager, "stone", {"all": "stone"}) self.sand = block_type.Block_type(self.texture_manager, "sand", {"all": "sand"}) self.planks = block_type.Block_type(self.texture_manager, "planks", {"all": "planks"}) self.log = block_type.Block_type(self.texture_manager, "log", { "top": "log_top", "bottom": "log_top", "sides": "log_side" }) self.texture_manager.generate_mipmaps( ) # generate mipmaps for our texture manager's texture # create vertex array object self.vao = gl.GLuint(0) gl.glGenVertexArrays(1, ctypes.byref(self.vao)) gl.glBindVertexArray(self.vao) # create vertex position vbo self.vertex_position_vbo = gl.GLuint(0) gl.glGenBuffers(1, ctypes.byref(self.vertex_position_vbo)) gl.glBindBuffer(gl.GL_ARRAY_BUFFER, self.vertex_position_vbo) gl.glBufferData( gl.GL_ARRAY_BUFFER, ctypes.sizeof(gl.GLfloat * len(self.grass.vertex_positions)), (gl.GLfloat * len(self.grass.vertex_positions))( *self.grass.vertex_positions ), # use grass block's vertex positions gl.GL_STATIC_DRAW) gl.glVertexAttribPointer(0, 3, gl.GL_FLOAT, gl.GL_FALSE, 0, 0) gl.glEnableVertexAttribArray(0) # create tex coord vbo self.tex_coord_vbo = gl.GLuint(0) gl.glGenBuffers(1, ctypes.byref(self.tex_coord_vbo)) gl.glBindBuffer(gl.GL_ARRAY_BUFFER, self.tex_coord_vbo) gl.glBufferData( gl.GL_ARRAY_BUFFER, ctypes.sizeof(gl.GLfloat * len(self.grass.tex_coords)), (gl.GLfloat * len(self.grass.tex_coords))( *self.grass.tex_coords ), # use grass block's texture coordinates positions gl.GL_STATIC_DRAW) gl.glVertexAttribPointer(1, 3, gl.GL_FLOAT, gl.GL_FALSE, 0, 0) gl.glEnableVertexAttribArray(1) # create index buffer object self.ibo = gl.GLuint(0) gl.glGenBuffers(1, self.ibo) gl.glBindBuffer(gl.GL_ELEMENT_ARRAY_BUFFER, self.ibo) gl.glBufferData( gl.GL_ELEMENT_ARRAY_BUFFER, ctypes.sizeof(gl.GLuint * len(self.grass.indices)), (gl.GLuint * len(self.grass.indices))( *self.grass.indices), # use grass block's indices gl.GL_STATIC_DRAW) # create shader self.shader = shader.Shader("vert.glsl", "frag.glsl") self.shader_matrix_location = self.shader.find_uniform(b"matrix") self.shader_sampler_location = self.shader.find_uniform( b"texture_array_sampler" ) # find our texture array sampler's uniform self.shader.use() # create matrices self.mv_matrix = matrix.Matrix() self.p_matrix = matrix.Matrix() self.x = 0 pyglet.clock.schedule_interval(self.update, 1.0 / 60)
def __init__(self, window): super(GameMain, self).__init__(window, texture=None, color='#000000') self.config = gl.Config(double_buffer=True, major_version=3, minor_version=3, depth_size=16, sample_buffers=bool(options.ANTIALIASING), samples=options.ANTIALIASING) # Options self.options = window.options if self.options.INDIRECT_RENDERING and not gl.gl_info.have_version( 4, 2): raise RuntimeError( """Indirect Rendering is not supported on your hardware This feature is only supported on OpenGL 4.2+, but your driver doesnt seem to support it, Please disable "INDIRECT_RENDERING" in options.py""") # Pause menu self.show_pause = False self.back_to_game = GuiButton(self.on_back_to_game, self.window, self.window.width / 2, self.window.height / 2 + 35, 'Back to game') self.save_game = GuiButton(self.on_save_game, self.window, self.window.width / 2, self.window.height / 2, 'Save and quit to title') # F3 Debug Screen self.show_f3 = False self.f3 = pyglet.text.Label("", x=10, y=self.height - 10, font_size=16, color=(255, 255, 255, 255), width=self.width // 3, multiline=True) self.system_info = f"""Python: {platform.python_implementation()} {platform.python_version()} System: {platform.machine()} {platform.system()} {platform.release()} {platform.version()} CPU: {platform.processor()} Display: {gl.gl_info.get_renderer()} {gl.gl_info.get_version()}""" logging.info(f"System Info: {self.system_info}") # create shader logging.info("Compiling Shaders") if not self.options.COLORED_LIGHTING: self.shader = shader.Shader("shaders/alpha_lighting/vert.glsl", "shaders/alpha_lighting/frag.glsl") else: self.shader = shader.Shader("shaders/colored_lighting/vert.glsl", "shaders/colored_lighting/frag.glsl") self.shader_sampler_location = self.shader.find_uniform( b"u_TextureArraySampler") self.shader.use() # create textures logging.info("Creating Texture Array") self.texture_manager = texture_manager.TextureManager(16, 16, 256) # create world self.world = world.World(self.shader, None, self.texture_manager, self.options) # player stuff logging.info("Setting up player & camera") self.player = player.Player(self.world, self.shader, self.width, self.height) self.world.player = self.player # pyglet stuff pyglet.clock.schedule(self.player.update_interpolation) pyglet.clock.schedule_interval(self.update, 1 / 600) self.window.mouse_captured = False # misc stuff self.holding = 50 # bind textures gl.glActiveTexture(gl.GL_TEXTURE0) gl.glBindTexture(gl.GL_TEXTURE_2D_ARRAY, self.world.texture_manager.texture_array) gl.glUniform1i(self.shader_sampler_location, 0) # enable cool stuff gl.glEnable(gl.GL_DEPTH_TEST) gl.glEnable(gl.GL_CULL_FACE) gl.glBlendFunc(gl.GL_SRC_ALPHA, gl.GL_ONE_MINUS_SRC_ALPHA) if self.options.ANTIALIASING: gl.glEnable(gl.GL_MULTISAMPLE) gl.glEnable(gl.GL_SAMPLE_ALPHA_TO_COVERAGE) gl.glSampleCoverage(0.5, gl.GL_TRUE) # controls stuff self.controls = [0, 0, 0] # joystick stuff self.joystick_controller = joystick.Joystick_controller(self) # mouse and keyboard stuff self.keyboard_mouse = keyboard_mouse.Keyboard_Mouse(self) # music stuff logging.info("Loading audio") try: self.music = [ pyglet.media.load(os.path.join("audio/music", file)) for file in os.listdir("audio/music") if os.path.isfile(os.path.join("audio/music", file)) ] except: self.music = [] self.media_player = pyglet.media.Player() self.media_player.volume = 0.5 if len(self.music) > 0: self.media_player.queue(random.choice(self.music)) self.media_player.play() self.media_player.standby = False else: self.media_player.standby = True self.media_player.next_time = 0 # GPU command syncs self.fences = deque()
import shader from pyglet.gl import * from math import pi, sin, cos, sqrt from euclid import * window = pyglet.window.Window(width=480, height=360, caption="Where The Light Breaks.") window.set_mouse_visible(False) pyglet.gl.glClearColor(0.4, 0.4, 1, 1) v_shader = open("./resources/shader/v2.sh", "r") f_shader = open("./resources/shader/f2.sh", "r") shader = shader.Shader([v_shader.read()], [f_shader.read()]) #pyglet.gl.glEnable(GL_BLEND) #pyglet.gl.glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA) player = player.Player( pyglet.sprite.Sprite(img=resources.player_frames[0], x=100, y=400, usage="dynamic")) player.frames = resources.player_frames game_objects = [] tile_batch = pyglet.graphics.Batch()
mandelbrot_shader = shader_module.Shader([ shader_module.ProgramShaderFragment(""" #extension GL_EXT_gpu_shader4 : enable /*for "%"*/ #if """ + str(int(use_double_precision)) + """ #extension GL_ARB_gpu_shader_fp64 : enable #define FVEC2 dvec2 #define FLOAT double #define LOG(X) FLOAT(log(float(X))) #else #define FVEC2 vec2 #define FLOAT float #define LOG(X) log(X) #endif #define NUM_COLORS 16 #define MAX_ITERS """ + str(iterations) + """ #define ANTIALIAS """ + str(antialias) + """ uniform FVEC2 bounds_x; uniform FVEC2 bounds_y; uniform FVEC2 screen_size; vec3 get_color(int iter) { switch (iter%16) { case 0: return vec3(241,233,191); case 1: return vec3(248,201, 95); case 2: return vec3(255,170, 0); case 3: return vec3(204,108, 0); case 4: return vec3(153, 87, 0); case 5: return vec3(106, 52, 3); case 6: return vec3( 66, 30, 15); case 7: return vec3( 25, 7, 26); case 8: return vec3( 9, 1, 47); case 9: return vec3( 4, 4, 73); case 10: return vec3( 0, 7,100); case 11: return vec3( 12, 44,138); case 12: return vec3( 24, 82,177); case 13: return vec3( 57,125,209); case 14: return vec3(134,181,229); case 15: return vec3(211,236,248); } } int shade_index(int iter) { return iter; } FLOAT shadesmooth_index(int iter, FVEC2 position) { FLOAT normal_iter = FLOAT(iter) - LOG(LOG(length(position))) / LOG(2.0); return (normal_iter+0.5) * """ + str(1.0 / smooth_shading_scale) + """; } FVEC2 complex_sq(FVEC2 z) { FVEC2 temp1 = z * z; FLOAT temp2 = z.x * z.y; return FVEC2(temp1.x-temp1.y,temp2+temp2); } //FVEC2 complex_mul(FVEC2 a, FVEC2 b) { // return FVEC2(a.x*b.x-a.y*b.y,a.y*b.x+a.x*b.y); //} //FVEC2 complex_add(FVEC2 a, FVEC2 b) { // return a + b; //} vec3 sample(FVEC2 c) { FVEC2 z = c; for (int i=0;i<MAX_ITERS;++i) { //z = complex_add(complex_mul(z,z),c); z = complex_sq(z) + c; //Want to calculate if length(z)>some radius. If it is, then we stop. //The minimum radius is 2.0, but smooth shading requires more to converge. FLOAT z_dot_z = dot(z,z); //z.x*z.x and z.y*z.y are also cool #if """ + str(int(not use_smooth_shading)) + """ //simple shading if (z_dot_z>2.0*2.0) { return vec3(get_color(shade_index(i))/255.0); } #else //smooth shading if (z_dot_z>8.0*8.0) { FLOAT index = shadesmooth_index(i,z); //gl_FragData[0] = vec4(vec3(index),1.0); int index2 = int(index); index -= FLOAT(index2); return vec3((get_color(index2)*(1.0-index)+get_color(index2+1)*index)/255.0); } #endif } return vec3(0.0,0.0,0.0); } void main(void) { vec4 color = vec4(0.0,0.0,0.0, 1.0); for (int y=0;y<ANTIALIAS;++y) { for (int x=0;x<ANTIALIAS;++x) { FVEC2 pixel = FVEC2(gl_FragCoord.xy) + FVEC2(-0.5+(FLOAT(x)+0.5)/FLOAT(ANTIALIAS),-0.5+(FLOAT(y)+0.5)/FLOAT(ANTIALIAS)); FVEC2 c = pixel/screen_size * FVEC2(bounds_x.y-bounds_x.x,bounds_y.y-bounds_y.x) + FVEC2(bounds_x.x,bounds_y.x); color.rgb += sample(c); } } color.rgb /= float(ANTIALIAS*ANTIALIAS); gl_FragData[0] = color; } """) ])
def __init__(self, **args): super().__init__(**args) # create blocks self.texture_manager = texture_manager.Texture_manager(16, 16, 256) self.cobblestone = block_type.Block_type(self.texture_manager, "cobblestone", {"all": "cobblestone"}) self.grass = block_type.Block_type(self.texture_manager, "grass", { "top": "grass", "bottom": "dirt", "sides": "grass_side" }) self.dirt = block_type.Block_type(self.texture_manager, "dirt", {"all": "dirt"}) self.stone = block_type.Block_type(self.texture_manager, "stone", {"all": "stone"}) self.sand = block_type.Block_type(self.texture_manager, "sand", {"all": "sand"}) self.planks = block_type.Block_type(self.texture_manager, "planks", {"all": "planks"}) self.log = block_type.Block_type(self.texture_manager, "log", { "top": "log_top", "bottom": "log_top", "sides": "log_side" }) self.texture_manager.generate_mipmaps() # create vertex array object self.vao = gl.GLuint(0) gl.glGenVertexArrays(1, ctypes.byref(self.vao)) gl.glBindVertexArray(self.vao) # create vertex position vbo self.vertex_position_vbo = gl.GLuint(0) gl.glGenBuffers(1, ctypes.byref(self.vertex_position_vbo)) gl.glBindBuffer(gl.GL_ARRAY_BUFFER, self.vertex_position_vbo) gl.glBufferData( gl.GL_ARRAY_BUFFER, ctypes.sizeof(gl.GLfloat * len(self.grass.vertex_positions)), (gl.GLfloat * len(self.grass.vertex_positions))(*self.grass.vertex_positions), gl.GL_STATIC_DRAW) gl.glVertexAttribPointer(0, 3, gl.GL_FLOAT, gl.GL_FALSE, 0, 0) gl.glEnableVertexAttribArray(0) # create tex coord vbo self.tex_coord_vbo = gl.GLuint(0) gl.glGenBuffers(1, ctypes.byref(self.tex_coord_vbo)) gl.glBindBuffer(gl.GL_ARRAY_BUFFER, self.tex_coord_vbo) gl.glBufferData(gl.GL_ARRAY_BUFFER, ctypes.sizeof(gl.GLfloat * len(self.grass.tex_coords)), (gl.GLfloat * len(self.grass.tex_coords))(*self.grass.tex_coords), gl.GL_STATIC_DRAW) gl.glVertexAttribPointer(1, 3, gl.GL_FLOAT, gl.GL_FALSE, 0, 0) gl.glEnableVertexAttribArray(1) # create index buffer object self.ibo = gl.GLuint(0) gl.glGenBuffers(1, self.ibo) gl.glBindBuffer(gl.GL_ELEMENT_ARRAY_BUFFER, self.ibo) gl.glBufferData(gl.GL_ELEMENT_ARRAY_BUFFER, ctypes.sizeof(gl.GLuint * len(self.grass.indices)), (gl.GLuint * len(self.grass.indices))(*self.grass.indices), gl.GL_STATIC_DRAW) # create shader self.shader = shader.Shader("vert.glsl", "frag.glsl") self.shader_sampler_location = self.shader.find_uniform( b"texture_array_sampler") self.shader.use() # pyglet stuff pyglet.clock.schedule_interval(self.update, 1.0 / 60) self.mouse_captured = False # camera stuff self.camera = camera.Camera(self.shader, self.width, self.height)