AtomicPower.java

package libsidplay.components.cart.supported;

import libsidplay.common.Event;
import libsidplay.components.cart.Cartridge;
import libsidplay.components.pla.Bank;
import libsidplay.components.pla.PLA;

import java.io.DataInputStream;
import java.io.EOFException;
import java.io.IOException;
import java.util.Arrays;

import static java.nio.charset.StandardCharsets.US_ASCII;

/**
 * CRT 9: Atomic Power/Nordic Power, 32 KiB ROM and 8 KiB SRAM.
 * Special mode $22 maps ROM at $8000 and SRAM at $A000, with no C64 RAM writes
 * beneath visible cartridge SRAM. IO2 aliases the final ROM/SRAM page.
 * Reference: https://github.com/VICE-Team/svn-mirror/blob/main/vice/src/c64/cart/atomicpower.c
 *
 * @author Antti Lankila
 */
public class AtomicPower extends Cartridge {
    boolean isActive;

    protected boolean exportA000Ram;

    protected boolean exportRam;

    protected final byte[] ram = new byte[0x2000];

    protected int currentRomBank;

    protected final byte[][] romLBanks;

    public AtomicPower(final DataInputStream dis, final PLA pla) throws IOException {
        super(pla);
        romLBanks = new byte[4][0x2000];
        for (byte[] bank : romLBanks) Arrays.fill(bank, (byte) 0xff);
        final byte[] chipHeader = new byte[0x10];
        for (int i = 0; i < 4; i++) {
            int count = readChipHeader(dis, chipHeader);
            if (count == 0) throw new EOFException("Missing Atomic Power CHIP record");
            if (count != chipHeader.length) throw new EOFException("Truncated Atomic Power CHIP header");
            if (!"CHIP".equals(new String(chipHeader, 0, 4, US_ASCII))) {
                throw new IOException("Invalid Atomic Power CHIP signature");
            }
            long length = (long) u16(chipHeader, 4) << 16 | u16(chipHeader, 6);
            int type = u16(chipHeader, 8);
            int bank = u16(chipHeader, 10);
            int size = u16(chipHeader, 14);
            // Banked hardware ignores the CHIP load-address metadata, as VICE does.
            if (length < chipHeader.length + size || (type != 0 && type != 2) || bank > 3 || size != 0x2000) {
                throw new IOException("Invalid Atomic Power CHIP record");
            }
            try {
                dis.readFully(romLBanks[bank]);
            } catch (EOFException e) {
                throw new EOFException("Truncated Atomic Power CHIP payload");
            }
            skipFully(dis, length - chipHeader.length - size, "Truncated Atomic Power CHIP padding");
        }
        int trailing = readChipHeader(dis, chipHeader);
        if (trailing != 0) {
            if (trailing != chipHeader.length) throw new EOFException("Truncated Atomic Power CHIP header");
            throw new IOException("Unexpected extra Atomic Power CHIP record");
        }
    }

    private static int u16(byte[] bytes, int offset) {
        return (bytes[offset] & 255) << 8 | bytes[offset + 1] & 255;
    }

    private void writeControl(byte value) {
        if (!isActive) return;
        int control = value & 255;
        currentRomBank = control >> 3 & 3;
        exportA000Ram = (control & 0xe7) == 0x22;
        exportRam = !exportA000Ram && (control & 0x20) != 0;
        isActive = (control & 4) == 0;
        // Commit state before the synchronous PLA rebuild installs its hooks.
        int mode = exportA000Ram ? 1 : control & 3;
        // Ordinary register accesses disconnect the cartridge during PHI1.
        pla.setGameExrom(true, true, (mode & 1) == 0, (mode & 2) != 0);
        if ((control & 0x40) != 0) setNMI(false);
    }

    protected final Bank io1Bank = new Bank() {
        @Override
        public byte read(int address) {
            byte value = pla.getDisconnectedBusBank().read(address);
            // R/W is not decoded: even a floating read clocks the register.
            writeControl(value);
            return value;
        }

        @Override
        public void write(int address, byte value) {
            writeControl(value);
        }
    };

    private final Bank io2Bank = new Bank() {
        @Override
        public byte read(int address) {
            if (!isActive) return pla.getDisconnectedBusBank().read(address);
            return exportRam || exportA000Ram ? ram[address & 0x1fff]
                    : romLBanks[currentRomBank][address & 0x1fff];
        }

        @Override
        public void write(int address, byte value) {
            if (isActive && (exportRam || exportA000Ram)) ram[address & 0x1fff] = value;
        }
    };

    private final Bank romlBank = new Bank() {
        @Override
        public byte read(int address) {
            return exportRam ? ram[address & 0x1fff] : romLBanks[currentRomBank][address & 0x1fff];
        }

        @Override
        public void write(int address, byte value) {
            if (exportRam) ram[address & 0x1fff] = value;
        }
    };

    private final Bank romhBank = new Bank() {
        @Override
        public byte read(int address) {
            return exportA000Ram ? ram[address & 0x1fff] : romLBanks[currentRomBank][address & 0x1fff];
        }

        @Override
        public void write(int address, byte value) {
            if (exportA000Ram) ram[address & 0x1fff] = value;
        }
    };

    @Override
    public void installBankHooks(final Bank[] cpuReadMap, final Bank[] cpuWriteMap) {
        if (exportRam) {
            for (int i = 8; i < 10; i++) {
                final Bank origBank = cpuWriteMap[i];
                // Ultimax already directs writes solely to cartridge SRAM.
                if (origBank == romlBank) continue;
                cpuWriteMap[i] = new Bank() {
                    @Override
                    public void write(int address, byte value) {
                        origBank.write(address, value);
                        romlBank.write(address, value);
                    }
                };
            }
        }
        if (exportA000Ram) {
            for (int i = 10; i < 12; i++) {
                // HIRAM can hide ROMH: then writes retain ordinary C64 RAM access.
                if (cpuReadMap[i] == romhBank) cpuWriteMap[i] = romhBank;
            }
        }
    }

    @Override
    public Bank getRomh() {
        return romhBank;
    }

    @Override
    public Bank getRoml() {
        return romlBank;
    }

    @Override
    public Bank getIO1() {
        return io1Bank;
    }

    @Override
    public Bank getIO2() {
        return io2Bank;
    }

    @Override
    public boolean isIO2ReadDriven(int address) { return isActive; }

    @Override
    public void reset() {
        pla.getCPU().getEventScheduler().cancel(newCartRomConfig);
        super.reset();
        isActive = true;
        currentRomBank = 0;
        exportRam = exportA000Ram = false;
        // Reset and freeze differ from an IO1 write in their PHI1 configuration.
        pla.setGameExrom(true, false);
    }

    private final Event newCartRomConfig = Event.of("AtomicPower freeze", event -> {
        isActive = true;
        currentRomBank = 0;
        exportRam = true;
        exportA000Ram = false;
        pla.setGameExrom(false, true);
    });

    @Override
    public void doFreeze() {
        var scheduler = pla.getCPU().getEventScheduler();
        if (scheduler.isPending(newCartRomConfig)) return;
        setNMI(true);
        scheduler.schedule(newCartRomConfig, 3, Event.Phase.PHI1);
    }
}