다마고치 연구소 한국어판 소스 공개
Paramix Studio / build (push) Canceled after 0s
Paramix Studio / pages (push) Canceled after 0s

This commit is contained in:
syskiller committed 2026-11-10 21:17:44 +09:00
commit db23855630
661 files changed
+503597

No files matched your search

+230
View File
@@ -0,0 +1,230 @@
# T7Emu for the Tamagotchi Paradise
An emulator for the Tama-Go (6502 based V7 chip) that runs on the Paradise. It also runs the
Tamagotchi Friends (same chip family, test).
The Studio builds it into the ROM together with the user's own Tama-Go ROM and
figure ROMs. No ROM is part of this repository.
- `t7.bin`: the program. The TamaEmu launcher copies it to PRAM and starts it.
Its settings block ("PMX7") is at 0x140 and is filled in by the Studio
(`src/emu.js`, `t7Patch`).
- `src/core`: the emulator core, a C port of
[tamago](https://github.com/asterick/tamago) by asterick (BSD), taken over
from the T7Emu app. `t7_run.inc` is a faster run loop with the same results
as `t7_cpu_step` (kept for the host tests).
- `src/app`: the Paradise side. `t7app.c` has screen, settings menu, clock
and saved state and also builds on the PC; `main.c` has the hardware part
(it uses `emu/src/emu/hw.c` and `flash.c`).
- `host`: PC tests. `hrun.c` boots the ROM and saves screenshots, `happ.c`
tests the app logic (clock, catching up, save, figures), `runcmp.c` and
`tr.c` compare the fast loop with the old step function. `setup.txt` is the
key sequence that finishes the first setup and hatches the egg.
- `test`: `devt7.py` runs `t7.bin` in Unicorn with a simulated Paradise,
`proft7.py` profiles it.
## Build
```
sh src/app/build.sh # clang, ld.lld, llvm-objcopy; writes t7.bin and t7x.bin (the JIT, second part)
KEEPELF=1 sh src/app/build.sh # keeps src/app/t7.elf for the profiler
```
## Layout in the Paradise flash
| Offset | What |
| --- | --- |
| 0x0A0000 | program (copied to PRAM on start) |
| 0x0C0000 | session (state of the running emulator, "T7SS") |
| 0x0C1000 | EEPROM of the Tama-Go, two slots of 8 KB ("T7EE", sequence, page mask, checksum, then 4 KB) |
| 0x0C5000 | settings from the menu ("T7S2", 16 bytes; layout 3 in r1 bits 0..3: light in bits 4..7, dim level in r0) and at +32 the clock note ("T7CK": seconds counter, game time, month and day when leaving) |
| 0x0C8000 | second part of the program (t7x.bin, the JIT, 1.6.12 test2) |
| 0x940000 | Tama-Go ROM (640 KB) or Tamagotchi Friends ROM (768 KB) |
| behind it, up to 0xD40000 | figure ROMs, trailing empty bytes cut, each on a 4 KB boundary |
The save.bin of the T7Emu app (page mask, then the 4 KB EEPROM, 4098 bytes)
has the same content as one EEPROM slot, see `src/saves.js`.
## More instances (1.6.0)
The program only uses its settings block for ROM, figures and save area, so the
Studio can put several copies into the flash (one per ROM, see the main README,
"More emulators"). `test/devt7.py` runs one of them with `APPOFF=<image offset>`.
## Tamagotchi Friends
The Friends ROM (768 KB) is recognised by its reset vector: not at 0x3FFC like the Tama-Go but at
0x7FFC. Differences, all in `src/core` behind `g_t7_static_off`:
- The file has 16 KB more in front. The static ROM ($C000) is at 0x4000, bank 0 begins at 0x4000
(its code is linked to $8000), bank n >= 1 at (n + 1) * 32 KB. 23 banks.
- The frame tick comes from IRQ 3 (every 122nd, counter $55) instead of the video IRQ. Instead of
7.3 kHz of interrupts the core sets the counter just below and fires IRQ 3 once per video frame.
- The second of the game clock is at 0x136 (Tama-Go 0x396); hour, minute, day and month as on the
Tama-Go.
- The IR hooks of the Tama-Go (bank 3) are off. No figures.
## Clock
Settings flag bit 1 (the Studio's "Take the clock from the Paradise at the
start", on by default): at every start the game clock is set to the Paradise's
own time, read from its SRAM before T7Emu uses it (`../emu/src/emu/paraclock.h`).
Nothing is caught up. When the game asks for the time (hour 255) it gets the
same time. Without the flag (or with the clock set to "Game" in the menu, or
when the time is not found) the old way: after a pause the missed hours pass,
up to 30.
## Timing
The core runs at 3.03 MHz with a video interrupt every 66,667 cycles (60 Hz).
The game clock is kept on the Paradise's seconds counter: every 2 s the app
sets minute and second; when a whole hour is missing it lets the game roll
the hour itself, so the day goes on as in the game. After a pause up to 30
hours are caught up, then the hour is set directly.
## PC passwords (1.6.8-test4, T7_PW_FIX)
The PC password code (bank 2, login $6229, encoding $6378, logout check $643E, reward $6192) uses a nibble helper: the
game writes a byte to $3080 and reads its high nibble at $3082, its low nibble at $3083 and the byte with swapped
nibbles at $308A. The core returned 0 there, so the login was always 000000000000 and every logout decoded to zeros
and failed. With T7_PW_FIX the login changes every time and a correct logout is accepted (host test: 0 to 5000 points).
Logout: same format as the login; byte 0 = 0x80 | login byte 0, byte 1 = login byte 1, points in thousands in byte 3
and the low 2 bits of byte 4, checksum nibble. Gotchi Points: RAM $0320-$0324 and EEPROM 0x030-0x034, 5 bytes BCD
lowest digits first (save.bin of the app: file offset 0x32-0x36, behind the 2 byte page mask); no checksum.
## Battery (T7_IDLE, T7_STOP, 1.6.9 test12)
Taken over from TamaGo for the Pebble (v0.3.0). T7_IDLE: the Tama-Go's main loop waits at $CE66 (5 JSR to the seed
routines at $D2ED, LDA $2D, BEQ back); when the BEQ goes back and no IRQ is taken, the passes that fit up to the end of
the run or the next sound event are added up at once (seeds $C4..$C8, the stack slots of the last JSR, A, flags).
Checked against the ROM bytes at the start (t7_idle_check; Friends: off). Bit-identical: host/runcmp.c gives the same
state hash every 2 ms with and without the switch. T7_STOP: writing 7 to $3001 halts the CPU (original sound only,
its timers wake it); any IRQ request or a key ($3007 bit 0 set, reported in $3008 bit 0) wakes it. On the PC (runcmp,
sound on, 10 minutes after setup): 78 % of the emulated cycles skipped, the game clock the same as without.
## Power save with the screen off (T7_JSR_HLE, T7_DARK_STEP, T7_SND_LAZY, T7_PW, 1.6.12 test1)
Measured on the PC with a hatched Tama in its room (host tools, see NOTIZEN): the 6502 runs about 213000 instructions a
second, 77 % of them in the sprite blit at $E4CD; with the screen off nobody sees it. Device simulation: nearly half of
the remaining time went into the sound timers (3322 and 512 events a second) although their IRQs are masked.
- T7_JSR_HLE (core): JSR $E4CD is left out while g_t7_dark is set (screen off): the game state stays the same apart from
the random seeds $C4..$C8, the picture comes back with the next frames. JSR $D460 (a delay: LDX #$D1, INX/BNE, RTS)
is done at once when it ends inside the run: the same state and cycles (runcmp identical). Both checked against the
ROM bytes at the start (Tama-Go only).
- T7_SND_LAZY (core): a sound timer whose IRQ is masked gets no events; when the mask opens (or the timer is set) its
next overflow is put where it would be. runcmp with sound: identical.
- T7_DARK_STEP: screen off: the emulation in steps up to 50 ms (the same emulated time).
- T7_PW (setting "Power save": Normal, Strong, Maximal; default Strong): screen off, no menu, no tone, no link:
Strong runs the chip from its internal 12 MHz RC with PLL and crystal off (datasheet: 1.6 mA instead of 9 to 12 mA),
Maximal also goes to deep sleep (0.4 mA) whenever the emulation has caught up; the RTC (1 s, as the Paradise sets it)
or a key wakes it, the ms tick continues from the RTC. The setting "Sleep/12M" shows the share of the time asleep and
at 12 MHz since the start (for tests).
Device simulation (test/devt7.py models the clock source and deep sleep), 35 s screen off: awake at 12 MHz 7 %, asleep
93 %; before: 48 MHz all the time.
## JIT (T7_JIT, 1.6.12 test2)
`src/core/t7_jit.c` translates straight runs of ROM code ($4000 up) into Thumb-2 code: 6502 A, X, Y, S and the flags
in ARM registers, memory through the page table (work and display RAM at a fixed address directly, the rest through
two shared stubs; an I/O write ends the block). A block runs only when the interpreter would run all of it in this
call (cycles left > its cycles before the last instruction, no sound event inside), with the same cycle sums, so the
result is the same instruction by instruction. Blocks follow each other inside the translated code while that holds
(exit stub with its own lookup). Blocks start where a run of code starts (after a jump or a block) and are made on
the 8th visit; keyed by the physical address, so banked code needs no flushing; buffer full: all thrown away.
Checked under qemu-arm against the x86 interpreter (host runner, state hash every 2 ms, 600 s with keys and sound):
identical. Device simulation (Unicorn, screen on): about 6,400 instead of 35,000 ARM instructions per ms.
The translator does not fit into the 64 KB of PRAM: it is a second part (`t7x.bin`, about 8 KB, magic "T7X1", build id,
length, sum) that the Studio writes into the save area at +0x8000 (main program 0x0C8000, menu instances save + 0x8000).
The program copies it into the SRAM behind its data; the rest of the SRAM up to the stack holds the translated code
(about 44 KB). Without a matching second part (older Studio, other build) T7Emu runs as before. Setting "JIT" (On/Off,
"missing" without the second part), settings byte r3 bit 0.
## Volume (T7_VOL, HW_VOL5, 1.6.12 test3)
The buzzer gets a pulse per period; its length sets the volume. Before: 1/32 of the period. Setting "Sound": Off, Quiet
(1/32, as before), Medium (1/8), Loud (1/4). A half period (square wave) was tried and was quieter than 1/4 on the
device. Stored in g_set.sound (old value 1 = Quiet).
## Tone and fixed settings (1.6.12 test4)
- T7_TONE_EV: the tone changes come from the core's tone events (t7_snd_tone_events: a look every ms of game time, a
new pitch only when it stays 4 ms, silent when the envelope at $93 has died away, with the cycle it happened). Before,
the main loop looked every 2 ms: at each note start the next pitch sounded for 2 ms, then 4 ms of silence, then the
note (host comparison of a melody: a click at every note); notes rang on after their envelope.
- T7_TONE_ISR: the tone queue (T7_TONE_Q) is played from the 1 ms tick instead of the main loop, where a note change
waited for drawing and the emulation. HW_TONE_IRQSAFE: hw_tone with the interrupts off, TONE_SAFE: a shorter period
below the running counter restarts it (otherwise silent until the counter wraps).
- T7_FIXED: power save maximal and the JIT always, without settings (tested over night).
- T7_WHEEL_RAW: the wheel's long press is timed with a tick count that is never set ahead (g_ms is moved on after
deep sleep and by eco_rtc, up to a second at once: a short press right after waking counted as long and left).
## Game clock tempo (T7_TBH_RATE, 1.6.12 test2)
The game counts its seconds from the 2 Hz timer (IRQ 13, two passes of $D1A3 per second). The core fired it every
2,000,000 cycles (4 MHz); the Paradise runs the core at 3.03 MHz for the tempo, so a game second lasted 1.32 s and the
clock note set it ahead by 2 to 3 seconds every few seconds (the seconds jumped). T7_TBH_RATE=1515150: two per real
second.
## Keys (T7_KEYQ, 1.6.9 test13)
The main loop read the keys once per pass; a pass that draws and catches up took longer than a quick tap, the tap was
lost. The 1 ms tick now counts every press (GPIO0 P0.9 A, P0.11 B, P0.10 C, pressed = 0); each counted press goes to
the game for at least 120 ms of emulated time (longer while held), then 100 ms released (test14: on the PC the
firmware lost taps shorter than about 120 ms or gaps shorter than about 80 ms, also without STOP).
test15: a press counts only after the key was up for 30 ms (KQ_DEB): the contacts bounce, one press
was taken as two (clock and straight back to the room).
T7_STOP_KEYACT (cycles, 4000000 = 1 s): after a key change no STOP. Halted, the firmware missed the release
(only IRQ 13 enabled, 2 Hz) and took the next press as the same one: 3 quick taps, 1 or 2 seen. Presses that wake the screen,
close the settings menu or come while it is open do not reach the game. host/hrun.c "k A hold gap" taps in 2 ms steps:
the core takes taps of 20 ms; test/devt7.py feeds the GPIO and the press counter.
## Save after a battery change (T7_SESS_EESEQ, T7_EE_SOON, 1.6.9 test16)
A user report: items bought in a figure shop vanished, after taking the batteries out the game was new. The run
state (session, 0x0C0000) holds the CPU, RAM and display, not the EEPROM; SESS_AUTO writes it every 30 minutes or
when the screen goes dark. After a battery change that old run state was resumed: its RAM won over the EEPROM the
game had written since, and the game wrote the old state back. Now the session sector notes at 0xFF8 "T7EQ" and the
sequence of the EEPROM slot in the flash (the EEPROM is stored first, then the session); a session whose sequence is
not the current one is dropped and the game starts from its EEPROM. Sessions without the note load as before.
T7_EE_SOON: the game's EEPROM writes go to the flash 5 s later (2 s without a key) instead of after a minute
without keys. The game writes its EEPROM seldom (host/hrun.c with -DT7_EEDBG, EEDBG=1: at the setup and at
events, nothing in 10 idle minutes). Checked in test/devt7.py (session with SESS_T1/T2 short: sequence noted;
a session with an older sequence: cold start from the EEPROM, the egg is there).
## Tone (T7_TONE_Q, 1.6.9 test14)
The tone was set right after each 2 ms step. After drawing or a flash write the loop catches up up to 30 ms at
once, so the notes of a melody (about 26 ms, host/hrun.c "tl <s>" lists them) came within a millisecond and were
swallowed. As T18Emu: tone changes queued with the game time, played 80 ms after the first of a sequence on the
real clock, late by more than 200 ms the timing starts anew.
## Pixel mode (T7_PIXSOFT, tried in test13, off)
A game pixel is 2 display pixels (pixel exact) or 2 to 3 (large). test13 drew the gap of every cell in its own colour,
a little lighter; on the device it no longer looked like pixels. Off again, the pixel mode is as before.
## Visits between two Paradise (T7_LINK, 1.6.9)
Tama-Go: connection icon, TAMA-GO, VISIT or GAME. Both wait in STAND BY, B on the device that goes visiting sends.
The game sends a packet with `$748E` (bank 3): `$32` and `$5B` minus the count, a preamble, then the bytes from `$0220`
by switching the infrared LED (`$3016` bit 3). `t7_ir_led_on` (called by `t7_io_write`, outside the hot loop) takes
the packet at the first LED switch-on of the preamble (`$32 == $5B`) as 32 bytes with the sum in the last, like the
older `t7_ir_bridge_tx_poll` (that one compared `$0220` and lost a packet sent again unchanged). The other device puts
it in with `t7_ir_bridge_rx` (the receive hook at `$60C4` of the IR bridge), only while its game is in the connection
screen (`t7_ir_activity` changed within 1.5 s), so an old packet does not wait. Between the devices: `T` frames over
the UART on the contacts (`../emu/src/emu/plink.h`, 460800 8N1, A5 type len data sum, hello every second).
Sound must be on: the game waits for its beeps to end (`$A3` bit 7) also during the visit. Checked on the PC with two
cores linked in lockstep: visit (guest away, the host shows both, guest home), GAME (YOU WIN / YOU LOSE), the second
device entering STAND BY late (the first one sends again).
## Clock note after a battery change (T7_CK_WRAP, 1.6.11 test1)
When the game asks for the time, the noted game time is counted on with the Paradise's seconds counter. After a
battery change that counter starts at 0 again, below the noted value; the difference wrapped to about 136 years and
the game got a date far off. Now the noted time is taken as it was (the clock from the Paradise sets it right after).
No session (SESS_FLAG, 1.7.3 test7): settings flag bit 12 (0x1000): the run state is never written (leaving, automatic sessions, battery empty) and an old one is dropped at the start; the EEPROM, settings and clock note are stored as before, so the toy starts from its own save.
+47
View File
@@ -0,0 +1,47 @@
0 3
B 0.2
0 2
B 0.2
0 0.6
B 0.2
0 0.6
B 0.2
0 0.6
A 0.2
0 0.6
B 0.2
0 0.6
B 0.2
0 0.6
B 0.2
0 0.6
B 0.2
0 0.6
B 0.2
0 0.8
B 0.2
0 0.8
B 0.2
0 0.8
B 0.2
0 0.8
B 0.2
0 0.8
B 0.2
0 0.8
B 0.2
0 0.8
B 0.2
0 0.8
0 120
A 0.2
0 1
B 0.2
0 3
C 0.2
0 2
A 0.2
A 0.2
0 1
B 0.2
0 10
+114
View File
@@ -0,0 +1,114 @@
/* PC test of the Paradise T7 app logic (t7app.c): screen, clock, save, catching up, figures.
* happ <rom> [figure...] commands on stdin:
* w <s> run s seconds (rtc counts along, app_clock every 2 s)
* slow <s> run s seconds, but the rtc counts twice as fast (emulation too slow)
* p A|B|C|W press (W = wheel short = figure menu)
* poke <h> <m> <s> set the game clock
* t print the game clock
* save <f> / load <f> [pause_s] save state / load it after a pause (catch up)
* s <file.ppm> screenshot of the 128x128 screen
*/
#include "../src/core/t7.h"
#include "../src/app/t7app.h"
#include <stdio.h>
void host_set_rom(unsigned char *p, size_t n);
void app_wheel_short(void);
static unsigned char *rd(const char *f, size_t *n) { FILE *x = fopen(f, "rb"); fseek(x, 0, 2); *n = ftell(x); fseek(x, 0, 0); unsigned char *p = malloc(*n); if (fread(p, 1, *n, x)) {} fclose(x); return p; }
static uint16_t fb[128][128]; static int rx0, rx1, ry;
static uint32_t g_rtc = 1000000, g_ms;
static T7Cfg cfg = { T7_MAGIC, 1, 0, 0, 0, 0, {{0}}, 0 };
static const uint8_t *figs[T7_FIG_MAX];
uint32_t plat_rtc(void) { return g_rtc; }
void plat_vol(int v) { (void)v; }
void plat_bat(char *s) { const char *t = "2.84V 80%"; int i = 0; while ((s[i] = t[i])) i++; }
void plat_rect(int x0, int y0, int x1, int y1) { rx0 = x0; rx1 = x1; ry = y0; (void)y1; }
void plat_row(const uint16_t *px, int n) { for (int i = 0; i < n && rx0 + i < 128; i++) fb[ry][rx0 + i] = px[i]; ry++; }
void plat_rect_end(void) {}
const uint8_t *plat_fig_ptr(int i) { return figs[i]; }
static uint8_t store[T7_STORE_LEN]; static int have_store;
int plat_store_load(uint8_t *b, uint32_t n) { if (!have_store) return 0; memcpy(b, store, n); return 1; }
void plat_store_write(const uint8_t *b, uint32_t n) { memcpy(store, b, n); have_store = 1; printf("store: bg=%d size=%d pixel=%d note=%d\n", b[4], b[8], b[9], b[32] == 'T'); }
static int keys, dark;
extern uint8_t g_t7_dark; int app_bell(void);
static int icon9_px(void) { int n = 0; for (int y = 106; y < 126; y++) for (int x = 4*128/5 + 2; x < 4*128/5 + 22; x++) if (fb[y][x] != fb[105][0]) n = fb[y][x]; return n; }
static void run(double s, int rtcx)
{
int n = (int)(s * 500 + 0.5);
for (int i = 0; i < n; i++) {
g_ms += 2;
t7_set_buttons((uint8_t)app_keys((uint32_t)keys, g_ms));
app_tick(g_ms);
t7_step_cycles(T7_CLOCK_RATE / 500);
{ static int pt; static uint32_t lt; uint8_t lv; int tn = t7_snd_tone_hz(&lv) != 0; if (tn && !pt) { if (g_ms - lt > 5000) { uint8_t ic[10]; t7_get_icons(ic); printf("TONE %02d:%02d ic %d calls %02x %02x %02x %02x %02x %02x %02x hh %02x %02x\n", t7_ram_read(0x306), t7_ram_read(0x307), ic[9], t7_ram_read(0x3b0), t7_ram_read(0x3b1), t7_ram_read(0x3b2), t7_ram_read(0x3b3), t7_ram_read(0x3b4), t7_ram_read(0x3b5), t7_ram_read(0x3b6), t7_ram_read(0x326), t7_ram_read(0x327)); } lt = g_ms; } pt = tn; }
{ static uint32_t cs; static int pc; int c = t7_ram_read(0x3b0) | t7_ram_read(0x3b1) | t7_ram_read(0x3b2) | t7_ram_read(0x3b4) | t7_ram_read(0x3b5) | t7_ram_read(0x3b6); uint8_t ic[10]; t7_get_icons(ic);
if (c && !pc) cs = g_ms; if (cs && ic[9]) { printf("CALL->ICON %u ms\n", g_ms - cs); cs = 0; } if (!c) cs = 0; pc = c != 0; }
if (g_ms % 1000 == 0) g_rtc += (uint32_t)rtcx;
if (g_ms % 500 == 0) app_setup_fill(g_rtc);
if (g_ms % 2000 == 0) app_clock(g_rtc, 0);
if (dark) { g_t7_dark = 1; if (app_bell()) { dark = 0; g_t7_dark = 0; app_render(1); printf("bell wake at %02d:%02d px %d\n", t7_ram_read(0x306), t7_ram_read(0x307), icon9_px()); } continue; }
g_t7_dark = 0;
if (g_ms % 34 == 0) { app_render(0); static int pb; int b = app_bell(); if (b != pb) { printf("bell %d at %02d:%02d px %d\n", b, t7_ram_read(0x306), t7_ram_read(0x307), icon9_px()); pb = b; } }
}
}
static void shot(const char *f)
{
app_render(0);
FILE *o = fopen(f, "wb"); fprintf(o, "P6 128 128 255\n");
for (int y = 0; y < 128; y++) for (int x = 0; x < 128; x++) { uint16_t p = fb[y][x]; fputc((p >> 11) << 3, o); fputc(((p >> 5) & 63) << 2, o); fputc((p & 31) << 3, o); }
fclose(o);
}
static void prog(int d, int t) { if (d == t) printf("caught up %d hours\n", t); }
int main(int c, char **v)
{
size_t n; unsigned char *rom = rd(v[1], &n); host_set_rom(rom, n);
for (int i = 2; i < c && i - 2 < T7_FIG_MAX; i++) {
size_t fn; figs[i - 2] = rd(v[i], &fn); cfg.fig[i - 2].len = (uint32_t)fn;
const char *b = strrchr(v[i], '_'); b = b ? b + 1 : v[i]; int k = 0;
while (b[k] && b[k] != '.' && k < 15) { cfg.fig[i - 2].name[k] = b[k]; k++; }
cfg.nfig++;
}
if (getenv("EE")) { size_t en; unsigned char *e = rd(getenv("EE"), &en); size_t m2 = en; extern void persist_restore_page(int, const uint8_t *); for (int i = 0; i < 16 && (size_t)(i + 1) * 256 <= en; i++) persist_restore_page(i, e + (m2 == 4098 ? 2 : 0) + i * 256); } /* EE=save (Studio save.bin: u16 have first) */
app_init(&cfg);
t7_init();
t7_snd_config(T7_CLOCK_RATE, 16000); t7_snd_capture(0); t7_snd_set_mode(1);
app_render(1);
char l[256];
while (fgets(l, sizeof l, stdin)) {
char cmd[16], a[200]; double x = 0; int k = sscanf(l, "%15s %199s %lf", cmd, a, &x);
if (k < 1) continue;
if (!strcmp(cmd, "w")) run(atof(a), 1);
else if (!strcmp(cmd, "slow")) run(atof(a), 2);
else if (!strcmp(cmd, "p")) {
if (a[0] == 'W') { app_wheel_short(); run(0.3, 1); }
else { keys = a[0] == 'A' ? 1 : a[0] == 'B' ? 2 : 4; run(0.2, 1); keys = 0; run(k > 2 ? x : 0.8, 1); }
}
else if (!strcmp(cmd, "poke")) { int h, m, s2; sscanf(l, "%*s %d %d %d", &h, &m, &s2); t7_ram_write(0x306, h); t7_ram_write(0x307, m); t7_ram_write(t7_rtc_sec_addr(), s2); }
else if (!strcmp(cmd, "t")) printf("game %02d:%02d:%02d day %d.%d rtc %u fig %d species %02x\n", t7_ram_read(0x306), t7_ram_read(0x307), t7_ram_read(t7_rtc_sec_addr()), t7_ram_read(0x305), t7_ram_read(0x304), g_rtc, t7_figure_get(), t7_ram_read(0x22));
else if (!strcmp(cmd, "save")) { static uint8_t b[4096]; uint32_t m = app_save(b, sizeof b); FILE *o = fopen(a, "wb"); fwrite(b, 1, m, o); fclose(o); printf("saved %u bytes\n", m); }
else if (!strcmp(cmd, "load")) {
size_t m; unsigned char *b = rd(a, &m); uint32_t sv;
g_rtc += (uint32_t)x;
t7_init();
printf("load %s\n", app_load(b, (uint32_t)m, &sv) ? "ok" : "FAILED");
if (app_clock_hard(g_rtc)) printf("clock from the Paradise\n"); else app_catchup(g_rtc, prog);
}
else if (!strcmp(cmd, "i")) { uint8_t ic[10]; t7_get_icons(ic); printf("icons"); for (int q = 0; q < 10; q++) printf(" %d", ic[q]); printf(" ram326 %02x %02x 3b0", t7_ram_read(0x326), t7_ram_read(0x327)); for (int q = 0; q < 7; q++) printf(" %02x", t7_ram_read((uint16_t)(0x3b0 + q))); printf(" t %02d:%02d\n", t7_ram_read(0x306), t7_ram_read(0x307)); }
else if (!strcmp(cmd, "s")) shot(a);
else if (!strcmp(cmd, "para")) { /* para <y> <m> <d> <h> <mi>: the Paradise's time now, clock flag on */
int y, mo, d, h, mi; sscanf(l, "%*s %d %d %d %d %d", &y, &mo, &d, &h, &mi);
int yy = y - (mo <= 2), era = yy / 400, yoe = yy - era * 400, doy = (153 * (mo + (mo > 2 ? -3 : 9)) + 2) / 5 + d - 1, doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
g_para_time = (uint32_t)(era * 146097 + doe - 719468) * 86400u + (uint32_t)(h * 3600 + mi * 60); g_para_cnt = g_rtc; cfg.flags |= 2u;
}
else if (!strcmp(cmd, "wall")) { int h, m, d, mo; sscanf(l, "%*s %d %d %d %d", &h, &m, &d, &mo); cfg.wall_cnt = g_rtc; cfg.wall_sod = (uint32_t)(h * 3600 + m * 60); cfg.wall_ymd = (2026u << 16) | (uint32_t)(mo << 8 | d); }
else if (!strcmp(cmd, "store")) app_store();
else if (!strcmp(cmd, "set")) { extern T7Set g_set; int sz = 0, px = 0, gr = -1; sscanf(l, "%*s %d %d %d", &sz, &px, &gr); g_set.size = (uint8_t)sz; g_set.pixel = (uint8_t)px; if (gr >= 0) g_set.grid = (uint8_t)gr; app_dim(1); app_dim(0); } /* set <size> <pixel> [grid] */
else if (!strcmp(cmd, "reboot")) { t7_init(); app_init(&cfg); app_render(1); }
else if (!strcmp(cmd, "wb")) { unsigned ad, v; sscanf(l, "%*s %x %x", &ad, &v); t7_ram_write((uint16_t)ad, (uint8_t)v); } /* test30 */
else if (!strcmp(cmd, "dump")) { FILE *o = fopen(a, "wb"); for (int i = 0; i < 0x600; i++) fputc(t7_ram_read((uint16_t)i), o); fclose(o); }
else if (!strcmp(cmd, "dark")) dark = atoi(a);
else if (!strcmp(cmd, "noclk")) cfg.flags &= ~2u; /* clock not from the Paradise */
else if (!strcmp(cmd, "q")) break;
fflush(stdout);
}
return 0;
}
+22
View File
@@ -0,0 +1,22 @@
/* Host build of the Paradise T7 app glue: ROM from a file, EEPROM pages in memory. */
#include "../src/core/pebble_compat.h"
#include <stdarg.h>
static unsigned char *g_rom; static size_t g_rom_n;
static unsigned char g_pages[16][256]; static unsigned char g_has[16];
void host_set_rom(unsigned char *p, size_t n){ g_rom=p; g_rom_n=n; }
void tama_log(const char *fmt, ...){ if(!getenv("T7LOG")) return; va_list a; va_start(a,fmt); vfprintf(stderr,fmt,a); va_end(a); }
ResHandle resource_get_handle(int id){ (void)id; return g_rom?1:0; }
size_t resource_size(ResHandle h){ (void)h; return g_rom_n; }
size_t resource_load_byte_range(ResHandle h, size_t off, uint8_t *out, size_t len){ (void)h; if(off>=g_rom_n) return 0; if(off+len>g_rom_n) len=g_rom_n-off; memcpy(out,g_rom+off,len); return len; }
const uint8_t *t7_compat_rom_mapped(void){ return g_rom; }
bool persist_exists(uint32_t key){ return key>=100 && key<116 && g_has[key-100]; }
int persist_read_data(uint32_t key, void *buf, size_t n){ if(!persist_exists(key)) return -1; if(n>256) n=256; memcpy(buf,g_pages[key-100],n); return (int)n; }
status_t persist_write_data(uint32_t key, const void *buf, size_t n){ if(key<100||key>=116) return -1; if(n>256) n=256; memcpy(g_pages[key-100],buf,n); g_has[key-100]=1; return S_SUCCESS; }
status_t persist_delete(uint32_t key){ if(key>=100&&key<116) g_has[key-100]=0; return S_SUCCESS; }
void persist_flush_to_disk(void){}
int persist_page_count(void){ return 16; }
int persist_page_size(void){ return 256; }
int persist_backup_page(int p, uint8_t *o){ memcpy(o,g_pages[p],256); return g_has[p]; }
void persist_restore_page(int p, const uint8_t *i){ memcpy(g_pages[p],i,256); g_has[p]=1; }
void t7_compat_set_rom_path(const char *p){ (void)p; }
void t7_compat_set_eeprom_path(const char *p){ (void)p; }
+81
View File
@@ -0,0 +1,81 @@
/* Host: boot the V7 ROM, press keys, save screenshots. hrun <rom> [figure]; stdin: p A|B|C [s] | w s | s file | q */
#include "../src/core/t7.h"
#include <stdio.h>
#include "../src/core/t7_internal.h"
void host_set_rom(unsigned char *p, size_t n);
void figure_rom_set_active(const unsigned char* p, unsigned int n);
static unsigned char *rd(const char *f, size_t *n){ FILE*x=fopen(f,"rb"); fseek(x,0,2); *n=ftell(x); fseek(x,0,0); unsigned char*p=malloc(*n); if(fread(p,1,*n,x)){} fclose(x); return p; }
#ifdef T7_STOP_DBG
static long g_step; void t7_stop_dbg(int w){ static int n; if (getenv("SDBG") && n++ < 400) fprintf(stderr, "step %ld STOP 3007=%02x 3008=%02x keys=%x halted=%d irqmask=%02x%02x nmi=%02x\n", g_step, g_cpureg[7], g_cpureg[8], g_keys, g_t7_halted, g_cpureg[0x70], g_cpureg[0x71], g_cpureg[0x76]); (void)w; }
#endif
#ifdef T7_EEDBG
static double g_now; void t7_eedbg(uint16_t a, uint8_t v){ static double last=-1; if (getenv("EEDBG") && g_now != last) { fprintf(stderr, "ee write at %.2f s: %03x=%02x\n", g_now, a, v); last = g_now; } }
#endif
static void frames(double s){ static int cyc; if(!cyc) cyc=getenv("CYC")?atoi(getenv("CYC")):40000; int n=(int)(s*100+0.5); for(int i=0;i<n;i++) { t7_step_cycles(cyc);
#ifdef T7_EEDBG
g_now += 0.01;
#endif
} }
static void shot(const char *f){ uint8_t d[48*31], ic[10]; t7_get_display(d); t7_get_icons(ic);
static const int pal[4]={0xE0,0xA0,0x60,0x20}; FILE*o=fopen(f,"wb"); fprintf(o,"P6 192 140 255\n");
for(int y=0;y<140;y++) for(int x=0;x<192;x++){ int v=0xF0;
if(y>=8&&y<132){ int yy=(y-8)/4, xx=x/4; if(yy<31) v=pal[d[yy*48+xx]]; }
else { int k=x/(192/5)+(y>=132?5:0); v=ic[k]?pal[ic[k]]:0xF0; }
fputc(v,o); fputc(v,o); fputc(v,o);} fclose(o); }
int main(int c, char **v){ size_t n; unsigned char *rom=rd(v[1],&n); host_set_rom(rom,n);
if(c>2){ size_t fn; unsigned char*f=rd(v[2],&fn); figure_rom_set_active(f,(unsigned)fn); t7_figure_set(1); }
if (getenv("EE")) { size_t en; unsigned char *e=rd(getenv("EE"),&en); extern void persist_restore_page(int,const uint8_t*); for (int i=0;i<16 && (size_t)(i+1)*256<=en;i++) persist_restore_page(i,e+i*256); } /* EE=save: EEPROM from a file */
if(!t7_init()){ printf("init failed\n"); return 1; }
if (getenv("SND")) { extern void t7_snd_set_mode(int); t7_snd_set_mode(1); }
#ifdef T7_JSR_HLE
if (getenv("DARK")) g_t7_dark = 1; /* screen off as on the device */
#endif
char l[256]; while(fgets(l,sizeof l,stdin)){ char cmd[16],a[200]; double x=0; int k=sscanf(l,"%15s %199s %lf",cmd,a,&x); if(k<1) continue;
if(!strcmp(cmd,"p")){ t7_set_buttons(a[0]=='A'?1:a[0]=='B'?2:4); frames(0.2); t7_set_buttons(0); frames(k>2?x:0.8); }
else if(!strcmp(cmd,"w")) frames(atof(a));
else if(!strcmp(cmd,"tl")){ /* tl <s>: tone list in 2 ms steps (hz x steps) */ extern uint32_t t7_snd_tone_hz(uint8_t*); uint32_t last=0xFFFFFFFF; int n=0; int m=(int)(atof(a)*500+0.5);
for(int i=0;i<m;i++){ t7_step_cycles(8000); uint8_t lv; uint32_t hz=t7_snd_tone_hz(&lv); if(hz!=last){ if(n) printf("%u x%d\n",last,n); last=hz; n=0; } n++; } printf("%u x%d\nEND\n",last,n); }
else if(!strcmp(cmd,"k")){ double g=0; sscanf(l,"%*s %*s %lf %lf",&x,&g); int m=a[0]=='A'?1:a[0]=='B'?2:4; /* k A hold gap: a quick press in 2 ms steps */
t7_set_buttons(m); for(int i=0;i<(int)(x*500+0.5);i++) { t7_step_cycles(8000);
#ifdef T7_STOP_DBG
g_step++; if (getenv("TL")) fputc(g_t7_halted ? 'h' : 'r', stderr);
#endif
}
#ifdef T7_STOP_DBG
if (getenv("TL")) fputc('|', stderr);
#endif
t7_set_buttons(0); for(int i=0;i<(int)(g*500+0.5);i++) { t7_step_cycles(8000);
#ifdef T7_STOP_DBG
if (getenv("TL")) fputc(g_t7_halted ? 'H' : 'R', stderr);
#endif
}
#ifdef T7_STOP_DBG
if (getenv("TL")) fputc('\n', stderr);
#endif
}
#ifdef T7_JSR_HLE
else if(!strcmp(cmd,"dk")){ g_t7_dark=(uint8_t)atoi(a); } /* dk 1|0: screen off/on */
#ifdef T7_WAKE_FRESH
else if(!strcmp(cmd,"wake")){ extern uint32_t g_t7_blits; uint32_t b0=g_t7_blits, bt=0; int t=0; g_t7_dark=0; /* wake: on as T7_WAKE_FRESH (light after a drawn picture) */
for(;;){ t7_step_cycles(8000); t+=2; if(g_t7_blits!=b0){ b0=g_t7_blits; bt=t; } if((bt && t-bt>=20) || t>=700) break; }
printf("wake light after %d ms\n", t); }
else if(!strcmp(cmd,"peek")){ extern uint32_t g_t7_blits; uint32_t b0=g_t7_blits, bt=0; int t=0; g_t7_dark=0; /* peek: one picture with the screen dark, then dark again */
for(;;){ t7_step_cycles(8000); t+=2; if(g_t7_blits!=b0){ b0=g_t7_blits; bt=t; } if((bt && t-bt>=20) || t>=700) break; }
g_t7_dark=1; shot(a); printf("peek %d ms\n", t); }
#endif
#endif
else if(!strcmp(cmd,"i")){ uint8_t ic[10]; t7_get_icons(ic); printf("icons"); for(int i=0;i<10;i++) printf(" %d",ic[i]); printf("\n"); }
else if(!strcmp(cmd,"s")) shot(a);
else if(!strcmp(cmd,"t")) printf("time %02d:%02d:%02d day %d.%d\n", t7_ram_read(0x306),t7_ram_read(0x307),t7_ram_read(t7_rtc_sec_addr()),t7_ram_read(0x305),t7_ram_read(0x304));
else if(!strcmp(cmd,"poke")){ t7_ram_write((uint16_t)strtol(a,0,16),(uint8_t)x); }
else if(!strcmp(cmd,"d")){ FILE*o=fopen(a,"wb"); fwrite(g_wram,1,T7_WRAM_SIZE,o); fclose(o); }
else if(!strcmp(cmd,"r")){ int a0=(int)strtol(a,0,16), m=x>0?(int)x:1; printf("ram %03x:",a0); for(int i=0;i<m;i++) printf(" %02x",t7_ram_read((uint16_t)(a0+i))); printf("\n"); }
#ifdef T7_BLIT_CACHE
else if(!strcmp(cmd,"bc")){ extern uint32_t g_bc_hit, g_bc_miss; printf("blit cache hit %u miss %u\n", g_bc_hit, g_bc_miss);
#ifdef T7_BC_LOG
{ extern void bc_print(void); bc_print(); }
#endif
}
#endif
else if(!strcmp(cmd,"q")) break; fflush(stdout); }
return 0; }
+15
View File
@@ -0,0 +1,15 @@
/* PC histogram of the V7 firmware (host). pcprof <rom> <setup.txt-like keys file> <secs> */
#include "../src/core/t7_internal.h"
#include <stdio.h>
void host_set_rom(unsigned char *p, size_t n);
static unsigned char *rd(const char *f, size_t *n){ FILE*x=fopen(f,"rb"); fseek(x,0,2); *n=ftell(x); fseek(x,0,0); unsigned char*p=malloc(*n); if(fread(p,1,*n,x)){} fclose(x); return p; }
static unsigned cnt[65536];
int main(int c,char**v){ size_t n; unsigned char *rm=rd(v[1],&n); host_set_rom(rm,n); if(!t7_init()) return 1;
double secs=atof(v[2]); long total=(long)(secs*4000000), done=0; long ins=0;
/* after 5 s, count */
while(done<total){ uint32_t s=t7_step_cycles(4000); done+=s; }
for(long k=0;k<(long)(2*4000000);){ uint16_t pc=g_cpu.pc; cnt[pc]++; ins++; uint32_t cy=t7_step_one(); if(!cy) cy=1; k+=cy;
static uint32_t acc; acc+=cy; if(acc>=66666){acc-=66666; t7_fire_irq(10); t7_fire_nmi(6);} }
printf("instr in 2 s: %ld (%.2f M/s)\n", ins, ins/2e6);
for(int r=0;r<15;r++){ int b=0; for(int i=1;i<65536;i++) if(cnt[i]>cnt[b]) b=i; printf("%04x %u bank %d\n",b,cnt[b],g_rom_bank_id); cnt[b]=0; }
}
+22
View File
@@ -0,0 +1,22 @@
/* Same key script on t7_cpu_step and on t7_cpu_run (build twice, -DT7_FASTRUN): prints a hash of
* the whole state after every 2 ms step; the two outputs must be equal. runcmp <rom> <script> */
#include "../src/core/t7_internal.h"
#include "../src/core/t7_sound.h"
#include <stdio.h>
#include <stdlib.h>
void host_set_rom(unsigned char *p, size_t n);
static unsigned char *rd(const char *f, size_t *n){ FILE*x=fopen(f,"rb"); fseek(x,0,2); *n=ftell(x); fseek(x,0,0); unsigned char*p=malloc(*n); if(fread(p,1,*n,x)){} fclose(x); return p; }
static uint32_t h(const uint8_t *p, int n, uint32_t s){ while(n--) s = s*16777619u ^ *p++; return s; }
int main(int c,char**v){ size_t n; unsigned char*rm=rd(v[1],&n); host_set_rom(rm,n); if(!t7_init()) return 1;
if (c>3) t7_snd_set_mode(1);
FILE*f=fopen(v[2],"r"); char l[128]; long step=0;
while(fgets(l,sizeof l,f)){ char k=0; double s=0; if(sscanf(l,"%c %lf",&k,&s)<2) continue;
t7_set_buttons(k=='A'?1:k=='B'?2:k=='C'?4:0);
int m=(int)(s*500+0.5);
for(int i=0;i<m;i++){ t7_step_cycles(8000); uint8_t buf[4096]; uint32_t sz=t7_serialize_state(buf,sizeof buf);
uint32_t hh=h(buf,sz,2166136261u); printf("%ld %08x pc=%04x a=%02x x=%02x y=%02x s=%02x w=%08x d=%08x r=%08x\n",step++,hh,g_cpu.pc,g_cpu.a,g_cpu.x,g_cpu.y,g_cpu.s,h(g_wram,0x600,1),h(g_dram,0x200,1),h(g_cpureg,256,1)); } }
if (getenv("CLK")) { for (int i = 0x390; i < 0x3A0; i++) fprintf(stderr, "%02x ", g_wram[i]); fprintf(stderr, "\n"); }
#if defined(T7_IDLE) || defined(T7_STOP)
fprintf(stderr, "idle ok %u, skipped %u cycles of %ld\n", g_t7_idle_ok, g_t7_idle_cyc, step * 8000L);
#endif
return 0; }
+18
View File
@@ -0,0 +1,18 @@
w 3
p B 2
p B 0.6
p B 0.6
p B 0.6
p A 0.6
p B 0.6
p B 0.6
p B 0.6
p B 0.6
p B 0.8
p B 0.8
p B 0.8
p B 0.8
p B 0.8
p B 0.8
p B 0.8
p B 0.8
+13
View File
@@ -0,0 +1,13 @@
#include "../src/core/t7_internal.h"
#include <stdio.h>
void host_set_rom(unsigned char *p, size_t n); uint8_t t7_dbg_p(void); uint32_t t7_cpu_run(uint32_t);
static unsigned char *rd(const char *f, size_t *n){ FILE*x=fopen(f,"rb"); fseek(x,0,2); *n=ftell(x); fseek(x,0,0); unsigned char*p=malloc(*n); if(fread(p,1,*n,x)){} fclose(x); return p; }
int main(int c,char**v){ size_t n; unsigned char*rm=rd(v[1],&n); host_set_rom(rm,n); t7_init(); long N=atol(v[2]);
for(long i=0;i<N;i++){
#ifdef T7_FASTRUN
uint32_t cy=t7_cpu_run(1);
#else
uint32_t cy=t7_cpu_step();
#endif
printf("%ld %04x %02x %02x %02x %02x %02x %u m48=%02x %02x\n",i,g_cpu.pc,g_cpu.a,g_cpu.x,g_cpu.y,g_cpu.s,t7_dbg_p(),cy,t7_read_page[0][0x48],t7_read_page[0][0x49]); }
}
+21
View File
@@ -0,0 +1,21 @@
#!/bin/sh
# Build the T7 app for the Paradise (clang/lld, Cortex-M3). Output: ../../t7.bin
set -e
cd "$(dirname "$0")"
E=../../../emu/src/emu
XID=${XID:-0x$(date +%s | sha1sum | cut -c1-8)} # the two parts belong together
CF="--target=thumbv7m-none-eabi -mcpu=cortex-m3 -mthumb -ffreestanding -nostdlib -fno-common -Wall -Wno-unused-function -fno-builtin-memset -DFAST_LCD -DEXIT_KEY -DLCD_FASTCLK -DTONE_FIX -DHW_TONE_RESTART -DWAKE_WHEEL -DBL_SLEEP -DT7_NOMALLOC -DT7_FREESTANDING -DT7_NO_SYNTH -DSPI_TRACE_MAX=1 -DT7_FASTRUN -DT7_VIDEO_CYCLES -DT7_SND_RING=16u -DT7_SND_SYN_N=4u -DT7_BELL_WAKE -DT7_FR_ICONS -DSESS_ONCE -DSESS_AUTO -DPARA_BACK -DPARA_MB_KEEP -DBL_PWM -DBL_MR3RST -DT7_PW_FIX -DT7_LINK -DT7_IDLE -DT7_STOP -DT7_KEYQ -DT7_STOP_KEYACT=4000000u -DT7_TONE_Q -DT7_SESS_EESEQ -DT7_EE_SOON -DBAT_SHOW -DCLK_ECO -DECO_LAG=400 -DT7_WFI_FIX -DT7_EE_SHIFT -DECO_RTC -DT7_GAME_KEEP -DT7_CK_WRAP -DT7_CARE -DASK_NUM -DT7_JSR_HLE -DT7_BLIT_CACHE -DT7_DARK_STEP -DT7_DARK_PEEK -DT7_NO_CATCHUP -DT7_PW -DT7_SND_LAZY -DT7_JIT -DT7_TBH_RATE=1515150u -DT7_VOL -DHW_VOL5 -DT7_FIXED -DT7_TONE_EV -DT7_TONE_ISR -DHW_TONE_IRQSAFE -DTONE_SAFE -DT7_WHEEL_RAW -DT7_PW_RTCWAIT -DT7_CATCHUP_SMOOTH -DBAT_SMOOTH -DT7_CLK_COLD -DBAT_GUARD -DBAT_PIC -DT7_SESS_KEEP -DT7_KQ_CAP -DPARA_FLASH -DPARA_FLASH_LATE -DPARA_CLEAN_CLK -DSESS_FLAG -DT7X_ID=$XID -I../core $XCF"
O=""
for f in main.c t7app.c compat.c $E/hw.c $E/ask.c $E/flash.c $E/libc.c libgcc.c ../core/t7.c ../core/t7_cpu.c ../core/t7_memory.c ../core/t7_eeprom.c ../core/t7_sound.c ../core/figure_data.c ../core/t7_jit.c; do
n=$(basename $f .c); OPT=-Os; [ "$n" = t7_cpu ] && OPT=${CPUOPT:--O2}; clang $CF $OPT -c $f -o $n.o; O="$O $n.o"; done
ld.lld -T link.ld --no-rosegment $O -o t7.elf
llvm-objcopy -O binary -j .text -j .data -j .init t7.elf t7.bin
llvm-objcopy -O binary -j .xcode t7.elf x.raw
python3 - "$XID" <<'PY'
import struct, sys
d = open('x.raw', 'rb').read(); d += b'\0' * (-len(d) % 4)
s = sum(struct.unpack('<%dI' % (len(d) // 4), d)) & 0xFFFFFFFF
open('../../t7x.bin', 'wb').write(struct.pack('<4I', 0x31583754, int(sys.argv[1], 16), len(d), s) + d)
PY
rm -f x.raw
cp t7.bin ../../t7.bin; rm -f *.o t7.bin; [ -n "$KEEPELF" ] || rm -f t7.elf; llvm-size ../../t7.bin 2>/dev/null; ls -l ../../t7.bin ../../t7x.bin
+119
View File
@@ -0,0 +1,119 @@
/* The platform functions the V7 core expects (pebble_compat.h), on the Paradise:
* ROM from the flash (cached XIP window), EEPROM pages in RAM, written to the flash
* by eeprom_store(). Author: mameise */
#include "../core/pebble_compat.h"
#include "../../../emu/src/emu/io.h"
#include "../../../emu/src/emu/flash.h"
extern const uint8_t *g_rom_xip; /* main.c: start of the ROM in the cached window */
extern uint32_t g_rom_size, g_rom_off;
static uint8_t g_ee[16][256] __attribute__((aligned(4))); /* test27: the flash DMA takes words (was at ...2: pages 2 bytes off) */
static uint16_t g_have, g_dirty;
void tama_log(const char *fmt, ...) { (void)fmt; }
ResHandle resource_get_handle(int id) { (void)id; return 1; }
size_t resource_size(ResHandle h) { (void)h; return g_rom_size; }
size_t resource_load_byte_range(ResHandle h, size_t off, uint8_t *out, size_t len)
{
(void)h;
if (off >= g_rom_size) return 0;
if (off + len > g_rom_size) len = g_rom_size - off;
const volatile uint8_t *s = XIP_PTR(g_rom_off + off); /* uncached: right after setting the window */
for (size_t i = 0; i < len; i++) out[i] = s[i];
return len;
}
const uint8_t *t7_compat_rom_mapped(void) { return g_rom_xip; }
void t7_compat_set_rom_path(const char *p) { (void)p; }
void t7_compat_set_eeprom_path(const char *p) { (void)p; }
/* EEPROM: 16 pages of 256 bytes, keys 100..115. In flash: one 4 KB sector,
* behind it a byte per page that says whether the page was ever written. */
bool persist_exists(uint32_t key) { return key >= 100 && key < 116 && (g_have >> (key - 100)) & 1u; }
int persist_read_data(uint32_t key, void *buf, size_t n)
{
if (!persist_exists(key)) return -1;
if (n > 256) n = 256;
uint8_t *d = buf; for (size_t i = 0; i < n; i++) d[i] = g_ee[key - 100][i];
return (int)n;
}
status_t persist_write_data(uint32_t key, const void *buf, size_t n)
{
if (key < 100 || key >= 116) return -1;
if (n > 256) n = 256;
const uint8_t *s = buf; int ch = 0;
for (size_t i = 0; i < n; i++) if (g_ee[key - 100][i] != s[i]) { g_ee[key - 100][i] = s[i]; ch = 1; }
if (ch || !persist_exists(key)) { g_have |= (uint16_t)(1u << (key - 100)); g_dirty = 1; }
return S_SUCCESS;
}
status_t persist_delete(uint32_t key) { if (key >= 100 && key < 116 && persist_exists(key)) { g_have &= (uint16_t)~(1u << (key - 100)); g_dirty = 1; } return S_SUCCESS; }
void persist_flush_to_disk(void) {}
int persist_page_count(void) { return 16; }
int persist_page_size(void) { return 256; }
int persist_backup_page(int p, uint8_t *o) { for (int i = 0; i < 256; i++) o[i] = g_ee[p][i]; return persist_exists(100u + (uint32_t)p); }
void persist_restore_page(int p, const uint8_t *in) { for (int i = 0; i < 256; i++) g_ee[p][i] = in[i]; g_have |= (uint16_t)(1u << p); g_dirty = 1; }
/* Flash: two slots of 8 KB (header sector, page sector) at at+0 and at+0x2000. A new state
* goes into the other slot (pages first, header last), so a power cut always leaves one
* complete slot. The newer valid slot wins. */
#define EE_MAGIC 0x45453754u /* "T7EE" */
static uint32_t g_seq; static int g_slot = -1;
static uint32_t rd32(const volatile uint8_t *h) { return h[0] | (h[1] << 8) | (h[2] << 16) | ((uint32_t)h[3] << 24); }
static uint32_t sum_pages(const volatile uint8_t *d) { uint32_t s = 0x7E7E; for (int i = 0; i < 4096; i++) s = s * 31u + d[i]; return s; }
#ifdef T7_EE_SHIFT
/* test27: up to test26 g_ee could lie at an address ...2; the flash DMA starts at the word below, so the page sector
* holds 2 other bytes, then the pages without their last 2 bytes (the header sum is over the right pages).
* Such a slot is taken 2 bytes on and written again correctly at the next store. */
static uint32_t sum_pages2(const volatile uint8_t *d) { uint32_t s = 0x7E7E; for (int i = 2; i < 4096; i++) s = s * 31u + d[i]; return s * 31u * 31u; }
static uint8_t g_shift[2];
#endif
static int slot_ok(uint32_t at, uint32_t *seq)
{
const volatile uint8_t *h = XIP_PTR(at);
if (rd32(h) != EE_MAGIC) return 0;
if (rd32(h + 12) != sum_pages(XIP_PTR(at + 0x1000u))) {
#ifdef T7_EE_SHIFT
if (rd32(h + 12) != sum_pages2(XIP_PTR(at + 0x1000u))) return 0;
*seq = rd32(h + 4);
return 2;
#else
return 0;
#endif
}
*seq = rd32(h + 4);
return 1;
}
void eeprom_load(uint32_t at)
{
uint32_t s0 = 0, s1 = 0; int a = slot_ok(at, &s0), b = slot_ok(at + 0x2000u, &s1);
#ifdef T7_EE_SHIFT
g_shift[0] = a == 2; g_shift[1] = b == 2;
#endif
g_have = 0; g_dirty = 0; g_slot = -1; g_seq = 0;
if (!a && !b) return;
g_slot = (a && (!b || (int32_t)(s0 - s1) > 0)) ? 0 : 1;
uint32_t base = at + (uint32_t)g_slot * 0x2000u;
g_seq = g_slot ? s1 : s0;
const volatile uint8_t *h = XIP_PTR(base);
g_have = (uint16_t)(h[8] | (h[9] << 8));
const volatile uint8_t *d = XIP_PTR(base + 0x1000u);
for (int p = 0; p < 16; p++) for (int i = 0; i < 256; i++) g_ee[p][i] = d[p * 256 + i];
#ifdef T7_EE_SHIFT
if (g_shift[g_slot]) { uint8_t *e = &g_ee[0][0]; for (int i = 0; i < 4094; i++) e[i] = d[i + 2]; e[4094] = e[4095] = 0; g_dirty = 1; }
#endif
}
int eeprom_dirty(void) { return g_dirty; }
uint32_t eeprom_seq(void) { return g_slot < 0 ? 0u : g_seq; } /* test16: which stored state is in the flash */
void eeprom_store(uint32_t at, uint8_t *sec4k)
{
if (!g_dirty) return;
int slot = g_slot == 0 ? 1 : 0;
uint32_t base = at + (uint32_t)slot * 0x2000u, seq = g_seq + 1u;
for (int i = 0; i < 0x1000; i++) sec4k[i] = 0xFF;
flash_update4k(base, sec4k); /* old header of this slot away */
flash_update4k(base + 0x1000u, &g_ee[0][0]);
uint32_t s = sum_pages(&g_ee[0][0]);
uint32_t v[4] = { EE_MAGIC, seq, g_have, s };
for (int k = 0; k < 4; k++) for (int b = 0; b < 4; b++) sec4k[k * 4 + b] = (uint8_t)(v[k] >> (8 * b));
flash_update4k(base, sec4k);
g_slot = slot; g_seq = seq; g_dirty = 0;
}
+99
View File
@@ -0,0 +1,99 @@
/* generated by gen/font.py: custom 5x7 font */
static const unsigned char g_font[96][7]={
{0x00,0x00,0x00,0x00,0x00,0x00,0x00},
{0x04,0x04,0x04,0x04,0x04,0x00,0x04},
{0x00,0x00,0x00,0x00,0x00,0x00,0x00},
{0x00,0x00,0x00,0x00,0x00,0x00,0x00},
{0x00,0x00,0x00,0x00,0x00,0x00,0x00},
{0x19,0x19,0x02,0x04,0x08,0x13,0x13},
{0x0c,0x12,0x14,0x08,0x15,0x12,0x0d},
{0x04,0x04,0x08,0x00,0x00,0x00,0x00},
{0x02,0x04,0x08,0x08,0x08,0x04,0x02},
{0x08,0x04,0x02,0x02,0x02,0x04,0x08},
{0x00,0x00,0x00,0x00,0x00,0x00,0x00},
{0x00,0x04,0x04,0x1f,0x04,0x04,0x00},
{0x00,0x00,0x00,0x00,0x0c,0x04,0x08},
{0x00,0x00,0x00,0x1f,0x00,0x00,0x00},
{0x00,0x00,0x00,0x00,0x00,0x0c,0x0c},
{0x01,0x01,0x02,0x04,0x08,0x10,0x10},
{0x0e,0x11,0x13,0x15,0x19,0x11,0x0e},
{0x04,0x0c,0x04,0x04,0x04,0x04,0x0e},
{0x0e,0x11,0x01,0x02,0x04,0x08,0x1f},
{0x1e,0x01,0x01,0x0e,0x01,0x01,0x1e},
{0x02,0x06,0x0a,0x12,0x1f,0x02,0x02},
{0x1f,0x10,0x1e,0x01,0x01,0x11,0x0e},
{0x0e,0x10,0x10,0x1e,0x11,0x11,0x0e},
{0x1f,0x01,0x02,0x04,0x08,0x08,0x08},
{0x0e,0x11,0x11,0x0e,0x11,0x11,0x0e},
{0x0e,0x11,0x11,0x0f,0x01,0x01,0x0e},
{0x00,0x04,0x04,0x00,0x04,0x04,0x00},
{0x00,0x00,0x00,0x00,0x00,0x00,0x00},
{0x02,0x04,0x08,0x10,0x08,0x04,0x02},
{0x00,0x00,0x1f,0x00,0x1f,0x00,0x00},
{0x08,0x04,0x02,0x01,0x02,0x04,0x08},
{0x0e,0x11,0x01,0x02,0x04,0x00,0x04},
{0x00,0x00,0x00,0x00,0x00,0x00,0x00},
{0x0e,0x11,0x11,0x1f,0x11,0x11,0x11},
{0x1e,0x11,0x11,0x1e,0x11,0x11,0x1e},
{0x0e,0x11,0x10,0x10,0x10,0x11,0x0e},
{0x1e,0x11,0x11,0x11,0x11,0x11,0x1e},
{0x1f,0x10,0x10,0x1e,0x10,0x10,0x1f},
{0x1f,0x10,0x10,0x1e,0x10,0x10,0x10},
{0x0e,0x11,0x10,0x17,0x11,0x11,0x0f},
{0x11,0x11,0x11,0x1f,0x11,0x11,0x11},
{0x0e,0x04,0x04,0x04,0x04,0x04,0x0e},
{0x07,0x02,0x02,0x02,0x02,0x12,0x0c},
{0x11,0x12,0x14,0x18,0x14,0x12,0x11},
{0x10,0x10,0x10,0x10,0x10,0x10,0x1f},
{0x11,0x1b,0x15,0x15,0x11,0x11,0x11},
{0x11,0x19,0x15,0x13,0x11,0x11,0x11},
{0x0e,0x11,0x11,0x11,0x11,0x11,0x0e},
{0x1e,0x11,0x11,0x1e,0x10,0x10,0x10},
{0x0e,0x11,0x11,0x11,0x15,0x12,0x0d},
{0x1e,0x11,0x11,0x1e,0x14,0x12,0x11},
{0x0f,0x10,0x10,0x0e,0x01,0x01,0x1e},
{0x1f,0x04,0x04,0x04,0x04,0x04,0x04},
{0x11,0x11,0x11,0x11,0x11,0x11,0x0e},
{0x11,0x11,0x11,0x11,0x11,0x0a,0x04},
{0x11,0x11,0x11,0x15,0x15,0x15,0x0a},
{0x11,0x11,0x0a,0x04,0x0a,0x11,0x11},
{0x11,0x11,0x0a,0x04,0x04,0x04,0x04},
{0x1f,0x01,0x02,0x04,0x08,0x10,0x1f},
{0x00,0x00,0x00,0x00,0x00,0x00,0x00},
{0x00,0x00,0x00,0x00,0x00,0x00,0x00},
{0x00,0x00,0x00,0x00,0x00,0x00,0x00},
{0x00,0x00,0x00,0x00,0x00,0x00,0x00},
{0x00,0x00,0x00,0x00,0x00,0x00,0x00},
{0x00,0x00,0x00,0x00,0x00,0x00,0x00},
{0x00,0x00,0x00,0x00,0x00,0x00,0x00},
{0x00,0x00,0x00,0x00,0x00,0x00,0x00},
{0x00,0x00,0x00,0x00,0x00,0x00,0x00},
{0x00,0x00,0x00,0x00,0x00,0x00,0x00},
{0x00,0x00,0x00,0x00,0x00,0x00,0x00},
{0x00,0x00,0x00,0x00,0x00,0x00,0x00},
{0x00,0x00,0x00,0x00,0x00,0x00,0x00},
{0x00,0x00,0x00,0x00,0x00,0x00,0x00},
{0x00,0x00,0x00,0x00,0x00,0x00,0x00},
{0x00,0x00,0x00,0x00,0x00,0x00,0x00},
{0x00,0x00,0x00,0x00,0x00,0x00,0x00},
{0x00,0x00,0x00,0x00,0x00,0x00,0x00},
{0x00,0x00,0x00,0x00,0x00,0x00,0x00},
{0x00,0x00,0x00,0x00,0x00,0x00,0x00},
{0x00,0x00,0x00,0x00,0x00,0x00,0x00},
{0x00,0x00,0x00,0x00,0x00,0x00,0x00},
{0x00,0x00,0x00,0x00,0x00,0x00,0x00},
{0x00,0x00,0x00,0x00,0x00,0x00,0x00},
{0x00,0x00,0x00,0x00,0x00,0x00,0x00},
{0x00,0x00,0x00,0x00,0x00,0x00,0x00},
{0x00,0x00,0x00,0x00,0x00,0x00,0x00},
{0x00,0x00,0x00,0x00,0x00,0x00,0x00},
{0x00,0x00,0x00,0x00,0x00,0x00,0x00},
{0x00,0x00,0x11,0x0a,0x04,0x0a,0x11},
{0x00,0x00,0x00,0x00,0x00,0x00,0x00},
{0x00,0x00,0x00,0x00,0x00,0x00,0x00},
{0x00,0x00,0x00,0x00,0x00,0x00,0x00},
{0x00,0x00,0x00,0x00,0x00,0x00,0x00},
{0x11,0x0e,0x11,0x1f,0x11,0x11,0x11},
{0x11,0x0e,0x11,0x11,0x11,0x11,0x0e},
{0x11,0x00,0x11,0x11,0x11,0x11,0x0e},
};
+13
View File
@@ -0,0 +1,13 @@
/* 20x20 icons (bit 0x80000 = left), drawn by mameise for the ESP32 version */
static const unsigned int g_icons[10][20]={
{0x00000000,0x00000000,0x00000000,0x00003FC0,0x0000C030,0x00010008,0x00022044,0x00021084,0x00048012,0x00045022,0x00041002,0x0005080A,0x00048812,0x00020604,0x00020904,0x00011088,0x00009090,0x00009F90,0x000070E0,0x00000000},
{0x00000000,0x00000000,0x00000000,0x000036C0,0x00004920,0x00004020,0x00003020,0x000010C0,0x00001080,0x00001F80,0x00002040,0x00004920,0x00008910,0x00008910,0x00008010,0x00009090,0x00004F20,0x00002040,0x00001F80,0x00000000},
{0x00000000,0x00000000,0x00000000,0x00000070,0x000000C8,0x00000088,0x00000188,0x00000118,0x00007F10,0x0000C090,0x00019C60,0x00012420,0x0001C860,0x000150A0,0x00013F20,0x00008040,0x00004080,0x00008040,0x0001FFE0,0x00000000},
{0x00000000,0x00000000,0x00000000,0x00001F80,0x000030C0,0x00006060,0x00004F20,0x000059A0,0x000050A0,0x000050A0,0x0000F0A0,0x0000F0A0,0x0000F0A0,0x000050A0,0x000050A0,0x000050A0,0x00004F20,0x00004020,0x00003FC0,0x00000000},
{0x00000000,0x00000000,0x00000000,0x000118C0,0x0000BDE0,0x00023FE0,0x00014010,0x00004010,0x00034010,0x00004010,0x00002020,0x00001040,0x00001020,0x00002010,0x00002230,0x00004420,0x00004420,0x0000FFF0,0x0000FFF0,0x00000000},
{0x00000000,0x00000000,0x00000078,0x00000186,0x00000102,0x00000102,0x00000106,0x000000B8,0x000000C0,0x00003E00,0x00004100,0x00008080,0x00011440,0x00011440,0x00010040,0x00012240,0x00009C80,0x00004100,0x00003E00,0x00000000},
{0x00000000,0x00000000,0x00000000,0x00000F00,0x00001080,0x00002040,0x00002040,0x00007FE0,0x00008010,0x00010608,0x00010608,0x00010608,0x00013FC8,0x00013FC8,0x00010608,0x00010608,0x00010608,0x00010008,0x0000FFF0,0x00000000},
{0x00000000,0x00000000,0x00000008,0x00000004,0x00000012,0x00000009,0x00000024,0x00000010,0x000030C0,0x000079E0,0x0000FFF0,0x0000FFF0,0x0000FFF0,0x0000FFF0,0x00007FE0,0x00003FC0,0x00001F80,0x00000F00,0x00000600,0x00000000},
{0x00000000,0x00000000,0x00000000,0x0001C038,0x000230C4,0x00020904,0x00020604,0x0002C034,0x000230C4,0x00020004,0x0002C034,0x00023044,0x00020004,0x0002C034,0x000200C4,0x00020004,0x0002E074,0x00011988,0x00000600,0x00000000},
{0x00000000,0x00000000,0x00000000,0x00000000,0x00003800,0x0000C600,0x00008200,0x00012900,0x00010100,0x00014570,0x0001388C,0x00008004,0x0000C482,0x00003AFA,0x00000252,0x00000104,0x0000018C,0x00000070,0x00000000,0x00000000},
};
+13
View File
@@ -0,0 +1,13 @@
/* 20x20 icons of the Tamagotchi Friends (bit 0x80000 = left), from the pictures of mameise: 0..4 top, 5..9 bottom */
static const unsigned int g_icons_fr[10][20]={
{0x00000000,0x00000000,0x00000000,0x00000000,0x00001F80,0x0000E070,0x00010008,0x00014928,0x00012048,0x00010008,0x00010608,0x00008F10,0x00009F90,0x00007FE0,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000},
{0x00000000,0x00015070,0x0002A888,0x0002A904,0x0002A904,0x00020904,0x00020904,0x00011088,0x0000A050,0x0000A050,0x00011088,0x00011088,0x00011088,0x00011088,0x00011088,0x00011088,0x00011088,0x0000E070,0x00000000,0x00000000},
{0x00000000,0x00000000,0x00000000,0x00000070,0x000000C8,0x00000088,0x00000188,0x00000118,0x00007F10,0x0000C090,0x00019C60,0x00012420,0x0001C860,0x000150A0,0x00013F20,0x00008040,0x00004080,0x00008040,0x0001FFE0,0x00000000},
{0x00000000,0x00000000,0x0000FFE0,0x0000E020,0x00009020,0x00008820,0x00008420,0x00008220,0x00008220,0x00008220,0x00008A20,0x00008E20,0x00008A20,0x00008220,0x000043E0,0x00002200,0x00001200,0x00000A00,0x00000600,0x00000000},
{0x00000008,0x00000004,0x00000012,0x00000009,0x00000024,0x00000010,0x0000E0E0,0x000191F0,0x00037BF8,0x0002FFF8,0x0003FFF8,0x0003FFF8,0x0001FFF0,0x0000FFE0,0x00007FC0,0x00003F80,0x00001F00,0x00000E00,0x00000400,0x00000000},
{0x00000000,0x00000000,0x00000000,0x00000000,0x0001FFF8,0x0003000C,0x00028014,0x00024924,0x00021F84,0x00021F84,0x00021F84,0x00024F24,0x00028614,0x0003000C,0x0001FFF8,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000},
{0x00000000,0x00000000,0x00010000,0x00038000,0x00013FF0,0x00004428,0x00008848,0x00008858,0x0000FFE8,0x00008848,0x00008848,0x00008848,0x00008850,0x00008860,0x0000FFC0,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000},
{0x00000000,0x00000000,0x00000000,0x0001C038,0x000230C4,0x00020904,0x00020604,0x0002C034,0x000230C4,0x00020004,0x0002C034,0x00023044,0x00020004,0x0002C034,0x000200C4,0x00020004,0x0002E074,0x00011988,0x00000600,0x00000000},
{0x00000000,0x00000000,0x00000000,0x00000F00,0x00001080,0x00002040,0x00002040,0x00007FE0,0x00008010,0x00010608,0x00010608,0x00010608,0x00013FC8,0x00013FC8,0x00010608,0x00010608,0x00010608,0x00010008,0x0000FFF0,0x00000000},
{0x00000000,0x00000000,0x00000000,0x00000000,0x00003800,0x0000C600,0x00008200,0x00012900,0x00010100,0x00014570,0x0001388C,0x00008004,0x0000C482,0x00003AFA,0x00000252,0x00000104,0x0000018C,0x00000070,0x00000000,0x00000000},
};
+24
View File
@@ -0,0 +1,24 @@
/* 64-bit division for the sound timers (no compiler runtime in this build).
* AEABI: quotient in r0:r1, remainder in r2:r3. */
typedef unsigned long long u64; typedef long long s64;
__attribute__((used)) u64 t7_udiv64(u64 n, u64 d, u64 *rem)
{
if (!d) { *rem = 0; return ~0ull; }
u64 q = 0, r = 0;
for (int i = 63; i >= 0; i--) { r = (r << 1) | ((n >> i) & 1u); if (r >= d) { r -= d; q |= 1ull << i; } }
*rem = r; return q;
}
__attribute__((used)) s64 t7_sdiv64(s64 n, s64 d, s64 *rem)
{
int neg = (n < 0) ^ (d < 0), nn = n < 0; u64 r;
u64 q = t7_udiv64(n < 0 ? (u64)-n : (u64)n, d < 0 ? (u64)-d : (u64)d, &r);
*rem = nn ? -(s64)r : (s64)r; return neg ? -(s64)q : (s64)q;
}
__attribute__((naked)) void __aeabi_uldivmod(void)
{
__asm__ volatile("push {r4, lr}\n sub sp, #16\n add r4, sp, #8\n str r4, [sp]\n bl t7_udiv64\n ldrd r2, r3, [sp, #8]\n add sp, #16\n pop {r4, pc}\n");
}
__attribute__((naked)) void __aeabi_ldivmod(void)
{
__asm__ volatile("push {r4, lr}\n sub sp, #16\n add r4, sp, #8\n str r4, [sp]\n bl t7_sdiv64\n ldrd r2, r3, [sp, #8]\n add sp, #16\n pop {r4, pc}\n");
}
+29
View File
@@ -0,0 +1,29 @@
ENTRY(Reset_Handler)
MEMORY {
PRAM (rwx) : ORIGIN = 0x00000000, LENGTH = 0x10000
SRAM (rw) : ORIGIN = 0x18000000, LENGTH = 0x1F000
XL (r) : ORIGIN = 0x00010000, LENGTH = 0x8000 /* 1.6.12 (T7_JIT): load place of the second part (t7x.bin) */
}
SECTIONS {
.text : {
KEEP(*(.vectors))
KEEP(*(.pmxcfg))
*(EXCLUDE_FILE(*t7_jit.o) .text*)
*(EXCLUDE_FILE(*t7_jit.o) .rodata*)
. = ALIGN(4);
__pdata_start = .;
} > PRAM
.bss (NOLOAD) : { __bss_start = .; *(.bss*) *(COMMON) . = ALIGN(4); __bss_end = .; } > SRAM
/* mutable data in SRAM (initial values in PRAM, copied at startup), as in TamaEmu */
.data : { __data_start = .; *(.data*) . = ALIGN(4); __data_end = .; } > SRAM AT > PRAM
__data_load = LOADADDR(.data);
.init : { . = ALIGN(4); KEEP(*(.initcode)) KEEP(*(.initdata*)) KEEP(*(.initcode_z)) . = ALIGN(4); __prog_end = .; } > PRAM
/* the second part: the translator (t7_jit.c), in the SRAM behind .bss; the program copies it from the flash
* (save area + 0x8000, written by the Studio) and runs without it when it is not there */
.xcode ALIGN(8) : { __x_start = .; *t7_jit.o(.text* .rodata*) *(.xcode_bat) . = ALIGN(8); __x_end = .; } > SRAM AT > XL
__x_load = LOADADDR(.xcode);
ASSERT(__prog_end <= 0x10000, "program too big for PRAM")
ASSERT(__x_end <= 0x1801F000, "RAM full")
ASSERT(__bss_end <= 0x1801F000, "RAM full")
/DISCARD/ : { *(.comment) *(.ARM.*) *(.note*) }
}
+846
View File
@@ -0,0 +1,846 @@
/* T7 (V7 6502 core, after asterick/tamago, BSD) on the Tamagotchi Paradise.
* Started like TamaEmu by the stub (A+C on the home screen, or autostart).
* Long press on the wheel: save and back to the Paradise. Short press: figure menu.
* Author: mameise */
#include "../../../emu/src/emu/hw.h"
#include "../../../emu/src/emu/exitkey.h"
#ifdef CLK_ECO
#include "../../../emu/src/emu/eco.h"
#endif
#include "../../../emu/src/emu/flash.h"
#include "../../../emu/src/emu/paraclock.h"
#ifdef PARA_BACK
#include "../../../emu/src/emu/paraback.h"
#endif
#include "../core/t7.h"
#include "../core/t7_sound.h"
#include "t7app.h"
#ifdef T7_JSR_HLE
extern uint8_t g_t7_dark;
#endif
#ifdef T7_LINK
#include "../../../emu/src/emu/plink.h"
#endif
void t7_eeprom_flush(void);
void eeprom_load(uint32_t at);
void eeprom_store(uint32_t at, uint8_t *sec4k);
int eeprom_dirty(void);
uint32_t eeprom_seq(void);
#ifdef T7_SESS_EESEQ
/* 1.6.9 test16: a session notes which EEPROM state was in the flash when it was written ("T7EQ" + sequence at the end of
* its sector). Battery out while playing: the automatic session can be up to 30 minutes old, its RAM (inventory,
* progress) won over the EEPROM the game had written since and the game wrote the old state back (items bought in a
* figure shop vanished, after an early session the whole game was new). Now a session whose EEPROM is no longer the
* one in the flash is not used: the game starts from its EEPROM, as the toy after a battery change. */
#define EQ_MAGIC 0x51453754u /* "T7EQ" */
static void sess_mark(uint8_t *sec) { uint32_t v[2] = { EQ_MAGIC, eeprom_seq() }; for (int k = 0; k < 2; k++) for (int b = 0; b < 4; b++) sec[0xFF8 + k * 4 + b] = (uint8_t)(v[k] >> (8 * b));
#ifdef ECO_RTC
{ extern volatile u32 g_eco_bad, g_eco_fix[2]; uint32_t w[2] = { g_eco_bad | g_eco_fix[0] << 8, g_eco_fix[1] }; /* test27: for a dump (tick checks) */
for (int k = 0; k < 2; k++) for (int b = 0; b < 4; b++) sec[0xFF0 + k * 4 + b] = (uint8_t)(w[k] >> (8 * b)); }
#endif
}
static int sess_eq_ok(const uint8_t *sec)
{
uint32_t m = sec[0xFF8] | sec[0xFF9] << 8 | sec[0xFFA] << 16 | (uint32_t)sec[0xFFB] << 24, q = sec[0xFFC] | sec[0xFFD] << 8 | sec[0xFFE] << 16 | (uint32_t)sec[0xFFF] << 24;
return m != EQ_MAGIC || q == eeprom_seq(); /* older sessions without the note: as before */
}
#endif
void app_wheel_short(void);
__attribute__((section(".pmxcfg"), used))
volatile const T7Cfg g_cfg = { T7_MAGIC, 1, 0x940000u, 0xA0000u, 0xC0000u, 0, {{0, 0, {0}}}, 0, 0, 0, 0 };
/* Emulated clock: 200000 cycles per 66 ms like the T7Emu app (game and animation tempo there were
* set by ear against the original). The game clock is kept right by app_clock. */
#define T7_RATE 3030300u
const uint8_t *g_rom_xip;
uint32_t g_rom_size, g_rom_off;
static uint8_t g_sec[0x1000] __attribute__((aligned(4))); /* the flash DMA takes words */
__attribute__((used)) volatile uint32_t g_t7st[4];
#ifdef T7_COUNT
volatile uint32_t g_t7_ninstr;
#endif /* emulated ms, dropped ms (for measuring) */
#define SESSION (g_cfg.save_off)
#define EEPROM (g_cfg.save_off + 0x1000u)
#define SETTINGS (g_cfg.save_off + 0x5000u)
#ifdef SESS_FLAG
#define NOSESS ((g_cfg.flags & T7_F_NOSESS) != 0u) /* 1.7.3 test7: no session, the toy runs from its EEPROM */
#else
#define NOSESS 0
#endif
/* Settings and the clock note: own sector (stays when the session is dropped) */
int plat_store_load(uint8_t *b, uint32_t n)
{
const volatile uint8_t *p = XIP_PTR(SETTINGS);
for (u32 i = 0; i < n; i++) b[i] = p[i];
return b[0] == 'T' && b[1] == '7';
}
void plat_store_write(const uint8_t *b, uint32_t n)
{
const volatile uint8_t *p = XIP_PTR(SETTINGS);
u32 same = 1; for (u32 i = 0; i < n; i++) if (p[i] != b[i]) { same = 0; break; }
if (same) return;
static uint8_t sec[0x1000] __attribute__((aligned(4)));
for (u32 i = 0; i < 0x1000u; i++) sec[i] = i < n ? b[i] : 0xFF;
hw_tone(0);
flash_update4k(SETTINGS, sec);
}
/* ---- time: SysTick 1 ms ---- */
static volatile uint32_t g_ms;
#ifdef T7_WHEEL_RAW
/* 1.6.12 test4: ms of the tick only, never set ahead. The wheel's long press is timed with it: g_ms is moved on after
* deep sleep and by the clock check (eco_rtc), up to a second at once; a short press right after waking counted as
* long and left the program */
static volatile uint32_t g_ms_raw;
#define WHEEL_NOW() g_ms_raw
#else
#define WHEEL_NOW() now
#endif
#define SYST_CSR REG(0xE000E010u)
#define SYST_RVR REG(0xE000E014u)
#define SYST_CVR REG(0xE000E018u)
#define CORE_HZ 96000000u
#define XIP_BASE_REG REG(0x4002F004u)
#define XIP_CTRL_REG REG(0x4002F000u)
#ifdef T7_TONE_Q
/* 1.6.9 test15: the tone on the real clock, as T18Emu (T18_TONE_Q). The emulation runs in steps of 2 ms, but after
* drawing or a flash write it catches up several steps at once: the notes of a melody (about 26 ms each) came within
* a millisecond and were swallowed or cut. Tone changes are queued with the game time and played TQ_LAT ms after the
* first of a sequence; late by more than 200 ms the timing starts anew. */
#define TQ_N 32u
#define TQ_LAT 80u
static uint32_t tq_t[TQ_N]; static uint16_t tq_hz[TQ_N]; static uint32_t tq_h, tq_w, tq_g0, tq_r0, tq_on, tq_cur, tq_quiet;
static void tq_put(uint32_t hz, uint32_t gms) {
#ifdef T7_TONE_ISR
__asm__ volatile("cpsid i" ::: "memory");
#endif
if (tq_w - tq_h >= TQ_N) tq_h++; tq_t[tq_w % TQ_N] = gms; tq_hz[tq_w % TQ_N] = (uint16_t)(hz > 0xFFFFu ? 0xFFFFu : hz); tq_w++;
#ifdef T7_TONE_ISR
__asm__ volatile("cpsie i" ::: "memory");
#endif
}
static int tq_busy(void) { return tq_h != tq_w || tq_cur; }
__attribute__((noinline, used)) static void tq_pump(void)
{
uint32_t now = g_ms;
if (tq_h == tq_w) { if (tq_on && !tq_cur && now - tq_quiet > 1000u) tq_on = 0; return; }
if (!tq_on) { tq_on = 1; tq_g0 = tq_t[tq_h % TQ_N]; tq_r0 = now + TQ_LAT; }
while (tq_h != tq_w) {
uint32_t i = tq_h % TQ_N, due = tq_r0 + (tq_t[i] - tq_g0);
int32_t late = (int32_t)(now - due);
if (late < 0) break;
if (late > 200) { tq_g0 = tq_t[i]; tq_r0 = now; }
tq_cur = tq_hz[i]; hw_tone(tq_cur); if (!tq_cur) tq_quiet = now; tq_h++;
}
}
#ifdef T7_TONE_ISR
/* 1.6.12 test4: the queue is played from the 1 ms tick. From the main loop a note change waited for drawing and the
* emulation (up to some 10 ms), the notes of a melody (about 26 ms) came unevenly */
static volatile uint8_t tq_isr_on = 1;
#define TQ_TICK() do { if (tq_isr_on) tq_pump(); } while (0)
#define TQ_MAIN() do { } while (0)
#else
#define TQ_TICK() do { } while (0)
#define TQ_MAIN() tq_pump()
#endif
#else
#define TQ_TICK() do { } while (0)
#endif
#ifdef T7_KEYQ
/* 1.6.9 test13: quick presses were lost (the loop reads the keys once per pass, a pass with drawing and catching up
* takes longer than a quick tap). The 1 ms tick counts each press (A P0.9, B P0.11, C P0.10, pressed = 0); the
* emulation gets every counted press for at least KQ_HOLD ms of its time, then KQ_GAP ms released (test14: the
* firmware needs about 120 and 80 ms, on the PC shorter taps were lost also without STOP). */
#define KQ_HOLD 120u
#define KQ_GAP 100u
#define KQ_DEB 30u /* test15: a press counts only after the key was up this long (contacts bounce: 1 press gave 2) */
static volatile uint8_t g_kin[3]; static uint8_t g_kout[3], g_kprev; static uint32_t g_kup[3];
__attribute__((used)) void systick_c(void) {
g_ms++;
#ifdef T7_WHEEL_RAW
g_ms_raw++;
#endif
TQ_TICK();
uint32_t d = REG(0x40018000u);
uint8_t k = (uint8_t)((d & (1u << 9) ? 0 : 1) | (d & (1u << 11) ? 0 : 2) | (d & (1u << 10) ? 0 : 4)), e = (uint8_t)(k & ~g_kprev), r = (uint8_t)(~k & g_kprev);
g_kprev = k;
for (int i = 0; i < 3; i++) {
if (r & (1u << i)) g_kup[i] = g_ms; /* went up */
if ((e & (1u << i)) && g_ms - g_kup[i] >= KQ_DEB) g_kin[i]++; /* down after a real release */
}
}
static void kq_clear(void) { for (int i = 0; i < 3; i++) g_kout[i] = g_kin[i]; }
/* one 2 ms step of emulated time: the keys the game sees (phys: held now) */
static uint8_t kq_step(uint8_t phys)
{
static uint8_t ph[3], tm[3];
uint8_t out = 0;
for (int i = 0; i < 3; i++) {
uint8_t bit = (uint8_t)(1u << i);
#ifdef T7_KQ_CAP
/* test22: at most one press waits: fast taps (a shooting game) queued up, the game took them one by one at its own
* pace and went on firing after the taps had stopped */
if ((uint8_t)(g_kin[i] - g_kout[i]) > 1u) g_kout[i] = (uint8_t)(g_kin[i] - 1u);
#endif
if (ph[i] == 0 && g_kin[i] != g_kout[i]) { g_kout[i]++; ph[i] = 1; tm[i] = 0; }
if (ph[i] == 1) { out |= bit; if (++tm[i] >= KQ_HOLD / 2u && !(phys & bit)) { ph[i] = 2; tm[i] = 0; } }
else if (ph[i] == 2) { if (++tm[i] >= KQ_GAP / 2u) ph[i] = 0; }
}
return out;
}
#else
__attribute__((used)) void systick_c(void) { g_ms++;
#ifdef T7_WHEEL_RAW
g_ms_raw++;
#endif
TQ_TICK(); }
#endif
__attribute__((naked)) void SysTick_Handler(void) { __asm__ volatile("b systick_c\n"); }
uint32_t plat_rtc(void) { return REG(0x45000304u); }
#ifdef BAT_SHOW
#if defined(BAT_PIC) && defined(T7_JIT)
#define BAT_PIC_ATTR __attribute__((section(".xcode_bat"), noinline, minsize)) /* test23: with the second part (PRAM is full) */
#endif
#include "../../../emu/src/emu/batt.h"
void plat_bat(char *s) { bat_text(s); }
#ifdef T7_VOL
void plat_vol(int v) { g_hw_vol5 = (u32)v; }
#endif
#endif
const uint8_t *plat_fig_ptr(int i) { return (const uint8_t *)(0x60000000u + g_cfg.fig[i].off); }
#ifdef FAST_LCD
void plat_rect(int x0, int y0, int x1, int y1) { hw_px_begin((u32)x0, (u32)y0, (u32)x1, (u32)y1); }
void plat_row(const uint16_t *px, int n) { hw_px_row(px, (u32)n); }
void plat_rect_end(void) { hw_px_end(); }
#else
static int r_x0, r_x1, r_y;
void plat_rect(int x0, int y0, int x1, int y1) { r_x0 = x0; r_x1 = x1; r_y = y0; (void)y1; }
void plat_row(const uint16_t *px, int n) { (void)n; hw_push(px - r_x0, 0, (u32)r_x0, (u32)r_y, (u32)r_x1, (u32)r_y + 1u); r_y++; }
void plat_rect_end(void) {}
#endif
#ifdef T7_PW
/* ---- 1.6.12 test1: power saving while the screen is off (setting "Power save", app_pw()) ----
* The chip (SNC7330 datasheet): 96 MHz from the PLL about 12 mA, 48 MHz 9 mA (the PLL runs on when the AHB divider
* slows the core), 12 MHz from the internal RC with the PLL off 1.6 mA, deep sleep 0.4 mA (all clocks off but the RTC,
* the RAM stays). 1 strong: screen off, no tone, no link: the system clock from the IHRC (12 MHz), PLL and crystal off.
* 2 maximal: in addition deep sleep whenever the emulation has caught up; the RTC (1 s, set by the Paradise) or a key
* (GPIO0 P0.8..11, both edges) wakes it; the seconds the RTC counted are added to the ms tick. With the screen on
* everything is as before (PLL, 96 MHz). Key held while asleep: seen at the next RTC second at the latest. */
#define OSC_CTRL REG(0x45000000u)
#define OSC_STAT REG(0x45000008u)
#define SYS_CLKCFG REG(0x4500000Cu)
#define SYS_AHBCP REG(0x45000010u)
#define ISO_CTRL REG(0x45000200u)
#define PMU_CTRL REG(0x45000300u)
#define RTC_C REG(0x45000304u)
#define GP0(o) REG(0x40018000u + (o))
#define NVIC_ISER0 REG(0xE000E100u)
#define NVIC_ICER0 REG(0xE000E180u)
#define NVIC_ICPR0 REG(0xE000E280u)
#define PW_KEYS 0xF00u /* P0.8 wheel, P0.9 A, P0.10 C, P0.11 B */
#define PW_IRQS ((1u << 2) | (1u << 26)) /* RTC, GPIO0 */
static int g_pw_low; /* running from the IHRC */
static uint32_t g_pw_t0, g_pw_slept, g_pw_lowms, g_pw_lowat, g_pw_rtc, g_pw_rtcms; /* statistics: start, seconds asleep, ms at 12 MHz */
#ifdef T7_PW_RTCWAIT
static volatile uint8_t g_pw_rtcw; /* the RTC woke the chip (its interrupt ran) */
static uint8_t g_pw_kw; /* woken by a key: the part of a second slept is not counted yet */
#define PW_RTCW_SET g_pw_rtcw = 1;
#else
#define PW_RTCW_SET
#endif
__attribute__((used)) void pw_rtc_irq(void) { PMU_CTRL = (PMU_CTRL & ~0x47u) | 0x10u; PW_RTCW_SET } /* RTC_FLAG: write 1 */
__attribute__((used)) void pw_gpio_irq(void) { GP0(0x20) = PW_KEYS; }
static void pw_full(void)
{
if (!g_pw_low) return;
OSC_CTRL |= 1u << 4; /* crystal on (the PLL's source, as hw_init sets it) */
for (u32 t = 0; !(OSC_STAT & (1u << 4)) && t < 2000000u; t++) {}
OSC_CTRL |= 1u << 15; /* PLL on */
for (u32 t = 0; !(OSC_STAT & (1u << 6)) && t < 2000000u; t++) {}
SYS_CLKCFG = 4u; /* system clock from the PLL */
for (u32 t = 0; ((SYS_CLKCFG >> 4) & 7u) != 4u && t < 2000000u; t++) {}
SYST_RVR = CORE_HZ / 1000u - 1u; SYST_CVR = 0;
g_pw_low = 0; g_pw_lowms += g_ms - g_pw_lowat;
}
static void pw_low(void)
{
if (g_pw_low) return;
#ifdef CLK_ECO
hw_clk_shift(0, CORE_HZ);
#endif
SYS_AHBCP = 0;
SYS_CLKCFG = 0; /* system clock from the IHRC (12 MHz) */
for (u32 t = 0; ((SYS_CLKCFG >> 4) & 7u) != 0u && t < 2000000u; t++) {}
if (((SYS_CLKCFG >> 4) & 7u) != 0u) { SYS_CLKCFG = 4u; return; } /* did not switch: stay as it was */
OSC_CTRL &= ~((1u << 15) | (1u << 4)); /* PLL and crystal off */
SYST_RVR = 12000000u / 1000u - 1u; SYST_CVR = 0;
g_pw_low = 1; g_pw_lowat = g_ms;
}
/* deep sleep until the next RTC second or a key; returns the seconds that passed */
static uint32_t pw_sleep(void)
{
uint32_t iso = ISO_CTRL;
if (!(iso & 0x80u) || (iso & 7u) != 0u) { __asm__ volatile("wfi"); return 0; } /* the RTC is not on 1 s: no deep sleep */
ISO_CTRL = iso & ~8u; /* RTC_WKP 0: the RTC interrupt wakes */
GP0(0x0C) &= ~PW_KEYS; GP0(0x10) |= PW_KEYS; GP0(0x20) = PW_KEYS; GP0(0x18) |= PW_KEYS; /* edges, both */
NVIC_ICPR0 = PW_IRQS; NVIC_ISER0 = PW_IRQS;
uint32_t r0 = RTC_C, csr = SYST_CSR;
SYST_CSR = 0; /* the tick stops in deep sleep anyway */
#ifdef T7_PW_RTCWAIT
g_pw_rtcw = 0;
#endif
PMU_CTRL = (PMU_CTRL & ~0x47u) | 2u; /* DSLEEP_EN */
__asm__ volatile("dsb\n wfi\n isb" ::: "memory");
PMU_CTRL = PMU_CTRL & ~0x47u;
NVIC_ICER0 = PW_IRQS; GP0(0x18) &= ~PW_KEYS; GP0(0x20) = PW_KEYS;
ISO_CTRL = (ISO_CTRL & ~8u) | (iso & 8u);
SYST_CVR = 0; SYST_CSR = csr;
#ifdef T7_PW_RTCWAIT
/* woken by the RTC: wait until the counter (32 kHz domain) shows the new second; read right away it could still
* be the old one and the second slept was lost */
uint32_t r = RTC_C;
if (g_pw_rtcw) for (uint32_t t = 0; r == r0 && t < 200000u; t++) r = RTC_C;
uint32_t n = r - r0;
if (!n) g_pw_kw = 1;
#else
uint32_t n = RTC_C - r0;
#endif
if (n > 3600u) n = 0;
g_pw_slept += n;
return n;
}
int plat_pw_pct(void) /* asleep * 1000 + at 12 MHz (asleep included): two percentages since the start */
{
uint32_t ms = g_ms - g_pw_t0; if (!ms) return 0;
uint32_t lo = g_pw_lowms + (g_pw_low ? g_ms - g_pw_lowat : 0);
uint32_t a = (uint32_t)((uint64_t)g_pw_slept * 100000u / ms), b = (uint32_t)((uint64_t)lo * 100u / ms);
return (int)((a > 100u ? 100u : a) * 1000u + (b > 100u ? 100u : b));
}
#endif
static void leave(int save)
{
#ifdef T7_PW
pw_full();
#endif
#ifdef CLK_ECO
hw_clk_shift(0, CORE_HZ);
#endif
#ifdef T7_TONE_ISR
tq_isr_on = 0;
#endif
hw_tone(0);
REG(0x20000FF8u) = 0; /* start counter of the home hooks */
REG(0x20000FFCu) = 0x4C584D50u; /* "PMXL": back on purpose, the autostart stays off */
#ifdef T7_SESS_EESEQ
t7_eeprom_flush(); eeprom_store(EEPROM, g_sec); /* the pet's own save first, the session notes its state */
if (save && !NOSESS) { /* 1.7.3 test7 */
uint32_t n = app_save(g_sec, sizeof g_sec);
if (n && n <= 0xFF0u) { for (uint32_t i = n; i < 0x1000u; i++) g_sec[i] = 0xFF; sess_mark(g_sec); flash_update4k(SESSION, g_sec); }
}
#else
if (save && !NOSESS) {
uint32_t n = app_save(g_sec, sizeof g_sec);
if (n) { for (uint32_t i = n; i < 0x1000u; i++) g_sec[i] = 0xFF; flash_update4k(SESSION, g_sec); }
}
t7_eeprom_flush(); eeprom_store(EEPROM, g_sec); /* the pet's own save always */
#endif
app_store(); /* settings and the clock note (for the next time setting) */
#ifdef PARA_BACK
para_back_fix(g_sec); /* 1.6.8: the Paradise skips the time spent here */
#endif
hw_bl_pwm_off();
for (u32 t = 0; hw_buttons() && t < 20000000u; t++) if ((t & 0xFFFFu) == 0) hw_wdt_feed();
XIP_BASE_REG = 0x60011000u; XIP_CTRL_REG = 3u;
hw_back_to_paradise();
}
static void drop_session(void) { if (!flash_isff(SESSION, 0x1000u)) flash_erase4k(SESSION); }
#ifdef SESS_AUTO
#ifndef SESS_T1
#ifdef T7_DARK_PEEK
/* 1.7.3 test27: wk_on 1 waking (light at once, the panel shows the last peek; drawn again once the game has drawn anew),
* 2 a peek with the screen dark (the game draws once, the picture goes to the sleeping panel, without light) */
extern uint32_t g_t7_blits; extern uint8_t g_t7_hle;
static int wk_on; static uint32_t wk_t, wk_b, wk_bt, pk_t;
#define WK_START(t) do { hw_backlight(1); if (g_t7_hle & 2u) { wk_on = 1; wk_t = (t); wk_b = g_t7_blits; wk_bt = 0; } else app_render(1); } while (0)
#elif defined(T7_WAKE_FRESH)
extern uint32_t g_t7_blits; extern uint8_t g_t7_hle;
static int wk_on; static uint32_t wk_t, wk_b, wk_bt; /* waking: light once the game has drawn anew (only where its drawing was left out) */
#define WK_START(t) do { if (g_t7_hle & 2u) { wk_on = 1; wk_t = (t); wk_b = g_t7_blits; wk_bt = 0; } else { hw_backlight(1); app_render(1); } } while (0)
#endif
#define SESS_T1 600000u /* screen dark: 10 minutes after the last time at the earliest */
#define SESS_T2 1800000u /* otherwise every 30 minutes */
#endif
/* 1.6.8: the run state now and then, without leaving (battery empty or out while playing): when the screen goes
* dark (10 minutes after the last time at the earliest), otherwise every 30 minutes after 10 s without a key */
static uint32_t g_sess_ms;
static void sess_auto(uint32_t now)
{
hw_tone(0);
#ifdef T7_SESS_EESEQ
t7_eeprom_flush(); if (eeprom_dirty()) eeprom_store(EEPROM, g_sec);
uint32_t n = NOSESS ? 0u : app_save(g_sec, sizeof g_sec); /* 1.7.3 test7: NOSESS, only the EEPROM */
if (n && n <= 0xFF0u) { for (uint32_t i = n; i < 0x1000u; i++) g_sec[i] = 0xFF; sess_mark(g_sec); flash_update4k(SESSION, g_sec); }
#else
uint32_t n = NOSESS ? 0u : app_save(g_sec, sizeof g_sec);
if (n) { for (uint32_t i = n; i < 0x1000u; i++) g_sec[i] = 0xFF; flash_update4k(SESSION, g_sec); }
t7_eeprom_flush(); if (eeprom_dirty()) eeprom_store(EEPROM, g_sec);
#endif
g_sess_ms = now;
}
#endif
#ifdef T7_LINK
/* 1.6.9: visits between two Paradise (Tama-Go: CONNECTION, TAMA-GO, VISIT): each infrared packet the game sends goes
* as it is to the other one ('T' frames of 32 bytes, as the T7Emu's IR bridge), and comes in there through the
* bridge's receive hook. Only taken while the game is in its connection screen (else an old packet would wait). */
static uint32_t g_lk_act, g_lk_ms;
static void lk_got(u8 ty, const u8 *d, int n) { if (ty == 'T' && n == 32 && g_ms - g_lk_ms < 1500u) t7_ir_bridge_rx(d); }
static void lk_tick(uint32_t now)
{
uint32_t a = t7_ir_activity(); if (a != g_lk_act) { g_lk_act = a; g_lk_ms = now; }
uint8_t p[32]; if (t7_ir_tx_take(p)) plink_send('T', p, 32);
plink_poll(now, now - g_lk_ms < 1500u ? 1u : 0u, lk_got);
}
#endif
static void prog(int done, int total) { hw_wdt_feed(); app_text_screen(app_lang() ? "Catching up" : "Zeit holt auf", 0, done, total); }
extern u32 __bss_start, __bss_end;
#ifdef T7_JIT
#include "../core/t7_jit.h"
/* 1.6.12 test2: the translator (second part t7x.bin, in the flash at the save area + 0x8000) into the SRAM behind the
* data, the rest of the SRAM up to the stack for the translated code. Without a matching second part: no JIT. */
#define T7X_MAGIC 0x31583754u /* "T7X1" */
static int g_x_ok;
#ifdef T7_DIAG
/* test22 (diagnosis build): every 2 s the emulated ms in that time (percent of real time) and the largest lag; kept
* while the menu is open */
static uint16_t g_dg_pct, g_dg_lag, g_dg_lagm; static uint32_t g_dg_t, g_dg_e;
static void dg_tick(uint32_t now, uint32_t emu) {
if (app_menu_open()) { g_dg_t = now; g_dg_e = emu; g_dg_lagm = 0; return; } /* the menu shows the time before it */
uint32_t l = now - emu; if (l > g_dg_lagm && l < 60000u) g_dg_lagm = (uint16_t)l;
if (now - g_dg_t >= 2000u) { g_dg_pct = (uint16_t)((emu - g_dg_e) * 100u / (now - g_dg_t)); g_dg_lag = g_dg_lagm; g_dg_lagm = 0; g_dg_t = now; g_dg_e = emu; }
}
void plat_tempo(char *v) {
uint32_t a = g_dg_pct, b = g_dg_lag, n = 0; char t[6]; int k;
k = 0; do { t[k++] = (char)('0' + a % 10u); a /= 10u; } while (a); while (k) v[n++] = t[--k]; v[n++] = '%'; v[n++] = ' ';
k = 0; do { t[k++] = (char)('0' + b % 10u); b /= 10u; } while (b); while (k) v[n++] = t[--k]; v[n++] = 'm'; v[n++] = 's'; v[n] = 0;
}
#endif
int plat_jit(int on) { if (!g_x_ok) return -1; g_t7j_on = on ? 1u : 0u; return on; }
static void x_load(void)
{
extern u32 __x_start, __x_end;
const volatile u32 *h = (const volatile u32 *)XIP_PTR(g_cfg.save_off + 0x8000u);
u32 n = (u32)(&__x_end - &__x_start), sum = 0;
if (h[0] != T7X_MAGIC || h[1] != (u32)T7X_ID || h[2] != n * 4u) return;
for (u32 i = 0; i < n; i++) { u32 v = h[4 + i]; (&__x_start)[i] = v; sum += v; }
if (sum != h[3]) return;
__asm__ volatile("dsb\n isb" ::: "memory");
u8 *buf = (u8 *)(((u32)&__x_end + 7u) & ~7u);
t7_jit_init(buf, 0x1801F000u - (u32)buf);
g_x_ok = g_t7j_on != 0;
plat_jit(app_jit());
}
#endif
void Reset_Handler(void)
{
__asm__ volatile("cpsid i");
/* the Paradise's clock, before its SRAM is overwritten (the stack is in the top 4 KB) */
uint32_t cnt = REG(0x45000304u), para = para_clock(cnt, 0, 0x1F000u, 0, 0);
if (!para) para = para_mailbox(cnt); /* 1.6.8: started from the menu */
#if defined(PARA_FLASH) && !defined(PARA_FLASH_LATE)
if (!para) para = para_flash(cnt); /* 1.6.9 test37: the base in the Paradise's settings page */
#endif
#ifdef PARA_BACK
para_leave_mark(cnt, para); /* 1.6.8: the Paradise does not live meanwhile */
#endif
__asm__ volatile("" ::: "memory");
for (u32 *p = &__bss_start; p < &__bss_end; p++) *p = 0;
{ extern u32 __data_start, __data_end, __data_load;
const u32 *src = &__data_load; for (u32 *p = &__data_start; p < &__data_end; p++) *p = *src++; }
g_para_time = para; g_para_cnt = cnt;
hw_init();
#if defined(PARA_FLASH) && defined(PARA_FLASH_LATE)
/* test17: as V3Emu: neither SRAM nor mailbox: the base in the Paradise's settings page (readable after hw_init) */
if (!g_para_time) { u32 c2 = REG(0x45000304u), t2 = 0;
#ifdef PARA_CLEAN_CLK
t2 = para_cleanclk(c2); /* 1.7.2 test17: start device without the Paradise */
#endif
if (!t2) t2 = para_flash(c2); if (t2) { g_para_time = t2; g_para_cnt = c2; para_mailbox_put(t2, c2); } }
#endif
g_rom_off = g_cfg.rom_off; g_rom_size = g_cfg.rom_len;
XIP_BASE_REG = 0x60000000u | g_rom_off; /* ROM in the cached window from 0x10000000 */
XIP_CTRL_REG = 3u;
g_rom_xip = (const uint8_t *)0x10000000u;
app_init(&g_cfg);
app_render(1);
eeprom_load(EEPROM);
t7_init();
#ifdef T7_JIT
x_load();
#endif
t7_snd_config(T7_RATE, 16000);
t7_snd_capture(0);
#ifndef T7_NOSND
t7_snd_set_mode(1); /* original sound: timers on, tone read for the buzzer */
#ifdef T7_TONE_EV
t7_snd_tone_events(T7_RATE / 1000u);
#endif
#endif
#ifdef T7_LINK
plink_init();
#endif
SYST_RVR = CORE_HZ / 1000u - 1u; SYST_CVR = 0; SYST_CSR = 7;
__asm__ volatile("cpsie i");
uint32_t saved = 0, restored = 0;
{ const volatile uint8_t *s = XIP_PTR(SESSION);
for (u32 i = 0; i < 0x1000u; i++) g_sec[i] = s[i]; }
#ifdef T7_SESS_EESEQ
/* the EEPROM is newer; 1.7.3 test7: NOSESS drops an old session too, boot from the EEPROM */
if (NOSESS || !sess_eq_ok(g_sec)) { drop_session(); for (u32 i = 0; i < 4u; i++) g_sec[i] = 0xFF; }
#else
if (NOSESS) { drop_session(); for (u32 i = 0; i < 4u; i++) g_sec[i] = 0xFF; } /* 1.7.3 test7 */
#endif
if (app_load(g_sec, sizeof g_sec, &saved)) {
restored = 1;
#if defined(SESS_ONCE) && !defined(T7_SESS_KEEP)
/* 1.6.8: the session is used once. Power gone without leaving (battery out): the next start begins from the
* toy's own save (EEPROM, written every minute) instead of an old session that would win over it */
drop_session();
#endif
if (!app_clock_hard(plat_rtc())) app_catchup(plat_rtc(), prog);
}
#if defined(T7_SESS_KEEP) && defined(SESS_AUTO)
/* test21: the session is kept (T7_SESS_EESEQ still drops it once the game's EEPROM is newer): power gone again soon
* after a start (weak batteries, a second battery change) began from the EEPROM only, and the Tama-Go keeps its pet
* in RAM: it was gone. A new session is written 2 minutes after the start (10 s without a key). */
g_sess_ms = g_ms - SESS_T2 + 120000u;
#endif
app_render(1);
#ifdef T7_PW
g_pw_t0 = g_ms;
#endif
uint32_t emu_ms = g_ms, last_draw = g_ms, last_clock = g_ms, last_fill = g_ms, t_start = g_ms, wheel_ms = 0, last_in = g_ms, quiet_since = g_ms;
int bl = 1, lock = 1, dimmed = 0;
for (;;) {
hw_wdt_feed();
#ifdef T7_TONE_Q
TQ_MAIN();
#endif
uint32_t now = g_ms;
#if defined(BAT_GUARD) && defined(SESS_AUTO)
/* test21: battery empty: the pet's EEPROM and the run state saved, then off until new batteries */
{ static uint32_t bt; if (now - bt >= 1000u) { bt = now; if (bat_guard_tick()) {
#ifdef T7_PW
pw_full();
#endif
sess_auto(now);
#ifdef T7_JIT
if (g_x_ok) BAT_PIC_SHOW(); /* the picture code comes with the second part */
#endif
hw_backlight(0);
for (;;) { hw_wdt_feed(); __asm__ volatile("wfi"); } } } }
#endif
u32 b = hw_buttons();
if (lock) { if (b) b = 0; else lock = 0; } /* wait until A+C from the start are released */
#ifdef T7_PW
/* 1.6.12 test1: screen off, no menu, no tone, no link: the low power modes */
int pw_quiet = !bl && !b && !app_menu_open() && !g_hw_tone_hz
#ifdef T7_TONE_Q
&& !tq_busy()
#endif
#ifdef T7_LINK
&& !(g_pl.last_rx && now - g_pl.last_rx < 30000u)
#endif
;
if (app_pw() && pw_quiet) pw_low(); else pw_full();
{ uint32_t r = RTC_C; /* when the RTC last stepped */
if (r != g_pw_rtc) {
#ifdef T7_PW_RTCWAIT
if (g_pw_kw) { uint32_t e = g_pw_rtcms + (r - g_pw_rtc) * 1000u; /* after a wake by a key: the part of a second slept */
__asm__ volatile("cpsid i" ::: "memory"); if ((int32_t)(e - g_ms) > 0) g_ms = e; __asm__ volatile("cpsie i" ::: "memory");
now = g_ms; g_pw_kw = 0; }
#endif
g_pw_rtc = r; g_pw_rtcms = now; } }
#endif
#ifdef CLK_ECO
/* test22: screen off, no key, no tone, no link traffic for 30 s: a lower clock (eco.h) */
#ifdef ECO_RTC
{ u32 a = eco_rtc(now, CORE_HZ); if (a) { __asm__ volatile("cpsid i" ::: "memory"); g_ms += a; __asm__ volatile("cpsie i" ::: "memory"); now = g_ms; } } /* test27 */
#endif
#ifdef T7_PW
if (!g_pw_low)
#endif
eco_poll(now, !bl && !b && !g_hw_tone_hz && !app_menu_open()
#ifdef T7_LINK
&& !(g_pl.last_rx && now - g_pl.last_rx < 30000u)
#endif
, (int)(now - emu_ms), CORE_HZ);
#endif
/* wheel: within 3 s after resuming = drop the session; long = leave; short = menu */
if (b & BTN_WHEEL) {
if (restored && now - t_start < 3000u) {
/* 1.6.6: ask first (a press meant for the menu threw the session away) */
app_text_screen(app_lang() ? "Reset?" : "Zuruecksetzen?", app_lang() ? "A yes B no" : "A ja B nein", 0, 0);
while (hw_buttons()) hw_wdt_feed();
u32 k; do { hw_wdt_feed(); k = hw_buttons(); } while (!(k & (BTN_A | BTN_B | BTN_WHEEL)));
while (hw_buttons()) hw_wdt_feed();
if (k & BTN_A) { drop_session(); leave(0); }
restored = 0; wheel_ms = 0; last_in = g_ms; app_render(1); continue;
}
if (!wheel_ms) wheel_ms = WHEEL_NOW() ? WHEEL_NOW() : 1;
else if (EXIT_NOW(WHEEL_NOW() - wheel_ms, 1500u)) leave(1);
} else if (wheel_ms) { if (WHEEL_NOW() - wheel_ms < 1000u && bl) app_wheel_short(); wheel_ms = 0; }
if (b) { last_in = now;
if (!bl) {
#ifdef T7_PW
pw_full();
#endif
#if defined(T7_WAKE_FRESH) || defined(T7_DARK_PEEK)
bl = 1; WK_START(now); while (hw_buttons()) hw_wdt_feed();
#else
bl = 1; hw_backlight(1); app_render(1); while (hw_buttons()) hw_wdt_feed();
#endif
#ifdef WAKE_WHEEL
wheel_ms = 0; /* 1.7.2: the wheel only wakes, its release does not open the settings */
#endif
#ifdef T7_KEYQ
kq_clear();
#endif
continue; }
if (dimmed) { dimmed = 0;
app_dim(0);
while (hw_buttons()) hw_wdt_feed();
#ifdef WAKE_WHEEL
wheel_ms = 0; /* 1.7.2: the wheel only wakes, its release does not open the settings */
#endif
#ifdef T7_KEYQ
kq_clear();
#endif
continue; } /* the key only wakes */
}
#ifdef T7_BELL_WAKE
/* test9: the pet calls (bell icon comes on): screen on, as after a key */
{ static int bell0; int bell = app_bell();
if (bell && !bell0) { last_in = now;
if (!bl) { bl = 1;
#ifdef T7_PW
pw_full();
#endif
#ifdef CLK_ECO
hw_clk_shift(0, CORE_HZ); /* test22: full speed before the panel wakes */
#endif
#if defined(T7_WAKE_FRESH) || defined(T7_DARK_PEEK)
WK_START(now); }
#else
hw_backlight(1); app_render(1); }
#endif
if (dimmed) { dimmed = 0; app_dim(0); } }
bell0 = bell; }
#endif
#ifdef T7_KEYQ
int menu0 = app_menu_open();
uint8_t gk = (uint8_t)app_keys(b, now);
int kq = !lock && !menu0 && !app_menu_open() && bl && !dimmed; /* a key that closed the menu does not reach the game */
if (!kq) { kq_clear(); t7_set_buttons(gk); }
#else
t7_set_buttons((uint8_t)app_keys(b, now));
#endif
app_tick(now);
/* emulate the time that passed, in steps of 2 ms (keys and sound stay fine-grained) */
if ((int32_t)(now - emu_ms) > 3000) { g_t7st[1] += now - 3000u - emu_ms; emu_ms = now - 3000u; } /* far behind: the clock is set by app_clock */
uint32_t t0 = g_ms;
#ifdef T7_JSR_HLE
#ifdef T7_DARK_PEEK
if (bl) pk_t = now;
else if (!wk_on && (g_t7_hle & 2u) && now - pk_t >= 60000u && !app_menu_open()) { wk_on = 2; wk_t = now; wk_b = g_t7_blits; wk_bt = 0; }
g_t7_dark = (uint8_t)(!bl && !app_menu_open() && wk_on != 2); /* a peek: the game draws once */
#else
g_t7_dark = (uint8_t)(!bl && !app_menu_open()); /* 1.6.12 test1: screen off: the game's sprite drawing is left out */
#endif
#endif
#ifdef T7_CATCHUP_SMOOTH
/* 1.6.13 test4: screen on and behind after a slow moment: catch up at most a quarter faster than real time.
* Before it caught up as fast as it could, seconds and animations ran visibly too fast for a moment. */
uint32_t cu = now, cu_e0 = emu_ms;
static uint32_t cu_q; /* catch-up credit in quarter ms */
{ static uint32_t pn; uint32_t el = now - pn; pn = now;
if (bl && (int32_t)(now - emu_ms) > 8) {
cu_q += el * 5u; if (cu_q > 200u) cu_q = 200u;
uint32_t lim = emu_ms + (cu_q >> 2); if ((int32_t)(lim - now) < 0) cu = lim;
} else cu_q = 0; }
#else
#define cu now
#endif
while ((int32_t)(cu - emu_ms) >= 2 && g_ms - t0 < 30u) {
#ifdef T7_KEYQ
if (kq) t7_set_buttons(kq_step(g_kprev));
#endif
#ifdef T7_DARK_STEP
/* 1.6.12 test1: screen off: up to 50 ms at once (fewer passes of this loop; the same emulated time) */
uint32_t st = 2;
if (!bl && !kq) { st = (now - emu_ms) & ~1u; if (st > 50u) st = 50u; }
t7_step_cycles((T7_RATE / 500u) * (st / 2u));
emu_ms += st; g_t7st[0] += st;
#else
t7_step_cycles(T7_RATE / 500u);
emu_ms += 2; g_t7st[0] += 2;
#endif
#ifdef CLK_ECO
ECO_CHECK(g_ms, g_ms - emu_ms, CORE_HZ);
#endif
#ifdef T7_LINK
lk_tick(g_ms);
#endif
static uint32_t hz_now;
#ifdef T7_TONE_EV
/* 1.6.12 test4: the tone changes as the core sees them (every ms of game time, a new pitch only when it stays
* 4 ms, silent when the envelope has died away), with their time; before: a look every 2 ms, glitches between
* the notes and notes that rang on after their envelope */
{ uint64_t cn = t7_snd_cycles(), ec; uint32_t ehz;
while (t7_snd_tone_peek(&ec, &ehz)) {
t7_snd_tone_pop();
if (!g_set.sound) ehz = 0;
if (ehz == hz_now) continue;
uint32_t back = (uint32_t)((cn - ec) / (T7_RATE / 1000u));
#ifdef T7_PW
if (ehz) pw_full(); /* the buzzer's timer runs on the PLL clock */
#endif
hz_now = ehz; tq_put(ehz, emu_ms - (back > 1000u ? 1000u : back));
} }
TQ_MAIN();
#elif defined(T7_TONE_Q)
uint8_t lv; uint32_t hz = t7_snd_tone_hz(&lv);
if (!g_set.sound) hz = 0;
#ifdef T7_PW
if (hz && hz != hz_now) pw_full(); /* the buzzer's timer runs on the PLL clock */
#endif
if (hz != hz_now) { hz_now = hz; tq_put(hz, emu_ms); }
TQ_MAIN();
#else
uint8_t lv; uint32_t hz = t7_snd_tone_hz(&lv);
if (!g_set.sound) hz = 0;
if (hz != hz_now) { hz_now = hz; hw_tone(hz); }
#endif
}
#ifdef T7_CATCHUP_SMOOTH
{ uint32_t used = (emu_ms - cu_e0) * 4u; cu_q = cu_q > used ? cu_q - used : 0; }
#else
#undef cu
#endif
#ifdef T7_TONE_Q
TQ_MAIN();
#endif
#ifdef T7_DIAG
dg_tick(now, emu_ms);
#endif
#ifdef T7_DARK_PEEK
/* 1.7.3 test27 (Bernd: not a picture from long ago when the screen comes on, but quickly): with the screen off the
* game's drawing is left out. Once a minute it draws one picture, which goes to the sleeping panel without light.
* After a key the light comes at once with that picture; the game's own picture follows once it has drawn anew
* (its blits, then 20 ms without one, at the latest after 0.7 s; before: up to half a second empty). */
if (wk_on) { if (g_t7_blits != wk_b) { wk_b = g_t7_blits; wk_bt = now | 1u; }
if ((wk_bt && now - wk_bt >= 20u) || now - wk_t >= 700u || (wk_on == 2 && bl)) {
if (wk_on == 2 && bl) { wk_on = 1; wk_t = now; wk_bt = 0; }
else { wk_on = 0; pk_t = now; app_render(1); last_draw = now; } } }
else
#elif defined(T7_WAKE_FRESH)
/* 1.7.3 test26: with the screen off the game's drawing is left out, its picture was empty or old. After a wake the
* light comes once the game has drawn anew (its blits, then 20 ms without one), at the latest after 0.7 s. Before the
* light came at once: up to half a second without the Tama on the screen. */
if (wk_on) { if (g_t7_blits != wk_b) { wk_b = g_t7_blits; wk_bt = now | 1u; }
if ((wk_bt && now - wk_bt >= 20u) || now - wk_t >= 700u || !bl) { wk_on = 0; if (bl) { app_render(1); hw_backlight(1); last_draw = now; } } }
else
#endif
if (now - last_draw >= 33u) { last_draw = now; if (bl) app_render(0); }
if (now - last_fill >= 500u) { last_fill = now; app_setup_fill(plat_rtc()); }
#ifdef T7_CLK_COLD
/* test17: started without a session (the toy's own save from the EEPROM): the Paradise's time is set as well,
* once the game runs with a valid hour (before only a resumed session got it, the toy kept its old time) */
{ static int cold_done; if (!cold_done && !restored && now - t_start >= 3000u && now - last_fill == 0u) {
if (app_clock_hard(plat_rtc()) || now - t_start > 90000u) cold_done = 1; } }
#endif
if (now - last_clock >= 2000u) { last_clock = now; app_clock(plat_rtc(), !restored && now - t_start < 90000u); }
/* 1.6.6: dimmed after the dim time, dark after the off time (both from the menu, without a key; the game runs on) */
if (bl && !app_menu_open()) {
uint32_t idle = now - last_in;
if (app_off_ms() && idle > app_off_ms()) { bl = 0; if (dimmed) app_dim(0); dimmed = 0; hw_backlight(0);
#ifdef SESS_AUTO
if (now - g_sess_ms > SESS_T1) sess_auto(now);
#endif
}
else if (!dimmed && app_dim_ms() && idle > app_dim_ms()) { dimmed = 1;
app_dim(app_dim_pct()); } /* darker colours: the backlight PWM had no effect */
}
#ifdef SESS_AUTO
if (now - g_sess_ms > SESS_T2 && now - last_in > 10000u && !app_menu_open()) sess_auto(now);
#endif
/* the pet's save: write it once things are quiet (1 minute after the last key) */
if (b) quiet_since = now;
if (now - quiet_since > 60000u) { t7_eeprom_flush(); if (eeprom_dirty()) { hw_tone(0);
#if defined(T7_SESS_KEEP) && defined(SESS_AUTO)
sess_auto(now);
#else
eeprom_store(EEPROM, g_sec);
#endif
} quiet_since = now; }
#ifdef T7_EE_SOON
/* test16: what the game wrote into its EEPROM (a purchase, a figure item) goes to the flash 5 s later when no key
* was pressed for 2 s, not only after a minute without keys (battery out before that: lost). The game writes its
* EEPROM seldom (on the PC: at the setup and at events, not while idle), so the flash is not worn. */
{ static uint32_t ee_t;
if (now - ee_t >= 5000u) { ee_t = now; t7_eeprom_flush(); if (eeprom_dirty() && now - last_in > 2000u) { hw_tone(0);
#if defined(T7_SESS_KEEP) && defined(SESS_AUTO)
sess_auto(now); /* test21: the session along (it notes the EEPROM's sequence: an older one would be dropped) */
#else
eeprom_store(EEPROM, g_sec);
#endif
} } }
#endif
/* caught up: sleep until the next tick, once the tick is known to arrive */
{ static uint32_t g0 = 0xFFFFFFFFu; static int tick_ok;
if (g0 == 0xFFFFFFFFu) g0 = g_ms;
if (!tick_ok && g_ms != g0) tick_ok = 1;
#ifdef T7_WFI_FIX
/* test26: the emulation runs in steps of 2 ms; one ms behind it waits for the next tick as well. Before, the
* loop spun through that ms without sleeping (half of all the time, a battery drain) */
#ifdef T7_PW
if (tick_ok && (int32_t)(g_ms - emu_ms) < 2 && app_pw() == 2 && pw_quiet && g_pw_low && !hw_buttons()) {
/* 1.6.12 test1: deep sleep until the next RTC second; the ms tick then continues from the time of the last
* RTC step (the awake time since then is in it already) */
if (pw_sleep()) { uint32_t r = RTC_C, t = g_pw_rtcms + (r - g_pw_rtc) * 1000u;
__asm__ volatile("cpsid i" ::: "memory"); if ((int32_t)(t - g_ms) > 0) g_ms = t; __asm__ volatile("cpsie i" ::: "memory");
g_pw_rtc = r; g_pw_rtcms = t; }
} else
#endif
if (tick_ok && (int32_t)(g_ms - emu_ms) < 2) __asm__ volatile("wfi"); }
#else
if (tick_ok && emu_ms == g_ms) __asm__ volatile("wfi"); }
#endif
}
}
__attribute__((naked)) static void Default_Handler(void) { __asm__ volatile("1: b 1b\n"); }
__attribute__((naked)) static void Irq_Off(void) { __asm__ volatile("cpsid i\n bx lr\n"); }
__attribute__((section(".vectors"), used))
const void *const g_vectors[16 + 64] = { (void *)0x18020000u, (void *)Reset_Handler,
[2 ... 10] = (void *)Default_Handler, [11] = (void *)Irq_Off, [12 ... 13] = (void *)Default_Handler, [14] = (void *)Irq_Off,
[15] = (void *)SysTick_Handler, [16 ... 79] = (void *)Irq_Off
#ifdef T7_PW
, [16 + 2] = (void *)pw_rtc_irq, [16 + 26] = (void *)pw_gpio_irq
#endif
#ifdef T7_LINK
, [16 + 37] = (void *)plink_irq
#endif
};
+762
View File
@@ -0,0 +1,762 @@
/* T7 on the Paradise: screen layout, settings menu, clock and saved state.
* No hardware access here (see main.c); the PC test in host/ uses the same file.
* Author: mameise */
#include "t7app.h"
#ifdef BL_PWM
void hw_bl_set(unsigned int pct);
#endif
#include "../core/t7.h"
#include "font.h"
#include "icons.h"
#ifdef T7_FR_ICONS
#include "icons_friends.h"
extern uint32_t g_rom_size;
#endif
void figure_rom_set_active(const unsigned char *p, unsigned int n);
/* ---------------------------------------------------------------- screen
* 128x128. Icons 20x20 in a row at the top (y 2) and at the bottom (y 106).
* Game screen 48x31: size 0 twice as big (96x62), size 1 as wide as the screen (128x83,
* cells of 2 or 3 pixels). Menu and messages use the whole area between the icons. */
#define SCR 128
#define ICON_TOP 2
#define ICON_BOT 106
#define MX 0
#define MY 22
#define MW 128
#define MH 84
#define LCDW T7_LCD_WIDTH
#define LCDH T7_LCD_HEIGHT
static const volatile T7Cfg *g_cfg;
static int GX, GY, GW, GH; /* game screen on the display */
static uint8_t g_cx[SCR], g_gx[SCR]; /* per display column: game column, last column of the cell */
static uint8_t g_ry[LCDH + 1]; /* first display row of each game row */
static uint16_t g_pal[4], g_grid, g_off, g_ghostc, g_mpal[4];
static uint8_t g_disp[LCDW * LCDH], g_prev[LCDW * LCDH];
static uint8_t g_ic[T7_ICON_COUNT], g_icp[T7_ICON_COUNT];
static uint16_t g_row[SCR];
static int g_full = 1;
static uint16_t mix(uint16_t a, uint16_t b, int pa) /* pa percent of a, rest b */
{
int r = (((a >> 11) & 31) * pa + ((b >> 11) & 31) * (100 - pa) + 50) / 100;
int g = (((a >> 5) & 63) * pa + ((b >> 5) & 63) * (100 - pa) + 50) / 100;
int c = ((a & 31) * pa + (b & 31) * (100 - pa) + 50) / 100;
return (uint16_t)((r << 11) | (g << 5) | c);
}
/* Settings. Colour tables and the grey, grid, pixel and icon values as in the ESP32 version. */
#define BG_N 14
static const uint16_t PAL_BG[BG_N] = { 0xFFFF, 0xAE66, 0x9DE1, 0xB79A, 0xFD80, 0xB71F, 0x4C67, 0x469A, 0xFF08, 0xFC06, 0xFD99, 0xC51F, 0x0000, 0xF800 };
static const char *const BG_DE[BG_N] = { "Weiss", "Gruen", "GB-Gruen", "Mint", "Amber", "Blau", "Dunkelgruen", "Tuerkis", "Gelb", "Orange", "Rosa", "Lila", "Schwarz", "Rot" };
static const char *const BG_EN[BG_N] = { "White", "Green", "GB green", "Mint", "Amber", "Blue", "Dark green", "Turquoise", "Yellow", "Orange", "Pink", "Purple", "Black", "Red" };
#ifdef BL_PWM
static const T7Set SET_DEF = { 1, 0, 90, 70, 0, 0, 0, 3, 3, 1, 2, 1, 0xFF, 3, 3, 5, PW_DEF, 0xFF, 0xFF, 0xFF };
#else
static const T7Set SET_DEF = { 1, 0, 90, 70, 0, 0, 0, 3, 3, 1, 2, 1, 0xFF, 1, 2, 5, PW_DEF, 0xFF, 0xFF, 0xFF };
#endif
T7Set g_set = { 1, 0, 90, 70, 0, 0, 0, 3, 3, 1, 2, 1, 0xFF, 1, 2, 5, PW_DEF, 0xFF, 0xFF, 0xFF };
static int g_lang; /* 0 German, 1 English */
static int g_dimp; /* dimmed: colours at this percent, 0 = normal */
int app_lang(void) { return g_lang; }
static const char *tr(const char *de, const char *en) { return g_lang ? en : de; }
static void geometry(void)
{
if (g_set.size) { GW = SCR; GH = 83; GX = 0; GY = MY + 1; }
else { GW = LCDW * 2; GH = LCDH * 2; GX = (SCR - GW) / 2; GY = MY + (MH - GH) / 2; }
for (int c = 0; c < LCDW; c++) {
int x0 = c * GW / LCDW, x1 = (c + 1) * GW / LCDW;
#ifdef T7_PIXSOFT
for (int x = x0; x < x1; x++) { g_cx[x] = (uint8_t)c; g_gx[x] = x == x1 - 1; } /* test13: a gap in every cell, in the cell's own colour (draw_row) */
#else
for (int x = x0; x < x1; x++) { g_cx[x] = (uint8_t)c; g_gx[x] = x == x1 - 1 && (!g_set.size || x1 - x0 >= 3); } /* large: gap only in 3 pixel cells, dots stay 2 wide */
#endif
}
for (int r = 0; r <= LCDH; r++) g_ry[r] = (uint8_t)(r * GH / LCDH);
}
static void palette(void)
{
if (g_set.bg >= BG_N) g_set.bg = 1;
if (g_set.ink > BG_N) g_set.ink = 0;
if (g_set.g1 > 100) g_set.g1 = 90;
if (g_set.g2 > 100) g_set.g2 = 70;
if (g_set.grid > 100) g_set.grid = 0;
if (g_set.pixvis > 10) g_set.pixvis = 3;
if (g_set.ghost > 10) g_set.ghost = 3;
g_lang = g_set.lang == 0xFF ? (int)(g_cfg->flags & 1u) : (g_set.lang & 1);
uint16_t bg = PAL_BG[g_set.bg];
uint16_t auto_ink = g_set.bg == 12 ? 0xFFFF : 0x0000; /* on black: white */
uint16_t ink = g_set.ink ? PAL_BG[g_set.ink - 1] : auto_ink;
const int pct[4] = { 100, g_set.g1, g_set.g2, 0 };
for (int i = 0; i < 4; i++) { g_pal[i] = mix(bg, ink, pct[i]); g_mpal[i] = mix(bg, auto_ink, i == 0 ? 100 : i == 1 ? 90 : i == 2 ? 60 : 0); }
g_grid = mix(bg, mix(bg, ink, 76), 100 - g_set.grid); /* full grid: 24 percent towards the ink */
g_off = mix(bg, ink, 100 - g_set.pixvis); /* pixels that are off, slightly visible */
g_ghostc = mix(bg, ink, 100 - g_set.ghost); /* icons that are off */
if (g_dimp) { /* dimmed (screen left on) */
for (int i = 0; i < 4; i++) { g_pal[i] = mix(g_pal[i], 0, g_dimp); g_mpal[i] = mix(g_mpal[i], 0, g_dimp); }
g_grid = mix(g_grid, 0, g_dimp); g_off = mix(g_off, 0, g_dimp); g_ghostc = mix(g_ghostc, 0, g_dimp);
}
geometry();
}
static int icon_x(int i) { return (i % 5) * SCR / 5 + (SCR / 5 - 20) / 2; }
static void draw_icon(int i, int on)
{
int x0 = icon_x(i), y0 = i < 5 ? ICON_TOP : ICON_BOT;
uint16_t c = on ? g_pal[3] : g_set.ghost ? g_ghostc : g_pal[0];
plat_rect(x0, y0, x0 + 20, y0 + 20);
for (int y = 0; y < 20; y++) {
#ifdef T7_FR_ICONS
uint32_t b = g_rom_size == 0xC0000u ? g_icons_fr[i][y] : g_icons[i][y]; /* Friends ROM (768 KB): its own icons */
#else
uint32_t b = g_icons[i][y];
#endif
for (int x = 0; x < 20; x++) g_row[x] = (b & (0x80000u >> x)) ? c : g_pal[0];
plat_row(g_row, 20);
}
plat_rect_end();
}
static void fill(int x0, int y0, int x1, int y1, uint16_t c)
{
plat_rect(x0, y0, x1, y1);
for (int x = 0; x < x1 - x0; x++) g_row[x] = c;
for (int y = y0; y < y1; y++) plat_row(g_row, x1 - x0);
plat_rect_end();
}
/* ---------------------------------------------------------------- menu */
static int g_menu, g_sel, g_top;
static int g_fig = -1, g_fig_next = -2; /* inserted figure, figure waiting to be inserted */
static uint32_t g_fig_at;
static uint8_t g_txt[MH][MW]; /* menu as levels 0..3 */
static int glyph(int c) { if (c >= 97 && c <= 122) c -= 32; return (c < 32 || c > 127) ? 0 : c - 32; }
static int slen(const char *s) { int n = 0; while (s[n]) n++; return n; }
static void txt(int x, int y, const char *s, uint8_t lv)
{
for (; *s && x < MW - 4; s++, x += 6) {
const uint8_t *g = g_font[glyph((unsigned char)*s)];
for (int r = 0; r < 7; r++) for (int c = 0; c < 5; c++)
if (g[r] & (0x10 >> c)) { int yy = y + r, xx = x + c; if (yy >= 0 && yy < MH && xx >= 0 && xx < MW) g_txt[yy][xx] = lv; }
}
}
static void num(char *o, int v, const char *unit) /* "25%" or "Aus" for 0 */
{
int n = 0;
if (!v) { const char *a = tr("Aus", "Off"); while (*a) o[n++] = *a++; o[n] = 0; return; }
if (v >= 100) o[n++] = (char)('0' + v / 100);
if (v >= 10) o[n++] = (char)('0' + (v / 10) % 10);
o[n++] = (char)('0' + v % 10);
while (*unit) o[n++] = *unit++;
o[n] = 0;
}
/* Menu: page 0 = settings, page 1 = figures */
static int g_page;
enum { M_FIG, M_BG, M_INK, M_G1, M_G2, M_SIZE, M_PIX, M_GRID, M_PVIS, M_GHOST, M_SND, M_BL, M_LIGHT, M_DIM, M_OFF, M_SYNC,
#ifdef T7_CARE
M_GP, M_CARE,
#endif
M_LANG,
#if defined(T7_PW) && !defined(T7_FIXED)
M_PW, M_PWST,
#endif
#if defined(T7_JIT) && (!defined(T7_FIXED) || defined(T7_DIAG))
M_JIT,
#endif
#ifdef BAT_SHOW
M_BAT, /* test17: the battery (shown, nothing to change) */
#endif
#ifdef T7_DIAG
M_TEMPO, /* test22 (diagnosis build): emulation speed and the largest lag of the last 2 s */
#endif
M_N };
static int g_items[M_N], g_nitems;
#define ROWS 7
static void menu_items(void)
{
g_nitems = 0;
#ifdef BAT_SHOW
g_items[g_nitems++] = M_BAT; /* first: seen when the menu opens */
#endif
if (g_cfg->nfig) g_items[g_nitems++] = M_FIG;
for (int k = M_BG; k < M_N; k++) {
#ifdef BAT_SHOW
if (k == M_BAT) continue;
#endif
#ifndef BL_PWM
if (k == M_BL) continue;
#endif
if (k != M_DIM || app_dim_ms()) g_items[g_nitems++] = k; /* dim level only when dimming */
}
}
#ifdef T7_CARE
/* test30: Tama-Go's and Friends' state block in the RAM from 0x2F0 (Friends: same places, checked in the PC run) (what it keeps in EEPROM page 0, same offsets; found in the
* simulation): Gotchi Points 0x320..0x324 (BCD, lowest digits first), hunger 0x326 and happy 0x327 (0..5 hearts) */
int hw_num_edit(const char *title, uint32_t *v, int digits, uint32_t max, int en);
static uint8_t g_cared; /* "OK" until the menu closes */
static uint32_t gp_get(void)
{
uint32_t n = 0;
for (int i = 4; i >= 0; i--) { uint8_t v = t7_ram_read((uint16_t)(0x320 + i)); n = n * 100u + (v >> 4) * 10u + (v & 15u); }
return n;
}
static void gp_set(uint32_t n)
{
for (int i = 0; i < 5; i++) { uint32_t d = n % 100u; n /= 100u; t7_ram_write((uint16_t)(0x320 + i), (uint8_t)((d / 10u) << 4 | (d % 10u))); }
}
#endif
static const char *onoff(int v) { return v ? tr("Ein", "On") : tr("Aus", "Off"); }
static void item_text(int it, const char **label, char *val)
{
static const char *const tDE[T7_T_N] = { "10 s", "20 s", "30 s", "1 Min", "2 Min", "5 Min", "10 Min" }, *const tEN[T7_T_N] = { "10 s", "20 s", "30 s", "1 min", "2 min", "5 min", "10 min" };
const char *const *tt = g_lang ? tEN : tDE, *never = tr("Nie", "Never");
const char *b = 0; val[0] = 0;
switch (it) {
case M_FIG: *label = tr("Figur", "Figure"); if (g_fig < 0) b = tr("Keine", "None"); else { int c = 0; for (; c < 15 && g_cfg->fig[g_fig].name[c]; c++) val[c] = g_cfg->fig[g_fig].name[c]; val[c] = 0; } break;
case M_BG: *label = tr("Farbe", "Colour"); b = g_lang ? BG_EN[g_set.bg] : BG_DE[g_set.bg]; break;
case M_INK: *label = "Tama"; b = g_set.ink ? (g_lang ? BG_EN[g_set.ink - 1] : BG_DE[g_set.ink - 1]) : "Auto"; break;
case M_G1: *label = tr("Hellgrau", "Light grey"); num(val, g_set.g1, "%"); if (!g_set.g1) { val[0] = '0'; val[1] = '%'; val[2] = 0; } break;
case M_G2: *label = tr("Dunkelgrau", "Dark grey"); num(val, g_set.g2, "%"); if (!g_set.g2) { val[0] = '0'; val[1] = '%'; val[2] = 0; } break;
case M_SIZE: *label = tr("Bild", "Screen"); b = g_set.size ? tr("Gross", "Large") : tr("Pixelgenau", "Pixel exact"); break;
case M_PIX: *label = "Pixel"; b = onoff(g_set.pixel); break;
case M_GRID: *label = tr("Gitter", "Grid"); num(val, g_set.grid, "%"); break;
case M_PVIS: *label = tr("Pixel-Sicht", "Pixel view"); num(val, g_set.pixvis, "%"); break;
case M_GHOST: *label = "Icons"; num(val, g_set.ghost, "%"); break;
#ifdef T7_VOL
case M_SND: { static const char *const de[T7_VOL_N] = { "Aus", "Leise", "Normal", "Laut" }, *const en[T7_VOL_N] = { "Off", "Quiet", "Normal", "Loud" };
*label = tr("Ton", "Sound"); b = (g_lang ? en : de)[g_set.sound % T7_VOL_N]; } break;
#else
case M_SND: *label = tr("Ton", "Sound"); b = onoff(g_set.sound); break;
#endif
#ifdef BL_PWM
case M_BL: *label = tr("Licht", "Light"); num(val, app_bl_pct(), "%"); break;
#endif
case M_LIGHT: *label = tr("Dimmen nach", "Dim after"); b = g_set.light >= T7_T_N ? never : tt[g_set.light]; break;
case M_DIM: *label = tr("Dimmen auf", "Dim to"); num(val, app_dim_pct(), "%"); break;
case M_OFF: *label = tr("Bild aus nach", "Screen off"); b = g_set.r2 ? tt[(g_set.r2 - 1) % T7_T_N] : never; break;
case M_SYNC: *label = tr("Uhr", "Clock"); b = g_set.sync ? "Auto" : tr("Spiel", "Game"); break;
case M_LANG: *label = tr("Sprache", "Language"); b = g_lang ? "English" : "Deutsch"; break;
#ifdef T7_CARE
case M_GP: { uint32_t v = gp_get(); char t[8]; int n = 0; do { t[n++] = (char)('0' + v % 10u); v /= 10u; } while (v); int j = 0; while (n) val[j++] = t[--n]; val[j++] = 'p'; val[j] = 0; } *label = "Gotchi Points"; break;
case M_CARE: *label = tr("Pflege voll", "Full care"); if (g_cared) { val[0] = 'O'; val[1] = 'K'; val[2] = 0; } break;
#endif
#ifdef BAT_SHOW
case M_BAT: *label = tr("Batterie", "Battery"); plat_bat(val); break;
#endif
#if defined(T7_PW) && !defined(T7_FIXED)
case M_PW: *label = tr("Strom sparen", "Power save"); { int m = app_pw(); b = m == 0 ? "Normal" : m == 1 ? tr("Stark", "Strong") : "Maximal"; } break;
case M_PWST: *label = tr("Schlaf/12M", "Sleep/12M"); { int v = plat_pw_pct(), a = v / 1000, c = v % 1000, n = 0; /* test: shares since the start */
char t[4]; int k;
k = 0; do { t[k++] = (char)('0' + a % 10); a /= 10; } while (a); while (k) val[n++] = t[--k]; val[n++] = '%'; val[n++] = ' ';
k = 0; do { t[k++] = (char)('0' + c % 10); c /= 10; } while (c); while (k) val[n++] = t[--k]; val[n++] = '%'; val[n] = 0; } break;
#endif
#ifdef T7_DIAG
case M_TEMPO: { extern void plat_tempo(char *v); *label = "Tempo"; plat_tempo(val); } break;
#endif
#if defined(T7_JIT) && (!defined(T7_FIXED) || defined(T7_DIAG))
case M_JIT: *label = "JIT"; b = plat_jit(app_jit()) < 0 ? tr("fehlt", "missing") : app_jit() ? tr("An", "On") : tr("Aus", "Off"); break;
#endif
}
if (b) { int n = 0; while (b[n] && n < 15) { val[n] = b[n]; n++; } val[n] = 0; }
}
static void menu_build(void)
{
for (int y = 0; y < MH; y++) for (int x = 0; x < MW; x++) g_txt[y][x] = 0;
int n = g_page ? (int)g_cfg->nfig + 1 : g_nitems;
txt(2, 1, g_page ? tr("FIGUR", "FIGURE") : tr("EINSTELLUNGEN", "SETTINGS"), 3);
for (int x = 0; x < MW; x++) g_txt[10][x] = 2;
if (g_sel < g_top) g_top = g_sel;
if (g_sel >= g_top + ROWS) g_top = g_sel - ROWS + 1;
for (int k = 0; k < ROWS && g_top + k < n; k++) {
int i = g_top + k, y = 13 + k * 10;
uint8_t lv = i == g_sel ? 0 : 3;
if (i == g_sel) for (int yy = y - 1; yy < y + 8 && yy < MH; yy++) for (int x = 0; x < MW; x++) g_txt[yy][x] = 3;
if (!g_page) {
const char *label = ""; char val[17];
item_text(g_items[i], &label, val);
txt(2, y, label, lv);
txt(MW - 2 - 6 * slen(val), y, val, lv);
} else {
char nm[17];
if (i == 0) { const char *a = tr("Keine", "None"); int c = 0; while (a[c]) { nm[c] = a[c]; c++; } nm[c] = 0; }
else { for (int c = 0; c < 16; c++) nm[c] = g_cfg->fig[i - 1].name[c]; nm[16] = 0; }
txt(2, y, (i - 1 == g_fig) ? "*" : " ", lv);
txt(10, y, nm, lv);
}
}
/* scroll marks */
for (int k = 0; k < 4; k++) for (int x = -k; x <= k; x++) {
if (g_top > 0) g_txt[2 + k][MW - 14 + x] = 2; /* more above */
if (g_top + ROWS < n) g_txt[7 - k][MW - 5 + x] = 2; /* more below */
}
g_full = 2;
}
int app_menu_open(void) { return g_menu; }
static void fig_insert(int i)
{
if (i < 0) { figure_rom_set_active(0, 0); t7_figure_set(0); g_fig = -1; return; }
figure_rom_set_active(plat_fig_ptr(i), g_cfg->fig[i].len);
t7_figure_set(1);
g_fig = i;
}
static void fig_choose(int i, uint32_t now)
{
if (i == g_fig) return;
/* like on the real toy: take the old figure off, wait, put the new one on */
fig_insert(-1);
if (i >= 0) { g_fig_next = i; g_fig_at = now + 2500u; }
}
void app_tick(uint32_t now)
{
if (g_fig_next >= 0 && (int32_t)(now - g_fig_at) >= 0) { fig_insert(g_fig_next); g_fig_next = -2; }
}
static int g_dirty_set;
static void change(int it)
{
switch (it) {
case M_BG: g_set.bg = (uint8_t)((g_set.bg + 1) % BG_N); break;
case M_INK: g_set.ink = (uint8_t)((g_set.ink + 1) % (BG_N + 1)); break;
case M_G1: g_set.g1 = (uint8_t)(g_set.g1 >= 100 ? 0 : (g_set.g1 / 5) * 5 + 5); break;
case M_G2: g_set.g2 = (uint8_t)(g_set.g2 >= 100 ? 0 : (g_set.g2 / 5) * 5 + 5); break;
case M_SIZE: g_set.size ^= 1; break;
case M_PIX: g_set.pixel ^= 1; break;
case M_GRID: g_set.grid = (uint8_t)(g_set.grid >= 100 ? 0 : (g_set.grid / 25) * 25 + 25); break;
case M_PVIS: g_set.pixvis = (uint8_t)(g_set.pixvis >= 10 ? 0 : g_set.pixvis + 1); break;
case M_GHOST: g_set.ghost = (uint8_t)(g_set.ghost >= 10 ? 0 : g_set.ghost + 1); break;
#ifdef T7_VOL
case M_SND: g_set.sound = (uint8_t)((g_set.sound + 1) % T7_VOL_N); plat_vol(g_set.sound); break;
#else
case M_SND: g_set.sound ^= 1; break;
#endif
#if defined(T7_PW) && !defined(T7_FIXED)
case M_PW: g_set.pw = (uint8_t)((app_pw() + 1) % 3); break;
#endif
#if defined(T7_JIT) && (!defined(T7_FIXED) || defined(T7_DIAG))
case M_JIT: g_set.r3 = (uint8_t)((g_set.r3 == 0xFFu ? 0u : g_set.r3) ^ 1u); plat_jit(app_jit()); break;
#endif
case M_LIGHT:
g_set.light = (uint8_t)((g_set.light + 1) % (T7_T_N + 1));
if (g_set.light < T7_T_N && g_set.r2 && g_set.r2 - 1 <= g_set.light) g_set.r2 = (uint8_t)(g_set.light + 2 <= T7_T_N ? g_set.light + 2 : 0); /* off stays after dimming */
menu_items();
break;
#ifdef BL_PWM
case M_BL: g_set.r1 = (uint8_t)((g_set.r1 & 0x0F) | (((((g_set.r1 >> 4) & 15) + 1) % T7_BL_N) << 4)); hw_bl_set((unsigned int)app_bl_pct()); break;
case M_DIM: g_set.r0 = (uint8_t)((g_set.r0 + 1) % T7_DIM_N); break;
#else
case M_DIM: g_set.r0 = (uint8_t)((g_set.r0 + 1) % 5); break;
#endif
case M_OFF:
do g_set.r2 = (uint8_t)((g_set.r2 + 1) % (T7_T_N + 1)); while (g_set.r2 && g_set.light < T7_T_N && g_set.r2 - 1 <= g_set.light);
break;
case M_SYNC: g_set.sync ^= 1; break;
case M_LANG: g_set.lang = (uint8_t)(g_lang ^ 1); break;
#ifdef T7_CARE
case M_GP: { uint32_t v = gp_get(); if (hw_num_edit("GOTCHI POINTS", &v, 6, 999999u, g_lang)) gp_set(v); } break;
case M_CARE: t7_ram_write(0x326, 5); t7_ram_write(0x327, 5); g_cared = 1; break;
#endif
}
g_dirty_set = 1;
palette();
/* the screen around the menu in the new colours */
fill(0, 0, SCR, MY, g_pal[0]); fill(0, MY + MH, SCR, SCR, g_pal[0]);
for (int i = 0; i < T7_ICON_COUNT; i++) g_icp[i] = 0xFF;
}
static void menu_close(void)
{
g_menu = 0; g_full = 1;
#ifdef T7_CARE
g_cared = 0;
#endif
if (g_dirty_set) { app_store(); g_dirty_set = 0; }
}
int app_keys(uint32_t b, uint32_t now)
{
static uint32_t last;
uint32_t press = b & ~last; last = b;
if (!g_menu) return (int)(b & 7u);
int n = g_page ? (int)g_cfg->nfig + 1 : g_nitems;
if (press & 1u) { g_sel = (g_sel + 1) % n; menu_build(); }
if (press & 2u) {
if (g_page) { fig_choose(g_sel - 1, now); g_page = 0; g_sel = 0; g_top = 0; menu_build(); }
else if (g_items[g_sel] == M_FIG) { g_page = 1; g_sel = g_fig + 1; g_top = 0; menu_build(); }
else { int k = g_items[g_sel]; change(k); menu_build();
#ifdef T7_CARE
if (k == M_GP) g_full = 1; /* the number screen covered everything */
#endif
}
}
if (press & 4u) {
if (g_page) { g_page = 0; g_sel = 0; g_top = 0; menu_build(); }
else menu_close();
}
return 0;
}
/* dimmed after the light time (screen left on) or normal again */
void app_dim(int pct)
{
#ifdef BL_PWM
hw_bl_set(pct ? (unsigned int)pct : (unsigned int)app_bl_pct()); /* 1.6.8: the light, as the Paradise does it, the colours stay */
return;
#endif
if (pct == g_dimp) return;
g_dimp = pct; palette();
for (int i = 0; i < T7_ICON_COUNT; i++) g_icp[i] = 0xFF;
g_full = 1; app_render(1);
}
/* wheel, short press: menu open/close */
void app_wheel_short(void)
{
if (g_menu) { menu_close(); return; }
#ifdef BAT_SHOW
g_menu = 1; menu_items(); g_page = 0; g_sel = 1; g_top = 0; menu_build(); /* the battery line is only shown */
#else
g_menu = 1; menu_items(); g_page = 0; g_sel = 0; g_top = 0; menu_build();
#endif
}
/* ---------------------------------------------------------------- stored settings and clock note
* Sector layout: "T7S2", the settings (16 bytes), then at 32 "T7CK", seconds counter, game
* second of the day, month and day then. Older layout "T7ST": bg ink pixel ghost sound light. */
#define CK_MAGIC 0x4B433754u /* "T7CK" */
static uint32_t g_ck_cnt, g_ck_sod, g_ck_md, g_ck_have;
static void w32(uint8_t *b, uint32_t v) { b[0] = (uint8_t)v; b[1] = (uint8_t)(v >> 8); b[2] = (uint8_t)(v >> 16); b[3] = (uint8_t)(v >> 24); }
static uint32_t r32(const uint8_t *b) { return b[0] | (b[1] << 8) | (b[2] << 16) | ((uint32_t)b[3] << 24); }
static void store_load(void)
{
uint8_t b[T7_STORE_LEN];
g_set = SET_DEF;
if (!plat_store_load(b, sizeof b)) return;
if (b[0] == 'T' && b[1] == '7' && b[2] == 'S' && b[3] == '2') {
uint8_t *d = (uint8_t *)&g_set; for (unsigned i = 0; i < sizeof g_set; i++) d[i] = b[4 + i];
} else if (b[0] == 'T' && b[1] == '7' && b[2] == 'S' && b[3] == 'T') {
g_set.bg = b[4]; g_set.ink = b[5]; g_set.pixel = b[6] & 1; g_set.sound = b[8] & 1; g_set.light = b[9];
g_set.r0 = 0; g_set.r1 = 0;
}
if ((g_set.r1 & 0x0F) != 2 && (g_set.r1 & 0x0F) != 3) { /* older layouts: what was "light off after" stays */
uint8_t off; /* index 0..6 (10 s .. 10 min) or 7 never */
if ((g_set.r1 & 0x0F) == 1) { static const uint8_t m[7] = { 0, 1, 2, 3, 4, 5, 7 }; off = m[g_set.light % 7]; } /* test builds 1.6.6 */
else { static const uint8_t m[5] = { 2, 3, 4, 5, 7 }; off = m[g_set.light % 5]; } /* 30 s, 1, 2, 5 min, never */
g_set.light = T7_T_N; g_set.r0 = 1; g_set.r2 = off >= T7_T_N ? 0 : (uint8_t)(off + 1); g_set.r1 = 2;
}
#ifdef BL_PWM
if ((g_set.r1 & 0x0F) == 2) { /* layout 2: dim 1, 5, 10, 25, 50 %, the light always full */
static const uint8_t m[5] = { 0, 3, 4, 6, 9 }; g_set.r0 = m[g_set.r0 % 5]; g_set.r1 = 3;
}
hw_bl_set((unsigned int)app_bl_pct());
#endif
#ifdef T7_VOL
if (g_set.sound == T7_VOL_N) g_set.sound = T7_VOL_N - 1; /* maximal of the test builds: loud */
else if (g_set.sound > T7_VOL_N) g_set.sound = 1;
plat_vol(g_set.sound);
#endif
if (r32(b + 32) == CK_MAGIC) { g_ck_cnt = r32(b + 36); g_ck_sod = r32(b + 40); g_ck_md = r32(b + 44); g_ck_have = 1; }
}
static int tama_sod(void);
static int g_ck_ok(void);
void app_store(void)
{
uint8_t b[T7_STORE_LEN];
for (unsigned i = 0; i < sizeof b; i++) b[i] = 0xFF;
b[0] = 'T'; b[1] = '7'; b[2] = 'S'; b[3] = '2';
const uint8_t *d = (const uint8_t *)&g_set; for (unsigned i = 0; i < sizeof g_set; i++) b[4 + i] = d[i];
int obs = tama_sod();
if (g_ck_ok() && obs >= 0) { g_ck_cnt = plat_rtc(); g_ck_sod = (uint32_t)obs; g_ck_md = (uint32_t)(t7_ram_read(0x0304) << 8 | t7_ram_read(0x0305)); g_ck_have = 1; }
if (g_ck_have) { w32(b + 32, CK_MAGIC); w32(b + 36, g_ck_cnt); w32(b + 40, g_ck_sod); w32(b + 44, g_ck_md); }
plat_store_write(b, sizeof b);
}
void app_init(const volatile T7Cfg *cfg)
{
g_cfg = cfg;
store_load();
palette();
g_full = 1;
}
/* one game row into the display rows of its cell */
static void draw_row(int r, const uint8_t *d)
{
int p = g_set.pixel;
#ifdef T7_PIXSOFT
/* 1.6.9 test13: pixel mode. A cell is only 2 or 3 display pixels: a gap in the grid colour left a dot of 1 pixel
* and the picture was hard to see. Now every cell has its gap (right column, bottom row), drawn as the cell's own
* colour moved a fifth towards the grid colour: the pixels stay full, a fine grid shows between them. */
if (p) {
uint16_t on[4], gap[4];
for (int v = 0; v < 4; v++) { on[v] = v ? g_pal[v] : g_off; gap[v] = mix(on[v], g_grid, 80); }
for (int y = g_ry[r]; y < g_ry[r + 1]; y++) {
int hl = y == g_ry[r + 1] - 1;
for (int x = 0; x < GW; x++) { int v = d[g_cx[x]] & 3; g_row[x] = (hl || g_gx[x]) ? gap[v] : on[v]; }
plat_row(g_row, GW);
}
return;
}
#endif
for (int y = g_ry[r]; y < g_ry[r + 1]; y++) {
if (p && y == g_ry[r + 1] - 1 && (!g_set.size || g_ry[r + 1] - g_ry[r] >= 3)) { for (int x = 0; x < GW; x++) g_row[x] = g_grid; }
else for (int x = 0; x < GW; x++) {
int v = d[g_cx[x]] & 3;
g_row[x] = (p && g_gx[x]) ? g_grid : (p && !v) ? g_off : g_pal[v];
}
plat_row(g_row, GW);
}
}
void app_render(int force)
{
if (force) g_full = 1;
if (g_full == 1) {
fill(0, 0, SCR, SCR, g_pal[0]);
for (int i = 0; i < T7_ICON_COUNT; i++) g_icp[i] = 0xFF;
for (int i = 0; i < LCDW * LCDH; i++) g_prev[i] = 0xFF;
}
if (g_menu) {
if (g_full) {
plat_rect(MX, MY, MX + MW, MY + MH);
for (int y = 0; y < MH; y++) { for (int x = 0; x < MW; x++) g_row[x] = g_mpal[g_txt[y][x]]; plat_row(g_row, MW); }
plat_rect_end();
for (int i = 0; i < LCDW * LCDH; i++) g_prev[i] = 0xFF; /* game screen again afterwards */
}
} else {
t7_get_display(g_disp);
int y = 0;
while (y < LCDH) {
int ch = 0;
for (int x = 0; x < LCDW; x++) if (g_disp[y * LCDW + x] != g_prev[y * LCDW + x]) { ch = 1; break; }
if (!ch) { y++; continue; }
int y1 = y;
while (y1 < LCDH) {
int c2 = 0;
for (int x = 0; x < LCDW; x++) if (g_disp[y1 * LCDW + x] != g_prev[y1 * LCDW + x]) { c2 = 1; break; }
if (!c2) break;
y1++;
}
plat_rect(GX, GY + g_ry[y], GX + GW, GY + g_ry[y1]);
for (int r = y; r < y1; r++) {
draw_row(r, &g_disp[r * LCDW]);
for (int x = 0; x < LCDW; x++) g_prev[r * LCDW + x] = g_disp[r * LCDW + x];
}
plat_rect_end();
y = y1;
}
}
t7_get_icons(g_ic);
for (int i = 0; i < T7_ICON_COUNT; i++) {
int on = g_ic[i] != 0;
if (on != g_icp[i]) { draw_icon(i, on); g_icp[i] = (uint8_t)on; }
}
g_full = 0;
}
/* the bell icon (the pet calls) */
int app_bell(void)
{
uint8_t ic[T7_ICON_COUNT];
t7_get_icons(ic);
return ic[9] != 0;
}
/* Full screen message (start up, catching up the time) with a bar */
void app_text_screen(const char *l1, const char *l2, int done, int total)
{
for (int y = 0; y < MH; y++) for (int x = 0; x < MW; x++) g_txt[y][x] = 0;
if (l1) txt(4, 20, l1, 3);
if (l2) txt(4, 32, l2, 3);
if (total > 0) {
int w = (MW - 16) * done / total;
for (int y = 50; y < 58; y++) for (int x = 8; x < MW - 8; x++) g_txt[y][x] = (x - 8 < w) ? 3 : ((y == 50 || y == 57 || x == 8 || x == MW - 9) ? 2 : 0);
}
plat_rect(MX, MY, MX + MW, MY + MH);
for (int y = 0; y < MH; y++) { for (int x = 0; x < MW; x++) g_row[x] = g_mpal[g_txt[y][x]]; plat_row(g_row, MW); }
plat_rect_end();
for (int i = 0; i < LCDW * LCDH; i++) g_prev[i] = 0xFF;
g_full = 1;
}
/* ---------------------------------------------------------------- clock
* The V7 keeps its time in work RAM (binary): hour 0x306, minute 0x307, second 0x396 (Friends 0x136),
* day 0x305, month 0x304. The hour may only change through the game itself (it ages the
* pet and runs its day events), so behind by an hour or more we put the clock just
* before the full hour and let the game count on. Within the hour, minute and second
* are simply set. Reference: the Paradise's seconds counter. */
#define RTC_H 0x0306
#define RTC_M 0x0307
#define RTC_S t7_rtc_sec_addr() /* 0x396, Friends 0x136 */
#define RTC_D 0x0305
#define RTC_MO 0x0304
static uint32_t g_ref_cnt, g_ref_sod, g_have_ref, g_last_obs, g_last_cnt;
static int g_ck_ok(void) { return (int)g_have_ref; }
static int tama_sod(void)
{
int h = t7_ram_read(RTC_H), m = t7_ram_read(RTC_M), s = t7_ram_read(RTC_S);
if (h > 23 || m > 59 || s > 59) return -1;
return h * 3600 + m * 60 + s;
}
static int32_t wrapdiff(int32_t a, int32_t b) /* a - b on the 24 h circle, -43200..43199 */
{
int32_t d = (a - b) % 86400; if (d < -43200) d += 86400; if (d >= 43200) d -= 86400; return d;
}
static uint32_t expected(uint32_t rtc) { return (g_ref_sod + (rtc - g_ref_cnt)) % 86400u; }
static void set_ms(int sod) { t7_ram_write(RTC_M, (uint8_t)((sod / 60) % 60)); t7_ram_write(RTC_S, (uint8_t)(sod % 60)); }
void app_clock(uint32_t rtc, int guard)
{
int obs = tama_sod();
#ifdef T7_GAME_KEEP
/* test27: with "Clock: Game" too the game's clock is kept on the Paradise's seconds counter while it runs
* (only its own time, nothing of the Paradise's) */
if (guard || obs < 0) { g_have_ref = 0; return; }
#else
if (guard || obs < 0 || !g_set.sync) { g_have_ref = 0; return; }
#endif
/* the clock stands (the game asks for the time, or it is being set): leave it alone */
if (g_have_ref && (uint32_t)obs == g_last_obs && rtc != g_last_cnt) { g_have_ref = 0; g_last_cnt = rtc; return; }
if (!g_have_ref) { g_ref_cnt = rtc; g_ref_sod = (uint32_t)obs; g_have_ref = 1; g_last_obs = (uint32_t)obs; g_last_cnt = rtc; return; }
/* clock set in the game: new reference */
int32_t jump = wrapdiff(obs, (int32_t)((g_last_obs + (rtc - g_last_cnt)) % 86400u));
if (jump > 30 || jump < -30) { g_ref_cnt = rtc; g_ref_sod = (uint32_t)obs; g_last_obs = (uint32_t)obs; g_last_cnt = rtc; return; }
int exp = (int)expected(rtc);
int32_t d = wrapdiff(exp, obs); /* > 0: the game is behind */
if (d >= 2 || d <= -2) {
if (exp / 3600 == obs / 3600) set_ms(exp);
else if (d > 0) { t7_ram_write(RTC_M, 59); t7_ram_write(RTC_S, 59); }
}
int now = tama_sod();
g_last_obs = (uint32_t)(now < 0 ? obs : now); g_last_cnt = rtc;
}
/* After a pause: one full hour after the other through the game (at most 30, like the
* phone app), the rest of the time is set directly. Returns the hours run. */
static void add_days(uint32_t *y, uint32_t *m, uint32_t *d, uint32_t n);
int app_catchup(uint32_t rtc, void (*progress)(int, int))
{
int obs = tama_sod();
if (!g_have_ref || obs < 0 || !g_set.sync) return 0;
int32_t ahead = (int32_t)(rtc - g_last_cnt); /* seconds since the save */
if (ahead < 0) { g_ref_cnt = rtc; g_ref_sod = (uint32_t)obs; g_last_obs = (uint32_t)obs; g_last_cnt = rtc; return 0; } /* counter went back: keep the game time */
int hours = (int)((obs % 3600 + ahead) / 3600);
#ifdef T7_NO_CATCHUP
/* 1.7.3 (Bernd: "kein Catching up, das Tama startet normal und nur die Uhr wird angepasst"): nothing is run through,
* the clock (and the date by the days in between) is set directly, as with the clock from the Paradise */
int n = 0;
{ uint32_t days = (uint32_t)(((uint32_t)obs + (uint32_t)ahead) / 86400u);
if (days) { uint32_t y = 0, m = t7_ram_read(RTC_MO), d = t7_ram_read(RTC_D); add_days(&y, &m, &d, days);
t7_ram_write(RTC_MO, (uint8_t)m); t7_ram_write(RTC_D, (uint8_t)d); } }
#else
int n = hours > 30 ? 30 : hours;
#endif
for (int k = 0; k < n; k++) {
if (progress) progress(k, n);
int h0 = t7_ram_read(RTC_H);
t7_ram_write(RTC_M, 59); t7_ram_write(RTC_S, 59);
for (int f = 0; f < 300 && t7_ram_read(RTC_H) == h0; f++) t7_step_cycles(40000); /* up to 3 s game time */
for (int f = 0; f < 50; f++) t7_step_cycles(40000); /* let the day events run */
}
int exp = (int)expected(rtc);
if (hours > n) t7_ram_write(RTC_H, (uint8_t)(exp / 3600)); /* beyond 30 hours: skip */
set_ms(exp);
int now = tama_sod();
g_last_obs = (uint32_t)(now < 0 ? exp : now); g_last_cnt = rtc;
if (progress && n) progress(n, n);
return n;
}
/* The game asks for the time (hour 255 while setting it up, after a fresh start). It only
* takes the time once the hour was changed, so midnight could not be entered. Filled in:
* the game time noted on leaving (counted on), else the time the Studio wrote along, else
* just hour 0. Once per request, the player can still change everything. */
static const uint8_t MDAYS[13] = { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
static void add_days(uint32_t *y, uint32_t *m, uint32_t *d, uint32_t n)
{
if (*m < 1 || *m > 12) *m = 1;
if (*d < 1) *d = 1;
while (n--) {
uint32_t len = MDAYS[*m] + (*m == 2 && *y && (*y % 4u) == 0 && ((*y % 100u) || (*y % 400u) == 0));
if (++*d > len) { *d = 1; if (++*m > 12) { *m = 1; if (*y) ++*y; } }
}
}
/* The Paradise's own time at the start (seconds since 1970, 0 = not found) and its seconds counter
* then, read by the platform before anything overwrote it. With settings flag 2 ("clock from the
* Paradise") the game clock is set to it at every start, nothing is run in between. */
uint32_t g_para_time, g_para_cnt;
static int para_hard(void) { return (g_cfg->flags & 2u) && g_para_time && g_set.sync; }
static void civil(uint32_t days, uint32_t *y, uint32_t *m, uint32_t *d)
{
uint32_t z = days + 719468u, era = z / 146097u, doe = z - era * 146097u;
uint32_t yoe = (doe - doe / 1460u + doe / 36524u - doe / 146096u) / 365u, doy = doe - (365u * yoe + yoe / 4u - yoe / 100u);
uint32_t mp = (5u * doy + 2u) / 153u;
*d = doy - (153u * mp + 2u) / 5u + 1u; *m = mp < 10u ? mp + 3u : mp - 9u; *y = yoe + era * 400u + (*m <= 2u);
}
static uint32_t para_now(uint32_t rtc) { return g_para_time + (rtc - g_para_cnt); }
int app_clock_hard(uint32_t rtc)
{
if (!para_hard() || t7_ram_read(RTC_H) > 23) return 0; /* hour 255: the game asks, app_setup_fill answers */
uint32_t now = para_now(rtc), sod = now % 86400u, y, m, d;
civil(now / 86400u, &y, &m, &d);
t7_ram_write(RTC_MO, (uint8_t)m); t7_ram_write(RTC_D, (uint8_t)d);
t7_ram_write(RTC_H, (uint8_t)(sod / 3600u)); t7_ram_write(RTC_M, (uint8_t)((sod / 60u) % 60u)); t7_ram_write(RTC_S, (uint8_t)(sod % 60u));
g_ref_cnt = rtc; g_ref_sod = sod; g_have_ref = 1; g_last_obs = sod; g_last_cnt = rtc;
return 1;
}
static int g_fill_seen, g_fill_done;
void app_setup_fill(uint32_t rtc)
{
int h = t7_ram_read(RTC_H);
/* 1.6.8: once the game's own setup is through (it asked for the time, now it has one), the Paradise's time
* replaces what was typed in (clock from the Paradise) */
static int asked, after;
if (h == 255) { asked = 1; after = 0; }
else if (h <= 23 && asked && ++after >= 4) { asked = 0; after = 0; app_clock_hard(rtc); }
if (h <= 23) { g_fill_seen = 0; g_fill_done = 0; return; }
if (h != 255 || !g_set.sync || g_fill_done) return;
if (++g_fill_seen < 2) return; /* seen twice, half a second apart */
g_fill_done = 1;
uint32_t sod, y = 0, m, d, have = 1, el;
if (para_hard()) { uint32_t now = para_now(rtc); el = now % 86400u; civil(now / 86400u, &y, &m, &d); y = 0; }
#ifdef T7_CK_WRAP
/* 1.6.12: after a battery change the Paradise's seconds counter starts at 0 again, below the noted one: the
* difference wrapped to about 136 years and the game got a date far off; now the noted time as it was */
else if (g_ck_have && rtc < g_ck_cnt) { el = g_ck_sod; m = (g_ck_md >> 8) & 0xFF; d = g_ck_md & 0xFF; }
#endif
else if (g_ck_have) { el = g_ck_sod + (rtc - g_ck_cnt); m = (g_ck_md >> 8) & 0xFF; d = g_ck_md & 0xFF; }
else if (g_cfg->wall_ymd) { el = g_cfg->wall_sod + (rtc - g_cfg->wall_cnt); y = g_cfg->wall_ymd >> 16; m = (g_cfg->wall_ymd >> 8) & 0xFF; d = g_cfg->wall_ymd & 0xFF; }
else { have = 0; el = 0; m = 1; d = 1; }
if (!have) { t7_ram_write(RTC_H, 0); return; }
sod = el % 86400u;
add_days(&y, &m, &d, el / 86400u);
t7_ram_write(RTC_MO, (uint8_t)m); t7_ram_write(RTC_D, (uint8_t)d);
t7_ram_write(RTC_H, (uint8_t)(sod / 3600u)); t7_ram_write(RTC_M, (uint8_t)((sod / 60u) % 60u)); t7_ram_write(RTC_S, (uint8_t)(sod % 60u));
}
/* ---------------------------------------------------------------- saved state */
#define SV_MAGIC 0x53533754u /* "T7SS" */
#define SV_VER 1u
uint32_t app_save(uint8_t *buf, uint32_t cap)
{
uint32_t n = t7_serialize_state(0, 0);
if (cap < 40u + n) return 0;
int fig = g_fig_next >= 0 ? g_fig_next : g_fig;
w32(buf, SV_MAGIC); w32(buf + 4, SV_VER); w32(buf + 8, plat_rtc());
w32(buf + 12, g_ref_cnt); w32(buf + 16, g_ref_sod); w32(buf + 20, g_have_ref);
w32(buf + 24, (uint32_t)fig); w32(buf + 28, n); w32(buf + 32, g_last_cnt);
t7_serialize_state(buf + 40, n);
uint32_t s = 0; for (uint32_t i = 0; i < 40u + n; i++) if (i < 36 || i >= 40) s = s * 31u + buf[i];
w32(buf + 36, s);
return 40u + n;
}
int app_load(const uint8_t *buf, uint32_t len, uint32_t *saved_rtc)
{
if (len < 40 || r32(buf) != SV_MAGIC || r32(buf + 4) != SV_VER) return 0;
uint32_t n = r32(buf + 28);
if (n != t7_serialize_state(0, 0) || 40u + n > len) return 0;
uint32_t s = 0; for (uint32_t i = 0; i < 40u + n; i++) if (i < 36 || i >= 40) s = s * 31u + buf[i];
if (s != r32(buf + 36)) return 0;
if (!t7_deserialize_state(buf + 40, n)) return 0;
*saved_rtc = r32(buf + 8);
g_ref_cnt = r32(buf + 12); g_ref_sod = r32(buf + 16); g_have_ref = r32(buf + 20);
g_last_cnt = r32(buf + 8);
{ int o = tama_sod(); g_last_obs = (uint32_t)(o < 0 ? 0 : o); }
int fig = (int32_t)r32(buf + 24);
if (fig >= 0 && fig < (int)g_cfg->nfig) fig_insert(fig); else fig_insert(-1);
g_full = 1;
return 1;
}
+95
View File
@@ -0,0 +1,95 @@
/* T7 on the Paradise: the part that does not touch the hardware (screen layout, clock,
* figure menu, saved state). Built for the device and for the PC test (host/). */
#ifndef T7APP_H
#define T7APP_H
#include <stdint.h>
/* Settings block, filled in by the Studio (magic "PMX7"), at 0x140 in the program. */
#define T7_FIG_MAX 16
typedef struct { uint32_t off, len; char name[16]; } T7Fig;
typedef struct {
uint32_t magic, version, rom_off, rom_len, save_off, nfig;
T7Fig fig[T7_FIG_MAX];
uint32_t flags; /* bit 0: English, bit 1: clock from the Paradise at every start, bit 12: no session (T7_F_NOSESS) */
uint32_t wall_cnt, wall_sod, wall_ymd; /* written by the Studio on the device: seconds counter, local time and date then (0 = none) */
} T7Cfg;
#define T7_MAGIC 0x37584D50u /* "PMX7" */
#define T7_F_NOSESS 0x1000u /* 1.7.3 test7 (SESS_FLAG): run state never written nor loaded, only the EEPROM */
/* Settings on the device (wheel, short press). Stored with the clock note in their own sector. */
typedef struct {
uint8_t bg, ink, g1, g2, size, pixel, grid, pixvis, ghost, sound, light, sync, lang, r0, r1, r2;
uint8_t pw, r3, r4, r5; /* 1.6.12 test1 (T7_PW): power saving while the screen is off, 0 normal, 1 strong (12 MHz),
2 maximal (12 MHz and deep sleep between the seconds); others (older settings: 0xFF) = PW_DEF */
} T7Set;
#define PW_DEF 1u
#ifdef T7_FIXED
/* 1.6.12 test4: power save maximal and the JIT always (tested over night: the call still rings and lights the screen) */
static inline int app_pw(void) { return 2; }
#else
static inline int app_pw(void) { extern T7Set g_set; return g_set.pw <= 2u ? g_set.pw : (int)PW_DEF; }
#endif
extern T7Set g_set;
/* 1.6.6: light = time without a key until the screen dims (0..6: 10 s .. 10 min, 7 = never),
* r0 = dim level (1, 5, 10, 25, 50 %), r2 = time until the screen goes off (0 = never, 1..7 = 10 s .. 10 min,
* always longer than the dim time), r1: bits 0..3 = 2 (this layout). Dimmed = darker colours (the backlight PWM had no effect on the device). */
#define T7_T_N 7
static inline uint32_t t7_t_ms(int i) { static const uint32_t t[T7_T_N] = { 10000u, 20000u, 30000u, 60000u, 120000u, 300000u, 600000u }; return t[i % T7_T_N]; }
static inline uint32_t app_dim_ms(void) { return g_set.light >= T7_T_N ? 0u : t7_t_ms(g_set.light); }
static inline uint32_t app_off_ms(void) { return g_set.r2 ? t7_t_ms(g_set.r2 - 1) : 0u; }
#ifdef BL_PWM
/* 1.6.8 (test45): layout 3. r0 = dim level 1..50 % (10 steps), r1 bits 4..7 = the light in general:
* 0 = 100 %, 1..10 = 5, 10, 20 .. 90 %. Dimmed is never brighter than the light in general. */
#define T7_DIM_N 10
#define T7_BL_N 11
static inline int app_bl_pct(void) { static const uint8_t p[T7_BL_N] = { 100, 5, 10, 20, 30, 40, 50, 60, 70, 80, 90 }; return p[((g_set.r1 >> 4) & 15) % T7_BL_N]; }
static inline int app_dim_pct(void) { static const uint8_t p[T7_DIM_N] = { 1, 2, 3, 5, 10, 15, 20, 30, 40, 50 }; int d = p[g_set.r0 % T7_DIM_N], b = app_bl_pct(); return d < b ? d : b; }
#else
static inline int app_dim_pct(void) { static const uint8_t p[5] = { 1, 5, 10, 25, 50 }; return p[g_set.r0 % 5]; }
#endif
void app_dim(int pct);
int app_bell(void); /* 1 = the bell icon is on (the pet calls) */
#define T7_STORE_LEN 64u
/* Platform (device or PC test) */
int plat_store_load(uint8_t *b, uint32_t n); /* bytes of the settings sector (0 = empty) */
void plat_store_write(const uint8_t *b, uint32_t n);
uint32_t plat_rtc(void);
#ifdef T7_JIT
/* 1.6.12 test2: r3 bit 0 = JIT off (0xFF of older settings: on) */
#if defined(T7_FIXED) && !defined(T7_DIAG)
static inline int app_jit(void) { return 1; }
#else
static inline int app_jit(void) { extern T7Set g_set; return g_set.r3 == 0xFFu || !(g_set.r3 & 1u); }
#endif
int plat_jit(int on); /* switch, -1: the second part is missing */
#endif
int plat_pw_pct(void); /* T7_PW: % asleep * 1000 + % at 12 MHz, since the start */
#ifdef T7_VOL
/* 1.6.12 test3: g_set.sound = volume 0 off, 1 quiet (as before), 2 medium, 3 loud (test5: maximal 1/2 was quieter than loud, gone) */
#define T7_VOL_N 4
void plat_vol(int v);
#endif
void plat_bat(char *s); /* BAT_SHOW: "2.84V 80%" (12 bytes) */ /* seconds counter, keeps running while switched off */
void plat_rect(int x0, int y0, int x1, int y1); /* start a rectangle on the screen */
void plat_row(const uint16_t *px, int n); /* pixels of the rectangle, row by row */
void plat_rect_end(void);
const uint8_t *plat_fig_ptr(int i); /* figure data (flash) */
/* App */
void app_init(const volatile T7Cfg *cfg);
void app_render(int force); /* draw what changed */
void app_text_screen(const char *line1, const char *line2, int progress, int total); /* simple message */
int app_keys(uint32_t buttons, uint32_t now_ms); /* buttons A=1 B=2 C=4 wheel=8 -> mask for the game (menu takes them) */
void app_tick(uint32_t now_ms); /* figure change in progress */
void app_clock(uint32_t rtc, int guard); /* keep the clock on the seconds counter (every 2 s) */
int app_catchup(uint32_t elapsed_s, void (*progress)(int done, int total)); /* after a pause: let the hours pass */
uint32_t app_save(uint8_t *buf, uint32_t cap); /* state for the flash (0 = too small) */
int app_load(const uint8_t *buf, uint32_t len, uint32_t *saved_rtc);
int app_menu_open(void);
int app_lang(void); /* 0 German, 1 English */
void app_setup_fill(uint32_t rtc); /* every 0.5 s: the game asks for the time, fill it in */
void app_store(void); /* settings and clock note into the flash (on leaving) */
extern uint32_t g_para_time, g_para_cnt; /* the Paradise's time at the start (platform), 0 = unknown */
int app_clock_hard(uint32_t rtc); /* settings flag 2: game clock = the Paradise's time (1 = done) */
#endif
+16
View File
@@ -0,0 +1,16 @@
/* Figur-ROMs (Figuren).
Werden zur Laufzeit von der SD-Karte in die figcache-Flash-Partition kopiert
und per esp_partition_mmap eingeblendet -- die Logik dazu steht in main.cpp.
Hier nur der aktive Zeiger + Laenge, die der Memory-Layer (t7_memory.c)
ueber figure_rom_ptr()/figure_rom_length() abfragt.
(Frueher lagen hier die 3 ~1.7MB grossen eingebetteten Arrays.) */
static const unsigned char* g_fig_ptr = 0;
static unsigned int g_fig_len = 0;
/* Von main.cpp aufgerufen, nachdem eine Figur in figcache gemappt wurde.
p=0, n=0 => keine Figur aktiv (Lite / Aus). */
void figure_rom_set_active(const unsigned char* p, unsigned int n){ g_fig_ptr = p; g_fig_len = n; }
const unsigned char* figure_rom_ptr(void){ return g_fig_ptr; }
unsigned int figure_rom_length(void){ return g_fig_len; }
+85
View File
@@ -0,0 +1,85 @@
/*
* pebble_compat.h - ESP32-C6 Variante des Pebble-API-Shims.
*
* Stellt exakt die Symbole bereit die der T7Emu-Emulator-Kern erwartet,
* damit t7.c / t7_cpu.c / t7_memory.c / t7_eeprom.c
* unveraendert kompilieren:
*
* - APP_LOG -> tama_log() (Serial/USB-CDC)
* - ResHandle + resource_* -> ROM aus LittleFS-Datei "/t7emu.bin"
* - persist_* -> NVS (Preferences), 16 Pages a 256 Byte
*
* Implementierung in pebble_compat.cpp (braucht C++ wegen LittleFS/Preferences).
* Header ist sowohl von C (Kern) als auch C++ (compat/main) inkludierbar.
*/
#ifndef PEBBLE_COMPAT_H
#define PEBBLE_COMPAT_H
#include <stdint.h>
#include <stddef.h>
#include <stdbool.h>
#ifdef T7_FREESTANDING
/* Paradise: no C library, only these from libc.c */
void *memset(void *d, int c, size_t n);
void *memcpy(void *d, const void *s, size_t n);
#else
#include <stdlib.h> // malloc/free (Core nutzt sie ueber diesen Header)
#include <string.h> // memset/memcpy/strncpy
#include <stdio.h> // snprintf
#include <time.h>
#endif
#ifdef __cplusplus
extern "C" {
#endif
// --- Logging --------------------------------------------------------------
#define APP_LOG_LEVEL_ERROR 0
#define APP_LOG_LEVEL_WARNING 1
#define APP_LOG_LEVEL_INFO 2
#define APP_LOG_LEVEL_DEBUG 3
void tama_log(const char *fmt, ...);
#define APP_LOG(level, fmt, ...) tama_log("[tama] " fmt "\n", ##__VA_ARGS__)
// --- Resource-API (ROM) ---------------------------------------------------
typedef int ResHandle;
// Vor t7_init() aufrufen. Pfad der ROM-Datei im LittleFS.
void t7_compat_set_rom_path(const char *path);
// Vor t7_init() aufrufen. NVS-Namespace fuer das Save-EEPROM.
void t7_compat_set_eeprom_path(const char *ns);
ResHandle resource_get_handle(int id);
size_t resource_size(ResHandle h);
size_t resource_load_byte_range(ResHandle h, size_t offset,
uint8_t *out, size_t len);
// Direktzeiger auf den memory-mapped ROM (XIP-Flash) oder NULL.
// Erlaubt zero-copy ROM-Banking (Page-Table zeigt direkt in den Flash).
const uint8_t *t7_compat_rom_mapped(void);
#define RESOURCE_ID_TAMA_ROM 1
// --- Persist-API (Save-EEPROM) --------------------------------------------
typedef int status_t;
#define S_SUCCESS 0
bool persist_exists(uint32_t key);
int persist_read_data(uint32_t key, void *buf, size_t size);
status_t persist_write_data(uint32_t key, const void *buf, size_t size);
status_t persist_delete(uint32_t key);
// Schreibt dirty Pages nach NVS. Periodisch + vor Sleep/Shutdown aufrufen.
void persist_flush_to_disk(void);
int persist_page_count(void);
int persist_page_size(void);
int persist_backup_page(int page, uint8_t *out);
void persist_restore_page(int page, const uint8_t *in);
#ifdef __cplusplus
}
#endif
#endif // PEBBLE_COMPAT_H
+435
View File
@@ -0,0 +1,435 @@
/*
* t7.c - top-level emulator integration
*
* Provides the public API declared in t7.h.
*/
#include "t7_internal.h"
#include "t7_eeprom.h"
#include "t7_sound.h"
#ifdef T7_FASTRUN
uint32_t t7_cpu_run(uint32_t budget);
#endif
// ----- Global state definitions ------------------------------------------
//
// Declared extern in t7_internal.h. Living as plain globals (rather
// than fields of a g_sys struct) lets the compiler resolve addresses at
// compile time and skip a pointer-indirection on every hot-path memory
// access. ~52 KB total, all in .bss.
cpu6502_t g_cpu;
uint8_t g_wram[T7_WRAM_SIZE];
uint8_t g_dram[T7_DRAM_SIZE];
uint8_t g_cpureg[T7_CPUREG_SIZE];
#if T7_PROFILE
// Profiling counters — see t7_internal.h. Plain global to let the
// linker resolve direct addresses (one less indirection vs a struct
// member access through a pointer).
t7_profile_t g_t7_profile;
#endif
uint8_t *g_rom_bank_buf = NULL; // malloc'd in t7_init
uint8_t *g_static_rom = NULL; // malloc'd in t7_init
uint16_t g_irq_vectors[16];
uint8_t g_irq_pending_any;
uint8_t g_rom_bank_id;
bool g_rom_loaded;
uint8_t g_keys;
ResHandle g_rom_resource;
bool g_initialised;
// ----- Init / Release -----------------------------------------------------
bool t7_init(void)
{
if (g_initialised) {
APP_LOG(APP_LOG_LEVEL_WARNING, "t7_init: already initialised");
return true;
}
// Allocate the big ROM caches on the heap. They have to live somewhere
// and putting them in .bss pushes us over Pebble's 16-bit virtual-size
// limit (65535 bytes). The heap on Emery has plenty of room.
#ifdef T7_NOMALLOC
/* Paradise: no heap. The banks are read straight from the mapped flash, only the
* static ROM is copied (16 KB in RAM). */
{ static uint8_t s_static[T7_STATIC_ROM_SIZE]; static uint8_t s_bank1[256];
g_static_rom = s_static; g_rom_bank_buf = s_bank1; }
#else
g_rom_bank_buf = (uint8_t *)malloc(T7_ROM_BANK_SIZE);
g_static_rom = (uint8_t *)malloc(T7_STATIC_ROM_SIZE);
#endif
#ifndef T7_NOMALLOC
if (!g_rom_bank_buf || !g_static_rom) {
APP_LOG(APP_LOG_LEVEL_ERROR,
"t7_init: out of memory (bank=%p static=%p)",
g_rom_bank_buf, g_static_rom);
if (g_rom_bank_buf) { free(g_rom_bank_buf); g_rom_bank_buf = NULL; }
if (g_static_rom) { free(g_static_rom); g_static_rom = NULL; }
return false;
}
#endif
memset(&g_cpu, 0, sizeof(g_cpu));
memset(g_wram, 0, sizeof(g_wram));
memset(g_dram, 0, sizeof(g_dram));
memset(g_cpureg, 0, sizeof(g_cpureg));
#ifndef T7_NOMALLOC
memset(g_rom_bank_buf, 0, T7_ROM_BANK_SIZE);
#endif
memset(g_static_rom, 0, T7_STATIC_ROM_SIZE);
g_keys = 0xFF;
g_rom_bank_id = 0xFF;
g_rom_loaded = false;
if (!t7_load_static_rom()) return false;
t7_idle_check();
t7_set_rom_bank(0);
t7_eeprom_init(); // load save data from persist
t7_cpu_reset();
g_initialised = true;
APP_LOG(APP_LOG_LEVEL_INFO,
"t7_init: ready, PC=$%04x", g_cpu.pc);
return true;
}
void t7_release(void)
{
// Flush any pending EEPROM writes back to persist before we tear down.
// Without this, save data written between the last STOP-after-WRITE
// and app exit would be lost.
t7_eeprom_flush();
#ifndef T7_NOMALLOC
if (g_rom_bank_buf) { free(g_rom_bank_buf); g_rom_bank_buf = NULL; }
if (g_static_rom) { free(g_static_rom); g_static_rom = NULL; }
#endif
g_initialised = false;
}
void t7_reset(void)
{
if (!g_initialised) return;
t7_cpu_reset();
}
// ----- Stepping -----------------------------------------------------------
uint8_t T7_HOT t7_step_one(void)
{
if (!g_initialised) return 0;
#ifdef T7_FASTRUN
return (uint8_t)t7_cpu_run(1);
#else
return t7_cpu_step();
#endif
}
/* Tamagotchi Friends: its frame tick comes from IRQ 3, every 122nd one (counter $55). Instead of
* 7.3 kHz of interrupts: at the video rate set the counter just below and fire IRQ 3 once. */
static inline void t7_friends_tick(void)
{
if (!g_t7_static_off) return;
if (g_wram[0x55] < 0x79) g_wram[0x55] = 0x79;
t7_fire_irq(3);
}
static uint32_t s_tbh_accumulator = 0;
#ifdef T7_TBH_RATE
/* 1.6.12 test2: the 2 Hz timer of the game clock in real time when the program runs the core slower than 4 MHz
* (Paradise: 3.03 MHz for the tempo): at 4 MHz cycles a game second lasted 1.32 s and the clock note jumped it ahead */
#define TBH_RATE (T7_TBH_RATE)
#else
#define TBH_RATE (T7_CLOCK_RATE / 2)
#endif
#ifdef T7_VIDEO_CYCLES
/* Paradise (as the ESP32 port): video IRQ at 60 Hz of emulated time, independent of how
* often and with how many cycles this is called. */
#define VIDEO_HZ 60
#define VIDEO_PERIOD_CYCLES (T7_CLOCK_RATE / VIDEO_HZ)
static uint32_t s_video_accumulator = 0;
uint32_t T7_HOT t7_step_cycles(uint32_t target_cycles)
{
if (!g_initialised) return 0;
uint32_t spent = 0;
while (spent < target_cycles) {
uint32_t step = target_cycles - spent;
uint32_t to_video = VIDEO_PERIOD_CYCLES - s_video_accumulator;
uint32_t to_tbh = TBH_RATE - s_tbh_accumulator;
if (to_video < step) step = to_video;
if (to_tbh < step) step = to_tbh;
if (step == 0) step = 1;
uint32_t did = 0;
#ifdef T7_FASTRUN
did = t7_cpu_run(step);
#else
if (g_snd_on) {
while (did < step) {
uint32_t c = t7_cpu_step();
did += c;
if ((g_snd_next -= (int32_t)c) <= 0) t7_snd_service();
}
} else {
while (did < step) did += t7_cpu_step();
}
#endif
spent += did;
s_video_accumulator += did;
if (s_video_accumulator >= VIDEO_PERIOD_CYCLES) {
s_video_accumulator -= VIDEO_PERIOD_CYCLES;
t7_fire_irq(10);
t7_fire_nmi(6);
t7_friends_tick();
}
s_tbh_accumulator += did;
if (s_tbh_accumulator >= TBH_RATE) {
s_tbh_accumulator -= TBH_RATE;
t7_fire_irq(13);
}
}
if (g_snd_on) t7_snd_flush();
#ifdef T7_STOP_KEYACT
g_t7_keyact = g_t7_keyact > spent ? g_t7_keyact - spent : 0;
#endif
return spent;
}
#else
// "Video" IRQ/NMI fire rate.
//
// On real V7 hardware these are driven by the LCD controller, which
// runs at roughly 60 Hz. We step the emulator 20× per second, so we need
// to fire 3 sub-frames worth of NMI/IRQ per call to match the rate the
// ROM expects.
//
// Symptoms when this is wrong: the Tama's clock runs slow because the
// game counts video frames to measure real time (e.g. "60 frames = 1
// second"). At 20 Hz it would clock at 1/3 speed.
#define VIDEO_FIRES_PER_FRAME 3
uint32_t T7_HOT t7_step_cycles(uint32_t target_cycles)
{
if (!g_initialised) return 0;
// Split the requested cycles into VIDEO_FIRES_PER_FRAME chunks so the
// ROM sees the video interrupt at roughly the hardware rate.
uint32_t per_chunk = target_cycles / VIDEO_FIRES_PER_FRAME;
uint32_t spent = 0;
for (int chunk = 0; chunk < VIDEO_FIRES_PER_FRAME; chunk++) {
t7_fire_irq(10);
t7_fire_nmi(6);
t7_friends_tick();
uint32_t chunk_target = (chunk == VIDEO_FIRES_PER_FRAME - 1)
? target_cycles // last chunk takes the rest
: (spent + per_chunk);
if (g_snd_on) {
while (spent < chunk_target) {
uint32_t c = t7_cpu_step();
spent += c;
if ((g_snd_next -= (int32_t)c) <= 0) t7_snd_service();
}
} else {
while (spent < chunk_target) {
spent += t7_cpu_step();
}
}
}
if (g_snd_on) t7_snd_flush();
// 2 Hz timer (IRQ 13) — the "TBH" counter that drives the game's
// real-time clock. Independent of the video IRQ rate.
s_tbh_accumulator += spent;
while (s_tbh_accumulator >= TBH_RATE) {
t7_fire_irq(13);
s_tbh_accumulator -= TBH_RATE;
}
return spent;
}
#endif
// ----- Display ------------------------------------------------------------
static const uint16_t LCD_ROW_OFFSETS[31] = {
0x0C0, 0x0CC, 0x0D8, 0x0E4,
0x0F0, 0x0FC, 0x108, 0x114,
0x120, 0x12C, 0x138, 0x144,
0x150, 0x15C, 0x168, 0x174,
0x0B4, 0x0A8, 0x09C, 0x090,
0x084, 0x078, 0x06C, 0x060,
0x054, 0x048, 0x03C, 0x030,
0x024, 0x018, 0x00C,
};
void t7_get_display(uint8_t *out)
{
if (!g_initialised || !out) return;
for (int y = 0; y < T7_LCD_HEIGHT; y++) {
uint16_t base = LCD_ROW_OFFSETS[y] % T7_DRAM_SIZE;
for (int x = 0; x < T7_LCD_WIDTH; x += 4) {
uint8_t d = g_dram[base++];
out[y * T7_LCD_WIDTH + x + 0] = (d >> 6) & 0x3;
out[y * T7_LCD_WIDTH + x + 1] = (d >> 4) & 0x3;
out[y * T7_LCD_WIDTH + x + 2] = (d >> 2) & 0x3;
out[y * T7_LCD_WIDTH + x + 3] = (d >> 0) & 0x3;
}
}
}
// Icon extraction matches the refresh_simple loop in t7emu/main.js:
// var a=4, b=0, g=0;
// while (g<10) { glyph = (dram[a] >> b) & 3; if ((b-=2)<0){b=6;a++;} ... }
//
// Walking the loop manually gives the table below. Two bits per icon,
// four icons per byte, 10 icons total across 4 bytes (DRAM[4..7]) — but
// only the first 2 bits of DRAM[4] and first 2 bits of DRAM[7] are used.
void t7_get_icons(uint8_t *out)
{
if (!g_initialised || !out) return;
out[0] = (g_dram[4] >> 0) & 0x3; // dashboard
out[1] = (g_dram[5] >> 6) & 0x3; // food
out[2] = (g_dram[5] >> 4) & 0x3; // trash
out[3] = (g_dram[5] >> 2) & 0x3; // globe
out[4] = (g_dram[5] >> 0) & 0x3; // user
out[5] = (g_dram[6] >> 6) & 0x3; // comments
out[6] = (g_dram[6] >> 4) & 0x3; // medkit
out[7] = (g_dram[6] >> 2) & 0x3; // heart
out[8] = (g_dram[6] >> 0) & 0x3; // book
out[9] = (g_dram[7] >> 6) & 0x3; // bell
}
// ----- Buttons ------------------------------------------------------------
void t7_set_buttons(uint8_t mask)
{
if (!g_initialised) return;
uint8_t lo = ~mask & 0x0F;
// Obere Bits MUESSEN 0 bleiben (wie in der Referenz: this.keys = 0xF).
// Frueher stand hier "| 0xF0", was die Figur-Bits (Bit 5-7 in PortA) komplett
// maskiert hat -> die Firmware konnte eine gesteckte Figur nie erkennen.
#ifdef T7_STOP
#ifdef T7_STOP_KEYACT
if (lo != g_keys) g_t7_keyact = T7_STOP_KEYACT;
#endif
if (g_t7_halted && (lo & 0x07) != 0x07 && (g_cpureg[0x07] & 0x01)) { g_cpureg[0x08] |= 0x01; g_t7_halted = 0; }
#endif
g_keys = lo;
}
// ----- WRAM direct access (used by RTC sync) ------------------------------
uint8_t t7_ram_read(uint16_t addr)
{
if (!g_initialised) return 0;
if (addr >= T7_WRAM_SIZE) return 0;
return g_wram[addr];
}
void t7_ram_write(uint16_t addr, uint8_t val)
{
if (!g_initialised) return;
if (addr >= T7_WRAM_SIZE) return;
g_wram[addr] = val;
}
// ----- Debug --------------------------------------------------------------
void t7_debug_get_state(uint16_t *pc, uint8_t *a, uint8_t *x, uint8_t *y,
uint8_t *s, uint8_t *bank)
{
if (!g_initialised) return;
if (pc) *pc = g_cpu.pc;
if (a) *a = g_cpu.a;
if (x) *x = g_cpu.x;
if (y) *y = g_cpu.y;
if (s) *s = g_cpu.s;
if (bank) *bank = g_rom_bank_id;
}
bool t7_debug_dram_dirty(void)
{
if (!g_initialised) return false;
for (int i = 0; i < T7_DRAM_SIZE; i++) if (g_dram[i]) return true;
return false;
}
uint16_t t7_debug_dram_nonzero_count(void)
{
if (!g_initialised) return 0;
uint16_t n = 0;
for (int i = 0; i < T7_DRAM_SIZE; i++) if (g_dram[i]) n++;
return n;
}
// ----- Save state ---------------------------------------------------------
#define T7_SAVE_MAGIC 0x54414D47
#define T7_SAVE_VERSION 1
#define T7_SAVE_SIZE \
(4 + 4 + sizeof(cpu6502_t) + \
T7_CPUREG_SIZE + T7_WRAM_SIZE + T7_DRAM_SIZE + 1 + 1)
uint32_t t7_serialize_state(uint8_t *buf, uint32_t bufsize)
{
if (!buf || bufsize < T7_SAVE_SIZE) return T7_SAVE_SIZE;
if (!g_initialised) return 0;
uint8_t *p = buf;
uint32_t magic = T7_SAVE_MAGIC;
memcpy(p, &magic, 4); p += 4;
*p++ = T7_SAVE_VERSION;
*p++ = 0; *p++ = 0; *p++ = 0;
memcpy(p, &g_cpu, sizeof(cpu6502_t)); p += sizeof(cpu6502_t);
memcpy(p, g_cpureg, T7_CPUREG_SIZE); p += T7_CPUREG_SIZE;
memcpy(p, g_wram, T7_WRAM_SIZE); p += T7_WRAM_SIZE;
memcpy(p, g_dram, T7_DRAM_SIZE); p += T7_DRAM_SIZE;
*p++ = g_rom_bank_id;
*p++ = g_keys;
return (uint32_t)(p - buf);
}
bool t7_deserialize_state(const uint8_t *buf, uint32_t bufsize)
{
if (!buf || bufsize < T7_SAVE_SIZE || !g_initialised) return false;
const uint8_t *p = buf;
uint32_t magic;
memcpy(&magic, p, 4); p += 4;
if (magic != T7_SAVE_MAGIC) return false;
uint8_t version = *p++;
if (version != T7_SAVE_VERSION) return false;
p += 3;
memcpy(&g_cpu, p, sizeof(cpu6502_t)); p += sizeof(cpu6502_t);
memcpy(g_cpureg, p, T7_CPUREG_SIZE); p += T7_CPUREG_SIZE;
memcpy(g_wram, p, T7_WRAM_SIZE); p += T7_WRAM_SIZE;
memcpy(g_dram, p, T7_DRAM_SIZE); p += T7_DRAM_SIZE;
uint8_t saved_bank = *p++;
g_keys = *p++;
g_irq_pending_any = (g_cpureg[0x73] | g_cpureg[0x74]) != 0;
t7_set_rom_bank(saved_bank);
t7_snd_resync();
return true;
}
void t7_profile_snapshot_and_reset(t7_profile_snapshot_t *out)
{
#if T7_PROFILE
if (out) {
out->opcodes = g_t7_profile.opcodes;
out->reads_fast = g_t7_profile.reads_fast;
out->reads_io = g_t7_profile.reads_io;
out->writes_fast = g_t7_profile.writes_fast;
out->writes_io = g_t7_profile.writes_io;
out->writes_dropped = g_t7_profile.writes_dropped;
out->irqs = g_t7_profile.irqs;
out->nmis = g_t7_profile.nmis;
out->irq_entries = g_t7_profile.irq_entries;
out->nmi_entries = g_t7_profile.nmi_entries;
}
memset(&g_t7_profile, 0, sizeof(g_t7_profile));
#else
if (out) memset(out, 0, sizeof(*out));
#endif
}
+178
View File
@@ -0,0 +1,178 @@
/*
* t7.h - V7 emulator core (6502), urspruenglich fuer Pebble
*
* Based on asterick/tamago (JavaScript implementation):
* https://github.com/asterick/tamago
*
* Hardware: GPLB52320A (8-bit 6502-family) @ 4 MHz
* Display: 64x32 pixels, 4 grayscale levels (512 bytes DRAM)
*
* Memory map (16-bit address space, banked):
* $0000-$0FFF Work RAM (1.5 KB, mirrored)
* $1000-$2FFF Display RAM (512 bytes, mirrored)
* $3000-$3FFF CPU control registers
* $4000-$BFFF Banked ROM (32 KB window, 20 banks total = 640 KB)
* $C000-$FFFF Static ROM (16 KB, always mapped from bank 0)
*
* The 640 KB ROM lives in Pebble flash as a resource. To save RAM we
* only keep the currently-selected bank (32 KB) mirrored in memory.
* Static ROM (bank 0, first 16 KB) is loaded once at boot.
*/
#ifndef T7_H
#define T7_H
#include "pebble_compat.h"
// Compile-time profile switch. Set to 1 to enable per-opcode / per-read /
// per-write counters (logged once a minute from main.c). Adds ~10-15%
// CPU overhead — keep OFF in production.
#define T7_PROFILE 0
// Display dimensions (native V7 hardware).
//
// The display is 48 pixels wide × 31 pixels high — this comes from the
// HTML template in the JS reference (canvas width=48 height=31). Although
// the hardware has 64 segments × 32 commons, the addressing scheme in
// _dram only gives meaningful pixels in the first 48 of each row; the
// remaining 16 are aliased into the start of the next row's bytes.
// The JS emulator handles this by drawing into a 48-px-wide canvas — the
// 16 "extra" pixels per row spill into the next row and get overwritten.
// In our C port we just clamp to 48 explicitly.
#define T7_LCD_WIDTH 48
#define T7_LCD_HEIGHT 31
// 4 grayscale levels per pixel (2 bits each)
#define T7_PALETTE_SIZE 4
// CPU clock rate (Hz)
#define T7_CLOCK_RATE 4000000
// Memory region sizes
#define T7_WRAM_SIZE 0x600 // 1.5 KB work RAM
#define T7_DRAM_SIZE 0x200 // 512 B display RAM
#define T7_CPUREG_SIZE 0x100 // 256 B control registers
#define T7_ROM_BANK_SIZE 0x8000 // 32 KB per bank
#define T7_STATIC_ROM_SIZE 0x4000 // 16 KB static (high) ROM
// Status flag bits in P register
#define FLAG_C 0x01 // Carry
#define FLAG_Z 0x02 // Zero
#define FLAG_I 0x04 // Interrupt disable
#define FLAG_D 0x08 // Decimal mode
#define FLAG_B 0x10 // Break (software)
#define FLAG_U 0x20 // Unused (always 1)
#define FLAG_V 0x40 // Overflow
#define FLAG_N 0x80 // Negative
// Button bitmask (V7 has 3 buttons: A, B, C plus reset)
#define T7_BTN_A 0x01
#define T7_BTN_B 0x02
#define T7_BTN_C 0x04
#define T7_BTN_RESET 0x08
// Forward declaration for the system state
typedef struct t7_system t7_system_t;
// Public API ---------------------------------------------------------------
// Initialize the emulator. Must be called once at startup. Returns false on
// failure (e.g. ROM resource missing).
bool t7_init(void);
/* After t7_init: 1 = Tamagotchi Friends ROM (768 KB), 0 = Tama-Go. */
int t7_is_friends(void);
uint16_t t7_rtc_sec_addr(void);
// Reset the CPU (jumps to the reset vector). Memory and EEPROM are preserved.
void t7_reset(void);
// Run the emulator for the given number of CPU cycles. Returns the actual
// number of cycles consumed (may differ slightly due to instruction lengths).
uint32_t t7_step_cycles(uint32_t target_cycles);
// Run a single instruction. Returns the cycle count of that instruction.
uint8_t t7_step_one(void);
// Read the current display state. Pixels are 2 bits each (0..3 = grayscale
// level). `out` must be at least T7_LCD_WIDTH * T7_LCD_HEIGHT bytes.
void t7_get_display(uint8_t *out);
// Number of status icons surrounding the main display. Layout (matching
// asterick/tamago):
// Top row: 0 dashboard, 1 food, 2 trash, 3 globe, 4 user
// Bottom row: 5 comments, 6 medkit, 7 heart, 8 book, 9 bell
#define T7_ICON_COUNT 10
// Read the 10 status icon values into `out` (length T7_ICON_COUNT).
// Each byte is a 2-bit intensity (0 = off, 1..3 = visible grayscale).
void t7_get_icons(uint8_t *out);
// --- Figur / SPI-Trace (Reverse-Engineering, Etappe 1) ---
void t7_figure_set(uint8_t id);
uint8_t t7_figure_get(void);
void t7_spi_set_ret(uint8_t v);
void t7_spitrace_arm(void);
void t7_irtrace_arm(void);
int t7_spitrace_count(void);
void t7_spitrace_get(int i, uint8_t *kind, uint8_t *reg, uint8_t *val, uint16_t *rep);
// Set the button state. `mask` is a bitmask of T7_BTN_* constants.
// Bits set = button pressed.
void t7_set_buttons(uint8_t mask);
// IR-BLE-Bridge: 32-Byte-Paket fuer die naechste Empfangsanfrage einspeisen
// (umgeht das IR-Physical-Layer). Aus BLE-Callback oder Test-Trigger aufrufen.
void t7_ir_bridge_rx(const uint8_t *pkt32);
void t7_ir_bridge_enable(int on); // Bridge ein/aus (TX-Completion-Fake)
int t7_ir_bridge_tx_poll(uint8_t *out32); // 1 = neues Sende-Paket in out32
uint32_t t7_ir_activity(void); // steigt im IR-Verbindungsmenue
int t7_ir_tx_take(uint8_t *out32); // T7_LINK (1.6.9): packet sent just now ($748E), 32 = new packet in out32
int t7_ir_tx_pending(void); // 1 = Firmware wartet auf Sende-Completion
void t7_ir_tx_complete(void); // Sende-Completion ausloesen (zeitverzoegert)
// Tear down the emulator and free resources.
void t7_release(void);
// Debug: return current CPU state for logging. Fills the passed-in pointers
// (any of which may be NULL) with the current register values.
void t7_debug_get_state(uint16_t *pc, uint8_t *a, uint8_t *x, uint8_t *y,
uint8_t *s, uint8_t *bank);
// Debug: return whether any dram bytes are non-zero. If the ROM hasn't
// touched the display at all, all dram = 0 and the screen appears uniform.
bool t7_debug_dram_dirty(void);
// Debug: count how many DRAM bytes are non-zero (0..512).
uint16_t t7_debug_dram_nonzero_count(void);
// State serialization for save/restore. Returns total size needed when
// `buf` is NULL or `bufsize` is too small; otherwise the number of bytes
// actually written.
uint32_t t7_serialize_state(uint8_t *buf, uint32_t bufsize);
bool t7_deserialize_state(const uint8_t *buf, uint32_t bufsize);
// Direct WRAM read/write. Used by the RTC sync code to poke the
// emulator's internal time counters. `addr` must be in the 0x0000-0x0FFF
// WRAM range — addresses outside that range are silently ignored.
uint8_t t7_ram_read(uint16_t addr);
void t7_ram_write(uint16_t addr, uint8_t val);
// Profiling — snapshot + reset the hot-path counters. Used by main.c
// to print a per-minute profile of where emulator time is going.
// Returns the snapshot via out-params. Pass NULL to skip retrieval.
typedef struct {
uint32_t opcodes;
uint32_t reads_fast;
uint32_t reads_io;
uint32_t writes_fast;
uint32_t writes_io;
uint32_t writes_dropped;
uint32_t irqs;
uint32_t nmis;
uint32_t irq_entries;
uint32_t nmi_entries;
} t7_profile_snapshot_t;
void t7_profile_snapshot_and_reset(t7_profile_snapshot_t *out);
#endif // T7_H
+885
View File
@@ -0,0 +1,885 @@
/*
* t7_cpu.c - 6502 CPU emulator for V7
*
* Port of asterick/tamago's JavaScript 6502 core to C. The original code:
* src/cpu/6502.js — fetch loop, IRQ, NMI, reset
* src/cpu/address.js — 13 addressing modes
* src/cpu/operations.js — 56 instruction implementations
* src/data/instructions.js — 256-entry opcode dispatch table
*
* Differences from the JS original:
* - Flags stored as separate booleans (c, z, i, d, v, n) matching the
* JS style. Slightly slower than packed P-register but readable.
* - Opcode dispatch is a switch instead of a function-pointer table.
* ARM's compiler turns dense switches into branch tables, which is
* fast and saves the indirect-call overhead.
* - Addressing modes are inlined as macros where it makes sense, to
* avoid function-call overhead in the inner loop.
*
* The CPU calls into t7_read / t7_write (defined in
* t7_memory.c) for every memory access.
*/
#include "t7_internal.h"
// Pebble's default -Os is wrong for this file — every static-inline op_*
// and addressing-mode helper benefits from -O2 unrolling/inlining. We
// don't apply it via per-function attribute because the inline helpers
// are called from multiple places; a file-level pragma covers them all.
#pragma GCC optimize ("O2")
// Convenience pointers to cut down on g_sys-> noise in this file.
#define CPU g_cpu
// Status-flag fields, stored as separate uint8_t for clarity. Non-zero
// means set; the actual bit values don't matter as long as we use them
// consistently. The packed P register is only assembled on PHP/RTI etc.
//
// We keep them inside cpu6502_t.p as packed bits because that's simpler
// for serialization. Accessor macros pack/unpack as needed.
//
// NOTE: We pack/unpack on every flag set/get. To avoid that overhead,
// we keep a *separate* flag set in static variables here and only sync
// to cpu.p when push/pull/reset/etc. needs it. This matches the JS
// original which has separate cpu.c/cpu.z/... fields.
// NZ flags stored lazily as byte values.
// N flag: (s_nz_n & 0x80) != 0 — bit 7 of the last "N source"
// Z flag: s_nz_z == 0 — last "Z source" was zero
//
// Two bytes (not one) because BIT and PLP can set N and Z from
// independent sources (e.g. BIT: N from v[7], Z from (A & v) == 0).
// Storing just one byte loses the N=1+Z=1 case that BIT routinely
// produces, which breaks branches after BIT — exactly the path the
// Tama firmware uses to test status bits.
//
// set_nz (the common case) updates both with the same value, which the
// compiler may even fuse into a single 16-bit store.
static uint8_t s_nz_n; // value whose bit 7 is the N flag
static uint8_t s_nz_z; // value whose zero-ness is the Z flag
static uint8_t s_flag_v; // Overflow
static uint8_t s_flag_d; // Decimal
static uint8_t s_flag_i; // IRQ disable
static uint8_t s_flag_c; // Carry
// Pack the six flags into a P-register byte. Bits 4 (B) and 5 (U) are
// the "always set" pair on push; we set them here too.
static inline uint8_t pack_p(void)
{
return (s_flag_c ? 0x01 : 0) |
((s_nz_z == 0) ? 0x02 : 0) |
(s_flag_i ? 0x04 : 0) |
(s_flag_d ? 0x08 : 0) |
0x20 |
(s_flag_v ? 0x40 : 0) |
(s_nz_n & 0x80);
}
// Unpack a P-register byte into the flags. N and Z are restored
// independently into their respective lazy bytes.
static inline void unpack_p(uint8_t p)
{
s_flag_c = p & 0x01;
s_flag_i = p & 0x04;
s_flag_d = p & 0x08;
s_flag_v = p & 0x40;
s_nz_n = (p & 0x80) ? 0x80 : 0; // N flag → bit 7 of s_nz_n
s_nz_z = (p & 0x02) ? 0 : 1; // Z flag → s_nz_z == 0
}
// Hot path — called by ~35% of opcodes. Two byte stores, no computes.
// The compiler may fuse these into a single 16-bit halfword store if
// s_nz_n and s_nz_z are adjacent in memory (they are).
static inline void set_nz(uint8_t v)
{
s_nz_n = v;
s_nz_z = v;
}
// ----- Stack operations ---------------------------------------------------
static inline void push(uint8_t v)
{
t7_write(0x0100 | CPU.s, v);
CPU.s = (CPU.s - 1) & 0xFF;
}
static inline uint8_t pull(void)
{
CPU.s = (CPU.s + 1) & 0xFF;
return t7_read(0x0100 | CPU.s);
}
// ----- Fetch operations ---------------------------------------------------
static inline uint8_t fetch(void)
{
uint8_t d = t7_read(CPU.pc);
CPU.pc = (CPU.pc + 1) & 0xFFFF;
return d;
}
static inline uint16_t fetch16(void)
{
uint8_t l = fetch();
uint8_t h = fetch();
return l | (h << 8);
}
// ----- IRQ / NMI / Reset --------------------------------------------------
void t7_cpu_reset(void)
{
CPU.a = 0;
CPU.x = 0;
CPU.y = 0;
CPU.s = 0xFF; // initial stack pointer; some 6502 conventions use 0xFF
s_nz_n = 0; // N=0
s_nz_z = 1; // Z=0 (non-zero)
s_flag_v = 0;
s_flag_d = 0;
s_flag_i = 1; // IRQs masked at reset
s_flag_c = 0;
CPU.p = pack_p();
// Reset vector at $FFFC
CPU.pc = t7_read16(0xFFFC);
}
void t7_cpu_nmi(void)
{
PROFILE_INC(nmi_entries);
push(CPU.pc >> 8);
push(CPU.pc & 0xFF);
push(pack_p());
CPU.pc = t7_read16(0xFFFA);
}
// IRQ entry: `brk` is true for BRK (software interrupt), which sets the
// B flag in the pushed P register but doesn't affect the running flags.
// IRQ dispatch via the priority-encoded vector happens in t7_memory.c.
static void cpu_irq_internal(bool brk)
{
push(CPU.pc >> 8);
push(CPU.pc & 0xFF);
push(pack_p() | (brk ? 0x10 : 0));
// For BRK, jump to the standard IRQ vector at $FFFE. For hardware IRQs
// we use the priority-encoded vector; see t7_cpu_irq below.
CPU.pc = t7_read16(0xFFFE);
s_flag_i = 1;
}
void t7_cpu_irq(void)
{
PROFILE_INC(irq_entries);
// Hardware IRQ: look up the highest-priority pending bit in
// cpureg[$73:$74] (16-bit) and jump to the corresponding vector.
// The vector indices are 0..15; index 0 is highest priority.
uint16_t pending = (g_cpureg[0x73] << 8) | g_cpureg[0x74];
if (!pending) return;
// Find highest set bit (0..15) via count-leading-zeros.
// __builtin_clz operates on 32-bit values; we shift to align bit 15
// of `pending` to bit 31 of the input so the result is the bit index
// (0 = bit 15 of pending = highest priority).
int idx = __builtin_clz((uint32_t)pending << 16);
// idx is now 0..15 where 0 = bit 15 of pending was set.
push(CPU.pc >> 8);
push(CPU.pc & 0xFF);
push(pack_p());
CPU.pc = g_irq_vectors[idx];
s_flag_i = 1;
// The ROM's IRQ handler will write to $3074 to clear the pending bit
// (which our io_write_int_flag refreshes g_irq_pending_any from). But
// for safety, refresh here too — covers cases where the cache might
// be out of sync.
g_irq_pending_any = (g_cpureg[0x73] | g_cpureg[0x74]) != 0;
}
// ----- Addressing mode resolvers ------------------------------------------
//
// Each resolver returns the effective address for the operation. For
// implied/accumulator modes there is no memory address — the operations
// that use these modes don't dereference the returned value.
static inline uint16_t addr_implied(void) { return 0; }
static inline uint16_t addr_accumulator(void){ return 0; }
static inline uint16_t addr_immediate(void) { uint16_t a = CPU.pc; CPU.pc = (CPU.pc+1) & 0xFFFF; return a; }
static inline uint16_t addr_zeropage(void) { return fetch(); }
static inline uint16_t addr_zeropageX(void) { return (fetch() + CPU.x) & 0xFF; }
static inline uint16_t addr_zeropageY(void) { return (fetch() + CPU.y) & 0xFF; }
static inline uint16_t addr_absolute(void) { return fetch16(); }
static inline uint16_t addr_absoluteX(void) { return (fetch16() + CPU.x) & 0xFFFF; }
static inline uint16_t addr_absoluteY(void) { return (fetch16() + CPU.y) & 0xFFFF; }
static inline uint16_t addr_relative(void) {
// Sign-extend the 8-bit offset.
int8_t offset = (int8_t)fetch();
return (CPU.pc + offset) & 0xFFFF;
}
static inline uint16_t addr_indirect(void) {
// Classic 6502 page-wrap bug: the high byte read wraps within the
// same page as the low byte. (See: JMP ($xxFF) doesn't cross the page.)
uint16_t ptr = fetch16();
uint8_t lo = t7_read(ptr);
uint8_t hi = t7_read((ptr & 0xFF00) | ((ptr + 1) & 0x00FF));
return lo | (hi << 8);
}
static inline uint16_t addr_indirectX(void) {
uint8_t zp = (fetch() + CPU.x) & 0xFF;
uint8_t lo = t7_read(zp);
uint8_t hi = t7_read((zp + 1) & 0xFF);
return lo | (hi << 8);
}
static inline uint16_t addr_indirectY(void) {
uint8_t zp = fetch();
uint8_t lo = t7_read(zp);
uint8_t hi = t7_read((zp + 1) & 0xFF);
return ((lo | (hi << 8)) + CPU.y) & 0xFFFF;
}
// ----- Instruction implementations ----------------------------------------
//
// Each instruction takes the effective address `addr`. For
// implied/accumulator-mode ops `addr` is ignored.
static inline void op_LDA(uint16_t addr) { CPU.a = t7_read(addr); set_nz(CPU.a); }
static inline void op_LDX(uint16_t addr) { CPU.x = t7_read(addr); set_nz(CPU.x); }
static inline void op_LDY(uint16_t addr) { CPU.y = t7_read(addr); set_nz(CPU.y); }
static inline void op_STA(uint16_t addr) { t7_write(addr, CPU.a); }
static inline void op_STX(uint16_t addr) { t7_write(addr, CPU.x); }
static inline void op_STY(uint16_t addr) { t7_write(addr, CPU.y); }
static inline void op_TAX(void) { CPU.x = CPU.a; set_nz(CPU.x); }
static inline void op_TAY(void) { CPU.y = CPU.a; set_nz(CPU.y); }
static inline void op_TXA(void) { CPU.a = CPU.x; set_nz(CPU.a); }
static inline void op_TYA(void) { CPU.a = CPU.y; set_nz(CPU.a); }
static inline void op_TSX(void) { CPU.x = CPU.s; set_nz(CPU.x); }
static inline void op_TXS(void) { CPU.s = CPU.x; }
static inline void op_INX(void) { CPU.x = (CPU.x + 1) & 0xFF; set_nz(CPU.x); }
static inline void op_INY(void) { CPU.y = (CPU.y + 1) & 0xFF; set_nz(CPU.y); }
static inline void op_DEX(void) { CPU.x = (CPU.x - 1) & 0xFF; set_nz(CPU.x); }
static inline void op_DEY(void) { CPU.y = (CPU.y - 1) & 0xFF; set_nz(CPU.y); }
static inline void op_INC(uint16_t addr) {
uint8_t v = (t7_read(addr) + 1) & 0xFF;
set_nz(v);
t7_write(addr, v);
}
static inline void op_DEC(uint16_t addr) {
uint8_t v = (t7_read(addr) - 1) & 0xFF;
set_nz(v);
t7_write(addr, v);
}
static inline void op_AND(uint16_t addr) { CPU.a &= t7_read(addr); set_nz(CPU.a); }
static inline void op_ORA(uint16_t addr) { CPU.a |= t7_read(addr); set_nz(CPU.a); }
static inline void op_EOR(uint16_t addr) { CPU.a ^= t7_read(addr); set_nz(CPU.a); }
static inline void op_BIT(uint16_t addr) {
uint8_t v = t7_read(addr);
s_flag_v = v & 0x40;
s_nz_n = v; // N from v[7]
s_nz_z = CPU.a & v; // Z from (A & v) == 0
}
// Shifts: when `acc` is true, operate on accumulator (addr ignored).
// We keep ASL/LSR/ROL/ROR as two variants — *_acc for accumulator,
// regular for memory.
static inline void op_ASL_mem(uint16_t addr) {
uint8_t d = t7_read(addr);
uint8_t o = (d << 1) & 0xFF;
s_flag_c = d & 0x80;
set_nz(o);
t7_write(addr, o);
}
static inline void op_ASL_acc(void) {
uint8_t o = (CPU.a << 1) & 0xFF;
s_flag_c = CPU.a & 0x80;
CPU.a = o;
set_nz(o);
}
static inline void op_LSR_mem(uint16_t addr) {
uint8_t d = t7_read(addr);
uint8_t o = d >> 1;
s_flag_c = d & 0x01;
set_nz(o);
t7_write(addr, o);
}
static inline void op_LSR_acc(void) {
uint8_t o = CPU.a >> 1;
s_flag_c = CPU.a & 0x01;
CPU.a = o;
set_nz(o);
}
static inline void op_ROL_mem(uint16_t addr) {
uint8_t d = t7_read(addr);
uint8_t o = ((d << 1) & 0xFF) | (s_flag_c ? 1 : 0);
s_flag_c = d & 0x80;
set_nz(o);
t7_write(addr, o);
}
static inline void op_ROL_acc(void) {
uint8_t o = ((CPU.a << 1) & 0xFF) | (s_flag_c ? 1 : 0);
s_flag_c = CPU.a & 0x80;
CPU.a = o;
set_nz(o);
}
static inline void op_ROR_mem(uint16_t addr) {
uint8_t d = t7_read(addr);
uint8_t o = (d >> 1) | (s_flag_c ? 0x80 : 0);
s_flag_c = d & 0x01;
set_nz(o);
t7_write(addr, o);
}
static inline void op_ROR_acc(void) {
uint8_t o = (CPU.a >> 1) | (s_flag_c ? 0x80 : 0);
s_flag_c = CPU.a & 0x01;
CPU.a = o;
set_nz(o);
}
// ADC/SBC: full implementation including decimal mode (matches JS original
// exactly). Most ROMs don't use decimal mode but we include it for safety.
static inline void op_ADC(uint16_t addr) {
uint8_t data = t7_read(addr);
uint16_t o = CPU.a + data + (s_flag_c ? 1 : 0);
// Overflow: same sign in A and data, different sign in result
s_flag_v = (~(CPU.a ^ data) & (CPU.a ^ o)) & 0x80;
set_nz(o & 0xFF);
if (s_flag_d) {
int al = (CPU.a & 0x0F) + (data & 0x0F) + (s_flag_c ? 1 : 0);
int ah = (CPU.a & 0xF0) + (data & 0xF0) + ((al >= 0x10) ? 0x10 : 0);
if (al > 0x09) al += 0x06;
if (ah > 0x90) ah += 0x60;
o = (al & 0x0F) + ah;
}
s_flag_c = (o > 0xFF) ? 1 : 0;
CPU.a = o & 0xFF;
}
static inline void op_SBC(uint16_t addr) {
uint8_t data = t7_read(addr);
int o = CPU.a - data - (s_flag_c ? 0 : 1);
s_flag_v = ((CPU.a ^ data) & (CPU.a ^ o)) & 0x80;
set_nz(o & 0xFF);
s_flag_c = (o >= 0) ? 1 : 0;
if (s_flag_d) {
int al = (CPU.a & 0x0F) - (data & 0x0F) - (s_flag_c ? 0 : 1);
int ah = (CPU.a & 0xF0) - (data & 0xF0) - ((al < 0) ? 0x10 : 0);
if (al < 0) al -= 0x06;
if (ah < 0) ah -= 0x60;
o = (al & 0x0F) + ah;
}
CPU.a = o & 0xFF;
}
static inline void op_CMP(uint16_t addr) {
uint8_t d = t7_read(addr);
s_flag_c = CPU.a >= d;
set_nz((CPU.a - d) & 0xFF);
}
static inline void op_CPX(uint16_t addr) {
uint8_t d = t7_read(addr);
s_flag_c = CPU.x >= d;
set_nz((CPU.x - d) & 0xFF);
}
static inline void op_CPY(uint16_t addr) {
uint8_t d = t7_read(addr);
s_flag_c = CPU.y >= d;
set_nz((CPU.y - d) & 0xFF);
}
// Flag operations
static inline void op_CLC(void) { s_flag_c = 0; }
static inline void op_SEC(void) { s_flag_c = 1; }
static inline void op_CLI(void) { s_flag_i = 0; }
static inline void op_SEI(void) { s_flag_i = 1; }
static inline void op_CLV(void) { s_flag_v = 0; }
static inline void op_CLD(void) { s_flag_d = 0; }
static inline void op_SED(void) { s_flag_d = 1; }
// Stack ops
static inline void op_PHA(void) { push(CPU.a); }
static inline void op_PLA(void) { CPU.a = pull(); set_nz(CPU.a); }
static inline void op_PHP(void) { push(pack_p() | 0x10); }
static inline void op_PLP(void) { unpack_p(pull()); }
// Jumps & branches
static inline void op_JMP(uint16_t addr) { CPU.pc = addr; }
static inline void op_JSR(uint16_t addr) {
// PC has already advanced past the 2-byte operand; push PC-1.
uint16_t r = (CPU.pc - 1) & 0xFFFF;
push(r >> 8);
push(r & 0xFF);
CPU.pc = addr;
}
static inline void op_RTS(void) {
uint8_t l = pull();
uint8_t h = pull();
CPU.pc = ((l | (h << 8)) + 1) & 0xFFFF;
}
static inline void op_RTI(void) {
unpack_p(pull());
uint8_t l = pull();
uint8_t h = pull();
CPU.pc = l | (h << 8);
}
static inline void op_BRK(void) {
CPU.pc = (CPU.pc + 1) & 0xFFFF;
cpu_irq_internal(true);
}
// Branch instructions take a relative offset and only jump if the
// condition is true.
#define BRANCH(cond) do { uint16_t a = addr_relative(); if (cond) CPU.pc = a; } while (0)
// ----- Main step function -------------------------------------------------
//
// Returns the cycle count of the executed instruction. The cycles table
// is generated from instructions.js — for unimplemented opcodes (illegal
// instructions on standard 6502) we return 2 and log a warning.
// Cycle counts indexed by opcode. Generated from data/instructions.js.
// 0 = illegal/unimplemented.
static const uint8_t opcode_cycles[256] = {
[0x00] = 7, [0x01] = 6, [0x05] = 3, [0x06] = 5, [0x08] = 3, [0x09] = 2,
[0x0A] = 2, [0x0D] = 4, [0x0E] = 6, [0x10] = 2, [0x11] = 5, [0x15] = 4,
[0x16] = 6, [0x18] = 2, [0x19] = 4, [0x1D] = 4, [0x1E] = 7, [0x20] = 6,
[0x21] = 6, [0x24] = 3, [0x25] = 3, [0x26] = 5, [0x28] = 4, [0x29] = 2,
[0x2A] = 2, [0x2C] = 4, [0x2D] = 4, [0x2E] = 6, [0x30] = 2, [0x31] = 5,
[0x35] = 4, [0x36] = 6, [0x38] = 2, [0x39] = 4, [0x3D] = 4, [0x3E] = 7,
[0x40] = 6, [0x41] = 6, [0x45] = 3, [0x46] = 5, [0x48] = 3, [0x49] = 2,
[0x4A] = 2, [0x4C] = 3, [0x4D] = 4, [0x4E] = 6, [0x50] = 2, [0x51] = 5,
[0x55] = 4, [0x56] = 6, [0x58] = 2, [0x59] = 4, [0x5D] = 4, [0x5E] = 7,
[0x60] = 6, [0x61] = 6, [0x65] = 3, [0x66] = 5, [0x68] = 4, [0x69] = 2,
[0x6A] = 2, [0x6C] = 5, [0x6D] = 4, [0x6E] = 6, [0x70] = 2, [0x71] = 5,
[0x75] = 4, [0x76] = 6, [0x78] = 2, [0x79] = 4, [0x7D] = 4, [0x7E] = 7,
[0x81] = 6, [0x84] = 3, [0x85] = 3, [0x86] = 3, [0x88] = 2, [0x8A] = 2,
[0x8C] = 4, [0x8D] = 4, [0x8E] = 4, [0x90] = 2, [0x91] = 6, [0x94] = 4,
[0x95] = 4, [0x96] = 4, [0x98] = 2, [0x99] = 5, [0x9A] = 2, [0x9D] = 5,
[0xA0] = 2, [0xA1] = 6, [0xA2] = 2, [0xA4] = 3, [0xA5] = 3, [0xA6] = 3,
[0xA8] = 2, [0xA9] = 2, [0xAA] = 2, [0xAC] = 4, [0xAD] = 4, [0xAE] = 4,
[0xB0] = 2, [0xB1] = 5, [0xB4] = 4, [0xB5] = 4, [0xB6] = 4, [0xB8] = 2,
[0xB9] = 4, [0xBA] = 2, [0xBC] = 4, [0xBD] = 4, [0xBE] = 4, [0xC0] = 2,
[0xC1] = 6, [0xC4] = 3, [0xC5] = 3, [0xC6] = 5, [0xC8] = 2, [0xC9] = 2,
[0xCA] = 2, [0xCC] = 4, [0xCD] = 4, [0xCE] = 6, [0xD0] = 2, [0xD1] = 5,
[0xD5] = 4, [0xD6] = 6, [0xD8] = 2, [0xD9] = 4, [0xDD] = 4, [0xDE] = 7,
[0xE0] = 2, [0xE1] = 6, [0xE4] = 3, [0xE5] = 3, [0xE6] = 5, [0xE8] = 2,
[0xE9] = 2, [0xEA] = 2, [0xEC] = 4, [0xED] = 4, [0xEE] = 6, [0xF0] = 2,
[0xF1] = 5, [0xF5] = 4, [0xF6] = 6, [0xF8] = 2, [0xF9] = 4, [0xFD] = 4,
[0xFE] = 7,
};
#ifdef T7_JIT
const uint8_t *const t7_opcode_cycles = opcode_cycles;
#endif
// `hot` attribute tells GCC this is a frequently-called function — it
// optimises it more aggressively (inlining decisions, branch ordering)
// and places it in a hot code section for better i-cache behaviour.
// Pebble builds with -Os by default (size-optimized). For this interpreter
// hot-loop -O2 unrolls the addressing mode inlines and the switch much
// better — measurably faster. Apply just to this function so we don't
// pay code-size cost elsewhere.
// === IR-BLE-Bridge: Paket-Inject-Trap ============================================
// Umgeht das gesamte IR-Physical-Layer (Carrier/Praeambel/Bit-Timing). Ein per
// BLE empfangenes 32-Byte-Paket wird direkt in den Empfangspuffer $0200 gelegt,
// die Receive-Routine ($72D0, gerufen bei $60C4) uebersprungen. Die Firmware
// validiert + verarbeitet das Paket nativ. Validiert: erzeugt "CONNECT".
static uint8_t s_ir_rx_pkt[32];
static volatile int s_ir_rx_pending = 0;
static volatile int s_ir_bridge_en = 0; // Bridge aktiv? (gated Completion-Fake)
static volatile uint32_t s_ir_activity = 0; // zaehlt $60C4-Polls (Verbindungsmenue aktiv)
static volatile int s_ir_tx_pending = 0; // Firmware wartet auf Sende-Completion ($7926)
// TX-Completion: main.cpp pollt _pending und loest _complete zeitverzoegert aus
// (mimt die echte IR-Sendedauer ~150 ms -> Sende-Loop rast nicht).
int t7_ir_tx_pending(void) { return s_ir_tx_pending; }
void t7_ir_tx_complete(void) { g_wram[0xA3] &= ~0x80; s_ir_tx_pending = 0; }
// Aktivitaetszaehler: steigt, solange die Firmware im IR-Verbindungsmenue ist.
uint32_t t7_ir_activity(void) { return s_ir_activity; }
// Aus dem Funk-Callback (oder Test-Trigger) aufrufen: Paket fuer die naechste
// Empfangsanfrage bereitstellen. Genau 32 Bytes erwartet.
void t7_ir_bridge_rx(const uint8_t *pkt32) {
for (int i = 0; i < 32; i++) s_ir_rx_pkt[i] = pkt32[i];
s_ir_rx_pending = 1;
}
// Bridge ein/aus: schaltet den TX-Completion-Fake ($7926) frei, damit der
// Sende-Deadlock nicht haengt. Im Normalbetrieb AUS (IR-Verhalten unveraendert).
void t7_ir_bridge_enable(int on) { s_ir_bridge_en = on; }
// TX-Capture: liefert das Sende-Paket aus $0220, wenn es gueltig (byte0&0F==2)
// und seit dem letzten Poll geaendert ist. 1 = neues Paket in out[32].
#ifdef T7_FREESTANDING
__attribute__((minsize))
#endif
int t7_ir_bridge_tx_poll(uint8_t *out) {
static uint8_t last[32];
if ((g_wram[0x220] & 0x0F) != 2) return 0;
int diff = 0;
for (int i = 0; i < 32; i++) if (g_wram[0x220 + i] != last[i]) diff = 1;
if (!diff) return 0;
for (int i = 0; i < 32; i++) { last[i] = g_wram[0x220 + i]; out[i] = last[i]; }
if (out[31] == 0) { int s = 0; for (int i = 0; i < 31; i++) s += out[i]; out[31] = (uint8_t)(s & 0xFF); }
return 1;
}
#ifdef T7_LINK
/* 1.6.9: the packet as it is sent. $748E (bank 3) sends $32 bytes from $0220 by switching the infrared LED ($3016
* bit 3): it sets $32 and $5B to minus the count, sends a preamble, then the bytes ($32 counts up). Taken at the
* first LED switch-on of the preamble ($32 == $5B): watching $0220 lost a packet the same as the last one (the game
* sends again when there is no answer). Outside the hot loop: t7_io_write calls t7_ir_led_on. */
static uint8_t s_ir_tx_pkt[32], s_ir_tx_n, s_ir_in;
void t7_ir_led_on(void)
{
if (g_rom_bank_id != 3 || g_t7_static_off) return;
if (g_wram[0x32] != g_wram[0x5B] || !g_wram[0x32]) { s_ir_in = 0; return; } /* bytes going out, or done */
if (s_ir_in || (g_wram[0x220] & 0x0F) != 2) return;
s_ir_in = 1;
/* as 32 bytes like t7_ir_bridge_tx_poll (the receive side gives the firmware 32 bytes, the sum in the last) */
uint8_t n = (uint8_t)(0u - g_wram[0x32]); if (n > 32) n = 32;
int sum = 0;
for (int i = 0; i < 32; i++) { uint8_t v = i < n ? g_wram[0x220 + i] : 0; s_ir_tx_pkt[i] = v; if (i < 31) sum += v; }
if (!s_ir_tx_pkt[31]) s_ir_tx_pkt[31] = (uint8_t)sum;
s_ir_tx_n = 32;
}
int t7_ir_tx_take(uint8_t *out) { int n = s_ir_tx_n; if (!n) return 0; for (int i = 0; i < 32; i++) out[i] = s_ir_tx_pkt[i]; s_ir_tx_n = 0; return n; }
#endif
#ifndef T7_FASTRUN
uint8_t T7_HOT t7_cpu_step(void) __attribute__((hot, optimize("O2")));
uint8_t t7_cpu_step(void)
{
PROFILE_INC(opcodes);
// IR-Bridge-Hooks: nur in Bank 3 (IR/Verbindung) ueberhaupt relevant. EIN
// Bank-Check vorne -> im Normalbetrieb (andere Bank) genau EIN Vergleich pro
// Instruktion statt sechs. Hot path (~4M Instr/s) -> spart spuerbar Emu-Zeit.
if (g_rom_bank_id == 3 && !g_t7_static_off) { /* Tama-Go only */
if (CPU.pc == 0x60C4) {
// $60C4 = IR-Empfangsanfrage (JSR $72D0). Wird nur im Verbindungsmenue/
// STAND BY gepollt -> Zaehler fuer Auto-Aktivierung der Bridge.
s_ir_activity++;
// RX-Bridge: bereitgestelltes Paket einspeisen, echte Receive-Routine
// ueberspringen.
if (s_ir_rx_pending) {
for (int i = 0; i < 32; i++) g_wram[0x200 + i] = s_ir_rx_pkt[i];
g_wram[0x5A] = 0x20; // Byte-Zaehler = 32 (sonst von Receive gesetzt)
g_wram[0x01B2] = 0x20;
CPU.a = 0x80; // Rueckgabe "Paket empfangen"
s_nz_z = 0x80; // Z = 0 (A != 0)
s_flag_c = 0; // C = 0 -> Handler nimmt den Verarbeitungspfad
CPU.pc = 0x60C7; // JSR $72D0 ueberspringen
s_ir_rx_pending = 0;
}
} else if (s_ir_bridge_en && CPU.pc == 0x7926) {
// TX-Bridge: Firmware will senden (Busy-Wait auf $A3 bit7). Flag setzen;
// main.cpp loest die Completion zeitverzoegert aus (~echte IR-Sendedauer).
s_ir_tx_pending = 1;
}
}
// Fire pending IRQs before fetching the next instruction.
// Fast path: a single byte cache flag, updated by t7_fire_irq and
// io_write_int_flag. Avoids reading cpureg[$73:$74] on every step.
if (g_irq_pending_any && !s_flag_i) {
t7_cpu_irq();
}
uint8_t opcode = fetch();
uint8_t cycles = opcode_cycles[opcode];
// Big switch dispatch. The compiler turns this into a branch table on
// ARM since the cases are dense. Each case computes the addressing
// mode (inline) and calls the instruction implementation.
switch (opcode) {
// --- LDA ---
case 0xA9: op_LDA(addr_immediate()); break;
case 0xA5: op_LDA(addr_zeropage()); break;
case 0xB5: op_LDA(addr_zeropageX()); break;
case 0xAD: op_LDA(addr_absolute()); break;
case 0xBD: op_LDA(addr_absoluteX()); break;
case 0xB9: op_LDA(addr_absoluteY()); break;
case 0xA1: op_LDA(addr_indirectX()); break;
case 0xB1: op_LDA(addr_indirectY()); break;
// --- LDX ---
case 0xA2: op_LDX(addr_immediate()); break;
case 0xA6: op_LDX(addr_zeropage()); break;
case 0xB6: op_LDX(addr_zeropageY()); break;
case 0xAE: op_LDX(addr_absolute()); break;
case 0xBE: op_LDX(addr_absoluteY()); break;
// --- LDY ---
case 0xA0: op_LDY(addr_immediate()); break;
case 0xA4: op_LDY(addr_zeropage()); break;
case 0xB4: op_LDY(addr_zeropageX()); break;
case 0xAC: op_LDY(addr_absolute()); break;
case 0xBC: op_LDY(addr_absoluteX()); break;
// --- STA ---
case 0x85: op_STA(addr_zeropage()); break;
case 0x95: op_STA(addr_zeropageX()); break;
case 0x8D: op_STA(addr_absolute()); break;
case 0x9D: op_STA(addr_absoluteX()); break;
case 0x99: op_STA(addr_absoluteY()); break;
case 0x81: op_STA(addr_indirectX()); break;
case 0x91: op_STA(addr_indirectY()); break;
// --- STX/STY ---
case 0x86: op_STX(addr_zeropage()); break;
case 0x96: op_STX(addr_zeropageY()); break;
case 0x8E: op_STX(addr_absolute()); break;
case 0x84: op_STY(addr_zeropage()); break;
case 0x94: op_STY(addr_zeropageX()); break;
case 0x8C: op_STY(addr_absolute()); break;
// --- Transfers ---
case 0xAA: op_TAX(); break;
case 0xA8: op_TAY(); break;
case 0x8A: op_TXA(); break;
case 0x98: op_TYA(); break;
case 0xBA: op_TSX(); break;
case 0x9A: op_TXS(); break;
// --- INC/DEC register ---
case 0xE8: op_INX(); break;
case 0xC8: op_INY(); break;
case 0xCA: op_DEX(); break;
case 0x88: op_DEY(); break;
// --- INC/DEC memory ---
case 0xE6: op_INC(addr_zeropage()); break;
case 0xF6: op_INC(addr_zeropageX()); break;
case 0xEE: op_INC(addr_absolute()); break;
case 0xFE: op_INC(addr_absoluteX()); break;
case 0xC6: op_DEC(addr_zeropage()); break;
case 0xD6: op_DEC(addr_zeropageX()); break;
case 0xCE: op_DEC(addr_absolute()); break;
case 0xDE: op_DEC(addr_absoluteX()); break;
// --- Logical ---
case 0x29: op_AND(addr_immediate()); break;
case 0x25: op_AND(addr_zeropage()); break;
case 0x35: op_AND(addr_zeropageX()); break;
case 0x2D: op_AND(addr_absolute()); break;
case 0x3D: op_AND(addr_absoluteX()); break;
case 0x39: op_AND(addr_absoluteY()); break;
case 0x21: op_AND(addr_indirectX()); break;
case 0x31: op_AND(addr_indirectY()); break;
case 0x09: op_ORA(addr_immediate()); break;
case 0x05: op_ORA(addr_zeropage()); break;
case 0x15: op_ORA(addr_zeropageX()); break;
case 0x0D: op_ORA(addr_absolute()); break;
case 0x1D: op_ORA(addr_absoluteX()); break;
case 0x19: op_ORA(addr_absoluteY()); break;
case 0x01: op_ORA(addr_indirectX()); break;
case 0x11: op_ORA(addr_indirectY()); break;
case 0x49: op_EOR(addr_immediate()); break;
case 0x45: op_EOR(addr_zeropage()); break;
case 0x55: op_EOR(addr_zeropageX()); break;
case 0x4D: op_EOR(addr_absolute()); break;
case 0x5D: op_EOR(addr_absoluteX()); break;
case 0x59: op_EOR(addr_absoluteY()); break;
case 0x41: op_EOR(addr_indirectX()); break;
case 0x51: op_EOR(addr_indirectY()); break;
case 0x24: op_BIT(addr_zeropage()); break;
case 0x2C: op_BIT(addr_absolute()); break;
// --- Shifts ---
case 0x0A: op_ASL_acc(); break;
case 0x06: op_ASL_mem(addr_zeropage()); break;
case 0x16: op_ASL_mem(addr_zeropageX()); break;
case 0x0E: op_ASL_mem(addr_absolute()); break;
case 0x1E: op_ASL_mem(addr_absoluteX()); break;
case 0x4A: op_LSR_acc(); break;
case 0x46: op_LSR_mem(addr_zeropage()); break;
case 0x56: op_LSR_mem(addr_zeropageX()); break;
case 0x4E: op_LSR_mem(addr_absolute()); break;
case 0x5E: op_LSR_mem(addr_absoluteX()); break;
case 0x2A: op_ROL_acc(); break;
case 0x26: op_ROL_mem(addr_zeropage()); break;
case 0x36: op_ROL_mem(addr_zeropageX()); break;
case 0x2E: op_ROL_mem(addr_absolute()); break;
case 0x3E: op_ROL_mem(addr_absoluteX()); break;
case 0x6A: op_ROR_acc(); break;
case 0x66: op_ROR_mem(addr_zeropage()); break;
case 0x76: op_ROR_mem(addr_zeropageX()); break;
case 0x6E: op_ROR_mem(addr_absolute()); break;
case 0x7E: op_ROR_mem(addr_absoluteX()); break;
// --- Arithmetic ---
case 0x69: op_ADC(addr_immediate()); break;
case 0x65: op_ADC(addr_zeropage()); break;
case 0x75: op_ADC(addr_zeropageX()); break;
case 0x6D: op_ADC(addr_absolute()); break;
case 0x7D: op_ADC(addr_absoluteX()); break;
case 0x79: op_ADC(addr_absoluteY()); break;
case 0x61: op_ADC(addr_indirectX()); break;
case 0x71: op_ADC(addr_indirectY()); break;
case 0xE9: op_SBC(addr_immediate()); break;
case 0xE5: op_SBC(addr_zeropage()); break;
case 0xF5: op_SBC(addr_zeropageX()); break;
case 0xED: op_SBC(addr_absolute()); break;
case 0xFD: op_SBC(addr_absoluteX()); break;
case 0xF9: op_SBC(addr_absoluteY()); break;
case 0xE1: op_SBC(addr_indirectX()); break;
case 0xF1: op_SBC(addr_indirectY()); break;
// --- Compares ---
case 0xC9: op_CMP(addr_immediate()); break;
case 0xC5: op_CMP(addr_zeropage()); break;
case 0xD5: op_CMP(addr_zeropageX()); break;
case 0xCD: op_CMP(addr_absolute()); break;
case 0xDD: op_CMP(addr_absoluteX()); break;
case 0xD9: op_CMP(addr_absoluteY()); break;
case 0xC1: op_CMP(addr_indirectX()); break;
case 0xD1: op_CMP(addr_indirectY()); break;
case 0xE0: op_CPX(addr_immediate()); break;
case 0xE4: op_CPX(addr_zeropage()); break;
case 0xEC: op_CPX(addr_absolute()); break;
case 0xC0: op_CPY(addr_immediate()); break;
case 0xC4: op_CPY(addr_zeropage()); break;
case 0xCC: op_CPY(addr_absolute()); break;
// --- Flags ---
case 0x18: op_CLC(); break;
case 0x38: op_SEC(); break;
case 0x58: op_CLI(); break;
case 0x78: op_SEI(); break;
case 0xB8: op_CLV(); break;
case 0xD8: op_CLD(); break;
case 0xF8: op_SED(); break;
// --- Stack ---
case 0x48: op_PHA(); break;
case 0x68: op_PLA(); break;
case 0x08: op_PHP(); break;
case 0x28: op_PLP(); break;
// --- Jumps ---
case 0x4C: op_JMP(addr_absolute()); break;
case 0x6C: op_JMP(addr_indirect()); break;
case 0x20: op_JSR(addr_absolute()); break;
case 0x60: op_RTS(); break;
case 0x40: op_RTI(); break;
case 0x00: op_BRK(); break;
// --- Branches ---
case 0x10: BRANCH(!(s_nz_n & 0x80)); break; // BPL
case 0x30: BRANCH( (s_nz_n & 0x80)); break; // BMI
case 0x50: BRANCH(!s_flag_v); break; // BVC
case 0x70: BRANCH( s_flag_v); break; // BVS
case 0x90: BRANCH(!s_flag_c); break; // BCC
case 0xB0: BRANCH( s_flag_c); break; // BCS
case 0xD0: BRANCH(s_nz_z != 0); break; // BNE
case 0xF0: BRANCH(s_nz_z == 0); break; // BEQ
// --- NOP and illegal ---
case 0xEA: /* NOP */ break;
default:
// Illegal/undefined opcode. The standard NMOS 6502 has many of
// these but the JS emulator throws on encountering them. We log
// and treat as NOP so we don't crash mid-game on a ROM glitch.
APP_LOG(APP_LOG_LEVEL_WARNING,
"t7_cpu: illegal opcode 0x%02x at PC=$%04x",
opcode, (CPU.pc - 1) & 0xFFFF);
cycles = 2;
break;
}
return cycles;
}
#endif
uint8_t t7_dbg_p(void) { return pack_p(); }
/* ---- 1.6.9 (test12) battery, taken over from TamaGo-Pebble v0.3.0 (tamago_cpu_idle_skip) ----
* The Tama-Go main loop waits at $CE66: JSR to 5 seed routines ($D2ED + 8 i: LDA $C4+i, CLC, ADC #k, STA $C4+i, RTS),
* LDA $2D, BEQ $CE66. Until an interrupt nothing ends it, so whole passes are added up at once: seeds + n k, the
* stack slots of the last JSR, A = 0, flags as after the last pass. Checked against the ROM bytes at the start
* (other ROMs, e.g. Friends: off). */
uint8_t g_t7_idle_ok, g_t7_halted;
#ifdef T7_JSR_HLE
/* 1.6.12 test1 (battery, Tama-Go only, checked against the ROM bytes): bit 0 the delay $D460 (LDX #$D1, INX/BNE 47
* times, RTS) done at once when it ends inside the run (the same state and cycles as interpreted); bit 1 the sprite
* blit $E4CD left out while g_t7_dark is set (the screen is off: nothing to see; the picture comes back with the
* next frame, the game state is the same apart from the random seeds) */
uint8_t g_t7_hle, g_t7_dark;
#if defined(T7_WAKE_FRESH) || defined(T7_DARK_PEEK)
uint32_t g_t7_blits;
#endif
#ifdef T7_BLIT_CACHE
/* 1.7.3 test24 T7_BLIT_CACHE: the blit may only be left out if its time passes as well. The main loop waits for the frame
* flag $2D (set by the frame IRQ); a blit takes long enough that the flag is often set already when the loop gets there.
* Without that time the game ran differently and counted no care mistakes. So a blit is run once for each set of its
* inputs (sprite pointer, bank, position and mode bytes) and its cycles are noted; with the screen off a known blit is
* left out and its cycles pass. Measured without JIT (also across runs); the cycles of IRQs inside do not count. */
#define BC_N 128u
typedef struct { uint8_t k[12]; uint32_t cyc; } T7BC;
static T7BC g_bc[BC_N];
uint32_t g_bc_hit, g_bc_miss;
static struct { uint32_t on, sp, ret, jit, slot, irq; int32_t start, irq0, irqc; uint8_t k[12]; } g_bm;
static struct { uint32_t rem, pc, sp; } g_bs; /* a left out blit: its cycles still to pass (an IRQ may come in between, as inside the blit) */ /* start, irq0: cycles of this run (may be < 0: an earlier run) */
static inline int bc_same(const uint8_t *a, const uint8_t *b) { for (int i = 0; i < 12; i++) if (a[i] != b[i]) return 0; return 1; }
static inline void bc_copy(uint8_t *d, const uint8_t *s) { for (int i = 0; i < 12; i++) d[i] = s[i]; }
static uint32_t bc_key(uint8_t *k)
{
k[0] = g_wram[0x6D]; k[1] = g_wram[0x6E]; k[2] = g_wram[0x6F]; k[3] = g_rom_bank_id;
for (int i = 0; i < 6; i++) k[4 + i] = g_wram[0x80 + i];
k[10] = g_wram[0x84]; k[11] = 1; /* never all zero (empty slot) */
uint32_t h = 2166136261u; for (int i = 0; i < 12; i++) h = (h ^ k[i]) * 16777619u;
return (h ^ (h >> 16)) & (BC_N - 1u);
}
#endif
#endif
uint32_t g_t7_idle_cyc, g_t7_keyact; /* keyact: cycles left without STOP after a key changed (T7_STOP_KEYACT) */
static const uint8_t IDLE_SIG[19] = { 0x20,0xED,0xD2, 0x20,0xF5,0xD2, 0x20,0xFD,0xD2, 0x20,0x05,0xD3, 0x20,0x0D,0xD3, 0xA5,0x2D, 0xF0,0xED };
static const uint8_t IDLE_ADD[5] = { 0x07, 0x03, 0x0D, 0x17, 0x13 };
#ifdef T7_FREESTANDING
__attribute__((minsize))
#endif
void t7_idle_check(void)
{
g_t7_idle_ok = 0; g_t7_halted = 0;
#ifdef T7_IDLE
if (!g_static_rom) return;
for (int i = 0; i < 19; i++) if (g_static_rom[T7_IDLE_PC - 0xC000u + i] != IDLE_SIG[i]) return;
for (int i = 0; i < 5; i++) {
const uint8_t *r = &g_static_rom[0xD2ED - 0xC000 + i * 8];
if (r[0] != 0xA5 || r[1] != 0xC4 + i || r[2] != 0x18 || r[3] != 0x69 || r[4] != IDLE_ADD[i] || r[5] != 0x85 || r[6] != 0xC4 + i || r[7] != 0x60) return;
}
g_t7_idle_ok = 1;
#endif
#ifdef T7_JSR_HLE
g_t7_hle = 0;
if (!g_static_rom || g_t7_static_off) return; /* Tama-Go only */
static const uint8_t DLY[6] = { 0xA2,0xD1, 0xE8, 0xD0,0xFD, 0x60 };
static const uint8_t BLT[19] = { 0xA5,0x84, 0x85,0x88, 0xA5,0x6D, 0x85,0x79, 0xA5,0x6E, 0x85,0x7A, 0xA5,0x6F, 0x85,0x7B, 0x20,0xF1,0xE5 };
int ok = 1; for (int i = 0; i < 6; i++) if (g_static_rom[0xD460 - 0xC000 + i] != DLY[i]) ok = 0;
if (ok) g_t7_hle |= 1u;
ok = 1; for (int i = 0; i < 19; i++) if (g_static_rom[0xE4CD - 0xC000 + i] != BLT[i]) ok = 0;
#if !defined(T7_NOBLIT_SKIP) || defined(T7_BLIT_CACHE)
if (ok) g_t7_hle |= 2u;
#endif
/* 1.7.3 test23 T7_NOBLIT_SKIP: the blit is run with the screen off as well. Left out, the game no longer counted
* care mistakes (a hungry pet whose call ran out with the screen off: none counted, it grew up as with full care). */
#endif
}
#ifdef T7_IDLE
/* passes that fit in budget cycles (pc at $CE66, no IRQ to take: checked by the caller); returns the cycles */
static uint32_t t7_idle_pass_cyc(void)
{
return 5u * (opcode_cycles[0x20] + opcode_cycles[0xA5] + opcode_cycles[0x18] + opcode_cycles[0x69] + opcode_cycles[0x85] + opcode_cycles[0x60])
+ opcode_cycles[0xA5] + opcode_cycles[0xF0];
}
#endif
#ifdef T7_JIT
#include "t7_jit.h"
#endif
#include "t7_run.inc"
+255
View File
@@ -0,0 +1,255 @@
/*
* t7_eeprom.c - emulated 4 KB I²C EEPROM backed by Pebble persist
*
* Faithful port of asterick/tamago src/cpu/eeprom.js. The state
* machine, command set, and bit timing all match exactly so save data
* written by the JS emulator could in principle be loaded here and vice
* versa.
*
* Persistence layout: the 4 KB EEPROM is split into 16 pages of 256
* bytes each, stored in Pebble persist keys EEPROM_PERSIST_BASE +
* page_index. Pebble's persist storage supports up to 256 bytes per key
* and ~4 KB total per app, which is exactly enough.
*
* Pages are loaded on init. Writes are batched: we set a dirty bit per
* page and only push to persist when t7_eeprom_flush() is called,
* or when an I²C STOP after a WRITE command commits the data. Persist
* writes are slow (flash-backed) so batching matters.
*/
#include "t7_eeprom.h"
#include "pebble_compat.h"
#ifndef T7_FREESTANDING
#include <string.h>
#endif
#define EEPROM_BIT_WIDTH 12
#define EEPROM_SIZE (1 << EEPROM_BIT_WIDTH) // 4096
#define EEPROM_MASK (EEPROM_SIZE - 1)
#define EEPROM_ADDR_BYTES 2 // ceil(12/8)
#define EEPROM_PAGE_SIZE 256
#define EEPROM_PAGE_COUNT (EEPROM_SIZE / EEPROM_PAGE_SIZE) // 16
#define EEPROM_PERSIST_BASE 100u // persist keys 100..115 reserved for us
// State machine — values match JS eeprom.js
typedef enum {
ST_DISABLED = 0,
ST_COMMAND = 1,
ST_ADDRESS = 2,
ST_READ = 3,
ST_WRITE = 4,
} eeprom_state_t;
static uint8_t s_data[EEPROM_SIZE]; // 4 KB in .bss
static uint16_t s_dirty; // bit N set ⇒ page N needs flush
// I²C bus state
static eeprom_state_t s_state;
static uint8_t s_output;
static uint8_t s_last_clk;
static uint8_t s_last_data;
// Transfer state
static uint8_t s_read; // 8-bit shift register (bit being assembled)
static uint8_t s_bits_tx; // bit counter within byte (0..8, 8 = ACK)
static uint16_t s_address; // current address pointer (12 bits)
static uint8_t s_addressbyte; // how many address bytes have we received
// ----- Persistence -------------------------------------------------------
void t7_eeprom_init(void)
{
// Initial bus state: power off, output high (NACK)
s_state = ST_DISABLED;
s_output = 1;
s_last_clk = 0;
s_last_data = 0;
s_read = 0;
s_bits_tx = 0;
s_address = 0;
s_addressbyte = 0;
s_dirty = 0;
// Load saved pages from persist. Missing pages stay zero-filled (the
// Tama firmware treats blank EEPROM as "first boot, run init").
memset(s_data, 0, sizeof(s_data));
int loaded_bytes = 0;
for (int p = 0; p < EEPROM_PAGE_COUNT; p++) {
uint32_t key = EEPROM_PERSIST_BASE + p;
if (persist_exists(key)) {
int n = persist_read_data(key, &s_data[p * EEPROM_PAGE_SIZE],
EEPROM_PAGE_SIZE);
if (n > 0) loaded_bytes += n;
}
}
APP_LOG(APP_LOG_LEVEL_INFO,
"t7_eeprom: loaded %d bytes from persist",
loaded_bytes);
}
void t7_eeprom_flush(void)
{
if (!s_dirty) return;
int pages_written = 0;
for (int p = 0; p < EEPROM_PAGE_COUNT; p++) {
if (s_dirty & (1u << p)) {
uint32_t key = EEPROM_PERSIST_BASE + p;
status_t st = persist_write_data(key,
&s_data[p * EEPROM_PAGE_SIZE],
EEPROM_PAGE_SIZE);
if (st >= 0) {
s_dirty &= ~(1u << p);
pages_written++;
} else {
APP_LOG(APP_LOG_LEVEL_ERROR,
"t7_eeprom: persist_write_data key=%u failed (%d)",
(unsigned)key, (int)st);
// Leave the dirty bit set so we retry next time.
}
}
}
if (pages_written > 0) {
APP_LOG(APP_LOG_LEVEL_INFO,
"t7_eeprom: flushed %d page(s)", pages_written);
}
}
void t7_eeprom_wipe(void)
{
// Clear all 4 KB of EEPROM in-memory + delete all persisted pages.
// The Tama firmware will see "blank" EEPROM on the next boot and
// start fresh (egg-select screen).
memset(s_data, 0, sizeof(s_data));
s_dirty = 0;
for (int p = 0; p < EEPROM_PAGE_COUNT; p++) {
uint32_t key = EEPROM_PERSIST_BASE + p;
persist_delete(key);
}
APP_LOG(APP_LOG_LEVEL_INFO,
"t7_eeprom: wiped (in-memory + persist)");
}
uint8_t t7_eeprom_output(void)
{
return s_output;
}
// ----- Bus state machine -------------------------------------------------
//
// Translated 1:1 from eeprom.js update(power, clk, data).
void t7_eeprom_update(uint8_t power, uint8_t clk, uint8_t data)
{
clk = clk ? 1 : 0;
data = data ? 1 : 0;
int clk_d = (int)clk - (int)s_last_clk;
int data_d = (int)data - (int)s_last_data;
s_last_clk = clk;
s_last_data = data;
// No power → chip idle, NACK on the bus.
if (!power) {
s_state = ST_DISABLED;
s_output = 1;
return;
}
// No bus change → no work.
if (!clk_d && !data_d) return;
// Data transition while CLK high = START/STOP condition.
if (clk && data_d) {
if (data_d > 0) {
// STOP condition. The page was marked dirty when we received the
// last write byte; the actual persist_write_data() flush is
// deferred to the periodic timer in main.c (every 60s) plus
// t7_release() on app exit. Persist writes are flash-backed
// (~10 ms each) and the ROM does dense write bursts during boot
// and save points — flushing eagerly here drops the emulator
// throughput by ~50% on heavy-write phases.
s_state = ST_DISABLED;
s_output = 0;
} else {
// START condition.
s_state = ST_COMMAND;
s_output = 0;
s_bits_tx = 0;
s_read = 0;
}
}
// If we ended up disabled (no active transfer), nothing more to do.
if (s_state == ST_DISABLED) return;
if (clk_d > 0) {
// Rising edge: sample data line into shift register (host → device).
s_read = (uint8_t)((s_read << 1) | data);
} else if (clk_d < 0) {
// Falling edge: drive next output bit (device → host) OR ACK.
if (s_bits_tx < 8) {
// Mid-byte: drive output bit if we're in READ mode, else high.
if (s_state == ST_READ) {
s_output = ((s_data[s_address] << s_bits_tx) & 0x80) ? 1 : 0;
} else {
s_output = 1;
}
} else if (s_bits_tx == 8) {
// Byte boundary: send ACK and process the byte we just received.
s_output = 0; // ACK
switch (s_state) {
case ST_COMMAND:
// I²C EEPROM address pattern. 0xA0/0xA1 = Atmel 24Cxx family
// device address with R/W bit; the chip ignores the middle
// bits hence the 0xF1 mask.
switch (s_read & 0xF1) {
case 0xA0: // Write command
s_state = ST_ADDRESS;
s_addressbyte = 0;
s_address = 0;
break;
case 0xA1: // Read command
s_state = ST_READ;
break;
default:
s_output = 1; // NACK
break;
}
break;
case ST_ADDRESS:
s_address = (uint16_t)((s_address << 8) | s_read);
if (++s_addressbyte >= EEPROM_ADDR_BYTES) {
s_state = ST_WRITE;
s_address &= EEPROM_MASK;
}
break;
case ST_WRITE: {
uint16_t addr = s_address & EEPROM_MASK;
s_data[addr] = s_read;
#ifdef T7_EEDBG
{ extern void t7_eedbg(uint16_t, uint8_t); t7_eedbg(addr, s_read); }
#endif
// Mark page dirty for the next flush.
s_dirty |= (1u << (addr / EEPROM_PAGE_SIZE));
s_address = (s_address + 1) & EEPROM_MASK;
break;
}
case ST_READ:
// Address pointer auto-increments on read too — matches
// 24Cxx sequential-read behaviour.
s_address = (s_address + 1) & EEPROM_MASK;
break;
default:
break;
}
}
s_bits_tx = (uint8_t)((s_bits_tx + 1) % 9);
}
}
+53
View File
@@ -0,0 +1,53 @@
/*
* t7_eeprom.h - emulated 4 KB I²C EEPROM backed by Pebble persist
*
* The real V7 has a 32 kbit (4 KB) external SPI/I²C EEPROM that
* holds all save data — Tama character, growth stage, stats, etc. When
* power cycles the internal RAM is lost but the EEPROM persists.
*
* We emulate that EEPROM in RAM and back it with Pebble's persist
* storage so Tama state survives app exits and watch reboots.
*
* Wire protocol (matches asterick/tamago eeprom.js exactly):
* START = data falling edge while CLK high → state = COMMAND
* STOP = data rising edge while CLK high → if state was WRITE, commit
* bit = sampled on CLK rising edge (input)
* = driven on CLK falling edge (output, only during READ)
*
* Commands (sent after START):
* $A0 Write — followed by 2 address bytes, then data bytes
* $A1 Read — start streaming data bytes from current address
*
* Wired to Port B ($3015 = direction, $3016 = data):
* bit 2 POWER (chip enable)
* bit 1 CLK
* bit 0 DATA (input from CPU when configured as output;
* driven by EEPROM when CPU configures as input)
*/
#ifndef T7_EEPROM_H
#define T7_EEPROM_H
#include <stdint.h>
#include <stdbool.h>
// Load saved data from persist storage. Call once during t7_init.
void t7_eeprom_init(void);
// Flush all dirty pages back to persist. Call on app exit and
// optionally periodically.
void t7_eeprom_flush(void);
// Wipe the entire EEPROM (in-memory and persist storage). The Tama
// firmware will boot into its first-time setup flow on the next start.
void t7_eeprom_wipe(void);
// Update the bus state. Equivalent to JS's eeprom.update(power, clk, data).
// power, clk, data are 0/non-zero (booleans).
void t7_eeprom_update(uint8_t power, uint8_t clk, uint8_t data);
// Current output bit (what the EEPROM is driving on the data line).
// 0 = pulled low, 1 = high-impedance / NACK.
uint8_t t7_eeprom_output(void);
#endif // T7_EEPROM_H
+164
View File
@@ -0,0 +1,164 @@
/*
* t7_internal.h - shared state structure for the emulator modules
*
* Not exposed to the Pebble app — only included by t7_*.c files.
*
* Performance note: hot-path state (CPU registers, work RAM, display RAM,
* CPU register array, page tables) is exposed as separate global
* variables rather than fields of a single g_sys struct. The reason is
* that GCC treats `g_sys->foo` as a load through a pointer that could be
* invalidated by any function call (because g_sys itself could in theory
* be reassigned). With globals it can compute the address at compile time
* and skip a level of indirection in the inner emulation loop. This
* matters at ~750,000 memory accesses per emulated frame.
*/
#ifndef T7_INTERNAL_H
#define T7_INTERNAL_H
// ----- Hot-Path-Platzierung: heisser Emulator-Pfad ins IRAM (kein Flash-
// Cache-Miss). Bei IRAM-Overflow im Linker -> #define T7_HOT leer.
#ifndef T7_HOT
# if defined(ESP_PLATFORM)
# include "esp_attr.h"
# define T7_HOT IRAM_ATTR
# else
# define T7_HOT
# endif
#endif
#include "t7.h"
// 6502 registers (split out as a global, not behind a pointer).
typedef struct {
uint16_t pc;
uint8_t a;
uint8_t x;
uint8_t y;
uint8_t s;
uint8_t p;
} cpu6502_t;
// Small frequently-accessed state kept as globals (compile-time addresses).
extern cpu6502_t g_cpu;
extern uint8_t g_wram[T7_WRAM_SIZE];
extern uint8_t g_dram[T7_DRAM_SIZE];
extern uint8_t g_cpureg[T7_CPUREG_SIZE];
// Large buffers are heap-allocated to keep .bss under the Pebble's
// 16-bit virtual-size limit (65535 bytes). They're only ever touched
// through the page table after init, so a heap pointer costs the same
// as a global array: page_table[p] already holds the absolute address
// either way.
extern uint8_t *g_rom_bank_buf;
extern uint8_t *g_static_rom;
// IRQ vector table (16 entries, loaded once at init).
extern uint16_t g_irq_vectors[16];
// Set non-zero by t7_fire_irq whenever it sets a bit in cpureg[$73:$74].
// Cleared by t7_cpu_irq when it services the highest-priority pending
// IRQ. The CPU step checks this single byte instead of reloading both
// cpureg bytes on every instruction — at ~3 million steps/sec that saves
// ~6 million memory loads/sec.
extern uint8_t g_irq_pending_any;
/* 1.6.9 (test12) battery, as TamaGo-Pebble v0.3.0: T7_IDLE jumps over the passes of the main loop's wait at $CE66
* (bit-identical), T7_STOP halts the CPU when the firmware writes 7 to $3001 (until an IRQ or a key) */
#define T7_IDLE_PC 0xCE66u
extern uint8_t g_t7_idle_ok, g_t7_halted;
#ifdef T7_JSR_HLE
extern uint8_t g_t7_hle, g_t7_dark;
#endif
extern uint32_t g_t7_idle_cyc, g_t7_keyact;
void t7_idle_check(void);
// Misc runtime state.
extern uint8_t g_rom_bank_id;
extern bool g_rom_loaded;
extern uint8_t g_keys;
extern ResHandle g_rom_resource;
// Whether the emulator is initialised. Used by t7_release to know
// whether g_dram etc were ever populated.
extern bool g_initialised;
// ----- Memory access (fast inline path) -----------------------------------
//
// Page table: 256 entries, one per 256-byte page of the 64K address space.
// Each entry points at the backing RAM/ROM buffer for that page, or NULL
// if the page needs slow-path I/O handling.
extern uint8_t *t7_read_page[256];
extern uint8_t *t7_write_page[256];
uint8_t t7_io_read(uint16_t addr);
void t7_io_write(uint16_t addr, uint8_t value);
// ----- Profiling counters (referenced by the inline read/write below) -----
//
// T7_PROFILE is set in the public t7.h. When OFF (the production
// default), PROFILE_INC compiles to nothing and the counter struct
// isn't even instantiated.
#if T7_PROFILE
typedef struct {
uint32_t opcodes; // t7_cpu_step calls
uint32_t reads_fast; // hit page-table (WRAM/DRAM/ROM)
uint32_t reads_io; // missed → t7_io_read
uint32_t writes_fast; // hit page-table
uint32_t writes_io; // hit I/O area
uint32_t writes_dropped; // hit ROM (silently ignored)
uint32_t irqs; // t7_fire_irq calls
uint32_t nmis; // t7_fire_nmi calls
uint32_t irq_entries; // actual CPU IRQ entries (after mask check)
uint32_t nmi_entries; // actual CPU NMI entries
} t7_profile_t;
extern t7_profile_t g_t7_profile;
# define PROFILE_INC(field) (g_t7_profile.field++)
#else
# define PROFILE_INC(field) ((void)0)
#endif
#define T7_INLINE static inline __attribute__((always_inline))
T7_INLINE uint8_t t7_read(uint16_t addr)
{
uint8_t *page = t7_read_page[addr >> 8];
if (page) { PROFILE_INC(reads_fast); return page[addr & 0xFF]; }
PROFILE_INC(reads_io);
return t7_io_read(addr);
}
T7_INLINE uint16_t t7_read16(uint16_t addr)
{
uint8_t lo = t7_read(addr);
uint8_t hi = t7_read((addr + 1) & 0xFFFF);
return lo | (hi << 8);
}
T7_INLINE void t7_write(uint16_t addr, uint8_t value)
{
uint8_t *page = t7_write_page[addr >> 8];
if (page) { PROFILE_INC(writes_fast); page[addr & 0xFF] = value; return; }
if ((addr >> 12) == 0x3) { PROFILE_INC(writes_io); t7_io_write(addr, value); return; }
PROFILE_INC(writes_dropped);
}
// ROM banking
extern uint32_t g_t7_static_off; /* 0 Tama-Go, 0x4000 Friends */
extern uint8_t g_t7_banks;
void t7_set_rom_bank(uint8_t bank);
bool t7_load_static_rom(void);
// CPU step (defined in t7_cpu.c)
uint8_t t7_cpu_step(void);
void t7_cpu_reset(void);
void t7_cpu_nmi(void);
void t7_cpu_irq(void);
// IRQ logic (defined in t7_memory.c since it touches cpureg)
void t7_fire_irq(uint8_t i);
void t7_fire_nmi(uint8_t i);
#endif // T7_INTERNAL_H
+552
View File
@@ -0,0 +1,552 @@
/*
* t7_jit.c - 6502 to Thumb-2 translator for the Paradise (Cortex-M3), switch T7_JIT (1.6.12 test2).
*
* Straight runs of ROM code (static $C000-$FFFF and the banked $4000-$BFFF) become native code. A block ends with a
* branch, JMP, JSR or RTS, or stops before anything the interpreter must do itself (IRQ flag CLI/PLP/RTI/BRK, decimal
* mode, PHP, the idle loop, the JSR shortcuts, the IR hooks, opcodes not handled here, the end of the page). Blocks
* are found by the physical address of their first byte (page table pointer), so banked code needs no flushing.
*
* Exactness (checked on the PC under qemu-arm, runcmp against the interpreter, state hash every 2 ms):
* - a block runs only when the interpreter would run all of its instructions in this run (cyc + pre < budget) and
* no sound event falls inside it (snd > all); its cycles are the same opcode_cycles sums;
* - the flags are kept as the interpreter keeps them (nzn, nzz, fc, fv); ADC/SBC binary only (blocks run with D = 0);
* - an I/O write ends the block right after it, with g_snd_next set before the write as the interpreter does;
* $0000-$0FFF work RAM, $1000-$2FFF display RAM (fixed), $3xxx I/O, ROM above (writes there do nothing).
*
* Registers in a block: r4 A, r5 X, r6 Y, r7 S, r8 nzn, r9 nzz, r10 C, r11 the state block; r0-r3, r12, lr free.
* Author: mameise
*/
#include "t7_internal.h"
#include "t7_sound.h"
#ifdef T7_JIT
#include "t7_jit.h"
#define T7J_HASH 1024u
#define T7J_MAXI 32u
#ifndef T7J_HOT
#define T7J_HOT 2u
#endif
static uint16_t *g_jbuf; /* code buffer (halfwords) */
static uint32_t g_jcap, g_jpos; /* in halfwords */
static uint32_t g_jexit, g_jexit0, g_jtramp, g_jrds, g_jwrs, g_jrts, g_jjsr; /* the shared exits, entry and memory stubs */
static T7JEnt g_t7j[T7J_HASH];
uint32_t g_t7j_on, g_t7j_stat[4]; /* blocks made, flushes, block runs, refused starts */
static int g_jfull;
/* ---------------------------------------------------------------- Thumb-2 emitter */
static __attribute__((noinline)) void e16(uint32_t h) { if (g_jpos + 1u > g_jcap) { g_jfull = 1; return; } g_jbuf[g_jpos++] = (uint16_t)h; }
static __attribute__((noinline)) void e32(uint32_t a, uint32_t b) { e16(a); e16(b); }
enum { R0, R1, R2, R3, R4, R5, R6, R7, R8, R9, R10, R11, R12, R13, LR, R15 };
#define RA R4
#define RX R5
#define RY R6
#define RST R7 /* low register: short loads of the state fields */
#define RN R8
#define RZ R9
#define RC R10
#define RS R11
#define OFS(f) ((uint32_t)offsetof(T7J, f))
#define OFS2(f) ((uint32_t)offsetof(T7JEnt, f))
/* data processing, register, shift type t by n */
static __attribute__((noinline)) void dpr32(uint32_t op, int rd, int rn, int rm, int t, int n) { e32(op | (uint32_t)rn, ((uint32_t)(n >> 2) << 12) | ((uint32_t)rd << 8) | ((uint32_t)(n & 3) << 6) | ((uint32_t)t << 4) | (uint32_t)rm); }
#define ADD_R 0xEB00u
#define SUB_R 0xEBA0u
#define SUBS_R 0xEBB0u
#define AND_R 0xEA00u
#define BIC_R 0xEA20u
#define ORR_R 0xEA40u
#define EOR_R 0xEA80u
#define LO(r) ((uint32_t)(r) < 8u)
/* the short (flag setting) forms where they fit; the flags of the host are only used right after a compare */
static __attribute__((noinline)) void dpr(uint32_t op, int rd, int rn, int rm, int t, int n)
{
if (!t && !n && LO(rd) && LO(rm) && rn != 15 && LO(rn)) {
if (op == ADD_R) { e16(0x1800u | ((uint32_t)rm << 6) | ((uint32_t)rn << 3) | (uint32_t)rd); return; }
if (op == SUB_R || op == SUBS_R) { e16(0x1A00u | ((uint32_t)rm << 6) | ((uint32_t)rn << 3) | (uint32_t)rd); return; }
if (rd == rn) {
uint32_t o16 = op == AND_R ? 0x4000u : op == EOR_R ? 0x4040u : op == ORR_R ? 0x4300u : op == BIC_R ? 0x4380u : 0u;
if (o16) { e16(o16 | ((uint32_t)rm << 3) | (uint32_t)rd); return; }
}
}
if (rn == 15 && op == ORR_R && LO(rd) && LO(rm) && n && t <= 1) { e16((t ? 0x0800u : 0x0000u) | ((uint32_t)n << 6) | ((uint32_t)rm << 3) | (uint32_t)rd); return; }
dpr32(op, rd, rn, rm, t, n);
}
static __attribute__((noinline)) void mov(int rd, int rm) { e16(0x4600u | (((uint32_t)rd & 8u) << 4) | ((uint32_t)rm << 3) | ((uint32_t)rd & 7u)); }
static __attribute__((noinline)) void mvn(int rd, int rm) { dpr(0xEA60u, rd, 15, rm, 0, 0); } /* ORN rd, pc, rm = MVN */
static __attribute__((noinline)) void lsli(int rd, int rm, int n) { dpr(ORR_R, rd, 15, rm, 0, n); }
static __attribute__((noinline)) void lsri(int rd, int rm, int n) { dpr(ORR_R, rd, 15, rm, 1, n); }
/* data processing, immediate 0..255 */
static __attribute__((noinline)) void dpi32(uint32_t op, int rd, int rn, uint32_t v) { e32(op | (uint32_t)rn, ((uint32_t)rd << 8) | (v & 0xFFu)); }
#define AND_I 0xF000u
#define TST_I 0xF010u
#define MOV_I 0xF04Fu
#define ADD_I 0xF100u
#define ADC_I 0xF140u
#define SUB_I 0xF1A0u
#define SUBS_I 0xF1B0u
static __attribute__((noinline)) void dpi(uint32_t op, int rd, int rn, uint32_t v)
{
v &= 0xFFu;
if (LO(rd) && rd == rn) {
if (op == ADD_I) { e16(0x3000u | ((uint32_t)rd << 8) | v); return; }
if (op == SUB_I) { e16(0x3800u | ((uint32_t)rd << 8) | v); return; }
}
if (op == SUBS_I && rd == 15 && LO(rn)) { e16(0x2800u | ((uint32_t)rn << 8) | v); return; } /* CMP */
dpi32(op, rd, rn, v);
}
static __attribute__((noinline)) void movi(int rd, uint32_t v) { if (LO(rd) && v < 256u) { e16(0x2000u | ((uint32_t)rd << 8) | v); return; } dpi(MOV_I, rd, 0, v); } /* MOVS: never between a compare and its use */
static __attribute__((noinline)) void addw(int rd, int rn, uint32_t v) { e32(0xF200u | (((v >> 11) & 1u) << 10) | (uint32_t)rn, (((v >> 8) & 7u) << 12) | ((uint32_t)rd << 8) | (v & 0xFFu)); }
static __attribute__((noinline)) void movw(int rd, uint32_t v) { e32(0xF240u | ((v >> 12) & 0xFu) | (((v >> 11) & 1u) << 10), (((v >> 8) & 7u) << 12) | ((uint32_t)rd << 8) | (v & 0xFFu)); }
static __attribute__((noinline)) void movt(int rd, uint32_t v) { e32(0xF2C0u | ((v >> 12) & 0xFu) | (((v >> 11) & 1u) << 10), (((v >> 8) & 7u) << 12) | ((uint32_t)rd << 8) | (v & 0xFFu)); }
static __attribute__((noinline)) void mov32(int rd, uint32_t v) { movw(rd, v & 0xFFFFu); if (v >> 16) movt(rd, v >> 16); }
static __attribute__((noinline)) void uxtb(int rd, int rm) { if (LO(rd) && LO(rm)) { e16(0xB2C0u | ((uint32_t)rm << 3) | (uint32_t)rd); return; } e32(0xFA5Fu, 0xF080u | ((uint32_t)rd << 8) | (uint32_t)rm); }
static __attribute__((noinline)) void uxth(int rd, int rm) { if (LO(rd) && LO(rm)) { e16(0xB280u | ((uint32_t)rm << 3) | (uint32_t)rd); return; } e32(0xFA1Fu, 0xF080u | ((uint32_t)rd << 8) | (uint32_t)rm); }
static __attribute__((noinline)) void ldrb_i(int rt, int rn, uint32_t o) { if (LO(rt) && LO(rn) && o < 32u) { e16(0x7800u | (o << 6) | ((uint32_t)rn << 3) | (uint32_t)rt); return; } e32(0xF890u | (uint32_t)rn, ((uint32_t)rt << 12) | (o & 0xFFFu)); }
static __attribute__((noinline)) void strb_i(int rt, int rn, uint32_t o) { if (LO(rt) && LO(rn) && o < 32u) { e16(0x7000u | (o << 6) | ((uint32_t)rn << 3) | (uint32_t)rt); return; } e32(0xF880u | (uint32_t)rn, ((uint32_t)rt << 12) | (o & 0xFFFu)); }
static __attribute__((noinline)) void ldr_i(int rt, int rn, uint32_t o) { if (LO(rt) && LO(rn) && o < 128u && !(o & 3u)) { e16(0x6800u | ((o >> 2) << 6) | ((uint32_t)rn << 3) | (uint32_t)rt); return; } e32(0xF8D0u | (uint32_t)rn, ((uint32_t)rt << 12) | (o & 0xFFFu)); }
static __attribute__((noinline)) void str_i(int rt, int rn, uint32_t o) { if (LO(rt) && LO(rn) && o < 128u && !(o & 3u)) { e16(0x6000u | ((o >> 2) << 6) | ((uint32_t)rn << 3) | (uint32_t)rt); return; } e32(0xF8C0u | (uint32_t)rn, ((uint32_t)rt << 12) | (o & 0xFFFu)); }
static __attribute__((noinline)) void ldrb_r(int rt, int rn, int rm) { if (LO(rt) && LO(rn) && LO(rm)) { e16(0x5C00u | ((uint32_t)rm << 6) | ((uint32_t)rn << 3) | (uint32_t)rt); return; } e32(0xF810u | (uint32_t)rn, ((uint32_t)rt << 12) | (uint32_t)rm); }
static __attribute__((noinline)) void strb_r(int rt, int rn, int rm) { if (LO(rt) && LO(rn) && LO(rm)) { e16(0x5400u | ((uint32_t)rm << 6) | ((uint32_t)rn << 3) | (uint32_t)rt); return; } e32(0xF800u | (uint32_t)rn, ((uint32_t)rt << 12) | (uint32_t)rm); }
static __attribute__((noinline)) void ldr_r2(int rt, int rn, int rm) { e32(0xF850u | (uint32_t)rn, ((uint32_t)rt << 12) | (2u << 4) | (uint32_t)rm); }
static __attribute__((noinline)) void blx(int rm) { e16(0x4780u | ((uint32_t)rm << 3)); }
static __attribute__((noinline)) void cmpi(int rn, uint32_t v) { dpi(SUBS_I, 15, rn, v); }
static __attribute__((noinline)) void call(const void *f) { mov32(R12, (uint32_t)(uintptr_t)f); blx(R12); }
static __attribute__((noinline)) void carry_to(int rd) { movi(rd, 0); dpi(ADC_I, rd, rd, 0); } /* C of the last SUBS: 1 = no borrow */
static __attribute__((noinline)) void nz(int r) { mov(RN, r); mov(RZ, r); }
static __attribute__((noinline)) void wram(int rd) { ldr_i(rd, RST, OFS(wram)); }
/* branches with fixups */
static __attribute__((noinline)) uint32_t bcond_at(int cond) { uint32_t at = g_jpos; e32(0xF000u | ((uint32_t)cond << 6), 0x8000u); return at; }
static uint32_t b_at(void) { uint32_t at = g_jpos; e32(0xF000u, 0x9000u); return at; }
static uint32_t bl_at(void) { uint32_t at = g_jpos; e32(0xF000u, 0xD000u); return at; }
static uint32_t cbz_at(int rn) { uint32_t at = g_jpos; e16(0xB100u | (uint32_t)rn); return at; } /* forward, fixed by fixcb */
static __attribute__((noinline)) void fixcb(uint32_t at, uint32_t to) { if (g_jfull) return; uint32_t off = (to - at) * 2u - 4u; g_jbuf[at] = (uint16_t)(g_jbuf[at] | (((off >> 6) & 1u) << 9) | (((off >> 1) & 0x1Fu) << 3)); }
static __attribute__((noinline)) void fix(uint32_t at, uint32_t to)
{
if (g_jfull || at + 1u >= g_jcap) return;
int32_t off = ((int32_t)to - (int32_t)at - 2) * 2;
uint32_t u = (uint32_t)off, s = off < 0 ? 1u : 0u, h1 = g_jbuf[at], h2 = g_jbuf[at + 1];
if (!(h2 & 0x1000u)) { /* T3 conditional: S J2 J1 imm6 imm11 */
g_jbuf[at] = (uint16_t)((h1 & 0xFBC0u) | (s << 10) | ((u >> 12) & 0x3Fu));
g_jbuf[at + 1] = (uint16_t)(0x8000u | (((u >> 18) & 1u) << 13) | (((u >> 19) & 1u) << 11) | ((u >> 1) & 0x7FFu));
} else { /* T4: S J1 J2 imm10 imm11 */
uint32_t i1 = (u >> 23) & 1u, i2 = (u >> 22) & 1u, j1 = (~(i1 ^ s)) & 1u, j2 = (~(i2 ^ s)) & 1u;
g_jbuf[at] = (uint16_t)(0xF000u | (s << 10) | ((u >> 12) & 0x3FFu));
g_jbuf[at + 1] = (uint16_t)((h2 & 0x4000u) | 0x9000u | (j1 << 13) | (j2 << 11) | ((u >> 1) & 0x7FFu));
}
}
enum { C_EQ = 0, C_NE = 1 };
/* ---------------------------------------------------------------- helpers called from blocks */
static uint32_t jrd(uint32_t a) { return t7_io_read((uint16_t)a); }
static void jwr(T7J *s, uint32_t a, uint32_t v, uint32_t cb)
{
g_snd_next = g_snd_on ? s->snd - (int32_t)cb : s->snd; /* as the interpreter's WR before an I/O write */
t7_io_write((uint16_t)a, (uint8_t)v);
}
/* ---------------------------------------------------------------- block parts */
static __attribute__((noinline)) void cycles_r1(uint32_t cyc) { if (cyc < 256u) e16(0x2100u | cyc); else movw(R1, cyc); }
static __attribute__((noinline)) void exit_to(uint32_t pc, uint32_t cyc, uint32_t io) /* r0 pc, r1 cycles, r2 io, to the exit */
{
movw(R0, pc);
if (cyc < 256u) e16(0x2100u | cyc); else movw(R1, cyc); /* MOVS r1: the host flags are dead here */
if (io) { movw(R2, io); fix(b_at(), g_jexit); } else fix(b_at(), g_jexit0);
}
/* constant addresses: work RAM (mirrored every 6 pages) and display RAM directly, the rest through the stubs */
static int ram_ofs(uint32_t ad, int *dram)
{
if (ad < 0x1000u) { *dram = 0; return (int)(((ad >> 8) % 6u) * 0x100u + (ad & 0xFFu)); }
if (ad < 0x3000u) { *dram = 1; return (int)(((ad >> 8) & 1u) * 0x100u + (ad & 0xFFu)); }
return -1;
}
static __attribute__((noinline)) void ram_base(int dram) { if (dram) mov32(R3, (uint32_t)(uintptr_t)g_dram); else wram(R3); }
static __attribute__((noinline)) void emit_rd(void) { fix(bl_at(), g_jrds); } /* r0 = address -> r0 = byte */
static __attribute__((noinline)) void emit_wr(uint32_t pcnext, uint32_t cb, uint32_t c) /* write r1 to address r0; on I/O the stub ends the block */
{
fix(bl_at(), g_jwrs);
e16(pcnext); e16(c); e16(cb); e16(0); /* data for the stub, skipped on return */
}
static __attribute__((noinline)) void ld_abs(int rt, uint32_t ad)
{
int d, o = ram_ofs(ad, &d);
if (o >= 0) { ram_base(d); ldrb_i(rt, R3, (uint32_t)o); return; }
movw(R0, ad); emit_rd(); if (rt != R0) mov(rt, R0);
}
static __attribute__((noinline)) void st_abs(int rt, uint32_t ad, uint32_t pn, uint32_t cb, uint32_t c)
{
int d, o = ram_ofs(ad, &d);
if (o >= 0) { ram_base(d); strb_i(rt, R3, (uint32_t)o); return; }
movw(R0, ad); if (rt != R1) mov(R1, rt); emit_wr(pn, cb, c);
}
static __attribute__((noinline)) void ea_absi(uint32_t ad, int ri) { movw(R0, ad); dpr(ADD_R, R0, R0, ri, 0, 0); uxth(R0, R0); }
static __attribute__((noinline)) void ea_zpi(uint32_t z, int ri) { dpi(ADD_I, R0, ri, z); uxtb(R0, R0); }
static __attribute__((noinline)) void ea_indx(uint32_t z)
{
wram(R3);
dpi(ADD_I, R1, RX, z); uxtb(R1, R1); ldrb_r(R0, R3, R1);
dpi(ADD_I, R1, R1, 1); uxtb(R1, R1); ldrb_r(R2, R3, R1);
dpr(ORR_R, R0, R0, R2, 0, 8);
}
static __attribute__((noinline)) void ea_indy(uint32_t z)
{
wram(R3);
ldrb_i(R0, R3, z); ldrb_i(R2, R3, (z + 1u) & 0xFFu);
dpr(ORR_R, R0, R0, R2, 0, 8);
dpr(ADD_R, R0, R0, RY, 0, 0); uxth(R0, R0);
}
static __attribute__((noinline)) void stubs(void)
{
g_jtramp = g_jpos; /* tramp(T7J *s, code) */
e32(0xE92Du, 0x4FF0u); /* push {r4-r11, lr} */
mov(RST, R0);
ldr_i(RA, RST, OFS(a)); ldr_i(RX, RST, OFS(x)); ldr_i(RY, RST, OFS(y)); ldr_i(RS, RST, OFS(s));
ldr_i(RN, RST, OFS(nzn)); ldr_i(RZ, RST, OFS(nzz)); ldr_i(RC, RST, OFS(fc));
e16(0x4708u); /* bx r1 */
/* exit without I/O: r0 pc, r1 the block's cycles. The next block follows here when it is made and the interpreter
* would run it now as well (as t7_cpu_run: pc from $4000, pre < budget left, all < sound countdown) */
g_jexit0 = g_jpos;
ldr_i(R3, RST, OFS(cyc)); dpr(ADD_R, R3, R3, R1, 0, 0); str_i(R3, RST, OFS(cyc));
ldr_i(R3, RST, OFS(son)); ldr_i(R2, RST, OFS(snd)); e32(0xFB01u, 0x2213u); str_i(R2, RST, OFS(snd)); /* mls r2, r1, r3, r2 */
ldr_i(R3, RST, OFS(rem)); dpr(SUB_R, R3, R3, R1, 0, 0); str_i(R3, RST, OFS(rem));
lsri(R2, R0, 14); uint32_t o1 = bcond_at(C_EQ);
lsri(R2, R0, 8); ldr_i(R1, RST, OFS(rp)); ldr_r2(R1, R1, R2);
uint32_t o2 = cbz_at(R1);
uxtb(R2, R0); dpr(ADD_R, R1, R1, R2, 0, 0); /* the key */
dpr32(EOR_R, R2, R1, R1, 1, 11); lsli(R2, R2, 22); lsri(R2, R2, 22); /* as t7_jit_get */
dpr32(ADD_R, R2, R2, R2, 0, 2); ldr_i(R12, RST, OFS(tbl)); dpr32(ADD_R, R12, R12, R2, 0, 2);
ldr_i(R2, R12, OFS2(key)); e16(0x4280u | (R1 << 3) | R2); /* cmp r2, r1 */
uint32_t o3 = bcond_at(C_NE);
ldr_i(R1, R12, OFS2(code));
uint32_t o4 = cbz_at(R1);
ldr_i(R2, R12, OFS2(pre)); e16(0x4280u | (R3 << 3) | R2); /* cmp r2, r3 */
uint32_t o5 = bcond_at(10); /* bge */
ldr_i(R3, RST, OFS(son));
uint32_t go = cbz_at(R3);
ldr_i(R2, R12, OFS2(all)); ldr_i(R3, RST, OFS(snd)); e16(0x4280u | (R3 << 3) | R2);
uint32_t o6 = bcond_at(10);
fixcb(go, g_jpos);
e16(0x4708u); /* bx r1 */
fix(o1, g_jpos); fixcb(o2, g_jpos); fix(o3, g_jpos); fixcb(o4, g_jpos); fix(o5, g_jpos); fix(o6, g_jpos);
e16(0x2200u); /* movs r2, #0 */
uint32_t sv = b_at();
g_jexit = g_jpos; /* exit after an I/O write: r0 pc, r1 cycles, r2 the write's cycles */
ldr_i(R3, RST, OFS(cyc)); dpr(ADD_R, R3, R3, R1, 0, 0); str_i(R3, RST, OFS(cyc));
fix(sv, g_jpos);
str_i(R0, RST, OFS(pc)); str_i(R2, RST, OFS(io));
str_i(RA, RST, OFS(a)); str_i(RX, RST, OFS(x)); str_i(RY, RST, OFS(y)); str_i(RS, RST, OFS(s));
str_i(RN, RST, OFS(nzn)); str_i(RZ, RST, OFS(nzz)); str_i(RC, RST, OFS(fc));
e32(0xE8BDu, 0x8FF0u); /* pop {r4-r11, pc} */
/* read: r0 address -> r0 byte (r1-r3, r12 used) */
g_jrds = g_jpos;
lsri(R1, R0, 8); ldr_i(R2, RST, OFS(rp)); ldr_r2(R2, R2, R1);
uint32_t z = cbz_at(R2);
uxtb(R3, R0); ldrb_r(R0, R2, R3); e16(0x4770u); /* bx lr */
fixcb(z, g_jpos);
e16(0xB500u); call(jrd); e16(0xBD00u); /* push {lr} .. pop {pc} */
/* write: r0 address, r1 byte; lr points at the data after the BL: pc next, cycles, cycles before (halfwords) */
g_jwrs = g_jpos;
lsri(R2, R0, 8); ldr_i(R3, RST, OFS(wp)); ldr_r2(R3, R3, R2);
z = cbz_at(R3);
uxtb(R2, R0); strb_r(R1, R3, R2);
uint32_t skip = g_jpos;
addw(LR, LR, 8); e16(0x4770u);
fixcb(z, g_jpos);
lsri(R2, R0, 12); cmpi(R2, 3);
fix(bcond_at(C_NE), skip); /* ROM: nothing happens */
e32(0xF2AEu, 0x0C01u); /* subw r12, lr, #1: the data */
str_i(R12, RST, OFS(tmp));
mov(R2, R1); mov(R1, R0); mov(R0, RST);
e32(0xF8BCu, 0x3004u); /* ldrh r3, [r12, #4]: cycles before */
call(jwr);
ldr_i(R3, RST, OFS(tmp));
e16(0x8818u); /* ldrh r0, [r3] */
e16(0x885Au); /* ldrh r2, [r3, #2] */
e16(0x8899u); /* ldrh r1, [r3, #4] */
dpr(ADD_R, R1, R1, R2, 0, 0);
fix(b_at(), g_jexit); /* the interpreter looks at the IRQs (chk) after it */
/* RTS: r1 cycles */
g_jrts = g_jpos;
wram(R3);
dpi(ADD_I, RS, RS, 1); uxtb(RS, RS); addw(R0, RS, 0x100); ldrb_r(R2, R3, R0);
dpi(ADD_I, RS, RS, 1); uxtb(RS, RS); addw(R0, RS, 0x100); ldrb_r(R0, R3, R0);
dpr32(ORR_R, R0, R2, R0, 0, 8); dpi(ADD_I, R0, R0, 1); uxth(R0, R0);
fix(b_at(), g_jexit0);
/* JSR: r0 return address - 1, r3 target, r1 cycles */
g_jjsr = g_jpos;
wram(R2);
addw(R12, RS, 0x100); lsri(LR, R0, 8); strb_r(LR, R2, R12); dpi(SUB_I, RS, RS, 1); uxtb(RS, RS);
addw(R12, RS, 0x100); strb_r(R0, R2, R12); dpi(SUB_I, RS, RS, 1); uxtb(RS, RS);
mov(R0, R3);
fix(b_at(), g_jexit0);
}
/* instruction length of the handled opcodes, 0 = not handled */
static uint32_t oplen(uint32_t op)
{
switch (op) {
case 0xA9: case 0xA2: case 0xA0: case 0x29: case 0x09: case 0x49: case 0xC9: case 0xE0: case 0xC0: case 0x69: case 0xE9:
case 0xA5: case 0xA6: case 0xA4: case 0x85: case 0x86: case 0x84: case 0xB5: case 0x95: case 0xB4: case 0x94: case 0xB6: case 0x96:
case 0x25: case 0x05: case 0x45: case 0xC5: case 0xE4: case 0xC4: case 0x65: case 0xE5: case 0x24: case 0xE6: case 0xC6:
case 0x35: case 0x15: case 0x55: case 0xD5: case 0x75: case 0xF5: case 0xF6: case 0xD6: case 0x06: case 0x46: case 0x26: case 0x66:
case 0x16: case 0x56: case 0x36: case 0x76:
case 0xA1: case 0xB1: case 0x81: case 0x91: case 0x21: case 0x31: case 0x01: case 0x11: case 0x41: case 0x51: case 0xC1: case 0xD1:
case 0x61: case 0x71: case 0xE1: case 0xF1:
case 0x10: case 0x30: case 0x50: case 0x70: case 0x90: case 0xB0: case 0xD0: case 0xF0:
return 2;
case 0xAD: case 0xAE: case 0xAC: case 0x8D: case 0x8E: case 0x8C: case 0xBD: case 0xB9: case 0x9D: case 0x99: case 0xBC: case 0xBE:
case 0x2D: case 0x0D: case 0x4D: case 0xCD: case 0xEC: case 0xCC: case 0x6D: case 0xED: case 0x2C: case 0xEE: case 0xCE: case 0xFE: case 0xDE:
case 0x3D: case 0x39: case 0x1D: case 0x19: case 0x5D: case 0x59: case 0xDD: case 0xD9: case 0x7D: case 0x79: case 0xFD: case 0xF9:
case 0x0E: case 0x4E: case 0x2E: case 0x6E: case 0x1E: case 0x5E: case 0x3E: case 0x7E:
case 0x4C: case 0x20:
return 3;
case 0xAA: case 0xA8: case 0x8A: case 0x98: case 0xBA: case 0x9A: case 0xE8: case 0xC8: case 0xCA: case 0x88:
case 0x18: case 0x38: case 0xB8: case 0xD8: case 0x78: case 0xEA: case 0x48: case 0x68: case 0x0A: case 0x4A: case 0x2A: case 0x6A: case 0x60:
return 1;
}
return 0;
}
/* one instruction; returns 0 not done, 1 done, 2 done and the block ends */
static __attribute__((noinline)) int emit_op(uint32_t op, uint32_t b1, uint32_t ad, uint32_t pn, uint32_t cb, uint32_t c)
{
switch (op) {
case 0xA9: movi(RA, b1); nz(RA); return 1;
case 0xA2: movi(RX, b1); nz(RX); return 1;
case 0xA0: movi(RY, b1); nz(RY); return 1;
case 0xA5: wram(R3); ldrb_i(RA, R3, b1); nz(RA); return 1;
case 0xA6: wram(R3); ldrb_i(RX, R3, b1); nz(RX); return 1;
case 0xA4: wram(R3); ldrb_i(RY, R3, b1); nz(RY); return 1;
case 0xB5: ea_zpi(b1, RX); wram(R3); ldrb_r(RA, R3, R0); nz(RA); return 1;
case 0xB4: ea_zpi(b1, RX); wram(R3); ldrb_r(RY, R3, R0); nz(RY); return 1;
case 0xB6: ea_zpi(b1, RY); wram(R3); ldrb_r(RX, R3, R0); nz(RX); return 1; /* page 0 is work RAM */
case 0xAD: ld_abs(RA, ad); nz(RA); return 1;
case 0xAE: ld_abs(RX, ad); nz(RX); return 1;
case 0xAC: ld_abs(RY, ad); nz(RY); return 1;
case 0xBD: ea_absi(ad, RX); emit_rd(); mov(RA, R0); nz(RA); return 1;
case 0xB9: ea_absi(ad, RY); emit_rd(); mov(RA, R0); nz(RA); return 1;
case 0xBC: ea_absi(ad, RX); emit_rd(); mov(RY, R0); nz(RY); return 1;
case 0xBE: ea_absi(ad, RY); emit_rd(); mov(RX, R0); nz(RX); return 1;
case 0xA1: ea_indx(b1); emit_rd(); mov(RA, R0); nz(RA); return 1;
case 0xB1: ea_indy(b1); emit_rd(); mov(RA, R0); nz(RA); return 1;
case 0x85: wram(R3); strb_i(RA, R3, b1); return 1;
case 0x86: wram(R3); strb_i(RX, R3, b1); return 1;
case 0x84: wram(R3); strb_i(RY, R3, b1); return 1;
case 0x95: ea_zpi(b1, RX); wram(R3); strb_r(RA, R3, R0); return 1;
case 0x94: ea_zpi(b1, RX); wram(R3); strb_r(RY, R3, R0); return 1;
case 0x96: ea_zpi(b1, RY); wram(R3); strb_r(RX, R3, R0); return 1;
case 0x8D: st_abs(RA, ad, pn, cb, c); return 1;
case 0x8E: st_abs(RX, ad, pn, cb, c); return 1;
case 0x8C: st_abs(RY, ad, pn, cb, c); return 1;
case 0x9D: ea_absi(ad, RX); mov(R1, RA); emit_wr(pn, cb, c); return 1;
case 0x99: ea_absi(ad, RY); mov(R1, RA); emit_wr(pn, cb, c); return 1;
case 0x81: ea_indx(b1); mov(R1, RA); emit_wr(pn, cb, c); return 1;
case 0x91: ea_indy(b1); mov(R1, RA); emit_wr(pn, cb, c); return 1;
case 0xAA: mov(RX, RA); nz(RX); return 1;
case 0xA8: mov(RY, RA); nz(RY); return 1;
case 0x8A: mov(RA, RX); nz(RA); return 1;
case 0x98: mov(RA, RY); nz(RA); return 1;
case 0xBA: mov(RX, RS); nz(RX); return 1;
case 0x9A: mov(RS, RX); return 1;
case 0xE8: dpi(ADD_I, RX, RX, 1); uxtb(RX, RX); nz(RX); return 1;
case 0xC8: dpi(ADD_I, RY, RY, 1); uxtb(RY, RY); nz(RY); return 1;
case 0xCA: dpi(SUB_I, RX, RX, 1); uxtb(RX, RX); nz(RX); return 1;
case 0x88: dpi(SUB_I, RY, RY, 1); uxtb(RY, RY); nz(RY); return 1;
case 0x18: movi(RC, 0); return 1;
case 0x38: movi(RC, 1); return 1;
case 0xB8: movi(R0, 0); str_i(R0, RST, OFS(fv)); return 1;
case 0xD8: return 1; /* CLD: D is 0 in a block already */
case 0x78: movi(R0, 1); str_i(R0, RST, OFS(fi)); return 1; /* SEI (as the interpreter: 1) */
case 0xEA: return 1;
case 0x48: wram(R3); addw(R0, RS, 0x100); strb_r(RA, R3, R0); dpi(SUB_I, RS, RS, 1); uxtb(RS, RS); return 1;
case 0x68: dpi(ADD_I, RS, RS, 1); uxtb(RS, RS); wram(R3); addw(R0, RS, 0x100); ldrb_r(RA, R3, R0); nz(RA); return 1;
case 0x4C: exit_to(ad, cb + c, 0); return 2;
case 0x20: movw(R0, (pn - 1u) & 0xFFFFu); movw(R3, ad); cycles_r1(cb + c); fix(b_at(), g_jjsr); return 2;
case 0x60: cycles_r1(cb + c); fix(b_at(), g_jrts); return 2;
case 0x10: case 0x30: case 0x50: case 0x70: case 0x90: case 0xB0: case 0xD0: case 0xF0: {
uint32_t tgt = (pn + (uint32_t)(int32_t)(int8_t)b1) & 0xFFFFu;
int cond;
cycles_r1(cb + c); /* first: MOVS sets the host flags */
switch (op) {
case 0x10: dpi(TST_I, 15, RN, 0x80); cond = C_EQ; break; /* BPL */
case 0x30: dpi(TST_I, 15, RN, 0x80); cond = C_NE; break; /* BMI */
case 0x50: ldr_i(R2, RST, OFS(fv)); cmpi(R2, 0); cond = C_EQ; break;
case 0x70: ldr_i(R2, RST, OFS(fv)); cmpi(R2, 0); cond = C_NE; break;
case 0x90: cmpi(RC, 0); cond = C_EQ; break;
case 0xB0: cmpi(RC, 0); cond = C_NE; break;
case 0xD0: cmpi(RZ, 0); cond = C_NE; break;
default: cmpi(RZ, 0); cond = C_EQ; break;
}
movw(R0, pn);
e16(cond == C_EQ ? 0xBF08u : 0xBF18u); /* IT EQ / IT NE */
movw(R0, tgt);
fix(b_at(), g_jexit0);
return 2;
}
}
/* ALU group with an operand in r0 */
int m;
switch (op) {
case 0x29: case 0x09: case 0x49: case 0xC9: case 0xE0: case 0xC0: case 0x69: case 0xE9: movi(R0, b1); m = 1; break;
case 0x25: case 0x05: case 0x45: case 0xC5: case 0xE4: case 0xC4: case 0x65: case 0xE5: case 0x24: wram(R3); ldrb_i(R0, R3, b1); m = 1; break;
case 0x35: case 0x15: case 0x55: case 0xD5: case 0x75: case 0xF5: ea_zpi(b1, RX); wram(R3); ldrb_r(R0, R3, R0); m = 1; break;
case 0x2D: case 0x0D: case 0x4D: case 0xCD: case 0xEC: case 0xCC: case 0x6D: case 0xED: case 0x2C: ld_abs(R0, ad); m = 1; break;
case 0x3D: case 0x1D: case 0x5D: case 0xDD: case 0x7D: case 0xFD: ea_absi(ad, RX); emit_rd(); m = 1; break;
case 0x39: case 0x19: case 0x59: case 0xD9: case 0x79: case 0xF9: ea_absi(ad, RY); emit_rd(); m = 1; break;
case 0x21: case 0x01: case 0x41: case 0xC1: case 0x61: case 0xE1: ea_indx(b1); emit_rd(); m = 1; break;
case 0x31: case 0x11: case 0x51: case 0xD1: case 0x71: case 0xF1: ea_indy(b1); emit_rd(); m = 1; break;
default: m = 0; break;
}
if (m) {
int grp;
if (op == 0xE0 || op == 0xE4 || op == 0xEC) grp = 10;
else if (op == 0xC0 || op == 0xC4 || op == 0xCC) grp = 11;
else if (op == 0x24 || op == 0x2C) grp = 12;
else grp = (int)(op >> 5);
switch (grp) {
case 0: dpr(ORR_R, RA, RA, R0, 0, 0); nz(RA); return 1;
case 1: dpr(AND_R, RA, RA, R0, 0, 0); nz(RA); return 1;
case 2: dpr(EOR_R, RA, RA, R0, 0, 0); nz(RA); return 1;
case 3: /* ADC: o = a + d + c */
dpr(ADD_R, R1, RA, R0, 0, 0); dpr(ADD_R, R1, R1, RC, 0, 0);
dpr(EOR_R, R2, RA, R0, 0, 0); dpr(EOR_R, R3, RA, R1, 0, 0); dpr(BIC_R, R2, R3, R2, 0, 0); dpi(AND_I, R2, R2, 0x80);
str_i(R2, RST, OFS(fv));
lsri(RC, R1, 8); uxtb(RA, R1); nz(RA); return 1;
case 6: dpr(SUBS_R, R1, RA, R0, 0, 0); carry_to(RC); uxtb(R1, R1); nz(R1); return 1; /* CMP */
case 7: /* SBC: o = a - d - !c (signed) */
dpr(SUB_R, R1, RA, R0, 0, 0); dpr(ADD_R, R1, R1, RC, 0, 0); dpi(SUB_I, R1, R1, 1);
dpr(EOR_R, R2, RA, R0, 0, 0); dpr(EOR_R, R3, RA, R1, 0, 0); dpr(AND_R, R2, R2, R3, 0, 0); dpi(AND_I, R2, R2, 0x80);
str_i(R2, RST, OFS(fv));
mvn(RC, R1); lsri(RC, RC, 31);
uxtb(RA, R1); nz(RA); return 1;
case 10: dpr(SUBS_R, R1, RX, R0, 0, 0); carry_to(RC); uxtb(R1, R1); nz(R1); return 1;
case 11: dpr(SUBS_R, R1, RY, R0, 0, 0); carry_to(RC); uxtb(R1, R1); nz(R1); return 1;
case 12: dpi(AND_I, R1, R0, 0x40); str_i(R1, RST, OFS(fv)); mov(RN, R0); dpr(AND_R, RZ, RA, R0, 0, 0); return 1;
}
return 0;
}
/* shifts, INC, DEC */
int sh = -1, mem = 1;
switch (op) {
case 0x0A: sh = 0; mem = 0; break; case 0x4A: sh = 1; mem = 0; break; case 0x2A: sh = 2; mem = 0; break; case 0x6A: sh = 3; mem = 0; break;
case 0x06: case 0x16: case 0x0E: case 0x1E: sh = 0; break;
case 0x46: case 0x56: case 0x4E: case 0x5E: sh = 1; break;
case 0x26: case 0x36: case 0x2E: case 0x3E: sh = 2; break;
case 0x66: case 0x76: case 0x6E: case 0x7E: sh = 3; break;
case 0xE6: case 0xF6: case 0xEE: case 0xFE: sh = 4; break;
case 0xC6: case 0xD6: case 0xCE: case 0xDE: sh = 5; break;
}
if (sh < 0) return 0;
uint32_t mode = op & 0x1Cu; /* 04 zp, 14 zp,X, 0C abs, 1C abs,X */
int zp = mode == 0x04u || mode == 0x14u, d = 0, ko = mode == 0x0Cu ? ram_ofs(ad, &d) : -1;
if (mode == 0x04u) { ko = (int)b1; d = 0; }
if (ko >= 0) { ram_base(d); ldrb_i(R0, R3, (uint32_t)ko); }
else if (mem) {
if (mode == 0x14u) ea_zpi(b1, RX); else if (mode == 0x0Cu) movw(R0, ad); else ea_absi(ad, RX);
str_i(R0, RST, OFS(tmp));
if (zp) { wram(R3); ldrb_r(R0, R3, R0); } else emit_rd();
} else mov(R0, RA);
switch (sh) {
case 0: lsri(RC, R0, 7); lsli(R1, R0, 1); uxtb(R1, R1); break;
case 1: dpi(AND_I, RC, R0, 1); lsri(R1, R0, 1); break;
case 2: lsli(R1, R0, 1); dpr(ORR_R, R1, R1, RC, 0, 0); lsri(RC, R0, 7); uxtb(R1, R1); break;
case 3: lsri(R1, R0, 1); dpr(ORR_R, R1, R1, RC, 0, 7); dpi(AND_I, RC, R0, 1); break;
case 4: dpi(ADD_I, R1, R0, 1); uxtb(R1, R1); break;
default: dpi(SUB_I, R1, R0, 1); uxtb(R1, R1); break;
}
nz(R1);
if (!mem) mov(RA, R1);
else if (ko >= 0) strb_i(R1, R3, (uint32_t)ko);
else if (zp) { ldr_i(R0, RST, OFS(tmp)); wram(R3); strb_r(R1, R3, R0); }
else { ldr_i(R0, RST, OFS(tmp)); emit_wr(pn, cb, c); }
return 1;
}
extern const uint8_t *const t7_opcode_cycles;
static int ok_pc(uint32_t pc, uint32_t b3)
{
b3 &= 1u;
if (b3 && (pc == 0x60C4u || pc == 0x7926u)) return 0; /* IR hooks of the Tama-Go */
#ifdef T7_IDLE
if (pc >= T7_IDLE_PC && pc < T7_IDLE_PC + 0x14u) return 0; /* the idle loop: the interpreter adds its passes up */
#endif
return 1;
}
static T7JEnt *translate(T7JEnt *e, uint32_t key, uint32_t pc, uint8_t *const *rp, uint32_t b3)
{
if (g_jcap - g_jpos < 1200u) { t7_jit_flush(); g_t7j_stat[1]++; }
uint32_t start = g_jpos, cyc = 0, pre = 0, n = 0, ended = 0;
const uint8_t *page = rp[pc >> 8];
#ifdef T7J_DEBUG
{ extern int g_t7j_log; if (g_t7j_log==1) printf("TRS pc %04x page %p key %08x bytes %02x %02x %02x bank %u\n", pc, page, key, page[pc&0xFF], page[(pc+1)&0xFF], page[(pc+2)&0xFF], g_rom_bank_id); if (g_t7j_log==1) { for (int q=0;q<12;q++) printf("%02x ", page[(pc+q)&0xFF]); printf("\n"); } }
#endif
g_jfull = 0;
while (n < T7J_MAXI && ok_pc(pc, b3)) {
uint32_t o = pc & 0xFFu, op = page[o], len = oplen(op);
if (!len || o + len > 0x100u) break;
#ifdef T7J_DEBUG
{ extern uint8_t g_t7j_deny[256]; if (g_t7j_deny[op]) break; }
#endif
uint32_t b1 = len > 1 ? page[o + 1] : 0, b2 = len > 2 ? page[o + 2] : 0, ad = b1 | (b2 << 8);
if (op == 0x20 && (ad == 0xD460u || ad == 0xE4CDu)) break; /* the JSR shortcuts stay with the interpreter */
#ifdef T7_IDLE
if (op == 0xF0 && ((pc + 2u + (uint32_t)(int32_t)(int8_t)b1) & 0xFFFFu) == T7_IDLE_PC) break;
#endif
uint32_t c = t7_opcode_cycles[op], pn = (pc + len) & 0xFFFFu, keep = g_jpos;
int r = emit_op(op, b1, ad, pn, cyc, c);
if (!r) { g_jpos = keep; break; }
#ifdef T7J_DEBUG
{ extern int g_t7j_log; if (g_t7j_log==3) fprintf(stderr,"O %02x %u\n", op, (unsigned)(g_jpos-keep)*2); }
#endif
pre = cyc; cyc += c; n++; pc = pn;
if (r == 2) { ended = 1; break; }
if (!(pc & 0xFFu)) break; /* the next page may be mapped elsewhere */
}
if (!ended && n) exit_to(pc, cyc, 0); /* stop before what the interpreter must do */
if (!n || g_jfull) { g_jpos = start; e->key = key; e->code = 0; e->cnt = 0x8000u; g_t7j_stat[3]++; return 0; }
e->key = key; e->code = (uint32_t)(uintptr_t)&g_jbuf[start] | 1u; e->pre = pre; e->all = cyc; e->cnt = 0;
g_t7j_stat[0]++;
#ifdef T7J_DEBUG
{ extern int g_t7j_log; if (g_t7j_log==3) fprintf(stderr,"T %x %x %u %u\n", key, pc, n, (unsigned)(g_jpos-start)*2); }
#endif
#ifdef T7J_DEBUG
{ uint32_t pc0 = pc; extern int g_t7j_log; if (g_t7j_log==1) { printf("TR start key %08x end %04x n %u cyc %u code:", key, pc0, n, cyc); for (uint32_t k = start; k < g_jpos; k++) printf(" %04x", g_jbuf[k]); printf("\n"); } }
#endif
#if defined(__arm__)
__asm__ volatile("dsb\n isb" ::: "memory");
#ifndef T7_FREESTANDING
__builtin___clear_cache((char *)&g_jbuf[start], (char *)&g_jbuf[g_jpos]);
#endif
#endif
return e;
}
void t7_jit_flush(void)
{
for (uint32_t i = 0; i < T7J_HASH; i++) { g_t7j[i].key = 0; g_t7j[i].code = 0; g_t7j[i].cnt = 0; }
g_jpos = 0; g_jfull = 0; stubs();
}
void t7_jit_init(void *buf, uint32_t bytes)
{
g_jbuf = (uint16_t *)buf; g_jcap = bytes / 2u; g_t7j_on = g_jbuf && g_jcap > 2048u;
if (g_t7j_on) t7_jit_flush();
}
T7JEnt *t7_jit_get(uint32_t key, uint32_t pc, uint8_t *const *rp, uint32_t b3)
{
T7JEnt *e = &g_t7j[(key ^ (key >> 11)) & (T7J_HASH - 1u)];
if (e->key == key) {
if (e->code) return e;
if (e->cnt >= 0x8000u) return 0; /* nothing to translate there */
if (++e->cnt < T7J_HOT) return 0;
return translate(e, key, pc, rp, b3);
}
if (!(b3 & 2u)) return 0; /* not where a run of code starts (after a jump or a block) */
if (e->code && e->cnt < 0x10u) { e->cnt++; return 0; } /* a used block stays for a while against a newcomer */
e->key = key; e->code = 0; e->cnt = 1;
return 0;
}
typedef void (*t7j_tramp)(T7J *, uint32_t);
void t7_jit_run(T7J *s, uint32_t code) { s->tbl = g_t7j; ((t7j_tramp)((uint32_t)(uintptr_t)&g_jbuf[g_jtramp] | 1u))(s, code); g_t7j_stat[2]++; }
#endif
+24
View File
@@ -0,0 +1,24 @@
/* t7_jit.h - 6502 to Thumb-2 translator (T7_JIT), see t7_jit.c. Author: mameise */
#ifndef T7_JIT_H
#define T7_JIT_H
#include <stdint.h>
#include <stddef.h>
/* the 6502 state as the run loop keeps it (in and out of a block) */
typedef struct {
uint32_t a, x, y, s, nzn, nzz, fc, fv, fi;
uint32_t pc, cyc, io; /* out: next pc, cycles used, io = cycles of the I/O write that ended the block (0: none) */
int32_t snd; /* in: the sound countdown at the start */
uint8_t *wram;
uint8_t *const *rp, *const *wp;
uint32_t tmp;
int32_t rem; /* in: budget - cycles (blocks follow each other in the code while they fit) */
uint32_t son; /* sound on: the blocks keep clear of the next sound event */
void *tbl;
} T7J;
typedef struct { uint32_t key, code, pre, all, cnt; } T7JEnt;
extern uint32_t g_t7j_on, g_t7j_stat[4];
void t7_jit_init(void *buf, uint32_t bytes);
void t7_jit_flush(void);
T7JEnt *t7_jit_get(uint32_t key, uint32_t pc, uint8_t *const *rp, uint32_t b3);
void t7_jit_run(T7J *s, uint32_t code);
#endif
+495
View File
@@ -0,0 +1,495 @@
/*
* t7_memory.c - memory map, ROM banking, and I/O registers
*
* Port of asterick/tamago. Highly optimized for the Pebble's ARM Cortex-M3.
*
* Memory map (16-bit address space):
* $0000-$0FFF Work RAM (1.5 KB, mirrored across 4 KB)
* $1000-$2FFF Display RAM (512 B, mirrored across 8 KB)
* $3000-$3FFF I/O registers (256 B, mirrored 16x)
* $4000-$BFFF Banked ROM (32 KB, 20 banks selectable via $3000)
* $C000-$FFFF Static ROM (16 KB, always mapped from beginning of ROM)
*
* Performance: the inner emulation loop hits memory ~3-4 times per
* instruction. To avoid expensive `addr % size` (modulo, which on M3
* compiles to a software divide) and function-call overhead, we build a
* page table at init: one pointer per 256-byte page of the 64K address
* space, pointing at the backing RAM/ROM buffer. Reads and writes that
* are pure RAM/ROM become a single array lookup + indirect load. Only
* the 256 bytes of I/O space ($3000-$30FF) require the slow path with
* register-specific handlers.
*/
#include "t7_internal.h"
#include "t7_eeprom.h"
#include "t7_sound.h"
// We need the resource ID generated from package.json's "media" entry.
// Defined in the generated header `src/resource_ids.auto.h` which is
// included via pebble.h.
#ifndef RESOURCE_ID_TAMA_ROM
#define RESOURCE_ID_TAMA_ROM 0
#endif
// ======================================================================
// FIGUR / SPI TRACE (Etappe 1 des Figuren-Reverse-Engineering)
//
// Ziel: herausfinden, wie die Firmware mit einer gesteckten Gotchi-Figur
// ueber SPI redet. Wir melden eine Figur als "gesteckt" (g_figure_id auf
// PortA Bit 5+) und schneiden jeden Zugriff auf PortA ($3012) und die
// SPI-Register ($30B0-$30BA) in einen Ringpuffer mit. Identische
// aufeinanderfolgende Reads werden zusammengefasst (rep-Zaehler), damit
// Status-Polling den Puffer nicht flutet.
//
// Steuerung per Serial (siehe main.cpp): fig / spiarm / spidump / spiret
// ======================================================================
uint8_t g_figure_id = 0; // 0 = keine Figur; 1..3 = Figur-Typ (live setzbar)
uint8_t g_spi_ret = 0xFF; // was $30B0-$30BA-Reads zurueckgeben (damit Status-Poll durchlaeuft)
#ifndef SPI_TRACE_MAX
#define SPI_TRACE_MAX 8192
#endif
typedef struct { uint8_t kind; uint8_t reg; uint8_t val; uint16_t rep; } spi_ev_t;
static spi_ev_t spi_trace[SPI_TRACE_MAX];
static int spi_trace_n = 0;
static bool spi_trace_armed = false; // Diagnose-Trace standardmaessig AUS (per 'spiarm' scharf)
static bool ir_trace_armed = false; // IR-Trace ($3070-$307F) per 'irarm' scharf
// kind: 0=Reg-Read 1=Reg-Write 2=CSN-Wechsel(val=neuer Pegel)
static void spi_log(uint8_t kind, uint8_t reg, uint8_t val) {
if (!spi_trace_armed && !ir_trace_armed) return;
if (spi_trace_n > 0) { // gleiche Reads zusammenfassen
spi_ev_t *e = &spi_trace[spi_trace_n - 1];
if (e->kind == kind && e->reg == reg && e->val == val && e->rep < 0xFFFF) { e->rep++; return; }
}
if (spi_trace_n < SPI_TRACE_MAX) spi_trace[spi_trace_n++] = (spi_ev_t){ kind, reg, val, 1 };
// voll -> einfrieren (nichts mehr aufzeichnen)
}
void t7_figure_set(uint8_t id) { g_figure_id = id; }
uint8_t t7_figure_get(void) { return g_figure_id; }
void t7_spi_set_ret(uint8_t v) { g_spi_ret = v; }
void t7_spitrace_arm(void) { spi_trace_n = 0; spi_trace_armed = true; }
void t7_irtrace_arm(void) { spi_trace_n = 0; ir_trace_armed = true; spi_trace_armed = false; }
int t7_spitrace_count(void) { return spi_trace_n; }
void t7_spitrace_get(int i, uint8_t *kind, uint8_t *reg, uint8_t *val, uint16_t *rep) {
if (i < 0 || i >= spi_trace_n) { *kind=*reg=*val=0; *rep=0; return; }
*kind = spi_trace[i].kind; *reg = spi_trace[i].reg;
*val = spi_trace[i].val; *rep = spi_trace[i].rep;
}
// ======================================================================
// SPI-FLASH-SLAVE (Gotchi-Figur)
//
// Aus dem ROM-Disassembly ($EA6E / $EB20) rekonstruiertes Protokoll:
// - CS = PortB-Data ($3016) Bit 4, aktiv-LOW.
// - Kommando ueber $30B3 (P_SPI_Write): 0x03 = Flash-Read, dann 3 Adressbytes
// (hi, mid, lo) = $71,$72,$73.
// - Danach liefern $30B6-Reads (P_SPI_Read) flash[addr], flash[addr+1], ...
// - $30B7 (P_SPI_Status) Bit 2 (0x04) = "Byte bereit".
// - Presence-Check der Firmware: $3012 (PortA) Bit 5/6.
// Verifiziert: Detektor liest Adresse 0x000001 und prueft auf 'AA 55' -
// makiko.bin[1..2] = AA 55.
// ======================================================================
extern const unsigned char* figure_rom_ptr(void);
extern unsigned int figure_rom_length(void);
// Echtes Full-Duplex-Modell: pro CS-low-Transaktion laeuft eine fortlaufende
// Transfer-Position. Bei einem Flash-Read (0x03) sind die ersten 4 Bytes
// Kommando+Adresse -> Flash gibt waehrenddessen NICHTS aus; die echten Daten
// kommen ab Position 4 (= flash[addr], flash[addr+1], ...). Die Firmware liest
// das exakt so: erst 4 "Leerbytes" wegwerfen, dann die Nutzdaten.
// - RX wird beim SENDEN (Write $30B3) erzeugt und in eine FIFO gelegt.
// - Reads ($30B6) holen die Bytes aus der FIFO (das waehrend des Sendens
// gleichzeitig empfangene Byte - so funktioniert SPI).
// Ist kein 0x03 das erste Byte (z.B. Loopback-Selbsttest $CA2C), wird das
// gesendete Byte zurueckgespiegelt (Echo).
static uint8_t spi_cs = 1; // 1=deasserted(high), 0=asserted(low)
static int spi_pos = 0; // Transfer-Position seit CS-low
static uint8_t spi_cmd0 = 0; // erstes Byte = Kommando
static uint8_t spi_addr_b[3];
static uint32_t spi_addr = 0;
static bool spi_is_read = false; // cmd0 == 0x03
static uint8_t spi_rxfifo[256];
static uint8_t spi_rxw = 0, spi_rxr = 0;
static const unsigned char* spi_rom = 0; // pro Transaktion gecacht (spart Aufrufe pro Byte)
static unsigned int spi_len = 0;
static void spi_cs_set(uint8_t level) // level: Bit4-Pegel von $3016
{
uint8_t cs = level ? 1 : 0;
if (cs == spi_cs) return;
spi_cs = cs;
if (cs == 0) { // fallende Flanke -> neue Transaktion
spi_pos = 0; spi_rxw = spi_rxr = 0; spi_is_read = false; spi_addr = 0;
spi_len = figure_rom_length(); // aktive Figur einmalig cachen
spi_rom = spi_len ? figure_rom_ptr() : 0;
}
}
static void spi_tx(uint8_t v) // Schreibzugriff auf $30B3 (= ein Transfer)
{
if (spi_cs) return; // nur bei aktivem CS
int p = spi_pos;
uint8_t rx;
if (p == 0) { spi_cmd0 = v; spi_is_read = (v == 0x03); }
if (p >= 1 && p <= 3) spi_addr_b[p - 1] = v;
if (p == 3 && spi_is_read)
spi_addr = ((uint32_t)spi_addr_b[0] << 16) | ((uint32_t)spi_addr_b[1] << 8) | spi_addr_b[2];
if (spi_is_read) {
if (p < 4) rx = 0x00; // waehrend cmd+addr: Flash noch stumm
else if (spi_len) { uint32_t a = spi_addr + (uint32_t)(p - 4); rx = (a < spi_len) ? spi_rom[a] : 0x00; }
else rx = 0xFF; // Lite (keine ROM) -> Signatur scheitert
} else {
rx = v; // Loopback/Echo
}
spi_rxfifo[spi_rxw++] = rx; // 8-bit-Index wrappt automatisch (256)
spi_pos++;
}
static uint8_t spi_rx(void) // Lesezugriff auf $30B6
{
if (spi_rxr != spi_rxw) return spi_rxfifo[spi_rxr++];
return 0xFF;
}
// ----- Page table ---------------------------------------------------------
//
// 65536 / 256 = 256 pages. Each page's pointer either points at the start
// of a 256-byte RAM/ROM region OR is NULL to signal "needs slow-path I/O
// handling" (only $3000-$30FF and its 15 mirrors).
//
// Global linkage so the inline accessors in t7_internal.h reach them.
// Renamed to the public-API names that the header expects.
uint8_t *t7_read_page[256];
uint8_t *t7_write_page[256];
// Memory-mapped ROM (XIP-Flash). Wenn gesetzt, zeigt die Page-Table fuer den
// gebankten Bereich direkt in den Flash -> Bank-Switch ohne 32-KB-Kopie.
static const uint8_t *g_rom_mapped = NULL;
// Debug: Zahl der echten Bank-Wechsel (fuer On-Screen-Diagnose).
uint32_t t7_debug_bank_switches = 0;
// Sound: jeder Schreibzugriff auf $3050-$306F wird gezaehlt (Huellkurven-Trigger).
volatile uint32_t t7_snd_write_seq = 0;
volatile uint8_t t7_snd_last_addr = 0;
volatile uint8_t t7_snd_last_val = 0;
uint32_t g_t7_static_off = 0;
uint8_t g_t7_banks = 20;
/* Tamagotchi Friends: the ROM file holds 16 KB more at the start. Bank 0 begins at 0x4000 (static
* ROM, then its code linked to $8000), bank n >= 1 at (n + 1) * 32 KB. Tama-Go: bank n at n * 32 KB. */
static inline size_t t7_bank_off(uint8_t b) { size_t o = (size_t)b * T7_ROM_BANK_SIZE; return g_t7_static_off ? (b ? o + T7_ROM_BANK_SIZE : 0x4000) : o; }
int t7_is_friends(void) { return g_t7_static_off != 0; }
uint16_t t7_rtc_sec_addr(void) { return g_t7_static_off ? 0x0136 : 0x0396; } /* second of the game clock */
// Rebuild the entire page table. Called on init and on every ROM bank switch.
static void rebuild_page_table(void)
{
// $0000-$0FFF — Work RAM (1.5 KB) mirrored.
for (int p = 0; p < 16; p++) {
int wram_page = p % 6;
t7_read_page[p] = g_wram + wram_page * 0x100;
t7_write_page[p] = g_wram + wram_page * 0x100;
}
// $1000-$2FFF — Display RAM (512 B) mirrored across 32 pages.
for (int p = 0x10; p < 0x30; p++) {
t7_read_page[p] = g_dram + (p & 1) * 0x100;
t7_write_page[p] = g_dram + (p & 1) * 0x100;
}
// $3000-$3FFF — I/O registers. NULL = slow path.
for (int p = 0x30; p < 0x40; p++) {
t7_read_page[p] = NULL;
t7_write_page[p] = NULL;
}
// $4000-$BFFF — Banked ROM (zero-copy aus dem gemappten Flash falls verfuegbar).
{
const uint8_t *bankbase = g_rom_mapped
? (g_rom_mapped + t7_bank_off(g_rom_bank_id))
: g_rom_bank_buf;
for (int p = 0x40; p < 0xC0; p++) {
t7_read_page[p] = (uint8_t *)(bankbase + (p - 0x40) * 0x100);
t7_write_page[p] = NULL;
}
}
// $C000-$FFFF — Static ROM.
for (int p = 0xC0; p < 0x100; p++) {
t7_read_page[p] = g_static_rom + (p - 0xC0) * 0x100;
t7_write_page[p] = NULL;
}
}
// ----- ROM banking --------------------------------------------------------
bool t7_load_static_rom(void)
{
ResHandle h = resource_get_handle(RESOURCE_ID_TAMA_ROM);
if (!h) {
APP_LOG(APP_LOG_LEVEL_ERROR, "t7emu: ROM resource not found");
return false;
}
size_t total = resource_size(h);
if (total < T7_STATIC_ROM_SIZE) {
APP_LOG(APP_LOG_LEVEL_ERROR,
"t7emu: ROM too small (%u < %u)",
(unsigned)total, (unsigned)T7_STATIC_ROM_SIZE);
return false;
}
/* Tama-Go: static ROM at 0, 20 banks. Tamagotchi Friends: its reset vector is not at
* 0x3FFC but at 0x7FFC, the static ROM is at 0x4000, 23 banks (see t7_bank_off). */
g_t7_static_off = 0; g_t7_banks = 20;
if (total >= 0x8000) {
uint8_t v[4];
resource_load_byte_range(h, 0x3FFC, v, 2); resource_load_byte_range(h, 0x7FFC, v + 2, 2);
if (!(v[0] | v[1]) && (v[2] | v[3])) { g_t7_static_off = 0x4000; g_t7_banks = 23; }
}
size_t n = resource_load_byte_range(h, g_t7_static_off, g_static_rom,
T7_STATIC_ROM_SIZE);
if (n != T7_STATIC_ROM_SIZE) {
APP_LOG(APP_LOG_LEVEL_ERROR,
"t7emu: short read on static ROM (%u/%u)",
(unsigned)n, (unsigned)T7_STATIC_ROM_SIZE);
return false;
}
APP_LOG(APP_LOG_LEVEL_INFO,
"t7emu: static ROM loaded (%u bytes), total ROM size %u",
(unsigned)n, (unsigned)total);
// Build IRQ vector table from $FFC0-$FFDF.
for (int i = 0; i < 16; i++) {
uint16_t lo = g_static_rom[0x3FC0 + i * 2];
uint16_t hi = g_static_rom[0x3FC0 + i * 2 + 1];
g_irq_vectors[i] = lo | (hi << 8);
}
g_rom_loaded = true;
g_rom_resource = h;
// Falls der ROM direkt im Flash adressierbar ist: zero-copy Banking.
g_rom_mapped = t7_compat_rom_mapped();
if (g_rom_mapped)
APP_LOG(APP_LOG_LEVEL_INFO, "t7emu: ROM memory-mapped (zero-copy banking)");
// Build the page table now that all backing buffers exist.
rebuild_page_table();
return true;
}
void T7_HOT t7_set_rom_bank(uint8_t bank)
{
uint8_t actual = bank % g_t7_banks;
if (actual == g_rom_bank_id && g_rom_loaded) return;
if (!g_rom_loaded) return;
g_rom_bank_id = actual;
t7_debug_bank_switches++;
if (g_rom_mapped) {
// Zero-copy: Page-Table-Zeiger auf die neue Bank im Flash umsetzen.
const uint8_t *bankbase = g_rom_mapped + t7_bank_off(actual);
for (int p = 0x40; p < 0xC0; p++)
t7_read_page[p] = (uint8_t *)(bankbase + (p - 0x40) * 0x100);
return;
}
// Fallback (Host): Bank in den RAM-Puffer kopieren.
size_t offset = t7_bank_off(actual);
size_t n = resource_load_byte_range(g_rom_resource, offset,
g_rom_bank_buf, T7_ROM_BANK_SIZE);
if (n != T7_ROM_BANK_SIZE)
APP_LOG(APP_LOG_LEVEL_ERROR, "t7emu: bank %u short read (%u/%u)",
actual, (unsigned)n, (unsigned)T7_ROM_BANK_SIZE);
}
// ----- I/O register handlers ----------------------------------------------
static void io_write_bank(uint8_t reg, uint8_t value)
{
g_cpureg[reg] = value;
t7_set_rom_bank(value);
}
// $3073, $3074: IRQ pending flags. Writes acknowledge (clear) pending bits.
static void io_write_int_flag(uint8_t reg, uint8_t value)
{
if (ir_trace_armed) spi_log(1, reg, value); // $3073/$3074 Int-Flags (IR-IRQ ack)
g_cpureg[reg] &= ~value;
// Recompute the fast-path cache flag.
g_irq_pending_any = (g_cpureg[0x73] | g_cpureg[0x74]) != 0;
}
static uint8_t s_last_csn = 0xFF;
static void io_write_porta(uint8_t reg, uint8_t value)
{
g_cpureg[reg] = value;
(void)s_last_csn; // PortA-Logging entfernt (war nur Rauschen + Serial-Flut)
}
static uint8_t io_read_porta(uint8_t reg)
{
(void)reg;
uint8_t mask = g_cpureg[0x11];
uint8_t value = g_cpureg[0x12];
uint8_t spi_power = mask & value & 0x10;
uint8_t inserted_figure = g_figure_id;
uint8_t input = g_keys | ((spi_power ? 0 : inserted_figure) << 5);
return (mask & value) | (~mask & input);
}
// $3015 (direction) and $3016 (data) writes both end up here. After
// updating the register, we feed the new bus state to the EEPROM bit
// banging engine. Matches write_portb_dir_data in registers.js exactly:
//
// d = ~mask | data (input bits read as 1 because of pull-ups)
// eeprom.update(d & 4, d & 2, d & 1)
//
// Bit 2 = POWER, bit 1 = CLK, bit 0 = DATA.
#ifdef T7_LINK
void t7_ir_led_on(void);
#endif
static void io_write_portb(uint8_t reg, uint8_t value)
{
g_cpureg[reg] = value;
if (reg == 0x16) spi_cs_set(value & 0x10); // $3016 Bit 4 = SPI-Figur-CS (aktiv-LOW)
#ifdef T7_LINK
if (reg == 0x16 && (value & 0x08)) t7_ir_led_on(); // 1.6.9: infrared LED on (packet for the other Paradise)
#endif
uint8_t mask = g_cpureg[0x15];
uint8_t d = (uint8_t)(~mask) | g_cpureg[0x16];
t7_eeprom_update(d & 4, d & 2, d & 1);
}
// Port B read: bits configured as outputs return what we drove; bits
// configured as inputs read from the EEPROM data line.
//
// (As in the JS reference, the EEPROM output bit is broadcast over all
// input bits via the ~mask term. Only bit 0 is actually meaningful for
// the EEPROM but the firmware only reads bit 0 anyway.)
static uint8_t io_read_portb(uint8_t reg)
{
uint8_t mask = g_cpureg[0x15];
uint8_t eeprom_out = t7_eeprom_output();
uint8_t input_bits = eeprom_out ? (uint8_t)~mask : 0;
return (uint8_t)((mask & g_cpureg[reg]) | input_bits);
}
// Slow-path I/O read — called only when t7_read_page[page] is NULL.
// Renamed from io_read to t7_io_read so the public inline in
// t7_internal.h can call it.
uint8_t T7_HOT t7_io_read(uint16_t addr)
{
uint8_t reg = addr & 0xFF;
switch (reg) {
#ifdef T7_PW_FIX
// Nibble helper used only by the PC password code (bank 2, $6180-$6520):
// the game writes a byte to $3080 and reads back its high nibble ($3082),
// low nibble ($3083) or the nibble-swapped byte ($308A). Without this the
// reads returned 0 and the login password was always 000000000000.
case 0x82: return (uint8_t)(g_cpureg[0x80] >> 4);
case 0x83: return (uint8_t)(g_cpureg[0x80] & 0x0F);
case 0x8A: return (uint8_t)((g_cpureg[0x80] << 4) | (g_cpureg[0x80] >> 4));
#endif
case 0x12: return io_read_porta(reg);
case 0x16: return io_read_portb(reg);
default:
if (reg >= 0xB0 && reg <= 0xBA) { // SPI-Registerbereich ($30B0-$30BA)
uint8_t r;
if (reg == 0xB6) r = spi_rx(); // P_SPI_Read -> Figur-ROM-Daten
else if (reg == 0xB7) r = g_figure_id ? 0x04 : g_cpureg[reg]; // Status Bit2 = bereit
else r = g_cpureg[reg];
spi_log(0, reg, r); // jetzt auch B6 loggen (Diagnose)
return r;
}
if (ir_trace_armed && reg >= 0x70 && reg <= 0x7F) spi_log(0, reg, g_cpureg[reg]); // IR-RX/Status
return g_cpureg[reg];
}
}
// Slow-path I/O write — called only when t7_write_page[page] is NULL.
void T7_HOT t7_io_write(uint16_t addr, uint8_t value)
{
uint8_t reg = addr & 0xFF;
switch (reg) {
case 0x00: io_write_bank(reg, value); break;
#ifdef T7_STOP
case 0x01: /* clock: 7 = CPU stops (STOP), with the original sound only (its timers wake) */
g_cpureg[reg] = value;
if (value == 0x07 && g_snd_on) {
#ifdef T7_STOP_KEYACT
if (g_t7_keyact) break; /* test14: keys in use (1 s after a change): no STOP. Asleep, the firmware missed the
release of a key and took the next press as the same one (on the PC: 3 quick taps, 1 to 2 seen) */
#endif
if ((g_cpureg[0x07] & 0x01) && (g_keys & 0x07) != 0x07) g_cpureg[0x08] |= 0x01; /* a key is down already: awake at once */
else g_t7_halted = 1;
#ifdef T7_STOP_DBG
{ extern void t7_stop_dbg(int); t7_stop_dbg(1); }
#endif
}
break;
#endif
case 0x11: io_write_porta(reg, value); break;
case 0x12: io_write_porta(reg, value); break;
case 0x15: io_write_portb(reg, value); break;
case 0x16: io_write_portb(reg, value); break;
case 0x73: io_write_int_flag(reg, value); break;
case 0x74: io_write_int_flag(reg, value); break;
default:
if (reg >= 0xB0 && reg <= 0xBA) { // SPI-Registerbereich ($30B0-$30BA)
spi_log(1, reg, value);
if (reg == 0xB3) spi_tx(value); // P_SPI_Write -> Kommando/Adresse
g_cpureg[reg] = value;
break;
}
if (reg >= 0x50 && reg <= 0x6F) { // Sound-Registerbereich
t7_snd_write_seq++;
t7_snd_last_addr = reg;
t7_snd_last_val = value;
}
if (ir_trace_armed && reg >= 0x70 && reg <= 0x7F) spi_log(1, reg, value); // IR-TX/Ctrl
g_cpureg[reg] = value;
// Originalton: Timer ($3031-$3035) und DAC ($3060/$3065) mitfuehren
if (g_snd_on && ((reg >= 0x30 && reg <= 0x35) || reg == 0x60 || reg == 0x65))
t7_snd_io_write(reg, value);
#ifdef T7_SND_LAZY
if (g_snd_on && (reg == 0x70 || reg == 0x71)) t7_snd_io_write(reg, value); /* IRQ mask: the timers' events again */
#endif
break;
}
}
// Sound investigation note (kept here for reference):
// $3060/$3062/$3064/$3065 are written in lockstep 4-tuples — strong
// candidate for SPU channel control. Re-add an I/O write counter here
// if/when sound work resumes. Removed to keep hot-path lean and the
// APP_LOG quiet.
// Roh-Auslese eines I/O-Registers ($3000-Seite) fuers Sound-Experiment.
uint8_t t7_debug_ioreg(uint8_t reg) { return g_cpureg[reg]; }
uint32_t t7_debug_snd_seq(void) { return t7_snd_write_seq; }
uint8_t t7_debug_snd_addr(void) { return t7_snd_last_addr; }
uint8_t t7_debug_snd_val(void) { return t7_snd_last_val; }
// ----- IRQ / NMI dispatch helpers ----------------------------------------
void t7_fire_irq(uint8_t i)
{
PROFILE_INC(irqs);
uint16_t mask = (g_cpureg[0x70] << 8) | g_cpureg[0x71];
if (!((0x8000 >> i) & mask)) return;
g_cpureg[0x73 + (i >> 3)] |= 0x80 >> (i & 7);
// Set the fast-path cache flag so the CPU step sees it cheaply.
g_irq_pending_any = 1;
}
void t7_fire_nmi(uint8_t i)
{
PROFILE_INC(nmis);
if (~g_cpureg[0x76] & (0x80 >> i)) return;
t7_cpu_nmi();
}
+311
View File
@@ -0,0 +1,311 @@
/*
* t7_run.inc - fast run loop for the Paradise (included at the end of t7_cpu.c with T7_FASTRUN).
*
* Same instructions as t7_cpu_step(), but the 6502 registers and flags live in local
* variables for a whole run (the compiler keeps most of them in ARM registers) instead of
* being loaded from and stored to memory for every instruction. The result is the same
* instruction by instruction (checked on the PC against t7_cpu_step, see t7/host/runcmp.c).
* Author: mameise
*/
#ifdef T7_FASTRUN
#include "t7_sound.h"
static void ir_hooks(void)
{
if (CPU.pc == 0x60C4) {
s_ir_activity++;
if (s_ir_rx_pending) {
for (int i = 0; i < 32; i++) g_wram[0x200 + i] = s_ir_rx_pkt[i];
g_wram[0x5A] = 0x20; g_wram[0x01B2] = 0x20;
CPU.a = 0x80; s_nz_z = 0x80; s_flag_c = 0; CPU.pc = 0x60C7;
s_ir_rx_pending = 0;
}
} else if (s_ir_bridge_en && CPU.pc == 0x7926) {
s_ir_tx_pending = 1;
}
}
uint32_t T7_HOT t7_cpu_run(uint32_t budget)
{
uint32_t pc = CPU.pc, a = CPU.a, x = CPU.x, y = CPU.y, sp = CPU.s;
uint32_t fc = s_flag_c ? 1u : 0u, fv = s_flag_v, fd = s_flag_d, fi = s_flag_i, nzn = s_nz_n, nzz = s_nz_z;
uint8_t *const *rp = t7_read_page, *const *wp = t7_write_page;
const int son = g_snd_on;
int32_t snd = g_snd_next;
uint32_t cyc = 0;
#ifdef T7_JIT
uint32_t lp = pc + 0x8000u; /* pc of the last interpreted instruction: blocks start only where a run of code starts */
#endif
uint32_t chk = 1, b3 = (g_rom_bank_id == 3 && !g_t7_static_off); /* look at IRQs / IR hooks only when something changed */
#define T7R_SAVE() do { CPU.pc = (uint16_t)pc; CPU.a = (uint8_t)a; CPU.x = (uint8_t)x; CPU.y = (uint8_t)y; CPU.s = (uint8_t)sp; \
s_flag_c = (uint8_t)fc; s_flag_v = (uint8_t)fv; s_flag_d = (uint8_t)fd; s_flag_i = (uint8_t)fi; s_nz_n = (uint8_t)nzn; s_nz_z = (uint8_t)nzz; g_snd_next = snd; } while (0)
#define T7R_LOAD() do { pc = CPU.pc; a = CPU.a; x = CPU.x; y = CPU.y; sp = CPU.s; fc = s_flag_c ? 1u : 0u; fv = s_flag_v; fd = s_flag_d; \
fi = s_flag_i; nzn = s_nz_n; nzz = s_nz_z; snd = g_snd_next; } while (0)
#define RD(ad) ({ uint32_t _ra = (ad); const uint8_t *_rp = rp[_ra >> 8]; _rp ? (uint32_t)_rp[_ra & 0xFF] : (uint32_t)t7_io_read((uint16_t)_ra); })
#define WR(ad, v) do { uint32_t _wa = (ad); uint8_t *_wp = wp[_wa >> 8]; uint8_t _wv = (uint8_t)(v); \
if (_wp) _wp[_wa & 0xFF] = _wv; else if ((_wa >> 12) == 3) { g_snd_next = snd; t7_io_write((uint16_t)_wa, _wv); snd = g_snd_next; chk = 1; b3 = (g_rom_bank_id == 3 && !g_t7_static_off); } } while (0)
#define FETCH() ({ uint32_t _fv = RD(pc); pc = (pc + 1) & 0xFFFF; _fv; })
#define FETCH16() ({ uint32_t _f16l = FETCH(); uint32_t _f16h = FETCH(); _f16l | (_f16h << 8); })
#define PUSH(v) do { g_wram[0x100 | sp] = (uint8_t)(v); sp = (sp - 1) & 0xFF; } while (0) /* page 1 is always work RAM */
#define PULL() ({ sp = (sp + 1) & 0xFF; (uint32_t)g_wram[0x100 | sp]; })
#define NZ(v) do { nzn = nzz = (v); } while (0)
#define PACKP() ((fc ? 0x01u : 0u) | (nzz == 0 ? 0x02u : 0u) | (fi ? 0x04u : 0u) | (fd ? 0x08u : 0u) | 0x20u | (fv ? 0x40u : 0u) | (nzn & 0x80u))
#define UNPACKP(p) do { uint32_t _up = (p); fc = _up & 1u; fi = _up & 0x04u; fd = _up & 0x08u; fv = _up & 0x40u; nzn = (_up & 0x80u) ? 0x80u : 0u; nzz = (_up & 0x02u) ? 0u : 1u; } while (0)
/* addressing */
#define A_IMM() ({ uint32_t _im = pc; pc = (pc + 1) & 0xFFFF; _im; })
#define A_ZP() FETCH()
#define ZRD(z) ((uint32_t)g_wram[(z)]) /* page 0: always work RAM */
#define ZWR(z, v) (g_wram[(z)] = (uint8_t)(v))
#define A_ZPX() ((FETCH() + x) & 0xFF)
#define A_ZPY() ((FETCH() + y) & 0xFF)
#define A_ABS() FETCH16()
#define A_ABX() ((FETCH16() + x) & 0xFFFF)
#define A_ABY() ((FETCH16() + y) & 0xFFFF)
#define A_INX() ({ uint32_t _xz = (FETCH() + x) & 0xFF; uint32_t _xl = ZRD(_xz); uint32_t _xh = ZRD((_xz + 1) & 0xFF); _xl | (_xh << 8); })
#define A_INY() ({ uint32_t _yz = FETCH(); uint32_t _yl = ZRD(_yz); uint32_t _yh = ZRD((_yz + 1) & 0xFF); ((_yl | (_yh << 8)) + y) & 0xFFFF; })
#define A_IND() ({ uint32_t _ip = FETCH16(); uint32_t _il = RD(_ip); uint32_t _ih = RD((_ip & 0xFF00) | ((_ip + 1) & 0xFF)); _il | (_ih << 8); })
/* operations */
#define LDA(m) do { a = RD(m); NZ(a); } while (0)
#define LDX(m) do { x = RD(m); NZ(x); } while (0)
#define LDY(m) do { y = RD(m); NZ(y); } while (0)
#define AND(m) do { a &= RD(m); NZ(a); } while (0)
#define ORA(m) do { a |= RD(m); NZ(a); } while (0)
#define EOR(m) do { a ^= RD(m); NZ(a); } while (0)
#define CMPR(r, m) do { uint32_t _d = RD(m); fc = (r) >= _d; NZ(((r) - _d) & 0xFF); } while (0)
#define INCM(m) do { uint32_t _a = (m); uint32_t _v = (RD(_a) + 1) & 0xFF; NZ(_v); WR(_a, _v); } while (0)
#define DECM(m) do { uint32_t _a = (m); uint32_t _v = (RD(_a) - 1) & 0xFF; NZ(_v); WR(_a, _v); } while (0)
#define ASLM(m) do { uint32_t _a = (m); uint32_t _d = RD(_a); uint32_t _o = (_d << 1) & 0xFF; fc = _d >> 7; NZ(_o); WR(_a, _o); } while (0)
#define LSRM(m) do { uint32_t _a = (m); uint32_t _d = RD(_a); uint32_t _o = _d >> 1; fc = _d & 1u; NZ(_o); WR(_a, _o); } while (0)
#define ROLM(m) do { uint32_t _a = (m); uint32_t _d = RD(_a); uint32_t _o = ((_d << 1) & 0xFF) | fc; fc = _d >> 7; NZ(_o); WR(_a, _o); } while (0)
#define RORM(m) do { uint32_t _a = (m); uint32_t _d = RD(_a); uint32_t _o = (_d >> 1) | (fc << 7); fc = _d & 1u; NZ(_o); WR(_a, _o); } while (0)
#define BIT(m) do { uint32_t _v = RD(m); fv = _v & 0x40u; nzn = _v; nzz = a & _v; } while (0)
#define ADC(m) do { uint32_t _d = RD(m); uint32_t _o = a + _d + fc; fv = (~(a ^ _d) & (a ^ _o)) & 0x80u; NZ(_o & 0xFF); \
if (fd) { int _al = (int)(a & 0x0F) + (int)(_d & 0x0F) + (int)fc; int _ah = (int)(a & 0xF0) + (int)(_d & 0xF0) + ((_al >= 0x10) ? 0x10 : 0); \
if (_al > 0x09) _al += 0x06; if (_ah > 0x90) _ah += 0x60; _o = (uint32_t)((_al & 0x0F) + _ah); } \
fc = _o > 0xFF; a = _o & 0xFF; } while (0)
#define SBC(m) do { uint32_t _d = RD(m); int _o = (int)a - (int)_d - (fc ? 0 : 1); fv = ((a ^ _d) & (a ^ (uint32_t)_o)) & 0x80u; NZ((uint32_t)_o & 0xFF); \
fc = _o >= 0; \
if (fd) { int _al = (int)(a & 0x0F) - (int)(_d & 0x0F) - (fc ? 0 : 1); int _ah = (int)(a & 0xF0) - (int)(_d & 0xF0) - ((_al < 0) ? 0x10 : 0); \
if (_al < 0) _al -= 0x06; if (_ah < 0) _ah -= 0x60; _o = (_al & 0x0F) + _ah; } \
a = (uint32_t)_o & 0xFF; } while (0)
#define BR(cond) do { int32_t _o = (int8_t)FETCH(); if (cond) pc = (pc + (uint32_t)_o) & 0xFFFF; } while (0)
while (cyc < budget) {
if (b3 && (pc == 0x60C4 || pc == 0x7926)) { T7R_SAVE(); ir_hooks(); T7R_LOAD(); }
if (chk) {
#ifdef T7_STOP
/* test12: halted (STOP): the cycles up to the end or the next sound event pass without instructions; any
* IRQ request wakes the CPU (taken only when the I flag allows, as on the chip) */
if (g_t7_halted) {
if (g_cpureg[0x73] | g_cpureg[0x74]) g_t7_halted = 0;
else {
uint32_t lim = budget - cyc;
if (son) { if (snd <= 0) lim = 1; else if ((uint32_t)snd < lim) lim = (uint32_t)snd; }
cyc += lim; g_t7_idle_cyc += lim;
if (son && (snd -= (int32_t)lim) <= 0) { g_snd_next = snd; t7_snd_service(); snd = g_snd_next; }
continue; /* chk stays set */
}
}
#endif
if (g_irq_pending_any && !fi) {
uint32_t pending = ((uint32_t)g_cpureg[0x73] << 8) | g_cpureg[0x74];
if (pending) {
PROFILE_INC(irq_entries);
int idx = __builtin_clz(pending << 16);
PUSH(pc >> 8); PUSH(pc & 0xFF); PUSH(PACKP());
pc = g_irq_vectors[idx]; fi = 1;
#ifdef T7_BLIT_CACHE
if (g_bm.on) { if (g_bm.irq++ == 0) g_bm.irq0 = (int32_t)cyc; } /* its cycles up to the RTI do not count */
#endif
g_irq_pending_any = (g_cpureg[0x73] | g_cpureg[0x74]) != 0;
}
}
#ifdef T7_IDLE
/* test12: the BEQ went back to $CE66 (chk bit 1) and no IRQ came: the passes that fit up to the end or the
* next sound event at once, the same state as interpreting them (t7_idle_check, TamaGo-Pebble) */
if ((chk & 2u) && pc == T7_IDLE_PC && !fd && g_wram[0x2D] == 0) {
uint32_t lim = budget - cyc;
if (son) { if (snd <= 0) lim = 0; else if ((uint32_t)snd < lim) lim = (uint32_t)snd; }
uint32_t pass = t7_idle_pass_cyc(), n = lim / pass;
if (n) {
static const uint8_t k[5] = { 0x07, 0x03, 0x0D, 0x17, 0x13 };
uint32_t prev = 0;
for (int i = 0; i < 5; i++) { uint32_t v = (g_wram[0xC4 + i] + (n - 1u) * k[i]) & 0xFF; prev = v; g_wram[0xC4 + i] = (uint8_t)(v + k[i]); }
uint32_t o = prev + 0x13u;
fv = (~(prev ^ 0x13u) & (prev ^ o)) & 0x80u; fc = o > 0xFFu;
g_wram[0x100 | sp] = 0xCE; g_wram[0x100 | ((sp - 1) & 0xFF)] = 0x74;
a = 0; NZ(0);
uint32_t s = n * pass;
cyc += s; g_t7_idle_cyc += s;
if (son && (snd -= (int32_t)s) <= 0) { g_snd_next = snd; t7_snd_service(); snd = g_snd_next; }
chk = 1; continue;
}
}
#endif
}
chk = 0;
#ifdef T7_BLIT_CACHE
/* the time of a left out blit passes here, in the caller's place; an IRQ is taken in between as above */
if (g_bs.rem && pc == g_bs.pc && sp == g_bs.sp) {
uint32_t lim = budget - cyc; if (lim > g_bs.rem) lim = g_bs.rem;
if (son) { if (snd <= 0) lim = 0; else if ((uint32_t)snd < lim) lim = (uint32_t)snd; }
cyc += lim; g_bs.rem -= lim;
if (son && (snd -= (int32_t)lim) <= 0) { g_snd_next = snd; t7_snd_service(); snd = g_snd_next; }
chk = 1; continue;
}
#endif
#ifdef T7_JIT
/* 1.6.12 test2: translated ROM code, when the interpreter would run all of the block now (t7_jit.c) */
if (g_t7j_on && !fd && pc >= 0x4000u) {
T7JEnt *je = t7_jit_get((uint32_t)(uintptr_t)(rp[pc >> 8] + (pc & 0xFFu)), pc, rp, b3 | (((pc - lp - 1u) & 0xFFFFu) > 2u ? 2u : 0u));
if (je && cyc + je->pre < budget && (!son || snd > (int32_t)je->all)) {
T7J js;
js.a = a; js.x = x; js.y = y; js.s = sp; js.nzn = nzn; js.nzz = nzz; js.fc = fc; js.fv = fv; js.fi = fi;
js.snd = snd; js.wram = g_wram; js.rp = rp; js.wp = wp; js.cyc = 0; js.rem = (int32_t)(budget - cyc); js.son = (uint32_t)son;
t7_jit_run(&js, je->code);
a = js.a; x = js.x; y = js.y; sp = js.s; nzn = js.nzn; nzz = js.nzz; fc = js.fc; fv = js.fv; fi = js.fi; pc = js.pc;
cyc += js.cyc;
if (js.io) { /* ended after an I/O write: as WR, then the IRQ check */
snd = g_snd_next; chk = 1; b3 = (g_rom_bank_id == 3 && !g_t7_static_off);
if (son && (snd -= (int32_t)js.io) <= 0) { g_snd_next = snd; t7_snd_service(); snd = g_snd_next; }
} else snd = js.snd;
lp = pc + 0x8000u;
continue;
}
lp = pc;
}
#endif
#ifdef T7_COUNT
{ extern volatile uint32_t g_t7_ninstr; g_t7_ninstr++; }
#endif
uint32_t op = FETCH();
uint32_t c = opcode_cycles[op];
switch (op) {
case 0xA9: LDA(A_IMM()); break; case 0xA5: a = ZRD(FETCH()); NZ(a); break; case 0xB5: a = ZRD(A_ZPX()); NZ(a); break; case 0xAD: LDA(A_ABS()); break;
case 0xBD: LDA(A_ABX()); break; case 0xB9: LDA(A_ABY()); break; case 0xA1: LDA(A_INX()); break; case 0xB1: LDA(A_INY()); break;
case 0xA2: LDX(A_IMM()); break; case 0xA6: x = ZRD(FETCH()); NZ(x); break; case 0xB6: LDX(A_ZPY()); break; case 0xAE: LDX(A_ABS()); break; case 0xBE: LDX(A_ABY()); break;
case 0xA0: LDY(A_IMM()); break; case 0xA4: y = ZRD(FETCH()); NZ(y); break; case 0xB4: LDY(A_ZPX()); break; case 0xAC: LDY(A_ABS()); break; case 0xBC: LDY(A_ABX()); break;
case 0x85: ZWR(FETCH(), a); break; case 0x95: ZWR(A_ZPX(), a); break; case 0x8D: WR(A_ABS(), a); break; case 0x9D: WR(A_ABX(), a); break;
case 0x99: WR(A_ABY(), a); break; case 0x81: WR(A_INX(), a); break; case 0x91: WR(A_INY(), a); break;
case 0x86: ZWR(FETCH(), x); break; case 0x96: WR(A_ZPY(), x); break; case 0x8E: WR(A_ABS(), x); break;
case 0x84: ZWR(FETCH(), y); break; case 0x94: WR(A_ZPX(), y); break; case 0x8C: WR(A_ABS(), y); break;
case 0xAA: x = a; NZ(x); break; case 0xA8: y = a; NZ(y); break; case 0x8A: a = x; NZ(a); break; case 0x98: a = y; NZ(a); break;
case 0xBA: x = sp; NZ(x); break; case 0x9A: sp = x; break;
case 0xE8: x = (x + 1) & 0xFF; NZ(x); break; case 0xC8: y = (y + 1) & 0xFF; NZ(y); break;
case 0xCA: x = (x - 1) & 0xFF; NZ(x); break; case 0x88: y = (y - 1) & 0xFF; NZ(y); break;
case 0xE6: { uint32_t _z = FETCH(); uint32_t _v = (ZRD(_z) + 1) & 0xFF; NZ(_v); ZWR(_z, _v); } break; case 0xF6: INCM(A_ZPX()); break; case 0xEE: INCM(A_ABS()); break; case 0xFE: INCM(A_ABX()); break;
case 0xC6: { uint32_t _z = FETCH(); uint32_t _v = (ZRD(_z) - 1) & 0xFF; NZ(_v); ZWR(_z, _v); } break; case 0xD6: DECM(A_ZPX()); break; case 0xCE: DECM(A_ABS()); break; case 0xDE: DECM(A_ABX()); break;
case 0x29: AND(A_IMM()); break; case 0x25: a &= ZRD(FETCH()); NZ(a); break; case 0x35: AND(A_ZPX()); break; case 0x2D: AND(A_ABS()); break;
case 0x3D: AND(A_ABX()); break; case 0x39: AND(A_ABY()); break; case 0x21: AND(A_INX()); break; case 0x31: AND(A_INY()); break;
case 0x09: ORA(A_IMM()); break; case 0x05: a |= ZRD(FETCH()); NZ(a); break; case 0x15: ORA(A_ZPX()); break; case 0x0D: ORA(A_ABS()); break;
case 0x1D: ORA(A_ABX()); break; case 0x19: ORA(A_ABY()); break; case 0x01: ORA(A_INX()); break; case 0x11: ORA(A_INY()); break;
case 0x49: EOR(A_IMM()); break; case 0x45: EOR(A_ZP()); break; case 0x55: EOR(A_ZPX()); break; case 0x4D: EOR(A_ABS()); break;
case 0x5D: EOR(A_ABX()); break; case 0x59: EOR(A_ABY()); break; case 0x41: EOR(A_INX()); break; case 0x51: EOR(A_INY()); break;
case 0x24: BIT(A_ZP()); break; case 0x2C: BIT(A_ABS()); break;
case 0x0A: fc = a >> 7; a = (a << 1) & 0xFF; NZ(a); break;
case 0x06: ASLM(A_ZP()); break; case 0x16: ASLM(A_ZPX()); break; case 0x0E: ASLM(A_ABS()); break; case 0x1E: ASLM(A_ABX()); break;
case 0x4A: fc = a & 1u; a >>= 1; NZ(a); break;
case 0x46: LSRM(A_ZP()); break; case 0x56: LSRM(A_ZPX()); break; case 0x4E: LSRM(A_ABS()); break; case 0x5E: LSRM(A_ABX()); break;
case 0x2A: { uint32_t _o = ((a << 1) & 0xFF) | fc; fc = a >> 7; a = _o; NZ(a); } break;
case 0x26: ROLM(A_ZP()); break; case 0x36: ROLM(A_ZPX()); break; case 0x2E: ROLM(A_ABS()); break; case 0x3E: ROLM(A_ABX()); break;
case 0x6A: { uint32_t _o = (a >> 1) | (fc << 7); fc = a & 1u; a = _o; NZ(a); } break;
case 0x66: RORM(A_ZP()); break; case 0x76: RORM(A_ZPX()); break; case 0x6E: RORM(A_ABS()); break; case 0x7E: RORM(A_ABX()); break;
case 0x69: ADC(A_IMM()); break; case 0x65: ADC(A_ZP()); break; case 0x75: ADC(A_ZPX()); break; case 0x6D: ADC(A_ABS()); break;
case 0x7D: ADC(A_ABX()); break; case 0x79: ADC(A_ABY()); break; case 0x61: ADC(A_INX()); break; case 0x71: ADC(A_INY()); break;
case 0xE9: SBC(A_IMM()); break; case 0xE5: SBC(A_ZP()); break; case 0xF5: SBC(A_ZPX()); break; case 0xED: SBC(A_ABS()); break;
case 0xFD: SBC(A_ABX()); break; case 0xF9: SBC(A_ABY()); break; case 0xE1: SBC(A_INX()); break; case 0xF1: SBC(A_INY()); break;
case 0xC9: CMPR(a, A_IMM()); break; case 0xC5: { uint32_t _d = ZRD(FETCH()); fc = a >= _d; NZ((a - _d) & 0xFF); } break; case 0xD5: CMPR(a, A_ZPX()); break; case 0xCD: CMPR(a, A_ABS()); break;
case 0xDD: CMPR(a, A_ABX()); break; case 0xD9: CMPR(a, A_ABY()); break; case 0xC1: CMPR(a, A_INX()); break; case 0xD1: CMPR(a, A_INY()); break;
case 0xE0: CMPR(x, A_IMM()); break; case 0xE4: CMPR(x, A_ZP()); break; case 0xEC: CMPR(x, A_ABS()); break;
case 0xC0: CMPR(y, A_IMM()); break; case 0xC4: CMPR(y, A_ZP()); break; case 0xCC: CMPR(y, A_ABS()); break;
case 0x18: fc = 0; break; case 0x38: fc = 1; break; case 0x58: fi = 0; chk = 1; break; case 0x78: fi = 1; break;
case 0xB8: fv = 0; break; case 0xD8: fd = 0; break; case 0xF8: fd = 1; break;
case 0x48: PUSH(a); break;
case 0x68: a = PULL(); NZ(a); break;
case 0x08: PUSH(PACKP() | 0x10u); break;
case 0x28: UNPACKP(PULL()); chk = 1; break;
case 0x4C: pc = A_ABS(); break;
case 0x6C: pc = A_IND(); break;
#ifdef T7_JSR_HLE
case 0x20: { uint32_t _t = A_ABS(); uint32_t _r = (pc - 1) & 0xFFFF;
if (g_t7_hle && (_t == 0xD460u || _t == 0xE4CDu)) {
#ifdef T7_BLIT_CACHE
if (_t == 0xE4CDu && (g_t7_hle & 2u) && g_t7_dark) { /* blit, screen off: left out when its time is known */
uint8_t _k[12]; uint32_t _s = bc_key(_k);
if (g_bc[_s].k[11] && bc_same(g_bc[_s].k, _k)) {
g_wram[0x100 | sp] = (uint8_t)(_r >> 8); g_wram[0x100 | ((sp - 1) & 0xFF)] = (uint8_t)_r;
g_bs.rem = g_bc[_s].cyc; g_bs.pc = pc; g_bs.sp = sp; g_bc_hit++; break; /* pc is the return address */
} else if (!g_bm.on) { /* measure this one */
g_bm.on = 1; g_bm.sp = sp; g_bm.ret = (_r + 1) & 0xFFFF; g_bm.start = (int32_t)(cyc + c); g_bm.irq = 0; g_bm.irqc = 0; g_bm.slot = _s; bc_copy(g_bm.k, _k); g_bc_miss++;
#ifdef T7_JIT
g_bm.jit = g_t7j_on; g_t7j_on = 0;
#endif
}
}
#else
if (_t == 0xE4CDu && (g_t7_hle & 2u) && g_t7_dark) { /* blit, screen off: JSR + RTS only */
g_wram[0x100 | sp] = (uint8_t)(_r >> 8); g_wram[0x100 | ((sp - 1) & 0xFF)] = (uint8_t)_r;
c += opcode_cycles[0x60]; break;
}
#endif
#if defined(T7_WAKE_FRESH) || defined(T7_DARK_PEEK)
if (_t == 0xE4CDu) g_t7_blits++; /* a blit that runs (the screen after a wake: drawn anew) */
#endif
if (_t == 0xD460u && (g_t7_hle & 1u)) { /* delay: whole when its RTS runs in this run */
uint32_t pre = c + opcode_cycles[0xA2] + 47u * (opcode_cycles[0xE8] + opcode_cycles[0xD0]), all = pre + opcode_cycles[0x60];
if (cyc + pre < budget && (!son || snd > (int32_t)all)) {
g_wram[0x100 | sp] = (uint8_t)(_r >> 8); g_wram[0x100 | ((sp - 1) & 0xFF)] = (uint8_t)_r;
x = 0; nzn = 0; nzz = 0; c = all; break;
}
}
}
PUSH(_r >> 8); PUSH(_r & 0xFF); pc = _t; } break;
#else
case 0x20: { uint32_t _t = A_ABS(); uint32_t _r = (pc - 1) & 0xFFFF; PUSH(_r >> 8); PUSH(_r & 0xFF); pc = _t; } break;
#endif
case 0x60: { uint32_t _l = PULL(); uint32_t _h = PULL(); pc = ((_l | (_h << 8)) + 1) & 0xFFFF;
#ifdef T7_BLIT_CACHE
if (g_bm.on && sp == g_bm.sp && pc == g_bm.ret) { /* the measured blit ends: note its cycles */
T7BC *_e = &g_bc[g_bm.slot]; bc_copy(_e->k, g_bm.k); _e->cyc = (uint32_t)((int32_t)(cyc + c) - g_bm.start - g_bm.irqc); g_bm.on = 0;
#ifdef T7_BC_LOG
{ extern void t7_bc_log(const uint8_t *, uint32_t); t7_bc_log(g_bm.k, _e->cyc); }
#endif
#ifdef T7_JIT
g_t7j_on = g_bm.jit;
#endif
}
#endif
} break;
case 0x40: { UNPACKP(PULL()); uint32_t _l = PULL(); uint32_t _h = PULL(); pc = _l | (_h << 8); } chk = 1;
#ifdef T7_BLIT_CACHE
if (g_bm.on && g_bm.irq && --g_bm.irq == 0) g_bm.irqc += (int32_t)(cyc + c) - g_bm.irq0;
#endif
break;
case 0x00: pc = (pc + 1) & 0xFFFF; PUSH(pc >> 8); PUSH(pc & 0xFF); PUSH(PACKP() | 0x10u);
{ uint32_t _l = RD(0xFFFE); uint32_t _h = RD(0xFFFF); pc = _l | (_h << 8); } fi = 1; break;
case 0x10: BR(!(nzn & 0x80u)); break; case 0x30: BR(nzn & 0x80u); break;
case 0x50: BR(!fv); break; case 0x70: BR(fv); break;
case 0x90: BR(!fc); break; case 0xB0: BR(fc); break;
case 0xD0: BR(nzz != 0); break;
#ifdef T7_IDLE
case 0xF0: BR(nzz == 0); if (pc == T7_IDLE_PC && g_t7_idle_ok) chk |= 2u; break;
#else
case 0xF0: BR(nzz == 0); break;
#endif
case 0xEA: break;
default: c = 2; break;
}
cyc += c;
if (son && (snd -= (int32_t)c) <= 0) { g_snd_next = snd; t7_snd_service(); snd = g_snd_next; chk = 1; }
}
#ifdef T7_BLIT_CACHE
if (g_bm.on) { g_bm.start -= (int32_t)cyc; if (g_bm.irq) g_bm.irq0 -= (int32_t)cyc; } /* goes on in the next run */
#endif
T7R_SAVE();
return cyc;
}
#undef T7R_SAVE
#undef T7R_LOAD
#undef RD
#undef WR
#endif
+541
View File
@@ -0,0 +1,541 @@
/*
* t7_sound.c - Originalton der V7 (Timer + DAC)
*
* Aus dem ROM rekonstruiert (Einzelheiten in docs/TON_FINDINGS.md):
* - Timer 0: Vorladewert $3032/$3033, zaehlt aufwaerts bis $FFFF, dann IRQ 0
* und neu laden. Takt 4 MHz, wenn das obere Nibble von $3031 = 2 ist.
* IRQ 0 ist der Ausgabetakt: Rechteck (Ton) oder Samples (5000 Hz).
* - Timer 1: Vorladewert $3034/$3035, unteres Nibble von $3031 = 2.
* Takt 32768 Hz, mit $3030 Bit 0 = 1 das Sechzehnfache (524288 Hz, ab v1.9).
* Ueberlauf -> IRQ 12 = Takt des Melodie-Sequenzers ($D230), im
* Normalbetrieb ($FC00) also 256 Hz.
* - $3060 = 8-Bit-DAC, vorzeichenbehaftet (0 = Ruhe). Der ROM rampt den
* Wert bei $F605 selbst auf 0, damit es nicht knackt.
* - $3065 Bit 1 = Verstaerker an.
*
* Belege: Die Notentabelle $F851/$F89A beginnt bei 65 Hz (C2), die
* Sample-Rate aus $F84F ergibt bei 4 MHz genau 5000 Hz, der Schlaftest $C78E
* stellt Timer 1 bei $3030=0 auf $8000 (bei 32768 Hz genau 1 s) und eine
* Melodie im ROM laeuft damit exakt mit 120 BPM.
*
* Aus dem DAC-Verlauf entsteht direkt ein fertiger 16-Bit-Tonstrom
* (Kastenfilter pro Ausgabe-Sample, sanfter Tiefpass, Gleichanteil-Filter),
* den die Plattform (Android AudioTrack / ESP32 I2S) nur noch abholt.
*
* Alles haengt am Schalter g_snd_on. Ist er aus, laufen weder Timer noch
* IRQ 0/12 - exakt das alte Verhalten.
*
* Aufwand: pro Instruktion nur ein Addieren und ein Vergleich. Timer und
* Tonstrom werden ereignisgesteuert nachgezogen.
*/
#include "t7_internal.h"
#include "t7_sound.h"
uint8_t g_snd_on = 0;
int32_t g_snd_next = 0x7FFFFFFF; // Zyklen bis zum naechsten Timer-Ereignis (zaehlt pro Instruktion runter)
uint32_t g_snd_irq12 = 0, g_snd_irq0 = 0;
// Zeitbasis: jetzt = s_base + (s_span - g_snd_next). So kostet die heisse
// Schleife pro Instruktion nur ein Subtrahieren und einen Vergleich.
static uint64_t s_base = 0; // CPU-Zyklen bei der letzten Planung
static int32_t s_span = 0x7FFFFFFF; // damals geplanter Abstand
uint32_t t7_snd_tone_hz(uint8_t *level);
static inline uint64_t snd_now(void) { return s_base + (uint64_t)(int64_t)(s_span - g_snd_next); }
// Takt Timer 0. Die Notentabelle ergibt bei 4 MHz ein C2 (65 Hz) als tiefsten
// Ton, bei 8 MHz ein C3. Am Geraet klang 4 MHz eine Oktave zu tief (v1.7,
// Bernds Hoertest), daher 8 MHz. Die Sample-Rate aus $F84F ist dann 10 kHz.
#ifndef T7_T0_HZ
#define T7_T0_HZ 8000000u
#endif
#define T0_HZ T7_T0_HZ
// ---- Ton-Ereignisse fuer Piezo-Geraete (ESP32) ----
// Alle s_smp_per Zyklen wird der gerade gespielte Rechteckton abgefragt; aendert
// er sich, landet (Zeitpunkt in CPU-Zyklen, Frequenz) in einem kleinen Ring.
// Die Plattform spielt die Ereignisse zeitversetzt in Echtzeit ab.
#define TEV_N 64u
static uint32_t s_smp_per = 0; // 0 = aus
static uint64_t s_smp_due = 0;
static uint32_t s_tev_last = 0;
static uint32_t s_tev_cand = 0; // neuer Wert, muss TEV_STABLE Abfragen lang stehen (keine Zuckungen)
#define TEV_STABLE 4u // ein neuer Ton muss 4 ms stehen (Zucken beim Notenwechsel weg)
#define TEV_STABLE_OFF 2u // Stille nur 2 ms (die kurze Pause zwischen gleichen Noten bleibt)
static uint8_t s_tev_seen = 0;
static uint8_t s_ev_on = 0; // Ereignisse fuer den Piezo (ESP32) gewuenscht
// ---- Klarer Ton (Android): Rechteck aus Tonhoehe + Huellkurve neu erzeugen ----
// Die Firmware kippt den DAC per Software im IRQ 0. Andere Interrupts (Sequenzer
// 256 Hz, Bild) verschieben diese Flanken um bis zu ~100 Zyklen. Aus dem DAC
// abgetastet klingt das rauschig mit leisem Knacksen darunter. Im Klar-Modus
// wird deshalb nur gelesen, WAS die Firmware spielt (Tonhoehe aus Timer 0,
// Lautstaerke aus der Huellkurve $93), und daraus ein sauberes, bandbegrenztes
// Rechteck erzeugt.
#ifndef T7_SND_SYN_N
#define T7_SND_SYN_N 512u // Zustaende im 1-ms-Raster (512 ms Vorlauf); ESP32 braucht das nicht
#endif
#define SYN_N T7_SND_SYN_N
typedef struct { uint64_t c; uint32_t hz; uint8_t lv; } syn_t;
static syn_t s_syn[SYN_N];
static uint32_t s_syn_w = 0, s_syn_r = 0;
static uint8_t s_syn_on = 0;
static float s_ph = 0.0f; // Phase 0..1
static float s_amp = 0.0f; // geglaettete Lautstaerke
static uint32_t s_ohz = 0; // zuletzt gespielte Tonhoehe (fuers Ausklingen)
static uint32_t s_rate = 48000;
static uint64_t s_tev_c[TEV_N];
static uint32_t s_tev_hz[TEV_N];
static volatile uint32_t s_tev_w = 0, s_tev_r = 0;
// Timer 1 bei $3030 Bit 0 = 1. v1.7/v1.8: 262144 (Sequenzer 256 Hz), am Geraet
// zu langsam (Bernd, Android und ESP32). Ab v1.9 524288 -> Sequenzer 512 Hz.
#ifndef T7_T1_FAST_HZ
#define T7_T1_FAST_HZ 524288u
#endif
static uint32_t s_t1_fast = T7_T1_FAST_HZ;
static uint32_t s_emu_hz = 4000000u; // CPU-Zyklen pro Echtzeit-Sekunde
static uint8_t s_run[2];
static uint64_t s_per[2]; // Periode in CPU-Zyklen (16.16)
static uint64_t s_due[2]; // naechster Ueberlauf, absolut (16.16)
// ---- Tonstrom ----
static uint8_t s_cap = 0;
static uint64_t s_cps_fp = 0; // CPU-Zyklen pro Ausgabe-Sample (16.16)
static uint64_t s_rend = 0; // bis hierhin gerendert (16.16)
static uint64_t s_pos = 0; // Anteil im laufenden Sample (16.16)
static int64_t s_acc = 0;
static int32_t s_dac = 0; // aktueller DAC-Wert (-128..127), 0 wenn Verstaerker aus
static int32_t s_vol = 60; // 0..100
static int32_t s_hp_x = 0, s_hp_y = 0; // Gleichanteil-Filter
static int32_t s_lp = 0; // sanfter Tiefpass (kleiner Lautsprecher)
#ifndef T7_SND_RING
#define T7_SND_RING 65536u // Zweierpotenz, 1,36 s bei 48 kHz
#endif
#define RING T7_SND_RING
static int16_t s_ring[RING];
static volatile uint32_t s_w = 0, s_r = 0;
static uint32_t s_rfrac = 0; // Nachkomma-Leseposition beim Abholen (16.16)
static int32_t s_last = 0; // zuletzt ausgegebener Wert
static uint32_t s_under = 0; // Zaehler Unterdeckungen (Diagnose)
static uint32_t timer_hz(int t)
{
if (t == 0) return T0_HZ;
return (g_cpureg[0x30] & 0x01) ? s_t1_fast : 32768u;
}
#ifdef T7_SND_LAZY
/* 1.6.12 test1 (battery): a timer whose IRQ is masked (0: IRQ 0, $3070 bit 7; 1: IRQ 12, $3071 bit 3) gets no events:
* its interrupt would do nothing (t7_fire_irq drops masked ones). The Tama-Go keeps both timers running while silent
* (3322 and 512 events a second, nearly half of the work with the screen off). When the mask opens, the timer's next
* overflow is put where it would be (the first one after now), so the IRQs come at the same cycles as before. */
static inline int tmr_masked(int t) { return t == 0 ? !(g_cpureg[0x70] & 0x80) : !(g_cpureg[0x71] & 0x08); }
static void tmr_catch_up(int t, uint64_t now)
{
if (!s_run[t] || s_due[t] > now || !s_per[t]) return;
uint64_t k = (now - s_due[t]) / s_per[t] + 1u;
s_due[t] += k * s_per[t];
}
#endif
static void reschedule(void)
{
uint64_t cnow = snd_now();
uint64_t now = cnow << 16;
uint64_t best = (uint64_t)0x7FFFFFFF << 16;
for (int t = 0; t < 2; t++) {
if (!s_run[t]) continue;
#ifdef T7_SND_LAZY
if (tmr_masked(t)) continue;
#endif
uint64_t d = s_due[t] > now ? s_due[t] - now : 0;
if (d < best) best = d;
}
if (s_smp_per) {
uint64_t sd = s_smp_due << 16;
uint64_t d = sd > now ? sd - now : 0;
if (d < best) best = d;
}
int64_t c = (int64_t)((best + 0xFFFF) >> 16);
if (c < 1) c = 1;
if (c > 0x3FFFFFFF) c = 0x3FFFFFFF;
s_base = cnow;
s_span = (int32_t)c;
g_snd_next = (int32_t)c;
}
static void recalc_timer(int t, int restart)
{
#ifdef T7_SND_LAZY
tmr_catch_up(t, snd_now() << 16); /* the overflows so far with the old period */
#endif
uint8_t ctl = g_cpureg[0x31];
uint8_t src = t == 0 ? (ctl >> 4) : (ctl & 0x0F);
uint32_t pre = t == 0 ? (g_cpureg[0x32] | (g_cpureg[0x33] << 8))
: (g_cpureg[0x34] | (g_cpureg[0x35] << 8));
uint32_t n = 0x10000u - pre;
if (n < 16) n = 16; // Schutz: kein IRQ-Sturm
uint8_t run = (src == 2);
s_per[t] = (((uint64_t)n * s_emu_hz) << 16) / timer_hz(t);
if (run && (!s_run[t] || restart)) s_due[t] = (snd_now() << 16) + s_per[t];
s_run[t] = run;
}
static inline void ring_put(int32_t v)
{
s_lp += (v - s_lp) >> 1; // ca. 5 kHz bei 48 kHz Abtastrate
v = s_lp;
int32_t y = v - s_hp_x + ((s_hp_y * 254) >> 8); // Koppelkondensator
s_hp_x = v; s_hp_y = y;
if (y > 32767) y = 32767;
if (y < -32768) y = -32768;
if (s_w - s_r >= RING - 1) return; // voll -> Neues verwerfen (nur der Leser bewegt s_r)
s_ring[s_w & (RING - 1)] = (int16_t)y;
s_w++;
}
// Tonstrom bis "jetzt" rendern (der DAC-Wert war seit s_rend konstant).
static void render_now(void)
{
if (s_syn_on) return; // Klar-Modus rendert aus den Zustaenden
uint64_t now = snd_now() << 16;
if (!s_cap || !s_cps_fp) { s_rend = now; return; }
if (now <= s_rend) return;
uint64_t span = now - s_rend;
s_rend = now;
if (span > s_cps_fp * 48000u) { // riesige Luecke (Aufholen) -> nicht nachrendern
s_pos = 0; s_acc = 0; return;
}
while (s_pos + span >= s_cps_fp) {
uint64_t take = s_cps_fp - s_pos;
s_acc += (int64_t)s_dac * (int64_t)take;
int32_t avg = (int32_t)(s_acc / (int64_t)(s_cps_fp >> 8)); // DAC * 256
ring_put(avg * s_vol / 100);
span -= take; s_pos = 0; s_acc = 0;
}
s_acc += (int64_t)s_dac * (int64_t)span;
s_pos += span;
}
void t7_snd_io_write(uint8_t reg, uint8_t value)
{
(void)value;
switch (reg) {
case 0x30: recalc_timer(1, 1); break;
case 0x31: recalc_timer(0, 0); recalc_timer(1, 0); break;
case 0x32: recalc_timer(0, 0); break;
case 0x33: recalc_timer(0, 1); break;
case 0x34: recalc_timer(1, 0); break;
case 0x35: recalc_timer(1, 1); break;
case 0x60: case 0x65:
render_now();
s_dac = (g_cpureg[0x65] & 0x02) ? (int32_t)(int8_t)g_cpureg[0x60] : 0;
return;
#ifdef T7_SND_LAZY
case 0x70: case 0x71: { uint64_t now = snd_now() << 16; tmr_catch_up(0, now); tmr_catch_up(1, now); } break;
#endif
default: return;
}
reschedule();
}
// Wird aufgerufen, wenn g_snd_next abgelaufen ist.
void T7_HOT t7_snd_service(void)
{
uint64_t now = snd_now() << 16;
#ifdef T7_SND_LAZY
if (s_run[0] && !tmr_masked(0)) while (s_due[0] <= now) { s_due[0] += s_per[0]; t7_fire_irq(0); g_snd_irq0++; }
if (s_run[1] && !tmr_masked(1)) while (s_due[1] <= now) { s_due[1] += s_per[1]; t7_fire_irq(12); g_snd_irq12++; }
#else
if (s_run[0]) while (s_due[0] <= now) { s_due[0] += s_per[0]; t7_fire_irq(0); g_snd_irq0++; }
if (s_run[1]) while (s_due[1] <= now) { s_due[1] += s_per[1]; t7_fire_irq(12); g_snd_irq12++; }
#endif
if (s_smp_per) {
uint64_t c = now >> 16;
if (c >= s_smp_due) {
s_smp_due += s_smp_per;
if (s_smp_due <= c) s_smp_due = c + s_smp_per; // weit zurueck -> neu aufsetzen
uint8_t lv;
uint32_t hz = t7_snd_tone_hz(&lv);
if (lv < 4) hz = 0; // Huellkurve fast aus = still
if (hz != s_tev_cand) { s_tev_cand = hz; s_tev_seen = 1; }
else if (s_tev_seen < TEV_STABLE) s_tev_seen++;
uint32_t need = hz ? TEV_STABLE : TEV_STABLE_OFF;
int changed = (s_tev_seen >= need && hz != s_tev_last);
if (changed) {
s_tev_last = hz;
if (s_ev_on && (s_tev_w - s_tev_r) < TEV_N) {
s_tev_c[s_tev_w % TEV_N] = c - (uint64_t)s_smp_per * (need - 1); // Beginn lag frueher
s_tev_hz[s_tev_w % TEV_N] = hz;
s_tev_w++;
}
}
if (s_syn_on && s_cap) {
if (s_syn_w - s_syn_r >= SYN_N) s_syn_r = s_syn_w - SYN_N + 1; // Renderer haengt -> Aeltestes weg
syn_t *e = &s_syn[s_syn_w % SYN_N];
e->c = c; e->hz = s_tev_last; e->lv = lv;
s_syn_w++;
if (changed) { // bestaetigte Aenderung rueckdatieren
for (uint32_t k = 1; k < need; k++) {
uint32_t idx = s_syn_w - 1 - k;
if ((int32_t)(idx - s_syn_r) < 0) break; // schon abgespielt
s_syn[idx % SYN_N].hz = s_tev_last;
}
}
}
}
}
reschedule();
}
#ifndef T7_NO_SYNTH
static inline float blep(float t, float dt)
{
if (t < dt) { t /= dt; return t + t - t * t - 1.0f; }
if (t > 1.0f - dt) { t = (t - 1.0f) / dt; return t * t + t + t + 1.0f; }
return 0.0f;
}
// Klar-Modus: Samples bis (jetzt - Vorlauf) aus den 1-ms-Zustaenden erzeugen.
static void render_synth(void)
{
if (!s_cap || !s_cps_fp || !s_smp_per) return;
uint64_t lag = (uint64_t)s_smp_per * (TEV_STABLE + 1);
uint64_t nowc = snd_now();
if (nowc <= lag) return;
uint64_t target = (nowc - lag) << 16;
if (target <= s_rend) return;
if (target - s_rend > s_cps_fp * 48000u) { // riesige Luecke -> nicht nachrendern
s_rend = target;
while (s_syn_w - s_syn_r > 1 && (s_syn[(s_syn_r + 1) % SYN_N].c << 16) <= s_rend) s_syn_r++;
return;
}
const float kAmp = 0.03f; // ~0,7 ms Glaettung (kein Klick, kein Reissverschluss)
while (s_rend + s_cps_fp <= target) {
s_rend += s_cps_fp;
while (s_syn_w - s_syn_r > 1 && (s_syn[(s_syn_r + 1) % SYN_N].c << 16) <= s_rend) s_syn_r++;
uint32_t hz = 0; uint8_t lv = 0;
if (s_syn_w != s_syn_r) { syn_t *e = &s_syn[s_syn_r % SYN_N]; hz = e->hz; lv = e->lv; }
float want = hz ? (float)lv * 256.0f : 0.0f;
if (hz) {
if (s_ohz == 0 && s_amp < 1.0f) s_ph = 0.0f; // neuer Ton aus der Stille: sauber bei Phase 0
s_ohz = hz;
}
s_amp += (want - s_amp) * kAmp;
int32_t out = 0;
if (s_ohz && s_amp > 0.5f) {
float dt = (float)s_ohz / (float)s_rate;
if (dt > 0.45f) dt = 0.45f;
float t2 = s_ph + 0.5f; if (t2 >= 1.0f) t2 -= 1.0f;
float v = (s_ph < 0.5f ? 1.0f : -1.0f) + blep(s_ph, dt) - blep(t2, dt);
out = (int32_t)(v * s_amp);
s_ph += dt; if (s_ph >= 1.0f) s_ph -= 1.0f;
} else if (!hz) {
s_ohz = 0;
}
out = out * s_vol / 100;
if (out > 32767) out = 32767;
if (out < -32768) out = -32768;
if (s_w - s_r >= RING - 1) continue;
s_ring[s_w & (RING - 1)] = (int16_t)out;
s_w++;
}
}
#endif
void t7_snd_flush(void)
{
if (!g_snd_on) return;
#ifndef T7_NO_SYNTH
if (s_syn_on) render_synth(); else
#endif
render_now();
}
static void smp_update(void)
{
uint32_t per = s_emu_hz / 1000u; // 1-ms-Raster
uint32_t want = (s_ev_on || s_syn_on) ? per : 0;
if (want != s_smp_per) {
s_smp_per = want;
s_smp_due = snd_now() + want;
}
}
// 1 = Klar-Modus (Rechteck neu erzeugt), 0 = DAC abtasten (roh, wie v1.7)
void t7_snd_synth(int on)
{
s_syn_on = on ? 1 : 0;
s_syn_r = s_syn_w;
s_rend = snd_now() << 16;
#ifndef T7_NO_SYNTH
s_amp = 0.0f; s_ohz = 0; s_ph = 0.0f;
#endif
smp_update();
reschedule();
}
void t7_snd_set_mode(int on)
{
g_snd_on = on ? 1 : 0;
s_run[0] = s_run[1] = 0;
s_dac = 0;
s_rend = snd_now() << 16;
if (g_snd_on) { recalc_timer(0, 1); recalc_timer(1, 1); }
reschedule();
}
void t7_snd_config(uint32_t emu_hz, uint32_t sample_rate)
{
if (emu_hz < 100000) emu_hz = 100000;
if (sample_rate < 8000) sample_rate = 8000;
s_emu_hz = emu_hz;
s_cps_fp = ((uint64_t)emu_hz << 16) / sample_rate;
s_rate = sample_rate;
s_pos = 0; s_acc = 0; s_rend = snd_now() << 16;
s_smp_per = 0; smp_update();
if (g_snd_on) { recalc_timer(0, 1); recalc_timer(1, 1); }
reschedule();
}
void t7_snd_capture(int on)
{
if (on && !s_cap) {
s_rend = snd_now() << 16; s_pos = 0; s_acc = 0;
s_syn_r = s_syn_w;
#ifndef T7_NO_SYNTH
s_amp = 0.0f; s_ohz = 0;
#endif
}
s_cap = on ? 1 : 0;
}
void t7_snd_volume(int pct) { if (pct < 0) pct = 0; if (pct > 100) pct = 100; s_vol = pct; }
void t7_snd_reset(void) { s_r = s_w; s_hp_x = s_hp_y = 0; s_lp = 0; s_rfrac = 0; s_last = 0; }
uint32_t t7_snd_avail(void) { return s_w - s_r; }
/*
* Tonstrom abholen, geregelt (wie bei TamaParadise, dort 0 Knackstellen):
* Der Emulator liefert in Schueben (66 ms), die Ausgabe holt in kleinen
* Bloecken. Statt bei leerem Vorrat mit Stille aufzufuellen (eine Stufe mitten
* in der Rechteckflanke = Knacks), wird die Lesegeschwindigkeit um ein paar
* Prozent gedehnt oder gestaucht, bis der Vorrat wieder bei `target` liegt.
* Reicht es trotzdem nicht, klingt der letzte Wert weich aus, statt auf Null
* zu springen. target = 0: ungeregelt (Stille auffuellen).
* Rueckgabe: Anzahl echt gelesener Ausgabe-Samples.
*/
uint32_t t7_snd_pull(int16_t *out, uint32_t n, uint32_t target)
{
uint32_t have = s_w - s_r;
uint32_t step = 65536;
if (target) {
// Zu viel Vorrat kommt vor allem von Widget-Tipps (0,7 s Ton auf einmal); danach
// pausiert die Emulation genauso lange, der Vorrat baut sich also selbst ab.
// Deshalb nur ganz sanft schneller (1,02) und erst ab 1 s hart schneiden.
uint32_t hard = RING * 3 / 4;
if (hard > 48000u) hard = 48000u;
if (have > hard) { s_r = s_w - target; have = target; s_rfrac = 0; }
if (have < target / 2) step = 60293; // 0,92
else if (have < target * 3 / 4) step = 62915; // 0,96
else if (have > target * 3) step = 66847; // 1,02
}
uint32_t real = 0;
int under = 0;
for (uint32_t i = 0; i < n; i++) {
have = s_w - s_r;
if (have >= 2) {
int32_t a = s_ring[s_r & (RING - 1)];
int32_t b = s_ring[(s_r + 1) & (RING - 1)];
int32_t v = a + (int32_t)(((int64_t)(b - a) * s_rfrac) >> 16);
out[i] = (int16_t)v; s_last = v;
s_rfrac += step;
s_r += s_rfrac >> 16;
s_rfrac &= 0xFFFF;
real++;
} else {
s_last = (s_last * 255) / 256; // weich ausklingen (~5 ms)
out[i] = (int16_t)s_last;
under = 1;
}
}
if (under) s_under++;
return real;
}
uint32_t t7_snd_underruns(void) { return s_under; }
// Nach dem Laden eines Spielstands: Timerzustand aus den Registern ableiten.
void t7_snd_resync(void)
{
s_run[0] = s_run[1] = 0;
s_dac = 0;
if (g_snd_on) { recalc_timer(0, 1); recalc_timer(1, 1); }
reschedule();
}
// 1 = gerade Tonausgabe aktiv (Timer 0 laeuft, IRQ 0 frei, Verstaerker an)
int t7_snd_active(void)
{
return g_snd_on && s_run[0] && (g_cpureg[0x70] & 0x80) && (g_cpureg[0x65] & 0x02);
}
// Nur fuer Versuche: schneller Takt von Timer 1 (Standard T7_T1_FAST_HZ).
void t7_snd_set_t1_hz(uint32_t hz)
{
if (hz < 1000) hz = 1000;
s_t1_fast = hz;
if (g_snd_on) { recalc_timer(1, 1); reschedule(); }
}
/*
* Fuer Geraete ohne DAC (ESP32 mit Piezo): welcher Rechteckton spielt die
* Firmware gerade? Nachgebildet aus dem IRQ-0-Handler $D1B9: das Rechteck
* wird nur ausgegeben, wenn $92 Bit 0 gesetzt ist und entweder $B3 Bit 0
* oder keines der Bits $94 in $97 (Sample-/Rampenbetrieb). Die Tonhoehe ist
* der halbe IRQ-0-Takt, die Lautstaerke steckt in $93 (Huellkurve).
* Rueckgabe 0 = still. *level = Betrag der Huellkurve (0..127).
*/
uint32_t t7_snd_tone_hz(uint8_t *level)
{
if (level) *level = 0;
if (!g_snd_on || !s_run[0]) return 0;
if (!(g_cpureg[0x70] & 0x80) || !(g_cpureg[0x65] & 0x02)) return 0;
if (!(g_wram[0x92] & 0x01)) return 0;
if (!(g_wram[0xB3] & 0x01) && (g_wram[0x97] & 0x94)) return 0;
int a = (int8_t)g_wram[0x93];
if (a == -128) a = 0;
if (a < 0) a = -a;
if (level) *level = (uint8_t)a;
if (a == 0) return 0;
uint32_t cnt = 0x10000u - (g_cpureg[0x32] | (g_cpureg[0x33] << 8));
if (cnt < 16) return 0;
return (T0_HZ / 2u + cnt / 2u) / cnt;
}
// ---- Ton-Ereignisse (Piezo) ----
void t7_snd_tone_events(uint32_t interval_cycles)
{
s_ev_on = interval_cycles ? 1 : 0;
s_smp_per = 0; smp_update();
if (s_ev_on && interval_cycles != s_smp_per) { s_smp_per = interval_cycles; s_smp_due = snd_now() + interval_cycles; }
s_tev_last = 0; s_tev_cand = 0; s_tev_seen = 0;
reschedule();
}
int t7_snd_tone_peek(uint64_t *cyc, uint32_t *hz)
{
if (s_tev_r == s_tev_w) return 0;
if (cyc) *cyc = s_tev_c[s_tev_r % TEV_N];
if (hz) *hz = s_tev_hz[s_tev_r % TEV_N];
return 1;
}
void t7_snd_tone_pop(void) { if (s_tev_r != s_tev_w) s_tev_r++; }
uint64_t t7_snd_cycles(void) { return snd_now(); }
// 1 = die Firmware spielt gerade eine Melodie oder einen Ton (nicht schlafen legen)
int t7_snd_busy(void)
{
if (!g_snd_on) return 0;
if (g_wram[0xA3] & 0x80) return 1; // Sequenzer laeuft ($FC4C setzt $A3=$80)
return s_tev_last != 0 || s_tev_r != s_tev_w;
}
+35
View File
@@ -0,0 +1,35 @@
/* t7_sound.h - Originalton (Timer 0/1 + DAC), siehe t7_sound.c */
#ifndef T7_SOUND_H
#define T7_SOUND_H
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
extern uint8_t g_snd_on;
extern int32_t g_snd_next;
void t7_snd_io_write(uint8_t reg, uint8_t value);
void t7_snd_service(void);
void t7_snd_flush(void);
void t7_snd_set_mode(int on); // 1 = Originalton (Timer + DAC), 0 = alt
void t7_snd_config(uint32_t emu_hz, uint32_t sample_rate);
void t7_snd_capture(int on); // Tonstrom aufzeichnen
void t7_snd_volume(int pct); // 0..100
void t7_snd_reset(void); // Ring leeren
uint32_t t7_snd_avail(void);
uint32_t t7_snd_pull(int16_t *out, uint32_t n, uint32_t target); // geregelt, target in Samples (0 = ungeregelt)
uint32_t t7_snd_underruns(void);
void t7_snd_synth(int on); // 1 = klarer Ton (Rechteck neu erzeugt), 0 = DAC roh
void t7_snd_resync(void);
int t7_snd_active(void);
uint32_t t7_snd_tone_hz(uint8_t *level); // Rechteckton gerade (fuer Piezo), 0 = still
void t7_snd_set_t1_hz(uint32_t hz);
// Piezo-Geraete: Ton-Ereignisse (Zeitpunkt in CPU-Zyklen, Frequenz in Hz, 0 = still)
void t7_snd_tone_events(uint32_t interval_cycles); // 0 = aus
int t7_snd_tone_peek(uint64_t *cyc, uint32_t *hz);
void t7_snd_tone_pop(void);
uint64_t t7_snd_cycles(void);
int t7_snd_busy(void);
#ifdef __cplusplus
}
#endif
#endif
BIN
View File
Binary file not shown.
BIN
View File
Binary file not shown.
+186
View File
@@ -0,0 +1,186 @@
# T7 app (t7.bin, device program) in Unicorn: hardware calls are caught, the screen is drawn
# into a picture, the SysTick is advanced every RT instructions (96 MHz Cortex-M3 ~ RT per ms).
# python3 devt7.py <t7.elf> <paradise_image_with_t7.bin> <ms> [KEYS="t:mask,..."] [SHOTS="t,t,..."] [OUT=dir]
import sys, struct, subprocess, os
from unicorn import *
from unicorn.arm_const import *
elf, img, total_ms = sys.argv[1], sys.argv[2], int(sys.argv[3])
RT = int(os.environ.get('RT', '64000')) # instructions per millisecond (96 MHz, ~1.5 cycles each)
out = os.environ.get('OUT', '.')
syms = {}
for l in subprocess.run(['llvm-nm', elf], capture_output=True, text=True).stdout.splitlines():
p = l.split()
if len(p) == 3: syms[p[2]] = int(p[0], 16)
fl = bytearray(open(img, 'rb').read())
u = Uc(UC_ARCH_ARM, UC_MODE_THUMB | UC_MODE_MCLASS)
u.ctl_set_cpu_model(UC_CPU_ARM_CORTEX_M4)
APPOFF = int(os.environ.get('APPOFF', '0xA0000'), 16) # program image (1.6.0: more programs elsewhere)
u.mem_map(0, 0x10000); u.mem_write(0, bytes(fl[APPOFF:APPOFF + 0x10000]))
u.mem_map(0x18000000, 0x20000); u.mem_map(0x20000000, 0x1000)
u.mem_map(0x10000000, 0x100000)
u.mem_map(0x60000000, 0x1000000); u.mem_write(0x60000000, bytes(fl))
u.mem_map(0x40000000, 0x100000); u.mem_map(0x45000000, 0x1000); u.mem_map(0xE000E000, 0x1000); u.mem_map(0xE0001000, 0x1000) # DWT (CYCCNT reads 0 here)
u.mem_write(0x4000B014, struct.pack('<I', 0x60)) # 1.6.9 T7_LINK: UART1 LSR, sender empty (nothing received)
cfg = APPOFF + 0x140
rom_off = struct.unpack_from('<I', fl, cfg + 8)[0]
u.mem_write(0x10000000, bytes(fl[rom_off:rom_off + 0x100000]))
fb = [[0] * 128 for _ in range(128)]
rect = {'x0': 0, 'x1': 0, 'y': 0, 'x': 0}
KS = []
for p in os.environ.get('KEYS', '').split(','):
if ':' in p: t, m = p.split(':'); KS.append((float(t), int(m)))
SH = [float(x) for x in os.environ.get('SHOTS', '').split(',') if x]
state = {'ms': 0, 'tone': [], 'left': 0, 'flashw': 0}
def keys():
m = 0
for t, v in KS:
if state['ms'] / 1000.0 >= t: m = v
return m
def ret(uc, v=None):
if v is not None: uc.reg_write(UC_ARM_REG_R0, v)
uc.reg_write(UC_ARM_REG_PC, uc.reg_read(UC_ARM_REG_LR) | 1)
def h_begin(uc, *a):
x0, y0, x1, y1 = (uc.reg_read(r) for r in (UC_ARM_REG_R0, UC_ARM_REG_R1, UC_ARM_REG_R2, UC_ARM_REG_R3))
rect.update(x0=x0, x1=x1, y=y0, x=x0); ret(uc)
def h_row(uc, *a):
p, n = uc.reg_read(UC_ARM_REG_R0), uc.reg_read(UC_ARM_REG_R1)
d = struct.unpack('<%dH' % n, uc.mem_read(p, 2 * n))
for v in d:
if rect['y'] < 128 and rect['x'] < 128: fb[rect['y']][rect['x']] = v
rect['x'] += 1
if rect['x'] >= rect['x1']: rect['x'] = rect['x0']; rect['y'] += 1
ret(uc)
def h_tone(uc, *a): state['tone'].append((state['ms'], uc.reg_read(UC_ARM_REG_R0))); ret(uc)
def h_btn(uc, *a): ret(uc, keys())
def h_prog(uc, *a):
ad, src = uc.reg_read(UC_ARM_REG_R0), uc.reg_read(UC_ARM_REG_R1)
d = bytes(uc.mem_read(src & ~3, 0x1000)); a = ad & 0xFFFFFF # test27: the device's DMA takes words (start rounded down)
uc.mem_write(0x60000000 + a, d); fl[a:a + 0x1000] = d; state['flashw'] += 1; ret(uc)
def h_erase(uc, *a):
a = uc.reg_read(UC_ARM_REG_R0) & 0xFFFFFF
uc.mem_write(0x60000000 + a, b'\xff' * 0x1000); fl[a:a + 0x1000] = b'\xff' * 0x1000; ret(uc)
def h_back(uc, *a): state['back'] = 1; uc.emu_stop()
def h_nop(uc, *a): ret(uc)
H = {'hw_px_begin': h_begin, 'hw_px_row': h_row, 'hw_px_end': h_nop, 'hw_tone': h_tone, 'hw_buttons': h_btn,
'flash_prog4k': h_prog, 'flash_erase4k': h_erase, 'hw_back_to_paradise': h_back, 'hw_init': h_nop,
'hw_backlight': h_nop, 'hw_bl_pwm_off': h_nop, 'hw_wdt_feed': h_nop}
for n, f in H.items():
a = syms[n] & ~1
u.hook_add(UC_HOOK_CODE, (lambda f: lambda uc, ad, sz, ud: f(uc))(f), begin=a, end=a)
def bad(uc, access, addr, size, value, ud):
print('unmapped', access, hex(addr), 'pc', hex(uc.reg_read(UC_ARM_REG_PC))); return False
u.hook_add(UC_HOOK_MEM_UNMAPPED, bad)
# 1.6.9 test22 CLK_ECO: the AHB prescaler at 0x45000010 slows the core: RT >> sh instructions per ms
state['sh'] = 0; state['shms'] = [0, 0, 0, 0]
def _ahb(uc, acc, a, sz, v, ud):
state['sh'] = v & 7
if os.environ.get('ECOLOG'): print('AHB', v & 7, 'at ms', state['ms'])
u.hook_add(UC_HOOK_MEM_WRITE, _ahb, begin=0x45000010, end=0x45000013)
# 1.6.12 test1 T7_PW: system clock source (0x4500000C: 0 IHRC 12 MHz, 4 PLL; status in bits 6:4), PLL locked flag,
# RTC on with 1 s, deep sleep (PMU_CTRL bit 1, then WFI): the time runs on to the next RTC second or a key change
u.mem_write(0x4500000C, struct.pack('<I', 0x44)); u.mem_write(0x45000008, struct.pack('<I', 0x55)); u.mem_write(0x45000200, struct.pack('<I', 0x80))
state['ihrc'] = 0; state['pw'] = {'full': 0, 'ihrc': 0, 'sleep': 0}
def _clk(uc, acc, a, sz, v, ud):
state['ihrc'] = (v & 7) == 0
uc.mem_write(0x4500000C, struct.pack('<I', (v & 7) | ((v & 7) << 4)))
if os.environ.get('ECOLOG'): print('CLKSRC', v & 7, 'at ms', state['ms'])
u.hook_add(UC_HOOK_MEM_WRITE, _clk, begin=0x4500000C, end=0x4500000F)
def _pmu(uc, acc, a, sz, v, ud):
# deep sleep: the time jumps to the next RTC second (or a key change) at once; the code after the WFI sees it
if v & 2 and not state.get('dsleep'):
k0 = keys(); t = state['ms']
while True:
t += 1
if t % 1000 == 0 or t >= total_ms or any(t / 1000.0 >= kt > state['ms'] / 1000.0 for kt, _ in KS): break
state['dsleep'] = t
if t % 1000 == 0 and 'g_pw_rtcw' in syms: uc.mem_write(syms['g_pw_rtcw'], b'\x01') # the RTC interrupt ran
if int(os.environ.get('RTCLAG', '0')):
# 1.6.13 test3: the counter shows the new second only a few reads after the wake (32 kHz domain)
state['rtc_new'] = rtc0 + t // 1000; state['rtclag'] = int(os.environ['RTCLAG'])
else: uc.mem_write(0x45000304, struct.pack('<I', rtc0 + t // 1000))
u.hook_add(UC_HOOK_MEM_WRITE, _pmu, begin=0x45000300, end=0x45000303)
def _rtcrd(uc, acc, a, sz, v, ud):
if 'rtc_new' in state:
if state['rtclag'] > 0: state['rtclag'] -= 1
else: uc.mem_write(0x45000304, struct.pack('<I', state.pop('rtc_new')))
u.hook_add(UC_HOOK_MEM_READ, _rtcrd, begin=0x45000304, end=0x45000307)
RTCLAGMS = int(os.environ.get('RTCLAGMS', '0'))
if RTCLAGMS:
# 1.6.13 test3: the counter shows a new second only RTCLAGMS ms after it began (the RTC interrupt comes on time)
def _rtcms(uc, acc, a, sz, v, ud):
eff = state.get('dsleep') or state['ms']
uc.mem_write(0x45000304, struct.pack('<I', rtc0 + max(eff - RTCLAGMS, 0) // 1000))
u.hook_add(UC_HOOK_MEM_READ, _rtcms, begin=0x45000304, end=0x45000307)
if os.environ.get('MEMW'):
_mw = int(os.environ['MEMW'], 16)
u.hook_add(UC_HOOK_MEM_WRITE, lambda uc, acc, a, sz, v, ud: print('W %08x = %08x at ms %d' % (a, v, state['ms'])), begin=_mw, end=_mw + 0x3F)
def shot(name):
from PIL import Image
im = Image.new('RGB', (128, 128))
for y in range(128):
for x in range(128):
v = fb[y][x]; im.putpixel((x, y), (((v >> 11) & 31) << 3, ((v >> 5) & 63) << 2, (v & 31) << 3))
im.save(os.path.join(out, name))
_RSAVE = [UC_ARM_REG_R0 + i for i in range(13)] + [UC_ARM_REG_SP, UC_ARM_REG_LR, UC_ARM_REG_XPSR]
sp, rst = struct.unpack('<II', bytes(u.mem_read(0, 8)))
u.reg_write(UC_ARM_REG_SP, sp)
pc = rst; gms = syms['g_ms']; rtc0 = int(os.environ.get('RTC0', '5000'))
emu_ms_sym = None
si = 0
while state['ms'] < total_ms and 'back' not in state:
u.mem_write(0x45000304, struct.pack('<I', rtc0 + state['ms'] // 1000))
try:
_sh = 3 if state['ihrc'] else state['sh']
u.emu_start(pc | 1, 0xFFFFFFF0, count=max(1, RT >> _sh)); state['shms'][min(_sh, 3)] += 1
state['pw']['ihrc' if state['ihrc'] else 'full'] += 1
except UcError as ex:
print('error', ex, hex(u.reg_read(UC_ARM_REG_PC))); break
pc = u.reg_read(UC_ARM_REG_PC)
_ds = state.pop('dsleep', 0)
if _ds:
n = _ds - state['ms']; state['ms'] = _ds
state['pw']['sleep'] += n
if os.environ.get('DBGSLEEP'): print('slept', n, 'to ms', state['ms'], 'pc', hex(pc), 'g_ms', struct.unpack('<I', u.mem_read(syms['g_ms'], 4))[0], 'emu', struct.unpack('<I', u.mem_read(syms['g_t7st'], 4))[0])
u.mem_write(0x45000304, struct.pack('<I', rtc0 + state['ms'] // 1000))
km = keys(); u.mem_write(0x40018000, struct.pack('<I', 0xFFFFFFFF & ~(((km & 1) << 9) | ((km & 2) << 10) | ((km & 4) << 8) | ((km & 8) << 5))))
continue
state['ms'] += 1
_ts = int(os.environ.get('TICKSLOW', '0')) # test27: a slow ms tick at a lower clock (device fault model)
if not (_ts and state['sh'] > 0 and state['ms'] % _ts):
v = struct.unpack('<I', u.mem_read(gms, 4))[0]; u.mem_write(gms, struct.pack('<I', v + 1))
if 'g_ms_raw' in syms: _r = syms['g_ms_raw']; u.mem_write(_r, struct.pack('<I', struct.unpack('<I', u.mem_read(_r, 4))[0] + 1))
# 1.6.12 test4 (T7_TONE_ISR): the tick plays the tone queue; here called like the interrupt would
if 'tq_isr_on' in syms and u.mem_read(syms['tq_isr_on'], 1)[0]:
_regs = [u.reg_read(r) for r in _RSAVE]
u.reg_write(UC_ARM_REG_SP, (_regs[13] - 64) & ~7); u.reg_write(UC_ARM_REG_LR, 0xFFF1)
u.emu_start(syms['tq_pump'] | 1, 0xFFF0, count=200000)
for r, v in zip(_RSAVE, _regs): u.reg_write(r, v)
# 1.6.9 test13 T7_KEYQ: the GPIO as the keys say (pressed = 0) and the tick's press counter
km = keys(); u.mem_write(0x40018000, struct.pack('<I', 0xFFFFFFFF & ~(((km & 1) << 9) | ((km & 2) << 10) | ((km & 4) << 8) | ((km & 8) << 5))))
if 'g_kin' in syms:
e = km & ~state.get('kprev', 0) & 7; state['kprev'] = km
u.mem_write(syms['g_kprev'], bytes([km & 7]))
for i in range(3):
if e & (1 << i): a = syms['g_kin'] + i; u.mem_write(a, bytes([(u.mem_read(a, 1)[0] + 1) & 0xFF]))
if si < len(SH) and state['ms'] >= SH[si] * 1000: shot('shot_%02d.png' % si); si += 1
LL = int(os.environ.get('LAGLOG', '0')) # 1.6.13 test4: every LL ms: emulated ms in that time (100 % = real time)
if LL and state['ms'] % LL == 0:
_st = struct.unpack('<2I', bytes(u.mem_read(syms['g_t7st'], 8))); _p = state.get('llp', _st)
print('lag', state['ms'], _st[0] - _p[0], _st[1] - _p[1], flush=True); state['llp'] = _st
if os.environ.get('CLOG') and state['ms'] % int(os.environ['CLOG']) == 0:
_w = bytes(u.mem_read(syms['g_wram'], 0x600)); _sa = int(os.environ.get('CSEC', '0x396'), 16)
_eb = struct.unpack('<3I', bytes(u.mem_read(syms['g_eco_bad'], 4)) + bytes(u.mem_read(syms['g_eco_fix'], 8))) if 'g_eco_bad' in syms else ()
if os.environ.get('DBGSYM'):
for _d in os.environ['DBGSYM'].split(','):
_s, _l = _d.split(':'); print(' ', _s, bytes(u.mem_read(syms[_s], int(_l, 0))).hex())
print('clock', state['ms'], 'rtc', rtc0 + state['ms'] // 1000, 'game %02d:%02d:%02d' % (_w[0x306], _w[0x307], _w[_sa]), 'sh', state['sh'], 'eco_bad/fix', _eb)
st = struct.unpack('<4I', bytes(u.mem_read(syms['g_t7st'], 16)))
print('emulated ms', st[0], 'dropped ms', st[1])
(os.environ.get('TONES') and print('tones:', state['tone']));print('ms', state['ms'], 'tones', len(state['tone']), 'flash writes', state['flashw'], 'back' if 'back' in state else '', 'pc', hex(pc))
print('ms per clock step (96, 48, 24, 12 MHz):', state['shms'])
print('power ms: full', state['pw']['full'], 'ihrc', state['pw']['ihrc'], 'deep sleep', state['pw']['sleep'])
open(os.path.join(out, 'flash_after.bin'), 'wb').write(fl)
for _n in os.environ.get('SYMDUMP', '').split(','):
if ':' in _n:
_s, _l = _n.split(':'); open(os.path.join(out, _s + '.bin'), 'wb').write(bytes(u.mem_read(syms[_s], int(_l, 0))))
shot('shot_end.png')
+16
View File
@@ -0,0 +1,16 @@
# per-function instruction profile of t7.bin in Unicorn (uses devt7 setup)
import sys, os, struct, subprocess, collections
os.environ.setdefault('SHOTS','')
src = open(os.path.join(os.path.dirname(__file__), 'devt7.py')).read()
src = src.replace("while state['ms'] < total_ms", "cnt=collections.Counter()\nFROM=int(os.environ.get('FROM','0'))\ndef hc(uc,a,s,d):\n if state['ms']>=FROM: cnt[a]+=1\nu.hook_add(UC_HOOK_CODE,hc,begin=0,end=0xffff)\nwhile state['ms'] < total_ms")
exec(compile(src, 'devt7', 'exec'))
fn = sorted((v, k) for k, v in syms.items() if v < 0x10000)
import bisect
keys=[a for a,_ in fn]
per=collections.Counter()
for a,c in cnt.items():
i=bisect.bisect_right(keys,a)-1; per[fn[i][1] if i>=0 else '?']+=c
tot=sum(per.values())
for n,c in per.most_common(25): print('%-28s %6.2f%%' % (n, 100*c/tot))
e=syms.get('t7_cpu_step',0)&~1
print('6502 instructions', cnt[e], 'ARM instr total', tot, 'per 6502 instr', tot/max(1,cnt[e]))