/* util.c
Copyright (C) 2026 Pierre Sarrazin
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see .
*/
#include "util.h"
#include "pmode4game.h" /* cardgame library */
word timer;
byte numVSyncsBeforeScreenFlip = 0;
static interrupt void
irqService(void)
{
asm
{
tst $ff03 ; do nothing if 63.5 us interrupt
bpl @done
; 60 Hz interrupt:
lda $ff02 ; reset PIA0, port B interrupt flag
; Decrement numVSyncsBeforeScreenFlip if not already zero.
tst :numVSyncsBeforeScreenFlip
beq @flipDecDone
dec :numVSyncsBeforeScreenFlip
@flipDecDone
ldd :timer
addd #1
std :timer
@done
}
}
void
setupIRQService(void)
{
asm
{
ldx $FFF8 ; 6809 IRQ vector address
lda #$7E ; JMP instruction
sta ,x
leay irqService ; new routine
sty 1,x
}
}
void
coldBoot(void)
{
disableInterrupts();
memset((void *) VIDRAM, 0x80, 512); // clear 32x16 screen at location used by Basic
// Copy a small routine to low RAM, then jump to the routine, which:
// - goes back to RAM-ROM mode to bring back Basic (CLR >$FFDE);
// - pokes 0 at 113 (CLR >$0071);
// - jumps at 40999 to cold boot Basic (JMP >$A027).
//
memcpy(0, "\x7F\xFF\xDE" "\x7F\x00\x71" "\x7E\xA0\x27", 9);
asm { jmp >0 }
}
__gcccall asm void
setCoCo12ColorSet(byte colorSet)
{
asm
{
lda $FF22
tstb ; B contains colorSet (re: __gcccall)
bne @colorSet1
anda #$F7
bra @store
@colorSet1
ora #$08
@store
sta $FF22
}
}
__gcccall void
setCoCo3ColorSet(byte colorSet)
{
// Palette slots 0..3 for color set 0: black, dark green, dark green, light green.
// Palette slots 0..3 for color set 1: black, blue, orange, white.
//
memcpy((byte *) 0xFFB0, colorSet ? "\x00\x0B\x34\xFF" : "\x00\x02\x02\x12", 4);
}
word
rnd(word lowerLimit, word upperLimit)
{
return rand() % (upperLimit - lowerLimit + 1) + lowerLimit;
}
asm sword
makeEven(sword n)
{
/* Original C code:
if (n >= 0)
return n & 0xFFFE;
return -((-n) & 0xFFFE);
*/
asm
{
ldd 2,s ; load 'n', changes N and Z, resets V
blt @negative
andb #$FE
bra @done
@negative
coma
comb
addd #1
andb #$FE
coma
comb
addd #1
@done
}
}
__gcccall byte
ceilDiv(byte num, byte den)
{
return (num + den - 1) / den;
}
__gcccall asm sword
signExtendYPos(byte screenRow)
{
#if 0 /* Original C code. */
if (screenRow < ROWS_PER_SCREEN)
return (sword) screenRow;
return (sbyte) screenRow; // -64..-1
#else
asm
{
; screenRow is received in B.
cmpb #ROWS_PER_SCREEN
bhs @negative
; B is 0..191; return this value as a word.
clra
bra @returnInX
@negative ; B is -64..-1; sign extend this value to return it as a word.
sex
@returnInX
tfr d,x ; a __gcccall function returns a word in X
}
#endif
}
void
addToDecimalDigit(byte valueToAdd, sbyte digitIndex, byte digitArray[SCORE_WIDTH])
{
byte *digitInArray = digitArray + digitIndex;
for (;;)
{
byte sum = valueToAdd + *digitInArray; // result in 0..18
if (sum < 10) // if no carry
{
*digitInArray = sum;
return;
}
*digitInArray-- = sum - 10;
if (digitIndex == 0)
return; // out of digits in array
--digitIndex;
valueToAdd = 1; // next iteration will add carry to previous digit
}
}
static byte leftMargin, logicalLineLength;
void
setWrappedPrinting(byte _leftMargin, byte _logicalLineLength)
{
leftMargin = _leftMargin;
logicalLineLength = _logicalLineLength;
}
void
printWrapped(const char *text)
{
assert(logicalLineLength > 0); // setWrappedPrinting() must have been called
const byte logicalLineEnd = leftMargin + logicalLineLength;
byte hPos, vPos;
getCursor(&hPos, &vPos); // call to cardgame library
if (hPos < leftMargin)
{
moveCursor(leftMargin, vPos);
hPos = leftMargin;
}
byte separator = !!isspace(text[0]); // 1 means next word must be preceded by a space
BOOL invColorEnabled = FALSE;
for (const char *p = text; ; )
{
// Skip white space, but do newlines.
while (isspace(*p))
{
if (*p == '\n')
{
moveCursor(leftMargin, textPosY + 1);
hPos = leftMargin;
separator = 0;
}
++p;
}
// Find end of current word.
const char *wordStart = p;
while (*p && !isspace(*p))
++p;
// If not enough space for word on current line, newline.
size_t wordLen = p - wordStart;
if (wordLen == 0)
break; // end of 'text'
// If current word would go over limit, newline before.
if (hPos + separator + wordLen > logicalLineEnd)
{
moveCursor(leftMargin, textPosY + 1);
hPos = leftMargin;
separator = 0;
}
else if (separator)
{
putchar(' ');
++hPos;
}
// Print the word at (wordStart, wordLen), with support
// for color inversion. Advance hPos.
//
for (byte j = 0; j < wordLen; ++j)
{
char ch = wordStart[j];
if (ch == INVERTED_COLOR_TOGGLE_CHAR)
{
invColorEnabled = !invColorEnabled;
enableInvertedColorText(invColorEnabled);
}
else
{
putchar(ch);
++hPos;
}
}
if (hPos != logicalLineEnd)
separator = 1;
}
}
void
copyDoubleRowBitmap(byte *screenPtr, const uint32_t bitmapRows[][8], byte numRows)
{
for (byte row = 0; row < numRows; ++row)
{
memcpy(screenPtr, bitmapRows[row], BYTES_PER_ROW); screenPtr += BYTES_PER_ROW;
memcpy(screenPtr, bitmapRows[row], BYTES_PER_ROW); screenPtr += BYTES_PER_ROW;
}
}
void
xorRegion(byte *screenPtr, byte numRows, byte xorArg)
{
size_t numBytes = (size_t) numRows * BYTES_PER_ROW;
for (size_t i = 0; i < numBytes; ++i)
screenPtr[i] ^= xorArg;
}
void
enableSound(void)
{
// Based on Color Basic code at $9A2B.
byte *pia0 = (byte *) 0xFF00;
pia0[1] &= 0xF7;
pia0[3] &= 0xF7;
byte *pia1 = (byte *) 0xFF20;
pia1[3] |= 0x08;
}
void
playSoundSample(const void *sampleArray, const void *sampleArrayEnd, word delayLength)
{
asm
{
ldx :sampleArray
//
// Assuming that the playing rate is 4000 Hz, as an example.
// The following sampling loop must write out a 6-bit sample 4000 times per second.
// The CoCo 6809 CPU, for example, executes 894886 cycles per second.
// Each iteration must last 894886 / 4000 cycles (about 224).
// Each iteration lasts 5+4+6+N*(3+3)+6+3 cycles (see asm code below),
// where N is the number of iterations of the between-samples delay loop.
// We have 6*N + 24 = 224, so N is about 33.
// Total formula: N = (224 - 24) / 6 = (894886 / 4000 - 24) / 6
// = (cpuCyclesPerSecond / playBackFrequencyInHz - 24) / 6
// This number can be computed by Player_getSamplePlayDelayLength().
//
@samplingLoop
lda ,x+ ; (5 cycles)
sta $FF20 ; (4) Write to PIA1
ldd :delayLength ; (6)
@delayLoop
subd #1 ; (3)
bhi @delayLoop ; (3)
cmpx :sampleArrayEnd ; (6)
blo @samplingLoop ; (3)
}
}