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
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 def load_file(self, path):
171 return bool(lib.mCoreLoadFile(self._core, path.encode('UTF-8')))
172
173 def is_rom(self, vfile):
174 return bool(self._core.isROM(vfile.handle))
175
176 def load_rom(self, vfile):
177 return bool(self._core.loadROM(self._core, vfile.handle))
178
179 def load_bios(self, vfile, id=0):
180 return bool(self._core.loadBIOS(self._core, vfile.handle, id))
181
182 def load_save(self, vfile):
183 return bool(self._core.loadSave(self._core, vfile.handle))
184
185 def load_temporary_save(self, vfile):
186 return bool(self._core.loadTemporarySave(self._core, vfile.handle))
187
188 def load_patch(self, vfile):
189 return bool(self._core.loadPatch(self._core, vfile.handle))
190
191 def load_config(self, config):
192 lib.mCoreLoadForeignConfig(self._core, config._native)
193
194 def autoload_save(self):
195 return bool(lib.mCoreAutoloadSave(self._core))
196
197 def autoload_patch(self):
198 return bool(lib.mCoreAutoloadPatch(self._core))
199
200 def autoload_cheats(self):
201 return bool(lib.mCoreAutoloadCheats(self._core))
202
203 def platform(self):
204 return self._core.platform(self._core)
205
206 def desired_video_dimensions(self):
207 width = ffi.new("unsigned*")
208 height = ffi.new("unsigned*")
209 self._core.desiredVideoDimensions(self._core, width, height)
210 return width[0], height[0]
211
212 def set_video_buffer(self, image):
213 self._core.setVideoBuffer(self._core, image.buffer, image.stride)
214
215 def reset(self):
216 self._core.reset(self._core)
217 self._load()
218
219 @needs_reset
220 @protected
221 def run_frame(self):
222 self._core.runFrame(self._core)
223
224 @needs_reset
225 @protected
226 def run_loop(self):
227 self._core.runLoop(self._core)
228
229 @needs_reset
230 def step(self):
231 self._core.step(self._core)
232
233 @staticmethod
234 def _keys_to_int(*args, **kwargs):
235 keys = 0
236 if 'raw' in kwargs:
237 keys = kwargs['raw']
238 for key in args:
239 keys |= 1 << key
240 return keys
241
242 @protected
243 def set_keys(self, *args, **kwargs):
244 self._core.setKeys(self._core, self._keys_to_int(*args, **kwargs))
245
246 @protected
247 def add_keys(self, *args, **kwargs):
248 self._core.addKeys(self._core, self._keys_to_int(*args, **kwargs))
249
250 @protected
251 def clear_keys(self, *args, **kwargs):
252 self._core.clearKeys(self._core, self._keys_to_int(*args, **kwargs))
253
254 @property
255 @needs_reset
256 def frame_counter(self):
257 return self._core.frameCounter(self._core)
258
259 @property
260 def frame_cycles(self):
261 return self._core.frameCycles(self._core)
262
263 @property
264 def frequency(self):
265 return self._core.frequency(self._core)
266
267 @property
268 def game_title(self):
269 title = ffi.new("char[16]")
270 self._core.getGameTitle(self._core, title)
271 return ffi.string(title, 16).decode("ascii")
272
273 @property
274 def game_code(self):
275 code = ffi.new("char[12]")
276 self._core.getGameCode(self._core, code)
277 return ffi.string(code, 12).decode("ascii")
278
279 def add_frame_callback(self, callback):
280 self._callbacks.video_frame_ended.append(callback)
281
282 @property
283 def crc32(self):
284 return self._native.romCrc32
285
286
287class ICoreOwner(object):
288 def claim(self):
289 raise NotImplementedError
290
291 def release(self):
292 raise NotImplementedError
293
294 def __enter__(self):
295 self.core = self.claim()
296 self.core._protected = True
297 return self.core
298
299 def __exit__(self, type, value, traceback):
300 self.core._protected = False
301 self.release()
302
303
304class IRunner(object):
305 def pause(self):
306 raise NotImplementedError
307
308 def unpause(self):
309 raise NotImplementedError
310
311 def use_core(self):
312 raise NotImplementedError
313
314 @property
315 def running(self):
316 raise NotImplementedError
317
318 @property
319 def paused(self):
320 raise NotImplementedError
321
322
323class Config(object):
324 def __init__(self, native=None, port=None, defaults={}):
325 if not native:
326 self._port = ffi.NULL
327 if port:
328 self._port = ffi.new("char[]", port.encode("UTF-8"))
329 native = ffi.gc(ffi.new("struct mCoreConfig*"), lib.mCoreConfigDeinit)
330 lib.mCoreConfigInit(native, self._port)
331 self._native = native
332 for key, value in defaults.items():
333 if isinstance(value, bool):
334 value = int(value)
335 lib.mCoreConfigSetDefaultValue(self._native, ffi.new("char[]", key.encode("UTF-8")), ffi.new("char[]", str(value).encode("UTF-8")))
336
337 def __getitem__(self, key):
338 string = lib.mCoreConfigGetValue(self._native, ffi.new("char[]", key.encode("UTF-8")))
339 if not string:
340 return None
341 return ffi.string(string)
342
343 def __setitem__(self, key, value):
344 if isinstance(value, bool):
345 value = int(value)
346 lib.mCoreConfigSetValue(self._native, ffi.new("char[]", key.encode("UTF-8")), ffi.new("char[]", str(value).encode("UTF-8")))