Appendix A
Find a call
A disk file starts at sector zero. A physical floppy starts numbering its sectors at one. Which number belongs in a C call? Pick the job below, or choose the header already at the top of your source file. Each symbol has its own bookmark. The book’s Search also accepts an exact spelling such as decb_readSector.
For declarations, byte means an eight-bit unsigned value and word a 16-bit unsigned value. An asterisk identifies an address in the guest. When an entry asks for a writable buffer, the caller owns the storage and keeps it alive until the operation finishes.
Start with a job
- Browse the SDC card · sdc_list_begin
- Switch a data disk · sdc_mount
- Read a line from a guest disk file · fgets
- Split a record, then split one of its fields · strtok_r
- Read records or exact binary bytes · fread
- Write a numbered observation directly to a file · fprintf
- Write a record and make it readable on disk · fflush
- Retry a refused save on the same disk · clearerr
- Keep a backup before installing a replacement · rename
- Delete a closed file from a guest disk · remove
- Read a disk sector from an open file · decb_readSector
- Read a physical track and sector · readDiskSector
- Open a named floppy file · decb_openSectorFile
- Report a missing file · DECB_ERR_NOT_FOUND
- Exchange a cassette file with BASIC · vcc_tape_read_line
- Send a report to the TP-10 · vcc_printer_printf
- Show a radar reading with fixed decimal places · vcc_fixed
- Print a greeting · printf
- Check a number typed at the keyboard · strtoul
- Read a signed decimal or hexadecimal value · strtol
- Measure a string · strlen
- Change text width · width
- Color a text cell · attr
- Fit a name in a bounded buffer · memcpy
- Poll a key · inkey
- Plot a 16-color pixel · Primitive_setPixel320x16
- Copy terrain from banked RAM · bank_read
- Show a completed graphics frame · gime_present
- Fire once on a joystick press · input_sample
- Read a joystick · Joystick_getAxisValues
- Play a tone · Player_sound
- Give an invented name its own pronunciation · ssc_store_allophones
- Build a fading landing alert · ssc_store_enveloped_tone
- Speak a phrase · ssc_say
- Send stereo samples · orch90_play
- Keep stereo playing while a game runs · orch90_start
- Format text safely into a buffer · snprintf
- Print in a graphics buffer · initHiResTextScreen2
- Reserve a bounded guest heap · vcc_heap_init
- Grow an allocation · realloc
- Allocate from a pool · MemPool_alloc
- Trace a grid path · astar_searchGrid
- Deal a card · pickCardFromDeck
- Edit a text buffer · Ebitor_processKey
Start with a header
Choose the feature’s header to see its public names and build setting. Two libraries can choose the same spelling. For example HiresTxt and CardGame each supply a moveCursor routine for their own renderer.
- vcc/decimal.h · Format a CoCo BASIC floating-point number into a bounded field.
- vcc/cassette.h · Write and read named text files on cassette.
- vcc/printer.h · Send formatted text to the serial printer.
- vcc/sdc.h · Browse the SDC card and choose the image in either drive.
- vcc/bank.h · Keep assets in four reserved CoCo 3 memory banks.
- vcc/input.h · Sample a joystick and recognize presses, holds and releases.
- vcc/gime.h · Draw on a hidden CoCo 3 graphics page and display the completed frame.
- vcc/ssc.h · Speak a phrase or play a tone through the Speech/Sound Cartridge.
- vcc/orch90.h · Play stereo sample frames through Orchestra-90.
- ctype.h · Classify ASCII bytes and convert letter case.
- errno.h · Check whether a number was outside the conversion range.
- limits.h · Look up the ranges of CMOC integer types.
- stddef.h · Use CMOC sizes, member offsets and pointer differences.
- stdint.h · Use explicit 8-, 16- and 32-bit types and limits.
- stdio.h · Read a guest disk file or format text into a bounded buffer.
- stdlib.h · Convert a number from text or manage a bounded guest heap.
- string.h · Split a string into tokens, compare text or move bytes.
- 8-bit-wide-font.h · Find the game renderer’s eight-pixel-wide glyph data.
- assert.h · Check program assumptions at build time and while running.
- astar.h · Find a path across a rectangular grid and walk back from the goal.
- cardgame.h · Build a deck, select a card and render game graphics.
- catmull-rom.h · Interpolate a smooth path through a sequence of points.
- clipping.h · Clip a line to a rectangle before drawing it.
- cmoc.h · Console output, strings, memory, arithmetic and callbacks.
- coco.h · BASIC display modes, keys, joysticks, sound and timing.
- compiled-cards.h · Find the precomputed suit symbols, ranks and edges used for drawing cards.
- decbfile.h · Read and write named Disk BASIC files, sectors and fixed-size records.
- disk.h · Read a Disk BASIC file or address a physical floppy sector.
- Drawer.h · Move a drawing pen and run a DRAW script in a graphics buffer.
- dskcon-standalone.h · Operate the floppy controller while the Disk BASIC ROM is banked out.
- Ebitor.h · Maintain an editable text buffer and a cursor through terminal callbacks.
- font4x8.h · Find the narrow four-pixel glyph data for HiresTxt.
- font5x8.h · Find the five-pixel glyph data for HiresTxt.
- gimeterm.h · Implement terminal operations using the CoCo 3 GIME hardware text screen.
- hirestxt.h · Render text and a cursor into a graphics screen.
- Joystick.h · Sample analog axes and detect joystick button presses.
- Keyboard.h · Poll a guest keyboard with CoCo 3 control, function and navigation keys.
- lores.h · Read or change the color of a low-resolution semigraphics block.
- Painter.h · Flood-fill a connected area with caller-owned scratch space.
- Player.h · Generate music with the CoCo sound DAC and interrupt timer.
- pmode4game.h · Set up the game buffer, graphics cursor, text and keyboard interaction.
- Primitive.h · Plot one pixel or draw lines and shapes using a buffer-specific callback.
- semigr.h · Manipulate legacy semigraphics pixel buffers.
- setjmp.h · Save and restore a nonlocal return point within a still-active call.
- sg4term.h · Implement terminal operations on a traditional CoCo character screen.
- SquareWaveGenerator.h · Produce square-wave samples for a chosen amplitude and period.
- stdarg.h · Pass a variable-length argument list through your own function.
- Trig.h · Use 15-degree sine and cosine increments without floating point.
- Window.h · Describe the guest text window used by the Ebitor terminal adapters.
- wydealloc.h · Manage variable-size allocations inside a buffer your program owns.
Which edition do I have?
This development edition indexes CMOC 0.1.101 targeting CoCo BASIC. Its C declarations were checked against the reconciled runtime headers and their target archive exports. The matching compiler and linker also resolved the addresses of the listed functions and data. This is a development-runtime audit, not a claim that the published application has changed. A See it used link identifies a worked program containing that symbol. Other entries document its interface. The hardware experiments and their observed results are in Choose a library for a job.
The standard CoCo floating-point backend calls BASIC. The optional MC6839 ROM backend and its conditional log2f and setMC6839Trap entries require a separately supplied archive. It was absent from the reviewed installation. The separately staged standalone disk driver was present. A public build without that option can use ROM-backed decbfile. DriveWire helpers, the file chooser and auxiliary binary loaders in the upstream disk library fall outside this installed subset.
The OS-9 terminal/timer headers and Vectrex headers belong to other targets. Headers whose names include private, the internal assertion implementation and the compiler’s internal variable-argument helper serve library implementations. cc3graph.h appears in BGraph sources but is outside this installed public header set.
For compiler, library and optional-driver credits, open Licenses & Notices in VCC Plus. The source shelf identifies the editions these entries describe.
cmoc.h
Console output, strings, memory, arithmetic and callbacks. The CoCo target supplies this header and runtime automatically.
abs · adddww · atoff · atoi · atol · atol16 · atoui · atoul · atoul16 · bsearch · cmpdww · ConsoleOutHook · delay · div328 · divdwb · divdww · divmod16 · divmod8 · dwtoa · enable_printf_float · exit · ftoa · isalnum · isalpha · isdigit · isspace · itoa · itoa10 · labs · logf · ltoa · ltoa10 · memchr · memcmp · memcpy · memichr · memicmp · memmove · memset · memset16 · mulwb · mulww · NULL · offsetof · printf · putchar · putstr · qsort · rand · RAND_MAX · readline · readword · sbrk · sbrkmax · set_null_ptr_handler · set_stack_overflow_handler · setConsoleOutHook · SIZE_MAX · size_t · sprintf · sqrt16 · sqrt32 · srand · SSIZE_MAX · ssize_t · strcat · strchr · strcmp · strcpy · strcspn · stricmp · strlen · strlwr · strncat · strncmp · strncpy · strpbrk · strrchr · strspn · strstr · strtof · strtok · strtol · strtol10 · strtol16 · strtoul · strtoul10 · strtoul16 · strupr · subdww · tolower · toupper · ultoa · ultoa10 · ultoa16 · utoa · utoa10 · vprintf · vsprintf · zerodw
abs
int abs(int j);
Return the magnitude as a signed value of the same width. The most negative input has no positive counterpart in that representation.
adddww
void adddww(unsigned *twoWords, unsigned term);
Treat two words, high word first, as one unsigned 32-bit quantity. The first three calls update it in place. Comparison returns −1, 0 or +1.
atoff
float atoff(const char *nptr);
Parse a decimal floating-point number. In the BASIC backend use uppercase E for an exponent; spaces can occur within a number. strtof can report the first unconsumed character through endptr.
atoi
int atoi(const char *s);
Read decimal digits from a string. Match the returned signedness and width to your data; these calls have no error-output parameter.
atol
long atol(const char *nptr);
Read decimal digits from a string. Match the returned signedness and width to your data; these calls have no error-output parameter.
atol16
long atol16(const char *nptr);
Read hexadecimal digits from a string into a 32-bit result. Choose the signed or unsigned form appropriate to the caller.
atoui
unsigned atoui(const char *s);
Read decimal digits from a string. Match the returned signedness and width to your data; these calls have no error-output parameter.
atoul
unsigned long atoul(const char *nptr);
Read decimal digits from a string. Match the returned signedness and width to your data; these calls have no error-output parameter.
atoul16
unsigned long atoul16(const char *nptr);
Read hexadecimal digits from a string into a 32-bit result. Choose the signed or unsigned form appropriate to the caller.
bsearch
void *bsearch(const void *key, const void *base, size_t nmemb, size_t size, int (*compar)(const void *key, const void *element));
Supply the size of one element in bytes and a consistent three-way comparator. qsort reorders the array in place. bsearch expects that ordering and returns a pointer into the array or NULL.
cmpdww
signed char cmpdww(unsigned left[2], unsigned right);
Treat two words, high word first, as one unsigned 32-bit quantity. The first three calls update it in place. Comparison returns −1, 0 or +1.
ConsoleOutHook
typedef void (*ConsoleOutHook)(void);
Install a character-output routine and keep the previous hook to restore later. The character arrives in register A. Preserve B, X, Y and U, including when the program calls printf.
delay
void delay(size_t sixtiethsOfASecond);
Wait for the specified number of 60 Hz ticks. A value of 60 is about a second at the normal guest timing.
div328
div328 = divdwb
Divide the unsigned value in two consecutive words by a nonzero divisor. The quotient replaces those words. div328 is the former spelling of divdwb.
divdwb
void divdwb(unsigned dividendInQuotientOut[2], unsigned char divisor);
Divide the unsigned value in two consecutive words by a nonzero divisor. The quotient replaces those words. div328 is the former spelling of divdwb.
divdww
void divdww(unsigned dividendInQuotientOut[2], unsigned divisor);
Divide the unsigned value in two consecutive words by a nonzero divisor. The quotient replaces those words. div328 is the former spelling of divdwb.
divmod16
void divmod16(unsigned dividend, unsigned divisor, unsigned *quotient, unsigned *remainder);
Divide by a nonzero value. Supply storage for both outputs; quotient and remainder use the width in the declaration.
divmod8
void divmod8(unsigned char dividend, unsigned char divisor, unsigned char *quotient, unsigned char *remainder);
Divide by a nonzero value. Supply storage for both outputs; quotient and remainder use the width in the declaration.
dwtoa
char *dwtoa(char *out, unsigned hi, unsigned lo);
Treat hi and lo as halves of one unsigned 32-bit value. Supply 11 bytes. Print from the returned pointer, which skips leading zeros.
enable_printf_float
void enable_printf_float(void);
Enables %f when using the separately supplied MC6839 backend. The standard CoCo BASIC float configuration uses its own initialization.
exit
void exit(int status);
End the current program. A return into BASIC requires its memory and execution environment to remain usable.
ftoa
char *ftoa(char out[38], float f);
Give the conversion a writable array of at least 38 bytes. The return is the start of the string on success or NULL on failure.
isalnum
int isalnum(int c);
Test a character for the property named in the function. A nonzero result means it belongs to the class.
isalpha
int isalpha(int c);
Test a character for the property named in the function. A nonzero result means it belongs to the class.
isdigit
int isdigit(int c);
Test a character for the property named in the function. A nonzero result means it belongs to the class.
isspace
int isspace(int c);
Test a character for the property named in the function. A nonzero result means it belongs to the class.
itoa
itoa(value,str,base)
Write decimal digits and a terminating zero into str. Signed output may need a minus sign. Allow 7 bytes for a signed 16-bit value and 12 for a signed 32-bit value. The three-argument compatibility forms always use decimal.
itoa10
char *itoa10(int value, char *str);
Write decimal digits and a terminating zero into str. Signed output may need a minus sign. Allow 7 bytes for a signed 16-bit value and 12 for a signed 32-bit value. The three-argument compatibility forms always use decimal.
labs
long int labs(long int j);
Return the magnitude as a signed value of the same width. The most negative input has no positive counterpart in that representation.
logf
float logf(float x);
These functions use the selected floating-point backend. For the BASIC backend keep its ROM mapped. logf requires a positive argument and sqrtf requires zero or greater; a BASIC math error can end the program.
ltoa
ltoa(value,str,base)
Write decimal digits and a terminating zero into str. Signed output may need a minus sign. Allow 7 bytes for a signed 16-bit value and 12 for a signed 32-bit value. The three-argument compatibility forms always use decimal.
ltoa10
char *ltoa10(long value, char *str);
Write decimal digits and a terminating zero into str. Signed output may need a minus sign. Allow 7 bytes for a signed 16-bit value and 12 for a signed 32-bit value. The three-argument compatibility forms always use decimal.
memchr
void *memchr(const void *s, int c, size_t n);
Search the first n bytes for c. The result points inside the original range, or is NULL. memichr folds letter case.
memcmp
int memcmp(const void *s1, const void *s2, size_t n);
Compare exactly n bytes of two readable ranges, including zero bytes. Zero means a match. memicmp ignores ASCII case.
memcpy
void *memcpy(void *dest, const void *src, size_t n);
Copy n bytes into caller-owned storage and return its address. Size both regions for n. Choose memmove if the two ranges overlap.
memichr
void *memichr(const void *s, int c, size_t n);
Search the first n bytes for c. The result points inside the original range, or is NULL. memichr folds letter case.
memicmp
int memicmp(const void *s1, const void *s2, size_t n);
Compare exactly n bytes of two readable ranges, including zero bytes. Zero means a match. memicmp ignores ASCII case.
memmove
void *memmove(void *dest, const void *src, size_t n);
Copy n bytes safely even if source and destination overlap, for example when shifting a row inside a manifest. Returns dest.
memset
void *memset(void *s, int c, size_t n);
Fill n bytes with the low eight bits of c. Returns the start address.
memset16
void *memset16(void *dest, unsigned short w, size_t num16BitWords);
Fill num16BitWords two-byte words. The destination needs twice that many bytes.
mulwb
unsigned mulwb(unsigned char *hi, unsigned wordFactor, unsigned char byteFactor);
Multiply the two unsigned inputs. Use the returned low word and the high portion stored through hi to recover the full product.
mulww
unsigned mulww(unsigned *hi, unsigned factor0, unsigned factor1);
Multiply the two unsigned inputs. Use the returned low word and the high portion stored through hi to recover the full product.
NULL
NULL = ((void *) 0)
The null pointer value. Check it before using a lookup or allocation result as an address.
offsetof
offsetof(Type,member)
Retrieve the offset in bytes of a member within a structure type. Useful when comparing C data with the debugger’s memory view.
printf
int printf(const char *format, ...);
Send formatted characters to the current console. For the cargo total use %u with an unsigned word. Other useful conversions are %d, %x, %X, %p, %s, %c and %%. A width can pad a field; left justification applies to strings. CMOC also handles long integers with a length modifier.
putchar
void putchar(int c);
Write one character through the current console output hook.
putstr
void putstr(const char *s, size_t n);
Send exactly n bytes. A zero byte inside the range does not shorten it. Keep all n bytes accessible.
qsort
void qsort(void *base, size_t nmemb, size_t size, int (*compar)(const void *, const void *));
Supply the size of one element in bytes and a consistent three-way comparator. qsort reorders the array in place. bsearch expects that ordering and returns a pointer into the array or NULL.
rand
int rand(void);
srand selects the starting seed for rand. Reusing a seed gives a repeatable sequence for a game or test. rand returns values from zero to RAND_MAX.
RAND_MAX
RAND_MAX = 0x7FFF
srand selects the starting seed for rand. Reusing a seed gives a repeatable sequence for a game or test. rand returns values from zero to RAND_MAX.
readline
char *readline(void);
Wait for a console line. readword converts a decimal word; readline returns a shared string or NULL on failure. Copy that string before a later read.
readword
unsigned readword(void);
Wait for a console line. readword converts a decimal word; readline returns a shared string or NULL on failure. Copy that string before a later read.
sbrk
void *sbrk(size_t increment);
Reserve bytes from the remaining target heap with sbrk. Failure is (void *)−1. A zero request queries the break; sbrkmax reports how many bytes are still available.
sbrkmax
size_t sbrkmax(void);
Reserve bytes from the remaining target heap with sbrk. Failure is (void *)−1. A zero request queries the break; sbrkmax reports how many bytes are still available.
set_null_ptr_handler
void set_null_ptr_handler(void (*newHandler)(void *addressPastFailedCheck));
With --check-null, install this callback before a checked pointer access can occur. In CMOC 0.1.101, addressPastFailedCheck is the address immediately after the call to the check routine, not the address of that call instruction. Use the matching listing and map to locate the user function. The handler may return, but doing so can allow a dangerous null access to continue; a failure handler normally reports the problem and exits. This check is opt-in and adds code and execution cost.
set_stack_overflow_handler
void set_stack_overflow_handler(void (*newHandler)(void *addressPastFailedCheck, void *stackRegister));
With --check-stack, install this callback before a checked function can overflow the stack. In CMOC 0.1.101, addressPastFailedCheck points immediately after the call to the check routine; stackRegister is the out-of-range stack pointer. The callback must not return. Use the matching listing to interpret the first address. This check is opt-in and adds execution cost.
setConsoleOutHook
ConsoleOutHook setConsoleOutHook(ConsoleOutHook routine);
Install a character-output routine and keep the previous hook to restore later. The character arrives in register A. Preserve B, X, Y and U, including when the program calls printf.
SIZE_MAX
SIZE_MAX = 0xFFFFu
A size in this target ABI occupies 16 bits. Unsigned size_t ranges from 0 to 65,535. Signed ssize_t tops out at 32,767.
size_t
typedef unsigned size_t;
A size in this target ABI occupies 16 bits. Unsigned size_t ranges from 0 to 65,535. Signed ssize_t tops out at 32,767.
sprintf
int sprintf(char *dest, const char *format, ...);
Write formatted characters and a final zero into the caller’s array. There is no capacity argument. Allow space for the longest possible expansion and its terminator. Both routines share formatting state; avoid re-entering from an interrupt.
sqrt16
unsigned char sqrt16(unsigned short n);
Return the integer part of the square root of an unsigned value. Use sqrt32 for a 32-bit input.
sqrt32
unsigned short sqrt32(unsigned long n);
Return the integer part of the square root of an unsigned value. Use sqrt32 for a 32-bit input.
srand
void srand(unsigned seed);
srand selects the starting seed for rand. Reusing a seed gives a repeatable sequence for a game or test. rand returns values from zero to RAND_MAX.
SSIZE_MAX
SSIZE_MAX = 0x7FFF
A size in this target ABI occupies 16 bits. Unsigned size_t ranges from 0 to 65,535. Signed ssize_t tops out at 32,767.
ssize_t
typedef signed ssize_t;
A size in this target ABI occupies 16 bits. Unsigned size_t ranges from 0 to 65,535. Signed ssize_t tops out at 32,767.
strcat
char *strcat(char *dest, const char *src);
The destination needs enough room for the finished string and its zero byte. strcpy replaces its contents; strcat starts at the existing terminator. Both return dest.
strchr
char *strchr(const char *s, int c);
Return a pointer into the original string, or NULL if there is no match. strchr finds the first character, strrchr the last, strstr a substring and strpbrk a character from the supplied set.
strcmp
int strcmp(const char *s1, const char *s2);
Compare two zero-terminated strings. Zero means equal. A negative or positive result orders the strings. stricmp folds letter case.
strcpy
char *strcpy(char *dest, const char *src);
The destination needs enough room for the finished string and its zero byte. strcpy replaces its contents; strcat starts at the existing terminator. Both return dest.
strcspn
size_t strcspn(const char *s, const char *reject);
Count the initial run of characters drawn from accept (strspn), or outside reject (strcspn). The string is left intact.
stricmp
int stricmp(const char *s1, const char *s2);
Compare two zero-terminated strings. Zero means equal. A negative or positive result orders the strings. stricmp folds letter case.
strlen
size_t strlen(const char *s);
Count characters before the first zero. A 256-byte disk sector is only a C string once you establish a terminator within its buffer.
strlwr
char *strlwr(char *s);
Change the case of ASCII letters in the supplied writable string. The result is the same storage.
strncat
char *strncat(char *dest, const char *src, size_t n);
Append up to n source characters and terminate the result. n limits the source contribution; it does not specify the destination capacity.
strncmp
int strncmp(const char *s1, const char *s2, size_t n);
Compare up to n characters, stopping earlier at a string end. Zero means the compared prefixes match.
strncpy
char *strncpy(char *dest, const char *src, size_t n);
Write n destination bytes, padding a short source with zeros. A source of length n or greater leaves the caller responsible for termination.
strpbrk
char *strpbrk(const char *s, const char *accept);
Return a pointer into the original string, or NULL if there is no match. strchr finds the first character, strrchr the last, strstr a substring and strpbrk a character from the supplied set.
strrchr
char *strrchr(const char *s, int c);
Return a pointer into the original string, or NULL if there is no match. strchr finds the first character, strrchr the last, strstr a substring and strpbrk a character from the supplied set.
strspn
size_t strspn(const char *s, const char *accept);
Count the initial run of characters drawn from accept (strspn), or outside reject (strcspn). The string is left intact.
strstr
char *strstr(const char *haystack, const char *needle);
Return a pointer into the original string, or NULL if there is no match. strchr finds the first character, strrchr the last, strstr a substring and strpbrk a character from the supplied set.
strtof
float strtof(const char *nptr, char **endptr);
Parse a decimal floating-point number. In the BASIC backend use uppercase E for an exponent; spaces can occur within a number. strtof can report the first unconsumed character through endptr.
strtok
char *strtok(char *str, const char *delim);
Split a writable string at any delimiter, replacing separators with zeros. Start with the string pointer, pass NULL to continue and finish when the returned pointer is NULL. Successive calls share a position. To work on a second string partway through the first, give each string its own position with strtok_r.
strtol
strtol(nptr,endptr,base)
With the default CMOC headers, this macro calls strtol10. Its third argument is ignored. To select the base or check the 32-bit range, use the vcccompat function from stdlib.h.
strtol10
strtol10(nptr,endptr)
Read decimal digits with the CMOC routine and interpret its result as a signed long. Supply endptr to find the first unconverted character. The vcccompat strtol function also checks the signed range.
strtol16
strtol16(nptr,endptr)
Use the CMOC hexadecimal routine and interpret its result as a signed long. Supply endptr to find the first unconverted character. The vcccompat strtol function also checks the signed range.
strtoul
strtoul(nptr,endptr,base)
With the default CMOC headers, this macro calls strtoul10. Its third argument is ignored. To select the base or check the 32-bit range, use the vcccompat function from stdlib.h.
strtoul10
unsigned long strtoul10(const char *nptr, char **endptr);
Read an unsigned long in decimal using the CMOC runtime. Supply endptr to find the first unconverted character. Use the vcccompat strtoul function for base selection and range checking.
strtoul16
unsigned long strtoul16(const char *nptr, char **endptr);
Read an unsigned long in hexadecimal using the CMOC runtime. Supply endptr to find the first unconverted character. Use the vcccompat strtoul function for base selection and range checking.
strupr
char *strupr(char *s);
Change the case of ASCII letters in the supplied writable string. The result is the same storage.
subdww
void subdww(unsigned *twoWords, unsigned term);
Treat two words, high word first, as one unsigned 32-bit quantity. The first three calls update it in place. Comparison returns −1, 0 or +1.
tolower
int tolower(int c);
Return the converted character value; assign it back if you intend to change the stored text.
toupper
int toupper(int c);
Return the converted character value; assign it back if you intend to change the stored text.
ultoa
ultoa(value,str,base)
Write decimal digits and a terminating zero into str. Signed output may need a minus sign. Allow 7 bytes for a signed 16-bit value and 12 for a signed 32-bit value. The three-argument compatibility forms always use decimal.
ultoa10
char *ultoa10(unsigned long value, char *str);
Write decimal digits and a terminating zero into str. Signed output may need a minus sign. Allow 7 bytes for a signed 16-bit value and 12 for a signed 32-bit value. The three-argument compatibility forms always use decimal.
ultoa16
char *ultoa16(unsigned long value, char *str);
Convert a 32-bit unsigned value to hexadecimal and terminate the string. Reserve room for eight digits and the final zero.
utoa
utoa(value,str,base)
Write decimal digits and a terminating zero into str. Signed output may need a minus sign. Allow 7 bytes for a signed 16-bit value and 12 for a signed 32-bit value. The three-argument compatibility forms always use decimal.
utoa10
char *utoa10(unsigned value, char *str);
Write decimal digits and a terminating zero into str. Signed output may need a minus sign. Allow 7 bytes for a signed 16-bit value and 12 for a signed 32-bit value. The three-argument compatibility forms always use decimal.
vprintf
int vprintf(const char *format, va_list ap);
Print using a va_list already positioned at the first variable argument. Use this in a wrapper that receives its own format and arguments.
vsprintf
int vsprintf(char *dest, const char *format, va_list ap);
Write formatted characters and a final zero into the caller’s array. There is no capacity argument. Allow space for the longest possible expansion and its terminator. Both routines share formatting state; avoid re-entering from an interrupt.
zerodw
void zerodw(unsigned *twoWords);
Treat two words, high word first, as one unsigned 32-bit quantity. The first three calls update it in place. Comparison returns −1, 0 or +1.
coco.h
BASIC display modes, keys, joysticks, sound and timing. The CoCo target supplies this header and runtime automatically.
One exception is readDECBFile, which requires the optional standalone controller driver. The WithDECB version uses Disk BASIC.
atanf · attr · BOOL · byte · cls · cmp · coldStart · cosf · DEV_CASSETTE · DEV_PRINTER · DEV_SCREEN · DEV_SERIAL · disableInterrupts · dword · enable6847T1TrueLowerCase · enableInterrupts · expf · fabsf · FALSE · floorf · getTextMode · getTimer · hscreen · hset · initCoCoSupport · inkey · int16_t · int32_t · int8_t · isCoCo3 · isKeyPressed · JOYSTK_BUTTON_1_LEFT · JOYSTK_BUTTON_1_RIGHT · JOYSTK_BUTTON_2_LEFT · JOYSTK_BUTTON_2_RIGHT · JOYSTK_LEFT_HORIZ · JOYSTK_LEFT_VERT · JOYSTK_MAX · JOYSTK_RIGHT_HORIZ · JOYSTK_RIGHT_VERT · KEY_BIT_0 · KEY_BIT_1 · KEY_BIT_2 · KEY_BIT_3 · KEY_BIT_4 · KEY_BIT_5 · KEY_BIT_6 · KEY_BIT_7 · KEY_BIT_8 · KEY_BIT_9 · KEY_BIT_A · KEY_BIT_ALT · KEY_BIT_AT · KEY_BIT_B · KEY_BIT_BREAK · KEY_BIT_C · KEY_BIT_CLEAR · KEY_BIT_COLON · KEY_BIT_COMMA · KEY_BIT_CTRL · KEY_BIT_D · KEY_BIT_DOWN · KEY_BIT_E · KEY_BIT_ENTER · KEY_BIT_F · KEY_BIT_F1 · KEY_BIT_F2 · KEY_BIT_G · KEY_BIT_H · KEY_BIT_HYPHEN · KEY_BIT_I · KEY_BIT_J · KEY_BIT_K · KEY_BIT_L · KEY_BIT_LEFT · KEY_BIT_M · KEY_BIT_N · KEY_BIT_O · KEY_BIT_P · KEY_BIT_PERIOD · KEY_BIT_Q · KEY_BIT_R · KEY_BIT_RIGHT · KEY_BIT_S · KEY_BIT_SEMICOLON · KEY_BIT_SHIFT · KEY_BIT_SLASH · KEY_BIT_SPACE · KEY_BIT_T · KEY_BIT_U · KEY_BIT_UP · KEY_BIT_V · KEY_BIT_W · KEY_BIT_X · KEY_BIT_Y · KEY_BIT_Z · KEY_PROBE_0 · KEY_PROBE_1 · KEY_PROBE_2 · KEY_PROBE_3 · KEY_PROBE_4 · KEY_PROBE_5 · KEY_PROBE_6 · KEY_PROBE_7 · KEY_PROBE_8 · KEY_PROBE_9 · KEY_PROBE_A · KEY_PROBE_ALT · KEY_PROBE_AT · KEY_PROBE_B · KEY_PROBE_BREAK · KEY_PROBE_C · KEY_PROBE_CLEAR · KEY_PROBE_COLON · KEY_PROBE_COMMA · KEY_PROBE_CTRL · KEY_PROBE_D · KEY_PROBE_DOWN · KEY_PROBE_E · KEY_PROBE_ENTER · KEY_PROBE_F · KEY_PROBE_F1 · KEY_PROBE_F2 · KEY_PROBE_G · KEY_PROBE_H · KEY_PROBE_HYPHEN · KEY_PROBE_I · KEY_PROBE_J · KEY_PROBE_K · KEY_PROBE_L · KEY_PROBE_LEFT · KEY_PROBE_M · KEY_PROBE_N · KEY_PROBE_O · KEY_PROBE_P · KEY_PROBE_PERIOD · KEY_PROBE_Q · KEY_PROBE_R · KEY_PROBE_RIGHT · KEY_PROBE_S · KEY_PROBE_SEMICOLON · KEY_PROBE_SHIFT · KEY_PROBE_SLASH · KEY_PROBE_SPACE · KEY_PROBE_T · KEY_PROBE_U · KEY_PROBE_UP · KEY_PROBE_V · KEY_PROBE_W · KEY_PROBE_X · KEY_PROBE_Y · KEY_PROBE_Z · KeyboardBits · locate · palette · paletteRGB · pcls · pmode · readDECBFile · readDECBFileWithDECB · readJoystickButtons · readJoystickPositions · resetPalette · rgb · roundf · sbyte · screen · sdword · setBorderColor · setCaseFlag · setHighSpeed · setOutputDevice · setPmodeGraphicsAddress · setPmodeGraphicsAddressEx · setSAMRegisters · setTimer · showGraphicsAddress · showLowResTextAddress · showPmode4 · sinf · sleep · sound · sqrtf · sword · tanf · textScreenHeight · textScreenWidth · TRUE · truncf · uint16_t · uint32_t · uint8_t · waitkey · width · word
atanf
float atanf(float radians);
The trigonometric functions use radians. Tangent is undefined at odd multiples of π/2. The BASIC ROM computes these results in the standard CoCo configuration.
attr
byte attr(byte foreColor, byte backColor, byte blink, byte underline);
Set the color indices for subsequent CoCo 3 text, plus blink and underline flags. Foreground and background each take 0–7. The hardware uses foreground palette slots 8–15 and background slots 0–7.
BOOL
typedef unsigned char BOOL;
A BOOL is one byte. A zero value tests false and any nonzero value tests true. Use named constants when passing option flags.
byte
typedef unsigned char byte;
Eight-bit storage. Unsigned values occupy 0–255 and signed values −128–127. Cargo Count uses byte counts for crates and meals per crate.
cls
void cls(byte color);
Clear the BASIC text screen. A value of 255 requests the no-argument BASIC CLS behavior.
cmp
void cmp(void);
Load the standard RGB or composite color assignments for the CoCo 3 palette. Select a matching signal in the emulator if comparing the two color systems.
coldStart
void coldStart();
Restart BASIC through its cold-start entry. This abandons the running program.
cosf
float cosf(float radians);
The trigonometric functions use radians. Tangent is undefined at odd multiples of π/2. The BASIC ROM computes these results in the standard CoCo configuration.
DEV_CASSETTE
DEV_CASSETTE = -1
A BASIC output destination for setOutputDevice.
DEV_PRINTER
DEV_PRINTER = -2
A BASIC output destination for setOutputDevice.
DEV_SCREEN
DEV_SCREEN = 0
A BASIC output destination for setOutputDevice.
DEV_SERIAL
DEV_SERIAL = -2
A BASIC output destination for setOutputDevice.
disableInterrupts
disableInterrupts()
Mask or enable both IRQ and FIRQ. Leave interrupt-dependent keyboard, disk and audio routines with the services they require.
dword
typedef unsigned long dword;
Thirty-two-bit storage. Good for tracking absolute file lengths that exceed 65,535 bytes. The debugger shows all four bytes of the guest value.
enable6847T1TrueLowerCase
enable6847T1TrueLowerCase()
Enable lowercase character shapes in the compatible 32-column text mode. BASIC character output can change this setting again.
enableInterrupts
enableInterrupts()
Mask or enable both IRQ and FIRQ. Leave interrupt-dependent keyboard, disk and audio routines with the services they require.
expf
float expf(float x);
These functions use the selected floating-point backend. For the BASIC backend keep its ROM mapped. logf requires a positive argument and sqrtf requires zero or greater; a BASIC math error can end the program.
fabsf
float fabsf(float x);
These functions use the selected floating-point backend. For the BASIC backend keep its ROM mapped. logf requires a positive argument and sqrtf requires zero or greater; a BASIC math error can end the program.
FALSE
FALSE = 0
A BOOL is one byte. A zero value tests false and any nonzero value tests true. Use named constants when passing option flags.
floorf
float floorf(float x);
Return a floating-point integral value: floor goes toward negative infinity, trunc toward zero, and round to nearest with exact halves away from zero.
getTextMode
byte getTextMode();
Under BASIC on the CoCo 3 choose 32, 40 or 80 columns. width reports success or failure. getTextMode reports the actual width.
getTimer
getTimer()
Access the BASIC 16-bit tick count. It wraps after 65,535; setting it changes the time seen by other guest code.
hscreen
byte hscreen(byte mode);
Select a CoCo 3 BASIC graphics mode before plotting. hset takes a pixel address and a color in the BASIC mode’s allowed range. These ROM calls depend on BASIC’s graphics workspace.
hset
byte hset(word x, word y, byte color);
Select a CoCo 3 BASIC graphics mode before plotting. hset takes a pixel address and a color in the BASIC mode’s allowed range. These ROM calls depend on BASIC’s graphics workspace.
initCoCoSupport
void initCoCoSupport(void);
Legacy program state populated by initCoCoSupport. Set the required mode explicitly with width and read the mode through getTextMode for new projects.
inkey
byte inkey();
inkey returns zero while no character is ready. waitkey waits and accepts a cursor-blink flag. Both use the BASIC keyboard routine.
int16_t
typedef signed int int16_t;
Sixteen-bit storage. An unsigned word can hold 360 even though an eight-bit byte cannot. Signed values span −32,768 to 32,767.
int32_t
typedef signed long int32_t;
Thirty-two-bit storage. Good for tracking absolute file lengths that exceed 65,535 bytes. The debugger shows all four bytes of the guest value.
int8_t
typedef signed char int8_t;
Eight-bit storage. Unsigned values occupy 0–255 and signed values −128–127. Cargo Count uses byte counts for crates and meals per crate.
isCoCo3
extern byte isCoCo3;
Legacy program state populated by initCoCoSupport. Set the required mode explicitly with width and read the mode through getTextMode for new projects.
isKeyPressed
byte isKeyPressed(byte probe, byte testBit);
Supply the matching KEY_PROBE and KEY_BIT values for one key. This polls the CoCo keyboard matrix without consuming a console character.
JOYSTK_LEFT_HORIZ
JOYSTK_LEFT_HORIZ = 2
An axis index or range limit for the array returned by readJoystickPositions.
JOYSTK_LEFT_VERT
JOYSTK_LEFT_VERT = 3
An axis index or range limit for the array returned by readJoystickPositions.
JOYSTK_MAX
JOYSTK_MAX = 63
An axis index or range limit for the array returned by readJoystickPositions.
JOYSTK_RIGHT_HORIZ
JOYSTK_RIGHT_HORIZ = 0
An axis index or range limit for the array returned by readJoystickPositions.
JOYSTK_RIGHT_VERT
JOYSTK_RIGHT_VERT = 1
An axis index or range limit for the array returned by readJoystickPositions.
KEY_BIT_0
KEY_BIT_0 = 16
Keyboard matrix value for 0. Pass KEY_PROBE_0 and KEY_BIT_0 together to isKeyPressed.
KEY_BIT_1
KEY_BIT_1 = 16
Keyboard matrix value for 1. Pass KEY_PROBE_1 and KEY_BIT_1 together to isKeyPressed.
KEY_BIT_2
KEY_BIT_2 = 16
Keyboard matrix value for 2. Pass KEY_PROBE_2 and KEY_BIT_2 together to isKeyPressed.
KEY_BIT_3
KEY_BIT_3 = 16
Keyboard matrix value for 3. Pass KEY_PROBE_3 and KEY_BIT_3 together to isKeyPressed.
KEY_BIT_4
KEY_BIT_4 = 16
Keyboard matrix value for 4. Pass KEY_PROBE_4 and KEY_BIT_4 together to isKeyPressed.
KEY_BIT_5
KEY_BIT_5 = 16
Keyboard matrix value for 5. Pass KEY_PROBE_5 and KEY_BIT_5 together to isKeyPressed.
KEY_BIT_6
KEY_BIT_6 = 16
Keyboard matrix value for 6. Pass KEY_PROBE_6 and KEY_BIT_6 together to isKeyPressed.
KEY_BIT_7
KEY_BIT_7 = 16
Keyboard matrix value for 7. Pass KEY_PROBE_7 and KEY_BIT_7 together to isKeyPressed.
KEY_BIT_8
KEY_BIT_8 = 32
Keyboard matrix value for 8. Pass KEY_PROBE_8 and KEY_BIT_8 together to isKeyPressed.
KEY_BIT_9
KEY_BIT_9 = 32
Keyboard matrix value for 9. Pass KEY_PROBE_9 and KEY_BIT_9 together to isKeyPressed.
KEY_BIT_A
KEY_BIT_A = 1
Keyboard matrix value for A. Pass KEY_PROBE_A and KEY_BIT_A together to isKeyPressed.
KEY_BIT_ALT
KEY_BIT_ALT = 64
Keyboard matrix value for ALT. Pass KEY_PROBE_ALT and KEY_BIT_ALT together to isKeyPressed.
KEY_BIT_AT
KEY_BIT_AT = 1
Keyboard matrix value for AT. Pass KEY_PROBE_AT and KEY_BIT_AT together to isKeyPressed.
KEY_BIT_B
KEY_BIT_B = 1
Keyboard matrix value for B. Pass KEY_PROBE_B and KEY_BIT_B together to isKeyPressed.
KEY_BIT_BREAK
KEY_BIT_BREAK = 64
Keyboard matrix value for BREAK. Pass KEY_PROBE_BREAK and KEY_BIT_BREAK together to isKeyPressed.
KEY_BIT_C
KEY_BIT_C = 1
Keyboard matrix value for C. Pass KEY_PROBE_C and KEY_BIT_C together to isKeyPressed.
KEY_BIT_CLEAR
KEY_BIT_CLEAR = 64
Keyboard matrix value for CLEAR. Pass KEY_PROBE_CLEAR and KEY_BIT_CLEAR together to isKeyPressed.
KEY_BIT_COLON
KEY_BIT_COLON = 32
Keyboard matrix value for COLON. Pass KEY_PROBE_COLON and KEY_BIT_COLON together to isKeyPressed.
KEY_BIT_COMMA
KEY_BIT_COMMA = 32
Keyboard matrix value for COMMA. Pass KEY_PROBE_COMMA and KEY_BIT_COMMA together to isKeyPressed.
KEY_BIT_CTRL
KEY_BIT_CTRL = 64
Keyboard matrix value for CTRL. Pass KEY_PROBE_CTRL and KEY_BIT_CTRL together to isKeyPressed.
KEY_BIT_D
KEY_BIT_D = 1
Keyboard matrix value for D. Pass KEY_PROBE_D and KEY_BIT_D together to isKeyPressed.
KEY_BIT_DOWN
KEY_BIT_DOWN = 8
Keyboard matrix value for DOWN. Pass KEY_PROBE_DOWN and KEY_BIT_DOWN together to isKeyPressed.
KEY_BIT_E
KEY_BIT_E = 1
Keyboard matrix value for E. Pass KEY_PROBE_E and KEY_BIT_E together to isKeyPressed.
KEY_BIT_ENTER
KEY_BIT_ENTER = 64
Keyboard matrix value for ENTER. Pass KEY_PROBE_ENTER and KEY_BIT_ENTER together to isKeyPressed.
KEY_BIT_F
KEY_BIT_F = 1
Keyboard matrix value for F. Pass KEY_PROBE_F and KEY_BIT_F together to isKeyPressed.
KEY_BIT_F1
KEY_BIT_F1 = 64
Keyboard matrix value for F1. Pass KEY_PROBE_F1 and KEY_BIT_F1 together to isKeyPressed.
KEY_BIT_F2
KEY_BIT_F2 = 64
Keyboard matrix value for F2. Pass KEY_PROBE_F2 and KEY_BIT_F2 together to isKeyPressed.
KEY_BIT_G
KEY_BIT_G = 1
Keyboard matrix value for G. Pass KEY_PROBE_G and KEY_BIT_G together to isKeyPressed.
KEY_BIT_H
KEY_BIT_H = 2
Keyboard matrix value for H. Pass KEY_PROBE_H and KEY_BIT_H together to isKeyPressed.
KEY_BIT_HYPHEN
KEY_BIT_HYPHEN = 32
Keyboard matrix value for HYPHEN. Pass KEY_PROBE_HYPHEN and KEY_BIT_HYPHEN together to isKeyPressed.
KEY_BIT_I
KEY_BIT_I = 2
Keyboard matrix value for I. Pass KEY_PROBE_I and KEY_BIT_I together to isKeyPressed.
KEY_BIT_J
KEY_BIT_J = 2
Keyboard matrix value for J. Pass KEY_PROBE_J and KEY_BIT_J together to isKeyPressed.
KEY_BIT_K
KEY_BIT_K = 2
Keyboard matrix value for K. Pass KEY_PROBE_K and KEY_BIT_K together to isKeyPressed.
KEY_BIT_L
KEY_BIT_L = 2
Keyboard matrix value for L. Pass KEY_PROBE_L and KEY_BIT_L together to isKeyPressed.
KEY_BIT_LEFT
KEY_BIT_LEFT = 8
Keyboard matrix value for LEFT. Pass KEY_PROBE_LEFT and KEY_BIT_LEFT together to isKeyPressed.
KEY_BIT_M
KEY_BIT_M = 2
Keyboard matrix value for M. Pass KEY_PROBE_M and KEY_BIT_M together to isKeyPressed.
KEY_BIT_N
KEY_BIT_N = 2
Keyboard matrix value for N. Pass KEY_PROBE_N and KEY_BIT_N together to isKeyPressed.
KEY_BIT_O
KEY_BIT_O = 2
Keyboard matrix value for O. Pass KEY_PROBE_O and KEY_BIT_O together to isKeyPressed.
KEY_BIT_P
KEY_BIT_P = 4
Keyboard matrix value for P. Pass KEY_PROBE_P and KEY_BIT_P together to isKeyPressed.
KEY_BIT_PERIOD
KEY_BIT_PERIOD = 32
Keyboard matrix value for PERIOD. Pass KEY_PROBE_PERIOD and KEY_BIT_PERIOD together to isKeyPressed.
KEY_BIT_Q
KEY_BIT_Q = 4
Keyboard matrix value for Q. Pass KEY_PROBE_Q and KEY_BIT_Q together to isKeyPressed.
KEY_BIT_R
KEY_BIT_R = 4
Keyboard matrix value for R. Pass KEY_PROBE_R and KEY_BIT_R together to isKeyPressed.
KEY_BIT_RIGHT
KEY_BIT_RIGHT = 8
Keyboard matrix value for RIGHT. Pass KEY_PROBE_RIGHT and KEY_BIT_RIGHT together to isKeyPressed.
KEY_BIT_S
KEY_BIT_S = 4
Keyboard matrix value for S. Pass KEY_PROBE_S and KEY_BIT_S together to isKeyPressed.
KEY_BIT_SEMICOLON
KEY_BIT_SEMICOLON = 32
Keyboard matrix value for SEMICOLON. Pass KEY_PROBE_SEMICOLON and KEY_BIT_SEMICOLON together to isKeyPressed.
KEY_BIT_SHIFT
KEY_BIT_SHIFT = 64
Keyboard matrix value for SHIFT. Pass KEY_PROBE_SHIFT and KEY_BIT_SHIFT together to isKeyPressed.
KEY_BIT_SLASH
KEY_BIT_SLASH = 32
Keyboard matrix value for SLASH. Pass KEY_PROBE_SLASH and KEY_BIT_SLASH together to isKeyPressed.
KEY_BIT_SPACE
KEY_BIT_SPACE = 8
Keyboard matrix value for SPACE. Pass KEY_PROBE_SPACE and KEY_BIT_SPACE together to isKeyPressed.
KEY_BIT_T
KEY_BIT_T = 4
Keyboard matrix value for T. Pass KEY_PROBE_T and KEY_BIT_T together to isKeyPressed.
KEY_BIT_U
KEY_BIT_U = 4
Keyboard matrix value for U. Pass KEY_PROBE_U and KEY_BIT_U together to isKeyPressed.
KEY_BIT_UP
KEY_BIT_UP = 8
Keyboard matrix value for UP. Pass KEY_PROBE_UP and KEY_BIT_UP together to isKeyPressed.
KEY_BIT_V
KEY_BIT_V = 4
Keyboard matrix value for V. Pass KEY_PROBE_V and KEY_BIT_V together to isKeyPressed.
KEY_BIT_W
KEY_BIT_W = 4
Keyboard matrix value for W. Pass KEY_PROBE_W and KEY_BIT_W together to isKeyPressed.
KEY_BIT_X
KEY_BIT_X = 8
Keyboard matrix value for X. Pass KEY_PROBE_X and KEY_BIT_X together to isKeyPressed.
KEY_BIT_Y
KEY_BIT_Y = 8
Keyboard matrix value for Y. Pass KEY_PROBE_Y and KEY_BIT_Y together to isKeyPressed.
KEY_BIT_Z
KEY_BIT_Z = 8
Keyboard matrix value for Z. Pass KEY_PROBE_Z and KEY_BIT_Z together to isKeyPressed.
KEY_PROBE_0
KEY_PROBE_0 = 254
Keyboard matrix value for 0. Pass KEY_PROBE_0 and KEY_BIT_0 together to isKeyPressed.
KEY_PROBE_1
KEY_PROBE_1 = 253
Keyboard matrix value for 1. Pass KEY_PROBE_1 and KEY_BIT_1 together to isKeyPressed.
KEY_PROBE_2
KEY_PROBE_2 = 251
Keyboard matrix value for 2. Pass KEY_PROBE_2 and KEY_BIT_2 together to isKeyPressed.
KEY_PROBE_3
KEY_PROBE_3 = 247
Keyboard matrix value for 3. Pass KEY_PROBE_3 and KEY_BIT_3 together to isKeyPressed.
KEY_PROBE_4
KEY_PROBE_4 = 239
Keyboard matrix value for 4. Pass KEY_PROBE_4 and KEY_BIT_4 together to isKeyPressed.
KEY_PROBE_5
KEY_PROBE_5 = 223
Keyboard matrix value for 5. Pass KEY_PROBE_5 and KEY_BIT_5 together to isKeyPressed.
KEY_PROBE_6
KEY_PROBE_6 = 191
Keyboard matrix value for 6. Pass KEY_PROBE_6 and KEY_BIT_6 together to isKeyPressed.
KEY_PROBE_7
KEY_PROBE_7 = 127
Keyboard matrix value for 7. Pass KEY_PROBE_7 and KEY_BIT_7 together to isKeyPressed.
KEY_PROBE_8
KEY_PROBE_8 = 254
Keyboard matrix value for 8. Pass KEY_PROBE_8 and KEY_BIT_8 together to isKeyPressed.
KEY_PROBE_9
KEY_PROBE_9 = 253
Keyboard matrix value for 9. Pass KEY_PROBE_9 and KEY_BIT_9 together to isKeyPressed.
KEY_PROBE_A
KEY_PROBE_A = 253
Keyboard matrix value for A. Pass KEY_PROBE_A and KEY_BIT_A together to isKeyPressed.
KEY_PROBE_ALT
KEY_PROBE_ALT = 247
Keyboard matrix value for ALT. Pass KEY_PROBE_ALT and KEY_BIT_ALT together to isKeyPressed.
KEY_PROBE_AT
KEY_PROBE_AT = 254
Keyboard matrix value for AT. Pass KEY_PROBE_AT and KEY_BIT_AT together to isKeyPressed.
KEY_PROBE_B
KEY_PROBE_B = 251
Keyboard matrix value for B. Pass KEY_PROBE_B and KEY_BIT_B together to isKeyPressed.
KEY_PROBE_BREAK
KEY_PROBE_BREAK = 251
Keyboard matrix value for BREAK. Pass KEY_PROBE_BREAK and KEY_BIT_BREAK together to isKeyPressed.
KEY_PROBE_C
KEY_PROBE_C = 247
Keyboard matrix value for C. Pass KEY_PROBE_C and KEY_BIT_C together to isKeyPressed.
KEY_PROBE_CLEAR
KEY_PROBE_CLEAR = 253
Keyboard matrix value for CLEAR. Pass KEY_PROBE_CLEAR and KEY_BIT_CLEAR together to isKeyPressed.
KEY_PROBE_COLON
KEY_PROBE_COLON = 251
Keyboard matrix value for COLON. Pass KEY_PROBE_COLON and KEY_BIT_COLON together to isKeyPressed.
KEY_PROBE_COMMA
KEY_PROBE_COMMA = 239
Keyboard matrix value for COMMA. Pass KEY_PROBE_COMMA and KEY_BIT_COMMA together to isKeyPressed.
KEY_PROBE_CTRL
KEY_PROBE_CTRL = 239
Keyboard matrix value for CTRL. Pass KEY_PROBE_CTRL and KEY_BIT_CTRL together to isKeyPressed.
KEY_PROBE_D
KEY_PROBE_D = 239
Keyboard matrix value for D. Pass KEY_PROBE_D and KEY_BIT_D together to isKeyPressed.
KEY_PROBE_DOWN
KEY_PROBE_DOWN = 239
Keyboard matrix value for DOWN. Pass KEY_PROBE_DOWN and KEY_BIT_DOWN together to isKeyPressed.
KEY_PROBE_E
KEY_PROBE_E = 223
Keyboard matrix value for E. Pass KEY_PROBE_E and KEY_BIT_E together to isKeyPressed.
KEY_PROBE_ENTER
KEY_PROBE_ENTER = 254
Keyboard matrix value for ENTER. Pass KEY_PROBE_ENTER and KEY_BIT_ENTER together to isKeyPressed.
KEY_PROBE_F
KEY_PROBE_F = 191
Keyboard matrix value for F. Pass KEY_PROBE_F and KEY_BIT_F together to isKeyPressed.
KEY_PROBE_F1
KEY_PROBE_F1 = 223
Keyboard matrix value for F1. Pass KEY_PROBE_F1 and KEY_BIT_F1 together to isKeyPressed.
KEY_PROBE_F2
KEY_PROBE_F2 = 191
Keyboard matrix value for F2. Pass KEY_PROBE_F2 and KEY_BIT_F2 together to isKeyPressed.
KEY_PROBE_G
KEY_PROBE_G = 127
Keyboard matrix value for G. Pass KEY_PROBE_G and KEY_BIT_G together to isKeyPressed.
KEY_PROBE_H
KEY_PROBE_H = 254
Keyboard matrix value for H. Pass KEY_PROBE_H and KEY_BIT_H together to isKeyPressed.
KEY_PROBE_HYPHEN
KEY_PROBE_HYPHEN = 223
Keyboard matrix value for HYPHEN. Pass KEY_PROBE_HYPHEN and KEY_BIT_HYPHEN together to isKeyPressed.
KEY_PROBE_I
KEY_PROBE_I = 253
Keyboard matrix value for I. Pass KEY_PROBE_I and KEY_BIT_I together to isKeyPressed.
KEY_PROBE_J
KEY_PROBE_J = 251
Keyboard matrix value for J. Pass KEY_PROBE_J and KEY_BIT_J together to isKeyPressed.
KEY_PROBE_K
KEY_PROBE_K = 247
Keyboard matrix value for K. Pass KEY_PROBE_K and KEY_BIT_K together to isKeyPressed.
KEY_PROBE_L
KEY_PROBE_L = 239
Keyboard matrix value for L. Pass KEY_PROBE_L and KEY_BIT_L together to isKeyPressed.
KEY_PROBE_LEFT
KEY_PROBE_LEFT = 223
Keyboard matrix value for LEFT. Pass KEY_PROBE_LEFT and KEY_BIT_LEFT together to isKeyPressed.
KEY_PROBE_M
KEY_PROBE_M = 223
Keyboard matrix value for M. Pass KEY_PROBE_M and KEY_BIT_M together to isKeyPressed.
KEY_PROBE_N
KEY_PROBE_N = 191
Keyboard matrix value for N. Pass KEY_PROBE_N and KEY_BIT_N together to isKeyPressed.
KEY_PROBE_O
KEY_PROBE_O = 127
Keyboard matrix value for O. Pass KEY_PROBE_O and KEY_BIT_O together to isKeyPressed.
KEY_PROBE_P
KEY_PROBE_P = 254
Keyboard matrix value for P. Pass KEY_PROBE_P and KEY_BIT_P together to isKeyPressed.
KEY_PROBE_PERIOD
KEY_PROBE_PERIOD = 191
Keyboard matrix value for PERIOD. Pass KEY_PROBE_PERIOD and KEY_BIT_PERIOD together to isKeyPressed.
KEY_PROBE_Q
KEY_PROBE_Q = 253
Keyboard matrix value for Q. Pass KEY_PROBE_Q and KEY_BIT_Q together to isKeyPressed.
KEY_PROBE_R
KEY_PROBE_R = 251
Keyboard matrix value for R. Pass KEY_PROBE_R and KEY_BIT_R together to isKeyPressed.
KEY_PROBE_RIGHT
KEY_PROBE_RIGHT = 191
Keyboard matrix value for RIGHT. Pass KEY_PROBE_RIGHT and KEY_BIT_RIGHT together to isKeyPressed.
KEY_PROBE_S
KEY_PROBE_S = 247
Keyboard matrix value for S. Pass KEY_PROBE_S and KEY_BIT_S together to isKeyPressed.
KEY_PROBE_SEMICOLON
KEY_PROBE_SEMICOLON = 247
Keyboard matrix value for SEMICOLON. Pass KEY_PROBE_SEMICOLON and KEY_BIT_SEMICOLON together to isKeyPressed.
KEY_PROBE_SHIFT
KEY_PROBE_SHIFT = 127
Keyboard matrix value for SHIFT. Pass KEY_PROBE_SHIFT and KEY_BIT_SHIFT together to isKeyPressed.
KEY_PROBE_SLASH
KEY_PROBE_SLASH = 127
Keyboard matrix value for SLASH. Pass KEY_PROBE_SLASH and KEY_BIT_SLASH together to isKeyPressed.
KEY_PROBE_SPACE
KEY_PROBE_SPACE = 127
Keyboard matrix value for SPACE. Pass KEY_PROBE_SPACE and KEY_BIT_SPACE together to isKeyPressed.
KEY_PROBE_T
KEY_PROBE_T = 239
Keyboard matrix value for T. Pass KEY_PROBE_T and KEY_BIT_T together to isKeyPressed.
KEY_PROBE_U
KEY_PROBE_U = 223
Keyboard matrix value for U. Pass KEY_PROBE_U and KEY_BIT_U together to isKeyPressed.
KEY_PROBE_UP
KEY_PROBE_UP = 247
Keyboard matrix value for UP. Pass KEY_PROBE_UP and KEY_BIT_UP together to isKeyPressed.
KEY_PROBE_V
KEY_PROBE_V = 191
Keyboard matrix value for V. Pass KEY_PROBE_V and KEY_BIT_V together to isKeyPressed.
KEY_PROBE_W
KEY_PROBE_W = 127
Keyboard matrix value for W. Pass KEY_PROBE_W and KEY_BIT_W together to isKeyPressed.
KEY_PROBE_X
KEY_PROBE_X = 254
Keyboard matrix value for X. Pass KEY_PROBE_X and KEY_BIT_X together to isKeyPressed.
KEY_PROBE_Y
KEY_PROBE_Y = 253
Keyboard matrix value for Y. Pass KEY_PROBE_Y and KEY_BIT_Y together to isKeyPressed.
KEY_PROBE_Z
KEY_PROBE_Z = 251
Keyboard matrix value for Z. Pass KEY_PROBE_Z and KEY_BIT_Z together to isKeyPressed.
KeyboardBits
enum KeyboardBits
Supply the matching KEY_PROBE and KEY_BIT values for one key. This polls the CoCo keyboard matrix without consuming a console character.
locate
byte locate(byte column, byte row);
Set the printing position in BASIC text coordinates, starting at column 0 and row 0. Stay inside the current text dimensions.
palette
byte palette(byte slot, byte color);
Set one of 16 CoCo 3 palette slots. palette accepts a hardware color 0–63 and reports whether its arguments were valid. paletteRGB uses separate red, green and blue components of 0–3 each.
paletteRGB
void paletteRGB(byte slot, byte red, byte green, byte blue);
Set one of 16 CoCo 3 palette slots. palette accepts a hardware color 0–63 and reports whether its arguments were valid. paletteRGB uses separate red, green and blue components of 0–3 each.
pcls
void pcls(byte byteToClearWith);
pmode records a graphics mode from 0–4 and a 512-byte-aligned buffer; it reports invalid inputs. pcls fills that buffer with a byte pattern. screen selects text or the prepared graphics display and color set.
pmode
BOOL pmode(byte mode, byte *screenBuffer);
pmode records a graphics mode from 0–4 and a 512-byte-aligned buffer; it reports invalid inputs. pcls fills that buffer with a byte pattern. screen selects text or the prepared graphics display and color set.
readDECBFile
byte readDECBFile(void *dest, byte driveNo, const char filename[11], byte workBuffer[256], size_t *sizePtr);
Supply an eleven-character, space-padded 8+3 name, a separate 256-byte work buffer and a destination large enough for whole sectors. Return 0 signals success; 2 means missing file. readDECBFile takes over the interrupt vectors temporarily and returns with interrupts masked. The WithDECB variant needs the ROM and ordinary IRQ/NMI services. This entry also needs the optional dskcon-standalone archive at link time.
coco.h · -ldskcon-standalone
readDECBFileWithDECB
byte readDECBFileWithDECB(void *dest, byte driveNo, const char filename[11], byte workBuffer[256], size_t *sizePtr);
Supply an eleven-character, space-padded 8+3 name, a separate 256-byte work buffer and a destination large enough for whole sectors. Return 0 signals success; 2 means missing file. readDECBFile takes over the interrupt vectors temporarily and returns with interrupts masked. The WithDECB variant needs the ROM and ordinary IRQ/NMI services.
readJoystickPositions
const byte *readJoystickPositions();
Poll the four axes; the returned pointer refers to four shared byte values from 0 to 63. Right horizontal/vertical are entries 0/1, left horizontal/vertical 2/3.
resetPalette
byte resetPalette(byte isRGB);
Load the standard RGB or composite color assignments for the CoCo 3 palette. Select a matching signal in the emulator if comparing the two color systems.
rgb
void rgb(void);
Load the standard RGB or composite color assignments for the CoCo 3 palette. Select a matching signal in the emulator if comparing the two color systems.
roundf
float roundf(float x);
Return a floating-point integral value: floor goes toward negative infinity, trunc toward zero, and round to nearest with exact halves away from zero.
sbyte
typedef signed char sbyte;
Eight-bit storage. Unsigned values occupy 0–255 and signed values −128–127. Cargo Count uses byte counts for crates and meals per crate.
screen
void screen(byte type, byte colorset);
pmode records a graphics mode from 0–4 and a 512-byte-aligned buffer; it reports invalid inputs. pcls fills that buffer with a byte pattern. screen selects text or the prepared graphics display and color set.
sdword
typedef signed long sdword;
Thirty-two-bit storage. Good for tracking absolute file lengths that exceed 65,535 bytes. The debugger shows all four bytes of the guest value.
setBorderColor
byte setBorderColor(byte color);
Choose a six-bit hardware color for the border in CoCo 3 40- or 80-column text mode. The border and the background of a character cell are separate.
setCaseFlag
void setCaseFlag(byte upperCase);
Select BASIC’s keyboard input case flag.
setHighSpeed
void setHighSpeed(BOOL fast);
Select the clock-speed setting. Restore the desired speed after running code whose timing assumes the normal clock.
setOutputDevice
void setOutputDevice(sbyte deviceNum);
Change BASIC’s output destination, such as screen or printer. Restore the screen when your program finishes redirecting text.
setPmodeGraphicsAddress
setPmodeGraphicsAddress(newPmodeScreenBuffer)
Use a buffer beginning on a 512-byte boundary. The Ex form can change the drawing target while leaving a different page visible.
setPmodeGraphicsAddressEx
void setPmodeGraphicsAddressEx(byte *newPmodeScreenBuffer, BOOL makeVisible);
Use a buffer beginning on a 512-byte boundary. The Ex form can change the drawing target while leaving a different page visible.
setSAMRegisters
void setSAMRegisters(byte *samAddr, byte value, byte numBits);
Write a sequence of SAM control bits starting at the specified register base. Pass only values and bit counts appropriate for that hardware register.
setTimer
setTimer(newValue)
Access the BASIC 16-bit tick count. It wraps after 65,535; setting it changes the time seen by other guest code.
showGraphicsAddress
void showGraphicsAddress(byte samVRegisterValue, byte pageNum);
Set the displayed SAM graphics page. pageNum is a 512-byte page number, 0–127. The SAM mode value and page address must describe the same buffer layout.
showLowResTextAddress
void showLowResTextAddress(void);
Legacy convenience entry. New programs can select a PMODE 4 buffer with pmode then screen, and return with screen(0, 0).
showPmode4
void showPmode4(byte colorset);
Legacy convenience entry. New programs can select a PMODE 4 buffer with pmode then screen, and return with screen(0, 0).
sinf
float sinf(float radians);
The trigonometric functions use radians. Tangent is undefined at odd multiples of π/2. The BASIC ROM computes these results in the standard CoCo configuration.
sleep
void sleep(int seconds);
Wait for an integral number of seconds from 0 to 1092.
sound
void sound(byte tone, byte duration);
Play a BASIC tone using its pitch and duration conventions. Color BASIC must be mapped.
sqrtf
float sqrtf(float x);
These functions use the selected floating-point backend. For the BASIC backend keep its ROM mapped. logf requires a positive argument and sqrtf requires zero or greater; a BASIC math error can end the program.
sword
typedef signed int sword;
Sixteen-bit storage. An unsigned word can hold 360 even though an eight-bit byte cannot. Signed values span −32,768 to 32,767.
tanf
float tanf(float radians);
The trigonometric functions use radians. Tangent is undefined at odd multiples of π/2. The BASIC ROM computes these results in the standard CoCo configuration.
textScreenHeight
extern byte textScreenHeight;
Legacy program state populated by initCoCoSupport. Set the required mode explicitly with width and read the mode through getTextMode for new projects.
textScreenWidth
extern byte textScreenWidth;
Legacy program state populated by initCoCoSupport. Set the required mode explicitly with width and read the mode through getTextMode for new projects.
TRUE
TRUE = 1
A BOOL is one byte. A zero value tests false and any nonzero value tests true. Use named constants when passing option flags.
truncf
float truncf(float x);
Return a floating-point integral value: floor goes toward negative infinity, trunc toward zero, and round to nearest with exact halves away from zero.
uint16_t
typedef unsigned int uint16_t;
Sixteen-bit storage. An unsigned word can hold 360 even though an eight-bit byte cannot. Signed values span −32,768 to 32,767.
uint32_t
typedef unsigned long uint32_t;
Thirty-two-bit storage. Good for tracking absolute file lengths that exceed 65,535 bytes. The debugger shows all four bytes of the guest value.
uint8_t
typedef unsigned char uint8_t;
Eight-bit storage. Unsigned values occupy 0–255 and signed values −128–127. Cargo Count uses byte counts for crates and meals per crate.
waitkey
byte waitkey(byte blinkCursor);
inkey returns zero while no character is ready. waitkey waits and accepts a cursor-blink flag. Both use the BASIC keyboard routine.
width
byte width(byte columns);
Under BASIC on the CoCo 3 choose 32, 40 or 80 columns. width reports success or failure. getTextMode reports the actual width.
word
typedef unsigned int word;
Sixteen-bit storage. An unsigned word can hold 360 even though an eight-bit byte cannot. Signed values span −32,768 to 32,767.
stdarg.h
Pass a variable-length argument list through your own function. The CoCo target supplies this header and runtime automatically.
va_arg
va_arg(ap,type)
Initialize a cursor after the last named argument. Fetch the next argument with its actual promoted type and finish the list before leaving the function.
va_end
va_end(ap)
Initialize a cursor after the last named argument. Fetch the next argument with its actual promoted type and finish the list before leaving the function.
va_list
typedef char *va_list;
Initialize a cursor after the last named argument. Fetch the next argument with its actual promoted type and finish the list before leaving the function.
va_start
va_start(ap,lastFixed)
Initialize a cursor after the last named argument. Fetch the next argument with its actual promoted type and finish the list before leaving the function.
setjmp.h
Save and restore a nonlocal return point within a still-active call. The CoCo target supplies this header and runtime automatically.
jmp_buf
typedef unsigned char jmp_buf[6];
Keep env alive in the calling frame. setjmp first returns zero. longjmp returns control there with a nonzero value. Jumping into a function that already returned invalidates the saved context.
longjmp
void longjmp(jmp_buf env, int value);
Keep env alive in the calling frame. setjmp first returns zero. longjmp returns control there with a nonzero value. Jumping into a function that already returned invalidates the saved context.
setjmp
int setjmp(jmp_buf env);
Keep env alive in the calling frame. setjmp first returns zero. longjmp returns control there with a nonzero value. Jumping into a function that already returned invalidates the saved context.
assert.h
Check program assumptions at build time and while running. The CoCo target supplies this header and runtime automatically.
_FailedAssertHandler · _FreezeOnFailedAssert · _SetFailedAssertHandler · assert · static_assert
_FailedAssertHandler
typedef void (*_FailedAssertHandler)(const char *file, int lineno, const char *condition);
An enabled assertion reports its failed condition. The default handler exits; the freeze switch or a custom handler changes that action. Defining NDEBUG removes the assertion, including evaluation of its operand.
_FreezeOnFailedAssert
void _FreezeOnFailedAssert(int freeze);
An enabled assertion reports its failed condition. The default handler exits; the freeze switch or a custom handler changes that action. Defining NDEBUG removes the assertion, including evaluation of its operand.
_SetFailedAssertHandler
void _SetFailedAssertHandler(_FailedAssertHandler newHandler);
An enabled assertion reports its failed condition. The default handler exits; the freeze switch or a custom handler changes that action. Defining NDEBUG removes the assertion, including evaluation of its operand.
assert
assert(cond)
An enabled assertion reports its failed condition. The default handler exits; the freeze switch or a custom handler changes that action. Defining NDEBUG removes the assertion, including evaluation of its operand.
static_assert
static_assert(cond)
Require an integer condition at compile time. Failure prevents a build without adding target instructions.
disk.h
Read a Disk BASIC file or address a physical floppy sector. The CoCo target supplies this header and runtime automatically.
advanceOffset · close · computeFileLength · curDriveNo · dskcon · DSKCON_READ · DSKCON_WRITE · fatBuffer · fatUpToDate · FileDesc · findDirEntry · getCurrentlyAvailableBytes · getDefaultDriveNo · getDefautlDriveNo · getFileLength · getGranuleLength · getLastBasicDriveNo · getNextSector · GRANULE_SIZE · granuleToTrack · initdisk · isLastSectorOfFile · MAX_NUM_GRANULES · normalizeFilename · openfile · read · readDiskSector · rewind · seek · setDefaultDriveNo · updateFAT · writeDiskSector
advanceOffset
void advanceOffset(struct FileDesc *fd, word numBytes);
Work within the descriptor’s current cached sector. Use the available count before advancing. Refreshing the sector replaces the pointed-to data.
close
sbyte close(struct FileDesc *fd);
Release a disk.h file descriptor after reading. Returns 0 on success or −1 on failure.
computeFileLength
byte computeFileLength(uint32_t *pLength, byte firstGran, word numBytesLastSector);
Inspect the allocation chain or a descriptor’s last sector. getFileLength places the byte length in the supplied dword on success. Distinguish that length from the rounded allocation size.
curDriveNo
extern byte curDriveNo;
The FAT describes a drive’s allocation chains. updateFAT returns the shared cache pointer or NULL on failure. The library tracks its current drive and cache freshness.
dskcon
byte dskcon(byte operation, byte *buffer, byte drive, byte track, byte sector);
Use a full 256-byte sector buffer. Drive 0–3, track 0–34 and physical sector 1–18 refer to the mounted disk. These routines return nonzero for success. A raw write changes actual guest media.
DSKCON_READ
DSKCON_READ = 2
Select the direction of a raw physical sector transfer. Work on a private disk image when experimenting with writes.
DSKCON_WRITE
DSKCON_WRITE = 3
Select the direction of a raw physical sector transfer. Work on a private disk image when experimenting with writes.
fatBuffer
extern byte *fatBuffer;
The FAT describes a drive’s allocation chains. updateFAT returns the shared cache pointer or NULL on failure. The library tracks its current drive and cache freshness.
fatUpToDate
extern byte fatUpToDate;
The FAT describes a drive’s allocation chains. updateFAT returns the shared cache pointer or NULL on failure. The library tracks its current drive and cache freshness.
FileDesc
struct FileDesc
Pass the address of a complete FileDesc to openfile. It owns the current sector cache and read position. Its size includes a whole 256-byte sector.
findDirEntry
byte findDirEntry(char *dirEntry, const char *filename);
Search the mounted directory for a filename. Supply space for the entry data read by disk.h.
getCurrentlyAvailableBytes
byte *getCurrentlyAvailableBytes(struct FileDesc *fd, word *numAvailBytes);
Work within the descriptor’s current cached sector. Use the available count before advancing. Refreshing the sector replaces the pointed-to data.
getDefaultDriveNo
getDefaultDriveNo()
The openfile API uses the selected drive. The misspelled getDefautlDriveNo macro is a historical alias for getDefaultDriveNo.
getDefautlDriveNo
getDefautlDriveNo()
The openfile API uses the selected drive. The misspelled getDefautlDriveNo macro is a historical alias for getDefaultDriveNo.
getFileLength
byte getFileLength(struct FileDesc *fd, uint32_t *pLength);
Inspect the allocation chain or a descriptor’s last sector. getFileLength places the byte length in the supplied dword on success. Distinguish that length from the rounded allocation size.
getGranuleLength
word getGranuleLength(byte *fat, byte granule, word numBytesLastSector);
Inspect the allocation chain or a descriptor’s last sector. getFileLength places the byte length in the supplied dword on success. Distinguish that length from the rounded allocation size.
getLastBasicDriveNo
byte getLastBasicDriveNo();
The openfile API uses the selected drive. The misspelled getDefautlDriveNo macro is a historical alias for getDefaultDriveNo.
getNextSector
byte getNextSector(struct FileDesc *fd);
Work within the descriptor’s current cached sector. Use the available count before advancing. Refreshing the sector replaces the pointed-to data.
GRANULE_SIZE
GRANULE_SIZE = 2304
These values describe the library’s ordinary 35-track Disk BASIC floppy. A granule spans nine 256-byte sectors; the directory has its own reserved track.
granuleToTrack
void granuleToTrack(byte granule, byte *track, byte *sec);
Convert a granule to its track and sector offset (0 or 9). The allocation skips the directory track.
initdisk
byte initdisk(byte newFATBuffer[]);
Provide a FAT cache of at least MAX_NUM_GRANULES bytes, kept alive while using disk.h. The return is 1 on success and 0 on failure.
isLastSectorOfFile
byte isLastSectorOfFile(struct FileDesc *fd);
Inspect the allocation chain or a descriptor’s last sector. getFileLength places the byte length in the supplied dword on success. Distinguish that length from the rounded allocation size.
MAX_NUM_GRANULES
MAX_NUM_GRANULES = 68
These values describe the library’s ordinary 35-track Disk BASIC floppy. A granule spans nine 256-byte sectors; the directory has its own reserved track.
normalizeFilename
void normalizeFilename(char *dest, const char *src);
Convert a dotted name to an eleven-character uppercase, space-padded name plus a terminating zero. Supply twelve writable bytes.
openfile
byte openfile(struct FileDesc *fd, const char *filename);
Prepare a real struct FileDesc with a dotted filename on the selected drive. Initialize disk.h first. A nonzero result permits reads; then close the descriptor.
read
word read(struct FileDesc *fd, char *buf, word numBytesRequested);
Read at most the requested number of bytes into a writable buffer. Trust the returned byte count when handling a partial read.
readDiskSector
byte readDiskSector(byte *dest, byte drive, byte track, byte sector);
Use a full 256-byte sector buffer. Drive 0–3, track 0–34 and physical sector 1–18 refer to the mounted disk. These routines return nonzero for success. A raw write changes actual guest media.
rewind
void rewind(struct FileDesc *fd);
Reset a file’s read position or choose an absolute unsigned byte offset. seek returns zero on success and −1 on failure.
seek
sbyte seek(struct FileDesc *fd, uint32_t newPos);
Reset a file’s read position or choose an absolute unsigned byte offset. seek returns zero on success and −1 on failure.
setDefaultDriveNo
byte setDefaultDriveNo(byte no);
The openfile API uses the selected drive. The misspelled getDefautlDriveNo macro is a historical alias for getDefaultDriveNo.
updateFAT
byte *updateFAT();
The FAT describes a drive’s allocation chains. updateFAT returns the shared cache pointer or NULL on failure. The library tracks its current drive and cache freshness.
writeDiskSector
byte writeDiskSector(byte *src, byte drive, byte track, byte sector);
Use a full 256-byte sector buffer. Drive 0–3, track 0–34 and physical sector 1–18 refer to the mounted disk. These routines return nonzero for success. A raw write changes actual guest media.
astar.h
Find a path across a rectangular grid and walk back from the goal. Add astar under Project Settings → Libraries, or link with -lastar in your Makefile.
Save the astar example for this book
astar_advancePathIteration · astar_initNode · astar_searchGrid · astar_startPathIteration · AStarGraph · AStarNode · AStarPathIterator
astar_advancePathIteration
AStarNode *astar_advancePathIteration(AStarPathIterator *iter);
After a successful search, start at that same goal. The iterator walks backward toward the start. Each pointer borrows a node from the graph; NULL ends the route.
astar.h · -lastar · See it used in route.c
astar_initNode
void astar_initNode(AStarNode *node, void *userData, byte canGoEast, byte canGoSouth);
Initialize each tile with its optional caller-owned data and east/south exit flags. The search uses the nodes as working storage. Keep every node alive during search and path traversal.
astar.h · -lastar · See it used in route.c
astar_searchGrid
BOOL astar_searchGrid(AStarGraph *graph, size_t startX, size_t startY, size_t goalX, size_t goalY);
Give the graph a row-major array of width × height nodes. Coordinates must name valid tiles. A nonzero return means a route reached the goal; zero means no path to follow.
astar.h · -lastar · See it used in route.c
astar_startPathIteration
void astar_startPathIteration(AStarPathIterator *iter, AStarGraph *graph, size_t goalX, size_t goalY);
After a successful search, start at that same goal. The iterator walks backward toward the start. Each pointer borrows a node from the graph; NULL ends the route.
astar.h · -lastar · See it used in route.c
AStarGraph
typedef struct AStarGraph { … } AStarGraph;
Give the graph a row-major array of width × height nodes. Coordinates must name valid tiles. A nonzero return means a route reached the goal; zero means no path to follow.
astar.h · -lastar · See it used in route.c
AStarNode
typedef struct AStarNode { … } AStarNode;
Initialize each tile with its optional caller-owned data and east/south exit flags. The search uses the nodes as working storage. Keep every node alive during search and path traversal.
astar.h · -lastar · See it used in route.c
AStarPathIterator
typedef struct AStarPathIterator { … } AStarPathIterator;
After a successful search, start at that same goal. The iterator walks backward toward the start. Each pointer borrows a node from the graph; NULL ends the route.
astar.h · -lastar · See it used in route.c
Keyboard.h
Poll a guest keyboard with CoCo 3 control, function and navigation keys. Add bcontrol under Project Settings → Libraries, or link with -lbcontrol in your Makefile.
Save the bcontrol example for this book
Keyboard · Keyboard_init · Keyboard_poll · Keyboard_shutdown
Keyboard
typedef struct Keyboard { … } Keyboard;
Initialize one caller-owned keyboard object before polling. A zero result from poll means no key available. Finish with shutdown before releasing the object.
Keyboard.h · -lbcontrol
Keyboard_init
void Keyboard_init(Keyboard *keyboard);
Initialize one caller-owned keyboard object before polling. A zero result from poll means no key available. Finish with shutdown before releasing the object.
Keyboard.h · -lbcontrol
Keyboard_poll
byte Keyboard_poll(Keyboard *keyboard);
Initialize one caller-owned keyboard object before polling. A zero result from poll means no key available. Finish with shutdown before releasing the object.
Keyboard.h · -lbcontrol
Keyboard_shutdown
void Keyboard_shutdown(Keyboard *keyboard);
Initialize one caller-owned keyboard object before polling. A zero result from poll means no key available. Finish with shutdown before releasing the object.
Keyboard.h · -lbcontrol
Joystick.h
Sample analog axes and detect joystick button presses. Add bcontrol under Project Settings → Libraries, or link with -lbcontrol in your Makefile.
Save the bcontrol example for this book
Joystick_compareAxis · Joystick_disableSound · Joystick_enableSound · Joystick_getAxisValues · Joystick_getAxisValuesAndButtonState · Joystick_getButtonStates · Joystick_getButtonStates2 · Joystick_selectAnalogMuxInputs
Joystick_compareAxis
BOOL Joystick_compareAxis(byte referenceValue);
Select axis 0/1 for right X/Y or 2/3 for left X/Y. Compare against a threshold from 0–63. Nonzero means at or above threshold. Return the mux to input 0 before playing DAC sound.
Joystick.h · -lbcontrol
Joystick_disableSound
void Joystick_disableSound(void);
Mute the analog multiplexer around direct axis polling and restore it when finished. Otherwise the varying voltage used to measure position can be audible.
Joystick.h · -lbcontrol · See it used in stick.c
Joystick_enableSound
void Joystick_enableSound(void);
Mute the analog multiplexer around direct axis polling and restore it when finished. Otherwise the varying voltage used to measure position can be audible.
Joystick.h · -lbcontrol · See it used in stick.c
Joystick_getAxisValues
void Joystick_getAxisValues(byte axisValues[4], byte axisSelectionMask);
Supply four bytes and set mask bits for the axes to sample. 0x03 selects the right port and 0x0C the left. Results are 0–63. Disable the analog sound path while polling.
Joystick.h · -lbcontrol · See it used in stick.c
Joystick_selectAnalogMuxInputs
void Joystick_selectAnalogMuxInputs(byte axis);
Select axis 0/1 for right X/Y or 2/3 for left X/Y. Compare against a threshold from 0–63. Nonzero means at or above threshold. Return the mux to input 0 before playing DAC sound.
Joystick.h · -lbcontrol · See it used in stick.c
catmull-rom.h
Interpolate a smooth path through a sequence of points. Add bgraph under Project Settings → Libraries, or link with -lbgraph in your Makefile.
Save the bgraph example for this book
CatmullRom_drawLine · CatmullRom_onPieceEnd · drawCatmullRomPath
CatmullRom_drawLine
typedef BOOL (*CatmullRom_drawLine)(short x0, short y0, short x1, short y1, void *cookie);
A callback type. Implement the shown return and argument types exactly. Keep any supplied user data alive while the library can call back.
catmull-rom.h · -lbgraph
CatmullRom_onPieceEnd
typedef BOOL (*CatmullRom_onPieceEnd)(size_t pointIndex, void *cookie);
A callback type. Implement the shown return and argument types exactly. Keep any supplied user data alive while the library can call back.
catmull-rom.h · -lbgraph
drawCatmullRomPath
BOOL drawCatmullRomPath(BOOL openPath, const ShortPoint *points, size_t numPoints, byte numSegmentsPerPiece, CatmullRom_onPieceEnd onPieceEnd, CatmullRom_drawLine drawLine, void *cookie);
Supply at least four points and at least two segments per piece. Keep the line callback and its cookie valid. A callback returning false stops the drawing and produces a false result.
catmull-rom.h · -lbgraph
clipping.h
Clip a line to a rectangle before drawing it. Add bgraph under Project Settings → Libraries, or link with -lbgraph in your Makefile.
cohenSutherlandLineClip
BOOL cohenSutherlandLineClip(short *x0, short *y0, short *x1, short *y1, const ShortClipRect *rect);
Clip the given segment to an ordered rectangle, with y increasing downward. A true result gives clipped endpoints through the four pointers; false rejects the segment.
clipping.h · -lbgraph
ShortClipRect
typedef struct ShortClipRect { … } ShortClipRect;
Signed pixel coordinates for the clipping routine. Supply a top-left corner and a bottom-right corner, with increasing y toward the bottom.
clipping.h · -lbgraph
ShortPoint
typedef struct ShortPoint { … } ShortPoint;
Signed pixel coordinates for the clipping routine. Supply a top-left corner and a bottom-right corner, with increasing y toward the bottom.
clipping.h · -lbgraph
Drawer.h
Move a drawing pen and run a DRAW script in a graphics buffer. Add bgraph under Project Settings → Libraries, or link with -lbgraph in your Makefile.
Save the bgraph example for this book
Drawer · Drawer_draw · Drawer_getPosition · Drawer_init · Drawer_initForHSCREEN · Drawer_initForPMODE · Drawer_setColorIndex · Drawer_setPosition
Drawer
typedef struct Drawer { … } Drawer;
Keep a writable screen buffer and a Drawer alive together. Supply dimensions and pixels per byte, or let the mode-specific initializer derive them. A false return rejects an invalid setup. Initialization positions the pen in the center; displaying the buffer is a separate operation.
Drawer.h · -lbgraph
Drawer_draw
const char *Drawer_draw(Drawer *d, const char *script);
Interpret DRAW commands against the initialized buffer. Coordinates must stay inside its actual pixel dimensions. NULL means the whole script was accepted; an error pointer identifies the problem character in the original script.
Drawer.h · -lbgraph
Drawer_getPosition
void Drawer_getPosition(Drawer *d, word *pX, byte *pY);
Set a palette index valid for the configured depth. Positions are pixel coordinates relative to the buffer. The getter writes both coordinates through caller-supplied pointers.
Drawer.h · -lbgraph
Drawer_init
BOOL Drawer_init(Drawer *d, byte *screenBuffer, word screenWidthInPixels, byte screenHeightInPixels, byte pixelsPerByte);
Keep a writable screen buffer and a Drawer alive together. Supply dimensions and pixels per byte, or let the mode-specific initializer derive them. A false return rejects an invalid setup. Initialization positions the pen in the center; displaying the buffer is a separate operation.
Drawer.h · -lbgraph
Drawer_initForHSCREEN
BOOL Drawer_initForHSCREEN(Drawer *d, byte *screenBuffer, byte modeNo);
Keep a writable screen buffer and a Drawer alive together. Supply dimensions and pixels per byte, or let the mode-specific initializer derive them. A false return rejects an invalid setup. Initialization positions the pen in the center; displaying the buffer is a separate operation.
Drawer.h · -lbgraph
Drawer_initForPMODE
BOOL Drawer_initForPMODE(Drawer *d, byte *screenBuffer, byte pmodeNo);
Keep a writable screen buffer and a Drawer alive together. Supply dimensions and pixels per byte, or let the mode-specific initializer derive them. A false return rejects an invalid setup. Initialization positions the pen in the center; displaying the buffer is a separate operation.
Drawer.h · -lbgraph
Drawer_setColorIndex
void Drawer_setColorIndex(Drawer *d, byte newColorIndex);
Set a palette index valid for the configured depth. Positions are pixel coordinates relative to the buffer. The getter writes both coordinates through caller-supplied pointers.
Drawer.h · -lbgraph
Drawer_setPosition
void Drawer_setPosition(Drawer *d, word x, byte y);
Set a palette index valid for the configured depth. Positions are pixel coordinates relative to the buffer. The getter writes both coordinates through caller-supplied pointers.
Drawer.h · -lbgraph
lores.h
Read or change the color of a low-resolution semigraphics block. Add bgraph under Project Settings → Libraries, or link with -lbgraph in your Makefile.
point
char point(const byte *screen, byte x, byte y);
Use the 32 × 16 character buffer as a 64 × 32 semigraphics grid. Coordinates begin at zero; set accepts colors 1–8. point returns the color or −1 for a text character.
lores.h · -lbgraph
reset
void reset(byte *screen, byte x, byte y);
Use the 32 × 16 character buffer as a 64 × 32 semigraphics grid. Coordinates begin at zero; set accepts colors 1–8. point returns the color or −1 for a text character.
lores.h · -lbgraph
set
void set(byte *screen, byte x, byte y, byte color);
Use the 32 × 16 character buffer as a 64 × 32 semigraphics grid. Coordinates begin at zero; set accepts colors 1–8. point returns the color or −1 for a text character.
lores.h · -lbgraph
Painter.h
Flood-fill a connected area with caller-owned scratch space. Add bgraph under Project Settings → Libraries, or link with -lbgraph in your Makefile.
Save the bgraph example for this book
Painter · Painter_continuationFuncPtr · Painter_getPixelFuncPtr · Painter_init · Painter_INVALID_ARGUMENT · Painter_NO_ERROR · Painter_OUT_OF_STACK · Painter_paint · Painter_setPixelFuncPtr
Painter
typedef struct Painter { … } Painter;
Prepare a flood fill with pixel callbacks, actual pixel dimensions and a caller-owned workspace kept alive during painting. A 64-byte workspace is a useful starting point. False indicates invalid setup.
Painter.h · -lbgraph
Painter_continuationFuncPtr
typedef BOOL (*Painter_continuationFuncPtr)(void *cookie);
A callback type. Implement the shown return and argument types exactly. Keep any supplied user data alive while the library can call back.
Painter.h · -lbgraph
Painter_getPixelFuncPtr
typedef byte (*Painter_getPixelFuncPtr)(word x, byte y, void *cookie);
A callback type. Implement the shown return and argument types exactly. Keep any supplied user data alive while the library can call back.
Painter.h · -lbgraph
Painter_init
BOOL Painter_init(Painter *p, Painter_getPixelFuncPtr getPixel, Painter_setPixelFuncPtr setPixel, Painter_continuationFuncPtr continuationFuncPtr, word screenWidthInPixels, byte screenHeightInPixels, byte *workSpace, size_t workSpaceCapacity);
Prepare a flood fill with pixel callbacks, actual pixel dimensions and a caller-owned workspace kept alive during painting. A 64-byte workspace is a useful starting point. False indicates invalid setup.
Painter.h · -lbgraph
Painter_INVALID_ARGUMENT
Painter_INVALID_ARGUMENT = 1
A Painter_paint status. Check invalid coordinates or colors for an argument failure and increase the Painter workspace for an out-of-stack result.
Painter.h · -lbgraph
Painter_NO_ERROR
Painter_NO_ERROR = 0
A Painter_paint status. Check invalid coordinates or colors for an argument failure and increase the Painter workspace for an out-of-stack result.
Painter.h · -lbgraph
Painter_OUT_OF_STACK
Painter_OUT_OF_STACK = 2
A Painter_paint status. Check invalid coordinates or colors for an argument failure and increase the Painter workspace for an out-of-stack result.
Painter.h · -lbgraph
Painter_paint
byte Painter_paint(Painter *p, word x, byte y, byte newColor, byte oldColor, void *cookie);
Fill from (x,y) using the configured callbacks and their cookie. Give distinct old and new color indices. Painter_OUT_OF_STACK means this shape exceeded the supplied scratch buffer.
Painter.h · -lbgraph
Painter_setPixelFuncPtr
typedef void (*Painter_setPixelFuncPtr)(word x, byte y, byte color, void *cookie);
A callback type. Implement the shown return and argument types exactly. Keep any supplied user data alive while the library can call back.
Painter.h · -lbgraph
Primitive.h
Plot one pixel or draw lines and shapes using a buffer-specific callback. Add bgraph under Project Settings → Libraries, or link with -lbgraph in your Makefile.
Save the bgraph example for this book
Primitive_15DegreeCircleArcs · Primitive_circle · Primitive_ellipse · Primitive_filledRectangle · Primitive_getAddressAndMaskPmode3 · Primitive_getAddressAndMaskPmode4 · Primitive_getPixel256x16 · Primitive_getPixel320x16 · Primitive_getPixelFuncPtr · Primitive_getPixelPmode3 · Primitive_getPixelPmode4 · Primitive_line · Primitive_lineFuncPtr · Primitive_rectangle · Primitive_setPixel256x16 · Primitive_setPixel320x16 · Primitive_setPixelFuncPtr · Primitive_setPixelPmode3 · Primitive_setPixelPmode4
Primitive_15DegreeCircleArcs
void Primitive_15DegreeCircleArcs(word x, byte y, word radius, byte arcBegin, byte arcEnd, byte color, Primitive_lineFuncPtr drawLine, Primitive_setPixelFuncPtr setPixel, void *cookie);
Use a pixel callback for the current buffer and keep the whole shape in bounds. Ellipse scale factors use 256 for one whole unit; the arc routine measures angles in 15-degree steps.
Primitive.h · -lbgraph
Primitive_circle
Primitive_circle(x,y,radius,color,setPixel,cookie)
Use a pixel callback for the current buffer and keep the whole shape in bounds. Ellipse scale factors use 256 for one whole unit; the arc routine measures angles in 15-degree steps.
Primitive.h · -lbgraph
Primitive_ellipse
void Primitive_ellipse(word x, byte y, word radius, byte color, word horizontalFactor, word verticalFactor, Primitive_setPixelFuncPtr setPixel, void *cookie);
Use a pixel callback for the current buffer and keep the whole shape in bounds. Ellipse scale factors use 256 for one whole unit; the arc routine measures angles in 15-degree steps.
Primitive.h · -lbgraph
Primitive_filledRectangle
void Primitive_filledRectangle(word x0, byte y0, word x1, byte y1, byte color, Primitive_setPixelFuncPtr setPixel, void *cookie);
Draw between inclusive pixel coordinates using the supplied pixel callback. Pass its required buffer or state as cookie. Clip coordinates to that buffer before drawing.
Primitive.h · -lbgraph
Primitive_getAddressAndMaskPmode3
void Primitive_getAddressAndMaskPmode3(word x, byte y, byte color, void *pmode3Buffer, byte **bytePtr, byte *andMask, byte *orMask);
A PMODE 3 buffer holds 128 × 192 two-bit pixels in 6,144 bytes. Use x 0–127, y 0–191 and a color of 0–3. The mask helper gives a byte address and the single-pixel masks.
Primitive.h · -lbgraph
Primitive_getAddressAndMaskPmode4
void Primitive_getAddressAndMaskPmode4(word x, byte y, byte color, void *pmode4Buffer, byte **bytePtr, byte *andMask, byte *orMask);
A PMODE 4 buffer holds 256 × 192 one-bit pixels in 6,144 bytes. Use x 0–255, y 0–191 and a color of 0 or 1. The mask helper returns an address and masks for changing one pixel while preserving its neighbors.
Primitive.h · -lbgraph
Primitive_getPixel256x16
byte Primitive_getPixel256x16(word x, byte y, void *screenBuffer);
Work in a 256-wide, four-bit pixel buffer. Two neighboring pixels share a byte, so each row takes 128 bytes. Supply x 0–255, y within the buffer height and a color index 0–15.
Primitive.h · -lbgraph
Primitive_getPixel320x16
byte Primitive_getPixel320x16(word x, byte y, void *screenBuffer);
Work in a 320-wide, four-bit pixel buffer. Its stride is 160 bytes per row. Use x 0–319, y within the allocated height and a color index 0–15. These calls access the supplied buffer whether or not that buffer is currently visible.
Primitive.h · -lbgraph · See it used in beacon.c
Primitive_getPixelFuncPtr
typedef byte (*Primitive_getPixelFuncPtr)(word x, byte y, void *cookie);
A callback type. Implement the shown return and argument types exactly. Keep any supplied user data alive while the library can call back.
Primitive.h · -lbgraph
Primitive_getPixelPmode3
byte Primitive_getPixelPmode3(word x, byte y, void *pmode3Buffer);
A PMODE 3 buffer holds 128 × 192 two-bit pixels in 6,144 bytes. Use x 0–127, y 0–191 and a color of 0–3. The mask helper gives a byte address and the single-pixel masks.
Primitive.h · -lbgraph
Primitive_getPixelPmode4
byte Primitive_getPixelPmode4(word x, byte y, void *pmode4Buffer);
A PMODE 4 buffer holds 256 × 192 one-bit pixels in 6,144 bytes. Use x 0–255, y 0–191 and a color of 0 or 1. The mask helper returns an address and masks for changing one pixel while preserving its neighbors.
Primitive.h · -lbgraph
Primitive_line
void Primitive_line(word x0, byte y0, word x1, byte y1, byte color, Primitive_setPixelFuncPtr setPixel, void *cookie);
Draw between inclusive pixel coordinates using the supplied pixel callback. Pass its required buffer or state as cookie. Clip coordinates to that buffer before drawing.
Primitive.h · -lbgraph
Primitive_lineFuncPtr
typedef void (*Primitive_lineFuncPtr)(word x0, byte y0, word x1, byte y1, byte color, Primitive_setPixelFuncPtr setPixel, void *cookie);
A callback type. Implement the shown return and argument types exactly. Keep any supplied user data alive while the library can call back.
Primitive.h · -lbgraph
Primitive_rectangle
void Primitive_rectangle(word x0, byte y0, word x1, byte y1, byte color, Primitive_setPixelFuncPtr setPixel, void *cookie);
Draw between inclusive pixel coordinates using the supplied pixel callback. Pass its required buffer or state as cookie. Clip coordinates to that buffer before drawing.
Primitive.h · -lbgraph
Primitive_setPixel256x16
void Primitive_setPixel256x16(word x, byte y, byte color, void *screenBuffer);
Work in a 256-wide, four-bit pixel buffer. Two neighboring pixels share a byte, so each row takes 128 bytes. Supply x 0–255, y within the buffer height and a color index 0–15.
Primitive.h · -lbgraph
Primitive_setPixel320x16
void Primitive_setPixel320x16(word x, byte y, byte color, void *screenBuffer);
Work in a 320-wide, four-bit pixel buffer. Its stride is 160 bytes per row. Use x 0–319, y within the allocated height and a color index 0–15. These calls access the supplied buffer whether or not that buffer is currently visible.
Primitive.h · -lbgraph · See it used in beacon.c
Primitive_setPixelFuncPtr
typedef void (*Primitive_setPixelFuncPtr)(word x, byte y, byte color, void *cookie);
A callback type. Implement the shown return and argument types exactly. Keep any supplied user data alive while the library can call back.
Primitive.h · -lbgraph
Primitive_setPixelPmode3
void Primitive_setPixelPmode3(word x, byte y, byte color, void *pmode3Buffer);
A PMODE 3 buffer holds 128 × 192 two-bit pixels in 6,144 bytes. Use x 0–127, y 0–191 and a color of 0–3. The mask helper gives a byte address and the single-pixel masks.
Primitive.h · -lbgraph
Primitive_setPixelPmode4
void Primitive_setPixelPmode4(word x, byte y, byte color, void *pmode4Buffer);
A PMODE 4 buffer holds 256 × 192 one-bit pixels in 6,144 bytes. Use x 0–255, y 0–191 and a color of 0 or 1. The mask helper returns an address and masks for changing one pixel while preserving its neighbors.
Primitive.h · -lbgraph
Trig.h
Use 15-degree sine and cosine increments without floating point. Add bgraph under Project Settings → Libraries, or link with -lbgraph in your Makefile.
Save the bgraph example for this book
compute15DegreeCosSin · cosSin15DegreeTable · CosSinFactorCouple
compute15DegreeCosSin
void compute15DegreeCosSin(byte i, BOOL *cosNegated, word *cosAbsValue, BOOL *sinNegated, word *sinAbsValue);
Express the angle in 15-degree steps: index 0 is 0°, 6 is 90° and 24 is 360°. The helper returns a separate sign and unsigned magnitude scaled to 65,535 for each result.
Trig.h · -lbgraph
cosSin15DegreeTable
extern const CosSinFactorCouple cosSin15DegreeTable[4];
Express the angle in 15-degree steps: index 0 is 0°, 6 is 90° and 24 is 360°. The helper returns a separate sign and unsigned magnitude scaled to 65,535 for each result.
Trig.h · -lbgraph
CosSinFactorCouple
typedef struct CosSinFactorCouple { … } CosSinFactorCouple;
One pair of unsigned sine/cosine magnitudes in the 15-degree lookup table. Use compute15DegreeCosSin to obtain the quadrant signs.
Trig.h · -lbgraph
semigr.h
Manipulate legacy semigraphics pixel buffers. Add bgraph under Project Settings → Libraries, or link with -lbgraph in your Makefile.
Save the bgraph example for this book
GetPixelFunction · getPixelSG12 · getPixelSG24 · getPixelSG8 · SetPixelFunction · setPixelSG12 · setPixelSG24 · setPixelSG8 · sgMode
GetPixelFunction
typedef byte (*GetPixelFunction)(byte *screenBuffer, byte x, byte y);
A callback type. Implement the shown return and argument types exactly. Keep any supplied user data alive while the library can call back.
semigr.h · -lbgraph
getPixelSG12
byte getPixelSG12(byte *screenBuffer, byte x, byte y);
Use an SG12 buffer. The grid spans x 0–63 and y 0–95. Changing buffer bytes and observing that mode on the hardware are separate checks.
semigr.h · -lbgraph
getPixelSG24
byte getPixelSG24(byte *screenBuffer, byte x, byte y);
Use an SG24 buffer. The grid spans x 0–63 and y 0–191. Match the buffer format and color convention before drawing.
semigr.h · -lbgraph
getPixelSG8
byte getPixelSG8(byte *screenBuffer, byte x, byte y);
Use an SG8 buffer. The grid spans x 0–63 and y 0–63. The returned byte is the pixel’s color index.
semigr.h · -lbgraph
SetPixelFunction
typedef void (*SetPixelFunction)(byte *screenBuffer, byte x, byte y, byte color);
A callback type. Implement the shown return and argument types exactly. Keep any supplied user data alive while the library can call back.
semigr.h · -lbgraph
setPixelSG12
void setPixelSG12(byte *screenBuffer, byte x, byte y, byte color);
Use an SG12 buffer. The grid spans x 0–63 and y 0–95. Changing buffer bytes and observing that mode on the hardware are separate checks.
semigr.h · -lbgraph
setPixelSG24
void setPixelSG24(byte *screenBuffer, byte x, byte y, byte color);
Use an SG24 buffer. The grid spans x 0–63 and y 0–191. Match the buffer format and color convention before drawing.
semigr.h · -lbgraph
setPixelSG8
void setPixelSG8(byte *screenBuffer, byte x, byte y, byte color);
Use an SG8 buffer. The grid spans x 0–63 and y 0–63. The returned byte is the pixel’s color index.
semigr.h · -lbgraph
sgMode
BOOL sgMode(byte mode, void *screenBuffer);
Select a semigraphics format and its buffer. Pass mode 8, 12 or 24, or 0 for ordinary SG4. Check its Boolean result and the display’s hardware support.
semigr.h · -lbgraph
Player.h
Generate music with the CoCo sound DAC and interrupt timer. Add bsound under Project Settings → Libraries, or link with -lbsound in your Makefile.
Save the bsound example for this book
Player · Player_continuationFuncPtr · PLAYER_DAC_SAMPLE_VALUE_SHIFT · Player_defaultIRQService · Player_disableSound · Player_enableSound · Player_getSamplePlayDelayLength · Player_init · PLAYER_MAX_AMPLITUDE · PLAYER_MAX_LEVEL · PLAYER_MID_LEVEL · PLAYER_MIN_LEVEL · Player_play · Player_playSample · Player_shutdown · Player_sound
Player
typedef struct Player { … } Player;
Keep one Player alive throughout playback. Pass true for library-owned 60 Hz IRQ service, or false and supply one tick yourself every sixtieth of a second. Choose one clock source. Shutdown removes the library’s hook when installed and disables its analog output.
Player.h · -lbsound · See it used in tone.c
Player_continuationFuncPtr
typedef BOOL (*Player_continuationFuncPtr)(void);
A callback type. Implement the shown return and argument types exactly. Keep any supplied user data alive while the library can call back.
Player.h · -lbsound
PLAYER_DAC_SAMPLE_VALUE_SHIFT
PLAYER_DAC_SAMPLE_VALUE_SHIFT = 2
The guest DAC accepts six significant bits. Player samples store them in the upper six bits of a byte. Use the shift constant when turning levels into sample bytes.
Player.h · -lbsound
Player_defaultIRQService
void Player_defaultIRQService(void);
Keep one Player alive throughout playback. Pass true for library-owned 60 Hz IRQ service, or false and supply one tick yourself every sixtieth of a second. Choose one clock source. Shutdown removes the library’s hook when installed and disables its analog output.
Player.h · -lbsound
Player_disableSound
void Player_disableSound(void);
Open or close the analog path to the CoCo sound output. This shares hardware with joystick measurements.
Player.h · -lbsound
Player_enableSound
void Player_enableSound(void);
Open or close the analog path to the CoCo sound output. This shares hardware with joystick measurements.
Player.h · -lbsound
Player_getSamplePlayDelayLength
word Player_getSamplePlayDelayLength(unsigned long cpuCyclesPerSecond, word playBackFrequencyInHz);
Provide a nonempty sample buffer and a pointer one byte past the last sample. Each byte uses its upper six bits for the DAC. Use CPU frequency and sample rate in Hz to compute the delay. Sample playback expects the 60 Hz IRQ disabled, unlike Player_sound.
Player.h · -lbsound
Player_init
void Player_init(Player *player, BOOL useInternalIRQService, Player_continuationFuncPtr contFuncPtr);
Keep one Player alive throughout playback. Pass true for library-owned 60 Hz IRQ service, or false and supply one tick yourself every sixtieth of a second. Choose one clock source. Shutdown removes the library’s hook when installed and disables its analog output.
Player.h · -lbsound · See it used in tone.c
PLAYER_MAX_AMPLITUDE
PLAYER_MAX_AMPLITUDE = 31
The guest DAC accepts six significant bits. Player samples store them in the upper six bits of a byte. Use the shift constant when turning levels into sample bytes.
Player.h · -lbsound
PLAYER_MAX_LEVEL
PLAYER_MAX_LEVEL = 63
The guest DAC accepts six significant bits. Player samples store them in the upper six bits of a byte. Use the shift constant when turning levels into sample bytes.
Player.h · -lbsound
PLAYER_MID_LEVEL
PLAYER_MID_LEVEL = 31
The guest DAC accepts six significant bits. Player samples store them in the upper six bits of a byte. Use the shift constant when turning levels into sample bytes.
Player.h · -lbsound
PLAYER_MIN_LEVEL
PLAYER_MIN_LEVEL = 0
The guest DAC accepts six significant bits. Player samples store them in the upper six bits of a byte. Use the shift constant when turning levels into sample bytes.
Player.h · -lbsound
Player_play
const char *Player_play(const char *script);
Play an Extended BASIC-style note string with interrupts ticking. NULL means the script finished or your continuation callback requested a stop. Any other return points to the rejected character. X substring commands and variable substitution are unsupported.
Player.h · -lbsound
Player_playSample
void Player_playSample(const void *sampleArray, const void *sampleArrayEnd, word delayLength);
Provide a nonempty sample buffer and a pointer one byte past the last sample. Each byte uses its upper six bits for the DAC. Use CPU frequency and sample rate in Hz to compute the delay. Sample playback expects the 60 Hz IRQ disabled, unlike Player_sound.
Player.h · -lbsound
Player_shutdown
void Player_shutdown(void);
Keep one Player alive throughout playback. Pass true for library-owned 60 Hz IRQ service, or false and supply one tick yourself every sixtieth of a second. Choose one clock source. Shutdown removes the library’s hook when installed and disables its analog output.
Player.h · -lbsound · See it used in tone.c
Player_sound
void Player_sound(byte tone, byte duration);
With the player initialized and its 60 Hz IRQ running, play a tone and duration from 1–255. Invalid arguments produce no tone.
Player.h · -lbsound · See it used in tone.c
SquareWaveGenerator.h
Produce square-wave samples for a chosen amplitude and period. Add bsound under Project Settings → Libraries, or link with -lbsound in your Makefile.
Save the bsound example for this book
SquareWaveGenerator · SquareWaveGenerator_getNextSamples · SquareWaveGenerator_init · SquareWaveGenerator_setNextNote
SquareWaveGenerator
typedef struct SquareWaveGenerator { … } SquareWaveGenerator;
The guest DAC accepts six significant bits. Player samples store them in the upper six bits of a byte. Use the shift constant when turning levels into sample bytes.
SquareWaveGenerator.h · -lbsound
SquareWaveGenerator_getNextSamples
void SquareWaveGenerator_getNextSamples(SquareWaveGenerator *self, byte *begin, byte *end);
Prepare a square wave using an amplitude and half-period measured in samples. Write into the nonempty caller-supplied range up to but excluding end. A pending note change takes effect at the period boundary.
SquareWaveGenerator.h · -lbsound
SquareWaveGenerator_init
void SquareWaveGenerator_init(SquareWaveGenerator *self, byte diffFromMidLevel, size_t numSamplesInHalfPeriod);
Prepare a square wave using an amplitude and half-period measured in samples. Write into the nonempty caller-supplied range up to but excluding end. A pending note change takes effect at the period boundary.
SquareWaveGenerator.h · -lbsound
SquareWaveGenerator_setNextNote
void SquareWaveGenerator_setNextNote(SquareWaveGenerator *self, size_t numSamplesInHalfPeriod);
Prepare a square wave using an amplitude and half-period measured in samples. Write into the nonempty caller-supplied range up to but excluding end. A pending note change takes effect at the period boundary.
SquareWaveGenerator.h · -lbsound
cardgame.h
Build a deck, select a card and render game graphics. Add cardgame under Project Settings → Libraries, or link with -lcardgame in your Makefile.
Save the cardgame example for this book
BAD_CARD_SUIT · BAD_CARD_VALUE · BAD_INDEX · beep · BEEP_MAX_VOL · BEEP_MIN_VOL · BYTES_PER_CARD_WIDTH · closeCardGame · drawCompiledCard · drawCompiledCard2 · drawCompiledPixMap · drawFaceDownCard · drawSuit · eraseCard · getCardType · getCardValue · getNumPixelRowsPerCard · getSuitName · getTicksForFrequency · initSound · NUMCARDS · openCardGame · pickCardFromDeck · ROWS_ABOVE_SUIT · ROWS_BELOW_SUIT · ROWS_PER_CARD_BOTTOM · ROWS_PER_CARD_TOP · ROWS_PER_CARD_VALUE · ROWS_PER_SUIT · shuffleDeck · SUIT_CLUBS · SUIT_DIAMONDS · SUIT_HEARTS · SUIT_JOKER · SUIT_NONE · SUIT_SPADES · whiteNoise
BAD_CARD_SUIT
BAD_CARD_SUIT = 0xFF
CardGame’s deck includes the usual four suits and two jokers. The named bad values represent an invalid suit, rank or index; do not use them to index the drawing tables.
cardgame.h · -lcardgame
BAD_CARD_VALUE
BAD_CARD_VALUE = 0
CardGame’s deck includes the usual four suits and two jokers. The named bad values represent an invalid suit, rank or index; do not use them to index the drawing tables.
cardgame.h · -lcardgame
BAD_INDEX
BAD_INDEX = 0xFF
CardGame’s deck includes the usual four suits and two jokers. The named bad values represent an invalid suit, rank or index; do not use them to index the drawing tables.
cardgame.h · -lcardgame
beep
void beep(byte duration, word ticks, byte volume);
Initialize this card library’s sound support before use. getTicksForFrequency converts Hz to the period value used by beep. Keep the period positive and the volume within BEEP_MAX_VOL.
cardgame.h · -lcardgame
BEEP_MAX_VOL
BEEP_MAX_VOL = 63
Volume limits for CardGame’s beep and whiteNoise. Initialize its sound hardware first.
cardgame.h · -lcardgame
BEEP_MIN_VOL
BEEP_MIN_VOL = 0
Volume limits for CardGame’s beep and whiteNoise. Initialize its sound hardware first.
cardgame.h · -lcardgame
BYTES_PER_CARD_WIDTH
BYTES_PER_CARD_WIDTH = 4
Layout of CardGame’s compiled artwork. Vertical measurements are pixel rows; horizontal width counts bytes in the PMODE 4 buffer.
cardgame.h · -lcardgame
closeCardGame
void closeCardGame(void);
Reserve the aligned 6,144-byte PMODE 4 buffer before opening a graphics game. The open/close pairs own their screen and console state while active. Use screen(0,0) when returning to ordinary 32-column text.
cardgame.h · -lcardgame
drawCompiledCard
void drawCompiledCard(byte cardValue, byte cardSuit, byte byteColumn, byte pixelRow);
Work on the prepared game buffer. Horizontal card columns are byte offsets (0–28 for a full card), while vertical position is in pixel rows. A 32-pixel-wide card uses four bytes per row.
cardgame.h · -lcardgame
drawCompiledCard2
void drawCompiledCard2(byte cardValue, byte cardSuit, byte byteColumn, byte pixelRow, char suitRowOffset, byte maxNumRowsToDraw);
Work on the prepared game buffer. Horizontal card columns are byte offsets (0–28 for a full card), while vertical position is in pixel rows. A 32-pixel-wide card uses four bytes per row.
cardgame.h · -lcardgame
drawCompiledPixMap
byte *drawCompiledPixMap(byte byteOffset, byte pixelRow, const word *wordArray, byte numRows, byte rowRepetitions);
A compiled picture supplies one 16-bit row per input element. Both source rows and repetition count must be positive. Use the height query when planning the card’s on-screen bounds.
cardgame.h · -lcardgame
drawFaceDownCard
void drawFaceDownCard(byte rowInPixels, byte colInBytes);
Work on the prepared game buffer. Horizontal card columns are byte offsets (0–28 for a full card), while vertical position is in pixel rows. A 32-pixel-wide card uses four bytes per row.
cardgame.h · -lcardgame
drawSuit
void drawSuit(byte col, byte row, byte suit);
Work on the prepared game buffer. Horizontal card columns are byte offsets (0–28 for a full card), while vertical position is in pixel rows. A 32-pixel-wide card uses four bytes per row.
cardgame.h · -lcardgame
eraseCard
void eraseCard(byte byteColumn, byte pixelRow);
Work on the prepared game buffer. Horizontal card columns are byte offsets (0–28 for a full card), while vertical position is in pixel rows. A 32-pixel-wide card uses four bytes per row.
cardgame.h · -lcardgame
getCardType
byte getCardType(byte card);
Decode a card to a suit and value. Ordinary ranks are 1–13; jokers use their own suit and values 1–2. Check for BAD_CARD_SUIT or BAD_CARD_VALUE on unexpected input. Suit names are borrowed strings.
cardgame.h · -lcardgame
getCardValue
byte getCardValue(byte card);
Decode a card to a suit and value. Ordinary ranks are 1–13; jokers use their own suit and values 1–2. Check for BAD_CARD_SUIT or BAD_CARD_VALUE on unexpected input. Suit names are borrowed strings.
cardgame.h · -lcardgame
getNumPixelRowsPerCard
byte getNumPixelRowsPerCard();
A compiled picture supplies one 16-bit row per input element. Both source rows and repetition count must be positive. Use the height query when planning the card’s on-screen bounds.
cardgame.h · -lcardgame
getSuitName
const char *getSuitName(byte suit);
Decode a card to a suit and value. Ordinary ranks are 1–13; jokers use their own suit and values 1–2. Check for BAD_CARD_SUIT or BAD_CARD_VALUE on unexpected input. Suit names are borrowed strings.
cardgame.h · -lcardgame
getTicksForFrequency
word getTicksForFrequency(word hertz);
Initialize this card library’s sound support before use. getTicksForFrequency converts Hz to the period value used by beep. Keep the period positive and the volume within BEEP_MAX_VOL.
cardgame.h · -lcardgame
initSound
void initSound();
Initialize this card library’s sound support before use. getTicksForFrequency converts Hz to the period value used by beep. Keep the period positive and the volume within BEEP_MAX_VOL.
cardgame.h · -lcardgame
NUMCARDS
NUMCARDS = 54
CardGame’s deck includes the usual four suits and two jokers. The named bad values represent an invalid suit, rank or index; do not use them to index the drawing tables.
cardgame.h · -lcardgame
openCardGame
void openCardGame(void *_scrnBuffer, byte _emulatePMode4OnCoCo3);
Reserve the aligned 6,144-byte PMODE 4 buffer before opening a graphics game. The open/close pairs own their screen and console state while active. Use screen(0,0) when returning to ordinary 32-column text.
cardgame.h · -lcardgame
pickCardFromDeck
byte pickCardFromDeck(byte deck[], byte *pNumCards);
Keep a mutable deck array and its current count. Shuffle the chosen number of cards, then pass the address of the count to deal one. Check that a card remains before dealing.
cardgame.h · -lcardgame · See it used in deal.c
ROWS_ABOVE_SUIT
ROWS_ABOVE_SUIT = 2
Layout of CardGame’s compiled artwork. Vertical measurements are pixel rows; horizontal width counts bytes in the PMODE 4 buffer.
cardgame.h · -lcardgame
ROWS_BELOW_SUIT
ROWS_BELOW_SUIT = 6
Layout of CardGame’s compiled artwork. Vertical measurements are pixel rows; horizontal width counts bytes in the PMODE 4 buffer.
cardgame.h · -lcardgame
ROWS_PER_CARD_BOTTOM
ROWS_PER_CARD_BOTTOM = ROWS_PER_CARD_TOP
Layout of CardGame’s compiled artwork. Vertical measurements are pixel rows; horizontal width counts bytes in the PMODE 4 buffer.
cardgame.h · -lcardgame
ROWS_PER_CARD_TOP
ROWS_PER_CARD_TOP = 5
Layout of CardGame’s compiled artwork. Vertical measurements are pixel rows; horizontal width counts bytes in the PMODE 4 buffer.
cardgame.h · -lcardgame
ROWS_PER_CARD_VALUE
ROWS_PER_CARD_VALUE = 10
Layout of CardGame’s compiled artwork. Vertical measurements are pixel rows; horizontal width counts bytes in the PMODE 4 buffer.
cardgame.h · -lcardgame
ROWS_PER_SUIT
ROWS_PER_SUIT = 7
Layout of CardGame’s compiled artwork. Vertical measurements are pixel rows; horizontal width counts bytes in the PMODE 4 buffer.
cardgame.h · -lcardgame
shuffleDeck
void shuffleDeck(byte deck[], byte numCards);
Keep a mutable deck array and its current count. Shuffle the chosen number of cards, then pass the address of the count to deal one. Check that a card remains before dealing.
cardgame.h · -lcardgame
SUIT_CLUBS
SUIT_CLUBS = 3
CardGame’s deck includes the usual four suits and two jokers. The named bad values represent an invalid suit, rank or index; do not use them to index the drawing tables.
cardgame.h · -lcardgame
SUIT_DIAMONDS
SUIT_DIAMONDS = 2
CardGame’s deck includes the usual four suits and two jokers. The named bad values represent an invalid suit, rank or index; do not use them to index the drawing tables.
cardgame.h · -lcardgame
SUIT_HEARTS
SUIT_HEARTS = 0
CardGame’s deck includes the usual four suits and two jokers. The named bad values represent an invalid suit, rank or index; do not use them to index the drawing tables.
cardgame.h · -lcardgame
SUIT_JOKER
SUIT_JOKER = 4
CardGame’s deck includes the usual four suits and two jokers. The named bad values represent an invalid suit, rank or index; do not use them to index the drawing tables.
cardgame.h · -lcardgame
SUIT_NONE
SUIT_NONE = 255
CardGame’s deck includes the usual four suits and two jokers. The named bad values represent an invalid suit, rank or index; do not use them to index the drawing tables.
cardgame.h · -lcardgame
SUIT_SPADES
SUIT_SPADES = 1
CardGame’s deck includes the usual four suits and two jokers. The named bad values represent an invalid suit, rank or index; do not use them to index the drawing tables.
cardgame.h · -lcardgame
whiteNoise
void whiteNoise(word duration, word spacing, byte volume);
Initialize this card library’s sound support before use. getTicksForFrequency converts Hz to the period value used by beep. Keep the period positive and the volume within BEEP_MAX_VOL.
cardgame.h · -lcardgame
pmode4game.h
Set up the game buffer, graphics cursor, text and keyboard interaction. Add cardgame under Project Settings → Libraries, or link with -lcardgame in your Makefile.
Save the cardgame example for this book
assertf · BYTES_PER_SCREEN · BYTES_PER_SCREEN_ROW · BYTES_PER_TEXT_ROW · closePMode4Game · concat · drawChar · drawCharAtAddressWithoutMovingCursor · drawCharWithoutMovingCursor · emulatingPMode4OnCoCo3 · enableInvertedColorText · getCurrentCharPos · getCursor · GetTimerFunction · hiResTextConsoleOutHook · invertCharAtCursor · invertCharAtCursorExceptRowBelowGlyph · KeyboardPollFunction · makeSpacesTransparent · moveCursor · moveCursorLeft · oldCHROUT · openPMode4Game · optDelay · PIXEL_ROWS_PER_GLYPH · PIXEL_ROWS_PER_SCREEN · PIXEL_ROWS_PER_TEXT_ROW · printCentered · readLineFromKeyboard · scrnBuffer · setColorInversionMask · setInvertedColorsParameters · setScreenBuffer · setScreenBuffer2 · setTextAreaScrollCallback · TEXT_COLS_PER_ROW · TEXT_ROWS_PER_SCREEN · TextAreaScrollCallback · textPosX · textPosY · waitForKeyWithAnimatedCursor · WORDS_PER_SCREEN_ROW
assertf
assertf(cond,...)
Report an assertion using formatted text. Its visibility and action depend on the build’s assertion settings.
pmode4game.h · -lcardgame
BYTES_PER_SCREEN
BYTES_PER_SCREEN = 0x1800
Size or stride for the renderer named below. A pixel row, a text row and a byte count measure different parts of the screen. Use the constant from the same header as your drawing function.
pmode4game.h · -lcardgame
BYTES_PER_SCREEN_ROW
BYTES_PER_SCREEN_ROW = 32
Size or stride for the renderer named below. A pixel row, a text row and a byte count measure different parts of the screen. Use the constant from the same header as your drawing function.
pmode4game.h · -lcardgame
BYTES_PER_TEXT_ROW
BYTES_PER_TEXT_ROW = 256
Size or stride for the renderer named below. A pixel row, a text row and a byte count measure different parts of the screen. Use the constant from the same header as your drawing function.
pmode4game.h · -lcardgame
closePMode4Game
void closePMode4Game(void);
Reserve the aligned 6,144-byte PMODE 4 buffer before opening a graphics game. The open/close pairs own their screen and console state while active. Use screen(0,0) when returning to ordinary 32-column text.
pmode4game.h · -lcardgame
concat
void concat(char *out, unsigned max, ...);
Join the supplied pieces into a bounded result. max includes space for the final zero. Follow the string argument list with a null pointer.
pmode4game.h · -lcardgame
drawChar
void drawChar(unsigned char c);
Draw a character onto the game graphics buffer. The explicit-address form requires writable bytes for each raster row. The stationary forms preserve the text position.
pmode4game.h · -lcardgame
drawCharAtAddressWithoutMovingCursor
void drawCharAtAddressWithoutMovingCursor(unsigned char c, byte *dest, BOOL drawBottomRow);
Draw a character onto the game graphics buffer. The explicit-address form requires writable bytes for each raster row. The stationary forms preserve the text position.
pmode4game.h · -lcardgame
drawCharWithoutMovingCursor
void drawCharWithoutMovingCursor(unsigned char c);
Draw a character onto the game graphics buffer. The explicit-address form requires writable bytes for each raster row. The stationary forms preserve the text position.
pmode4game.h · -lcardgame
emulatingPMode4OnCoCo3
extern byte emulatingPMode4OnCoCo3;
State maintained by the active game renderer. The text position counts character cells and the emulation flag distinguishes the CoCo 3 compatibility display.
pmode4game.h · -lcardgame
enableInvertedColorText
void enableInvertedColorText(BOOL enabled);
Change how later character drawing combines glyph pixels with the background. Transparent spaces preserve pixels already in the game image.
pmode4game.h · -lcardgame
getCurrentCharPos
byte *getCurrentCharPos(void);
Borrow the address of the top-left byte for the current 8×8 glyph in the graphics text buffer.
pmode4game.h · -lcardgame
getCursor
void getCursor(byte *x, byte *y);
Work in character columns and rows, starting at zero. Set or retrieve the coordinates using the active text renderer. HiresTxt and CardGame each export moveCursor; use the intended renderer and link library.
pmode4game.h · -lcardgame
GetTimerFunction
typedef word (*GetTimerFunction)(void *userdata);
A callback type. Implement the shown return and argument types exactly. Keep any supplied user data alive while the library can call back.
pmode4game.h · -lcardgame
hiResTextConsoleOutHook
void hiResTextConsoleOutHook();
The game renderer can intercept console output to draw characters in its PMODE 4 buffer. Preserve the previous hook for cleanup.
pmode4game.h · -lcardgame
invertCharAtCursor
void invertCharAtCursor(void);
Toggle the pixels occupied by the cursor cell in the game buffer. The shorter form excluding the bottom raster row preserves that row’s graphics.
pmode4game.h · -lcardgame
invertCharAtCursorExceptRowBelowGlyph
void invertCharAtCursorExceptRowBelowGlyph(void);
Toggle the pixels occupied by the cursor cell in the game buffer. The shorter form excluding the bottom raster row preserves that row’s graphics.
pmode4game.h · -lcardgame
KeyboardPollFunction
typedef byte (*KeyboardPollFunction)(void *userdata);
A callback type. Implement the shown return and argument types exactly. Keep any supplied user data alive while the library can call back.
pmode4game.h · -lcardgame
makeSpacesTransparent
void makeSpacesTransparent(BOOL transparent);
Change how later character drawing combines glyph pixels with the background. Transparent spaces preserve pixels already in the game image.
pmode4game.h · -lcardgame
moveCursor
void moveCursor(byte x, byte y);
Work in character columns and rows, starting at zero. Set or retrieve the coordinates using the active text renderer. HiresTxt and CardGame each export moveCursor; use the intended renderer and link library.
pmode4game.h · -lcardgame
moveCursorLeft
void moveCursorLeft(byte numColumns);
Work in character columns and rows, starting at zero. Set or retrieve the coordinates using the active text renderer. HiresTxt and CardGame each export moveCursor; use the intended renderer and link library.
pmode4game.h · -lcardgame
oldCHROUT
extern ConsoleOutHook oldCHROUT;
The game renderer can intercept console output to draw characters in its PMODE 4 buffer. Preserve the previous hook for cleanup.
pmode4game.h · -lcardgame
openPMode4Game
void openPMode4Game(void *_scrnBuffer, byte _emulatePMode4OnCoCo3);
Reserve the aligned 6,144-byte PMODE 4 buffer before opening a graphics game. The open/close pairs own their screen and console state while active. Use screen(0,0) when returning to ordinary 32-column text.
pmode4game.h · -lcardgame
optDelay
optDelay(ticks)
Target-specific timing convenience for card-game code. Inspect its definition for the selected target before relying on a delay.
pmode4game.h · -lcardgame
PIXEL_ROWS_PER_GLYPH
PIXEL_ROWS_PER_GLYPH = 7
Size or stride for the renderer named below. A pixel row, a text row and a byte count measure different parts of the screen. Use the constant from the same header as your drawing function.
pmode4game.h · -lcardgame
PIXEL_ROWS_PER_SCREEN
PIXEL_ROWS_PER_SCREEN = 192
Size or stride for the renderer named below. A pixel row, a text row and a byte count measure different parts of the screen. Use the constant from the same header as your drawing function.
pmode4game.h · -lcardgame
PIXEL_ROWS_PER_TEXT_ROW
PIXEL_ROWS_PER_TEXT_ROW = 8
Size or stride for the renderer named below. A pixel row, a text row and a byte count measure different parts of the screen. Use the constant from the same header as your drawing function.
pmode4game.h · -lcardgame
printCentered
byte printCentered(byte row, const char *str);
Render a string centered on the requested text row. The return value is the starting column used.
pmode4game.h · -lcardgame
readLineFromKeyboard
BOOL readLineFromKeyboard(KeyboardPollFunction poll, void *userdata, word ticksPerCursorPeriod, GetTimerFunction getTimerValue, char *lineBuffer, size_t bufferSize);
Supply a polling function, timer callback and their user data. Keep the display buffer alive. For a line, check whether Enter accepted it or Break canceled it.
pmode4game.h · -lcardgame
scrnBuffer
extern byte *scrnBuffer;
Select a different buffer for graphics output. Under CoCo 3 PMODE emulation, the address convention depends on which setter is used; use the header for the active game configuration.
pmode4game.h · -lcardgame
setColorInversionMask
void setColorInversionMask(byte newColorInversionMask);
Change how later character drawing combines glyph pixels with the background. Transparent spaces preserve pixels already in the game image.
pmode4game.h · -lcardgame
setInvertedColorsParameters
void setInvertedColorsParameters(BOOL drawRowOverGlyph, BOOL drawColumnAtRightOfGlyph);
Change how later character drawing combines glyph pixels with the background. Transparent spaces preserve pixels already in the game image.
pmode4game.h · -lcardgame
setScreenBuffer
void setScreenBuffer(void *screen);
Select and display the supplied screen. In CoCo 3 PMODE emulation the address is relative to physical $70000. See setScreenBuffer2 when preparing an offscreen drawing buffer.
pmode4game.h · -lcardgame
setScreenBuffer2
void setScreenBuffer2(void *screen);
Select the library’s drawing buffer without changing the video mode or making the buffer visible.
pmode4game.h · -lcardgame
setTextAreaScrollCallback
void setTextAreaScrollCallback(TextAreaScrollCallback callback, void *userdata);
Install the scroll callback and its user data. The user data must remain valid when the renderer calls back.
pmode4game.h · -lcardgame
TEXT_COLS_PER_ROW
TEXT_COLS_PER_ROW = 32
Size or stride for the renderer named below. A pixel row, a text row and a byte count measure different parts of the screen. Use the constant from the same header as your drawing function.
pmode4game.h · -lcardgame
TEXT_ROWS_PER_SCREEN
TEXT_ROWS_PER_SCREEN = 24
Size or stride for the renderer named below. A pixel row, a text row and a byte count measure different parts of the screen. Use the constant from the same header as your drawing function.
pmode4game.h · -lcardgame
TextAreaScrollCallback
typedef void (*TextAreaScrollCallback)(void *userdata);
A callback type. Implement the shown return and argument types exactly. Keep any supplied user data alive while the library can call back.
pmode4game.h · -lcardgame
textPosX
extern byte textPosX;
State maintained by the active game renderer. The text position counts character cells and the emulation flag distinguishes the CoCo 3 compatibility display.
pmode4game.h · -lcardgame
textPosY
extern byte textPosY;
State maintained by the active game renderer. The text position counts character cells and the emulation flag distinguishes the CoCo 3 compatibility display.
pmode4game.h · -lcardgame
waitForKeyWithAnimatedCursor
byte waitForKeyWithAnimatedCursor(KeyboardPollFunction poll, void *userdata, word ticksPerCursorPeriod, GetTimerFunction getTimerValue);
Supply a polling function, timer callback and their user data. Keep the display buffer alive. For a line, check whether Enter accepted it or Break canceled it.
pmode4game.h · -lcardgame
WORDS_PER_SCREEN_ROW
WORDS_PER_SCREEN_ROW = 16
Size or stride for the renderer named below. A pixel row, a text row and a byte count measure different parts of the screen. Use the constant from the same header as your drawing function.
pmode4game.h · -lcardgame
8-bit-wide-font.h
Find the game renderer’s eight-pixel-wide glyph data. Add cardgame under Project Settings → Libraries, or link with -lcardgame in your Makefile.
eightBitWideFont
extern const unsigned char eightBitWideFont[65][7];
Library-owned glyph data. Use the renderer for the font’s dimensions and treat the original bytes as read-only.
8-bit-wide-font.h · -lcardgame
compiled-cards.h
Find the precomputed suit symbols, ranks and edges used for drawing cards. Add cardgame under Project Settings → Libraries, or link with -lcardgame in your Makefile.
Save the cardgame example for this book
blackCard_1 · blackCard_10 · blackCard_11 · blackCard_12 · blackCard_13 · blackCard_2 · blackCard_3 · blackCard_4 · blackCard_5 · blackCard_6 · blackCard_7 · blackCard_8 · blackCard_9 · blackCards · blackJokerSuit · blackJokerValue · cardBottomLeft · cardBottomRight · cardLeft · cardRight · cardTopLeft · cardTopRight · redCard_1 · redCard_10 · redCard_11 · redCard_12 · redCard_13 · redCard_2 · redCard_3 · redCard_4 · redCard_5 · redCard_6 · redCard_7 · redCard_8 · redCard_9 · redCards · redJokerSuit · redJokerValue · suit_clubs · suit_diamonds · suit_hearts · suit_spades · suits
blackCard_1
extern const unsigned short blackCard_1[10];
Precomputed graphics used by the card renderer. Treat this library-owned data as read-only.
compiled-cards.h · -lcardgame
blackCard_10
extern const unsigned short blackCard_10[10];
Precomputed graphics used by the card renderer. Treat this library-owned data as read-only.
compiled-cards.h · -lcardgame
blackCard_11
extern const unsigned short blackCard_11[10];
Precomputed graphics used by the card renderer. Treat this library-owned data as read-only.
compiled-cards.h · -lcardgame
blackCard_12
extern const unsigned short blackCard_12[10];
Precomputed graphics used by the card renderer. Treat this library-owned data as read-only.
compiled-cards.h · -lcardgame
blackCard_13
extern const unsigned short blackCard_13[10];
Precomputed graphics used by the card renderer. Treat this library-owned data as read-only.
compiled-cards.h · -lcardgame
blackCard_2
extern const unsigned short blackCard_2[10];
Precomputed graphics used by the card renderer. Treat this library-owned data as read-only.
compiled-cards.h · -lcardgame
blackCard_3
extern const unsigned short blackCard_3[10];
Precomputed graphics used by the card renderer. Treat this library-owned data as read-only.
compiled-cards.h · -lcardgame
blackCard_4
extern const unsigned short blackCard_4[10];
Precomputed graphics used by the card renderer. Treat this library-owned data as read-only.
compiled-cards.h · -lcardgame
blackCard_5
extern const unsigned short blackCard_5[10];
Precomputed graphics used by the card renderer. Treat this library-owned data as read-only.
compiled-cards.h · -lcardgame
blackCard_6
extern const unsigned short blackCard_6[10];
Precomputed graphics used by the card renderer. Treat this library-owned data as read-only.
compiled-cards.h · -lcardgame
blackCard_7
extern const unsigned short blackCard_7[10];
Precomputed graphics used by the card renderer. Treat this library-owned data as read-only.
compiled-cards.h · -lcardgame
blackCard_8
extern const unsigned short blackCard_8[10];
Precomputed graphics used by the card renderer. Treat this library-owned data as read-only.
compiled-cards.h · -lcardgame
blackCard_9
extern const unsigned short blackCard_9[10];
Precomputed graphics used by the card renderer. Treat this library-owned data as read-only.
compiled-cards.h · -lcardgame
blackCards
extern const unsigned short * const blackCards[13];
Precomputed graphics used by the card renderer. Treat this library-owned data as read-only.
compiled-cards.h · -lcardgame
blackJokerSuit
extern const unsigned short blackJokerSuit[7];
Precomputed graphics used by the card renderer. Treat this library-owned data as read-only.
compiled-cards.h · -lcardgame
blackJokerValue
extern const unsigned short blackJokerValue[10];
Precomputed graphics used by the card renderer. Treat this library-owned data as read-only.
compiled-cards.h · -lcardgame
cardBottomLeft
extern const unsigned short cardBottomLeft[5];
Precomputed graphics used by the card renderer. Treat this library-owned data as read-only.
compiled-cards.h · -lcardgame
cardBottomRight
extern const unsigned short cardBottomRight[5];
Precomputed graphics used by the card renderer. Treat this library-owned data as read-only.
compiled-cards.h · -lcardgame
cardLeft
extern const unsigned short cardLeft[1];
Precomputed graphics used by the card renderer. Treat this library-owned data as read-only.
compiled-cards.h · -lcardgame
cardRight
extern const unsigned short cardRight[1];
Precomputed graphics used by the card renderer. Treat this library-owned data as read-only.
compiled-cards.h · -lcardgame
cardTopLeft
extern const unsigned short cardTopLeft[5];
Precomputed graphics used by the card renderer. Treat this library-owned data as read-only.
compiled-cards.h · -lcardgame
cardTopRight
extern const unsigned short cardTopRight[5];
Precomputed graphics used by the card renderer. Treat this library-owned data as read-only.
compiled-cards.h · -lcardgame
redCard_1
extern const unsigned short redCard_1[10];
Precomputed graphics used by the card renderer. Treat this library-owned data as read-only.
compiled-cards.h · -lcardgame
redCard_10
extern const unsigned short redCard_10[10];
Precomputed graphics used by the card renderer. Treat this library-owned data as read-only.
compiled-cards.h · -lcardgame
redCard_11
extern const unsigned short redCard_11[10];
Precomputed graphics used by the card renderer. Treat this library-owned data as read-only.
compiled-cards.h · -lcardgame
redCard_12
extern const unsigned short redCard_12[10];
Precomputed graphics used by the card renderer. Treat this library-owned data as read-only.
compiled-cards.h · -lcardgame
redCard_13
extern const unsigned short redCard_13[10];
Precomputed graphics used by the card renderer. Treat this library-owned data as read-only.
compiled-cards.h · -lcardgame
redCard_2
extern const unsigned short redCard_2[10];
Precomputed graphics used by the card renderer. Treat this library-owned data as read-only.
compiled-cards.h · -lcardgame
redCard_3
extern const unsigned short redCard_3[10];
Precomputed graphics used by the card renderer. Treat this library-owned data as read-only.
compiled-cards.h · -lcardgame
redCard_4
extern const unsigned short redCard_4[10];
Precomputed graphics used by the card renderer. Treat this library-owned data as read-only.
compiled-cards.h · -lcardgame
redCard_5
extern const unsigned short redCard_5[10];
Precomputed graphics used by the card renderer. Treat this library-owned data as read-only.
compiled-cards.h · -lcardgame
redCard_6
extern const unsigned short redCard_6[10];
Precomputed graphics used by the card renderer. Treat this library-owned data as read-only.
compiled-cards.h · -lcardgame
redCard_7
extern const unsigned short redCard_7[10];
Precomputed graphics used by the card renderer. Treat this library-owned data as read-only.
compiled-cards.h · -lcardgame
redCard_8
extern const unsigned short redCard_8[10];
Precomputed graphics used by the card renderer. Treat this library-owned data as read-only.
compiled-cards.h · -lcardgame
redCard_9
extern const unsigned short redCard_9[10];
Precomputed graphics used by the card renderer. Treat this library-owned data as read-only.
compiled-cards.h · -lcardgame
redCards
extern const unsigned short * const redCards[13];
Precomputed graphics used by the card renderer. Treat this library-owned data as read-only.
compiled-cards.h · -lcardgame
redJokerSuit
extern const unsigned short redJokerSuit[7];
Precomputed graphics used by the card renderer. Treat this library-owned data as read-only.
compiled-cards.h · -lcardgame
redJokerValue
extern const unsigned short redJokerValue[10];
Precomputed graphics used by the card renderer. Treat this library-owned data as read-only.
compiled-cards.h · -lcardgame
suit_clubs
extern const unsigned short suit_clubs[7];
Precomputed graphics used by the card renderer. Treat this library-owned data as read-only.
compiled-cards.h · -lcardgame
suit_diamonds
extern const unsigned short suit_diamonds[7];
Precomputed graphics used by the card renderer. Treat this library-owned data as read-only.
compiled-cards.h · -lcardgame
suit_hearts
extern const unsigned short suit_hearts[7];
Precomputed graphics used by the card renderer. Treat this library-owned data as read-only.
compiled-cards.h · -lcardgame
suit_spades
extern const unsigned short suit_spades[7];
Precomputed graphics used by the card renderer. Treat this library-owned data as read-only.
compiled-cards.h · -lcardgame
suits
extern const unsigned short * const suits[4];
Precomputed graphics used by the card renderer. Treat this library-owned data as read-only.
compiled-cards.h · -lcardgame
Ebitor.h
Maintain an editable text buffer and a cursor through terminal callbacks. Add ebitor under Project Settings → Libraries, or link with -lebitor in your Makefile.
Save the ebitor example for this book
Ebitor · ebitor_clear · ebitor_clrtoeolFunc · Ebitor_findEOL · Ebitor_findSOL · Ebitor_findStringAndScrollToShow · Ebitor_getContentLength · ebitor_getCursorPosFunc · Ebitor_getInstance · Ebitor_getLogicalCursorOffset · Ebitor_getLogicalOffsetAtHome · Ebitor_init · ebitor_KEY_ARROW_DOWN · ebitor_KEY_ARROW_LEFT · ebitor_KEY_ARROW_RIGHT · ebitor_KEY_ARROW_UP · ebitor_KEY_ESCAPE · Ebitor_locateCursorAtSavedPosition · ebitor_locateFunc · ebitor_printFunc · ebitor_printPrefixFunc · Ebitor_processEditing · Ebitor_processKey · Ebitor_processUpOrDownArrowsAndRefresh · Ebitor_saveCursorPosition · ebitor_scrollTerminalDownFunc · ebitor_scrollTerminalUpFunc · Ebitor_scrollToShowLogicalOffset · Ebitor_setContentLength · Ebitor_setLogicalCursorAtBeginning · Ebitor_shutdown · ebitor_waitKeyFunc · INSERT_BUFFER_SIZE · InsertBuffer
Ebitor
typedef struct Ebitor { … } Ebitor;
Supply a persistent writable text buffer, its byte capacity, the terminal dimensions, and compatible screen and key callbacks. The editor manages one instance. Release it with shutdown before repurposing its buffer.
Ebitor.h · -lebitor · See it used in editlog.c
ebitor_clear
typedef void (*ebitor_clear)(void);
A callback type. Implement the shown return and argument types exactly. Keep any supplied user data alive while the library can call back.
Ebitor.h · -lebitor
ebitor_clrtoeolFunc
typedef void (*ebitor_clrtoeolFunc)(void);
A callback type. Implement the shown return and argument types exactly. Keep any supplied user data alive while the library can call back.
Ebitor.h · -lebitor
Ebitor_findEOL
size_t Ebitor_findEOL(size_t startOffset);
Locate the byte offset of the line beginning or its delimiter from a position within the text. The last unterminated line ends at the filled buffer length.
Ebitor.h · -lebitor
Ebitor_findSOL
size_t Ebitor_findSOL(size_t startOffset);
Locate the byte offset of the line beginning or its delimiter from a position within the text. The last unterminated line ends at the filled buffer length.
Ebitor.h · -lebitor
Ebitor_findStringAndScrollToShow
BOOL Ebitor_findStringAndScrollToShow(size_t startLogicalOffset, const char *strSearchedFor, size_t *foundLogicalOffset);
Search for a nonempty zero-terminated string starting at a byte offset, or display a known range. The search writes the found offset and scrolls only upon success.
Ebitor.h · -lebitor
Ebitor_getContentLength
size_t Ebitor_getContentLength(void);
After filling the text buffer, tell the editor how many bytes contain text. The length must fit the capacity supplied at init. Setting it repositions the cursor at the beginning.
Ebitor.h · -lebitor · See it used in editlog.c
ebitor_getCursorPosFunc
typedef void (*ebitor_getCursorPosFunc)(byte *column, byte *row);
A callback type. Implement the shown return and argument types exactly. Keep any supplied user data alive while the library can call back.
Ebitor.h · -lebitor
Ebitor_getInstance
Ebitor *Ebitor_getInstance(void);
Borrow the singleton editor state for debugging its internals. Use the public editing functions for normal interaction.
Ebitor.h · -lebitor
Ebitor_getLogicalCursorOffset
size_t Ebitor_getLogicalCursorOffset(void);
Distinguish byte offsets within the entire document from the on-screen row and column. Home in the current window can correspond to text partway through a file.
Ebitor.h · -lebitor
Ebitor_getLogicalOffsetAtHome
size_t Ebitor_getLogicalOffsetAtHome(byte cursorCol, byte cursorRow);
Distinguish byte offsets within the entire document from the on-screen row and column. Home in the current window can correspond to text partway through a file.
Ebitor.h · -lebitor
Ebitor_init
void Ebitor_init(char *bufferBegin, size_t bufferSize, byte termWidth, byte termHeight, ebitor_clear clear, ebitor_locateFunc locate, ebitor_getCursorPosFunc getCursorPos, ebitor_printFunc print, ebitor_printPrefixFunc printPrefix, ebitor_clrtoeolFunc clrtoeol, ebitor_scrollTerminalUpFunc scrollTerminalUp, ebitor_scrollTerminalDownFunc scrollTerminalDown, ebitor_waitKeyFunc waitKey);
Supply a persistent writable text buffer, its byte capacity, the terminal dimensions, and compatible screen and key callbacks. The editor manages one instance. Release it with shutdown before repurposing its buffer.
Ebitor.h · -lebitor · See it used in editlog.c
ebitor_KEY_ARROW_DOWN
ebitor_KEY_ARROW_DOWN = 259
These codes start above the byte range. Keep the terminal key in a word so the editor can distinguish a command from a printable character. Handle escape outside Ebitor_processKey.
Ebitor.h · -lebitor
ebitor_KEY_ARROW_LEFT
ebitor_KEY_ARROW_LEFT = 256
These codes start above the byte range. Keep the terminal key in a word so the editor can distinguish a command from a printable character. Handle escape outside Ebitor_processKey.
Ebitor.h · -lebitor · See it used in editlog.c
ebitor_KEY_ARROW_RIGHT
ebitor_KEY_ARROW_RIGHT = 257
These codes start above the byte range. Keep the terminal key in a word so the editor can distinguish a command from a printable character. Handle escape outside Ebitor_processKey.
Ebitor.h · -lebitor
ebitor_KEY_ARROW_UP
ebitor_KEY_ARROW_UP = 258
These codes start above the byte range. Keep the terminal key in a word so the editor can distinguish a command from a printable character. Handle escape outside Ebitor_processKey.
Ebitor.h · -lebitor
ebitor_KEY_ESCAPE
ebitor_KEY_ESCAPE = 260
These codes start above the byte range. Keep the terminal key in a word so the editor can distinguish a command from a printable character. Handle escape outside Ebitor_processKey.
Ebitor.h · -lebitor
Ebitor_locateCursorAtSavedPosition
void Ebitor_locateCursorAtSavedPosition(void);
Save or restore the current terminal location around a series of programmatically supplied keys.
Ebitor.h · -lebitor · See it used in editlog.c
ebitor_locateFunc
typedef void (*ebitor_locateFunc)(byte column, byte row);
A callback type. Implement the shown return and argument types exactly. Keep any supplied user data alive while the library can call back.
Ebitor.h · -lebitor
ebitor_printFunc
typedef BOOL (*ebitor_printFunc)(const char *str);
A callback type. Implement the shown return and argument types exactly. Keep any supplied user data alive while the library can call back.
Ebitor.h · -lebitor
ebitor_printPrefixFunc
typedef BOOL (*ebitor_printPrefixFunc)(const char *str, size_t prefixLength);
A callback type. Implement the shown return and argument types exactly. Keep any supplied user data alive while the library can call back.
Ebitor.h · -lebitor
Ebitor_processEditing
void Ebitor_processEditing(BOOL startWithRefresh);
Run the editing loop through the installed input and output callbacks. startWithRefresh requests a repaint. Returning from the loop saves the current position.
Ebitor.h · -lebitor
Ebitor_processKey
void Ebitor_processKey(word key);
Apply one printable character or supported navigation code. Restore the saved cursor before a sequence and save it again afterward. Handle the escape request outside this routine.
Ebitor.h · -lebitor · See it used in editlog.c
Ebitor_processUpOrDownArrowsAndRefresh
void Ebitor_processUpOrDownArrowsAndRefresh(BOOL isUpArrow, size_t numRepetitions);
Move up or down by the specified number of repeats and refresh once. Use this for a large move to avoid repainting on each simulated key.
Ebitor.h · -lebitor
Ebitor_saveCursorPosition
void Ebitor_saveCursorPosition(void);
Save or restore the current terminal location around a series of programmatically supplied keys.
Ebitor.h · -lebitor · See it used in editlog.c
ebitor_scrollTerminalDownFunc
typedef void (*ebitor_scrollTerminalDownFunc)(byte numRows);
A callback type. Implement the shown return and argument types exactly. Keep any supplied user data alive while the library can call back.
Ebitor.h · -lebitor
ebitor_scrollTerminalUpFunc
typedef void (*ebitor_scrollTerminalUpFunc)(byte numRows);
A callback type. Implement the shown return and argument types exactly. Keep any supplied user data alive while the library can call back.
Ebitor.h · -lebitor
Ebitor_scrollToShowLogicalOffset
void Ebitor_scrollToShowLogicalOffset(size_t logicalOffsetToShow, size_t lengthToShow);
Search for a nonempty zero-terminated string starting at a byte offset, or display a known range. The search writes the found offset and scrolls only upon success.
Ebitor.h · -lebitor
Ebitor_setContentLength
void Ebitor_setContentLength(size_t newLength);
After filling the text buffer, tell the editor how many bytes contain text. The length must fit the capacity supplied at init. Setting it repositions the cursor at the beginning.
Ebitor.h · -lebitor · See it used in editlog.c
Ebitor_setLogicalCursorAtBeginning
void Ebitor_setLogicalCursorAtBeginning(void);
Distinguish byte offsets within the entire document from the on-screen row and column. Home in the current window can correspond to text partway through a file.
Ebitor.h · -lebitor
Ebitor_shutdown
void Ebitor_shutdown(void);
Supply a persistent writable text buffer, its byte capacity, the terminal dimensions, and compatible screen and key callbacks. The editor manages one instance. Release it with shutdown before repurposing its buffer.
Ebitor.h · -lebitor · See it used in editlog.c
ebitor_waitKeyFunc
typedef word (*ebitor_waitKeyFunc)(void);
A callback type. Implement the shown return and argument types exactly. Keep any supplied user data alive while the library can call back.
Ebitor.h · -lebitor
INSERT_BUFFER_SIZE
INSERT_BUFFER_SIZE = 64
Ebitor’s internal insert buffer stages pending characters. For application text length use the content-length functions.
Ebitor.h · -lebitor
InsertBuffer
typedef struct InsertBuffer { … } InsertBuffer;
Ebitor’s internal insert buffer stages pending characters. For application text length use the content-length functions.
Ebitor.h · -lebitor
Window.h
Describe the guest text window used by the Ebitor terminal adapters. Add ebitor under Project Settings → Libraries, or link with -lebitor in your Makefile.
ebitor_Window
typedef struct ebitor_Window { … } ebitor_Window;
Describe the guest-side text window served by the terminal adapter. The GIME window also supplies normal and inverted character attributes.
Window.h · -lebitor · See it used in editlog.c
sg4term.h
Implement terminal operations on a traditional CoCo character screen. Add ebitor under Project Settings → Libraries, or link with -lebitor in your Makefile.
Save the ebitor example for this book
sg4term_clear · sg4term_clrtoeol · sg4term_convertASCIIToScreenByte · sg4term_eraseCurrentLine · sg4term_getChars · sg4term_getCursorPos · sg4term_init · sg4term_invertColors · sg4term_locate · sg4term_print · sg4term_printPrefix · sg4term_scrollWindowDown · sg4term_scrollWindowUp · sg4term_waitEditorKey
sg4term_clear
void sg4term_clear(void);
Fill the current terminal window with spaces. Erasing the view and moving the cursor are separate operations.
sg4term.h · -lebitor · See it used in editlog.c
sg4term_clrtoeol
void sg4term_clrtoeol(void);
Clear from the current position to the end, or erase the whole line and position the cursor at its start.
sg4term.h · -lebitor · See it used in editlog.c
sg4term_convertASCIIToScreenByte
char sg4term_convertASCIIToScreenByte(char c);
Translate an ASCII character to the compatible screen encoding, or copy a specified number of cells from a screen position. Size the destination for len bytes.
sg4term.h · -lebitor
sg4term_eraseCurrentLine
void sg4term_eraseCurrentLine(void);
Clear from the current position to the end, or erase the whole line and position the cursor at its start.
sg4term.h · -lebitor
sg4term_getChars
void sg4term_getChars(byte column, byte row, char *dest, size_t len);
Translate an ASCII character to the compatible screen encoding, or copy a specified number of cells from a screen position. Size the destination for len bytes.
sg4term.h · -lebitor
sg4term_getCursorPos
void sg4term_getCursorPos(byte *column, byte *row);
Supply or read a zero-based column and row relative to the terminal window. Check bounds in the caller.
sg4term.h · -lebitor · See it used in editlog.c
sg4term_init
void sg4term_init(char *screenBuffer, const ebitor_Window *window, byte (*inkeyFuncPtr)(void *cookie), void *inkeyFuncCookie, word *timerPtr);
Prepare an existing screen with a window, a nonblocking key callback, caller data and a timer ticking at 60 Hz. GIME works with hardware text cells; SG4 uses the character screen. Choose and allocate the proper display before initialization.
sg4term.h · -lebitor · See it used in editlog.c
sg4term_invertColors
void sg4term_invertColors(void);
Choose the character colors for later writes. In GIME mode each character has a separate attribute byte. Attribute setters return the previous value.
sg4term.h · -lebitor
sg4term_locate
void sg4term_locate(byte column, byte row);
Supply or read a zero-based column and row relative to the terminal window. Check bounds in the caller.
sg4term.h · -lebitor · See it used in editlog.c
sg4term_print
BOOL sg4term_print(const char *str);
Write inside the configured terminal window. A false result means output reached the bottom. Scroll and reposition explicitly. For a prefix supply the number of valid input characters.
sg4term.h · -lebitor · See it used in editlog.c
sg4term_printPrefix
BOOL sg4term_printPrefix(const char *str, size_t prefixLength);
Write inside the configured terminal window. A false result means output reached the bottom. Scroll and reposition explicitly. For a prefix supply the number of valid input characters.
sg4term.h · -lebitor · See it used in editlog.c
sg4term_scrollWindowDown
void sg4term_scrollWindowDown(byte numRows);
Shift the terminal window’s contents by a number of text rows. The caller chooses the direction and then positions the cursor as appropriate.
sg4term.h · -lebitor · See it used in editlog.c
sg4term_scrollWindowUp
void sg4term_scrollWindowUp(byte numRows);
Shift the terminal window’s contents by a number of text rows. The caller chooses the direction and then positions the cursor as appropriate.
sg4term.h · -lebitor · See it used in editlog.c
sg4term_waitEditorKey
word sg4term_waitEditorKey(void);
Block for keyboard input. Editor keys may exceed byte range, so keep the word result for arrow and editing codes. The simple GIME waitKey returns a byte.
sg4term.h · -lebitor · See it used in editlog.c
gimeterm.h
Implement terminal operations using the CoCo 3 GIME hardware text screen. Add ebitor under Project Settings → Libraries, or link with -lebitor in your Makefile.
Save the ebitor example for this book
gimeterm_clear · gimeterm_clrtoeol · gimeterm_eraseCurrentLine · gimeterm_getCursorPos · gimeterm_getWindow · gimeterm_init · gimeterm_invertColors · gimeterm_locate · gimeterm_newline · gimeterm_print · gimeterm_printPrefix · gimeterm_putchar · gimeterm_scrollWindowDown · gimeterm_scrollWindowUp · gimeterm_setInvertedTextAttribute · gimeterm_setTextAttribute · gimeterm_setWindow · gimeterm_waitEditorKey · gimeterm_waitKey · gimeterm_Window
gimeterm_clear
void gimeterm_clear(void);
Fill the current terminal window with spaces. Erasing the view and moving the cursor are separate operations.
gimeterm.h · -lebitor
gimeterm_clrtoeol
void gimeterm_clrtoeol(void);
Clear from the current position to the end, or erase the whole line and position the cursor at its start.
gimeterm.h · -lebitor
gimeterm_eraseCurrentLine
void gimeterm_eraseCurrentLine(void);
Clear from the current position to the end, or erase the whole line and position the cursor at its start.
gimeterm.h · -lebitor
gimeterm_getCursorPos
void gimeterm_getCursorPos(byte *column, byte *row);
Supply or read a zero-based column and row relative to the terminal window. Check bounds in the caller.
gimeterm.h · -lebitor
gimeterm_getWindow
void gimeterm_getWindow(gimeterm_Window *dest);
Copy the active GIME window state to caller storage or install saved state. Coordinates in later terminal operations are relative to its origin.
gimeterm.h · -lebitor
gimeterm_init
void gimeterm_init(void *screenBuffer, byte screenMode, const gimeterm_Window *window, byte (*inkeyFuncPtr)(void *cookie), void *inkeyFuncCookie, word *timerPtr);
Prepare an existing screen with a window, a nonblocking key callback, caller data and a timer ticking at 60 Hz. GIME works with hardware text cells; SG4 uses the character screen. Choose and allocate the proper display before initialization.
gimeterm.h · -lebitor
gimeterm_invertColors
void gimeterm_invertColors(void);
Choose the character colors for later writes. In GIME mode each character has a separate attribute byte. Attribute setters return the previous value.
gimeterm.h · -lebitor
gimeterm_locate
void gimeterm_locate(byte column, byte row);
Supply or read a zero-based column and row relative to the terminal window. Check bounds in the caller.
gimeterm.h · -lebitor
gimeterm_newline
BOOL gimeterm_newline(void);
Write inside the configured terminal window. A false result means output reached the bottom. Scroll and reposition explicitly. For a prefix supply the number of valid input characters.
gimeterm.h · -lebitor
gimeterm_print
BOOL gimeterm_print(const char *str);
Write inside the configured terminal window. A false result means output reached the bottom. Scroll and reposition explicitly. For a prefix supply the number of valid input characters.
gimeterm.h · -lebitor
gimeterm_printPrefix
BOOL gimeterm_printPrefix(const char *str, size_t prefixLength);
Write inside the configured terminal window. A false result means output reached the bottom. Scroll and reposition explicitly. For a prefix supply the number of valid input characters.
gimeterm.h · -lebitor
gimeterm_putchar
BOOL gimeterm_putchar(int c);
Write inside the configured terminal window. A false result means output reached the bottom. Scroll and reposition explicitly. For a prefix supply the number of valid input characters.
gimeterm.h · -lebitor
gimeterm_scrollWindowDown
void gimeterm_scrollWindowDown(byte numRows);
Shift the terminal window’s contents by a number of text rows. The caller chooses the direction and then positions the cursor as appropriate.
gimeterm.h · -lebitor
gimeterm_scrollWindowUp
void gimeterm_scrollWindowUp(byte numRows);
Shift the terminal window’s contents by a number of text rows. The caller chooses the direction and then positions the cursor as appropriate.
gimeterm.h · -lebitor
gimeterm_setInvertedTextAttribute
byte gimeterm_setInvertedTextAttribute(byte newAttribute);
Choose the character colors for later writes. In GIME mode each character has a separate attribute byte. Attribute setters return the previous value.
gimeterm.h · -lebitor
gimeterm_setTextAttribute
byte gimeterm_setTextAttribute(byte newAttribute);
Choose the character colors for later writes. In GIME mode each character has a separate attribute byte. Attribute setters return the previous value.
gimeterm.h · -lebitor
gimeterm_setWindow
void gimeterm_setWindow(const gimeterm_Window *state);
Copy the active GIME window state to caller storage or install saved state. Coordinates in later terminal operations are relative to its origin.
gimeterm.h · -lebitor
gimeterm_waitEditorKey
word gimeterm_waitEditorKey(void);
Block for keyboard input. Editor keys may exceed byte range, so keep the word result for arrow and editing codes. The simple GIME waitKey returns a byte.
gimeterm.h · -lebitor
gimeterm_waitKey
byte gimeterm_waitKey(void);
Block for keyboard input. Editor keys may exceed byte range, so keep the word result for arrow and editing codes. The simple GIME waitKey returns a byte.
gimeterm.h · -lebitor
gimeterm_Window
typedef struct gimeterm_Window { … } gimeterm_Window;
Describe the guest-side text window served by the terminal adapter. The GIME window also supplies normal and inverted character attributes.
gimeterm.h · -lebitor
hirestxt.h
Render text and a cursor into a graphics screen. Add hirestxt under Project Settings → Libraries, or link with -lhirestxt in your Makefile.
Save the hirestxt example for this book
animateCursor · BYTES_PER_PIXEL_ROW · clear · clearRowsToEOS · closeHiResTextScreen · clrscr · clrtobot · clrtoeol · getCursorColumn · getCursorRow · HIRESHEIGHT · HiResTextScreenInit · HiResTextScreenInit2 · home · initHiResTextScreen · initHiResTextScreen2 · initVT52 · invertPixelsAtCursor · moveCursor · PIXEL_COLS_PER_SCREEN · PIXEL_ROWS_PER_SCREEN · PIXEL_ROWS_PER_TEXT_ROW · processConsoleOutChar · removeCursor · scrollTextScreenUp · setBackgroundColor · setBoldMode · setForegroundBoldColor · setForegroundColor · setInverseVideoMode · waitKeyBlinkingCursor · writeCenteredLine · writeChar · writeCharAt · writeCharAt_320x16 · writeCharAt_42cols · writeCharAt_51cols · WriteCharAtFuncPtr · writeDecWord · writeString
animateCursor
void animateCursor(void);
Update the software cursor from the configured timer, remove it after animation, or wait for a key while it blinks. The default input function expects BASIC.
hirestxt.h · -lhirestxt
BYTES_PER_PIXEL_ROW
BYTES_PER_PIXEL_ROW = 4
Size or stride for the renderer named below. A pixel row, a text row and a byte count measure different parts of the screen. Use the constant from the same header as your drawing function.
hirestxt.h · -lhirestxt
clear
void clear(void);
Erase part or all of the graphics text buffer. For explicit rows use a raster fill byte and a zero-based text row. Choose the narrower operation if surrounding graphics should survive.
hirestxt.h · -lhirestxt
clearRowsToEOS
void clearRowsToEOS(byte byteToClearWith, byte textRow);
Erase part or all of the graphics text buffer. For explicit rows use a raster fill byte and a zero-based text row. Choose the narrower operation if surrounding graphics should survive.
hirestxt.h · -lhirestxt
closeHiResTextScreen
void closeHiResTextScreen(void);
Draw text into a caller-owned graphics buffer. Choose a renderer for the actual width, depth and font. For 320×192×16 and 64 text columns use the extended initializer. If printf is redirected, finish with closeHiResTextScreen to restore the hook.
hirestxt.h · -lhirestxt · See it used in glyph.c
clrscr
void clrscr(void);
Erase part or all of the graphics text buffer. For explicit rows use a raster fill byte and a zero-based text row. Choose the narrower operation if surrounding graphics should survive.
hirestxt.h · -lhirestxt
clrtobot
void clrtobot(void);
Erase part or all of the graphics text buffer. For explicit rows use a raster fill byte and a zero-based text row. Choose the narrower operation if surrounding graphics should survive.
hirestxt.h · -lhirestxt
clrtoeol
void clrtoeol(void);
Erase part or all of the graphics text buffer. For explicit rows use a raster fill byte and a zero-based text row. Choose the narrower operation if surrounding graphics should survive.
hirestxt.h · -lhirestxt
getCursorColumn
byte getCursorColumn(void);
Read the current character position or move it to the origin. Screen coordinates here count character cells, independent of the underlying pixel width.
hirestxt.h · -lhirestxt
getCursorRow
byte getCursorRow(void);
Read the current character position or move it to the origin. Screen coordinates here count character cells, independent of the underlying pixel width.
hirestxt.h · -lhirestxt
HIRESHEIGHT
HIRESHEIGHT = 0
Size or stride for the renderer named below. A pixel row, a text row and a byte count measure different parts of the screen. Use the constant from the same header as your drawing function.
hirestxt.h · -lhirestxt
HiResTextScreenInit
struct HiResTextScreenInit
Draw text into a caller-owned graphics buffer. Choose a renderer for the actual width, depth and font. For 320×192×16 and 64 text columns use the extended initializer. If printf is redirected, finish with closeHiResTextScreen to restore the hook.
hirestxt.h · -lhirestxt
HiResTextScreenInit2
struct HiResTextScreenInit2
Draw text into a caller-owned graphics buffer. Choose a renderer for the actual width, depth and font. For 320×192×16 and 64 text columns use the extended initializer. If printf is redirected, finish with closeHiResTextScreen to restore the hook.
hirestxt.h · -lhirestxt · See it used in glyph.c
home
home()
Read the current character position or move it to the origin. Screen coordinates here count character cells, independent of the underlying pixel width.
hirestxt.h · -lhirestxt
initHiResTextScreen
void initHiResTextScreen(const struct HiResTextScreenInit *init);
Draw text into a caller-owned graphics buffer. Choose a renderer for the actual width, depth and font. For 320×192×16 and 64 text columns use the extended initializer. If printf is redirected, finish with closeHiResTextScreen to restore the hook.
hirestxt.h · -lhirestxt
initHiResTextScreen2
void initHiResTextScreen2(const struct HiResTextScreenInit2 *init);
Draw text into a caller-owned graphics buffer. Choose a renderer for the actual width, depth and font. For 320×192×16 and 64 text columns use the extended initializer. If printf is redirected, finish with closeHiResTextScreen to restore the hook.
hirestxt.h · -lhirestxt · See it used in glyph.c
initVT52
void initVT52(void);
Initialize the escape-sequence parser and feed it one console character at a time. Control sequences can change the cursor, clear cells and change how later text is rendered.
hirestxt.h · -lhirestxt
invertPixelsAtCursor
void invertPixelsAtCursor(void);
Invert the pixels at the cursor, or scroll the graphics text by one text row. Both modify the buffer in place.
hirestxt.h · -lhirestxt
moveCursor
void moveCursor(byte x, byte y);
Work in character columns and rows, starting at zero. Set or retrieve the coordinates using the active text renderer. HiresTxt and CardGame each export moveCursor; use the intended renderer and link library.
hirestxt.h · -lhirestxt
PIXEL_COLS_PER_SCREEN
PIXEL_COLS_PER_SCREEN = 1
Size or stride for the renderer named below. A pixel row, a text row and a byte count measure different parts of the screen. Use the constant from the same header as your drawing function.
hirestxt.h · -lhirestxt
PIXEL_ROWS_PER_SCREEN
PIXEL_ROWS_PER_SCREEN = 2
Size or stride for the renderer named below. A pixel row, a text row and a byte count measure different parts of the screen. Use the constant from the same header as your drawing function.
hirestxt.h · -lhirestxt
PIXEL_ROWS_PER_TEXT_ROW
PIXEL_ROWS_PER_TEXT_ROW = 3
Size or stride for the renderer named below. A pixel row, a text row and a byte count measure different parts of the screen. Use the constant from the same header as your drawing function.
hirestxt.h · -lhirestxt
processConsoleOutChar
void processConsoleOutChar(byte ch);
Initialize the escape-sequence parser and feed it one console character at a time. Control sequences can change the cursor, clear cells and change how later text is rendered.
hirestxt.h · -lhirestxt
removeCursor
void removeCursor(void);
Update the software cursor from the configured timer, remove it after animation, or wait for a key while it blinks. The default input function expects BASIC.
hirestxt.h · -lhirestxt
scrollTextScreenUp
void scrollTextScreenUp(void);
Invert the pixels at the cursor, or scroll the graphics text by one text row. Both modify the buffer in place.
hirestxt.h · -lhirestxt
setBackgroundColor
void setBackgroundColor(byte color);
Choose the style for future rendered characters. In the four-bit graphics mode, normal foreground, bold foreground and background are palette indices 0–15.
hirestxt.h · -lhirestxt
setBoldMode
void setBoldMode(BOOL bold);
Choose the style for future rendered characters. In the four-bit graphics mode, normal foreground, bold foreground and background are palette indices 0–15.
hirestxt.h · -lhirestxt
setForegroundBoldColor
void setForegroundBoldColor(byte color);
Choose the style for future rendered characters. In the four-bit graphics mode, normal foreground, bold foreground and background are palette indices 0–15.
hirestxt.h · -lhirestxt
setForegroundColor
void setForegroundColor(byte color);
Choose the style for future rendered characters. In the four-bit graphics mode, normal foreground, bold foreground and background are palette indices 0–15.
hirestxt.h · -lhirestxt
setInverseVideoMode
void setInverseVideoMode(BOOL invert);
Choose the style for future rendered characters. In the four-bit graphics mode, normal foreground, bold foreground and background are palette indices 0–15.
hirestxt.h · -lhirestxt
waitKeyBlinkingCursor
byte waitKeyBlinkingCursor(void);
Update the software cursor from the configured timer, remove it after animation, or wait for a key while it blinks. The default input function expects BASIC.
hirestxt.h · -lhirestxt
writeCenteredLine
void writeCenteredLine(byte row, const char *line);
Draw text in the current software-rendered screen. writeString stops at the first zero, and writeCenteredLine centers on a zero-based text row. writeDecWord produces decimal digits.
hirestxt.h · -lhirestxt
writeChar
void writeChar(byte ch);
Draw text in the current software-rendered screen. writeString stops at the first zero, and writeCenteredLine centers on a zero-based text row. writeDecWord produces decimal digits.
hirestxt.h · -lhirestxt
writeCharAt
void writeCharAt(byte x, byte y, byte asciiCode);
Write a glyph at a zero-based character cell in the initialized graphics buffer. Select the width-specific raster routine when preparing the renderer. The 320×16 routine is for 64 columns of software text.
hirestxt.h · -lhirestxt
writeCharAt_320x16
void writeCharAt_320x16(byte x, byte y, byte asciiCode);
Write a glyph at a zero-based character cell in the initialized graphics buffer. Select the width-specific raster routine when preparing the renderer. The 320×16 routine is for 64 columns of software text.
hirestxt.h · -lhirestxt
writeCharAt_42cols
void writeCharAt_42cols(byte x, byte y, byte asciiCode);
Write a glyph at a zero-based character cell in the initialized graphics buffer. Select the width-specific raster routine when preparing the renderer. The 320×16 routine is for 64 columns of software text.
hirestxt.h · -lhirestxt
writeCharAt_51cols
void writeCharAt_51cols(byte x, byte y, byte asciiCode);
Write a glyph at a zero-based character cell in the initialized graphics buffer. Select the width-specific raster routine when preparing the renderer. The 320×16 routine is for 64 columns of software text.
hirestxt.h · -lhirestxt · See it used in glyph.c
WriteCharAtFuncPtr
typedef void (*WriteCharAtFuncPtr)(byte x, byte y, byte asciiCode);
A callback type. Implement the shown return and argument types exactly. Keep any supplied user data alive while the library can call back.
hirestxt.h · -lhirestxt
writeDecWord
void writeDecWord(word w);
Draw text in the current software-rendered screen. writeString stops at the first zero, and writeCenteredLine centers on a zero-based text row. writeDecWord produces decimal digits.
hirestxt.h · -lhirestxt
writeString
void writeString(const char *str);
Draw text in the current software-rendered screen. writeString stops at the first zero, and writeCenteredLine centers on a zero-based text row. writeDecWord produces decimal digits.
hirestxt.h · -lhirestxt · See it used in glyph.c
font4x8.h
Find the narrow four-pixel glyph data for HiresTxt. Add hirestxt under Project Settings → Libraries, or link with -lhirestxt in your Makefile.
font4x8
extern const unsigned char font4x8[1536];
Library-owned glyph data. Use the renderer for the font’s dimensions and treat the original bytes as read-only.
font4x8.h · -lhirestxt
font5x8.h
Find the five-pixel glyph data for HiresTxt. Add hirestxt under Project Settings → Libraries, or link with -lhirestxt in your Makefile.
font5x8
extern const unsigned char font5x8[1536];
Library-owned glyph data. Use the renderer for the font’s dimensions and treat the original bytes as read-only.
font5x8.h · -lhirestxt
wydealloc.h
Manage variable-size allocations inside a buffer your program owns. Add wydealloc under Project Settings → Libraries, or link with -lwydealloc in your Makefile.
Save the wydealloc example for this book
AllocatedBlockFunctor · MemPool · MemPool_alloc · MemPool_free · MemPool_getPoolSize · MemPool_getStats · MemPool_init · MemPool_owns
AllocatedBlockFunctor
typedef void (*AllocatedBlockFunctor)(const void *clientBlockAddress, unsigned short clientBlockSizeInBytes, void *userData);
A callback type. Implement the shown return and argument types exactly. Keep any supplied user data alive while the library can call back.
wydealloc.h · -lwydealloc
MemPool
typedef struct MemPool { … } MemPool;
Give the pool a persistent byte array, passing its first byte and the address just past the last one. Initialization returns false if the region is too small. The calling program owns this backing memory.
wydealloc.h · -lwydealloc · See it used in pool.c
MemPool_alloc
void *MemPool_alloc(MemPool *pool, unsigned short numBytesRequested);
Allocate from your initialized pool. NULL means insufficient space. A zero-sized request is treated as one byte. Successful bytes are uninitialized. Release with the same pool; freeing NULL does nothing.
wydealloc.h · -lwydealloc · See it used in pool.c
MemPool_free
void MemPool_free(MemPool *pool, void *ptr);
Allocate from your initialized pool. NULL means insufficient space. A zero-sized request is treated as one byte. Successful bytes are uninitialized. Release with the same pool; freeing NULL does nothing.
wydealloc.h · -lwydealloc · See it used in pool.c
MemPool_getPoolSize
unsigned short MemPool_getPoolSize(const MemPool *pool);
Query whether an address lies in the pool, the size of its backing region, or its usage statistics. An optional callback visits blocks that remain allocated.
wydealloc.h · -lwydealloc
MemPool_getStats
void MemPool_getStats(const MemPool *pool, unsigned short *numAllocatedBlocks, unsigned short *numFreeBlocks, unsigned short *totalAllocatedBytes, unsigned short *totalFreeBytes, unsigned short *largestFreeBlock, AllocatedBlockFunctor allocatedBlockFunctor, void *allocatedBlockFunctorUserData);
Query whether an address lies in the pool, the size of its backing region, or its usage statistics. An optional callback visits blocks that remain allocated.
wydealloc.h · -lwydealloc
MemPool_init
BOOL MemPool_init(MemPool *pool, void *start, void *end);
Give the pool a persistent byte array, passing its first byte and the address just past the last one. Initialization returns false if the region is too small. The calling program owns this backing memory.
wydealloc.h · -lwydealloc · See it used in pool.c
MemPool_owns
BOOL MemPool_owns(MemPool *pool, void *ptr);
Query whether an address lies in the pool, the size of its backing region, or its usage statistics. An optional callback visits blocks that remain allocated.
wydealloc.h · -lwydealloc
decbfile.h
Read and write named Disk BASIC files, sectors and fixed-size records. Add decbfile under Project Settings → Libraries, or link with -ldecbfile in your Makefile.
For a worked route from drive registration through a file read and cleanup, open Follow a word through FD0. See also where a file lives inside a floppy image.
Save the decbfile example for this book
decb_closeDir · decb_closeRecordFile · decb_closeSectorFile · decb_computeTrackAndSector · decb_copyFile · decb_createRecordFile · decb_createSectorFile · decb_denormalizeFilename · decb_dskcon · DECB_DSKCON_READ · DECB_DSKCON_WRITE · DECB_ERR_ALREADY_EXISTS · DECB_ERR_CORRUPT_DIR · DECB_ERR_CORRUPT_FAT · DECB_ERR_DRIVE_NOT_REGISTERED · DECB_ERR_END_OF_DIR · DECB_ERR_FAT_NOT_LOADED · DECB_ERR_INTERRUPTED · DECB_ERR_INVALID_ARGUMENT · DECB_ERR_IO · DECB_ERR_NOT_FOUND · DECB_ERR_OUT_OF_SPACE · decb_findDirEntry · decb_findFreeGranule · decb_flush · DECB_FORMAT_ASCII · DECB_FORMAT_BINARY · decb_freeGranuleChain · decb_getFileGranuleFromIndex · decb_getFileSizeFromDirEntry · decb_getFileSizeFromFilename · decb_getFreeSpaceAddress · decb_getFreeSpaceSize · decb_getNumFreeGranules · decb_getNumGranulesInOpenFile · decb_getNumRecords · decb_getOpenFileSize · decb_hasFullSector · decb_init · decb_initSeqWriteBuffer · decb_isValidFATEntry · decb_kill · DECB_LAST_DIR_SECTOR · DECB_MAX_NUM_GRANULES · DECB_MAX_NUM_TRACKS · decb_normalizeFilename · DECB_OK · decb_openDir · decb_openRecordFile · decb_openSectorFile · decb_openSectorFileFromDirEntry · decb_readDir · decb_readFAT · decb_readHeader · decb_readRecord · decb_readSector · decb_registerDrive · decb_registerWrittenBytes · decb_rename · DECB_SEQ_WRITE_BUFFER_SIZE · decb_setDskConAddresses · decb_setFATEntry · decb_setNumBytesUsedInLastSector · decb_shutdown · decb_truncateOpenFile · decb_truncateOpenRecordFile · DECB_TYPE_ASCII_TEXT · DECB_TYPE_BASIC_DATA · DECB_TYPE_BASIC_PROGRAM · DECB_TYPE_MACHINE_CODE · decb_unregisterAllDrives · decb_unregisterDrive · decb_writeFAT · decb_writeHeader · decb_writeRecord · decb_writeSector · DECBDirEntry · DECBDirIterator · DECBDrive · DECBDskConVariables · DECBFile · DECBRecordFile · DECBSeqWriteBuffer
decb_closeDir
byte decb_closeDir(DECBDirIterator *dirIter);
Keep the iterator for the duration of a directory scan. Each successful read yields a pointer to an entry in its buffer. Copy an entry before advancing if you need it later. Stop on DECB_ERR_END_OF_DIR or another error, then close.
decbfile.h · -ldecbfile
decb_closeRecordFile
byte decb_closeRecordFile(DECBRecordFile *recFile);
Truncate at a record boundary, then close the open record file to complete updates. Check each status independently.
decbfile.h · -ldecbfile
decb_closeSectorFile
byte decb_closeSectorFile(DECBFile *file);
Close an open sector file, completing any pending directory metadata update. Check the returned DECB status. A write can succeed before a later close fails.
decbfile.h · -ldecbfile · See it used in disk.c
decb_computeTrackAndSector
byte decb_computeTrackAndSector(DECBFile *file, byte fileGranIndex, byte sectorIndexInGranule, byte *track, byte *sector);
Translate a file-relative granule index using the open file’s allocation chain. Within a granule the sector offset is 0–8. Check the DECB status before using the physical coordinates.
decbfile.h · -ldecbfile
decb_copyFile
byte decb_copyFile(byte srcDriveNo, DECBDirEntry *srcDirEntry, byte destDriveNo, const char *destFilename, byte (*progressFunctor)(word currentSectorIndex, word totalNumSectors, void *userData), void *userData);
Copy an entry to a destination name, optionally reporting progress after sectors. A callback that returns zero leaves a partial destination and reports DECB_ERR_INTERRUPTED.
decbfile.h · -ldecbfile
decb_createRecordFile
byte decb_createRecordFile(DECBRecordFile *recFile, byte driveNo, const char *filename, word headerSize, word recordSize);
Choose a header length in bytes and a fixed nonzero record size. Use the same layout when reopening. The caller owns the DECBRecordFile state.
decbfile.h · -ldecbfile
decb_createSectorFile
byte decb_createSectorFile(DECBFile *file, byte driveNo, const char *filename, byte fileType, byte fileFormat);
Create a new empty file and supply the directory type and encoding as DECB_TYPE_* and DECB_FORMAT_*. An existing name can return DECB_ERR_ALREADY_EXISTS. Work on writable practice media.
decbfile.h · -ldecbfile
decb_denormalizeFilename
void decb_denormalizeFilename(char dest[13], char src[11], byte lowerCase);
The on-disk field is eight name characters and three extension characters padded with spaces. For normalization supply 12 destination bytes; for the dotted result allow 13. The latter can choose lowercase output.
decbfile.h · -ldecbfile
decb_dskcon
byte decb_dskcon(byte operation, void *buffer, byte drive, byte track, byte sector);
Raw DSKCON operation: supply a 256-byte buffer, track 0–34 and physical sector 1–18. This call uses nonzero for success, the opposite convention from decb_readSector. Raw writes can alter the directory or allocation table.
decbfile.h · -ldecbfile
DECB_DSKCON_READ
DECB_DSKCON_READ = 2
Select the direction of a raw physical sector transfer. Work on a private disk image when experimenting with writes.
decbfile.h · -ldecbfile
DECB_DSKCON_WRITE
DECB_DSKCON_WRITE = 3
Select the direction of a raw physical sector transfer. Work on a private disk image when experimenting with writes.
decbfile.h · -ldecbfile
DECB_ERR_ALREADY_EXISTS
DECB_ERR_ALREADY_EXISTS = 8
A file-library status code. Compare the returned status before using an open file or the contents of a sector buffer.
decbfile.h · -ldecbfile
DECB_ERR_CORRUPT_DIR
DECB_ERR_CORRUPT_DIR = 7
A file-library status code. Compare the returned status before using an open file or the contents of a sector buffer.
decbfile.h · -ldecbfile
DECB_ERR_CORRUPT_FAT
DECB_ERR_CORRUPT_FAT = 6
A file-library status code. Compare the returned status before using an open file or the contents of a sector buffer.
decbfile.h · -ldecbfile
DECB_ERR_DRIVE_NOT_REGISTERED
DECB_ERR_DRIVE_NOT_REGISTERED = 11
A file-library status code. Compare the returned status before using an open file or the contents of a sector buffer.
decbfile.h · -ldecbfile
DECB_ERR_END_OF_DIR
DECB_ERR_END_OF_DIR = 10
A file-library status code. Compare the returned status before using an open file or the contents of a sector buffer.
decbfile.h · -ldecbfile
DECB_ERR_FAT_NOT_LOADED
DECB_ERR_FAT_NOT_LOADED = 5
A file-library status code. Compare the returned status before using an open file or the contents of a sector buffer.
decbfile.h · -ldecbfile
DECB_ERR_INTERRUPTED
DECB_ERR_INTERRUPTED = 9
A file-library status code. Compare the returned status before using an open file or the contents of a sector buffer.
decbfile.h · -ldecbfile
DECB_ERR_INVALID_ARGUMENT
DECB_ERR_INVALID_ARGUMENT = 1
A file-library status code. Compare the returned status before using an open file or the contents of a sector buffer.
decbfile.h · -ldecbfile
DECB_ERR_IO
DECB_ERR_IO = 2
A file-library status code. Compare the returned status before using an open file or the contents of a sector buffer.
decbfile.h · -ldecbfile
DECB_ERR_NOT_FOUND
DECB_ERR_NOT_FOUND = 3
A file-library status code. Compare the returned status before using an open file or the contents of a sector buffer.
decbfile.h · -ldecbfile
DECB_ERR_OUT_OF_SPACE
DECB_ERR_OUT_OF_SPACE = 4
A file-library status code. Compare the returned status before using an open file or the contents of a sector buffer.
decbfile.h · -ldecbfile
decb_findDirEntry
byte decb_findDirEntry(byte forNewFile, byte driveNo, char normalizedFilename[12], byte dirSectorBuffer[256], byte *dirSectorNum, byte *byteOffsetInDirSector);
Supply a normalized 12-byte name and 256-byte scratch sector. Select lookup or new-file search. Check the returned status before using the directory sector and offset outputs.
decbfile.h · -ldecbfile
decb_findFreeGranule
byte decb_findFreeGranule(byte driveNo);
Search the drive allocation table for unused space. A result of 0xFF means a free entry could not be obtained.
decbfile.h · -ldecbfile
decb_flush
byte decb_flush(DECBFile *file, DECBSeqWriteBuffer *writeBuffer);
Check whether buffered data fills a sector. Flush to the open file and check the returned status. Finish the last partial sector and close the file.
decbfile.h · -ldecbfile
DECB_FORMAT_ASCII
DECB_FORMAT_ASCII = 255
Directory metadata for decb_createSectorFile. A file has both a type and an encoding.
decbfile.h · -ldecbfile
DECB_FORMAT_BINARY
DECB_FORMAT_BINARY = 0
Directory metadata for decb_createSectorFile. A file has both a type and an encoding.
decbfile.h · -ldecbfile
decb_freeGranuleChain
byte decb_freeGranuleChain(byte driveNo, byte firstGranule);
Release the chain beginning at the given granule in the FAT cache. Flush the FAT explicitly. Use a spare image for allocation-table work.
decbfile.h · -ldecbfile
decb_getFileGranuleFromIndex
byte decb_getFileGranuleFromIndex(DECBFile *file, byte fileGranIndex, byte *fatEntryIndex);
Translate a file-relative granule index using the open file’s allocation chain. Within a granule the sector offset is 0–8. Check the DECB status before using the physical coordinates.
decbfile.h · -ldecbfile
decb_getFileSizeFromDirEntry
byte decb_getFileSizeFromDirEntry(byte driveNo, DECBDirEntry *entry, word *numSectors, dword *lengthInBytes);
The return is a granule count, with 255 indicating failure. The separate outputs distinguish used sectors and, where requested, the actual byte length.
decbfile.h · -ldecbfile
decb_getFileSizeFromFilename
byte decb_getFileSizeFromFilename(byte driveNo, const char *filename, word *numSectors, dword *lengthInBytes);
The return is a granule count, with 255 indicating failure. The separate outputs distinguish used sectors and, where requested, the actual byte length.
decbfile.h · -ldecbfile
decb_getFreeSpaceAddress
byte *decb_getFreeSpaceAddress(DECBSeqWriteBuffer *writeBuffer);
Get the write buffer’s next free position and remaining capacity. Only after copying bytes into that space, report the count you actually wrote.
decbfile.h · -ldecbfile
decb_getFreeSpaceSize
word decb_getFreeSpaceSize(DECBSeqWriteBuffer *writeBuffer);
Get the write buffer’s next free position and remaining capacity. Only after copying bytes into that space, report the count you actually wrote.
decbfile.h · -ldecbfile
decb_getNumFreeGranules
byte decb_getNumFreeGranules(byte driveNo, byte *numFreeGranules);
On DECB_OK the output byte holds the number of free 2,304-byte allocation units on this drive. The return itself is a status.
decbfile.h · -ldecbfile
decb_getNumGranulesInOpenFile
byte decb_getNumGranulesInOpenFile(DECBFile *file, byte *lastFileGranule, word *numSectors);
The return is a granule count, with 255 indicating failure. The separate outputs distinguish used sectors and, where requested, the actual byte length.
decbfile.h · -ldecbfile
decb_getNumRecords
word decb_getNumRecords(DECBRecordFile *recFile);
Read the count from the open record-file state. Valid existing record indices start at zero and end before that count.
decbfile.h · -ldecbfile
decb_getOpenFileSize
byte decb_getOpenFileSize(DECBFile *file, word *numSectors, dword *lengthInBytes);
The return is a granule count, with 255 indicating failure. The separate outputs distinguish used sectors and, where requested, the actual byte length.
decbfile.h · -ldecbfile
decb_hasFullSector
byte decb_hasFullSector(DECBSeqWriteBuffer *writeBuffer);
Check whether buffered data fills a sector. Flush to the open file and check the returned status. Finish the last partial sector and close the file.
decbfile.h · -ldecbfile
decb_init
byte decb_init(DECBDrive *driveArray, word numDrives);
Give the library an array with one DECBDrive for each drive you want open at the same time. Keep the array allocated through shutdown. A status of DECB_OK permits the next step, registration.
decbfile.h · -ldecbfile · See it used in disk.c
decb_initSeqWriteBuffer
void decb_initSeqWriteBuffer(DECBSeqWriteBuffer *writeBuffer);
Prepare the caller’s buffer for sequential output to a newly created file. Keep it alive until its contents have been flushed.
decbfile.h · -ldecbfile
decb_isValidFATEntry
byte decb_isValidFATEntry(byte entry);
Test whether a byte has a legal allocation-table encoding. This alone cannot validate the chain of an entire file.
decbfile.h · -ldecbfile
decb_kill
byte decb_kill(byte driveNo, const char *filename);
Delete a named file or change its directory name on a registered drive. Check the DECB status and use a working copy when experimenting.
decbfile.h · -ldecbfile
DECB_LAST_DIR_SECTOR
DECB_LAST_DIR_SECTOR = 18
These values describe the library’s ordinary 35-track Disk BASIC floppy. A granule spans nine 256-byte sectors; the directory has its own reserved track.
decbfile.h · -ldecbfile
DECB_MAX_NUM_GRANULES
DECB_MAX_NUM_GRANULES = 68
These values describe the library’s ordinary 35-track Disk BASIC floppy. A granule spans nine 256-byte sectors; the directory has its own reserved track.
decbfile.h · -ldecbfile
DECB_MAX_NUM_TRACKS
DECB_MAX_NUM_TRACKS = 35
These values describe the library’s ordinary 35-track Disk BASIC floppy. A granule spans nine 256-byte sectors; the directory has its own reserved track.
decbfile.h · -ldecbfile
decb_normalizeFilename
void decb_normalizeFilename(char dest[12], const char *src);
The on-disk field is eight name characters and three extension characters padded with spaces. For normalization supply 12 destination bytes; for the dotted result allow 13. The latter can choose lowercase output.
decbfile.h · -ldecbfile
DECB_OK
DECB_OK = 0
A file-library status code. Compare the returned status before using an open file or the contents of a sector buffer.
decbfile.h · -ldecbfile · See it used in disk.c
decb_openDir
byte decb_openDir(byte driveNo, DECBDirIterator *dirIter);
Keep the iterator for the duration of a directory scan. Each successful read yields a pointer to an entry in its buffer. Copy an entry before advancing if you need it later. Stop on DECB_ERR_END_OF_DIR or another error, then close.
decbfile.h · -ldecbfile
decb_openRecordFile
byte decb_openRecordFile(DECBRecordFile *recFile, byte driveNo, const char *filename, word headerSize, word recordSize);
Choose a header length in bytes and a fixed nonzero record size. Use the same layout when reopening. The caller owns the DECBRecordFile state.
decbfile.h · -ldecbfile
decb_openSectorFile
byte decb_openSectorFile(DECBFile *file, byte driveNo, const char *filename);
Open a dotted name such as WORDS.DAT on a registered drive. Supply your own DECBFile object. At status 0 it describes an open file; status 3 means the name was missing. Close only after a successful open.
decbfile.h · -ldecbfile · See it used in disk.c
decb_openSectorFileFromDirEntry
byte decb_openSectorFileFromDirEntry(DECBFile *file, byte driveNo, DECBDirEntry *entry);
Open using a directory record from the same registered drive. Keep your own DECBFile until close and inspect status before reading.
decbfile.h · -ldecbfile
decb_readDir
byte decb_readDir(DECBDirIterator *dirIter, DECBDirEntry **dirEntry);
Keep the iterator for the duration of a directory scan. Each successful read yields a pointer to an entry in its buffer. Copy an entry before advancing if you need it later. Stop on DECB_ERR_END_OF_DIR or another error, then close.
decbfile.h · -ldecbfile
decb_readFAT
byte decb_readFAT(byte driveNo);
Load a registered drive’s allocation table before working on it. Change entries only through the setter, then write the table back. These calls can change what data every file on the image owns.
decbfile.h · -ldecbfile
decb_readHeader
byte decb_readHeader(DECBRecordFile *recFile, byte *header);
Provide storage covering the file’s entire configured header length. These calls transfer that fixed-length binary block.
decbfile.h · -ldecbfile
decb_readRecord
byte decb_readRecord(DECBRecordFile *recFile, byte *record, word recordIndex);
Supply a complete record-sized buffer and a zero-based record index. Reading past the end can return DECB_ERR_NOT_FOUND. Writing past the end extends the file.
decbfile.h · -ldecbfile
decb_readSector
byte decb_readSector(DECBFile *file, byte sectorBuffer[256], word fileSectorIndex);
To read a disk sector inside a file, open the file first. Index 0 is its first sector. Reserve 256 writable bytes, even for a short final sector. Status 0 means the sector was read; DECB_ERR_NOT_FOUND can mean the index is past the file. A successful read does not add a string terminator.
decbfile.h · -ldecbfile · See it used in disk.c · Follow the read in chapter 6
decb_registerDrive
byte decb_registerDrive(byte decbDriveNo);
Associate a BASIC drive number with an available state record before opening files. A second registration may report DECB_ERR_ALREADY_EXISTS. Finish using its files before releasing the record.
decbfile.h · -ldecbfile · See it used in disk.c
decb_registerWrittenBytes
void decb_registerWrittenBytes(DECBSeqWriteBuffer *writeBuffer, word numBytes);
Get the write buffer’s next free position and remaining capacity. Only after copying bytes into that space, report the count you actually wrote.
decbfile.h · -ldecbfile
decb_rename
byte decb_rename(byte driveNo, const char *existingFilename, const char *newFilename);
Delete a named file or change its directory name on a registered drive. Check the DECB status and use a working copy when experimenting.
decbfile.h · -ldecbfile
DECB_SEQ_WRITE_BUFFER_SIZE
DECB_SEQ_WRITE_BUFFER_SIZE = 512
Capacity in bytes of the data array inside DECBSeqWriteBuffer. Query the free-space size before copying into a partly occupied buffer.
decbfile.h · -ldecbfile
decb_setDskConAddresses
byte decb_setDskConAddresses(void (*dskconRoutine)(), DECBDskConVariables *vars);
Redirect the disk routines to a different DSKCON implementation and its matching contiguous variables. The standard ROM-backed path needs no override. Initialize the replacement and keep its IRQ and NMI services operative.
decbfile.h · -ldecbfile
decb_setFATEntry
byte decb_setFATEntry(byte driveNo, byte entryIndex, byte newValue);
Load a registered drive’s allocation table before working on it. Change entries only through the setter, then write the table back. These calls can change what data every file on the image owns.
decbfile.h · -ldecbfile
decb_setNumBytesUsedInLastSector
byte decb_setNumBytesUsedInLastSector(DECBFile *file, word numBytesUsedInLastSector);
Record the logical byte count in the last sector, 0–256. Close the file to finish updating the directory.
decbfile.h · -ldecbfile
decb_shutdown
byte decb_shutdown();
After closing files, release the library’s drive registrations. If you explicitly changed the FAT, write it before shutdown. Keep the drive array valid until this call returns.
decbfile.h · -ldecbfile · See it used in disk.c
decb_truncateOpenFile
byte decb_truncateOpenFile(DECBFile *file, word newNumSectors, word numBytesUsedInLastSector);
Adjust the sector length and final byte count within the existing allocation. Close the file after success so the new size reaches disk.
decbfile.h · -ldecbfile
decb_truncateOpenRecordFile
byte decb_truncateOpenRecordFile(DECBRecordFile *recFile, word recordIndex);
Truncate at a record boundary, then close the open record file to complete updates. Check each status independently.
decbfile.h · -ldecbfile
DECB_TYPE_ASCII_TEXT
DECB_TYPE_ASCII_TEXT = 3
Directory metadata for decb_createSectorFile. A file has both a type and an encoding.
decbfile.h · -ldecbfile
DECB_TYPE_BASIC_DATA
DECB_TYPE_BASIC_DATA = 1
Directory metadata for decb_createSectorFile. A file has both a type and an encoding.
decbfile.h · -ldecbfile
DECB_TYPE_BASIC_PROGRAM
DECB_TYPE_BASIC_PROGRAM = 0
Directory metadata for decb_createSectorFile. A file has both a type and an encoding.
decbfile.h · -ldecbfile
DECB_TYPE_MACHINE_CODE
DECB_TYPE_MACHINE_CODE = 2
Directory metadata for decb_createSectorFile. A file has both a type and an encoding.
decbfile.h · -ldecbfile
decb_unregisterAllDrives
byte decb_unregisterAllDrives();
Associate a BASIC drive number with an available state record before opening files. A second registration may report DECB_ERR_ALREADY_EXISTS. Finish using its files before releasing the record.
decbfile.h · -ldecbfile
decb_unregisterDrive
byte decb_unregisterDrive(byte decbDriveNo);
Associate a BASIC drive number with an available state record before opening files. A second registration may report DECB_ERR_ALREADY_EXISTS. Finish using its files before releasing the record.
decbfile.h · -ldecbfile
decb_writeFAT
byte decb_writeFAT(byte driveNo);
Load a registered drive’s allocation table before working on it. Change entries only through the setter, then write the table back. These calls can change what data every file on the image owns.
decbfile.h · -ldecbfile
decb_writeHeader
byte decb_writeHeader(DECBRecordFile *recFile, byte *header);
Provide storage covering the file’s entire configured header length. These calls transfer that fixed-length binary block.
decbfile.h · -ldecbfile
decb_writeRecord
byte decb_writeRecord(DECBRecordFile *recFile, byte *record, word recordIndex);
Supply a complete record-sized buffer and a zero-based record index. Reading past the end can return DECB_ERR_NOT_FOUND. Writing past the end extends the file.
decbfile.h · -ldecbfile
decb_writeSector
byte decb_writeSector(DECBFile *file, const byte sectorBuffer[256], word fileSectorIndex);
Write a full 256-byte buffer at a zero-based logical sector of the open file. The result is a DECB status. Set the last-sector byte count when the useful data ends partway through it.
decbfile.h · -ldecbfile
DECBDirEntry
typedef struct DECBDirEntry { … } DECBDirEntry;
Keep the iterator for the duration of a directory scan. Each successful read yields a pointer to an entry in its buffer. Copy an entry before advancing if you need it later. Stop on DECB_ERR_END_OF_DIR or another error, then close.
decbfile.h · -ldecbfile
DECBDirIterator
typedef struct DECBDirIterator { … } DECBDirIterator;
Keep the iterator for the duration of a directory scan. Each successful read yields a pointer to an entry in its buffer. Copy an entry before advancing if you need it later. Stop on DECB_ERR_END_OF_DIR or another error, then close.
decbfile.h · -ldecbfile
DECBDrive
typedef struct DECBDrive { … } DECBDrive;
Give the library an array with one DECBDrive for each drive you want open at the same time. Keep the array allocated through shutdown. A status of DECB_OK permits the next step, registration.
decbfile.h · -ldecbfile · See it used in disk.c
DECBDskConVariables
typedef struct DECBDskConVariables { … } DECBDskConVariables;
Redirect the disk routines to a different DSKCON implementation and its matching contiguous variables. The standard ROM-backed path needs no override. Initialize the replacement and keep its IRQ and NMI services operative.
decbfile.h · -ldecbfile
DECBFile
typedef struct DECBFile { … } DECBFile;
Open a dotted name such as WORDS.DAT on a registered drive. Supply your own DECBFile object. At status 0 it describes an open file; status 3 means the name was missing. Close only after a successful open.
decbfile.h · -ldecbfile · See it used in disk.c
DECBRecordFile
typedef struct DECBRecordFile { … } DECBRecordFile;
Choose a header length in bytes and a fixed nonzero record size. Use the same layout when reopening. The caller owns the DECBRecordFile state.
decbfile.h · -ldecbfile
DECBSeqWriteBuffer
typedef struct DECBSeqWriteBuffer { … } DECBSeqWriteBuffer;
Prepare the caller’s buffer for sequential output to a newly created file. Keep it alive until its contents have been flushed.
decbfile.h · -ldecbfile
dskcon-standalone.h
Operate the floppy controller while the Disk BASIC ROM is banked out. This optional driver must be present in the installed toolchain. Link decbfile then dskcon-standalone when replacing the disk API’s ROM backend.
DCBPT · DCDRV · DCOPC · DCSEC · DCSTA · DCTRK · DNMIVC · DR0TRK · DRGRAM · dskcon_driveEnableMasks · dskcon_init · dskcon_irqService · dskcon_nmiService · dskcon_NmiServiceFunctionPointer · dskcon_processSector · dskcon_shutdown · DSKREG · FDCREG · NMIFLG · RDYTMR
DCBPT
extern unsigned char *DCBPT;
The standalone driver’s physical sector request uses a drive (0–3), track (0–34), sector (1–18) and pointer to 256 bytes. Request 2 reads and 3 writes. Read the status after the transfer.
dskcon-standalone.h · -ldskcon-standalone
DCDRV
extern unsigned char DCDRV;
The standalone driver’s physical sector request uses a drive (0–3), track (0–34), sector (1–18) and pointer to 256 bytes. Request 2 reads and 3 writes. Read the status after the transfer.
dskcon-standalone.h · -ldskcon-standalone
DCOPC
extern unsigned char DCOPC;
The standalone driver’s physical sector request uses a drive (0–3), track (0–34), sector (1–18) and pointer to 256 bytes. Request 2 reads and 3 writes. Read the status after the transfer.
dskcon-standalone.h · -ldskcon-standalone
DCSEC
extern unsigned char DCSEC;
The standalone driver’s physical sector request uses a drive (0–3), track (0–34), sector (1–18) and pointer to 256 bytes. Request 2 reads and 3 writes. Read the status after the transfer.
dskcon-standalone.h · -ldskcon-standalone
DCSTA
extern unsigned char DCSTA;
The standalone driver’s physical sector request uses a drive (0–3), track (0–34), sector (1–18) and pointer to 256 bytes. Request 2 reads and 3 writes. Read the status after the transfer.
dskcon-standalone.h · -ldskcon-standalone
DCTRK
extern unsigned char DCTRK;
The standalone driver’s physical sector request uses a drive (0–3), track (0–34), sector (1–18) and pointer to 256 bytes. Request 2 reads and 3 writes. Read the status after the transfer.
dskcon-standalone.h · -ldskcon-standalone
DNMIVC
extern void *DNMIVC;
Driver state for the motor, selected drives and interrupt handling. Let dskcon_init, the service routines and dskcon_shutdown maintain it during ordinary file I/O.
dskcon-standalone.h · -ldskcon-standalone
DR0TRK
extern unsigned char DR0TRK[4];
Driver state for the motor, selected drives and interrupt handling. Let dskcon_init, the service routines and dskcon_shutdown maintain it during ordinary file I/O.
dskcon-standalone.h · -ldskcon-standalone
DRGRAM
extern unsigned char DRGRAM;
Driver state for the motor, selected drives and interrupt handling. Let dskcon_init, the service routines and dskcon_shutdown maintain it during ordinary file I/O.
dskcon-standalone.h · -ldskcon-standalone
dskcon_driveEnableMasks
extern unsigned char dskcon_driveEnableMasks[4];
Driver state for the motor, selected drives and interrupt handling. Let dskcon_init, the service routines and dskcon_shutdown maintain it during ordinary file I/O.
dskcon-standalone.h · -ldskcon-standalone
dskcon_init
unsigned long dskcon_init(dskcon_NmiServiceFunctionPointer newNMIService);
This optional standalone FD-502 driver takes responsibility for controller interrupts. With interrupts masked, install the NMI handler and save the exact initialization return value for shutdown. Service the driver's IRQ from a suitable periodic guest ISR, then restore the vectors on exit.
dskcon-standalone.h · -ldskcon-standalone
dskcon_irqService
void dskcon_irqService();
This optional standalone FD-502 driver takes responsibility for controller interrupts. With interrupts masked, install the NMI handler and save the exact initialization return value for shutdown. Service the driver's IRQ from a suitable periodic guest ISR, then restore the vectors on exit.
dskcon-standalone.h · -ldskcon-standalone
dskcon_nmiService
interrupt void dskcon_nmiService();
This optional standalone FD-502 driver takes responsibility for controller interrupts. With interrupts masked, install the NMI handler and save the exact initialization return value for shutdown. Service the driver's IRQ from a suitable periodic guest ISR, then restore the vectors on exit.
dskcon-standalone.h · -ldskcon-standalone
dskcon_NmiServiceFunctionPointer
typedef interrupt void (*dskcon_NmiServiceFunctionPointer)();
A callback type. Implement the shown return and argument types exactly. Keep any supplied user data alive while the library can call back.
dskcon-standalone.h · -ldskcon-standalone
dskcon_processSector
void dskcon_processSector();
Fill the driver’s operation, drive, track, sector and buffer variables, then call. DCSTA is the resulting hardware error mask; zero signals success. A transfer uses 256 bytes.
dskcon-standalone.h · -ldskcon-standalone
dskcon_shutdown
void dskcon_shutdown(unsigned long initReturnValue);
This optional standalone FD-502 driver takes responsibility for controller interrupts. With interrupts masked, install the NMI handler and save the exact initialization return value for shutdown. Service the driver's IRQ from a suitable periodic guest ISR, then restore the vectors on exit.
dskcon-standalone.h · -ldskcon-standalone
DSKREG
DSKREG = 65344
Guest addresses of the drive-control and floppy-controller registers respectively. Ordinary clients use dskcon_processSector or a file-level API.
dskcon-standalone.h · -ldskcon-standalone
FDCREG
FDCREG = 65352
Guest addresses of the drive-control and floppy-controller registers respectively. Ordinary clients use dskcon_processSector or a file-level API.
dskcon-standalone.h · -ldskcon-standalone
NMIFLG
extern unsigned char NMIFLG;
Driver state for the motor, selected drives and interrupt handling. Let dskcon_init, the service routines and dskcon_shutdown maintain it during ordinary file I/O.
dskcon-standalone.h · -ldskcon-standalone
RDYTMR
extern unsigned char RDYTMR;
Driver state for the motor, selected drives and interrupt handling. Let dskcon_init, the service routines and dskcon_shutdown maintain it during ordinary file I/O.
dskcon-standalone.h · -ldskcon-standalone
vcc/ssc.h
Add ssc in Project Settings → Libraries and select the Speech/Sound Cartridge in the machine configuration. Supply its two firmware files. Use one command producer at a time. Before sending a command, select cartridge sound with ssc_route_audio. Give the sound time to finish before restoring the prior audio route.
ssc_status · ssc_try_write · ssc_route_audio · ssc_restore_audio · ssc_reset · ssc_phrase · ssc_begin_phrase · ssc_service · ssc_say · ssc_play_effect · ssc_play_noise · SSC_OK · SSC_TIMEOUT · SSC_INVALID · SSC_PENDING · SSC_READY · SSC_SPEECH_IDLE · SSC_EFFECT_IDLE · SSC_MAX_TEXT
The cartridge has eight speech slots and eight independent sound slots. Loading a slot is silent. Playback is a separate command. Each call below has a per-byte polling limit. A zero limit gives a timeout on a valid call. If a transfer times out partway through, reset and reload your slots before sending another command. The slots are lost when the cartridge resets.
- Store and speak. ssc_store_phrase, ssc_play_phrase, ssc_store_allophones, ssc_play_allophones.
- Store and play sound. ssc_store_enveloped_tone, ssc_play_stored_effect.
- Envelope shapes. SSC_ENV_DECAY, SSC_ENV_REPEAT_DECAY, SSC_ENV_REPEAT_RISE, SSC_ENV_TRIANGLE.
- Pauses. PA1, PA2, PA3, PA4, PA5.
- Vowels and syllables. OY, AY, EH, IH, AX, IY, EY, UW1, AO, AA, AE, UH, UW2, AW, XR, ER1, ER2, OW, OR, AR, YR, EL.
- Consonants. BB1, BB2, CH, DD1, DD2, DH1, DH2, FF, GG1, GG2, GG3, HH1, HH2, JH, KK1, KK2, KK3, LL, MM, NG, NN1, NN2, PP, RR1, RR2, SH, SS, TH, TT1, TT2, VV, WH, WW, YY1, YY2, ZH, ZZ.
ssc_status
unsigned char ssc_status(void);
Read the cartridge status flags. Test READY before each command byte. Idle flags can take time to change after submission. An unmapped read does not reliably identify whether the cartridge is installed.
ssc_try_write
unsigned char ssc_try_write(unsigned char value);
Attempt one command byte. Returns 1 when the cartridge accepted it and 0 while it is busy. On 0, keep the same byte for your next attempt.
ssc_route_audio
unsigned int ssc_route_audio(void);
Select cartridge audio and enable the speaker. Keep the returned token until playback has finished. Joystick or cassette routines can change the shared CoCo audio multiplexer.
ssc_restore_audio
void ssc_restore_audio(unsigned int saved);
Pass the original route token after playback to restore the CoCo’s previous audio routing. This call returns immediately.
ssc_reset
void ssc_reset(void);
Reset the cartridge and discard pending speech, effects and buffered commands. Use deliberately when recovering from a partial submission.
ssc_phrase
typedef struct { … } ssc_phrase;
Keep this state and its input string alive from ssc_begin_phrase until the last ssc_service. Give a phrase exclusive use of the command port.
ssc_begin_phrase
unsigned char ssc_begin_phrase(ssc_phrase *phrase, const char *text);
Validate 1–62 printable ASCII characters and initialize the phrase state. This call sends no bytes. Keep the original text unchanged until submission finishes.
ssc_service
unsigned char ssc_service(ssc_phrase *phrase);
Try at most one byte from a prepared phrase. Continue the main loop on SSC_PENDING. SSC_OK means the entire command has been submitted; playback may still be in progress.
ssc_say
unsigned char ssc_say(const char *text, unsigned int poll_limit);
Submit a printable phrase synchronously. The poll limit applies separately to each byte. Timeout may leave a partial command; reset before sending something unrelated. Successful submission can return before you hear the end of the phrase.
ssc_play_effect
unsigned char ssc_play_effect(unsigned char channel, unsigned int period, unsigned char volume, unsigned char duration, unsigned int poll_limit);
Submit a tone effect on channel A, B or C (0–2). Set its tone period to 1–4095 and volume to 0–15. Duration is 0–255 cartridge timer units. It replaces cartridge effect buffer 0 and ends the effect in silence.
ssc_play_noise
unsigned char ssc_play_noise(unsigned char channel, unsigned char period, unsigned char volume, unsigned char duration, unsigned int poll_limit);
Submit a noise effect on channel 0–2, with noise period 0–31, volume 0–15 and duration 0–255 cartridge timer units. It shares effect buffer 0 with tone effects.
SSC_OK
SSC_OK = 0
The command was submitted successfully. The firmware may still be playing it.
SSC_TIMEOUT
SSC_TIMEOUT = 1
A bounded wait expired. Some earlier bytes may have been accepted.
SSC_INVALID
SSC_INVALID = 2
An argument fell outside the accepted range.
SSC_PENDING
SSC_PENDING = 3
The phrase still has bytes to send. Call ssc_service again.
SSC_READY
SSC_READY = 0x80
Mask the status byte with this bit to check whether the cartridge accepts another byte.
SSC_SPEECH_IDLE
SSC_SPEECH_IDLE = 0x40
Set when the speech synthesizer is idle. Allow time for a submitted phrase to start before waiting for completion.
SSC_EFFECT_IDLE
SSC_EFFECT_IDLE = 0x20
Set when the sound effect is idle. It reports the effect engine independently of speech.
SSC_MAX_TEXT
SSC_MAX_TEXT = 62
Maximum number of printable ASCII characters in a phrase; leave space in the C string for its terminator.
ssc_store_phrase
unsigned char ssc_store_phrase(unsigned char slot, const char *text, unsigned int poll_limit);
Save 1–62 printable ASCII characters in speech slot 0–7. Lowercase letters are converted to uppercase. The slot can be played again after the caller reuses the string. Replaces earlier text or allophones in the same slot.
ssc_play_phrase
unsigned char ssc_play_phrase(unsigned char slot, unsigned int poll_limit);
Speak the English text most recently saved in this speech slot. Store it first with ssc_store_phrase. Wait for it to finish before replacing its contents.
ssc_store_allophones
unsigned char ssc_store_allophones(unsigned char slot, const unsigned char *codes, unsigned int count, unsigned int poll_limit);
Save 1–62 SP0256 sound codes from a byte array in speech slot 0–7. Pass the number of sounds, including any pauses you put between them. The helper supplies a final quiet pause and the end marker. Invalid input leaves the old slot intact.
ssc_play_allophones
unsigned char ssc_play_allophones(unsigned char slot, unsigned int poll_limit);
Replay a custom pronunciation saved with ssc_store_allophones. Select the cartridge audio route before listening. The loop in Mission Announcer accepts a joystick press during playback.
ssc_store_enveloped_tone
unsigned char ssc_store_enveloped_tone(unsigned char slot, unsigned char channel, unsigned int tone_period, unsigned char shape, unsigned int envelope_period, unsigned char duration, unsigned int poll_limit);
Save a fading or repeating tone in sound slot 0–7. Channels A, B and C are 0–2. A larger tone period (1–4095) lowers the pitch. Shape (0–15) chooses the volume pattern. A larger envelope period (1–65535) slows that pattern. Duration (0–255) counts cartridge timer units before silencing the chosen channel. The three channels share one envelope generator.
ssc_play_stored_effect
unsigned char ssc_play_stored_effect(unsigned char slot, unsigned int poll_limit);
Start the sequence in a previously loaded sound slot. This bank is separate from speech. The fixed-volume tone and noise helpers replace sound slot 0, so choose another slot to keep a custom alert across those calls.
SSC_MAX_ALLOPHONES
SSC_MAX_ALLOPHONES = 62
Maximum caller-supplied sound codes in one stored pronunciation. Allocate an unsigned char for each code, including pauses.
SSC_ENV_DECAY
SSC_ENV_DECAY = 0
Start at full volume, fall to silence and stay there.
SSC_ENV_REPEAT_DECAY
SSC_ENV_REPEAT_DECAY = 8
Start loud, fade, then jump back to full volume for each repetition.
SSC_ENV_REPEAT_RISE
SSC_ENV_REPEAT_RISE = 12
Start quiet and swell, then drop back to silence for each repetition.
SSC_ENV_TRIANGLE
SSC_ENV_TRIANGLE = 14
Rise and fall repeatedly between silence and full volume.
SSC_AL_PA1
SSC_AL_PA1 = 0
A very short silent gap; the store helper also appends this pause at the end.
SSC_AL_PA2
SSC_AL_PA2 = 1
A short silent gap.
SSC_AL_PA3
SSC_AL_PA3 = 2
A medium silent gap.
SSC_AL_PA4
SSC_AL_PA4 = 3
A longer silent gap.
SSC_AL_PA5
SSC_AL_PA5 = 4
A long silent gap.
SSC_AL_OY
SSC_AL_OY = 5
Listen for the vowel in voice.
SSC_AL_AY
SSC_AL_AY = 6
Listen for the vowel in flight.
SSC_AL_EH
SSC_AL_EH = 7
Listen for the vowel in jet.
SSC_AL_KK3
SSC_AL_KK3 = 8
Listen for the initial k sound in cold.
SSC_AL_PP
SSC_AL_PP = 9
Listen for the initial p in pilot.
SSC_AL_JH
SSC_AL_JH = 10
Listen for the initial j in jet.
SSC_AL_NN1
SSC_AL_NN1 = 11
Listen for the final n in sun.
SSC_AL_IH
SSC_AL_IH = 12
Listen for the vowel in ship.
SSC_AL_TT2
SSC_AL_TT2 = 13
Listen for the initial t in two.
SSC_AL_RR1
SSC_AL_RR1 = 14
Listen for the initial r in red.
SSC_AL_AX
SSC_AL_AX = 15
Listen for the weak first vowel in about.
SSC_AL_MM
SSC_AL_MM = 16
Listen for the initial m in moon.
SSC_AL_TT1
SSC_AL_TT1 = 17
Listen for the final t in light.
SSC_AL_DH1
SSC_AL_DH1 = 18
Listen for the voiced th in this.
SSC_AL_IY
SSC_AL_IY = 19
Listen for the vowel in beam.
SSC_AL_EY
SSC_AL_EY = 20
Listen for the vowel in space.
SSC_AL_DD1
SSC_AL_DD1 = 21
Listen for the final d in land.
SSC_AL_UW1
SSC_AL_UW1 = 22
Listen for the oo vowel in too.
SSC_AL_AO
SSC_AL_AO = 23
Listen for the aw vowel in launch.
SSC_AL_AA
SSC_AL_AA = 24
Listen for the ah vowel in pod.
SSC_AL_YY2
SSC_AL_YY2 = 25
Listen for the initial y in yard.
SSC_AL_AE
SSC_AL_AE = 26
Listen for the vowel in map.
SSC_AL_HH1
SSC_AL_HH1 = 27
Listen for the initial h in heat.
SSC_AL_BB1
SSC_AL_BB1 = 28
Listen for the initial b in base.
SSC_AL_TH
SSC_AL_TH = 29
Listen for the unvoiced th in thrust.
SSC_AL_UH
SSC_AL_UH = 30
Listen for the vowel in push.
SSC_AL_UW2
SSC_AL_UW2 = 31
Listen for the long oo in moon.
SSC_AL_AW
SSC_AL_AW = 32
Listen for the vowel in cloud.
SSC_AL_DD2
SSC_AL_DD2 = 33
Listen for the initial d in dock.
SSC_AL_GG3
SSC_AL_GG3 = 34
Listen for the final g in flag.
SSC_AL_VV
SSC_AL_VV = 35
Listen for the initial v in valve.
SSC_AL_GG1
SSC_AL_GG1 = 36
Listen for the initial g in gone.
SSC_AL_SH
SSC_AL_SH = 37
Listen for the sh in ship.
SSC_AL_ZH
SSC_AL_ZH = 38
Listen for the middle consonant in measure.
SSC_AL_RR2
SSC_AL_RR2 = 39
Listen for the r after b in brake.
SSC_AL_FF
SSC_AL_FF = 40
Listen for the initial f in fuel.
SSC_AL_KK2
SSC_AL_KK2 = 41
Listen for the k after s in scan.
SSC_AL_KK1
SSC_AL_KK1 = 42
Listen for the initial k sound in cap.
SSC_AL_ZZ
SSC_AL_ZZ = 43
Listen for the initial z in zero.
SSC_AL_NG
SSC_AL_NG = 44
Listen for the final ng in wing.
SSC_AL_LL
SSC_AL_LL = 45
Listen for the initial l in launch.
SSC_AL_WW
SSC_AL_WW = 46
Listen for the initial w in wind.
SSC_AL_XR
SSC_AL_XR = 47
Listen for the air sound in flare.
SSC_AL_WH
SSC_AL_WH = 48
Listen for the breathy wh in where in accents that distinguish it from wear.
SSC_AL_YY1
SSC_AL_YY1 = 49
Listen for the initial y in year.
SSC_AL_CH
SSC_AL_CH = 50
Listen for the ch in chart.
SSC_AL_ER1
SSC_AL_ER1 = 51
Listen for the stressed er in turn.
SSC_AL_ER2
SSC_AL_ER2 = 52
Listen for a longer er sound, as in burn.
SSC_AL_OW
SSC_AL_OW = 53
Listen for the vowel in probe.
SSC_AL_DH2
SSC_AL_DH2 = 54
Listen for a second voiced th sound, as in those.
SSC_AL_SS
SSC_AL_SS = 55
Listen for the final s sound in space.
SSC_AL_NN2
SSC_AL_NN2 = 56
Listen for the initial n in north.
SSC_AL_HH2
SSC_AL_HH2 = 57
Listen for the initial h in home.
SSC_AL_OR
SSC_AL_OR = 58
Listen for the or in orbit.
SSC_AL_AR
SSC_AL_AR = 59
Listen for the ar in star.
SSC_AL_YR
SSC_AL_YR = 60
Listen for the ear sound in near.
SSC_AL_GG2
SSC_AL_GG2 = 61
Listen for the initial g in gear.
SSC_AL_EL
SSC_AL_EL = 62
Listen for the final syllable in shuttle.
SSC_AL_BB2
SSC_AL_BB2 = 63
Listen for a second b sound, as in boot.
vcc/orch90.h
Add orch90 in Project Settings → Libraries and assign an Orchestra-90 cartridge. Direct sample writes work without the optional Orchestra music ROM. Each byte selects a DAC level from 0 through 255. Choose the clock constant that matches the guest CPU speed.
orch90_frame · orch90_write · orch90_play · orch90_start · orch90_active · orch90_stop · ORCH90_CLOCK_NORMAL · ORCH90_CLOCK_FAST
orch90_frame
struct orch90_frame
One interleaved stereo pair of unsigned bytes. left is the left DAC level and right the right DAC level. A block of 128 frames occupies 256 bytes.
orch90_write
void orch90_write(unsigned char left, unsigned char right);
Latch one unsigned level on each stereo channel. Both hold their values until the next write. To finish a centered waveform, write 128 to each channel.
orch90_play
unsigned char orch90_play(const struct orch90_frame *frames, unsigned int count, unsigned char clock);
Send count stereo frames from guest-addressable memory at approximately 4,000 pairs per second. The call occupies the foreground while sending samples. Interrupts can delay it. An empty valid block succeeds without a write. Bad clock, missing data or an address wrap returns 0. Success cannot establish that this write-only device is installed.
orch90_start
unsigned char orch90_start(const struct orch90_frame *frames, unsigned int count, unsigned char loop, unsigned char clock);
Start stereo playback from the foreground. Pass a nonempty array of stereo frames, 0 for one pass or 1 to loop, and the current guest CPU speed. Keep the array mapped and unchanged until orch90_active returns 0. Its lifetime, and that of the program and stack, must cover the entire playback.
The player uses fast speed while active and takes one stereo frame every four serviced horizontal interrupts. With NTSC timing that allows about 3,930 frames per second. Leave the ordinary BASIC vertical interrupt and IRQ enabled. Playback begins within two vertical ticks once the clock settles. Long interrupt masks or reads of the joystick’s PIA can delay a sample. Reserve the horizontal interrupt, CPU clock and Orchestra DACs for the player. The GIME timer and FIRQ vector remain available.
A return of 1 means the player accepted the buffer. A zero return can mean invalid arguments, playback already in progress, a replaced BASIC IRQ vector or an unavailable horizontal interrupt. The DACs are write-only, so starting can succeed with an empty cartridge slot. Steer the Stereo Flyby while a sample repeats.
orch90_active
unsigned char orch90_active(void);
Returns 1 while the background player owns the sample and 0 after a one-shot finishes or orch90_stop releases it. A foreground loop can use this answer to light a playback indicator. It cannot detect a cartridge.
orch90_stop
void orch90_stop(void);
End background playback before changing the sample, changing its memory mapping or returning to BASIC. Playback cleanup centers both DACs and releases the player’s interrupt and clock settings. Calling stop again after completion is safe.
ORCH90_CLOCK_NORMAL
ORCH90_CLOCK_NORMAL = 0
Tell the player the guest starts at normal CPU speed. Foreground playback uses this setting for a delay. Background playback uses it to restore normal speed afterward.
ORCH90_CLOCK_FAST
ORCH90_CLOCK_FAST = 1
Tell the player the guest starts at fast CPU speed. Foreground playback uses the fast delay. Background playback leaves the guest at fast speed when it finishes.
errno.h
Use vcccompat and include <errno.h> to inspect a numeric conversion. Set errno to zero just before the call. A failure can set EINVAL or ERANGE. Disk streams have their own device error reporting.
errno
extern int errno;
The guest's numeric conversions share this error indicator. A successful conversion leaves its previous value alone. The same is true when the input contains no digits. To tell an empty conversion from a valid zero, compare the returned end pointer with the original string pointer.
EINVAL
EINVAL = 22
The requested base was outside the accepted set. Choose zero for automatic detection or a base from 2 through 36. The conversion returns zero and leaves the end pointer at the original input.
ERANGE
ERANGE = 34
The digits describe a value outside the result type's range. The return value is the nearest signed limit for strtol or ULONG_MAX for strtoul. The end pointer still advances past the full sequence of valid digits.
ctype.h
Add vcccompat and include <ctype.h>. Pass an unsigned byte value or EOF. Cast a plain char through unsigned char first when it may contain a high-bit character. The runtime also supplies isalnum, isalpha, isdigit, isspace, tolower and toupper.
isblank · iscntrl · isgraph · islower · isprint · ispunct · isupper · isxdigit
isblank
int isblank(int c);
Test for space or horizontal tab.
iscntrl
int iscntrl(int c);
Test for ASCII control codes 0–31 or DEL (127).
isgraph
int isgraph(int c);
Test for a visible ASCII character other than space.
islower
int islower(int c);
Test for a lowercase ASCII letter.
isprint
int isprint(int c);
Test for a visible ASCII character or space.
ispunct
int ispunct(int c);
Test for a printable ASCII punctuation mark. Space, digits and letters return false.
isupper
int isupper(int c);
Test for an uppercase ASCII letter.
isxdigit
int isxdigit(int c);
Test for ASCII digits 0–9, A–F or a–f.
limits.h
Add vcccompat and include <limits.h>. A plain char is signed. Short and int occupy two bytes, long four. The target has no 64-bit integer type.
CHAR_BIT · SCHAR_MIN · SCHAR_MAX · UCHAR_MAX · CHAR_MIN · CHAR_MAX · SHRT_MIN · SHRT_MAX · USHRT_MAX · INT_MIN · INT_MAX · UINT_MAX · LONG_MIN · LONG_MAX · ULONG_MAX · MB_LEN_MAX
CHAR_BIT
CHAR_BIT = 8
Number of bits in a target byte.
SCHAR_MIN
SCHAR_MIN = (-127 - 1)
Smallest representable value of signed char on the CMOC target.
SCHAR_MAX
SCHAR_MAX = 127
Largest representable value of signed char on the CMOC target.
UCHAR_MAX
UCHAR_MAX = 255U
Largest representable value of unsigned char on the CMOC target.
CHAR_MIN
CHAR_MIN = SCHAR_MIN
Smallest representable value of plain char on the CMOC target.
CHAR_MAX
CHAR_MAX = SCHAR_MAX
Largest representable value of plain char on the CMOC target.
SHRT_MIN
SHRT_MIN = (-32767 - 1)
Smallest representable value of short on the CMOC target.
SHRT_MAX
SHRT_MAX = 32767
Largest representable value of short on the CMOC target.
USHRT_MAX
USHRT_MAX = 65535U
Largest representable value of unsigned short on the CMOC target.
INT_MIN
INT_MIN = SHRT_MIN
Smallest representable value of int on the CMOC target.
INT_MAX
INT_MAX = SHRT_MAX
Largest representable value of int on the CMOC target.
UINT_MAX
UINT_MAX = USHRT_MAX
Largest representable value of unsigned int on the CMOC target.
LONG_MIN
LONG_MIN = (-2147483647L - 1L)
Smallest representable value of long on the CMOC target.
LONG_MAX
LONG_MAX = 2147483647L
Largest representable value of long on the CMOC target.
ULONG_MAX
ULONG_MAX = 4294967295UL
Largest representable value of unsigned long on the CMOC target.
MB_LEN_MAX
MB_LEN_MAX = 1
Maximum byte count for one character in this single-byte subset.
stddef.h
Add vcccompat and include <stddef.h>. The runtime supplies size_t, NULL and offsetof. Only subtract pointers within the same array or one past its end.
ptrdiff_t
typedef signed int ptrdiff_t;
Signed 16-bit difference between two positions in the same array, when representable.
stdint.h
Add vcccompat and include <stdint.h>. The exact-width integer types match the declarations in coco.h. Pointers occupy 16 bits. This subset also supplies the pointer-width and maximum-width types and their limits. Omit 64-bit, least-width and fast-width types when writing code for this subset.
intptr_t · uintptr_t · intmax_t · uintmax_t · INT8_MIN · INT8_MAX · UINT8_MAX · INT16_MIN · INT16_MAX · UINT16_MAX · INT32_MIN · INT32_MAX · UINT32_MAX · INTPTR_MIN · INTPTR_MAX · UINTPTR_MAX · INTMAX_MIN · INTMAX_MAX · UINTMAX_MAX
intptr_t
typedef signed int intptr_t;
Signed 16-bit integer capable of holding a converted guest pointer.
uintptr_t
typedef unsigned int uintptr_t;
Unsigned 16-bit integer capable of holding a converted guest pointer.
intmax_t
typedef signed long intmax_t;
The widest signed integer supported here, a 32-bit long.
uintmax_t
typedef unsigned long uintmax_t;
The widest unsigned integer supported here, a 32-bit unsigned long.
INT8_MIN
INT8_MIN = SCHAR_MIN
Smallest representable value of int8_t.
INT8_MAX
INT8_MAX = SCHAR_MAX
Largest representable value of int8_t.
UINT8_MAX
UINT8_MAX = UCHAR_MAX
Largest representable value of uint8_t.
INT16_MIN
INT16_MIN = INT_MIN
Smallest representable value of int16_t.
INT16_MAX
INT16_MAX = INT_MAX
Largest representable value of int16_t.
UINT16_MAX
UINT16_MAX = UINT_MAX
Largest representable value of uint16_t.
INT32_MIN
INT32_MIN = LONG_MIN
Smallest representable value of int32_t.
INT32_MAX
INT32_MAX = LONG_MAX
Largest representable value of int32_t.
UINT32_MAX
UINT32_MAX = ULONG_MAX
Largest representable value of uint32_t.
INTPTR_MIN
INTPTR_MIN = INT_MIN
Smallest representable value of intptr_t.
INTPTR_MAX
INTPTR_MAX = INT_MAX
Largest representable value of intptr_t.
UINTPTR_MAX
UINTPTR_MAX = UINT_MAX
Largest representable value of uintptr_t.
INTMAX_MIN
INTMAX_MIN = LONG_MIN
Smallest representable value of intmax_t.
INTMAX_MAX
INTMAX_MAX = LONG_MAX
Largest representable value of intmax_t.
UINTMAX_MAX
UINTMAX_MAX = ULONG_MAX
Largest representable value of uintmax_t.
stdio.h
Add vcccompat for the bounded formatters. For Disk BASIC file streams, select vcccompat followed by decbfile and include <stdio.h>. The guest can keep two streams open at once. Each uses the disk currently routed to its logical drive. Close all streams before changing the mounted image or its routing. Finish any BASIC file operations on that drive before opening a writer. Console printf keeps its CMOC formatting conventions.
snprintf · vsnprintf · fprintf · vfprintf · EOF · FILE · fopen · fgetc · fgets · fread · fputc · fputs · fwrite · fflush · ftell · fseek · rewind · vcc_rewind · SEEK_SET · SEEK_CUR · SEEK_END · feof · ferror · clearerr · rename · remove · fclose · vcc_file_error
FILE
typedef struct VCCFile FILE;
Each handle has its own sector buffer, position and error indicator. A reader also keeps track of end-of-file. Keep the pointer returned by fopen, then release it once with fclose.
fopen
FILE *fopen(const char *path, const char *mode);
Open a file on a mounted guest disk. Use an 8.3 Disk BASIC filename, optionally followed by a drive number, as in PLANETS.TXT:0. Drives 0 through 3 are accepted. The guest firmware determines which device answers. Use a one-to-eight-character name and, if present, a one-to-three-character extension. Spaces, wildcards and folder paths are rejected. Names are case-insensitive and default to drive 0. A null result means open failed. Check vcc_file_error for the Disk BASIC status.
| Text mode | Binary mode | What happens at open |
|---|---|---|
r |
rb |
Read an existing file from byte zero. |
r+ |
r+b or rb+ |
Read and write an existing file from byte zero. Its contents and length are preserved. A missing file returns DECB_ERR_NOT_FOUND. |
w |
wb |
Write from byte zero. Create the file if absent or immediately truncate it if present. |
w+ |
w+b or wb+ |
Create an empty file for reading and writing. Opening an existing file immediately discards its contents. |
a |
ab |
Keep existing contents and write at the end. Create the file if absent. |
a+ |
a+b or ab+ |
Read existing contents from byte zero. Every write appends, even after a seek. Create the file if absent. |
These are the supported modes. Text input translates CR, LF and CRLF to a C newline. Text output stores a newline as CR. Choose binary mode for fixed-size records. Before opening a write-capable handle, close any other handle to that filename. After a successful flush, a second read-only handle can open the published contents.
On an update stream, use fseek before switching from reading to writing. You can write immediately if the read reached end-of-file. To switch from writing to reading, first flush or seek successfully. A direction change without the required step fails, leaves the position intact and sets vcc_file_error() to DECB_ERR_INVALID_ARGUMENT. Mark a planet as visited or add a return trip.
fgetc
int fgetc(FILE *stream);
Read one character at the current position and advance. Keep the result in an int until you have compared it with EOF. In binary mode a stored $FF byte yields 255, distinct from EOF. On EOF, inspect ferror to distinguish a read failure from the end of the file.
fgets
char *fgets(char *dest, int capacity, FILE *stream);
Supply a writable array and its capacity, including room for the final zero. A successful call returns dest and includes the newline if it fit. With capacity 1 the function returns an empty string and consumes no input. Use at least 2 to advance. A long line can take several calls. A final line without a newline can still be delivered before end-of-file. On a null result, check ferror before using the array.
fread
size_t fread(void *dest, size_t size, size_t count, FILE *stream);
Read up to count items of size bytes into a writable buffer with room for all requested data. The return counts complete items. A short item can leave part of its data in the buffer. For a byte count, pass size 1. Choose rb when the data contains arbitrary bytes. A request for zero items or zero-sized items returns zero.
fputc
int fputc(int c, FILE *stream);
Write one byte to an open output stream. Returns the byte as an integer, or EOF on failure. In a text file the C newline is stored as a Disk BASIC carriage return. Use a binary mode to preserve the byte exactly.
fputs
int fputs(const char *text, FILE *stream);
Write a zero-terminated C string. The terminating zero stays in memory. Include a newline in the string if you want to end the disk record. A nonnegative result means the stream accepted the text. EOF signals an error.
fprintf
int fprintf(FILE *stream, const char *format, ...);
Write formatted characters directly to a writable guest file. Use the conversions, width and precision described under snprintf. Supply a matching argument for each conversion. The return counts characters accepted by the stream. A result of −1 signals a format, range or output failure. A prefix of the record may already have been written. A C newline follows the open file’s text or binary mode. Check fflush or fclose to catch errors that surface when the disk receives the buffered data.
vfprintf
int vfprintf(FILE *stream, const char *format, va_list args);
Use this form inside a function that accepts a variable argument list. Pass the destination file, the format string and an initialized va_list. It uses the same conversions, return count and failure handling as fprintf.
fwrite
size_t fwrite(const void *source, size_t size, size_t count, FILE *stream);
Write up to count elements of size bytes from an array. Returns the number of whole elements accepted. Use size 1 for a byte count. Zero size or count returns zero. A short result can include a partially written last element. Check the result before advancing the source pointer, then check flush or close for buffered output errors.
fflush
int fflush(FILE *stream);
Make pending output readable on the mounted guest disk and keep the stream open so the program can write the next record. Pass NULL to flush all open output streams. A successful flush also lets an update stream switch from output to input at its current position. Passing a read-only handle or an update handle whose last operation was input returns EOF. Flushing all streams skips handles in the input phase. A zero result means success. On EOF, check ferror before closing. If a protected disk refused a flush, leave the stream open, make that same disk writable, call clearerr and retry the flush. If a long write fails, the file can contain the portion already written. The emulator's write-protection and temporary-changes settings still govern the disk image on the Mac.
ftell
long ftell(FILE *stream);
Get the current file position. Store it in a long so it still works above byte 65,535. At the beginning the position is zero. On a binary stream it counts bytes from the beginning. On a text reader, use the result as a bookmark with SEEK_SET. A carriage return and line feed on disk can produce just one C newline. On an output stream the position includes bytes accepted into its buffer. A return of −1 signals failure.
fseek
int fseek(FILE *stream, long offset, int origin);
Move to a position in an open file. For a binary stream, choose SEEK_SET, SEEK_CUR or SEEK_END and supply a signed byte offset. Both the beginning and the exact end of the file are valid destinations. Success returns zero and clears the end-of-file indicator. An out-of-range request returns nonzero and leaves the previous position and EOF indicator intact.
For text, restore a bookmark with SEEK_SET, or use a zero offset to go to the start, the current position or the end. Seeking on a writer flushes pending bytes. A successful seek on an update stream permits either reading or writing next. Check the result before continuing. An ordinary writer can then overwrite part of what it has written. In append mode the next write always goes to the end. A seek past the end cannot grow the file.
rewind
rewind = vcc_rewind
With stdio.h alone, write rewind(stream) to return to the beginning. A source file that also includes disk.h can use both interfaces. In that file use vcc_rewind for a FILE stream and rewind for a FileDesc.
vcc_rewind
void vcc_rewind(FILE *stream);
Return to the start of the file and clear the stream’s error and EOF indicators on success. Use this after reading the last record to read the first one again. When a program needs to check whether repositioning succeeded, use fseek with zero and SEEK_SET.
SEEK_SET
SEEK_SET = 0
Measure the offset from the start of the file. With fixed-size binary records, multiply the zero-based record number by the record size. Use a long operand before multiplying when the product may exceed a 16-bit integer.
SEEK_CUR
SEEK_CUR = 1
Measure the offset from the stream’s current position. A negative offset moves a binary reader backward. Text streams accept a zero relative offset.
SEEK_END
SEEK_END = 2
Measure the offset from the end of the file. On a nonempty binary file, −1 selects the last byte. Zero selects the position immediately after the last byte and also works on empty files and text streams.
feof
int feof(FILE *stream);
Return nonzero after a read has encountered end-of-file. Reading exactly the last available byte can succeed with this indicator still clear. Drive a loop with the result of the read and inspect feof and ferror afterward.
ferror
int ferror(FILE *stream);
Return the saved decbfile error code when disk I/O or allocation has failed on this open stream. Inspect the indicator before closing the file. A disk that successfully delivered its last byte can reach EOF with its error indicator clear.
clearerr
void clearerr(FILE *stream);
Clear the saved error and end-of-file indicators for this open stream. The file position, pending output and current read/write direction stay intact. After a failed flush on a protected practice disk, make the same disk writable, call clearerr, then check the result of a new fflush. Only a successful flush confirms the buffered bytes reached the guest disk. After clearing EOF on a reader, another read at the end can set EOF again.
rename
int rename(const char *oldPath, const char *newPath);
Give a closed guest disk file a new 8.3 name on the same logical drive. For example, rename("ATLAS.DAT:1", "ATLAS.BAK:1") keeps the data and changes the directory entry on drive 1. An omitted drive suffix means drive 0 on either argument. The new name must be unused. Names compare without regard to case, so a change of capitalization alone also fails. Close any streams using either name first. A successful call returns zero. On failure it returns a nonzero value and vcc_file_error gives the reason. Renaming the old atlas and installing its replacement are two separate operations. The exercise shows which name to look for if the program stops between them.
remove
int remove(const char *path);
Delete a closed file from the mounted guest disk and release its granules for reuse. An optional suffix such as :1 selects the logical drive. There is no undo. Check that you have a complete copy under the name you intend to keep before removing a draft or backup. Zero means success. A nonzero result means failure. Check vcc_file_error to distinguish a missing file from a disk error.
fclose
int fclose(FILE *stream);
Flush pending output and release the stream slot. A successful close returns zero. Check for EOF on a failed output operation or an invalid handle. A disk can fill while flushing the last sector, even after a write appeared to succeed. The pointer is no longer usable after close. Close both handles individually if two files are open.
vcc_file_error
unsigned char vcc_file_error(void);
Look up the most recent file failure, particularly after fopen returns a null pointer. The result is a DECB_ERR_* code from decbfile.h. A successful open clears the saved code. An update-stream direction error also appears here. For a disk I/O error on a particular open stream, use ferror.
snprintf
int snprintf(char *dest, size_t capacity, const char *format, ...);
Format into a caller-owned buffer. A positive capacity always leaves a terminating NUL after the stored prefix. A zero capacity writes nothing and permits a null pointer. The return is the number of bytes the complete result would occupy, excluding the terminator. A value at least as large as capacity indicates truncation. Negative means an unsupported format or a result outside the signed 16-bit range. Supported conversions are %% (a percent sign), %c, %s, %d, %i, %u, %o, %x and %X. Integer conversions accept l. Decimal width, left alignment, numeric zero padding, and string or integer precision are available. Dynamic width, floating point and %n are outside this subset.
vsnprintf
int vsnprintf(char *dest, size_t capacity, const char *format, va_list args);
Same bounded behavior and format subset as snprintf. Supply an initialized va_list for the arguments after the format string. Each conversion must match its promoted argument type.
EOF
EOF = (-1)
A negative int distinct from valid unsigned byte values. It can be passed through the character classifiers.
stdlib.h
Use vcccompat for strtol and strtoul. For allocation, also add wydealloc after vcccompat in library order. The VCC Plus allocation functions share one foreground heap inside a caller-owned guest memory region. Initialize it before requesting storage. A request can fail when free space is fragmented or the pool is exhausted. The raw WydeAlloc interface can manage additional independent pools.
vcc_heap_init · malloc · calloc · realloc · free
strtol (stdlib.h)
long strtol(const char *text, char **endptr, int base);
Read a signed 32-bit number from a zero-terminated string. Leading ASCII whitespace and a single plus or minus sign are accepted. Supply base 2 through 36 to choose the digits. Letters A through Z stand for values 10 through 35, in either case. Base zero recognizes hexadecimal 0x or 0X before a hex digit, octal for a leading 0, and decimal otherwise. Base 16 also accepts the hex prefix. For binary input use base 2 and supply the digits without a prefix.
With a writable char pointer called end, pass &end to receive the address of the first unconverted character. If no digit was read, the result is zero and end points to the original input. You may pass NULL when you do not need the end position. On overflow the result is LONG_MIN (−2,147,483,648) or LONG_MAX (2,147,483,647) and errno becomes ERANGE. An unsupported base sets EINVAL.
strtoul (stdlib.h)
unsigned long strtoul(const char *text, char **endptr, int base);
Read an unsigned 32-bit number using the same digits, bases, optional sign and end-pointer rules as strtol. A leading minus sign negates an in-range magnitude in unsigned arithmetic, so -1 yields 4,294,967,295. A magnitude larger than 4,294,967,295 yields ULONG_MAX and sets ERANGE. Clear errno before converting if you need to distinguish overflow from an exact ULONG_MAX.
vcc_heap_init
int vcc_heap_init(void *buffer, size_t capacity);
Give the allocator a writable region of at least 16 bytes that stays mapped at the same guest address throughout use. A static byte array works. Pass the array and its size in bytes. The address immediately after the region must also fit in 16 bits. Keep stack space and other application data outside this region. Bookkeeping takes part of the capacity. A return of 1 means success. Invalid arguments or any live allocation cause the call to return 0 and preserve the previous heap. Once every block has been released, you may initialize a new region.
malloc
void *malloc(size_t size);
Request a contiguous block of size bytes from the initialized heap. Initialize its contents before reading them. A zero request, an unavailable heap or insufficient space yields a null pointer. Release each successful allocation exactly once with free unless realloc has already replaced or released it.
calloc
void *calloc(size_t count, size_t size);
Request space for count objects of size bytes each. All bytes in a successful allocation start at zero. A zero argument, a product too large for a 16-bit size, or insufficient memory yields a null pointer. Pass count and size separately so the allocator can detect multiplication overflow.
realloc
void *realloc(void *ptr, size_t size);
Resize a live allocation from this heap. Keep the returned pointer in a temporary until you check it. A nonzero request that fails leaves the original pointer and all its bytes valid. Success preserves the first bytes up to the smaller of the old and new sizes. Initialize any new bytes. Shrinking keeps the same block and reserves its underlying storage until it is freed. When growth moves the data, the old and new blocks must both fit during the copy. Passing a null pointer makes an ordinary allocation. Size zero releases the old allocation and returns a null pointer.
free
void free(void *ptr);
Return a live allocation to the same heap. Use the pointer to the beginning of the block returned by malloc, calloc or realloc. All pointers into that block expire when it is freed. Passing a null pointer is harmless.
string.h
Add vcccompat and include <string.h>. This header publishes the existing CMOC declarations, including strlen, strcmp, strchr, strtok, memcpy and memmove. When buffers overlap, choose memmove. Only the documented CMOC subset is available.
For a list inside a record, use strtok_r with one saved position for the record and another for the list.
strtok_r
char *strtok_r(char *text, const char *delimiters, char **saveptr);
This POSIX extension finds the next nonempty token in a writable string. Start with the string and the address of a char * variable. To continue, pass NULL for the string and the same variable’s address. Each character in delimiters is a separator. Leading and repeated separators are skipped. An empty delimiter string takes the whole remaining text as one token. When no token remains, the call returns NULL.
The result points into the original buffer. The function writes a zero byte at the separator following a token, so use a writable array and finish with the returned pointers before refilling that array. Each scan gets its own saved position. In Planet Survey, this lets you resume the outer record after splitting the traits inside it.
vcc/printer.h
Select vcccompat under Project Settings → Libraries. These foreground routines call the CoCo BASIC ROM to send text to its serial printer. Each call preserves the program’s regular output destination. Open Media → Printer Output… and choose Start Capture to collect the bytes on the Mac. Send the flight report.
vcc_printer_printf
int vcc_printer_printf(const char *format, ...);
Supply the format string and one argument for each conversion. The snprintf formatting rules apply. The printer receives a carriage return for each C newline. The result counts formatted characters handed to BASIC. A format error or a count above 32,767 returns −1. A prefix may already have gone to the printer. To check that capture was enabled, look in Printer Output after sending. Flight report exercise.
vcc_printer_vprintf
int vcc_printer_vprintf(const char *format, va_list args);
Use this form inside a helper that takes a variable number of arguments. Initialize the list with va_start, forward it with the format string, then call va_end in the helper. It uses the same printer route, conversions and return values as vcc_printer_printf.
vcc/input.h
Add input, then bcontrol to your linked libraries. Use the standard analog CoCo joystick and the usual BASIC PIA configuration. Initialize one record per port and let movement, firing and charging all read the same snapshot. Launch a survey probe.
Sampling runs in the foreground. It temporarily masks IRQ and FIRQ while it reads the axes and buttons, then restores the interrupt masks, keyboard column output, DAC value and sound routing. Reading a PIA data register can acknowledge a pending PIA interrupt. When using Orchestra-90 foreground playback, sample between blocks. Shorter blocks let the game check the controls more often.
VccInput · INPUT_RIGHT · INPUT_LEFT · INPUT_PRIMARY · INPUT_SECONDARY · input_init · input_sample
VccInput
typedef struct { … } VccInput;
Keep one of these records per player. After a sample, x and y range from 0 to 63, increasing to the right and down. The signed dx and dy fields report direction: −1 below 26, zero from 26 through 37, and +1 above 37. Use held, pressed and released as button masks. All three describe the same sample.
INPUT_RIGHT
INPUT_RIGHT = 0
Select the right CoCo joystick port when initializing a record.
INPUT_LEFT
INPUT_LEFT = 1
Select the left CoCo joystick port. Each port can have its own record and press history.
INPUT_PRIMARY
INPUT_PRIMARY = 1
Test the first fire button with a bitwise AND, for example stick.pressed & INPUT_PRIMARY. The expression is true on the sample where the press first appears.
INPUT_SECONDARY
INPUT_SECONDARY = 2
Test the second fire button in any of the three button fields. Both buttons can be down together.
input_init
void input_init(VccInput *input, unsigned char port);
Establish the starting position and held buttons. If a player holds fire as the program starts, held includes it and both event masks start empty. An invalid port leaves a neutral, inactive record. A null pointer is ignored.
input_sample
void input_sample(VccInput *input);
Refresh the record once per game update. pressed contains the buttons that went down since the last sample, released contains those that went up, and held contains all buttons down now. A complete tap between samples can go unobserved. A null pointer is ignored.
vcc/gime.h
Add gime to a CoCo 3 BASIC project to use one 320 × 192 graphics display with 16 palette slots and two pages. Start from BASIC text mode (32, 40 or 80 columns), with the usual BASIC memory map, task 0 and interrupts enabled. The library temporarily uses the upper part of the CPU address space to reach video RAM. Keep your program, data and stack below $8000. Use this API from the foreground. Finish your drawing and close the session before using BASIC services such as printing or disk I/O.
Reserve physical $40000 through $4FFFF on a machine with at least 512 KiB of RAM. Opening clears the pictures in those 64 KiB. A page has 192 rows of 160 bytes and takes up four 8 KiB memory blocks. The two pages share a hardware palette. Fly the lander to see the pages alternate.
GIME_WIDTH · GIME_HEIGHT · gime_open · gime_clear · gime_plot · gime_fill_rect · gime_set_palette · gime_present · gime_close
GIME_WIDTH
GIME_WIDTH = 320
Number of pixels in a row. The x coordinate of the rightmost pixel is GIME_WIDTH minus one.
GIME_HEIGHT
GIME_HEIGHT = 192
Number of rows in each graphics page. The y coordinate of the bottom row is GIME_HEIGHT minus one.
gime_open
unsigned char gime_open(void);
Begin a two-page graphics session. A result of 1 means you can draw on the back page. A result of 0 means the requested session could not start, including when a session is already active. Check the result before drawing. The physical video pages belong to this session until you close it.
gime_clear
void gime_clear(unsigned char color);
Fill the entire back page with the palette slot color (0 through 15). The current picture stays visible while you prepare its replacement. Clearing all 30,720 bytes every frame costs guest CPU time. For a moving object on an otherwise static picture, consider erasing just its old footprint on each page.
gime_plot
void gime_plot(unsigned x, unsigned y, unsigned char color);
Set one back-page pixel. The origin is the upper left. Valid coordinates are x = 0 through 319 and y = 0 through 191. One byte holds two palette-slot numbers. Plotting one pixel preserves its neighbor. A BGraph drawing callback can pass its coordinates and slot directly to this function.
gime_fill_rect
void gime_fill_rect(unsigned x, unsigned y, unsigned w, unsigned h, unsigned char color);
Fill a back-page rectangle, starting at x, y. Its width and height are pixel counts. A width of 1 paints a single column. A height of 1 paints a single row. Drawing is clipped to the 320 × 192 picture. Choose a palette slot from 0 through 15. Zero-sized rectangles, origins outside the picture and invalid slots leave the page untouched.
gime_set_palette
void gime_set_palette(unsigned char slot, unsigned char rgb);
Set one of the 16 hardware palette slots to a six-bit GIME color (0 through 63). The bits, from high to low, are the high red, green and blue bits followed by their three low bits. On RGB output, $00 gives black, $3F gives white and $1B gives bright cyan. A palette change immediately affects both pages, including pixels already on screen.
gime_present
unsigned char gime_present(void);
Wait for a vertical field boundary and display the completed back page. A result of 1 means the previous front page is now yours to draw on. Its existing pixels remain there. A result of 0 means the pages did not swap. Check that a session is active and its field timing is available. In the lander, a failed presentation goes through normal cleanup and reports the problem after returning to text.
gime_close
void gime_close(void);
End the graphics session. Repeated calls after closing are safe. BASIC regains its text display and saved palette, and the CPU regains its original mapping. You can print the landing result and return from main. Data you previously kept in the two physical graphics pages is not recovered.
vcc/bank.h
Include <vcc/bank.h> and link bank to copy data between a C buffer and four reserved physical RAM banks on a CoCo 3. Use the ordinary CoCo 3 BASIC memory map with at least 512 KiB. Keep the program, its stack and the buffers below $8000. Use the library from foreground code, with the standard expansion bank group selected. A program that changes the raw MMU or expansion registers must restore the BASIC setup before using this library.
Dedicate physical $50000 through $57FFF to the program's assets. The caller owns this reservation. An asset offset counts bytes from $50000. It can span a bank boundary in a single call. The library temporarily maps one bank into the CPU window at $8000, transfers bytes, then restores the window. Code outside the call uses ordinary pointers to its own buffers. The GIME graphics pages occupy a separate region. Run the two-landscape exercise.
BANK_PAGE_SIZE · BANK_FIRST_PAGE · BANK_CAPACITY · bank_open · bank_read · bank_write · bank_close
BANK_PAGE_SIZE
BANK_PAGE_SIZE = 8192u
Number of bytes in one MMU bank. In the terrain exercise this is also the offset of the first Mars byte. The last Earth-bank byte is at offset 8,191.
BANK_FIRST_PAGE
BANK_FIRST_PAGE = 0x28
Physical number of the first reserved bank. Multiply by $2000 bytes per bank to find its starting address in the debugger. Use offset zero to reach this location in a transfer.
BANK_CAPACITY
BANK_CAPACITY = 32768u
Capacity of all four banks together, in bytes. The last asset byte has offset 32,767. A two-byte transfer from there fails before either byte is copied.
bank_open
unsigned char bank_open(void);
Start a bank session before the first transfer. Check for 1 before using it. Call with IRQ enabled. A repeated open or a failed mapping or memory check returns 0. On expanded machines the bank selector at $FF9B is write-only, so the caller must retain its normal BASIC setting. Opening preserves existing contents, so initialize the bytes your program plans to read.
bank_read
unsigned char bank_read(unsigned offset, void *destination, unsigned length);
Copy length bytes from the reserved banks into your writable C buffer. Check for 1 before using the result. A refused request returns 0 and leaves the destination alone. Supply a buffer large enough for the whole transfer. The library can check the address range but cannot determine a C array's declared length.
bank_write
unsigned char bank_write(unsigned offset, const void *source, unsigned length);
Copy length bytes from your C buffer into the reservation, starting at offset. Returns 1 on success and 0 on refusal. A transfer may continue into the next reserved bank. A request extending past the reservation changes no asset bytes. In an open session a zero-length transfer at the end of the reservation is valid.
bank_close
void bank_close(void);
End the session. Closing preserves the bytes in RAM and is safe to repeat. A later program or a power cycle can change that memory. To keep an edit across sessions, save the data to guest media.
vcc/sdc.h
Include <vcc/sdc.h> and link sdc. Use foreground calls from a low-memory CMOC program with the normal CoCo 3 BASIC map. The supported configuration uses the bundled 16 KiB SDC-DOS ROM and routes cartridge ROM and I/O to the same Multi-Pak slot, as in the CoCo SDC profile. The library leaves the Multi-Pak selection and the current card directory alone.
Browse a card with sdc_list_begin and sdc_list_next. Inspect the selected disk with sdc_mounted. Close guest files before changing a disk with sdc_mount. Open a file inside the selected image with fopen. Fly Planet Expedition.
SdcEntry · SDC_DIRECTORY · SDC_READ_ONLY · SDC_OK · SDC_END · SDC_UNAVAILABLE · SDC_TIMEOUT · SDC_INVALID · SDC_IO · SDC_NOT_FOUND · SDC_IN_USE · sdc_probe · sdc_list_begin · sdc_list_next · sdc_mounted · sdc_mount · SDC_PROTECTED
SdcEntry
typedef struct { … } SdcEntry;
A caller-owned result. name holds a terminated 8.3 basename, including the dot when there is an extension. attributes is a bit mask. size is a 32-bit byte count. Read the fields after a successful call. Save a copy if you reuse the same variable for your next result.
SDC_DIRECTORY
SDC_DIRECTORY = 0x10
Test this bit in attributes before offering to mount an entry. A directory can be browsed by passing its path and a pattern to sdc_list_begin.
SDC_READ_ONLY
SDC_READ_ONLY = 0x01
The entry carries the read-only attribute. A mounted image can still be read from a protected card. Check each disk operation for its own result.
SDC_OK
SDC_OK = 0
The operation succeeded. During enumeration this means entry describes one item, so the program can use it and request the next.
SDC_END
SDC_END = 1
The enumeration has reached its end. A pattern with no matches is a normal empty list. Start a fresh enumeration to browse again.
SDC_TIMEOUT
SDC_TIMEOUT = 3
The controller did not reach the expected state within the polling limit. Stop issuing dependent commands and query the drive again before opening a file.
SDC_INVALID
SDC_INVALID = 0x84
Check the drive number, argument, path and candidate image. A rejected image leaves the previous disk available in VCC Plus.
SDC_IO
SDC_IO = 0x88
The controller reported an input/output failure. Check the selected card folder and media before retrying.
SDC_NOT_FOUND
SDC_NOT_FOUND = 0x90
The requested file or folder could not be found. After a missing-image error from sdc_mount, the program can query the drive and read the disk that was already there.
SDC_IN_USE
SDC_IN_USE = 0xa0
The requested change conflicts with a disk already in use. Close files on the target drive and check whether the other drive already has this image mounted.
sdc_probe
unsigned char sdc_probe(void);
Call this before presenting card controls. Success means the guest can reach a supported SDC-DOS controller. A subsequent directory or image operation can still fail if the card folder is unavailable.
sdc_list_begin
unsigned char sdc_list_begin(const char *pattern);
Begin a card-directory listing. An absolute pattern such as **/*.DSK matches disk images at the root. Use /TRIPS/** followed by a pattern to inspect a subdirectory. A null or empty pattern lists the current directory. Only one listing is active at a time. Card paths use printable ASCII and fit in 253 bytes. Starting a second listing replaces the first. Finish the listing before mounting an image, because the mount uses the controller’s directory cursor.
sdc_list_next
unsigned char sdc_list_next(SdcEntry *entry);
Supply a writable entry. While the call returns SDC_OK, use the name, attributes and byte count. SDC_END finishes the loop. Treat other statuses as errors. The library fetches another controller block when a directory has more than 16 entries.
sdc_mounted
unsigned char sdc_mounted(unsigned char drive, SdcEntry *entry);
Supply drive 0 or 1 and an entry for the result. On success name holds the image’s basename and size counts its bytes on the card. The controller supplies the basename even for an image in a subdirectory. Keep the original card path separately if you will need to remount it. SDC_NOT_FOUND means the drive is empty.
sdc_mount
unsigned char sdc_mount(unsigned char drive, const char *path);
Mount an existing image on drive 0 or 1. Use an absolute card path such as /EARTH.DSK for a predictable location. First close every guest file on that drive. After success, open files on the replacement disk. In VCC Plus, a missing, invalid or already-mounted candidate leaves the previous image in place. Try a missing planet. Finish any decbfile session that caches the old disk’s allocation table. The library checks for a regular file before asking SDC-DOS to mount it. This prevents a folder named ALBUM.DSK from being treated as a set of disks.
SDC_PROTECTED
SDC_PROTECTED = 0xc0
The controller reports write protection. The library can list and mount readable images on a protected card. Check the mounted entry’s SDC_READ_ONLY bit when deciding whether to offer editing.
vcc/cassette.h
Select vcccompat in Project Settings → Libraries. One foreground program can have one cassette file open. The tape moves forward as you read. Set up the transport in Media → Cassette… before each trip. Flight Recorder shows how to write a file in C and read it from BASIC, then switch roles.
vcc_tape_open_write · vcc_tape_write_line · vcc_tape_open_read · vcc_tape_read_line · vcc_tape_close
VCC_TAPE_OK · VCC_TAPE_EOF · VCC_TAPE_IO · VCC_TAPE_INVALID · VCC_TAPE_LONG · VCC_TAPE_BUSY · VCC_TAPE_TYPE
vcc_tape_open_write
int vcc_tape_open_write(const char *name);
Choose New Recording → CAS before calling. Supply a guest filename of one to eight printable ASCII characters, such as FLIGHT. Use the same letter case when you open the file for reading. BASIC stores the spelling inside its filename string. The call writes its name block to the cassette. Check for VCC_TAPE_OK before writing lines, then close the file after the last line. Use Export Tape… to keep the recording on your Mac.
vcc_tape_write_line
int vcc_tape_write_line(const char *line);
Send one observation as a zero-terminated string of printable ASCII characters. The routine adds a carriage return so BASIC can use LINE INPUT #-1 to read that observation. Pass the text without a line ending. An empty string records a blank line. A file with no calls to this routine contains zero lines.
vcc_tape_open_read
int vcc_tape_open_read(const char *name);
Choose Play and supply the name the writer recorded. The tape search starts at the current position. Rewind before looking for a name you have already passed. Start reading once this call returns VCC_TAPE_OK.
vcc_tape_read_line
int vcc_tape_read_line(char *line, unsigned capacity);
Read the next complete line into a writable array. Pass the array size, including space for a trailing zero. A return of VCC_TAPE_OK means the array holds the record without its carriage return. A blank line returns that success code with an empty string. If BASIC suppressed the last carriage return with a trailing semicolon on PRINT, a verified end block completes that final string. The next read returns VCC_TAPE_EOF. VCC_TAPE_EOF means the tape contained its recorded end block. A negative return means reading failed. If a line was too long, the routine consumes that line and clears the array. You can read the next line. Check the result before using the array.
vcc_tape_close
int vcc_tape_close(void);
Finish the open file. On a writer, this sends any buffered data and the end block. A successful return means the CoCo finished sending them. Check the Cassette window and export the recording to keep it on the Mac. On a reader, close after reaching the end or after an error. To start reading the file again, rewind in the Cassette window and choose Play.
VCC_TAPE_OK
VCC_TAPE_OK = 0
The operation succeeded. From vcc_tape_read_line, this means one record was read. The record may have zero characters.
VCC_TAPE_EOF
VCC_TAPE_EOF = 1
The reader verified the file’s end block. Use this result to end a read loop normally.
VCC_TAPE_IO
VCC_TAPE_IO = (-1)
Reading failed. A missing end block, an incomplete data block or an invalid checksum can produce this result. Close the reader and try again with a complete recording.
VCC_TAPE_INVALID
VCC_TAPE_INVALID = (-2)
The arguments or operation were invalid. Check the filename, text, or buffer capacity and confirm that the file is open in the intended direction.
VCC_TAPE_LONG
VCC_TAPE_LONG = (-3)
The line exceeds the destination capacity, including its trailing zero. The reader consumes the oversized line and returns an empty string. Supply a larger buffer for longer observations.
VCC_TAPE_BUSY
VCC_TAPE_BUSY = (-4)
A C or BASIC cassette file is already open, or the tape motor is active. Finish the operation and close any open file before trying again.
VCC_TAPE_TYPE
VCC_TAPE_TYPE = (-5)
The name matched a file of an unsupported type. The reader expects a sequential ASCII data file recorded with gaps between its blocks.
vcc/decimal.h
Select vcccompat under Project Settings → Libraries and use the default CoCo BASIC floating-point backend. The destination belongs to your program. You can print a formatted field with the ordinary %s conversion. Descent Computer uses the same speed once for display and once to estimate a landing.
vcc_fixed
int vcc_fixed(char *dest, unsigned capacity, float value, unsigned char places);
Write a signed decimal number with zero to three places after the decimal point. The input magnitude must be less than 65,536. A tie rounds away from zero, so −1.875 at two places becomes −1.88. A value that rounds to zero has no minus sign. The rounded output may reach 65,536 in magnitude. CMOC’s BASIC float stores a binary value. Rounding acts on that stored number, which can differ slightly from the decimal a person typed.
The result is the full character count, excluding the terminating zero byte. Positive capacity reserves one byte for that terminator. A short buffer holds the prefix that fits. To measure first, pass a null destination with zero capacity. An invalid destination, precision or input range returns −1 and empties a supplied buffer if its capacity is positive. A complete field requires a nonnegative result strictly smaller than the capacity.