all repos — mgba @ dbeff59c066c9e75f6359f1e4f9b4764eb99b7ff

mGBA Game Boy Advance Emulator

src/platform/python/mgba/tile.py (view raw)

 1# Copyright (c) 2013-2016 Jeffrey Pfau
 2#
 3# This Source Code Form is subject to the terms of the Mozilla Public
 4# License, v. 2.0. If a copy of the MPL was not distributed with this
 5# file, You can obtain one at http://mozilla.org/MPL/2.0/.
 6from ._pylib import ffi, lib
 7from . import image
 8
 9class Tile:
10    def __init__(self, data):
11        self.buffer = data
12
13    def toImage(self):
14        i = image.Image(8, 8)
15        self.composite(i, 0, 0)
16        return i
17
18    def composite(self, i, x, y):
19        for iy in range(8):
20            for ix in range(8):
21                i.buffer[ix + x + (iy + y) * i.stride] = image.u16ToColor(self.buffer[ix + iy * 8])
22
23class TileView:
24    def __init__(self, core):
25        self.core = core
26        self.cache = ffi.gc(ffi.new("struct mTileCache*"), core._deinitTileCache)
27        core._initTileCache(self.cache)
28        lib.mTileCacheSetPalette(self.cache, 0)
29        self.paletteSet = 0
30
31    def getTile(self, tile, palette):
32        return Tile(lib.mTileCacheGetTile(self.cache, tile, palette))
33
34    def setPalette(self, paletteSet):
35        if paletteSet > 1 or paletteSet < 0:
36            raise IndexError("Palette Set ID out of bounds")
37        lib.mTileCacheSetPalette(self.cache, paletteSet)
38        self.paletteSet = paletteSet
39
40class Sprite(object):
41    TILE_BASE = 0, 0
42    PALETTE_BASE = 0, 0
43
44    def constitute(self, tileView, tilePitch, paletteSet):
45        oldPaletteSet = tileView.paletteSet
46        tileView.setPalette(paletteSet)
47        i = image.Image(self.width, self.height)
48        tileId = self.tile + self.TILE_BASE[paletteSet]
49        for y in range(self.height // 8):
50            for x in range(self.width // 8):
51                tile = tileView.getTile(tileId, self.paletteId + self.PALETTE_BASE[paletteSet])
52                tile.composite(i, x * 8, y * 8)
53                tileId += 1
54            if tilePitch:
55                tileId += tilePitch - self.width // 8
56        self.image = i
57        tileView.setPalette(oldPaletteSet)