def __init__(self): ''' Initializes a new render engine. Creates the display and inits the renderers. ''' # has to be the first call because it calls glfw.init() self.wm = WindowManager(RenderEngine.WINDOW_WIDTH, RenderEngine.WINDOW_HEIGHT, RenderEngine.FPS_CAP) self.renderer = Renderer()
def __init__(self, data) : self.mistery_flower = [4.5, 1]; self.learning_rate = 0.2; self.costs = []; self.data = data; self.render = Renderer(); self.w1 = np.random.randn(); self.w2 = np.random.randn(); self.b = np.random.randn(); CC = [4.5, 1]; T = np.linspace(-20, 20 , 100); Y = self.sigmoid(T); Y_P = self.sigmoid_pred(T); #print(T); #print(Y); #self.render.scatter(self.data); self.trainNN(); #self.printResults(); z = self.mistery_flower[0] * self.w1 + self.mistery_flower[0] * self.w2 + self.b; pred = self.sigmoid(z); print(pred); return; self.render.renderSigmoid(T, Y, 'r'); self.render.renderSigmoid(T, Y_P, 'b'); self.render.renderSigmoidPlt();
def __init__(self): pygame.init() self.size = self.width, self.height = 640, 640 self.screen = pygame.display.set_mode(self.size) pygame.display.set_caption('Traveling Salesman Problem') self.clock = pygame.time.Clock() self.renderer = Renderer(self) self.calculator = Calculator(self) self.saved_points = [] self.screenshot_requested = False while True: events = pygame.event.get() for event in events: if event.type == pygame.QUIT: sys.exit() if event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE: sys.exit() self.update(events) self.renderer.draw(self.screen) if self.screenshot_requested: util.save_screenshot(self) self.screenshot_requested = False pygame.display.flip()
def write(self, fhOrFilename): if isinstance(fhOrFilename, str): fh = open(fhOrFilename, 'w+') else: fh = fhOrFilename r = Renderer() r.Write(self, fh)
def adjusterInit(self): # print("-------" + self.outputAdjustDataPath) self.adjusters = [] self.renderer = Renderer() print(self.outputAdjustDataPath) # 读文件,如果存在的话 if os.path.exists(self.outputAdjustDataPath): with open(self.outputAdjustDataPath, "r") as f: self.outputAdjustData = f.read() adjustDataDict = json.loads(self.outputAdjustData) # print(adjustDataDict) # outer loop run only once... for adjustItem in adjustDataDict[self.outputAdjustDataPath]: for key in adjustItem: d = adjustItem[key] self.adjusters.append( AdjusterFactory.createAdjuster(key, d)) else: len(self.adjusters) for adjusterName in AdjusterFactory.defaultAdjustersNames: self.adjusters.append( AdjusterFactory.createAdjuster(adjusterName))
def __init__(self, default=None): if default is None: from Renderer import Renderer default = Renderer() Facility.__init__(self, name="renderer", default=default) return
def on_init(self): pygame.init() pygame.display.set_caption('Simulation') self.renderer = Renderer(self.env, self.size, self.info_panel_size, self.info_panel_pos, fps=self.fps)
def __init__(self, renderer=None): if renderer is None: from Renderer import Renderer renderer = Renderer() self.renderer = renderer return
def __init__(self): super().__init__() self.add_component('renderer', Renderer()) self.add_component( 'physics', Physics(CIRCLE_MASS, CIRCLE_S_FRICTION, CIRCLE_K_FRICTION, Vector2D(0, 0))) self.add_component('body', Body.Circle(0, Vector2D(300, 300), 50, 30)) self.add_component('controller', Controller.CircleController())
def Setup(self): ''' Set up the main level - can usually be guaranteed to run before Run() ''' glEnable(GL_DEPTH_TEST) if not self._setup: # This starts threads and stuff, so don't grunk up anything by self._renderer = Renderer(self.Window(), self._camera) self._renderer.Setup() self._setup = True
def __init__(self): super().__init__() self.add_component('controller', Controller.PlayerController()) self.add_component('renderer', Renderer()) self.add_component( 'body', Body.Polygon(0, Vector2D(100, 100), 30, PLAYER_SHAPE_VECTOR)) self.add_component( 'physics', Physics(PLAYER_MASS, PLAYER_STATIC_FRICTION, PLAYER_KINETIC_FRICTION, Vector2D(0, 0)))
def main(self): args = self.parser.parse_args(sys.argv[1:]) self.func = Function(args.function) self.renderer = Renderer() self.func.expand_eval(complex(args.z0), complex(args.a)) points = [] for i in range(0, int(args.degree)): points.append(self.func.next_term()) self.renderer.addPoints(points) filename = 'spectralEval' + args.function + '.png' self.renderer.image.save('output.png', 'PNG') print('Saved .png to this directory.') self.renderer.dump() print('Dumped points as .json file in this directory.')
def runLoop(self): exit = False buttonPressed = False imageIndex = int(self.config.get('Images', 'current')) timeout = int(self.config.get('Display', 'timeout')) maxImageIndex = len(self.imageList) lastActivity = time.time() self.displayData = self.images.getFileData(imageIndex) self.renderer = Renderer(self.config, self.displayData, self.interface) self.interface.scytheHome() self.renderer.blank() while (not exit): buttons = self.interface.buttons() if not buttonPressed and buttons != 0: buttonPressed = True lastActivity = time.time() # 1 = select # 2 = right # 4 = down # 8 = up # 16 = left if buttons == 1: print('select') self.interface.off() sys.exit(0) if buttons == 8: print('up') if imageIndex > 0: imageIndex = imageIndex - 1 self.displayData = self.images.getFileData(imageIndex) self.displayImage(imageIndex) if buttons == 4: print('down') if imageIndex + 1 < maxImageIndex: imageIndex = imageIndex + 1 self.displayData = self.images.getFileData(imageIndex) self.displayImage(imageIndex) if buttons == 2: print('right') if buttons == 16: print('left') elif buttonPressed and buttons == 0: buttonPressed = False if time.time() - lastActivity > timeout: self.interface.off()
def __init__(self, width, height, title): self.__width = width self.__height = height self.__title = title self.__should_close = False self.__objects = [] # Init SDL, create window and renderer SDL_Init(SDL_INIT_EVERYTHING) self.__window = SDL_CreateWindow(title.encode("ASCII"), SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, int(width * cf.SCALE), int(height * cf.SCALE), 0) self.renderer = Renderer(self.__width, self.__height, self.__window)
def main(): title = "Game!" target_fps = 60 pygame.init() size = (720,480) renderer = Renderer(size) polygons = [] current_polygon = Polygon() prev_time = time.time() RUN = True while RUN: for polygon in polygons: polygon.draw(renderer) current_polygon.draw(renderer) renderer.update() for event in pygame.event.get(): if event.type == pygame.MOUSEMOTION: current_polygon.point = event.pos if event.type == pygame.MOUSEBUTTONDOWN: current_polygon.vertices.append(event.pos) if event.type == pygame.KEYDOWN: if(event.key == pygame.K_RETURN): current_polygon.close() #merges overlapping polygons, removeing them from the list of polygons and adding the new merged polygon polygons = list(filter(lambda polygon:not current_polygon.try_merge(polygon) ,polygons)) polygons.append(current_polygon) current_polygon = Polygon() if event.type == pygame.QUIT: RUN = False curr_time = time.time() diff = curr_time - prev_time delay = max(1.0/target_fps - diff, 0) time.sleep(delay) fps = 1.0/(delay + diff) prev_time = curr_time pygame.display.set_caption("{0}: {1:.2f}".format(title, fps))
def run(): bounds = (1000, 1000) engine = Engine(bounds) # mass_1 = Mass(100000,1,500,500, 0, 0) # engine.add_mass(mass_1) agent_1 = RandomAgent(100000, 1, 500, 500) engine.add_mass(agent_1) renderer = Renderer(engine, bounds) renderer.start() def step(): global steps engine.step() steps += 1 frame_time = 1 / FPS while (renderer.is_running): run_frame(step, frame_time)
def __init__(self, window): pygame.init() self.window = window self.event_handler = EventHandler() self.renderer = Renderer(window) self.data = Data(10, 300, 64) self.buttons = [ RandomizeButton(BLACK, 25, 25, 125, 25, 'Randomize Data', WHITE, self.data), SorterButton(BLACK, 175, 25, 125, 25, 'Bubble Sort', WHITE, BubbleSorter(self.renderer), self.data), SorterButton(BLACK, 325, 25, 125, 25, 'Selection Sort', WHITE, SelectionSorter(self.renderer), self.data), SorterButton(BLACK, 475, 25, 125, 25, 'Insertion Sort', WHITE, InsertionSorter(self.renderer), self.data), SorterButton(BLACK, 625, 25, 125, 25, 'Merge Sort', WHITE, MergeSorter(self.renderer), self.data), SorterButton(BLACK, 775, 25, 125, 25, 'Quick Sort', WHITE, QuickSorter(self.renderer), self.data) ] self.event_handler.register_buttons(self.buttons) self.renderer.register_buttons(self.buttons) self.renderer.register_data(self.data)
def _createRenderer(self): from Renderer import Renderer return Renderer()
mod = getattr(mod, submodule) return mod # Main if __name__ == "__main__": envName = "SnakeGame" if len(sys.argv) > 1: envName = sys.argv[1] agentName = "HumanAgent" if len(sys.argv) > 2: agentName = sys.argv[2] # Create env print (f"Creating env {envName}") Environment = importModule(f'Environments.{envName}').Environment env = Environment() # Load agent print(f"Starting agent {agentName}") Agent = importModule(f'Agents.{agentName}').Agent agent = Agent() # Create renderer renderer = Renderer(512, 384) while True: renderer.clock.tick(10) agent.step(env, renderer) renderer.pollEvents() renderer.draw(env.render)
def __init__(self, N, H): super().__init__() assert (N > 0) assert (H > 0) net = [nn.Linear(3, H), nn.LeakyReLU(0.1)] for i in range(0, N): net += [nn.Linear(H, H), nn.LeakyReLU(0.1)] net += [nn.Linear(H, 1), nn.LeakyReLU(0.1)] self.model = nn.Sequential(*net) def forward(self, x): x = self.model(x) output = torch.tanh(x) return output if __name__ == '__main__': sdf = NeuralImplicit() sdf.encode('wave.sdf') sdf.load('_apple_entity_wave.pth') campos = torch.Tensor([0, 0, 2]) at = torch.Tensor([0, 0, 0]) width = 128 height = 128 tol = 0.001 renderer = Renderer(sdf.model, campos, at, width, height, tol) renderer.render() # renderer.showImage() renderer.save('apple.png')
def create_window(self, width: int, height: int, name="default"): self.__renderer = Renderer(width, height, name)
def main(stdscr): menu = Menu(stdscr) response = None key = Key(Note(c.NOTE_C)) menu.set_response("Current key: " + str(key)) option = -1 while option != c.OPTN_EXIT: menu.display(options_dict=c.MAIN_MENU_DICT, header="Main Menu") menu.printstr("Pick an option: ") option = int(menu.read_input()) if option == c.OPTN_CHOOSE_KEY: menu.printstr("New key: ") new_key_str = menu.read_input() note_str = parse_note(new_key_str) if note_str is None: menu.set_response(new_key_str + " is not a valid key!") else: root = Note(name=note_str[0], accidental=note_str[1]) key.set_tonic(root) # check if key is minor if ("minor" in new_key_str) or ("min" in new_key_str): key.set_tonality(c.TONALITY_MINOR) else: key.set_tonality(c.TONALITY_MAJOR) menu.set_response("Key updated! New key is " + str(key)) elif option == c.OPTN_GET_NOTES_IN_KEY: s = "" for n in key.get_notes(): s += str(n) + " " menu.set_response(s) elif option == c.OPTN_GET_CHORDS_IN_KEY: s = "" for chord in key.get_chords(): s += str(chord) + " " s += "\n" + key.get_chord_numerals() menu.set_response(s) elif option == c.OPTN_GET_INTERVALS: pass elif option == c.OPTN_VIEW_INSTRUMENT: fretboard = GuitarFretboard() renderer = Renderer() sub_option = -1 while sub_option != c.OPTN_BACK: menu.display(options_dict=c.INSTRUMENT_MENU_DICT, header="Instrument Viewer") menu.printstr("Pick an option: ") sub_option = int(menu.read_input()) if sub_option == c.OPTN_DISPLAY_ROOTS: root = key.get_tonic() fretboard_str = renderer.plot(root) response = "Displaying all roots of " + str(root) + ".\n\n" menu.set_response(response + fretboard_str) elif sub_option == c.OPTN_DISPLAY_NOTES_IN_KEY: fretboard_str = renderer.plot(key.get_notes()) response = "Displaying all notes in the key of " + str( key) + ".\n\n" menu.set_response(response + fretboard_str) elif sub_option == c.OPTN_DISPLAY_CHORD: chords = key.get_chords() chord_index = 0 cbreak() while True: curr_chord = chords[chord_index % (len(chords) - 1)] fretboard_str = renderer.plot(curr_chord) menu.refresh() menu.printstr_ln( "Press left/right arrows to cycle through chords (press any other key to go back)." ) menu.printstr_ln("Shown: " + str(curr_chord)) menu.printstr_ln(fretboard_str) user_input = stdscr.getch() if user_input == KEY_LEFT: chord_index -= 1 elif user_input == KEY_RIGHT: chord_index += 1 else: break nocbreak() elif sub_option == c.OPTN_DISPLAY_SCALE: pass else: menu.set_response("Invalid input.") else: menu.set_response("Invalid input.")
from GameEngine import GameEngine from ImpossibleGame.SpriteCan import SpriteCan from ImpossibleGame.GratedCircle import GratedCircle from ImpossibleGame.Keyboard import Keyboard from ImpossibleGame.SpriteCanController import SpriteCanController import numpy import random num_gratings = 10 sprite_can = SpriteCan() sprite_can.instantiateN(1) gratings = GratedCircle() gratings.instantiateN(num_gratings) renderer = Renderer() io = Keyboard() controller = SpriteCanController(sprite_can, io) sprite_can.set_initial_position([[-0.5, 0]]) y_pool = numpy.linspace(0, 0.5, 20) x_pool = numpy.linspace(-0.66, 0.66, 20) grating_locs = [[random.choice(x_pool), random.choice(y_pool)] for i in range(num_gratings)] gratings.set_initial_position(grating_locs) ge = GameEngine(sprite_can, gratings, renderer, io, controller)
simu_cfg = json.load(simu_cfg_file) # Ajout des objets dans le worldstate drones = simu_cfg['drones'] stations = simu_cfg['stations'] for drone in drones: battery = Battery(drone["battery"]["maxCycle"], drone["battery"]["lvl"], drone["battery"]["consumption"]) el = Drone(drone["name"],(drone["homeLocation"]["x"], drone["homeLocation"]["y"]), (drone["position"]["x"], drone["position"]["y"]), drone["position"]["z"], drone["failureFrequency"], drone["averageSpeed"], battery) WorldObjects.drones.append(el) for station in stations: chargingBatteries = [] chargedBatteries = [] for battery in station["chargingBatteries"]: chargingBatteries.append(Battery(battery["maxCycle"], battery["lvl"], battery["consumption"])) for battery in station["chargedBatteries"]: chargedBatteries.append(Battery(battery["maxCycle"],battery["lvl"], battery["consumption"])) el = Station(station["name"], (station["position"]["x"], station["position"]["y"]), chargedBatteries, station["storageCapacity"], station["chargingTime"], station["chargingSlots"], station["changeDuration"], station["failureFrequency"]) WorldObjects.stations.append(el) r = Renderer(800, 640) sch = Scheduler() sch.start() r.mainloop()
def main(): options = parse_args(constants.TOOL_RUNNER) # Save us having to pass debugging everywhere. die = functools.partial(_die, options.verbosity >= 3) log.set_verbosity(options.verbosity) def done(s): ret = 0 if s: options.outfile.write(s) options.outfile.close() sys.exit(ret) if not options.platform or options.platform in ('?', 'help') \ or options.platform not in PLATFORMS: die('Valid --platform arguments are %s' % ', '.join(PLATFORMS)) if not options.file or len(options.file) > 1: die('A single input file must be provided for this operation') # Construct the compilation cache if requested. cache = None if options.cache in ('on', 'readonly', 'writeonly'): cache = Cache(options.cache_dir) f = options.file[0] try: s = f.read() # Try to find this output in the compilation cache if possible. This is # one of two places that we check in the cache. This check will 'hit' # if the source files representing the input spec are identical to some # previous execution. if options.cache in ('on', 'readonly'): key = [ version_hash(), os.path.abspath(f.name), s, cache_relevant_options(options), options.platform, options.item ] value = cache.get(key) assert value is None or isinstance(value, FileSet), \ 'illegally cached a value for %s that is not a FileSet' % options.item if value is not None and value.valid(): # Cache hit. log.debug('Retrieved %(platform)s.%(item)s from cache' % \ options.__dict__) done(value.output) ast = parser.parse_to_ast(s, options.cpp, options.cpp_flag, options.ply_optimise) parser.assign_filenames(ast, f.name) except parser.CAmkESSyntaxError as e: e.set_column(s) die('%s:%s' % (f.name, str(e))) except Exception as inst: die('While parsing \'%s\': %s' % (f.name, inst)) try: for t in AST_TRANSFORMS[PRE_RESOLUTION]: ast = t(ast) except Exception as inst: die('While transforming AST: %s' % str(inst)) try: ast, imported = parser.resolve_imports(ast, \ os.path.dirname(os.path.abspath(f.name)), options.import_path, options.cpp, options.cpp_flag, options.ply_optimise) except Exception as inst: die('While resolving imports of \'%s\': %s' % (f.name, inst)) try: # if there are multiple assemblies, combine them now compose_assemblies(ast) except Exception as inst: die('While combining assemblies: %s' % str(inst)) # If we have a readable cache check if our current target is in the cache. # The previous check will 'miss' and this one will 'hit' when the input # spec is identical to some previous execution modulo a semantically # irrelevant element (e.g. an introduced comment). I.e. the previous check # matches when the input is exactly the same and this one matches when the # AST is unchanged. if options.cache in ('on', 'readonly'): key = [ version_hash(), ast, cache_relevant_options(options), options.platform, options.item ] value = cache.get(key) if value is not None: assert options.item not in NEVER_AST_CACHE, \ '%s, that is marked \'never cache\' is in your cache' % options.item log.debug('Retrieved %(platform)s.%(item)s from cache' % \ options.__dict__) done(value) # If we have a writable cache, allow outputs to be saved to it. if options.cache in ('on', 'writeonly'): orig_ast = deepcopy(ast) fs = FileSet(imported) def save(item, value): # Save an input-keyed cache entry. This one is based on the # pre-parsed inputs to save having to derive the AST (parse the # input) in order to locate a cache entry in following passes. # This corresponds to the first cache check above. key = [ version_hash(), os.path.abspath(options.file[0].name), s, cache_relevant_options(options), options.platform, item ] specialised = fs.specialise(value) if item == 'capdl': specialised.extend(options.elf) cache[key] = specialised if item not in NEVER_AST_CACHE: # Save an AST-keyed cache entry. This corresponds to the second # cache check above. cache[[ version_hash(), orig_ast, cache_relevant_options(options), options.platform, item ]] = value else: def save(item, value): pass ast = parser.dedupe(ast) try: ast = parser.resolve_references(ast) except Exception as inst: die('While resolving references of \'%s\': %s' % (f.name, inst)) try: parser.collapse_references(ast) except Exception as inst: die('While collapsing references of \'%s\': %s' % (f.name, inst)) try: for t in AST_TRANSFORMS[POST_RESOLUTION]: ast = t(ast) except Exception as inst: die('While transforming AST: %s' % str(inst)) try: resolve_hierarchy(ast) except Exception as inst: die('While resolving hierarchy: %s' % str(inst)) # All references in the AST need to be resolved for us to continue. unresolved = reduce(lambda a, x: a.union(x), map(lambda x: x.unresolved(), ast), set()) if unresolved: die('Unresolved references in input specification:\n %s' % \ '\n '.join(map(lambda x: '%(filename)s:%(lineno)s:\'%(name)s\' of type %(type)s' % { 'filename':x.filename or '<unnamed file>', 'lineno':x.lineno, 'name':x._symbol, 'type':x._type.__name__, }, unresolved))) # Locate the assembly assembly = [x for x in ast if isinstance(x, AST.Assembly)] if len(assembly) > 1: die('Multiple assemblies found') elif len(assembly) == 1: assembly = assembly[0] else: die('No assembly found') obj_space = ObjectAllocator() obj_space.spec.arch = options.architecture cspaces = {} pds = {} conf = assembly.configuration shmem = defaultdict(dict) templates = Templates(options.platform) map(templates.add_root, options.templates) r = Renderer(templates.get_roots(), options) # The user may have provided their own connector definitions (with # associated) templates, in which case they won't be in the built-in lookup # dictionary. Let's add them now. Note, definitions here that conflict with # existing lookup entries will overwrite the existing entries. for c in (x for x in ast if isinstance(x, AST.Connector)): if c.from_template: templates.add(c.name, 'from.source', c.from_template) if c.to_template: templates.add(c.name, 'to.source', c.to_template) # We're now ready to instantiate the template the user requested, but there # are a few wrinkles in the process. Namely, # 1. Template instantiation needs to be done in a deterministic order. The # runner is invoked multiple times and template code needs to be # allocated identical cap slots in each run. # 2. Components and connections need to be instantiated before any other # templates, regardless of whether they are the ones we are after. Some # other templates, such as the Makefile depend on the obj_space and # cspaces. # 3. All actual code templates, up to the template that was requested, # need to be instantiated. This is related to (1) in that the cap slots # allocated are dependent on what allocations have been done prior to a # given allocation call. # Instantiate the per-component source and header files. for id, i in enumerate(assembly.composition.instances): # Don't generate any code for hardware components. if i.type.hardware: continue if i.address_space not in cspaces: p = Perspective(phase=RUNNER, instance=i.name, group=i.address_space) cnode = obj_space.alloc(seL4_CapTableObject, name=p['cnode'], label=i.address_space) cspaces[i.address_space] = CSpaceAllocator(cnode) pd = obj_space.alloc(seL4_PageDirectoryObject, name=p['pd'], label=i.address_space) pds[i.address_space] = pd for t in ('%s.source' % i.name, '%s.header' % i.name, '%s.linker' % i.name): try: template = templates.lookup(t, i) g = '' if template: g = r.render(i, assembly, template, obj_space, cspaces[i.address_space], \ shmem, options=options, id=id, my_pd=pds[i.address_space]) save(t, g) if options.item == t: if not template: log.warning('Warning: no template for %s' % options.item) done(g) except Exception as inst: die('While rendering %s: %s' % (i.name, inst)) # Instantiate the per-connection files. conn_dict = {} for id, c in enumerate(assembly.composition.connections): tmp_name = c.name key_from = (c.from_instance.name + '_' + c.from_interface.name) in conn_dict key_to = (c.to_instance.name + '_' + c.to_interface.name) in conn_dict if not key_from and not key_to: # We need a new connection name conn_name = 'conn' + str(id) c.name = conn_name conn_dict[c.from_instance.name + '_' + c.from_interface.name] = conn_name conn_dict[c.to_instance.name + '_' + c.to_interface.name] = conn_name elif not key_to: conn_name = conn_dict[c.from_instance.name + '_' + c.from_interface.name] c.name = conn_name conn_dict[c.to_instance.name + '_' + c.to_interface.name] = conn_name elif not key_from: conn_name = conn_dict[c.to_instance.name + '_' + c.to_interface.name] c.name = conn_name conn_dict[c.from_instance.name + '_' + c.from_interface.name] = conn_name else: continue for t in (('%s.from.source' % tmp_name, c.from_instance.address_space), ('%s.from.header' % tmp_name, c.from_instance.address_space), ('%s.to.source' % tmp_name, c.to_instance.address_space), ('%s.to.header' % tmp_name, c.to_instance.address_space)): try: template = templates.lookup(t[0], c) g = '' if template: g = r.render(c, assembly, template, obj_space, cspaces[t[1]], \ shmem, options=options, id=id, my_pd=pds[t[1]]) save(t[0], g) if options.item == t[0]: if not template: log.warning('Warning: no template for %s' % options.item) done(g) except Exception as inst: die('While rendering %s: %s' % (t[0], inst)) c.name = tmp_name # The following block handles instantiations of per-connection # templates that are neither a 'source' or a 'header', as handled # above. We assume that none of these need instantiation unless we are # actually currently looking for them (== options.item). That is, we # assume that following templates, like the CapDL spec, do not require # these templates to be rendered prior to themselves. # FIXME: This is a pretty ugly way of handling this. It would be nicer # for the runner to have a more general notion of per-'thing' templates # where the per-component templates, the per-connection template loop # above, and this loop could all be done in a single unified control # flow. for t in (('%s.from.' % c.name, c.from_instance.address_space), ('%s.to.' % c.name, c.to_instance.address_space)): if not options.item.startswith(t[0]): # This is not the item we're looking for. continue try: # If we've reached here then this is the exact item we're # after. template = templates.lookup(options.item, c) if template is None: raise Exception('no registered template for %s' % options.item) g = r.render(c, assembly, template, obj_space, cspaces[t[1]], \ shmem, options=options, id=id, my_pd=pds[t[1]]) save(options.item, g) done(g) except Exception as inst: die('While rendering %s: %s' % (options.item, inst)) # Perform any per component simple generation. This needs to happen last # as this template needs to run after all other capabilities have been # allocated for id, i in enumerate(assembly.composition.instances): # Don't generate any code for hardware components. if i.type.hardware: continue assert i.address_space in cspaces if conf and conf.settings and [x for x in conf.settings if \ x.instance == i.name and x.attribute == 'simple' and x.value]: for t in ('%s.simple' % i.name, ): try: template = templates.lookup(t, i) g = '' if template: g = r.render(i, assembly, template, obj_space, cspaces[i.address_space], \ shmem, options=options, id=id, my_pd=pds[i.address_space]) save(t, g) if options.item == t: if not template: log.warning('Warning: no template for %s' % options.item) done(g) except Exception as inst: die('While rendering %s: %s' % (i.name, inst)) # Derive a set of usable ELF objects from the filenames we were passed. elfs = {} for e in options.elf: try: name = os.path.basename(e) if name in elfs: raise Exception( 'duplicate ELF files of name \'%s\' encountered' % name) elf = ELF(e, name, options.architecture) p = Perspective(phase=RUNNER, elf_name=name) group = p['group'] # Avoid inferring a TCB as we've already created our own. elf_spec = elf.get_spec(infer_tcb=False, infer_asid=False, pd=pds[group], use_large_frames=options.largeframe) obj_space.merge(elf_spec, label=group) elfs[name] = (e, elf) except Exception as inst: die('While opening \'%s\': %s' % (e, inst)) if options.item in ('capdl', 'label-mapping'): # It's only relevant to run these filters if the final target is CapDL. # Note, this will no longer be true if we add any other templates that # depend on a fully formed CapDL spec. Guarding this loop with an if # is just an optimisation and the conditional can be removed if # desired. for f in CAPDL_FILTERS: try: # Pass everything as named arguments to allow filters to # easily ignore what they don't want. f(ast=ast, obj_space=obj_space, cspaces=cspaces, elfs=elfs, options=options, shmem=shmem) except Exception as inst: die('While forming CapDL spec: %s' % str(inst)) # Instantiate any other, miscellaneous template. If we've reached this # point, we know the user did not request a code template. try: template = templates.lookup(options.item) if template: g = r.render(assembly, assembly, template, obj_space, None, \ shmem, imported=imported, options=options) save(options.item, g) done(g) except Exception as inst: die('While rendering %s: %s' % (options.item, inst)) die('No valid element matching --item %s' % options.item)
import pygame from Keyboard import Keyboard from Renderer import Renderer from Wheel import Wheel from Car import Car from NewGround import NewGround from Physics import Vector, Point, Function # init R = Renderer(1000, 500) K = Keyboard() NG = NewGround() ground_display = 500 / R.scale WF = Wheel(NG, 128, -800) # front wheel WB = Wheel(NG, 0, -800) # back wheel C = Car(WB, WF) run = True # main loop while run: R.delay(20) # event handle for event in pygame.event.get(): if event.type == pygame.QUIT: run = False K.check(C)
# from Parser import Parser default_parser = Parser() def parse(stream, *args): return default_parser.parse(stream, *args) def parse_file(filename, *args): return parse(open(filename), *args) from Renderer import Renderer default_renderer = Renderer() def render(scatterer, renderer=None): '''render(scatterer) --> text of the xml file - Inputs: scatterer: scatterer hierarchy - return: a list of strings ''' if renderer is None: renderer = default_renderer class Options: pass options = Options()
def __init__(self): super().__init__() self.add_component('body', Body.Circle(0, (0, 0), 0, 3, False)) self.add_component('renderer', Renderer())
# Imports import Color from Vector import vec from Sprite import Sprite from Renderer import Renderer from Animation import Animation from TransformationGraph import Transform from ResourceManager import ResourceManager #-------------------------------------------------------# window = pyglet.window.Window(800, 600) winDimensions = [800, 600] rendMan = Renderer(winSize=winDimensions) Renderer.activeRenderer = rendMan sg = rendMan.getSceneGraph() rm = ResourceManager("Tests\\data") ResourceManager.activeManager = rm rm.registerExtension(".jpg", "img", ["img"], pyglet.image.load) rm.registerExtension(".bmp", "img", ["img"], pyglet.image.load) rm.registerExtension(".png", "img", ["img"], pyglet.image.load) rm.registerExtension(".anim", "anim", ["anim"], Animation) anim1 = rm.request("CharizardEvolve.anim") anim2 = rm.request("PShip.anim") s1 = Sprite(anim1, t=sg.newTransform())
def make_color(self): c = Colorer() self.color = c.coder(self.data) self.r = Renderer(self.bad, self.color)