Example #1
0
 def LoadAtlas(self) -> None:
     """ Loads the atlas picture file(s) """
     oAtlas: Atlas
     try:
         Logger.debug(u'TheScreen: Loading Skin Atlas')
         if not Globals.bIgnoreAtlas:
             if Globals.oFnAtlasSkin.Exists():
                 oAtlas = Atlas(Globals.oFnAtlasSkin.string)
                 Cache.append('kv.atlas', Globals.oFnAtlasSkin.string,
                              oAtlas)
             Logger.debug(u'TheScreen: Loading Definition Atlas')
             if Globals.oDefinitionPathes.oFnDefinitionAtlas.Exists():
                 oAtlas = Atlas(
                     Globals.oDefinitionPathes.oFnDefinitionAtlas.string)
                 Cache.append(
                     'kv.atlas',
                     Globals.oDefinitionPathes.oFnDefinitionAtlas.string,
                     oAtlas)
     except ParseError as e:
         ShowErrorPopUp(uTitle="Fatal Error",
                        uMessage=LogError(
                            uMsg=u'TheScreen: Fatal Error:Load Atlas',
                            oException=e),
                        bAbort=True)
     return None
Example #2
0
    def __init__(self, **kwargs):
        super(HexGrid, self).__init__(do_rotation=False,
                                      scale_min=.5,
                                      scale_max=3.,
                                      auto_bring_to_front=False)
        self.gridsize = kwargs['gridsize']
        self.gametype = kwargs['gametype']
        self.gui = kwargs['gui']

        # Preparem atlas d'imatges pels tiles
        self.baseatlas = Atlas('assets/basetiles.atlas')
        self.playeratlas = Atlas('assets/playertiles.atlas')
        self.uiatlas = Atlas('assets/uitiles.atlas')

        # Nomes gridsize inparell
        assert (self.gridsize % 2 != 0)

        # Preparem store
        self.store = DictStore('hexland.dict')

        self.grid = []
        self.deads = {1: 0, 2: 0}
        self.resetScore()

        self.setup()

        # Si ens construeixen amb estat, el carreguem
        if kwargs['state']:
            self.loadState(kwargs['state'], True)
            self.reloadGridGraphics()

        # Si estem vs cpu, creem el jugador CPU
        if not self.gametype == GAMETYPE["PVP"]:
            self.cpu = CpuPlayer(self.gametype)
Example #3
0
 def on_filename(self, *args):
     if not self.filename:
         return
     resource = resource_find(self.filename)
     if not resource:
         raise ValueError("Couldn't find atlas: {}".format(self.filename))
     self.atlas = Atlas(resource)
Example #4
0
def CreateAtlas(oPicPath,oAtlasFile,uDebugMsg):
    ''' creates an atlas file from all picture files in a folder '''

    if oORCA.bIgnoreAtlas:
        return

    #can\'t get JPEG lib included in package, so just ignore atlas
    #if oORCA.uPlatform=='macosx'  or oORCA.uPlatform=="ios" or oORCA.uPlatform=="win":
    if oORCA.uPlatform=='macosx'  or oORCA.uPlatform=="ios":
        return

    try:
        if not FileExists(oAtlasFile):
            Logger.debug(uDebugMsg)
            #aExtensions=[u'.png',u'.jpg',u'.bmp',u'.gif']
            # we exclude gifs as they might be animated
            aExtensions=[u'.png',u'.jpg',u'.bmp']
            aPicFiles=[]

            oDirList=GetFileList(oPicPath, bSubDirs=True,bFullPath=True)
            for uFileName in oDirList:
                uExtension = os.path.splitext(uFileName)[1].lower()
                if uExtension in aExtensions:
                    if uFileName.find( AdjustPathToOs(oORCA.uSkinPath+u'/atlas/'))==-1:
                        aPicFiles.append(uFileName)
            try:
                Atlas.create(oAtlasFile[:-6],aPicFiles,1024)
            except Exception:
                pass
    except Exception as e:
        LogError(u'Error creating Atlas File:',e)
Example #5
0
 def __init__(self, **kwargs):
     super().__init__(**kwargs)
     self.rec_shadow = Atlas(f"{images_path}rec_shadow.atlas")
     self.rec_st_shadow = Atlas(f"{images_path}rec_st_shadow.atlas")
     self.quad_shadow = Atlas(f"{images_path}quad_shadow.atlas")
     self.round_shadow = Atlas(f"{images_path}round_shadow.atlas")
     Clock.schedule_once(lambda x: self.on_theme_style(0, self.theme_style))
     self._determine_device_orientation(None, Window.size)
     Window.bind(size=self._determine_device_orientation)
Example #6
0
    def __init__(self, **kwargs):
        super(RenderWidget, self).__init__(**kwargs)
        self.size = 608, 608
        self.tile_size = 32
        self.atlas = Atlas(ATLAS_FILE)
        self.atlas_trees = Atlas(ATLAS_TREE_FILE)
        self.char_atlas = Atlas(ATLAS_CHAR_FILE)
        self.map_width = 50
        self.map_height = 50

        # Load Particle Textures
        self.particle_tex = CoreImage('{}/assets/twirl_01.png'.format(
            os.getcwd())).texture
        # self.add_widget(self.kivy_particle)

        ind = -1
        for name, tex in self.atlas.textures.items():

            if '_' in name:
                tile_name, tile_number = name.split('_')
            else:
                tile_name, tile_number = name, '0'

            # tex.flip_vertical()
            if self.data.get(tile_name):
                self.data[tile_name].append(tex)
            else:
                ind += 1
                self.data[tile_name] = [tex]
            self.data_size[tile_name] = tex.size

            if not self.tile_enum.get(ind):
                self.tile_enum[ind] = tile_name

        # Tree Textures
        ind = 1
        for name, tex in self.atlas_trees.textures.items():
            self.tree_data[name] = tex
            self.tree_enum[ind] = name
            ind += 1

        # Entity Textures
        for name, tex in self.char_atlas.textures.items():
            self.char_data[name] = tex

        with self.canvas.before:
            Callback(self._set_blend_func)
        with self.canvas.after:
            Callback(self._reset_blend_func)

        self.initialize_tiles()
        Window.bind(on_key_down=self._keydown)
        Window.bind(on_key_up=self._keyup)
        Clock.schedule_interval(self.check_for_keys, 60**-1)
        self.tile_clock = Clock.schedule_interval(self.update_tiles, 60**-1)
Example #7
0
class Pallet(StackLayout):
    """Many :class:`SwatchButton`, gathered from an :class:`kivy.atlas.Atlas`."""
    atlas = ObjectProperty()
    """:class:`kivy.atlas.Atlas` object I'll make :class:`SwatchButton` from."""
    filename = StringProperty()
    """Path to an atlas; will construct :class:`kivy.atlas.Atlas` when set"""
    swatches = DictProperty({})
    """:class:`SwatchButton` widgets here, keyed by name of their graphic"""
    swatch_width = NumericProperty(100)
    """Width of each and every :class:`SwatchButton` here"""
    swatch_height = NumericProperty(75)
    """Height of each and every :class:`SwatchButton` here"""
    swatch_size = ReferenceListProperty(swatch_width, swatch_height)
    """Size of each and every :class:`SwatchButton` here"""
    selection = ListProperty([])
    """List of :class:`SwatchButton`s that are selected"""
    selection_mode = OptionProperty('single', options=['single', 'multiple'])
    """Whether to allow only a 'single' selected :class:`SwatchButton` (default), or 'multiple'"""
    def on_selection(self, *args):
        Logger.debug('Pallet: {} got selection {}'.format(
            self.filename, self.selection))

    def on_filename(self, *args):
        if not self.filename:
            return
        resource = resource_find(self.filename)
        if not resource:
            raise ValueError("Couldn't find atlas: {}".format(self.filename))
        self.atlas = Atlas(resource)

    def on_atlas(self, *args):
        if self.atlas is None:
            return
        self.upd_textures()
        self.atlas.bind(textures=self.upd_textures)

    def upd_textures(self, *args):
        """Create one :class:`SwatchButton` for each texture"""
        if self.canvas is None:
            Clock.schedule_once(self.upd_textures, 0)
            return
        for name in list(self.swatches.keys()):
            if name not in self.atlas.textures:
                self.remove_widget(self.swatches[name])
                del self.swatches[name]
        for (name, tex) in self.atlas.textures.items():
            if name in self.swatches and self.swatches[name] != tex:
                self.remove_widget(self.swatches[name])
            if name not in self.swatches or self.swatches[name] != tex:
                self.swatches[name] = SwatchButton(name=name,
                                                   tex=tex,
                                                   size_hint=(None, None),
                                                   size=self.swatch_size)
                self.add_widget(self.swatches[name])
    def __init__(self,atlas,name,frames,**kwargs):
        self.atlas = atlas
        self.atlas_str = str('atlas://' + atlas + '/')
        self.name = name
        self.frames = frames
        self.update_now = False

        try:
            self.icon = Atlas(atlas)[name]
            self.icon_str = str(self.atlas_str + name)
        except KeyError:
            self.icon = Atlas(atlas)[name + "-1"]
            self.icon_str = str(self.atlas_str + name + '-1')

        super(WorldObject,self).__init__(**kwargs)
Example #9
0
def create(folder):
    cwd = getcwd()
    images = []
    for root, dirname, filenames in walk(folder):
        for filename in filenames:
            image = join(root, filename)[len(folder) + 1:]
            print image
            images.append(image)

    chdir(folder)
    outfn = None
    size = DEFAULT_SIZE
    while not outfn:
        try:
            fname = join('..', basename(folder))
            outfn=Atlas.create(fname, images, size, use_path=True)
        except:
            pass
        if not outfn or ((size<1024) and (len(outfn)>1 and len(outfn[1])>2)):
                numfiles = len(outfn[1]) if outfn else 0
                for i in range (0, numfiles):
                    outf = '%s-%d.png' % (fname, i)
                    try:
                        remove(outf)
                    except:
                        pass
                outfn = None
        size *= 2
    chdir(cwd)
Example #10
0
 def build(self):
     label = Label(text="Testing going on.")
     atlas = Atlas("player_sheet.atlas")
     image1 = Image(allow_stretch=True)
     image1.texture = atlas["walkleft4"]
     label.add_widget(image1)
     return label
Example #11
0
 def __init__(self, source, scale, pos, angle):
     super().__init__(pos=pos)
     self.scale = scale
     self.images = Atlas('images/hat.atlas')  ## Atlas initialization
     self.keys = list(
         self.images.textures.keys())  ## atlas keys into a list
     print('keys in Hat', self.keys)
     self.kys = ('hat_burnt0', 'hat_burnt1', 'hat_burnt2', 'hat_burnt3',
                 'hat_burnt4', 'hat_burnt-final')
     print('hat keys list', self.kys)
     self.image = Sprite(texture=self.images['hat'],
                         scale=self.scale,
                         pos=pos)
     #self.image = Sprite(source=source, scale=self.scale, pos=pos)
     self.size = self.image.size
     self.add_widget(self.image)
     self.inhand = False
     self.onhead = False
     self.onhead_timer = 0
     self.moving = False
     #burning status
     self.burning = False
     self.burnt = False
     self.burn_counter = 0
     self.sprite = 0
     self.animation_value = int(200 / (len(self.kys) - 1))
     print('animation value', self.animation_value)
     self.vy = 0
     self.combust = SoundLoader.load('audio/combust-both.wav')
Example #12
0
 def __init__(self):
     super(Player, self).__init__()
     self.new_frame = True
     self.direction = "idle"
     self.stopping = False
     self.anim_timer = 0
     self.atlas = Atlas("images/player_sheet.atlas")
     self.image = Image(allow_stretch=True,
                        source='atlas://images/player_sheet/idle1')
     self.image.size = (64, 64)
     self.size = (32, 64)
     self.speech = SpeechBubble()
     self.speech.size = (0, 50)
     self.add_widget(self.speech)
     self.add_widget(self.image)
     self.target = [0, 0]
     self.speed = 3
     self.anim = 0
     self.world = (0, 0)
     self.moves = {
         "up": False,
         "down": False,
         "left": False,
         "right": False
     }
     self.dirs = {
         "up": (0, self.speed),
         "down": (0, -self.speed),
         "left": (-self.speed, 0),
         "right": (self.speed, 0)
     }
Example #13
0
 def __init__(self, *args, **kwargs):
     super(MiniMapBox, self).__init__(**kwargs)
     self.spritesheet = Atlas('spritesheet.atlas')
     #        print(self.spritesheet.textures.keys())
     self.decal_x = -88
     self.decal_y = -76
     self.reveal_map((0, 0))
Example #14
0
 def __init__(self, source, scale, **kwargs):
     super().__init__()
     self.images = Atlas('images/background.atlas')
     #self.keys = self.images.keys()
     #list(  self.images.textures.keys( ) )
     self.keys = ('top', 'back', 'mid')
     print('bg keys', self.keys)
     self.scale = scale
     self.size = (self.scale * 1600, self.scale * 640)  #self.image.size
     x0 = -self.width / 2
     print('x0 in Background is', x0)
     print('initial x position', x0)
     self.image_bot = Sprite(texture=self.images['back'],
                             scale=self.scale,
                             x=x0)
     self.add_widget(self.image_bot)
     #self.image = Sprite( source=source, scale=self.scale)
     #source2 = 'images/backgroundMAC.png'
     self.image_mid = Sprite(texture=self.images['mid'],
                             scale=self.scale,
                             x=x0)
     self.add_widget(self.image_mid)
     self.image_top = Sprite(texture=self.images['top'],
                             scale=self.scale,
                             x=x0)
     self.add_widget(self.image_top)
    def __init__(self,atlas,material_name,position,frames,subtile_id=None):
        self.atlas = atlas
        self.material_name = material_name
        self.position = [[True,True],[True,True]] if position is None else position
        self.frames = frames
        self.subtile_id = subtile_id
        
        # Caution: this parses the atlas URL and may or may not be compatible with windows. I do not know. This code ought to be refactored to be the same as WorldObject anyway
        atlas_stripped = atlas[8:].rpartition('/')[0]+'.atlas'

        try:
            self.icon = Atlas(atlas_stripped)['Tile-' + material_name]
            self.icon_str = str(atlas + 'Tile-' + material_name)
        except KeyError:
            self.icon = Atlas(atlas_stripped)['Tile-' + material_name + "-1"]
            self.icon_str = str(atlas + 'Tile-' + material_name + '-1')        
Example #16
0
class Notificator(Factory.BoxLayout, Factory.StencilView):
    default_font_size = NumericProperty(16)
    color = ListProperty((1, 1, 1, 1, ))
    icon_texture_dict = DictProperty()

    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.icon_texture_dict = Atlas(ATLAS_PATH).textures

    def add_notification(
            self, *,
            text,
            font_size=None,
            icon_key='',
            duration='4'):
        item = NotificatorItem(
            text=text,
            icon_texture=self.icon_texture_dict.get(icon_key),
            font_size=(
                self.default_font_size if font_size is None else font_size),
            color=self.color,
            x=self.x,
            top=self.y,
            width=self.width,)
        magnet = Magnet(
            transitions={'pos': 'linear', },
            duration=0.5,
            size_hint_y=None)
        item.bind(height=magnet.setter('height'))
        magnet.add_widget(item)
        self.add_widget(magnet)
        Clock.schedule_once(
            lambda __: fadeout_widget(magnet, duration=2),
            duration)
Example #17
0
    def __init__(self, **kwargs):
        self.uiatlas = Atlas('assets/uitiles.atlas')
        self.store = DictStore('hexland.dict')
        super(Menu, self).__init__(**kwargs)

        self.logo_img.size_hint = 0.1, 0.1

        Animation(size_hint=(0.8, 0.3), t='out_bounce').start(self.logo_img)
Example #18
0
    def __init__(self, pos, size, block_type):
        self.pos = pos
        self.size = size
        self.block_type = block_type
        self.atlas = Atlas(os.path.join(ROOT_FOLDER, 'textures', 'special_blocks.atlas'))
        self.texture = self.atlas[self.block_type]

        super(HitBlock, self).__init__(self.pos, self.size, self.texture)
 def set_textures(self, atlas, board):
     self.atlas = atlas + '.atlas'
     self.board = board
     dir = path.dirname(sys.argv[0])
     if not path.isabs(self.atlas):
         self.atlas = path.join(dir, self.atlas)
     if not path.isabs(self.board):
         self.board = path.join(dir, self.board)
     self.atlas = Atlas(self.atlas)
Example #20
0
    def layout(self):
        self.charge = False
        self.amount = ''
        self.ready = False

        def on_text_charge(instance, value):
            self.amount = value
            if len(value) >= 1:
                self.ready = True
            else:
                self.ready = False
            setButtonColor()

        layout = BoxLayout(orientation='vertical',
                           padding=(2 * dp(48), 2 * dp(48)))

        #Charge Box
        chargeField = MDTextField()
        chargeField.hint_text = "Enter Amount to Charge"
        chargeField.input_filter = "int"
        chargeField.bind(text=on_text_charge)
        layout.add_widget(chargeField)

        proceedButton = MDRaisedButton(text='Proceed',
                                       size_hint=(None, None),
                                       size=(4 * dp(48), dp(48)))
        proceedButton.md_bg_color = [0.9, 0, 0, 0.9]

        app = App.get_running_app()

        def setButtonColor():
            if self.ready:
                proceedButton.md_bg_color = app.theme_cls.primary_color
                proceedButton.bind(on_press=lambda x: self.createCharge())

        proceedAnchor = AnchorLayout(anchor_x='center',
                                     anchor_y='bottom',
                                     padding=[60])
        proceedAnchor.add_widget(proceedButton)
        layout.add_widget(proceedAnchor)

        content = Builder.load_string(spinner)
        self.stripepopup = Popup(title='Charging Card',
                                 title_align='center',
                                 size_hint=(None, None),
                                 size=(dp(200), dp(200)))
        self.stripepopup.add_widget(content)
        self.stripepopup.title_font = 'data/fonts/Roboto-Bold.ttf'
        self.stripepopup.title_color = App.get_running_app(
        ).theme_cls.primary_color
        self.stripepopup.separator_color = App.get_running_app(
        ).theme_cls.primary_color
        self.stripepopup.background = str(
            Atlas('{}round_shadow.atlas'.format(images_path)))

        return layout
    def bulk_load(self, path_glob):
        """
        Bulk load YAML files into storage

        :param path_glob: array of paths
        """

        for file in path_glob:
            for doc in yaml.load_all(open(file, mode='r')):
                if 'imagedb' not in doc:
                    logging.warning('%s does not contains images' % file)
                else:
                    # locale and priority of current document
                    locale = doc['imagedb'].get('locale', self._def_locale)
                    priority = doc['imagedb'].get('priority', 0)

                    # iterate over each string
                    for k, v in doc['imagedb'].get('images', {}).items():

                        v = path.join(path.dirname(file), v)

                        # if key of this string exists in db
                        if k in self._db:

                            # if locale exists, select image with greater prio
                            if locale in self._db[k]:
                                if self._db[k][locale]['priority'] < priority:
                                    self._db[k][locale] = dict(
                                        priority=priority, file=v)
                        else:
                            self._db[k] = {locale: dict(priority=priority,
                                                        file=v)}

                    # apply atlases found in yaml
                    for k, v in doc['imagedb'].get('atlases', {}).items():
                        atl = Atlas(path.join(path.dirname(file), v))

                        for k, v in atl.textures.items():
                            atl_path = 'atlas://%s/%s' % (
                                str(atl.filename).split('.atlas')[0].strip('./'),
                                k)

                            # if key of this string exists in db
                            if k in self._db:

                                # if locale exists, select image with greater prio
                                if self._db[k][locale]['priority'] < priority:
                                    self._db[k][locale] = dict(
                                        priority=priority, file=atl_path)
                            else:
                                self._db[k] = {locale: dict(priority=priority,
                                                            file=atl_path)}

        return self
Example #22
0
def get_atlas(atlas_path):
    """ Get atlas from the Kivy cache if present, otherwise initialize it """
    from kivy.atlas import Atlas
    from kivy.cache import Cache

    atlas = Cache.get('kv.atlas', atlas_path.replace('atlas://', ''))
    if not atlas:
        logger.info(f'Initializing atlas "{atlas_path}"')
        atlas = Atlas(f'{atlas_path}.atlas')
        Cache.append('kv.atlas', atlas_path, atlas)
    return atlas
Example #23
0
 def __init__(self, *args, **kwargs):
     super(MiniMapBox, self).__init__(**kwargs)
     self.spritesheet = Atlas('spritesheet.atlas')
     #        print(self.spritesheet.textures.keys())
     self.decal_x = -88
     self.decal_y = -76
     for i in range(0, 8):
         for j in range(0, 7):
             self.reveal_map(
                 ('(' + str(i) + ',' + str(j) + ')'),
                 ((i * 25) + self.decal_x, (j * 25) + self.decal_y))
Example #24
0
def main(argv=None):
    try:
        cwd = getcwd()
        for path in glob('*.atlas'):
            a = Atlas(path)
            print 'Atlas %s:' % basename(path)
            for key in a.textures.keys():
                print '\t', key

    except Exception, e:
        print e
Example #25
0
 def __init__(self, pos, size, type):
     self.pos = pos
     self.size = size
     self.type = type
     super(Item, self).__init__()
     self.atlas = Atlas(os.path.join(ROOT_FOLDER, 'textures',
                                     'items.atlas'))
     self.texture = self.atlas[self.type]
     with self.canvas:
         self.platform = Rectangle(pos=self.pos,
                                   size=self.size,
                                   texture=self.texture)
Example #26
0
 def __init__(self, *, atlasfilepath, **kwargs):
     super().__init__(**kwargs)
     self.clock_event = None
     atlas = Atlas(atlasfilepath)
     x, y, = self.pos
     width, height, = self.size
     for texture in atlas.textures.values():
         sprite = MostxTitleSprite(texture=texture)
         sprite.x = x + random() * width
         sprite.y = y + random() * height
         sprite.velocity_x_base = sprite.velocity_x = random() * 5
         sprite.velocity_y_base = sprite.velocity_y = random() * 5
         sprite.velocity_rotation = random() * 5
         self.add_widget(sprite)
Example #27
0
 def spawn_entity(self, coord, euid, skin, size=(1, 1)):
     size = (size[0] * self.scale, size[1] * self.scale)
     entity = Entity(
         source='{}/{}'.format(ENTITY_PATH, skin),
         pos=self.coord_to_pos(coord),
         size=size,
         coord=coord,
     )
     # ToDo: somehow it doesn't set the texture, so it is set manually
     # figure out why that is, fix it and delete the next two lines
     atlas = Atlas('content/entities/entities.atlas')
     entity.texture = atlas[skin]
     self.entities[euid] = entity
     self.add_widget(entity)
Example #28
0
def CreateAtlas(oPicPath, oAtlasFile, uDebugMsg):
    """
    creates an atlas file from all picture files in a folder

    :param cPath oPicPath: The Path to a Picture Folder
    :param cFileName oAtlasFile: The Atlas Files to Create
    :param string uDebugMsg: A Debug Message for the function
    :return:
    """
    if Globals.bIgnoreAtlas:
        return

    #can\'t get JPEG lib included in package, so just ignore atlas
    if Globals.uPlatform == 'macosx' or Globals.uPlatform == "ios":
        return

    try:
        if not oAtlasFile.Exists():
            Logger.debug(uDebugMsg)
            #aExtensions=[u'.png',u'.jpg',u'.bmp',u'.gif']
            # we exclude gifs as they might be animated
            aExtensions = [u'.png', u'.jpg', u'.bmp']
            aPicFiles = []

            aFileList = oPicPath.GetFileList(bSubDirs=False, bFullPath=True)
            for uFileName in aFileList:
                uExtension = os.path.splitext(uFileName)[1].lower()
                if uExtension in aExtensions:
                    if uFileName.find(Globals.oPathSkin.string +
                                      u'/atlas/') == -1:
                        aPicFiles.append(uFileName)
            try:
                Atlas.create(oAtlasFile[:-6], aPicFiles, 1024)
            except Exception:
                pass
    except Exception as e:
        LogError(u'Error creating Atlas File:', e)
Example #29
0
def build_atlas(image_paths, src_x, src_y, atlas_name, padding=2, **limit_kwarg):
    """Build a Kivy  Kivy :py:class:`~kivy.atlas.Atlas`

    Args:
        image_paths (list): Paths to images and/or image directories
        src_x: Max width of source images
        src_y: Max height of source images
        atlas_name: Name of atlas file to create
        \\*\\*limit_kwarg: At most one limit to provide to :py:func:`.get_atlas_dimensions`
    """
    from kivy.atlas import Atlas

    # Allow smallest dimension to be as low as half the max. This this works because each thumbnail
    # size category is over twice the size of the next smallest one
    min_x = ceil(src_x / 2)
    min_y = ceil(src_y / 2)
    logger.info(f'Atlas: Searching for images of dimensions ({min_x}-{src_x}) x ({min_y}-{src_y})...')
    image_paths = list(filter_images_by_size(image_paths, src_x, src_y, min_x, min_y))
    logger.info(f'Atlas: {len(image_paths)} images found')

    atlas_size = get_atlas_dimensions(len(image_paths), src_x, src_y, padding=padding, **limit_kwarg)
    logger.info(f'Atlas: Calculated atlas size: {atlas_size}')
    if atlas_size != (0, 0):
        Atlas.create(atlas_name, image_paths, atlas_size, padding=padding)
Example #30
0
    def __init__(self, pos, size):
        self.x = pos[0]
        self.y = pos[1]
        self.pos = pos
        self.size = size
        super(Hero, self).__init__()
        self.atlas = Atlas(os.path.join(ROOT_FOLDER, 'textures', 'trump.atlas'))
        self.texture = self.atlas['stand']
        with self.canvas:
            self.rect = Rectangle(pos=self.pos, size=self.size,
                                  texture=self.texture)

        self.run_frames = ['run1', 'run2', 'run3', 'run4',
                           'run5', 'run6', 'run7', 'run8']
        self.run_frame_cycle = cycle(self.run_frames)
Example #31
0
    def __init__(self, **kwargs):
        super(ParticleEmitter, self).__init__(**kwargs)

        # create list of textures
        basename = 'VFX_SmokeParticle'
        atlas = Atlas('VFX/smoke_particles.atlas')
        all_keys = atlas.textures.keys()
        wanted_keys = filter(lambda x: x.startswith(basename), all_keys)

        if len(wanted_keys) > 1:
            pattern = re.compile(r'[0-9]+$')
            print wanted_keys
            wanted_keys.sort(key=lambda x: int(pattern.search(x).group()))

        self.texture_list = [atlas[key] for key in wanted_keys]

        Clock.schedule_interval(self.emit_particle, 0.1)
Example #32
0
        #print join(i, "include")
        print "  [ ] Copying included images...",
        if exists(join(i, "include")):
            for img in (join(i, "include", f) for f in os.listdir(join(i, "include"))):
                #print img
                shutil.copy(img, tmp)

        print "\r  [x] Images copied.            "

        # All done, pack everything into an atlas
        print "  [ ] Generating the atlas...",
        fnames = []
        tot_size = 0
        for i in (join(tmp, f) for f in os.listdir(tmp)):
            if i.lower().endswith(".png"):
                fnames.append(i)
                tot_size += os.stat(i).st_size
        data = Atlas.create(atlasname, fnames, get_atlas_best_size(fnames))
        if not data:
            print "\r  [!] Atlas not generated."
            continue
        else:
            fn, meta = data
            atl_size = 0
            for i in meta.keys():
                atl_size += os.stat(i).st_size
            print "\r  [x] Atlas \"{0}\" generated ({1} image{2}, {3} saved).".format(fn, len(meta), 's' if len(meta) > 1 else '', hr_size(tot_size - atl_size))

        shutil.rmtree(tmp)

    print "All done."
Example #33
0
def make_atlas(folder):
    fold = Path(folder)
    subdirs = fold.dirs()
    for dirc in subdirs:
        Atlas.create("images/{}".format(dirc.basename()), dirc.files("*.png"), [160,256])