Documentation
¶
Index ¶
- Constants
- Variables
- func BasicTape(name, source string) ([]byte, error)
- func CompositeLayer2(ula, l2 *image.RGBA, ulaOnTop bool) *image.RGBA
- func CompositeNextLayers(ula, l2, sprites *image.RGBA, nr15 uint8) *image.RGBA
- func CountAttrMatches(zx *ZenZX, m attrMatch, rowStart, rowEnd int) int
- func DetectSnapshotFormat(filename string) string
- func InitDisplay(scale int, showBorder bool, renderer VideoRenderer) (int, int)
- func ListSnapshots(dir string) ([]string, error)
- func ParseAddr(s string) (uint16, error)
- func ParseAddrSigned(s string) (int, error)
- func ReadScreen(zx *ZenZX) []string
- func ReadScreenRow(zx *ZenZX, row int) string
- func RegisterVideoRenderer(r VideoRenderer)
- func ResolveROMBytes(name, romDir string) ([]byte, error)
- func RunGUI(args []string)
- func SetLogOutput(w io.Writer)
- func SetTraceOutput(w io.Writer)
- type AYChip
- type Action
- type AudioBackend
- type AudioDevice
- type AudioEngine
- func (am *AudioEngine) Close()
- func (am *AudioEngine) GetAY() *AYChip
- func (am *AudioEngine) GetBufferStatus() (level float32, samples int, requested int)
- func (am *AudioEngine) GetDebugInfo() (speakerChanges int, cpuCycle uint64)
- func (am *AudioEngine) Initialize() error
- func (am *AudioEngine) IsEnabled() bool
- func (am *AudioEngine) Read(buf []byte) (int, error)
- func (am *AudioEngine) SetAYVolume(volume float32)
- func (am *AudioEngine) SetAudioFilter(on bool)
- func (am *AudioEngine) SetBeeperVolume(volume float32)
- func (am *AudioEngine) SetDevice(d AudioDevice)
- func (am *AudioEngine) SetEnabled(enabled bool)
- func (am *AudioEngine) SetMasterVolume(volume float32)
- func (am *AudioEngine) UpdateCPUCycle(cycles uint64)
- func (am *AudioEngine) UpdateSpeaker(speaker bool, cycles uint64)
- type AudioInterface
- type AudioMetadata
- type AudioState
- type AudioWrapper
- func (aw *AudioWrapper) Close()
- func (aw *AudioWrapper) GetAY() *AYChip
- func (aw *AudioWrapper) GetAYVolume() float32
- func (aw *AudioWrapper) GetBeeperVolume() float32
- func (aw *AudioWrapper) GetBufferStatus() (level float32, samples int, requested int)
- func (aw *AudioWrapper) GetDebugInfo() (speakerChanges int, cpuCycle uint64)
- func (aw *AudioWrapper) GetMasterVolume() float32
- func (aw *AudioWrapper) Initialize() error
- func (aw *AudioWrapper) IsEnabled() bool
- func (aw *AudioWrapper) ReadAYRegister(reg uint8) uint8
- func (aw *AudioWrapper) SetAYVolume(volume float32)
- func (aw *AudioWrapper) SetBeeperVolume(volume float32)
- func (aw *AudioWrapper) SetDevice(d AudioDevice)
- func (aw *AudioWrapper) SetEnabled(enabled bool)
- func (aw *AudioWrapper) SetMasterVolume(volume float32)
- func (aw *AudioWrapper) UpdateCPUCycle(cycles uint64)
- func (aw *AudioWrapper) UpdateSpeaker(speaker bool, cycles uint64)
- func (aw *AudioWrapper) WriteAYRegister(reg, value uint8)
- type BandLimitedInterpolator
- type BiquadFilter
- type BootDetector
- type BorderChange
- type BorderHistory
- type CPUMetadata
- type CPUState
- type CPUWrapper
- type ChunkHeader
- type DCBlocker
- type DebugSnapshot
- func (ds *DebugSnapshot) AnalyzeCPUState()
- func (ds *DebugSnapshot) AnalyzeMemoryState()
- func (ds *DebugSnapshot) AnalyzeRRegister()
- func (ds *DebugSnapshot) CheckROMLocation()
- func (ds *DebugSnapshot) CheckStackContents()
- func (ds *DebugSnapshot) RunFullDiagnostics()
- func (ds *DebugSnapshot) TestEndianness()
- type DebugView
- func (d DebugView) Halted() bool
- func (d DebugView) PC() uint16
- func (d DebugView) ReadMem(addr uint16, n int) []byte
- func (d DebugView) Regs() Regs
- func (d DebugView) SetFetchHook(hook func(pc uint16))
- func (d DebugView) SetPC(addr uint16)
- func (d DebugView) SetReg(name RegName, value uint16) (ok bool)
- func (d DebugView) Step() int
- func (d DebugView) WriteMem(addr uint16, data []byte)
- type Disk
- type DiskSector
- type DiskTrack
- type Display
- type DisplayManager
- func (dm *DisplayManager) CleanupTextures()
- func (dm *DisplayManager) GetCurrentSize() (int, int)
- func (dm *DisplayManager) InitializeAfterWindow()
- func (dm *DisplayManager) IsBorderStripesEnabled() bool
- func (dm *DisplayManager) MinMultiplierForMode() int
- func (dm *DisplayManager) Render(paused bool, mem *SpectrumMemory, screen *SpectrumScreen, io *SpectrumIO)
- func (dm *DisplayManager) ScaleDown() bool
- func (dm *DisplayManager) ScaleUp() bool
- func (dm *DisplayManager) SetAudioManager(audio *AudioWrapper)
- func (dm *DisplayManager) SetBorderChanges(changes []BorderChange, frameOrigin uint64, cyclesPerFrame int)
- func (dm *DisplayManager) SetBorderColor(color uint8)
- func (dm *DisplayManager) SetInitialSize(width, height int)
- func (dm *DisplayManager) SetPreEndDrawHook(fn func())
- func (dm *DisplayManager) SetReservedTopHeight(h int)
- func (dm *DisplayManager) SetScale(n int) bool
- func (dm *DisplayManager) SetSpectrumIO(io *SpectrumIO)
- func (dm *DisplayManager) SetSpriteGPUCacheCapacity(capacity int)
- func (dm *DisplayManager) SetVideoRenderer(r VideoRenderer)
- func (dm *DisplayManager) ToggleBorder()
- func (dm *DisplayManager) ToggleBorderStripes()
- func (dm *DisplayManager) ToggleDebugOverlay()
- func (dm *DisplayManager) ToggleFPS()
- func (dm *DisplayManager) UpdateWindowSize()
- type DivMMC
- func (d *DivMMC) MemRead(address uint16) (uint8, bool)
- func (d *DivMMC) MemWrite(address uint16, value uint8) bool
- func (d *DivMMC) OnM1(pc uint16, opcode uint8, context string)
- func (d *DivMMC) ReadControl() uint8
- func (d *DivMMC) ReadData() uint8
- func (d *DivMMC) SD() *SDCard
- func (d *DivMMC) SD2() *SDCard
- func (d *DivMMC) SetAutomapEnabled(enabled bool)
- func (d *DivMMC) WriteCS(value uint8)
- func (d *DivMMC) WriteControl(value uint8)
- func (d *DivMMC) WriteData(value uint8)
- type Engine
- type FDC765
- func (fdc *FDC765) AutoCommit(debounceFrames int) bool
- func (fdc *FDC765) Busy() bool
- func (fdc *FDC765) CreateBlankDisk()
- func (fdc *FDC765) DiskFile() string
- func (fdc *FDC765) EjectDisk()
- func (fdc *FDC765) EnableDebug(enable bool)
- func (fdc *FDC765) FileChanged() bool
- func (fdc *FDC765) HasDisk() bool
- func (fdc *FDC765) IsModified() bool
- func (fdc *FDC765) LoadDisk(filename string) error
- func (fdc *FDC765) ReadData() uint8
- func (fdc *FDC765) ReadStatus() uint8
- func (fdc *FDC765) SaveDisk() error
- func (fdc *FDC765) Tick(frame int)
- func (fdc *FDC765) WriteData(value uint8)
- type FDCMetadata
- type FDCState
- type FastGUIRenderer
- type FastLoader
- type IOMetadata
- type IOState
- type JoystickMode
- type JoystickState
- type KeyMapping
- type KeyQueue
- type Link
- func (l *Link) Addr() string
- func (l *Link) Close()
- func (l *Link) Counts() (received, sent uint64)
- func (l *Link) Listen(addr string) error
- func (l *Link) Pending() int
- func (l *Link) Ports() (data, control uint16)
- func (l *Link) Receive() []byte
- func (l *Link) Reset()
- func (l *Link) Send(p []byte)
- func (l *Link) SetPorts(data, control uint16) error
- type MemoryFlags
- type MemoryMetadata
- type MemoryPage16k
- type MouseMode
- type MouseState
- type NextRegisterFile
- type NonStandardConfig
- type PagingState
- type RegName
- type Regs
- type SDCard
- type SDCardImage
- type ScheduleConfig
- type Scheduler
- type Script
- type SincFilter
- type SnapshotHeader
- type SnapshotMetadata
- type SpeakerChange
- type SpectrumIO
- func (io *SpectrumIO) CombineULAAndTilemap(ula *image.RGBA, screen *SpectrumScreen) *image.RGBA
- func (io *SpectrumIO) ComposeNextFrame(standard func() *image.RGBA, screen *SpectrumScreen, border uint8) *image.RGBA
- func (io *SpectrumIO) DecodeLayer2() *image.RGBA
- func (io *SpectrumIO) DecodeNextTimex(screen *SpectrumScreen) *image.RGBA
- func (io *SpectrumIO) DecodeSprites() *image.RGBA
- func (io *SpectrumIO) DecodeSpritesFrame() *image.RGBA
- func (io *SpectrumIO) DisableFDC()
- func (io *SpectrumIO) EnableDivMMC(sdImage SDCardImage, sdSize int64, romImage []byte)
- func (io *SpectrumIO) EnableFDC()
- func (io *SpectrumIO) EndFrame()
- func (io *SpectrumIO) FDCTick(frame, debounceFrames int)
- func (io *SpectrumIO) GetAYRegister() uint8
- func (io *SpectrumIO) GetAYRegisters() [16]uint8
- func (io *SpectrumIO) GetBorderColor() uint8
- func (io *SpectrumIO) GetBorderHistory() []BorderChange
- func (io *SpectrumIO) GetInterruptVector() uint8
- func (io *SpectrumIO) GetKeyboardState() [8]uint8
- func (io *SpectrumIO) GetMMUSlots() [8]uint8
- func (io *SpectrumIO) GetMode0Instruction() []uint8
- func (io *SpectrumIO) GetNextRegister(reg uint8) uint8
- func (io *SpectrumIO) GetSpeaker() bool
- func (io *SpectrumIO) GetTapeEar() bool
- func (io *SpectrumIO) In(port uint16) uint8
- func (io *SpectrumIO) LoadDisk(filename string) error
- func (io *SpectrumIO) MultifaceButton()
- func (io *SpectrumIO) NextFrame(standard func() *image.RGBA, screen *SpectrumScreen, border uint8) *image.RGBA
- func (io *SpectrumIO) Out(port uint16, value uint8)
- func (io *SpectrumIO) PopAMXInterrupt() (vector uint8, ok bool)
- func (io *SpectrumIO) PressKey(row, col uint8)
- func (io *SpectrumIO) ReadPort(port uint16) uint8
- func (io *SpectrumIO) ReleaseKey(row, col uint8)
- func (io *SpectrumIO) ResetKeyboard()
- func (io *SpectrumIO) SaveDisk() error
- func (io *SpectrumIO) SaveDiskAs(filename string) error
- func (io *SpectrumIO) SetAYRegisters(registers [16]uint8)
- func (io *SpectrumIO) SetBorderColor(color uint8)
- func (io *SpectrumIO) SetCPU(cpu Z80CPU)
- func (io *SpectrumIO) SetFDCDebug(enable bool)
- func (io *SpectrumIO) SetJoystickMode(mode JoystickMode)
- func (io *SpectrumIO) SetJoystickState(s JoystickState)
- func (io *SpectrumIO) SetJoystickStateBoth(port1, port2 JoystickState)
- func (io *SpectrumIO) SetMouseMode(mode MouseMode)
- func (io *SpectrumIO) SetMouseState(s MouseState)
- func (io *SpectrumIO) SetNextRegister(reg uint8, value uint8)
- func (io *SpectrumIO) SetTS2068JoystickState(player int, s JoystickState)
- func (io *SpectrumIO) SetTapeEar(level bool)
- func (io *SpectrumIO) StartFrame()
- func (io *SpectrumIO) WritePort(port uint16, value uint8)
- type SpectrumKey
- type SpectrumMemory
- func (m *SpectrumMemory) DisableBootROM()
- func (m *SpectrumMemory) Enable128K()
- func (m *SpectrumMemory) EnableNext()
- func (m *SpectrumMemory) EnablePlus3()
- func (m *SpectrumMemory) Load(address uint16, data []byte)
- func (m *SpectrumMemory) LoadROM(data []byte)
- func (m *SpectrumMemory) NextIssue() int
- func (m *SpectrumMemory) Read(address uint16) uint8
- func (m *SpectrumMemory) SetBootROM(data []byte)
- func (m *SpectrumMemory) SetNextIssue(issue int) error
- func (m *SpectrumMemory) SetNextLegacyBank7FFD(value uint8)
- func (m *SpectrumMemory) SetNextLegacyPortDFFD(value uint8)
- func (m *SpectrumMemory) SetNextSlot(slot int, page uint8)
- func (m *SpectrumMemory) SetPaging(value uint8)
- func (m *SpectrumMemory) SetPlus3Paging(value uint8)
- func (m *SpectrumMemory) SetROMBank(bank int, data []byte) error
- func (m *SpectrumMemory) Write(address uint16, value uint8)
- type SpectrumScreen
- type SymbolTable
- type Tape
- func (t *Tape) AttachFastLoader(fl *FastLoader)
- func (t *Tape) GetBlockInfo() []string
- func (t *Tape) GetStatus() string
- func (t *Tape) LoadFile(filename string) error
- func (t *Tape) Play()
- func (t *Tape) Rewind()
- func (t *Tape) SetMode(mode TapeMode)
- func (t *Tape) Stop()
- func (t *Tape) Tick(cycles int)
- type TapeBlock
- type TapeMode
- type TapeState
- type VideoRenderer
- type Z80CPU
- type ZenZX
- func (zx *ZenZX) AttachLink(l *Link)
- func (zx *ZenZX) AutoSave() error
- func (zx *ZenZX) AutorunBASIC(name, source, model string) error
- func (zx *ZenZX) AutorunFile(path, model string) error
- func (zx *ZenZX) AutorunPending() bool
- func (zx *ZenZX) AutorunTAP(name string, image []byte, model string) error
- func (zx *ZenZX) Debug() DebugView
- func (zx *ZenZX) DecodeDisplay() *image.RGBA
- func (zx *ZenZX) DumpNextState(w io.Writer)
- func (zx *ZenZX) EnableDivMMC(sdImage SDCardImage, sdSize int64, romImage []byte)
- func (zx *ZenZX) EnableZ80N()
- func (zx *ZenZX) FirstProgram() string
- func (zx *ZenZX) HandleInput()
- func (zx *ZenZX) InsertSecondCard(path string, readOnly bool) (protected bool, err error)
- func (zx *ZenZX) Link() *Link
- func (zx *ZenZX) Load128KROM(rom0Path, rom1Path string) error
- func (zx *ZenZX) Load128KROMBytes(data0, data1 []byte) error
- func (zx *ZenZX) LoadBIN(filename string, loadAddr uint16, startAddr int) error
- func (zx *ZenZX) LoadBINWithSafeReturn(filename string, loadAddr uint16, startAddr int) error
- func (zx *ZenZX) LoadPlus3ROM(rom0Path, rom1Path, rom2Path, rom3Path string) error
- func (zx *ZenZX) LoadPlus3ROMBytes(data0, data1, data2, data3 []byte) error
- func (zx *ZenZX) LoadROM(filename string) error
- func (zx *ZenZX) LoadROMBytes(data []byte) error
- func (zx *ZenZX) LoadSCR(filename string) error
- func (zx *ZenZX) LoadSNA(filename string) error
- func (zx *ZenZX) LoadSZX(filename string) error
- func (zx *ZenZX) LoadSnapshot(filename string) error
- func (zx *ZenZX) LoadSnapshotFormat(filename string, format string) error
- func (zx *ZenZX) LoadTS2068ROM(homePath, extPath string) error
- func (zx *ZenZX) LoadTS2068ROMBytes(home, ext []byte) error
- func (zx *ZenZX) LoadZ80(filename string) error
- func (zx *ZenZX) OverrideROMBank(bank int, path string) error
- func (zx *ZenZX) PlayStopTape()
- func (zx *ZenZX) PressKey(row, col uint8)
- func (zx *ZenZX) QuickLoad() error
- func (zx *ZenZX) QuickSave() error
- func (zx *ZenZX) ReleaseKey(row, col uint8)
- func (zx *ZenZX) RemoveSecondCard()
- func (zx *ZenZX) Render()
- func (zx *ZenZX) Reset()
- func (zx *ZenZX) RewindTape()
- func (zx *ZenZX) RunFrame()
- func (zx *ZenZX) RunTurboAwareFrame(blockedOnRealMemory bool)
- func (zx *ZenZX) SaveSNA(filename string) error
- func (zx *ZenZX) SaveSnapshot(filename string) error
- func (zx *ZenZX) SaveSnapshotFormat(filename string, format string) error
- func (zx *ZenZX) SaveZ80(filename string) error
- func (zx *ZenZX) SecondCard() string
- func (zx *ZenZX) SelectVideoRenderer(graphicsMode string) error
- func (zx *ZenZX) SetAYVolume(volume float32)
- func (zx *ZenZX) SetBeeperVolume(volume float32)
- func (zx *ZenZX) SetDisplay(d Display)
- func (zx *ZenZX) SetMasterVolume(volume float32)
- func (zx *ZenZX) ShowTapeInfo()
- func (zx *ZenZX) ToggleAudio()
- func (zx *ZenZX) TogglePause()
- func (zx *ZenZX) ToggleTapeMode()
- func (zx *ZenZX) TypeText(text string)
Constants ¶
const ( // Core audio parameters AudioSampleRate = 44100 // 44.1kHz sample rate AudioChannels = 1 // Mono AudioBufferSize = 512 // For raylib compatibility // Ring buffer size - smaller now for low latency // Must be power of 2 for efficient masking RingBufferSize = 16384 // ~370ms at 44100Hz RingBufferMask = RingBufferSize - 1 // 16383 RingBufferTarget = RingBufferSize / 2 // Target fill level )
const ( AudioFormat = oto.FormatFloat32LE OtoBufferSize = 512 // Samples per buffer (low latency) )
const ( // Display dimensions ScreenWidth = 256 ScreenHeight = 192 MaxMultiplier = 5 // Border dimensions in Spectrum pixels BorderLeft = 32 BorderRight = 32 BorderTop = 24 BorderBottom = 32 // Total display area including border TotalWidth = ScreenWidth + BorderLeft + BorderRight // 320 TotalHeight = ScreenHeight + BorderTop + BorderBottom // 248 // RefWidth/RefHeight (2026-09-15, T-29 GUI-wiring pass) are the // window's permanent client-area size whenever the standard 256x192 // video renderer is active, REPLACING TotalWidth/TotalHeight for // window-sizing purposes (TotalWidth/TotalHeight above are kept as // pure documentation of the classic screen+border geometry, still // read by nothing else in this codebase). The goal, per the tech team's own // framing: the window must never shapeshift just because a Next // program switches Layer 2 resolution mode at runtime -- only an // explicit user zoom (ScaleUp/ScaleDown/SetScale) changes the window // size. RefWidth stays 320 (TotalWidth unchanged: 320-wide Layer 2 // mode's own 320 columns already fit the classic border's total // width exactly, with zero horizontal margin left over in that mode). // RefHeight grows from TotalHeight's 248 to 256 -- the smallest value // that fits 320x256 mode's real 256 rows without cropping -- so it is // 8px taller than pre-existing classic-only window height. That 8px // is permanent, not conditional on Layer 2 being enabled: DisplayManager. // totalSize() (display.go) returns these constants unconditionally // for the standard renderer rather than switching between two frame // sizes depending on mode, which is what "never shapeshifts" requires. // The classic 256x192 picture's own border margins (BorderTop/Bottom // above) are consequently increased by 4px each (not 8 on one side) // to consume the extra height symmetrically -- see // DisplayManager.classicScreenOffset in display.go, which is the only // place that extra 4px top/bottom is actually applied; BorderTop/ // BorderBottom themselves are intentionally left unchanged here so // every other reader of those two constants (there are none outside // this file today, but the constants document real 1985 hardware // values and should keep meaning that) is unaffected. // // Non-standard renderers (e.g. hicolourVideoRenderer) do not use // RefWidth/RefHeight at all -- Layer 2/sprites only ever run // alongside the standard renderer in this codebase, so // DisplayManager.totalSize() falls back to its pre-existing // screenW/screenH+border computation for any other renderer, // unchanged. RefWidth = TotalWidth // 320 -- unchanged; already exact for 320-wide Layer 2 mode RefHeight = TotalHeight + 8 // 256 -- fits 320x256 mode's real height with 0 spare // Timing constants for border effects ScanlinesPerFrame = 312 CyclesPerScanline = 224 // ZX Spectrum Colors ZX_BLACK = 0 ZX_BLUE = 1 ZX_RED = 2 ZX_MAGENTA = 3 ZX_GREEN = 4 ZX_CYAN = 5 ZX_YELLOW = 6 ZX_WHITE = 7 ZX_BRIGHT = 1 ZX_DIM = 0 )
Shared display constants, raylib-free, compiled into both GUI and headless builds. The GUI renderer (display.go) and the headless framebuffer decoder (DecodeDisplay in zenzx.go) both depend on these.
const ( SectorsPerTrack = 9 BytesPerSector = 512 TracksPerSide = 40 Sides = 2 // Double-sided for +3 DiskImageSize = TracksPerSide * Sides * SectorsPerTrack * BytesPerSector // 180KB )
+3 Disk format constants
const ( LinkDataPort = 16384 LinkControlPort = 16385 )
The link: a byte channel between a machine and the world outside it.
A program on the machine sees two I/O ports. A program outside sees a TCP socket. Bytes written to the socket are handed to the machine one at a time through a four-step handshake that a BASIC program can keep up with; bytes the machine writes to its data port go out on the socket as they are.
data port IN: the byte being offered OUT: send a byte to the host control port IN: 0 idle, 1 ready, 2 taken OUT: bit 1 is the acknowledge
Receiving a byte, as the machine sees it:
- the control port reads 1: a byte is on the data port
- the machine reads the data port, then writes 3 to the control port
- the control port reads 2: the host has seen the acknowledge
- the machine writes 0 to the control port, which reads 0 again until the next byte is ready
The two ports are matched on all sixteen address bits and answered before anything else in the machine, the ULA and the 128K paging latch included. That matters with the default numbers, 16384 and 16385: on the hardware an even port is the ULA's and 16385 falls on the 128K's paging port. A machine with no link attached is not affected in any way.
const ( ROMSize = 16384 // 16KB RAMSize = 49152 // 48KB )
const ( NSGraphicsTimex001HiColour = "mode-timex-001-hicolour" // Extended Colour Mode: 256x192, 32x192 attribute resolution (8x1 blocks). See docs/timex-modes.md. NSGraphicsZenZX01 = "mode-zenzx-01" // 256x192, 3px/byte, linear framebuffer, no attribute clash NSGraphicsZenZX02 = "mode-zenzx-02" // 512x384, double resolution )
Recognised -ns-graphics values. Timex/SCLD modes are numbered (mode-timex-NNN-name); further ones (hi-res, dual-screen -- see docs/timex-modes.md) may be added under the same scheme once designed. Only hi-colour is implemented as a flag value so far.
const ( // Magic header for ZenZX snapshots SnapshotMagic = "ZENZX" // Version numbers SnapshotVersion1 = 1 // Initial version SnapshotVersion2 = 2 // Added +3 FDC state SnapshotVersion3 = 3 // Added JSON metadata CurrentSnapshotVersion = SnapshotVersion3 // Chunk IDs ChunkCPU = 0x4350 // "CP" - CPU state ChunkMem48 = 0x4D34 // "M4" - 48K memory ChunkMem128 = 0x4D31 // "M1" - 128K memory banks ChunkMemPlus3 = 0x4D33 // "M3" - +3 memory banks ChunkScreen = 0x5343 // "SC" - Screen state ChunkIO = 0x494F // "IO" - I/O state ChunkPaging = 0x5047 // "PG" - Memory paging state ChunkFDC = 0x4644 // "FD" - FDC state (+3 only) ChunkDisk = 0x4453 // "DS" - Disk image (+3 only) ChunkAudio = 0x4155 // "AU" - Audio state ChunkEnd = 0x454E // "EN" - End marker )
const ( FlagCompressed = 1 << 0 // Data chunks are gzip compressed Flag128K = 1 << 1 // 128K model FlagPlus3 = 1 << 2 // +3 model with 4 ROM banks FlagFDC = 1 << 3 // FDC present and active FlagDiskPresent = 1 << 4 // Disk image included FlagHasMetadata = 1 << 5 // JSON metadata file exists )
SnapshotFlags bit definitions
const ( // Timing -- these remain the package-level PAL defaults, used as-is // by every model except TS2068. Genuinely per-instance timing lives // on ZenZX (cyclesPerFrame/interruptLength below), defaulting to // these values at construction and overridden only by // LoadTS2068ROM. CPUFrequency/FramesPerSecond stay global constants // deliberately, not yet threaded per-instance: TS2068 audio (Stage // 4, AY ports) isn't implemented yet, so nothing currently reads // them expecting TS2068's real 3.528MHz/60.1145Hz -- revisit when // Stage 4 lands, since AY pitch generation genuinely needs the true // clock. See docs/TS2068_DEVELOPMENT_PLAN.md Stage 2. CPUFrequency = 3500000 // 3.5 MHz FramesPerSecond = 50 // 50 Hz PAL nominal CyclesPerFrame = CPUFrequency / FramesPerSecond // 70000 -- the naive 3.5MHz/50Hz figure. Real PAL frames are ULAFrameCycles, giving the authentic ~50.08Hz; this remains only as display code's pre-first-frame fallback. ULAFrameCycles = 69888 // real interrupt-to-interrupt frame: 224 T-states x 312 lines (WoS FAQ; libspectrum agrees) InterruptLength = 32 // T-states the ULA holds /INT low at the top of each frame )
const BootTolerance = 0.05
BootTolerance is the fractional band applied to a baseline frame when used as a regression guard (+-5%).
const CustomROMDir = "custom-roms"
CustomROMDir is the default location scanned by -custom-roms-menu. Intended for language-translated and other alternate ROM variants for international users -- distinct from rom/, which holds the standard, embedded set (embedded_roms.go).
const MemoryPageCount = 12
const (
NSStoragePosix = "storage-zenzx-posix"
)
Recognised -ns-storage values.
const NextFrameCycles = 311 * 228
NextFrameCycles is a Next's frame: 311 lines of 228 T-states, the 128K machines' timing that the Next has at 50 Hz. The line counter, the copper and the line interrupt count those 311 lines.
Variables ¶
var ZXPaletteRGBA = []rl.Color{ rl.NewColor(0x00, 0x00, 0x00, 0xff), rl.NewColor(0x00, 0x00, 0xc8, 0xff), rl.NewColor(0xc8, 0x00, 0x00, 0xff), rl.NewColor(0xc8, 0x00, 0xc8, 0xff), rl.NewColor(0x00, 0xc8, 0x00, 0xff), rl.NewColor(0x00, 0xc8, 0xc8, 0xff), rl.NewColor(0xc8, 0xc8, 0x00, 0xff), rl.NewColor(0xc8, 0xc8, 0xc8, 0xff), rl.NewColor(0x00, 0x00, 0x00, 0xff), rl.NewColor(0x00, 0x00, 0xff, 0xff), rl.NewColor(0xff, 0x00, 0x00, 0xff), rl.NewColor(0xff, 0x00, 0xff, 0xff), rl.NewColor(0x00, 0xff, 0x00, 0xff), rl.NewColor(0x00, 0xff, 0xff, 0xff), rl.NewColor(0xff, 0xff, 0x00, 0xff), rl.NewColor(0xff, 0xff, 0xff, 0xff), }
Functions ¶
func BasicTape ¶
BasicTape tokenises BASIC source text and returns a .tap image holding it as one program, named name, that runs from its first line when loaded.
func CompositeLayer2 ¶
CompositeLayer2 blends a Layer 2 image over (or under) a ULA image per layer2ULAOnTop, producing the final on-screen picture. Both images must already be layer2Width x layer2Height (== ScreenWidth x ScreenHeight -- the two constants are numerically identical but named separately per-layer since Layer 2's wider modes will one day diverge from the ULA's fixed 256x192). ula is never mutated -- a fresh image is returned -- so a caller holding onto the ULA-only image for another purpose (screenshot diffing, etc.) is unaffected.
Transparent Layer 2 pixels (outside the clip window, alpha 0 -- see DecodeLayer2) always show the ULA pixel beneath them regardless of ulaOnTop, matching real hardware: the clip window controls where Layer 2 draws at all, independent of the separate priority-ordering question of which layer wins where both would otherwise draw.
func CompositeNextLayers ¶
CompositeNextLayers blends ULA, Layer 2, and sprite images together per nextLayerOrder, producing the final on-screen picture -- the sprite- aware successor to CompositeLayer2 (kept as-is for its own existing callers/tests; this function is DecodeDisplay's new entry point once sprites exist). l2 and sprites may each be nil (Layer 2 disabled, sprite layer disabled) -- a nil layer is treated as fully transparent everywhere, exactly like an all-transparent image would be, so passing nil rather than constructing a throwaway blank image is both cheaper and matches DecodeLayer2/DecodeSprites' own "return nil when disabled" convention. ula must never be nil -- there is always a base ULA image.
Composites bottom-to-top per pixel: each layer in nextLayerOrder either overwrites the running result with its own opaque pixel, or leaves the result untouched where it's transparent -- so the last opaque layer in the order wins, matching "topmost wins every overlap". ULA itself is always treated as fully opaque (it is the base image, never a transparent one), so it always sets the result when its turn comes.
func CountAttrMatches ¶
CountAttrMatches returns how many cells in the given row range (inclusive) satisfy the predicate. rowStart/rowEnd of -1 mean the whole screen.
func DetectSnapshotFormat ¶
DetectSnapshotFormat detects the format of a snapshot file
func InitDisplay ¶
func InitDisplay(scale int, showBorder bool, renderer VideoRenderer) (int, int)
InitDisplay creates the window sized for renderer's own dimensions and border margins (not the hardcoded standard 256x192 -- see videorender.go), then clamps the requested scale down if it wouldn't fit the current monitor (point 3, 2026-08-17). For the standard renderer specifically, the window's client area is the fixed reference canvas (RefWidth, RefHeight -- display_constants.go, 2026-09-15 T-29 GUI-wiring pass) rather than screenW/screenH+border, matching DisplayManager.totalSize's own logic exactly (this free function runs before a usable DisplayManager exists, so it can't just call totalSize() -- see this project's zenzx_gui.go call site comment on why renderer resolution happens before InitDisplay), so the very first window drawn already has room for Layer 2's wider modes without an initial-frame resize.
func ListSnapshots ¶
ListSnapshots lists all snapshot files in a directory
func ParseAddrSigned ¶
ParseAddrSigned parses an address like ParseAddr, but accepts -1 to mean "leave PC unchanged". Returns -1 for that case, otherwise the address.
func ReadScreen ¶
ReadScreen recognises the whole display into 24 rows of text.
func ReadScreenRow ¶
ReadScreenRow recognises a full character row (0-23) into a string. Cells that match no glyph are rendered as '?'.
func RegisterVideoRenderer ¶
func RegisterVideoRenderer(r VideoRenderer)
RegisterVideoRenderer adds a renderer to the registry, keyed by its own Name(). Panics on a duplicate name: two renderers claiming the same -ns-graphics value is always a programming error, not a runtime condition, and failing fast at init() time (rather than silently letting the second registration win) is safer than discovering it via a wrong picture at run time.
func ResolveROMBytes ¶
ResolveROMBytes returns the bytes of a named ROM, looking in romDir on disk first and falling back to the copy embedded in the binary. It is the exported form of the package's own ROM resolution, for embedders (such as the zendbg CLI) that build a machine and need its ROM without reaching into the package internals.
func RunGUI ¶
func RunGUI(args []string)
RunGUI is the ZenZX program with its window: it parses args (the command line without the program's name), runs until the window is closed, and exits the process on a bad argument. cmd/zenzx is this and nothing else.
func SetLogOutput ¶
SetLogOutput sets where the machine's messages go; nil discards them. It is meant to be called once, before any machine runs.
func SetTraceOutput ¶
SetTraceOutput sets where traces and warnings go; nil discards them. Like SetLogOutput it is meant to be called once, before any machine runs.
Types ¶
type AYChip ¶
type AYChip struct {
// contains filtered or unexported fields
}
func (*AYChip) GenerateSamples ¶
GenerateSamples generates audio samples for the given number of CPU cycles
func (*AYChip) ReadRegister ¶
ReadRegister reads a value from an AY register
func (*AYChip) WriteRegister ¶
WriteRegister writes a value to an AY register
type Action ¶
type Action struct {
Frame int // absolute frame offset from boot (>= 0)
Verb string // canonical verb, lower-case
Args []string // raw positional arguments after the verb
Line int // 1-based source line number, for diagnostics
}
Action is a single scheduled instruction parsed from a .zen file.
type AudioBackend ¶
type AudioBackend int
AudioBackend represents which audio system to use
const (
AudioBackendOto AudioBackend = iota
)
type AudioDevice ¶
AudioDevice plays what an AudioEngine produces. Open is given the engine as a reader of float32 little-endian mono samples at AudioSampleRate and starts pulling from it; Close stops. A device may be opened again after Close.
func NewOtoAudioDevice ¶
func NewOtoAudioDevice() AudioDevice
NewOtoAudioDevice returns a device that plays through the sound card.
type AudioEngine ¶
type AudioEngine struct {
// contains filtered or unexported fields
}
func NewAudioEngine ¶
func NewAudioEngine() *AudioEngine
NewAudioEngine makes an engine with sound on and no device.
func (*AudioEngine) Close ¶
func (am *AudioEngine) Close()
func (*AudioEngine) GetAY ¶
func (am *AudioEngine) GetAY() *AYChip
GetAY returns the AY chip instance
func (*AudioEngine) GetBufferStatus ¶
func (am *AudioEngine) GetBufferStatus() (level float32, samples int, requested int)
GetBufferStatus returns the current buffer level and health
func (*AudioEngine) GetDebugInfo ¶
func (am *AudioEngine) GetDebugInfo() (speakerChanges int, cpuCycle uint64)
GetDebugInfo returns additional debug information
func (*AudioEngine) Initialize ¶
func (am *AudioEngine) Initialize() error
func (*AudioEngine) IsEnabled ¶
func (am *AudioEngine) IsEnabled() bool
IsEnabled returns whether audio is enabled
func (*AudioEngine) Read ¶
func (am *AudioEngine) Read(buf []byte) (int, error)
Read implements io.Reader for the AudioDevice Keep this SIMPLE and STABLE
func (*AudioEngine) SetAYVolume ¶
func (am *AudioEngine) SetAYVolume(volume float32)
SetAYVolume sets the AY chip volume (0.0 to 1.0)
func (*AudioEngine) SetAudioFilter ¶
func (am *AudioEngine) SetAudioFilter(on bool)
SetAudioFilter enables or disables the output anti-alias filtering (DC blocker + lowpass). On by default; disabling yields the raw duty-cycle output for comparison or for a deliberately harsher sound.
func (*AudioEngine) SetBeeperVolume ¶
func (am *AudioEngine) SetBeeperVolume(volume float32)
SetBeeperVolume sets the beeper volume (0.0 to 1.0)
func (*AudioEngine) SetDevice ¶
func (am *AudioEngine) SetDevice(d AudioDevice)
SetDevice sets where the engine's sound goes. It is meant to be called before Initialize; nil leaves the engine silent.
func (*AudioEngine) SetEnabled ¶
func (am *AudioEngine) SetEnabled(enabled bool)
SetEnabled enables or disables audio
func (*AudioEngine) SetMasterVolume ¶
func (am *AudioEngine) SetMasterVolume(volume float32)
SetMasterVolume sets the master volume (0.0 to 1.0)
func (*AudioEngine) UpdateCPUCycle ¶
func (am *AudioEngine) UpdateCPUCycle(cycles uint64)
UpdateCPUCycle updates the current CPU cycle count
func (*AudioEngine) UpdateSpeaker ¶
func (am *AudioEngine) UpdateSpeaker(speaker bool, cycles uint64)
UpdateSpeaker records a speaker state change with cycle-accurate timing
type AudioInterface ¶
type AudioInterface interface {
Initialize() error
Close()
UpdateSpeaker(speaker bool, cycles uint64)
UpdateCPUCycle(cycles uint64)
GetBufferStatus() (level float32, samples int, requested int)
GetDebugInfo() (speakerChanges int, cpuCycle uint64)
SetMasterVolume(volume float32)
SetBeeperVolume(volume float32)
SetAYVolume(volume float32)
SetEnabled(enabled bool)
IsEnabled() bool
GetAY() *AYChip
}
AudioInterface defines the common interface for audio managers
type AudioMetadata ¶
type AudioMetadata struct {
Enabled bool `json:"enabled"`
MasterVolume float32 `json:"master_volume"`
BeeperVolume float32 `json:"beeper_volume"`
AYVolume float32 `json:"ay_volume"`
Speaker bool `json:"speaker"`
AYRegisters []string `json:"ay_registers,omitempty"`
}
AudioMetadata contains audio state for metadata
type AudioState ¶
type AudioState struct {
BeeperLevel bool
AYRegisters [16]uint8
MasterVolume float32
BeeperVolume float32
AYVolume float32
AudioEnabled bool
}
AudioState contains audio subsystem state
type AudioWrapper ¶
type AudioWrapper struct {
// contains filtered or unexported fields
}
AudioWrapper wraps either raylib or Oto audio implementation
func NewAudioWrapper ¶
func NewAudioWrapper(backend AudioBackend) *AudioWrapper
NewAudioWrapper creates a new audio wrapper with the specified backend
func (*AudioWrapper) GetAYVolume ¶
func (aw *AudioWrapper) GetAYVolume() float32
func (*AudioWrapper) GetBeeperVolume ¶
func (aw *AudioWrapper) GetBeeperVolume() float32
func (*AudioWrapper) GetBufferStatus ¶
func (aw *AudioWrapper) GetBufferStatus() (level float32, samples int, requested int)
GetBufferStatus returns buffer status
func (*AudioWrapper) GetDebugInfo ¶
func (aw *AudioWrapper) GetDebugInfo() (speakerChanges int, cpuCycle uint64)
GetDebugInfo returns debug info
func (*AudioWrapper) GetMasterVolume ¶
func (aw *AudioWrapper) GetMasterVolume() float32
Direct property access helpers for compatibility
func (*AudioWrapper) Initialize ¶
func (aw *AudioWrapper) Initialize() error
Initialize initializes the audio system
func (*AudioWrapper) IsEnabled ¶
func (aw *AudioWrapper) IsEnabled() bool
IsEnabled returns if audio is enabled
func (*AudioWrapper) ReadAYRegister ¶
func (aw *AudioWrapper) ReadAYRegister(reg uint8) uint8
ReadAYRegister reads from AY register with proper locking
func (*AudioWrapper) SetAYVolume ¶
func (aw *AudioWrapper) SetAYVolume(volume float32)
SetAYVolume sets AY chip volume
func (*AudioWrapper) SetBeeperVolume ¶
func (aw *AudioWrapper) SetBeeperVolume(volume float32)
SetBeeperVolume sets beeper volume
func (*AudioWrapper) SetDevice ¶
func (aw *AudioWrapper) SetDevice(d AudioDevice)
SetDevice sets where the machine's sound goes; see AudioEngine.SetDevice.
func (*AudioWrapper) SetEnabled ¶
func (aw *AudioWrapper) SetEnabled(enabled bool)
SetEnabled enables/disables audio
func (*AudioWrapper) SetMasterVolume ¶
func (aw *AudioWrapper) SetMasterVolume(volume float32)
SetMasterVolume sets master volume
func (*AudioWrapper) UpdateCPUCycle ¶
func (aw *AudioWrapper) UpdateCPUCycle(cycles uint64)
UpdateCPUCycle updates CPU cycle count
func (*AudioWrapper) UpdateSpeaker ¶
func (aw *AudioWrapper) UpdateSpeaker(speaker bool, cycles uint64)
UpdateSpeaker updates speaker state
func (*AudioWrapper) WriteAYRegister ¶
func (aw *AudioWrapper) WriteAYRegister(reg, value uint8)
WriteAYRegister writes to AY register with proper locking
type BandLimitedInterpolator ¶
type BandLimitedInterpolator struct {
// contains filtered or unexported fields
}
BandLimitedInterpolator provides high-quality arbitrary rate conversion
func NewBandLimitedInterpolator ¶
func NewBandLimitedInterpolator(oversampleFactor, sincTaps int) *BandLimitedInterpolator
NewBandLimitedInterpolator creates a new interpolator oversampleFactor: internal oversampling (higher = better quality, more CPU) sincTaps: number of sinc taps (8-64 typical)
func (*BandLimitedInterpolator) Interpolate ¶
func (bli *BandLimitedInterpolator) Interpolate(samples []float32, fraction float32) float32
Interpolate performs band-limited interpolation at fractional position samples: input samples around the interpolation point fraction: fractional position (0-1) between samples
type BiquadFilter ¶
type BiquadFilter struct {
// contains filtered or unexported fields
}
BiquadFilter implements a second-order IIR filter
func NewLowpassBiquad ¶
func NewLowpassBiquad(sampleRate, cutoff, q float32) *BiquadFilter
NewLowpassBiquad creates a lowpass biquad filter sampleRate: sample rate in Hz cutoff: cutoff frequency in Hz q: quality factor (0.707 for Butterworth)
func (*BiquadFilter) Process ¶
func (bf *BiquadFilter) Process(input float32) float32
Process applies the biquad filter to a sample
type BootDetector ¶
type BootDetector struct {
// contains filtered or unexported fields
}
BootDetector tracks boot progress across frames. Construct one with the model's rainbow expectation, call Update(zx) once per emulated frame (after RunFrame), and check Ready().
Readiness is "the last content change was at least stableConfirmFrames ago" -- i.e. the screen has held steady through a confirmation window. This correctly skips the transient boot-animation plateaus, which are each followed by further changes. Rainbow-expecting models additionally require the menu's rainbow band to have appeared, so that the intermediate clear the +3 shows before its FDC drive check completes is not mistaken for the finished menu.
func NewBootDetector ¶
func NewBootDetector(expectRainbow bool) *BootDetector
NewBootDetector returns a detector. Set expectRainbow true for the 128/+2/+3 models, whose startup menu paints a rainbow band; false for the 48K family and the older Investronica Spanish 128K, which have none.
func (*BootDetector) Ready ¶
func (d *BootDetector) Ready() bool
Ready reports whether boot has completed.
func (*BootDetector) ReadyFrame ¶
func (d *BootDetector) ReadyFrame() int
ReadyFrame returns the frame of the last content change before the screen settled into its ready state, or -1 if not yet ready.
func (*BootDetector) Update ¶
func (d *BootDetector) Update(zx *ZenZX)
Update advances the detector by one frame. It must be called once per emulated frame, after zx.RunFrame().
type BorderChange ¶
type BorderChange struct {
Cycle uint64 // CPU cycle when change occurred
Color uint8 // New border color (0-7)
}
BorderChange records a border color change at a specific cycle
type BorderHistory ¶
type BorderHistory struct {
// contains filtered or unexported fields
}
BorderHistory tracks border changes for current frame
func NewBorderHistory ¶
func NewBorderHistory() *BorderHistory
NewBorderHistory creates a border change tracker
func (*BorderHistory) Clear ¶
func (bh *BorderHistory) Clear()
Clear resets the history for a new frame
func (*BorderHistory) GetChanges ¶
func (bh *BorderHistory) GetChanges() []BorderChange
GetChanges returns the border changes for the current frame
func (*BorderHistory) Record ¶
func (bh *BorderHistory) Record(cycle uint64, color uint8)
Record adds a border change at the current cycle
type CPUMetadata ¶
type CPUMetadata struct {
PC string `json:"pc"`
SP string `json:"sp"`
AF string `json:"af"`
BC string `json:"bc"`
DE string `json:"de"`
HL string `json:"hl"`
IX string `json:"ix"`
IY string `json:"iy"`
I string `json:"i"`
R string `json:"r"`
IFF1 bool `json:"iff1"`
IFF2 bool `json:"iff2"`
IM int `json:"im"`
Halted bool `json:"halted"`
Cycles uint64 `json:"cycles"`
}
CPUMetadata contains CPU state for debugging
type CPUState ¶
type CPUState struct {
// Main registers
AF, BC, DE, HL uint16
// Alternate registers
AF_, BC_, DE_, HL_ uint16
// Index registers
IX, IY uint16
// Special registers
SP, PC, WZ uint16
I, R uint8
// Interrupt state
IFF1, IFF2 bool
IM uint8
Halted bool
// Timing
Cycles uint64
// Additional state
INT bool // Current INT line state
NMI bool // Current NMI state
NMIEdge bool // NMI edge detection
}
CPUState contains all Z80 registers and state
type CPUWrapper ¶
type CPUWrapper struct {
// contains filtered or unexported fields
}
CPUWrapper wraps the Z80 CPU to implement the Z80CPU interface
func (*CPUWrapper) GetCycles ¶
func (cw *CPUWrapper) GetCycles() uint64
type ChunkHeader ¶
type ChunkHeader struct {
ID uint16 // Chunk identifier
Size uint32 // Size of chunk data (excluding header)
}
ChunkHeader precedes each data chunk
type DCBlocker ¶
type DCBlocker struct {
// contains filtered or unexported fields
}
DCBlocker removes DC offset from audio signal
func NewDCBlocker ¶
NewDCBlocker creates a new DC blocking filter cutoff: highpass cutoff frequency (typically 20-40 Hz) sampleRate: sample rate in Hz
type DebugSnapshot ¶
type DebugSnapshot struct {
// contains filtered or unexported fields
}
DebugSnapshot provides detailed debugging information for snapshots
func NewDebugSnapshot ¶
func NewDebugSnapshot(zx *ZenZX) *DebugSnapshot
NewDebugSnapshot creates a new snapshot debugger
func (*DebugSnapshot) AnalyzeCPUState ¶
func (ds *DebugSnapshot) AnalyzeCPUState()
AnalyzeCPUState prints detailed CPU state analysis
func (*DebugSnapshot) AnalyzeMemoryState ¶
func (ds *DebugSnapshot) AnalyzeMemoryState()
AnalyzeMemoryState prints memory configuration analysis
func (*DebugSnapshot) AnalyzeRRegister ¶
func (ds *DebugSnapshot) AnalyzeRRegister()
AnalyzeRRegister investigates the R register behavior
func (*DebugSnapshot) CheckROMLocation ¶
func (ds *DebugSnapshot) CheckROMLocation()
CheckROMLocation checks what's at the current PC in ROM
func (*DebugSnapshot) CheckStackContents ¶
func (ds *DebugSnapshot) CheckStackContents()
CheckStackContents examines what's on the stack
func (*DebugSnapshot) RunFullDiagnostics ¶
func (ds *DebugSnapshot) RunFullDiagnostics()
RunFullDiagnostics runs all diagnostic tests
func (*DebugSnapshot) TestEndianness ¶
func (ds *DebugSnapshot) TestEndianness()
TestEndianness verifies that 16-bit values are saved correctly
type DebugView ¶
type DebugView struct {
// contains filtered or unexported fields
}
DebugView is the narrow, embedder-facing handle a debugger attaches to a running machine. It is the T-39 machine facade's debugging seam and nothing more: enough to read and write the CPU's registers and the machine's memory, to single-step, and to observe each instruction fetch, without exposing the whole ZenZX internals or letting a debugger disturb the emulation's own wiring.
A DebugView is a value that borrows the live machine; it holds no state of its own. Driving execution through it (Step) advances the same CPU the host's RunFrame drives, so a debugger and the normal frame loop act on one machine, never on a copy.
Multiple machines: the per-instruction fetch seam (SetFetchHook) wraps the package-global z80.DebugPCHook, which is shared across every z80.Z80 in the process. For a single standalone machine that is exact. An ensemble of machines must not rely on it; a debugger over several machines drives each one's Step directly instead, which needs no global hook. See docs/proposals/workbench.md (several machines) and zen80's DebugPCHook.
func (DebugView) ReadMem ¶
ReadMem copies n bytes from the machine's memory starting at addr, wrapping the 16-bit address space. It reads through the same SpectrumMemory the CPU uses, so it sees the current paging.
func (DebugView) SetFetchHook ¶
SetFetchHook installs a function called with the PC at the top of every Step, before the instruction executes, or clears it when hook is nil. It wraps zen80's unconditional DebugPCHook (not the DEBUG_M1-gated M1Hook), so it fires whatever the build's tracing flags are.
The hook is process-global in zen80, so this is for a single machine. A debugger that drives Step itself in a loop (checking PC after each) needs no hook and is the path the ensemble case must take.
func (DebugView) SetReg ¶
SetReg writes a register or register pair. An 8-bit register ignores the high byte of value. It reports whether name was recognised.
func (DebugView) Step ¶
Step executes one instruction and returns the T-states it took. PC, the registers and the cycle count advance as they do in normal running; only the caller, not the frame loop, decides when the next instruction runs.
type Disk ¶
type Disk struct {
NumTracks uint8
NumSides uint8
Extended bool
Tracks []DiskTrack // indexed track-major: idx = track*NumSides + side
Modified bool
}
Disk is a parsed DSK image.
func (*Disk) FindSector ¶
func (d *Disk) FindSector(track, side, r uint8) *DiskSector
FindSector locates a sector by its physical track/side and record ID (R). It returns a pointer into the disk's data so writes are reflected. Returns nil if no such sector exists.
type DiskSector ¶
type DiskSector struct {
C, H, R, N uint8 // cylinder, head, record (sector ID), size code
ST1, ST2 uint8 // FDC status register 1/2 as recorded in the image
Data []byte // sector contents
}
DiskSector is one sector: its CHRN address, recorded FDC status bytes, and data. SizeCode is the N value (actual bytes = 128 << N).
type DiskTrack ¶
type DiskTrack struct {
Track, Side uint8
SizeCode uint8 // track-level sector size code
GapLength uint8
Filler uint8
Sectors []DiskSector
}
DiskTrack is one physical track: its number/side and ordered sector list.
type Display ¶
type Display interface {
// Render draws the current frame.
Render(paused bool, mem *SpectrumMemory, screen *SpectrumScreen, io *SpectrumIO)
// SetBorderChanges hands over the finished frame's border history.
SetBorderChanges(changes []BorderChange, frameOrigin uint64, cyclesPerFrame int)
// UpdateWindowSize is called once a frame, before Render.
UpdateWindowSize()
// SetAudioManager, SetSpectrumIO and SetVideoRenderer tell the display
// about the machine it is showing; SetDisplay calls all three.
SetAudioManager(audio *AudioWrapper)
SetSpectrumIO(io *SpectrumIO)
SetVideoRenderer(r VideoRenderer)
}
Display is what the machine asks of whatever shows its picture.
type DisplayManager ¶
type DisplayManager struct {
// contains filtered or unexported fields
}
============================================================================ Display Manager ============================================================================
func NewDisplayManager ¶
func NewDisplayManager(screen *SpectrumScreen) *DisplayManager
func (*DisplayManager) CleanupTextures ¶
func (dm *DisplayManager) CleanupTextures()
CleanupTextures should be called before closing the window.
func (*DisplayManager) GetCurrentSize ¶
func (dm *DisplayManager) GetCurrentSize() (int, int)
func (*DisplayManager) InitializeAfterWindow ¶
func (dm *DisplayManager) InitializeAfterWindow()
InitializeAfterWindow creates the border texture, sized to the active renderer's geometry. The screen texture is created lazily on the first Render call, once there is an actual decoded image to size it from.
func (*DisplayManager) IsBorderStripesEnabled ¶
func (dm *DisplayManager) IsBorderStripesEnabled() bool
func (*DisplayManager) MinMultiplierForMode ¶
func (dm *DisplayManager) MinMultiplierForMode() int
minMultiplierForMode returns the smallest zoom multiplier the active Layer 2 mode allows. Every mode except 640x256x4bpp allows 1x.
CORRECTED reasoning (2026-09-15): an earlier draft of this comment claimed 640-mode's 640 real columns "exceed the fixed 320-column reference canvas at 1x" and would force cropping or window growth -- wrong, and contradicted by an exact wiki.specnext.dev/ Layer_2_Control_Register quote found while double-checking the tech team's own stated design against it: "every byte is displayed as two half-width paired pixels". 640-mode's pixels are HALF the physical width of a normal pixel, so 640 of them occupy exactly the SAME picture width as 320-mode's own 320 full-width pixels -- confirmed by layer2PixelWidthScale/layer2DisplayedSize (layer2.go), which is what nextLayersViewportOffset actually centres against. There is no canvas-overflow problem at any multiplier, including 1x.
The real (and much narrower) reason 1x is still refused: a half-width pixel at multiplier m draws at m/2 screen pixels wide. That is a whole number only when m is even (m=2 -> 1px, m=4 -> 2px); at m=1 it is 0.5px, which can't render as a clean, sharp pixel edge. Refusing 1x catches the worst case cheaply. It does NOT catch every case -- m=3 (1.5px) is still allowed by this gate and still renders with sub-pixel blur; fully solving that would mean restricting 640-mode to only even multipliers (skipping 3 during ScaleUp/ScaleDown, not just flooring at 2), which this pass does not implement -- a known, minor, documented cosmetic limitation rather than an invented claim of full precision.
Returns 1 (no gate) when dm.io is nil -- headless/classic-machine callers, and any test that hasn't called SetSpectrumIO.
func (*DisplayManager) Render ¶
func (dm *DisplayManager) Render(paused bool, mem *SpectrumMemory, screen *SpectrumScreen, io *SpectrumIO)
Render draws the current frame: the active VideoRenderer's output, composited with the border texture if the active renderer has a border and it is currently shown. If the active renderer implements FastGUIRenderer, it draws directly via pre-baked, GPU-resident textures (videorender_gpu.go) -- no CPU-side image.RGBA is built and no texture is re-uploaded that frame. Otherwise mem/screen are decoded once here and the result uploaded to a single texture, exactly as before. Every mode draws through this one path; nothing here is standard-Spectrum-specific.
The io parameter (T-29/T-30) is used by renderNextLayersGPU (videorender_gpu.go) to draw Layer 2 and/or the sprite layer as ADDITIONAL passes after the ULA layer above, in the correct relative order for the current NR 0x15 priority (layersAboveULA, layer2.go) -- neither Layer 2 nor sprites are themselves a VideoRenderer, and neither takes over this function's existing fast/slow-path branching. renderNextLayersGPU draws nothing extra on every classic machine and on a Next machine that hasn't enabled Layer 2 or sprites, so this parameter changes no existing behaviour by itself.
func (*DisplayManager) ScaleDown ¶
func (dm *DisplayManager) ScaleDown() bool
func (*DisplayManager) ScaleUp ¶
func (dm *DisplayManager) ScaleUp() bool
func (*DisplayManager) SetAudioManager ¶
func (dm *DisplayManager) SetAudioManager(audio *AudioWrapper)
func (*DisplayManager) SetBorderChanges ¶
func (dm *DisplayManager) SetBorderChanges(changes []BorderChange, frameOrigin uint64, cyclesPerFrame int)
func (*DisplayManager) SetBorderColor ¶
func (dm *DisplayManager) SetBorderColor(color uint8)
func (*DisplayManager) SetInitialSize ¶
func (dm *DisplayManager) SetInitialSize(width, height int)
func (*DisplayManager) SetPreEndDrawHook ¶
func (dm *DisplayManager) SetPreEndDrawHook(fn func())
SetPreEndDrawHook installs fn to run at the end of every future Render call, still inside the BeginDrawing/EndDrawing bracket. Pass nil to remove a previously-installed hook.
func (*DisplayManager) SetReservedTopHeight ¶
func (dm *DisplayManager) SetReservedTopHeight(h int)
SetReservedTopHeight sets how much extra window-pixel space at the top is reserved for a fixed menu bar (0 to release it), then triggers the same animated resize toggling the border already uses -- the window grows or shrinks to accommodate the change rather than jumping to it instantly. A no-op if the value isn't actually changing, matching ToggleBorder's own "don't animate to where you already are" behaviour.
func (*DisplayManager) SetScale ¶
func (dm *DisplayManager) SetScale(n int) bool
SetScale sets the display multiplier directly to n, if n is within [minMultiplierForMode(), maxMultiplierThatFits()] -- returns false and does nothing otherwise. Used by the View menu's zoom items (X1/X2/X3), which jump straight to a specific scale rather than stepping one at a time the way ScaleUp/ScaleDown do.
func (*DisplayManager) SetSpectrumIO ¶
func (dm *DisplayManager) SetSpectrumIO(io *SpectrumIO)
SetSpectrumIO stores io for maxMultiplierThatFits/SetScale's 640x256 minimum-zoom clamp -- see the io field's own doc comment above for why this is a stored reference rather than a parameter on those methods. Safe to call at any point, including before InitializeAfterWindow; nil is a valid value (restores the pre-T-29 "no Layer 2 gate" behaviour).
func (*DisplayManager) SetSpriteGPUCacheCapacity ¶
func (dm *DisplayManager) SetSpriteGPUCacheCapacity(capacity int)
SetSpriteGPUCacheCapacity changes the sprite GPU texture cache's (spriteGPUCache, videorender_gpu.go) capacity at runtime -- the "buffer size configurable" knob from T-30's own design direction. Shrinking evicts least-recently-used entries immediately; growing just raises the ceiling for future insertions. Safe to call before InitializeAfterWindow (the cache itself is constructed by NewDisplayManager, independent of the GL context bitPatternGPU/ paperColourGPU need) and at any point during a running session.
func (*DisplayManager) SetVideoRenderer ¶
func (dm *DisplayManager) SetVideoRenderer(r VideoRenderer)
SetVideoRenderer updates the cached geometry DisplayManager draws from. Both front ends resolve -ns-graphics and call this before the window (and therefore the GPU textures) exist, so sizing always reflects the right renderer from the start; this does not support switching renderers after InitializeAfterWindow has run.
func (*DisplayManager) ToggleBorder ¶
func (dm *DisplayManager) ToggleBorder()
func (*DisplayManager) ToggleBorderStripes ¶
func (dm *DisplayManager) ToggleBorderStripes()
func (*DisplayManager) ToggleDebugOverlay ¶
func (dm *DisplayManager) ToggleDebugOverlay()
func (*DisplayManager) ToggleFPS ¶
func (dm *DisplayManager) ToggleFPS()
func (*DisplayManager) UpdateWindowSize ¶
func (dm *DisplayManager) UpdateWindowSize()
type DivMMC ¶
type DivMMC struct {
// Debug, when true, logs automap trigger/exit transitions and
// every 0xE3 control-register write to stderr -- off by default,
// no behaviour change unless a caller sets it (zenzx_headless.go/
// zenzx_gui.go's -divmmc-debug flag, which also sets sd.Debug).
Debug bool
// contains filtered or unexported fields
}
DivMMC models the ZX Spectrum Next's built-in DivMMC interface: the automap/CONMEM memory-paging logic behind IO port 0xE3, layered on top of the SD-over-SPI transport in sdcard.go (ports 0xE7/0xEB). Part of T-36's Tier 2 boot chain (docs/TRACKING.md, docs/NEXT_SUPPORT_DEVELOPMENT_PLAN.md).
What this does NOT model: the FPGA's own separate "config mode" boot ROM (docs/NEXT_BOOT_REFERENCE.md stage 1's "nextboot.rom", gated by NextREG 0x03's boot-rom-enable bit) is a distinct mechanism from DivMMC's own automap ROM below -- real hardware runs the config-mode boot ROM BEFORE any classic-compatible personality (and DivMMC's own automap addressing) is even active. That remains a separate, unstarted gap (NEXT_SUPPORT_DEVELOPMENT_PLAN.md Tier 2 item 6, "NR 0x03 as a real register"), not folded into this file. sdcard.go's SD/SPI transport is shared physical hardware either way, so it's already usable by both once that gap closes.
Sourcing for the memory-mapping behaviour below (0xE3's bit meanings, the automap trigger/exit addresses): confirmed against two independent sources, cross-checked against each other rather than taken from either alone --
- the ZX-Uno core's own Spectrum-Next-compatible DivMMC implementation (cores/Spectrum/new_memory.v, a real, shipped hardware core), for the 0xE3 bit layout (CONMEM/MAPRAM/SRAM page) and the low-8K-vs-high-8K addressing rules, and
- a ZX-Uno developer's own account of implementing this same logic (board.esxdos.org, "ESXDOS in the ZX-Uno hardware: NMI not working"), which independently states the same six automap entry addresses and the 0x1FF8-0x1FFF exit range, plus that DivMMC "mandates a minimum of 128K RAM" (vs DivIDE's 32K) -- this file's own SRAM sizing below matches that figure.
Neither source is the ZX Spectrum Next's own FPGA core repository directly; one direct confirmation against gitlab.com/SpectrumNext/ZX_Spectrum_Next_FPGA is worth doing before this is trusted as authoritative rather than well-corroborated.
One confirmed real-hardware subtlety is deliberately NOT modelled: Garry Lancaster (NextZXOS's own author) reported against the real Next FPGA core (gitlab.com/SpectrumNext/ZX_Spectrum_Next_FPGA issue #5) that automap entry at 0x0038 takes effect one byte late (the byte AT 0x0038 itself still executes from whatever was mapped before), specifically so esxDOS's own RST-hook interrupt-reentrancy works. This stub's own target -- a cold-boot SD read, not esxDOS-hosted RST-hook reentrancy -- doesn't exercise that edge case, but any future esxDOS-hosting work should revisit this before relying on automap timing being exact.
func NewDivMMC ¶
NewDivMMC constructs a DivMMC with the given ESXDOS/boot ROM image (copied into an internal 8192-byte array; a shorter image is zero-padded, a longer one silently truncated -- callers should treat either as their own error rather than relying on this coping quietly) and the SD card it talks to.
func (*DivMMC) MemRead ¶
MemRead/MemWrite are memory.go's divMMCReadFn/WriteFn targets. ok/handled=false means "DivMMC isn't intercepting this address, fall through to the normal dispatch unchanged" -- the same contract layer2AccessReadFn/WriteFn already established for the Layer 2 Access Port (T-29 completion pass).
func (*DivMMC) OnM1 ¶
OnM1 is the CPU's M1 hook. zen80 calls it after it has read the opcode at pc and before the instruction does anything else, so a delayed change set here takes effect at the right moment: on the next memory access. An instant entry point cannot be handled here, because its opcode has to come from the DivMMC already; instantEntry does that from the memory read itself, when the CPU's program counter is available (pcFn). Without pcFn an instant entry point maps here, one opcode late.
func (*DivMMC) ReadControl ¶
ReadControl returns 0xFF (floating bus) rather than the stored value: gitlab.com/SpectrumNext/ZX_Spectrum_Next_FPGA issue #5 states outright that "on an original divmmc interface, the port containing CONMEM is not readable" -- that source discusses it as a limitation the Next's own core might improve on, so whether the Next's port is actually readable is genuinely unconfirmed either way; this keeps the more conservative, source-stated default rather than assuming an improvement that wasn't directly confirmed.
On the Next the port is documented as read/write (ports.txt, "0xE3 Divmmc control (R/W)"), so there it reads back; controlReadable is set when the interface is wired to a Next.
func (*DivMMC) SetAutomapEnabled ¶
SetAutomapEnabled is called from nextreg.go on every write to NextREG 0x0A, passing bit 4. On an enabled-to-disabled transition, also clears paged immediately -- confirmed against jnext (DA-08, mirroring VHDL's i_automap_reset): disabling automap drops any in-progress overlay right away rather than waiting for the normal exit-address path.
func (*DivMMC) WriteControl ¶
WriteControl/ReadControl handle port 0xE3 ("divMMC Control", confirmed against github.com/avlixa/zx_spectrum_next_03.01.09's own ports.txt).
MAPRAM (bit 6) is a one-way latch on real DivIDE/DivMMC hardware: confirmed across several independent DivIDE programming-model docs (velesoft.speccy.cz/zx/divide, k1.spdns.de's DivIDE references) -- "once set to '1', MAPRAM can only be reset again with a power-on"; a plain RESET leaves it unchanged too. Firmware relies on this being true (observed directly: real ESXDOS/DivMMC ROM code loops writing alternating CONMEM|page and CONMEM|MAPRAM|page values, apparently self-checking that MAPRAM actually stuck, and never proceeds if it didn't). This emulator has no separate power-on-vs-soft-reset distinction yet, so the latch simply never clears for one DivMMC instance's whole lifetime, which is only ever constructed once per process run -- matching the power-on-default-is-0 case fine, but worth revisiting if F1 soft-reset and true power-cycle ever need to behave differently here.
type Engine ¶
Engine is a convenience alias so the field name reads naturally; the real type is pkg/debug.Engine.
type FDC765 ¶
type FDC765 struct {
// contains filtered or unexported fields
}
FDC765 implements a basic NEC 765 Floppy Disk Controller
func (*FDC765) AutoCommit ¶
AutoCommit flushes a modified disk back to its file, but only once writing has settled: it commits when the disk is dirty, the controller is idle (no command in execution or result phase), and at least debounceFrames have passed since the last write. This avoids serializing a torn image in the middle of a multi-sector operation. No-op when there is nothing to commit. Returns true if a commit occurred.
func (*FDC765) Busy ¶
Busy reports that the controller is in the middle of a command, when the disc in memory may be half-written.
func (*FDC765) CreateBlankDisk ¶
func (fdc *FDC765) CreateBlankDisk()
CreateBlankDisk creates a blank formatted +3 disk
func (*FDC765) DiskFile ¶
DiskFile is the file the disc in the drive came from, "" for no disc and for a blank disc that has no file yet.
func (*FDC765) EnableDebug ¶
EnableDebug enables debug output
func (*FDC765) FileChanged ¶
FileChanged reports that the disc's file is no longer the one that was read into memory or last written from it: something else has changed, replaced or removed it since.
func (*FDC765) IsModified ¶
IsModified returns true if the disk has been modified
func (*FDC765) ReadStatus ¶
ReadStatus reads the main status register
type FDCMetadata ¶
type FDCMetadata struct {
Present bool `json:"present"`
DiskPresent bool `json:"disk_present"`
DiskModified bool `json:"disk_modified"`
DiskFilename string `json:"disk_filename,omitempty"`
DiskSize int `json:"disk_size,omitempty"`
Track int `json:"track"`
Head int `json:"head"`
Sector int `json:"sector"`
}
FDCMetadata contains FDC state
type FDCState ¶
type FDCState struct {
Present bool
DiskPresent bool
DiskModified bool
DiskFilename string
CurrentTrack uint8
CurrentHead uint8
CurrentSector uint8
MainStatus uint8
ST0, ST1, ST2, ST3 uint8
}
FDCState contains FDC controller state (+3 only)
type FastGUIRenderer ¶
type FastGUIRenderer interface {
RenderGPU(dm *DisplayManager, mem *SpectrumMemory, screen *SpectrumScreen, offsetX, offsetY float32, multiplier int)
}
FastGUIRenderer is an optional interface a VideoRenderer can also implement for GPU-accelerated live rendering via raylib texture blitting, used by DisplayManager.Render instead of Decode()+texture- upload when available. A renderer without this interface -- or the headless build, which has no GL context to blit into -- uses Decode() exactly as before; nothing about that portable path changes.
RenderGPU draws directly to whatever render target is currently bound (the main window, already cleared and with the border texture drawn if applicable by the time Render calls this) -- no intermediate texture, matching how this renderer worked before the VideoRenderer abstraction existed. offsetX/offsetY is where the screen area begins (0,0 if borderless, or just past the border if not); multiplier is the fixed integer pixel scale (dm.screen.multiplier) -- both pkg-textures (bitPatternGPU, paperColourGPU) are baked once and never re-uploaded; only draw calls happen per frame.
type FastLoader ¶
type FastLoader struct {
Enabled bool
}
func (*FastLoader) TryIntercept ¶
func (fl *FastLoader) TryIntercept(zx *ZenZX, t *Tape) bool
TryIntercept attempts to intercept the real ROM's tape loading routine -- the standard 48K-compatible LD-BYTES (any model whose currently-paged ROM bank is genuinely that one) or TS2068's own R_TAPE (reached only when chunk 0 is genuinely switched to Extension ROM) -- and inject a parsed block directly, replacing only the slow pulse-by-pulse reading loop; everything before the trap point ran as genuine ROM code. Both routines share an identical register contract (confirmed by direct disassembly: TS2068's R_TAPE/W_TAPE are a byte-for-byte relocated copy of LD-BYTES/SA-BYTES, offset by a constant 0x045A), so trapLoad handles both without needing to know which one fired. Returns true if it fired (successfully or not -- a wrong/missing block is a legitimate real-hardware outcome, reported via Carry, not a reason to fall through to something else).
Save-side (SA-BYTES/W_TAPE) is intentionally not implemented: zenzx has no existing tape-save capture to hook into, and adding one is new feature work, not part of hardening the load path. Both save trap points are still checked so a program calling into them does not risk falling through to whatever real ROM code happens to sit at that address being misread as something else -- they currently just decline (return false) and let the real save code run normally (slowly, generating real pulses nobody currently records, but that is a known, pre-existing gap).
type IOMetadata ¶
type IOMetadata struct {
BorderColor int `json:"border_color"`
Speaker bool `json:"speaker"`
AYRegister int `json:"ay_register,omitempty"`
Keyboard string `json:"keyboard"`
}
IOMetadata contains I/O state
type IOState ¶
type IOState struct {
BorderColor uint8
Keyboard [8]uint8
AYRegister uint8
Speaker bool
AYRegisters [16]uint8 // AY register cache
}
IOState contains I/O device states
type JoystickMode ¶
type JoystickMode int
JoystickMode selects which hardware joystick mechanism, if any, abstract JoystickState updates are translated into. The *Both modes are distinct from their single-port counterparts -- they drive two real ports simultaneously from two separate host inputs, where the single-port modes each drive one port from one.
const ( JoystickNone JoystickMode = iota JoystickKempston JoystickKempston2 JoystickKempstonBoth JoystickSinclair1 JoystickSinclair2 JoystickSinclairBoth JoystickCursor // keys 5 6 7 8 0: joyports.go JoystickNext // a Next: each port is what NextREG 0x05 says (joyports.go) )
func ParseJoystickMode ¶
func ParseJoystickMode(s string) (JoystickMode, error)
ParseJoystickMode validates a -joystick flag value. "sinclair" is kept as a backward-compatible alias for "sinclair1" (this flag's only value for Sinclair before this session's dual-port work). "kempston" remains the alias-free name for the classic single port (0x1F), matching every existing script/habit built around it. "auto" is handled by the caller (zenzx_headless.go/zenzx_gui.go), which resolves it against -model before ever reaching this function -- ParseJoystickMode itself has no notion of which model is running.
Unlike the older -tapemode flag's silent-fallback style, an unrecognised value is a hard error -- consistent with the -ns-graphics/-non-standard validation established in nonstandard.go.
func (JoystickMode) String ¶
func (m JoystickMode) String() string
type JoystickState ¶
type JoystickState struct {
Up, Down, Left, Right, Fire bool
// A Next's ports read more buttons: a second fire button on a Kempston port, and A
// and START as well on an MD pad (joyports.go). The classic machines ignore them.
Fire2, A, Start bool
}
JoystickState is the abstract, hardware-independent state of one joystick for one frame. Diagonals and fire-while-moving are both valid (multiple fields true at once) -- real joysticks and all emulated mechanisms support this natively.
type KeyMapping ¶
type KeyMapping struct {
Key int32 // Raylib key code
Keys []SpectrumKey // Spectrum keys to press (for combinations)
}
KeyMapping represents a mapping from PC key to Spectrum key(s)
type KeyQueue ¶
type KeyQueue struct {
// contains filtered or unexported fields
}
KeyQueue is a frame-driven queue of key steps. The scheduler advances it one frame per Tick via Step, which applies the current hold to the matrix.
func NewKeyQueue ¶
NewKeyQueue returns an empty queue with the given hold/gap timing.
func (*KeyQueue) EnqueueChord ¶
func (q *KeyQueue) EnqueueChord(keys []matrixPos)
EnqueueChord adds a single explicit chord. A two-key chord whose first key is a shift (CAPS or SYMBOL) is staged like a human shift-press; other chords are pressed together.
func (*KeyQueue) EnqueueText ¶
EnqueueText expands a string into key chords, tracking BASIC's K/L editor mode as it goes. A fresh command line starts in K mode, where the next keypress selects a whole keyword (LOAD, PRINT, GOTO, ...) rather than a letter; after a keyword, the editor is in L mode for the rest of the line. Only "LOAD" is recognised as a keyword for now (see keywordKeys above); anything else is typed letter-by-letter, which is correct for program lines, variable names, and text following a keyword's own arguments.
func (*KeyQueue) Step ¶
Step advances the queue by one frame and applies the current hold to the emulator's key matrix. It clears any previously-held scripted keys first by resetting the matrix, then pressing the current step's keys. It returns true while the queue is still active.
Note: this resets the whole matrix each frame, which is correct for the headless build (no other keyboard source). The GUI build, whose HandleInput rewrites the matrix every frame, applies scripted keys after HandleInput so they win; see the GUI wiring.
type Link ¶
type Link struct {
// contains filtered or unexported fields
}
Link is one machine's channel to the outside. Make one with NewLink, attach it with ZenZX.AttachLink, and either serve it on a socket with Listen or drive it directly with Send and Receive. It is safe to use from several goroutines.
func (*Link) Close ¶
func (l *Link) Close()
Close stops listening and disconnects every host. The link can still be driven with Send and Receive afterwards.
func (*Link) Counts ¶
Counts reports how many bytes the machine has taken from the host and how many it has written.
func (*Link) Listen ¶
Listen serves the link on a TCP address such as "127.0.0.1:16384". A port of 0 takes any free one; Addr says which. Several hosts may connect at once: what any of them writes goes to the machine in the order it arrives, and what the machine writes goes to all of them.
func (*Link) Pending ¶
Pending is how many bytes from the host the machine has not taken yet, the one being offered included.
func (*Link) Receive ¶
Receive takes the bytes the machine has written that no host has had. With a host connected there are none: they went to the socket.
func (*Link) Reset ¶
func (l *Link) Reset()
Reset returns the handshake to idle, as a reset of the machine does. The bytes still queued stay queued; a byte that was being offered and had not been acknowledged is offered again.
type MemoryFlags ¶
type MemoryFlags uint64
MemoryFlags tags what a physical page actually is. The low 4 bits are a page-type enum (room for up to 16 without a layout change); bits 4-6 are independent boolean properties.
const ( PageTypeSpectrum128 MemoryFlags = iota // standard 128K/+2 ROM or RAM bank PageTypePlus3 // +3-specific ROM bank (editor/syntax/48-BASIC/DOS) PageTypeTimex // reserved for future TS2068 Extension ROM modelling PageTypeNext // reserved for future Next compatibility-mode paging )
const ( FlagROM MemoryFlags = 1 << 4 // set: ROM (read-only); clear: RAM FlagSwappable MemoryFlags = 1 << 5 // set: can be paged out; clear: always mapped regardless of paging state FlagUser MemoryFlags = 1 << 6 // set: user/game RAM; clear: system-reserved )
type MemoryMetadata ¶
type MemoryMetadata struct {
Model string `json:"model"`
ROMBank int `json:"rom_bank"`
RAMBankTop int `json:"ram_bank_top"`
ScreenBank int `json:"screen_bank"`
PagingLocked bool `json:"paging_locked"`
SpecialMode int `json:"special_mode,omitempty"`
Port7FFD string `json:"port_7ffd,omitempty"`
Port1FFD string `json:"port_1ffd,omitempty"`
}
MemoryMetadata contains memory configuration
type MemoryPage16k ¶
type MemoryPage16k [16384]byte
MemoryPage16k is one physical, independently-addressable 16K page -- exactly the real hardware's own paging granularity.
type MouseMode ¶
type MouseMode int
MouseMode selects which hardware mouse interface, if any, is emulated.
func ParseMouseMode ¶
ParseMouseMode validates a -mouse flag value.
type MouseState ¶
type MouseState struct {
DeltaX, DeltaY float32
Left, Right, Middle bool
Wheel float32 // notches turned since the last frame; a Next reads the wheel
}
MouseState is the abstract, hardware-independent per-frame mouse state. DeltaX/DeltaY are movement since the last frame in native Spectrum pixels -- the caller (input.go, GUI-only) is responsible for converting from host window-client pixels by dividing by the current display magnification before constructing this; mouse.go has no notion of window scale at all, deliberately, the same separation joystick.go keeps from its own host input source.
type NextRegisterFile ¶
type NextRegisterFile struct {
// contains filtered or unexported fields
}
NextRegisterFile is the ZX Spectrum Next's register-bus state: which register is currently selected, and the stored value of every register this emulator implements.
type NonStandardConfig ¶
NonStandardConfig holds the validated state of the master switch and its sub-switches. An empty Graphics/Storage means "standard behaviour for that subsystem" -- Enabled does not imply every sub-switch is engaged.
func ParseNonStandardConfig ¶
func ParseNonStandardConfig(masterRaw, graphicsRaw, storageRaw string) (NonStandardConfig, error)
ParseNonStandardConfig validates the raw flag values together. masterRaw must be "on" or "off" (case-sensitive, matching every other enumerated flag in this codebase, e.g. -tapemode). graphicsRaw and storageRaw must each be "" or one of their recognised values, and must be "" whenever masterRaw is "off".
func (NonStandardConfig) Summary ¶
func (c NonStandardConfig) Summary() string
Summary returns a one-line human-readable description for startup logging, or "" when non-standard features are off.
type PagingState ¶
type PagingState struct {
ROMBank uint8
RAMBankTop uint8
ScreenBank uint8
PagingLocked bool
Port7FFD uint8
Port1FFD uint8 // +3 only
SpecialMode uint8 // +3 special paging mode
}
PagingState contains memory banking configuration
type RegName ¶
type RegName string
RegName is a writable register named for the debugger's `set REG VALUE`.
const ( RegA RegName = "A" RegF RegName = "F" RegB RegName = "B" RegC RegName = "C" RegD RegName = "D" RegE RegName = "E" RegH RegName = "H" RegL RegName = "L" RegBC RegName = "BC" RegDE RegName = "DE" RegHL RegName = "HL" RegIX RegName = "IX" RegIY RegName = "IY" RegSP RegName = "SP" RegPC RegName = "PC" )
type Regs ¶
type Regs struct {
A, F, B, C, D, E, H, L uint8
IXH, IXL, IYH, IYL uint8
I, R uint8
SP, PC, WZ uint16
IFF1, IFF2, Halted bool
Cycles uint64
}
Regs is a snapshot of the CPU's registers at one instant. It is a copy: reading it never touches the live CPU, and writing a field here does not change the machine. Use SetReg to write a register back.
type SDCard ¶
type SDCard struct {
// Debug, when true, logs every CS transition and command/response
// frame to stderr -- off by default (zero value), no behaviour
// change unless a caller sets it (zenzx_headless.go/zenzx_gui.go's
// -divmmc-debug flag).
Debug bool
// contains filtered or unexported fields
}
SDCard emulates an SD card's SPI-mode command protocol closely enough for real Next firmware's own documented boot sequence (docs/NEXT_BOOT_REFERENCE.md stage 1: "CMD12 -> CMD0 -> CMD8 -> ACMD41 -> CMD58") to succeed, plus CMD9 and CMD17 for the register read and the actual sector reads that follow.
This file was rewritten this session (T-36) after direct comparison against jorgegv/jnext's own sd_card.cpp -- a reference implementation with an extensive, real-firmware-verified history of exactly these command formats (their own comments cite specific TBBLUE.FW/enNxtmmc.rom memory addresses their fixes were driven by). Every non-obvious byte value and timing detail below is ported from there, cited individually, rather than re-derived -- this stub's own earlier version got CMD0's persistent-response behaviour and CMD8's R7 format wrong in exactly the ways jnext's own history describes hitting and fixing.
Deliberate remaining simplifications, not ported from jnext:
- No CRC *checking* on incoming command frames (SPI-mode CRC is normally disabled after CMD8, and real firmware issuing well-formed commands doesn't need this stub to validate them).
- CMD55/ACMD41 gating: the boot path only ever does CMD55 then ACMD41, so command index 41 is treated as ACMD41 whenever it follows CMD55, without jnext's fuller "fall through to the regular CMD switch for any other post-CMD55 command" handling.
- CMD9 (SEND_CSD) and CMD18 (READ_MULTIPLE_BLOCK) are implemented -- both confirmed required by real firmware this session (enNxtmmc.rom's own SD-init flow for CMD9; TBBLUE.FW's FatFs for CMD18) -- but CMD10/16/23/24 (CID, set-blocklen, writes) are not; they fall to the illegal-command default below.
func NewSDCard ¶
func NewSDCard(img SDCardImage, sizeBytes int64) *SDCard
NewSDCard constructs an SDCard backed by img, which holds exactly sizeBytes of raw sector data (typically a whole SD-card image file, FAT32 filesystem and all -- SDCard itself knows nothing about filesystems, only sectors; pkg/nextdisk reads the FAT32 structure this card exposes, one layer up).
func (*SDCard) ReadData ¶
ReadData returns the byte most recently shifted back from the card (port 0xEB read).
Confirmed necessary by direct instruction-trace evidence this session (not inferred): real firmware sometimes polls with a tight bare `IN A,(0xEB)` loop -- no paired `OUT` at all -- waiting for the first non-0xFF byte. If ReadData only ever returned whatever WriteData last produced, such a loop could never see anything past the first stale byte and would spin forever, which is exactly what was observed: thousands of identical polling reads, all 0xFF, against a queue that genuinely had a non-0xFF byte still in it a few positions deep.
freshByte (see its own field comment) distinguishes this from the earlier, working part of the same boot sequence, which pairs each OUT with an immediate IN to read that specific clock's response -- that paired IN must NOT also clock, or multi-byte responses would drain twice as fast as bytes actually arrive.
func (*SDCard) WriteCS ¶
WriteCS handles port 0xE7 ("SPI CS (sd card, flash, rpi)", confirmed against github.com/avlixa/zx_spectrum_next_03.01.09's own ports.txt -- the official FPGA core repository's port table). Bit 0 clear asserts CS (selects the card): the universal SD/MMC-over-SPI convention, not independently confirmed against real Next firmware this session, since ports.txt names the port but not its bit polarity. Deselecting mid-command discards whatever partial command/ response was in flight, matching real SPI behaviour -- EXCEPT an open CMD18 stream, which survives CS deassert. Confirmed against jnext, which cites this as a specific, previously-hit NextZXOS-boot bug (its own commit dated 2026-07-09): in SPI mode, deasserting CS pauses the card; a multi-block read is ended by CMD12 (or a new command), not by CS. esxDOS's own driver deselects between blocks and later reselects, polling port 0xEB for the next block WITHOUT sending any command -- aborting the stream on CS deassert makes that poll see endless 0xFF and time out, exactly the failure jnext documents hitting and fixing.
func (*SDCard) WriteData ¶
WriteData handles port 0xEB ("SPI DATA" per the same ports.txt): one full-duplex byte shift. Real Next hardware provides a byte-at-a-time SPI shifter here, not a bit-banged GPIO pin, so one port access moves a whole byte each way, matching how real Next firmware drives it. value is whatever the host is currently driving out; the byte the "card" simultaneously shifts back becomes readable via ReadData until the next call.
The read side (draining a queued response, or returning persistentByte once that queue is empty) and the write side (collecting a new command) are independent, not mutually exclusive: real SPI shifts a bit each way on every clock, so the master's outgoing byte is a real byte on the wire even on a clock that's also draining a preceding command's last response byte. Treating them as either/or was a real, observed bug this session: real firmware sometimes starts clocking a new command's first byte on the very same transfer that drains the previous command's last response byte, and discarding that byte instead of capturing it shifted every subsequent command frame by one byte, permanently.
The write side resyncs on the SD command start-bit pattern (bits 7:6 == 0b01, i.e. 0x40-0x7F) rather than blindly counting every byte that goes by -- confirmed against jnext's own receive(), which uses the identical `(tx & 0xC0) == 0x40` check. This matters once the read side can be draining a large response (a whole 512-byte CMD17 data block): without resyncing, the 0xFF filler bytes real firmware sends while reading that block would themselves get miscounted as command bytes every 6 bytes. A start-bit byte arriving while a response is still draining also aborts that response, matching jnext's confirmed behaviour (its receive() does the same in its RESPONDING/SENDING_DATA/WRITE_RESP states), not just when idle.
type SDCardImage ¶
SDCardImage is the minimal block-read interface an SDCard needs from whatever backs it -- the same raw bytes pkg/nextdisk's fatfs.Volume interprets as a filesystem one layer up, read here instead at the plain 512-byte-sector level real SD/MMC hardware actually speaks. *os.File and bytes.NewReader-wrapped images both already satisfy this via io.ReaderAt.
type ScheduleConfig ¶
type ScheduleConfig struct {
ShotDir string // directory screenshots are written into
ShotPrefix string // filename prefix for auto-named screenshots
Quiet bool // suppress informational and warning logging
Model string // Spectrum model name, for boot detection (wait-boot)
}
ScheduleConfig carries the front-end-specific settings the handlers need. Both main loops populate this from their own flags before constructing the scheduler. The GUI front-end has no -shot-dir/-shot-prefix flags, so it passes its own sensible defaults.
type Scheduler ¶
type Scheduler struct {
// contains filtered or unexported fields
}
Scheduler holds a script and the run-time state needed to drive it.
func NewScheduler ¶
func NewScheduler(script *Script, cfg ScheduleConfig) *Scheduler
NewScheduler builds a scheduler for the given script and configuration.
func (*Scheduler) BlockingOnRealMemory ¶
BlockingOnRealMemory reports whether a barrier that reads real screen or memory content (wait-boot, wait-screen, wait-attr, wait-mem) is currently active. Turbo mode (turbo.go) checks this to stay inactive during these windows -- a barrier like wait-boot has no way to observe progress being written to Turbo mode's own flat, unsynced scratch memory instead of the real SpectrumMemory/screen it actually reads.
func (*Scheduler) ExpectFailures ¶
ExpectFailures returns the number of failed expect-screen assertions.
func (*Scheduler) OwnsKeyboard ¶
OwnsKeyboard reports whether the script has keys down: typing in progress, or a key a press action still holds. A front end that fills the key matrix from the host keyboard each frame must leave it alone meanwhile, or the script's keys never reach the machine.
func (*Scheduler) QuitRequested ¶
QuitRequested reports whether a 'quit' action has fired. The headless loop checks this to break early; the GUI loop may ignore it or use it to close.
func (*Scheduler) ShotsTaken ¶
ShotsTaken returns the number of screenshots the script has captured.
func (*Scheduler) Tick ¶
Tick advances the scheduler by one frame and fires any due actions. It must be called exactly once per emulated frame, before RunFrame.
Actions fire against an *effective* clock (s.frame - s.rebase). A wait-boot action blocks the timeline: while it is the next action and boot is not yet ready, no later action fires and the effective clock does not advance past it. When boot completes, the rebase origin is set to the current frame, so every offset after a wait-boot is measured from boot-ready -- making scripts portable across models with different boot times.
type Script ¶
type Script struct {
Actions []Action
}
Script is an ordered set of actions, sorted by frame then source order.
func ParseScriptFile ¶
ParseScriptFile reads and parses a .zen file from disk.
type SincFilter ¶
type SincFilter struct {
// contains filtered or unexported fields
}
SincFilter provides high-quality audio resampling using windowed sinc interpolation
func NewSincFilter ¶
func NewSincFilter(taps int, cutoff float32) *SincFilter
NewSincFilter creates a new windowed sinc filter taps: number of filter taps (8, 16, 32, 64 for quality/performance tradeoff) cutoff: normalized cutoff frequency (typically 0.45-0.495 to prevent aliasing)
func (*SincFilter) Process ¶
func (sf *SincFilter) Process(input float32) float32
Process applies the sinc filter to a single input sample
func (*SincFilter) ProcessBatch ¶
func (sf *SincFilter) ProcessBatch(input []float32) []float32
ProcessBatch processes multiple samples at once (more efficient)
type SnapshotHeader ¶
type SnapshotHeader struct {
Magic [5]byte // "ZENZX"
Version uint8 // Snapshot format version
Flags uint16 // Bit flags for features
Timestamp uint64 // Unix timestamp
Model uint8 // 0=48K, 1=128K, 2=+2, 3=+2A, 4=+3
Reserved [7]byte // Reserved for future use
}
SnapshotHeader is the main file header
type SnapshotMetadata ¶
type SnapshotMetadata struct {
Version int `json:"version"`
Timestamp time.Time `json:"timestamp"`
Model string `json:"model"`
Description string `json:"description,omitempty"`
Emulator string `json:"emulator"`
EmulatorVer string `json:"emulator_version"`
CPU CPUMetadata `json:"cpu"`
Memory MemoryMetadata `json:"memory"`
IO IOMetadata `json:"io"`
FDC *FDCMetadata `json:"fdc,omitempty"`
Audio *AudioMetadata `json:"audio,omitempty"`
Checksums map[string]string `json:"checksums"`
ChunkSizes map[string]int `json:"chunk_sizes"`
Debug map[string]interface{} `json:"debug,omitempty"`
}
SnapshotMetadata contains human-readable snapshot information
func ValidateSnapshot ¶
func ValidateSnapshot(filename string) (*SnapshotMetadata, error)
ValidateSnapshot checks if a snapshot file is valid and returns metadata
type SpeakerChange ¶
SpeakerChange records when the speaker state changed
type SpectrumIO ¶
type SpectrumIO struct {
// contains filtered or unexported fields
}
func NewSpectrumIO ¶
func NewSpectrumIO(memory *SpectrumMemory, audio *AudioWrapper) *SpectrumIO
func (*SpectrumIO) CombineULAAndTilemap ¶
func (io *SpectrumIO) CombineULAAndTilemap(ula *image.RGBA, screen *SpectrumScreen) *image.RGBA
CombineULAAndTilemap makes the "U" layer from the ULA picture (256x192) and the tilemap. With the tilemap off it returns the ULA picture itself. Otherwise the result is 256 pixels wide, or 512 in 80 column mode, where each ULA pixel covers two.
In the ordinary mode the result is the topmost pixel that is not transparent: the tile's where the tile is above the ULA, the ULA's where the tile says the ULA goes over it. A ULA pixel is transparent when its colour in the Next's ULA palette is the global transparency colour (NextREG 0x14); programs make a paper colour transparent that way and print over the tilemap. In stencil mode, NextREG 0x68 bit 0 with both enabled, a pixel is the AND of the two colours, and transparent where either is. Where nothing is left the fallback colour (NextREG 0x4A) shows.
func (*SpectrumIO) ComposeNextFrame ¶
func (io *SpectrumIO) ComposeNextFrame(standard func() *image.RGBA, screen *SpectrumScreen, border uint8) *image.RGBA
ComposeNextFrame draws the frame. standard draws the classic 256x192 picture, for when the screen is not given or a Timex mode is not in use; screen, when not nil, lets the classic picture's pixels go through the Next's ULA palette, which is what can make them transparent; border is the border colour, 0 to 7.
It draws all of the frame from the state as it is now. A frame in which the state changes part of the way down is put together from pieces by NextFrame (nextraster.go).
func (*SpectrumIO) DecodeLayer2 ¶
func (io *SpectrumIO) DecodeLayer2() *image.RGBA
DecodeLayer2 renders Layer 2's current framebuffer as a 256x192 image.RGBA, honouring the NR 0x18 clip window: pixels outside the clip rectangle are transparent (alpha 0) rather than black, so a caller compositing this over the ULA image sees the ULA layer show through unclipped regions instead of a black rectangle. Returns nil if Layer 2 is not enabled (see layer2Enabled) -- callers must check for nil rather than compositing an always-present image, since "Layer 2 not active" and "Layer 2 active showing an all-black frame" are genuinely different states worth keeping distinguishable at this layer.
func (*SpectrumIO) DecodeNextTimex ¶
func (io *SpectrumIO) DecodeNextTimex(screen *SpectrumScreen) *image.RGBA
DecodeNextTimex draws the Timex mode a Next is in, or returns nil in the standard mode, which the ordinary renderer draws. The picture is 256x192, or 512x192 in hi-res.
func (*SpectrumIO) DecodeSprites ¶
func (io *SpectrumIO) DecodeSprites() *image.RGBA
DecodeSprites renders every visible sprite into a 256x192 image.RGBA, sprite 0 drawn first and sprite 127 last so a higher-numbered sprite wins where two overlap -- matching the wiki's documented default priority (real hardware also offers the reverse via NR 0x15 bit 6, explicitly deferred here along with the other NR 0x15 bits this scope doesn't consume; see nextLayerOrder's own comment). Pixels with no visible, opaque sprite covering them are left at the image's zero value (alpha 0, transparent), exactly matching DecodeLayer2's own convention so both layers composite the same way. Returns nil if the sprite layer is not enabled (spriteEnabled).
func (*SpectrumIO) DecodeSpritesFrame ¶
func (io *SpectrumIO) DecodeSpritesFrame() *image.RGBA
DecodeSpritesFrame draws the sprites on the frame, 320x256, where a sprite at (32,32) has its corner on the classic picture's. nil when the sprites are off. Without "sprites over border" they show only on the classic picture, inside their clip window; with it they show on the whole frame, or inside the clip window when NextREG 0x15 bit 5 asks.
func (*SpectrumIO) DisableFDC ¶
func (io *SpectrumIO) DisableFDC()
DisableFDC disables Floppy Disk Controller emulation
func (*SpectrumIO) EnableDivMMC ¶
func (io *SpectrumIO) EnableDivMMC(sdImage SDCardImage, sdSize int64, romImage []byte)
EnableDivMMC attaches a DivMMC interface (T-36): the automap/CONMEM memory overlay plus the SD-card-over-SPI transport (divmmc.go, sdcard.go), backed by sdImage (sdSize bytes) and romImage (the ESXDOS/boot ROM to page in at 0x0000-0x1FFF -- see divmmc.go's own header comment for what this is NOT). Wires memory's divMMCReadFn/WriteFn, the same closure-injection direction NewSpectrumIO already uses for the Layer 2 Access Port.
Does NOT wire the CPU's M1Hook, which automap needs to see PC on every M1 cycle: SpectrumIO only ever holds the narrow Z80CPU interface (SetCPU, GetCycles-only), not zen80's concrete *z80.Z80. The caller must also call ZenZX's own EnableDivMMC (zenzx.go), which does both this and the M1Hook wiring together -- calling this method directly leaves automap permanently un-triggered (CONMEM-forced paging would still work; the boot chain's own cold-start entry at PC=0 would not).
func (*SpectrumIO) EnableFDC ¶
func (io *SpectrumIO) EnableFDC()
EnableFDC enables Floppy Disk Controller emulation for +3
func (*SpectrumIO) EndFrame ¶
func (io *SpectrumIO) EndFrame()
EndFrame is the end of a frame's T-states: on a Next the copper runs to the end of it (nextraster.go).
func (*SpectrumIO) FDCTick ¶
func (io *SpectrumIO) FDCTick(frame, debounceFrames int)
FDCTick advances the FDC frame clock and runs the auto-commit debounce. The front-end calls it once per frame. A modified disk is flushed to its file after it has been quiet for debounceFrames and the controller is idle.
func (*SpectrumIO) GetAYRegister ¶
func (io *SpectrumIO) GetAYRegister() uint8
GetAYRegister returns the currently selected AY register
func (*SpectrumIO) GetAYRegisters ¶
func (io *SpectrumIO) GetAYRegisters() [16]uint8
GetAYRegisters returns a copy of the cached AY registers
func (*SpectrumIO) GetBorderColor ¶
func (io *SpectrumIO) GetBorderColor() uint8
GetBorderColor returns the current border color
func (*SpectrumIO) GetBorderHistory ¶
func (io *SpectrumIO) GetBorderHistory() []BorderChange
GetBorderHistory returns the border change history for rendering
func (*SpectrumIO) GetInterruptVector ¶
func (io *SpectrumIO) GetInterruptVector() uint8
GetInterruptVector implements zen80's optional InterruptController interface (z80.InterruptController), consulted for every IM2 interrupt acceptance, not just AMX's. Only AMX mouse ever needs anything but the standard Spectrum ULA's fixed 0xFF (zen80's own default when this interface isn't implemented at all) -- an AMX vector, when one is pending, takes priority; otherwise this returns exactly what zen80 would have defaulted to on its own, so implementing this interface at all changes nothing for any software that isn't AMX-aware.
func (*SpectrumIO) GetKeyboardState ¶
func (io *SpectrumIO) GetKeyboardState() [8]uint8
GetKeyboardState returns a copy of the keyboard matrix
func (*SpectrumIO) GetMMUSlots ¶
func (io *SpectrumIO) GetMMUSlots() [8]uint8
GetMMUSlots returns the eight NextREG MMU slot values (registers 0x50-0x57), for ti0.r2's paging model to read once it exists.
func (*SpectrumIO) GetMode0Instruction ¶
func (io *SpectrumIO) GetMode0Instruction() []uint8
GetMode0Instruction implements the other half of the same optional interface. Nothing in this project uses IM0; a NOP is a harmless, universal default so the interface can be satisfied at all.
func (*SpectrumIO) GetNextRegister ¶
func (io *SpectrumIO) GetNextRegister(reg uint8) uint8
GetNextRegister returns register reg's current value regardless of access mode -- for snapshot/debug/test use, not the guest-facing port path (which honours write-only/read-only above).
func (*SpectrumIO) GetSpeaker ¶
func (io *SpectrumIO) GetSpeaker() bool
GetSpeaker returns the current speaker state
func (*SpectrumIO) GetTapeEar ¶
func (io *SpectrumIO) GetTapeEar() bool
GetTapeEar returns the current tape input level
func (*SpectrumIO) In ¶
func (io *SpectrumIO) In(port uint16) uint8
func (*SpectrumIO) LoadDisk ¶
func (io *SpectrumIO) LoadDisk(filename string) error
LoadDisk loads a disk image into the FDC
func (*SpectrumIO) MultifaceButton ¶
func (io *SpectrumIO) MultifaceButton()
MultifaceButton is the M1 button, if NextREG 0x06 lets it make an NMI.
func (*SpectrumIO) NextFrame ¶
func (io *SpectrumIO) NextFrame(standard func() *image.RGBA, screen *SpectrumScreen, border uint8) *image.RGBA
NextFrame is the Next's picture for the front ends: the pieces of the current frame composed so far, and the rest of it from the state as it is now. standard, screen and border are as for ComposeNextFrame.
func (*SpectrumIO) Out ¶
func (io *SpectrumIO) Out(port uint16, value uint8)
func (*SpectrumIO) PopAMXInterrupt ¶
func (io *SpectrumIO) PopAMXInterrupt() (vector uint8, ok bool)
PopAMXInterrupt is called from ZenZX's per-instruction run loop (only when AMX mouse mode is active) to check for and consume the next queued step. Returns ok=false when nothing is pending. The popped request's port value becomes what port 0x1F/0x3F returns until the next request is popped (io.go's port dispatch reads amxPortValue).
func (*SpectrumIO) PressKey ¶
func (io *SpectrumIO) PressKey(row, col uint8)
func (*SpectrumIO) ReadPort ¶
func (io *SpectrumIO) ReadPort(port uint16) uint8
func (*SpectrumIO) ReleaseKey ¶
func (io *SpectrumIO) ReleaseKey(row, col uint8)
func (*SpectrumIO) ResetKeyboard ¶
func (io *SpectrumIO) ResetKeyboard()
func (*SpectrumIO) SaveDisk ¶
func (io *SpectrumIO) SaveDisk() error
SaveDisk saves the current disk image
func (*SpectrumIO) SaveDiskAs ¶
func (io *SpectrumIO) SaveDiskAs(filename string) error
SaveDiskAs saves the current disk image with a new filename
func (*SpectrumIO) SetAYRegisters ¶
func (io *SpectrumIO) SetAYRegisters(registers [16]uint8)
SetAYRegisters restores AY registers from a snapshot
func (*SpectrumIO) SetBorderColor ¶
func (io *SpectrumIO) SetBorderColor(color uint8)
SetBorderColor sets the border color
func (*SpectrumIO) SetCPU ¶
func (io *SpectrumIO) SetCPU(cpu Z80CPU)
SetCPU sets the CPU reference for cycle tracking
func (*SpectrumIO) SetFDCDebug ¶
func (io *SpectrumIO) SetFDCDebug(enable bool)
SetFDCDebug enables or disables FDC debug output
func (*SpectrumIO) SetJoystickMode ¶
func (io *SpectrumIO) SetJoystickMode(mode JoystickMode)
SetJoystickMode configures which hardware mechanism, if any, future SetJoystickState/SetJoystickStateBoth calls are translated into.
func (*SpectrumIO) SetJoystickState ¶
func (io *SpectrumIO) SetJoystickState(s JoystickState)
SetJoystickState updates the joystick's abstract state for single-target modes (None, Kempston, Kempston2, Sinclair1, Sinclair2) and applies it to whichever hardware mechanism is configured. A no-op for JoystickNone and for the two *Both modes (which need two states -- see SetJoystickStateBoth).
func (*SpectrumIO) SetJoystickStateBoth ¶
func (io *SpectrumIO) SetJoystickStateBoth(port1, port2 JoystickState)
SetJoystickStateBoth updates both ports at once for either dual-port mode -- the +2/+2A/+3's real built-in Sinclair ports, or a neo-Spectrum platform's configured dual Kempston ports -- from two independent states in the same call, matching the machine's two simultaneous physical ports. A no-op unless one of the two *Both modes is configured.
func (*SpectrumIO) SetMouseMode ¶
func (io *SpectrumIO) SetMouseMode(mode MouseMode)
SetMouseMode configures which hardware interface, if any, future SetMouseState calls are translated into.
func (*SpectrumIO) SetMouseState ¶
func (io *SpectrumIO) SetMouseState(s MouseState)
SetMouseState updates the mouse's abstract state and applies it to whichever hardware mechanism is configured. Safe to call with MouseNone configured -- a no-op past the mode switch.
Fractional deltas are accumulated across frames (mouseRemX/Y) rather than truncated per-frame: at high magnification a single frame's magnification-corrected delta is often well under 1.0, and truncating it to zero every frame would silently discard slow mouse movement entirely rather than merely making it coarse.
func (*SpectrumIO) SetNextRegister ¶
func (io *SpectrumIO) SetNextRegister(reg uint8, value uint8)
SetNextRegister writes register reg's value directly -- for snapshot restore, bypassing access-mode checks the same way GetNextRegister bypasses them for reads.
func (*SpectrumIO) SetTS2068JoystickState ¶
func (io *SpectrumIO) SetTS2068JoystickState(player int, s JoystickState)
SetTS2068JoystickState updates one of TS2068's two built-in joystick ports. player is 1 or 2; any other value is a no-op.
func (*SpectrumIO) SetTapeEar ¶
func (io *SpectrumIO) SetTapeEar(level bool)
SetTapeEar sets the tape input level
func (*SpectrumIO) StartFrame ¶
func (io *SpectrumIO) StartFrame()
StartFrame prepares for a new frame's border tracking
func (*SpectrumIO) WritePort ¶
func (io *SpectrumIO) WritePort(port uint16, value uint8)
type SpectrumKey ¶
SpectrumKey represents a key position on the Spectrum keyboard matrix
type SpectrumMemory ¶
type SpectrumMemory struct {
// contains filtered or unexported fields
}
func NewSpectrumMemory ¶
func NewSpectrumMemory(screen *SpectrumScreen) *SpectrumMemory
func (*SpectrumMemory) DisableBootROM ¶
func (m *SpectrumMemory) DisableBootROM()
DisableBootROM turns off the boot ROM overlay. Called from nextreg.go's nextRegWriteDirect on any write to NextREG 0x03 -- see the bootROM field's own doc comment for why that trigger is unconditional on the value written.
func (*SpectrumMemory) Enable128K ¶
func (m *SpectrumMemory) Enable128K()
func (*SpectrumMemory) EnableNext ¶
func (m *SpectrumMemory) EnableNext()
EnableNext turns on the Next-mode 8-slot/8K-granularity MMU (T-28, wave ti0.r2, item #19). This is a NEW, additive addressing path -- it does NOT set is128K/isPlus3 and does not disturb ramBankLow/High/Top or any existing 48K/128K/+3/TS2068 behaviour; Read/Write dispatch to the new path only when isNext is true, checked before every other branch.
nextSlots starts zeroed (all 8 slots pointing at logical page 0, the low 8K half of RAM bank 0) rather than mirroring nextreg.go's mmuBootDefaults -- wiring NextREG 0x50-0x57 to actually drive nextSlots is T-28 item #26, a separate, later change; until then this is a deliberately inert default a caller/test can override directly.
func (*SpectrumMemory) EnablePlus3 ¶
func (m *SpectrumMemory) EnablePlus3()
func (*SpectrumMemory) Load ¶
func (m *SpectrumMemory) Load(address uint16, data []byte)
Load writes a block of bytes into memory starting at the given address, going through the normal Write path so RAM banking and the screen mirror are honoured and ROM regions are protected. Bytes that would extend past the top of the 64K address space are silently dropped; callers that need to detect overflow should check len(data)+int(address) <= 0x10000 first.
This mirrors the Load convention used by zen80's RAM/MappedMemory types (address is uint16, matching the Z80's 16-bit address bus).
func (*SpectrumMemory) LoadROM ¶
func (m *SpectrumMemory) LoadROM(data []byte)
func (*SpectrumMemory) NextIssue ¶
func (m *SpectrumMemory) NextIssue() int
NextIssue returns the board issue: 2, 4 or 5.
func (*SpectrumMemory) Read ¶
func (m *SpectrumMemory) Read(address uint16) uint8
func (*SpectrumMemory) SetBootROM ¶
func (m *SpectrumMemory) SetBootROM(data []byte)
SetBootROM attaches the FPGA config-mode boot ROM (nextboot.rom on real hardware) and enables its overlay immediately -- see the bootROM field's own doc comment (above, in the struct) for the jnext-confirmed sizing/mirroring/priority/disable rules this implements. data shorter than 8192 bytes is zero-padded, longer is truncated, matching jnext's own set_boot_rom (mmu.cpp) exactly.
func (*SpectrumMemory) SetNextIssue ¶
func (m *SpectrumMemory) SetNextIssue(issue int) error
SetNextIssue chooses the board issue, which is how much SRAM a physical address reaches.
func (*SpectrumMemory) SetNextLegacyBank7FFD ¶
func (m *SpectrumMemory) SetNextLegacyBank7FFD(value uint8)
SetNextLegacyBank7FFD is the Next-mode counterpart to SetPaging for port 0x7FFD (T-28 item #27): on a genuine Next machine the SAME physical port that drives classic 128K/+3 paging also recomposes the Next MMU's own slots 6/7 (the 0xC000-0xFFFF 16K-bank-select role) -- confirmed against jnext's own developer documentation ("the legacy ports maintain no map of their own: they recompose the same eight slots", src/doc/developer-guide/03-subsystems/02-memory.md) and its compose_bank_/apply_legacy_ram_slots_ implementation (src/memory/mmu.cpp). This is a wholly separate, additive path from SetPaging: it does not call SetPaging, does not read or write port7FFD/ramBankTop/romBank/pagingLocked/screenBank or any other classic field, and SetPaging itself is completely unmodified by T-28 -- both are called side by side from io.go's port-0x7FFD dispatch, each blind to the other. A no-op when isNext is false, so this has zero effect on any classic 48K/128K/+3/TS2068 machine.
Does NOT model the classic paging-lock bit (value bit 5) at all -- that is a distinct mechanism on real Next hardware (jnext's own port_7ffd_locked_/effective_paging_locked gating) that would need its own dedicated design; recognised here as an explicit open limitation rather than silently ignored or half-implemented.
func (*SpectrumMemory) SetNextLegacyPortDFFD ¶
func (m *SpectrumMemory) SetNextLegacyPortDFFD(value uint8)
SetNextLegacyPortDFFD is port 0xDFFD's write handler (T-28 item #27): the ZX Next's extended-bank-bits port, supplying the bits of the composed 16K bank number that port 0x7FFD's 3 bits alone (banks 0-7) cannot reach -- confirmed against jnext's Mmu::write_port_dffd / compose_bank_ (src/memory/mmu.cpp) and FPGA-REPO-ANALYSIS.md ("Extended bank bits (bits 3:0 high bank)"). 0xDFFD has no defined role on any non-Next machine this emulator models (48K/128K/+3/ TS2068) -- it is a Next/Profi-heritage extension, not a standard Sinclair port -- so this is a no-op when isNext is false, matching that real hardware scope rather than a shortcut.
func (*SpectrumMemory) SetNextSlot ¶
func (m *SpectrumMemory) SetNextSlot(slot int, page uint8)
SetNextSlot sets logical 8K slot `slot` (0-7, address>>13) to page `page` -- the memory-side half of T-28 item #26 (wiring NextREG 0x50-0x57 to actual paging). nextreg.go's nextRegWriteDirect and SetNextRegister call this whenever a write lands on 0x50-0x57, so a NextREG write to those registers now genuinely changes what address space that slot serves, not merely the mmuSlots mirror nextreg.go keeps for readback. Silently ignores an out-of-range slot rather than panicking -- callers pass reg-0x50 (always 0-7 by construction of the 0x50-0x57 range check), but this stays defensive rather than assuming that invariant forever.
func (*SpectrumMemory) SetPaging ¶
func (m *SpectrumMemory) SetPaging(value uint8)
SetPaging handles the 128K memory paging via port 0x7FFD
func (*SpectrumMemory) SetPlus3Paging ¶
func (m *SpectrumMemory) SetPlus3Paging(value uint8)
SetPlus3Paging handles +3 specific paging via port 0x1FFD
func (*SpectrumMemory) SetROMBank ¶
func (m *SpectrumMemory) SetROMBank(bank int, data []byte) error
SetROMBank overwrites a single ROM bank (0-3) in place, without touching the others or re-inferring is128K/isPlus3 -- the memory-level primitive behind -rom0 through -rom3 (zenzx.go's OverrideROMBank), which replace one bank of an already-loaded model's ROM set (e.g. only +3DOS via -rom3 on an otherwise-standard +3) rather than requiring every bank to be respecified.
func (*SpectrumMemory) Write ¶
func (m *SpectrumMemory) Write(address uint16, value uint8)
type SpectrumScreen ¶
type SpectrumScreen struct {
// contains filtered or unexported fields
}
SpectrumScreen holds the display file plus the two pieces of state a renderer needs alongside it: the current FLASH phase, and the live-display scale factor (also read by DisplayManager for window sizing).
func NewSpectrumScreen ¶
func NewSpectrumScreen() *SpectrumScreen
NewSpectrumScreen allocates the 6144-byte bitmap and 768-byte attribute buffers.
func (*SpectrumScreen) Clear ¶
func (s *SpectrumScreen) Clear()
Clear blanks the display file: an empty bitmap, black ink on white paper throughout.
func (*SpectrumScreen) GetMultiplier ¶
func (s *SpectrumScreen) GetMultiplier() int
func (*SpectrumScreen) IsFlashEnabled ¶
func (s *SpectrumScreen) IsFlashEnabled() bool
func (*SpectrumScreen) LoadFromFile ¶
func (s *SpectrumScreen) LoadFromFile(filename string) error
LoadFromFile reads a standard 6912-byte .scr dump (6144 bytes of bitmap followed by 768 bytes of attributes) directly into the display file.
func (*SpectrumScreen) SetMultiplier ¶
func (s *SpectrumScreen) SetMultiplier(mult int)
SetMultiplier and GetMultiplier control the live-display scale factor. Headless builds carry this field for shape parity but never read it.
func (*SpectrumScreen) ToggleFlash ¶
func (s *SpectrumScreen) ToggleFlash()
ToggleFlash and IsFlashEnabled control whether FLASH is honoured at all.
type SymbolTable ¶
SymbolTable is a name -> address map loaded from a .sym file.
func LoadSymbolTable ¶
func LoadSymbolTable(path string) (SymbolTable, error)
LoadSymbolTable parses a pasmo/zenas-format .sym file. Each line is whitespace-separated fields; a line is a symbol definition only if its second field (case-insensitively) is EQU and its third field is a hexadecimal value with a trailing H (with or without a leading 0). Lines that don't match this shape are skipped, not errored -- a .sym file can carry other directives this parser does not need to understand.
func (SymbolTable) Resolve ¶
func (t SymbolTable) Resolve(name string) (uint16, error)
Resolve looks up name in the table. If the table is nil (no 'sym' verb has run yet) or name isn't found, it falls back to parsing name as a literal numeric address via ParseAddr -- so wait-mem/expect-mem work with either a symbol or a raw address, with or without a loaded symbol table.
type Tape ¶
type Tape struct {
// contains filtered or unexported fields
}
Tape manages tape loading and playback
func (*Tape) AttachFastLoader ¶
func (t *Tape) AttachFastLoader(fl *FastLoader)
AttachFastLoader attaches a fast loader implementation
func (*Tape) GetBlockInfo ¶
GetBlockInfo returns information about tape blocks
type TapeBlock ¶
type TapeBlock struct {
Data []byte // Raw block data (including flag byte)
IsHeader bool // True if this is a header block
// Header fields, valid only when IsHeader is true. Populated by
// zentools/pkg/tap's own parser -- for a .tap file, directly from
// tap.Decode's own Block; for a TZX 0x10 (standard-speed data)
// block, by running tap.DecodeBlock over its Data, since a 0x10
// payload IS a TAP-format block's raw bytes (flag+payload+checksum),
// just carried in a TZX container. GetBlockInfo (tape.go) reads
// these directly rather than re-deriving them from raw byte offsets
// itself.
HeaderType byte // TypeProgram / TypeCode / ... (see zentools/pkg/tap)
HeaderName string // 10-char name, trailing spaces trimmed
DataLength uint16
}
TapeBlock represents a single block of tape data
type TapeState ¶
type TapeState struct {
Loaded bool // Is a tape loaded?
Filename string // Current tape filename
Mode TapeMode // Current loading mode
Playing bool // Is tape playing?
Position int // Current position (block index or pulse index)
EdgeOffset int // Sub-pulse position for accurate mode
EarLevel bool // Current EAR output level
Blocks []TapeBlock // Parsed tape blocks
Pulses []int // Pulse durations in T-states (for accurate mode)
// BlockBoundaries marks the pulse indices (keys into Pulses) at which
// each new TZX block's own pulses begin -- populated by loadTZX as
// each block's pulses are appended, one entry per block that
// contributed any pulses at all. Turbo mode's fast memory/IO path
// (loopskip.go... [see turbo.go]) uses this to synchronise its flat,
// paging-unaware scratch memory against the real, paging-aware
// SpectrumMemory once per block rather than once per file -- correct
// for the overwhelmingly common case of a 128K loader switching RAM
// banks between blocks, not mid-block (switching mid-receive, in the
// middle of a time-sensitive bit-sampling loop, would be
// self-defeating for the loader itself, not just rare in practice).
// nil is a valid, common state (a TAP-sourced tape, or any tape with
// only one contributing block) and simply means no boundary besides
// the file's own start and end.
BlockBoundaries []int
// StopPoints marks pulse indices (keys into Pulses) where accurate-mode
// playback should halt once that pulse has fully played, matching TZX's
// own "stop the tape" signal (a 0x20 pause block with pause==0) --
// confirmed against SpecIde's own stopData set (source/src/TZXFile.cc).
// A genuine, distinct signal from an ordinary pause, used by real
// multi-part loaders to mark a point where the tape should wait rather
// than keep playing through. nil is a valid, common state (no stop
// points recorded) and reads as "not a stop point" for any index.
StopPoints map[int]bool
// StopPointsIf48K is TZX's separate 0x2A ("Stop The Tape If In 48K
// Mode") signal -- a distinct set from StopPoints, matching SpecIde's
// own separate stopIf48K set (source/src/Tape.h: "Stop points only
// for 48K mode"). Real multi-part loaders use this to require manual
// intervention on memory-constrained machines while letting 128K-class
// machines, which don't have the same constraint, play straight
// through -- confirmed against SpecIde's own Tape::advance(): "if
// (is48K && stopIf48K.find(pointer) ...)". No pulses accompany this
// marker (see loadTZX's own case 0x2A): unlike an ordinary pause,
// SpecIde's own case 0x2A adds nothing to the pulse stream, just
// records the current position.
StopPointsIf48K map[int]bool
}
TapeState holds the current tape state
type VideoRenderer ¶
type VideoRenderer interface {
// Name is this renderer's registry key: "" for the standard renderer,
// or the exact -ns-graphics value it implements (e.g.
// NSGraphicsTimex001HiColour).
Name() string
// Decode reads whatever memory it needs -- through mem, through
// screen, or both -- and returns a 256x192 image.RGBA ready to
// display or save. mem is included even though the standard renderer
// does not use it, because a renderer whose display memory does not
// live on SpectrumScreen (e.g. a hi-colour screen-1 buffer, once T-11
// decides where that lives) needs a way to read it.
Decode(mem *SpectrumMemory, screen *SpectrumScreen) *image.RGBA
// Dimensions reports the pixel size of images this renderer's Decode
// returns. DisplayManager (GUI) and headless PNG output size
// themselves from this rather than assuming 256x192, since not every
// mode will be that size (see docs/TRACKING.md T-09's mode-zenzx-02,
// 512x384).
Dimensions() (width, height int)
// BorderMargins reports this renderer's border thickness, in this
// renderer's own output pixels, as (left, right, top, bottom). Border
// is optional per mode: a renderer with no border returns all zeros,
// and DisplayManager skips border compositing entirely in that case.
BorderMargins() (left, right, top, bottom int)
}
VideoRenderer turns Spectrum display memory into a displayed picture.
func LookupVideoRenderer ¶
func LookupVideoRenderer(graphicsMode string) (VideoRenderer, error)
LookupVideoRenderer resolves the renderer for a -ns-graphics value ("" for standard). It errors rather than silently falling back to standard, so a valid-but-not-yet-implemented mode fails loudly at startup instead of quietly rendering the standard screen while the summary line claims something else is active.
type Z80CPU ¶
type Z80CPU interface {
GetCycles() uint64
}
Z80CPU interface to avoid circular dependency
type ZenZX ¶
type ZenZX struct {
// contains filtered or unexported fields
}
func NewZenZX ¶
func NewZenZX(audioBackend AudioBackend) *ZenZX
func (*ZenZX) AttachLink ¶
AttachLink connects a link to the machine's I/O ports, or with nil takes the machine's link away.
func (*ZenZX) AutorunBASIC ¶
AutorunBASIC arranges for BASIC source text to be loaded and run on this machine once it has started. model is the machine's model as -model names it; name becomes the program's name on the tape (ten characters at most are kept).
func (*ZenZX) AutorunFile ¶
AutorunFile is AutorunBASIC for a text file; the program takes the file's name without its extension.
func (*ZenZX) AutorunPending ¶
AutorunPending reports whether an autorun has yet to finish typing.
func (*ZenZX) AutorunTAP ¶
AutorunTAP arranges for a prebuilt tape image (a .tap/.tzx that already carries its own loader, such as an assembled machine-code program) to be loaded and run once the machine has started. It types the same LOAD "" the BASIC path does; the tape's own loader takes it from there.
func (*ZenZX) Debug ¶
Debug returns a DebugView over this machine. It is the only entry point a debugger needs; the ZenZX internals it reaches stay unexported.
func (*ZenZX) DecodeDisplay ¶
DecodeDisplay draws the picture of the machine as it is now. Both front ends can call it -- the headless build does, to encode a PNG -- so neither needs to know which renderer is active. It is 256x192 for every machine but the Next, whose picture is the whole 320x256 frame, border included (640x256 with a double resolution layer): nextframe.go, and nextraster.go for what changes part of the way down it.
func (*ZenZX) DumpNextState ¶
DumpNextState writes the state of the Next's hardware that decides what is mapped and what is drawn: the registers that are not zero, the memory mapping, and the start of the palettes. It is the headless build's -next-dump, for working out why a program does not display.
func (*ZenZX) EnableDivMMC ¶
func (zx *ZenZX) EnableDivMMC(sdImage SDCardImage, sdSize int64, romImage []byte)
EnableDivMMC attaches a DivMMC interface (T-36) to this instance: the automap/CONMEM memory overlay plus the SD-card-over-SPI transport (divmmc.go, sdcard.go, io.go's EnableDivMMC), AND wires the CPU's own M1Hook to drive automap paging -- the one piece SpectrumIO.EnableDivMMC can't do itself, since io.go only holds the narrow Z80CPU interface (SetCPU), never zen80's concrete *z80.Z80.
M1Hook is a single func field, not a chain: this overwrites whatever hook was previously installed (e.g. the trace harness's own installM1Hook, zzz_trace_callstack_test.go) rather than composing with it. Harmless for this emulator's current uses -- DivMMC and the trace harness are never exercised in the same run -- but a real limitation if that ever changes; flagged rather than silently accepted.
func (*ZenZX) EnableZ80N ¶
func (zx *ZenZX) EnableZ80N()
EnableZ80N turns on the CPU core's Z80N (ZX Spectrum Next) extended instruction set. Off by default, matching zen80's own default -- none of ZenZX's existing -model options are the Next, and this method exists specifically for CPU-level Z80N verification (running a test binary and reading results back, e.g. via a "dump-mem" script action) rather than as a claim of Next hardware emulation (that is -model next: memory paging, sprites, the copper and the rest come with the machine, not with this). See -z80n in the headless and GUI entry points.
func (*ZenZX) FirstProgram ¶
FirstProgram is the name of the first BASIC program the machine has loaded, "" while it has loaded none. Once there is one it does not change.
func (*ZenZX) HandleInput ¶
func (zx *ZenZX) HandleInput()
HandleInput processes all input for the emulator
func (*ZenZX) InsertSecondCard ¶
InsertSecondCard puts the card image at path in the second slot, taking out the one that was there. The machine must have a DivMMC (a Next that boots NextZXOS has). NextZXOS looks at the slots when it starts and when its Browser is told to remount (M, then Y), so a card put in while it runs is seen after one of those.
func (*ZenZX) Load128KROM ¶
Load128KROM loads two separate 16KB ROM files for 128K models
func (*ZenZX) Load128KROMBytes ¶
Load128KROMBytes is Load128KROM's byte-data equivalent.
func (*ZenZX) LoadBIN ¶
LoadBIN loads the file at filename into memory starting at loadAddr.
If startAddr >= 0, the program counter is set to uint16(startAddr) so the blob begins executing on the next frame. Pass startAddr < 0 to load without altering PC (e.g. to stage data while existing code runs).
Loading is bank-aware: bytes are written via memory.Write against the current paging configuration. Callers that need a specific bank paged in should configure paging before calling LoadBIN.
func (*ZenZX) LoadBINWithSafeReturn ¶
LoadBINWithSafeReturn is LoadBIN, but for startAddr >= 0 it also gives the loaded code a safe place to return TO: a two-byte "JR $" (opcode 0x18, 0xFE -- jump to self, an infinite loop) is written at safeHaltAddr, and its address is pushed onto the stack before PC is set to startAddr.
This exists because a raw -bin load has no calling convention behind it the way Sinclair BASIC's "RANDOMIZE USR n" does on real hardware (which itself pushes a return address before jumping) -- plain LoadBIN leaves the stack exactly as the machine's own boot sequence left it. A test binary ending in a bare RET, expecting to be CALLed properly, instead pops whatever the stack already contained and jumps there: on real hardware or in CSpect that lands back in BASIC or NextZXOS safely, but a bare LoadBIN start has no such target, and execution runs away into unrelated memory, corrupting anything it happens to touch as it goes -- confirmed directly: two dump-mem reads of the same "finished" test result, taken at different frame counts after the same run, returned different values each time, worse the longer the wait, which is exactly the signature of an ongoing runaway write rather than a stable result. Routing the same RET into a harmless self-loop instead makes the result stable forever once written, so any sufficiently long wait after loading gives the same, correct answer.
Safe to call with SP already low (near 0x0000) in unusual configurations -- it just decrements SP by 2 and writes through the normal memory path, the same as two PUSH byte-writes would.
func (*ZenZX) LoadPlus3ROM ¶
LoadPlus3ROM loads four 16KB ROM files for +3 model
func (*ZenZX) LoadPlus3ROMBytes ¶
LoadPlus3ROMBytes is LoadPlus3ROM's byte-data equivalent.
func (*ZenZX) LoadROMBytes ¶
LoadROMBytes is LoadROM's byte-data equivalent, used when the caller has already resolved the ROM's bytes (from the embedded binary or the filesystem -- see resolveROMBytes in zenzx_headless.go/ zenzx_gui.go) rather than holding a bare path. LoadROM itself is now a thin wrapper around this.
func (*ZenZX) LoadSCR ¶
LoadSCR loads a raw ZX Spectrum screen dump (.scr) onto the display.
A .scr is exactly the display file: 6144 bytes of bitmap (0x4000-0x57FF) followed by 768 bytes of attributes (0x5800-0x5AFF), 6912 bytes total. Bytes are written through the normal memory path at 0x4000, so the screen mirror and the underlying RAM stay consistent (a running program would see the same bytes). Loading a .scr does not alter CPU state -- it paints the screen but does not start anything running.
Files shorter than 6912 bytes are loaded as far as they go; anything beyond 6912 bytes is ignored.
func (*ZenZX) LoadSZX ¶
LoadSZX loads a .szx (ZX-State) snapshot, delegating to zentools/pkg/szx. Saving to .szx is not supported.
func (*ZenZX) LoadSnapshot ¶
LoadSnapshot loads emulator state from a file with optional metadata validation
func (*ZenZX) LoadSnapshotFormat ¶
LoadSnapshotFormat loads a snapshot in the specified format
func (*ZenZX) LoadTS2068ROM ¶
LoadTS2068ROM loads the Home ROM (16K) and Extension ROM (8K) and switches memory into TS2068 mode. Deliberately does NOT set is128K -- TS2068's RAM organisation (16K Home Bank RAM + 32K upper RAM, screen mirroring at 0x4000-0x5AFF) is structurally identical to the existing 48K path, so is128K stays false and that addressing is reused unchanged. Only isTS2068 distinguishes it, gating the ROM-region special-casing in memory.go's Read.
func (*ZenZX) LoadTS2068ROMBytes ¶
LoadTS2068ROMBytes is LoadTS2068ROM's byte-data equivalent, used when the caller has already resolved the Home/Extension ROM bytes (from the embedded binary or the filesystem -- see resolveROMBytes in zenzx_headless.go/zenzx_gui.go) rather than holding bare paths.
func (*ZenZX) LoadZ80 ¶
LoadZ80 loads a .z80 snapshot (v1/v2/v3, 48K/128K), delegating to zentools/pkg/snapshot.
func (*ZenZX) OverrideROMBank ¶
OverrideROMBank replaces a single ROM bank of the currently loaded model's ROM set in place, leaving every other bank exactly as -model loaded it -- the mechanism behind -rom0 through -rom3 and behind -rom's own multi-path form (zenzx_headless.go/zenzx_gui.go), letting a program swap e.g. just the +3DOS ROM (bank 3) on an otherwise- standard +3, or just TS2068's Extension ROM (bank 1) on an otherwise- standard TS2068, without needing to also respecify every other bank the way LoadROM/Load128KROM/LoadPlus3ROM/LoadTS2068ROM all require.
Must be called after the model's own standard ROM set has already been loaded -- it edits banks in place, it doesn't establish which banks exist in the first place (that's is128K/isPlus3/isTS2068, already set by the -model load).
func (*ZenZX) PlayStopTape ¶
func (zx *ZenZX) PlayStopTape()
PlayStopTape toggles tape playback, a no-op if no tape is loaded. Extracted from handleAltCombinations (Alt+P); see ToggleTapeMode.
func (*ZenZX) ReleaseKey ¶
ReleaseKey simulates a key release at the given matrix position
func (*ZenZX) RemoveSecondCard ¶
func (zx *ZenZX) RemoveSecondCard()
RemoveSecondCard empties the second slot.
func (*ZenZX) RewindTape ¶
func (zx *ZenZX) RewindTape()
RewindTape rewinds the loaded tape to its start, a no-op if none is loaded. Extracted from handleAltCombinations (Alt+R); see ToggleTapeMode.
func (*ZenZX) RunTurboAwareFrame ¶
RunTurboAwareFrame is the single entry point a driver loop should call once per frame: it owns the whole Turbo-mode lifecycle (snapshot-in the first frame the tape is playing in TapeTurbo mode, periodic real-memory sync as Position crosses each BlockBoundaries entry -- now purely for screen-shadow/script-visibility freshness, since turboRemap already handles paging correctness immediately as it happens -- snapshot-out the moment the tape stops), falling through to plain RunFrame in every other case (tape not loaded, not in Turbo mode, already finished, or a script-level barrier -- wait-boot, wait-screen, wait-attr, wait-mem -- is currently blocking on real screen/memory content the fast path's own unsynced scratch memory has no way to reflect). A caller never needs to reason about the lifecycle itself, only call this once per frame, passing whether such a barrier is currently active (nil scheduler, or no barrier: pass false).
zx.turboNextBoundary is deliberately NOT reset when pausing for a barrier -- only turboActive toggles. Block-boundary progress is a property of how far the tape has actually loaded, not of whether the fast path happens to be active on any given frame; pausing and resuming must not replay or skip a sync.
func (*ZenZX) SaveSNA ¶
SaveSNA saves the current state in .sna format SaveSNA saves the current state in .sna format, delegating to zentools/pkg/snapshot (the verified codec). Replaces the previous in-tree implementation, which lost PC in 48K output.
func (*ZenZX) SaveSnapshot ¶
SaveSnapshot saves the complete emulator state to a file with metadata
func (*ZenZX) SaveSnapshotFormat ¶
SaveSnapshotFormat saves a snapshot in the specified format
func (*ZenZX) SaveZ80 ¶
SaveZ80 saves the current state in .z80 format (version 3, 128K-capable), delegating to zentools/pkg/snapshot.
func (*ZenZX) SecondCard ¶
SecondCard returns the path of the card in the second slot, "" when it is empty.
func (*ZenZX) SelectVideoRenderer ¶
SelectVideoRenderer resolves and activates the renderer for a -ns-graphics value ("" for standard), returning an error if no renderer is registered for it. See LookupVideoRenderer in videorender.go.
func (*ZenZX) SetAYVolume ¶
SetAYVolume sets the AY chip volume (0.0 to 1.0)
func (*ZenZX) SetBeeperVolume ¶
SetBeeperVolume sets the beeper volume (0.0 to 1.0)
func (*ZenZX) SetDisplay ¶
SetDisplay gives the machine the display it draws through, and tells that display about the machine: its audio (for the debug overlay), its I/O (for the 640x256 Layer 2 mode's minimum-zoom clamp, see DisplayManager.io) and, if one has been selected, its video renderer. nil puts back the display that draws nothing.
func (*ZenZX) SetMasterVolume ¶
SetMasterVolume sets the master audio volume (0.0 to 1.0)
func (*ZenZX) ShowTapeInfo ¶
func (zx *ZenZX) ShowTapeInfo()
ShowTapeInfo prints the tape's status and block list, a no-op if none is loaded. Extracted from handleAltCombinations (Alt+I); see ToggleTapeMode.
func (*ZenZX) TogglePause ¶
func (zx *ZenZX) TogglePause()
TogglePause flips the emulator's paused state. Extracted from handleFunctionKeys (F2) so the menu bar's Machine menu can call the identical logic rather than duplicate it.
func (*ZenZX) ToggleTapeMode ¶
func (zx *ZenZX) ToggleTapeMode()
ToggleTapeMode switches between accurate and fast tape loading, a no-op if no tape is loaded. Extracted from handleAltCombinations (Alt+T) so the menu bar's Tape menu can call the identical logic rather than duplicate it.
Source Files
¶
- audio_common.go
- audio_device_oto.go
- audio_engine.go
- audio_oto.go
- audio_selector.go
- audio_sinc_filter.go
- autorun.go
- ay8912.go
- ay_gate.go
- bootbaselines.go
- bootdetect.go
- contention.go
- custom_roms_menu.go
- custom_roms_menu_gui.go
- debugview.go
- display.go
- display_constants.go
- display_core.go
- display_nextula.go
- divmmc.go
- divmmc_entries.go
- dockicon_gui.go
- dockround_gui.go
- dsk.go
- dskadd.go
- embedded_roms.go
- fdc.go
- floatingbus.go
- floppies_gui.go
- gui_demo_overlay.go
- hud_draw_gui.go
- hud_gui.go
- im2vector.go
- info_gui.go
- input.go
- io.go
- joyports.go
- joystick.go
- keyboard_script.go
- layer2.go
- layer2accessport.go
- link.go
- loadbin.go
- logging.go
- machine_model.go
- machinedeck_gui.go
- markdownmodal_gui.go
- memory.go
- menubar_gui.go
- modelswitch_gui.go
- mountdrawer_draw_gui.go
- mountdrawer_gui.go
- mouse.go
- multi.go
- multi_gui.go
- nextadd.go
- nextaltrom.go
- nextbootable.go
- nextchain.go
- nextconfig.go
- nextcopper.go
- nextdma.go
- nextdump.go
- nextframe.go
- nextint.go
- nextlineint.go
- nextlores.go
- nextmultiface.go
- nextpalette.go
- nextphys.go
- nextraster.go
- nextreg.go
- nextreg8e.go
- nextreglog.go
- nextremount.go
- nextsetup_cli.go
- nextsetup_gui.go
- nextsoftula.go
- nextspeed.go
- nexttilemap.go
- nexttimex.go
- nextvideoline.go
- nonstandard.go
- program_name.go
- rom_export.go
- scheduler.go
- screen.go
- screen_read.go
- script.go
- sdcard.go
- sdcard2.go
- sdcard_write.go
- sdcardmenu_gui.go
- sdcards_gui.go
- snapshot.go
- snapshot_adapter.go
- snapshot_chunks.go
- snapshot_debug.go
- snapshot_formats.go
- sprite.go
- spriteports.go
- symtab.go
- tape.go
- tape_types.go
- ts2068.go
- turbo.go
- turbo_pages.go
- version_main.go
- videorender.go
- videorender_gpu.go
- videorender_hicolour.go
- zenzx.go
- zenzx_gui.go
Directories
¶
| Path | Synopsis |
|---|---|
|
cmd
|
|
|
tapereport
command
Command tapereport generates an HTML compatibility report for zenzx's TAP/TZX decoding and playback wiring, measured against a real corpus of tape files rather than synthetic test cases.
|
Command tapereport generates an HTML compatibility report for zenzx's TAP/TZX decoding and playback wiring, measured against a real corpus of tape files rather than synthetic test cases. |
|
zendbg
command
Command zendbg is the standalone CLI surface of the ZenZX debugger: it builds one headless machine, attaches the debug engine, and reads commands on stdin.
|
Command zendbg is the standalone CLI surface of the ZenZX debugger: it builds one headless machine, attaches the debug engine, and reads commands on stdin. |
|
zenzx
command
Command zenzx is the ZenZX emulator with its window.
|
Command zenzx is the ZenZX emulator with its window. |
|
contrib
|
|
|
tape-corpus-harness
module
|
|
|
pkg
|
|
|
debug
Package debug is the ZenZX debugger engine: a debug session over one running machine, address-keyed, built on the machine's DebugView facade and zendis for disassembly.
|
Package debug is the ZenZX debugger engine: a debug session over one running machine, address-keyed, built on the machine's DebugView facade and zendis for disassembly. |
|
debugcmd
Package debugcmd is the command layer of the ZenZX debugger: it parses a line of text into a command and renders engine results as fixed-format text.
|
Package debugcmd is the command layer of the ZenZX debugger: it parses a line of text into a command and renders engine results as fixed-format text. |
|
fonts
Package fonts embeds the bundled BDF bitmap fonts and decodes them through pkg/bdf.
|
Package fonts embeds the bundled BDF bitmap fonts and decodes them through pkg/bdf. |
|
machineconfig
Package machineconfig loads and validates the Machine menu's own configured layout from machines.json -- which groups, separators, titles, and (single-level) submenus it's organised into, and which display label each model gets.
|
Package machineconfig loads and validates the Machine menu's own configured layout from machines.json -- which groups, separators, titles, and (single-level) submenus it's organised into, and which display label each model gets. |
|
nextcard
Package nextcard obtains and prepares the files a ZX Spectrum Next needs to boot NextZXOS: the SD card image, the DivMMC ROM and the boot ROM.
|
Package nextcard obtains and prepares the files a ZX Spectrum Next needs to boot NextZXOS: the SD card image, the DivMMC ROM and the boot ROM. |
|
nextdisk
Package nextdisk is the read side of zenzx's future DivMMC/SD-card bridge: opening a FAT16/FAT32 disk image and reading named files out of it, the same shape a real ZX Spectrum Next's boot ROM and TBBLUE.FW use to find config.ini, menu.def, and the machine/ peripheral ROM images during the real boot sequence (see docs/NEXT_BOOT_REFERENCE.md, stages 1-2).
|
Package nextdisk is the read side of zenzx's future DivMMC/SD-card bridge: opening a FAT16/FAT32 disk image and reading named files out of it, the same shape a real ZX Spectrum Next's boot ROM and TBBLUE.FW use to find config.ini, menu.def, and the machine/ peripheral ROM images during the real boot sequence (see docs/NEXT_BOOT_REFERENCE.md, stages 1-2). |
|
settingsconfig
Package settingsconfig loads, validates, and saves the user's menu-configured preferences -- theme, font, font zoom, display scale, and whether the menu bar is pinned shown -- to settings.json.
|
Package settingsconfig loads, validates, and saves the user's menu-configured preferences -- theme, font, font zoom, display scale, and whether the menu bar is pinned shown -- to settings.json. |
|
version
Package version provides version information for ZenZX.
|
Package version provides version information for ZenZX. |
|
tools
|
|
|
depmap
command
Command depmap reports the file-level dependency structure of one Go package under one build configuration: which file references which, how the references fall between named clusters of files, which names are declared once per build tag (the seams between configurations), the package-level variables, and the process-level calls (os.Exit, flag, log, fmt.Print...) that tie a package to being a program.
|
Command depmap reports the file-level dependency structure of one Go package under one build configuration: which file references which, how the references fall between named clusters of files, which names are declared once per build tag (the seams between configurations), the package-level variables, and the process-level calls (os.Exit, flag, log, fmt.Print...) that tie a package to being a program. |
|
mkfont
command
Command mkfont extracts the 8x8 ZX Spectrum character set (codes 32-127) from a Spectrum 48K ROM and writes it as a BDF font, reproducing the exact layout of pkg/fonts/sinclair.bdf.
|
Command mkfont extracts the 8x8 ZX Spectrum character set (codes 32-127) from a Spectrum 48K ROM and writes it as a BDF font, reproducing the exact layout of pkg/fonts/sinclair.bdf. |











