all repos — mgba @ 4346c5db1b931df3bde87631d628f398e10e4461

mGBA Game Boy Advance Emulator

src/platform/python/mgba/core.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  # pylint: disable=no-name-in-module
  7from . import tile, audio
  8from cached_property import cached_property
  9from functools import wraps
 10
 11
 12def find(path):
 13    core = lib.mCoreFind(path.encode('UTF-8'))
 14    if core == ffi.NULL:
 15        return None
 16    return Core._init(core)
 17
 18
 19def find_vf(vfile):
 20    core = lib.mCoreFindVF(vfile.handle)
 21    if core == ffi.NULL:
 22        return None
 23    return Core._init(core)
 24
 25
 26def load_path(path):
 27    core = find(path)
 28    if not core or not core.load_file(path):
 29        return None
 30    return core
 31
 32
 33def load_vf(vfile):
 34    core = find_vf(vfile)
 35    if not core or not core.load_rom(vfile):
 36        return None
 37    return core
 38
 39
 40def needs_reset(func):
 41    @wraps(func)
 42    def wrapper(self, *args, **kwargs):
 43        if not self._was_reset:
 44            raise RuntimeError("Core must be reset first")
 45        return func(self, *args, **kwargs)
 46    return wrapper
 47
 48
 49def protected(func):
 50    @wraps(func)
 51    def wrapper(self, *args, **kwargs):
 52        if self._protected:
 53            raise RuntimeError("Core is protected")
 54        return func(self, *args, **kwargs)
 55    return wrapper
 56
 57
 58@ffi.def_extern()
 59def _mCorePythonCallbacksVideoFrameStarted(user):  # pylint: disable=invalid-name
 60    context = ffi.from_handle(user)
 61    context._video_frame_started()
 62
 63
 64@ffi.def_extern()
 65def _mCorePythonCallbacksVideoFrameEnded(user):  # pylint: disable=invalid-name
 66    context = ffi.from_handle(user)
 67    context._video_frame_ended()
 68
 69
 70@ffi.def_extern()
 71def _mCorePythonCallbacksCoreCrashed(user):  # pylint: disable=invalid-name
 72    context = ffi.from_handle(user)
 73    context._core_crashed()
 74
 75
 76@ffi.def_extern()
 77def _mCorePythonCallbacksSleep(user):  # pylint: disable=invalid-name
 78    context = ffi.from_handle(user)
 79    context._sleep()
 80
 81
 82class CoreCallbacks(object):
 83    def __init__(self):
 84        self._handle = ffi.new_handle(self)
 85        self.video_frame_started = []
 86        self.video_frame_ended = []
 87        self.core_crashed = []
 88        self.sleep = []
 89        self.context = lib.mCorePythonCallbackCreate(self._handle)
 90
 91    def _video_frame_started(self):
 92        for callback in self.video_frame_started:
 93            callback()
 94
 95    def _video_frame_ended(self):
 96        for callback in self.video_frame_ended:
 97            callback()
 98
 99    def _core_crashed(self):
100        for callback in self.core_crashed:
101            callback()
102
103    def _sleep(self):
104        for callback in self.sleep:
105            callback()
106
107
108class Core(object):
109    if hasattr(lib, 'PLATFORM_GBA'):
110        PLATFORM_GBA = lib.PLATFORM_GBA
111
112    if hasattr(lib, 'PLATFORM_GB'):
113        PLATFORM_GB = lib.PLATFORM_GB
114
115    def __init__(self, native):
116        self._core = native
117        self._was_reset = False
118        self._protected = False
119        self._callbacks = CoreCallbacks()
120        self._core.addCoreCallbacks(self._core, self._callbacks.context)
121        self.config = Config(ffi.addressof(native.config))
122
123    def __del__(self):
124        self._was_reset = False
125
126    @cached_property
127    def graphics_cache(self):
128        if not self._was_reset:
129            raise RuntimeError("Core must be reset first")
130        return tile.CacheSet(self)
131
132    @cached_property
133    def tiles(self):
134        tiles = []
135        native_tiles = ffi.addressof(self.graphics_cache.cache.tiles)
136        for i in range(lib.mTileCacheSetSize(native_tiles)):
137            tiles.append(tile.TileView(lib.mTileCacheSetGetPointer(native_tiles, i)))
138        return tiles
139
140    @cached_property
141    def maps(self):
142        maps = []
143        native_maps = ffi.addressof(self.graphics_cache.cache.maps)
144        for i in range(lib.mMapCacheSetSize(native_maps)):
145            maps.append(tile.MapView(lib.mMapCacheSetGetPointer(native_maps, i)))
146        return maps
147
148    @classmethod
149    def _init(cls, native):
150        core = ffi.gc(native, native.deinit)
151        success = bool(core.init(core))
152        lib.mCoreInitConfig(core, ffi.NULL)
153        if not success:
154            raise RuntimeError("Failed to initialize core")
155        return cls._detect(core)
156
157    @classmethod
158    def _detect(cls, core):
159        if hasattr(cls, 'PLATFORM_GBA') and core.platform(core) == cls.PLATFORM_GBA:
160            from .gba import GBA
161            return GBA(core)
162        if hasattr(cls, 'PLATFORM_GB') and core.platform(core) == cls.PLATFORM_GB:
163            from .gb import GB
164            return GB(core)
165        return Core(core)
166
167    def _load(self):
168        self._was_reset = True
169
170    @protected
171    def load_file(self, path):
172        return bool(lib.mCoreLoadFile(self._core, path.encode('UTF-8')))
173
174    def is_rom(self, vfile):
175        return bool(self._core.isROM(vfile.handle))
176
177    @protected
178    def load_rom(self, vfile):
179        return bool(self._core.loadROM(self._core, vfile.handle))
180
181    @protected
182    def load_bios(self, vfile, id=0):
183        return bool(self._core.loadBIOS(self._core, vfile.handle, id))
184
185    @protected
186    def load_save(self, vfile):
187        return bool(self._core.loadSave(self._core, vfile.handle))
188
189    @protected
190    def load_temporary_save(self, vfile):
191        return bool(self._core.loadTemporarySave(self._core, vfile.handle))
192
193    @protected
194    def load_patch(self, vfile):
195        return bool(self._core.loadPatch(self._core, vfile.handle))
196
197    @protected
198    def load_config(self, config):
199        lib.mCoreLoadForeignConfig(self._core, config._native)
200
201    @protected
202    def autoload_save(self):
203        return bool(lib.mCoreAutoloadSave(self._core))
204
205    @protected
206    def autoload_patch(self):
207        return bool(lib.mCoreAutoloadPatch(self._core))
208
209    @protected
210    def autoload_cheats(self):
211        return bool(lib.mCoreAutoloadCheats(self._core))
212
213    @property
214    def platform(self):
215        return self._core.platform(self._core)
216
217    @protected
218    def desired_video_dimensions(self):
219        width = ffi.new("unsigned*")
220        height = ffi.new("unsigned*")
221        self._core.desiredVideoDimensions(self._core, width, height)
222        return width[0], height[0]
223
224    @protected
225    def set_video_buffer(self, image):
226        self._core.setVideoBuffer(self._core, image.buffer, image.stride)
227
228    @protected
229    def set_audio_buffer_size(self, size)
230        self._core.setAudioBufferSize(self._core, size)
231
232    @property
233    def audio_buffer_size(self):
234        return self._core.getAudioBufferSize(self._core)
235
236    @protected
237    def get_audio_channels(self):
238        return audio.StereoBuffer(self.get_audio_channel(0), self.get_audio_channel(1));
239
240    @protected
241    def get_audio_channel(self, channel):
242        return audio.Buffer(self._core.getAudioChannel(self._core, channel), self.frequency)
243
244    @protected
245    def reset(self):
246        self._core.reset(self._core)
247        self._load()
248
249    @needs_reset
250    @protected
251    def run_frame(self):
252        self._core.runFrame(self._core)
253
254    @needs_reset
255    @protected
256    def run_loop(self):
257        self._core.runLoop(self._core)
258
259    @needs_reset
260    @protected
261    def step(self):
262        self._core.step(self._core)
263
264    @needs_reset
265    @protected
266    def load_raw_state(self, state):
267        if len(state) < self._core.stateSize(self._core):
268            return False
269        return self._core.loadState(self._core, state)
270
271    @needs_reset
272    @protected
273    def save_raw_state(self):
274        state = ffi.new('unsigned char[%i]' % self._core.stateSize(self._core))
275        if self._core.saveState(self._core, state):
276            return state
277        return None
278
279    @staticmethod
280    def _keys_to_int(*args, **kwargs):
281        keys = 0
282        if 'raw' in kwargs:
283            keys = kwargs['raw']
284        for key in args:
285            keys |= 1 << key
286        return keys
287
288    @protected
289    def set_keys(self, *args, **kwargs):
290        self._core.setKeys(self._core, self._keys_to_int(*args, **kwargs))
291
292    @protected
293    def add_keys(self, *args, **kwargs):
294        self._core.addKeys(self._core, self._keys_to_int(*args, **kwargs))
295
296    @protected
297    def clear_keys(self, *args, **kwargs):
298        self._core.clearKeys(self._core, self._keys_to_int(*args, **kwargs))
299
300    @property
301    @needs_reset
302    def frame_counter(self):
303        return self._core.frameCounter(self._core)
304
305    @property
306    def frame_cycles(self):
307        return self._core.frameCycles(self._core)
308
309    @property
310    def frequency(self):
311        return self._core.frequency(self._core)
312
313    @property
314    def game_title(self):
315        title = ffi.new("char[16]")
316        self._core.getGameTitle(self._core, title)
317        return ffi.string(title, 16).decode("ascii")
318
319    @property
320    def game_code(self):
321        code = ffi.new("char[12]")
322        self._core.getGameCode(self._core, code)
323        return ffi.string(code, 12).decode("ascii")
324
325    def add_frame_callback(self, callback):
326        self._callbacks.video_frame_ended.append(callback)
327
328    @property
329    def crc32(self):
330        return self._native.romCrc32
331
332
333class ICoreOwner(object):
334    def claim(self):
335        raise NotImplementedError
336
337    def release(self):
338        raise NotImplementedError
339
340    def __enter__(self):
341        self.core = self.claim()
342        self.core._protected = True
343        return self.core
344
345    def __exit__(self, type, value, traceback):
346        self.core._protected = False
347        self.release()
348
349
350class IRunner(object):
351    def pause(self):
352        raise NotImplementedError
353
354    def unpause(self):
355        raise NotImplementedError
356
357    def use_core(self):
358        raise NotImplementedError
359
360    @property
361    def running(self):
362        raise NotImplementedError
363
364    @property
365    def paused(self):
366        raise NotImplementedError
367
368
369class Config(object):
370    def __init__(self, native=None, port=None, defaults={}):
371        if not native:
372            self._port = ffi.NULL
373            if port:
374                self._port = ffi.new("char[]", port.encode("UTF-8"))
375            native = ffi.gc(ffi.new("struct mCoreConfig*"), lib.mCoreConfigDeinit)
376            lib.mCoreConfigInit(native, self._port)
377        self._native = native
378        for key, value in defaults.items():
379            if isinstance(value, bool):
380                value = int(value)
381            lib.mCoreConfigSetDefaultValue(self._native, ffi.new("char[]", key.encode("UTF-8")), ffi.new("char[]", str(value).encode("UTF-8")))
382
383    def __getitem__(self, key):
384        string = lib.mCoreConfigGetValue(self._native, ffi.new("char[]", key.encode("UTF-8")))
385        if not string:
386            return None
387        return ffi.string(string)
388
389    def __setitem__(self, key, value):
390        if isinstance(value, bool):
391            value = int(value)
392        lib.mCoreConfigSetValue(self._native, ffi.new("char[]", key.encode("UTF-8")), ffi.new("char[]", str(value).encode("UTF-8")))