init repo

This commit is contained in:
RomanRom2 committed 2025-01-28 19:17:01 +03:00
commit 90e6151613
3260 files changed
+3745062

No files matched your search

+115
View File
@@ -0,0 +1,115 @@
const SAMPLES_PER_SECOND = 44100;
var AudioContext = window.AudioContext || window.webkitAudioContext;
/** Audio output */
export class Audio {
/**
* Create an Audio.
* @param {Gigatron} cpu - The CPU
*/
constructor(cpu) {
this.cpu = cpu;
let context = this.context = new AudioContext();
this.mute = false;
this.volume = 0.33;
this.cycle = 0;
this.bias = 0;
this.alpha = 0.99;
this.scheduled = 0;
this.full = false;
let numSamples = Math.floor(SAMPLES_PER_SECOND / 50);
this.buffers = [];
for (let i = 0; i < 8; i++) {
let buffer = context.createBuffer(1,
numSamples,
SAMPLES_PER_SECOND);
this.buffers.push(buffer);
}
this.headBufferIndex = 0;
this.tailBufferIndex = 0;
this.duration = this.buffers[0].duration;
this.tailTime = 0; // time at which tail buffer will start
this.headTime = this.duration; // time at which head buffer will end
this.channelData = this.buffers[0].getChannelData(0);
this.sampleIndex = 0;
}
/** drain completed head buffers */
drain() {
let currentTime = this.context.currentTime;
let headTime = this.headTime;
let headBufferIndex = this.headBufferIndex;
let scheduled = this.scheduled;
let numBuffers = this.buffers.length;
while (scheduled > 0 && headTime < currentTime) {
headBufferIndex = (headBufferIndex == numBuffers - 1) ? 0 :
(headBufferIndex + 1);
headTime += this.duration;
scheduled--;
}
this.headTime = headTime;
this.scheduled = scheduled;
this.full = scheduled == numBuffers;
}
/** flush current tail buffer */
_flushChannelData() {
let context = this.context;
let currentTime = context.currentTime;
let tailBufferIndex = this.tailBufferIndex;
let buffer = this.buffers[tailBufferIndex];
let scheduled = this.scheduled;
let numBuffers = this.buffers.length;
/* if the tail can't keep ahead of realtime, jump it to now */
if (this.tailTime < currentTime) {
// console.log('audio skip');
this.tailTime = currentTime;
this.headTime = currentTime + this.duration;
this.headBufferIndex = tailBufferIndex;
scheduled = 0;
}
if (!this.mute) {
let source = context.createBufferSource();
source.buffer = buffer;
source.connect(context.destination);
source.start(this.tailTime);
}
scheduled++;
this.tailTime += this.duration;
tailBufferIndex = (tailBufferIndex == numBuffers - 1) ? 0 :
(tailBufferIndex + 1);
this.channelData = this.buffers[tailBufferIndex].getChannelData(0);
this.sampleIndex = 0;
this.tailBufferIndex = tailBufferIndex;
this.scheduled = scheduled;
this.full = scheduled == numBuffers;
}
/** advance simulation by one tick */
tick() {
this.cycle += SAMPLES_PER_SECOND;
if (this.cycle >= this.cpu.hz) {
this.cycle -= this.cpu.hz;
let sample = (this.cpu.outx >> 4) / 8;
this.bias = (this.alpha * this.bias) + ((1 - this.alpha) * sample);
sample = (sample - this.bias) * this.volume;
this.channelData[this.sampleIndex++] = sample;
if (this.sampleIndex == this.channelData.length) {
this._flushChannelData();
}
}
}
}
@@ -0,0 +1,31 @@
/** Blinkenlights on outx register */
export class BlinkenLights {
/** Create a new BlinkenLights
* @param {Gigatron} cpu
*/
constructor(cpu) {
this.cpu = cpu;
this.outx = cpu.outx & 0x0f;
this.timer = null;
for (let i = 0; i < 4; i++) {
$(`.led-${i}`).addClass(
`led-${(this.outx & (1<<i)) ? 'on' : 'off'}`);
}
}
/** advance simulation by one tick */
tick() {
let outx = this.cpu.outx & 0x0f;
let changed = this.outx ^ outx;
if (changed) {
for (let i = 0; i < 4; i++) {
if (changed & (1 << i)) {
$(`.led-${i}`).toggleClass('led-on led-off');
}
}
this.outx = outx;
}
}
}
+155
View File
@@ -0,0 +1,155 @@
export const BUTTON_A = 0x80;
export const BUTTON_B = 0x40;
export const BUTTON_SELECT = 0x20;
export const BUTTON_START = 0x10;
export const BUTTON_UP = 0x08;
export const BUTTON_DOWN = 0x04;
export const BUTTON_LEFT = 0x02;
export const BUTTON_RIGHT = 0x01;
/** map from controller button name to inReg bit */
const buttonMap = {
a: BUTTON_A,
b: BUTTON_B,
select: BUTTON_SELECT,
start: BUTTON_START,
up: BUTTON_UP,
down: BUTTON_DOWN,
left: BUTTON_LEFT,
right: BUTTON_RIGHT,
};
const axisThreshold = 0.5;
/** map from standard gamepad button index to inReg bit */
const gamepadButtonMap = {
0: buttonMap.a,
1: buttonMap.b,
6: buttonMap.b,
7: buttonMap.a,
8: buttonMap.select,
9: buttonMap.start,
12: buttonMap.up,
13: buttonMap.down,
14: buttonMap.left,
15: buttonMap.right,
};
/** map from standard gamepad axis index to negative and positive inReg bits */
const gamepadAxisMap = {
0: [buttonMap.left, buttonMap.right],
1: [buttonMap.up, buttonMap.down],
};
/** Gamepad device */
export class Gamepad {
/** Create a Gamepad
* @param {Gigatron} cpu - The cpu to control
* @param {Object.<string,string[]>} keys - Map from controller button
* name to list of keys
*/
constructor(cpu, keys) {
this.cpu = cpu;
this.enabled = false;
this.pressed = 0;
this.keyMap = {};
/* build map from keyboard key to controller button name */
for (let button of Object.keys(keys)) {
for (let key of keys[button]) {
this.keyMap[key] = buttonMap[button];
}
}
/* build map of ASCII codes that the Gigatron understands as well */
this.asciiMap = {
'Tab': 9,
'Enter': 10,
'Escape': 27,
'Esc': 27,
'Delete': 127,
'Backspace': 127,
};
for (let ascii=32; ascii<127; ascii++) {
this.asciiMap[String.fromCharCode(ascii)] = ascii;
}
for (let fnKey=1; fnKey<=12; fnKey++) {
this.asciiMap['F' + fnKey] = 0xc0 + fnKey;
}
}
/** start handling key events */
start() {
$(document)
.on('keydown', (event) => {
let bit = this.keyMap[event.key];
if (bit) {
this.pressed |= bit;
event.preventDefault();
} else {
let ascii = this.asciiMap[event.key];
if (ascii) {
if (event.ctrlKey) {
// Control codes (e.g. Ctrl-C for ETX or BREAK)
if (ascii == 63 /*'?'*/) ascii = 127;
else if (ascii == 32 /*' '*/) ascii = 0;
else ascii &= 31;
}
this.pressed = ascii ^ 0xff; /// will be inverted again in tick()
event.preventDefault();
}
}
})
.on('keyup', (event) => {
let bit = this.keyMap[event.key];
if (bit) {
this.pressed &= ~bit;
} else {
this.pressed = 0;
}
event.preventDefault();
});
this.enabled = true;
}
/** stop handling key events */
stop() {
$(document).off('keydown keyup');
this.enabled = false;
}
/** check gamepads */
tick() {
let pressed = this.pressed;
if (navigator.getGamepads) {
let gamepads = navigator.getGamepads();
for (let gamepad of gamepads) {
if (gamepad) {
// check the axes
for (let axisIndex of Object.keys(gamepadAxisMap)) {
let axis = gamepad.axes[axisIndex];
let bits = gamepadAxisMap[axisIndex];
if (axis < -axisThreshold) {
pressed |= bits[0];
} else if (axis > axisThreshold) {
pressed |= bits[1];
}
}
// check the buttons
for (let buttonIndex of Object.keys(gamepadButtonMap)) {
let bit = gamepadButtonMap[buttonIndex];
if (gamepad.buttons[buttonIndex].pressed) {
pressed |= bit;
}
}
}
}
}
if (this.enabled) {
this.cpu.inReg = pressed ^ 0xff; // active low
}
}
}
+283
View File
@@ -0,0 +1,283 @@
/**
* @return {Uint8} a random Uint8
* */
function randomUint8() {
return Math.floor(Math.random() * 256);
}
/** Gigatron processor */
export class Gigatron {
/** Create a Gigatron
* @param {Object} options
*/
constructor(options) {
this.hz = options.hz || 6250000;
this.rom = new Uint16Array(1 << (options.romAddressWidth || 16));
this.romMask = this.rom.length - 1;
this.ram = new Uint8Array(1 << (options.ramAddressWidth || 15));
this.ramMask = this.ram.length - 1;
this.reset();
// randomize ram
for (let i = 0; i < this.ram.length; i++) {
this.ram[i] = randomUint8();
}
console.log(this.ram.length, this.ramMask);
}
/** reset registers to power-on state */
reset() {
this.pc = 0;
this.nextpc = (this.pc + 1) & this.romMask;
this.ac = 0;
this.x = 0;
this.y = 0;
this.out = 0;
this.outx = 0;
this.inReg = 0xff; // active low!
this.ctrl = 0x7c;
this.bank = 0;
this.prevctrl = -1;
this.miso = 0;
}
/** advance simulation by one tick */
tick() {
let pc = this.pc;
this.pc = this.nextpc;
this.nextpc = (this.pc + 1) & this.romMask;
this.prevctrl = -1;
let ir = this.rom[pc];
let op = (ir >> 13) & 0x0007;
let mode = (ir >> 10) & 0x0007;
let bus = (ir >> 8) & 0x0003;
let d = (ir >> 0) & 0x00ff;
switch (op) {
case 0:
case 1:
case 2:
case 3:
case 4:
case 5:
this.aluOp(op, mode, bus, d);
break;
case 6:
this.storeOp(mode, bus, d);
break;
case 7:
this.branchOp(mode, bus, d);
break;
}
}
/** perform an alu op
* @param {number} op
* @param {number} mode
* @param {number} bus
* @param {number} d
*/
aluOp(op, mode, bus, d)
{
let b = 0;
switch (bus) {
case 0:
b = d;
break;
case 1:
let addr = this.addr(mode, d);
if (this.ctrl & 1) {
b = this.miso;
} else {
if (addr & 0x8000) { addr = addr ^ this.bank; }
b = this.ram[addr & this.ramMask];
}
break;
case 2:
b = this.ac;
break;
case 3:
b = this.inReg;
break;
}
switch (op) {
case 1:
b = this.ac & b;
break;
case 2:
b = this.ac | b;
break;
case 3:
b = this.ac ^ b;
break;
case 4:
b = (this.ac + b) & 0xff;
break;
case 5:
b = (this.ac - b) & 0xff;
break;
}
switch (mode) {
case 0:
case 1:
case 2:
case 3:
this.ac = b;
break;
case 4:
this.x = b;
break;
case 5:
this.y = b;
break;
case 6:
case 7:
let rising = ~this.out & b;
this.out = b;
// rising edge of out[6] registers outx from ac
if (rising & 0x40) {
this.outx = this.ac;
}
break;
}
}
/** perform a store op
* @param {number} mode
* @param {number} bus
* @param {number} d
*/
storeOp(mode, bus, d)
{
let b = 0;
let w = 1;
let addr = this.addr(mode, d);
switch (bus) {
case 0:
b = d;
break;
case 1:
if (this.ram.length <= 65536) {
b = 0;
console.error('UNDEFINED BEHAVIOR!');
} else {
this.prevctrl = this.ctrl;
this.ctrl = addr & 0x80fd;
this.bank = ((this.ctrl & 0xc0) << 9) ^ 0x8000;
w = 0;
}
break;
case 2:
b = this.ac;
break;
case 3:
b = this.inReg;
break;
}
if (w) {
if (addr & 0x8000) { addr = addr ^ this.bank; }
this.ram[addr & this.ramMask] = b;
}
switch (mode) {
case 4:
this.x = this.ac;
break;
case 5:
this.y = this.ac;
break;
}
}
/** perform a branch op
* @param {number} mode
* @param {number} bus
* @param {number} d
*/
branchOp(mode, bus, d) {
const ZERO = 0x80;
let c = true;
let ac = this.ac ^ ZERO;
let base = this.pc & 0xff00;
switch (mode) {
case 0: // jmp
base = this.y << 8;
break;
case 1: // bgt
c = ac > ZERO;
break;
case 2: // blt
c = ac < ZERO;
break;
case 3: // bne
c = ac != ZERO;
break;
case 4: // beq
c = ac == ZERO;
break;
case 5: // bge
c = ac >= ZERO;
break;
case 6: // ble
c = ac <= ZERO;
break;
case 7: // bra
c = true;
break;
}
if (c) {
let b = this.offset(bus, d);
this.nextpc = base | b;
}
}
/** calculate a ram address
* @param {number} mode
* @param {number} d
* @return {number} the address
*/
addr(mode, d) {
switch (mode) {
case 0:
case 4:
case 5:
case 6:
return d;
case 1:
return this.x;
case 2:
return (this.y << 8) | d;
case 3:
return (this.y << 8) | this.x;
case 7:
let addr = (this.y << 8) | this.x;
this.x = (this.x + 1) & 0xff;
return addr;
}
}
/** calculate a branch page offset
* @param {number} bus
* @param {number} d
* @return {number} page offset
*/
offset(bus, d) {
switch (bus) {
case 0:
return d;
case 1:
// RAM always has at least 1 page, so no need to mask address
return this.ram[d];
case 2:
return this.ac;
case 3:
return this.inReg;
}
}
}
@@ -0,0 +1 @@
roms/dev128k7.rom
+259
View File
@@ -0,0 +1,259 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=640, initial-scale=0.5">
<title>Gigatron</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css" integrity="sha384-9gVQ4dYFwwWSjIDZnLEWnxCjeSWFphJiwGPXr1jddIhOegiu1FwO5qRGvFXOdJZ4" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.0/umd/popper.min.js" integrity="sha384-cs/chFZiN24E4KMATLdqdvsezGxaGsi4hLGOzlXwp5UZB1LY//20VyM2taTB4QvJ" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js" integrity="sha384-uefMccjFJAIv6A+rW+L4AHf99KvxDjWSu1z9VI8SKNVmz4sk7buKt/6v9KI65qnm" crossorigin="anonymous"></script>
<script src="https://unpkg.com/rxjs@^7/dist/bundles/rxjs.umd.min.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootswatch/4.1.0/slate/bootstrap.min.css" integrity="sha384-A0hm/Pn0Gvk8w7szlEuTOZrIyQCCBNXQF9ccseoCI36nWRfMEAapo5UJ56zLPvPw" crossorigin="anonymous">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/open-iconic/1.1.1/font/css/open-iconic-bootstrap.min.css" integrity="sha256-BJ/G+e+y7bQdrYkS2RBTyNfBHpA9IuGaPmf9htub5MQ=" crossorigin="anonymous" />
<script type="module" src="./main.js"></script>
<style>
kbd {
background-color: black;
}
#vga-canvas {
background-color: black;
}
.gamepad-btn.pressed {
fill: #00f;
fill-opacity: 0.5;
}
.gamepad-btn:hover {
stroke: gray;
stroke-width: 5;
}
.led.led-on {
--led-lamp-fill: url(#led-lamp-on);
--led-hilight-fill: url(#led-hilight-on);
}
.led.led-off {
--led-lamp-fill: url(#led-lamp-off);
--led-hilight-fill: url(#led-hilight-off);
}
</style>
</head>
<body>
<div class="container">
<div class="row mt-3">
<div class="col">
<div class="mx-auto" style="width:640px;">
<!-- LOGO -->
<!--
<a href="https://gigatron.io">
<img src="https://gigatron.io/wp-content/uploads/2018/02/cropped-logo2.png" width="350" height="70">
</a>
<hr>
-->
<!-- BLINKENLIGHTS -->
<svg xmlns="http://www.w3.org/2000/svg" xlink:xmlns="http://www.w3.org/1999/xlink" width="80" height="24">
<defs>
<linearGradient id="led-lamp-on" x1="50%" x2="50%" y1="0%" y2="100%">
<stop offset="0%" stop-color="#e00"/>
<stop offset="100%" stop-color="#e22"/>
</linearGradient>
<linearGradient id="led-lamp-off" x1="50%" x2="50%" y1="0%" y2="100%">
<stop offset="0%" stop-color="#800"/>
<stop offset="100%" stop-color="#822"/>
</linearGradient>
<linearGradient id="led-hilight-on" x1="50%" x2="50%" y1="0%" y2="100%">
<stop offset="0%" stop-color="#e88"/>
<stop offset="100%" stop-color="#e00"/>
</linearGradient>
<linearGradient id="led-hilight-off" x1="50%" x2="50%" y1="0%" y2="100%">
<stop offset="0%" stop-color="#888"/>
<stop offset="100%" stop-color="#800"/>
</linearGradient>
<g id="led">
<circle cx="0" cy="0" r="8" fill="var(--led-lamp-fill)"/>
<ellipse cx="0" cy="-3.25" rx="5" ry="4" fill="var(--led-hilight-fill)"/>
</g>
</defs>
<use class="led led-0" xlink:href="#led" x="10" y="12"/>
<use class="led led-1" xlink:href="#led" x="30" y="12"/>
<use class="led led-2" xlink:href="#led" x="50" y="12"/>
<use class="led led-3" xlink:href="#led" x="70" y="12"/>
</svg>
<!-- VGA -->
<canvas id="vga-canvas" class="border border-white rounded p-1" width="640" height="480"></canvas>
<hr>
<div class="row">
<div>
<!-- GAMEPAD -->
<svg class="gamepad" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 630 250" width="400" height="180">
<defs>
<radialGradient id="button-gradient" fx="0.8" fy="0.8">
<stop offset="5%" stop-color="gray"/>
<stop offset="100%" stop-color="black"/>
</radialGradient>
</defs>
<g>
<rect x="0" y="0" width="630" height="250" rx="15" ry="15" stroke="#802020" stroke-width="5" fill="#82332f"/>
<path d="m 15,30 a 15,15 0 0 1 15,-15 h 180 a 15,15 0 0 1 15,15 v 60 a 15,15 0 0 0 15,15 h 360 a 15,15 0 0 1 15,15 v 100 a 15,15 0 0 1 -15,15 h -570 a 15,15 0 0 1 -15,-15 z" stroke="#f0d0d0" fill="#f7f1db"/>
<line x1="15" y1="200" x2="615" y2="200" stroke-width="4" stroke="black"/>
<line x1="15" y1="208" x2="615" y2="208" stroke-width="4" stroke="black"/>
</g>
<g transform="translate(102,150)">
<!-- <rect id="dpad" x="-80" y="-80" width="160" height="160" fill="none"/> -->
<path d="m-24,-68 a4,4 0 0,1 4,-4 h40 a4,4 0 0,1 4,4 v40 a4,4 0 0,0 4,4 h40 a4,4 0 0,1 4,4 v40 a4,4 0 0,1 -4,4 h-40 a4,4 0 0,0 -4,4 v40 a 4,4 0 0,1 -4,4 h-40 a4,4 0 0,1 -4,-4 v-40 a4,4 0 0,0 -4,-4 h-40 a4,4 0 0,1 -4,-4 v-40 a4,4 0 0,1 4,-4 h40 a4,4 0 0,0 4,-4 z" stroke="#82332f" stroke-width="5" fill="black"/>
<circle cx="0" cy="0" r="10" fill="url(#button-gradient)"/>
<g transform="translate(-48,0) rotate(0)">
<path d="m-15,0 l30,-15 v30 z" fill="#444"/>
<rect class="gamepad-btn gamepad-btn-left" x="-24" y="-24" width="48" height="48" rx="4" ry="4" fill-opacity="0"/>
</g>
<g transform="translate(48,0) rotate(180)">
<path d="m-15,0 l30,-15 v30 z" fill="#444"/>
<rect class="gamepad-btn gamepad-btn-right" x="-24" y="-24" width="48" height="48" rx="4" ry="4" fill-opacity="0"/>
</g>
<g transform="translate(0,-48) rotate(90)">
<path d="m-15,0 l30,-15 v30 z" fill="#444"/>
<rect class="gamepad-btn gamepad-btn-up" x="-24" y="-24" width="48" height="48" rx="4" ry="4" fill-opacity="0"/>
</g>
<g transform="translate(0,48) rotate(270)">
<path d="m-15,0 l30,-15 v30 z" fill="#444"/>
<rect class="gamepad-btn gamepad-btn-down" x="-24" y="-24" width="48" height="48" rx="4" ry="4" fill-opacity="0"/>
</g>
</g>
<g transform="translate(300,190)">
<rect x="-100" y="-30" width="200" height="60" rx="30" ry="30" stroke="#82332f" stroke-width="8" fill="#954540"/>
<g transform="translate(-45)">
<text x="0" y="-40" font-family="sans-serif" font-size="16" text-anchor="middle" fill="black">SELECT</text>
<rect x="-35" y="-12" width="70" height="24" rx="10" ry="10" fill="#222"/>
<rect class="gamepad-btn gamepad-btn-select" x="-35" y="-12" width="70" height="24" rx="10" ry="10" fill-opacity="0"/>
</g>
<g transform="translate(45)">
<text x="0" y="-40" font-family="sans-serif" font-size="16" text-anchor="middle" fill="black">START</text>
<rect x="-35" y="-12" width="70" height="24" rx="10" ry="10" fill="#222"/>
<rect class="gamepad-btn gamepad-btn-start" x="-35" y="-12" width="70" height="24" rx="10" ry="10" fill-opacity="0"/>
</g>
</g>
<g transform="translate(510,200)">
<g transform="translate(-50)">
<circle cx="0" cy="0" r="15" fill="black"/>
<text x="0" y="6" font-family="sans-serif" font-size="18" font-weight="bold" text-anchor="middle" fill="#f7f1db">A</text>
</g>
<circle cx="0" cy="0" r="30" stroke="#82332f" stroke-width="5" fill="url(#button-gradient)"/>
<circle class="gamepad-btn gamepad-btn-a" cx="0" cy="0" r="30" fill-opacity="0"/>
</g>
<g transform="translate(450,135)">
<g transform="translate(-50)">
<circle cx="0" cy="0" r="15" fill="black"/>
<text x="0" y="6" font-family="sans-serif" font-size="18" font-weight="bold" text-anchor="middle" fill="#f7f1db">B</text>
</g>
<circle cx="0" cy="0" r="30" stroke="#82332f" stroke-width="5" fill="url(#button-gradient)"/>
<circle class="gamepad-btn gamepad-btn-b" cx="0" cy="0" r="30" fill-opacity="0"/>
</g>
<g transform="translate(570,135)">
<circle cx="0" cy="0" r="30" stroke="#82332f" stroke-width="5" fill="url(#button-gradient)"/>
<circle cx="0" cy="0" r="30" fill-opacity="0"/>
</g>
<g transform="translate(510,70)">
<circle cx="0" cy="0" r="30" stroke="#82332f" stroke-width="5" fill="url(#button-gradient)"/>
<circle cx="0" cy="0" r="30" fill-opacity="0"/>
</g>
</svg>
</div>
<div class="col">
<!-- VOLUME -->
<div class="form-row">
<div class="col-sm-10">
<input id="volume-slider" type="range" class="custom-range"> Volume <label for="volume-slider"></label>
</div>
<div class="col">
<span id="unmute" class="btn btn-sm btn-danger oi oi-volume-off d-none" style="width:30px;" data-toggle="tooltip" title="Unmute"></span>
<span id="mute" class="btn btn-sm btn-success oi oi-volume-high" style="width:30px;" data-toggle="tooltip" title="Mute"></span>
</div>
</div>
<!-- FILE LOADER -->
<form>
<div class="form-group">
<div class="custom-file">
<input id="load-file-input" type="file" class="form-control custom-file-input" accept=".gt1,.gt1x">
<label class="custom-file-label" for="load-file-input">Load GT1 file</label>
</div>
</div>
</form>
<!-- VHD LOADER -->
<form>
<div class="form-group">
<div class="custom-file">
<input id="load-vhd-input" type="file" class="form-control custom-file-input" accept=".vhd,.img">
<label class="custom-file-label" for="load-vhd-input">Mount VHD image</label>
</div>
</div>
</form>
</div>
</div>
<hr>
<!-- KEYMAP -->
Keyboard shortcuts:
<p>
<dl class="row">
<dt class="col-sm-2"><span class="badge badge-pill badge-secondary">[A] button</span></dt>
<dd class="col-sm-4"><kbd>Delete/End key</kbd></dd>
<dt class="col-sm-2"><span class="badge badge-pill badge-secondary">[B] button</span></dt>
<dd class="col-sm-4"><kbd>Insert/Home key</kbd></dd>
<dt class="col-sm-2"><span class="badge badge-pill badge-secondary">[Select] button</span></dt>
<dd class="col-sm-4"><kbd>PageDown key</kbd></dd>
<dt class="col-sm-2"><span class="badge badge-pill badge-secondary">[Start] button</span></dt>
<dd class="col-sm-4"><kbd>PageUp key</kbd></dd>
</dl>
</div>
</div>
</div>
</div>
<div id="error-modal" class="modal fade" role="alert">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h4>Error</h4>
<button type="button" class="close" data-dismiss="modal"><span class="oi oi-x"></span></button>
</div>
<div id="error-modal-body" class="modal-body">
</div>
</div>
</div>
</div>
</body>
</html>
+334
View File
@@ -0,0 +1,334 @@
import {
HSYNC,
VSYNC,
} from './vga.js';
import {
BUTTON_DOWN,
BUTTON_A,
} from './gamepad.js';
const {
Observable,
Subject,
concat,
defer,
range,
} = rxjs;
const {
concatMap,
concatAll,
finalize,
} = rxjs.operators;
const MAX_PAYLOAD_SIZE = 60;
const START_OF_FRAME = 'L'.charCodeAt(0);
const INIT_CHECKSUM = 'g'.charCodeAt(0);
/** Repeat an Observable count times
* @param {number} count
* @param {Observable} observable
* @return {Observable}
*/
function replicate(count, observable) {
// return concat(...new Array(count).fill(observable));
let go = (observer) => {
if (count-- > 0) {
observable.subscribe({
next: (value) => observer.next(value),
error: (err) => observer.error(err),
complete: () => go(observer),
});
} else {
observer.complete();
}
};
return Observable.create(go);
}
/** Loader */
export class Loader {
/** Create a new Loader
* @param {Gigatron} cpu
*/
constructor(cpu) {
this.cpu = cpu;
this.strobes = new Subject();
}
/** load a gt1 file
* @param {File} file
* @return {Observable}
*/
load(file) {
return this.readFile(file).pipe(
concatMap((buffer) => {
let data = new DataView(buffer);
return concat(
this.startLoader(),
defer(() => {
// Send one frame with false checksum to force
// a checksum resync at the receiver
this.checksum = 0;
return this.sendFrame(0xff, 0);
}),
defer(() => {
// Setup checksum properly
this.checksum = INIT_CHECKSUM;
return this.sendSegments(data);
}));
}),
finalize(() => {
// Set the input register back to quiesced state
this.cpu.inReg = 0xff;
}));
}
/** read a file returning a Promise
* @param {File} file
* @return {Observable}
*/
readFile(file) {
return Observable.create((observer) => {
let reader = new FileReader();
reader.onload = (event) => {
observer.next(reader.result);
observer.complete();
};
reader.onerror = (event) => {
observer.error(new Error('FileReader error'));
};
reader.readAsArrayBuffer(file);
});
}
/** start the loader on the gigatron
* @return {Observable}
*/
startLoader() {
return concat(
defer(() => {
this.cpu.reset();
return replicate(100, this.atPosedge(VSYNC));
}),
replicate(10, this.pressButton(BUTTON_DOWN, 1, 1)),
this.pressButton(BUTTON_A, 1, 60)
);
}
/** simulate a button press
* @param {number} bit
* @param {number} downTime
* @param {number} upTime
* @return {Observable}
*/
pressButton(bit, downTime, upTime) {
return concat(
defer(() => {
this.cpu.inReg = bit ^ 0xff;
return replicate(downTime, this.atPosedge(VSYNC));
}),
defer(() => {
this.cpu.inReg = 0xff;
return replicate(upTime, this.atPosedge(VSYNC));
})
);
}
/** load sections from data until busy
* @param {DataView} data
* @return {Observable<Observable<T>>}
*/
sendSegments(data) {
return Observable.create((observer) => {
let offset = 0;
while (offset < data.byteLength) {
if (data.getUint8(offset) == 0 && offset != 0) {
// start address segment
offset += 1;
let startAddr = data.getUint16(offset);
offset += 2;
if (startAddr != 0) {
observer.next(this.sendStartCommand(startAddr));
}
break;
} else {
// data segment
let addr = data.getUint16(offset);
offset += 2;
let size = data.getUint8(offset);
offset += 1;
if (size == 0) {
size = 256;
}
let payload = new DataView(
data.buffer,
data.byteOffset + offset,
size);
observer.next(this.sendDataSegment(addr, payload));
offset += size;
}
}
if (offset > data.byteLength) {
observer.error(new Error('Last segment exceeds file size'));
}
observer.complete();
}).pipe(concatAll());
}
/** send a start command
* @param {number} addr
* @return {Observable}
*/
sendStartCommand(addr) {
return this.sendFrame(START_OF_FRAME, addr);
}
/** send a data block
* @param {number} addr
* @param {DataView} data
* @return {Observable}
*/
sendDataSegment(addr, data) {
return Observable.create((observer) => {
let buffer = data.buffer;
let size = data.byteLength;
let offset = data.byteOffset;
let bytesInPage = 256 - (addr & 255);
if (size > bytesInPage) {
observer.error(new Error('Segment crosses page boundary'));
} else {
while (size != 0) {
let n = Math.min(size, MAX_PAYLOAD_SIZE);
let payload = new DataView(buffer, offset, n);
observer.next(this.sendFrame(
START_OF_FRAME, addr, payload));
addr += n;
offset += n;
size -= n;
}
observer.complete();
}
}).pipe(concatAll());
}
/** send the payload frame
* @param {number} firstByte
* @param {number} addr
* @param {DataView} payload
* @return {Observable}
*/
sendFrame(firstByte, addr, payload) {
return concat(
this.atNegedge(VSYNC),
// account for 2 cycles delay in 74HCT595 and ?
this.atPosedge(HSYNC),
this.atPosedge(HSYNC),
this.sendDataBits(firstByte, 8),
defer(() => {
this.checksum = (this.checksum + (firstByte << 6)) & 0xff;
return this.sendDataBits(payload ? payload.byteLength : 0, 6);
}),
this.sendDataBits(addr & 0xff, 8),
this.sendDataBits(addr >> 8, 8),
this.sendDataBytes(payload),
defer(() => {
this.checksum = (-this.checksum) & 0xff;
return this.sendBits(this.checksum, 8);
}));
}
/** send bytes from payload
* @param {Uint8Array} payload
* @return {Observable}
*/
sendDataBytes(payload) {
return range(0, MAX_PAYLOAD_SIZE).pipe(
concatMap((offset) => {
let byte = (payload && offset < payload.byteLength) ?
payload.getUint8(offset) : 0;
return this.sendDataBits(byte, 8);
}));
}
/** send bits and add to checksum
* @param {number} value - byte containing bits to send (msb first)
* @param {number} n - number of bits to send
* @return {Observable}
*/
sendDataBits(value, n) {
return defer(() => {
this.checksum = (this.checksum + value) & 0xff;
return this.sendBits(value, n);
});
}
/** shift one bit into inReg
* @param {number} bit
*/
shiftBit(bit) {
this.cpu.inReg = ((this.cpu.inReg << 1) & 0xff) | (bit ? 1 : 0);
}
/** send bits
* @param {number} value - byte containing bits to send (msb first)
* @param {number} n - number of bits to send
* @return {Observable}
*/
sendBits(value, n) {
return range(0, n).pipe(
concatMap((i) => {
this.shiftBit(value & (1 << (n - i - 1)));
return this.atPosedge(HSYNC);
}));
}
/** wait for negedge of signal
* @param {number} mask
* @return {Observable}
*/
atNegedge(mask) {
return Observable.create((observer) => {
let prev = this.cpu.out;
let subscription = this.strobes.subscribe((curr) => {
if (prev & ~curr & mask) {
observer.complete();
subscription.unsubscribe();
} else {
prev = curr;
}
});
});
}
/** wait for posedge of signal
* @param {number} mask
* @return {Observable}
*/
atPosedge(mask) {
return Observable.create((observer) => {
let prev = this.cpu.out;
let subscription = this.strobes.subscribe((curr) => {
if (~prev & curr & mask) {
observer.complete();
subscription.unsubscribe();
} else {
prev = curr;
}
});
});
}
/** advance one tick */
tick() {
if ((this.out ^ this.cpu.out) & (HSYNC | VSYNC)) {
this.out = this.cpu.out;
this.strobes.next(this.out);
}
}
}
+350
View File
@@ -0,0 +1,350 @@
import {
Vga,
} from './vga.js';
import {
BlinkenLights,
} from './blinkenlights.js';
import {
Gigatron,
} from './gigatron.js';
import {
Gamepad,
} from './gamepad.js';
import {
Audio,
} from './audio.js';
import {
Loader,
} from './loader.js';
import {
Spi,
} from './spi.js';
const {
finalize,
} = rxjs.operators;
const HZ = 6250000;
const romUrl = 'gigatron.rom';
$(function() {
$('[data-toggle="tooltip"]').tooltip();
let muteButton = $('#mute');
let unmuteButton = $('#unmute');
let volumeSlider = $('#volume-slider');
let vgaCanvas = $('#vga-canvas');
let loadFileInput = $('#load-file-input');
let loadVhdInput = $('#load-vhd-input');
/** Trigger a keydown/keyup event in response to a mousedown/mouseup event
* @param {JQuery} $button
* @param {string} key
*/
function bindKeyToButton($button, key) {
$button
.on('mousedown', (event) => {
event.preventDefault();
document.dispatchEvent(new KeyboardEvent('keydown', {
'key': key,
}));
$button.addClass('pressed');
})
.on('mouseenter', (event) => {
event.preventDefault();
if (event.originalEvent.buttons & 1) {
document.dispatchEvent(new KeyboardEvent('keydown', {
'key': key,
}));
$button.addClass('pressed');
}
})
.on('mouseup mouseleave', (event) => {
event.preventDefault();
document.dispatchEvent(new KeyboardEvent('keyup', {
'key': key,
}));
$button.removeClass('pressed');
});
}
bindKeyToButton($('.gamepad-btn-a'), 'Delete');
bindKeyToButton($('.gamepad-btn-b'), 'Insert');
bindKeyToButton($('.gamepad-btn-start'), 'PageUp');
bindKeyToButton($('.gamepad-btn-select'), 'PageDown');
bindKeyToButton($('.gamepad-btn-up'), 'ArrowUp');
bindKeyToButton($('.gamepad-btn-down'), 'ArrowDown');
bindKeyToButton($('.gamepad-btn-left'), 'ArrowLeft');
bindKeyToButton($('.gamepad-btn-right'), 'ArrowRight');
// jQuery targets of current touches indexed by touch identifier
let $touchTargets = {};
// track touches within the fc30 and map them to mouse events
$('.gamepad')
.on('touchstart', (event) => {
event.preventDefault();
for (let touch of event.changedTouches) {
let $currTarget = $(document.elementFromPoint(
touch.clientX, touch.clientY))
.filter('.gamepad-btn');
$touchTargets[touch.identifier] = $currTarget;
$currTarget.trigger('mousedown');
if ($currTarget.length > 0 && navigator.vibrate) {
navigator.vibrate(20);
}
}
})
.on('touchmove', (event) => {
event.preventDefault();
for (let touch of event.changedTouches) {
let $prevTarget = $touchTargets[touch.identifier];
let $currTarget = $(document.elementFromPoint(
touch.clientX, touch.clientY))
.filter('.gamepad-btn');
if ($prevTarget.get(0) != $currTarget.get(0)) {
$prevTarget.trigger('mouseup');
$touchTargets[touch.identifier] = $currTarget;
$currTarget.trigger('mousedown');
if ($currTarget.length > 0 && navigator.vibrate) {
navigator.vibrate(20);
}
}
}
})
.on('touchend touchcancel', (event) => {
event.preventDefault();
for (let touch of event.changedTouches) {
let $prevTarget = $touchTargets[touch.identifier];
$prevTarget.trigger('mouseup');
delete $touchTargets[touch.identifier];
}
});
/** display the error modal with the given message
* @param {JQuery} body
*/
function showError(body) {
$('#error-modal-body')
.empty()
.append(body);
$('#error-modal').modal();
}
let cpu = new Gigatron({
hz: HZ,
romAddressWidth: 16,
ramAddressWidth: 17,
});
let vga = new Vga(vgaCanvas.get(0), cpu, {
horizontal: {
frontPorch: 16,
pulse: 96,
backPorch: 48,
visible: 640,
},
vertical: {
frontPorch: 6,
pulse: 8,
backPorch: 27,
visible: 480,
},
});
let blinkenLights = new BlinkenLights(cpu);
let audio = new Audio(cpu);
let gamepad = new Gamepad(cpu, {
up: ['ArrowUp'],
down: ['ArrowDown'],
left: ['ArrowLeft'],
right: ['ArrowRight'],
select: ['PageDown'],
start: ['PageUp'],
a: ['Delete', 'Backspace', 'End'],
b: ['Insert', 'Home'],
});
let loader = new Loader(cpu);
let spi = new Spi(cpu, 0);
spi.loadvhdurl('./sd.vhd');
muteButton.click(function() {
audio.mute = true;
$([muteButton, unmuteButton]).toggleClass('d-none');
});
unmuteButton.click(function() {
audio.mute = false;
$([muteButton, unmuteButton]).toggleClass('d-none');
});
volumeSlider.val(100 * audio.volume);
volumeSlider.on('input', function(event) {
let target = event.target;
target.labels[0].textContent = target.value + '%';
audio.volume = target.value / 100;
});
volumeSlider.trigger('input');
/** load a GT1 file
* @param {File} file
*/
function loadGt1(file) {
gamepad.stop();
spi.stop();
loader.load(file)
.pipe(finalize(() => {
gamepad.start();
spi.start();
}))
.subscribe({
error: (error) => showError($(`\
<p>\
Could not load GT1 from <code>${file.name}</code>\
</p>\
<hr>\
<p class="alert alert-danger">\
<span class="oi oi-warning"></span> ${error.message}\
</p>`)),
});
}
loadFileInput
.on('click', (event) => {
loadFileInput.closest('form').get(0).reset();
})
.on('change', (event) => {
let target = event.target;
if (target.files.length != 0) {
let file = target.files[0];
loadGt1(file);
}
});
loadVhdInput
.on('click', (event) => {
loadVhdInput.closest('form').get(0).reset();
})
.on('change', (event) => {
let target = event.target;
if (target.files.length != 0) {
let file = target.files[0];
spi.loadvhdfile(file);
}
});
$(document)
.on('dragenter', (event) => {
event.preventDefault();
event.stopPropagation();
let dataTransfer = event.originalEvent.dataTransfer;
dataTransfer.dropEffect = 'link';
})
.on('dragover', (event) => {
event.preventDefault();
event.stopPropagation();
})
.on('drop', (event) => {
let dataTransfer = event.originalEvent.dataTransfer;
if (dataTransfer) {
let files = dataTransfer.files;
if (files.length != 0) {
event.preventDefault();
event.stopPropagation();
let fn = files[0].name.toLowerCase()
if (fn.endsWith('.gt1')) {
loadGt1(files[0])
} else if (fn.endsWith('.vhd') || fn.endsWith('.img')) {
spi.loadvhdfile(files[0])
}
}
}
});
let timer = 0;
let lastdate = 0;
/** start the simulation loop */
function startRunLoop() {
gamepad.start();
lastdate = Date.now()
timer = setInterval(() => {
/* Self correcting simulation speed */
let newdate = Date.now()
let cycles = cpu.hz * Math.min(newdate-lastdate, 30)/1000
lastdate = newdate
audio.drain();
while (cycles-- >= 0 && !audio.full) {
cpu.tick();
vga.tick();
audio.tick();
spi.tick();
loader.tick();
}
blinkenLights.tick(); // don't need realtime update
gamepad.tick();
}, audio.duration * 500);
audio.context.resume();
// Chrome suspends the AudioContext on reload
// and doesn't allow it to be resumed unless there
// is user interaction
if (audio.context.state === 'suspended') {
vga.ctx.fillStyle = 'white';
vga.ctx.textAlign = 'center';
vga.ctx.textBaseline = 'middle';
vga.ctx.font = '4em sans-serif';
vga.ctx.fillText('Click to start', 320, 240);
vgaCanvas.on('click', (event) => {
audio.context.resume();
vgaCanvas.off('click');
});
}
}
/** stop the simulation loop */
function stopRunLoop() { // eslint-disable-line
clearTimeout(timer);
gamepad.stop();
}
/** load the ROM image
* @param {string} url
*/
function loadRom(url) {
var req = new XMLHttpRequest();
req.open('GET', url);
req.responseType = 'arraybuffer';
/* req.setRequestHeader('accept-encoding','gzip'); */
req.onload = (event) => {
if (req.status != 200) {
showError($(`\
<p>\
Could not load ROM from <code>${url}</code>\
</p>\
<hr>\
<p class="alert alert-danger">\
<span class="oi oi-warning"></span> ${req.statusText}\
</p>`));
} else {
let dataView = new DataView(req.response);
let wordCount = dataView.byteLength >> 1;
// convert to host endianess
for (let wordIndex = 0; wordIndex < wordCount; wordIndex++) {
cpu.rom[wordIndex] = dataView.getUint16(2 * wordIndex);
}
startRunLoop();
}
};
req.send(null);
}
loadRom(romUrl);
});
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -0,0 +1 @@
../../../../../ROMv1.rom
@@ -0,0 +1 @@
../../../../../ROMv2.rom
@@ -0,0 +1 @@
../../../../../ROMv3.rom
@@ -0,0 +1 @@
../../../../../ROMv4.rom
@@ -0,0 +1 @@
../../../../../ROMv5a.rom
@@ -0,0 +1 @@
../../../../../ROMv6.rom
+1
View File
@@ -0,0 +1 @@
vhds/misc.vhd.gz
+431
View File
@@ -0,0 +1,431 @@
const ACTION_WAIT = 0;
const ACTION_RECV = 1;
const ACTION_SEND = 2;
const ACTION_BUSY = 3;
const CTX_INIT = 0;
const CTX_CMD = 1;
const CTX_APPCMD = 2;
const CTX_REG = 3;
const CTX_READ = 4;
const CTX_READM = 5;
const CTX_WRITE = 6;
const CTX_WRITE1 = 7;
const CTX_WRITEM = 8;
const CTX_WRITEM1 = 9;
function crc7(b, j, c)
{
let crc = 0;
while(c--) {
crc = crc ^ b[j++];
for (let i = 0; i < 8; i++) {
crc = (crc & 0x80) ? ((crc << 1) ^ 0x89) : (crc << 1);
}
}
return crc & 0xff | 0x01;
}
function crc16(b, j, c)
{
let crc = 0;
while (c--) {
crc = crc ^ (b[j++] << 8);
for (let i = 0; i < 8; i++) {
crc = (crc & 0x8000) ? ((crc << 1) ^ 0x1021) : (crc << 1);
}
}
return crc & 0xffff;
}
export class Spi {
/** Create a new Spi
* @param {Gigatron} cpu
* @param {Object} options
*/
constructor(cpu, id) {
this.cpu = cpu
/* spi stuff */
this.cs = (id >=0 && id < 4) ? (4 << id) : 0;
this.mask = 0;
this.miso = 0;
this.mosi = 0;
/* sd stuff */
this.vhd = 0;
this.vhdlen = 0;
this.buffer = new Uint8Array(520);
this.idle = 1;
this.action = 0;
this.context = 0;
this.count = 0;
this.len = 0;
this.offset = 0;
this.serial = 0;
}
/** Advance spi simulation by one tick */
tick() {
let b = this.cpu.prevctrl;
if (b >= 0) {
let a = this.cpu.ctrl;
let selected = this.cs && !(a & this.cs);
if (selected && (b & this.cs)) {
this.mask = 0x80;
this.miso = this.spiselect();
this.cpu.miso = (this.miso & this.mask) ? 0xf : 0;
}
if (selected && ((a ^ b) & 1)) {
if (a & 1) {
/* clock rising (latch) */
let mask = this.mask;
let mosi = this.mosi;
this.mosi = (a & 0x8000) ? (mosi | mask) : (mosi & ~mask)
} else {
/* clock falling (shift) */
this.mask >>= 1;
if (! this.mask) {
this.mask = 0x80;
this.miso = this.spibyte(this.mosi)
}
this.cpu.miso = (this.miso & this.mask) ? 0xf : 0;
}
}
}
}
loadvhdurl(url) {
let req = new XMLHttpRequest();
req.open('GET', url);
req.responseType = 'arraybuffer';
/* req.setRequestHeader('accept-encoding','gzip'); */
req.onload = (event) => {
if (req.status == 200) {
let vhd = new Uint8Array(req.response);
if (vhd.length > 0) {
this.vhd = vhd;
this.vhdlen = vhd.length;
this.serial += 1;
}
}
};
req.onerror = (event) => {
console.log("error while reading vhd from", url);
};
req.send();
}
loadvhdfile(file) {
let reader = new FileReader();
reader.onload = (event) => {
let vhd = new Uint8Array(reader.result);
if (vhd.length > 0) {
this.vhd = vhd;
this.vhdlen = vhd.length;
this.serial += 1;
}
};
reader.onerror = (event) => {
console.log("error while reading vhd from", file);
};
reader.readAsArrayBuffer(file);
}
/** enable/disable SD card emulation */
stop() {
this.vhdlen = 0;
}
start() {
if (this.vhd)
this.vhdlen = this.vhd.length;
}
/** Set state (action,context) */
set_wait_state(ctx) {
this.context = ctx;
this.action = ACTION_WAIT;
}
set_recv_state(ctx, n) {
this.context = ctx;
this.action = ACTION_RECV;
this.len = n;
this.count = 0;
}
set_recv_state1(ctx, n, b) {
this.context = ctx;
this.action = ACTION_RECV;
this.len = n;
this.buffer[0] = b;
this.count = 1;
}
set_send_state(ctx, n) {
this.context = ctx;
this.action = ACTION_SEND;
this.len = n;
this.count = 0;
}
set_send_r1_state(ctx, r1) {
this.buffer[0] = r1;
this.set_send_state(ctx, 1);
}
set_busy_state(ctx, n) {
this.context = ctx;
this.action = ACTION_BUSY;
this.len = n;
this.count = 0;
}
/** Which byte is returned by the device when selected */
spiselect() {
if (this.action == ACTION_BUSY) {
return 0x00;
}
if (this.context != CTX_INIT && this.context != CTX_APPCMD) {
this.context = CTX_CMD;
}
this.set_wait_state(this.context);
return 0xff;
}
/** Which byte is returned to the master when receiving mosi */
spibyte(mosi) {
let c = this.context;
let a = this.action;
switch(a) {
case ACTION_WAIT:
if (mosi == 0xff || this.vhdlen <= 0) { return 0xff; }
break;
case ACTION_RECV:
this.buffer[this.count] = mosi;
if (++this.count < this.len) { return 0xff; }
break;
case ACTION_SEND:
if (c == CTX_READM && mosi == 64 + 12) { break; } // CMD12
if (this.count < this.len) { return this.buffer[this.count++]; }
break;
case ACTION_BUSY:
if (this.count++ < this.len) { return 0; }
break;
}
switch(c) {
case CTX_INIT:
case CTX_CMD:
case CTX_APPCMD:
if (a == ACTION_WAIT) {
this.set_recv_state1(c, 6, mosi);
} else if (a == ACTION_SEND || a == ACTION_BUSY) {
this.set_wait_state(c);
} else {
this.sdcommand(c);
}
return 0xff;
case CTX_REG:
this.buffer[0] = 0xfe;
this.buffer[16] = crc7(this.buffer, 1, 15);
let crc = crc16(this.buffer, 1, 16);
this.buffer[17] = crc >> 8;
this.buffer[18] = crc;
this.set_send_state(CTX_CMD, 16 + 3);
return 0xff;
case CTX_READ:
if (! this.read_data()) {
this.set_send_r1_state(CTX_CMD, 9);
} else {
this.set_send_state(CTX_CMD, 512+3);
}
return 0xff;
case CTX_READM:
if (mosi == 64 + 12) {
this.set_recv_state1(CTX_CMD, 6, mosi);
} else if (! this.read_data()) {
this.set_send_r1_state(CTX_CMD, 9);
} else {
this.set_send_state(CTX_READM, 512+3);
}
this.offset += 512;
return 0xff;
case CTX_WRITE:
this.set_wait_state(CTX_WRITE1);
return 0xff;
case CTX_WRITE1:
if (a == ACTION_WAIT) {
this.set_recv_state1(CTX_WRITE1, 512+3, mosi);
} else {
this.set_busy_state(CTX_CMD, 4);
return (this.buffer[0] == 0xfe && this.write_data()) ? 0x5 : 0xd;
}
return 0xff;
case CTX_WRITEM:
this.set_wait_state(CTX_WRITEM1);
return 0xff;
case CTX_WRITEM1:
if (a == ACTION_WAIT && mosi == 0xfd) {
this.set_busy_state(CTX_CMD, 4); // stop tran
} else if (a == ACTION_WAIT) {
this.set_recv_state1(CTX_WRITEM1, 512+3, mosi);
} else if (this.buffer[0] == 0xfc && this.write_data()) {
this.offset += 512;
this.set_busy_state(ACTION_WRITEM, 4);
return 0x5;
} else {
this.set_busy_state(CTX_CMD, 4);
return 0xd;
}
return 0xff;
}
this.set_send_r1_state(CTX_CMD, 4);
return 0xff;
}
sdcommand(ctx) {
let buffer = this.buffer;
let cmd = buffer[0] & 0x3f;
if (ctx == CTX_INIT
&& !(buffer[0]==0x40 && buffer[1]==0 && buffer[2]==0
&& buffer[3]==0 && buffer[4]==0 && buffer[5]==0x95) ) {
this.set_send_r1_state(CTX_INIT, 5);
return;
}
if (buffer[0] != cmd + 64) {
this.set_send_r1_state(CTX_CMD, 5);
return;
}
if (ctx == CTX_APPCMD) {
cmd += 128;
}
if (this.idle && cmd != 0 && cmd != 1 && cmd != 8
&& cmd != 128+41 && cmd != 55 && cmd != 58) {
cmd = 0xff;
}
switch(cmd) {
case 128+41: // ACMD41: APP_SEND_OP_COND
if (this.vhdlen == 0) {
this.set_send_r1_state(CTX_CMD, 4 + this.idle)
} else {
this.idle = 0;
this.set_send_r1_state(CTX_CMD, 0)
}
break;
case 128+23: // ACMD22: SET_WR_BLOCK_ERASE_COUNT
// ignored but not illegal
this.set_send_r1_state(CTX_CMD, 0);
break;
case 0: // CMD0: GO_IDLE_STATE
this.idle = 1;
this.set_send_r1_state(CTX_CMD, this.idle);
break;
case 1: // CMD1: SEND_OP_COND
this.idle = 0;
this.set_send_r1_state(CTX_CMD, 0);
break;
case 8: // CMD8: SEND_IF_COND
buffer[0] = this.idle;
if (this.vhdlen == 0) {
this.set_send_r1_state(CTX_CMD, 4 + idle);
} else {
this.set_send_state(CTX_CMD, 5);
}
break;
case 9: { // CMD9: SEND_CSD
let size = this.vhdlen / (512 * 1024);
buffer.set([0, 0x40, 0xe, 0, 0x32, 0x5b, 0x59, 0, 0,
0, 0, 0x7f, 0x80, 0xa, 0x40, 0x40, 0xf1], 0);
buffer[10] = size & 0xff;
buffer[9] = (size & 0xff00) >> 8;
buffer[8] = (size & 0xcf0000) >> 16;
this.set_send_state(CTX_REG, 1); }
break;
case 10: // CMD10: SEND_CID
buffer.set([0x00, 0xbb, 83, 68, 48, 48, 48, 48, 48,
0x11, 0, 0, 0, 0, 0, 1, 0xf1, 88, 88], 0);
buffer[11] = this.serial;
buffer[12] = this.serial >> 8;
this.set_send_state(CTX_REG, 1);
break;
case 12: // CMD12: STOP_TRANSMISSION
this.set_busy_state(CTX_CMD, 3);
break;
case 16: { // CMD16: SET_BLOCK_LENGTH
let bl = (buffer[1]<<24)|(buffer[2]<<16)|(buffer[3]<<8)|(buffer[4]);
if (bl != 512) {
this.set_send_r1_state(CTX_CMD, 64);
} else {
set_send_r1_state(CTX_CMD, 0);
} }
break;
case 17: // CMD17: READ_SINGLE_BLOCK
this.offset = (buffer[1]<<24)|(buffer[2]<<16)|(buffer[3]<<8)|(buffer[4]);
this.offset *= 512;
if (this.offset > this.vhdlen - 512) {
this.set_send_r1_state(CTX_CMD, 64);
} else {
this.set_send_r1_state(CTX_READ, 0);
}
break;
case 18: // CMD18: READ_MULTIPLE_BLOCK
this.offset = (buffer[1]<<24)|(buffer[2]<<16)|(buffer[3]<<8)|(buffer[4]);
this.offset *= 512;
if (this.offset > this.vhdlen - 512) {
this.set_send_r1_state(CTX_CMD, 64);
} else {
this.set_send_r1_state(CTX_READM, 0);
}
break;
case 24: // CMD24: WRITE_SINGLE_BLOCK
this.offset = (buffer[1]<<24)|(buffer[2]<<16)|(buffer[3]<<8)|(buffer[4]);
this.offset *= 512;
if (this.offset > this.vhdlen - 512) {
this.set_send_r1_state(CTX_CMD, 64);
} else {
this.set_send_r1_state(CTX_WRITE, 0);
}
break;
case 25: // CMD18: WRITE_MULTIPLE_BLOCK
this.offset = (buffer[1]<<24)|(buffer[2]<<16)|(buffer[3]<<8)|(buffer[4]);
this.offset *= 512;
if (this.offset > this.vhdlen - 512) {
this.set_send_r1_state(CTX_CMD, 64);
} else {
this.set_send_r1_state(CTX_WRITEM, 0);
}
break;
case 55: // CMD55: APP_CMD
this.set_send_r1_state(CTX_APPCMD, this.idle);
break;
case 58: // CMD58: READ_OCR
buffer.set([0, 0x40, 0xff, 0x80, 0], 0);
this.set_send_state(CTX_CMD, 5);
break;
default:
this.set_send_r1_state(CTX_CMD, 4 + this.idle);
break;
}
return 0;
}
read_data() {
let offset = this.offset;
let buffer = this.buffer;
let vhd = this.vhd;
buffer[0] = 0xfe;
for (let i=0; i<512; i++)
buffer[1 + i] = vhd[offset + i];
let crc = 0; /* crc16(buffer, 1, 512) */
buffer[513] = crc >> 8;
buffer[514] = crc;
return 1;
}
write_data() {
let offset = this.offset;
let buffer = this.buffer;
let vhd = this.vhd;
buffer[0] = 0xfe;
for (let i=0; i<512; i++)
vhd[offset + i] = buffer[1 + i];
return 1;
}
}
+36
View File
@@ -0,0 +1,36 @@
/** right pad a string
* @param {string} value - The value to pad
* @param {number} width - The width to pad to
* @param {string} [pad=' '] - The pad string
* @return {string} The padded string
*/
export function rpad(value, width, pad) {
pad = pad || ' ';
if (value.length < width) {
value = value + pad.repeat(width - value.length);
}
return value;
}
/** left pad a string
* @param {string} value - The value to pad
* @param {number} width - The width to pad to
* @param {string} [pad=' '] - The pad string
* @return {string} The padded string
*/
export function lpad(value, width, pad) {
pad = pad || ' ';
if (value.length < width) {
value = pad.repeat(width - value.length) + value;
}
return value;
}
/** convert a number to a zero-padded hex string
* @param {number} value - The number to convert to hex
* @param {number} width - The width of the result
* @return {string} The padded hex string
*/
export function toHex(value, width) {
return lpad(value.toString(16), width, '0');
}
+83
View File
@@ -0,0 +1,83 @@
export const VSYNC = 0x80;
export const HSYNC = 0x40;
/** Vga */
export class Vga {
/** Create a new Vga
* @param {HTMLCanvasElement} canvas
* @param {Gigatron} cpu
* @param {Object} options
*/
constructor(canvas, cpu, options) {
this.canvas = canvas;
this.canvas.width = options.horizontal.visible;
this.canvas.height = options.vertical.visible;
this.ctx = canvas.getContext('2d', {
alpha: false,
});
this.imageData = this.ctx.getImageData(
0, 0,
canvas.width, canvas.height);
this.pixels = this.imageData.data;
this.cpu = cpu;
this.row = 0;
this.minRow = options.vertical.backPorch + options.vertical.pulse;
this.maxRow = this.minRow + options.vertical.visible;
this.col = 0;
this.minCol = options.horizontal.backPorch + options.horizontal.pulse;
this.maxCol = this.minCol + options.horizontal.visible;
this.pixel = 0;
this.out = 0;
// turn all pixels black with full alpha
for (let i = 0; i < this.pixels.length; i++) {
this.pixels[i] = (i % 4) == 3 ? 255 : 0;
}
this.render();
}
/** draw the pixels into the canvas */
render() {
this.ctx.putImageData(this.imageData, 0, 0);
}
/** advance simulation by one tick */
tick() {
let out = this.cpu.out;
let falling = this.out & ~out;
if (falling & VSYNC) {
this.row = -1; // After 4 more CPU cycles HSYNC increments row to 0
this.pixel = 0;
this.render();
}
if (falling & HSYNC) {
this.col = 0;
this.row++;
}
// Chrome optimizer put this before the falling calculation
// if it follows immediately after it, so it got moved down here
this.out = out;
if ((this.row >= this.minRow && this.row < this.maxRow) &&
(this.col >= this.minCol && this.col < this.maxCol)) {
let pixels = this.pixels;
let pixel = this.pixel;
let r = (out ) & 3;
let g = (out >> 2) & 3;
let b = (out >> 4) & 3;
for (let i = 0; i < 4; i++) {
pixels[pixel++] = 85 * r;
pixels[pixel++] = 85 * g;
pixels[pixel++] = 85 * b;
pixel++;
}
this.pixel = pixel;
}
this.col += 4;
}
}
Binary file not shown.