├── app └── .gitkeep ├── .gitignore ├── resources └── font │ ├── icons.ttf │ ├── VT323-Regular.ttf │ └── BebasNeue-Regular.ttf ├── app.ctn ├── src ├── CPU │ ├── InstructionHandler.php │ ├── RegistryInstructionHandler.php │ ├── InstructionRegistry.php │ └── InstructionSet.php ├── Renderer │ ├── MonitorPassData.php │ ├── RenderState.php │ ├── MonitorRenderer.php │ └── GuiRenderer.php ├── Monitor.php ├── Memory.php ├── Program.php ├── CPU.php └── Application.php ├── bin └── start.php ├── composer.json ├── phpunit.xml ├── bootstrap.php ├── tests └── CPUTest.php ├── README.md └── LICENSE /app/.gitkeep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /var/cache/* 2 | /vendor/ -------------------------------------------------------------------------------- /resources/font/icons.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mario-deluna/php-chip8/HEAD/resources/font/icons.ttf -------------------------------------------------------------------------------- /resources/font/VT323-Regular.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mario-deluna/php-chip8/HEAD/resources/font/VT323-Regular.ttf -------------------------------------------------------------------------------- /resources/font/BebasNeue-Regular.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mario-deluna/php-chip8/HEAD/resources/font/BebasNeue-Regular.ttf -------------------------------------------------------------------------------- /app.ctn: -------------------------------------------------------------------------------- 1 | /** 2 | * This is the application's main container file. In other words, 3 | * it's the place where you want to specify your parameters and services. 4 | * 5 | * By default, all container files located in the `/app` directory are added 6 | * to the current namespace. This means that you can easily import these files 7 | * anywhere in your code by using the `import app/myfile` syntax. 8 | */ 9 | :project.name: 'php-chip8' -------------------------------------------------------------------------------- /src/CPU/InstructionHandler.php: -------------------------------------------------------------------------------- 1 | appClass = \App\Application::class; 11 | $options->container = $container; 12 | $options->windowTitle = $container->getParameter('project.name'); // defined in: /app.ctn 13 | }); 14 | 15 | // forwards the command line arguments to the app container 16 | $container->setParameter('argv', array_slice($argv, 1)); 17 | 18 | $quickstart->run(); -------------------------------------------------------------------------------- /composer.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "phpgl/visu-quickstart", 3 | "autoload": { 4 | "psr-4": { 5 | "App\\": "src/" 6 | } 7 | }, 8 | "require": { 9 | "phpgl/visu": "@dev" 10 | }, 11 | "require-dev": { 12 | "phpgl/ide-stubs": "dev-main", 13 | "phpunit/phpunit": "^11.0" 14 | }, 15 | "scripts": { 16 | "post-root-package-install": [ 17 | "php ./bin/install.php", 18 | "mkdir var/ && mkdir var/cache/ && chmod -R 777 var/" 19 | ], 20 | "post-autoload-dump": [ 21 | "ClanCats\\Container\\ComposerContainerFileLoader::generateMap" 22 | ] 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/CPU/RegistryInstructionHandler.php: -------------------------------------------------------------------------------- 1 | registry->getHandler($opcode); 20 | return $handler ? $handler->disassemble($opcode) : null; 21 | } 22 | 23 | public function handle(CPU $cpu, int $opcode): void 24 | { 25 | $this->registry->getHandler($opcode)?->handle($cpu, $opcode); 26 | } 27 | } -------------------------------------------------------------------------------- /src/Monitor.php: -------------------------------------------------------------------------------- 1 | blob = new UByteBuffer(); 17 | $this->reset(); 18 | } 19 | 20 | public function reset() 21 | { 22 | $this->blob->fill($this->width * $this->height * 2, 0x00); 23 | } 24 | 25 | public function setPixel(int $x, int $y, int $value) 26 | { 27 | $this->blob[$x + $y * $this->width] = $value; 28 | } 29 | 30 | public function getPixel(int $x, int $y): int 31 | { 32 | return $this->blob[$x + $y * $this->width] ?: 0; 33 | } 34 | } -------------------------------------------------------------------------------- /phpunit.xml: -------------------------------------------------------------------------------- 1 | 2 | 11 | 12 | 13 | tests 14 | 15 | 16 | 17 | 18 | 19 | src 20 | 21 | 22 | 23 | -------------------------------------------------------------------------------- /src/CPU/InstructionRegistry.php: -------------------------------------------------------------------------------- 1 | $handlers An array of instruction handlers 11 | */ 12 | public function __construct( 13 | public readonly int $bitmask, 14 | public readonly int $shiftRight = 0, 15 | private array $handlers = [] 16 | ) 17 | { 18 | } 19 | 20 | /** 21 | * Returns the instruction handler for the given opcode 22 | */ 23 | public function getHandler(int $opcode) : ?InstructionHandler 24 | { 25 | return $this->handlers[($opcode >> $this->shiftRight) & $this->bitmask] ?? null; 26 | } 27 | } -------------------------------------------------------------------------------- /src/Memory.php: -------------------------------------------------------------------------------- 1 | blob = new UByteBuffer(); 16 | $this->reset(); 17 | } 18 | 19 | public function reset() 20 | { 21 | $this->blob->fill($this->size, 0x0); 22 | } 23 | 24 | public function storeOpcode(int $address, int $opcode) 25 | { 26 | $this->blob[$address] = $opcode >> 8; 27 | $this->blob[$address + 1] = $opcode & 0x00FF; 28 | } 29 | 30 | public function fetchSprite(int $address, int $length): UByteBuffer 31 | { 32 | $sprite = new UByteBuffer(); 33 | $sprite->fill($length, 0x0); 34 | 35 | for ($i = 0; $i < $length; $i++) { 36 | $sprite[$i] = $this->blob[$address + $i]; 37 | } 38 | 39 | return $sprite; 40 | } 41 | } -------------------------------------------------------------------------------- /bootstrap.php: -------------------------------------------------------------------------------- 1 | viewport = new Viewport(0, 1920, 1080, 0, 1, 1); 71 | $this->monitorOffest = new Vec2(25.0, -25.0); 72 | } 73 | 74 | /** 75 | * Returns the position of the monitor in screen space 76 | */ 77 | public function getMonitorPosition() : Vec2 78 | { 79 | if ($this->fullscreenMonitor) { 80 | return new Vec2(0, 0); 81 | } 82 | 83 | $pos = new Vec2($this->viewport->width * 0.5, $this->viewport->top); 84 | 85 | // move the mointor a bit into the viewport 86 | $pos = $pos - $this->monitorOffest; 87 | 88 | return $pos; 89 | } 90 | 91 | /** 92 | * Returns the size of the monitor in screen space 93 | */ 94 | public function getMonitorSize() : Vec2 95 | { 96 | if ($this->fullscreenMonitor) { 97 | return new Vec2($this->viewport->width, $this->viewport->height); 98 | } 99 | 100 | $width = $this->viewport->width * 0.5; 101 | // as chip-8 is 64x32, we want to keep the aspect ratio 102 | $height = $width * 0.5; 103 | 104 | return new Vec2($width, $height); 105 | } 106 | } -------------------------------------------------------------------------------- /tests/CPUTest.php: -------------------------------------------------------------------------------- 1 | createCPU(); 19 | $cpu->memory->storeOpcode(0x200, Program::opJump(0x250)); 20 | $cpu->memory->storeOpcode(0x250, Program::opJump(0x200)); 21 | 22 | $this->assertEquals('JP 0x250', $cpu->disassembleInstructionAt(0x200)); 23 | $this->assertEquals('JP 0x200', $cpu->disassembleInstructionAt(0x250)); 24 | 25 | $cpu->runCycles(1); 26 | 27 | // program counter should be 0x250 28 | $this->assertEquals(0x250, $cpu->programCounter); 29 | 30 | $cpu->runCycles(1); 31 | 32 | // program counter should be 0x200 33 | $this->assertEquals(0x200, $cpu->programCounter); 34 | } 35 | 36 | public function testSubroutineInst() 37 | { 38 | $cpu = $this->createCPU(); 39 | $cpu->memory->storeOpcode(0x200, Program::opClearScreen()); 40 | $cpu->memory->storeOpcode(0x202, Program::opCall(0x250)); 41 | $cpu->memory->storeOpcode(0x204, Program::opJump(0x200)); 42 | $cpu->memory->storeOpcode(0x250, Program::opReturn()); 43 | 44 | $this->assertEquals('CLS', $cpu->disassembleInstructionAt(0x200)); 45 | $this->assertEquals('CALL 0x250', $cpu->disassembleInstructionAt(0x202)); 46 | $this->assertEquals('JP 0x200', $cpu->disassembleInstructionAt(0x204)); 47 | $this->assertEquals('RET', $cpu->disassembleInstructionAt(0x250)); 48 | 49 | // now run 50 | $cpu->runCycles(1); 51 | $this->assertEquals(0x202, $cpu->programCounter); 52 | 53 | $cpu->runCycles(1); 54 | $this->assertEquals(0x250, $cpu->programCounter); 55 | 56 | $cpu->runCycles(1); 57 | $this->assertEquals(0x204, $cpu->programCounter); 58 | 59 | $cpu->runCycles(1); 60 | $this->assertEquals(0x200, $cpu->programCounter); 61 | } 62 | 63 | public function testComparison() 64 | { 65 | $cpu = $this->createCPU(); 66 | $cpu->memory->storeOpcode(0x200, Program::opLoadValue(0x1, 0x42)); 67 | $cpu->memory->storeOpcode(0x202, Program::opSkipIfEqualValue(0x1, 0x42)); 68 | $cpu->memory->storeOpcode(0x204, Program::opLoadValue(0x2, 0xFF)); 69 | $cpu->memory->storeOpcode(0x206, Program::opExit()); 70 | $cpu->run(); 71 | 72 | // reister 2 should still be 0 73 | $this->assertEquals(0, $cpu->registers[0x2]); 74 | 75 | // now a not 76 | $cpu = $this->createCPU(); 77 | $cpu->memory->storeOpcode(0x200, Program::opLoadValue(0x1, 0x42)); 78 | $cpu->memory->storeOpcode(0x202, Program::opSkipIfNotEqualValue(0x1, 0x42)); 79 | $cpu->memory->storeOpcode(0x204, Program::opLoadValue(0x2, 0xFF)); 80 | $cpu->memory->storeOpcode(0x206, Program::opExit()); 81 | $cpu->run(); 82 | 83 | // reister 2 should now be 0xFF 84 | $this->assertEquals(0xFF, $cpu->registers[0x2]); 85 | } 86 | } 87 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # PHP Chip-8 Emulator 2 | 3 | I don't know how many turing mashines deep this is but here is a Chip8 Emulator written in PHP. 4 | 5 | Built on [PHP-GLFW](http://github.com/mario-deluna/php-glfw) and the [VISU](https://github.com/phpgl/visu) framework. 6 | 7 | ![demo](https://github.com/mario-deluna/php-chip8/assets/956212/ae03baa0-8a00-4872-8131-39ca420a6310) 8 | 9 | * [Features](#features) 10 | * [FAQ](#faq) 11 | * [How To use it ](#how-to-use-it) 12 | * [Credits](#credits) 13 | * [License](#license) 14 | 15 | ## Features 16 | 17 | * **It runs Chip8 ROMs!** 18 | This is obvious, but the moment it started working was magical to me, so I'm putting it here. 19 | * **Debugger** 20 | You can step through the code and see the state of the registers and memory. 21 | Press `space` to pause or hit the _Pause button_. 22 | ![stepper](https://github.com/mario-deluna/php-chip8/assets/956212/dbcf3e7c-4652-4f5e-a05e-21e96745d978) 23 | * **Drag and Drop**
As seen in the demo, you can simply drag and drop your ROMs onto the emulator. 24 | * **Fullscreen mode**
25 | If you don't care for all the debugging stuff, you can simply go fullscreen and enjoy the game. 26 | * **Virtual Keyboard** 27 | You can use the keyboard in the GUI or use the keybindings: 28 | 29 | keyboard 30 | 31 | | | | | | | | | | | 32 | |---|---|---|---|----|---|---|---|---| 33 | | 1 | 2 | 3 | C | `->` | 1 | 2 | 3 | 4 | 34 | | 4 | 5 | 6 | D | `->` | q | w | e | r | 35 | | 7 | 8 | 9 | E | `->` | a | s | d | f | 36 | | A | 0 | B | F | `->` | y | x | c | v | 37 | * **Ghosting Effect** 38 | I'm honestly not very knowledgeable about old hardware, but I'm assuming that the old CRTs would take some time for the phosphor to fade out. I tried to emulate this effect by adding a ghosting effect to the display, as the flickering otherwise is quite unpleasant. 39 | You can change the strength of the effect. 40 | ![ghosting](https://github.com/mario-deluna/php-chip8/assets/956212/b0014e39-ed44-4bde-a6a1-2f314502a21c) 41 | 42 | * **CRT Effect** 43 | Some might hate this effect; I like it, but of course, you can turn it off. 44 | ![crt](https://github.com/mario-deluna/php-chip8/assets/956212/5d2c269c-55fd-481a-8699-0695c258b978) 45 | 46 | * **GUI!** 47 | The GUI is created using an immediate mode style of drawing. You get results really quickly, the code is really ugly and performance is really not great. 48 | 49 | ## FAQ 50 | 51 | * **What is this?**
52 | It is a Chip8 Emulator written in PHP. 53 | * **Can I use it in Production?**
54 | Of course! Its beyond my understanding why you would want to do that, but sure go for it! 55 | * **Why did you make this?**
56 | Yes! 57 | * **Thats not a real answer**
58 | Yes! 59 | * **Is this a real FAQ?**
60 | Yes! 61 | * **Yes!**
62 | No! 63 | 64 | ## How To use it 65 | 66 | 1. Clone the repository
67 | ``` 68 | $ git clone git@github.com:mario-deluna/php-chip8.git 69 | ``` 70 | 2. Install the dependencies
71 | ``` 72 | $ cd php-chip8 73 | $ composer install 74 | ``` 75 | 3. Double check [PHP-GLFW](http://github.com/mario-deluna/php-glfw) is properly installed. 76 | 4. Run the emulator
77 | ``` 78 | $ php bin/start.php 79 | ``` 80 | 81 | ## Credits 82 | 83 | - [Mario Döring](https://github.com/mario-deluna) 84 | - [All Contributors](https://github.com/mario-deluna/php-chip8/contributors) 85 | 86 | ## License 87 | 88 | Please see [License File](https://github.com/mario-deluna/php-chip8/blob/master/LICENSE) for more information. 89 | -------------------------------------------------------------------------------- /src/CPU.php: -------------------------------------------------------------------------------- 1 | registers = new UByteBuffer(); 47 | $this->registers->fill(16, 0x0); 48 | 49 | $this->timers = new UByteBuffer(); 50 | $this->timers->fill(2, 0x0); 51 | 52 | $this->stack = new UShortBuffer(); 53 | $this->stack->fill(64, 0x0); 54 | 55 | $this->keyPressStates = new UByteBuffer(); 56 | $this->keyPressStates->fill(16, 0x0); 57 | 58 | // load the default instruction set 59 | $this->instructionSet = InstructionSet::defaultSet(); 60 | } 61 | 62 | public function loadRomFile(string $filename) 63 | { 64 | $this->currentRomFilePath = $filename; 65 | 66 | $data = file_get_contents($filename); 67 | 68 | // convert the data to a byte array 69 | $bytes = array_values(unpack('C*', $data)); 70 | 71 | // store the data in the memory 72 | for($i = 0; $i < count($bytes); $i++) { 73 | $this->memory->blob[$i + 0x200] = $bytes[$i]; 74 | } 75 | } 76 | 77 | public function reset() 78 | { 79 | $this->registers->fill(16, 0x0); 80 | $this->registerI = 0x0; 81 | $this->programCounter = 0x200; 82 | $this->stackPointer = 0x0; 83 | $this->stack->fill(64, 0x0); 84 | $this->timers->fill(2, 0x0); 85 | $this->keyPressStates->fill(16, 0x0); 86 | $this->monitor->reset(); 87 | $this->memory->reset(); 88 | $this->shouldExit = false; 89 | } 90 | 91 | /** 92 | * Load the default font into the memory 93 | */ 94 | public function loadDefaultFont() : void 95 | { 96 | $sprites = [ 97 | 0x0 => [0xF0, 0x90, 0x90, 0x90, 0xF0], 98 | 0x1 => [0x20, 0x60, 0x20, 0x20, 0x70], 99 | 0x2 => [0xF0, 0x10, 0xF0, 0x80, 0xF0], 100 | 0x3 => [0xF0, 0x10, 0xF0, 0x10, 0xF0], 101 | 0x4 => [0x90, 0x90, 0xF0, 0x10, 0x10], 102 | 0x5 => [0xF0, 0x80, 0xF0, 0x10, 0xF0], 103 | 0x6 => [0xF0, 0x80, 0xF0, 0x90, 0xF0], 104 | 0x7 => [0xF0, 0x10, 0x20, 0x40, 0x40], 105 | 0x8 => [0xF0, 0x90, 0xF0, 0x90, 0xF0], 106 | 0x9 => [0xF0, 0x90, 0xF0, 0x10, 0xF0], 107 | 0xA => [0xF0, 0x90, 0xF0, 0x90, 0x90], 108 | 0xB => [0xE0, 0x90, 0xE0, 0x90, 0xE0], 109 | 0xC => [0xF0, 0x80, 0x80, 0x80, 0xF0], 110 | 0xD => [0xE0, 0x90, 0x90, 0x90, 0xE0], 111 | 0xE => [0xF0, 0x80, 0xF0, 0x80, 0xF0], 112 | 0xF => [0xF0, 0x80, 0xF0, 0x80, 0x80] 113 | ]; 114 | 115 | $i = 0x050; 116 | foreach ($sprites as $digit => $sprite) { 117 | $this->digitSpriteLocations[$digit] = $i; 118 | foreach ($sprite as $byte) { 119 | $this->memory->blob[$i++] = $byte; 120 | } 121 | } 122 | } 123 | 124 | 125 | /** 126 | * Returns the current opcode from the memory and increments to the next one 127 | * 128 | * I've taken these directly from: http://devernay.free.fr/hacks/chip8/C8TECH10.HTM#00E0 129 | * 130 | * nnn or addr - A 12-bit value, the lowest 12 bits of the instruction 131 | * n or nibble - A 4-bit value, the lowest 4 bits of the instruction 132 | * x - A 4-bit value, the lower 4 bits of the high byte of the instruction 133 | * y - A 4-bit value, the upper 4 bits of the low byte of the instruction 134 | * kk or byte - An 8-bit value, the lowest 8 bits of the instruction 135 | * 136 | * Unfortunately, PHP does not have macros that would allow me to easily extract these values from the opcode 137 | * I do not want to make them separate functions calls as the overhead is significant... 138 | * 139 | * Quick list of how to extract the values for my own reference: 140 | * nnn = $opcode & 0x0FFF 141 | * n = $opcode & 0x000F 142 | * x = $opcode >> 8 & 0x0F 143 | * y = $opcode >> 4 & 0x0F 144 | * kk = $opcode & 0x00FF 145 | * 146 | */ 147 | private function fetchOpcode(): int 148 | { 149 | $opcode = $this->memory->blob[$this->programCounter] << 8 | $this->memory->blob[$this->programCounter + 1]; 150 | $this->programCounter += 2; 151 | return $opcode; 152 | } 153 | 154 | /** 155 | * Returns the current opcode from the memory WITHOUT incrementing to the next one 156 | */ 157 | public function peekOpcode(): int 158 | { 159 | return $this->memory->blob[$this->programCounter] << 8 | $this->memory->blob[$this->programCounter + 1]; 160 | } 161 | 162 | /** 163 | * Return the opcode at the given index 164 | */ 165 | public function getOpcodeAt(int $index): int 166 | { 167 | return $this->memory->blob[$index] << 8 | $this->memory->blob[$index + 1]; 168 | } 169 | 170 | /** 171 | * Returns the instruction handlers for the given opcodes 172 | * 173 | * @param array $opcodes 174 | * @return array 175 | */ 176 | public function getInstructionHandlersFor(array $opcodes) : array 177 | { 178 | $handlers = []; 179 | foreach ($opcodes as $opcode) { 180 | $handlers[] = $this->instructionSet->getHandler($opcode); 181 | } 182 | return $handlers; 183 | } 184 | 185 | /** 186 | * Returns the instruction handler for an opcode at a given index 187 | * 188 | * @param int $index 189 | * @return InstructionHandler | null 190 | */ 191 | public function getInstructionHandlerAt(int $index) : ?InstructionHandler 192 | { 193 | return $this->instructionSet->getHandler($this->getOpcodeAt($index)); 194 | } 195 | 196 | /** 197 | * Returns the disassembled instruction for the opcode at the given index 198 | */ 199 | public function disassembleInstructionAt(int $index) : ?string 200 | { 201 | $opcode = $this->getOpcodeAt($index); 202 | $handler = $this->instructionSet->getHandler($opcode); 203 | return $handler ? $handler->disassemble($opcode) : null; 204 | } 205 | 206 | 207 | /** 208 | * Runs the CPU until the program ends or the timeout is reached 209 | */ 210 | public function run(float $timeout = 60) : int 211 | { 212 | $startTime = microtime(true); 213 | 214 | while (!$this->shouldExit) { 215 | if (microtime(true) - $startTime > $timeout) { 216 | return -2; 217 | } 218 | 219 | $opcode = $this->fetchOpcode(); 220 | $this->executeOpcode($opcode); 221 | } 222 | 223 | return 0; 224 | } 225 | 226 | /** 227 | * Runs the CPU for a approximate given amount of time and then returns. 228 | * 229 | * @param float $deltaTimeInMs 230 | * @return int the exit code of the program, -1 if the program is still running 231 | */ 232 | public function runFor(float $deltaTimeInMs) : int 233 | { 234 | $startTime = microtime(true); 235 | $endTime = $startTime + $deltaTimeInMs / 1000.0; 236 | 237 | while (microtime(true) < $endTime) { 238 | if ($this->shouldExit) { 239 | return 0; 240 | } 241 | 242 | $opcode = $this->fetchOpcode(); 243 | $this->executeOpcode($opcode); 244 | } 245 | 246 | return -1; 247 | } 248 | 249 | /** 250 | * Runs the CPU for a given amount of cycles and then returns. 251 | * 252 | * @param int $count the amount of cycles to run 253 | * @return int the exit code of the program, -1 if the program is still running 254 | */ 255 | public function runCycles(int $count = 1) : int 256 | { 257 | for ($i = 0; $i < $count; $i++) { 258 | if ($this->shouldExit) { 259 | return 0; 260 | } 261 | 262 | $opcode = $this->fetchOpcode(); 263 | $this->executeOpcode($opcode); 264 | } 265 | 266 | return -1; 267 | } 268 | 269 | /** 270 | * Time udpate, decrements the timers. Call this at 60Hz 271 | */ 272 | public function updateTimers() 273 | { 274 | if ($this->timers[0] > 0) { 275 | $this->timers[0] = $this->timers[0] - 1; 276 | } 277 | 278 | if ($this->timers[1] > 0) { 279 | $this->timers[1] = $this->timers[1] - 1; 280 | } 281 | } 282 | 283 | public function executeOpcode(int $opcode) 284 | { 285 | $handler = $this->instructionSet->getHandler($opcode); 286 | 287 | if ($handler === null) { 288 | throw new Exception(sprintf('Opcode 0x%X not implemented', $opcode)); 289 | } 290 | 291 | $handler->handle($this, $opcode); 292 | } 293 | } -------------------------------------------------------------------------------- /src/Application.php: -------------------------------------------------------------------------------- 1 | bindButton('pause', Key::SPACE); 50 | $actions->bindButton('step', Key::S); 51 | $actions->bindButton('fullscreen', Key::F); 52 | $actions->bindButton('toggle_crt', Key::T); 53 | $actions->bindButton('toggle_ghosting', Key::G); 54 | 55 | $this->inputContext->registerAndActivate('main', $actions); 56 | 57 | // load the VT323 font 58 | if ($this->vg->createFont('vt323', VISU_PATH_RESOURCES . '/font/VT323-Regular.ttf') === -1) { 59 | throw new Error('vt323 font could not be loaded.'); 60 | } 61 | 62 | if ($this->vg->createFont('bebas', VISU_PATH_RESOURCES . '/font/BebasNeue-Regular.ttf') === -1) { 63 | throw new Error('Bebas font could not be loaded.'); 64 | } 65 | 66 | if ($this->vg->createFont('icons', VISU_PATH_RESOURCES . '/font/icons.ttf') === -1) { 67 | throw new Error('Icon font could not be loaded.'); 68 | } 69 | 70 | // create the chip8 71 | $this->monitor = new Monitor; 72 | $this->chip8 = new CPU(new Memory, $this->monitor); 73 | 74 | $this->chip8->loadDefaultFont(); 75 | 76 | $args = $this->container->getParameter('argv'); 77 | if ($romFile = $args[0] ?? null) { 78 | $romFile = realpath($romFile); 79 | 80 | if (!file_exists($romFile)) { 81 | die(sprintf('Rom "%s" does not exist and could not be loaded.', $romFile)); 82 | } 83 | 84 | $this->chip8->loadRomFile($romFile); 85 | } 86 | 87 | // register a file drop callback 88 | $this->dispatcher->register(Input::EVENT_DROP, function(DropSignal $signal) { 89 | $firstFile = $signal->paths[0] ?? null; 90 | $this->chip8->reset(); 91 | $this->chip8->loadRomFile($firstFile); 92 | $this->isRunning = true; 93 | }); 94 | 95 | // create a texture for the monitor 96 | $this->monitorTexture = new Texture($this->gl, 'chip8_monitor'); 97 | 98 | // rendering state 99 | $this->renderState = new RenderState; 100 | 101 | // create a renderer for the monitor 102 | $this->monitorRenderer = new MonitorRenderer($this->gl, $this->renderState); 103 | 104 | // create a renderer for the GUI 105 | $this->guiRenderer = new GuiRenderer($this->vg, $this->renderState, $this->input, $this->dispatcher); 106 | 107 | // handle some application events 108 | $this->dispatcher->register('cpu.start', function() { 109 | $this->isRunning = true; 110 | }); 111 | 112 | $this->dispatcher->register('cpu.pause', function() { 113 | $this->isRunning = false; 114 | }); 115 | } 116 | 117 | /** 118 | * Prepare / setup additional render passes before the quickstart draw pass 119 | * This is an "setup" method meaning you should not emit any draw calls here, but 120 | * rather add additional render passes to the pipeline. 121 | * 122 | * @param RenderContext $context 123 | * @param RenderTargetResource $renderTarget 124 | * @return void 125 | */ 126 | public function setupDrawBefore(RenderContext $context, RenderTargetResource $renderTarget) : void 127 | { 128 | // we construct a viewport that matches the render target 129 | // this is not what we would usally use this helper for but in this case 130 | // its just a nice helper to work with our screen real estate 131 | $this->renderState->viewport = new Viewport( 132 | 0, 133 | $renderTarget->width / $renderTarget->contentScaleX, 134 | $renderTarget->height / $renderTarget->contentScaleY, 135 | 0, 136 | 1.0, 137 | 1.0 138 | 139 | ); 140 | 141 | $this->renderState->cpuIsRunning = $this->isRunning; 142 | 143 | // upload the buffer 144 | $options = new TextureOptions(); 145 | $options->dataFormat = GL_RED_INTEGER; 146 | $options->internalFormat = GL_R8UI; 147 | $options->dataType = GL_UNSIGNED_BYTE; 148 | $options->width = $this->monitor->width; 149 | $options->height = $this->monitor->height; 150 | $options->minFilter = GL_NEAREST; 151 | $options->magFilter = GL_NEAREST; 152 | $options->generateMipmaps = false; 153 | $this->monitorTexture->uploadBuffer($options, $this->monitor->blob); 154 | 155 | $textureResource = $context->pipeline->importTexture('chip8_monitor', $this->monitorTexture); 156 | 157 | $this->monitorRenderer->attachPass($context->pipeline, $renderTarget, $textureResource); 158 | } 159 | 160 | /** 161 | * Draw the scene. (You most definetly want to use this) 162 | * 163 | * This is called from within the Quickstart render pass where the pipeline is already 164 | * prepared, a VG frame is also already started. 165 | */ 166 | public function draw(RenderContext $context, RenderTarget $renderTarget) : void 167 | { 168 | QuickstartDebugMetricsOverlay::debugString('Press "F" to toggle fullscreen'); 169 | 170 | // draw the screen frame 171 | $this->guiRenderer->renderGUI($this->chip8); 172 | } 173 | 174 | /** 175 | * Update the games state 176 | * This method might be called multiple times per frame, or not at all if 177 | * the frame rate is very high. 178 | * 179 | * The update method should step the game forward in time, this is the place 180 | * where you would update the position of your game objects, check for collisions 181 | * and so on. 182 | */ 183 | public function update() : void 184 | { 185 | parent::update(); 186 | 187 | // update key states 188 | if ($this->inputContext->actions->didButtonPress('pause')) { 189 | $this->isRunning = !$this->isRunning; 190 | } 191 | 192 | // step the CPU 193 | if ($this->inputContext->actions->didButtonPress('step')) { 194 | $this->chip8->runCycles(1); 195 | } 196 | 197 | // toggle fullscreen 198 | if ($this->inputContext->actions->didButtonPress('fullscreen')) { 199 | $this->renderState->fullscreenMonitor = !$this->renderState->fullscreenMonitor; 200 | } 201 | 202 | // toggle crt effect 203 | if ($this->inputContext->actions->didButtonPress('toggle_crt')) { 204 | $this->renderState->crtEffectEnabled = !$this->renderState->crtEffectEnabled; 205 | } 206 | 207 | // toggle ghosting 208 | if ($this->inputContext->actions->didButtonPress('toggle_ghosting')) { 209 | $this->renderState->ghostingEffectLevel = match ($this->renderState->ghostingEffectLevel) { 210 | GhostingEffectLevel::None => GhostingEffectLevel::Low, 211 | GhostingEffectLevel::Low => GhostingEffectLevel::Medium, 212 | GhostingEffectLevel::Medium => GhostingEffectLevel::High, 213 | GhostingEffectLevel::High => GhostingEffectLevel::None, 214 | }; 215 | } 216 | 217 | // update the keyboard states 218 | if ($this->chip8->wantKeyboardUpdates) { 219 | $this->chip8->keyPressStates[0x1] = (int) $this->input->isKeyPressed(Key::NUM_1); 220 | $this->chip8->keyPressStates[0x2] = (int) $this->input->isKeyPressed(Key::NUM_2); 221 | $this->chip8->keyPressStates[0x3] = (int) $this->input->isKeyPressed(Key::NUM_3); 222 | $this->chip8->keyPressStates[0xC] = (int) $this->input->isKeyPressed(Key::NUM_4); 223 | $this->chip8->keyPressStates[0x4] = (int) $this->input->isKeyPressed(Key::Q); 224 | $this->chip8->keyPressStates[0x5] = (int) $this->input->isKeyPressed(Key::W); 225 | $this->chip8->keyPressStates[0x6] = (int) $this->input->isKeyPressed(Key::E); 226 | $this->chip8->keyPressStates[0xD] = (int) $this->input->isKeyPressed(Key::R); 227 | $this->chip8->keyPressStates[0x7] = (int) $this->input->isKeyPressed(Key::A); 228 | $this->chip8->keyPressStates[0x8] = (int) $this->input->isKeyPressed(Key::S); 229 | $this->chip8->keyPressStates[0x9] = (int) $this->input->isKeyPressed(Key::D); 230 | $this->chip8->keyPressStates[0xE] = (int) $this->input->isKeyPressed(Key::F); 231 | $this->chip8->keyPressStates[0xA] = (int) $this->input->isKeyPressed(Key::Y); 232 | $this->chip8->keyPressStates[0x0] = (int) $this->input->isKeyPressed(Key::X); 233 | $this->chip8->keyPressStates[0xB] = (int) $this->input->isKeyPressed(Key::C); 234 | $this->chip8->keyPressStates[0xF] = (int) $this->input->isKeyPressed(Key::V); 235 | } 236 | 237 | if (!$this->isRunning) { 238 | return; 239 | } 240 | 241 | $this->chip8->updateTimers(); 242 | 243 | // quick sanity check on the cycles per tick value 244 | $this->renderState->cyclesPerTick = max(1, min(5000, $this->renderState->cyclesPerTick)); 245 | 246 | // effective cylces that should be run 247 | if ($this->renderState->cyclesPerTick > RenderState::SUBTICK_DIV) { 248 | $effectiveCycles = $this->renderState->cyclesPerTick - RenderState::SUBTICK_DIV; 249 | } else { 250 | $effectiveCycles = (int) ($this->tickIndex % ((RenderState::SUBTICK_DIV + 1) - $this->renderState->cyclesPerTick) === 0); 251 | } 252 | 253 | if ($this->chip8->runCycles($effectiveCycles) === 0) { 254 | $this->isRunning = false; 255 | } 256 | } 257 | } -------------------------------------------------------------------------------- /src/Renderer/MonitorRenderer.php: -------------------------------------------------------------------------------- 1 | shaderProgram = new ShaderProgram($glstate); 38 | 39 | // attach a simple vertex shader 40 | $this->shaderProgram->attach(new ShaderStage(ShaderStage::VERTEX, <<< 'GLSL' 41 | #version 330 core 42 | 43 | layout (location = 0) in vec3 aPos; 44 | layout (location = 1) in vec2 aTexCoord; 45 | 46 | // im lazy to so just transform in the shader via uniforms 47 | uniform vec2 position; 48 | uniform vec2 size; 49 | uniform vec2 screen_size; 50 | 51 | out vec2 tex_coords; 52 | 53 | void main() 54 | { 55 | // position are in screen space pixel coordinates 56 | vec2 npos = position; 57 | npos.y = screen_size.y - npos.y - size.y; 58 | vec2 npos_normalized = (2.0 * npos) / screen_size - 1.0; 59 | vec2 nsize = (2.0 * size) / screen_size; 60 | 61 | vec2 pos = npos_normalized + ((aPos.xy + 1.0) * 0.5) * nsize; 62 | 63 | gl_Position = vec4(pos, aPos.z, 1.0); 64 | tex_coords = aTexCoord; 65 | } 66 | GLSL)); 67 | 68 | // also attach a simple fragment shader 69 | $this->shaderProgram->attach(new ShaderStage(ShaderStage::FRAGMENT, <<< 'GLSL' 70 | #version 330 core 71 | 72 | out vec4 fragment_color; 73 | in vec2 tex_coords; 74 | 75 | uniform sampler2D u_texture; 76 | uniform float u_time; 77 | uniform int u_crt_effect; 78 | 79 | vec2 curve(vec2 uv) 80 | { 81 | uv = (uv - 0.5) * 2.0; 82 | uv *= 1.1; 83 | uv.x *= 1.0 + pow((abs(uv.y) / 5.0), 2.0); 84 | uv.y *= 1.0 + pow((abs(uv.x) / 4.0), 2.0); 85 | uv = (uv / 2.0) + 0.5; 86 | uv = uv *0.92 + 0.04; 87 | return uv; 88 | } 89 | 90 | vec4 get_color(vec2 coords) { 91 | return texture(u_texture, coords); 92 | } 93 | 94 | /** 95 | * This is a modified version of the "MattiasCRT" shader from shadertoy 96 | * https://www.shadertoy.com/view/Ms23DR 97 | */ 98 | vec4 get_color_crt(vec2 coords) 99 | { 100 | vec2 iResolution = vec2(640, 320); 101 | 102 | vec2 uv = curve(coords); 103 | vec3 oricol = get_color(coords).xyz; 104 | vec3 col; 105 | float x = sin(0.3*u_time+uv.y*21.0)*sin(0.7*u_time+uv.y*29.0)*sin(0.3+0.33*u_time+uv.y*31.0)*0.0017; 106 | 107 | col.r = get_color(vec2(x+uv.x+0.001,uv.y+0.001)).x+0.05; 108 | col.g = get_color(vec2(x+uv.x+0.000,uv.y-0.002)).y+0.05; 109 | col.b = get_color(vec2(x+uv.x-0.002,uv.y+0.000)).z+0.05; 110 | col.r += 0.08*get_color(0.75*vec2(x+0.025, -0.027)+vec2(uv.x+0.001,uv.y+0.001)).x; 111 | col.g += 0.05*get_color(0.75*vec2(x+-0.022, -0.02)+vec2(uv.x+0.000,uv.y-0.002)).y; 112 | col.b += 0.08*get_color(0.75*vec2(x+-0.02, -0.018)+vec2(uv.x-0.002,uv.y+0.000)).z; 113 | 114 | col = clamp(col*0.6+0.4*col*col*1.0,0.0,1.0); 115 | 116 | float vig = (0.0 + 1.0*16.0*uv.x*uv.y*(1.0-uv.x)*(1.0-uv.y)); 117 | col *= vec3(pow(vig,0.3)); 118 | 119 | col *= vec3(0.95,1.05,0.95); 120 | col *= 2.8; 121 | 122 | float scans = clamp( 0.35+0.35*sin(3.5*u_time+uv.y*iResolution.y*1.5), 0.0, 1.0); 123 | 124 | float s = pow(scans,1.7); 125 | col = col*vec3( 0.4+0.7*s) ; 126 | 127 | col *= 1.0+0.01*sin(110.0*u_time); 128 | col*=1.0-0.65*vec3(clamp((mod(coords.x, 2.0)-1.0)*2.0,0.0,1.0)); 129 | 130 | return vec4(col, 1.0); 131 | } 132 | 133 | void main() 134 | { 135 | if (u_crt_effect == 0) { 136 | fragment_color = get_color(tex_coords); 137 | return; 138 | } 139 | fragment_color = get_color_crt(tex_coords); 140 | } 141 | GLSL)); 142 | $this->shaderProgram->link(); 143 | 144 | /** 145 | * Ghosting shader 146 | */ 147 | $this->shaderProgramGhosting = new ShaderProgram($glstate); 148 | $this->shaderProgramGhosting->attach(new ShaderStage(ShaderStage::VERTEX, <<< 'GLSL' 149 | #version 330 core 150 | 151 | layout (location = 0) in vec3 aPos; 152 | layout (location = 1) in vec2 aTexCoord; 153 | 154 | out vec2 tex_coords; 155 | 156 | void main() 157 | { 158 | gl_Position = vec4(aPos, 1.0); 159 | tex_coords = aTexCoord; 160 | } 161 | GLSL)); 162 | 163 | $this->shaderProgramGhosting->attach(new ShaderStage(ShaderStage::FRAGMENT, <<< 'GLSL' 164 | #version 330 core 165 | 166 | out vec4 fragment_color; 167 | in vec2 tex_coords; 168 | 169 | uniform sampler2D u_texture; 170 | uniform float u_ghosting_amount; 171 | 172 | void main() 173 | { 174 | vec4 color = texture(u_texture, tex_coords); 175 | 176 | // slightly darken the color 177 | // color *= 0.995; 178 | // color *= 0.99; 179 | color *= u_ghosting_amount; 180 | 181 | fragment_color = color; 182 | } 183 | GLSL)); 184 | 185 | $this->shaderProgramGhosting->link(); 186 | 187 | /** 188 | * Screen shader 189 | */ 190 | $this->shaderProgramScreen = new ShaderProgram($glstate); 191 | $this->shaderProgramScreen->attach(new ShaderStage(ShaderStage::VERTEX, <<< 'GLSL' 192 | #version 330 core 193 | 194 | layout (location = 0) in vec3 aPos; 195 | layout (location = 1) in vec2 aTexCoord; 196 | 197 | out vec2 tex_coords; 198 | 199 | void main() 200 | { 201 | gl_Position = vec4(aPos, 1.0); 202 | tex_coords = aTexCoord; 203 | } 204 | GLSL)); 205 | 206 | $this->shaderProgramScreen->attach(new ShaderStage(ShaderStage::FRAGMENT, <<< 'GLSL' 207 | #version 330 core 208 | 209 | out vec4 fragment_color; 210 | in vec2 tex_coords; 211 | 212 | uniform usampler2D u_texture; 213 | uniform int u_monochrome; 214 | 215 | vec4 get_color(vec2 coords) { 216 | uint pixel = texture(u_texture, coords * vec2(1, -1)).r; 217 | 218 | // monochrome mode here just means either on or off 219 | if (u_monochrome == 1) { 220 | return vec4(pixel > uint(0) ? 1.0 : 0.0); 221 | } 222 | 223 | // unpack the pixel into 3,3,2 bits 224 | uint r = (pixel >> 5u) & 0x07u; 225 | uint g = (pixel >> 2u) & 0x07u; 226 | uint b = pixel & 0x03u; 227 | 228 | // normalize the color 229 | float red = float(r) / 7.0; 230 | float green = float(g) / 7.0; 231 | float blue = float(b) / 3.0; 232 | 233 | return vec4(red, green, blue, pixel > uint(0) ? 1.0 : 0.0); 234 | } 235 | 236 | void main() 237 | { 238 | fragment_color = get_color(tex_coords); 239 | } 240 | 241 | GLSL)); 242 | 243 | $this->shaderProgramScreen->link(); 244 | } 245 | 246 | /** 247 | * Attaches a render pass to the pipeline 248 | * 249 | * @param RenderPipeline $pipeline 250 | * @param RenderTargetResource $renderTarget 251 | * @param TextureResource $texture 252 | */ 253 | public function attachPass( 254 | RenderPipeline $pipeline, 255 | RenderTargetResource $renderTarget, 256 | TextureResource $texture 257 | ) : void 258 | { 259 | $pipeline->addPass(new CallbackPass( 260 | 'ScreenGhosting', 261 | function(RenderPass $pass, RenderPipeline $pipeline, PipelineContainer $data) use ($texture, $renderTarget) { 262 | 263 | $passData = $data->create(MonitorPassData::class); 264 | 265 | $nearestOpt = new TextureOptions; 266 | $nearestOpt->minFilter = GL_NEAREST; 267 | $nearestOpt->magFilter = GL_NEAREST; 268 | 269 | $passData->ghostingTarget = $pipeline->createRenderTarget('ghosting_fade', $texture->width, $texture->height); 270 | $passData->ghostingTexture = $pipeline->createColorAttachment($passData->ghostingTarget, 'screen_fade', $nearestOpt); 271 | 272 | $passData->screenTarget = $pipeline->createRenderTarget('screen', $texture->width, $texture->height); 273 | $passData->screenTexture = $pipeline->createColorAttachment($passData->screenTarget, 'screen', $nearestOpt); 274 | 275 | $pipeline->writes($pass, $passData->ghostingTarget); 276 | $pipeline->writes($pass, $passData->screenTarget); 277 | $pipeline->reads($pass, $texture); 278 | 279 | // clear the ghosting target 280 | $pipeline->addPass(new ClearPass($passData->ghostingTarget)); 281 | 282 | // then render a ghost of the previous frame on the ghosting target 283 | $ghostPass = new FullscreenQuadPass( 284 | $passData->ghostingTarget, 285 | $passData->screenTexture, 286 | $this->shaderProgramGhosting, 287 | ); 288 | 289 | $ghostAmount = match ($this->renderState->ghostingEffectLevel) { 290 | GhostingEffectLevel::None => 0.0, 291 | GhostingEffectLevel::Low => 0.95, 292 | GhostingEffectLevel::Medium => 0.98, 293 | GhostingEffectLevel::High => 0.995, 294 | }; 295 | 296 | $ghostPass->extraUniforms['u_ghosting_amount'] = $ghostAmount; 297 | 298 | $pipeline->addPass($ghostPass); 299 | 300 | // then render the monitor on the ghosting target aswell 301 | $screenPass = new FullscreenQuadPass( 302 | $passData->ghostingTarget, 303 | $texture, 304 | $this->shaderProgramScreen, 305 | ); 306 | $screenPass->shouldBlend = $this->renderState->ghostingEffectLevel != GhostingEffectLevel::None; 307 | $screenPass->extraUniforms['u_monochrome'] = (int) $this->renderState->monochrome; 308 | 309 | $pipeline->addPass($screenPass); 310 | 311 | // clear the screen target and render the ghosted frame on the screen target 312 | // so we can use it in the next frame 313 | $pipeline->addPass(new ClearPass($passData->screenTarget)); 314 | $copyPass = new FullscreenQuadPass( 315 | $passData->screenTarget, 316 | $passData->ghostingTexture, 317 | $this->shaderProgramGhosting, 318 | ); 319 | $pipeline->addPass($copyPass); 320 | 321 | // clear the actual render target 322 | $pipeline->addPass(new ClearPass($renderTarget)); 323 | 324 | // render the monitor on the actual render target 325 | $quadPass = new FullscreenQuadPass( 326 | $renderTarget, 327 | $passData->ghostingTexture, 328 | $this->shaderProgram, 329 | ); 330 | 331 | $monitorPos = $this->renderState->getMonitorPosition(); 332 | $monitorSize = $this->renderState->getMonitorSize(); 333 | 334 | // var_dump($monitorPos, $monitorSize); die; 335 | 336 | $quadPass->extraUniforms['position'] = $monitorPos; 337 | $quadPass->extraUniforms['size'] = $monitorSize; 338 | $quadPass->extraUniforms['screen_size'] = new Vec2( 339 | $renderTarget->width / $renderTarget->contentScaleX, 340 | $renderTarget->height / $renderTarget->contentScaleY 341 | ); 342 | 343 | 344 | 345 | // if ($this->renderState->fullscreenMonitor) { 346 | // $quadPass->extraUniforms['position'] = new Vec2(0, 0); 347 | // $quadPass->extraUniforms['size'] = new Vec2(1, 1); 348 | // } else { 349 | // $quadPass->extraUniforms['position'] = new Vec2(0.5, 0.5); 350 | // $quadPass->extraUniforms['size'] = new Vec2(0.5, 0.5); 351 | // } 352 | 353 | $quadPass->extraUniforms['u_time'] = glfwGetTime(); 354 | $quadPass->extraUniforms['u_crt_effect'] = (int) $this->renderState->crtEffectEnabled; 355 | 356 | $pipeline->addPass($quadPass); 357 | 358 | }, 359 | function(PipelineContainer $data, PipelineResources $resources) use ($texture) { 360 | // activate the screen render target to ensure the screen 361 | // texture is available in the next frame 362 | $passData = $data->get(MonitorPassData::class); 363 | $resources->activateRenderTarget($passData->screenTarget); 364 | }, 365 | )); 366 | } 367 | } 368 | -------------------------------------------------------------------------------- /src/CPU/InstructionSet.php: -------------------------------------------------------------------------------- 1 | new class extends InstructionHandler { 18 | public function disassemble(int $opcode): string { 19 | return 'CLS'; 20 | } 21 | 22 | public function handle(CPU $cpu, int $opcode): void { 23 | $cpu->monitor->blob->fill($cpu->monitor->blob->size(), 0); 24 | } 25 | }, 26 | 27 | 0xEE => new class extends InstructionHandler { 28 | public function disassemble(int $opcode): string { 29 | return 'RET'; 30 | } 31 | 32 | public function handle(CPU $cpu, int $opcode): void { 33 | $cpu->programCounter = $cpu->stack[--$cpu->stackPointer]; 34 | } 35 | }, 36 | 37 | 0xFD => new class extends InstructionHandler { 38 | public function disassemble(int $opcode): string { 39 | return 'EXIT'; 40 | } 41 | 42 | public function handle(CPU $cpu, int $opcode): void { 43 | $cpu->shouldExit = true; 44 | } 45 | }, 46 | ] 47 | ); 48 | 49 | $registerInstructions = new InstructionRegistry( 50 | bitmask: 0x000F, 51 | handlers: [ 52 | /** 53 | * 8xy0 - LD Vx, Vy 54 | * Set Vx = Vy 55 | */ 56 | 0x0 => new class extends InstructionHandler { 57 | public function disassemble(int $opcode): string { 58 | return sprintf('LD V%X, V%X', ($opcode & 0x0F00) >> 8, ($opcode & 0x00F0) >> 4); 59 | } 60 | 61 | public function handle(CPU $cpu, int $opcode): void { 62 | $registerX = ($opcode & 0x0F00) >> 8; 63 | $registerY = ($opcode & 0x00F0) >> 4; 64 | 65 | $cpu->registers[$registerX] = $cpu->registers[$registerY]; 66 | } 67 | }, 68 | 69 | /** 70 | * 8xy1 - OR Vx, Vy 71 | * Set Vx = Vx OR Vy 72 | */ 73 | 0x1 => new class extends InstructionHandler { 74 | public function disassemble(int $opcode): string { 75 | return sprintf('OR V%X, V%X', ($opcode & 0x0F00) >> 8, ($opcode & 0x00F0) >> 4); 76 | } 77 | 78 | public function handle(CPU $cpu, int $opcode): void { 79 | $registerX = ($opcode & 0x0F00) >> 8; 80 | $registerY = ($opcode & 0x00F0) >> 4; 81 | 82 | $cpu->registers[$registerX] |= $cpu->registers[$registerY]; 83 | } 84 | }, 85 | 86 | /** 87 | * 8xy2 - AND Vx, Vy 88 | * Set Vx = Vx AND Vy 89 | */ 90 | 0x2 => new class extends InstructionHandler { 91 | public function disassemble(int $opcode): string { 92 | return sprintf('AND V%X, V%X', ($opcode & 0x0F00) >> 8, ($opcode & 0x00F0) >> 4); 93 | } 94 | 95 | public function handle(CPU $cpu, int $opcode): void { 96 | $registerX = ($opcode & 0x0F00) >> 8; 97 | $registerY = ($opcode & 0x00F0) >> 4; 98 | 99 | $cpu->registers[$registerX] &= $cpu->registers[$registerY]; 100 | } 101 | }, 102 | 103 | /** 104 | * 8xy3 - XOR Vx, Vy 105 | * Set Vx = Vx XOR Vy 106 | */ 107 | 0x3 => new class extends InstructionHandler { 108 | public function disassemble(int $opcode): string { 109 | return sprintf('XOR V%X, V%X', ($opcode & 0x0F00) >> 8, ($opcode & 0x00F0) >> 4); 110 | } 111 | 112 | public function handle(CPU $cpu, int $opcode): void { 113 | $registerX = ($opcode & 0x0F00) >> 8; 114 | $registerY = ($opcode & 0x00F0) >> 4; 115 | 116 | $cpu->registers[$registerX] ^= $cpu->registers[$registerY]; 117 | } 118 | }, 119 | 120 | /** 121 | * 8xy4 - ADD Vx, Vy 122 | * Set Vx = Vx + Vy, set VF = carry 123 | */ 124 | 0x4 => new class extends InstructionHandler { 125 | public function disassemble(int $opcode): string { 126 | return sprintf('ADD V%X, V%X', ($opcode & 0x0F00) >> 8, ($opcode & 0x00F0) >> 4); 127 | } 128 | 129 | public function handle(CPU $cpu, int $opcode): void { 130 | $registerX = ($opcode & 0x0F00) >> 8; 131 | $registerY = ($opcode & 0x00F0) >> 4; 132 | 133 | $sum = $cpu->registers[$registerX] + $cpu->registers[$registerY]; 134 | $cpu->registers[$registerX] = $sum & 0xFF; 135 | $cpu->registers[0xF] = $sum > 0xFF ? 1 : 0; 136 | } 137 | }, 138 | 139 | /** 140 | * 8xy5 - SUB Vx, Vy 141 | * Set Vx = Vx - Vy, set VF = NOT borrow 142 | */ 143 | 0x5 => new class extends InstructionHandler { 144 | public function disassemble(int $opcode): string { 145 | return sprintf('SUB V%X, V%X', ($opcode & 0x0F00) >> 8, ($opcode & 0x00F0) >> 4); 146 | } 147 | 148 | public function handle(CPU $cpu, int $opcode): void { 149 | $registerX = ($opcode & 0x0F00) >> 8; 150 | $registerY = ($opcode & 0x00F0) >> 4; 151 | 152 | $diff = $cpu->registers[$registerX] - $cpu->registers[$registerY]; 153 | $cpu->registers[$registerX] = $diff & 0xFF; 154 | $cpu->registers[0xF] = $diff >= 0 ? 1 : 0; 155 | } 156 | }, 157 | 158 | /** 159 | * 8xy6 - SHR Vx {, Vy} 160 | * Set Vx = Vx SHR 1 161 | */ 162 | 0x6 => new class extends InstructionHandler { 163 | public function disassemble(int $opcode): string { 164 | return sprintf('SHR V%X', ($opcode & 0x0F00) >> 8); 165 | } 166 | 167 | public function handle(CPU $cpu, int $opcode): void { 168 | $registerX = ($opcode & 0x0F00) >> 8; 169 | $lsb = $cpu->registers[$registerX] & 0x1; 170 | $cpu->registers[$registerX] >>= 1; 171 | $cpu->registers[0xF] = $lsb; 172 | } 173 | }, 174 | 175 | /** 176 | * 8xy7 - SUBN Vx, Vy 177 | * Set Vx = Vy - Vx, set VF = NOT borrow 178 | */ 179 | 0x7 => new class extends InstructionHandler { 180 | public function disassemble(int $opcode): string { 181 | return sprintf('SUBN V%X, V%X', ($opcode & 0x0F00) >> 8, ($opcode & 0x00F0) >> 4); 182 | } 183 | 184 | public function handle(CPU $cpu, int $opcode): void { 185 | $registerX = ($opcode & 0x0F00) >> 8; 186 | $registerY = ($opcode & 0x00F0) >> 4; 187 | 188 | $diff = $cpu->registers[$registerY] - $cpu->registers[$registerX]; 189 | $cpu->registers[$registerX] = $diff & 0xFF; 190 | $cpu->registers[0xF] = $diff >= 0 ? 1 : 0; 191 | } 192 | }, 193 | 194 | /** 195 | * 8xyE - SHL Vx {, Vy} 196 | * Set Vx = Vx SHL 1 197 | */ 198 | 0xE => new class extends InstructionHandler { 199 | public function disassemble(int $opcode): string { 200 | return sprintf('SHL V%X', ($opcode & 0x0F00) >> 8); 201 | } 202 | 203 | public function handle(CPU $cpu, int $opcode): void { 204 | $registerX = ($opcode & 0x0F00) >> 8; 205 | $msb = $cpu->registers[$registerX] >> 7; 206 | $cpu->registers[$registerX] <<= 1; 207 | $cpu->registers[0xF] = $msb; 208 | } 209 | }, 210 | ] 211 | ); 212 | 213 | $keyInstructions = new InstructionRegistry( 214 | bitmask: 0x00FF, 215 | handlers: [ 216 | /** 217 | * Ex9E - SKP Vx 218 | * Skip next instruction if key with the value of Vx is pressed 219 | */ 220 | 0x9E => new class extends InstructionHandler { 221 | public function disassemble(int $opcode): string { 222 | return sprintf('SKP V%X', ($opcode & 0x0F00) >> 8); 223 | } 224 | 225 | public function handle(CPU $cpu, int $opcode): void { 226 | $register = $opcode >> 8 & 0x0F; 227 | if ($cpu->keyPressStates[$cpu->registers[$register]] === 1) { 228 | $cpu->programCounter += 2; 229 | } 230 | } 231 | }, 232 | 233 | /** 234 | * ExA1 - SKNP Vx 235 | * Skip next instruction if key with the value of Vx is not pressed 236 | */ 237 | 0xA1 => new class extends InstructionHandler { 238 | public function disassemble(int $opcode): string { 239 | return sprintf('SKNP V%X', ($opcode & 0x0F00) >> 8); 240 | } 241 | 242 | public function handle(CPU $cpu, int $opcode): void { 243 | $register = $opcode >> 8 & 0x0F; 244 | if ($cpu->keyPressStates[$cpu->registers[$register]] === 0) { 245 | $cpu->programCounter += 2; 246 | } 247 | } 248 | }, 249 | ] 250 | ); 251 | 252 | $timerInstructions = new InstructionRegistry( 253 | bitmask: 0x00FF, 254 | handlers: [ 255 | /** 256 | * Fx07 - LD Vx, DT 257 | * Set Vx = delay timer value 258 | */ 259 | 0x07 => new class extends InstructionHandler { 260 | public function disassemble(int $opcode): string { 261 | return sprintf('LD V%X, DT', ($opcode & 0x0F00) >> 8); 262 | } 263 | 264 | public function handle(CPU $cpu, int $opcode): void { 265 | $register = ($opcode & 0x0F00) >> 8; 266 | $cpu->registers[$register] = $cpu->timers[0]; 267 | } 268 | }, 269 | 270 | /** 271 | * Fx0A - LD Vx, K 272 | * Wait for a key press, store the value of the key in Vx 273 | */ 274 | 0x0A => new class extends InstructionHandler { 275 | public function disassemble(int $opcode): string { 276 | return sprintf('LD V%X, K', ($opcode & 0x0F00) >> 8); 277 | } 278 | 279 | public function handle(CPU $cpu, int $opcode): void { 280 | $register = ($opcode & 0x0F00) >> 8; 281 | $keyPressed = false; 282 | for ($i = 0; $i < 16; $i++) { 283 | if ($cpu->keyPressStates[$i] === 1) { 284 | $cpu->registers[$register] = $i; 285 | $keyPressed = true; 286 | break; 287 | } 288 | } 289 | if (!$keyPressed) { 290 | $cpu->programCounter -= 2; 291 | } 292 | } 293 | }, 294 | 295 | /** 296 | * Fx15 - LD DT, Vx 297 | * Set delay timer = Vx 298 | */ 299 | 0x15 => new class extends InstructionHandler { 300 | public function disassemble(int $opcode): string { 301 | return sprintf('LD DT, V%X', ($opcode & 0x0F00) >> 8); 302 | } 303 | 304 | public function handle(CPU $cpu, int $opcode): void { 305 | $register = ($opcode & 0x0F00) >> 8; 306 | $cpu->timers[0] = $cpu->registers[$register]; 307 | } 308 | }, 309 | 310 | /** 311 | * Fx18 - LD ST, Vx 312 | * Set sound 313 | * timer = Vx 314 | */ 315 | 0x18 => new class extends InstructionHandler { 316 | public function disassemble(int $opcode): string { 317 | return sprintf('LD ST, V%X', ($opcode & 0x0F00) >> 8); 318 | } 319 | 320 | public function handle(CPU $cpu, int $opcode): void { 321 | $register = ($opcode & 0x0F00) >> 8; 322 | $cpu->timers[1] = $cpu->registers[$register]; 323 | } 324 | }, 325 | 326 | /** 327 | * Fx1E - ADD I, Vx 328 | * Set I = I + Vx 329 | */ 330 | 0x1E => new class extends InstructionHandler { 331 | public function disassemble(int $opcode): string { 332 | return sprintf('ADD I, V%X', ($opcode & 0x0F00) >> 8); 333 | } 334 | 335 | public function handle(CPU $cpu, int $opcode): void { 336 | $register = ($opcode & 0x0F00) >> 8; 337 | $cpu->registerI += $cpu->registers[$register]; 338 | } 339 | }, 340 | 341 | /** 342 | * Fx29 - LD F, Vx 343 | * Set I = location of sprite for digit Vx 344 | */ 345 | 0x29 => new class extends InstructionHandler { 346 | public function disassemble(int $opcode): string { 347 | return sprintf('LD F, V%X', ($opcode & 0x0F00) >> 8); 348 | } 349 | 350 | public function handle(CPU $cpu, int $opcode): void { 351 | $register = ($opcode & 0x0F00) >> 8; 352 | $digit = $cpu->registers[$register]; 353 | $loc = $cpu->digitSpriteLocations[$digit]; 354 | $cpu->registerI = $loc; 355 | } 356 | }, 357 | 358 | /** 359 | * Fx33 - LD B, Vx 360 | * Store BCD representation of Vx in memory locations I, I+1, and I+2 361 | */ 362 | 0x33 => new class extends InstructionHandler { 363 | public function disassemble(int $opcode): string { 364 | return sprintf('LD B, V%X', ($opcode & 0x0F00) >> 8); 365 | } 366 | 367 | public function handle(CPU $cpu, int $opcode): void { 368 | $register = ($opcode & 0x0F00) >> 8; 369 | $value = $cpu->registers[$register]; 370 | 371 | $cpu->memory->blob[$cpu->registerI] = (int) ($value / 100); 372 | $cpu->memory->blob[$cpu->registerI + 1] = (int) (((int)($value / 10)) % 10); 373 | $cpu->memory->blob[$cpu->registerI + 2] = (int) ($value % 10); 374 | } 375 | }, 376 | 377 | /** 378 | * Fx55 - LD [I], Vx 379 | * Store registers V0 through Vx in memory starting at location I 380 | */ 381 | 0x55 => new class extends InstructionHandler { 382 | public function disassemble(int $opcode): string { 383 | return sprintf('LD [I], V%X', ($opcode & 0x0F00) >> 8); 384 | } 385 | 386 | public function handle(CPU $cpu, int $opcode): void { 387 | $endRegister = ($opcode & 0x0F00) >> 8; 388 | for ($i = 0; $i <= $endRegister; $i++) { 389 | $cpu->memory->blob[$cpu->registerI + $i] = $cpu->registers[$i]; 390 | } 391 | } 392 | }, 393 | 394 | /** 395 | * Fx65 - LD Vx, [I] 396 | * Read registers V0 through Vx from memory starting at location I 397 | */ 398 | 0x65 => new class extends InstructionHandler { 399 | public function disassemble(int $opcode): string { 400 | return sprintf('LD V%X, [I]', ($opcode & 0x0F00) >> 8); 401 | } 402 | 403 | public function handle(CPU $cpu, int $opcode): void { 404 | $endRegister = ($opcode & 0x0F00) >> 8; 405 | for ($i = 0; $i <= $endRegister; $i++) { 406 | $cpu->registers[$i] = $cpu->memory->blob[$cpu->registerI + $i]; 407 | } 408 | } 409 | }, 410 | ] 411 | ); 412 | 413 | return new InstructionRegistry( 414 | bitmask: 0x0F, 415 | shiftRight: 12, 416 | handlers: [ 417 | 0x0 => new RegistryInstructionHandler($x00Instructions), 418 | 419 | /** 420 | * 1nnn - JP addr 421 | * Jump to location nnn 422 | */ 423 | 0x1 => new class extends InstructionHandler { 424 | public function disassemble(int $opcode): string { 425 | return sprintf('JP 0x%03X', $opcode & 0x0FFF); 426 | } 427 | 428 | public function handle(CPU $cpu, int $opcode): void { 429 | $cpu->programCounter = $opcode & 0x0FFF; 430 | } 431 | }, 432 | 433 | /** 434 | * 2nnn - CALL addr 435 | * Call subroutine at nnn 436 | */ 437 | 0x2 => new class extends InstructionHandler { 438 | public function disassemble(int $opcode): string { 439 | return sprintf('CALL 0x%03X', $opcode & 0x0FFF); 440 | } 441 | 442 | public function handle(CPU $cpu, int $opcode): void { 443 | $address = $opcode & 0x0FFF; 444 | $cpu->stack[$cpu->stackPointer++] = $cpu->programCounter; 445 | $cpu->programCounter = $address; 446 | } 447 | }, 448 | 449 | /** 450 | * 3xkk - SE Vx, byte 451 | * Skip next instruction if Vx = kk 452 | */ 453 | 0x3 => new class extends InstructionHandler { 454 | public function disassemble(int $opcode): string { 455 | return sprintf('SE V%X, 0x%02X', ($opcode & 0x0F00) >> 8, $opcode & 0x00FF); 456 | } 457 | 458 | public function handle(CPU $cpu, int $opcode): void { 459 | $register = ($opcode & 0x0F00) >> 8; 460 | $value = $opcode & 0x00FF; 461 | 462 | if ($cpu->registers[$register] === $value) { 463 | $cpu->programCounter += 2; 464 | } 465 | } 466 | }, 467 | 468 | /** 469 | * 4xkk - SNE Vx, byte 470 | * Skip next instruction if Vx != kk 471 | */ 472 | 0x4 => new class extends InstructionHandler { 473 | public function disassemble(int $opcode): string { 474 | return sprintf('SNE V%X, 0x%02X', ($opcode & 0x0F00) >> 8, $opcode & 0x00FF); 475 | } 476 | 477 | public function handle(CPU $cpu, int $opcode): void { 478 | $register = ($opcode & 0x0F00) >> 8; 479 | $value = $opcode & 0x00FF; 480 | 481 | if ($cpu->registers[$register] !== $value) { 482 | $cpu->programCounter += 2; 483 | } 484 | } 485 | }, 486 | 487 | /** 488 | * 5xy0 - SE Vx, Vy 489 | * Skip next instruction if Vx = Vy 490 | */ 491 | 0x5 => new class extends InstructionHandler { 492 | public function disassemble(int $opcode): string { 493 | return sprintf('SE V%X, V%X', ($opcode & 0x0F00) >> 8, ($opcode & 0x00F0) >> 4); 494 | } 495 | 496 | public function handle(CPU $cpu, int $opcode): void { 497 | $registerX = ($opcode & 0x0F00) >> 8; 498 | $registerY = ($opcode & 0x00F0) >> 4; 499 | 500 | if ($cpu->registers[$registerX] === $cpu->registers[$registerY]) { 501 | $cpu->programCounter += 2; 502 | } 503 | } 504 | }, 505 | 506 | /** 507 | * 6xkk - LD Vx, byte 508 | * Set Vx = kk 509 | */ 510 | 0x6 => new class extends InstructionHandler { 511 | public function disassemble(int $opcode): string { 512 | return sprintf('LD V%X, 0x%02X', ($opcode & 0x0F00) >> 8, $opcode & 0x00FF); 513 | } 514 | 515 | public function handle(CPU $cpu, int $opcode): void { 516 | $register = ($opcode & 0x0F00) >> 8; 517 | $value = $opcode & 0x00FF; 518 | 519 | $cpu->registers[$register] = $value; 520 | } 521 | }, 522 | 523 | /** 524 | * 7xkk - ADD Vx, byte 525 | * Set Vx = Vx + kk 526 | */ 527 | 0x7 => new class extends InstructionHandler { 528 | public function disassemble(int $opcode): string { 529 | return sprintf('ADD V%X, 0x%02X', ($opcode & 0x0F00) >> 8, $opcode & 0x00FF); 530 | } 531 | 532 | public function handle(CPU $cpu, int $opcode): void { 533 | $register = ($opcode & 0x0F00) >> 8; 534 | $value = $opcode & 0x00FF; 535 | 536 | $cpu->registers[$register] += $value; 537 | } 538 | }, 539 | 540 | /** 541 | * 8xxx - Register instructions 542 | */ 543 | 0x8 => new RegistryInstructionHandler($registerInstructions), 544 | 545 | /** 546 | * 9xy0 - SNE Vx, Vy 547 | * Skip next instruction if Vx != Vy 548 | */ 549 | 0x9 => new class extends InstructionHandler { 550 | public function disassemble(int $opcode): string { 551 | return sprintf('SNE V%X, V%X', ($opcode & 0x0F00) >> 8, ($opcode & 0x00F0) >> 4); 552 | } 553 | 554 | public function handle(CPU $cpu, int $opcode): void { 555 | $registerX = ($opcode & 0x0F00) >> 8; 556 | $registerY = ($opcode & 0x00F0) >> 4; 557 | 558 | if ($cpu->registers[$registerX] !== $cpu->registers[$registerY]) { 559 | $cpu->programCounter += 2; 560 | } 561 | } 562 | }, 563 | 564 | /** 565 | * Annn - LD I, addr 566 | * Set I = nnn 567 | */ 568 | 0xA => new class extends InstructionHandler { 569 | public function disassemble(int $opcode): string { 570 | return sprintf('LD I, 0x%03X', $opcode & 0x0FFF); 571 | } 572 | 573 | public function handle(CPU $cpu, int $opcode): void { 574 | $cpu->registerI = $opcode & 0x0FFF; 575 | } 576 | }, 577 | 578 | /** 579 | * Bnnn - JP V0, addr 580 | * Jump to location nnn + V0 581 | */ 582 | 0xB => new class extends InstructionHandler { 583 | public function disassemble(int $opcode): string { 584 | return sprintf('JP V0, 0x%03X', $opcode & 0x0FFF); 585 | } 586 | 587 | public function handle(CPU $cpu, int $opcode): void { 588 | $address = $opcode & 0x0FFF; 589 | $cpu->programCounter = $cpu->registers[0] + $address; 590 | } 591 | }, 592 | 593 | /** 594 | * Cxkk - RND Vx, byte 595 | * Set Vx = random byte AND kk 596 | */ 597 | 0xC => new class extends InstructionHandler { 598 | public function disassemble(int $opcode): string { 599 | return sprintf('RND V%X, 0x%02X', ($opcode & 0x0F00) >> 8, $opcode & 0x00FF); 600 | } 601 | 602 | public function handle(CPU $cpu, int $opcode): void { 603 | $register = ($opcode & 0x0F00) >> 8; 604 | $value = $opcode & 0x00FF; 605 | 606 | $cpu->registers[$register] = random_int(0, 255) & $value; 607 | } 608 | }, 609 | 610 | /** 611 | * Dxyn - DRW Vx, Vy, nibble 612 | * Display n-byte sprite starting at memory location I at (Vx, Vy), set VF = collision 613 | */ 614 | 0xD => new class extends InstructionHandler { 615 | public function disassemble(int $opcode): string { 616 | return sprintf('DRW V%X, V%X, 0x%X', ($opcode & 0x0F00) >> 8, ($opcode & 0x00F0) >> 4, $opcode & 0x000F); 617 | } 618 | 619 | public function handle(CPU $cpu, int $opcode): void { 620 | $x = $cpu->registers[($opcode & 0x0F00) >> 8]; 621 | $y = $cpu->registers[($opcode & 0x00F0) >> 4]; 622 | $height = $opcode & 0x000F; 623 | 624 | $cpu->registers[0xF] = 0; 625 | 626 | for ($yline = 0; $yline < $height; $yline++) { 627 | $pixel = $cpu->memory->blob[$cpu->registerI + $yline]; 628 | for ($xline = 0; $xline < 8; $xline++) { 629 | if (($pixel & (0x80 >> $xline)) !== 0) { 630 | if ($cpu->monitor->getPixel($x + $xline, $y + $yline) === 1) { 631 | $cpu->registers[0xF] = 1; 632 | } 633 | $cpu->monitor->setPixel($x + $xline, $y + $yline, $cpu->monitor->getPixel($x + $xline, $y + $yline) ^ 1); 634 | } 635 | } 636 | } 637 | } 638 | }, 639 | 640 | /** 641 | * Exxx - Key instructions 642 | */ 643 | 0xE => new RegistryInstructionHandler($keyInstructions), 644 | 645 | /** 646 | * Fxxx - Timer instructions 647 | */ 648 | 0xF => new RegistryInstructionHandler($timerInstructions), 649 | ] 650 | ); 651 | } 652 | } -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU AFFERO GENERAL PUBLIC LICENSE 2 | Version 3, 19 November 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU Affero General Public License is a free, copyleft license for 11 | software and other kinds of works, specifically designed to ensure 12 | cooperation with the community in the case of network server software. 13 | 14 | The licenses for most software and other practical works are designed 15 | to take away your freedom to share and change the works. By contrast, 16 | our General Public Licenses are intended to guarantee your freedom to 17 | share and change all versions of a program--to make sure it remains free 18 | software for all its users. 19 | 20 | When we speak of free software, we are referring to freedom, not 21 | price. Our General Public Licenses are designed to make sure that you 22 | have the freedom to distribute copies of free software (and charge for 23 | them if you wish), that you receive source code or can get it if you 24 | want it, that you can change the software or use pieces of it in new 25 | free programs, and that you know you can do these things. 26 | 27 | Developers that use our General Public Licenses protect your rights 28 | with two steps: (1) assert copyright on the software, and (2) offer 29 | you this License which gives you legal permission to copy, distribute 30 | and/or modify the software. 31 | 32 | A secondary benefit of defending all users' freedom is that 33 | improvements made in alternate versions of the program, if they 34 | receive widespread use, become available for other developers to 35 | incorporate. Many developers of free software are heartened and 36 | encouraged by the resulting cooperation. However, in the case of 37 | software used on network servers, this result may fail to come about. 38 | The GNU General Public License permits making a modified version and 39 | letting the public access it on a server without ever releasing its 40 | source code to the public. 41 | 42 | The GNU Affero General Public License is designed specifically to 43 | ensure that, in such cases, the modified source code becomes available 44 | to the community. It requires the operator of a network server to 45 | provide the source code of the modified version running there to the 46 | users of that server. Therefore, public use of a modified version, on 47 | a publicly accessible server, gives the public access to the source 48 | code of the modified version. 49 | 50 | An older license, called the Affero General Public License and 51 | published by Affero, was designed to accomplish similar goals. This is 52 | a different license, not a version of the Affero GPL, but Affero has 53 | released a new version of the Affero GPL which permits relicensing under 54 | this license. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | TERMS AND CONDITIONS 60 | 61 | 0. Definitions. 62 | 63 | "This License" refers to version 3 of the GNU Affero General Public License. 64 | 65 | "Copyright" also means copyright-like laws that apply to other kinds of 66 | works, such as semiconductor masks. 67 | 68 | "The Program" refers to any copyrightable work licensed under this 69 | License. Each licensee is addressed as "you". "Licensees" and 70 | "recipients" may be individuals or organizations. 71 | 72 | To "modify" a work means to copy from or adapt all or part of the work 73 | in a fashion requiring copyright permission, other than the making of an 74 | exact copy. The resulting work is called a "modified version" of the 75 | earlier work or a work "based on" the earlier work. 76 | 77 | A "covered work" means either the unmodified Program or a work based 78 | on the Program. 79 | 80 | To "propagate" a work means to do anything with it that, without 81 | permission, would make you directly or secondarily liable for 82 | infringement under applicable copyright law, except executing it on a 83 | computer or modifying a private copy. Propagation includes copying, 84 | distribution (with or without modification), making available to the 85 | public, and in some countries other activities as well. 86 | 87 | To "convey" a work means any kind of propagation that enables other 88 | parties to make or receive copies. Mere interaction with a user through 89 | a computer network, with no transfer of a copy, is not conveying. 90 | 91 | An interactive user interface displays "Appropriate Legal Notices" 92 | to the extent that it includes a convenient and prominently visible 93 | feature that (1) displays an appropriate copyright notice, and (2) 94 | tells the user that there is no warranty for the work (except to the 95 | extent that warranties are provided), that licensees may convey the 96 | work under this License, and how to view a copy of this License. If 97 | the interface presents a list of user commands or options, such as a 98 | menu, a prominent item in the list meets this criterion. 99 | 100 | 1. Source Code. 101 | 102 | The "source code" for a work means the preferred form of the work 103 | for making modifications to it. "Object code" means any non-source 104 | form of a work. 105 | 106 | A "Standard Interface" means an interface that either is an official 107 | standard defined by a recognized standards body, or, in the case of 108 | interfaces specified for a particular programming language, one that 109 | is widely used among developers working in that language. 110 | 111 | The "System Libraries" of an executable work include anything, other 112 | than the work as a whole, that (a) is included in the normal form of 113 | packaging a Major Component, but which is not part of that Major 114 | Component, and (b) serves only to enable use of the work with that 115 | Major Component, or to implement a Standard Interface for which an 116 | implementation is available to the public in source code form. A 117 | "Major Component", in this context, means a major essential component 118 | (kernel, window system, and so on) of the specific operating system 119 | (if any) on which the executable work runs, or a compiler used to 120 | produce the work, or an object code interpreter used to run it. 121 | 122 | The "Corresponding Source" for a work in object code form means all 123 | the source code needed to generate, install, and (for an executable 124 | work) run the object code and to modify the work, including scripts to 125 | control those activities. However, it does not include the work's 126 | System Libraries, or general-purpose tools or generally available free 127 | programs which are used unmodified in performing those activities but 128 | which are not part of the work. For example, Corresponding Source 129 | includes interface definition files associated with source files for 130 | the work, and the source code for shared libraries and dynamically 131 | linked subprograms that the work is specifically designed to require, 132 | such as by intimate data communication or control flow between those 133 | subprograms and other parts of the work. 134 | 135 | The Corresponding Source need not include anything that users 136 | can regenerate automatically from other parts of the Corresponding 137 | Source. 138 | 139 | The Corresponding Source for a work in source code form is that 140 | same work. 141 | 142 | 2. Basic Permissions. 143 | 144 | All rights granted under this License are granted for the term of 145 | copyright on the Program, and are irrevocable provided the stated 146 | conditions are met. This License explicitly affirms your unlimited 147 | permission to run the unmodified Program. The output from running a 148 | covered work is covered by this License only if the output, given its 149 | content, constitutes a covered work. This License acknowledges your 150 | rights of fair use or other equivalent, as provided by copyright law. 151 | 152 | You may make, run and propagate covered works that you do not 153 | convey, without conditions so long as your license otherwise remains 154 | in force. You may convey covered works to others for the sole purpose 155 | of having them make modifications exclusively for you, or provide you 156 | with facilities for running those works, provided that you comply with 157 | the terms of this License in conveying all material for which you do 158 | not control copyright. Those thus making or running the covered works 159 | for you must do so exclusively on your behalf, under your direction 160 | and control, on terms that prohibit them from making any copies of 161 | your copyrighted material outside their relationship with you. 162 | 163 | Conveying under any other circumstances is permitted solely under 164 | the conditions stated below. Sublicensing is not allowed; section 10 165 | makes it unnecessary. 166 | 167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 168 | 169 | No covered work shall be deemed part of an effective technological 170 | measure under any applicable law fulfilling obligations under article 171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 172 | similar laws prohibiting or restricting circumvention of such 173 | measures. 174 | 175 | When you convey a covered work, you waive any legal power to forbid 176 | circumvention of technological measures to the extent such circumvention 177 | is effected by exercising rights under this License with respect to 178 | the covered work, and you disclaim any intention to limit operation or 179 | modification of the work as a means of enforcing, against the work's 180 | users, your or third parties' legal rights to forbid circumvention of 181 | technological measures. 182 | 183 | 4. Conveying Verbatim Copies. 184 | 185 | You may convey verbatim copies of the Program's source code as you 186 | receive it, in any medium, provided that you conspicuously and 187 | appropriately publish on each copy an appropriate copyright notice; 188 | keep intact all notices stating that this License and any 189 | non-permissive terms added in accord with section 7 apply to the code; 190 | keep intact all notices of the absence of any warranty; and give all 191 | recipients a copy of this License along with the Program. 192 | 193 | You may charge any price or no price for each copy that you convey, 194 | and you may offer support or warranty protection for a fee. 195 | 196 | 5. Conveying Modified Source Versions. 197 | 198 | You may convey a work based on the Program, or the modifications to 199 | produce it from the Program, in the form of source code under the 200 | terms of section 4, provided that you also meet all of these conditions: 201 | 202 | a) The work must carry prominent notices stating that you modified 203 | it, and giving a relevant date. 204 | 205 | b) The work must carry prominent notices stating that it is 206 | released under this License and any conditions added under section 207 | 7. This requirement modifies the requirement in section 4 to 208 | "keep intact all notices". 209 | 210 | c) You must license the entire work, as a whole, under this 211 | License to anyone who comes into possession of a copy. This 212 | License will therefore apply, along with any applicable section 7 213 | additional terms, to the whole of the work, and all its parts, 214 | regardless of how they are packaged. This License gives no 215 | permission to license the work in any other way, but it does not 216 | invalidate such permission if you have separately received it. 217 | 218 | d) If the work has interactive user interfaces, each must display 219 | Appropriate Legal Notices; however, if the Program has interactive 220 | interfaces that do not display Appropriate Legal Notices, your 221 | work need not make them do so. 222 | 223 | A compilation of a covered work with other separate and independent 224 | works, which are not by their nature extensions of the covered work, 225 | and which are not combined with it such as to form a larger program, 226 | in or on a volume of a storage or distribution medium, is called an 227 | "aggregate" if the compilation and its resulting copyright are not 228 | used to limit the access or legal rights of the compilation's users 229 | beyond what the individual works permit. Inclusion of a covered work 230 | in an aggregate does not cause this License to apply to the other 231 | parts of the aggregate. 232 | 233 | 6. Conveying Non-Source Forms. 234 | 235 | You may convey a covered work in object code form under the terms 236 | of sections 4 and 5, provided that you also convey the 237 | machine-readable Corresponding Source under the terms of this License, 238 | in one of these ways: 239 | 240 | a) Convey the object code in, or embodied in, a physical product 241 | (including a physical distribution medium), accompanied by the 242 | Corresponding Source fixed on a durable physical medium 243 | customarily used for software interchange. 244 | 245 | b) Convey the object code in, or embodied in, a physical product 246 | (including a physical distribution medium), accompanied by a 247 | written offer, valid for at least three years and valid for as 248 | long as you offer spare parts or customer support for that product 249 | model, to give anyone who possesses the object code either (1) a 250 | copy of the Corresponding Source for all the software in the 251 | product that is covered by this License, on a durable physical 252 | medium customarily used for software interchange, for a price no 253 | more than your reasonable cost of physically performing this 254 | conveying of source, or (2) access to copy the 255 | Corresponding Source from a network server at no charge. 256 | 257 | c) Convey individual copies of the object code with a copy of the 258 | written offer to provide the Corresponding Source. This 259 | alternative is allowed only occasionally and noncommercially, and 260 | only if you received the object code with such an offer, in accord 261 | with subsection 6b. 262 | 263 | d) Convey the object code by offering access from a designated 264 | place (gratis or for a charge), and offer equivalent access to the 265 | Corresponding Source in the same way through the same place at no 266 | further charge. You need not require recipients to copy the 267 | Corresponding Source along with the object code. If the place to 268 | copy the object code is a network server, the Corresponding Source 269 | may be on a different server (operated by you or a third party) 270 | that supports equivalent copying facilities, provided you maintain 271 | clear directions next to the object code saying where to find the 272 | Corresponding Source. Regardless of what server hosts the 273 | Corresponding Source, you remain obligated to ensure that it is 274 | available for as long as needed to satisfy these requirements. 275 | 276 | e) Convey the object code using peer-to-peer transmission, provided 277 | you inform other peers where the object code and Corresponding 278 | Source of the work are being offered to the general public at no 279 | charge under subsection 6d. 280 | 281 | A separable portion of the object code, whose source code is excluded 282 | from the Corresponding Source as a System Library, need not be 283 | included in conveying the object code work. 284 | 285 | A "User Product" is either (1) a "consumer product", which means any 286 | tangible personal property which is normally used for personal, family, 287 | or household purposes, or (2) anything designed or sold for incorporation 288 | into a dwelling. In determining whether a product is a consumer product, 289 | doubtful cases shall be resolved in favor of coverage. For a particular 290 | product received by a particular user, "normally used" refers to a 291 | typical or common use of that class of product, regardless of the status 292 | of the particular user or of the way in which the particular user 293 | actually uses, or expects or is expected to use, the product. A product 294 | is a consumer product regardless of whether the product has substantial 295 | commercial, industrial or non-consumer uses, unless such uses represent 296 | the only significant mode of use of the product. 297 | 298 | "Installation Information" for a User Product means any methods, 299 | procedures, authorization keys, or other information required to install 300 | and execute modified versions of a covered work in that User Product from 301 | a modified version of its Corresponding Source. The information must 302 | suffice to ensure that the continued functioning of the modified object 303 | code is in no case prevented or interfered with solely because 304 | modification has been made. 305 | 306 | If you convey an object code work under this section in, or with, or 307 | specifically for use in, a User Product, and the conveying occurs as 308 | part of a transaction in which the right of possession and use of the 309 | User Product is transferred to the recipient in perpetuity or for a 310 | fixed term (regardless of how the transaction is characterized), the 311 | Corresponding Source conveyed under this section must be accompanied 312 | by the Installation Information. But this requirement does not apply 313 | if neither you nor any third party retains the ability to install 314 | modified object code on the User Product (for example, the work has 315 | been installed in ROM). 316 | 317 | The requirement to provide Installation Information does not include a 318 | requirement to continue to provide support service, warranty, or updates 319 | for a work that has been modified or installed by the recipient, or for 320 | the User Product in which it has been modified or installed. Access to a 321 | network may be denied when the modification itself materially and 322 | adversely affects the operation of the network or violates the rules and 323 | protocols for communication across the network. 324 | 325 | Corresponding Source conveyed, and Installation Information provided, 326 | in accord with this section must be in a format that is publicly 327 | documented (and with an implementation available to the public in 328 | source code form), and must require no special password or key for 329 | unpacking, reading or copying. 330 | 331 | 7. Additional Terms. 332 | 333 | "Additional permissions" are terms that supplement the terms of this 334 | License by making exceptions from one or more of its conditions. 335 | Additional permissions that are applicable to the entire Program shall 336 | be treated as though they were included in this License, to the extent 337 | that they are valid under applicable law. If additional permissions 338 | apply only to part of the Program, that part may be used separately 339 | under those permissions, but the entire Program remains governed by 340 | this License without regard to the additional permissions. 341 | 342 | When you convey a copy of a covered work, you may at your option 343 | remove any additional permissions from that copy, or from any part of 344 | it. (Additional permissions may be written to require their own 345 | removal in certain cases when you modify the work.) You may place 346 | additional permissions on material, added by you to a covered work, 347 | for which you have or can give appropriate copyright permission. 348 | 349 | Notwithstanding any other provision of this License, for material you 350 | add to a covered work, you may (if authorized by the copyright holders of 351 | that material) supplement the terms of this License with terms: 352 | 353 | a) Disclaiming warranty or limiting liability differently from the 354 | terms of sections 15 and 16 of this License; or 355 | 356 | b) Requiring preservation of specified reasonable legal notices or 357 | author attributions in that material or in the Appropriate Legal 358 | Notices displayed by works containing it; or 359 | 360 | c) Prohibiting misrepresentation of the origin of that material, or 361 | requiring that modified versions of such material be marked in 362 | reasonable ways as different from the original version; or 363 | 364 | d) Limiting the use for publicity purposes of names of licensors or 365 | authors of the material; or 366 | 367 | e) Declining to grant rights under trademark law for use of some 368 | trade names, trademarks, or service marks; or 369 | 370 | f) Requiring indemnification of licensors and authors of that 371 | material by anyone who conveys the material (or modified versions of 372 | it) with contractual assumptions of liability to the recipient, for 373 | any liability that these contractual assumptions directly impose on 374 | those licensors and authors. 375 | 376 | All other non-permissive additional terms are considered "further 377 | restrictions" within the meaning of section 10. If the Program as you 378 | received it, or any part of it, contains a notice stating that it is 379 | governed by this License along with a term that is a further 380 | restriction, you may remove that term. If a license document contains 381 | a further restriction but permits relicensing or conveying under this 382 | License, you may add to a covered work material governed by the terms 383 | of that license document, provided that the further restriction does 384 | not survive such relicensing or conveying. 385 | 386 | If you add terms to a covered work in accord with this section, you 387 | must place, in the relevant source files, a statement of the 388 | additional terms that apply to those files, or a notice indicating 389 | where to find the applicable terms. 390 | 391 | Additional terms, permissive or non-permissive, may be stated in the 392 | form of a separately written license, or stated as exceptions; 393 | the above requirements apply either way. 394 | 395 | 8. Termination. 396 | 397 | You may not propagate or modify a covered work except as expressly 398 | provided under this License. Any attempt otherwise to propagate or 399 | modify it is void, and will automatically terminate your rights under 400 | this License (including any patent licenses granted under the third 401 | paragraph of section 11). 402 | 403 | However, if you cease all violation of this License, then your 404 | license from a particular copyright holder is reinstated (a) 405 | provisionally, unless and until the copyright holder explicitly and 406 | finally terminates your license, and (b) permanently, if the copyright 407 | holder fails to notify you of the violation by some reasonable means 408 | prior to 60 days after the cessation. 409 | 410 | Moreover, your license from a particular copyright holder is 411 | reinstated permanently if the copyright holder notifies you of the 412 | violation by some reasonable means, this is the first time you have 413 | received notice of violation of this License (for any work) from that 414 | copyright holder, and you cure the violation prior to 30 days after 415 | your receipt of the notice. 416 | 417 | Termination of your rights under this section does not terminate the 418 | licenses of parties who have received copies or rights from you under 419 | this License. If your rights have been terminated and not permanently 420 | reinstated, you do not qualify to receive new licenses for the same 421 | material under section 10. 422 | 423 | 9. Acceptance Not Required for Having Copies. 424 | 425 | You are not required to accept this License in order to receive or 426 | run a copy of the Program. Ancillary propagation of a covered work 427 | occurring solely as a consequence of using peer-to-peer transmission 428 | to receive a copy likewise does not require acceptance. However, 429 | nothing other than this License grants you permission to propagate or 430 | modify any covered work. These actions infringe copyright if you do 431 | not accept this License. Therefore, by modifying or propagating a 432 | covered work, you indicate your acceptance of this License to do so. 433 | 434 | 10. Automatic Licensing of Downstream Recipients. 435 | 436 | Each time you convey a covered work, the recipient automatically 437 | receives a license from the original licensors, to run, modify and 438 | propagate that work, subject to this License. You are not responsible 439 | for enforcing compliance by third parties with this License. 440 | 441 | An "entity transaction" is a transaction transferring control of an 442 | organization, or substantially all assets of one, or subdividing an 443 | organization, or merging organizations. If propagation of a covered 444 | work results from an entity transaction, each party to that 445 | transaction who receives a copy of the work also receives whatever 446 | licenses to the work the party's predecessor in interest had or could 447 | give under the previous paragraph, plus a right to possession of the 448 | Corresponding Source of the work from the predecessor in interest, if 449 | the predecessor has it or can get it with reasonable efforts. 450 | 451 | You may not impose any further restrictions on the exercise of the 452 | rights granted or affirmed under this License. For example, you may 453 | not impose a license fee, royalty, or other charge for exercise of 454 | rights granted under this License, and you may not initiate litigation 455 | (including a cross-claim or counterclaim in a lawsuit) alleging that 456 | any patent claim is infringed by making, using, selling, offering for 457 | sale, or importing the Program or any portion of it. 458 | 459 | 11. Patents. 460 | 461 | A "contributor" is a copyright holder who authorizes use under this 462 | License of the Program or a work on which the Program is based. The 463 | work thus licensed is called the contributor's "contributor version". 464 | 465 | A contributor's "essential patent claims" are all patent claims 466 | owned or controlled by the contributor, whether already acquired or 467 | hereafter acquired, that would be infringed by some manner, permitted 468 | by this License, of making, using, or selling its contributor version, 469 | but do not include claims that would be infringed only as a 470 | consequence of further modification of the contributor version. For 471 | purposes of this definition, "control" includes the right to grant 472 | patent sublicenses in a manner consistent with the requirements of 473 | this License. 474 | 475 | Each contributor grants you a non-exclusive, worldwide, royalty-free 476 | patent license under the contributor's essential patent claims, to 477 | make, use, sell, offer for sale, import and otherwise run, modify and 478 | propagate the contents of its contributor version. 479 | 480 | In the following three paragraphs, a "patent license" is any express 481 | agreement or commitment, however denominated, not to enforce a patent 482 | (such as an express permission to practice a patent or covenant not to 483 | sue for patent infringement). To "grant" such a patent license to a 484 | party means to make such an agreement or commitment not to enforce a 485 | patent against the party. 486 | 487 | If you convey a covered work, knowingly relying on a patent license, 488 | and the Corresponding Source of the work is not available for anyone 489 | to copy, free of charge and under the terms of this License, through a 490 | publicly available network server or other readily accessible means, 491 | then you must either (1) cause the Corresponding Source to be so 492 | available, or (2) arrange to deprive yourself of the benefit of the 493 | patent license for this particular work, or (3) arrange, in a manner 494 | consistent with the requirements of this License, to extend the patent 495 | license to downstream recipients. "Knowingly relying" means you have 496 | actual knowledge that, but for the patent license, your conveying the 497 | covered work in a country, or your recipient's use of the covered work 498 | in a country, would infringe one or more identifiable patents in that 499 | country that you have reason to believe are valid. 500 | 501 | If, pursuant to or in connection with a single transaction or 502 | arrangement, you convey, or propagate by procuring conveyance of, a 503 | covered work, and grant a patent license to some of the parties 504 | receiving the covered work authorizing them to use, propagate, modify 505 | or convey a specific copy of the covered work, then the patent license 506 | you grant is automatically extended to all recipients of the covered 507 | work and works based on it. 508 | 509 | A patent license is "discriminatory" if it does not include within 510 | the scope of its coverage, prohibits the exercise of, or is 511 | conditioned on the non-exercise of one or more of the rights that are 512 | specifically granted under this License. You may not convey a covered 513 | work if you are a party to an arrangement with a third party that is 514 | in the business of distributing software, under which you make payment 515 | to the third party based on the extent of your activity of conveying 516 | the work, and under which the third party grants, to any of the 517 | parties who would receive the covered work from you, a discriminatory 518 | patent license (a) in connection with copies of the covered work 519 | conveyed by you (or copies made from those copies), or (b) primarily 520 | for and in connection with specific products or compilations that 521 | contain the covered work, unless you entered into that arrangement, 522 | or that patent license was granted, prior to 28 March 2007. 523 | 524 | Nothing in this License shall be construed as excluding or limiting 525 | any implied license or other defenses to infringement that may 526 | otherwise be available to you under applicable patent law. 527 | 528 | 12. No Surrender of Others' Freedom. 529 | 530 | If conditions are imposed on you (whether by court order, agreement or 531 | otherwise) that contradict the conditions of this License, they do not 532 | excuse you from the conditions of this License. If you cannot convey a 533 | covered work so as to satisfy simultaneously your obligations under this 534 | License and any other pertinent obligations, then as a consequence you may 535 | not convey it at all. For example, if you agree to terms that obligate you 536 | to collect a royalty for further conveying from those to whom you convey 537 | the Program, the only way you could satisfy both those terms and this 538 | License would be to refrain entirely from conveying the Program. 539 | 540 | 13. Remote Network Interaction; Use with the GNU General Public License. 541 | 542 | Notwithstanding any other provision of this License, if you modify the 543 | Program, your modified version must prominently offer all users 544 | interacting with it remotely through a computer network (if your version 545 | supports such interaction) an opportunity to receive the Corresponding 546 | Source of your version by providing access to the Corresponding Source 547 | from a network server at no charge, through some standard or customary 548 | means of facilitating copying of software. This Corresponding Source 549 | shall include the Corresponding Source for any work covered by version 3 550 | of the GNU General Public License that is incorporated pursuant to the 551 | following paragraph. 552 | 553 | Notwithstanding any other provision of this License, you have 554 | permission to link or combine any covered work with a work licensed 555 | under version 3 of the GNU General Public License into a single 556 | combined work, and to convey the resulting work. The terms of this 557 | License will continue to apply to the part which is the covered work, 558 | but the work with which it is combined will remain governed by version 559 | 3 of the GNU General Public License. 560 | 561 | 14. Revised Versions of this License. 562 | 563 | The Free Software Foundation may publish revised and/or new versions of 564 | the GNU Affero General Public License from time to time. Such new versions 565 | will be similar in spirit to the present version, but may differ in detail to 566 | address new problems or concerns. 567 | 568 | Each version is given a distinguishing version number. If the 569 | Program specifies that a certain numbered version of the GNU Affero General 570 | Public License "or any later version" applies to it, you have the 571 | option of following the terms and conditions either of that numbered 572 | version or of any later version published by the Free Software 573 | Foundation. If the Program does not specify a version number of the 574 | GNU Affero General Public License, you may choose any version ever published 575 | by the Free Software Foundation. 576 | 577 | If the Program specifies that a proxy can decide which future 578 | versions of the GNU Affero General Public License can be used, that proxy's 579 | public statement of acceptance of a version permanently authorizes you 580 | to choose that version for the Program. 581 | 582 | Later license versions may give you additional or different 583 | permissions. However, no additional obligations are imposed on any 584 | author or copyright holder as a result of your choosing to follow a 585 | later version. 586 | 587 | 15. Disclaimer of Warranty. 588 | 589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 597 | 598 | 16. Limitation of Liability. 599 | 600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 608 | SUCH DAMAGES. 609 | 610 | 17. Interpretation of Sections 15 and 16. 611 | 612 | If the disclaimer of warranty and limitation of liability provided 613 | above cannot be given local legal effect according to their terms, 614 | reviewing courts shall apply local law that most closely approximates 615 | an absolute waiver of all civil liability in connection with the 616 | Program, unless a warranty or assumption of liability accompanies a 617 | copy of the Program in return for a fee. 618 | 619 | END OF TERMS AND CONDITIONS 620 | 621 | How to Apply These Terms to Your New Programs 622 | 623 | If you develop a new program, and you want it to be of the greatest 624 | possible use to the public, the best way to achieve this is to make it 625 | free software which everyone can redistribute and change under these terms. 626 | 627 | To do so, attach the following notices to the program. It is safest 628 | to attach them to the start of each source file to most effectively 629 | state the exclusion of warranty; and each file should have at least 630 | the "copyright" line and a pointer to where the full notice is found. 631 | 632 | 633 | Copyright (C) 634 | 635 | This program is free software: you can redistribute it and/or modify 636 | it under the terms of the GNU Affero General Public License as published 637 | by the Free Software Foundation, either version 3 of the License, or 638 | (at your option) any later version. 639 | 640 | This program is distributed in the hope that it will be useful, 641 | but WITHOUT ANY WARRANTY; without even the implied warranty of 642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 643 | GNU Affero General Public License for more details. 644 | 645 | You should have received a copy of the GNU Affero General Public License 646 | along with this program. If not, see . 647 | 648 | Also add information on how to contact you by electronic and paper mail. 649 | 650 | If your software can interact with users remotely through a computer 651 | network, you should also make sure that it provides a way for users to 652 | get its source. For example, if your program is a web application, its 653 | interface could display a "Source" link that leads users to an archive 654 | of the code. There are many ways you could offer source, and different 655 | solutions will be better for different programs; see section 13 for the 656 | specific requirements. 657 | 658 | You should also get your employer (if you work as a programmer) or school, 659 | if any, to sign a "copyright disclaimer" for the program, if necessary. 660 | For more information on this, and how to apply and follow the GNU AGPL, see 661 | . -------------------------------------------------------------------------------- /src/Renderer/GuiRenderer.php: -------------------------------------------------------------------------------- 1 | bodyColorLight = new VGColor(0.776, 0.639, 0.541, 1.0); 52 | $this->bodyColorDark = new VGColor(0.565, 0.451, 0.369, 1.0); 53 | $this->panelColor = new VGColor(0.675, 0.549, 0.459, 1.0); 54 | 55 | $this->displayColorStart = new VGColor(0.016, 0.286, 0.271, 1.0); 56 | $this->displayColorEnd = new VGColor(0.027, 0.384, 0.353, 1.0); 57 | $this->displayColorBorderer = new VGColor(0.027, 0.173, 0.161, 1.0); 58 | $this->displayColorText = new VGColor(0.576, 1.0, 0.706, 1.0); 59 | 60 | $this->valuePanelColorStart = new VGColor(0.31, 0.31, 0.31, 1.0); 61 | $this->valuePanelColorEnd = new VGColor(0.314, 0.29, 0.259, 1.0); 62 | } 63 | 64 | /** 65 | * Creates a gradient paint that goes vertically from light to dark 66 | */ 67 | public function createBodyGradient($ystart, $yend) : VGPaint 68 | { 69 | return $this->vg->linearGradient(0, $ystart, 0, $yend, $this->bodyColorLight, $this->bodyColorDark); 70 | } 71 | 72 | public function renderBodyPanel(Vec2 $pos, Vec2 $size, bool $invert = false, float $radius = 10.0, bool $autofill = true) 73 | { 74 | $this->vg->beginPath(); 75 | 76 | if ($invert) { 77 | $paint = $this->createBodyGradient($pos->y + $size->y, $pos->y); 78 | } else { 79 | $paint = $this->createBodyGradient($pos->y, $pos->y + $size->y); 80 | } 81 | 82 | $this->vg->fillPaint($paint); 83 | $this->vg->roundedRect($pos->x, $pos->y, $size->x, $size->y, $radius); 84 | 85 | if ($autofill) { 86 | $this->vg->fill(); 87 | } 88 | } 89 | 90 | public function renderGUI(CPU $cpu) 91 | { 92 | // No GUI in fullscreen mode 93 | if ($this->renderState->fullscreenMonitor) { 94 | return; 95 | } 96 | 97 | $underMonitor = $this->renderMonitorFrame($cpu); 98 | $this->renderKeyboard($underMonitor, $cpu); 99 | $nextPanel = $this->renderStatePanel($underMonitor->x - $this->panelPadding, $cpu); 100 | $this->renderDissaemblyPanel($nextPanel, $underMonitor->x - $this->panelPadding, $cpu); 101 | } 102 | 103 | /** 104 | * @return Vec2 The xy position of the monitor bottom left corner 105 | */ 106 | public function renderMonitorFrame(CPU $cpu) : Vec2 107 | { 108 | $this->vg->beginPath(); 109 | 110 | $pos = $this->renderState->getMonitorPosition(); 111 | $size = $this->renderState->getMonitorSize(); 112 | 113 | $framePos = $pos - new Vec2($this->monitorFrameWidth, $this->monitorFrameWidth); 114 | $frameSize = $size + new Vec2($this->monitorFrameWidth * 2, $this->monitorFrameWidth * 2); 115 | 116 | // make the outer panel bigger to show a front panel 117 | $frameSize->y = $frameSize->y + $this->monitorFrameFrontPanel; 118 | 119 | $framePosInner = $pos - new Vec2($this->monitorFrameWidth * 0.5, $this->monitorFrameWidth * 0.5); 120 | $frameSizeInner = $size + new Vec2($this->monitorFrameWidth, $this->monitorFrameWidth); 121 | 122 | $this->renderBodyPanel($framePos, $frameSize, false, $this->monitorRadius, false); 123 | 124 | // render a hole into the monitor where the render display data is 125 | $this->vg->roundedRect($pos->x, $pos->y, $size->x, $size->y, 10); 126 | $this->vg->pathWinding(VGContext::CW); 127 | $this->vg->fill(); 128 | 129 | // and the inner one 130 | $this->vg->pathWinding(VGContext::CCW); 131 | $this->renderBodyPanel($framePosInner, $frameSizeInner, true, $this->monitorRadius, false); 132 | $this->vg->roundedRect($pos->x, $pos->y, $size->x, $size->y, 10); 133 | $this->vg->pathWinding(VGContext::CW); 134 | $this->vg->fill(); 135 | 136 | 137 | // render front panel text 138 | $this->vg->fontFace('vt323'); 139 | $this->vg->fontSize(32); 140 | $this->vg->textAlign(VGAlign::CENTER | VGAlign::MIDDLE); 141 | 142 | $frontPanelVBB = new Vec2( 143 | $pos->y + $size->y + $this->monitorFrameWidth * 0.5, 144 | $pos->y + $size->y + $this->monitorFrameWidth + $this->monitorFrameFrontPanel 145 | ); 146 | 147 | $textY = $frontPanelVBB->x + ($frontPanelVBB->y - $frontPanelVBB->x) * 0.5; 148 | 149 | // now a white shadow for the emboss effect 150 | $this->vg->fontBlur(2); 151 | $this->vg->fillColor(new VGColor(1.0, 1.0, 1.0, 0.7)); 152 | $this->vg->text($pos->x + $size->x * 0.5, $textY + 1, 'PHP CHIP-8'); 153 | 154 | // render the label shadow 155 | $this->vg->fontBlur(2); 156 | $this->vg->fillColor(VGColor::black()); 157 | $this->vg->text($pos->x + $size->x * 0.5, $textY - 1, 'PHP CHIP-8'); 158 | 159 | // render the actual label 160 | $this->vg->fontBlur(0); 161 | $this->vg->fillColor(VGColor::white()); 162 | $this->vg->text($pos->x + $size->x * 0.5, $textY, 'PHP CHIP-8'); 163 | 164 | 165 | // render a power LED on the right when the CPU is running 166 | $ledPos = $pos; 167 | $ledPos->y = $frontPanelVBB->x + $this->monitorFrameFrontPanel * 0.5 + 5; 168 | 169 | $this->vg->beginPath(); 170 | $this->vg->circle($ledPos->x, $ledPos->y, 5.0); 171 | $this->vg->strokeColor(VGColor::black()); 172 | $this->vg->fillColor(!$this->renderState->cpuIsRunning ? new VGColor(0.8, 0.2, 0.2, 1.0) : new VGColor(0.2, 0.8, 0.2, 1.0)); 173 | $this->vg->strokeWidth(2); 174 | $this->vg->fill(); 175 | $this->vg->stroke(); 176 | 177 | // render a fullscreen button on the right 178 | if ($this->renderRoundButton( 179 | new Vec2($pos->x + $size->x - 20, $pos->y), 180 | 20, 181 | $this->renderState->fullscreenMonitor ? '@@fullscreen' : '@@fullscreen', 182 | false, 183 | false, 184 | 'icons', 185 | 20 186 | )) { 187 | $this->renderState->fullscreenMonitor = !$this->renderState->fullscreenMonitor; 188 | } 189 | 190 | return new Vec2($framePos->x, $frontPanelVBB->y); 191 | } 192 | 193 | public function getIndetGradient($ystart, $yend) : VGPaint 194 | { 195 | return $this->vg->linearGradient(0, $ystart, 0, $yend, new VGColor(0.0, 0.0, 0.0, 0.4), new VGColor(1.0, 1.0, 1.0, 0.2)); 196 | } 197 | 198 | /** 199 | * @param bool $continues If true the button will return true as long as the mouse is pressed 200 | * @return bool 201 | */ 202 | public function renderRoundButton( 203 | Vec2 $pos, 204 | float $radius, 205 | string $text, 206 | bool $isActive = false, 207 | bool $continues = false, 208 | string $font = 'bebas', 209 | int $fontSize = 32 210 | ) : bool 211 | { 212 | $mousePos = $this->input->getCursorPosition(); 213 | $isHovering = $mousePos->distanceTo($pos) < $radius; 214 | $didPress = $this->input->hasMouseButtonBeenPressedThisFrame(MouseButton::LEFT); 215 | $isPressed = $this->input->isMouseButtonPressed(MouseButton::LEFT); 216 | 217 | $id = $text; 218 | // if the text contains a @@ we use the second part as the id 219 | if (strpos($text, '@@') !== false) { 220 | $parts = explode('@@', $text); 221 | $id = $parts[1]; 222 | $text = $parts[0]; 223 | } 224 | 225 | $buttonId = ((string) $pos->x . (string) $pos->y) . $id; 226 | 227 | // render a the indent for the button 228 | $this->vg->beginPath(); 229 | $this->vg->circle($pos->x, $pos->y, $radius); 230 | $this->vg->fillPaint($this->getIndetGradient($pos->y - $radius, $pos->y + $radius)); 231 | $this->vg->fill(); 232 | 233 | // now a dark circle to akt as a spacer 234 | $this->vg->beginPath(); 235 | $this->vg->circle($pos->x, $pos->y, $radius * 0.9); 236 | $this->vg->fillColor(VGColor::black()); 237 | if (($isHovering && ($isPressed || $didPress)) || $isActive) { 238 | $this->lastButtonPress[$buttonId] = glfwGetTime(); 239 | } 240 | $this->vg->fill(); 241 | 242 | // we fade out the highlight after a while 243 | $hoveringTime = 2.0; 244 | if (isset($this->lastButtonPress[$buttonId]) && glfwGetTime() - $this->lastButtonPress[$buttonId] < $hoveringTime) { 245 | 246 | $fadeDelta = $this->lastButtonPress[$buttonId] - glfwGetTime() + $hoveringTime; 247 | $fadeDelta /= $hoveringTime; 248 | 249 | $this->vg->beginPath(); 250 | $this->vg->circle($pos->x, $pos->y, $radius * 0.9); 251 | $this->vg->fillColor(new VGColor(0.973, 0.875, 0.012, $fadeDelta)); 252 | $this->vg->fill(); 253 | } 254 | 255 | // btn colors 256 | $buttonInnerA = new VGColor(0.263, 0.149, 0.027, 1.0); 257 | $buttonInnerB = new VGColor(0.396, 0.22, 0.02, 1.0); 258 | $buttonOuterA = new VGColor(0.655, 0.369, 0.063, 1.0); 259 | $buttonOuterB = new VGColor(0.263, 0.149, 0.027, 1.0); 260 | 261 | if ($isHovering) { 262 | $buttonInnerA = $buttonInnerA->darken(0.3); 263 | } 264 | 265 | // render the button 266 | $innerGradient = $this->vg->linearGradient(0, $pos->y - $radius, 0, $pos->y + $radius, $buttonInnerA, $buttonInnerB); 267 | $outerGradient = $this->vg->linearGradient(0, $pos->y - $radius, 0, $pos->y + $radius, $buttonOuterA, $buttonOuterB); 268 | 269 | $this->vg->beginPath(); 270 | $this->vg->circle($pos->x, $pos->y, $radius * 0.8); 271 | $this->vg->fillPaint($innerGradient); 272 | $this->vg->strokePaint($outerGradient); 273 | $this->vg->fill(); 274 | $this->vg->strokeWidth(2); 275 | $this->vg->stroke(); 276 | 277 | $this->vg->fontFace($font); 278 | $this->vg->fontSize($fontSize); 279 | $this->vg->textAlign(VGAlign::CENTER | VGAlign::MIDDLE); 280 | $this->vg->fillColor(VGColor::white()); 281 | 282 | // handle font specific offests 283 | if ($font === 'bebas') { 284 | $pos = $pos + new Vec2(0, 3); 285 | } 286 | elseif ($font === 'icons') { 287 | $pos = $pos + new Vec2(0, 0); 288 | } 289 | 290 | $this->vg->text($pos->x, $pos->y, $text); 291 | 292 | if (!$isHovering) return false; 293 | 294 | if ($continues) { 295 | return $isPressed; 296 | } 297 | return $didPress; 298 | } 299 | 300 | public function renderSelectorSwitch(Vec2 $pos, Vec2 $size, &$value, array $labels) 301 | { 302 | $selectorId = 'sel'.((string) $pos->x . (string) $pos->y); 303 | 304 | $r = $size->y * 0.5; 305 | 306 | $this->vg->beginPath(); 307 | $this->vg->fillColor(new VGColor(0, 0, 0, 0.3)); 308 | $this->vg->roundedRect($pos->x, $pos->y, $size->x, $size->y, $r); 309 | 310 | $gradient = $this->getIndetGradient($pos->y, $pos->y + $size->y); 311 | $this->vg->strokePaint($gradient); 312 | $this->vg->fill(); 313 | $this->vg->strokeWidth(2); 314 | $this->vg->stroke(); 315 | 316 | // get the center points 317 | $settings = count($labels); 318 | 319 | $w = ($size->x - $r * 2); 320 | $spacing = $w / ($settings - 1); 321 | 322 | $centerPoints = []; 323 | for ($i = 0; $i < $settings; $i++) { 324 | $centerPoints[] = $pos->x + $r + $spacing * $i; 325 | } 326 | 327 | 328 | // render a line from first to last 329 | $innerGuideColor = new VGColor(0.2, 0.2, 0.2, 1.0); 330 | $this->vg->beginPath(); 331 | $this->vg->moveTo($pos->x + $r, $pos->y + $size->y * 0.5); 332 | $this->vg->lineTo($pos->x + $size->x - $r, $pos->y + $size->y * 0.5); 333 | $this->vg->strokeColor($innerGuideColor); 334 | $this->vg->strokeWidth(5); 335 | $this->vg->stroke(); 336 | 337 | // render a circle for each setting 338 | $this->vg->fillColor($innerGuideColor); 339 | for ($i = 0; $i < $settings; $i++) { 340 | $p = $centerPoints[$i]; 341 | $this->vg->beginPath(); 342 | $this->vg->circle($p, $pos->y + $size->y * 0.5, $r * 0.25); 343 | $this->vg->fill(); 344 | 345 | // handle selection 346 | if ($this->input->hasMouseButtonBeenPressedThisFrame(MouseButton::LEFT)) { 347 | if ($this->input->getCursorPosition()->distanceTo(new Vec2($p, $pos->y + $size->y * 0.5)) < $r) { 348 | $value = array_keys($labels)[$i]; 349 | } 350 | } 351 | } 352 | 353 | // render a label on top 354 | $this->vg->fontFace('bebas'); 355 | $this->vg->fontSize(16); 356 | $this->vg->textAlign(VGAlign::CENTER | VGAlign::MIDDLE); 357 | 358 | foreach ($labels as $label) { 359 | $i = array_search($label, $labels); 360 | $p = $centerPoints[$i]; 361 | 362 | // white if its the current value 363 | $this->vg->fillColor($value === $i ? VGColor::white() : VGColor::white()->darken(0.15)); 364 | $this->vg->text($p, $pos->y - 20, $label); 365 | } 366 | 367 | // render a knob for the current value 368 | $knobAtIndex = array_search($value, array_keys($labels)); 369 | $knobPos = $centerPoints[$knobAtIndex]; 370 | 371 | if (!isset($this->knobStaticPos[$selectorId])) { 372 | $this->knobStaticPos[$selectorId] = $knobPos; 373 | } 374 | 375 | // move the knob closer to the target 376 | $this->knobStaticPos[$selectorId] = $this->knobStaticPos[$selectorId] + ($knobPos - $this->knobStaticPos[$selectorId]) * 0.1; 377 | $realKnobPos = $this->knobStaticPos[$selectorId]; 378 | 379 | // knob color 380 | $knobColorOuterStart = new VGColor(0.918, 0.933, 0.937, 1.0); 381 | $knobColorOuterEnd = new VGColor(0.459, 0.475, 0.478, 1.0); 382 | $knobColorInnerStart = new VGColor(0.514, 0.553, 0.549, 1.0); 383 | $knobColorInnerEnd = new VGColor(0.71, 0.725, 0.729, 1.0); 384 | 385 | $this->vg->beginPath(); 386 | $this->vg->circle($realKnobPos, $pos->y + $size->y * 0.5, $r * 0.6); 387 | $knobFillPaint = $this->vg->linearGradient($realKnobPos - $r, $pos->y, $realKnobPos + $r, $pos->y + $size->y, $knobColorInnerStart, $knobColorInnerEnd); 388 | $this->vg->fillPaint($knobFillPaint); 389 | $this->vg->fill(); 390 | 391 | $knobStrokePaint = $this->vg->linearGradient($realKnobPos - $r, $pos->y, $realKnobPos + $r, $pos->y + $size->y, $knobColorOuterStart, $knobColorOuterEnd); 392 | $this->vg->strokePaint($knobStrokePaint); 393 | $this->vg->strokeWidth(8); 394 | $this->vg->stroke(); 395 | } 396 | 397 | public function renderKeyboard(Vec2 $startPos, CPU $cpu) 398 | { 399 | $startPos->y = $startPos->y + $this->panelPadding; 400 | 401 | $panelSize = new Vec2( 402 | $this->renderState->viewport->width - $startPos->x - $this->panelPadding, 403 | $this->renderState->viewport->height - $startPos->y - $this->panelPadding 404 | ); 405 | 406 | $this->renderBodyPanel($startPos, $panelSize, false, $this->panelRadius); 407 | 408 | $innerPos = $startPos + new Vec2($this->panelBorderWidth, $this->panelBorderWidth); 409 | $innerSize = $panelSize - new Vec2($this->panelBorderWidth * 2, $this->panelBorderWidth * 2); 410 | 411 | // render the panel inside 412 | $this->vg->beginPath(); 413 | $this->vg->fillColor($this->panelColor); 414 | $this->vg->roundedRect($innerPos->x, $innerPos->y, $innerSize->x, $innerSize->y, $this->panelRadius * 0.8); 415 | $this->vg->fill(); 416 | 417 | // render the keyboard buttons 418 | $buttons = [ 419 | ['1', '2', '3', 'C'], 420 | ['4', '5', '6', 'D'], 421 | ['7', '8', '9', 'E'], 422 | ['A', '0', 'B', 'F'], 423 | ]; 424 | 425 | $buttonHalfSpace = ($innerSize->y / 4) * 0.5; 426 | $buttonHalfSpace = min($buttonHalfSpace, ($innerSize->x * 0.4 / 4) * 0.5); 427 | $buttonHalfSpace = max($buttonHalfSpace, 20); 428 | $cpu->wantKeyboardUpdates = true; 429 | 430 | for ($y = 0; $y < 4; $y++) { 431 | for ($x = 0; $x < 4; $x++) { 432 | $buttonX = $innerPos->x + $x * $buttonHalfSpace * 2 + $buttonHalfSpace; 433 | $buttonY = $innerPos->y + $y * $buttonHalfSpace * 2 + $buttonHalfSpace; 434 | 435 | // convert the hex string to a number 436 | $n = hexdec($buttons[$y][$x]); 437 | 438 | $isDown = $this->renderRoundButton( 439 | new Vec2($buttonX, $buttonY), 440 | $buttonHalfSpace * 0.85, 441 | $buttons[$y][$x], 442 | $cpu->keyPressStates[$n] > 0, 443 | true 444 | ); 445 | 446 | // stop keyboard updates if the button is pressed 447 | if ($isDown) { 448 | $cpu->wantKeyboardUpdates = false; 449 | } 450 | 451 | $cpu->keyPressStates[$n] = $isDown ? 1 : 0; 452 | } 453 | } 454 | 455 | $rightSidePos = $innerPos + new Vec2($innerSize->x * 0.5, 0); 456 | $rightSideSize = $innerSize * new Vec2(0.5, 1); 457 | 458 | // split right side height into N panels 459 | $rightSideSubElCount = 3; 460 | $rightSideItemSize = $rightSideSize->y / $rightSideSubElCount; 461 | 462 | // we need the middle point of each 463 | $vstackPositions = []; 464 | for($i = 0; $i < $rightSideSubElCount; $i++) { 465 | $vstackPositions[] = $rightSideItemSize * $i + $rightSideItemSize * 0.5; 466 | } 467 | 468 | $labelVOff = 17; 469 | 470 | // render a persitance of vision selector switch 471 | $labelPos = $rightSidePos + new Vec2(20, $vstackPositions[0] + $labelVOff); 472 | $this->vg->fontFace('bebas'); 473 | $this->vg->fontSize(16); 474 | $this->vg->textAlign(VGAlign::RIGHT | VGAlign::MIDDLE); 475 | $this->vg->fillColor(VGColor::white()); 476 | $this->vg->text($labelPos->x, $labelPos->y, 'Ghosting'); 477 | 478 | $currentGhostingValue = $this->renderState->ghostingEffectLevel->value; 479 | $this->renderSelectorSwitch($rightSidePos + new Vec2(20 + 20, $vstackPositions[0]), new Vec2($rightSideSize->x - 60, 35), $currentGhostingValue, [ 480 | GhostingEffectLevel::None->value => 'None', 481 | GhostingEffectLevel::Low->value => 'Low', 482 | GhostingEffectLevel::Medium->value => 'Medium', 483 | GhostingEffectLevel::High->value => 'High', 484 | ]); 485 | 486 | $this->renderState->ghostingEffectLevel = GhostingEffectLevel::from($currentGhostingValue); 487 | 488 | // crt effect toggle 489 | $labelPos = $rightSidePos + new Vec2(20, $vstackPositions[1] + $labelVOff); 490 | $this->vg->fontFace('bebas'); 491 | $this->vg->fontSize(16); 492 | $this->vg->textAlign(VGAlign::RIGHT | VGAlign::MIDDLE); 493 | $this->vg->fillColor(VGColor::white()); 494 | $this->vg->text($labelPos->x, $labelPos->y, 'CRT Effect'); 495 | 496 | $this->renderSelectorSwitch($rightSidePos + new Vec2(20 + 20, $vstackPositions[1]), new Vec2($rightSideSize->x - 60, 35), $this->renderState->crtEffectEnabled, [ 497 | false => 'Off', 498 | true => 'On', 499 | ]); 500 | 501 | // monochrome effect toggle 502 | $labelPos = $rightSidePos + new Vec2(20, $vstackPositions[2] + $labelVOff); 503 | $this->vg->fontFace('bebas'); 504 | $this->vg->fontSize(16); 505 | $this->vg->textAlign(VGAlign::RIGHT | VGAlign::MIDDLE); 506 | $this->vg->fillColor(VGColor::white()); 507 | $this->vg->text($labelPos->x, $labelPos->y, 'Monochrome'); 508 | 509 | $this->renderSelectorSwitch($rightSidePos + new Vec2(20 + 20, $vstackPositions[2]), new Vec2($rightSideSize->x - 60, 35), $this->renderState->monochrome, [ 510 | false => 'Off', 511 | true => 'On', 512 | ]); 513 | 514 | 515 | // if ($this->renderState->fullscreenMonitor) { 516 | // if ($this->renderRoundButton($innerPos + new Vec2(30, 30), 30, "@@pause", false, false, 'icons', '20')) { 517 | // $this->dispatcher->dispatch('cpu.pause', new Signal); 518 | // } 519 | // } else { 520 | // if ($this->renderRoundButton($innerPos + new Vec2(30, 30), 30, "@@pause", false, false, 'icons', '20')) { 521 | // $this->dispatcher->dispatch('cpu.start', new Signal); 522 | // } 523 | // } 524 | } 525 | 526 | public function renderTinyDisplay(Vec2 $pos, Vec2 $size, string $text) 527 | { 528 | $gradiend = $this->vg->linearGradient(0, $pos->y, 0, $pos->y + $size->y, $this->displayColorStart, $this->displayColorEnd); 529 | 530 | $this->vg->beginPath(); 531 | $this->vg->roundedRect($pos->x, $pos->y, $size->x, $size->y, 6); 532 | $this->vg->fillPaint($gradiend); 533 | $this->vg->strokeColor($this->displayColorBorderer); 534 | $this->vg->fill(); 535 | $this->vg->strokeWidth(2); 536 | $this->vg->stroke(); 537 | 538 | $this->vg->fontFace('vt323'); 539 | 540 | $textSize = 40; 541 | // note this is really slow obviously 542 | // but im lazy and it will do for now as we only have really on 543 | // large display to render 544 | if (strlen($text) > 4) { 545 | do { 546 | $textSize -= 2; 547 | $this->vg->fontSize($textSize); 548 | $bounds = new Vec4(); 549 | $w = $this->vg->textBounds($pos->x, $pos->y, $text, $bounds); 550 | } while ($w > $size->x); 551 | } else { 552 | $this->vg->fontSize(40); 553 | } 554 | 555 | $this->vg->textAlign(VGAlign::LEFT | VGAlign::MIDDLE); 556 | 557 | 558 | // render a glow 559 | $this->vg->fontBlur(10); 560 | $this->vg->fillColor($this->displayColorText); 561 | $this->vg->text($pos->x + 10, $pos->y + $size->y * 0.5, $text); 562 | 563 | // render the actual text 564 | $this->vg->fontBlur(0); 565 | $this->vg->fillColor($this->displayColorText); 566 | $this->vg->text($pos->x + 10, $pos->y + $size->y * 0.5, $text); 567 | } 568 | 569 | public function renderValuePanel(Vec2 $pos, Vec2 $size) 570 | { 571 | $this->vg->beginPath(); 572 | $paint = $this->vg->linearGradient(0, $pos->y, 0, $pos->y + $size->y, $this->valuePanelColorStart, $this->valuePanelColorEnd); 573 | $this->vg->fillPaint($paint); 574 | $this->vg->roundedRect($pos->x, $pos->y, $size->x, $size->y, 8); 575 | $this->vg->fill(); 576 | } 577 | 578 | public function renderValueDisplay(Vec2 $pos, Vec2 $size, string $value, string $label) 579 | { 580 | $this->renderValuePanel($pos, $size); 581 | 582 | $padding = 8; 583 | $height = $size->y * 0.5 - $padding; 584 | 585 | $this->vg->fontFace('bebas'); 586 | $this->vg->fontSize(16); 587 | $this->vg->textAlign(VGAlign::CENTER | VGAlign::MIDDLE); 588 | $this->vg->fillColor(new VGColor(0.647, 0.647, 0.647, 1.0)); 589 | $this->vg->text( 590 | $pos->x + $size->x * 0.5, 591 | $pos->y - $padding + $height * 2, 592 | $label 593 | ); 594 | 595 | // render display on top 596 | $dpos = $pos + new Vec2($padding, $padding); 597 | $dsize = new Vec2($size->x - $padding * 2, $height); 598 | 599 | $this->renderTinyDisplay($dpos, $dsize, $value); 600 | } 601 | 602 | /** 603 | * Register display looks very similar to the value one but the label is on the left 604 | */ 605 | public function renderRegisterDisplay(Vec2 $pos, Vec2 $size, string $value, string $label) 606 | { 607 | $this->renderValuePanel($pos, $size); 608 | 609 | $padding = 8; 610 | $width = $size->x * 0.5 - $padding; 611 | 612 | $this->vg->fontFace('bebas'); 613 | $this->vg->fontSize(28); 614 | $this->vg->textAlign(VGAlign::CENTER | VGAlign::MIDDLE); 615 | $this->vg->fillColor(new VGColor(0.647, 0.647, 0.647, 1.0)); 616 | $this->vg->text( 617 | $pos->x + $width * 0.5, 618 | $pos->y + $size->y * 0.5 + 2, 619 | $label 620 | ); 621 | 622 | // render display on right 623 | $dpos = $pos + new Vec2($size->x * 0.5, $padding); 624 | $dsize = new Vec2($width, $size->y - $padding * 2); 625 | 626 | $this->renderTinyDisplay($dpos, $dsize, $value); 627 | } 628 | 629 | public function renderStatePanel(float $width, CPU $cpu) : float 630 | { 631 | $pos = new Vec2($this->panelPadding, $this->panelPadding); 632 | $panelSize = new Vec2($width - $pos->x, 382); 633 | 634 | $this->renderBodyPanel($pos, $panelSize, false, $this->panelRadius); 635 | 636 | // inside 637 | $innerPos = $pos + new Vec2($this->panelBorderWidth, $this->panelBorderWidth); 638 | $innerSize = $panelSize - new Vec2($this->panelBorderWidth * 2, $this->panelBorderWidth * 2); 639 | 640 | $this->vg->beginPath(); 641 | $this->vg->fillColor($this->panelColor); 642 | $this->vg->roundedRect($innerPos->x, $innerPos->y, $innerSize->x, $innerSize->y, $this->panelRadius * 0.8); 643 | $this->vg->fill(); 644 | 645 | 646 | // we render 4 displays at the top for 647 | // - program counter 648 | // - stack pointer 649 | // - register I 650 | // - delay timer 651 | $gutter = 10; 652 | $x = $innerPos->x + $gutter; 653 | $displaySize = new Vec2(($innerSize->x - $gutter * 5) * 0.25, 100); 654 | $displayPos = $innerPos + new Vec2($gutter, $gutter); 655 | 656 | $this->renderValueDisplay($displayPos, $displaySize, str_pad(dechex($cpu->programCounter), 4, '0', STR_PAD_LEFT), 'Program Counter'); 657 | $displayPos->x = $displayPos->x + $displaySize->x + $gutter; 658 | $this->renderValueDisplay($displayPos, $displaySize, str_pad(dechex($cpu->stackPointer), 2, '0', STR_PAD_LEFT), 'Stack Pointer'); 659 | $displayPos->x = $displayPos->x + $displaySize->x + $gutter; 660 | $this->renderValueDisplay($displayPos, $displaySize, str_pad(dechex($cpu->registerI), 4, '0', STR_PAD_LEFT), 'Register I'); 661 | $displayPos->x = $displayPos->x + $displaySize->x + $gutter; 662 | $this->renderValueDisplay($displayPos, $displaySize, str_pad(dechex($cpu->timers[0]), 2, '0', STR_PAD_LEFT), 'Delay Timer'); 663 | 664 | $startY = $displayPos->y + $displaySize->y; 665 | 666 | // render the 16 registers in a 4x4 grid 667 | $gutter = 10; 668 | $x = $innerPos->x + $gutter; 669 | $displaySize = new Vec2(($innerSize->x - $gutter * 5) * 0.25, 50); 670 | $displayPos = $innerPos + new Vec2($gutter, $startY); 671 | 672 | for ($i = 0; $i < 16; $i++) { 673 | $this->renderRegisterDisplay($displayPos, $displaySize, strtoupper(str_pad(dechex($cpu->registers[$i]), 2, '0', STR_PAD_LEFT)), 'V' . dechex($i)); 674 | $displayPos->x = $displayPos->x + $displaySize->x + $gutter; 675 | if ($i % 4 == 3) { 676 | $displayPos->x = $innerPos->x + $gutter; 677 | $displayPos->y = $displayPos->y + $displaySize->y + $gutter; 678 | } 679 | } 680 | 681 | return $pos->y + $panelSize->y + $this->panelPadding; 682 | } 683 | 684 | public function renderDissaemblyPanel(float $y, float $width, CPU $cpu) 685 | { 686 | $panelPos = new Vec2($this->panelPadding, $y); 687 | $panelSize = new Vec2($width - $this->panelPadding, $this->renderState->viewport->height - $y - $this->panelPadding); 688 | 689 | $this->renderBodyPanel($panelPos, $panelSize, false, $this->panelRadius); 690 | 691 | // render display box 692 | $displayPos = new Vec2($panelPos->x + 10, $panelPos->y + 10); 693 | $displaySize = new Vec2($panelSize->x - 20, $panelSize->y - 20); 694 | 695 | $gradiend = $this->vg->linearGradient(0, $displayPos->y, 0, $displayPos->y + $displaySize->y, $this->displayColorStart, $this->displayColorEnd); 696 | 697 | $this->vg->beginPath(); 698 | $this->vg->roundedRect($displayPos->x, $displayPos->y, $displaySize->x - $width * 0.5, $displaySize->y, 10); 699 | $this->vg->fillPaint($gradiend); 700 | $this->vg->strokeColor($this->displayColorBorderer); 701 | $this->vg->fill(); 702 | $this->vg->strokeWidth(2); 703 | $this->vg->stroke(); 704 | 705 | // draw the current opcode 706 | $this->vg->fontFace('vt323'); 707 | $this->vg->fontSize(16); 708 | $this->vg->fillColor($this->displayColorText); 709 | $this->vg->textAlign(VGAlign::LEFT | VGAlign::TOP); 710 | 711 | // estimate range based on height of the display 712 | $displayInnerSpace = $displaySize->y - 20; 713 | 714 | $range = (int) (($displayInnerSpace / 10) / 2); 715 | // $ystart = 50; 716 | // $currentInst = $cpu->programCounter; 717 | 718 | // // dissassemble the next 20 instructions and last 20 instructions 719 | // for ($i = $currentInst - $range; $i < $currentInst + $range; $i += 2) { 720 | // if ($i < 0) { 721 | // continue; 722 | // } 723 | 724 | // if ($i == $currentInst) { 725 | // $this->vg->fillColor(VGColor::red()); 726 | // } else { 727 | // $this->vg->fillColor(VGColor::white()); 728 | // } 729 | 730 | // if ($string = $cpu->disassembleInstructionAt($i)) { 731 | // $offset = $i - $currentInst + 20; 732 | // $this->vg->text(10, $ystart + $offset * 10, $string); 733 | // } 734 | // } 735 | 736 | $instructionText = ""; 737 | $currentInst = $cpu->programCounter; 738 | for ($i = $currentInst - $range; $i < $currentInst + $range; $i++) { 739 | if ($i < 0) { 740 | continue; 741 | } 742 | 743 | if (!$diss = $cpu->disassembleInstructionAt($i)) { 744 | continue; 745 | } 746 | 747 | $counterString = str_pad(dechex($i), 4, '0', STR_PAD_LEFT); 748 | 749 | $prefix = $i == $currentInst ? "=> " : "| "; 750 | $instructionText .= $prefix . $counterString . ": " . $diss . "\n"; 751 | } 752 | 753 | $this->vg->scissor($displayPos->x, $displayPos->y, $displaySize->x, $displaySize->y); 754 | $this->vg->textBox($displayPos->x, $displayPos->y, $displaySize->x, $instructionText); 755 | 756 | $this->vg->resetScissor(); 757 | 758 | // render start pause reset buttons 759 | $buttonPanel = new Vec2($panelPos->x + $width * 0.5 - 10, $panelPos->y + 10); 760 | 761 | if ($this->renderState->cpuIsRunning) { 762 | if ($this->renderRoundButton($buttonPanel + new Vec2(30, 30), 30, "@@pause", false, false, 'icons', '20')) { 763 | $this->dispatcher->dispatch('cpu.pause', new Signal); 764 | } 765 | } else { 766 | if ($this->renderRoundButton($buttonPanel + new Vec2(30, 30), 30, "@@pause", false, false, 'icons', '20')) { 767 | $this->dispatcher->dispatch('cpu.start', new Signal); 768 | } 769 | } 770 | 771 | if ($this->renderRoundButton($buttonPanel + new Vec2(100, 30), 30, "@@step", false, false, 'icons', '20')) { 772 | $cpu->runCycles(1); 773 | } 774 | 775 | // reset button on the right 776 | if ($this->renderRoundButton($buttonPanel + new Vec2($width * 0.5 - 50, 30), 30, "@@reset", false, false, 'icons', '20')) { 777 | $cpu->reset(); 778 | if ($cpu->currentRomFilePath) { 779 | $cpu->loadRomFile($cpu->currentRomFilePath); 780 | } 781 | } 782 | 783 | // render the simulation speed 784 | // make it a bit more human readable 785 | $effectiveSpeed = $this->renderState->cyclesPerTick - RenderState::SUBTICK_DIV; 786 | $simSpeedHuman = $effectiveSpeed; 787 | if ($simSpeedHuman === 0) { 788 | $simSpeedHuman = '60tps'; 789 | } 790 | else if ($simSpeedHuman < 0) { 791 | $simSpeedHuman = '1/' . $simSpeedHuman * -1; 792 | } 793 | 794 | $simSpeedDispW = $displaySize->x * 0.3; 795 | $this->renderRegisterDisplay( 796 | $buttonPanel + new Vec2(0, $displaySize->y - 170), 797 | new Vec2($simSpeedDispW, 50), 798 | $simSpeedHuman, 799 | 'CpT', 800 | 0.9 801 | ); 802 | 803 | // buttons to change the simulation speed 804 | if ($this->renderRoundButton( 805 | $buttonPanel + new Vec2($simSpeedDispW + 30, $displaySize->y - 170 + 25), 806 | 20, 807 | '+' 808 | )) { 809 | 810 | if ($effectiveSpeed > 200) { 811 | $this->renderState->cyclesPerTick += 100; 812 | } elseif ($effectiveSpeed > 50) { 813 | $this->renderState->cyclesPerTick += 10; 814 | } elseif ($effectiveSpeed > 20) { 815 | $this->renderState->cyclesPerTick += 5; 816 | } elseif ($effectiveSpeed > 10) { 817 | $this->renderState->cyclesPerTick += 2; 818 | } else { 819 | $this->renderState->cyclesPerTick++; 820 | } 821 | } 822 | if ($this->renderRoundButton( 823 | $buttonPanel + new Vec2($simSpeedDispW + 80, $displaySize->y - 170 + 25), 824 | 20, 825 | '-' 826 | )) { 827 | if ($effectiveSpeed > 200) { 828 | $this->renderState->cyclesPerTick -= 100; 829 | } elseif ($effectiveSpeed > 50) { 830 | $this->renderState->cyclesPerTick -= 10; 831 | } elseif ($effectiveSpeed > 20) { 832 | $this->renderState->cyclesPerTick -= 5; 833 | } elseif ($effectiveSpeed > 10) { 834 | $this->renderState->cyclesPerTick -= 2; 835 | } else { 836 | $this->renderState->cyclesPerTick--; 837 | } 838 | } 839 | 840 | // render display with the current rom 841 | $this->renderValueDisplay( 842 | $buttonPanel + new Vec2(0, $displaySize->y - 100), 843 | new Vec2($displaySize->x * 0.5, 100), 844 | basename($cpu->currentRomFilePath), 845 | 'ROM' 846 | ); 847 | 848 | // if ($this->renderState->cpuIsRunning) { 849 | // // render a play icon 850 | // $this->vg->translate($buttonPanel->x, $buttonPanel->y); 851 | // $this->vg->beginPath(); 852 | // $this->vg->moveTo(-5, -8); 853 | // $this->vg->lineTo(-5, 8); 854 | // $this->vg->lineTo(8, 0); 855 | // $this->vg->fillColor(VGColor::white()); 856 | // $this->vg->fill(); 857 | // } else { 858 | // // render a pause icon 859 | // $this->vg->translate($buttonPanel->x, $buttonPanel->y); 860 | // $this->vg->beginPath(); 861 | // $this->vg->rect(-5, -8, 5, 16); 862 | // $this->vg->rect(0, -8, 5, 16); 863 | // $this->vg->fillColor(VGColor::white()); 864 | // $this->vg->fill(); 865 | // } 866 | } 867 | } --------------------------------------------------------------------------------