Tidepod is a development suite for the TI-99/4A. You write C (or compiled Extended BASIC, or assembly), and Tidepod
turns it into a cartridge image or disk program, runs it in an emulator and lets you debug it at source level.
The same tidepod binary is both the graphical IDE and a command-line project manager.
This page describes the pieces and how they fit together. You do not need to build any of them: every release
ships with the complete toolchain.
Components
Component
What it is
You interact with it via
tidepod
IDE (editor, build, embedded emulator, debugger, graphics viewers, profiler) and CLI project manager.
GUI, or tidepod new/add/remove/list/set-type/sync/run
Generated from .project by tidepod sync. Never edited by hand.
make, make debug, make clean
tms9900-elf-gcc
GCC 14.2 cross compiler for the TMS9900, plus binutils (as, ld, objdump, objcopy, …) and tms9900-elf-gdb. Also compiles Extended BASIC (-x xb).
Invoked by the Makefile
tms9900-packer
Auto-banker: distributes code and data over 8 KB cartridge banks, writes the linker script, cross-bank trampolines and resource headers, and produces EA5 disk images.
C library: strings, ctype, stdlib (with optional near heap and SAMS far heap), console I/O and conio, keyboard, soft-float math, disk I/O through fopen and friends, VDP detection, F18A GPU host helpers, ROM resource copy.
The details of each step, and every generated file, are covered in Build pipeline.
Project types
--type
"type" in .project
Language
Output
Needs 32K expansion
8k
0
C
Single 8 KB cartridge, no banking. .data/.bss live in scratchpad.
No
banked (default)
1
C
Bank-switched cartridge (paged378 PCB).
Yes
xb
2
Extended BASIC, compiled
Bank-switched cartridge.
Yes
ea5
3
C
Editor/Assembler option 5 program files on a .dsk image.
Yes
custom
4
any
You provide the build; no Makefile generation.
—
—
5
C
8 KB cartridge that uses the 32K expansion (IDE only).
Yes
Memory map as Tidepod uses it
Range
Region
Used by Tidepod for
0x2000–0x3FFF
Low 8K expansion RAM
.persistent: runtime stubs, cross-bank trampolines, code you mark persistent.
0x4000–0x5FFF
Peripheral DSR space
Disk controller ROMs (not yours).
0x6000–0x7FFF
Cartridge window
One 8 KB bank of your code/data/resources at a time.
0x8300–0x83FF
Scratchpad RAM
Workspace registers; .scratchpad code from 0x8342 by default. 0x83C0–0x83FF belongs to the console ISR/GPL.
0x8400, 0x8800–0x8C02
Sound / VDP ports
Memory-mapped I/O, not RAM.
0xA000–0xFFFF
High 24K expansion RAM
.data, .bss and the C stack (grows down from the top).
Video RAM (16 KB) is on a separate bus and is only reachable through the VDP ports. Where your code and data end
up is controlled per file; see Memory placement.
What happens at power-on (banked carts)
Bank 0: the console finds the cartridge header and jumps to _start. Interrupts are off. A small copier is copied into scratchpad (0x8342) and started.
Scratchpad copier: copies .persistent to low RAM (0x2000), .data to high RAM (0xA000), then your .scratchpad code over itself.
_persistent_init: clears .bss and calls main().
If main() returns, the C runtime startup code (crt0) safely catches it in an endless loop (while (1) {}). Returning from main() is completely safe and will not crash or jump into uninitialized memory.
Type model
int and size_t are 16-bit, long is 32-bit, and float is IEEE
binary32 implemented in software. The near-heap allocator (malloc, calloc,
realloc, free in high 32K RAM) defaults to 0 bytes unless enabled via
"heapSize" in .project (or --heap-size on tms9900-packer), and
<sams.h> provides a far-heap allocator (sams_malloc) for SAMS paged memory; prefer
static or global buffers when dynamic allocation isn't needed. For a detailed breakdown of 16-bit type pitfalls,
memory banking constraints, and performance tips, see the C Programming Gotchas & Porting Guide.
Tidepod is distributed as a completely self-contained offline developer suite. Each release package includes
the graphical IDE, command-line interface, the full tms9900-elf-* GCC toolchain, standard C and
Extended BASIC runtime libraries, assembler and linker scripts, manual pages, bundled example projects, the
AI coding agent skill, and the stand-alone ti994a-emu emulator with integrated GDB server.
Pre-built binaries are provided for macOS (Apple Silicon DMG), Linux (x86-64 and arm64 DEB packages), and
Windows 64-bit (interactive Setup installer and zero-install portable ZIP archive).
macOS (Apple Silicon)
Open tidepod-<version>-macos-arm64.dmg and drag Tidepod.app to Applications.
To use the CLI and toolchain from a terminal, add both directories to your PATH:
The package installs to /opt/tidepod and links /usr/bin/tidepod. The toolchain lives in
/opt/tidepod/resources/toolchain/bin; add it to your PATH if you want to call
tms9900-elf-gcc, tms9900-elf-gdb or ti994a-emu directly:
Installer (…-windows-x86_64-setup.exe): installs to Program Files\Tidepod, adds Start Menu and desktop shortcuts, and by default puts Tidepod and the toolchain on the system PATH. Uninstall from Settings → Apps.
Portable (…-windows-x86_64.zip): unpack anywhere and run tidepod.exe. PATH is not changed; the IDE still finds its bundled toolchain. The bundle includes the small set of Unix tools the generated Makefiles need.
Check the installation
Terminal
tidepod new --help # CLI usage for "new"
tms9900-elf-gcc --version # GCC 14.2.0 for the TMS9900
ti994a-emu --version
Note
tidepod with no command, or with an argument it doesn't recognise as a command, opens the IDE.
Use a subcommand with --help to stay in the terminal.
This guide walks through creating, compiling, and running a complete banked C cartridge using the Tidepod toolchain.
In under two minutes, you will establish a reproducible build workflow that targets the TMS9900 CPU and TMS9918A VDP.
The workflow operates identically from the command line or within the integrated IDE.
1. Create the project
Scaffold a new project using the tidepod new command. Specifying --type banked configures
an auto-banked cartridge utilizing the standard 378/379 bank-switching latch, while --menu "HELLO" defines
the exact menu label displayed by the TI-99/4A master console selection screen upon power-on.
Terminal
tidepod new hello --type banked --menu "HELLO" --path ./hello
cd hello
In the IDE: Choose File → New Project… (Cmd+Shift+N on macOS,
Ctrl+N on Linux/Windows). In the creation dialog, enter Project Name:hello,
set Cart Menu Title: to HELLO, choose your workspace directory in Location:,
select Project Type:C Banked Cartridge - 32K, and click Create.
The IDE creates the files and opens the workspace immediately with main.c active in the editor tab and the
directory structure listed in the Files sidebar.
The scaffolding establishes a standardized directory layout designed to isolate your source code from
toolchain-generated artifacts. The table below details each generated file and its lifecycle during compilation:
File
Purpose
Edit?
hello.project
Project description (JSON)
Through the CLI/IDE; hand edits need tidepod sync
main.c
Your program (template prints two lines)
Yes
.cart_header.asm
Cartridge header with the menu name (hidden file)
No; regenerated by sync. To customise, copy it to cart_header.asm, which then takes precedence
include/bankswitch.h
switchtobank() macro
No
Makefile
Generated build
Never
Makefile.custom
Your extra make rules; included by the Makefile and never regenerated
Notice that the root Makefile is managed entirely by Tidepod. Whenever you add files, change compiler
flags, or adjust memory placement pragmas, Tidepod regenerates the Makefile to ensure dependency graphs and bank
allocations remain perfectly synchronized. If your build requires custom pre-processing stages (such as asset
conversion scripts or automated tests), define them in Makefile.custom, which is automatically included
and preserved across synchronizations.
2. Build
Compile the project by running make in the project directory. The build pipeline invokes
tms9900-elf-gcc with optimization flags, compiles main.c against Tidepod libc
runtime headers, and runs tms9900-packer to produce both a raw binary and an RPK cartridge package:
Terminal
make
In the IDE: Click the Build (Wrench) button on the top toolbar or press F7
(or choose Build → Build). Compiler diagnostics and bank-packing messages stream into the
Build Log panel at the bottom. If an error occurs, clicking the red diagnostic line jumps directly
to the offending source line in the editor.
The build produces two distinct output artifacts in the project root:
hello.bin: A flat binary image containing the physical ROM banks concatenated in order.
This image is ready for flashing directly to physical cartridge EEPROMs or modern flash multi-carts.
hello.rpk: An emulator package containing the ROM slices and a generated layout.xml.
The descriptor specifies the memory socket mapping, cartridge board type (e.g. paged378), and 32 KB expansion
requirements for ti994a-emu and MAME.
To build with full symbolic debugging information from the command line, run make debug instead. This compiles
with -O0 -g -gdwarf-2, generating rich DWARF symbols and line mappings required by the embedded debugger and GDB.
In the IDE, initiating a debug session with F5 automatically triggers a debug build.
3. Run
Launch your software immediately in the emulator:
Terminal
tidepod run
tidepod run initializes ti994a-emu, attaches the hello.rpk package, configures
the console peripheral expansion box (PEB) cards, and executes the console startup sequence with automatic menu
bypass so your program starts instantly. Note that tidepod run executes the existing build output without
recompiling: always run make before testing your changes in the terminal.
In the IDE: Click the Run (Play) button on the toolbar or press
Mod+R (or choose Build → Run). The IDE automatically saves open files, performs
an incremental build if sources have changed, and starts execution inside the embedded Emulator panel.
Click inside the emulator display to capture keyboard and joystick input (click back into the editor to resume typing).
Press F6 to pause or resume execution at any time. To debug step-by-step with register inspection and breakpoints,
press F5 (or click the Debug (Bug) icon) instead.
4. Add files as the project grows
As your codebase expands into multiple translation units and graphics assets, register each file with Tidepod so
the build engine can manage dependencies and auto-banking:
Terminal
tidepod add src/player.c src/level.c # new C sources
tidepod add resources/tiles.dat # a binary resource
tidepod list # inspect active build members
make
The tidepod add command updates hello.project, routes the new sources through the appropriate
compiler or resource packer, and re-emits the Makefile in a single atomic step. When you compile with make,
the tms9900-packer automatically measures the size of each compiled object and places functions into
ROM banks according to your configured packing heuristic.
In the IDE: You manage project members visually through the Files sidebar:
Create or import: Right-click inside the workspace tree and choose New File… or New Folder…, or copy files from your desktop into the project directory.
Register member: Right-click any file in the Files sidebar and check Include in Build. The IDE inspects the file extension, registers it under srcFiles (or libFiles for .a archives) in hello.project, and updates the Makefile automatically.
Configure placement: Right-click a source file in the Files sidebar and toggle Force Persistent, Force Scratchpad, or F18A GPU source (which opens the F18A GPU source dialog to configure VRAM base: and Stack top:, later editable via Edit GPU base / stack…).
The scaffolded project open in the Tidepod IDE, ready to build and run.
Every Tidepod project is anchored by a single <name>.project file in its root directory. This
JSON manifest is the single source of truth for the entire build pipeline: it specifies the target cartridge architecture,
all C and assembly build members, binary resources, memory placement directives, bank-packing heuristics, and compiler
optimization levels. Whenever you modify project settings through the IDE or using CLI commands like tidepod add
and tidepod set-type, the project file is updated and Tidepod automatically regenerates the underlying
Makefile, linker scripts, and emulator layout.xml cartridge descriptor.
Project types
The project type determines how the linker organizes the object code and what physical hardware environment is
assumed. You select the target architecture when initializing a new workspace via tidepod new --type …,
or switch existing projects using tidepod set-type or the Project Settings dialog in the IDE.
Small programs that fit one ROM bank and the console's 256 bytes of scratchpad RAM
—
5
8 KB cartridge that uses the 32K expansion
Small code, more RAM. Selected in Project Settings (“8K Cart + 32K RAM”)
banked (default)
1
Bank-switched cartridge, any number of 8 KB banks; requires 32K
Almost everything: the packer spreads your code and data over banks automatically
xb
2
Banked cartridge built from Extended BASIC source (main.bas) compiled to machine code
BASIC programs that need to run fast
ea5
3
Editor/Assembler option 5 program files (NAME1, NAME2, …) and a .dsk image containing them
Disk-loaded programs
custom
4
Whatever your own Makefile builds
Projects with their own build; Tidepod never writes the Makefile
Banked Cartridges (Type 1) represent the standard configuration for modern TI-99/4A software.
Under this model, the 8 KB cartridge memory space mapped at address range 0x6000–0x7FFF is
bank-switched dynamically using inverted 378/379 latch writes. Because banked carts require the 32 KB Memory
Expansion, persistent variables and the execution stack reside in dedicated CPU RAM, while the tms9900-packer
distributes compiled C functions across any number of 8 KB ROM banks and automatically synthesizes transparent
cross-bank trampolines.
Unexpanded 8K Cartridges (Type 0 and 5) are designed for standalone distribution where no peripheral
expansion box is assumed. Because an unexpanded console provides only 256 bytes of internal scratchpad RAM
(0x8300–0x83FF), Type 0 cartridges must manage memory with extreme care: static variables and
call frames must fit within the unreserved portions of the scratchpad. Type 5 retains the single 8 KB ROM limitation
but enables the 32 KB expansion RAM for larger heap and stack allocations.
Extended BASIC (Type 2) ingests standard Extended BASIC source code (main.bas) and
translates it via GCC's Extended BASIC frontend into native TMS9900 machine code. Rather than interpreting tokens
through the console's GPL interpreter, the compiled binary links directly against Tidepod libc,
producing standalone cartridges that execute 20 to 50 times faster while preserving the familiar BASIC syntax.
A typical file
Below is a complete example of a banked game project file. It defines compiler flags, cycle budget targets for the
frame profiler, scratchpad memory offsets, auto-mounted floppy disks, and per-file placement rules:
The project manifest exposes fine-grained control over the compilation pipeline, memory placement, and emulator
integration. Below is a complete breakdown of each supported configuration key:
Key
Meaning
name
Project name. The output files are named after it in lower case (mygame.bin, mygame.rpk).
cartMenuName
Text shown in the console's cartridge menu (upper case, max. 31 characters).
type
Project type, see the table above.
workspacePath
Project directory.
toolchainPath
Toolchain used by the Makefile. Tidepod corrects it automatically when it points at a toolchain that no longer exists (for example after moving the install).
Frame-rate target used by the profiler to compute the frame budget: 60, 30, 20, 15 or 10. Budget = (60 / target) × 50,065 CPU cycles.
includePaths
Extra include directories, separated by spaces or ;. Each becomes -I….
libPaths
Extra library directories.
customCompilerFlags, customLinkerFlags
Appended verbatim to the compile / link commands.
scratchpadBase, scratchpadSize
Where the packer may place scratchpad code. Omitted = packer default (base 0x8342, up to 0x8400). Project Settings offers presets under Scratchpad Base:: Full scratchpad (0x8320), +libtivgm2 (0x8340), +disk access (0x8380), and Custom.
heapSize
Near-heap size in bytes reserved in high 32K expansion RAM for malloc, calloc, realloc, and free (integer, default 0). Passed as --heap-size to tms9900-packer.
Cartridge board written to layout.xml: standard (8K), paged378 (banked default) or paged379i (inverted bank order; old projects that carry it by mistake are migrated automatically).
dsk1–dsk3
Disk images mounted when the project is opened in the IDE or run with tidepod run. Workspace-relative or absolute paths. See Disks & peripherals.
hard1–hard3
Raw hard-disk images (.hd, .hdf, .raw) for an HFDC controller.
emu
Optional per-project emulator overrides (PEB cards, VDP). See The emulator.
srcFiles
Build members, see below.
libFiles
Extra static libraries (.a) to link. "forcePersistent": true puts the whole library in persistent RAM (--persistent-lib).
Compiler Optimization Strategies: Setting optLevelRelease to 3 invokes
GCC's -Os size-optimization profile. On the TMS9900 16-bit processor, where each instruction requires two
to four bytes of ROM and memory access is bounded by 8-bit multiplexed bus cycles, optimizing for code compactness
almost always yields the highest overall execution speed. GCC minimizes stack frame manipulation, maximizes
utilization of the 16 workspace registers (R0–R15), and eliminates redundant SWPB
byte-swapping operations. For active debugging, optLevelDebug: 0 emits unoptimized, line-accurate code
with full DWARF debug symbols that map cleanly to source lines in the debugger.
Bank Packing Algorithms: The packing_algo parameter directs how the
tms9900-packer assigns compiled object files into physical 8 KB ROM banks. Best-Fit Decreasing
(bfd, algo 0) packs the largest translation units first into the tightest available bank space to minimize
slack bytes. First-Fit Decreasing (ffd, algo 1) fills banks sequentially. Call-Graph Clustering
(cluster, algo 2) analyzes call trees across functions: tightly coupled caller and callee routines are
deliberately co-located within the same bank, dramatically reducing runtime bank-switching overhead during time-critical
game loops.
Scratchpad Memory Management: The console's internal 256 bytes of 16-bit scratchpad RAM
(0x8300–0x83FF) offers zero-wait-state access, making it several times faster than external
32K expansion RAM. However, the console BIOS reserves specific regions: 0x8300–0x831F for
the primary workspace registers, 0x8320–0x833F for sound players, and
0x834A–0x837F for disk controller DSR communication buffers (plus 0x83C0–0x83FF
if the console ISR is enabled). New projects leave scratchpadBase empty, which uses the packer default
(0x8342, or 0x8320 / 0x8340 / 0x8380 via the Scratchpad Base:
preset in Project Settings), ensuring user routines do not clobber active system hooks while squeezing maximum performance
out of critical hot paths.
srcFiles entries
Each entry in srcFiles describes a build artifact and optional placement directives. Tidepod inspects
the file extension to route the member through the appropriate compilation stage:
Code and data go to RAM that is always mapped, instead of a ROM bank.
"forceScratchpad": true
add --scratchpad
Code goes to the fast 16-bit scratchpad RAM.
"forceGpu": true, "gpuBase", "gpuStack"
add --gpu --gpu-base … --gpu-stack …
Builds the file as an F18A GPU image instead of host code. See F18A GPU code.
Persistent RAM Placement: In a banked cartridge, switching the ROM bank at 0x6000 causes
all functions and constants located in that bank to immediately vanish from the CPU address space. This creates a severe
hazard for Interrupt Service Routines (ISRs) and audio playback engines, which can be triggered at any moment by the
60 Hz vertical blank interrupt. Applying "forcePersistent": true (or #pragma bank persistent)
instructs the linker to place the compiled code into the unbanked 32 KB expansion RAM. Persistent code is always
resident and immediately callable without bank transition penalties.
Fast Scratchpad Routines: Code tagged with "forceScratchpad": true (or
#pragma bank scratchpad) is packed into the cartridge ROM but copied into the console's zero-wait-state
scratchpad RAM at startup. This is ideal for cycle-critical inner loops such as sprite coordinate transformers,
collision detection routines, or software math functions.
F18A GPU Coprocessor Execution: When a source file is marked with "forceGpu": true,
Tidepod compiles it with the GPU target flags, outputs a binary blob, and embeds it as a ROM resource. It also
generates a companion header (e.g. gpu_map.h) containing the VRAM load address and entry points. At
runtime, the host CPU copies this code into VRAM and signals the F18A GPU to execute asynchronously.
The same placement can be requested from inside a C file with #pragma bank persistent,
#pragma bank scratchpad or #pragma bank gpu (plus #pragma gpu base /
#pragma gpu stack). The pragmas are read when the project is synced.
Editing by hand
You can edit the .project file in any editor. Run tidepod sync afterwards so the Makefile and
layout.xml are regenerated from it.
The IDE combines a code editor, the build pipeline, an integrated emulator and a source-level debugger in one window.
Start it from the terminal with tidepod (empty workspace) or tidepod path/to/name.project.
It runs the exact same make and emulator core as the command line, ensuring your code builds and runs
identically in both environments.
The Tidepod IDE with a project open, showing editor, emulator and sidebar.
Window layout
Area
What it does
Sidebar (left)
Three view tabs:
Files — Workspace directory tree. Double-click any source file to open it in an editor tab; double-click bank_report.json to open the interactive graphical bank report viewer.
Git — Track repository status, view diffs and commit changes.
Docs — Built-in manual page reference library. Double-click any entry to view the man page in an editor tab.
Toggle the sidebar with View → Toggle Explorer.
Editor (centre)
Tabbed source editor featuring syntax highlighting for C, TMS9900 assembly and Extended BASIC; multi-cursor editing; and gutter breakpoint toggling. Man pages open in read-only tabs.
Emulator
The running TI-99/4A emulator panel. Click directly inside the display area to capture keyboard and joystick input; click back into the editor to return focus to coding. Toggle with View → Toggle Emulator or the toolbar button.
Debug panel
Active during debugging sessions with eight specialised tabs:
CPU — Active workspaces (WP, PC, ST), registers R0–R15, and RAM hex inspect.
VDP — Standard registers VR0–VR7 (plus enhanced F18A/Pico registers VR0–VR57) and VRAM inspector.
ASM — Live TMS9900 disassembly synchronized to the current Program Counter.
BRK — Breakpoint list manager (__dbg_printf logpoints appear in the Debug Log).
WCH — Watch expressions with struct field expansion.
GFX — Visual inspection of Pattern Tables, Sprite Attribute Tables, and Color Tables.
DSK — Floppy and hard disk mounts, catalog inspection, and the New Disk creation tool.
PRF — Function-level execution profiler and cycle counts.
Bottom panel
Three bottom tabs:
Build Log — Output from compiler, banker, and linker passes with clickable error diagnostics.
Emulator / Debugger Toolbar (below the CRT display):
Pause / Resume — Halt or continue execution in the emulator (F6).
Step Line / Step Over — Source-level C/XB step into (F11) and step over (F10).
Step Inst / Step OvInst — Assembly instruction-level step into (Shift+F11) and step over (Shift+F10).
Load Cartridge — Open an external .rpk or .bin cartridge image directly in the emulator.
Disk Drive Controller (Floppy icon) — Configure per-project PEB: controller, VDP: type, DSK1:–DSK3: floppy images, and HARD1:–HARD3: hard disk images.
Menus
File — New / Open / Save / Save As / Close Tab; Save Snapshot… / Load Snapshot… (emulator state); New / Open / Save / Close Project; Project Settings…; Preferences….
Edit — Undo, Redo, Cut, Copy, Paste, Select All, Find…, Find in Project…, Replace…, Replace in Project….
File → Project Settings… opens the configuration dialog editing the .project file:
project type (banked, 8k, ea5, xb, custom), cartridge menu label, optimization levels for release and debug,
scratchpad preset (Scratchpad Base:), banker packing algorithm, include and library paths, and custom compiler/linker flags.
Saving regenerates the Makefile automatically.
Project Settings modal dialog.
Disks and emulator settings
The Disk Drive Controller dialog (floppy icon on the emulator toolbar) and the DSK tab mount floppy (.dsk) and hard-disk (.hd) images to DSK1–3 and HARD1–3,
and select the per-project PEB configuration (Inherit, None, TI Controller, HFDC, WHT SCSI) and VDP override. Project-specific mounts are saved directly into
the .project file. Global machine defaults (default VDP engine, global PEB configuration) live in
File → Preferences…. See Disks & peripherals.
Preferences dialog modal.
Session restore
The IDE remembers the active project, open file tabs, window layout, and panel visibility, restoring them automatically
on the next launch.
This first tutorial builds a cartridge that prints text, draws a box with line-drawing characters and echoes key presses.
You'll use the console I/O functions from stdio.h and conio.h. No hardware programming is needed:
the C library handles the screen and keyboard for you.
The finished program after pressing H, I and Q (stock TMS9918A, 40 columns).
What you'll learn
Creating, building and running a project from the command line or the IDE.
Switching to text mode and loading the built-in font.
Printing with printf, positioning with gotoxy and drawing boxes.
Reading keys with cgetc.
Step 1: Create the project
Terminal
tidepod new hello
cd hello
tidepod new creates a folder hello/ with a project file (hello.project), a starter
main.c, a generated Makefile and an empty Makefile.custom for your own rules.
Without --type you get a banked cartridge, which can grow as big as you need. See
Projects for the other types.
In the IDE: Choose File → New Project… (Cmd+Shift+N on macOS,
Ctrl+N on Linux/Windows), enter Project Name:hello, ensure
Project Type: is set to C Banked Cartridge - 32K, and click Create.
The starter main.c opens directly in the central editor tab, with project files listed in the
Files sidebar.
stdio.h declares printf and the screen set-up functions ti_text_mode and
ti_text_load_builtin_font. conio.h declares the console functions: cursor positioning,
colours, box drawing, and cgetc for the keyboard. It also defines the line-drawing character codes
(CH_ULCORNER and friends).
Line 4
main is called by the Tidepod start-up code once memory is set up. Interrupts are disabled when
main starts and stay disabled unless you enable them yourself.
Lines 5–6
Local variables: the screen size (filled in on line 13) and a counter for key presses. Locals live on the stack in
the 32K memory expansion.
Line 8
ti_text_mode(40) switches the video chip to 40-column text mode and resets the cursor to the top-left.
It puts the screen (the name table) at VRAM 0x0000 and the character patterns at 0x1000.
Ask for 80 and you get 80 columns on an F18A, or 40 columns on a stock video chip.
Line 9
ti_text_mode doesn't load any character shapes, so without this line the screen would show blank
or garbage characters. ti_text_load_builtin_font() copies Tidepod's 5×8 font (all 256 codes, including
the box-drawing characters) to 0x1000. It is only linked into your cartridge if you call it. To use your
own font instead, copy it to 0x1000 with rom_to_vram
(see Tutorial 3).
Lines 10–11
Set the background to colour 4 (dark blue) and the text to colour 15 (white). Colours are the 16 standard TMS9918A
palette indices. On an F18A, ti_text_mode loads an EGA-style palette, so the same numbers look different
there (compare the two screenshots below).
Line 12
clrscr() fills the screen with spaces and moves the cursor to (0, 0).
Line 13
screensize stores the current width and height in characters. Using it instead of hard-coding 40 is
what lets the same program draw a correct box in 80-column mode.
Lines 15–16
printf writes at the cursor position and \n moves to the start of the next line, just like
on a PC. %u prints an unsigned number. Text output goes straight to video memory; there is no buffering.
Lines 18–25
Draw a box from row 3 to row 7, the full width of the screen. cputcxy(x, y, c) puts one character at a
position; chlinexy(x, y, len) draws a horizontal line and cvlinexy(x, y, len) a vertical one.
The corners use the CH_…CORNER constants. All console coordinates are (column, row), starting at 0.
Line 27
cputsxy prints a string at a position, inside the box.
Lines 29–31
An endless loop. cgetc() waits for a key press and returns its character code. The console starts with
Alpha Lock on, so letters normally arrive as upper case.
Lines 32–33
gotoxy(2, 6) moves the cursor and cprintf prints formatted text there. Because the
fields have fixed widths (%3d, %3u), each new line overwrites the previous one exactly.
Lines 34–36
Leave the loop on Q. Both cases are checked in case Alpha Lock is off.
Lines 39–41
Print a goodbye and return. A cartridge has nowhere to return to: when main returns, the runtime
simply loops forever, so the screen stays as it is. To start over, reset the emulator.
Step 3: Build and run
Terminal
make
tidepod run
make compiles main.c, packs the code into banks and writes hello.rpk.
tidepod run starts the stand-alone emulator with that cartridge and passes --autorun,
launching directly into your program (bypassing the TI title screen and cartridge menu; run
ti994a-emu --cart hello.rpk without --autorun if you want to see the console title screen
and select HELLO manually).
In the IDE: Click the Build & Run (Play) button in the top toolbar or press Mod+R
(or press F7 to compile only). The Build Log panel at the bottom confirms compiler progress,
and the cartridge boots instantly inside the integrated Emulator panel on the right. Click directly
inside the emulator window to capture keyboard input and type keys into the program. Press F6 to pause or
resume execution at any time.
The hello project in the IDE, running in the built-in emulator.
Try it: 80 columns
Change line 8 to ti_text_mode(80);, rebuild, and run the emulator with an F18A:
Terminal
make
ti994a-emu --f18a --cart hello.rpk
The box now spans 80 columns because the code uses screensize. On a stock console the same cartridge
falls back to 40 columns. To always run this project with an F18A from the command line, add
"emu": { "vdp": "tidepod-f18a" } to hello.project (see The emulator).
In the IDE: Click the Disk Drive Controller button (floppy disk icon on the
emulator/debugger toolbar below the CRT display) and set VDP: to F18A (or
pico-f18a) for this project—or change the global default in File → Preferences…
(Emulator tab → VDP Type:)—then press Mod+R. The emulator
launches directly into high-resolution 80-column mode.
ti_text_mode(40) on a stock TMS9918A.ti_text_mode(80) on an F18A. The border shows the backdrop colour from the F18A palette.
Next
The console functions are the easiest way to show text. For games you usually program the video chip directly:
Tutorial 2 sets up graphics mode, a sprite, the joystick and sound.
Games usually skip the console library and talk to the video chip directly. In this tutorial you set up graphics mode
yourself, move a sprite with joystick 1 and beep when fire is pressed. Everything here is plain C plus one small piece
of inline assembly. The program uses a handful of tiny helper functions that you can copy into your own projects.
The ball sprite after moving right and up. The bottom line shows its position.
What you'll learn
Writing video chip (VDP) registers and video memory (VRAM) from C.
Where graphics mode keeps its tables, and how to use the built-in font outside text mode.
Defining and moving a sprite, in sync with the screen refresh.
Reading the joystick with inline assembly, and making a sound.
Step 1: Create the project
Terminal
tidepod new sprites
cd sprites
In the IDE: Select File → New Project… (Cmd+Shift+N on macOS,
Ctrl+N on Linux/Windows), set Project Name: to sprites, leave
Project Type: as C Banked Cartridge - 32K, and click Create.
Step 2: Write the program
Replace main.c with the listing below. The walkthrough after it covers every line.
Only stdio.h is needed, for snprintf and ti_text_load_builtin_font.
Lines 3–7
The hardware is controlled through fixed memory addresses. Each macro turns an address into a byte variable you can
read or write. volatile is essential: it tells the compiler that every access matters, so it won't drop
or merge repeated writes. 0x8C00 writes VRAM data, 0x8C02 sets a VRAM address or a VDP
register, 0x8802 reads the VDP status, and 0x8400 is the sound chip.
Lines 9–14
The VDP has 16 KB of its own memory (VRAM). In graphics mode it reads several tables from there; you choose where
each table lives. This layout fits them all below 0x1800:
the name table (768 bytes, one character code per screen cell, 32×24),
the colour table (32 bytes, one colour pair per group of 8 characters),
the sprite attribute table (4 bytes per sprite),
the sprite patterns, and the character patterns (8 bytes per character).
The character patterns are at 0x1000 on purpose: that's where
ti_text_load_builtin_font puts the font.
Lines 16–21
Names for the bits returned by read_joystick1, so the main loop reads naturally.
Lines 23–26
vdp_reg writes a VDP register: first the value, then the register number with the top bit set
(0x80), both to the address port.
Lines 28–31
vdp_write_at prepares a VRAM write: the low byte of the address, then the high byte with bit
0x40 set (meaning "write"). After this, every byte written to VDP_DATA goes to the next
VRAM address automatically.
Lines 33–45
vdp_fill writes the same byte count times; vdp_copy copies a buffer from CPU
memory to VRAM. Both rely on the auto-increment.
Lines 47–52
vdp_print writes a string into the name table. The screen is 32 cells wide, so cell (col, row) is at
row * 32 + col. Each character code selects a pattern from the font.
Lines 54–57
wait_vblank waits until the VDP has finished drawing a frame. The top bit of the status register is set
once per frame (60 times a second) and cleared when the status is read. Since interrupts are disabled, polling it is
the simplest way to keep to a steady 60 frames per second, and updating sprites right after it avoids flicker.
Lines 59–72
Joystick 1 is read through the keyboard matrix, which is only reachable with the CPU's CRU instructions. C can't
express those, so this uses GCC-style inline assembly. The two register … __asm__("rN") variables pin
the C values to registers R2 and R1.
li r12,>0024 and ldcr r2,3 select column 6 (joystick 1).
src r12,7 is only a short delay. li r12,>0006 and stcr r1,8 read the eight
row lines into the high byte of R1.
The : "=r"(rows) : "r"(column) : "r12" part tells the compiler what goes in, what comes out, and that
R12 is overwritten. A pressed direction reads as 0, so the result is inverted and shifted down: bit 0 is fire,
then left, right, down and up.
Lines 74–79
sound_off sets the volume of all four sound channels (three tones and noise) to silent. The sound chip
isn't reset when a cartridge starts, so it's good practice to do this first.
Lines 81–85
beep_on sets tone channel 1 to a 10-bit period (two bytes: low 4 bits, then high 6 bits) and its volume to
maximum (0x90). A higher period gives a lower pitch; 127 is roughly 880 Hz.
Lines 87–89
The sprite's shape: 8 rows of 8 pixels, one byte per row, leftmost pixel in the top bit. const keeps it
in cartridge ROM instead of copying it to RAM.
Lines 92–94
The sprite position (pixels; the screen is 256×192), a countdown for the beep, and a text buffer for the status line
(32 characters plus the terminating zero).
Line 96
Silence the sound chip.
Lines 98–105
Program the VDP. Register 1 is written first with 0x80 (16 KB VRAM, display off) so nothing is shown
while the tables are being filled. Register 0 = 0x00 selects graphics mode. Registers 2–6 hold the table
addresses, each divided by its required alignment: that's why the code divides by 0x400,
0x40, 0x800, 0x80 and 0x800. Register 7 sets the backdrop colour
(4, dark blue).
Line 107
Load the built-in font to 0x1000. It works in graphics mode too because the pattern table is there.
Lines 108–111
Clear the screen with spaces; give all characters white text on a transparent background (0xF0: high
nibble foreground, low nibble background); copy the ball shape to sprite pattern 0; and write 0xD0 as the
first sprite's Y position. 0xD0 means "no more sprites", which hides all sprites until the loop draws one.
Lines 113–114
Print the title, then turn the display on: 0xC1 is 16 KB, display on, 8×8 sprites, magnified to 16×16.
Lines 116–122
The game loop. Read the joystick once per frame and move 2 pixels in each pressed direction, staying on screen.
Lines 124–127
On fire, start a beep that lasts 8 frames. Checking beep_frames == 0 stops holding fire from
restarting it every frame.
Line 129
Wait for the end of the frame.
Lines 131–136
Write sprite 0: Y, X, pattern number 0 and colour 0x0B (light yellow). The following 0xD0
ends the sprite list.
Lines 138–140
Count the beep down and silence it when it reaches zero.
Lines 142–143
Format the position with snprintf (which never writes past sizeof line) and print it on
the last row.
Lines 145–146
Never reached; it keeps the compiler happy.
Step 3: Build and run
Terminal
make
tidepod run
In the emulator, joystick 1 is on the arrow keys, with Tab as fire.
In the IDE: Click the Run (Play) button on the toolbar or press
Mod+R. Click the Emulator panel on the right to capture input focus. Use the
arrow keys to move the ball sprite and press Tab to trigger the beep.
Live VDP Inspection: To inspect how the video chip manages tables in memory, start a debug session
with F5 (or click the Debug (Bug) icon). In the debug panel, switch to the GFX
tab to view pattern bitmaps, color assignments, and the live sprite attribute table (SAT). As you move the joystick, the
X/Y coordinates in the SAT update in real time. Switch to the VDP tab to inspect the exact values in
registers VR0 through VR7.
Why not use interrupts?
Tidepod starts main with interrupts disabled, and the C library doesn't need them. Polling the VDP
status, as in wait_vblank, is the usual way to time a game loop.
Try it
Change vdp_reg(1, 0xC1) to 0xC0 to see the sprite at its real 8×8 size.
Add a second sprite: write 4 more bytes before the 0xD0.
Make the beep pitch depend on x.
Next
Drawing tiles by hand gets tedious. Tutorial 3 generates graphics with a script
and lets the build pack them into the cartridge.
Real games carry far more graphics than you'd want to type into C arrays. Tidepod treats any binary file you add to
the project as a resource: the build packs it into the cartridge and gives you its location as
#defines, and rom_to_vram copies it to video memory. In this tutorial a small Python script
generates four tiles and a screen map, and a rule in Makefile.custom re-runs it when it changes.
The screen map: a brick border, a diagonal grid of boxes and a sine wave of diamonds.
What you'll learn
Adding binary .dat files to a project and reading resource_defs.h.
Copying resources to VRAM with rom_to_vram and unwrap.
Generating assets during the build with Makefile.custom.
How graphics-mode colours work per group of 8 characters.
Step 1: Create the project and the generator
Terminal
tidepod new assets
cd assets
mkdir tools
In the IDE: Choose File → New Project… (Cmd+Shift+N on macOS,
Ctrl+N on Linux/Windows), set Project Name: to assets, leave
Project Type: as C Banked Cartridge - 32K, and click Create. In the
Files sidebar, right-click the project root, choose New Folder…, and name it
tools. Right-click tools/, choose New File…, name it make_assets.py,
and paste the script below.
Save this as tools/make_assets.py:
tools/make_assets.py
#!/usr/bin/env python3
"""Generate resources/tiles.dat and resources/screen.dat for Tutorial 3."""
import math
import os
os.makedirs("resources", exist_ok=True)
# Four 8x8 tiles, one byte per pixel row, most significant bit = leftmost pixel.
tiles = [
[0x00] * 8, # 0: empty
[0xFF, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0xFF], # 1: hollow box
[0xFE, 0xFE, 0xFE, 0x00, 0xEF, 0xEF, 0xEF, 0x00], # 2: bricks
[0x18, 0x3C, 0x7E, 0xFF, 0xFF, 0x7E, 0x3C, 0x18], # 3: diamond
]
with open("resources/tiles.dat", "wb") as f:
for tile in tiles:
f.write(bytes(tile))
# A 32x24 screen map: brick border, diamonds on a sine wave inside.
screen = bytearray(32 * 24)
for row in range(24):
for col in range(32):
if row in (0, 23) or col in (0, 31):
tile = 2
elif row == 12 + round(6 * math.sin(col / 3)):
tile = 3
elif (row + col) % 8 == 0:
tile = 1
else:
tile = 0
screen[row * 32 + col] = 0x80 + tile * 8
with open("resources/screen.dat", "wb") as f:
f.write(screen)
Lines 1–6
A plain Python 3 script with no dependencies. It runs from the project folder and makes sure
resources/ exists.
Lines 8–17
Four tiles of 8 bytes each, written back to back: tiles.dat is 32 bytes. Each byte is one row of 8 pixels;
a 1 bit is drawn in the foreground colour, a 0 bit in the background colour.
Lines 19–31
A 32×24 map, one byte per screen cell, exactly the layout of the VDP name table. Each byte is the character code
to show. The tiles will be loaded as characters 0x80, 0x88, 0x90 and
0x98, so tile n is 0x80 + n * 8. The spacing of 8 is explained in the C code below.
tidepod add lists the files in assets.project and regenerates the Makefile.
Any file that isn't C or assembly is treated as a binary resource. The resource name is the file name without its
extension: tiles and screen.
In the IDE: Once the script has run and generated the files, expand the resources/
directory in the Files sidebar. Right-click tiles.dat and check Include in Build,
then right-click screen.dat and check Include in Build. The IDE registers both as cartridge
resources in assets.project.
Step 3: Rebuild the assets automatically
Add these lines to the end of Makefile.custom. Tidepod never overwrites this file, and the generated
Makefile includes it.
The first rule says: tiles.dat is out of date when the script is newer, and the script rebuilds it.
The second says screen.dat comes along with tiles.dat (the script writes both).
The recipe line must start with a tab. Now editing the script, or deleting the .dat
files, makes the next make regenerate them before anything else.
In the IDE: Double-click Makefile.custom in the Files sidebar to open it
in an editor tab, paste the rules above, and press Mod+S to save.
Why two rules?
GNU make 4.3 can say "one recipe makes both files" with &:, but macOS ships make 3.81, which doesn't
support it. The two-rule form works everywhere.
The numbers change as you add resources, which is why you always use the names.
Lines 4–23
The same VDP port macros and helpers as in Tutorial 2. This time the
character patterns are at 0x0800, because this program doesn't use the built-in font.
Lines 12–13
The tiles become characters starting at 0x80, well away from the letters and digits.
Lines 25–26
One colour byte per tile: black on black for the empty tile, dark blue boxes, light red bricks on dark red, and
light yellow diamonds. In graphics mode each colour-table byte covers a group of 8 consecutive characters.
That's why the tiles are 8 character codes apart: each tile gets a group, and therefore a colour, of its own.
Lines 31–37
Display off, graphics mode, table addresses, and a black backdrop (register 7 = 1). Register 6 (sprite patterns)
isn't needed because there are no sprites.
Lines 39–40
Write 0xD0 as the first sprite's Y so no stray sprites show up.
Lines 42–47
For each tile: work out its character code, copy its 8 bytes from the cartridge to that character's pattern
(PATTERNS + ch * 8), and write its colour to the group's colour-table byte
(COLOR_TABLE + ch / 8). The four rom_to_vram arguments are the source bank, the offset
within it, the length and the VRAM destination. Copying part of a resource is just a matter of adding to the offset.
Line 49
unwrap(screen) expands to screen_bank, screen_offset, screen_length, so this copies the
whole map into the name table in one call.
Lines 51–54
Turn the display on and stay here. The picture is now entirely in VRAM; the CPU has nothing left to do.
Step 5: Build and run
Terminal
make
tidepod run
One make is enough. The build first assigns resource locations and writes resource_defs.h
(the [RES] line), then compiles main.c against it:
Change a tile in the script, run make again, and the new graphics appear. See
Resources for how resources are placed and for using them from banked code.
In the IDE: Press Mod+R (or click Run (Play)). The IDE
executes make, which invokes tools/make_assets.py if the assets are missing or modified,
packs the newly generated tiles into ROM bank 0, and runs the cartridge in the embedded Emulator panel.
Next
Tutorial 4 splits a program over several files and looks at where the packer
puts your code.
Tutorial 4: Multiple source files and code placement
Intermediate
As a program grows you'll split it over several files. On a banked cartridge that raises a question that doesn't
exist on a PC: where does each piece of code end up? This tutorial builds a small game skeleton (title screen,
play, game over) as a state machine in three files, shows when code has to be placed in RAM, and how to check what
the packer did.
The title state, showing the best score so far.The play state after a few keys, followed by game over.
What you'll learn
Organising sources in a src/ folder with a shared header.
Why code called through function pointers must be persistent, and how to mark it.
How the packer promotes frequently called code to RAM on its own.
Reading bank_report.json.
Step 1: Set up the project
Terminal
tidepod new multi
cd multi
rm main.c
tidepod remove main.c
mkdir src
The starter main.c is removed from disk and from the project. Create the four files below, then add the
three C files:
Terminal
tidepod add src/main.c src/states.c src/score.c
Headers aren't listed in the project. game.h sits next to the C files that include it, so
#include "game.h" finds it.
In the IDE: Choose File → New Project… (Cmd+Shift+N on macOS,
Ctrl+N on Linux/Windows), set Project Name: to multi, leave
Project Type: as C Banked Cartridge - 32K, and click Create. In the
Files sidebar, right-click the root main.c and select Delete. Right-click
the project folder, select New Folder…, and name it src. Create the four files inside
src/. Then right-click src/main.c, src/states.c, and src/score.c and
check Include in Build.
To mark a file persistent without using a source code pragma, right-click src/states.c in the Files
sidebar and check Force Persistent. The IDE sets "forcePersistent": true in
multi.project and regenerates the Makefile flags.
The shared header
src/game.h
#ifndef GAME_H
#define GAME_H
enum state { STATE_TITLE, STATE_PLAY, STATE_OVER, STATE_COUNT };
typedef enum state (*state_fn)(void);
/* states.c (persistent RAM) */
extern const state_fn state_table[STATE_COUNT];
/* score.c (banked) */
void score_reset(void);
void score_add(unsigned int points);
unsigned int score_get(void);
unsigned int score_best(void);
#endif
Lines 1–2, 17
The usual include guard.
Line 4
One value per screen of the game. STATE_COUNT is not a state; it's the number of states, used to size
the table.
Line 6
state_fn is a pointer to a function that takes nothing and returns the next state. Each state runs
until something happens, then says where to go next.
Lines 8–9
The table of state functions, defined in states.c.
Lines 11–15
A small score module. The rest of the program only uses these four functions, never the variables behind them.
The score module
src/score.c
#include "game.h"
static unsigned int score;
static unsigned int best;
void score_reset(void) {
score = 0;
}
void score_add(unsigned int points) {
score += points;
if (score > best) {
best = score;
}
}
unsigned int score_get(void) {
return score;
}
unsigned int score_best(void) {
return best;
}
Lines 3–4
static keeps the variables private to this file. Like all globals they live in RAM (in
.bss), and the start-up code sets them to zero, so best starts at 0.
Lines 6–23
Reset, add (keeping the best score up to date), and two getters. There's nothing special here: ordinary
functions in an ordinary C file, which the packer is free to place wherever it likes.
The states
src/states.c
/* Called through function pointers, so it must live in RAM. */
#pragma bank persistent
#include <stdio.h>
#include <conio.h>
#include "game.h"
static enum state title(void) {
clrscr();
printf("TUTORIAL 4: STATES\n\n");
printf("Best score: %u\n\n", score_best());
printf("Press any key to play.\n");
cgetc();
score_reset();
return STATE_PLAY;
}
static enum state play(void) {
unsigned char key;
clrscr();
printf("Press keys to score points.\n");
printf("Digits are worth their value.\n");
printf("Press X to end the game.\n");
for (;;) {
gotoxy(0, 5);
cprintf("Score: %5u", score_get());
key = cgetc();
if (key == 'X') {
return STATE_OVER;
}
if (key >= '0' && key <= '9') {
score_add(key - '0');
} else {
score_add(1);
}
}
}
static enum state over(void) {
gotoxy(0, 8);
cprintf("Game over! You scored %u.", score_get());
gotoxy(0, 10);
cprintf("Press any key.");
cgetc();
return STATE_TITLE;
}
const state_fn state_table[STATE_COUNT] = { title, play, over };
Lines 1–2
#pragma bank persistent puts this whole file in persistent RAM: it's copied from the
cartridge to the 32K expansion at start-up and is always reachable.
Why it matters: a banked cartridge only shows one 8 KB bank at a time. When you call a banked function by name, the
packer knows the target and inserts a small trampoline that switches to the right bank. A call through a
function pointer has no name, so no trampoline can be inserted; the CPU would jump into whatever bank happens to be
visible. Code in RAM doesn't have that problem.
The pragma must come before the first line of code (comments are fine). Tidepod reads it when it generates the
Makefile and compiles the file with -mpersistent; you'll see
src/states.o: CCFLAGS += -mpersistent in the Makefile. The command-line alternative is
tidepod add src/states.c --persistent.
Lines 4–6
Console I/O (see Tutorial 1) and the shared header.
Lines 8–16
The title state: clear the screen, show the best score, wait for a key, reset the score and move on to
STATE_PLAY. static hides the function from other files; they reach it through the table.
Lines 18–38
The play state: print the rules, then loop. Each turn redraws the score in a fixed-width field and waits for a key.
X ends the game. Digits add their value (key - '0' turns '7' into 7) and any other key adds
1. Letters arrive in upper case because Alpha Lock is on by default.
Lines 40–47
Game over: print the result below the score, wait for a key, back to the title.
Line 49
The table, in the same order as enum state. It's const, so it holds only addresses of
functions that are in RAM.
The main loop
src/main.c
#include <stdio.h>
#include "game.h"
int main(void) {
enum state current = STATE_TITLE;
ti_text_mode(40);
ti_text_load_builtin_font();
for (;;) {
current = state_table[current]();
}
}
Lines 5–8
Start at the title, in 40-column text mode with the built-in font.
Lines 10–12
The whole state machine: call the function for the current state and store whatever it returns. Adding a state
means adding an enum value, a function and a table entry; this loop never changes.
Step 2: Build and run
Terminal
make
tidepod run
In the IDE: Click the Run (Play) button on the toolbar or press
Mod+R. If you edit game.h, choose Build → Clean Workspace
(Mod+Shift+K) before rebuilding to ensure every file including the header re-compiles.
Changing a header
The generated Makefile doesn't yet know which C files include game.h. After changing a header, rebuild
everything with make clean && make.
Step 3: Where did the code go?
Every build writes bank_report.json. In the terminal, list every placed unit with its
bank, classification, size and "hotness":
states.o is persistent, as requested. But so are main.o, score.o and most of
the C library, even though nothing asked for that. This is the packer's persistent promotion:
After placing the code you marked, the packer ranks the remaining units by hotness: how many call sites
in the program refer to them.
Starting with the hottest, it moves units into the persistent region while they fit, then into high RAM
(persistent_high).
Whatever is left goes into banks.
Code in RAM needs no trampolines, so small programs often end up with none at all. Check the summary and the free
space per region:
To see the decisions as they're made, build with the packer in verbose mode and look for "Phase 2.5":
Terminal
make clean
make PACKER_EXTRA_FLAGS=-v
Output (excerpt)
--- Phase 2.5: Profile-Guided Persistent Promotion ---
Persistent space currently used: 1854 / 7660 bytes
auto-promoted 'console_vdp.o' to persistent (hotness: 52, size: 194)
auto-promoted 'console_attr.o' to persistent (hotness: 11, size: 540)
auto-promoted 'printf_core.o' to persistent (hotness: 11, size: 1546)
...
auto-promoted 'score.o' to persistent (hotness: 5, size: 40)
...
auto-promoted 'ti_text_builtin_font.o' to persistent_high (hotness: 1, size: 2074)
Promotion is not a promise
Promotion depends on how much room is left, so code that's in RAM today can end up banked when the program grows.
If code must be in RAM (function pointers, callbacks, interrupt handlers), mark it persistent yourself, as
states.c does. See Code placement.
In the IDE: Visual Bank Report Viewer
You do not need command-line tools like jq in the IDE. In the Files sidebar, simply
double-click bank_report.json. This opens the interactive graphical bank report viewer:
Memory Region Bars: Color-coded horizontal bar graphs show exact capacity and free headroom for ROM Bank 0, ROM Bank 1, Low Persistent RAM (persistent_lower), and High RAM (persistent_high).
Unit Manifest: Browse each placed object file with its byte size, assigned ROM bank or RAM address, and hotness score. Units marked with forcePersistent appear with a persistent badge, while auto-promoted units display an "auto-promoted" tag.
Call Graph and Trampolines: Hover over any unit to trace inbound and outbound function calls and see whether cross-bank trampolines were synthesized.
The same information in the IDE's bank report view.
Try it
Add a STATE_PAUSE state that P switches to during play.
Remove the pragma, run tidepod sync and make, and check where states.o ends up.
It may well still be in RAM thanks to promotion, but nothing guarantees it.
Next
Tutorial 5 runs C code on the F18A's own processor.
The F18A FPGA replacement (and compatible cores like the Pico9918) features an integrated, high-speed 16-bit
coprocessor known as the GPU. While the console's primary TMS9900 CPU operates at 3.0 MHz and accesses
video memory indirectly through bottlenecked 8-bit memory-mapped I/O ports (0x8C00/0x8C02),
the F18A GPU executes instructions directly out of VRAM at up to 100 MHz. This architecture provides orders of
magnitude higher bandwidth for graphical operations, procedural animation, tile manipulation, and physics routines,
completely freeing the host CPU for game logic and audio playback.
Tidepod provides first-class support for compiling standard C code targeting the F18A GPU. The build pipeline
compiles the GPU code in a freestanding environment, links it against the designated VRAM memory map, packages the
resulting binary as a cartridge resource, and generates C symbol bindings (gpu_map.h) for the host program.
In this tutorial, you will implement a true asymmetric dual-processor application: the GPU runs an autonomous loop
in VRAM that rotates screen tiles and updates a hardware frame counter, while the host CPU detects the video chip,
bootstraps the GPU, and polls the shared counter across the VDP bus.
With an F18A: the middle row is rotated by the GPU, and the frame counter is written by the GPU and printed by the CPU.The same cartridge on a stock TMS9918A.
What you'll learn
Adding a dedicated GPU translation unit with tidepod add --gpu and configuring memory anchors.
Architecting a shared VRAM layout between host TMS9900 code and coprocessor code via a shared header.
Runtime hardware detection with ti_vdp_detect(), unlocking enhanced registers via VR57, and starting the coprocessor.
Reading back coprocessor output across the VDP memory bus with zero CPU contention.
Step 1: Set up the project
Begin by initializing a clean project directory using the Tidepod command-line tool. Because this project contains
two distinct executables—the cartridge ROM binary for the console and the VRAM binary for the GPU—we remove the
default main.c and organize our sources into a structured layout:
Terminal
tidepod new gpudemo --menu "GPU DEMO"
cd gpudemo
rm main.c
tidepod remove main.c
mkdir -p src include
Next, register the GPU source file and host application with Tidepod. When adding a GPU source unit, you must supply
the target VRAM load address and the stack pointer:
The --gpu flag instructs the build system that src/gpu.c is not destined for cartridge ROM banks.
Instead, the toolchain compiles it with -ffreestanding -nostdlib -ffixed-r15 -Os, links it with
crt0_gpu.o, and resolves all absolute pointers relative to 0x3000. The GPU's stack is anchored at
0x3F00 and grows downwards towards the code section. In your gpudemo.project manifest, Tidepod
records this metadata under "forceGpu": true, "gpuBase": "0x3000", and "gpuStack": "0x3F00".
In the IDE: Choose File → New Project… (Cmd+Shift+N on macOS,
Ctrl+N on Linux/Windows), enter Project Name:gpudemo, set
Cart Menu Title: to GPU DEMO, leave Project Type: as
C Banked Cartridge - 32K, and click Create. In the Files sidebar,
delete the starter main.c, create src/ and include/ folders, and create the files.
To register and configure the GPU code without command-line flags: right-click src/gpu.c in the Files
sidebar, check Include in Build, and select F18A GPU source. In the
F18A GPU source dialog, enter VRAM base:0x3000 and
Stack top:0x3F00 (you can adjust these later via Edit GPU base / stack…).
Then right-click src/main.c and check Include in Build.
The shared VRAM layout
Because the host CPU and the F18A GPU communicate through video memory, both programs must strictly adhere to an
identical memory layout. VRAM addresses must be partitioned to prevent display tables, tile patterns, and executable
coprocessor code from overwriting each other:
include/shared.h
#ifndef SHARED_H
#define SHARED_H
/* VRAM layout shared by the host program and the GPU program. */
#define NAME_TABLE 0x0000
#define COLOR_TABLE 0x0300
#define SPRITE_ATTRS 0x0380
#define GPU_FRAMES 0x0400 /* 16-bit counter, written by the GPU */
#define PATTERNS 0x1000
#define SCROLL_ROW (NAME_TABLE + 12 * 32)
#endif
In this partition, standard display tables occupy the bottom 8 KB of VRAM: the screen name table sits at 0x0000
(768 bytes), the color attribute table at 0x0300, sprite attributes at 0x0380, and font patterns
at 0x1000. Notice GPU_FRAMES at offset 0x0400: this two-byte word serves as an
inter-processor communication mailbox. The GPU increments this word once per video frame, and the host CPU reads it back
to monitor coprocessor activity. Everything fits safely below 0x3000, ensuring complete isolation from the
GPU executable image and stack.
The GPU program
src/gpu.c
#include <f18a_gpu.h>
#include "shared.h"
void main(void) __attribute__((noreturn));
void main(void) {
volatile unsigned char *row = (volatile unsigned char *)SCROLL_ROW;
unsigned int frames = 0;
for (;;) {
F18A_GPU_IDLE();
frames++;
F18A_GPU_MMIO16(GPU_FRAMES) = frames;
if ((frames & 3) == 0) {
unsigned char first = row[0];
unsigned int i;
for (i = 0; i < 31; i++) {
row[i] = row[i + 1];
}
row[31] = first;
}
}
}
Lines 1–2
GPU programs can't use the C library; f18a_gpu.h provides the few helpers they need.
Lines 4–6
The GPU start-up code calls main, which must never return: there's nothing to return to.
noreturn tells the compiler so.
Line 7
The GPU sees VRAM as its own memory, starting at address 0. So a plain pointer to SCROLL_ROW points
straight at screen row 12. volatile makes sure every read and write really happens.
Line 11
F18A_GPU_IDLE() puts the GPU to sleep until its trigger fires. The main program sets the trigger to
"once per frame", so this line paces the loop at 60 times a second.
Lines 13–14
Count the frame and store the count as a 16-bit word at GPU_FRAMES.
F18A_GPU_MMIO16(addr) is a volatile word access to an address.
Lines 16–23
Every fourth frame, rotate the 32 characters of the row one place to the left: remember the first, shift the other
31, put the first at the end. The text appears to scroll, and the console CPU isn't involved at all.
vdpinfo.h has ti_vdp_detect; f18a_gpu_host.h has
f18a_gpu_start; resource_copy.h and resource_defs.h are as in
Tutorial 3. gpu_map.h is generated from the GPU build and defines
gpu_base, gpu_entry, gpu_stack and gpu_size. The GPU program is
packed as a resource named gpu (after the file name), so resource_defs.h also has
gpu_bank, gpu_offset and gpu_length.
Lines 9–36, 47–50
The VDP helpers from Tutorial 2, plus the VRAM read port 0x8800.
Lines 38–45
vdp_read_word reads two bytes from VRAM. Setting an address without the 0x40 bit
prepares a read; each read from 0x8800 then returns the next byte. The GPU stored the counter high byte
first, so the first byte read is the high byte.
Line 54
ti_vdp_detect() finds out which video chip is fitted: TI_VDP_STOCK,
TI_VDP_F18A or TI_VDP_PICO9918. Do this first, before setting up the screen.
Lines 56–68
The same graphics-mode set-up as Tutorial 2, with the built-in font at 0x1000. The counter in VRAM is
zeroed so the CPU never shows a stale value.
Lines 70–76
On a stock chip there is no GPU, so explain and stop. Writing F18A registers to a stock chip would scramble its
normal registers, so this check has to come before any of the F18A code below.
Lines 78–80
The F18A's extra registers are locked at power-on. Writing 0x1C to register 57 twice unlocks them.
Register 30 is then set to 32, the number of sprites allowed per scanline. Its reset value is 4, which would
make sprites disappear unexpectedly in a real game.
Lines 82–84
Print a title and the row the GPU will scroll, then turn the display on.
Line 86
Copy the GPU program from the cartridge to VRAM 0x3000. It must go to the address it was built for,
which is exactly what gpu_base holds.
Line 87
Register 50 bit 0x20 makes the GPU's IDLE wake up once per frame (at vertical sync).
Without it, F18A_GPU_IDLE() would sleep forever.
Line 88
f18a_gpu_start sets the GPU's program counter to the entry point and starts it. From here on both
processors run at the same time.
Lines 90–94
Once per frame, read the GPU's counter and print it on row 20. The CPU's only job is reporting.
Step 2: Build and run
Terminal
make
ti994a-emu --f18a --cart gpudemo.rpk
The build compiles the GPU program first ([GPU-CC], [GPU-LD], [GPU-BIN]),
then the main program. Run it with tidepod run instead and you'll get whatever video chip Preferences
selects; with a stock chip you'll see the "NO F18A FOUND" message. To make the F18A the default for this project from the
command line, add "emu": { "vdp": "tidepod-f18a" } to gpudemo.project.
In the IDE: Configure the project to use the enhanced video processor by clicking the
Disk Drive Controller button (floppy disk icon on the emulator/debugger toolbar below the CRT display)
and setting VDP: to F18A (or pico-f18a)—or by setting the global
default in File → Preferences… (Emulator tab → VDP Type:). Press
Mod+R (or click Build & Run (Play)). The IDE compiles both the GPU freestanding binary and
the host cartridge, starts the embedded emulator with F18A coprocessor support enabled, and begins real-time execution.
The generated include/gpu_map.h shows how small the GPU program is:
Programming the F18A GPU requires thinking in terms of two asynchronous processors operating on a shared memory bus.
The console's host CPU (TMS9900) executes from ROM and system RAM at 3.0 MHz, while the GPU executes directly from video RAM
at 100 MHz. Unlike standard desktop multi-threading where cache coherency and mutexes are managed by an operating system,
here you manage memory synchronization directly through VRAM and VDP hardware registers.
The host CPU communicates with VRAM through memory-mapped I/O ports at 0x8C00 (data write),
0x8C02 (address latch), and 0x8800 (data read). Every byte transferred across this interface
requires setting up a 14-bit VRAM address pointer in the VDP and performing byte-wide read or write operations. In sharp
contrast, the F18A GPU treats VRAM as its native flat address space from 0x0000 to 0x3FFF.
A C pointer dereference such as *row = val translates into a single 16-bit memory store inside the VDP itself,
completing in a single 100 MHz clock cycle. Because the F18A memory controller arbitrates access between the host port
and the GPU core transparently during display scanlines, the two processors never crash or lock up each other's memory bus.
Hardware safety is maintained by the F18A's register lock mechanism. At console power-on, all registers beyond VR7 are
locked to maintain strict backward compatibility with legacy TMS9918A games. Writing the magic sequence 0x1C
twice to VDP Register 57 (VR57) unlocks the enhanced register file. Immediately following unlock, our host code sets
VR30 to 32. On a stock TMS9918A, a scanline containing more than 4 sprites causes subsequent sprites to drop out (flicker).
The F18A supports up to 32 active sprites per scanline; configuring VR30 unlocks this capacity for the entire frame.
Pacing the GPU is controlled through VDP Register 50. Setting bit 0x20 (decimal 32) instructs the F18A
to issue an execution trigger at the start of each vertical blanking interval. When the GPU executes F18A_GPU_IDLE(),
it suspends execution and consumes negligible internal bus bandwidth until the VSYNC pulse arrives. Once awakened,
the GPU performs its row rotation and increments GPU_FRAMES in under a fraction of a millisecond, then
immediately returns to the idle state. This hardware synchronization completely eliminates tearing and race conditions
without requiring spinlocks or semaphores.
Try it
Scroll every frame instead of every fourth, or scroll the other way.
Let the CPU write a value into VRAM that the GPU reads, for example a scroll speed.
See resources/examples/f18a_bump in the Tidepod install for a GPU that draws pixels in bitmap mode.
The C library's fopen, fread and fwrite work on TI disk files. In this tutorial
the program keeps a small save game on DSK1: how many times it has run, a player name and a best score.
You'll also create a blank disk image and tell the emulator to use it.
First run: there's no save file yet, so the program starts fresh and saves a score of 420.Second run: the save game is loaded back from the disk.
What you'll learn
Creating a disk image and mounting it from the project file.
Writing and reading a struct with fwrite and fread.
Telling "no file yet" apart from a real error with stdio_last_error.
Project settings for programs that use disks.
TI FDC vs HFDC missing-file codes
Opening a missing file returns NULL on both controllers (it must not hang).
TI FDC reports stdio_last_error() == 2; HFDC reports
7 (STDIO_ERR_FILE). This tutorial uses the HFDC so the sample can treat
“no save yet” as error 7. See docs/stdio_errors.md and stdio_last_error(3).
Step 1: Create the project and a blank disk
Terminal
tidepod new notes
cd notes
mkdir tools disks
From the command line, this script writes a blank 90 KB disk (single-sided, single density). Save it as
tools/blank_dsk.py:
tools/blank_dsk.py
#!/usr/bin/env python3
"""Create a blank, formatted 90 KB (single-sided, single-density) TI disk image."""
import sys
SECTORS = 360
path = sys.argv[1]
name = (sys.argv[2] if len(sys.argv) > 2 else "BLANK").upper()
image = bytearray(SECTORS * 256)
vib = bytearray(256)
vib[0:10] = name.ljust(10)[:10].encode("ascii") # disk name, space padded
vib[10:12] = SECTORS.to_bytes(2, "big") # total sectors
vib[12] = 9 # sectors per track
vib[13:16] = b"DSK" # format marker
vib[16] = 0x20 # not protected
vib[17] = 40 # tracks per side
vib[18] = 1 # sides
vib[19] = 1 # density
vib[0x38] = 0x03 # bitmap: sectors 0 and 1 in use
for i in range(0x38 + SECTORS // 8, 256):
vib[i] = 0xFF # sectors that don't exist
image[0:256] = vib
# Sector 1 (the file index) stays all zeros: no files.
with open(path, "wb") as f:
f.write(image)
Lines 5–9
A disk image is just its sectors in order: 360 sectors of 256 bytes. The disk name comes from the command line.
Lines 11–19
Sector 0 describes the disk: its name, size and geometry, and the DSK marker that identifies a
formatted disk.
Lines 20–22
From offset 0x38, one bit per sector says whether it's in use (lowest bit = lowest sector). Sectors 0 and
1 belong to the disk itself; bytes beyond the last sector are marked as used so nothing is ever allocated there.
Lines 24–28
Sector 1, the list of files, stays empty. Everything else is zeros too.
Terminal
python3 tools/blank_dsk.py disks/notes.dsk NOTES
In the IDE (no script required): Create the project via File → New Project…
(Cmd+Shift+N on macOS, Ctrl+N on Linux/Windows) with
Project Name:notes. Then switch to the DSK tab in the right-hand
debug panel, select drive DSK1, and click New Disk. Choose a save path such as
disks/notes.dsk in the file dialog: the IDE creates a formatted 90 KB (SSSD) disk image and
immediately mounts it in DSK1.
Step 2: Configure the project
Open notes.project in an editor and add three entries after "libFiles" (mind the comma
after the ]):
The emulator mounts this image as DSK1 whenever it runs the project. The path is relative to the project folder.
scratchpadBase
The disk system uses part of the console's scratchpad RAM. Starting Tidepod's scratchpad area at 0x8380 (the +disk access (0x8380) preset in Project Settings) keeps the two apart. See Code placement.
emu
Use only an HFDC disk controller at CRU 0x1100 (4352) for this project, instead of the controllers set in Preferences. See The emulator.
Then regenerate the Makefile so it picks up the new scratchpad base:
Terminal
tidepod sync
In the IDE: Rather than editing JSON by hand, configure these options through the IDE dialogs:
Open File → Project Settings…, set Scratchpad Base: to +disk access (0x8380), and click Save.
Click the Disk Drive Controller button (floppy disk icon on the emulator/debugger toolbar below the CRT display). Set PEB: to HFDC (>1100), ensure disks/notes.dsk is mounted under DSK1:, and close the dialog. The IDE writes these settings directly to notes.project.
Step 3: Write the program
Replace main.c with:
main.c
#include <stdio.h>
#include <string.h>
#include <conio.h>
#define SAVE_FILE "DSK1.SAVEGAME"
#define SAVE_MAGIC 0x5444
struct save_game {
unsigned int magic;
unsigned int runs;
unsigned int best;
char name[12];
};
static struct save_game save;
static int load_game(void) {
FILE *f = fopen(SAVE_FILE, "rb");
size_t got;
if (f == NULL) {
return 0;
}
got = fread(&save, sizeof save, 1, f);
fclose(f);
return got == 1 && save.magic == SAVE_MAGIC;
}
static int save_game(void) {
FILE *f = fopen(SAVE_FILE, "wb");
size_t put;
if (f == NULL) {
return 0;
}
put = fwrite(&save, sizeof save, 1, f);
fclose(f);
return put == 1;
}
static unsigned int read_number(void) {
unsigned int value = 0;
unsigned char key;
for (;;) {
key = cgetc();
if (key == KEY_ENTER) {
return value;
}
if (key >= '0' && key <= '9' && value < 6000) {
value = value * 10 + (key - '0');
cputc(key);
}
}
}
int main(void) {
unsigned int score;
ti_text_mode(40);
ti_text_load_builtin_font();
stdio_set_vdp_base(0x2000);
if (load_game()) {
printf("Save game loaded from disk.\n");
} else {
printf("No save game (error %u).\n", stdio_last_error());
memset(&save, 0, sizeof save);
save.magic = SAVE_MAGIC;
strcpy(save.name, "PLAYER ONE");
}
save.runs++;
printf("\nName: %s\n", save.name);
printf("Runs: %u\n", save.runs);
printf("Best: %u\n", save.best);
printf("\nType a score and press ENTER: ");
score = read_number();
if (score > save.best) {
save.best = score;
printf("\nNew best score!");
}
if (save_game()) {
printf("\nSaved to %s.\n", SAVE_FILE);
} else {
printf("\nSave failed (error %u).\n", stdio_last_error());
}
return 0;
}
Line by line
Lines 1–3
File functions and printf from stdio.h; memset and strcpy from
string.h; cgetc, cputc and KEY_ENTER from conio.h.
Lines 5–6
TI file names include the device: DSK1.SAVEGAME is the file SAVEGAME on drive 1. File names
are at most 10 characters. The magic number (the letters "TD") lets the program recognise its own file.
Lines 8–15
Everything that's saved, in one struct (18 bytes). It's a global so it isn't on the small stack, and
static keeps it private to this file.
Lines 17–27
load_game opens the file for binary reading ("rb"). fopen returns
NULL if it can't open it, typically because it doesn't exist yet. fread returns the number of
whole items read; the load counts as good only if one full struct came back and it carries the magic number.
Always fclose a file you opened.
Lines 29–39
save_game does the reverse with "wb", which creates the file or replaces it. Binary files
are created as TI "INTERNAL/FIXED 128" files: data is stored in 128-byte records, so this 18-byte struct takes one
record. See fopen(3) for the other file types.
Lines 41–55
read_number reads digits until ENTER, echoing each digit with cputc. Other keys are
ignored, and the value < 6000 check keeps the result within an unsigned int (16 bits).
stdio_set_vdp_base(0x2000) moves the DSR Peripheral Access Block (PAB) and VDP record buffers to VRAM
0x2000 so disk operations do not collide with the 40-column font pattern table at 0x0800–0x0FFF
(or 0x1000–0x17FF). See stdio_set_vdp_base(3).
Lines 64–71
Try to load. If that fails, show why with stdio_last_error(), which returns the error code of the last
failed file operation, and start a fresh save game. On a fresh disk you'll see error 7: the file isn't there.
Lines 73–76
Count this run and show the save game.
Lines 78–83
Ask for a score and keep it if it's a new best.
Lines 85–89
Write the save game back and report the result.
Lines 90–91
Return; the runtime then loops forever with the text still on screen.
Step 4: Build and run
Terminal
make
tidepod run
tidepod run mounts disks/notes.dsk and uses the HFDC from the project file. The first time,
the program reports "No save game (error 7)". Type a score and press ENTER. Run it again and the save game comes back.
To start over, recreate the disk with the script.
In the IDE: Press Mod+R (or click Run (Play)). The embedded
emulator boots with disks/notes.dsk attached to drive 1. Click inside the emulator panel, type a number,
and press Enter.
Inspecting the Disk Catalog: While the program is running (or paused), switch to the DSK
tab in the debug panel. The drive list shows DSK1: disks/notes.dsk with an active directory catalog:
you will see SAVEGAME listed alongside its record format (INT/FIX 128) and sector count.
To run the emulator directly from the command line outside of Tidepod, pass the equivalent hardware switches:
The DSK tab in the IDE, with notes.dsk mounted in DSK1 and SAVEGAME in its file list.
Text files
This tutorial sticks to binary fwrite/fread.
For DISPLAY/VARIABLE text, open with "w" or "w:dv:80" and write lines with
fputs/fprintf that include \n (each newline ends a record).
See fopen(3) and fputs(3).
Try it
Let the player type a name and store it in save.name (leave room for the terminating zero).
Keep a top-five table instead of one best score.
See Disks and peripherals for hard disks, the other controllers and the IDE's disk tools.
Tidepod includes a full optimizing compiler for TI Extended BASIC. Rather than interpreting tokens slowly
through the console ROM's GPL runtime, Tidepod translates Extended BASIC source (.bas) directly into
native TMS9900 machine code, linking it with libxb.a and libc.a.
The resulting cartridge images run between 20× and 100× faster than the original
1980s interpreter. This tutorial covers:
The critical role of CALL VSYNC and frame synchronization in compiled code.
The interplay between CALL VSYNC, CALL MOTION, and asynchronous CALL SOUND.
Example 1: Classic line-numbered Extended BASIC (100% retro type-in compatible).
Example 2: Modern structured Extended BASIC (labels, WHILE, IF/ENDIF, and SUB routines).
Creating, building, and running an Extended BASIC project in Tidepod.
The Heartbeat of Compiled Games: CALL VSYNC
On the original 1980s Extended BASIC cartridge, interpreted programs executed so slowly that game loops naturally took
several video frames per iteration. Furthermore, background tasks—such as updating automotion sprites and decrementing sound
timers—were serviced automatically by the console's vertical-blank interrupt service routine (ISR).
In compiled native machine code, a tight loop executes tens of thousands of times per second. Without throttling,
a game loop would spin uncontrollably fast.
What CALL VSYNC Does
CALL VSYNC is a statement provided by libxb. It halts CPU execution until the next VDP
vertical blanking interrupt (60 Hz on NTSC, 50 Hz on PAL). Calling CALL VSYNC inside your game loop accomplishes two vital things:
1. Locks framerate: Paces your game loop to a rock-solid, smooth 60 FPS.
2. Drives the background engine: It serves as the heartbeat dispatcher for CALL MOTION
sprite automotion and asynchronous CALL SOUND durations.
The Interplay: VSYNC, MOTION, and SOUND
Understanding how these three statements cooperate is essential for writing responsive games:
1. Sprite Automotion (CALL MOTION)
CALL MOTION(#sprite, row_vel, col_vel) assigns independent row and column velocities
(−128 to 127) to a hardware sprite. Velocities use 12.4 fixed-point scaling, where a value of
16 advances the sprite by 1 pixel per 60 Hz frame (60 pixels/second).
In compiled mode, sprites only advance their positions when CALL VSYNC is called!
Each time CALL VSYNC executes, the runtime adds velocity to each sprite's 12.4 fixed-point accumulator and updates VRAM coordinates from the integer part. If you forget CALL VSYNC, sprites with automotion will freeze in place.
2. Non-Blocking Audio (CALL SOUND with negative duration)
CALL SOUND(duration, freq, vol, ...) plays tones or noise through the SN76489 sound chip:
Positive duration: (e.g. CALL SOUND(150, 440, 2)) — Synchronous. The program halts and waits 150 ms before executing the next line of code.
Negative duration: (e.g. CALL SOUND(-300, 220, 0) or CALL SOUND(-200, -7, 0) for an explosion) — Asynchronous. The sound chip begins playing immediately, and execution returns to your program with zero delay.
The Audio Timer Gotcha
Asynchronous sound duration counters are decremented frame-by-frame inside CALL VSYNC.
If your loop does not call CALL VSYNC, negative-duration sounds will never expire and will play forever!
How they work together in an event loop
! Trigger an asynchronous explosion sound (does not pause gameplay)
CALL SOUND(-250, -7, 0)
! Launch an enemy missile gliding diagonally (16 = 1 px/frame)
CALL MOTION(#2, 6, 8)
! The central game loop pumps both systems:
WHILE GAME_ACTIVE%
CALL VSYNC ! 1. Waits for 60Hz tick
! 2. Moves sprite #2 by (6/16, 8/16) = (0.375, 0.5) px/frame
! 3. Decrements sound countdown by 16.6ms
CALL KEY(1, K%, S%)
! Read input, check collisions, update game state...
WEND
Example 1: Classic Line-Numbered Extended BASIC
Tidepod compiles traditional 1980s line-numbered BASIC without modification. Below is a complete, playable
meteor evasion game written in classic syntax. Adding a single CALL VSYNC
at line 320 is all it takes to adapt a classic game to run at locked 60 FPS compiled speed.
Classic Extended BASIC running compiled in the TI-99/4A emulator: Meteor Dodge with sprite automotion and sound.
meteor.bas (Classic Style)
100 REM =====================================
110 REM METEOR DODGE - CLASSIC TI EXTENDED BASIC
120 REM =====================================
130 CALL CLEAR :: CALL SCREEN(2)
140 CALL MAGNIFY(2)
150 CALL CHAR(96,"183C7EFFFF7E3C18")
160 CALL CHAR(100,"00183C3C18000000")
170 CALL COLOR(9,7,1) :: CALL COLOR(10,9,1)
180 DISPLAY AT(1,9):"METEOR DODGE"
190 DISPLAY AT(24,1):"JOYSTICK 1: MOVE FIRE: SPEED"
200 REM --- SETUP SPRITES ---
210 REM #1 = Player (Cyan, row 150, col 128)
220 CALL SPRITE(#1,96,7,150,128)
230 REM #2 = Meteor with automotion downward
240 CALL SPRITE(#2,100,9,10,64)
250 CALL MOTION(#2,12,0)
260 SCORE% = 0 :: LIVES% = 3 :: SEED% = 42 :: PX% = 128
270 REM --- ASYNCHRONOUS ENGINE SOUND ---
280 CALL SOUND(-200, 110, 15)
290 REM =====================================
300 REM MAIN GAME LOOP
310 REM =====================================
320 CALL VSYNC
330 CALL JOYST(1, JX%, JY%)
340 CALL KEY(1, K%, S%)
350 REM Move player horizontally
360 IF JX% = 4 THEN PX% = PX% + 4 ELSE IF JX% = -4 THEN PX% = PX% - 4
370 IF PX% < 10 THEN PX% = 10 ELSE IF PX% > 240 THEN PX% = 240
380 CALL LOCATE(#1, 150, PX%)
390 REM Check if meteor reached bottom of screen
400 CALL POSITION(#2, MY%, MX%)
410 IF MY% > 160 THEN GOSUB 600
420 REM Check collision between player and meteor
430 CALL COINC(#1, #2, 12, HIT%)
440 IF HIT% <> 0 THEN GOSUB 700
450 SCORE% = SCORE% + 1
460 IF LIVES% > 0 THEN 320
470 REM =====================================
480 REM GAME OVER
490 REM =====================================
500 CALL DELSPRITE(ALL)
510 DISPLAY AT(12,10):"GAME OVER!"
520 DISPLAY AT(14,8):"SCORE: ";SCORE%
530 CALL SOUND(800, 150, 0)
540 GOTO 540
550 REM =====================================
560 REM SUBROUTINE: RESET METEOR
570 REM =====================================
600 SCORE% = SCORE% + 50
610 CALL SOUND(-80, 880, 5)
620 SEED% = (SEED% * 37 + 11) MOD 200
630 RANDOM_COL% = SEED% + 20
640 CALL LOCATE(#2, 1, RANDOM_COL%)
650 CALL MOTION(#2, (SEED% MOD 6) + 6, 0)
660 RETURN
670 REM =====================================
680 REM SUBROUTINE: PLAYER HIT
690 REM =====================================
700 LIVES% = LIVES% - 1
710 REM Trigger non-blocking explosion noise (-7 is white noise)
720 CALL SOUND(-350, -7, 0)
730 CALL LOCATE(#2, 1, 128)
740 RETURN
Example 2: Modern Structured Extended BASIC
Tidepod also supports modern structured Extended BASIC. You do not need line numbers.
You can use named labels, WHILE / ENDWHILE loops,
native 16-bit integer variables (% suffix for maximum speed),
and modular SUB definitions with parameters.
Modern Structured Extended BASIC: Paddle Bounce with custom characters, modular SUBs, and locked 60 FPS pacing.
paddle.bas (Structured Style)
! =======================================================
! PADDLE BOUNCE - MODERN STRUCTURED EXTENDED BASIC
! =======================================================
CALL SCREEN(1)
CALL CLEAR
CALL MAGNIFY(2)
! Define custom characters
CALL CHAR(96, "FFFFFFFFFFFFFFFF") ! Paddle bar
CALL CHAR(100, "3C7EFFFFFFFF7E3C") ! Ball
! Initialize Globals (Integer % for high speed)
PADDLE_X% = 120
BALL_X% = 128
BALL_Y% = 30
DX% = 3
DY% = 3
SCORE% = 0
RUNNING% = 1
! Create Sprites
CALL SPRITE(#1, 96, 7, 160, PADDLE_X%)
CALL SPRITE(#2, 100, 15, BALL_Y%, BALL_X%)
! Draw UI
DISPLAY AT(1, 1): "SCORE:"
CALL UPDATE_HUD(SCORE%)
! Non-blocking start sound
CALL SOUND(-250, 659, 0)
! =======================================================
! MAIN GAME LOOP
! =======================================================
WHILE RUNNING%
CALL VSYNC()
! Read Joystick 1
CALL JOYST(1, JX%, JY%)
IF JX% = 4 THEN PADDLE_X% = PADDLE_X% + 4
IF JX% = -4 THEN PADDLE_X% = PADDLE_X% - 4
! Clamp paddle to screen boundaries
IF PADDLE_X% < 16 THEN PADDLE_X% = 16
IF PADDLE_X% > 224 THEN PADDLE_X% = 224
CALL LOCATE(#1, 160, PADDLE_X%)
! Update Ball Position
BALL_X% = BALL_X% + DX%
BALL_Y% = BALL_Y% + DY%
! Bounce off left / right walls
IF (BALL_X% < 8) OR (BALL_X% > 240) THEN
DX% = -DX%
CALL SOUND(-60, 1200, 4)
ENDIF
! Bounce off ceiling
IF BALL_Y% < 10 THEN
DY% = -DY%
CALL SOUND(-60, 1000, 4)
ENDIF
! Check Paddle Collision
CALL COINC(#1, #2, 16, HIT%)
IF HIT% <> 0 THEN
DY% = -DY%
BALL_Y% = 152
SCORE% = SCORE% + 10
CALL UPDATE_HUD(SCORE%)
CALL SOUND(-80, 800, 2)
ENDIF
! Check Bottom Miss (Game Over)
IF BALL_Y% > 170 THEN RUNNING% = 0
! Update Ball Sprite Position
CALL LOCATE(#2, BALL_Y%, BALL_X%)
ENDWHILE
! =======================================================
! GAME OVER SEQUENCE
! =======================================================
CALL DELSPRITE(ALL)
DISPLAY AT(12, 11): "GAME OVER"
DISPLAY AT(14, 9): "FINAL: "; SCORE%
CALL SOUND(600, -7, 0)
@GAMEOVER_LOOP:
CALL VSYNC()
GOTO @GAMEOVER_LOOP
! =======================================================
! SUBROUTINES
! =======================================================
SUB UPDATE_HUD(S%)
DISPLAY AT(1, 8): S%
SUBEND
Step-by-Step: Creating an Extended BASIC Project
Using the Command Line
Terminal
# Create a new Extended BASIC project
tidepod new my_xb_game --type xb
cd my_xb_game
# Run directly in the built-in emulator
tidepod run
This creates a project file my_xb_game.project with "type": 2 (Extended BASIC),
a template main.bas, and a generated Makefile.
Using the IDE
Open Tidepod and select File → New Project… (Cmd+Shift+N on macOS, Ctrl+N on Linux/Windows).
Enter Project Name: (e.g. my_xb_game).
In the Project Type: dropdown, select Extended BASIC.
Click Create. The IDE opens main.bas directly in the syntax-highlighted editor.
Press Mod+R (or click Build & Run) to compile and launch in the embedded emulator.
Performance Tips for Compiled Extended BASIC
Use integer variables (% suffix): Plain variables (e.g. X) are treated as 32-bit IEEE floats. Adding a percent sign (e.g. X%) forces 16-bit native TMS9900 hardware math, which is dramatically faster.
Always place CALL VSYNC in loops: Without CALL VSYNC, loops spin thousands of times per second, burning CPU cycles and breaking automotion and sound timers.
Prefer WHILE/WEND over GOTO: In structured code, WHILE/WEND produces cleaner assembly branch patterns and makes complex logic easier to maintain.
Tutorial 8: SuperAMS — fat pointers that look like C
Intermediate
SuperAMS does not give the TMS9900 a flat megabyte of RAM. Native
char * stays 16-bit. Extra SRAM is reached by remapping 4K windows.
Tidepod’s GNU C named address space __sams (and the optional
<sams_far.h> macros) let you write far memory almost like ordinary C:
p[i] = …, static far tables, typed allocs, and a lock helper for hot loops.
The finished tutorial cart after each sugar check (emulator with --mem sams).
What you'll learn
Near vs far memory, and when to use each.
Allocating with sams_malloc / sams_new and indexing with p[i].
Declaring static far objects in .sams_bss.
Optional sugar in <sams_far.h>, and locking a page for bulk fills.
Requires SAMS in the emulator
Always run with --mem sams (or real SuperAMS hardware). Without it,
sams_init() fails and far allocs return null. Tidepod projects default to
-std=gnu99 so the __sams qualifier is available; plain
-std=c99 rejects it.
Near vs far (one table)
Kind
Type
Where it lives
How you touch it
Near
char *, int *
.data / .bss / stack / lock window
Ordinary C
Far
T __sams * / sams_ptr_t
SAMS pages (fat heap or .sams_*)
p[i], or lock → near
Keep code, small state, and hot working sets near; put large tables and level data far.
Linking any sams_* symbol forces the packer’s SAMS near map (near image under >C000, 8K)
so lock windows stay free. See sams(3).
Step 1: Create the project
Terminal
tidepod new sams_demo
cd sams_demo
A banked cartridge is fine. Replace main.c with the program below
(or study the ready-made cart in Tidepod’s
resources/examples/sams_tutorial/).
In the IDE:File → New Project…, name it sams_demo,
type C Banked Cartridge - 32K. Paste the listing into main.c.
When you run from the IDE, set memory expansion to SAMS in Preferences
(or pass --mem sams on the command line).
Step 2: The program
main.c
#include <conio.h>
#include <sams_far.h>
#include <stdio.h>
/* Static far BSS — zeroed by crt0 via sams_static_init. */
SAMS_FAR_OBJ(unsigned char, g_marks)[64];
static void hang(void) {
volatile int h = 1;
while (h) { }
}
static void fail(const char *msg) {
clrscr();
cputsxy(0, 0, msg);
cputsxy(0, 22, "RESULT: FAIL");
hang();
}
int main(void) {
SAMS_FAR_PTR(unsigned char) buf;
SAMS_FAR_PTR(unsigned) words;
unsigned i;
__asm__ __volatile__("limi 0" : : : "cc");
ti_text_mode(40);
ti_text_load_builtin_font();
clrscr();
cputsxy(0, 0, "SAMS tutorial");
cputsxy(0, 1, "sugar + far heap");
if (sams_init() != 0)
fail("NO SAMS (use --mem sams)");
/* 1. Untyped alloc — sams_malloc returns void __sams * (no cast). */
buf = sams_new_bytes(128);
if (!buf)
fail("OOM bytes");
for (i = 0; i < 128; i++)
buf[i] = (unsigned char)(i & 0xFFu);
for (i = 0; i < 128; i++) {
if (buf[i] != (unsigned char)(i & 0xFFu))
fail("FAIL p[i]");
}
/* 2. Typed alloc + 16-bit store. */
words = sams_new(unsigned, 16);
if (!words)
fail("OOM words");
words[0] = 0xBEEFu;
if (buf[1] != 1)
fail("FAIL isolation");
if ((unsigned char)(words[0] >> 8) != 0xBE)
fail("FAIL hi");
/* 3. Static far object. */
for (i = 0; i < 64; i++)
g_marks[i] = (unsigned char)(0x40u + (i & 0x0Fu));
if (g_marks[3] != 0x43)
fail("FAIL static");
/* 4. Lock once for a fast near fill. */
SAMS_WITH_NEAR(buf, unsigned char, near, {
for (i = 0; i < 128; i++)
near[i] = 0xA5;
});
if (buf[0] != 0xA5 || buf[127] != 0xA5)
fail("FAIL lock");
sams_delete(words);
sams_delete(buf);
cputsxy(0, 3, "1 malloc p[i] OK");
cputsxy(0, 4, "2 sams_new HI OK");
cputsxy(0, 5, "3 static FAR OK");
cputsxy(0, 6, "4 WITH_NEAR OK");
cputsxy(0, 22, "RESULT: PASS");
hang();
return 0;
}
Include
<sams_far.h> pulls in <sams.h> and defines the sugar macros.
You can use raw __sams instead; the header is optional.
g_marks
SAMS_FAR_OBJ expands to unsigned char __sams g_marks. The linker places it in
.sams_bss at a fat VMA (page 0x10 onward). crt0 zeroes it before
main.
sams_init
Probe the card, identity-map classic windows, enable MAP mode. Call once before any far alloc or access.
sams_new_bytes / p[i]
Fat heap alloc. Each buf[i] expands to a map + load/store through the accessor window.
Fine for sparse access; slow for multi-kilobyte fills (see lock below).
sams_new / words[0]
Typed sams_calloc. A 16-bit store on the same page maps the accessor window once.
SAMS_WITH_NEAR
Locks the page into >C000 or >D000, runs the block with a native near pointer,
then unlocks. Only two lock windows exist — nested locks of the same page refcount.
Step 3: Build and run
Terminal
make
ti994a-emu --cart sams_demo.rpk --mem sams --autorun --f18a
You should see four OK lines and RESULT: PASS. Without
--mem sams, expect NO SAMS.
If you have written a game or utility in C for a desktop PC—or another retro platform with a flat address space—porting it to the TI-99/4A often hits a wall as soon as your data outgrows the standard 32 KB RAM expansion.
A SuperAMS (SAMS) memory card expands the console up to 1 MB of RAM, which is plenty of room for large tilemaps, level layouts, lookup tables, and dynamic objects. However, using that extra memory requires a slightly different mental model than desktop C. This guide walks through how SAMS memory works in plain terms, how locks work when you need several far arrays at once, and how to adapt an existing C codebase step by step.
If you haven't tried SAMS in a small program yet, start with Tutorial 8: SuperAMS first, or keep the sams(3) reference page handy.
1. Why You Can't Just Call malloc(200000)
On a modern computer, a pointer (char *) is 32 or 64 bits wide. The CPU can point directly to any byte in gigabytes of RAM at any time.
The TI-99/4A's TMS9900 processor has a 16-bit address bus. Every normal C pointer (void *, char *, int *) is only 2 bytes wide and can only address 64 KB (0x0000–0xFFFF) in total. Half of that 64 KB is permanently wired to console ROM, cartridge ROM, and hardware registers—leaving only 32 KB of CPU address space for RAM (0x2000–0x3FFF and 0xA000–0xFFFF).
So how does a 1 MB SAMS card fit into a 32 KB space? Paging.
The SAMS card divides its 1 MB of RAM into 256 pages of 4 KB each.
The CPU still sees the same 32 KB of RAM addresses, divided into eight 4 KB "windows."
At any moment, you can tell the SAMS card: "Show me SAMS page #42 inside one of my 4 KB RAM windows."
Because a SAMS buffer isn't permanently sitting at a fixed 16-bit CPU address, Tidepod distinguishes between two kinds of pointers:
Pointer Kind
How to Write It
Size
What It Means
Regular ("Near") Pointer
unsigned char *p
2 bytes (16-bit)
Points directly to standard RAM that is always visible to the CPU. Fast (one instruction per access), but limited to ~16 KB of working space.
SAMS ("Far") Pointer
unsigned char __sams *p orSAMS_FAR_PTR(unsigned char) p
4 bytes (32-bit)
Stores both a SAMS page number and a byte offset (0–4095) within that page. Whenever you read or write p[i], the compiler automatically maps the right 4 KB page into view.
How Tidepod Organizes RAM When You Use SAMS
As soon as your program uses any sams_* function, Tidepod automatically reserves the 4 KB windows at 0xC000–0xEFFF as temporary staging windows for SAMS pages (and keeps 0xF000–0xFFFF for the C call stack). Your normal global variables (.data / .bss) and regular malloc heap live in the 8 KB block at 0xA000–0xBFFF.
2. Deciding What Goes Where
You don't need to move every single variable into SAMS. In fact, your program will be much simpler and faster if you only move the bulky data:
Keep in regular RAM: Loop counters, player coordinates, state flags, small structs, file handles, and anything your code touches dozens of times every frame.
Move to SAMS (__sams): Large arrays, world maps, decompressed graphics buffers, level history, and large dynamically allocated tables.
Stream from disk when needed: Remember that SAMS is volatile RAM—it starts empty when the console powers on. If you have hundreds of kilobytes of pre-built level data, store it in cartridge ROM banks (see Binary Resources) or on disk, and unpack or generate your working state in SAMS at runtime.
3. Step-by-Step Code Changes
Step A: Initialize SAMS at Startup
Before touching any SAMS variable or calling sams_malloc(), call sams_init() once at the beginning of main(). It checks that a SAMS card is attached, sets up the default 4 KB windows, and turns on page mapping.
main.c
#include <sams.h>
#include <sams_far.h> /* Optional helper macros */
int main(void) {
if (sams_init() != 0) {
/* SAMS card not enabled — remind the user to pass --mem sams */
return 1;
}
/* Safe to use __sams arrays and sams_malloc() from here on */
}
Step B: Move Large Global and Static Arrays to SAMS
The quickest way to free up regular RAM is to find your biggest global or static arrays and add the __sams qualifier (or the SAMS_FAR_OBJ macro from <sams_far.h>):
Before → After
/* Before: Takes up 4 KB of precious regular RAM */
static unsigned char dungeon_map[64 * 64];
/* After: Lives in SAMS RAM instead — zero regular RAM used! */
static unsigned char __sams dungeon_map[64 * 64];
/* Or using the optional <sams_far.h> macro: */
static SAMS_FAR_OBJ(unsigned char, dungeon_map)[64 * 64];
You can still read and write dungeon_map[i] just like a normal array. Note that SAMS global arrays cannot have compile-time initializers (like = {1, 2, 3}); they start zeroed out at boot and should be filled by your code at runtime.
Step C: Replace Large malloc Calls with sams_malloc
If your C program dynamically allocates large buffers with malloc(), switch those allocations to the SAMS heap functions:
Standard C Heap (Regular RAM)
SAMS Heap (1 MB SAMS RAM)
<sams_far.h> Shorthand
malloc(bytes)
sams_malloc(bytes)
sams_new_bytes(bytes)
calloc(count, size)
sams_calloc(count, size)
sams_new(Type, count)
realloc(ptr, bytes)
sams_realloc(ptr, bytes)
—
free(ptr)
sams_free(ptr)
sams_delete(ptr)
Important 4 KB limit per allocation: Each individual sams_malloc() allocation must fit inside a single 4 KB SAMS page (up to ~4,080 bytes). If your original program allocates a single 32 KB block with malloc(32768), split it into an array of eight 4 KB SAMS pointers (or allocate per room/chunk instead of one giant block).
Step D: Update Function Parameters and Struct Pointers
Because a regular pointer is 2 bytes and a SAMS pointer is 4 bytes, the compiler treats unsigned char * and unsigned char __sams * as different types. If a function receives a SAMS buffer, add __sams to its parameter declaration in both the .c file and the .h header:
Updating Function Signatures & Structs
/* Function that reads directly from a SAMS buffer */
void render_map_row(unsigned char __sams *row_data, int width);
/* Struct living in regular RAM, holding a pointer to a large buffer in SAMS */
struct LevelRoom {
int width, height; /* Small fields: stay in regular RAM */
char title[16]; /* Small string: stays in regular RAM */
unsigned char __sams *tile_buffer; /* Large array: lives in SAMS! */
};
4. Working with Functions That Expect Regular Pointers
What if you have an existing function—or a standard library function like memcpy()—that expects a regular char * or void *, and you don't want to rewrite it to take __sams pointers? You have two easy tools:
Option 1: Temporarily "Lock" the SAMS Page into Regular RAM
Calling sams_lock(far_ptr) maps that SAMS page into one of two dedicated 4 KB windows in regular RAM
(>C000 and >D000) and returns a normal 16-bit pointer (void *) to it.
While it is locked, any function can read or write that memory using standard C pointers at full CPU speed.
When you're done, call sams_unlock(far_ptr).
Using sams_lock() / sams_unlock()
/* An existing function that only accepts a regular C pointer */
void unpack_room(unsigned char *dest, int size);
void load_room_into_sams(unsigned char __sams *far_buf, int size) {
/* 1. Pin the SAMS page into regular RAM and get a normal pointer */
unsigned char *near_buf = (unsigned char *)sams_lock(far_buf);
if (!near_buf) return;
/* 2. Pass the normal pointer to our unchanged function */
unpack_room(near_buf, size);
/* 3. Unpin the page when finished */
sams_unlock(far_buf);
}
The SAMS_WITH_NEAR macro in <sams_far.h> does the lock and unlock automatically for a block of code:
Yes — you can hold more than one lock at a time, including when the arrays live on
different SAMS pages. Tidepod reserves exactly
two lock windows (SAMS_LOCK_SLOTS is 2):
Two far arrays on different pages: both can be locked together.
Each call returns its own near pointer (one in >C000, one in >D000),
and you can use both in the same loop — for example, copying from one SAMS buffer into another.
Two far arrays on the same page: they share one slot.
A second sams_lock of that page bumps a refcount and returns another near pointer into the same window.
A third distinct page while two different pages are already locked:
sams_lock returns NULL. Unlock one of the held pages first, then lock the third.
Two different SAMS pages locked together
void copy_sams_to_sams(unsigned char __sams *src,
unsigned char __sams *dst,
unsigned n) {
unsigned char *s = (unsigned char *)sams_lock(src);
unsigned char *d = (unsigned char *)sams_lock(dst);
unsigned i;
if (!s || !d) {
/* Third distinct page already locked elsewhere, or no SAMS */
if (s) sams_unlock(src);
if (d) sams_unlock(dst);
return;
}
for (i = 0; i < n; i++)
d[i] = s[i];
sams_unlock(dst);
sams_unlock(src);
}
Locks vs p[i] accessors
Element access like far[i] uses a separate scratch window (>E000) and
does not consume a lock slot. You can keep two pages locked for hot near loops and still
touch other SAMS data with p[i] / sams_read8 in the same function — just don't
expect that third buffer to have a long-lived near pointer until you unlock something and lock it.
Option 2: Copy or Fill with SAMS Helper Functions
Standard memcpy() and memset() from <string.h> only work on regular 16-bit pointers. To copy data between regular RAM and SAMS (or fill a SAMS buffer), use the built-in SAMS helpers:
sams_memcpy_to(far_dst, near_src, bytes) — Copy from regular RAM into SAMS.
sams_memcpy_from(near_dst, far_src, bytes) — Copy from SAMS into regular RAM.
sams_memset(far_dst, byte_val, bytes) — Fill a SAMS buffer with a byte value.
5. Keeping Performance Snappy
Reading or writing far_ptr[i] is super convenient, but behind the scenes each access calls a small helper function that maps the SAMS page before reading or writing the byte.
For occasional reads and writes (checking a tile where the player is standing, updating an inventory item), far_ptr[i] is plenty fast and keeps your code clean.
For tight loops over hundreds of bytes (clearing a screen buffer, decompressing a level, copying a row of tiles), lock the page once with SAMS_WITH_NEAR (or sams_lock) and loop over the regular pointer inside. That maps the page just once instead of hundreds of times, running at full native CPU speed.
Slow vs. Fast Loop Over a SAMS Buffer
/* Slower: Remaps the SAMS window 1,024 times (once per byte) */
for (int i = 0; i < 1024; i++) {
far_buf[i] = 0;
}
/* Fast: Maps the SAMS window ONCE, then loops at full native speed */
SAMS_WITH_NEAR(far_buf, unsigned char, near_buf, {
for (int i = 0; i < 1024; i++) {
near_buf[i] = 0;
}
});
6. Common Pitfalls to Avoid
Don't cast a SAMS pointer to a regular pointer: Writing (char *)far_ptr throws away the SAMS page number and leaves you with a bogus memory address. Always use sams_lock(far_ptr) when you need a regular pointer.
Don't keep a locked pointer after sams_unlock(): Once unlocked, that 4 KB window in regular RAM may be reused by the next SAMS page lock. Unlock as soon as your loop or function finishes.
Only two different SAMS pages at once: See
Locking several SAMS arrays at once above.
Two pages is the hard ABI limit; a third distinct sams_lock returns NULL.
Don't mix free() and sams_free(): Pointers from malloc() must be freed with free(); pointers from sams_malloc() must be freed with sams_free() (or sams_delete()).
Remember to enable SAMS in the emulator: Pass --mem sams to ti994a-emu (or select SAMS under Memory Expansion in Tidepod's Preferences), otherwise sams_init() will report that no SAMS card is installed.
The Debugging chapter introduces the debugger panels. This guide is about using them well
on real projects: where breakpoints can land on a banked cartridge, how stepping behaves across bank trampolines,
how to read watches on SuperAMS (__sams) data, what the bank and SAMS lines on the CPU tab mean, and what
to expect from Extended BASIC projects.
If you prefer a terminal or an external frontend, see The Standalone GDB Bridge. For
banked carts and XB the IDE debugger is currently the more capable of the two.
1. Open the Project and Build Debug
Open the project (tidepod mygame.project, or File → Open Project) and start a session
with Build → Debug (F5, or Cmd+D on macOS). That runs
make debug, which compiles with -O<optLevelDebug> -g -gdwarf-2 and keeps
__dbg_printf and BRK(). The packer writes <project>.debug next to the
.rpk: an ELF sidecar holding DWARF, the bank map (.tms9900.bankmap) and logpoints. The IDE
loads it fresh on every debug launch.
Debug at -O0
Keep optLevelDebug at 0. From -O1 up, locals move into registers or disappear,
line rows merge, and stepping jumps around. A plain Run builds release (-DNDEBUG,
stripped): there is no .debug, so breakpoints and watches do nothing.
2. Breakpoints
Where
How
Source
Click the gutter next to an executable line.
Assembly
Click an address in the ASM tab.
Code
BRK() from debug.h pauses when reached (debug builds only).
List
The BRK tab jumps to or deletes any breakpoint.
Breakpoints are keyed by bank and address. On a banked cart the same
>6000–>7FFF address exists in every bank, so a source breakpoint takes its bank from
the DWARF line row (through the bank map, with --bank-base applied) and fires only when that bank is
selected. A breakpoint set in the ASM tab uses whichever bank is selected at that moment.
A gutter click on a line with no code (a comment, a declaration with no initializer, most closing braces) has no
line row to bind to. Put the breakpoint on the next statement.
3. Stepping
Key
Action
F6
Pause / continue
F10
Step over (C line)
F11
Step into (C line)
Shift+F11
Step out
Shift+F10
Step one TMS9900 instruction
Line steps run until the program counter maps to a different source line. Cross-bank calls go through packer
trampolines, which have no line rows, so Step Into passes straight through them and stops in the
callee. To watch a trampoline switch banks, step by instruction in the ASM tab. All bindings can be changed under
Preferences → Shortcuts.
4. Watches
Type a name into the WCH tab and press Add. Watches are re-resolved against the
current PC, so a local is shown only while it is live at that PC. Outside its range it shows as unresolved, not as
stale memory. Double-click a value to edit it.
Kind
Shown as
Notes
Scalar
decimal / hex
Size from the DWARF type (uint8_t is 1 byte, long is 4).
Struct
expandable
One level of members per expansion.
Array
-> @0xADDR
Elements from the DWARF array bounds.
Near pointer
-> @0xADDR
Expands the first 10 elements of the pointed-to type.
T __sams * / sams_ptr_t
-> @pPPPP:OOOO
4-byte fat pointer: SAMS page and offset.
Reading __sams watches
A SAMS pointer is a page number plus an offset, not a CPU address (see
Working with SuperAMS memory). The watch shows the raw pair. If that page is
currently mapped into one of the CPU's 4 KB windows, it also shows the near address the CPU would use:
WCH tab
level -> @p0042:0123 (=0xE123) page 0x42 is in the >E000 window
tiles -> @p0051:0000 page 0x51 is not mapped right now
You can expand a fat pointer's elements only while its page is mapped. The debugger never remaps SAMS behind your
program's back, because that would change the state you are debugging. To look inside an unmapped buffer, break in
code that has it locked (sams_lock / SAMS_WITH_NEAR) and watch the near pointer
sams_lock returned.
Ordinary globals, the near heap and stack locals are read through the SAMS mapper exactly as the CPU sees them. With
Tidepod's SAMS layout they sit in >A000–>BFFF and >F000, so they always
resolve.
BNK is the physical cart bank currently selected on the cartridge board.
Breakpoints and the bank map use the same number. Projects built with --bank-base N number their
logical banks from N, so BNK can differ from the names in
bank_report.json by that offset.
SAMS MAP / ACC are the mapper's mapping-mode and register-access bits.
The SAMS lines appear only when the emulator runs with SAMS. tidepod run turns SAMS on by itself when
bank_report.json shows the project uses the SAMS memory layout.
The page row lists the SAMS page in each 4 KB window. In Tidepod's layout C and
D are the two sams_lock windows, E is the scratch window used by
p[i] accesses, and F holds the stack. A window showing its own number
(A:0A) is identity-mapped.
The RAM hex view shows the CPU's current view, so >C000–>EFFF
show whichever page is mapped there right now.
Debugger reads are passive
Inspecting memory never disturbs the machine. Reads have no VDP, GROM or sound side effects and cost no cycles, and
the I/O ports at >8400–>9FFF read as 0. Edits in the cart window
(>6000–>7FFF) are ignored, so a hex-view poke can never switch banks by accident.
With SAMS enabled, >4000–>5FFF shows the mapper registers.
6. Extended BASIC Projects
XB projects are compiled by xb1, Tidepod's GCC Extended BASIC front end (see
Tutorial 7). The debugger knows when a project is BASIC:
Pause lands on your BASIC. If you pause inside the runtime (sound, CALL helpers, the
interrupt handler), the debugger keeps running until it reaches a line of your .bas file.
Every statement has a line.xb1 emits a line entry for each executable statement,
including assignments, GOSUB/RETURN, NEXT, ELSE and
SUBEND, plus markers for lines that generate no code. Breakpoints on assignments and inside
GOSUB bodies hit the right line.
Variables are typed. Main-program variables are emitted as real debug variables with named
types, so X%, SCORE and NAME$ watch like C globals.
Optimised builds work.FOR loops no longer crash the compiler at
-O1/-Os.
Similar variable names
Name matching is still loose. A watch on BALL% can bind to BALL_SPEED% if the exact name is
not found. When two variables share a prefix, check the type and address in the watch row.
7. Known Limits
No data breakpoints. Neither the IDE nor the GDB stub has watchpoints yet. Break where the value
is written, or add __dbg_printf at the suspect sites.
Unmapped SAMS pages are not browsable. Fat-pointer children and the hex view show only pages
that are currently mapped.
Physical bank numbers only.BNK and breakpoint banks are physical. A logical/physical
display is planned.
Optimised code. Above -O0 expect missing locals, merged lines, and
Step Over stopping on the same line twice.
IDE-only features. BASIC auto-skip and line stepping are not yet in the standalone emulator, so
ti994a-emu --gdb behaves like plain GDB.
One level of pointer expansion. Children of an expanded pointer don't expand further.
ti994a-emu has a GDB Remote Serial Protocol server built in. Use it from a terminal, from CI scripts,
or from any GDB/MI frontend such as VS Code. Host GDB doesn't know the TMS9900, so always connect with the
toolchain's tms9900-elf-gdb.
This guide covers starting the stub, the extra bank register, how breakpoints pick a bank,
monitor sams, frontend setup, and an honest list of what does not work yet. For interactive debugging of
banked carts and XB programs, the IDE debugger is currently more capable.
1. Start the Stub
Terminal 1
make debug
tidepod run --debug # emulator window + GDB server on :3333
# Or drive the emulator directly / headless in CI:
ti994a-emu --cart mygame.rpk --autorun --headless --gdb 3333
ti994a-emu --cart mygame.rpk --autorun --gdb 4444 --debug-dwarf build/mygame.debug
GDB_TRACE=1 ti994a-emu --cart mygame.rpk --autorun --gdb # log every packet to stderr
tidepod run --debug uses the same machine setup as the IDE: VDP, PEB cards, memory expansion and disk
mounts from Preferences and the project's "emu" settings. --gdb with no port listens on
3333. The emulator finds the matching .debug next to the cartridge (mygame.rpk →
mygame.debug) and uses it to pick breakpoint banks and to print __dbg_printf logpoints.
Network exposure
The stub listens on all network interfaces and accepts one client at a time. Don't run it on a network you don't
trust.
2. Connect
Terminal 2
tms9900-elf-gdb mygame.debug -ex 'target remote :3333'
0x0000601a in _vector ()
(gdb) break main
Breakpoint 1 at 0x65a6: file src/main.c, line 148.
(gdb) continue
Breakpoint 1, main (argc=..., argv=...) at src/main.c:148
148 int main(int argc, char *argv[]) {
(gdb) next
152 init_graphics();
The CPU halts wherever it happens to be when GDB connects. With --autorun that is usually already inside
your cartridge; without it, the console is still on the title screen.
You may see Python Exception … No module named 'gdb' warnings at startup. They are harmless: regular
commands and MI still work.
3. Registers and the Bank Register
Besides pc, wp, st and r0–r15, the stub exposes a
bank register holding the physical cartridge bank that is currently selected:
gdb
(gdb) p $bank
$1 = 0
(gdb) set $bank = 1
(gdb) x/2xh 0x6000 # now reads bank 1's ROM
0x6000: 0x022a 0xfffc
(gdb) set $bank = 99
Could not write register "bank"; remote failure reply '01'
Writes are checked against the cartridge size. Changing bank swaps the ROM under the running program, so
set it back before you continue. It is for looking at other banks, not for redirecting execution.
4. Breakpoints and Banks
Only software breakpoints are supported. Each breakpoint address in the cart window
(>6000–>7FFF) exists once per bank, so the stub decides which bank you meant:
Addresses outside the cart window match in any bank.
Otherwise, if the debug info has a source line at that address, the stub uses that line's bank.
Otherwise it uses the bank that is currently selected.
So break file.c:42 and break function do the right thing on banked carts in most cases. To
force a bank, the stub accepts the bank in the high bits of the address (0x1713a = bank 1,
>713A). GDB's TMS9900 addresses are 16 bits wide, so break *0x1713a is truncated before
it reaches the stub. Send the raw packet instead:
This prints the mapper state and the SAMS page in each 4 KB CPU window, using the same window roles as
Working with SuperAMS memory. Without SAMS enabled the reply is
SAMS not enabled.
GDB reads memory through the CPU's current mapping. A __sams pointer prints as its raw 32-bit value: page
in the high word, offset in the low word. To read the data behind it, find the window that holds the page in
monitor sams and read window base + offset, or stop where your program has the page locked.
6. Interrupting and Memory Access
Interrupt:Ctrl+C in GDB (or -exec-interrupt in MI) pauses
the CPU and reports SIGINT. An interrupt sent while already stopped is ignored. Older stubs answered it
with a second stop reply, which knocked frontends out of sync.
Reads are passive and shared with the IDE debugger. They have no VDP, GROM or sound side
effects, go through the SAMS mapper, and the cart window shows the current bank.
Writes to RAM and scratchpad go straight to memory. Writes to console ROM or the cart window
(>6000–>7FFF) are refused, so GDB reports Cannot access memory instead
of silently switching banks. Writes to the VDP, GROM and sound ports still reach the hardware. Use
$bank to change banks.
7. Frontends: GDB/MI and VS Code
The stub implements the packets that target remote and GDB/MI need, including target description,
no-ack mode, continue/step, register and memory access, breakpoints, monitor, detach and kill. Raw MI looks
like this:
GDB/MI
tms9900-elf-gdb --interpreter=mi2 mygame.debug
-target-select remote localhost:3333
-break-insert main
-exec-continue
-exec-next
-data-list-register-values x
-exec-interrupt
For VS Code with the C/C++ extension, start the emulator first (for example from a task running
tidepod run --debug) and attach with:
This configuration has not been through an automated MI test yet. If a frontend hangs, restart the emulator with
GDB_TRACE=1 and look at the last packet it logged.
hbreak fails on insert. A software watch single-steps the whole program and is far too slow. Break at the write site instead.
Source lines on banked carts
GDB has no map of cartridge banks. Breakpoints land, but at a stop GDB may show a resource symbol and "No line number information". Use the IDE, or debug code that sits in an unbanked cart or persistent RAM.
break *0xBAAAA with a bank
Truncated to 16 bits by GDB. Use maint packet Z0,BAAAA,2.
GDB's built-in int is 4 bytes
Variables print with their real 16-bit types. In casts, use short / unsigned short.
Deep backtraces, finish
The unwinder may stop with "frame did not save the PC" after the first frame or two.
kill
Exits the emulator. Use detach to keep it running.
Other banks and unmapped SAMS pages
Peek with set $bank and restore it afterwards, or stop where the page is mapped.
The TI-99/4A uses a 16-bit, big-endian TMS9900 CPU paired with an 8 KB banked cartridge memory model.
While Tidepod provides a modern GCC 14.2 C99 compiler, bare-metal 16-bit systems have fundamental architectural constraints
that will surprise experienced desktop C developers or anyone porting existing C code.
This guide highlights the most common architectural gotchas, silent bugs, memory placement rules, and code generation traps to watch out for.
1. Memory Model & Variable Storage
Where variables live: memory regions and storage classes
In a modern desktop OS, memory feels like a flat 64-bit pool. On the TI-99/4A, memory is partitioned into distinct hardware regions
with very different speeds, persistence guarantees, and banking behaviors:
Storage Class / Declaration
Section
Memory Region & Address
Access & Lifetime
int local_var; (in function)
Stack / Regs
High RAM (0xFFFF down) or Workspace (0x8300)
Allocated on stack (or kept in registers R1–R8). Destroyed when function returns.
int global_score = 100;
.data
High RAM (0xA000–0xFFFF)
Read-write global RAM. Initial values copied from cartridge ROM by crt0 at boot.
int enemy_buffer[64]; (uninitialized)
.bss
High RAM (0xA000–0xFFFF)
Read-write global RAM. Cleared to zero by crt0 during system boot.
const uint8_t level_tiles[] = { ... };
.rodata
Cartridge ROM (0x6000–0x7FFF)
Read-only. Stays in the source file's assigned bank. Only visible when that bank is switched in!
__attribute__((section(".persistent")))
.persistent
Low RAM (0x2000–0x3FFF)
Always visible regardless of active ROM bank. Ideal for trampolines and shared state.
__attribute__((section(".scratchpad")))
.scratchpad
Scratchpad RAM (0x8342–0x83BF)
Internal 16-bit CPU RAM. Zero wait-states, ultra-fast access, but extremely limited in size.
// --- Example: Variable placement in practice ---
// Placed in ROM (.rodata) inside this file's assigned bank:
const uint8_t TILE_MAP[256] = { 0x01, 0x02, ... };
// Placed in High RAM (.data) at 0xA000+; initialized from ROM at startup:
int player_lives = 3;
// Placed in High RAM (.bss) at 0xA000+; zero-initialized at startup:
int high_scores[10];
// Placed in Low RAM (.persistent) at 0x2000+; always accessible across all banks:
__attribute__((section(".persistent"))) int active_bank_payload;
void update_player(int delta) {
// Kept in workspace register R1-R8 (0x8302-0x8310 in Scratchpad RAM),
// or spilled to stack at top of High RAM (growing down from 0xFFFF):
int new_x = player_lives * delta;
}
16-bit pointers cannot encode a bank
Pointers in the TMS9900 C ABI are strictly 16-bit addresses (0x0000–0xFFFF). A pointer has no bits
reserved for a cartridge bank number. If a function in Bank 1 takes a pointer to local read-only data in Bank 1,
and you pass that pointer to a function in Bank 2, dereferencing the pointer in Bank 2 will read whatever bytes happen
to sit at that offset in Bank 2 ROM.
The Rule for Shared Data
Any data passed between functions across different banks by reference must reside in RAM: either
persistent low RAM (0x2000–0x3FFF), high expansion RAM (.data / .bss at 0xA000–0xFFFF),
or Scratchpad RAM (0x8300–0x83FF).
Local string literal arrays vs. static strings
In standard C, declaring an initialized local array inside a function allocates stack space and copies the string from ROM on every single function call:
// AVOID: Allocates 16 bytes on the stack and runs memcpy from ROM on every call
void show_dialog(void) {
char msg[] = "Press Any Key!";
con_puts(msg);
}
// PREFERRED: Zero stack allocation, directly references ROM string constant
void show_dialog(void) {
static const char * const msg = "Press Any Key!";
con_puts(msg);
}
On a system where stack memory is precious, declaring local string arrays or large local buffers triggers hidden
runtime copy overhead and consumes stack headroom.
Dynamic heap (malloc / free) is opt-in
libc.a provides both a near-heap allocator (malloc(), calloc(),
realloc(), and free() in high 32K expansion RAM; see malloc(3))
and a SAMS far-heap allocator (sams_malloc(), sams_calloc(), sams_realloc(),
and sams_free() in <sams.h>; see sams_init(3)).
However, the near-heap reservation defaults to 0 bytes unless you set "heapSize" in your
.project file (or pass --heap-size <bytes> to tms9900-packer).
Because 32K RAM is shared with .data, .bss, overflow persistent code, and the stack, prefer static allocation when dynamic allocation isn't needed:
Static pre-allocated object pools (e.g., fixed array of sprite/entity structs).
Fixed-size ring buffers for I/O queues and audio commands.
Global scratch buffers placed in designated high RAM.
Scratchpad RAM layout & CPU workspace registers
The TMS9900 has a unique architectural property: its 16 general-purpose registers (R0–R15) do not live
inside the CPU silicon—they are physically mapped to memory in Scratchpad RAM (0x8300–0x831F).
In unexpanded console configurations (or when using Scratchpad for user stack space), stack overflow is catastrophic:
a downward-growing stack will silently overwrite the current register workspace, destroying return addresses (R11),
frame pointers (R9), and console ISR hooks (0x83C4). Always keep call depths shallow and local variables small.
2. CPU Architecture & C Integer Semantics
Strict word alignment & silent LSB masking
The TMS9900 requires 16-bit word operations (uint16_t, int, pointers) to be aligned to
even memory addresses.
The Silent Read Trap
On modern processors (x86, ARM), an unaligned word read either succeeds via hardware unaligned support or raises a hardware fault.
On the TMS9900, the CPU hardware silently ignores bit 0 of the address for word operations!
If you attempt to read a 16-bit word from odd address 0xA005, the CPU will execute the read from 0xA004 without error.
Ensure packed binary structs and asset parsers respect 2-byte alignment.
16-bit int and size_t
Under GCC for TMS9900, sizeof(int) == 2, sizeof(short) == 2, and sizeof(size_t) == 2.
Only long and long long are 32-bit (4 bytes) and 64-bit (8 bytes).
Shift overflows:1 << 16 evaluates to 0! To shift into a 32-bit quantity, explicitly cast the literal: 1UL << 16.
Arithmetic truncation:int area = width * height; will overflow if the product exceeds 32,767. Use long for products of large numbers.
Pointer subtraction: Difference between pointers yields a 16-bit signed ptrdiff_t.
High-byte register convention for byte operations
The TMS9900 is strictly Big-Endian. Crucially, the hardware instruction MOVB operates on the
most significant (high) byte (bits 0–7) of a workspace register, whereas standard C integer expressions
evaluate in the low byte (bits 8–15).
The compiler automatically emits SWPB (Swap Bytes) instructions when loading and storing bytes to maintain
standard C semantics. However, if you write inline assembly or use union casting tricks (such as reading ((char*)&my_int)[0]),
remember that index 0 corresponds to the high byte.
Heavy cost of 32-bit math & software floating-point
The TMS9900 provides hardware 16-bit integer multiplication (MPY) and division (DIV). However:
32-bit integer arithmetic (long multiplication, division, modulo) is synthesized through multi-instruction software library calls.
All floating-point types (float, double) are soft-float routines.
Avoid floating-point calculations in performance-critical code such as physics engines, sprite movement, or raster loops.
Instead, use fixed-point arithmetic (typically Q8.8 with 16-bit integers, or Q16.16 with 32-bit integers).
Float format is IEEE 754, NOT TI RADIX-100
TI-99/4A veterans and developers interfacing with legacy console ROM routines, TI BASIC, or Extended BASIC will naturally expect
the platform's historical RADIX-100 floating-point format (an 8-byte, base-100 excess-64 representation).
RADIX-100 vs. IEEE 754 (binary32)
Tidepod's C compiler uses standard IEEE 754 single-precision (binary32) for float (4 bytes)
and IEEE 754 double-precision (binary64) for double (8 bytes).
Crucial Gotcha: You cannot directly cast or memcpy floating-point values between TI BASIC variables,
disk catalog sectors, and C float variables! When reading raw disk catalog records (which encode file sizes and record lengths
as 8-byte RADIX-100 floats) or calling console GPL subroutines, numbers must be converted explicitly (as performed internally by
ti_opendir).
Note: A dedicated suite of bidirectional conversion helpers (radix100_to_float() and float_to_radix100())
is planned for a future release of Tidepod's libc.
If you need to unpack an 8-byte RADIX-100 buffer (e.g., from raw disk catalog sectors or file metadata) into a C float or double,
you can use the following decoder:
// Converts an 8-byte TI RADIX-100 buffer to standard IEEE double/float
double radix100_to_double(const unsigned char *r) {
if (r[0] == 0 && r[1] == 0) return 0.0;
unsigned char b0 = r[0], b1 = r[1];
double sign = 1.0;
// Negative numbers have the first 16-bit word two's-complemented
if (b0 & 0x80) {
unsigned int w = ((unsigned int)(~b0) << 8) | (unsigned int)(~b1);
w = (w + 1u) & 0xFFFFu;
b0 = (unsigned char)(w >> 8);
b1 = (unsigned char)w;
sign = -1.0;
}
int exp = (int)b0 - 0x40; // Excess-64 exponent (powers of 100)
double val = 0.0;
double scale = 1.0;
if (exp >= 0) {
for (int i = 0; i < exp; i++) scale *= 100.0;
} else {
for (int i = 0; i < -exp; i++) scale /= 100.0;
}
// Each mantissa byte is a base-100 digit (0..99)
for (int i = 0; i < 7; i++) {
unsigned char digit = (i == 0) ? b1 : r[i + 1];
if (digit > 99) digit = 99;
val += (double)digit * scale;
scale /= 100.0;
}
return sign * val;
}
3. Writing Efficient Code & Function Design
Loop induction variable sizing: prefer unsigned int over char
Many developers instinctively use uint8_t or unsigned char for small loop counters thinking it saves memory:
// SLOWER & LARGER: Compiler inserts byte masking / SWPB to simulate 8-bit overflow
for (unsigned char i = 0; i < 100; i++) { ... }
// FASTER & SMALLER: Matches native 16-bit register width directly (INC / CI / JLT)
for (unsigned int i = 0; i < 100; i++) { ... }
Because CPU registers are 16 bits wide, arithmetic on 8-bit types forces GCC to emit truncation instructions
after every increment to simulate 8-bit wrap-around. Use native unsigned int or int for loop counters and math temporaries.
Avoid recursion
Each function call on TMS9900 pushes the return address (R11), the caller's frame pointer (R9),
and any preserved callee-saved registers (R4–R8) to the stack. Recursive tree searches or recursive pathfinding
algorithms will quickly exhaust the stack and trigger silent memory corruption. Always write iterative algorithms with explicit small state buffers.
Function pointers across banks
The auto-banker (tms9900-packer) generates cross-bank trampolines for direct function calls
using the linker's --wrap feature.
Function Pointers are Not Wrapped
Calling a function through a function pointer ((*fn_ptr)(arg)) is an indirect branch (B *R1)
that bypasses the trampoline and executes in whatever cartridge bank happens to be active.
Functions called via function pointers (such as state machine dispatch tables or event handlers) must either reside
in the same source file as the caller, or be placed into persistent RAM.
Memory-mapped I/O and the volatile keyword
When interacting directly with memory-mapped hardware ports (such as sound registers at 0x8400 or custom expansion devices),
you must access them through volatile pointers:
#define SOUND_PORT (*(volatile unsigned char *)0x8400)
// Without volatile, the compiler optimizer would eliminate the first two writes!
SOUND_PORT = 0x9F; // Silence voice 1
SOUND_PORT = 0xBF; // Silence voice 2
SOUND_PORT = 0xDF; // Silence voice 3
Without volatile, GCC's Dead Code Elimination (DCE) pass will fold sequential stores to the same memory
location into a single write, breaking multi-byte hardware protocols.
4. Translation Units & Packer Strategies
Keep your Translation Units (TUs) small
In Tidepod's banking architecture, the translation unit (a single .c or .asm file)
is an atomic, indivisible block. tms9900-packer places entire object files into 8 KB banks; it
cannot split individual functions of one file across multiple banks.
Modularity Prevents Bank Overflow
If you write a monolithic 7 KB game.c, the packer has almost zero flexibility: that file can only fit
into an almost empty bank, causing severe internal fragmentation in other banks and often triggering
Bank overflow could not be resolved.
Best Practice: Break your codebase into small, focused files (e.g., player.c, enemies.c,
physics.c, title_screen.c, sound_driver.c). Smaller chunks (1–3 KB each) give the
bin-packing algorithm maximum puzzle flexibility to pack 8 KB banks tightly with minimal wasted ROM.
Understanding packer strategies (packing_algo)
The packer implements three distinct bin-packing algorithms to partition your compiled translation units across 8 KB banks.
You can configure the strategy in your project settings ("packing_algo" in .project) or pass
it via command-line options:
ID
Option
Strategy
How It Works & Trade-offs
0 (Default)
bfd
Best-Fit Decreasing
Sorts all translation units by compiled size in descending order, then fits each unit into the bank with the least remaining space that can still hold it.
Objective: Maximum density. Produces the smallest total number of ROM banks and minimal wasted cartridge space.
1
ffd
First-Fit Decreasing
Sorts units by size and inserts each into the first bank with sufficient headroom.
Objective: Deterministic layout stability. Reduces cascade shifts across banks during incremental compilation when one file changes slightly.
2
cluster
Call-Graph Clustering
Parses the static call graph generated by the compiler and clusters tightly coupled translation units that call each other into the same bank.
Objective: Maximum execution speed. Drastically slashes cross-bank trampolines and trampoline latency, at the cost of potentially needing 1 extra ROM bank.
To evaluate the impact of different strategies on your build, compare summary.total_trampolines and bank headroom in
bank_report.json. For games with tight 60 FPS inner loops calling helper functions across modules,
switching to cluster can reclaim valuable CPU cycles.
Tidepod generates a plain GNU Makefile from the .project file.
The IDE's Build command runs exactly this Makefile, so make in a terminal gives the same result.
This page follows a banked cartridge build step by step; the other cartridge types use the same steps with a
different start-up object and linker template.
Targets
Command
Result
make
Release build: <name>.bin and <name>.rpk.
make debug
Debug build: the same plus <name>.debug (an ELF file with DWARF debug info), which is also packed into the .rpk for the debugger.
make clean
Removes objects, packer output and build results.
Switching between make and make debug deletes the project's objects first (the mode is
remembered in .build_mode), so you never link a mix of release and debug objects.
Each .dat resource is wrapped into an object file, and a packer pre-pass computes where every resource will live. The result is include/resource_defs.h, which your C code includes to find resources. Because every C object depends on this header, it is written before anything is compiled, and one make is always enough. See Binary resources.
[CC] / [AS]
Each C file is compiled with tms9900-elf-gcc, each .asm file assembled with tms9900-elf-as. Every source file (translation unit) becomes one object.
[BK]
tms9900-packer reads all objects plus libc.a, measures each translation unit, builds the call graph and distributes the units over 8 KB banks. It writes the linker script and the cross-bank call stubs. See Banking and the packer.
[AS] trampolines
The generated autobank_trampolines.s is assembled.
[LD]
tms9900-elf-ld links everything with the generated autobank.ld. The link map is written to link.map.
[PAD]
The ROM image is padded to the next power of two (8, 16, 32 KB, …) so cartridge boards and emulators accept it.
[ZP]
The .rpk is a zip of layout.xml, the .bin, the .debug file (debug builds) and any disk images in the project directory.
The optimisation level comes from optLevelRelease / optLevelDebug, include paths and
customCompilerFlags are appended. Note -Werror: every warning stops the build. Files placed in
persistent RAM or scratchpad additionally get -mpersistent or -mscratchpad
(see Code placement).
Generated files
Do not edit these; they are rewritten by tidepod sync or by every build.
File
Written by
Contents
Makefile
sync
The build. Starts with # [GENERATED BY TI-99 IDE - DO NOT EDIT MANUALLY].
layout.xml
sync
Cartridge board description for the .rpk.
.cart_header.asm
sync
Cartridge header with the menu name.
include/resource_defs.h
build
Bank, offset and length of every resource.
autobank.ld
build
Linker script with the bank assignment.
autobank_trampolines.s, autobank_wrap.txt
build
Cross-bank call stubs and the matching --wrap linker options.
Your own build steps go in Makefile.custom, which is included by the Makefile and never overwritten.
See Makefile.custom.
Things to know
Header changes are not tracked
The %.o: %.c rule has no dependencies on your own headers (only on include/resource_defs.h).
After changing a header, rebuild everything with make clean && make, or list the dependencies in
Makefile.custom.
EA5 projects
EA5 projects link a single ELF and run tms9900-packer --ea5, which slices it into Editor/Assembler
option 5 program files (NAME1, NAME2, …) and writes them to <name>.dsk.
There is no bank packing.
A cartridge sees ROM through one 8 KB window at 0x6000–0x7FFF. Larger cartridges are split into
8 KB banks; writing to an address in the window selects which bank is visible. Tidepod hides this from
you: you write normal C, and tms9900-packer decides which bank every source file goes into and
generates the glue for calls between banks.
The unit of packing is the source file
The packer places whole translation units (one .c or .asm file = one object).
All functions of one file end up in the same bank. Consequences:
No single source file may be larger than one bank (8 KB of code and read-only data). Split big files.
Calls between functions in the same file are always direct and cost nothing extra.
Keep functions that call each other a lot in the same file, or put the hot one in persistent RAM.
Memory layout of a banked cartridge
Region
Address
What the toolchain puts there
Cartridge ROM window
0x6000–0x7FFF
The current bank: header and start-up code (bank 0 only), your code (“auto” units), resources.
Low expansion RAM
0x2000–0x3FFF
“Persistent” code: C runtime, bank-switch stubs, files you mark persistent.
High expansion RAM
0xA000–0xFFFF
.data, .bss, persistent overflow, and the stack (top of RAM, growing down).
Scratchpad RAM
0x8300–0x83FF
Registers/workspace, and code you mark scratchpad (from 0x8342 by default).
Start-up
When the console starts a banked cartridge:
_start (bank 0) disables interrupts, checks that the 32K memory expansion is present (if not, it prints 32K MEM REQUIRED! and stops) and copies a small copier routine into scratchpad.
The copier copies the persistent section to 0x2000. It can read from any bank, so this section can sit at the end of the ROM.
_persistent_init (now running from RAM) copies the scratchpad section over the copier, copies high persistent code and .data to high RAM, clears .bss, maps bank 0 and calls main().
main() starts with interrupts disabled, and the runtime never enables them. If your program
needs the console interrupt routine, enable interrupts yourself. If main() returns, the runtime loops forever.
Cross-bank calls (trampolines)
When a function in bank 2 calls a function in bank 5, the call is redirected (with the linker's
--wrap) to a small stub in persistent RAM. The stub saves the current bank, switches to bank 5, calls the
function, switches back and returns. You do not write anything for this, but it costs a few dozen cycles per call.
The number of stubs is reported as summary.total_trampolines in
bank_report.json.
Function pointers are not wrapped
Only direct calls get a trampoline. If you take the address of a function and call it through a pointer from
another bank, the call jumps into whatever bank is currently mapped. Put functions that are called through
pointers (callbacks, state-machine tables) in persistent RAM, or call them only from their own file.
Automatic persistent promotion (Phase 2.5)
Before packing translation units into cartridge ROM banks, the packer analyzes the static call graph and calculates a
hotness score for each unit (the number of static call sites referencing it).
If free capacity remains in low persistent RAM (0x2000–0x3EFF), the packer automatically promotes the hottest
units into persistent memory. If low persistent RAM fills up, remaining hot units overflow into high expansion RAM
(persistent_high).
Promoted code runs from RAM and needs no trampolines when called from any bank.
Common C library routines (such as console_vdp.o, printf_core.o, and arithmetic helpers) and frequently invoked project units are often auto-promoted in small cartridges.
You can observe promotion decisions in verbose packer output (make PACKER_EXTRA_FLAGS=-v) and in the classification field of bank_report.json.
Explicit vs. Automatic
Automatic promotion is opportunistic: as your project grows, units previously promoted to RAM may be placed back into banked ROM.
If a routine must reside in RAM (such as functions called via pointers or interrupt handlers), always mark it explicitly
with #pragma bank persistent or tidepod add --persistent. See Code placement.
Strings and constants across banks
A pointer to read-only data in bank 2 is useless once bank 5 is mapped. For every file that calls into another bank,
the packer therefore moves string literals and small constants (.rodata.str*, .rodata.cst*
and plain .rodata up to 128 bytes) into always-mapped RAM. So
printf("score %d", s) from banked code just works. Large const tables stay in their bank:
don't pass pointers to them into functions in other files — copy the data first, or put the table in a persistent file.
Switching banks yourself
Normally you never do this. Banked projects get include/bankswitch.h, which defines
switchtobank(n) (a write to 0x6000 + (n << 1)) and declares
currentbank, the variable the trampolines keep up to date. The resource copy functions use it to restore
the bank after reading from another one. If you switch manually, only do it from persistent or scratchpad code and
switch back before returning.
Packing Heuristics and Trade-offs
Distributing dozens of translation units across fixed 8 KB ROM boundaries is an NP-hard bin-packing problem.
tms9900-packer implements three distinct heuristic algorithms to solve this partitioning. You can select
the active strategy via packing_algo in your project settings or pass it directly on the command line:
Algorithm ID
Packer Option
Strategy & Optimization Objective
0 (Default)
bfd
Best-Fit Decreasing: Sorts all translation units by compiled byte size in descending order, then places each unit into the tightest-fitting bank that can accommodate it. Minimizes internal fragmentation and produces the absolute smallest number of ROM banks.
1
ffd
First-Fit Decreasing: Sorts units by size and inserts each into the first bank with sufficient headroom. Simpler deterministic placement that can reduce cascade shifts during incremental builds.
2
cluster
Call-Graph Clustering: Analyzes call graph edges and groups tightly coupled functions into the same bank. May require additional ROM banks, but significantly reduces cross-bank trampolines and execution latency.
For most projects, bfd is the recommended choice because it packs cartridge ROM images into the fewest
physical EEPROM chips. However, if your application features high-frequency calls between multiple game modules,
switching to cluster will trade a small amount of ROM space for substantial reductions in trampoline overhead.
After changing algorithms, check summary.total_trampolines in bank_report.json
to evaluate the improvement.
Packer Command-Line Options
Tidepod's generated Makefile automatically supplies the appropriate flags to tms9900-packer based on your
project manifest. For advanced customization—such as integrating custom bootloaders, adjusting stack allocation, or
building multi-cartridge collections—you can inject additional flags via PACKER_EXTRA_FLAGS in
Makefile.custom:
Command-Line Option
Argument
Description & Operational Details
--bank-size
N (bytes)
Overrides the default 8,192-byte bank capacity. Useful when targeting experimental hardware or non-standard paging schemes.
--bank-base
N (index)
Sets the physical cartridge bank offset corresponding to logical bank 0. Used when merging your binary into a multi-bank compilation image behind other ROM cartridges.
--heap-size
N (bytes)
Reserves expansion RAM for dynamic allocation pools when custom runtime allocators are integrated.
--stack-size
N (bytes)
Overrides the static stack depth calculated from the call graph. Essential when code uses function pointers or recursion that static analysis cannot trace.
--no-32k
Flag
Compiles and packs targeting an unexpanded console (8K ROM Cartridge type). Allocates all variables, buffers, and workspaces within internal scratchpad RAM.
--flat-rom
Flag
Disables bank switching entirely, generating a single unbanked 8 KB cartridge image.
--persistent-lib
path/to/lib.a
Forces an entire static archive to reside in persistent expansion RAM (equivalent to libFiles[].forcePersistent).
--scratchpad-base
0x83xx
Specifies the starting VMA address for code compiled with -mscratchpad (default is 0x8342).
--scratchpad-size
N (bytes)
Defines the maximum byte capacity allocated for scratchpad code routines.
--packing-algo
bfd|ffd|cluster
Selects the bin-packing heuristic for translation unit placement.
--ea5
ELF BASE
Editor/Assembler #5 conversion mode: slices a linked ELF binary into disk-loadable program image files and generates a bootable DSK image.
-v
Flag
Enables verbose diagnostic logging, printing step-by-step unit placement, hotness calculations, and relocation tracking to stdout.
Memory architecture on the TI-99/4A is strictly segmented across distinct physical buses with radically different
performance characteristics. By default, Tidepod treats every C and assembly source file as banked code:
the object is placed in one of the cartridge's 8 KB ROM banks and swapped into view at 0x6000–0x7FFF on demand.
While this allows cartridges to scale up to 512 KB or larger, calling functions across different banks incurs trampoline
switching overhead.
To maximize application responsiveness, Tidepod provides explicit code placement controls. You can direct critical
subsystems into persistent expansion RAM (always mapped, zero trampoline penalty) or internal
scratchpad RAM (16-bit wide, zero wait states). In addition, Tidepod's automated linker pass
implements profile-guided promotion, elevating the hottest call-target modules into free persistent RAM automatically.
Memory Placement Characteristics
Placement Mode
Physical Memory Range
Ideal Use Cases
Performance & Memory Cost
Banked (Default)
Cartridge ROM Banks (0x6000–0x7FFF)
General game logic, menus, level data, initialization code, dialogue systems.
Zero RAM cost. Calls from other ROM banks require a 12-to-24 cycle trampoline stub.
Persistent
Low Expansion RAM (0x2000–0x3FFF), overflow to High RAM (0xA000+)
Interrupt handlers (VBLANK ISR), audio engines, callbacks, jump tables, functions called via pointers.
Consumes 32K Expansion RAM. Copied from cartridge ROM at cold boot. Direct calls from any bank without trampolines.
Extremely scarce (< 190 bytes). Runs on the 16-bit internal bus with 0 wait states, delivering maximum CPU throughput.
Marking a Translation Unit for Placement
Code placement in Tidepod is configured at the granularity of the translation unit (the source file). You can mark
placement either from the command-line CLI or directly inside the source code using pragmas:
Tidepod scans for #pragma bank persistent or #pragma bank scratchpad within the leading
comment and preprocessor block of the file. Any pragma appearing after the first executable statement is ignored.
Whenever you add or modify a pragma, run tidepod sync (or save project settings in the IDE). The build
system automatically appends -mpersistent or -mscratchpad to the compiler flags for that file,
directing GCC to emit functions into the appropriate ELF memory section.
Unexpanded 8K Cartridges
Persistent expansion RAM and large scratchpad allocations require the physical 32K memory expansion. For unexpanded
8K cartridges (Project Type 0), persistent placement is ignored, and all global variables and workspaces are packed
into internal scratchpad memory.
Placing Third-Party Libraries in RAM
When linking precompiled static libraries (such as sound drivers, PSG audio players, or math routines) that are invoked
frequently throughout your game loop, placing individual object files into RAM manually is impractical. You can add a
library with tidepod add lib/libsound.a --persistent, or set "forcePersistent": true on any
entry in libFiles in your <name>.project file:
The build system passes --persistent-lib lib/libsound.a to tms9900-packer, which relocates
every symbol in the archive into low expansion RAM during the link phase.
Scratchpad Layout Presets and Hardware Safety
The TI-99/4A console contains only 256 bytes of internal scratchpad RAM (0x8300–0x83FF). Because the CPU
workspace (R0–R15) resides at 0x8300 (32 bytes), scratchpad code is anchored at scratchpadBase
(defaulting to 0x8342 when omitted) and by default can allocate up to 0x8400 unless restricted
by scratchpadSize or the 0x83C0 console ISR workspace boundary. To prevent memory corruption
with console ROM subsystems, Tidepod's Scratchpad Base: dropdown in Project Settings provides four presets:
Preset Name (IDE)
Base Address
Available Code Space
Hardware Coexistence & Safety Requirements
Full scratchpad (0x8320)
0x8320
224 B to 0x8400 (160 B below 0x83C0)
Maximizes scratchpad code capacity immediately above the C workspace. Safe only if no music drivers or disk routines use scratchpad.
+libtivgm2 (0x8340)
0x8340
192 B to 0x8400 (128 B below 0x83C0)
Leaves 32 bytes (0x8320–0x833F) reserved for TI-99/4A chiptune sound players (such as libtivgm2) and envelope generators.
+disk access (0x8380)
0x8380
128 B to 0x8400 (64 B below 0x83C0)
Mandatory for disk access: Disk controller DSRs use scratchpad between 0x834A and 0x837F (plus 0x83C0+ during DSR execution). Placing code below 0x8380 causes crashes during file I/O.
Custom
User defined
Variable
Allows advanced developers to set an arbitrary base address (must be ≥ 0x8320) and optional scratchpadSize.
The Upper Scratchpad Danger Zone (0x83C0–0x83FF)
Addresses 0x83C0–0x83FF are reserved by the TI-99/4A console ROM for the interrupt service routine,
GROM address counters, and sound generator shadow registers. If console interrupts are enabled, the console ISR writes
to this memory 60 times a second. Never place scratchpad code above 0x83BF unless your cartridge permanently
disables console interrupts (limi 0) and never returns control to the master console menu.
Validating Placement in the Build Report
After relocating code or modifying pragmas, always review bank_report.json.
Inspect regions.persistent_lower.free and regions.persistent_high.free to ensure adequate
headroom remains for initialized globals (.data) and uninitialized buffers (.bss). Overfilling
high RAM will cause the descending stack to collide with global memory.
Graphics, fonts, level data, music: anything that is just bytes can be added to a cartridge as a
resource. Resources are stored in ROM banks after your code and copied to VRAM or RAM when you need them.
They cost no RAM until you load them.
1. Add the file
Give the file a .dat extension and a base name that is a valid C identifier, then add it:
Terminal
tidepod add resources/tiles.dat
make
The Makefile turns the file into an object (ld -r -b binary, renamed to a .resource section),
and the packer assigns it a place in ROM before any C file is compiled, so a single make is enough.
2. The generated header
The packer writes three constants per resource, named after the file, into include/resource_defs.h:
Treat bank and offset as opaque values for the copy functions. _length is the file size in bytes.
3. Copy it where you need it
resource_copy.h (in the toolchain include directory) provides:
resource_copy.h
#define unwrap(x) x##_bank, x##_offset, x##_length
void rom_to_vram(unsigned int srcbank, unsigned int srcoffset,
unsigned int length, unsigned int dst);
void rom_to_ram(unsigned int srcbank, unsigned int srcoffset,
unsigned int length, unsigned char *dst);
typedef void (*resource_copy_hook_t)(unsigned int bytes_copied, unsigned int total_bytes);
void rom_to_vram_ex(unsigned int srcbank, unsigned int srcoffset, unsigned int length,
unsigned int dst, unsigned int chunk_size, resource_copy_hook_t hook);
void rom_to_ram_ex(unsigned int srcbank, unsigned int srcoffset, unsigned int length,
unsigned char *dst, unsigned int chunk_size, resource_copy_hook_t hook);
unwrap(name) expands to the three constants, so the first three arguments are always written as unwrap(name).
rom_to_vram copies to a VRAM address; rom_to_ram to a CPU RAM buffer.
The _ex variants copy in chunks of chunk_size bytes and call hook with progress, e.g. to draw a loading bar or keep music playing during a long copy.
The functions switch banks to read the data and restore currentbank afterwards, so they can be called from any bank.
Tidepod does not convert images or audio. Produce raw bytes in the format your code expects (pattern tables,
colour tables, sound lists, …) with your own tools, and add the result. A Makefile.custom rule can
regenerate a .dat from its source automatically; see Makefile.custom and
Tutorial 3, which does exactly that with a Python script.
You don't need a font resource for text
libc has a built-in 5×8 font: call ti_text_load_builtin_font() after
ti_text_mode() and it is copied to the pattern table at 0x1000.
It is only linked if you call it, and it covers all 256 codes, including the CP437 box-drawing characters used by
chline() and cvline(). Use a font resource only if you want a different look.
Never edit RESOURCE_OBJS
The resource list in the Makefile comes from the project. Use tidepod add / tidepod remove;
hand edits are lost on the next sync.
The F18A (and the Pico9918) video replacements contain their own TMS9900-compatible processor, the GPU, which runs
from VRAM in parallel with the console CPU. Tidepod can compile a C file for the GPU, pack the resulting program as
a resource, and give the host code the addresses it needs to load and start it.
The canonical, complete example is resources/examples/f18a_bump in the Tidepod install. The snippets on
this page come from it.
The prefix is the file's base name: src/fx.c gives include/fx_map.h, fx_base, fx_entry, and the resource fx.
3. The GPU Execution Environment
The F18A GPU is a custom, hardware-implemented 16-bit processor integrated directly onto the FPGA alongside the VDP core.
Because it shares internal routing with video RAM, it can read and modify tiles, pattern bitmaps, and sprite attribute
tables with zero wait states at 100 MHz.
GPU translation units run in an unhosted, freestanding environment. They do not link against the standard C library
(no malloc, printf, or standard file I/O). Instead, <f18a_gpu.h> provides direct
hardware definitions, status register accessors, and memory-mapped I/O macros:
src/gpu.c (excerpt)
#include <f18a_gpu.h>
#include "layout.h" /* VRAM addresses shared with the host */
void main(void) __attribute__((noreturn));
void main(void)
{
for (;;) {
F18A_GPU_IDLE(); /* Sleep until the host-configured trigger (e.g. VSYNC) */
int lx = (signed char)F18A_GPU_MMIO8(LIGHT_LX); /* Read a parameter written by host */
...
/* Write pixel data directly to VRAM via 16-bit pointers at 100 MHz */
}
}
GPU Runtime Header Reference (f18a_gpu.h)
Symbol / Macro
Value / Signature
Operational Mechanics & Usage Notes
F18A_GPU_IDLE()
Macro (idle instruction)
Puts the GPU into a low-power hardware sleep state until an event trigger configured in VR50 (such as VSYNC) fires. Paces the GPU frame loop without burning memory cycles or polling.
F18A_GPU_MMIO8(addr)
*(volatile uint8_t *)(addr)
Performs a volatile byte read or write to any VRAM location or GPU status register.
F18A_GPU_MMIO16(addr)
*(volatile uint16_t *)(addr)
Performs a single-cycle 16-bit word transfer to even VRAM addresses.
F18A_GPU_VRAM_BASE
0x0000
The base address of the 16 KB VRAM space as mapped within the GPU's flat memory view.
F18A_GPU_GRAM_BASE
0x4000
The base address of the 2 KB dedicated GPU private static RAM on original F18A hardware.
F18A_GPU_WS_BASE
0x4800
The fixed hardware workspace register base (R0–R15).
F18A_GPU_SCANLINE
0x7000
Memory-mapped read-only register reporting the currently rendering raster beam scanline (0–261).
F18A_GPU_BLANKING
0x7001
Read-only status bit indicating active display blanking. Using F18A_GPU_IDLE() is strongly preferred over busy-wait polling.
F18A_ECM3_P0/P1/P2
Plane offsets
Precomputed byte offsets for Enhanced Color Mode 3 (ECM3) bitplane patterns.
Hardware GPU Constraints
The F18A GPU workspace is permanently hard-wired to address 0x4800. Never execute LWPI
(Load Workspace Pointer Immediate) in GPU C or inline assembly; changing the workspace pointer will crash the core.
Additionally, register R15 is the F18A GPU's hardware subroutine stack pointer used by CALL,
RET, PUSH, and POP (initialized to _gpu_stack in crt0_gpu.asm
and reserved from register allocation by -ffixed-r15).
4. Host Control Interface
The host TMS9900 CPU controls the GPU lifecycle through enhanced VDP registers. The host is responsible for unlocking
the register set, configuring hardware triggers, copying the GPU binary image into VRAM, and starting execution:
src/main.c (excerpt)
#include "vdp.h"
#include "f18a_gpu_host.h"
#include "resource_copy.h"
#include "resource_defs.h"
#include "gpu_map.h"
void f18a_unlock(void)
{
/* Unlock enhanced register file by writing 0x1C twice to VR57 */
VDP_SET_REGISTER(57, 0x1C);
VDP_SET_REGISTER(57, 0x1C);
}
int main(void)
{
f18a_unlock();
/* Load the compiled GPU executable image into VRAM at gpu_base */
rom_to_vram(unwrap(gpu), gpu_base);
/* Configure VR50 to trigger GPU wakeup on vertical sync (0x20) */
VDP_SET_REGISTER(50, 0x20);
/* Set GPU program counter to entry point and start execution */
f18a_gpu_start(gpu_entry);
for (;;) {
/* Host continues running standard game logic */
}
}
Host Control API Reference (f18a_gpu_host.h)
Function
Parameters
Action & Register Manipulation
f18a_gpu_start
unsigned int entry_pc
Writes the target execution address into GPU Program Counter registers VR54 (high byte) and VR55 (low byte), then asserts the run bit in VR56.
f18a_gpu_stop
void
Clears the run bit in VR56, immediately halting coprocessor execution.
f18a_gpu_load_at
unsigned int vram_addr, const unsigned char *src, unsigned int len
Streams a preloaded binary image from host CPU RAM into the specified VRAM destination address.
f18a_gpu_load_and_start
unsigned int vram_addr, const unsigned char *src, unsigned int len, unsigned int entry_pc
Transfers the image into VRAM and initiates execution in a single combined call.
When your GPU binary is bundled as a cartridge resource using tidepod add --gpu, you will typically copy it
directly from cartridge ROM to VRAM using rom_to_vram(unwrap(gpu), gpu_base) followed by
f18a_gpu_start(gpu_entry). The load variants are intended for dynamic overlays or code loaded
from floppy disk.
Host Initialization Checklist
Always perform runtime chip detection using ti_vdp_detect() before
attempting to unlock or write to registers beyond VR7. On an original TMS9918A, writing to register addresses above 7
corrupts standard display registers and locks up video output. After unlocking, remember to set VR30 to 32 to activate
32-sprite-per-scanline mode.
Running it
Run with an F18A-capable VDP: ti994a-emu --cart game.rpk --f18a, or select
tidepod-f18a / pico-f18a as VDP in Preferences or in the project's emu settings.
The generated Makefile is rewritten whenever the project changes, so you never edit it.
Everything you want to add goes into Makefile.custom in the project directory. Tidepod creates it once
(with a comment header) and never touches it again.
How it is included
The Makefile includes Makefile.customafter it has defined its variables
(OBJECT_LIST, RESOURCE_OBJS, CCFLAGS, …) and .DEFAULT_GOAL := all,
but before the all and debug recipes. So you can:
read and change variables — the recipes use your values;
add your own rules and targets without changing what plain make builds;
add prerequisites to existing objects.
Available variables include $(NAME), $(CC), $(AS), $(LD),
$(OBJCOPY), $(CCFLAGS), $(CCFLAGS_DBG), $(OBJECT_LIST),
$(RESOURCE_OBJS), $(STARTUP_OBJS), $(GCC_TOOLS) (toolchain bin),
$(TOOLCHAIN_INC) and $(TOOLCHAIN_LIB).
Hooks
Variable
Effect
POST_BUILD
A shell command run at the very end of all and debug, after the .rpk is zipped. Use it for post-processing instead of overriding the targets.
PACKER_EXTRA_FLAGS
Extra packer options, e.g. --stack-size 1280 or --bank-base 2.
MAKEFILE_CUSTOM_POST := 1
Includes Makefile.custom a second time at the end of the Makefile, after the stock recipes, for the rare case where you need to see or wrap them.
Recipes
Track header dependencies. The generated %.o: %.c rule doesn't know about headers. List them yourself so objects rebuild when a header changes:
The Makefile's own %.o: %.dat rule then picks up the new .dat.
Copy the result somewhere after each build.
Makefile.custom
POST_BUILD = cp $(NAME).rpk ~/Dropbox/ti99/
Raise the stack estimate. The packer computes the stack size from the call graph; recursion and calls through pointers are invisible to it.
Makefile.custom
PACKER_EXTRA_FLAGS := --stack-size 1024
A large real-world example
resources/examples/fileman/Makefile.custom adds header dependencies, reorders resources, uses its own
start-up objects, checks GPU image sizes and merges the cartridge with another ROM in POST_BUILD.
Don't re-implement the build
Avoid redefining all or debug (make will warn about overriding recipes, and the IDE relies
on them). Add sources with tidepod add rather than appending to OBJECT_LIST, so the packer,
the IDE and the debugger all know about them.
Every successful compilation in Tidepod produces bank_report.json in the project root. Generated by
tms9900-packer during the final packaging phase, this file contains a complete structural blueprint of
your cartridge image. It records the exact byte allocation across every 8 KB ROM bank, tracks memory utilization in
both low and high expansion RAM, calculates static stack depth projections, and enumerates every cross-bank trampoline
generated by the linker.
Because retro development on the TI-99/4A operates under tight hardware boundaries—an 8 KB cartridge paging window
and a 32 KB RAM expansion—careful inspection of this report is the most effective way to catch memory leaks, stack
overflows, and cross-bank performance regressions before testing on hardware.
Top-Level Report Structure
The root object of bank_report.json organizes your cartridge's memory and call graph into dedicated
subsections. Each key isolates a specific layer of the binary layout:
JSON Key
Type
Description & Engineering Significance
summary
Object
High-level binary metrics, including total_banks allocated in ROM and total_trampolines synthesized for cross-bank calls.
ram_overhead
Object
Comprehensive expansion RAM metrics: data_bytes (initialized globals), bss_bytes (zero-initialized globals), stack_vma (top of stack, typically 0xFFFE), and max_stack_depth (worst-case call chain in bytes).
regions
Object
Memory region descriptors for persistent_lower (8 KB at 0x2000–0x3FFF) and persistent_high (24 KB at 0xA000–0xFFFF), reporting total capacity, used bytes, and remaining free bytes.
ram_items
Array
Fixed RAM summary regions: .data (system_data), .bss (system_bss), WP_Reserved (wp_reserved at 0x8300), and Stack (stack). Individual RAM-resident object files (persistent, persistent_high, scratchpad) appear inside banks[b].items under the ROM bank holding their load image (lma), with vma set to their RAM execution address.
banks
Array
The physical ROM bank layout: an array of bank objects specifying bank_id (0 to N), capacity (8,192 bytes), used bytes, and an items array detailing the translation units packed into that bank.
call_edges
Array
The static call graph extracted from .tms9900.callgraph ELF sections and relocation tables: lists caller, callee, caller_tu, callee_tu, caller_bank, callee_bank, call weight, and is_trampoline (true whenever a global --wrap trampoline exists for callee).
trampolines
Array
The synthesized linker wrappers: reports each symbol redirected through a persistent RAM stub and its target_bank.
Object Classifications
The packer categorizes every translation unit and data object into a distinct classification. These classifications
govern where the code resides at runtime, how it is bootstrapped at power-on, and how calls into it are resolved:
Classification
Target Memory
Bootstrapping & Runtime Behavior
pinned
ROM Bank 0 (0x6000)
Anchored permanently at the base of the cartridge ROM. Contains the standard TI-99/4A cartridge header, the power-on reset vector, memory expansion detection routines, and initial boot code.
boot_copier
Scratchpad RAM (0x8342)
A small, self-contained machine routine copied into scratchpad during cold boot. It copies the persistent runtime and initialized data from ROM into expansion RAM, then executes _persistent_init.
auto
Cartridge ROM Banks (1 to N)
Standard banked C and assembly modules. The packer assigns these objects automatically using the selected packing heuristic (such as Best-Fit Decreasing) to optimize ROM capacity and minimize cross-bank calls.
persistent
Low RAM (0x2000–0x3FFF)
High-speed resident code copied from ROM at start-up. Includes routines explicitly tagged with #pragma bank persistent, as well as modules automatically promoted by the packer during Phase 2.5 hotness scoring.
persistent_high
High RAM (0xA000–0xFFFF)
Overflow persistent code placed in high expansion RAM when low RAM is exhausted. Shares space with .data, .bss, and the descending C stack.
scratchpad
Scratchpad (0x8342–0x83FF)
Ultra-hot computational routines running directly from 16-bit internal scratchpad memory with zero wait states.
resource
Cartridge ROM Banks
Binary data files (graphics tiles, sound streams, maps) packaged via tidepod add --resource and accessed at runtime via rom_to_vram or rom_to_ram.
system_data, system_bss
High RAM (0xA000+)
The C runtime global data segments in ram_items: initialized global/static variables copied from ROM (.data) and zero-cleared runtime buffers (.bss).
wp_reserved, stack
Scratchpad (0x8300) / High RAM (0xFFFE down)
Fixed system reservations in ram_items: the reserved CPU workspace registers (WP_Reserved) and the C execution stack region (Stack).
Visual Bank Report in the IDE
In the Tidepod IDE, double-clicking bank_report.json in the Files sidebar opens an interactive
graphical bank report viewer. It displays color-coded capacity bars for each ROM bank and RAM region, lists every
unit with its size and hotness, and visualizes cross-bank trampolines.
The visual bank report viewer in the Tidepod IDE.
Critical Metrics: Avoiding Memory Collision and Performance Traps
When evaluating build health, four primary metrics must be monitored to ensure system stability:
High RAM Clearance (regions.persistent_high.free): In the TI-99/4A architecture, High Expansion RAM (24 KB, 0xA000–0xFFFF) is a shared arena. Static globals (.data and .bss) grow upwards from 0xA000, while the C execution stack grows downwards from 0xFFFE. If persistent_high.free drops below 1,024 bytes, deep function nesting or interrupt service routines can cause the stack pointer to collide with global variables, creating silent memory corruption.
Static Stack Projection (ram_overhead.max_stack_depth): The packer analyzes the static call graph to calculate the maximum cumulative stack frame depth from main() down to the deepest leaf function. While recursive functions and function pointers cannot be modeled statically, this number provides a baseline. Ensure that free RAM in high memory comfortably exceeds max_stack_depth.
Trampoline Inflation (summary.total_trampolines): A sudden increase in total trampolines indicates that functions frequently calling each other have been split across different ROM banks. Each trampoline incurs a 12-to-24 cycle penalty to switch banks and restore state. If a time-critical game loop begins dropping frames, inspect call_edges to identify which cross-bank calls can be eliminated.
Unit Migration: Because the packer runs a bin-packing heuristic on whole translation units, modifying one source file can cause other files to shift into different ROM banks. If your code calls a function through a raw function pointer across banks, such a shift will break execution (see Banking).
Automating CI Verification with jq
You can integrate automated layout assertions into your build scripts using jq. These queries verify that
critical performance and memory thresholds are maintained across Git commits:
Terminal
# 1. Print executive memory overview:
jq '{summary, ram_overhead, regions}' bank_report.json
# 2. Assert remaining High RAM headroom is greater than 2 KB:
jq -e '.regions.persistent_high.free >= 2048' bank_report.json > /dev/null \
|| echo "CRITICAL WARNING: High RAM headroom is dangerously low!"
# 3. List fill percentage across all ROM banks:
jq -r '.banks[] | "Bank \(.bank_id): \(.used)/\(.capacity) bytes (\((.used*100/.capacity)|round)%)"' bank_report.json
# 4. Enumerate all functions wrapped by cross-bank trampolines:
jq -r '.trampolines[] | "Trampoline -> \(.symbol) in Bank \(.target_bank)"' bank_report.json
# 5. Identify the top 5 largest translation units in the project:
jq -r '[.banks[].items[] | select(.classification=="auto")] | sort_by(-.size) | .[0:5][] | "\(.size) bytes\t\(.filename)"' bank_report.json
Commit Your Baseline
Commit bank_report.json to your repository alongside major releases. Running git diff bank_report.json
after refactoring reveals exactly how your changes affected bank allocation, trampoline counts, and RAM margins.
The tidepod executable is both the IDE and a command-line tool. With a command it works on a project and
exits; without one (or with a .project path) it opens the IDE.
Usage
tidepod <command> [options]
tidepod [project.project] # open the IDE
tidepod <command> --help # options of one command
Commands that work on an existing project find it through --project <file>, a *.project
argument, or the single .project file in the current directory.
Command
What it does
new
Create a project directory with boilerplate.
add
Add files to the build and regenerate the Makefile.
remove
Remove files from the build (the files stay on disk).
list
Show project info and the file list with their flags.
set-type
Change the project type and regenerate the Makefile.
sync
Regenerate the Makefile (and layout.xml, cartridge header) from the .project file.
run
Start the stand-alone emulator with the project's cartridge.
There is no build command: run make or make debug in the project directory.
tidepod new
Synopsis
tidepod new <name> [--type 8k|banked|xb|ea5|custom] [--menu <name>] [--path <dir>]
Creates <name>.project, a starter main.c (main.bas for XB), the cartridge
header, the Makefile, Makefile.custom, layout.xml, and installs the
agent skill under .agents/skills/ and .cursor/skills/.
Regenerates the Makefile, layout.xml and the cartridge header from the .project file, and
re-reads #pragma bank … / #pragma gpu … from the sources. Run it after editing the
.project file by hand or adding a placement pragma.
tidepod run
Synopsis
tidepod run [--debug] [--project <file>]
Starts ti994a-emu with <name>.rpk from the project directory and --autorun.
The emulator configuration is layered:
the machine defaults from Tidepod's preferences.json (PEB cards, VDP engine),
the project's optional "emu" overrides,
the project's disk mounts dsk1–dsk3 and hard1–hard3.
--debug also starts the GDB server on port 3333 (see Debugging).
run does not build — run make first — and it opens the stand-alone emulator,
not the IDE. For headless runs and other options, call ti994a-emu directly
(The emulator).
ti994a-emu is the emulator used by the IDE, packaged as a separate program. It ships in the toolchain's
bin directory next to the compiler. tidepod run starts it for you; call it directly for
headless runs, screenshots, snapshots and anything else on this page.
Common invocations
Terminal
ti994a-emu --cart game.rpk # boot to the title screen, pick the cart yourself
ti994a-emu --cart game.rpk --autorun # start the cartridge directly
ti994a-emu --cart game.rpk --f18a # with an F18A
ti994a-emu --cart game.rpk --dsk1 data.dsk # with a disk in DSK1
ti994a-emu --cart game.rpk --gdb # with the GDB server on :3333
Cartridge and machine state
Option
Meaning
--cart <file>
Load a cartridge: .rpk (recommended, includes the board type and debug info) or raw .bin.
Print the resolved VDP, cartridge and disk configuration and exit.
--version, -h/--help
Version / option list.
--autorun is a shortcut, not a test
--autorun jumps into the cartridge without going through the console's title screen and menu, a path real
users never take. A program can behave differently that way. To check that a build really boots, start normally and
select it with key injection; see Headless testing.
Video
--vdp engine
Emulates
tidepod-tms9918a
The stock TMS9918A (default).
tidepod-f18a
F18A (also selected by --f18a).
pico-f18a
F18A, Pico9918-based core.
pico-v9938
V9938 (Pico9918-based core).
pico-pico9918
Pico9918 PRO.
Disks and peripherals
--dsk1…--dsk4, --hard1…--hard3, --peb-card,
--peb-none, --dsr and --fast-disk are described in
Disks & peripherals.
Load a .debug file for source-level information (not needed for .rpk files built with make debug, which contain it).
--dump-regs <N>
Run N frames, then print CPU registers, interrupt state, scratchpad and VRAM tables (implies both --headless and --autorun).
-v, --verbose
Log every interrupt with its source (VDP / timer / external).
See Debugging for GDB and --dump-regs in practice.
Configuration used by tidepod run and the IDE
The emulator itself only knows its command-line options. Tidepod builds them from three layers: the machine
defaults in Preferences (stored in preferences.json), the optional "emu" block in the
project, and the project's disk mounts. The "emu" block:
Programs that read or write files need a disk controller card in the emulated Peripheral Expansion Box (PEB) and
a disk image to work on. This page covers how to set that up for the IDE, tidepod run and
ti994a-emu. For the C side (fopen and friends) see the
API reference.
Disk images in a project
Mount images in the IDE's Disk dialog or DSK tab, or put them in the project file. Paths can be
relative to the project directory:
The IDE mounts them when the project opens and tidepod run passes them to the emulator via
--dsk1…--dsk3 and --hard1…--hard3. Disk images
(*.dsk, *.hd, …) in the project directory are also archived into the .rpk
by the build for distribution, though ti994a-emu mounts disk images from the explicit
--dsk1..3 / --hard1..3 flags (which the IDE and tidepod run supply automatically).
The DSK tab in the IDE: mounted disks, catalog inspection, and the New Disk tool.
Emulator options
Option
Meaning
--dsk1 … --dsk3 <file>
Mount a sector disk image (.dsk).
--dsk4 <file>
Fourth floppy drive; needs the HFDC card.
--hard1 … --hard3 <file>
Mount a hard-disk image (HFDC).
--peb-card <type@cru>
Add a card: tifdc@1100, hfdc@1100 or whtscsi@1200. Repeatable; the first use replaces the default TI FDC.
--peb-none
Empty PEB: no disk controller at all.
--dsr <base>:<file>
Load a DSR ROM at a CRU base, e.g. 1100:disk.bin.
--fast-disk
Disable realistic disk timing.
Controller cards
Type
Default CRU
Notes
tifdc
1100
TI floppy disk controller. The default when nothing is configured.
hfdc
1100
Myarc HFDC: floppies (including DSK4) and hard disks.
whtscsi
1200
WHT SCSI card; work in progress.
Combinations are explicit: --peb-card tifdc@1100 --peb-card whtscsi@1200. Two cards on the same CRU
base are emulated as a bus clash, not refused.
Hard-disk images
Hard-disk images must be raw sector dumps (.hd, .hdf, .raw). MAME CHD files are
refused at mount time; convert them first:
Terminal
chdman extracthd -i disk.chd -o disk.hd
chdman is part of MAME's tools (Homebrew package rom-tools).
Testing without a disk controller
Set "peb": "none" in the project's "emu" block (or pass --peb-none) to check how
your program behaves on a console without disks. The dsk/hard entries stay in the project
but are not mounted.
Programs that use disk files
Use the +disk access (0x8380) scratchpad preset in Project Settings; the disk system uses lower scratchpad. See Code placement.
By default fopen goes through the disk controller's own file routines. Other back-ends are opt-in: see stdio_enable(3).
Debugging on 1970s and 1980s retro hardware typically involves painful trial-and-error, blinking screen borders, or
slow serial monitor routines. Tidepod brings modern, source-level debugging to the TI-99/4A through a tightly integrated
toolchain. By emitting standard DWARF symbol tables into an ELF container and embedding them directly within the
cartridge bundle, Tidepod allows you to set visual breakpoints, single-step through C source statements, evaluate complex
structs, inspect hardware VDP tables live, and trace variables without altering cycle timing.
Whether you prefer the all-in-one graphical debugger inside the Tidepod IDE or command-line scripting with
tms9900-elf-gdb, the underlying execution engine remains cycle-accurate and hardware-faithful.
Source-Level Debugging in the IDE
When you initiate a debug build (F5 or make debug), Tidepod invokes GCC with -O0 -g
and creates <project>.debug alongside the cartridge image. The IDE boots the internal emulator, attaches
to the CPU execution pipeline, and loads the symbol database:
Setting breakpoints: Click in the margin gutter next to any executable C statement. A red marker indicates an active hardware breakpoint.
Execution control: Launch with F5. Control execution with standard debugger shortcuts:
F10 — Step Over: Execute the current statement, stepping over function calls.
F11 — Step Into (Step Line): Follow execution into the called function body.
Shift+F10 — Step OvInst: Step over one TMS9900 machine instruction.
Shift+F11 — Step Out: Run until the current function returns.
F6 — Pause / Continue: Toggle execution state.
State inspection panels (8 debugger tabs):
CPU: Displays the Workspace Pointer (WP), Program Counter (PC), Status Register (ST), the 16 primary workspace registers (R0–R15) in hex and decimal, and RAM hex view.
ASM: Disassembles the active memory window in real time, synchronized to the current Program Counter.
BRK: Manages active source and address breakpoints.
WCH (Watch): Evaluates local variables, global symbols, and complex pointer chains. Structs expand hierarchically.
GFX: Visualizes live pattern generator tables, color tables, and sprite attribute tables.
DSK: Inspects mounted floppy/hard disk catalogs and creates formatted 90 KB disk images (New Disk).
PRF: Real-time cycle-accurate frame profiler and block breakdown charts.
Source-level debugging in the IDE: paused at a breakpoint with variable watches.
For breakpoints on banked carts, __sams watches, the CPU tab's bank and SAMS map lines, Extended BASIC
behaviour and known limits, see Debugging in the Tidepod IDE.
Remote Debugging with GDB
For automated testing, scripting, or developers who prefer terminal workflows, the stand-alone emulator
(ti994a-emu) includes a built-in GDB Remote Serial Protocol server. Because standard host GDB installations
do not support the TMS9900 architecture, you must use the cross-debugger provided with Tidepod: tms9900-elf-gdb.
Terminal 1 — Start the Emulator with GDB Server
make debug
# Run with graphical display and GDB server listening on port 3333:
tidepod run --debug
# Or run headless in continuous integration:
ti994a-emu --cart mygame.rpk --autorun --headless --gdb 3333
Terminal 2 — Connect tms9900-elf-gdb
tms9900-elf-gdb mygame.debug -ex 'target remote :3333'
(gdb) break main
(gdb) continue
Continuing.
Breakpoint 1, main () at src/main.c:42
42 player_init(&hero);
(gdb) print hero
$1 = {x = 120, y = 80, dx = 0, dy = 0, health = 100, state = 1}
(gdb) info registers
wp 0x8300 33536
pc 0x6148 0x6148 <main+12>
st 0x0000 0
r0 0x0078 120
r1 0x0050 80
...
(gdb) backtrace
#0 main () at src/main.c:42
Where GDB Stops on Connect
When target remote :3333 connects, the emulator halts wherever the CPU is at that moment. With
--autorun that is usually already inside the cartridge. Set your breakpoints and issue
continue.
The bank register, bank-qualified breakpoints, monitor sams, VS Code / MI setup and the full list of
what the stub does and doesn't support are covered in The Standalone GDB Bridge.
Zero-Cost Logpoints: __dbg_printf
Calling standard printf on an embedded 16-bit processor is notoriously heavy: it pulls hundreds of bytes of
format-parsing routines into memory and takes thousands of clock cycles to format strings, frequently causing games to
miss their 60 Hz frame deadline. Tidepod solves this with zero-overhead host logpoints via debug.h.
At compile time, each __dbg_printf call emits only a single 2-byte NOP instruction in the
executable binary. The format string literal and the symbolic names of the arguments are segregated into a custom ELF section
(.tms9900.logpoints) in the .debug sidecar. When the emulator hits the NOP, the host reads
argument values via DWARF, formats the message on your workstation, and prints it — in the IDE’s Debug Log,
or on the console of standalone ti994a-emu when --debug-dwarf <file>, --gdb, or
--dump-regs is passed (matching uses physical cart bank + address in the >6000 window):
src/player.c
#include "debug.h"
void player_take_damage(int amount) {
player.health -= amount;
/* Zero-overhead trace: formats on your Mac/PC, zero cycles on the TI */
__dbg_printf(DBG_RED "DAMAGE: " DBG_RESET "player took %d dmg, remaining=%d", amount, player.health);
if (player.health <= 0) {
__dbg_printf(DBG_BRIGHT_RED "PLAYER DIED at x=%d, y=%d" DBG_RESET, player.x, player.y);
BRK(); /* Software breakpoint: halts the debugger immediately */
}
}
Logpoint Specifications
Feature
Syntax / Macro
Behavior & Constraints
Format String
Standard C specifiers (%d, %u, %x, %s, %p)
Formatted on host workstation; no C formatting code linked into TI ROM.
Max Arguments
Up to 8 arguments
Arguments must be named variables or parameters resolvable via DWARF symbols.
Terminal Colors
DBG_RED, DBG_GREEN, DBG_YELLOW, DBG_RESET
ANSI escape sequences rendered in the IDE Debug Log.
Cursor Control
DBG_CLEAR, DBG_HOME, DBG_GOTO(row, col)
Positions log messages on a host debugging dashboard.
Software Breakpoint
BRK()
Triggers an immediate debugger pause in the IDE when hit.
Release Builds
-DNDEBUG in release CCFLAGS
Tidepod’s generated Makefile defines NDEBUG for make (release). Logpoints and BRK() expand to nothing; use make debug to keep them.
Logpoint traces displayed in the IDE's Debug Log panel.
Diagnosing Crashes, Hangs, and Bank Faults
When an embedded program locks up, the console screen often freezes without giving any diagnostic feedback.
ti994a-emu provides automated autopsy dumps through --dump-regs (which implies both
--headless and --autorun) and verbose interrupt tracing:
Terminal
# Auto-start headless (--dump-regs implies --headless and --autorun), simulate keys, and dump registers at frame 900:
ti994a-emu --cart mygame.rpk -v \
--keys "WAIT:120 ENTER WAIT:300" \
--dump-regs 900 --frames 920 2>interrupts.log | tee register_dump.log
Common Crash Signatures and Root Causes
Observed Symptom
Primary Root Cause
Remediation Workflow
Illegal Opcode Exception: Console reports invalid instruction or halts in unmapped ROM space.
Calling a function pointer across banks without switching the cartridge bank register. Direct calls use wrapped trampolines; indirect calls do not.
Move functions called via pointers into persistent RAM using #pragma bank persistent or tidepod add --persistent. See Banking.
Spontaneous Reboot or Data Corruption: Variables suddenly change values or game resets during deep recursion.
The C stack (growing downwards from 0xFFFE) has collided with ascending static variables in .bss.
Inspect ram_overhead.max_stack_depth and regions.persistent_high.free in bank_report.json. Reduce local array sizes or allocate buffers statically.
Garbled Graphics / Tile Corruption: Screen fills with scrambled patterns after VDP update.
Missing address setup byte or failing to observe VDP port delay constraints during high-speed VRAM writes.
Ensure write addresses set bit 0x40 on the second byte to latch write mode. Use standard library routines like vdpmemcpy.
Frozen Execution Loop: Program hangs with PC stuck in console ROM (0x0000–0x1FFF).
Console interrupt routine was executed while workspace or scratchpad vectors were modified.
Keep interrupts disabled (__asm__("limi 0")) if using scratchpad memory between 0x83C0 and 0x83FF.
High-performance TI-99/4A programming requires budgeting every CPU instruction against the 60 Hz vertical blanking
interval. The Tidepod IDE features a built-in cycle-accurate Frame Profiler (PRF) that monitors execution
timing in real time. By inserting lightweight markers from profiler.h into your C source, you can partition
your game loop into distinct visual categories—such as physics, input handling, sprite animation, and VDP rendering—and
immediately see how many clock cycles each subsystem consumes relative to your target frame budget.
Unlike software profilers that inject instrumentation calls, timestamp traps, or interrupt polling overhead, Tidepod's
profiler is completely non-invasive. The instrumentation macros emit zero machine instructions and consume zero clock
cycles: they simply export linker symbol labels that the emulator tracks passively at the hardware bus level.
Instrumenting a main loop
To profile an application, include <profiler.h> and wrap functional blocks in your game loop with
PROF_BEGIN and PROF_END macros. Mark the boundary between consecutive display frames using
PROF_FRAME_END():
src/main.c
#include "profiler.h"
for (;;) {
PROF_FRAME_END(); /* Mark start of frame boundary */
PROF_BEGIN(808080, vblank_wait); /* Grey: idle wait for vertical blank */
wait_for_vblank(); /* Polling VDP status flag */
PROF_END(808080, vblank_wait);
PROF_BEGIN(4FC3F7, input); /* Cyan: joystick & keyboard polling */
read_input();
PROF_END(4FC3F7, input);
PROF_BEGIN(81C784, update); /* Green: game simulation */
update_world();
PROF_BEGIN(FFB74D, physics); /* Orange: nested physics calculations */
run_physics();
PROF_END(FFB74D, physics);
PROF_END(81C784, update);
PROF_BEGIN(E57373, render); /* Red: VDP sprite and tile transfers */
render_screen();
PROF_END(E57373, render);
}
Instrumentation Rules and Semantics
The profiler macros operate by mapping the TMS9900 Program Counter (PC) against the symbol table emitted during compilation:
Color syntax: The color argument must be six hexadecimal digits (RRGGBB) without a leading 0x or #. This color defines the visual band displayed in the IDE's flame chart.
Label identifiers: The block name is a bare C token, not a string literal: write PROF_BEGIN(FF8800, render) rather than quotes.
Strict pairing: Every PROF_BEGIN(col, name) invocation must be matched by a closing PROF_END(col, name) with an identical name and color tag.
Proper nesting: Profiler blocks may be nested arbitrarily deep (for example, timing an inner algorithm inside a larger subsystem), but overlapping or interleaved blocks are invalid and will corrupt the profile stack.
Frame delimitation: Call PROF_FRAME_END() exactly once per game iteration, typically at the top of your loop immediately before awaiting the vertical blank interrupt. The profiler counts hardware VDP interrupts between successive delimiters to calculate effective FPS.
Accounting for idle time: Always wrap your vertical sync wait routine with a profiler block (conventionally colored grey 808080). This makes it easy to visualize your frame budget headroom: any time spent in vblank_wait represents unused CPU capacity.
Frame Budget and Hardware Clocking
The TMS9900 CPU in the TI-99/4A runs at a master frequency of 3.0 MHz, generated by dividing the console's 10.738635 MHz
crystal by 3.58 via the TIM9904 clock driver. Under standard NTSC video timing, the screen refreshes at approximately
59.94 Hz. This establishes a fixed budget of approximately 50,065 CPU cycles per video frame:
Complex simulations, RPGs, board games with heavy AI
20 FPS (3 VSYNCs)
50.04 ms
150,195 cycles
3D wireframe renderers, raycasters, deep strategy games
15 FPS (4 VSYNCs)
66.72 ms
200,260 cycles
Turn-based adventure games, text-heavy engines
In the IDE's PRF tab, you can select your desired target frame rate from the dropdown (60, 30, 20, 15,
or 10 FPS). The profiler renders two live charts:
FRAME PERFORMANCE PROFILER: A rolling 120-frame line chart plotting total CPU cycles per frame against a horizontal budget threshold line (100% of the target frame budget). When a frame exceeds the budget line, the indicator highlights the frame hitch. If your game misses the 50,065-cycle mark by even a single cycle, it waits for the next VSYNC pulse, dropping from 60 FPS to 30 FPS.
BLOCK BREAKDOWN: A per-frame stacked breakdown bar chart and legend showing the cycle count and percentage of the frame budget consumed by each instrumented PROF_BEGIN / PROF_END block (up to 10 color-coded blocks per frame).
Memory Architecture and Cycle Penalties
When analyzing profiler results, keep in mind that TMS9900 instruction cycle counts vary drastically depending on where
code and data reside in memory:
16-bit Scratchpad RAM (0x8300–0x83FF): Located directly on the CPU's internal 16-bit bus with zero wait states. A register-to-register operation like MOV R1, R2 executes in its baseline 14 clock cycles. Inner loops placed in scratchpad run at maximum hardware speed.
Cartridge ROM and 32K Expansion RAM: Connected through the TI-99/4A's multiplexed 8-bit bus. Every 16-bit word read or write requires two sequential 8-bit cycles, injecting 4 hardware wait states per word. The same MOV instruction accessing variables in expansion RAM takes substantially longer.
Cross-bank Trampolines: Direct calls across cartridge ROM banks require a trampoline stub in persistent RAM to latch the new bank register and restore the caller's bank upon return. This adds 12 to 24 cycles of overhead per call.
Optimization Strategies from Profiler Insights
When the PRF tab reveals that a specific block is consuming excessive cycles, apply these proven optimization steps:
Relocate hot functions: Mark the most cycle-intensive routines with #pragma bank scratchpad or tidepod add --scratchpad. Putting a 100-byte collision routine in scratchpad can save thousands of cycles per frame.
Eliminate trampoline thrashing: If the profiler shows high overhead in inter-module calls, place frequently called functions in persistent RAM (#pragma bank persistent) or consolidate tightly coupled functions into the same translation unit so they pack into a single ROM bank.
Precalculate complex math: Avoid software multiplication and division in per-frame loops. Use lookup tables for sine, cosine, screen offsets, and fixed-point physics.
Tune compiler optimization: Debug builds (make debug) compile with -O0, leaving local variables on the stack frame. Rebuilding with -Os or increasing optLevelDebug promotes variables into TMS9900 workspace registers (R0–R15), dramatically shrinking cycle counts.
The PRF (profiler) tab showing the 120-frame performance chart and per-block cycle breakdown.
ti994a-emu can run without a window, type on the TI keyboard from a script and save screenshots. That
is enough to check in a script or CI job that a build boots and reaches a given screen.
--screenshot-at 300,600,900 captures several frames; with more than one, the frame number is appended to the file name.
The default path is screenshot.png.
Images are cropped to the active display. In 80-column mode every scanline is doubled (512×384) so the pixels are square.
Making it a test
Look for illegal-opcode messages in the output: they mean the program jumped somewhere it shouldn't.
Compare the screenshot with a known-good reference image.
--dump-regs N gives you register and VRAM state at frame N as text, easy to grep. See Debugging.
Merged cartridges
If your cartridge image is placed behind other ROM banks (packer --bank-base), the bank numbers the
emulator reports are offset from the ones in bank_report.json.
Symptoms you are likely to run into, and what to do about them.
Build
Symptom
Cause and fix
A warning stops the build
Builds use -Werror. Fix the warning.
A header change has no effect
Objects don't depend on your headers. Rebuild with make clean && make, or list the dependencies in Makefile.custom.
The packer reports a unit that doesn't fit in a bank
One source file has more than 8 KB of code and constant data. Split it. See Banking.
Changes to the .project file are ignored
Run tidepod sync.
malloc returns NULL immediately
The near-heap reservation defaults to 0 bytes; set "heapSize" in your .project file (or pass --heap-size <bytes> to tms9900-packer), use sams_malloc from <sams.h>, or use static buffers. See malloc(3).
Make warns about overriding recipes
Makefile.custom redefines all or debug. Use POST_BUILD instead.
Running
Symptom
Cause and fix
tidepod run shows the old version
run doesn't build. Run make first.
Works with --autorun but not from the menu (or the other way round)
Test the real boot path with key injection; see Headless testing.
Crash or illegal-opcode flood after calling through a function pointer
Calls through pointers are not bank-switched. Move the target function to persistent RAM. See Banking.
A string or table passed to another file reads as garbage
It points into a bank that is no longer mapped. Copy it first or move the table to a persistent file.
Random corruption that gets worse as the program grows
Stack overflow into .bss. Move large locals to static, check max_stack_depth and RAM headroom in bank_report.json.
Disk access corrupts the program or hangs
Scratchpad code overlaps the disk system's area. Use the +disk access (0x8380) preset in Project Settings. See Code placement.
Hard-disk image is refused
CHD images are not supported; extract a raw image with chdman extracthd. See Disks.
Text mode shows blanks or garbage instead of letters
ti_text_mode sets up the mode but loads no font. Call ti_text_load_builtin_font() right after it, or copy your own font to 0x1000 with rom_to_vram.
The screen says 32K MEM REQUIRED!
Banked cartridges need the 32K memory expansion. On real hardware, check that it is installed and switched on. For a console-only cartridge use the 8K project type.
Only 4 sprites per line on the F18A
Set VR30 after unlocking; its reset value is 4. See F18A GPU code.
Debugging
Symptom
Cause and fix
No source lines in the debugger
Build with make debug (F5 in the IDE).
GDB stops at PC=0024
That's the reset vector; continue.
GDB shows nonsense for VRAM addresses
x/ reads CPU memory. Use the VDP tab or --dump-regs.
Logpoints print nothing
Build with make debug (release defines -DNDEBUG and strips them). They fire in the IDE debugger and in standalone ti994a-emu when DWARF / --debug-dwarf is loaded. Match is physical cart bank + address in the cart window.
Every page in this section is generated from the man pages shipped with Tidepod
(resources/man), so it always matches the library you have installed. The same pages are
available offline in the IDE and with man. 157 pages are listed below; use the filter or the tree.
CRU matrix scan with edge detection.
kbhit()
is nonzero when a new key (or joystick) edge is available.
cgetc()
blocks until input arrives and returns KEY_* codes
or ASCII.
getchar()
returns EOF if nothing is waiting, otherwise the
same codes.
Joystick 1 (and host arrow keys in the Tidepod emu) map to the same
KEY_* values. Joystick fire maps to
KEY_TAB (pane-switch convention for apps like
fileman).
Common
chords
Fctn-=
KEY_ESC
(TI QUIT)
Fctn-1
KEY_DEL
(0x7F, TI DEL)
Fctn-6
KEY_TAB
(TI PROC'D)
Ctrl-H
KEY_BS
(0x08, Backspace)
Ctrl-I
KEY_TAB
Ctrl-C
KEY_ESC
Held keys support VSync-paced auto-repeat after an initial delay.
Plain digit and letter keys return ASCII (e.g. 3,
5, Q). Fctn+digit is
not
translated to KEY_F1 ...
KEY_F5; prefer plain numerics for app commands.
Addressable console functions sharing state with
putchar(3) /
printf(3). Coordinates are 0-based.
Use conio for panel UIs; avoid mixing with streaming
printf()
on the same screen.
Absolute draws (cputcxy,
cputsxy, cclearxy,
chlinexy, cvlinexy) clip at
the screen edge and do
not wrap or scroll
(safe for dual-pane UIs). Streaming
cputc()
/
putchar()
still wrap and scroll.
chline()
/
cvline()
emit CP437 box-drawing codes (CH_HLINE,
CH_VLINE, CH_DHLINE,
CH_DVLINE, corners/tees,
etc.) so the pattern descriptor table must include those glyphs (e.g.
fileman's 6x8 box set in the 5x8 font resource).
Text and line output: cputc(),
cputcxy(),
cputs(),
cputsxy(),
cprintf(),
vcprintf()
(128-byte stack format buffer), chline(),
chlinexy(),
cvline(),
cvlinexy().
int fcopy_path_pg(const
char *src, const char
*dst);
int fcopy_path_typed(const
char *src, const char
*dst, int ti_type,
unsigned reclen);
DESCRIPTION
fcopy_path()
probes src (same FDR path as)
fopen()
on an existing file , opens dst with a matching create
mode (e.g. wb:pg, wb:if:64,
w:dv:80), and copies with
fread()
/
fwrite()
only. No VDP LOAD/SAVE.
fcopy_path_pg()
copies a PROGRAM (:pg) file directly using only two
pointer arguments, which is safe across banked cartridge trampolines.
fcopy_path_typed()
copies src to dst using a
caller-supplied TI catalog type ti_type
(TI_DF, TI_DV,
TI_IF, TI_IV,
orTI_PG) and record length
reclen (e.g. from
ti_readdir(3)) without re-probing
the source FDR.
RETURN
VALUES
Returns 0 on success, -1 on failure. Check
stdio_last_error(3) first
(DSR status); errno may also be set by some
backends.
Reads one byte from stream. On
stdin it uses the console keyboard path. On a disk
stream it is implemented via
fread()
and inherits that stream's record type and buffering (DISPLAY/VARIABLE
newlines, FIXED records, PROGRAM AU, chip/FAT/WDS backends); see
fopen(3).
RETURN
VALUES
The byte as an unsigned char cast to
int, or EOF on end-of-file or
error.
Reads at most n−1 bytes into
s, stopping at newline or EOF, and NUL-terminates the
buffer. On disk streams this uses
fread()
with the same buffering and DISPLAY VARIABLE newline rules as
fopen(3).
RETURN
VALUES
s on success, or
NULL on end-of-file or error before any data is
read.
Existing
files: FDR probe always wins for type and record length. A
:type[:reclen] suffix on open is ignored so helpers
can reuse one mode builder.
Create
defaults:
no b → DISPLAY/VARIABLE 80
(w) creates DV80
b
present → INTERNAL/FIXED 128 (wb) creates
IF128
explicit :df|:dv|:if|:iv|:pg[:reclen] overrides
the b defaults (e.g.
wb:df:80, wb:pg,
wb:if:64)
b on create without a type
selects INTERNAL/FIXED 128. On an existing
DISPLAY file
(df /dv), plain
r / rb applies
record→newline text munging. Opaque DISPLAY I/O requires an explicit
type with b (e.g. rb:df:80,
wb:dv:80). fcopy_path always
uses typed opaque modes for bit-identical copies. For text lines
(fprintf(),
fputs())
with newline record boundaries, open w or
w:dv:80 (not
wb:dv:…), which treats newlines as data.
PROGRAM
(pg) uses an AU/sector byte stream inside libc. Each
FILE carries a
STDIO_SECTOR_BUF (128-byte)
FILE.sector_buf cache with buf_pos /
buf_len. Apps never issue LOAD/SAVE for copy or normal read/write.
Record files (df/dv/if/iv) use Level-3 READ/WRITE; libc caches one record
(up to 128 bytes in sector_buf) so a one-byte
fread()
does not re-hit the DSR every time.
Paths and mode are copied into stack scratch
at entry (up to TI_PATH_MAX) /
STDIO_MODE_MAX so a later cart-bank trampoline
cannot invalidate a caller pointer. Banked callers should keep mode strings
in RAM (not banked .rodata).
At most STDIO_MAX_FILES (3) simultaneous
disk FILE objects are supported.
HFDC/WDS Level-2 AU I/O uses a 256-byte VRAM sector buffer
(default 0x3DA8), high under FILES . Call
stdio_set_wds_vdp_buf(3)
if that window overlaps your screen, attributes, or PAB arena (fileman parks
it at 0x3600); Text80 attrs live at
>2000, pattern generator table at
>0800.
feof()
and
ferror()
return nonzero when the stream end-of-file or error indicator is set;
clearerr()
clears both indicators on stream.
vdp_load_file()
and
vdp_save_file()
issue classic Level-3 DSR LOAD (opcode 5) and
SAVE (opcode 6) for PROGRAM images directly to/from
VDP RAM at vdp_addr (or copying len
bytes from CPU RAMsrc via VDP) using the PAB
arena at stdio_vdp_base.
fcopy_path()
copies src to dst using only
fopen(/)
fread(/)
fwrite(/)
fclose()
(probes source type; bit-preserving for probed kinds); see
fcopy_path(3).
stdin, stdout, and
stderr are console sentinels, not disk files.
RETURN
VALUES
fopen() returns a FILE
* or NULL on failure.
fread() / fwrite() return
the number of complete elements transferred.
fcopy_path() returns 0 on success, -1 on
failure.
ERRORS
On fopen() /
fcopy_path() failure, call
stdio_last_error(3) for the
DSR-style status (primary signal). errno may also be
set by native backends (chip / FAT / WDS) but is often left unchanged after
classic PAB/DSR failures — do not rely on errno
alone.
Writes the low 8 bits of c to
stream. On stdout /
stderr this goes through
putchar().
On a disk stream it uses
fwrite()
and the stream's record/AU buffering (see
fopen(3)). A newline on a DISPLAY
VARIABLE text stream ends the current record.
Writes the NUL-terminated string s to
stream without appending a newline. On
stdout / stderr each
character goes through
putchar().
On disk streams the string is written with
fwrite()
(same buffering and DISPLAY VARIABLE newline rules as)
fopen(3).
For one record per line on DISPLAY VARIABLE files, open
with w or w:dv:80 and
include \n in the string (or call)
fputs() then
write a lone newline. Do not use wb:dv:… for
text; that mode keeps newlines as opaque bytes.
Transfer size ×
nmemb bytes to/from stream.
Bytes come from FILE.sector_buf
(STDIO_SECTOR_BUF, 128
bytes) when the cache still has unread data; otherwise libc fills the
next Level-3 record or PROGRAM AU chunk and continues. A one-byte
fread()
does not
re-read the disk sector every call.
DISPLAY streams without b may map newlines
to VARIABLE record boundaries. INTERNAL / b /
PROGRAM streams are opaque byte streams.
fseek()
repositions a disk FILE. Console streams are not
seekable.
Native backends (chip, FAT12, WDS, PROGRAM-AU)
implement byte seeks when available. The default Level-3 PAB path supports
SEEK_SET and SEEK_CUR by
issuing RESTORE and discarding bytes with
fread()
(record-oriented; not a random FIXED-128 map).
SEEK_END is not supported and fails with
EINVAL.
rewind()
is fseek(stream,
0, SEEK_SET) and clears the
error indicator.
ftell()
reports the current logical byte offset when the backend tracks it.
RETURN
VALUES
fseek() returns 0 on success, nonzero on
failure. ftell() returns the offset, or -1 on
error.
int snprintf(char
*str, size_t size,
const char *fmt,
...);
int vprintf(const
char *fmt, va_list
ap);
int vfprintf(FILE
*stream, const char
*fmt, va_list
ap);
int vsprintf(char
*str, const char
*fmt, va_list
ap);
int vsnprintf(char
*str, size_t size,
const char *fmt,
va_list ap);
DESCRIPTION
Subset of ISO C
printf()
for the TI-99/4A.
printf()
and
vprintf()
write to the VDP nametable via the console cursor (see
putchar(3)). Call
ti_text_mode()
first to select 32, 40, or 80 columns.
fprintf()
/
vfprintf()
to stdout / stderr use the
same path; disk FILE * streams format into a 128-byte
stack buffer (truncating at 127 characters per call) and emit via
fputc(3) (as do
cprintf(and)
vcprintf(in)
conio(3)).
Supported conversions: %s %c %d %i %u %x %X %p
%%, plus length modifier l for 32-bit
long integers (%ld %li %lu %lx
%lX). Field width is supported for strings and integers, and the
- flag left-aligns %s
fields. Precision (.digits) and flags
+, space, 0, and
# are parsed and ignored.
Not supported: %f %e %g,
asprintf(),
positional %n$, and length modifiers other than a
single l.
TYPE
MODEL
int and size_t are
16-bit; long is 32-bit.
RETURN
VALUES
Number of characters emitted (or that would be emitted for
snprintf()), not counting a trailing NUL written
into string buffers.
By default, fopen(3) uses
Level-3 DSR PAB I/O only (classic DSK1.NAME) paths .
That keeps game carts slim: unused chip / FAT / WDS / PROGRAM-AU translation
units are not pulled from libc.a into upper RAM.
Apps that need the native backends must call one or
more of these enable routines
before disk I/O
(typically before)
stdio_disk_init()
or the first
fopen():
stdio_enable_chip()
TIFDC / HFDC floppy DSK* via
ti_fs_chip (no Level-3 PAB).
stdio_enable_fat()
FAT12 volumes on HFDC DSK* (opaque byte
stream).
stdio_enable_wds()
HFDC hard WDS* via chip AU streams (also installs
the optional HFDC face poke used before PAB opens).
stdio_enable_prog()
DSR PROGRAM files as AU byte streams (:pg) and
untyped fall-through to PROGRAM .
stdio_enable_all_disk()
Convenience for file managers and disk tests: enables chip, FAT, WDS, and
PROGRAM. Lives in its own archive member so games that never call it do
not pull those backends.
Each
stdio_enable_*()
registers function pointers used by
fopen()
/
fread()
/
fwrite()
/
fseek()
Calling an enable pulls that backend’s .text
and .bss from the archive; call only what you
need.
Games
that only save/load on a classic floppy DSR should call
none of
these (e.g. Commander Keen).
Fileman
and the disk suite examples call
stdio_enable_all_disk().
Calls
stdio_enable_chip(),
stdio_enable_fat(),
stdio_enable_wds(),
and
stdio_enable_prog().
Use in file managers and disk test carts. Do
not call
from RAM-tight games that only need Level-3 PAB
fopen();
this symbol lives in its own archive member so omitting the call keeps chip
/ WDS .bss out of the link.
Registers the ti_fs_chip path matcher and
stream ops so fopen(3) can open TIFDC
/ HFDC floppy DSK* paths without Level-3 PAB. Call
once at startup before disk I/O. Pulls chip FS .bss
into upper RAM; omit on carts that only need classic DSR PAB.
Registers the FAT12 path matcher and stream ops so
fopen(3) can open HFDC
DSK* volumes formatted as FAT12 (opaque byte
stream). Call once at startup before disk I/O.
Registers PROGRAM (:pg) open and stream
ops so fopen(3) can treat DSR PROGRAM
images as sequential AU byte streams (no app-visible LOAD/SAVE). Without
this enable, untyped opens that resolve to PROGRAM fall back toward record
OPEN (which)
fopen()
rejects for true PROGRAM FDRs .
Registers WDS* chip AU stream ops and the optional HFDC face poke
used before PAB opens on HFDC-owned units. Required for
WDS1.... paths through
fopen(3). Also set
stdio_set_wds_vdp_buf(3)
if the default Level-2 VRAM window overlaps your screen tables.
Disk path APIs (fopen,
remove, ti_opendir,
fcopy_path, …) record
a DSR-style status in an internal stdio_last_err and
expose it via
stdio_last_error().
This is the
primary
failure signal for classic Level-3 PAB I/O.
Defined codes (see stdio.h):
STDIO_ERR_NONE
0 — success / cleared
STDIO_ERR_BADDEV
1 — bad device
STDIO_ERR_PROTECT
2 — write protect
STDIO_ERR_BADOPEN
3 — bad open
STDIO_ERR_NOSPACE
4 — out of space
STDIO_ERR_EOF
5 — end of file / missing
STDIO_ERR_DEVICE
6 — device error
STDIO_ERR_FILE
7 — file error
Some helpers also use extended codes 9–12 (verify / layout
/ bad path). Successful opens and many helpers clear the code to 0.
errno
is not set
on every DSR failure. Native backends (chip / FAT / WDS / HFDC Level-2) may
set errno (e.g. EINVAL,
ENOSPC, ENOTSUP) in addition
to
stdio_last_error().
Prefer stdio_last_error() for portable disk error
handling; check errno only when a backend documents
it.
stdio_set_vdp_base()
sets the starting VDP RAM address (stdio_vdp_base)
where libc places Peripheral Access Blocks (PABs)
and their associated record transfer buffers for Level-3 DSR disk
operations.
If
stdio_set_vdp_base()
is never called, stdio_vdp_base defaults to
0x3000 (occupying
>3000–>32FF). Any program whose VRAM
layout overlaps >3000–>32FF should
relocate the PAB arena to a free VRAM region before opening files.
VRAM
Arena Layout
Up to STDIO_MAX_FILES (3) streams may be
open simultaneously. Each slot idx (0
<= idx < 3) occupies 0x0100 (256) bytes
at pab_base + idx * 0x0100:
+0x0000
.. +0x001F (32 bytes, f->vdp_pab = pab_base
+ idx * 0x0100): 10-byte PAB header followed by the device/file
pathname (e.g. “DSK1.MYFILE”).
+0x0020
.. +0x00DF (192 bytes, f->vdp_buf = vdp_pab
+ 0x0020): VDP record buffer (up to
STDIO_REC_MAX) used by DSR
OPEN, READ, and
WRITE calls.
In total, the three file slots reserve 3 * 0x0100
= 0x0300 (768) bytes of VRAM: pab_base .. pab_base +
0x02FF (default
>3000–>32FF).
Avoiding
VRAM Collisions
When choosing pab_base, ensure the
0x0300-byte arena does not overlap:
Screen Image / Name Table (typically
>0000–>07FF), pattern generator table
at >0800, and F18A Text80 attribute table at
>2000 (ATTR_BASE =
0x2000).
Pattern Descriptor Table
(>0800–>0FFF) or
>1000–>17FF in text modes, or up to
>1FFF / >37FF in bitmap modes .
Catalog PAB scratch at >1C00
(CAT_PAB = 0x1C00, CAT_BUF =
0x1C40) used by
ti_opendir(3) when reading
directory entries via Level-3 DSR, and delete PAB scratch at
>1D00 used by
remove(3).
Myarc HFDC Level-2 sector buffer configured by
stdio_set_wds_vdp_buf(3)
(default 0x3DA8); often moved to
0x3600.
The DSR FILES(n) reserved area at the top of 16K
VRAM: for FILES(3), >8370
is 0x37D7, so VRAM from
0x37D7 through 0x3FFF is
owned by the disk controller DSR and VDP stack.
Note: native chip-level floppy I/O
(stdio_enable_chip(3)) and
FAT12 streams
(stdio_enable_fat(3))
transfer sectors directly between controller registers and CPU RAM without
using the PAB arena, whereas Level-3 PAB fallback and DSR PROGRAM loads
still use stdio_vdp_base.
EXAMPLES
Place the 3-slot PAB arena at 0x3200
(occupying 0x3200–0x34FF), safely below
FILES(3) at 0x37D7:
Myarc HFDC Level-2 sector I/O (AU read/write via subprogram
>10) uses a 256-byte VRAM window. The DSR
programs HDC DMA to the same numeric address; on this toolchain the emulator
mirrors that transfer into VDP RAM, so the window must not overlap screen
nametable, F18A attribute table, bitmap color table, catalog PABs, or the
stdio_set_vdp_base()
PAB arena.
The libc default is
0x3DA8 (high under FILES(2)), the traditional Myarc
location. Console Text80 attributes live at >2000
(ATTR_BASE = 0x2000, while the
pattern generator table is at>0800) so
HFDC mirrors around >221A can overlap attributes
unless relocated; apps that use Text80 attributes or place their own tables
high should call
stdio_set_wds_vdp_buf()
(e.g. fileman uses 0x3600), below its PAB arena at
>3800.
Addresses that cannot fit 256 bytes
below >4000 are rejected and the default is
restored.
stdio_get_wds_vdp_buf()
returns the address currently in use.
ti_text_mode()
selects 32, 40, or 80 column text, programs VDP registers for the console
nametable at (>0000) and pattern table at (>1000), and resets the
console cursor. If cols is 80 but
ti_vdp_text80_ok()
is false, the call falls back to 40 columns. On a stock TMS9918A only
VR0–7 are written; F18A/Pico enhanced registers are gated behind
detect so they cannot alias into VR1 and blank the display.
ti_text_mode()
does not
load glyph patterns. Call
ti_text_load_builtin_font()
afterward to upload a bundled 5x8 font into the PDT, or
rom_to_vram()
a project resource (as fileman does with font_5x8.dat
).ti_text_load_builtin_font() lives in its
own libc object and is linked only if referenced.
int rename(const
char *oldpath, const char
*newpath);
DESCRIPTION
remove()
and
unlink()
delete a TI path such as DSK1.MYFILE (Level-3 DELETE
at VDP scratch >1D00 or FS mutate,
binding-dispatched).
rename()
renames within the same volume when
stdio_enable_chip(3)
(TIFDC floppy) or HFDC WDS
(stdio_enable_wds(3)) is
active; otherwise it returns -1 with errno set to
ENOTSUP. Cross-volume rename is not supported
— use
fcopy_path()
then remove().
Walk PEB CRU bases (>1000) through
>1F00, map each card ROM, and collect type-8
device names from the list at >4008. Only
catalogable unit names are returned: DSK1 through
DSK8 and WDS1 through
WDS3 (bare DSK /WDS, TIME,
and other names are skipped).
Names are written without a trailing period. Pass
the result to
ti_opendir()
as DSK1. or WDS1. to
catalog.
ti_dsr_enum_ex()
performs the same scan as
ti_dsr_enum()
but also records the card CRU base address in
out[i].cru for driver binding.
At most TI_DSR_MAX (16) entries are
returned; max is clamped to that limit.
RETURN
VALUES
Number of names written to out (zero if none
found or arguments are invalid).
int ti_dir_volume(const
ti_DIR *dir, ti_volume_t
*out);
DIR * opendir(const
char *name);
struct dirent * readdir(DIR
*dir);
int closedir(DIR
*dir);
DESCRIPTION
Open device (e.g. DSK1.
orWDS1.) as an INTERNAL/FIXED 38 catalog
(OPEN passes record length 0 so the DSR fills 38; required for Myarc HFDC).
The device name is copied into always-mapped storage at entry before any
further catalog work (bank-safe).
ti_readdir()
fills ent and returns nonzero while file entries
remain (the volume record is consumed internally and is not returned as an
entry).
ti_dir_volume()
copies volume metadata gathered from catalog record 0 into
out. Call it before
ti_closedir().
It returns nonzero when volume data is available.
ti_dirent
name
NUL-terminated file name, max TI_NAME_MAX (12,
accommodating FAT 8.3 names such as FDCONFIG.SYS;
classic TI names are <= 10) characters.
Record length for DF/DV/IF/IV files, or EOF offset in the last sector for
PROGRAM files.
flags
Bit 0 set if the file is write-protected.
ti_volume_t
volume
Disk volume name.
total_sectors,
free_sectors
From catalog record 0.
POSIX
wrappers (opendir, readdir, closedir)
opendir(),
readdir(),
and
closedir()
provide a POSIX-shaped directory stream over DIR and
struct dirent (with d_name[NAME_MAX +
1], d_typeDT_REG /DT_DIR /DT_UNKNOWN,
and optional TI catalog fieldsd_ti_type, d_flags,
d_sectors, d_reclen).
Numeric catalog fields use BASIC INTERNAL encoding: a
length-prefixed name followed by three length-prefixed RADIX-100 floats
(each numeric is 08 then 8 float bytes). Negative
type means write-protected (first two float bytes are ones-complemented).
Libc also accepts layouts without per-float length bytes and flat emulator
catalogs (10-char name at offset 0 with floats at 10/18/26, or big-endian
words at 10/12/14). The standard FIXED-38 catalog does
not include
timestamps.
Supported on classic floppy DSRs, Myarc HFDC hard disks
(WDSn.), and emulator DSK/HD images. Discover unit
names with ti_dsr_enum(3) rather
than hardcoding DSKn. /
WDSn..
RETURN
VALUES
ti_opendir() returns a directory handle,
or NULL on failure.
ti_readdir() returns nonzero for a valid entry, zero
at end-of-catalog or on error. ti_dir_volume()
returns nonzero when out was filled.
typedef struct {
unsigned char type; /* catalog type codes */
unsigned int sectors;
unsigned int reclen;
unsigned char flags; /* bit0 protected; bit1 directory */
} ti_stat_t;
DESCRIPTION
ti_stat()
probes TIFDC Level-2 floppy FDR metadata only
(DSK1...DSK3.) and fills
st for an existing file.
ti_protect(),
ti_mkdir(),
and
ti_rmdir()
copy path into a local stack buffer and dispatch
across the active filesystem bindings (TIFDC floppy layout, HFDC WDS, FAT12,
…). ti_protect() sets
(protect=1) or clears
(protect=0) the FDR protect bit where the volume
supports it. ti_mkdir() and
ti_rmdir() create or remove a subdirectory (HFDC WDS
paths such as WDS1.NEWDIR); TIFDC floppies have no
subdirectories and return ENOTSUP.
ti_vdp_detect()
unlocks an F18A-compatible VDP (VR57 twice) and reads status register 14. It
returns TI_VDP_STOCK,
TI_VDP_F18A, or
TI_VDP_PICO9918 (currently reported as
F18A-compatible; TI_VDP_V9990 is also defined for
Yamaha V9990/V999x but not probed yet). Results are cached.
ti_vdp_text80_ok()
is nonzero when 80-column text mode is safe (enhanced VDP with firmware
>= 1.6).
ti_vdp_has_attrs()
returns nonzero when per-cell foreground/background attributes are available
in F18A/Pico9918 Text40 or Text80 modes.
ti_vdp_has_gpu()
returns nonzero when the F18A/Pico9918 GPU DMA blit engine is available.
console_gpu_invalidate()
drops libc's cached GPU scroll blob upload (e.g. after an application
overwrites VRAM around 0x3000).
ti_load_ega_palette()
and
ti_load_tms9918_palette()
program the F18A 16-entry palette registers to the classic EGA 16-color
palette or restore the stock TMS9918A colors (no-op on stock TMS9918A).
typedef void (*resource_copy_hook_t)(unsigned
int bytes_copied,
unsigned int
total_bytes);
void rom_to_vram(unsigned
int srcbank, unsigned int
srcoffset, unsigned int
length, unsigned int
dst);
void rom_to_ram(unsigned
int srcbank, unsigned int
srcoffset, unsigned int
length, unsigned char
*dst);
void rom_to_vram_ex(unsigned
int srcbank, unsigned int
srcoffset, unsigned int
length, unsigned int
dst, unsigned int
chunk_size,
resource_copy_hook_t
hook);
void rom_to_ram_ex(unsigned
int srcbank, unsigned int
srcoffset, unsigned int
length, unsigned char
*dst, unsigned int
chunk_size,
resource_copy_hook_t
hook);
DESCRIPTION
The
<resource_copy.h> header
declares the runtime interface for copying binary resources (tilesets,
sprite sheets, fonts, audio streams, and F18A GPU blobs) from banked
cartridge ROM into VDP RAM or 32K CPU expansion RAM.
In a Tidepod banked cartridge project, binary files added with
tidepod add are packed contiguously into cartridge
ROM banks starting at linker symbols
_binary_start_bank and
_binary_start_offset. During the build, a packer
pre-pass generates include/resource_defs.h with
three preprocessor constants per resource
(<name>_bank,
<name>_offset,
<name>_length), where
<name> is the file stem with non-identifier
characters converted to underscores.
Pass
unwrap(name)
as the first three arguments to
rom_to_vram(3),
rom_to_ram(),
rom_to_vram_ex(),
or
rom_to_ram_ex()
to transfer the asset across one or more 8 KB cartridge banks without
manual bank calculations.
For complete parameter descriptions, bank-wrapping behavior, and
progress-hook examples, see
rom_to_vram(3).
typedef void (*resource_copy_hook_t)(unsigned
int bytes_copied,
unsigned int
total_bytes);
void rom_to_vram(unsigned
int srcbank, unsigned int
srcoffset, unsigned int
length, unsigned int
dst);
void rom_to_ram(unsigned
int srcbank, unsigned int
srcoffset, unsigned int
length, unsigned char
*dst);
void rom_to_vram_ex(unsigned
int srcbank, unsigned int
srcoffset, unsigned int
length, unsigned int
dst, unsigned int
chunk_size,
resource_copy_hook_t
hook);
void rom_to_ram_ex(unsigned
int srcbank, unsigned int
srcoffset, unsigned int
length, unsigned char
*dst, unsigned int
chunk_size,
resource_copy_hook_t
hook);
DESCRIPTION
The
<resource_copy.h> routines
stream binary assets packed into banked cartridge ROM
(>6000–>7FFF) into VDP RAM or CPU RAM,
automatically stepping across 8 KB (0x2000)
cartridge bank boundaries and restoring the caller's active bank before
returning.
When a binary asset (e.g.
resources/font_5x8.dat) is registered with a Tidepod
project via tidepod add, the build converts it into
a linkable .binary section object and
tms9900-packer emits three constants into the
generated header
<resource_defs.h>:
The convenience macro
unwrap(sym)
expands to the comma-separated triple sym_bank,
sym_offset, sym_length expected
as the first three arguments of all four copy routines.
All four routines reside in .persistent
memory (upper 32K RAM) so they can safely switch cartridge banks at
>6000 without unmapping their own code:
rom_to_vram()
Copies length bytes starting at
(srcbank, srcoffset) relative
to the linker's _binary_start_bank and
_binary_start_offset symbols into VDP RAM beginning
at byte address dst
(0x0000–0x3FFF) on stock TMS9918A, or
higher when F18A extended VRAM is unlocked. Writes use an inlined VDP
burst loop (port >8C02) address setup followed
by streaming writes to >8C00 rather than
calling a banked helper, so the active source bank at
>6000 is never clobbered mid-transfer.
rom_to_ram()
Copies length bytes from banked cartridge ROM into
CPU RAM at dst using
memcpy(3) across bank boundaries.
The destination buffer must be in persistent RAM (32K expansion or
scratchpad), never inside the
>6000–>7FFF cartridge window.
rom_to_vram_ex()
Chunked variant of rom_to_vram() for keeping
music, sound effects, or loading bars alive during large asset uploads.
Transfers at most chunk_size bytes per step (or the
remainder of the current 8 KB bank if smaller); when
chunk_size is 0, each bank slice is transferred in
one chunk. After each chunk, if hook is non-null,
calls
hook(bytes_copied,
total_bytes) while the resource bank is still
latched. If the hook itself switches banks, it must restore
currentbank or reside in persistent memory.
rom_to_ram_ex()
Chunked variant of rom_to_ram() with the same
chunk_size and hook progress
callback semantics.
Bank
Arithmetic and Preservation
Before switching banks, each function reads the global
currentbank variable, adds the linker symbols
_binary_start_bank and
_binary_start_offset to srcbank
and srcoffset, and normalizes
srcoffset modulo 0x2000.
Whenever a copy spans the end of an 8 KB bank
(srcoffset + length > 0x2000), the routine copies
the tail of the current bank, increments srcbank,
resets srcoffset to 0, and continues until
length bytes have been transferred. Finally,
switchtobank(saved)
restores the caller's original bank.
EXAMPLES
Upload a packed 2 KB font resource into the Pattern
Descriptor Table at VRAM >1000:
SuperAMS (74LS612) does not enlarge the TMS9900 address space.
Native char * pointers remain 16-bit and can see at
most the classic ~32K expansion windows at once. Extra SRAM is reached by
rewriting 4K mapper pages through CRU base >1E00
(bit 0 = mapper registers at >4000,
bit 1 = MAP mode).
Tidepod exposes that card with
sams_ptr_t fat pointers (page + offset) and helpers
that either lock a
page into a reserved CPU window (yielding a temporary near)
void *, or
access
bytes through a scratch window without a long-lived near pointer.
Ordinary .data / .bss / .persistent and
the C stack stay near forever (identity-mapped windows). Do not remap
>F000 while C code is running: the default linker
places the stack there.
With a toolchain that defines
__TMS9900_SAMS_AS__, GCC accepts the named address
space qualifier __sams (GNU C:)
-std=gnu99 or -std=gnu11,
not plain -std=c99. Tidepod project Makefiles
default to -std=gnu99. A pointer such as
unsigned char __sams * is an SI fat pointer with the
same page:offset encoding as sams_ptr_t (under gnu99,)
sams_malloc()
returns void __sams * so no cast is needed . Loads and
stores expand to
__sams_load_qi(/,
__sams_store_qi) and
__sams_load_hi(/,
__sams_store_hi) (thin wrappers over the accessors; HI
touches map the accessor window once when both bytes share a page). Static
objects (static unsigned char __sams buf[N]) land in
.sams_bss (or) .sams_data if
initialized at fat VMA 0x00100000 (page 0x10
onward);
sams_static_init()
in crt0 zeroes BSS via the packer bookkeeping symbols. Pointer arithmetic
within a page-local object is ordinary SI add (matching)
sams_malloc() chunks . Cast through
sams_ptr_t to convert between the integer API and
__sams pointers; use
sams_lock()
for a temporary near void *. See
resources/examples/sams_as_test/.
Call
sams_init()
once before other helpers (except)
sams_present()
/
sams_page_count(),
which may probe . Without a SAMS card (or with emulator)
--mem 32k|none, sams_init()
returns -1 and lock/accessors fail closed.
Detection
and mapper
sams_present()
Nonzero if a SuperAMS-compatible mapper responds to a page-swap
probe.
sams_page_count()
Number of 4K pages (currently 256 for the 1MB configuration, or 0 if
absent).
sams_init()
Probes the card, writes the classic identity map for windows
>2000, >3000,
>A000–>F000, and enables MAP mode.
Returns 0 on success, -1 if no SAMS.
sams_map()
Maps page into the 4K CPU window whose high address
nibble is window_nibble
(0x2, 0x3,
or0xA–0xF).
sams_get()
Returns the page currently mapped at
window_nibble.
Fat
pointers
sams_ptr()
Builds a fat pointer from page and
offset (offset masked to 12 bits).
sams_page_of(/)
sams_offset_of()
Unpack a fat pointer.
sams_add()
Adds a signed byte delta, carrying across 4K page boundaries. Returns
SAMS_PTR_NULL if underflow would wrap below page
0.
Lock
windows
Two reserved windows (>C000 and>D000) hold locked pages.
>E000 is reserved for accessor scratch;
>F000 is left for the stack.
sams_lock()
Maps p's page into a free lock window (or reuses an
existing mapping of that page) and returns a near void
* into that window at p's offset. Nested locks
on the same page refcount. Returns NULL if both
slots are busy or SAMS is absent.
sams_unlock()
Drops one ref on p's page. When the refcount hits
zero the window is restored to its identity page.
Using the near
pointer after unlock is undefined (use-after-free).
Accessors
These map through >E000 (last-page
cache) and do not consume a lock slot. Prefer them for bulk or one-shot
traffic; prefer sams_lock() when many near-pointer
operations on the same object are needed.
RETURN
VALUES
sams_init() returns 0 or -1.
sams_lock() returns a near pointer or
NULL. Accessors that cannot map (no SAMS) read as
0xFF / ignore writes.
Fat
heap
sams_malloc() allocates from non-reserved
SAMS pages (reserved identity pages are 2, 3, A, B, F); pages behind windows
C/D/E are eligible . Chunks never cross a 4K page boundary in this phase
(max payload just under 4K). The allocator does not leave the object mapped;
use sams_lock() or the accessors to touch payload.
sams_get_free_heap() sums free-chunk bytes on the
fat freelist (including headers). Without a SAMS card these calls fail
closed (NULL / 0).
When a SAMS card is present, near
malloc(3) is clipped under
>C000 so lock windows never overlay the near
arena.
The packer also enforces that layout: any undefined
sams_* reference (or explicit)
--sams sets the SAMS near map so
.persistent_high / .data / .bss / heap fit in
>A000–BFFF (8K). Spilling into
>C000–EFFF is a pack
FATAL, not a silent hang under
sams_lock(). The ceiling is fixed ABI (matches libc
lock/accessor windows); it is not a project knob.
EXAMPLES
#include <sams.h>
if (sams_init() != 0)
/* plain 32K — no fat heap path */
;
unsigned char __sams *p = sams_malloc(64);
if (p) {
p[0] = 0xBE;
sams_free(p);
}
Optional sugar (SAMS_FAR,
sams_new(),
SAMS_WITH_NEAR()) lives in
<sams_far.h>. Tutorial and
porting notes: docs/sams_tutorial.md and
docs/sams_porting.md.
<debug.h> provides
host-assisted debugging and formatted trace output for TI-99/4A C programs
running in the Tidepod IDE debugger, with minimal impact in debug builds and
strictly zero code or data overhead in release builds.
Host-Evaluated
Logpoints (__dbg_printf)
Traditional printf(3) on
the TMS9900 consumes hundreds of bytes of stack/RAM, thousands of CPU cycles
per call, and VDP bandwidth. By contrast,
__dbg_printf()
performs no
formatting or I/O on the TI-99/4A CPU:
<debug> builds (without
NDEBUG): each
__dbg_printf() invocation emits a single 2-byte
NOP instruction in .text
to anchor the program counter, and records the format string and up to 8
argument variable/expression names into a non-allocatable ELF section
named .tms9900.logpoints. That metadata exists
only in the .debug ELF sidecar;
tms9900-elf-objcopy strips it out of the final
cartridge .bin. When the Tidepod debugger executes
the NOP, the host intercepts the PC, resolves each
named argument via DWARF debug symbols (registers, stack locals, globals,
or banked variables), formats the message on the host machine, and writes
it to the IDE's Debug Log panel.
<release> builds
(NDEBUG defined, which Tidepod sets automatically in
releaseCCFLAGS):
__dbg_printf() and
BRK() expand
to ((void)0). No NOP, no
strings, and no metadata are emitted.
__dbg_printf()
accepts 0 to 8 arguments after fmt. Standard
printf()
format specifiers (%d, %u,
%x, %04X,
%s, %c,
etc.) are supported directly without doubling
percent signs. Because arguments are evaluated by the host DWARF reader by
name rather than passed at runtime in registers, pass simple variable names
or expressions that correspond to inspectable symbols in the current scope,
and never rely on side effects (such as i++) inside
a __dbg_printf() argument list.
Soft
Breakpoints (BRK)
BRK()
emits a special zero-argument logpoint marker
(“__BRK__”) in debug builds. When the
Tidepod debugger hits a BRK() anchor during a Debug
session, it immediately pauses CPU execution and syncs the source editor and
register/watch views to that line. When running outside the debugger or on
real hardware, the anchor is a harmless 2-byte NOP;
in release builds (NDEBUG), it compiles to
nothing.
ANSI
Terminal Formatting Macros
The Tidepod Debug Log panel emulates an ANSI
color terminal. <debug.h>
defines string-literal macros that can be concatenated directly into
__dbg_printf() format strings:
Screen &
Cursor Control
DBG_RESET
(reset attributes), DBG_CLEAR (clear screen),
DBG_HOME (cursor to 1,1),
DBG_CLREOL (clear to end of line),
DBG_CLRLN (clear entire line),
DBG_GOTO(row,
col) (1-based cursor position),
DBG_UP(n),
DBG_DOWN(n),
DBG_RIGHT(n),
DBG_LEFT(n),
DBG_COL(n).
<profiler.h>
provides zero-overhead source annotations that feed the Tidepod IDE's
real-time Frame Profiler (the PRF) tab in the right-hand
Debugger panel . Including
<profiler.h> also includes
debug(3) (providing
__dbg_printf(and)
BRK()).
Unlike instrumentation that reads hardware timers or writes to
memory, these macros emit zero instructions and occupy
zero bytes of ROM or RAM. Instead, each macro emits a
unique global assembler label at the current program counter (PC):
__prof_frame_end_<n>
__prof_block_<RRGGBB>_<id>_start_<n>
__prof_block_<RRGGBB>_<id>_end_<n>
When a debug build is loaded in Tidepod, the
DWARF/ELF reader extracts these symbol addresses from the
.debug sidecar. As the emulator runs, it measures
exact TMS9900 clock cycles elapsed between each
PROF_BEGIN()
and
PROF_END()
pair, counts VDP vertical blanking interrupts between
PROF_FRAME_END()
markers to determine effective frame rate (60 Hz, 30 Hz,
20 Hz, etc.), and plots a 120-frame stacked cycle history against the
project's target FPS cycle budget (50,065 cycles per 60 Hz NTSC
frame). Clicking a block legend in the PRF tab jumps the
editor directly to the corresponding PROF_BEGIN()
line in source.
Macros
PROF_FRAME_END()
Marks the boundary of one logical game frame. Place this macro exactly
once per main-loop iteration, typically at the very top of the loop before
waiting for VBlank.
PROF_BEGIN(color,
id)
Marks the start of a timed code region named id
rendered in the IDE profiler with hex color
color.
PROF_END(color,
id)
Marks the end of the timed code region started by the matching
PROF_BEGIN(color,
id).
Annotation
Rules
color must be a bare 6-digit hexadecimal RGB
token (RRGGBB) with
no leading
0x or # (e.g.
4FC3F7, not0x4FC3F7).
id must be a bare C identifier (letters, digits,
underscores — no quotation marks or spaces).
Every PROF_BEGIN(color,
id) must be paired with a matching
PROF_END(color,
id) using the exact same color
and id tokens. The same
(color, id) pair may appear
multiple times in a frame; each expansion receives a unique assembler
suffix via %=.
Blocks may nest (e.g. a physics block inside an
outerupdate block), but must not partially
overlap.
Wrap your VBlank wait (e.g.
vdpwaitvint())
in its own block (conventionally grey, 808080) so
idle wait time is distinguished from active CPU work.
Recommended
Palette
Hex
Color
Hex
Color
4FC3F7
Light blue
81C784
Green
FFB74D
Orange
E57373
Red
BA68C8
Purple
FFD54F
Yellow
4DB6AC
Teal
F06292
Pink
808080
Grey (idle)
EXAMPLES
Annotate a 60 Hz game loop with idle, input, physics, and
render phases:
<f18a_gpu.h>
provides freestanding macros and memory-map constants for C translation
units compiled to run on the F18A or Pico9918 internal 100 MHz
TMS9900-compatible GPU coprocessor.
is compiled as an independent freestanding binary linked at VDP
address gpuBase with its own startup routine
(crt0_gpu.o) and packed into the cartridge as a
binary resource alongside a generated map header
(include/gpu_<stem>_map.h). The host CPU
uploads and starts the image via
rom_to_vram(3) and
f18a_gpu_host(3).
GPU
Memory Map Constants
The F18A GPU sees a flat 64 KB byte-addressed space
completely separate from the host TI-99/4A CPU bus:
F18A_GPU_VRAM_BASE
(0x0000u)
Start of the 16 KB VDP RAM window
(0x0000–0x3FFF) shared with the host VDP
ports. Host-loaded GPU code, stacks, and shared parameter mailboxes must
reside in this region.
F18A_GPU_GRAM_BASE
(0x4000u)
Start of the 2 KB GPU-private RAM
(0x4000–0x47FF) on classic F18A. Note:
standard host VDP address writes wrap at 16 KB
(0x3FFF), so the host cannot upload directly into
0x4000+ with
rom_to_vram();
only the GPU itself can read and write this region directly.
Read-only byte MMIO reporting the current raster scanline
(0–255).
F18A_GPU_BLANKING
(0x7001u)
Read-only byte MMIO whose LSB indicates horizontal/vertical blanking. Use
with care: in some emulators (e.g. JS99er) the blanking bit can be sticky
across frames; prefer
F18A_GPU_IDLE()
with a VR50 trigger for deterministic synchronization.
F18A_ECM3_P0,
F18A_ECM3_P1,
F18A_ECM3_P2
Byte offsets (0x0000,
0x0800, 0x1000) for the
three bitplanes of an Enhanced Color Mode 3 (8-color) pattern table when
VR29 tile plane size is set to 00 (2 KB per
plane).
Macros
F18A_GPU_IDLE()
Emits the TMS9900 IDLE instruction, suspending GPU
execution until the next GPU trigger configured in VDP Register 50 (HSYNC
or VSYNC) or until the host writes VR55.
F18A_GPU_MMIO8(addr)
Dereferences addr as a volatile
unsigned char in the GPU address space (VRAM, GPU RAM, palette RAM
at 0x5000, VDP registers
at0x6000, or status MMIO
at0x7000).
F18A_GPU_MMIO16(addr)
Dereferences even byte address addr as a 16-bit
big-endian volatile unsigned int.
Critical
GPU Coding Constraints
Never execute
LWPI: The F18A GPU workspace pointer is hardwired to
F18A_GPU_WS_BASE (0x4800).
Executing LWPI has no effect or undefined behavior
on F18A derivatives.
Register
R15 is the hardware call stack pointer: The F18A replaces standard
TMS9900 BLWP with hardware
CALL and RET instructions
that push and pop return addresses through R15.
Tidepod automatically compiles GPU translation units with
-ffixed-r15 and initializes
R15 to gpuStack in
crt0_gpu.o. Never clobber
R15 in inline assembly.
“not call host libc functions: Host libc
routines access host memory-mapped ports (>8800 /
>8C00) and cartridge banks (>6000)
that do not exist in the GPU address space. GPU TUs must be
self-contained.”
EXAMPLES
A minimal GPU routine that increments a palette entry on every
VSync trigger:
#include <f18a_gpu.h>
void main(void) {
for (;;) {
F18A_GPU_MMIO16(0x5000u) += 0x0011u; /* Palette 0 */
F18A_GPU_IDLE(); /* Wait for next VR50 trigger */
}
}
void f18a_gpu_load_at(unsigned
int vram_addr, const
unsigned char *src,
unsigned int len);
void f18a_gpu_start(unsigned
int entry_pc);
void f18a_gpu_stop(void);
void f18a_gpu_load_and_start(unsigned
int vram_addr, const
unsigned char *src,
unsigned int len,
unsigned int
entry_pc);
DESCRIPTION
The
<f18a_gpu_host.h> functions
run on the host TI-99/4A TMS9900 CPU to upload machine code into VDP RAM and
start or stop the F18A (or Pico9918) internal GPU coprocessor via extended
VDP registers VR54, VR55, and VR56.
Before calling any of these routines, the F18A must be unlocked
(writing 0x1C twice to VR57), which
ti_vdp_detect(3) performs
automatically when probing for an enhanced VDP.
All four routines are marked #pragma bank
persistent so they remain mapped in upper 32K RAM regardless of which
cartridge bank is selected at >6000.
f18a_gpu_stop()
Writes 0x00 to VDP Register 56, immediately
halting the GPU coprocessor if it is running and clearing any pending GPU
state.
f18a_gpu_start()
Writes the high byte of entry_pc to VDP Register 54
and the low byte to VDP Register 55. On the F18A, the write to VR55
latches the 16-bit program counter (VR54:VR55) and
immediately starts GPU execution at entry_pc.
f18a_gpu_load_at()
Copies len bytes from the CPU buffer
src into VDP RAM starting at byte address
vram_addr
(0x0000–0x3FFF) via
vdpmemcpy().
Use this when the GPU machine-code blob already resides in persistent CPU
RAM or the currently active ROM bank. When the GPU image is a Tidepod
banked resource (added with tidepod add ...
--gpu), prefer
rom_to_vram(3) with
unwrap(),
which handles multi-bank offset normalization automatically.
f18a_gpu_load_and_start()
Convenience wrapper that calls f18a_gpu_stop(),
uploads len bytes from src to
vram_addr via
f18a_gpu_load_at(), and starts the GPU at
entry_pc via
f18a_gpu_start().
Generated
GPU Map Headers
When a C file src/gpu_fx.c is added to a
Tidepod project with tidepod add src/gpu_fx.c --gpu
--gpu-base 0x3800 --gpu-stack 0x3FFE, the build generates
include/gpu_gpu_fx_map.h containing:
gpu_gpu_fx_entry:
Entry PC symbol (_gpu_start,
typically equal togpu_gpu_fx_base).
gpu_gpu_fx_end
and gpu_gpu_fx_size: End address and byte length
of the linked GPU image, plus addresses of any global mailbox variables
exported by the GPU translation unit.
EXAMPLES
Unlock the F18A via
ti_vdp_detect(3), upload a
packed GPU image from cartridge ROM into VRAM, and start it:
Appends at most n characters from
src onto dst, then writes a
terminating NUL. dst must have room for the existing
string, up to n new characters, and the NUL.
Copies at most n bytes from
src to dst. If
src is shorter than n, the
remainder of dst is filled with NULs. If
src is n bytes or longer,
dst is
not
NUL-terminated.
The
strstr()
function locates the first occurrence of the null-terminated string
needle in the null-terminated string
haystack.
RETURN
VALUES
If needle is an empty string,
haystack is returned; if needle
occurs nowhere in haystack,
NULL is returned; otherwise a pointer to the first
character of the first occurrence of needle is
returned.
The
strtok()
function is used to isolate sequential tokens in a null-terminated string,
str. These tokens are separated in the string by at
least one of the characters in sep. The first time
that strtok() is called, str
should be specified; subsequent calls, wishing to obtain further tokens from
the same string, should pass a null pointer instead. The separator string,
sep, must be supplied each time, and may change
between calls.
The
strtok()
function modifies its first argument by replacing delimiter characters with
null bytes.
RETURN
VALUES
The strtok() function returns a pointer to
the beginning of each subsequent token in the string, after replacing the
separator character following it with a null byte. When no more tokens
remain, a null pointer is returned.
Converts an uppercase letter to lowercase; returns c
unchanged otherwise.
toupper()
Converts a lowercase letter to uppercase; returns c
unchanged otherwise.
RETURN
VALUES
The classification functions return non-zero if the character
tests true and zero if it tests false. tolower() and
toupper() return the converted character or
c if no conversion applies.
The
isalpha()
function tests for any character for which
isupper(3) or
islower(3) is true. In the ASCII
character set, this includes the following characters (listed in their
numeric order):
A-Z
a-z
RETURN
VALUES
The isalpha() function returns zero if the
character tests false and returns non-zero if the character tests true.
The
isgraph()
function tests for any printing character except space. The graphical
characters are those with ASCII values 0x21
(‘!’) through 0x7E
(‘~’).
RETURN
VALUES
The isgraph() function returns zero if the
character tests false and returns non-zero if the character tests true.
The
isprint()
function tests for any printing character, including space. This is any
character for which iscntrl(3) is
false. The printable characters are those with ASCII values 0x20 (space)
through 0x7E (~).
RETURN
VALUES
The isprint() function returns zero if the
character tests false and returns non-zero if the character tests true.
The
tolower()
function converts an upper-case letter to the corresponding lower-case
letter. The argument must be representable as an unsigned
char or the value of EOF.
RETURN
VALUES
If the argument is an upper-case letter, the
tolower() function returns the corresponding
lower-case letter if there is one; otherwise, the argument is returned
unchanged.
The
toupper()
function converts a lower-case letter to the corresponding upper-case
letter. The argument must be representable as an unsigned
char or the value of EOF.
RETURN
VALUES
If the argument is a lower-case letter, the
toupper() function returns the corresponding
upper-case letter if there is one; otherwise, the argument is returned
unchanged.
calloc()
allocates space from the near heap for an array of
count objects, each of size
bytes, and initializes all allocated bytes to zero.
The near heap resides in high expansion RAM after
.bss when the project
heapSize (or linker
--defsym=__heap_size=N / packer--heap-size) is greater than zero; see
malloc(3) for arena layout and
configuration. For SuperAMS fat-pointer allocations, use
sams_calloc()
(see sams(3)).
RETURN
VALUES
calloc() returns a word-aligned pointer to
the zeroed allocation, or NULL on failure, overflow,
or when __heap_size is 0.
Both functions ignore status and enter an
infinite loop. There is no process model, no
atexit()
registry, and no stream flush on exit. Cartridge programs should normally
end
main()
with an endless loop instead of calling exit().
free()
releases a block previously allocated from the near heap by
malloc(3),
calloc(3), or
realloc(3) and coalesces adjacent
free chunks in constant time. If ptr is
NULL, no action is performed.
The near heap resides in high expansion RAM after
.bss when the project
heapSize (or linker
--defsym=__heap_size=N / packer--heap-size) is greater than zero; see
malloc(3) for arena layout and
configuration. For SuperAMS fat-pointer allocations, use
sams_free()
(see sams(3)).
These functions manage a near heap in high expansion RAM after
.bss. Native pointers remain 16-bit.
The arena is [_bss_end, _bss_end + N)
where N is the absolute linker symbol
__heap_size (C reads it as
(unsigned)&__heap_size), not a load from memory
. crt0 writes one free-chunk header when N is non-zero
(linker PROVIDE(__heap_size = 0)), overridden by
--defsym=__heap_size=N.
Project
reservation
Set heapSize in the
.project file (bytes). Tidepod passes
--heap-size to
tms9900-packer (so auto-promoted
.persistent_high) does not consume the arena and
--defsym=__heap_size to the linker. Default
0 means no heap (promotion stays aggressive;
malloc())
returns NULL.
Each allocated block has a 2-byte header (size in words,
free bit, prev_free bit). Free blocks also store a size footer so
free()
coalesces adjacent free chunks in constant time.
malloc() searches a LIFO free list only (first fit
with split).
Querying
free space
There is no POSIX API for “free heap bytes”. This
libc provides the glibc/BSD-shaped
mallinfo()
(not in POSIX.1). fordblks is free bytes in the arena
(including free-chunk headers).
get_free_heap()
returns the same value.
malloc_walk()
visits every chunk for debugging.
On a machine with SuperAMS present, the near arena
is clipped under >C000 so SAMS lock windows never
overlay
malloc()
blocks. Large allocations use
sams_malloc()
(see) sams(3).
heapSize should stay modest on SAMS carts;
the fat heap is the large store.
RETURN
VALUES
malloc(),
calloc(), and realloc()
return a word-aligned pointer, or NULL on failure or
when __heap_size is 0. free()
of NULL is a no-op.
realloc()
changes the size of the near-heap block pointed to by
ptr to size bytes, copying
existing contents up to the lesser of the old and new sizes when moving the
block. If ptr is NULL,
realloc() behaves like
malloc(size).
If size is 0, ptr is freed and
NULL is returned.
The near heap resides in high expansion RAM
after .bss when the project
heapSize (or linker
--defsym=__heap_size=N / packer--heap-size) is greater than zero; see
malloc(3) for arena layout and
configuration. For SuperAMS fat-pointer allocations, use
sams_realloc()
(see sams(3)).
RETURN
VALUES
realloc() returns a word-aligned pointer
to the resized block, or NULL on failure or when
__heap_size is 0 (leaving the original block unchanged
on allocation failure).
long strtol(const
char *str, char
**endptr, int
base);
unsigned long strtoul(const
char *str, char
**endptr, int
base);
int atoi(const
char *str);
long atol(const
char *str);
DESCRIPTION
long is 32-bit on this target.
base 0 means auto-detect (0x)
hex, leading 0 octal, else decimal. No
errno is set; overflow wraps modulo 2^32.
atoi()
is (int)strtol(str,
NULL, 10).
The header
<errno.h> declares the
modifiable global integer errno and defines standard
POSIX-shaped error constants for Tidepod libc.
Defined error constants:
EPERM
1 — Operation not permitted
ENOENT
2 — No such file or directory
EIO
5 — Input/output error
ENXIO
6 — No such device or address
EBADF
9 — Bad file descriptor
ENOMEM
12 — Cannot allocate memory
EACCES
13 — Permission denied
EEXIST
17 — File exists
EXDEV
18 — Cross-device link
ENODEV
19 — Operation not supported by device
ENOTDIR
20 — Not a directory
EISDIR
21 — Is a directory
EINVAL
22 — Invalid argument
ENFILE
23 — Too many open files in system
EMFILE
24 — Too many open files
ENOSPC
28 — No space left on device
EROFS
30 — Read-only file system
ENOTSUP
95 — Operation not supported
ETIMEDOUT
110 — Operation timed out
Native filesystem backends (chip floppy, FAT12, HFDC WDS) set
errno on failure in addition to recording a DSR status
code. Classic Level-3 PAB disk operations record their primary status via
stdio_last_error(3) and do
not always update errno.
Tidepod/tms9900-gcc libc is a
freestanding-friendly C library built as tiny translation units so the
packer can bank unused symbols away.
Provided: string and ctype; stdlib including near-heap
allocation when heapSize /
--heap-size is configured
(atoi, strtol,
rand, qsort,
exit, malloc,
free, calloc,
realloc); console printf /
putchar and
conio(3) cursor I/O on the VDP;
keyboard (cgetc, kbhit);
ti_vdp_detect(3) and
ti_text_mode(3) for
F18A/Pico9918 and 32/40/80-column text; banked ROM resource streaming via
resource_copy(3) /
rom_to_vram(3); F18A GPU host
loader and coprocessor macros via
f18a_gpu_host(3) and
f18a_gpu(3); zero-cost host
logpoints, soft breakpoints, and cycle profiling via
debug(3) and
profiler(3); SuperAMS mapper
helpers and fat pointers via sams(3)
(detect, map, lock, accessors, sams_malloc); mathf
via soft-float; disk fopen(3) family
(mode grammar with :df|:dv|:if|:iv|:pg), FDR probe
on existing files, PROGRAM as AU byte streams,
fcopy_path; catalog
ti_opendir(3), DSR unit discovery
ti_dsr_enum(3), metadata
(ti_stat, ti_protect,
ti_mkdir, ti_rmdir), and
remove(3) /
rename. Default
fopen() is
Level-3 PAB only; native chip / FAT / WDS / PROGRAM-AU backends are opt-in
via stdio_enable(3). Disk path
APIs copy path/mode into stack scratch at entry so banked callers remain
safe across trampolines (packer also hoists string literals for trampoline
TUs). Level-3 PAB VRAM placement uses
stdio_set_vdp_base(3)
(default 0x3000); HFDC Level-2 sector DMA uses
stdio_set_wds_vdp_buf(3)
(default 0x3DA8).
Disk
errors: after a failed fopen /
fcopy_path / remove /
ti_opendir, read
stdio_last_error(3) (DSR
status). errno is secondary and not always updated for
Level-3 PAB failures.
Not provided: asprintf.
Type model: int /
size_t are 16-bit; long is
32-bit; float is IEEE binary32 soft-float.
<sams_far.h> is an
optional convenience layer over
<sams.h>. It does not add a
second ABI; every macro expands to the named address space qualifier
__sams or to existing
sams_malloc(/)
sams_calloc(/)
sams_lock()
helpers.
Use it when application code wants shorter names or typed allocs.
Raw __sams is equally supported. Requires
-std=gnu99 (Tidepod default).
See docs/sams_tutorial.md and
resources/examples/sams_tutorial/.
return ASCII code of a string's first character (not implemented yet)
NAME
ASC — return ASCII
code of a string's first character (not implemented yet)
SYNOPSIS
ASC(string$);
DESCRIPTION
UNIMPLEMENTED — not available in the current XB
compiler or libxb.
The classic XB
ASC() function
would return the ASCII code (0–255) of the first character of
string$. It is not recognized by the frontend today: a
call such as ‘ASC(S$)’ is parsed as an
array reference and will not compile as a builtin.
The CALLCHAR()
statement redefines the visual representation of one or more characters.
char_code is the starting ASCII character code to
redefine (typically 32–143). pattern$ must be a
compile-time hexadecimal string literal where each 16 hex digits (8 bytes)
define one 8×8 pixel grid, MSB-left from top row to bottom row.
Multi-character definitions up to 512 hex digits (32 consecutive
characters starting at char_code) are supported;
partial 8-byte blocks are zero-padded. In
‘libxb’, patterns are written to both
the VDP Pattern Descriptor Table
(‘0x0800’) and the Sprite Pattern
Table (‘0x1800’).
The CALLCHARSET()
statement restores the default TI-99/4A font patterns for ASCII characters
32 through 127 (character sets 1 through 12, including uppercase and
lowercase letters) in the VDP Pattern Descriptor Table
(‘0x0800’), erasing any custom
definitions created by CALLCHAR()
for those characters.
The CALLCLEAR()
statement clears the 32×24 screen by filling the 768-byte VDP Name
Table with the space character (ASCII 32) and resets the cursor to the
top-left corner. In ‘libxb’,
CALLCLEAR()
also clears all hardware sprites (writes
‘0xD0’ to the Sprite Attribute List at
‘0x0380’ and resets sprite motion
state).
define foreground and background colors for a character set
NAME
COLOR — define
foreground and background colors for a character set
SYNOPSIS
CALLCOLOR(character_set,
foreground, background);
DESCRIPTION
The CALLCOLOR()
statement assigns a foreground and background color to a specific character
set. The TI-99/4A divides its 256 characters into 32 sets of 8 characters
each.
character_set must be between 1 and 14 (or
up to 32, depending on graphics mode). foreground and
background must be colors from 1 to 16.
DELSPRITE — delete
a specific sprite or all active sprites
SYNOPSIS
CALLDELSPRITE((#no
| ALL));
DESCRIPTION
The CALLDELSPRITE()
statement removes sprites from the screen. Passing a sprite number removes
only that sprite. Passing ALL removes all currently
active sprites.
DISPLAY AT — print
text at a specific screen location
SYNOPSIS
DISPLAY AT(row, col) [SIZE(n)]:expr
CALLDISPLAY_AT(row,
col, text$);
DESCRIPTION
The DISPLAYAT()
statement positions the text cursor at row
(1–24) and col (1–28) and prints the
expression following the colon (‘:’).
In matching classic TI Extended BASIC's 28-column text window,
col is offset by +2 columns on the 32-column hardware
screen (so column 1 maps to screen column 3).
If the optional
SIZE(n) clause is given, the
output field is padded or truncated to n characters;
without SIZE, the remainder of the 28-column row is
cleared before printing.
Numeric expressions are formatted via
xb_itoa();
floating-point values are truncated to integers when formatted by
DISPLAYAT().
The subroutine form CALLDISPLAY_AT(row,
col, text$) is also supported.
DISTANCE — compute
the squared distance between two sprites
SYNOPSIS
CALLDISTANCE(#sp1,
#sp2, var);
DESCRIPTION
The CALLDISTANCE()
statement calculates the squared Euclidean pixel distance
(dy*dy + dx*dx) between sprite
#sp1 and sprite #sp2, clamped to
‘32767’ on 16-bit signed overflow, and
stores the result in var.
Note: The 4-argument pixel-coordinate form
‘CALL DISTANCE(#sp1, row, col, var)’
is not yet implemented.
The CALLHCHAR()
statement places character char_code at
row (1–24) and col
(1–32). If the optional count is provided
(default 1), it repeats the character horizontally to the right
count times, wrapping at column 32 to column 1 of the
next row (and wrapping from row 24, column 32 back to row 1, column 1).
In classic TI Extended BASIC, CALLINIT()
initializes the 32K memory expansion for assembly language subprograms
loaded via CALLLOAD().
In compiled ‘libxb’ programs,
CALLINIT()
is accepted for source compatibility and performs runtime state
initialization (no-op when hardware and VDP state are already initialized by
the startup code).
The CALLJOYST()
statement reads the directional status of joystick
unit (1 or 2). return_x and
return_y are populated with -4, 0, or 4 depending on
the joystick's deflection.
The CALLKEY()
statement reads the keyboard or joystick inputs without halting the program.
unit defines which hardware to scan:
0
Console keyboard
1
Joystick 1
2
Joystick 2
3
Left side of split keyboard
4
Right side of split keyboard
5
Pascal keyboard mode
return_key is populated with the ASCII
keycode of the pressed key (or 255 if none).
return_status is populated with 1 if a new key was
pressed, -1 if the same key was held, or 0 if no key is pressed.
MOTION — update
the row and column velocities of a sprite
SYNOPSIS
CALLMOTION((#no,
rv, cv));
DESCRIPTION
The CALLMOTION()
statement changes the vertical and horizontal velocities of sprite
#no (1–32). rv is the
signed row velocity and cv is the signed column
velocity (-128 to 127).
In ‘libxb’, sprite positions
are tracked in 12.4 fixed-point and advanced on each
vsync(3xb) call: a velocity of
‘16’ moves the sprite 1 pixel per
frame at 60 Hz (a velocity of ‘1’
moves 1/16 pixel per frame).
The CALLPOKE()
statement writes one 16-bit word val to CPU address
address.
This is not the classic multi-byte XB form. Only a single
word is written; extra values are not stored sequentially.
CALLLOAD() is not
an alias and is unimplemented; see
load(3xb).
CALLRND()
stores a pseudo-random floating-point value in var in
the half-open range [0.0, 1.0] (matching classic TI Extended BASIC RND). The
target variable var must be a floating-point variable
(an identifier without a ‘%’ or
‘$’ suffix).
The expression form ‘RND’
uses the same generator and returns that value directly:
‘X = RND * 10’. It does not take
arguments. ‘RANDOMIZE’ is
unimplemented.
‘INT(expr)’ is a numeric
builtin that truncates toward zero (the C cast to int). Classic TI
‘INT’ floors negative values; positive
results match.
Requires float mode (-mfloat-ieee) or
-mfloat-fixed.
extract a substring from a string (not implemented yet)
NAME
SEG$ — extract a
substring from a string (not implemented yet)
SYNOPSIS
SEG$(string$,
position, length);
DESCRIPTION
UNIMPLEMENTED — not available in the current XB
compiler or libxb.
The classic XB
SEG$()
function would extract a substring from string$
starting at 1-indexed position for up to
length characters. It is not recognized by the
frontend today.
The CALLSOUND()
statement plays up to four simultaneous sound channels (up to three tone
channels and one noise channel) on the SN76489 sound chip.
duration is the playback time in
milliseconds. A negative duration starts asynchronous playback in the
background without halting the program; asynchronous sound duration is
advanced on each vsync(3xb)
tick.
freq1 ..freq4 specify
frequencies in Hertz (110–44733) for tone channels. Values from -1 to
-8 in any frequency slot configure the SN76489 noise generator instead of a
tone channel.
vol1 ..vol4 specify
volume attenuation from 0 (loudest) to 30 (silent).
SOUND_LIST — play
an asynchronous VDP/ROM sound list
SYNOPSIS
CALLSOUND_LIST(@label);
DESCRIPTION
The CALLSOUND_LIST()
statement starts asynchronous playback of a standard TI-99/4A byte-stream
sound list located at @label (defined with the
‘BYTES’ directive).
Each entry in a sound list consists of a byte count
N, followed by N bytes written
to the SN76489 sound generator port
(‘0x8400’), followed by a duration
byte in 1/60-second ticks (a byte count of
‘0’ terminates the sound list). The
sound list is advanced automatically on each
vsync(3xb) tick until completion or
until stopped with
sound_stop(3xb).
stop active asynchronous sound or sound list playback
NAME
SOUND_STOP — stop
active asynchronous sound or sound list playback
SYNOPSIS
CALLSOUND_STOP();
DESCRIPTION
The CALLSOUND_STOP()
statement immediately halts any active asynchronous
sound(3xb) or
sound_list(3xb) playback and
mutes all four SN76489 sound channels (writing attenuation
‘0x9F’,
‘0xBF’,
‘0xDF’, and
‘0xFF’ to the sound chip).
The CALLSPRITE()
statement creates a hardware sprite. #no is the sprite
number (1-32). char is the ASCII character code to use
for its graphics. color is the sprite's color (1-16).
r and c are the pixel
coordinates on screen (1-256). rv and
cv are optional row and column velocities for
automotion (-128 to 127). In ‘libxb’,
sprite positions are tracked in 12.4 fixed-point and advanced on each
vsync(3xb) call, so a velocity of
‘16’ moves 1 pixel per frame at 60 Hz
(‘1 = 1/16
pixel/frame’).
convert numeric value to string (not implemented yet)
NAME
STR$ — convert
numeric value to string (not implemented yet)
SYNOPSIS
STR$(number);
DESCRIPTION
UNIMPLEMENTED — not available in the current XB
compiler or libxb.
The classic XB
STR$()
function would convert a numeric value to its string representation. It is
not recognized by the frontend today. (Numeric values can be shown with
DISPLAY AT, which uses xb_itoa internally).
The CALLVCHAR()
statement places character char_code at
row (1–24) and col
(1–32). If the optional count is provided
(default 1), it repeats the character vertically downward
count times, wrapping from row 24 to the top (row 1)
of the next column (and from column 32 back to column 1).
The CALLVDPMEMCPY()
statement copies count bytes from the ROM or CPU data
block at @label (defined with the
‘BYTES’ directive) into VDP memory
starting at the 14-bit address vdp_addr.
This is a ‘libxb’ extension
for fast bulk transfers of pattern tables, tile maps, and sprite graphics
without per-byte BASIC loop overhead.
VDPMEMSET — fill a
block of VDP RAM with a byte value
SYNOPSIS
CALLVDPMEMSET(vdp_addr,
byte_val, count);
DESCRIPTION
The CALLVDPMEMSET()
statement fills count consecutive bytes of VDP memory
starting at the 14-bit address vdp_addr with the 8-bit
value byte_val (0–255).
halt execution until the next VDP vertical blanking interrupt
NAME
VSYNC — halt
execution until the next VDP vertical blanking interrupt
SYNOPSIS
CALLVSYNC();
DESCRIPTION
The CALLVSYNC()
statement synchronizes program execution with the screen refresh rate (60Hz
NTSC / 50Hz PAL).
This statement is
new to this Extended
Basic compiler and libxb. In compiled programs, you
must call
CALLVSYNC()
inside your main game loops. It is responsible for processing background
tasks, including:
Sprite automotion (CALL MOTION)
Asynchronous sound updates (CALL SOUND with negative durations)
XB BASIC DATA, READ, RESTORE, and BYTES directives
NAME
xb-data — XB BASIC
DATA, READ, RESTORE, and BYTES directives
DESCRIPTION
Inline data storage and retrieval.
DATA
val1, val2, ...
Store constant values in a program-wide data pool.
DATA
10,20,30,"HELLO",42
READ
var1, var2, ...
Read the next value(s) from the DATA pool into variables.
‘READ’ supports integer
(‘%’) and string
(‘$’) variables (reading into
floating-point variables is not yet supported).
READ X%,Y%,Z%,MSG$,N%
RESTORE
[@label | line]
Reset the DATA read pointer to the beginning of the data pool, or
to the first ‘DATA’ statement at or
after the specified @label or line number.
RESTORE
RESTORE @LEVEL2_DATA
BYTES
val, val, ...
(Extension)
Define raw binary data bytes under a label. Values are 8-bit (0–255
or >00–>FF). Used with CALL VDPMEMCPY for bulk VDP
transfers.
Multiple BYTES lines under the same label are concatenated.
DATA
ENCODING
The compiler emits all
‘DATA’ items as an array of C string
literals (__xb_data_pool[]) indexed by a runtime read
cursor (__xb_data_ptr). String variables receive the
literal pointer directly; integer
(‘%’) variables parse the string entry
at runtime via
xb_atoi().
PARTIAL — named math functions (ABS, SGN, SQR, SIN,
...), ‘PI’, and
‘RANDOMIZE’ are not implemented.
‘INT(expr)’ truncates toward zero.
Expression ‘RND’ returns the same value
as rnd(3xb). Operators, comparisons, and
‘AND / OR’ work; unary
‘NOT’ does not. For random floats use
expression ‘RND’ or
rnd(3xb) (CALL RND).
Float arithmetic requires float mode
(-mfloat-ieee) or
-mfloat-fixed.
ABS(x),
SGN(x), SQR(x)
Unimplemented. Would return absolute value, sign
(-1/0/1), and square root.
INT(x)
Truncates x toward zero and returns an
integer. Positive values match classic TI
‘INT’; negative values differ (classic
INT floors).
RND
Expression form returns a float in [0.0, 1.0] using the same
generator as ‘CALL RND(var)’
(rnd(3xb)).
‘RANDOMIZE’ is unimplemented.
XB BASIC screen, color, and character definition commands
NAME
xb-screen — XB
BASIC screen, color, and character definition commands
DESCRIPTION
Screen initialization, color table manipulation, and character
pattern definition for the TI-99/4A VDP in Graphics I mode.
CALL
CLEAR
Clear the screen (fill name table with spaces), reset the cursor
position, and clear all hardware sprites (writes
‘0xD0’ to the Sprite Attribute List at
‘0x0380’ and resets sprite motion
state).
CALL CLEAR
CALL
SCREEN(color)
Set the screen background color. color is a
VDP color code (1–16):
1 Transparent
5 Dark Blue
9 Medium Red
13 Dark Green
2 Black
6 Light Blue
10 Light Red
14 Magenta
3 Medium Green
7 Dark Red
11 Dark Yellow
15 Gray
4 Light Green
8 Cyan
12 Light Yellow
16 White
CALL SCREEN(2)
CALL
COLOR(set, fg, bg)
Set the foreground and background colors for a character set. Each
set controls 8 consecutive character codes:
Set
Characters
(ASCII)
1
32–39
2
40–47
...
...
14
136–143
fg and bg are VDP
color codes (1–16).
CALL COLOR(2,16,2)
CALL
CHAR(code, pattern)
Redefine the pixel pattern starting at character
code (32–143). pattern is
a compile-time hexadecimal string literal where each 16 hex digits represent
8 bytes (8×8 pixels). Multi-character definitions up to 512 hex
digits (32 consecutive characters) are supported; partial 8-byte blocks are
zero-padded.
CALL
CHAR(42,"007E424242427E00")
Each hex pair represents one row, MSB–left. Patterns are
written to both the Pattern Descriptor Table
(‘0x0800’) and the Sprite Pattern
Table (‘0x1800’).
TI-99/4A
NOTES
The TI-99/4A VDP operates in Graphics I mode with 32 character sets.
CALL CLEAR writes 0x20 (space) to the entire 768-byte name table.
Color table is 32 bytes: one byte per set (high nybble = fg, low =
bg).
Pattern table is 2048 bytes: 8 bytes per character × 256
characters.
PARTIAL — ‘CALL
SOUND’ supports multiple channels. ‘CALL
SAY’ is not supported. ‘CALL
SOUND_LIST’ and ‘CALL
SOUND_STOP’ are also implemented in
‘libxb’ (see
sound_list(3xb) and
sound_stop(3xb) ).
Implemented.
Play tones on up to three tone channels plus noise. Additional
freq / vol pairs select further channels (up to four
total).
duration is in milliseconds (converted to
~60Hz frames; minimum 1 frame). Negative duration starts asynchronous
playback.
freq is the frequency in Hz. If
freq is 0, only the duration timer is set (silence).
Negative freq selects noise types on the noise
channel.
vol is the volume using TI Extended BASIC
convention: 0 = loudest, 30 = silent (mapped to SN76489 attenuation by
dividing by 2).
CALL SOUND(200,440,2)
CALL
SOUND(500,262,2,330,4,392,6)
CALL
SAY(word)
Unimplemented.
Speech synthesis is not supported in the current runtime or emulator.
CALL SAY("HELLO")! does not
work
TIMER
Sound duration is managed by the VBlank / sound tick path. The
tick counter decrements each frame (~60Hz); when it reaches zero, channels
are silenced. One tick ∼ 17ms (1/60s).
EXAMPLES
! Play a simple tone
CALL SOUND(500,262,2) ! Middle C for ~500ms
! Play descending tones
FOR I%=1 TO 5
CALL SOUND(200,440-I%*50,0)
NEXT I%
XB BASIC sprite creation, movement, and collision commands
NAME
xb-sprites — XB
BASIC sprite creation, movement, and collision commands
DESCRIPTION
Hardware sprite management via the TMS9918A VDP. Up to 32 sprites
are supported, numbered #1 through #32.
CALL
SPRITE(#id, pat, color, y, x [, vy, vx])
Create or update sprite #id with pattern
pat, VDP color color, at pixel
position (y, x), and optional
initial velocity (vy, vx).
CALL
SPRITE(#1,33,7,96,128)
Pattern numbers refer to character codes. In 8×8 magnify
mode, each sprite uses one character pattern; in 16×16 mode, four
consecutive character patterns are used.
CALL
DELSPRITE(#id)
Delete sprite #id from the sprite table
(writes ‘0xC0’ / Y=192 to move it
off-screen and clears its velocity).
CALL DELSPRITE(#1)
Use ‘CALL DELSPRITE(ALL)’ to
delete all sprites.
CALL
MOTION(#id, vy, vx)
Set the velocity of sprite #id.
vy is vertical speed (positive = down), and
vx is horizontal speed (positive = right). Values
range from -128 to 127 in 12.4 fixed-point units
(‘16 = 1 pixel/frame at 60
Hz’). The sprite position is updated on each
‘CALL VSYNC’.
CALL MOTION(#1,0,64)
CALL
MAGNIFY(n)
Set the sprite magnification mode for all sprites:
Value
Size
Patterns
1
8×8
1 char each
2
8×8 doubled
1 char each
3
16×16
4 chars each
4
16×16 doubled
4 chars each
CALL MAGNIFY(3)
CALL
PATTERN(#id, pat)
Change the pattern of sprite #id to
pat without affecting position or color.
CALL PATTERN(#1,37)
CALL
LOCATE(#id, y, x)
Move sprite #id to absolute pixel position
(y, x).
CALL LOCATE(#1,0,0)
CALL
POSITION(#id, y, x)
Read the current position of sprite #id into
variables y and x.
CALL
POSITION(#1,SY%,SX%)
CALL
COINC(#id1, #id2, tol, flag)
Check if two sprites overlap within tol
pixels. flag is set to -1 (true) if they coincide, 0
otherwise.
CALL COINC(#1,#2,8,HIT%)
Use ‘CALL COINC(ALL,flag)’
to check if any two active sprites overlap.
CALL
DISTANCE(#id1, #id2, dist)
Calculate the squared distance between two sprites.
dist receives (dy*dy + dx*dx).
CALL DISTANCE(#1,#2,D%)
SPRITE
LIMITS
The TMS9918A supports up to 32 sprites, but only 4 per scanline.
Sprites with lower IDs have higher display priority.
Y position 208 (0xD0) terminates sprite processing for all subsequent
sprites.
Sprite coordinates are in pixels: Y 0–191, X 0–255.
xb-tiles — XB
BASIC tile placement and reading commands
DESCRIPTION
Place or read characters on the 32×24 screen grid. Row
values are 1–24, column values are 1–32.
CALL
HCHAR(row, col, char [, count])
Place character char at position
(row, col) horizontally. If
count is specified, repeat the character
count times, wrapping to the next row at column
32.
CALL HCHAR(1,1,42,32)
CALL
VCHAR(row, col, char [, count])
Place character char at position
(row, col) vertically. If
count is specified, repeat downward, wrapping to the
next column at row 24.
CALL VCHAR(1,1,42,24)
CALL
GCHAR(row, col, var)
Read the character code at position (row,
col) into integer variable
var.
CALL GCHAR(12,16,C%)
ADDRESSING
Screen positions map to VDP Name Table addresses:
addr = (row - 1) * 32 + (col -
1)
Row 1 is the top row, column 1 is the leftmost column. The name
table starts at VDP address 0x0000 by default.
EXAMPLES
! Draw a border around the screen
CALL HCHAR(1,1,42,32) ! Top row
CALL HCHAR(24,1,42,32) ! Bottom row
CALL VCHAR(2,1,42,22) ! Left column
CALL VCHAR(2,32,42,22) ! Right column
XB BASIC VDP memory access and bulk transfer commands
NAME
xb-vdp — XB BASIC
VDP memory access and bulk transfer commands
DESCRIPTION
Direct VDP (Video Display Processor) memory access for bulk data
transfers, pattern loading, and low-level hardware control. These are
extensions to standard TI Extended BASIC.
‘CALL PEEK’ and
‘CALL POKE’ below read/write a 16-bit
CPU word, not a single byte. Use ‘CALL PEEKB /
POKEB’ for bytes.
CALL
VDPMEMCPY(addr, label, len)
Copy len bytes from a BYTES data block
labeled label to VDP memory starting at address
addr.
CALL
VDPMEMCPY(>0800,@PATTERN_DATA,64)
addr can be specified in decimal or hex with
the ‘>’ prefix.
label must reference a
‘BYTES’ data block defined in the
source.
CALL
VDPMEMSET(addr, byte, len)
Fill len bytes of VDP memory starting at
addr with the value byte.
CALL
VDPMEMSET(>0000,32,768)
CALL
VDPREAD(addr, var)
Read a single unsigned byte from VDP memory address
addr into variable var. See
vdpread(3xb) and
peekv(3xb).
CALL
VDPREAD(>0000,CH%)
CALL
PEEKB(addr, var)
Read a single unsigned byte (0–255) from CPU memory address
addr into variable var. See
peekb(3xb).
CALL PEEKB(>8375,K%)
CALL
POKEB(addr, val)
Write a single byte val (0–255) to
CPU memory address addr. See
pokeb(3xb).
CALL
POKEB(>8300,>FF)
CALL
PEEK(addr, var)
Read one 16-bit word from CPU memory address
addr into variable var. See
peek(3xb).
CALL PEEK(>8300,V%)
CALL
POKE(addr, val)
Write 16-bit word val to CPU memory address
addr. See
poke(3xb).
CALL
POKE(>8300,>1234)
VDP
MEMORY MAP
The default VDP memory layout for Graphics I mode:
Address
Size
Contents
>0000
768
Name Table (32×24 screen)
>0300
32
Color Table (1 byte per set)
>0380
128
Sprite Attribute Table (32 × 4 bytes)
>0800
2048
Pattern Table (8 bytes per char)
>1800
2048
Sprite Pattern Table
BYTES
DIRECTIVE
The ‘BYTES’ directive
defines raw binary data blocks in ROM:
Each value is a single byte (0–255 or
>00–>FF). Labels referenced by VDPMEMCPY must use the
‘@’ prefix.
EXAMPLES
! Load custom character patterns from ROM
@MY_CHARS:
BYTES >00,>7E,>42,>42,>42,>42,>7E,>00
BYTES >18,>3C,>7E,>FF,>FF,>7E,>3C,>18
CALL VDPMEMCPY(>0800+42*8,@MY_CHARS,16)
Tidepod ships an agent skill: a set of Markdown files that tells AI coding assistants how to work on a
Tidepod project. Without it, assistants tend to edit the generated Makefile, invent compiler or packer flags, and
call library functions that don't exist. With it they use the CLI, the real build and the real emulator options.
Where it is
tidepod new copies the skill into every new project, in the two locations most assistants look for
project skills:
The master copy is in the Tidepod install under resources/agent-skills/ti99-tidepod-gamedev/. For
existing projects, copy that directory into the project yourself. If your assistant uses another location, copy or
link it there; the files are plain Markdown with a YAML header.
Contents
File
What it covers
SKILL.md
When to use the skill, the hard rules, the canonical new/add/build/run loop, CLI table, emulator and GDB usage, PEB/disk configuration, hang forensics with --dump-regs, headless verification, banking and F18A essentials, a pitfall checklist, and pointers to the example projects.
reference.md
Memory map, project-file details (disk mounts, PEB cards), packer outputs and options, VDP and F18A notes, current emulator flags, tool paths, debug/profiler helpers.
examples.md
Short recipes: new banked cartridge, persistent code plus a resource, F18A GPU image, headless GDB session, disk/EA5, and which example project to open for what.
When an assistant uses it
The skill's description makes assistants load it for anything involving Tidepod projects: building banked
cartridges, EA5 disks or XB projects, VDP/F18A graphics, packer or banking problems, code placement, emulator
debugging, and adding or removing sources and resources.
Keeping it current
The skill is versioned with Tidepod. After updating Tidepod, refresh the copies in your projects from
resources/agent-skills/ so assistants see the current CLI and emulator options. If you have project
rules of your own, put them in a separate file rather than editing the skill, so they survive the refresh.
These are the rules the skill gives to assistants. They are good rules for humans too; if an assistant breaks one,
point it at the skill.
Hard rules
Never edit the generated Makefile. It starts with # [GENERATED BY TI-99 IDE - DO NOT EDIT MANUALLY] and is overwritten by the next sync. Extra rules go in Makefile.custom.
Change the build list only with the CLI: tidepod add, tidepod remove, or edit srcFiles in the .project file and run tidepod sync. In particular, never add a resource by editing RESOURCE_OBJS.
Build with make / make debug. There is no tidepod build.
Prefer the Tidepod CLI over hand-made packer or linker flags.
tidepod run starts the stand-alone emulator, not the IDE. It uses the layered configuration (Preferences, project "emu" block, disk mounts). For headless runs, call ti994a-emu directly.
No large local variables. The stack is small. Buffers of about 64 bytes or more (sector buffers, file records, tables) must be static or global, never locals.
Canonical loop
Terminal
tidepod new mygame --type banked --path ./mygame
cd mygame
# edit main.c, tidepod add new files / resources
tidepod sync && make debug
tidepod run --debug # emulator + GDB on :3333
# verify boot the way a user sees it (no --autorun)
ti994a-emu --cart mygame.rpk --f18a --headless \
--keys "WAIT:300 SPACE WAIT:120" --screenshot-at 450 --frames 480
Pitfall checklist
Before handing over a build, the skill has the assistant check:
VR30 set after unlocking the F18A.
Interrupt / vsync strategy is intentional.
Programs using disk files: scratchpad area starts at 0x8380 or higher.
No source file larger than one bank.
Makefile and RESOURCE_OBJS never edited by hand.
No edits to generated packer, resource or GPU map files.
make debug + --gdb used for debugging rather than a home-made debug protocol.
Boot verified without --autorun, using --keys and --screenshot-at.
bank_report.json headroom, trampolines and stack depth compared with the last good build.