diff --git a/README.md b/README.md index 3a602ec..e311a02 100644 --- a/README.md +++ b/README.md @@ -1575,9 +1575,9 @@ to the other bit positions has no effect". Clearing them happens at a "writing a 1 into these positions or writing into the other bit positions has no effect". Everything else in this machine is cleared by touching an address; this one is cleared by writing a zero into a bit at a second address. The -one-second interrupt fires from the same frame counter; the scan-line one has -its enable and its status but no source yet, because the source is a bit in the -Super Hi-Res scanline control bytes and there is no Super Hi-Res. +one-second interrupt fires from the same frame counter; the scan-line one is +the odd one out and gets a section of its own below, because its source is not +a register at all. Two things the tests caught that running the ROM would not have. **The line is a wire, not an event**: it follows the enables and the flags continuously, so @@ -1976,6 +1976,68 @@ comes out in the order the manual names them, from a renderer with no table of colours in it anywhere. And a screen of `HCOLOR=3` diagonals comes out as the green-and-violet moiré that Apple II line drawing has always looked like. +### An interrupt whose source is a picture + +Super Hi-Res is the Video Graphics Controller's display and it is nothing like +the one the machine inherited. There is no dot stream and no colour subcarrier: +there are pixels, with colour numbers in them, and the numbers mean whatever a +palette in memory says they mean. Which is why it is `src/superhires.zig` and +not more of `src/video.zig` — different chip, different grid, different idea of +what a colour is. + +Thirty-two kilobytes of bank `$e1` hold all of it: two hundred lines of a +hundred and sixty bytes at `$2000`, then two hundred **scan-line control +bytes** at `$9d00`, then sixteen palettes of sixteen twelve-bit colours at +`$9e00`. The control byte is the interesting one, and it is why this is drawn a +line at a time. Every line decides for itself which palette it uses, whether it +is 320 pixels or 640, whether Color Fill is on — and whether the beam reaching +it raises an interrupt. + +That last one is worth stopping on. Every other interrupt in this machine comes +from a register: something is enabled, something happens, a bit goes up. This +one comes from **a byte in the middle of the picture**. A program changes what +interrupts and when by *drawing*, and the model has to walk the control bytes +as the beam crosses them — counted rather than caught, the same way the frame +counter is, and clamped to one frame back because walking further is walking +over lines already looked at. + +#### Two modes that are not what they look like + +**Color Fill** turns colour `$0` from a colour into "the same as the pixel to +my left". A run of solid colour costs one byte instead of six, which is what it +is for; the price is fifteen colours a line rather than sixteen, and the manual +notes that the first pixel of a line must not be `$0` because there is nothing +to its left and "an undetermined color results". + +**640 mode** is four pixels to a byte and two bits each, which sounds like four +colours and is not. The palette is divided into four groups of four, and which +group a pixel uses depends on *where in the byte it is*: the first pixel takes +the third group, the second the fourth, the third the first, the fourth the +second. So all sixteen colours are still available along a line even though any +one pixel can only be four of them. The rotation looks arbitrary until you +notice what it is for — two adjacent 640 pixels are half a dot each, and half a +dot is what makes colour on a composite monitor, so the groups are arranged to +put the pairs that dither well next to each other. + +#### What checked it + +No real Super Hi-Res software has been run against this, because there is none +here to run: the 800K disk this project can boot is ProDOS 8 and forty columns +of text. What there is instead is the format tested against the manual clause +by clause, and a picture written *through the machine* — into bank `$e1` of the +real model, with the real bank latch and the real memory map — that uses all +four of the things above at once: a rainbow in 320, the same colours as fill +runs, 640 showing its four groups side by side, and fifty bands each with a +palette of its own. All four come out. + +Writing that test caught the seam again, in the place it always catches people. +Turning Super Hi-Res on means writing bit 7 of `$c029` — and writing *just* bit +7 clears bit 0, which is the bank latch, and without the latch a write to bank +`$e1` goes through the old soft switches and lands in the main half of the Mega +II instead. Nothing reaches the buffer and the screen stays black. Real +software sets both, and the machine's own firmware comes up with the latch +already set, which is why the picture worked before the test did. + ### What is left Every 8-bit processor is complete and, as far as the corpus can tell, exact. The @@ -2229,6 +2291,8 @@ machine around them is not. | `src/screen.zig` | reading the text screen: the modes and the character set | | `src/video.zig` | drawing the graphics screen: dots, and the colour four of them make | | `src/font.zig` | the character generator: which chip, which entry, and the flash clock | +| `src/superhires.zig` | the IIgs's own graphics: pixels, palettes and a control byte a line | +| `src/png.zig` | writing an indexed picture out, for both of the displays | | `src/fonts/*.zig` | the shapes themselves, transcribed from the chips | | `src/speaker.zig` | when the cone moved, and turning that into sound | | `src/cassette.zig` | the cassette port, whose output is the speaker over again | diff --git a/src/memory16/apple2gs.zig b/src/memory16/apple2gs.zig index a4e1d14..ebedf8f 100644 --- a/src/memory16/apple2gs.zig +++ b/src/memory16/apple2gs.zig @@ -63,6 +63,7 @@ const adb_module = @import("../adb.zig"); const rtc_module = @import("../rtc.zig"); const iwm_module = @import("../iwm.zig"); const disk35 = @import("../disk35.zig"); +const superhires = @import("../superhires.zig"); const ensoniq = @import("../ensoniq.zig"); const vgc_module = @import("../vgc.zig"); const scc_module = @import("../scc.zig"); @@ -368,6 +369,11 @@ pub fn AppleIIgs(comptime options: Options) fn (type) type { /// Which interrupts are enabled and which have happened. interrupts: Interrupts, + /// Where the beam has got to, counted in scan lines since the + /// machine started, so that the lines it has crossed since + /// anything last looked can be walked. + scan_lines: u64 = 0, + /// Whether the beam is off the bottom of the screen. blanked: bool, /// How many vertical blanking intervals have begun since the @@ -582,6 +588,27 @@ pub fn AppleIIgs(comptime options: Options) fn (type) type { // anything moves it further: sixty frames' worth in one // step counted as one frame, and the interrupts that are // measured in frames came out sixty times too slow. + // The scan-line interrupt, which is the only interrupt in + // this machine whose source is a byte in memory rather than + // a register. Each of the two hundred Super Hi-Res lines + // has a control byte, and bit 6 of it asks for an interrupt + // as the beam reaches that line — so what interrupts and + // when is part of the picture, and a program can change it + // by drawing. + // + // Counted the same way the frames below are, and for the + // same reason. Walking back further than one frame would be + // walking over lines already looked at. + const reached = now / cycles_per_line; + if (self.vgc.new_video & vgc_module.Vgc.super_hires != 0) { + var line = @max(self.scan_lines, reached -| lines_per_frame); + while (line < reached) : (line += 1) { + const y: u16 = @intCast(line % lines_per_frame); + if (superhires.interruptsOn(&self.mega2, y)) self.vgc.scan_line = true; + } + } + self.scan_lines = reached; + const begun = (now + blanking_cycles) / cycles_per_frame; while (self.frames < begun) { self.frames += 1; @@ -1393,6 +1420,13 @@ pub fn AppleIIgs(comptime options: Options) fn (type) type { /// Writes out what the machine asked for and did not get, most /// wanted first. This is the whole point of the model as it /// stands: run the ROM, read this, and it says what to build. + /// Whether the video controller has the memory to itself and + /// is drawing Super Hi-Res rather than the Mega II drawing an + /// Apple II's screen. + pub fn superHiRes(self: *const Self) bool { + return self.vgc.new_video & vgc_module.Vgc.super_hires != 0; + } + pub fn report(self: *const Self, writer: *std.Io.Writer) !void { var total: u64 = 0; var kinds: usize = 0; @@ -2472,3 +2506,73 @@ test "an enabled interrupt is one the processor actually takes" { _ = cpu.memory.read(0x00c047, .data); try testing.expect(!cpu.irq); } + +test "a scan line interrupts when its control byte says to" { + // The one interrupt in this machine whose source is a byte in memory + // rather than a register: each of the two hundred Super Hi-Res lines has + // a control byte, and bit 6 of it asks for an interrupt as the beam + // reaches that line. So what interrupts, and when, is part of the picture. + var cpu: TestCPU = undefined; + try cpu.init(testing.allocator, null); + defer cpu.deinit(); + + // The bank latch first, or nothing written to bank $e1 lands there: with + // it clear the old soft switches decide which half of the Mega II an odd + // bank reaches, and they point at the main one. Software that uses this + // display sets the latch, and the machine's own firmware comes up with it + // set. It is the same seam as ever, and it catches everything once. + const showing = vgc_module.Vgc.super_hires | vgc_module.Vgc.bank_latch; + cpu.memory.write(0x00c029, vgc_module.Vgc.bank_latch, .data); + + // Line 100 asks; nothing else does. + cpu.memory.write(0xe10000 + superhires.control_bytes + 100, 0x40, .data); + cpu.memory.write(0x00c023, TestMemory.Vgc.scan_line_enable, .data); + + // With the old video on the screen the control bytes are just memory: + // the controller has not got the buffer and is drawing nothing. + cpu.clock.cycles = Memory16.cycles_per_frame; + _ = cpu.memory.read(0x000000, .data); + try testing.expect(!cpu.memory.vgc.scan_line); + try testing.expect(!cpu.irq); + + // Hand it the memory and the same frame raises it. + cpu.memory.write(0x00c029, showing, .data); + try testing.expect(cpu.memory.superHiRes()); + cpu.clock.cycles += Memory16.cycles_per_frame; + _ = cpu.memory.read(0x000000, .data); + try testing.expect(cpu.memory.vgc.scan_line); + try testing.expect(cpu.irq); + + // It is cleared where every other video interrupt is, by writing a zero + // into its bit at $c032, and the line goes down with it. + cpu.memory.write(0x00c032, 0xff & ~TestMemory.Vgc.scan_line_status, .data); + try testing.expect(!cpu.memory.vgc.scan_line); + try testing.expect(!cpu.irq); + + // And a line that does not ask does not raise it, however many go by. + cpu.memory.write(0xe10000 + superhires.control_bytes + 100, 0x00, .data); + cpu.clock.cycles += Memory16.cycles_per_frame * 10; + _ = cpu.memory.read(0x000000, .data); + try testing.expect(!cpu.memory.vgc.scan_line); +} + +test "the beam is not walked further back than one frame" { + // A clock that jumps a long way must not cost a walk proportional to the + // jump: every line has been crossed already, and looking at them again + // says nothing new. + var cpu: TestCPU = undefined; + try cpu.init(testing.allocator, null); + defer cpu.deinit(); + + cpu.memory.write(0x00c029, vgc_module.Vgc.super_hires | vgc_module.Vgc.bank_latch, .data); + cpu.memory.write(0xe10000 + superhires.control_bytes + 5, 0x40, .data); + + // A thousand frames in one step still finds it, exactly once. + cpu.clock.cycles = Memory16.cycles_per_frame * 1000; + _ = cpu.memory.read(0x000000, .data); + try testing.expect(cpu.memory.vgc.scan_line); + try testing.expectEqual( + cpu.clock.cycles / Memory16.cycles_per_line, + cpu.memory.scan_lines, + ); +} diff --git a/src/png.zig b/src/png.zig new file mode 100644 index 0000000..d844413 --- /dev/null +++ b/src/png.zig @@ -0,0 +1,274 @@ +// SPDX-FileCopyrightText: 2026 Jeffrey C. Ollie +// +// SPDX-License-Identifier: MIT + +//! Writing a picture out, for the two things here that make one. +//! +//! Both of this project's displays are *indexed*: an Apple II screen is a dot +//! number and a table of sixteen colours, and a Super Hi-Res screen is a +//! palette number and a colour number and a table of two hundred and fifty-six. +//! Neither is three bytes of colour a pixel, and turning them into that before +//! writing would throw away the one thing they are. So this writes indexed +//! PNGs, with the palette in the file's own palette chunk, which is the same +//! shape as the thing being written. +//! +//! Nothing is compressed. A PNG's image data is a zlib stream, and a zlib +//! stream may be made of *stored* blocks — deflate's way of saying "the next +//! n bytes are themselves". Three good things come of taking that way out. +//! The length of the image data is arithmetic rather than something that has +//! to be discovered, so the chunk header can be written before the pixels and +//! the pixels streamed straight through it. The checksums can be carried along +//! as the bytes go by rather than taken over a buffer at the end. And so there +//! is no allocator here at all, and nothing that can fail but the writer. +//! +//! The cost is size: a screen comes to about a hundred kilobytes where a +//! compressed one would be a few. That is the right way round for something +//! written by a key press and looked at immediately. + +const std = @import("std"); + +/// How much of a picture is repeated. +/// +/// Neither of these machines has square pixels, so a caller usually wants at +/// least the lines doubled. Repeating rather than interpolating is deliberate: +/// the dots are what the machine made, and blurring them is somebody else's +/// decision. +pub const Scale = struct { + across: u3 = 1, + down: u3 = 2, +}; + +/// The widest row this will write, in bytes: the widest picture either display +/// makes, at the largest scale, one byte a pixel. +const max_row = 1 + 640 * 4; + +/// Writes an indexed PNG. +/// +/// `plte` is the palette, three bytes an entry, at most 256 of them; `bits` is +/// how many bits an index takes and must be 4 or 8, which between them cover +/// both displays. `rows` is anything with a `row(y)` returning that line's +/// `wide` indices — it is asked for each line exactly once, in order, so a +/// caller can render as it goes rather than holding a frame. +pub fn writeIndexed( + writer: *std.Io.Writer, + plte: []const u8, + bits: u4, + wide: u16, + tall: u16, + scale: Scale, + rows: anytype, +) std.Io.Writer.Error!void { + std.debug.assert(bits == 4 or bits == 8); + std.debug.assert(plte.len % 3 == 0 and plte.len <= 256 * 3); + const across: usize = @max(1, @min(4, scale.across)); + const down: usize = @max(1, @min(7, scale.down)); + const dots = @as(usize, wide) * across; + const lines = @as(usize, tall) * down; + const per_byte: usize = if (bits == 4) 2 else 1; + // A filter byte in front of every row, and the indices packed after it. + const stride = 1 + (dots + per_byte - 1) / per_byte; + std.debug.assert(stride <= max_row); + const raw = stride * lines; + // Stored deflate blocks hold at most 65,535 bytes and cost five bytes of + // header each; the zlib wrapper is two bytes in front and four behind. + const blocks = (raw + 0xffff - 1) / 0xffff; + const idat = 2 + raw + 5 * blocks + 4; + + try writer.writeAll(&.{ 0x89, 'P', 'N', 'G', 0x0d, 0x0a, 0x1a, 0x0a }); + + var header: [13]u8 = undefined; + std.mem.writeInt(u32, header[0..4], @intCast(dots), .big); + std.mem.writeInt(u32, header[4..8], @intCast(lines), .big); + header[8] = bits; + header[9] = 3; // the indices are into a palette + header[10] = 0; // deflate, which is the only choice + header[11] = 0; // the only filter set there is + header[12] = 0; // not interlaced + try chunk(writer, "IHDR", &header); + try chunk(writer, "PLTE", plte); + + var length: [4]u8 = undefined; + std.mem.writeInt(u32, &length, @intCast(idat), .big); + try writer.writeAll(&length); + var crc: std.hash.Crc32 = .init(); + var adler: Adler32 = .{}; + try emit(writer, &crc, "IDAT"); + try emit(writer, &crc, &.{ 0x78, 0x01 }); + + var row: [max_row]u8 = undefined; + var left = raw; + var at: usize = 0; // how much room is left in the current stored block + for (0..tall) |y| { + const indices = rows.row(@intCast(y)); + @memset(row[0..stride], 0); + for (indices[0..wide], 0..) |index, x| { + for (0..across) |again| { + const dot = x * across + again; + if (bits == 8) { + row[1 + dot] = index; + } else if (dot % 2 == 0) { + // The first of a pair goes in the high nibble: a PNG's + // bits run from the most significant down. + row[1 + dot / 2] |= index << 4; + } else { + row[1 + dot / 2] |= index & 0x0f; + } + } + } + for (0..down) |_| { + var written: usize = 0; + while (written < stride) { + if (at == 0) { + const take = @min(left, 0xffff); + var head: [5]u8 = undefined; + head[0] = if (take == left) 1 else 0; + std.mem.writeInt(u16, head[1..3], @intCast(take), .little); + std.mem.writeInt(u16, head[3..5], ~@as(u16, @intCast(take)), .little); + try emit(writer, &crc, &head); + at = take; + } + const take = @min(stride - written, at); + try emit(writer, &crc, row[written..][0..take]); + adler.update(row[written..][0..take]); + written += take; + at -= take; + left -= take; + } + } + } + var sum: [4]u8 = undefined; + std.mem.writeInt(u32, &sum, adler.final(), .big); + try emit(writer, &crc, &sum); + std.mem.writeInt(u32, &length, crc.final(), .big); + try writer.writeAll(&length); + + try chunk(writer, "IEND", ""); +} + +/// Writes bytes and carries them into a checksum at the same time, which is +/// what lets the image data be written without being held first. +fn emit(writer: *std.Io.Writer, crc: *std.hash.Crc32, bytes: []const u8) std.Io.Writer.Error!void { + crc.update(bytes); + try writer.writeAll(bytes); +} + +fn chunk(writer: *std.Io.Writer, kind: *const [4]u8, data: []const u8) std.Io.Writer.Error!void { + var scratch: [4]u8 = undefined; + std.mem.writeInt(u32, &scratch, @intCast(data.len), .big); + try writer.writeAll(&scratch); + var crc: std.hash.Crc32 = .init(); + crc.update(kind); + crc.update(data); + try writer.writeAll(kind); + try writer.writeAll(data); + std.mem.writeInt(u32, &scratch, crc.final(), .big); + try writer.writeAll(&scratch); +} + +/// The checksum zlib puts on the end of a stream: two running sums, one of the +/// bytes and one of that sum. +const Adler32 = struct { + a: u32 = 1, + b: u32 = 0, + + fn update(self: *Adler32, bytes: []const u8) void { + for (bytes) |byte| { + self.a = (self.a + byte) % 65521; + self.b = (self.b + self.a) % 65521; + } + } + + fn final(self: *const Adler32) u32 { + return self.b << 16 | self.a; + } +}; + +/// Reads back what `writeIndexed` wrote, checking every length and checksum on +/// the way, and hands over the rows of indices. +/// +/// This is here for the tests in `video.zig` and `superhires.zig` rather than +/// for its own sake: a writer with nobody to read it is a writer nobody has +/// checked. Reading is only easy because nothing was compressed, which is one +/// more thing the stored blocks bought. +pub const Read = struct { + wide: u32, + tall: u32, + bits: u4, + plte: []const u8, + /// The rows, each one a filter byte and then the packed indices. + raw: []const u8, + stride: usize, + + pub const Error = error{Malformed}; + + pub fn at(self: *const Read, x: usize, y: usize) u8 { + const row = self.raw[y * self.stride + 1 ..]; + if (self.bits == 8) return row[x]; + const byte = row[x / 2]; + return if (x % 2 == 0) byte >> 4 else byte & 0x0f; + } +}; + +/// Parses a file `writeIndexed` wrote, into a caller's buffer. +pub fn read(file: []const u8, into: []u8) (Read.Error)!Read { + if (file.len < 8 or !std.mem.eql(u8, file[0..8], &.{ 0x89, 'P', 'N', 'G', 0x0d, 0x0a, 0x1a, 0x0a })) + return error.Malformed; + var result: Read = .{ .wide = 0, .tall = 0, .bits = 0, .plte = &.{}, .raw = &.{}, .stride = 0 }; + var data: []const u8 = &.{}; + var at: usize = 8; + var ended = false; + while (at + 12 <= file.len) { + const length = std.mem.readInt(u32, file[at..][0..4], .big); + if (at + 12 + length > file.len) return error.Malformed; + const kind = file[at + 4 ..][0..4]; + const body = file[at + 8 ..][0..length]; + var crc: std.hash.Crc32 = .init(); + crc.update(kind); + crc.update(body); + if (crc.final() != std.mem.readInt(u32, file[at + 8 + length ..][0..4], .big)) + return error.Malformed; + if (std.mem.eql(u8, kind, "IHDR")) { + result.wide = std.mem.readInt(u32, body[0..4], .big); + result.tall = std.mem.readInt(u32, body[4..8], .big); + result.bits = @truncate(body[8]); + if (body[9] != 3) return error.Malformed; + } else if (std.mem.eql(u8, kind, "PLTE")) { + result.plte = body; + } else if (std.mem.eql(u8, kind, "IDAT")) { + data = body; + } else if (std.mem.eql(u8, kind, "IEND")) { + ended = true; + } + at += 12 + length; + } + if (!ended or at != file.len) return error.Malformed; + + const per_byte: usize = if (result.bits == 4) 2 else 1; + result.stride = 1 + (result.wide + per_byte - 1) / per_byte; + const want = result.stride * result.tall; + if (into.len < want or data.len < 2) return error.Malformed; + if (data[0] != 0x78) return error.Malformed; + + var from: usize = 2; + var made: usize = 0; + while (true) { + if (from + 5 > data.len) return error.Malformed; + const last = data[from] & 1 != 0; + const stored = std.mem.readInt(u16, data[from + 1 ..][0..2], .little); + if (~stored != std.mem.readInt(u16, data[from + 3 ..][0..2], .little)) return error.Malformed; + // A block holds up to 65,535 bytes, which is one more than a u16 can + // count past once the five byte header is added to it. + const take: usize = stored; + if (from + 5 + take > data.len or made + take > want) return error.Malformed; + @memcpy(into[made..][0..take], data[from + 5 ..][0..take]); + made += take; + from += 5 + take; + if (last) break; + } + if (made != want or from + 4 != data.len) return error.Malformed; + var adler: Adler32 = .{}; + adler.update(into[0..made]); + if (adler.final() != std.mem.readInt(u32, data[from..][0..4], .big)) return error.Malformed; + result.raw = into[0..made]; + return result; +} diff --git a/src/root.zig b/src/root.zig index 759ed20..fa94e2e 100644 --- a/src/root.zig +++ b/src/root.zig @@ -49,6 +49,13 @@ pub const video = @import("video.zig"); /// of the shapes the chips hold. pub const font = @import("font.zig"); +/// Super Hi-Res: the Apple IIgs's own graphics, which are pixels and palettes +/// rather than dots and a colour subcarrier. +pub const superhires = @import("superhires.zig"); + +/// Writing a picture out, which both of the displays above can do. +pub const png = @import("png.zig"); + /// The Disk II: the controller card, its drives, and the encoding that turns /// a disk image into what a drive would read off the surface. pub const disk2 = @import("disk2.zig"); @@ -186,6 +193,8 @@ test { _ = @import("instantiation.zig"); _ = video; _ = font; + _ = superhires; + _ = png; _ = disk2; _ = disk35; _ = dos33; diff --git a/src/superhires.zig b/src/superhires.zig new file mode 100644 index 0000000..aca3fdb --- /dev/null +++ b/src/superhires.zig @@ -0,0 +1,408 @@ +// SPDX-FileCopyrightText: 2026 Jeffrey C. Ollie +// +// SPDX-License-Identifier: MIT + +//! Super Hi-Res: the Apple IIgs's own graphics, and nothing like the old ones. +//! +//! `video.zig` draws what the Mega II draws, which is what an Apple II drew: +//! a stream of dots at four times the colour subcarrier, coloured by what +//! four of them at a time do to a television. None of that is true here. Super +//! Hi-Res is the Video Graphics Controller's, it has actual pixels with actual +//! colour numbers in them, and the numbers mean whatever a palette in memory +//! says they mean. It is a different chip drawing a different picture on a +//! different grid, which is why it is a different file. +//! +//! The buffer is thirty-two kilobytes of the auxiliary half of the slow RAM — +//! bank `$e1`, `$2000` to `$9fff` — and it holds three things: +//! +//! | Where | What | +//! | ---------------- | ------------------------------------------------- | +//! | `$2000`-`$9cff` | 200 lines of 160 bytes | +//! | `$9d00`-`$9dc7` | one scan-line control byte per line | +//! | `$9e00`-`$9fff` | sixteen palettes of sixteen twelve-bit colours | +//! +//! ## A palette per line +//! +//! The control byte is the interesting part, and it is why this is drawn a +//! scan line at a time rather than a frame at a time. Every line chooses, +//! independently: which of the sixteen palettes it uses, whether it is 320 +//! pixels or 640, whether Color Fill is on, and whether the beam reaching it +//! raises an interrupt. So a picture can have far more than sixteen colours in +//! it, and a program can change the palette *underneath the beam* and have +//! more again. +//! +//! ## 320, and Color Fill +//! +//! Two pixels to a byte, four bits each, and the four bits are a colour number +//! straight into the line's palette. With Color Fill on, colour `$0` stops +//! being a colour and means "the same as the pixel to my left" — so a line of +//! `A 0 0 0 0 0 B 0 0 0 0 0 C` is three runs of solid colour and cost three +//! bytes to write rather than eighteen. Fifteen colours a line rather than +//! sixteen, and the manual is careful to say that the first pixel of a line +//! must not be `$0`, because there is nothing to its left and "an undetermined +//! color results". +//! +//! ## 640, and the four groups +//! +//! Four pixels to a byte, two bits each — which would be four colours, except +//! that it is not. The sixteen colours of the palette are divided into four +//! groups of four, and *which group a pixel uses depends on where it is in the +//! byte*: the first pixel takes the third group, the second the fourth, the +//! third the first, and the fourth the second. So sixteen colours are still +//! available along a line even though any one pixel can only be four of them, +//! and 640 mode gets its colour by putting the right value in the right +//! column. Hardware Reference, table 4-21. +//! +//! That rotation looks arbitrary until you notice what it is for: two adjacent +//! pixels on a 640 screen are half a dot each, and half a dot is what makes +//! colour on a composite monitor. The groups are arranged so that the pairs +//! that dither well sit next to each other. +//! +//! ## What is not here +//! +//! The border, which is a colour round the outside rather than part of the +//! picture, and which shares an address with the clock. And the fifty-sixth +//! scan line's worth of bytes past the control bytes, which the manual +//! reserves and says not to touch. + +const std = @import("std"); + +const png = @import("png.zig"); +const video = @import("video.zig"); + +/// The widest a line can be. A 320-pixel line is drawn at half the dot clock, +/// so it covers the same width of screen with each pixel twice as wide, and +/// that is what `scanLine` fills in: 640 either way, so that everything +/// downstream is one shape. +pub const width = 640; + +/// And two hundred lines rather than the old video's hundred and ninety-two. +pub const height = 200; + +/// Where the pixels are, in bank `$e1`, and how much of it each line takes. +pub const buffer = 0x2000; +pub const bytes_per_line = 160; + +/// Where the scan-line control bytes are: one per line, at `$9d00` plus the +/// line number. +pub const control_bytes = 0x9d00; + +/// And the palettes: sixteen of them, sixteen colours each, two bytes a +/// colour. +pub const palette_table = 0x9e00; +pub const palettes = 16; +pub const colours = 16; + +/// What one line's control byte says about it. +pub const Control = packed struct(u8) { + /// Which of the sixteen palettes the line uses. + palette: u4, + /// Reserved: the manual says to write zero. + reserved: u1, + /// Colour `$0` means "the same as the pixel to my left". 320 only; in 640 + /// mode this bit does nothing. + fill: bool, + /// Raise the scan-line interrupt when the beam reaches this line. + interrupt: bool, + /// 640 pixels rather than 320. + wide: bool, + + pub fn of(byte: u8) Control { + return @bitCast(byte); + } +}; + +/// One line of the display. +pub const Line = struct { + /// Which colour each of the 640 dot positions is, as a number from 0 to + /// 255: the palette in the high nibble and the colour in the low, which is + /// exactly where it came from and is a number a whole frame can share. + entries: [width]u8 = @splat(0), + /// How many pixels the line really has, which is 320 or 640. The entries + /// above are always 640 — a 320-pixel line has each of its pixels written + /// twice, because that is what the dot clock does to it. + pixels: u16 = 320, + /// What its control byte said. + control: Control = .of(0), +}; + +/// Draws one line. +/// +/// The machine has to answer `videoByte(auxiliary, address)`, which is the +/// same thing the old video asks of it; everything here is in the auxiliary +/// half, which is bank `$e1`. +pub fn scanLine(machine: anytype, y: u16, into: *Line) void { + const control: Control = .of(machine.videoByte(true, control_bytes + y)); + into.control = control; + into.pixels = if (control.wide) 640 else 320; + const line = buffer + @as(u16, y) * bytes_per_line; + const high: u8 = @as(u8, control.palette) << 4; + + if (control.wide) { + for (0..bytes_per_line) |at| { + const byte = machine.videoByte(true, line + @as(u16, @intCast(at))); + for (0..4) |pixel| { + // Which four of the sixteen a pixel may be depends on where it + // sits in the byte: third group, fourth, first, second. + const group: u8 = @intCast((pixel + 2) % 4 * 4); + const value: u8 = byte >> @intCast(6 - pixel * 2) & 0x03; + into.entries[at * 4 + pixel] = high | group | value; + } + } + return; + } + + var last: u8 = 0; + for (0..bytes_per_line) |at| { + const byte = machine.videoByte(true, line + @as(u16, @intCast(at))); + for (0..2) |pixel| { + var value: u8 = if (pixel == 0) byte >> 4 else byte & 0x0f; + // Colour zero with Color Fill on is not a colour: it is the pixel + // to the left over again. At the start of a line there is nothing + // to the left, and the manual says so rather than saying what + // happens; what happens here is colour zero. + if (control.fill and value == 0) value = last else last = value; + const entry = high | value; + into.entries[(at * 2 + pixel) * 2] = entry; + into.entries[(at * 2 + pixel) * 2 + 1] = entry; + } + } +} + +/// Reads all sixteen palettes: 256 colours, indexed the way `Line.entries` +/// indexes them. +/// +/// A colour is twelve bits in two, four bits to a channel, and it is stored +/// low byte first with green and blue in it and red in the byte above. Each +/// nibble is repeated to widen it, so `$f` becomes `$ff` and `$0` stays `$0`. +pub fn palette(machine: anytype, into: *[palettes * colours]video.Rgb) void { + for (0..palettes) |which| { + for (0..colours) |colour| { + const at: u16 = @intCast(palette_table + which * colours * 2 + colour * 2); + const low = machine.videoByte(true, at); + const top = machine.videoByte(true, at + 1); + into[which * colours + colour] = .{ + .r = (top & 0x0f) * 0x11, + .g = (low >> 4) * 0x11, + .b = (low & 0x0f) * 0x11, + }; + } + } +} + +/// Whether the beam reaching this line should raise the scan-line interrupt. +pub fn interruptsOn(machine: anytype, y: u16) bool { + if (y >= height) return false; + return Control.of(machine.videoByte(true, control_bytes + y)).interrupt; +} + +/// Writes the display as an indexed PNG: one byte a pixel, with all sixteen +/// palettes flattened into the file's own palette chunk. +/// +/// That is exactly the shape the hardware is in — a pixel names a colour in a +/// palette and a line names the palette — so the file holds what the machine +/// holds, with nothing worked out and nothing thrown away. Every colour a +/// frame can show is in the two hundred and fifty-six. +/// +/// A 320-pixel line is written at 640 with each of its pixels twice, since +/// that is what the dot clock does to it and it is how the two kinds of line +/// come out the same width on a screen. +pub fn writePng(machine: anytype, writer: *std.Io.Writer, scale: png.Scale) std.Io.Writer.Error!void { + var table: [palettes * colours]video.Rgb = undefined; + palette(machine, &table); + var plte: [palettes * colours * 3]u8 = undefined; + for (table, 0..) |colour, i| { + plte[i * 3 + 0] = colour.r; + plte[i * 3 + 1] = colour.g; + plte[i * 3 + 2] = colour.b; + } + var rows: Rows(@TypeOf(machine)) = .{ .machine = machine }; + try png.writeIndexed(writer, &plte, 8, width, height, scale, &rows); +} + +/// Hands the writer one line at a time, so that a whole frame never has to +/// exist anywhere. +fn Rows(comptime Machine: type) type { + return struct { + machine: Machine, + line: Line = .{}, + + pub fn row(self: *@This(), y: u16) []const u8 { + scanLine(self.machine, y, &self.line); + return &self.line.entries; + } + }; +} + +const testing = std.testing; + +/// Thirty-two kilobytes of bank $e1 and nothing else, for the tests below. +const Bare = struct { + ram: [0x10000]u8 = @splat(0), + + pub fn videoByte(self: *const Bare, auxiliary: bool, address: u16) u8 { + std.debug.assert(auxiliary); + return self.ram[address]; + } + + fn setColour(self: *Bare, which: u4, colour: u4, rgb: u12) void { + const at = palette_table + @as(usize, which) * 32 + @as(usize, colour) * 2; + self.ram[at] = @truncate(rgb); + self.ram[at + 1] = @truncate(rgb >> 8); + } +}; + +test "a control byte is four things and a palette number" { + const control: Control = .of(0b1110_0101); + try testing.expect(control.wide); + try testing.expect(control.interrupt); + try testing.expect(control.fill); + try testing.expectEqual(@as(u1, 0), control.reserved); + try testing.expectEqual(@as(u4, 5), control.palette); + + // And nothing at all, which is what an unwritten buffer holds: 320 + // pixels, palette zero, no fill and no interrupt. + const empty: Control = .of(0); + try testing.expect(!empty.wide); + try testing.expect(!empty.interrupt); + try testing.expect(!empty.fill); + try testing.expectEqual(@as(u4, 0), empty.palette); +} + +test "320 mode is two pixels a byte, each of them twice as wide" { + var machine: Bare = .{}; + var line: Line = .{}; + machine.ram[control_bytes] = 0x03; // 320, palette 3 + machine.ram[buffer] = 0x59; + scanLine(&machine, 0, &line); + + try testing.expectEqual(@as(u16, 320), line.pixels); + try testing.expectEqual(@as(u4, 3), line.control.palette); + // The high nibble is the left pixel, and each covers two of the 640. + try testing.expectEqual(@as(u8, 0x35), line.entries[0]); + try testing.expectEqual(@as(u8, 0x35), line.entries[1]); + try testing.expectEqual(@as(u8, 0x39), line.entries[2]); + try testing.expectEqual(@as(u8, 0x39), line.entries[3]); +} + +test "Color Fill makes colour zero mean the pixel to the left" { + var machine: Bare = .{}; + var line: Line = .{}; + machine.ram[control_bytes] = 0x20; // 320, fill on, palette 0 + // A 0 0 0 B 0 0 0, which the manual gives as the whole point of the mode. + machine.ram[buffer + 0] = 0xa0; + machine.ram[buffer + 1] = 0x00; + machine.ram[buffer + 2] = 0xb0; + machine.ram[buffer + 3] = 0x00; + scanLine(&machine, 0, &line); + + for (0..8) |x| try testing.expectEqual(@as(u8, 0x0a), line.entries[x]); + for (8..16) |x| try testing.expectEqual(@as(u8, 0x0b), line.entries[x]); + + // With fill off the same bytes are a colour and then colour zero. + machine.ram[control_bytes] = 0x00; + scanLine(&machine, 0, &line); + try testing.expectEqual(@as(u8, 0x0a), line.entries[0]); + try testing.expectEqual(@as(u8, 0x00), line.entries[2]); +} + +test "640 mode takes its four groups in the order the manual gives" { + // "The first pixel in each horizontal line can select one of 4 colors from + // the third group of 4 in the palette. The second pixel selects from the + // fourth group. The third pixel selects from the first group, and the + // fourth pixel selects from the second group." + var machine: Bare = .{}; + var line: Line = .{}; + machine.ram[control_bytes] = 0x80; // 640, palette 0 + machine.ram[buffer] = 0b11_11_11_11; // value 3 in all four + scanLine(&machine, 0, &line); + + try testing.expectEqual(@as(u16, 640), line.pixels); + try testing.expectEqual(@as(u8, 0x0b), line.entries[0]); // third group: $8-$b + try testing.expectEqual(@as(u8, 0x0f), line.entries[1]); // fourth: $c-$f + try testing.expectEqual(@as(u8, 0x03), line.entries[2]); // first: $0-$3 + try testing.expectEqual(@as(u8, 0x07), line.entries[3]); // second: $4-$7 + + // And the two bits are read from the top of the byte down. + machine.ram[buffer] = 0b01_00_00_00; + scanLine(&machine, 0, &line); + try testing.expectEqual(@as(u8, 0x09), line.entries[0]); + try testing.expectEqual(@as(u8, 0x0c), line.entries[1]); +} + +test "a colour is twelve bits, low byte first, with red on its own" { + var machine: Bare = .{}; + machine.setColour(0, 1, 0xf00); // red + machine.setColour(0, 2, 0x0f0); // green + machine.setColour(0, 3, 0x00f); // blue + machine.setColour(15, 15, 0xfff); + + var table: [palettes * colours]video.Rgb = undefined; + palette(&machine, &table); + try testing.expectEqual(video.Rgb{ .r = 0xff, .g = 0, .b = 0 }, table[1]); + try testing.expectEqual(video.Rgb{ .r = 0, .g = 0xff, .b = 0 }, table[2]); + try testing.expectEqual(video.Rgb{ .r = 0, .g = 0, .b = 0xff }, table[3]); + try testing.expectEqual(video.Rgb{ .r = 0xff, .g = 0xff, .b = 0xff }, table[255]); + try testing.expectEqual(video.Rgb{ .r = 0, .g = 0, .b = 0 }, table[0]); +} + +test "every line chooses for itself" { + var machine: Bare = .{}; + var line: Line = .{}; + for (0..height) |y| { + // Alternating 320 and 640, and a different palette every line. + machine.ram[control_bytes + y] = @as(u8, if (y % 2 == 0) 0 else 0x80) | @as(u8, @truncate(y % 16)); + } + for (0..height) |y| { + scanLine(&machine, @intCast(y), &line); + try testing.expectEqual(@as(u16, if (y % 2 == 0) 320 else 640), line.pixels); + try testing.expectEqual(@as(u4, @truncate(y % 16)), line.control.palette); + } +} + +test "a Super Hi-Res screen written out reads back as itself" { + const gpa = testing.allocator; + const machine = try gpa.create(Bare); + defer gpa.destroy(machine); + machine.* = .{}; + + // Sixteen palettes, each a ramp of a different hue, and lines that use + // them in turn: the thing this display can do that the old one cannot. + for (0..palettes) |which| { + for (0..colours) |colour| { + const level: u12 = @intCast(colour); + machine.setColour(@intCast(which), @intCast(colour), switch (which % 3) { + 0 => level << 8, + 1 => level << 4, + else => level, + }); + } + } + for (0..height) |y| { + machine.ram[control_bytes + y] = @intCast(y % palettes); + for (0..bytes_per_line) |at| { + machine.ram[buffer + y * bytes_per_line + at] = @truncate(at); + } + } + + const file = try gpa.alloc(u8, 1024 * 1024); + defer gpa.free(file); + var writer: std.Io.Writer = .fixed(file); + try writePng(machine, &writer, .{ .across = 1, .down = 1 }); + + const raw = try gpa.alloc(u8, 1024 * 1024); + defer gpa.free(raw); + const back = try png.read(writer.buffered(), raw); + try testing.expectEqual(@as(u32, width), back.wide); + try testing.expectEqual(@as(u32, height), back.tall); + try testing.expectEqual(@as(u4, 8), back.bits); + // All sixteen palettes are in the file, which is what lets one frame show + // two hundred and fifty-six colours. + try testing.expectEqual(@as(usize, 256 * 3), back.plte.len); + + var line: Line = .{}; + for (0..height) |y| { + scanLine(machine, @intCast(y), &line); + for (0..width) |x| try testing.expectEqual(line.entries[x], back.at(x, y)); + } +} diff --git a/src/vgc.zig b/src/vgc.zig index 4e0e77a..e913af3 100644 --- a/src/vgc.zig +++ b/src/vgc.zig @@ -32,8 +32,8 @@ //! //! What is *not* here is the drawing. These are the registers, and they read //! back what was written to them, which is what a program setting up a display -//! needs. Turning any of it into a picture is the video's job and the video is -//! not modelled. +//! needs. Turning them into a picture is `superhires.zig`'s job for this +//! chip's own modes and `video.zig`'s for the ones it inherited. const std = @import("std"); @@ -106,6 +106,10 @@ pub const Vgc = struct { /// The bank latch, bit 0 of the New-Video register. pub const bank_latch: u8 = 0x01; + /// And bit 7 of it, which is the one that matters most: with it set the + /// old Apple II video is gone and the controller has the memory to itself. + pub const super_hires: u8 = 0x80; + /// The VGC Interrupt register's bits, at `$c023`. The top three are status /// and read-only; the two enables are the only ones a program can write. pub const interrupting_bit: u8 = 0x80; diff --git a/src/video.zig b/src/video.zig index 8c562aa..b628e9f 100644 --- a/src/video.zig +++ b/src/video.zig @@ -90,6 +90,7 @@ const std = @import("std"); const font = @import("font.zig"); +const png = @import("png.zig"); const screen = @import("screen.zig"); /// Dot positions across the screen. Every mode divides into this: Lo-Res is @@ -394,9 +395,7 @@ pub const Picture = struct { /// A dot on this machine is not square: five hundred and sixty of them /// across and a hundred and ninety-two down is a screen four units wide /// and three tall, so the default doubles the lines and gets within a few - /// per cent of that. Repeating rather than interpolating is deliberate — - /// the dots are what the machine made and blurring them is somebody else's - /// decision. + /// per cent of that. across: u3 = 1, down: u3 = 2, /// Whether to write the black and white a monochrome monitor shows rather @@ -405,143 +404,44 @@ pub const Picture = struct { monochrome: bool = false, }; -/// Writes the display as a PNG. -/// -/// Four bits to a dot, with the sixteen colours in the file's own palette -/// chunk, which is what this machine's screen actually is: an index and a -/// table, not three bytes of colour. Nothing is compressed — the deflate -/// stream is stored blocks — so there is no allocator here and nothing to -/// fail but the writer. A screen comes to about a hundred kilobytes. +/// Writes the display as an indexed PNG: four bits to a dot, with the sixteen +/// colours in the file's own palette chunk, which is what this machine's +/// screen actually is. See `png.zig` for why nothing is compressed. pub fn writePng(machine: anytype, writer: *std.Io.Writer, picture: Picture) std.Io.Writer.Error!void { - const across: usize = @max(1, picture.across); - const down: usize = @max(1, picture.down); - const wide = width * across; - const tall = height * down; - // Two dots to a byte, and a filter byte in front of every row. - const stride = 1 + (wide + 1) / 2; - const raw = stride * tall; - // Stored deflate blocks hold at most 65,535 bytes and cost five bytes of - // header each, and the zlib wrapper is two bytes in front and four behind. - const blocks = (raw + 0xffff - 1) / 0xffff; - const idat = 2 + raw + 5 * blocks + 4; - - try writer.writeAll(&.{ 0x89, 'P', 'N', 'G', 0x0d, 0x0a, 0x1a, 0x0a }); - - var header: [13]u8 = undefined; - std.mem.writeInt(u32, header[0..4], @intCast(wide), .big); - std.mem.writeInt(u32, header[4..8], @intCast(tall), .big); - header[8] = 4; // four bits a dot - header[9] = 3; // and they are indices into a palette - header[10] = 0; // deflate, which is the only choice - header[11] = 0; // the only filter set there is - header[12] = 0; // not interlaced - try chunk(writer, "IHDR", &header); - - var entries: [16 * 3]u8 = undefined; + var plte: [16 * 3]u8 = undefined; for (palette, 0..) |colour, i| { - entries[i * 3 + 0] = colour.r; - entries[i * 3 + 1] = colour.g; - entries[i * 3 + 2] = colour.b; - } - try chunk(writer, "PLTE", &entries); - - // The image data, which is too big to hold and so is written as it is - // made: the length was worked out above and the checksums are carried - // along rather than taken at the end. - var length: [4]u8 = undefined; - std.mem.writeInt(u32, &length, @intCast(idat), .big); - try writer.writeAll(&length); - var crc: std.hash.Crc32 = .init(); - var adler: Adler32 = .{}; - try emit(writer, &crc, "IDAT"); - try emit(writer, &crc, &.{ 0x78, 0x01 }); - - var row: [1 + (width * 7 + 1) / 2]u8 = undefined; - var line: Line = .{}; - var left = raw; - var at: usize = 0; // where in the current deflate block - for (0..height) |y| { - _ = scanLine(machine, @intCast(y), &line); - @memset(row[0..stride], 0); - for (0..width) |x| { - const colour: u8 = if (picture.monochrome) - (if (line.dots[x]) @intFromEnum(Colour.white) else 0) - else - line.colours[x]; - for (0..across) |again| { - const dot = 1 + (x * across + again); - // The first dot of a pair goes in the high nibble, since a - // PNG's bits run from the most significant down. - if (dot % 2 == 1) row[dot / 2 + 1] |= colour << 4 else row[dot / 2] |= colour; - } - } - for (0..down) |_| { - var written: usize = 0; - while (written < stride) { - if (at == 0) { - const take = @min(left, 0xffff); - var head: [5]u8 = undefined; - head[0] = if (take == left) 1 else 0; - std.mem.writeInt(u16, head[1..3], @intCast(take), .little); - std.mem.writeInt(u16, head[3..5], ~@as(u16, @intCast(take)), .little); - try emit(writer, &crc, &head); - at = take; - } - const take = @min(stride - written, at); - try emit(writer, &crc, row[written..][0..take]); - adler.update(row[written..][0..take]); - written += take; - at -= take; - left -= take; - } - } - } - var sum: [4]u8 = undefined; - std.mem.writeInt(u32, &sum, adler.final(), .big); - try emit(writer, &crc, &sum); - std.mem.writeInt(u32, &length, crc.final(), .big); - try writer.writeAll(&length); - - try chunk(writer, "IEND", ""); -} - -/// Writes bytes and carries them into a checksum at the same time, which is -/// what lets the image data be written without being held first. -fn emit(writer: *std.Io.Writer, crc: *std.hash.Crc32, bytes: []const u8) std.Io.Writer.Error!void { - crc.update(bytes); - try writer.writeAll(bytes); -} - -fn chunk(writer: *std.Io.Writer, kind: *const [4]u8, data: []const u8) std.Io.Writer.Error!void { - var scratch: [4]u8 = undefined; - std.mem.writeInt(u32, &scratch, @intCast(data.len), .big); - try writer.writeAll(&scratch); - var crc: std.hash.Crc32 = .init(); - crc.update(kind); - crc.update(data); - try writer.writeAll(kind); - try writer.writeAll(data); - std.mem.writeInt(u32, &scratch, crc.final(), .big); - try writer.writeAll(&scratch); + plte[i * 3 + 0] = colour.r; + plte[i * 3 + 1] = colour.g; + plte[i * 3 + 2] = colour.b; + } + var rows: Rows(@TypeOf(machine)) = .{ .machine = machine, .monochrome = picture.monochrome }; + try png.writeIndexed(writer, &plte, 4, width, height, .{ + .across = picture.across, + .down = picture.down, + }, &rows); } -/// The checksum zlib puts on the end of a stream: two running sums, one of the -/// bytes and one of that sum. -const Adler32 = struct { - a: u32 = 1, - b: u32 = 0, - - fn update(self: *Adler32, bytes: []const u8) void { - for (bytes) |byte| { - self.a = (self.a + byte) % 65521; - self.b = (self.b + self.a) % 65521; +/// Hands the writer one line at a time, so that a whole frame never has to +/// exist anywhere. +fn Rows(comptime Machine: type) type { + return struct { + machine: Machine, + monochrome: bool, + line: Line = .{}, + indices: [width]u8 = @splat(0), + + pub fn row(self: *@This(), y: u16) []const u8 { + _ = scanLine(self.machine, y, &self.line); + for (0..width) |x| { + self.indices[x] = if (self.monochrome) + (if (self.line.dots[x]) @intFromEnum(Colour.white) else 0) + else + self.line.colours[x]; + } + return &self.indices; } - } - - fn final(self: *const Adler32) u32 { - return self.b << 16 | self.a; - } -}; + }; +} const testing = std.testing; @@ -852,79 +752,28 @@ test "a screen written as a PNG reads back as the screen" { machine.fillHires(40, 0x55, 0x2a); const gpa = testing.allocator; - const buffer = try gpa.alloc(u8, 256 * 1024); - defer gpa.free(buffer); - var writer: std.Io.Writer = .fixed(buffer); + const file = try gpa.alloc(u8, 256 * 1024); + defer gpa.free(file); + var writer: std.Io.Writer = .fixed(file); try writePng(&machine, &writer, .{ .across = 1, .down = 1 }); - const file = writer.buffered(); - // The signature, and then chunks whose lengths and checksums agree. - try testing.expectEqualSlices(u8, &.{ 0x89, 'P', 'N', 'G', 0x0d, 0x0a, 0x1a, 0x0a }, file[0..8]); - var at: usize = 8; - var data: []const u8 = &.{}; - var saw_end = false; - var kinds: usize = 0; - while (at < file.len) { - const length = std.mem.readInt(u32, file[at..][0..4], .big); - const kind = file[at + 4 ..][0..4]; - const body = file[at + 8 ..][0..length]; - var crc: std.hash.Crc32 = .init(); - crc.update(kind); - crc.update(body); - try testing.expectEqual(crc.final(), std.mem.readInt(u32, file[at + 8 + length ..][0..4], .big)); - kinds += 1; - if (std.mem.eql(u8, kind, "IHDR")) { - try testing.expectEqual(@as(u32, width), std.mem.readInt(u32, body[0..4], .big)); - try testing.expectEqual(@as(u32, height), std.mem.readInt(u32, body[4..8], .big)); - try testing.expectEqual(@as(u8, 4), body[8]); - try testing.expectEqual(@as(u8, 3), body[9]); - } else if (std.mem.eql(u8, kind, "PLTE")) { - try testing.expectEqual(@as(u32, 16 * 3), length); - try testing.expectEqual(palette[15].r, body[15 * 3]); - } else if (std.mem.eql(u8, kind, "IDAT")) { - data = body; - } else if (std.mem.eql(u8, kind, "IEND")) { - saw_end = true; - } - at += 12 + length; - } - try testing.expect(saw_end); - try testing.expectEqual(@as(usize, 4), kinds); - try testing.expectEqual(file.len, at); - - // Nothing is compressed, so reading the image back is a matter of walking - // the stored blocks — which is the whole reason for writing it that way. - const raw = try gpa.alloc(u8, (1 + width / 2) * height); + // Reading it back checks every length and checksum in it on the way. + const raw = try gpa.alloc(u8, 256 * 1024); defer gpa.free(raw); - try testing.expectEqualSlices(u8, &.{ 0x78, 0x01 }, data[0..2]); - var from: usize = 2; - var into: usize = 0; - while (true) { - const last = data[from] & 1 != 0; - const take = std.mem.readInt(u16, data[from + 1 ..][0..2], .little); - try testing.expectEqual(~take, std.mem.readInt(u16, data[from + 3 ..][0..2], .little)); - @memcpy(raw[into..][0..take], data[from + 5 ..][0..take]); - into += take; - from += 5 + take; - if (last) break; - } - try testing.expectEqual(raw.len, into); - var adler: Adler32 = .{}; - adler.update(raw); - try testing.expectEqual(adler.final(), std.mem.readInt(u32, data[from..][0..4], .big)); - try testing.expectEqual(data.len, from + 4); + const back = try png.read(writer.buffered(), raw); + try testing.expectEqual(@as(u32, width), back.wide); + try testing.expectEqual(@as(u32, height), back.tall); + try testing.expectEqual(@as(u4, 4), back.bits); + try testing.expectEqual(@as(usize, 16 * 3), back.plte.len); + try testing.expectEqual(palette[15].r, back.plte[15 * 3]); // And the dots in it are the dots the renderer made. const painted = try gpa.create([width * height]u4); defer gpa.destroy(painted); paint(&machine, painted); for (0..height) |y| { - const row = raw[y * (1 + width / 2) ..]; - try testing.expectEqual(@as(u8, 0), row[0]); // no filter for (0..width) |x| { - const packed_byte = row[1 + x / 2]; - const index: u4 = @truncate(if (x % 2 == 0) packed_byte >> 4 else packed_byte); - try testing.expectEqual(painted[y * width + x], index); + try testing.expectEqual(@as(u8, painted[y * width + x]), back.at(x, y)); } } } diff --git a/tools/bootgs.zig b/tools/bootgs.zig index b448ddb..d1358b5 100644 --- a/tools/bootgs.zig +++ b/tools/bootgs.zig @@ -296,9 +296,20 @@ pub fn main(init: std.process.Init) !void { var file = try std.Io.Dir.cwd().createFile(io, picture, .{}); defer file.close(io); var out_file = file.writer(io, &buffer); - try zig65.video.writePng(&cpu.memory.mega2, &out_file.interface, .{}); + // Which of the machine's two displays is on the screen. They are + // different chips drawing different pictures on different grids, and + // the New-Video register's top bit is what says which one has the + // memory. + const super = cpu.memory.superHiRes(); + if (super) + try zig65.superhires.writePng(&cpu.memory.mega2, &out_file.interface, .{}) + else + try zig65.video.writePng(&cpu.memory.mega2, &out_file.interface, .{}); try out_file.interface.flush(); - try w.print("\nwrote the screen to {s}\n", .{picture}); + try w.print("\nwrote the {s} screen to {s}\n", .{ + if (super) "Super Hi-Res" else "Apple II", + picture, + }); } // And what is on the text screen, which is the Mega II's to draw and so