def __init__(self, scene: Scene, size: tuple[int, int] = (1280, 720), **kwargs): super().__init__(size=size) digest_config(self, kwargs) self.scene = scene self.pressed_keys = set() self.title = str(scene) self.size = size mglw.activate_context(window=self) self.timer = Timer() self.config = mglw.WindowConfig(ctx=self.ctx, wnd=self, timer=self.timer) self.timer.start() # No idea why, but when self.position is set once # it sometimes doesn't actually change the position # to the specified tuple on the rhs, but doing it # twice seems to make it work. ¯\_(ツ)_/¯ initial_position = self.find_initial_position(size) self.position = initial_position self.position = initial_position
def __init__(self, renderer, size=None, **kwargs): if size is None: # Default to making window half the screen size # but make it full screen if --fullscreen is passed in monitors = get_monitors() mon_index = config.window_monitor monitor = monitors[min(mon_index, len(monitors) - 1)] window_width = monitor.width if not config.fullscreen: window_width //= 2 window_height = int(window_width * config.frame_height // config.frame_width) size = (window_width, window_height) super().__init__(size=size) self.title = f"Manim Community {__version__}" self.size = size self.renderer = renderer mglw.activate_context(window=self) self.timer = Timer() self.config = mglw.WindowConfig(ctx=self.ctx, wnd=self, timer=self.timer) self.timer.start() self.swap_buffers() initial_position = self.find_initial_position(size, monitor) self.position = initial_position
def __init__(self, window_settings={}, renderer_settings={}, context_enables=DEFAULT_CONTEXT_ENABLES): Renderer.__init__(self) window_settings = {**DEFAULT_WINDOW_SETTINGS, **window_settings} renderer_settings = {**DEFAULT_RENDERER_SETTINGS, **renderer_settings} self.size = window_settings['size'] for key, value in renderer_settings.items(): setattr(self, key, value) self.context = moderngl.create_standalone_context(require=430) window_cls = import_string(window_settings["class"]) self.wnd = window_cls(**window_settings) self.context.enable(context_enables) moderngl_window.activate_context(self.wnd, self.context) self.context = self.wnd.ctx # register event methods self.wnd.resize_func = self.resize self.wnd.iconify_func = self.iconify self.wnd.key_event_func = self.key_event self.wnd.mouse_position_event_func = self.mouse_position_event self.wnd.mouse_drag_event_func = self.mouse_drag_event self.wnd.mouse_scroll_event_func = self.mouse_scroll_event self.wnd.mouse_press_event_func = self.mouse_press_event self.wnd.mouse_release_event_func = self.mouse_release_event self.wnd.unicode_char_entered_func = self.unicode_char_entered self.wnd.close_func = self.close self.set_advance_time_function(self.advance_time)
def setUpClass(cls): """Create a headless window and activate the context""" settings.WINDOW['class'] = 'moderngl_window.context.headless.Window' settings.WINDOW['size'] = cls.window_size settings.WINDOW['aspect_ratio'] = cls.aspect_ratio settings.WINDOW['gl_version'] = cls.gl_version cls.window = mglw.create_window_from_settings() mglw.activate_context(window=cls.window)
def __init__(self, scene, **kwargs): super().__init__(**kwargs) digest_config(self, kwargs) self.scene = scene self.title = str(scene) self.pressed_keys = set() self.position = self.find_initial_position() mglw.activate_context(window=self) self.timer = Timer() self.config = mglw.WindowConfig(ctx=self.ctx, wnd=self, timer=self.timer) self.timer.start()
def __init__(self, scene, **kwargs): digest_config(self, kwargs) super().__init__(**kwargs) self.scene = scene self.title = str(scene) # Put at the top of the screen self.position = (self.position[0], 0) mglw.activate_context(window=self) self.timer = Timer() self.config = mglw.WindowConfig(ctx=self.ctx, wnd=self, timer=self.timer) self.timer.start()
def __init__(self): window_cls = mglw.get_window_cls('moderngl_window.context.pyglet.Window') window = window_cls(title="GoBang", gl_version=(4, 1), size=(800, 600), ) mglw.activate_context(ctx=window.ctx) super().__init__(ctx=window.ctx, wnd=window) self.prog = self.ctx.program( vertex_shader=''' #version 330 in vec2 in_vert; in vec2 in_pos; in float in_scale; in vec4 in_color; out vec4 v_color; void main() { gl_Position = vec4(in_pos + (in_vert * in_scale), 0.0, 1.0); v_color = in_color; } ''', fragment_shader=''' #version 330 in vec4 v_color; out vec4 f_color; void main() { f_color = v_color; } ''', ) self.scale = 0.8 color = np.array([[0.0, 1.0, 0.0, 1.0]], dtype='f4') self.color_buffer = self.ctx.buffer(color.tobytes()) # self.mvp = self.prog['Mvp'] # self.mvp.write((np.array([[self.scale, 0, 0, 0], [0, self.scale, 0, 0], # [0, 0, self.scale, 0], [0, 0, 0, 1]], dtype='f4')).tobytes()) self.index_buffer = self.ctx.buffer(np.array([ 0, 1, 2, 1, 2, 3 ], 'i4').tobytes()) self.share_cache = None self.w = 0 self.h = 0
def __init__(self, renderer, size=None, **kwargs): if size is None: size = (config["pixel_width"], config["pixel_height"]) super().__init__(size=size) self.title = f"Manim Community {__version__}" self.size = size self.renderer = renderer mglw.activate_context(window=self) self.timer = Timer() self.config = mglw.WindowConfig(ctx=self.ctx, wnd=self, timer=self.timer) self.timer.start() self.swap_buffers()
def setUpClass(cls): window_cls = mglw.get_local_window_cls() cls.window = window_cls( title=cls.TestConfig.title, size=cls.TestConfig.window_size, resizable=cls.TestConfig.resizable, gl_version=cls.TestConfig.gl_version, aspect_ratio=cls.TestConfig.aspect_ratio, samples=cls.TestConfig.samples, cursor=cls.TestConfig.cursor, ) cls.config = cls.TestConfig( wnd=cls.window, ctx=cls.window.ctx, timer=None, ) cls.window.config = cls.config mglw.activate_context(window=cls.window)
def __init__(self, renderer, size=config.window_size, **kwargs): monitors = get_monitors() mon_index = config.window_monitor monitor = monitors[min(mon_index, len(monitors) - 1)] if size == "default": # make window_width half the width of the monitor # but make it full screen if --fullscreen window_width = monitor.width if not config.fullscreen: window_width //= 2 # by default window_height = 9/16 * window_width window_height = int( window_width * config.frame_height // config.frame_width, ) size = (window_width, window_height) else: size = tuple(size) super().__init__(size=size) self.title = f"Manim Community {__version__}" self.size = size self.renderer = renderer mglw.activate_context(window=self) self.timer = Timer() self.config = mglw.WindowConfig(ctx=self.ctx, wnd=self, timer=self.timer) self.timer.start() self.swap_buffers() initial_position = self.find_initial_position(size, monitor) self.position = initial_position
def _initCfg(self): # GL context self.ctx = moderngl.create_context(require=330) moderngl_window.activate_context(ctx=self.ctx) # the selected program will be used in the prepareData method self._program = None self._programs = {} # elapsed time self._elapsedTime = 0 # TODO : remove this line when moderngl is 5.7.0 self.ctx.info["GL_MAX_GEOMETRY_OUTPUT_VERTICES"] = 256 # Display minimal information on GL Device print("\nYou are using the following GL device :") for field in ["GL_VENDOR", "GL_RENDERER", "GL_VERSION", "GL_MAX_TEXTURE_SIZE", "GL_MAX_GEOMETRY_OUTPUT_VERTICES", ]: hardCoded = "" if field == "GL_MAX_GEOMETRY_OUTPUT_VERTICES": hardCoded = "(/!\ HARD-CODED /!\)" print(f" - {field} : {self.ctx.info[field]} {hardCoded}") print()
def run(pop_size, ngen, cxpb, mutpb, enable_plot=False): """ Run the parameterized experiment. :param pop_size: The size of the population. :param ngen: The number of generations. :param cxpb: The probability of a cross-over event. :param mutpb: The probability of a mutation event. :param enable_plot: A flag to enable live plotting of results. """ window_cls = mglw.get_local_window_cls() window = window_cls(title="Genetic Programming for Shader Optimization", gl_version=(4, 1), vsync=False) mglw.activate_context(ctx=window.ctx) if pop_size % 4 != 0: print("Population size must be multiple of 4") return # Parse shader ast = parse_file("resources/programs/fresnel.glsl", use_cpp=False) name, params, tree = shader.parse(ast.ext[0])[0] pset = sgp.generate_pset(name, params, tree) # Setup GP creator = sgp.setup_creator() toolbox = sgp.setup_toolbox(creator, pset, tree) sgp.setup_operators(toolbox, pset) # Setup evaluator evaluator = Evaluator(window, enable_plot=enable_plot) baseline = evaluator.determine_baseline() toolbox.register("evaluate", evaluator.eval, genesis=tree, baseline=baseline) pop = toolbox.population(n=pop_size) hof = tools.ParetoFront() # Child of tools.HallOfFame stats = tools.Statistics(lambda ind: ind.fitness.values) stats.register("avg", np.mean, axis=0) stats.register("std", np.std, axis=0) stats.register("min", np.min, axis=0) stats.register("max", np.max, axis=0) pop, log = sgp.algorithm(pop, toolbox, cxpb=cxpb, mutpb=mutpb, ngen=ngen, stats=stats, halloffame=hof, verbose=True) print(f'Hall of Fame ({len(hof)} individuals):') for individual in hof: frame_time, error = individual.fitness.values print('Fitness:') print(f'Avg Frame Time [ns]: {frame_time}') print(f'Avg Frame Error: {error}') print('Variant:') diff = shader.diff(name, params, tree, individual) sys.stdout.writelines(diff) print('') # Ensure that we write a newline
font_size=48) counter = pyglet.window.FPSDisplay(window=game_window) player_ship = None player_lives = [] score = 0 num_asteroids = 3 game_objects = [] # We need to pop off as many event stack frames as we pushed on # every time we reset the level. event_stack_size = 0 ctx = moderngl.create_context() moderngl_window.activate_context(ctx=ctx) moderngl_window.resources.register_dir( Path(__file__).resolve().parent / 'resources') quad = geometry.quad_2d(size=(800 / 600, 1.0)) fbo = ctx.framebuffer(color_attachments=ctx.texture((window_x, window_y), components=4), # depth_attachment=ctx.depth_texture((800, 600)), ) texture_program = moderngl_window.resources.programs.load( meta.ProgramDescription(path='texture.glsl')) scene = moderngl_window.resources.scenes.load( # meta.SceneDescription(path='VC/glTF/VC.gltf') meta.SceneDescription(path='Sponza/glTF/Sponza.gltf')) projection = matrix44.create_perspective_projection(90, window_x / window_y,
def __init__(self, width=512, height=512, mode='auto', resource_dir='.', quality=None, **kwargs): """""" if mode == 'auto': if is_rl_worker(): mode = 'hidden' elif is_python_script(): mode = 'window' else: mode = 'jupyter' assert mode in ['window', 'jupyter', 'hidden'] assert not (is_remote() and mode == 'window') if is_remote() and mode == 'jupyter' and quality is None: quality = 20 sys.stderr.write(REMOTE_WARNING + '\n') self._show_remote_warning = True self._use_shm = False self._shm = None self._width = width self._height = height self.window_size = (width, height) set_window_size(self.window_size) conf = Dict(get_config_dict(self)) # pyglet may crash on osx. if conf.window == 'pyglet' and is_osx(): conf.window = 'glfw' conf.update(kwargs) if mode == 'window' and is_python_script(): for k, v in vars(parse_args()).items(): if v is not None: conf[k] = v for k, v in conf.items(): self.__dict__[k] = v setup_basic_logging(conf.log_level) #logger.warning('Create app object with width %r, height %r, and the following configuration: %r', width, height, conf) if mode in ['jupyter', 'hidden']: window_cls = JupyterWindow elif mode == 'window': window_cls = mglw.get_local_window_cls(conf.window) # Hack to scale glfw window to monitor DPI. if conf.window == 'glfw': import glfw glfw.init() glfw.window_hint(0x0002200C, True) self.window = window_cls(size=(width, height), **conf) self.print_context_info(self.window) patch_method(self.window, 'clear', _clear) mglw.activate_context(window=self.window) if mode == 'hidden': self.fake_time = setup_fake_time() self.timer = Timer() ClockLeg.__init__(self, timer=self.timer) EventLeg.__init__(self, ctx=self.window.ctx, wnd=self.window, timer=self.timer) self.mode = mode self.buffer = b'' self.canvas = None if mode == 'jupyter': empty = _ime(PIL.Image.new('RGB', (width, height))) self.canvas = ipywidgets.Image(value=empty, format='JPEG') self.canvas_quality = quality or 85 self.canvas_interval = 1 / 24 if self.canvas_quality > 50 else 1 / 12 self.window._watch_canvas(self.canvas) self._run_timestamp = None self.is_running = False self.interval = 1 / 48 self.ndraws = 0 register_dir(resource_dir, callerpath()) register_dir(abspath('assets')) set_context(self.ctx) self.ctx.enable_only(moderngl.BLEND) #max_textures = self.ctx.info['GL_MAX_TEXTURE_IMAGE_UNITS'] set_shader_3d( self.load_program( vertex_shader='shaders/default-vertex-shader.glsl', fragment_shader='shaders/default-fragment-shader.glsl', )) shader = set_shader_2d(self.load_program('shaders/sprite.glsl')) shader['projection'].write(glm.ortho(0, width, 0, height, -1, 1)) self._time2draw = 0 self._time2draw_rm = 0
def __init__(self, lines=None, line_colors=None, lw=1, points=None, point_colors=None, point_r=1): self.point_r = point_r # Configure to use pyglet window window_str = 'moderngl_window.context.pyglet.Window' window_cls = moderngl_window.get_window_cls(window_str) window = window_cls( title="My Window", gl_version=(3, 3), # aspect_ratio=1.0, # resizable=False, # size=(1600, 800), ) self.wnd = window moderngl_window.activate_context(ctx=window.ctx) # self.wnd.gl_version = (3, 3) resources.register_dir(Path(__file__).parent.absolute()) self.ctx = self.wnd.ctx # register event methods self.wnd.resize_func = self.resize # self.wnd.iconify_func = self.iconify # self.wnd.key_event_func = self.key_event # self.wnd.mouse_position_event_func = self.mouse_position_event # self.wnd.mouse_drag_event_func = self.mouse_drag_event # self.wnd.mouse_scroll_event_func = self.mouse_scroll_event # self.wnd.mouse_press_event_func = self.mouse_press_event # self.wnd.mouse_release_event_func = self.mouse_release_event # self.wnd.unicode_char_entered_func = self.unicode_char_entered self.line_prog = programs.load( ProgramDescription(path="rich_lines.glsl")) self.point_prog = programs.load(ProgramDescription(path="points.glsl")) bbox = drawing_bbox(lines + points) bbox = drawing_bbox(lines + points, padding=0.05 * bbox[2]) self.bbox = bbox self.drawing_W = bbox[2] self.drawing_H = bbox[3] if len(lines) > 0: vertex, index, colors = build_buffers(lines, line_colors) vbo = self.ctx.buffer(vertex) ibo = self.ctx.buffer(index) cbo = self.ctx.buffer(colors) self.line_vao = self.ctx.vertex_array(self.line_prog, [ (vbo, "2f", "in_position"), (cbo, "4f", "in_color"), ], index_buffer=ibo) else: self.line_vao = None if len(points) > 0: point_vertex, point_color = build_point_buffers( points, point_colors) vbo = self.ctx.buffer(point_vertex) cbo = self.ctx.buffer(point_color) self.point_vao = self.ctx.vertex_array(self.point_prog, [ (vbo, "2f", "in_position"), (cbo, "4f", "in_color"), ]) else: self.point_vao = None # Set the desired properties for the lines. # Note: # - round cap/ends are used if miter_limit < 0 # - antialias value is in model space and should probably be scaled to be ~1.5px in # screen space self.line_prog["linewidth"].value = lw self.line_prog["antialias"].value = 1.5 self.line_prog["miter_limit"].value = -1 # self.line_prog["color"].value = 0, 0, 0, 1 self.update_projection()
title = "ModernGL shader view" window_size = (1024, 1024) height, width = window_size aspect_ratio = 1 / 1 resizable = True samples = 4 window_str = 'moderngl_window.context.pyglet.Window' window_cls = mglw.get_window_cls(window_str) window = window_cls( title="My Window", gl_version=(4, 1), size=(1024, 1024), aspect_ratio=aspect_ratio, ) ctx = window.ctx mglw.activate_context(ctx=ctx) with open("domain_color_util_1_glsl.txt") as file: util_shader_code = file.read() prog = ctx.program(vertex_shader=''' #version 430 in vec2 in_vert; out vec2 v_text; void main() { gl_Position = vec4(in_vert, 0.0, 1.0); v_text = in_vert; } ''',