class MainWorld (World): def __init__(self, window, player_ship_data = None, use_pygame = False, **kwargs): super( MainWorld, self ).__init__( **kwargs) self.window = window resolution = (self.window.width, self.window.height ) self.setup_graphics( resolution ) self.setup_game( player_ship_data = player_ship_data ) self.setup_input() self.setup_hud() self.camera.following = self.player self.main_layer.camera = self.camera if use_pygame: self.setup_pygame( resolution ) self.display.add_anonymous_hook( self.update_pygame ) self.pre_display.add_anonymous_hook( self.update_psys_managed_objects ) self.pre_physics.add_anonymous_hook( self.update_camera ) self.display.add_anonymous_hook( self.scene.update ) self.player.body.velocity_limit = 800.0 # experiment with this for actually chasing fleeing ships self.pre_physics.add_hook( self.player, self.player.update ) self.pre_physics.add_hook( self.enemy, lambda dt : ai.ai_seek_target( dt, self.enemy, self.player, partial( self.shoot_volley, self.enemy ) ) ) # self.pre_physics.add_hook( self.enemy, lambda dt : ai.ai_flee_target( dt, self.enemy, self.player ) ) self.pre_physics.add_hook( self.enemy, self.enemy.update ) self.pre_physics.add_hook( self.enemy2, lambda dt : ai.ai_seek_target( dt, self.enemy2, self.player, partial( self.shoot_volley, self.enemy2 ) ) ) # self.pre_physics.add_hook( self.enemy2, lambda dt : ai.ai_flee_target( dt, self.enemy2, self.player ) ) self.pre_physics.add_hook( self.enemy2, self.enemy2.update ) for x in (self.player, self.enemy, self.enemy2): self.post_physics.add_hook( x, x.tick ) x.add_to_minimap( self.minimap, "solid_white_5x5.png", (0,255,0) if x == self.player else (255,0,0) ) # for x in self.things: # x.add_to_minimap( self.minimap, "solid_white_5x5.png", (128,128,128) ) self.physics.add_anonymous_hook( self.sim.tick ) self.scene.schedule( self.update_everything ) def on_save_ship(self, *args): import sys s = self.player.dump_string() print >> sys.stderr, s self.player.dump_file( "dumped_ship.yaml" ) def update_everything(self, dt): self.tick( dt ) self.display_update() def update_camera(self, dt): self.camera.update( dt ) def setup_pygame(self, resolution): pygame.init() self.screen = pygame.display.set_mode( resolution ) def setup_graphics(self, resolution): self.camera = graphics.Camera( self.window ) self.scene = graphics.Scene( self.window ) graphics.Layer( self.scene, cocos.layer.ColorLayer( 0, 0, 0, 1 ) ) for i in range(8): graphics.Layer( self.scene, graphics.BackgroundCocosLayer( self.camera, 10.0 + 0.5 * i, "starfield{0}.png".format(i) ) ) self.hud_width = 170 self.main_layer = graphics.Layer( self.scene ) self.main_layer.cocos_layer.position = self.camera.offset() self.main_layer.size = (self.window.width-self.hud_width,self.window.height) self.hud_cocos_layer = graphics.BlankingCocosLayer() self.hud_cocos_layer.clear_colour = (0,40,40,255) self.hud_cocos_layer.clear_rect = ((self.window.width-self.hud_width,0),(self.window.width,0),(self.window.width,self.window.height),(self.window.width-self.hud_width,self.window.height)) self.hud_layer = graphics.Layer( self.scene, cocos_layer = self.hud_cocos_layer ) self.hud_layer.cocos_layer.position = 0,0 self.gem_images = pyglet.image.ImageGrid( pyglet.image.load("gems3.png"), 4, 4 ) self.atlas = Atlas( "atlas.generated" ) self.object_psys = bsgl.System( texture_id = self.atlas.sheet.get_texture().id ) self.hud_psys = bsgl.System( texture_id = self.atlas.sheet.get_texture().id ) def setup_hud(self): def update_hp_display(): undamaged = 255,255,255 undamaged_cockpit = 0,255,0 damaged = damaged_cockpit = 255,0,0 # for block, sprite in self.hud_sprite.subcomponent.items(): # rel = float(block.hp) / block.max_hp # a = damaged_cockpit if block.cockpit else damaged # b = undamaged_cockpit if block.cockpit else undamaged # sprite.color = vector_lerp( rel, a, b ) # cockpit = False def create_hp_display(): self.hud_sprite = self.player.block_structure.create_sys_structure( self.hud_psys, self.atlas, self.player, sync_to_thing = False ) expected_size = self.hud_width update_hp_display() def recreate_hp_display(): self.hud_sprite.kill() create_hp_display() bar = graphics.VerticalBar( 8, 256, (0,64,0), (128,0,0) ) bar.position = (self.window.width - self.hud_width + 16), (self.window.height - self.hud_width - bar.height) x, y = self.window.width - self.hud_width + 32, self.window.height - self.hud_width speed_label = last_element = graphics.create_label( x, y, layer = self.hud_cocos_layer ) y -= last_element.height + 8 power_supply_size_label = last_element = graphics.create_label( x, y, layer = self.hud_cocos_layer ) y -= last_element.height + 8 power_production_label = last_element = graphics.create_label( x, y, layer = self.hud_cocos_layer ) y -= last_element.height + 8 thrust_power_label = last_element = graphics.create_label( x, y, layer = self.hud_cocos_layer ) y -= last_element.height + 8 turn_power_label = last_element = graphics.create_label( x, y, layer = self.hud_cocos_layer ) y -= last_element.height + 8 brake_power_label = last_element = graphics.create_label( x, y, layer = self.hud_cocos_layer ) y -= last_element.height + 8 number_of_engines_label = last_element = graphics.create_label( x, y, layer = self.hud_cocos_layer ) y -= last_element.height + 8 number_of_guns_label = last_element = graphics.create_label( x, y, layer = self.hud_cocos_layer ) y -= last_element.height + 8 x, y = self.window.width - self.hud_width + 16, self.window.height - self.hud_width - bar.height - 16 position_label = graphics.create_label( x, y, layer = self.hud_cocos_layer ) def update_labels(): x, y = self.player.position position_label.element.text = "({0},{1})".format( int(x*0.1), int(y*0.1) ) speed_label.element.text = "S: {0:.1f}".format( self.player.speed ) power_production_label.element.text = "PP: {0}".format( int(sum( self.player.psu.production.values() ) ) ) power_supply_size_label.element.text = "MP: {0}".format( int(self.player.psu.max_storage) ) thrust_power_label.element.text = "T: {0}".format( self.player.thrust_power ) turn_power_label.element.text = "R: {0}".format( self.player.turn_power ) brake_power_label.element.text = "B: {0}".format( self.player.brake_power ) number_of_engines_label.element.text = "#E: {}".format( len( self.player.all_engines() ) ) number_of_guns_label.element.text = "#G: {0}/{1}".format( len( self.player.ready_guns() ), len( self.player.all_guns() ) ) def update_power_display(): bar.fill = self.player.psu.charge_rate() self.hud_cocos_layer.add( bar ) self.minimap = graphics.Minimap( self.hud_width - 32, self.hud_width - 32, 5000, 5000, self.player ) self.minimap.position = (self.window.width - self.hud_width + 16), (self.window.height - self.hud_width - bar.height - self.hud_width - 16) self.hud_cocos_layer.add( self.minimap ) def update_hud(): update_labels() update_hp_display() update_power_display() self.minimap.update() create_hp_display() self.post_physics.add_anonymous_hook( ignore_arguments( update_hud ) ) self.player.reshape_hooks.add_anonymous_hook( recreate_hp_display ) def setup_game(self, player_ship_data = None): self.sim = physics.PhysicsSimulator( timestep = None ) # self.player = create_ship_thing( self, self.main_layer, (500,500), shape = "small", hp = 5 ) if not player_ship_data: self.player = Ship.load_file( "current_garage_ship.yaml", self ) else: self.player = Ship.load_data( player_ship_data, self ) self.player.position = (300,300) self.player.invulnerable = False self.enemy = create_ship_thing( self, (500,500), shape = "small", hp = 10 ) self.enemy.invulnerable = False self.enemy.body.angular_velocity_limit = degrees_to_radians(144*2) self.enemy2 = create_ship_thing( self, (0,500), shape = "small", hp = 10 ) self.enemy2.invulnerable = False self.enemy2.body.angular_velocity_limit = degrees_to_radians(144*2) self.enemy.angle_degrees = random.random() * 360.0 self.enemy2.angle_degrees = random.random() * 360.0 self.batch = cocos.batch.BatchNode() self.main_layer.cocos_layer.add( self.batch ) self.physics_objects = [] self.things = [] self.psys_managed_things = [] for i in range(200): cols = "red", "purple", "grey", "blue", "green", "yellow" sq = create_square_thing( self, None, (100,0), None ) sq.position = (random.random()-0.5) * 4000, (random.random()-0.5) * 4000 sq.angle_radians = random.random() * math.pi * 2 sq.mylabel = sq.position sq.velocity = (300,10) kw = {} name = "polygon_normals.4.generated" kw[ "size" ] = Vec2d(106.6666666,106.6666666) kw[ "texture_coordinates" ] = self.atlas.texcoords( name ) kw[ "texture_size" ] = self.atlas.texsize( name ) z = random.random() * 6.28 r = 0.1 + random.random() * 10.0 pos = r*math.cos(z), r*math.sin(z) # need to translate from pixel space # [0,self. # to # [-1.3333,1.3333] x [-1,1] p = sq.position p = p + self.main_layer.cocos_layer.position p = Vec2d(p) / Vec2d( self.window.width, self.window.height ) p = (p * 2) - Vec2d(1,1) p = p * Vec2d( self.window.width / float(self.window.height), 1 ) kw[ "position" ] = p kw[ "angle" ] = sq.angle_radians kw[ "colour" ] = 1.0, 0.5, 0.5, 1.0 index = self.object_psys.add( **kw ) self.psys_managed_things.append( (sq, index) ) self.things.append( sq ) def draw_psys(): # CMSDTv # T = translate by self.main_layer.cocos_layer.position # # M = v -> v - (1,1) # C = v -> v * (w/h, 1) w = float(self.window.width) h = float(self.window.height) x, y = self.main_layer.cocos_layer.position mat = (2.0/w, 0.0, 0.0, (2*x/w-1), 0.0, 2.0/h, 0.0, (2*y/h-1), 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0) self.object_psys.set_transformation_matrix( mat ) glEnable( GL_SCISSOR_TEST ) glScissor( 0, 0, self.window.width + 1 - self.hud_width, self.window.height ) self.object_psys.draw() glDisable( GL_SCISSOR_TEST ) s = 0.3 sx, sy = 500 + self.sim._t * 100,200 sx, sy = self.window.width - self.hud_width * 0.5, self.window.height - self.hud_width * 0.5 mat = (0.0, s*2.0/w, 0.0, (2*sx/w-1), s*2.0/h, 0, 0.0, (2*sy/h-1), 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0) self.hud_psys.set_transformation_matrix( mat ) self.hud_psys.draw() graphics.Layer( self.scene, cocos_layer = graphics.FunctionCocosLayer( draw_psys ) ) self.sim.space.add_collision_handler( physics.CollisionTypes["main"], physics.CollisionTypes["bullet"], self.collide_general_with_bullet ) def setup_input(self): input_layer = graphics.Layer( self.scene, gameinput.CocosInputLayer() ) for k in (key.LEFT, key.RIGHT, key.UP, key.DOWN): input_layer.cocos_layer.set_key_hook( k, self.player.on_controls_state ) input_layer.cocos_layer.set_key_hook( k, self.player.on_controls_state ) input_layer.cocos_layer.set_key_hook( key.LSHIFT, self.player.on_controls_state ) input_layer.cocos_layer.set_key_press_hook( key.SPACE, lambda *args, **kwargs: (self.player.on_controls_state(*args,**kwargs), self.shoot_volley(self.player)) ) input_layer.cocos_layer.set_key_release_hook( key.SPACE, lambda *args, **kwargs: self.player.on_controls_state(*args,**kwargs) ) input_layer.cocos_layer.set_key_press_hook( key.P, self.on_save_ship ) def shoot_volley(self, shooter): guns = shooter.ready_guns() index = 0 for gun in guns: if not gun.may_activate(): continue gun.shoot( shooter ) gun.activated( index ) def update_pygame(self): self.screen.fill( pygame.color.THECOLORS[ "black" ] ) draw_space( self.screen, self.sim.space ) pygame.display.flip() def update_psys_managed_objects(self): for thing, index in self.psys_managed_things: self.object_psys.update_position_and_angle( index, thing.position, thing.angle_radians ) def collide_general_with_bullet(self, space, arbiter ): anything, bullet = arbiter.shapes try: thing = anything.thing index = anything.extra_info except AttributeError: bullet.thing.ttl = min( bullet.thing.ttl, 0.05 ) return False if bullet.thing.inert: return False if (bullet.thing.shooter == thing) and bullet.thing.grace > 0.0: return False try: block = thing.block_structure.blocks[ index ] hp = block.hp except KeyError: return False except AttributeError: return False bullet.thing.impact( thing = thing, block_index = index, block = block ) bullet.thing.inert = True bullet.thing.ttl = min( bullet.thing.ttl, 0.05 ) return False def run(self): self.window.run( self.scene )
def generateAtlases(self, basePath, sortOn, writer): ''' Создание атласов и их описаний. basePath путь и префикс имени файла с атласом sortOn параметр сортировки атласов (ширина или высота) writer объект для записи атласов ''' assert sortOn in ('width', 'height'), 'SortOn must be either width or height' assert writer in WRITERS, 'Unknown writer' print >> self.__log, '[AtlasManager] generating atlases' # Сортируем изображения в порядке увеличения параметра сортировки (будем искать подходящее # по размерам изображение начиная с конца. self.__images.sort(key=lambda i: getattr(i.paddedSourceRect.size, sortOn)) writer = WRITERS[writer]() # Размещаем изображения. atlasIndex = 0 while self.__images: # Количество помещенных изображений imageCount = 0 # Количество дубликатов duplicateCount = 0 atlas = Atlas(self.__maxSize, self.__log) areas = [Rect(Point(0, 0), self.__maxSize)] while areas: # Ищем изображение, максимально подходящее по размеру. area = areas.pop() image = self.__retainMostFittableImage(area.size) # Если изображение не найдено, переходим к следующей области. if image is None: continue # Размещаем изображение в верхний левый угол области и делим оставшееся пространство. atlas.placeImage(image, area.origin) areas.extend(self.__splitRect(area, image.paddedSourceRect.size, sortOn)) imageCount += 1 # Ищем оставшиеся дубликаты изображения groupImages = self.__imagesGroupedBySize[image.sourceRect.size.sizeTuple] groupImages.remove(image) for dupeImage in list(groupImages): if dupeImage.isEqual(image): groupImages.remove(dupeImage) atlas.placeImage(dupeImage, area.origin, isDuplicate=True) duplicateCount += 1 imageCount += 1 self.__images.remove(dupeImage) # Записываем атлас. if not self.__withoutOptimize: atlas.optimize() atlasName = basePath + str(atlasIndex) writer.writeAtlas(atlasName, atlas) atlasIndex += 1 print >> self.__log, ' * [AtlasManager] writing atlas "%s" (images %d, duplicates %d%%)' % (os.path.basename(atlasName), imageCount, float(duplicateCount) / imageCount * 100.0)
def setup_graphics(self, resolution): self.camera = graphics.Camera(self.window) self.scene = graphics.Scene(self.window) graphics.Layer(self.scene, cocos.layer.ColorLayer(0, 0, 0, 1)) for i in range(8): graphics.Layer( self.scene, graphics.BackgroundCocosLayer(self.camera, 10.0 + 0.5 * i, "starfield{0}.png".format(i))) self.hud_width = 170 self.main_layer = graphics.Layer(self.scene) self.main_layer.cocos_layer.position = self.camera.offset() self.main_layer.size = (self.window.width - self.hud_width, self.window.height) self.hud_cocos_layer = graphics.BlankingCocosLayer() self.hud_cocos_layer.clear_colour = (0, 40, 40, 255) self.hud_cocos_layer.clear_rect = ((self.window.width - self.hud_width, 0), (self.window.width, 0), (self.window.width, self.window.height), (self.window.width - self.hud_width, self.window.height)) self.hud_layer = graphics.Layer(self.scene, cocos_layer=self.hud_cocos_layer) self.hud_layer.cocos_layer.position = 0, 0 self.gem_images = pyglet.image.ImageGrid( pyglet.image.load("gems3.png"), 4, 4) self.atlas = Atlas("atlas.generated") self.object_psys = bsgl.System( texture_id=self.atlas.sheet.get_texture().id) self.hud_psys = bsgl.System( texture_id=self.atlas.sheet.get_texture().id)
def run_game(): # game settings cells = Group() gameset = Settings() gamestat = GameStat() atlas = Atlas(gameset) pygame.init() screen = pygame.display.set_mode((gameset.scr_width, gameset.scr_height)) pygame.display.set_caption("Conway's Game of Life") # main loop. 2 steps only for test. evolvecount = 2 while True: gf.check_events(gameset, gamestat, screen, atlas, cells) # when the mouse is pressed down, begin setcell if gamestat.setcell: gf.check_setcell(gameset, gamestat, screen, atlas, cells) print('matrix after cellset') print(atlas.matrix) # when game is on, atlas evolve itself. if not gamestat.paused: atlas.evolve() evolvecount -= 1 # create cells according to atlas, and draw them. gf.create_cells(gameset, gamestat, screen, atlas, cells) gf.update_screen(gameset, screen, atlas, cells)
def _find_atlases(self): """ Return a list of FSL atlases """ fsldir = utils.environment()["FSLDIR"] if fsldir is None: return [] atlases_dir = os.path.join(fsldir, "data", "atlases") if not os.path.isdir(atlases_dir): return [] atlases = [] for entry in os.listdir(atlases_dir): if not os.path.isfile(os.path.join(atlases_dir, entry)): continue try: atlas = Atlas.read(os.path.join(atlases_dir, entry)) except medipy.base.Exception, e: # Cannot read the atlas logging.warning("Cannot read the atlas: '{0}'".format(e)) continue else: atlases.append(atlas)
def __init__(self): pg.init() self.fps = 60 self.clock = pg.time.Clock() self.ship = Ship() self.screen = Screen(self.ship, self.clock) self.atlas = Atlas() self.fragments = Fragments(Vector(0, 0), self.atlas.dim, int(abs(self.atlas.dim) / 10)) self.all = [self.screen, self.fragments, self.ship, self.atlas]
def pack_charts(chart_list, list_cut_charts_dicts=[ dict(), ]): # List of computed packed atlases atlas_list = list() # List of the computed packed atlases' scores score_list = list() # Run for each of the cuts for cut_charts_dict in list_cut_charts_dicts: # Create a new charts dictionary for each cut chart_dict = dict(chart_list.charts) new_id = chart_list._new_id # Replace the charts with the cut charts for each affected chart for key in cut_charts_dict: cut_charts_dict[key][0].chart_id = key chart_dict[key] = cut_charts_dict[key][0] cut_charts_dict[key][1].chart_id = new_id chart_dict[new_id] = cut_charts_dict[key][1] new_id += 1 # Get a sorted list from big to small charts sorted_list_charts = _sorted_chart_dict(chart_dict) if not sorted_list_charts: raise RuntimeError('pack_charts: sorted_list_charts is empty') # Create atlas from the biggest chart atlas = Atlas.from_chart(sorted_list_charts[0]) # Pop the biggest chart sorted_list_charts.pop(0) # Run as long as the list is not empty (pop every iteration) while sorted_list_charts: _add_chart_to_atlas(atlas, sorted_list_charts.pop(0)) # Add the atlas to the list of computed packed atlases atlas_list.append(atlas) # Add the atlas's score to the list score_list.append(atlas.calc_score()) # Find the atlas with the maximal score max_score_ind = 0 for i in range(len(score_list)): if score_list[i] > score_list[max_score_ind]: max_score_ind = i # Return the atlas with the maximal score return (atlas_list[max_score_ind], score_list[max_score_ind])
def input_analysis(name: str, test: list): """ This function calulaces the input mean/variance from both the provided human input and the open pose input. :param str name: Is the name of the set in dataset diretory. :param list test: Test method if several is avaible. """ dataobj = dataset(name) atlasobj = Atlas(dataobj.setconf) dataobj.set_atlas(atlasobj) print(f"Created dataset object {name} {dataobj} size = {dataobj.count}") dataobj.create_views()
def setup_graphics(self, resolution): self.camera = graphics.Camera( self.window ) self.scene = graphics.Scene( self.window ) graphics.Layer( self.scene, cocos.layer.ColorLayer( 0, 0, 0, 1 ) ) for i in range(8): graphics.Layer( self.scene, graphics.BackgroundCocosLayer( self.camera, 10.0 + 0.5 * i, "starfield{0}.png".format(i) ) ) self.hud_width = 170 self.main_layer = graphics.Layer( self.scene ) self.main_layer.cocos_layer.position = self.camera.offset() self.main_layer.size = (self.window.width-self.hud_width,self.window.height) self.hud_cocos_layer = graphics.BlankingCocosLayer() self.hud_cocos_layer.clear_colour = (0,40,40,255) self.hud_cocos_layer.clear_rect = ((self.window.width-self.hud_width,0),(self.window.width,0),(self.window.width,self.window.height),(self.window.width-self.hud_width,self.window.height)) self.hud_layer = graphics.Layer( self.scene, cocos_layer = self.hud_cocos_layer ) self.hud_layer.cocos_layer.position = 0,0 self.gem_images = pyglet.image.ImageGrid( pyglet.image.load("gems3.png"), 4, 4 ) self.atlas = Atlas( "atlas.generated" ) self.object_psys = bsgl.System( texture_id = self.atlas.sheet.get_texture().id ) self.hud_psys = bsgl.System( texture_id = self.atlas.sheet.get_texture().id )
def test_set(name): """ Tests a set in the dataset directory. :param str name: is the name of the dataset that is loaded with this function """ # conf = None # with open('./readset.yaml','r') as f: # conf = yaml.load(f,Loader=yaml.FullLoader) print("test") datap1 = dataset(name) myatlas = Atlas(datap1.setconf) datap1.set_atlas(myatlas) print(f"Created dataset object {name} {datap1} size = {datap1.count}") datap1.create_views() print("Done. Loaded all images") datap1.show_atlas() print("builds the atlas") datap1.build_atlas() print('Sovle geometry') # datap1.geometry_solver() datap1.create_latex_img_table(4) print("end")
def __init__(self, window, continuation_with_ship=None, **kwargs): super(GarageWorld, self).__init__(**kwargs) self.window = window self.scene = graphics.Scene(self.window) self.sim = physics.PhysicsSimulator(timestep=None) self.input_layer = gameinput.CocosInputLayer() layer = graphics.Layer(self.scene, cocos.layer.ColorLayer(128, 0, 128, 255)) graphics.Layer(self.scene, cocos_layer=graphics.FunctionCocosLayer(self.draw_psys)) layer.cocos_layer.position = 0, 0 graphics.Layer(self.scene, self.input_layer) self.atlas = Atlas("atlas.generated") self.object_psys = bsgl.System( texture_id=self.atlas.sheet.get_texture().id) self.input_layer.mouse_motion_hooks.append(self.on_mouse_motion) self.main_layer = graphics.Layer(self.scene) self.root_node = cocos.cocosnode.CocosNode() self.main_layer.cocos_layer.add(self.root_node) self.continuation_with_ship = continuation_with_ship root = PolygonBlock.load_file("blocks/poly5.yaml") self.root_node.scale = 1 # for i in range(7): # a = s.attach((0,i), blocks.QuadBlock(32), 0) # b = s.attach((a,2), blocks.QuadBlock(32), 0) # c = s.attach((b,2), blocks.QuadBlock(32), 0) # d = s.attach((c,1), blocks.QuadBlock(32), 3) # self.sprite_structure = None self.garage_ship = None self.block_shapes = map( lambda n: (lambda: PolygonBlock.load_file("blocks/poly{}.yaml".format(n))), (3, 4, 5, 6, 8)) self.block_decorators = [ decorate_block_armour, decorate_block_battery, decorate_block_generator ] self.block_gun_mounter = decorate_block_with_guns_within self.block_engine_mounter = decorate_block_with_engines_within self.current_block_shape = self.block_shapes[0] self.current_block_decorator = self.block_decorators[0] self.restart_block_structure() self.mouse_index = None self.current_rotation = 0.0 self.current_position = (0, 0) self.set_current_block() self.input_layer.mouse_scroll_hooks.add_anonymous_hook( self.on_mouse_scroll) if self.continuation_with_ship: self.input_layer.set_key_press_hook(key.ENTER, self.on_continue_with_ship) self.input_layer.set_key_press_hook(key.SPACE, self.on_place_block) self.input_layer.set_key_press_hook(key.UP, self.on_next_shape) self.input_layer.set_key_press_hook(key.DOWN, self.on_previous_shape) self.input_layer.set_key_press_hook(key.RIGHT, self.on_next_decorator) self.input_layer.set_key_press_hook(key.LEFT, self.on_previous_decorator) self.input_layer.set_key_press_hook(key.R, self.on_restart_with_current) self.input_layer.set_key_press_hook(key.P, self.on_save_ship) self.input_layer.set_key_press_hook(key.L, self.on_load_ship) self.input_layer.mouse_press_hooks[mouse.RIGHT] = self.on_next_shape self.input_layer.mouse_press_hooks[mouse.LEFT] = self.on_place_block self.refresh_garage_ship() self.physics.add_anonymous_hook(self.sim.tick) self.idle_time = 0.0 self.currently_idle = False
def create_and_run(idx, Consumer): CONSUMER_CONFIG["ID"] = idx consumer = Consumer(config=CONSUMER_CONFIG) step = Atlas(consumer, config=STEP_CONFIG, level=level) step.start()
class MainWorld(World): def __init__(self, window, player_ship_data=None, use_pygame=False, **kwargs): super(MainWorld, self).__init__(**kwargs) self.window = window resolution = (self.window.width, self.window.height) self.setup_graphics(resolution) self.setup_game(player_ship_data=player_ship_data) self.setup_input() self.setup_hud() self.camera.following = self.player self.main_layer.camera = self.camera if use_pygame: self.setup_pygame(resolution) self.display.add_anonymous_hook(self.update_pygame) self.pre_display.add_anonymous_hook(self.update_psys_managed_objects) self.pre_physics.add_anonymous_hook(self.update_camera) self.display.add_anonymous_hook(self.scene.update) self.player.body.velocity_limit = 800.0 # experiment with this for actually chasing fleeing ships self.pre_physics.add_hook(self.player, self.player.update) self.pre_physics.add_hook( self.enemy, lambda dt: ai.ai_seek_target( dt, self.enemy, self.player, partial(self.shoot_volley, self.enemy))) # self.pre_physics.add_hook( self.enemy, lambda dt : ai.ai_flee_target( dt, self.enemy, self.player ) ) self.pre_physics.add_hook(self.enemy, self.enemy.update) self.pre_physics.add_hook( self.enemy2, lambda dt: ai.ai_seek_target( dt, self.enemy2, self.player, partial(self.shoot_volley, self.enemy2))) # self.pre_physics.add_hook( self.enemy2, lambda dt : ai.ai_flee_target( dt, self.enemy2, self.player ) ) self.pre_physics.add_hook(self.enemy2, self.enemy2.update) for x in (self.player, self.enemy, self.enemy2): self.post_physics.add_hook(x, x.tick) x.add_to_minimap(self.minimap, "solid_white_5x5.png", (0, 255, 0) if x == self.player else (255, 0, 0)) # for x in self.things: # x.add_to_minimap( self.minimap, "solid_white_5x5.png", (128,128,128) ) self.physics.add_anonymous_hook(self.sim.tick) self.scene.schedule(self.update_everything) def on_save_ship(self, *args): import sys s = self.player.dump_string() print >> sys.stderr, s self.player.dump_file("dumped_ship.yaml") def update_everything(self, dt): self.tick(dt) self.display_update() def update_camera(self, dt): self.camera.update(dt) def setup_pygame(self, resolution): pygame.init() self.screen = pygame.display.set_mode(resolution) def setup_graphics(self, resolution): self.camera = graphics.Camera(self.window) self.scene = graphics.Scene(self.window) graphics.Layer(self.scene, cocos.layer.ColorLayer(0, 0, 0, 1)) for i in range(8): graphics.Layer( self.scene, graphics.BackgroundCocosLayer(self.camera, 10.0 + 0.5 * i, "starfield{0}.png".format(i))) self.hud_width = 170 self.main_layer = graphics.Layer(self.scene) self.main_layer.cocos_layer.position = self.camera.offset() self.main_layer.size = (self.window.width - self.hud_width, self.window.height) self.hud_cocos_layer = graphics.BlankingCocosLayer() self.hud_cocos_layer.clear_colour = (0, 40, 40, 255) self.hud_cocos_layer.clear_rect = ((self.window.width - self.hud_width, 0), (self.window.width, 0), (self.window.width, self.window.height), (self.window.width - self.hud_width, self.window.height)) self.hud_layer = graphics.Layer(self.scene, cocos_layer=self.hud_cocos_layer) self.hud_layer.cocos_layer.position = 0, 0 self.gem_images = pyglet.image.ImageGrid( pyglet.image.load("gems3.png"), 4, 4) self.atlas = Atlas("atlas.generated") self.object_psys = bsgl.System( texture_id=self.atlas.sheet.get_texture().id) self.hud_psys = bsgl.System( texture_id=self.atlas.sheet.get_texture().id) def setup_hud(self): def update_hp_display(): undamaged = 255, 255, 255 undamaged_cockpit = 0, 255, 0 damaged = damaged_cockpit = 255, 0, 0 # for block, sprite in self.hud_sprite.subcomponent.items(): # rel = float(block.hp) / block.max_hp # a = damaged_cockpit if block.cockpit else damaged # b = undamaged_cockpit if block.cockpit else undamaged # sprite.color = vector_lerp( rel, a, b ) # cockpit = False def create_hp_display(): self.hud_sprite = self.player.block_structure.create_sys_structure( self.hud_psys, self.atlas, self.player, sync_to_thing=False) expected_size = self.hud_width update_hp_display() def recreate_hp_display(): self.hud_sprite.kill() create_hp_display() bar = graphics.VerticalBar(8, 256, (0, 64, 0), (128, 0, 0)) bar.position = (self.window.width - self.hud_width + 16), (self.window.height - self.hud_width - bar.height) x, y = self.window.width - self.hud_width + 32, self.window.height - self.hud_width speed_label = last_element = graphics.create_label( x, y, layer=self.hud_cocos_layer) y -= last_element.height + 8 power_supply_size_label = last_element = graphics.create_label( x, y, layer=self.hud_cocos_layer) y -= last_element.height + 8 power_production_label = last_element = graphics.create_label( x, y, layer=self.hud_cocos_layer) y -= last_element.height + 8 thrust_power_label = last_element = graphics.create_label( x, y, layer=self.hud_cocos_layer) y -= last_element.height + 8 turn_power_label = last_element = graphics.create_label( x, y, layer=self.hud_cocos_layer) y -= last_element.height + 8 brake_power_label = last_element = graphics.create_label( x, y, layer=self.hud_cocos_layer) y -= last_element.height + 8 number_of_engines_label = last_element = graphics.create_label( x, y, layer=self.hud_cocos_layer) y -= last_element.height + 8 number_of_guns_label = last_element = graphics.create_label( x, y, layer=self.hud_cocos_layer) y -= last_element.height + 8 x, y = self.window.width - self.hud_width + 16, self.window.height - self.hud_width - bar.height - 16 position_label = graphics.create_label(x, y, layer=self.hud_cocos_layer) def update_labels(): x, y = self.player.position position_label.element.text = "({0},{1})".format( int(x * 0.1), int(y * 0.1)) speed_label.element.text = "S: {0:.1f}".format(self.player.speed) power_production_label.element.text = "PP: {0}".format( int(sum(self.player.psu.production.values()))) power_supply_size_label.element.text = "MP: {0}".format( int(self.player.psu.max_storage)) thrust_power_label.element.text = "T: {0}".format( self.player.thrust_power) turn_power_label.element.text = "R: {0}".format( self.player.turn_power) brake_power_label.element.text = "B: {0}".format( self.player.brake_power) number_of_engines_label.element.text = "#E: {}".format( len(self.player.all_engines())) number_of_guns_label.element.text = "#G: {0}/{1}".format( len(self.player.ready_guns()), len(self.player.all_guns())) def update_power_display(): bar.fill = self.player.psu.charge_rate() self.hud_cocos_layer.add(bar) self.minimap = graphics.Minimap(self.hud_width - 32, self.hud_width - 32, 5000, 5000, self.player) self.minimap.position = (self.window.width - self.hud_width + 16), (self.window.height - self.hud_width - bar.height - self.hud_width - 16) self.hud_cocos_layer.add(self.minimap) def update_hud(): update_labels() update_hp_display() update_power_display() self.minimap.update() create_hp_display() self.post_physics.add_anonymous_hook(ignore_arguments(update_hud)) self.player.reshape_hooks.add_anonymous_hook(recreate_hp_display) def setup_game(self, player_ship_data=None): self.sim = physics.PhysicsSimulator(timestep=None) # self.player = create_ship_thing( self, self.main_layer, (500,500), shape = "small", hp = 5 ) if not player_ship_data: self.player = Ship.load_file("current_garage_ship.yaml", self) else: self.player = Ship.load_data(player_ship_data, self) self.player.position = (300, 300) self.player.invulnerable = False self.enemy = create_ship_thing(self, (500, 500), shape="small", hp=10) self.enemy.invulnerable = False self.enemy.body.angular_velocity_limit = degrees_to_radians(144 * 2) self.enemy2 = create_ship_thing(self, (0, 500), shape="small", hp=10) self.enemy2.invulnerable = False self.enemy2.body.angular_velocity_limit = degrees_to_radians(144 * 2) self.enemy.angle_degrees = random.random() * 360.0 self.enemy2.angle_degrees = random.random() * 360.0 self.batch = cocos.batch.BatchNode() self.main_layer.cocos_layer.add(self.batch) self.physics_objects = [] self.things = [] self.psys_managed_things = [] for i in range(200): cols = "red", "purple", "grey", "blue", "green", "yellow" sq = create_square_thing(self, None, (100, 0), None) sq.position = (random.random() - 0.5) * 4000, (random.random() - 0.5) * 4000 sq.angle_radians = random.random() * math.pi * 2 sq.mylabel = sq.position sq.velocity = (300, 10) kw = {} name = "polygon_normals.4.generated" kw["size"] = Vec2d(106.6666666, 106.6666666) kw["texture_coordinates"] = self.atlas.texcoords(name) kw["texture_size"] = self.atlas.texsize(name) z = random.random() * 6.28 r = 0.1 + random.random() * 10.0 pos = r * math.cos(z), r * math.sin(z) # need to translate from pixel space # [0,self. # to # [-1.3333,1.3333] x [-1,1] p = sq.position p = p + self.main_layer.cocos_layer.position p = Vec2d(p) / Vec2d(self.window.width, self.window.height) p = (p * 2) - Vec2d(1, 1) p = p * Vec2d(self.window.width / float(self.window.height), 1) kw["position"] = p kw["angle"] = sq.angle_radians kw["colour"] = 1.0, 0.5, 0.5, 1.0 index = self.object_psys.add(**kw) self.psys_managed_things.append((sq, index)) self.things.append(sq) def draw_psys(): # CMSDTv # T = translate by self.main_layer.cocos_layer.position # # M = v -> v - (1,1) # C = v -> v * (w/h, 1) w = float(self.window.width) h = float(self.window.height) x, y = self.main_layer.cocos_layer.position mat = (2.0 / w, 0.0, 0.0, (2 * x / w - 1), 0.0, 2.0 / h, 0.0, (2 * y / h - 1), 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0) self.object_psys.set_transformation_matrix(mat) glEnable(GL_SCISSOR_TEST) glScissor(0, 0, self.window.width + 1 - self.hud_width, self.window.height) self.object_psys.draw() glDisable(GL_SCISSOR_TEST) s = 0.3 sx, sy = 500 + self.sim._t * 100, 200 sx, sy = self.window.width - self.hud_width * 0.5, self.window.height - self.hud_width * 0.5 mat = (0.0, s * 2.0 / w, 0.0, (2 * sx / w - 1), s * 2.0 / h, 0, 0.0, (2 * sy / h - 1), 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0) self.hud_psys.set_transformation_matrix(mat) self.hud_psys.draw() graphics.Layer(self.scene, cocos_layer=graphics.FunctionCocosLayer(draw_psys)) self.sim.space.add_collision_handler(physics.CollisionTypes["main"], physics.CollisionTypes["bullet"], self.collide_general_with_bullet) def setup_input(self): input_layer = graphics.Layer(self.scene, gameinput.CocosInputLayer()) for k in (key.LEFT, key.RIGHT, key.UP, key.DOWN): input_layer.cocos_layer.set_key_hook(k, self.player.on_controls_state) input_layer.cocos_layer.set_key_hook(k, self.player.on_controls_state) input_layer.cocos_layer.set_key_hook(key.LSHIFT, self.player.on_controls_state) input_layer.cocos_layer.set_key_press_hook( key.SPACE, lambda *args, **kwargs: (self.player.on_controls_state( *args, **kwargs), self.shoot_volley(self.player))) input_layer.cocos_layer.set_key_release_hook( key.SPACE, lambda *args, **kwargs: self.player.on_controls_state( *args, **kwargs)) input_layer.cocos_layer.set_key_press_hook(key.P, self.on_save_ship) def shoot_volley(self, shooter): guns = shooter.ready_guns() index = 0 for gun in guns: if not gun.may_activate(): continue gun.shoot(shooter) gun.activated(index) def update_pygame(self): self.screen.fill(pygame.color.THECOLORS["black"]) draw_space(self.screen, self.sim.space) pygame.display.flip() def update_psys_managed_objects(self): for thing, index in self.psys_managed_things: self.object_psys.update_position_and_angle(index, thing.position, thing.angle_radians) def collide_general_with_bullet(self, space, arbiter): anything, bullet = arbiter.shapes try: thing = anything.thing index = anything.extra_info except AttributeError: bullet.thing.ttl = min(bullet.thing.ttl, 0.05) return False if bullet.thing.inert: return False if (bullet.thing.shooter == thing) and bullet.thing.grace > 0.0: return False try: block = thing.block_structure.blocks[index] hp = block.hp except KeyError: return False except AttributeError: return False bullet.thing.impact(thing=thing, block_index=index, block=block) bullet.thing.inert = True bullet.thing.ttl = min(bullet.thing.ttl, 0.05) return False def run(self): self.window.run(self.scene)
def generate(matrix): size = matrix.size voxels = matrix.voxels uv_slices = [] vertices = [] indices = [] uvs = [] faces = [] for side in sides: normal = side.normal right = side.right up = side.up stack_size = abs(normal.x) * size.x + abs(normal.y) * size.y + abs(normal.z) * size.z slice_width = abs(right.x) * size.x + abs(right.y) * size.y + abs(right.z) * size.z slice_height = abs(up.x) * size.x + abs(up.y) * size.y + abs(up.z) * size.z slice = numpy.empty(shape=(slice_width, slice_height), dtype=numpy.object) for _z in range(stack_size): for _x, _y in product(range(slice_width), range(slice_height)): x = right.x * _x + up.x * _y + abs(normal.x) * _z y = right.y * _x + up.y * _y + abs(normal.y) * _z z = right.z * _x + up.z * _y + abs(normal.z) * _z if voxels[x, y, z] is None: continue if not 0 <= x + normal.x < size.x or \ not 0 <= y + normal.y < size.y or \ not 0 <= z + normal.z < size.z or \ voxels[x + normal.x, y + normal.y, z + normal.z] is None: slice[_x, _y] = voxels[x, y, z] quads = [] for _y in range(slice_height): _x = 0 while _x < slice_width: qc = slice[_x, _y] if qc is not None: qx, qy = _x, _y qw, qh = 1, 1 while qx + qw < slice_width and slice[qx + qw, qy] == qc: qw += 1 while qy + qh < slice_height: k = 0 while k < qw and slice[qx + k, qy + qh] == qc: k += 1 if k != qw: break qh += 1 quads.append(Quad(qx, qy, qw, qh, qc)) for x, y in product(range(qw), range(qh)): slice[qx + x, qy + y] = None _x += qw else: _x += 1 uv_slice_index = len(vertices) for q in quads: _indices = [0, 1, 2, 3] if side.clockwise else [0, 3, 2, 1] for i in _indices: indices.append(i + len(vertices)) def make_vertex(x, y): return FbxVector4(x * right.x + y * up.x + (_z + 0.5) * abs(normal.x) + 0.5 * normal.x, x * right.y + y * up.y + (_z + 0.5) * abs(normal.y) + 0.5 * normal.y, x * right.z + y * up.z + (_z + 0.5) * abs(normal.z) + 0.5 * normal.z) vertices.extend([ make_vertex(q.x, q.y), make_vertex(q.x, q.y + q.height), make_vertex(q.x + q.width, q.y + q.height), make_vertex(q.x + q.width, q.y) ]) uvs.extend([ FbxVector2(q.x, q.y), FbxVector2(q.x, q.y + q.height), FbxVector2(q.x + q.width, q.y + q.height), FbxVector2(q.x + q.width, q.y), ]) faces.append(q.color) uv_slices_count = len(vertices) - uv_slice_index if uv_slices_count > 0: uv_slices.append(UVSlice(uv_slice_index, uv_slices_count, slice_width, slice_height)) # build uv map for u in uv_slices: min_x = max_x = uvs[u.index][0] min_y = max_y = uvs[u.index][1] for i in range(u.index + 1, u.index + u.count - 1): x, y = uvs[i] min_x, max_x = min(x, min_x), max(x, max_x) min_y, max_y = min(y, min_y), max(y, max_y) for i in range(u.index, u.index + u.count): uvs[i] = FbxVector2(uvs[i][0] - min_x, uvs[i][1] - min_y) u.width, u.height = max_x - min_x, max_y - min_y padding = 1 s = 0 for u in uv_slices: s += (u.width + padding) * (u.height + padding) map_size = 2 while pow(map_size, 2) < s: map_size *= 2 atlas = None while True: fit = True atlas = Atlas(map_size, map_size) for u in uv_slices: if not atlas.append(u.width + padding, u.height + padding, u): fit = False break if fit: break else: map_size *= 2 for x, y, u in atlas: for i in range(u.index, u.index + u.count): uvs[i] = FbxVector2(uvs[i][0] + x, uvs[i][1] + y) # normalize uvs to [0..1] for i, uv in enumerate(uvs): uvs[i] = FbxVector2(uv[0] / map_size, uv[1] / map_size) return vertices, indices, uvs, faces
# # Execute the ETL job in Spark ... # print("==> Executing Spark ETL job ") master = "local[*]" appName = "Simple ETL Job" sc = SparkContext(master, appName) sc.setLogLevel("ERROR") sqlContext = HiveContext(sc) startTime = datetime.utcnow() emp_dept_flat = etl() endTime = datetime.utcnow() print("Started: %s" % startTime.isoformat()) print("Ended: %s" % endTime.isoformat()) # # ... and add the lineage to Atlas # print("Adding Lineage to Atlas (using the code in function 'etl')") atlas = Atlas(cluster, atlasHost, user, password) atlas.lineage.createHiveToHive(sourceDB, sourceTables, targetDB, targetTable, targetColumns, \ etl, usedSparkPackages, atlas.timestamp(startTime), atlas.timestamp(endTime), owner) print("Done")
def main(): start_of_program_time = time.time() ITERATIONS = 8 SCORE_RATIO = 0.7 if len(sys.argv) == 1 or ( len(sys.argv) == 2 and (sys.argv[1] == '-h' or sys.argv[1] == '/h' or sys.argv[1] == '--help' or sys.argv[1] == '-help' or sys.argv[1] == 'help')): print('Usage: box_cutter PATH_TO_IMAGE FLAGS') print( '(The image needs to be a bitmap file, and should not be more than 128x128 pixels)' ) print('\t-n INT\t\tMax number of void boxes to consider') print('\t-i INT\t\tMax number of cut-repack iterations') print('\t-s FLOAT\tMin ratio between starting score to current score') print('\t-r\t\tEnable chart rotation for the packing phase') print('\t-x\t\tEnable upside-down mirroring') print('\t-y\t\tEnable left-to-right mirroring') return path = sys.argv[1] path.strip(' \'\"') im = Image.open(path) prv_arg = None for arg in sys.argv[2:]: if prv_arg == '-n': if is_int(arg): BoxQueue.N = int(arg) else: raise Exception( '__main__.py: The argument following \'-n\' must be an int' ) if prv_arg == '-i': if is_int(arg): ITERATIONS = int(arg) else: raise Exception( '__main__.py: The argument following \'-i\' must be an int' ) if prv_arg == '-s': if is_int(arg) or is_float(arg): SCORE_RATIO = float(arg) else: raise Exception( '__main__.py: The argument following \'-s\' must be a float' ) if arg == '-r': pc.ORIENTATIONS = 4 if arg == '-x': pc.MIRROR_X = 2 if arg == '-y': pc.MIRROR_Y = 2 prv_arg = arg print('Importing atlas from image...') atlas = Atlas.from_image(im) start_time = time.time() print('Doing the initial repacking of the atlas...') (atlas, start_score) = pack_charts(atlas.chart_list) end_time = time.time() print('Took ' + str_time(end_time, start_time)) score = start_score Atlas.MAX_AXIS = max(atlas.height, atlas.width) for iteration in range(ITERATIONS): start_time = time.time() atlas.chart_list.import_from_atlas(atlas) # Workaround for a bug print('Iteration ' + str(iteration + 1) + ' out of ' + str(ITERATIONS) + ':') print('\t' + str(iteration + 1) + ':' + 'Score ratio: ' + str(float(start_score / score))) print('\t' + str(iteration + 1) + ':' + 'Cutting the charts...') li = cut_charts(atlas) print('\t' + str(iteration + 1) + ':' + 'Repacking the charts...') (atlas, score) = pack_charts(atlas.chart_list, li) end_time = time.time() print('\t' + str(iteration + 1) + ':' + 'Took ' + str_time(end_time, start_time)) if (start_score / score) <= SCORE_RATIO: print( 'Reached the desirable score improvement of start_score/score=' + str(float(start_score)) + '/' + str(float(score)) + '=' + str(float(start_score / score)) + '<=' + str(float(SCORE_RATIO)) + '=desirable_score_ratio') break print('Converting atlas to image...') new_im = atlas.to_image() new_path = path[:len(path) - 4] + '_repacked.bmp' new_im.save(new_path) end_of_program_time = time.time() print('Total elapsed time: ' + str_time(end_of_program_time, start_of_program_time))
import os import sys import logging SCRIPT_PATH = os.path.dirname(os.path.abspath(__file__)) PACKAGE_PATH = os.path.abspath(os.path.join(SCRIPT_PATH, "..")) sys.path.append(PACKAGE_PATH) from settings import * level = logging.INFO if os.getenv("LOGGING_DEBUG"): level = logging.DEBUG logging.basicConfig( level=level, format='%(asctime)s %(levelname)s %(name)s.%(funcName)s: %(message)s', datefmt='%Y-%m-%d %H:%M:%S', ) from atlas import Atlas from apf.consumers import KafkaConsumer as Consumer consumer = Consumer(config=CONSUMER_CONFIG) step = Atlas(consumer, config=STEP_CONFIG, level=level) step.start()
def atlas(): from atlas import Atlas a = Atlas() a.fetch_all() a.test_active_tickets()
def setup(name, height, width): # setup atlas atlas = Atlas(name, height, width) return atlas
when = c.data.split('_')[3] keyboard = templates.HOURS_INLINE(when) bot.answer_callback_query(c.id) bot.edit_message_text("Set hour:", message.chat.id, message.message_id, reply_markup=keyboard) @bot.callback_query_handler(func=lambda c: c.data.startswith('min')) def change_minute(c: telebot.types.CallbackQuery): if not check_admin_rights(c): return message = c.message when = c.data.split('_')[1] m = c.data.split('_')[2] atlas.change_minute(message.chat.id, when, m) time = atlas.time(message.chat.id, when) bot.answer_callback_query(c.id, "Time is changed to " + time) if __name__ == '__main__': atlas = Atlas() templates = Templates(atlas) sender = Sender() sender.start() try: bot.polling(none_stop=True) except: pass
def main(): include_build_directory() import pyglet import pyglet.gl import bsgl import sys window = pyglet.window.Window(vsync=True, width=1300, height=1000) print window.width, window.height label = pyglet.text.Label("Hello world!", font_name="Times New Roman", font_size=36, x=window.width // 2, y=window.height // 2, anchor_x="center", anchor_y="center") atlas = Atlas("atlas.generated") tex = atlas.sheet.get_texture() fps = pyglet.clock.ClockDisplay() pyglet.clock.schedule(lambda _: None) t0 = [time.time(), time.time()] psys = bsgl.System(texture_id=tex.id) print psys.get_capacity(), psys.get_number_of_elements() amount = 1000 psys.reserve(amount) things = {} def add_things(): for i in range(amount): z = random.random() * 6.28 r = 0.001 + random.random() * 0.01 pos = r * math.cos(z), r * math.sin(z) vel = tuple( Vec2d(pos).normalized() * (1 + 4 * random.random()) * 3) offset = 0, 0 texcoords = 0, 0 texsize = 1, 1 angle = random.random() * 6.28 avel = (-1 if random.random() > 0.5 else 1) * ( random.random() * 0.1 + 0.9) * 10 * Vec2d(vel).get_length() size = (0.1, 0.1) rgba = [random.random() for i in range(3)] + [1.0] name = "polygon_normals.{}.generated".format( random.choice((3, 4, 5, 6, 8))) rv = psys.add(size=size, texture_coordinates=atlas.texcoords(name), texture_size=atlas.texsize(name), position=pos, offset=offset, angle=angle, colour=rgba) things[rv] = (pos, angle, vel, avel) def update_things(dt): for index, (pos, a, vel, avel) in things.items(): x, y = pos dx, dy = vel t = 0.2 * dt xp, yp = x + t * dx, y + t * dy ap = a + t * avel things[index] = ((xp, yp), ap, vel, avel) psys.update_position_and_angle(index, (xp, yp), ap) def reset_things(): for index in things.keys(): del things[index] psys.remove(index) assert len(things) == 0 add_things() add_things() indices = things.keys() add_things() for index in indices: psys.remove(index) del things[index] print psys.get_capacity(), psys.get_number_of_elements() @window.event def on_draw(): pyglet.gl.glClearColor(0.5, 0.2, 0.5, 1.0) window.clear() label.draw() t1 = time.time() dt = t1 - t0[0] t0[0] = t1 if (t1 - t0[1]) > 3.0: reset_things() t0[1] = t1 update_things(dt) psys.draw() # position = (dt,2*dt) ) fps.draw() pyglet.app.run()
def loadAtlasFromXml(self, node, filePath): try: atlas = self.atlases[filePath] drawable = atlas.drawable except KeyError: atlas = Atlas(self.factory) atlas.path = filePath atlas.connect("sprite-added", self.workzone._spriteAddedCb) atlas.connect("sprite-removed", self.workzone._spriteRemovedCb) atlas.loadSprites(node) atlas.connect("sprite-removed", self._atlasChangedCb) atlas.connect("sprite-added", self._atlasChangedCb) observer = AtlasLogObserver(self.workzone.app.action_log) observer.startObserving(atlas) self.atlases[filePath] = atlas try: drawable = self.factory.makeDrawableFromPath(filePath) self.logger.info("User opened an atlas : %s", filePath) except: drawable = self.factory.makeNewDrawable(node.attrib["width"], node.attrib["height"]) if not node.attrib["width"]: #Imported atlas node.attrib["width"] = str(drawable.image.size[0]) node.attrib["height"] = str(drawable.image.size[1]) atlas.setDrawable(drawable) atlas.setXmlNode(node) self.currentAtlas = atlas try: atlas.selection.disconnect_by_function(self.photoshop._atlasSelectionChangedCb) except Exception: pass atlas.selection.connect("selected-changed", self.photoshop._atlasSelectionChangedCb) self.photoshop.displayImage(drawable.image) self._getOffsetsFromXml(node)
#!/usr/bin/env python from atlas import Atlas import logging import time logging.basicConfig(filename="tail.log", filemode='a', format='%(asctime)s,%(msecs)d %(name)s %(levelname)s %(message)s', datefmt='%H:%M:%S', level=logging.DEBUG) logger = logging.getLogger atlas = Atlas() while True: try: print atlas.get_topic() except: break
class Grid: def __init__(self, x, y, x_tile_gap, y_tile_gap, atlas_file): self.set_atlas(atlas_file, atlas_file) self.set_tiles(x, y, x_tile_gap, y_tile_gap) self.characters = {} def set_atlas(self, atlas_name, atlas_file_loc): self.atlas = Atlas(atlas_name, atlas_file_loc) # The integer value at each bitmap position will represent an asset id assigned to an asset # in the atlas json. def set_tiles(self, x, y, x_tile_gap, y_tile_gap): self.tiles = [[Tile(i, j, x_tile_gap, y_tile_gap) for i in range(x)] for j in range(y)] self.selected_x = 0 self.selected_y = 0 self.batches = {} bitmaps = self.atlas.get_bitmaps() x_loc = 0 for row in range(x): y_loc = 0 for col in range(y): for bm_key in bitmaps: if bm_key not in self.batches: self.batches[bm_key] = pyglet.graphics.Batch() bitmap = bitmaps[bm_key] do_draw = bitmap[row][col] if do_draw == 1: asset = self.atlas.get_asset(bm_key, self.batches[bm_key]) self.tiles[row][col].set_xy(x_loc, y_loc) self.tiles[row][col].add_image(asset["image"], asset["name"], asset["layer"]) y_loc += y_tile_gap x_loc += x_tile_gap def add_character(self, char_obj, x, y, image_type="image"): if "characters" not in self.batches: self.batches["characters"] = pyglet.graphics.Batch() char_obj.set_image(self.batches["characters"]) self.characters[char_obj.name] = char_obj.image tile = self.tiles[x][y] char_obj.image.x = tile.x char_obj.image.y = tile.y def get_selected_tile(self): print("selected tile: ({},{},{})".format( self.selected_x, self.selected_y, self.tiles[self.selected_x][ self.selected_y].get_image_descriptions())) def move_selected_tile_up(self): self.selected_y += 1 def move_selected_tile_left(self): self.tiles[self.selected_x][self.selected_y].deselect() self.selected_x -= 1 self.tiles[self.selected_x][self.selected_y].select() def move_selected_tile_right(self): self.tiles[self.selected_x][self.selected_y].deselect() self.selected_x += 1 self.tiles[self.selected_x][self.selected_y].select() def move_selected_tile_down(self): self.tiles[self.selected_x][self.selected_y].deselect() self.selected_y -= 1 self.tiles[self.selected_x][self.selected_y].select() # Grid's draw method doesn't call tile's draw method. # For optimization purposes, it uses batches that hold the tile's images. # @TODO: Create 2 draw methods that can do either one of those options. def draw(self): # First draw the terrain assets. assets_by_layer = self.atlas.get_assets_by_layer() for asset in assets_by_layer: asset_name = asset[0] self.batches[asset_name].draw() # Second draw the selected tile lines. # @TODO: Make this more versatile. # Draw rectangle around selected tile. s_tile = self.tiles[self.selected_x][self.selected_y] pyglet.graphics.draw( 2, pyglet.gl.GL_LINES, ('v2i', (s_tile.x, s_tile.y, s_tile.x, s_tile.y + s_tile.height))) pyglet.graphics.draw(2, pyglet.gl.GL_LINES, ('v2i', (s_tile.x, s_tile.y + s_tile.height, s_tile.x + s_tile.width, s_tile.y + s_tile.height))) pyglet.graphics.draw( 2, pyglet.gl.GL_LINES, ('v2i', (s_tile.x + s_tile.width, s_tile.y + s_tile.height, s_tile.x + s_tile.width, s_tile.y))) pyglet.graphics.draw( 2, pyglet.gl.GL_LINES, ('v2i', (s_tile.x + s_tile.width, s_tile.y, s_tile.x, s_tile.y))) # Third draw the character sprites. self.batches["characters"].draw()
def set_atlas(self, atlas_name, atlas_file_loc): self.atlas = Atlas(atlas_name, atlas_file_loc)
if len(sys.argv) not in [2, 3]: print("Usage: gps.py numCities|atlasFile [debugLevel].") sys.exit(1) if len(sys.argv) > 2: if sys.argv[2] not in ['DEBUG', 'INFO', 'WARNING', 'ERROR']: print('Debug level must be one of: DEBUG, INFO, WARNING, ERROR.') sys.exit(2) logging.getLogger().setLevel(sys.argv[2]) else: logging.getLogger().setLevel('INFO') try: num_cities = int(sys.argv[1]) logging.info( 'Building random atlas with {} cities...'.format(num_cities)) usa = Atlas(num_cities) logging.info('...built.') except: logging.info('Loading atlas from file {}...'.format(sys.argv[1])) usa = Atlas.from_filename(sys.argv[1]) logging.info('...loaded.') path, cost = find_best_path(usa) print('Best path from {} to {} costs {}: {}.'.format( 0, usa.get_num_cities() - 1, cost, path)) print('You expanded {} nodes: {}'.format(len(usa._nodes_expanded), usa._nodes_expanded))
def init_atlas(debug=False): global atlas, username, password, api_url load_credentials() atlas = Atlas(username, password, api_url, verify_credentials=False, debug=debug)