// SPDX-FileCopyrightText: 2026 Jeffrey C. Ollie // // SPDX-License-Identifier: MIT //! An Apple-1, the 1976 machine: a 6502, four kilobytes of RAM, the Woz //! Monitor in 256 bytes of PROM, a 6820 PIA between the processor and the //! world, and a terminal that is not video memory at all. //! //! That last is the whole difference from everything after it. An Apple II //! draws its screen out of memory the processor can see; an Apple-1's display //! section "contains its own memory, leaving all of RAM for user programs" //! (Apple Computer Company, 1976, p. 1) — a kilobyte of dynamic shift //! registers, seven bits wide, that the processor cannot read and can only //! add one character to at a time, through the PIA, the way it would drive a //! Teletype. So there is no text page here to draw from: the terminal's forty //! by twenty-four characters live in this model, and the screen-drawing code //! is shown them as though they were a text page, since a terminal drawing //! them cannot tell the difference and should not have to. //! //! What the manual documents, and this models, in its own words (Apple //! Computer Company, 1976, p. 6, "Hardware Notes"): //! //! - `KBD Data D010`: "High order bit equals 1." //! - `KBD Control Reg. D011`: "High order bit indicates 'key ready'. Reading //! key clears flag. Rising edge of KBD sets flag." //! - `DSP Data D012`: "Lower seven bits are data output, high order bit is //! 'display ready' input" — and the Monitor's own `ECHO` says which way //! round: `BIT DSP / BMI ECHO / STA DSP`, waiting while bit 7 is *set*, so //! set is busy and clear is ready. //! - `DSP Control Reg. D013`. //! - And how those four addresses are decoded, from the "KBD/DSP Interface" //! drawing on the next page (Apple Computer Company, 1976, p. 7): `RS0` //! is A0, `RS1` is A1, `CS0` is A4, `CS1` is tied high and `CS2` is //! "Decode A15, A14, A13, A12 to $DXXX". Nothing looks at A2, A3 or A5 to //! A11, so the PIA answers at every address in the `D` block with A4 set, //! and its register is the low two bits. That is not a curiosity: Apple's //! BASIC for this machine drives the display through `$d0f2`, and a model //! that decoded the four addresses exactly ran BASIC without a prompt. //! The BASIC binary that circulates for replicas has exactly two bytes //! changed from the tape, and they are those two operands, patched to //! `$d012` for boards that decode all sixteen address lines — which is //! the same fact seen from the other side. //! - "Four out of every 65 clock cycles is dedicated to memory refresh ... //! the processor is held in Ø1", which is why the specification sheet //! gives a 1.023 MHz clock and an "Effective Cycle Frequency (Including //! Refresh Waits)" of 0.960 MHz: 61 of every 65 cycles are the //! processor's. //! - "The board has sockets for up to 8K bytes of the 16 pin, 4K type, RAM", //! with 4K supplied. The second bank is the one at `$e000`, which is where //! Apple's BASIC for this machine lives. //! //! The PIA is modeled as far as the machine wires it and the Monitor drives //! it: each side's control register with bit 2 choosing between the data //! register and the data direction register, the keyboard flag in bit 7 of //! control register A, and the display's handshake in bit 7 of port B. That //! last matters more than it looks: the Monitor's first act at reset is `STY //! DSP` with `#$7F`, which is a write to the *direction* register because the //! control register is still clear from reset — a model that took it for a //! character would print a `?` before the prompt. //! //! Two things here are this model's own reading rather than the manual's. //! The display takes a character once a frame, at the next vertical retrace //! after it was written, which is what a shift-register store with one //! insertion point a frame allows and gives the sixty characters a second an //! Apple-1 is known for; the manual gives the store and the frame rate but not //! the sentence. And the display recognizes carriage return and nothing else //! among the control codes, which is what the Monitor and BASIC send and what //! a store of glyphs can do with them; the other thirty-one are dropped here. const std = @import("std"); const bus_log = @import("bus.zig"); const Options = bus_log.Options; const cassette = @import("../cassette.zig"); const font = @import("../font.zig"); const screen = @import("../screen.zig"); const speaker = @import("../speaker.zig"); /// One bank of RAM: the 4K the board took per row of chips. pub const bank_size = 0x1000; /// Where the second bank sits: the address Apple's BASIC was written for. pub const high_bank = 0xe000; /// The Woz Monitor's 256 bytes, at the top of memory where the vectors are. pub const rom_size = 0x100; pub const rom_base = 0x10000 - rom_size; /// The Cassette Interface: the `C` block, of which the card decodes the first /// 512 bytes. The PROM's 256 bytes appear in both halves; the lower half is /// also the tape, whose output flips on every access to it and whose input is /// read through the PROM at `$c081`. pub const aci_base: u16 = 0xc000; pub const aci_rom_size = 0x100; pub const aci_flip: u16 = aci_base; pub const aci_tape_in: u16 = aci_base + 0x81; /// The PIA's four addresses, as the manual names them. The chip itself sees /// only the block, A4 and the low two bits, so each is one of many. pub const kbd = 0xd010; pub const kbdcr = 0xd011; pub const dsp = 0xd012; pub const dspcr = 0xd013; /// The terminal: "40 characters/line, 24 lines; with automatic scrolling" /// (Apple Computer Company, 1976, specifications). pub const terminal_columns: u16 = 40; pub const terminal_rows: u16 = 24; /// The clock: 1.023 MHz, from the specification sheet. The line and frame /// are the Apple II's 65 cycles and 262 lines, which the sheet's blank "Line /// Rate" and "Frame Rate" entries do not contradict and which the same /// designer used again a year later; the display's timing is derived from /// them. pub const cycles_per_second: u64 = 1_023_000; pub const cycles_per_line: u64 = 65; pub const lines_per_frame: u64 = 262; pub const cycles_per_frame: u64 = cycles_per_line * lines_per_frame; /// "Four out of every 65 clock cycles is dedicated to memory refresh." pub const refresh_cycles_per_line: u64 = 4; /// The 6820, as far as this machine wires it. /// /// Each side has a control register whose bit 2 selects what the other /// address reaches — the data register when set, the data direction register /// when clear — and whose bit 7 is the interrupt flag its C1 line sets. The /// keyboard's strobe is CA1, so bit 7 of control register A is "key ready"; /// the display's acknowledgement is what port B's bit 7 reads. Bits 6 and 7 /// of a control register are read-only flags, which is why a write keeps six /// bits. const Pia = struct { cra: u8 = 0, crb: u8 = 0, ddra: u8 = 0, ddrb: u8 = 0, /// What was last written to port B: the character on its way to the /// display, which reads back on the output lines. prb: u8 = 0, fn dataA(self: *const Pia) bool { return self.cra & 0x04 != 0; } fn dataB(self: *const Pia) bool { return self.crb & 0x04 != 0; } }; pub fn AppleI(comptime options: Options) fn (type) type { return struct { fn model(comptime CPU: type) type { return struct { const Self = @This(); pub const Access = bus_log.Access; bus: bus_log.Log(options.bus_log) = .{}, /// `$0000` to `$0fff`, the 4K supplied. ram: [bank_size]u8 = undefined, /// `$e000` to `$efff`, the other 4K the board had sockets for. high: [bank_size]u8 = undefined, high_fitted: bool = false, /// `$ff00` to `$ffff`. rom: [rom_size]u8 = undefined, pia: Pia = .{}, /// The last key pressed, seven bits, and whether the program /// has taken it yet — which is the PIA's CA1 flag. keyboard: u8 = 0, strobe: bool = false, /// How many times the key-ready flag has been read and found /// clear since a key was last pressed. The front end uses it /// to tell that the machine is sitting in a read loop before /// handing over the next typed character, as it does for the /// Apple II. empty_polls: u16 = 0, /// The terminal's store: what each of the 960 cells shows, /// as the seven bits the display was handed. cells: [terminal_rows * terminal_columns]u8 = @splat(' '), /// Where the next character goes. cursor: u16 = 0, /// A character written to the display and not yet taken by /// it, and the frame it was written in. The display takes it /// at the next retrace, and until then port B reads busy. pending: ?u8 = null, pending_frame: u64 = 0, /// How many lines' refresh stalls have been charged to the /// processor so far. refreshed_lines: u64 = 0, /// The Cassette Interface, if one is fitted: its PROM. aci_fitted: bool = false, aci_rom: [aci_rom_size]u8 = @splat(0), /// The card's output flip-flop, and when it changed: the /// record of the flips is the whole of what goes onto a tape, /// as it is for the Apple II. cassette_out: bool = false, cassette_log: speaker.Log(options.cassette_log) = .{}, /// What the comparator sees, for a caller setting the input /// directly rather than playing a tape. cassette_in: bool = false, cassette_tape: ?cassette.Tape = null, /// The CPU this belongs to, recovered from the field it is /// embedded in. inline fn getCPU(self: *Self) *CPU { return @alignCast(@fieldParentPtr("memory", self)); } pub fn init(self: *Self, _: ?usize) void { self.* = .{ .ram = @splat(0), .high = @splat(0), .rom = @splat(0), }; } /// The RESET button. It reaches the processor and the PIA, /// whose registers all clear — which is what leaves the data /// direction registers selected for the Monitor to set up. /// The display is not reset: it has its own button. pub fn reset(self: *Self) void { self.pia = .{}; self.strobe = false; } /// The CLEAR SCREEN button, which is the other switch on the /// keyboard connector and is wired to the display section /// rather than to the processor. pub fn clearScreen(self: *Self) void { self.cells = @splat(' '); self.cursor = 0; } /// Fits the board's RAM: 4K, which is what was supplied, or /// 8K, which puts the second row of chips at `$e000`. pub fn fitMemory(self: *Self, bytes: usize) error{NotAConfiguration}!void { self.high_fitted = switch (bytes) { bank_size => false, 2 * bank_size => true, else => return error.NotAConfiguration, }; } /// Fits the Cassette Interface, which is its PROM: "two PROMS /// on the ACI board", 82S129s of 256 by four bits, side by /// side as one image of 256 bytes. pub fn fitCassetteInterface(self: *Self, image: []const u8) error{WrongSize}!void { if (image.len != aci_rom_size) return error.WrongSize; @memcpy(&self.aci_rom, image); self.aci_fitted = true; } /// Lays the ROM image down so that its last byte falls at /// `$ffff`. The socket is 256 bytes; a larger image keeps its /// tail, which is what "at end" means. pub fn loadROMAtEnd(self: *Self, image: []const u8) !void { if (image.len == 0) return error.Empty; const take = @min(image.len, rom_size); @memset(&self.rom, 0); @memcpy(self.rom[rom_size - take ..], image[image.len - take ..]); } pub fn loadProgram(self: *Self, location: u16, program: []const u8) !void { for (program, 0..) |byte, i| { const at = @as(usize, location) + i; if (at > 0xffff) return error.Overflow; self.poke(@intCast(at), byte); } } /// Which physical byte an address is, or null where there is /// a device or nothing. fn target(self: *Self, address: u16) ?*u8 { return switch (address) { 0x0000...bank_size - 1 => &self.ram[address], high_bank...high_bank + bank_size - 1 => if (self.high_fitted) &self.high[address - high_bank] else null, rom_base...0xffff => &self.rom[address - rom_base], else => null, }; } fn isRom(address: u16) bool { return address >= rom_base; } /// "CS0" is A4 and "CS2" is the `D` block: the PIA, wherever /// both hold. fn isPia(address: u16) bool { return address & 0xf010 == 0xd010; } /// Which of the PIA's four registers an address reaches: RS0 /// and RS1 are A0 and A1. fn piaRegister(address: u16) u16 { return kbd | (address & 0x3); } /// Whether the Cassette Interface answers this address: the /// first 512 bytes of the `C` block, when the card is there. fn isCard(self: *const Self, address: u16) bool { return self.aci_fitted and address >= aci_base and address < aci_base + 2 * aci_rom_size; } /// The card as the processor sees it. Every access with A8 /// clear clocks the output flip-flop, whether the processor is /// reading or writing: the decode has no R/W in it. fn touchCard(self: *Self, address: u16) void { if (address & 0x100 != 0) return; self.cassette_out = !self.cassette_out; self.cassette_log.record(self.getCPU().clock.cycles); } /// What a read of the card returns: the PROM, from both halves, /// with A0 to the PROM forced low when the low half's upper /// page is read while the comparator is high. That is the /// tape input, and it is the only way the card has of saying /// anything. fn readCard(self: *Self, address: u16) u8 { self.touchCard(address); var offset: u8 = @truncate(address); if (address & 0x180 == 0x80 and self.cassetteInput()) offset &= 0xfe; return self.aci_rom[offset]; } /// What the comparator's output is: the tape being played, or /// the level set by hand when there is none. fn cassetteInput(self: *Self) bool { const tape = self.cassette_tape orelse return self.cassette_in; return tape.levelAt(self.getCPU().clock.cycles -| tape.started, cycles_per_second); } /// Puts the tape input one way or the other, for a caller /// making its own signal rather than playing a tape. pub fn setCassetteInput(self: *Self, level: bool) void { self.cassette_in = level; } /// Starts playing a tape into the card, from this cycle. Where /// the tape has got to is worked out from the machine's clock, /// refresh stalls and all, so it plays at the speed the program /// reading it expects however fast the machine is run. pub fn playTape(self: *Self, levels: []const u8, sample_rate: u32) void { self.cassette_tape = .{ .levels = levels, .sample_rate = sample_rate, .started = self.getCPU().clock.cycles, }; } /// Takes the tape off. pub fn stopTape(self: *Self) void { self.cassette_tape = null; } /// Reads a byte without the processor being involved: memory /// as it is, and nothing for a register, since peeking must /// not clear a flag. pub fn peek(self: *Self, address: u16) u8 { if (self.isCard(address)) return self.aci_rom[@as(u8, @truncate(address))]; const t = self.target(address) orelse return 0; return t.*; } /// Writes a byte with the processor not involved. ROM keeps /// what it has, as it does for the processor. pub fn poke(self: *Self, address: u16, value: u8) void { if (isRom(address)) return; const t = self.target(address) orelse return; t.* = value; } /// The processor's cycle, and what the board does around it: /// the refresh stalls it is held for, and the display taking /// a character at the retrace. fn spend(self: *Self) void { const cpu = self.getCPU(); cpu.clock.sleep(1); // "Four out of every 65 clock cycles is dedicated to // memory refresh ... the processor is held in Ø1." Charged // a line at a time as the clock crosses into each new // line, which puts the stall in the right place to within // a line and the right number of cycles exactly. const line = cpu.clock.cycles / cycles_per_line; while (self.refreshed_lines < line) : (self.refreshed_lines += 1) { cpu.clock.sleep(refresh_cycles_per_line); } self.updateDisplay(); } /// Lets the display take the character waiting for it, if /// the retrace it was waiting for has come. fn updateDisplay(self: *Self) void { const pending = self.pending orelse return; const frame = self.getCPU().clock.cycles / cycles_per_frame; if (frame <= self.pending_frame) return; self.pending = null; self.show(pending); } /// Puts one character on the terminal, the way its hardware /// does: a carriage return starts the next line, anything /// printable goes at the cursor, and past the last line the /// screen scrolls. fn show(self: *Self, character: u8) void { const c = character & 0x7f; if (c == 0x0d) { self.cursor = (self.cursor / terminal_columns + 1) * terminal_columns; } else if (c >= 0x20) { self.cells[self.cursor] = c; self.cursor += 1; } else { // See the header: the other control codes are dropped. return; } if (self.cursor >= terminal_rows * terminal_columns) { std.mem.copyForwards(u8, self.cells[0 .. (terminal_rows - 1) * terminal_columns], self.cells[terminal_columns..]); @memset(self.cells[(terminal_rows - 1) * terminal_columns ..], ' '); self.cursor = (terminal_rows - 1) * terminal_columns; } } /// What the processor sees at one of the PIA's addresses. fn readPia(self: *Self, address: u16) u8 { switch (piaRegister(address)) { kbd => { if (!self.pia.dataA()) return self.pia.ddra; // "Reading key clears flag." self.strobe = false; // "High order bit equals 1." return self.keyboard | 0x80; }, kbdcr => { if (!self.strobe) self.empty_polls +|= 1; return self.pia.cra | @as(u8, if (self.strobe) 0x80 else 0); }, dsp => { if (!self.pia.dataB()) return self.pia.ddrb; // The outputs read back, and bit 7 is the // display's acknowledgement: set until it has // taken the character. return (self.pia.prb & 0x7f) | @as(u8, if (self.pending != null) 0x80 else 0); }, dspcr => return self.pia.crb, else => unreachable, } } fn writePia(self: *Self, address: u16, value: u8) void { switch (piaRegister(address)) { kbd => if (self.pia.dataA()) { // Port A is all inputs on this board; an output // written to it goes nowhere. } else { self.pia.ddra = value; }, kbdcr => self.pia.cra = value & 0x3f, dsp => if (self.pia.dataB()) { self.pia.prb = value; // "Output character. Sets DA." The display will // take it at the next retrace. self.pending = value & 0x7f; self.pending_frame = self.getCPU().clock.cycles / cycles_per_frame; } else { self.pia.ddrb = value; }, dspcr => self.pia.crb = value & 0x3f, else => unreachable, } } /// Reads memory, spending the cycle. An address with nothing /// behind it is the floating bus, which is zero here as /// everywhere this project has nothing to say. pub fn read(self: *Self, comptime T: type, address: u16) T { const info = @typeInfo(T); if (info != .int) @compileError("must be an integer"); if (info.int.signedness != .unsigned) @compileError("must be unsigned"); switch (info.int.bits) { 8 => { self.spend(); const value = if (isPia(address)) self.readPia(address) else if (self.isCard(address)) self.readCard(address) else if (self.target(address)) |t| t.* else 0; self.bus.record(address, value, .read); return value; }, 16 => { const low = self.read(u8, address); const high_ = self.read(u8, address +% 1); return @as(u16, high_) << 8 | low; }, else => @compileError("must be a u8 or a u16"), } } /// Writes memory, spending the cycle whether or not anything /// is listening. pub fn write(self: *Self, comptime T: type, address: u16, value: T) void { const info = @typeInfo(T); if (info != .int) @compileError("must be an integer"); if (info.int.signedness != .unsigned) @compileError("must be unsigned"); switch (info.int.bits) { 8 => { self.spend(); self.bus.record(address, value, .write); if (isPia(address)) { self.writePia(address, value); } else if (self.isCard(address)) { // The PROM keeps what it has; the flip-flop // does not know a write from a read. self.touchCard(address); } else if (!isRom(address)) { if (self.target(address)) |t| t.* = value; } }, 16 => { self.write(u8, address, @truncate(value)); self.write(u8, address +% 1, @truncate(value >> 8)); }, else => @compileError("must be a u8 or a u16"), } } // ---------------------------------------------------------- // The keyboard. /// A key pressed on the ASCII keyboard: seven bits and a /// strobe. The keyboard had no lowercase, so the host's is /// folded up as an alpha lock would have. pub fn pressKey(self: *Self, character: u8) void { const pressed = if (character >= 'a' and character <= 'z') character - 0x20 else character; self.keyboard = pressed & 0x7f; self.strobe = true; self.empty_polls = 0; } // ---------------------------------------------------------- // The terminal, shown to whoever draws screens as if it were // an Apple II text page, because that is the shape every // drawer here knows and a terminal cannot tell the difference. pub fn mode(self: *const Self) screen.Mode { _ = self; return .text; } pub fn columns(self: *const Self) u16 { _ = self; return terminal_columns; } /// The drawers ask this by the Apple II's name. pub fn displayPage(self: *const Self) u16 { _ = self; return 0x0400; } pub fn hiresPage(self: *const Self) u16 { _ = self; return 0x2000; } /// The character at a text-page address, worked back to the /// cell it names. The Apple II's page interleaves three terminal_rows /// into each 128 bytes; undoing that gives row and column, /// and the eight bytes past each set of three terminal_rows are the /// screen holes, which show as blanks. pub fn videoByte(self: *const Self, auxiliary: bool, address: u16) u8 { _ = auxiliary; const offset = address -% 0x0400; const within = offset & 0x7f; if (within >= 3 * terminal_columns) return 0xa0; const row: u16 = (offset >> 7) + 8 * (within / terminal_columns); const column: u16 = within % terminal_columns; if (row >= terminal_rows) return 0xa0; const index = row * terminal_columns + column; // The cursor is the display's own: an `@`, flashing, which // in the Apple II's text codes is exactly `$40`. if (index == self.cursor) return 0x40; // The store holds seven bits and the character generator // is the same 2513 an Apple II has, addressed by six of // them: `@` to `_` and space to `?`, which in the Apple // II's codes are the normal set at `$80`. return 0x80 | (self.cells[index] & 0x3f); } /// The same 2513 as an Apple II Plus, one set, no alternate. pub fn characterSet(self: *const Self) font.Set { _ = self; return .apple2; } pub fn alternateCharacters(self: *const Self) bool { _ = self; return false; } pub fn flashing(self: *Self) bool { return font.flashing(self.getCPU().clock.cycles, cycles_per_second); } /// Composite video with no color in it at all: there is no /// color burst on an Apple-1's output and nothing to make /// one. pub fn colourBurst(self: *const Self) bool { _ = self; return false; } pub fn delaysHires(self: *const Self) bool { _ = self; return false; } /// The terminal's text, row by row. See screen.write. pub fn writeText(self: *Self, writer: *std.Io.Writer) std.Io.Writer.Error!void { return screen.write(self, writer); } /// One row of the terminal as characters, for tests. pub fn rowText(self: *const Self, row: u16) []const u8 { return self.cells[row * terminal_columns ..][0..terminal_columns]; } }; } }.model; } const testing = std.testing; const TestCPU = @import("../cpu8.zig").CPU(@import("../clock.zig").FakeClock, AppleI(.{})); /// The Woz Monitor's reset sequence, as far as the PIA goes: from the /// listing (Apple Computer Company, 1976, p. 3). fn setUpPia(cpu: *TestCPU) void { cpu.memory.write(u8, dsp, 0x7f); // STY DSP: the direction register, CRB being clear cpu.memory.write(u8, kbdcr, 0xa7); // STA KBDCR cpu.memory.write(u8, dspcr, 0xa7); // STA DSPCR } test "the Monitor's first write to the display is to its direction register, and prints nothing" { // Reset leaves both control registers clear, so `STY DSP` with #$7F is // the data direction register and not a character. A model that showed // it would put a `?` before the prompt. var cpu: TestCPU = undefined; try cpu.init(null, null); setUpPia(&cpu); try testing.expectEqual(@as(?u8, null), cpu.memory.pending); try testing.expectEqual(@as(u8, 0x7f), cpu.memory.pia.ddrb); // And afterwards the same address is the data register. cpu.memory.write(u8, dsp, 0xdc); // a backslash, as the Monitor sends it try testing.expectEqual(@as(?u8, 0x5c), cpu.memory.pending); } test "a character is taken at the next retrace, and the display reads busy until then" { var cpu: TestCPU = undefined; try cpu.init(null, null); setUpPia(&cpu); cpu.memory.write(u8, dsp, 0xc1); // 'A' try testing.expect(cpu.memory.read(u8, dsp) & 0x80 != 0); try testing.expectEqual(@as(u8, ' '), cpu.memory.rowText(0)[0]); // A frame later it is on the screen and the display is ready again. cpu.clock.cycles += cycles_per_frame; try testing.expect(cpu.memory.read(u8, dsp) & 0x80 == 0); try testing.expectEqual(@as(u8, 'A'), cpu.memory.rowText(0)[0]); try testing.expectEqual(@as(u16, 1), cpu.memory.cursor); } test "carriage return starts the next line, and the last line scrolls" { var cpu: TestCPU = undefined; try cpu.init(null, null); setUpPia(&cpu); for ("HI\rTHERE") |c| { cpu.memory.write(u8, dsp, c | 0x80); cpu.clock.cycles += cycles_per_frame; _ = cpu.memory.read(u8, dsp); } try testing.expectEqualStrings("HI", cpu.memory.rowText(0)[0..2]); try testing.expectEqualStrings("THERE", cpu.memory.rowText(1)[0..5]); // Twenty-three more returns and the top line goes off the screen. for (0..23) |_| { cpu.memory.write(u8, dsp, 0x8d); cpu.clock.cycles += cycles_per_frame; _ = cpu.memory.read(u8, dsp); } try testing.expectEqualStrings("THERE", cpu.memory.rowText(0)[0..5]); try testing.expectEqual((terminal_rows - 1) * terminal_columns, cpu.memory.cursor); } test "the keyboard flag is set by a key and cleared by reading it" { // "High order bit indicates 'key ready'. Reading key clears flag." var cpu: TestCPU = undefined; try cpu.init(null, null); setUpPia(&cpu); try testing.expect(cpu.memory.read(u8, kbdcr) & 0x80 == 0); cpu.memory.pressKey('a'); try testing.expect(cpu.memory.read(u8, kbdcr) & 0x80 != 0); // Uppercase, and "high order bit equals 1". try testing.expectEqual(@as(u8, 'A' | 0x80), cpu.memory.read(u8, kbd)); try testing.expect(cpu.memory.read(u8, kbdcr) & 0x80 == 0); } test "the PIA answers wherever A4 is set in the D block, which is how BASIC reaches the display at $d0f2" { // "CS0" is A4, "CS2" is the block decode, and nothing looks at the other // address lines (Apple Computer Company, 1976, p. 7). var cpu: TestCPU = undefined; try cpu.init(null, null); setUpPia(&cpu); cpu.memory.write(u8, 0xd0f2, 0xbe); // BASIC's prompt, the way BASIC sends it try testing.expectEqual(@as(?u8, '>'), cpu.memory.pending); try testing.expect(cpu.memory.read(u8, 0xdff2) & 0x80 != 0); cpu.memory.pressKey('a'); try testing.expect(cpu.memory.read(u8, 0xd7d1) & 0x80 != 0); try testing.expectEqual(@as(u8, 'A' | 0x80), cpu.memory.read(u8, 0xd090)); // A4 clear is not the PIA, whatever else is set. try testing.expectEqual(@as(u8, 0), cpu.memory.read(u8, 0xd0e2)); } test "the processor is held for four cycles in every sixty-five" { // "Effective Cycle Frequency (Including Refresh Waits) 0.960 MHz" against // a 1.023 MHz clock: 61 of 65. var cpu: TestCPU = undefined; try cpu.init(null, null); const before = cpu.clock.cycles; // The stall is charged as the clock crosses into each line, so sixty-one // accesses of the processor's own take sixty-five cycles of the board's: // a hundred full lines, and the sixty-one of the line still under way. for (0..61 * 101) |_| _ = cpu.memory.read(u8, 0x0000); const total = cpu.clock.cycles - before; try testing.expectEqual(@as(u64, 100 * 65 + 61), total); } test "four kilobytes at the bottom, the Monitor at the top, and nothing between until the second bank is fitted" { var cpu: TestCPU = undefined; try cpu.init(null, null); var rom: [rom_size]u8 = @splat(0xea); rom[0xfc] = 0x00; rom[0xfd] = 0xff; try cpu.memory.loadROMAtEnd(&rom); cpu.memory.write(u8, 0x0fff, 0x11); try testing.expectEqual(@as(u8, 0x11), cpu.memory.read(u8, 0x0fff)); cpu.memory.write(u8, 0xe000, 0x22); try testing.expectEqual(@as(u8, 0x00), cpu.memory.read(u8, 0xe000)); try cpu.memory.fitMemory(2 * bank_size); cpu.memory.write(u8, 0xe000, 0x22); try testing.expectEqual(@as(u8, 0x22), cpu.memory.read(u8, 0xe000)); try testing.expectEqual(@as(u8, 0xea), cpu.memory.read(u8, 0xff00)); cpu.memory.write(u8, 0xff00, 0x00); try testing.expectEqual(@as(u8, 0xea), cpu.memory.read(u8, 0xff00)); try testing.expectEqual(@as(u16, 0xff00), cpu.memory.read(u16, 0xfffc)); try testing.expectError(error.NotAConfiguration, cpu.memory.fitMemory(3 * bank_size)); } test "the terminal is shown as a text page: interleaved terminal_rows, a flashing @ for the cursor" { var cpu: TestCPU = undefined; try cpu.init(null, null); setUpPia(&cpu); for ("A\rB") |c| { cpu.memory.write(u8, dsp, c | 0x80); cpu.clock.cycles += cycles_per_frame; _ = cpu.memory.read(u8, dsp); } // Row 0 starts at $400, row 1 at $480, and the cursor sits after the B. try testing.expectEqual(@as(u8, 0x81), cpu.memory.videoByte(false, 0x0400)); try testing.expectEqual(@as(u8, 0x82), cpu.memory.videoByte(false, 0x0480)); try testing.expectEqual(@as(u8, 0x40), cpu.memory.videoByte(false, 0x0481)); try testing.expectEqual(@as(u8, 0xa0), cpu.memory.videoByte(false, 0x0482)); // The screen holes are blank. try testing.expectEqual(@as(u8, 0xa0), cpu.memory.videoByte(false, 0x0478)); // A color monitor has nothing to lock to. try testing.expect(!cpu.memory.colourBurst()); } /// A Cassette Interface whose PROM holds its own offsets, so what a read /// returns says which address reached the chip. fn fitTestCard(memory: anytype) void { var image: [aci_rom_size]u8 = undefined; for (&image, 0..) |*byte, i| byte.* = @intCast(i); memory.fitCassetteInterface(&image) catch unreachable; } test "the Cassette Interface's PROM answers in both halves of its block, and only the lower half touches the tape" { var cpu: TestCPU = undefined; try cpu.init(null, null); // Without the card the block is empty. try testing.expectEqual(@as(u8, 0), cpu.memory.read(u8, 0xc100)); fitTestCard(&cpu.memory); // The program's copy, at $c100, leaves the tape alone. try testing.expectEqual(@as(u8, 0x23), cpu.memory.read(u8, 0xc123)); try testing.expect(!cpu.memory.cassette_out); // The same byte at $c023 clocks the flip-flop. try testing.expectEqual(@as(u8, 0x23), cpu.memory.read(u8, 0xc023)); try testing.expect(cpu.memory.cassette_out); // So does a write: the decode has no R/W in it. cpu.memory.write(u8, aci_flip, 0); try testing.expect(!cpu.memory.cassette_out); // The card decodes 512 bytes, and the rest of the block is nothing. try testing.expectEqual(@as(u8, 0), cpu.memory.read(u8, 0xc200)); // Peeking is not the processor: it neither flips nor reads the tape. try testing.expectEqual(@as(u8, 0x81), cpu.memory.peek(aci_tape_in)); try testing.expect(!cpu.memory.cassette_out); // And the PROM has a wrong size. try testing.expectError(error.WrongSize, cpu.memory.fitCassetteInterface(&[_]u8{ 1, 2, 3 })); } test "the tape input is read through the PROM: the even byte while the signal is high, the odd while it is low" { var cpu: TestCPU = undefined; try cpu.init(null, null); fitTestCard(&cpu.memory); cpu.memory.setCassetteInput(true); try testing.expectEqual(@as(u8, 0x80), cpu.memory.read(u8, aci_tape_in)); cpu.memory.setCassetteInput(false); try testing.expectEqual(@as(u8, 0x81), cpu.memory.read(u8, aci_tape_in)); // A7 clear is not the input: $c001 reads $01 whatever the signal. cpu.memory.setCassetteInput(true); try testing.expectEqual(@as(u8, 0x01), cpu.memory.read(u8, 0xc001)); // Nor is the upper half, where A8 keeps the I/O select off. try testing.expectEqual(@as(u8, 0x81), cpu.memory.read(u8, 0xc181)); // Reading the input is an access to the lower half, so it flips the // output as well; the program does not mind and neither did the card. try testing.expect(cpu.memory.cassette_out); } test "the flips are logged with their cycle, which is what a tape is made of" { const LoggedCPU = @import("../cpu8.zig").CPU(@import("../clock.zig").FakeClock, AppleI(.{ .cassette_log = true })); var cpu: LoggedCPU = undefined; try cpu.init(null, null); fitTestCard(&cpu.memory); _ = cpu.memory.read(u8, aci_flip); _ = cpu.memory.read(u8, 0x0000); _ = cpu.memory.read(u8, aci_flip); const flips = cpu.memory.cassette_log.taken(); try testing.expectEqual(@as(usize, 2), flips.len); try testing.expect(flips[1] > flips[0]); } test "a tape plays into the card at the machine's own pace" { var cpu: TestCPU = undefined; try cpu.init(null, null); fitTestCard(&cpu.memory); // Two samples a second: high for half a second, then low. const levels = [_]u8{ 1, 0 }; cpu.memory.playTape(&levels, 2); try testing.expectEqual(@as(u8, 0x80), cpu.memory.read(u8, aci_tape_in)); cpu.clock.cycles += cycles_per_second / 2; try testing.expectEqual(@as(u8, 0x81), cpu.memory.read(u8, aci_tape_in)); // Run out, the tape reads low whatever was set by hand. cpu.clock.cycles += cycles_per_second; cpu.memory.setCassetteInput(true); try testing.expectEqual(@as(u8, 0x81), cpu.memory.read(u8, aci_tape_in)); // Taking it off leaves the level set by hand. cpu.memory.stopTape(); try testing.expectEqual(@as(u8, 0x80), cpu.memory.read(u8, aci_tape_in)); }