SlideShare a Scribd company logo
1 of 34
Download to read offline
Build Gameboy Emulator in Rust and
WebAssembly
Author: Yodalee
<lc85301@gmail.com>
Outline
1. Inside Gameboy
2. Gameboy Emulator in Rust
3. Migrate Rust to WebAssembly
Star Me on Github!
Source Code
https://github.com/yodalee/ruGameboy
Note: (Traditional Chinese)
https://yodalee.me/tags/gameboy/
Inside Gameboy
Gameboy
4MHz 8-bit Sharp LR35902
32KB Cartridge
8KB SRAM
8KB Video RAM
160x144 LCD screen
CPU Register
D15..D8 D7..D0
A F
B C
D E
H L
D15..D0
SP (stack pointer)
PC (program counter)
Flag Register
Z N H C 0 0 0 0
Z - Zero Flag
N - Subtract Flag
H - Half Carry Flag
C - Carry Flag
0 - Not used, always zero
CPU Instruction
4MHz CPU based on Intel 8080 and Z80.
245 instructions and another 256 extended (CB) instructions
Memory Layout
Start Size Description
0x0000 32 KB Cartridge ROM
0x8000 6 KB GPU Tile Content
0x9800 2 KB GPU Background Index
0xC000 8KB RAM
0xFE00 160 Bytes GPU Foreground Index
GPU Tile
1 tile = 8x8 = 64 pixels.
256
256
2 bits/pixel
1 tile = 16 bytes
Virtual Screen = 1024 Tiles
GPU Background
...
VRAM 0x8000-0xA000 (8K)
1. 0x8000-0x9000 or 0x8800-0x9800 => 4KB / 16B = 256 Tiles
2. 0x9800-0x9C00 or 0x9C00-A000 => 1KB = Tiles index
0x9800 - 0x9C00
Tile Index Table
From 0xFE00 to 0xFE9F = 160 bytes
4 bytes per Sprite => 40 Sprite
Sprite Size = 1 Tile = 8x8
GPU Sprite Foreground
Byte 0 Offset X
Byte 1 Offset Y
Byte 2 Tile Index
Byte 3 Flags: x flip, y flip, etc.
Note the width:
8 pixels
Line 0
Line 1
Line 2
Line 143
HBlank
VBlank
GPU Timing
160
144
Mode Cycle
Scanline Sprite 80
Scanline BG 172
HBlank 204
VBlank 4560 (10 lines)
Total 70224
4 MHz clock
70224 cycles ~= 0.0176s ~= 60 Hz
Gameboy Emulator in Rust
Emulator Architecture
GPU Cartridge RAM ….
Bus Register
VM
CPU
Display Buffer
Implement Register
F register All Register Interface
pub struct
FlagRegister {
pub zero: bool,
pub subtract: bool,
pub half_carry: bool,
pub carry: bool
}
pub struct Register {
pub a: u8,
pub b: u8,
pub c: u8,
pub d: u8,
pub e: u8,
pub f: FlagRegister,
pub h: u8,
pub l: u8,
}
impl Register {
fn get_hl() -> u16 {
(self.h as u16) << 8 | self.l as u16
}
fn set_hl(&mut self, value: u16) {
self.h = ((value >> 8) & 0xff) as u8;
self.l = (value & 0xff) as u8;
}
//...
}
Encode Instruction to Enum
Register X,Y Move Register X to Y Byte to Instruction
enum Target
{
A,
B,
C,
...
}
enum Instruction {
NOP
LDRR(Target, Target)
ADD(Target)
...
}
impl Instruction {
fn from_byte(u8) -> Instruction {
0x00 => Instruction::NOP,
0x01 => //…
0x02 => //…
//…
}
}
Implement CPU
CPU Step
pub struct Cpu {
regs: Register,
sp: u16,
pub pc: u16,
pub bus: Bus,
}
let byte = self.load(self.pc);
self.pc + 1;
let inst = Instruction::from_byte(byte);
match inst {
Instruction::JPHL => self.pc = self.regs.get_hl(),
Instruction::LDRR(source, target) => {
match (&source, &target) {
(&Target::C, &Target::B) => self.regs.b = self.regs.c,
//...
Implement Bus
Device Load/Store
pub trait Device {
fn load(&self, addr: u16) ->
Result<u8, ()>;
fn store(&mut self, addr: u16,
value: u8) -> Result<(), ()>;
}
impl Bus {
fn load(&self, addr: u16) -> Result<u8, ()> {
match addr {
CATRIDGE_START ..= CATRIDGE_END =>
self.cartridge.load(addr),
VRAM_START ..= VRAM_END =>
self.gpu.load(addr),
RAM_START ..= RAM_END =>
self.ram.load(addr),
//...
Implement Gpu
Sprite Gpu Render
struct Sprite {
tile_idx: u8,
x: isize,
y: isize,
// flag...
}
struct Gpu {
sprite: [Sprite:40]
vram: Vec<u8>,
oam: Vec<u8>,
//...
}
impl Device for Gpu {
//...
fn build_background(&mut self, buffer: &mut
Vec<u32>) {
for row in 0..HEIGHT {
for col in 0..WIDTH {
let tile_addr = row * 32 + col;
let tile_idx = self.vram[tile_addr];
let pixels = self.get_tile(tile_idx);
buffer.splice(start..end, pixels.iter()...);
VM
Screen built with minifb.
Loop:
1. run CPU until VBlank
2. Render Screen.
Let GPU fill display buffer Vec<u32>
Migrate Rust to WebAssembly
Rust x WebAssembly
https://rustwasm.github.io/book/
Tool needed:
1. rustup install
wasm32-unknown-unknown
2. wasm-pack
3. cargo-generate
4. npm
Migration Step
1. cargo generate --git https://github.com/rustwasm/wasm-pack-template
2. Expose Interface to Javascript
3. wasm-pack build
4. Import WebAssembly from Javascript
Done
https://github.com/yodalee/
wasm_gameboy
Expose Interface to Javascript
Magic Word
#[wasm_bindgen]
wasm_bindgen
// rust
#[wasm_bindgen]
pub struct Gameboy {
cartridge: Vec<u8>,
vm: Option<Vm>
}
// javascript
import Gameboy from "wasmgb"
Gameboy.new()
wasm_bindgen
// rust
#[wasm_bindgen]
impl Gameboy {
pub fn get_buffer(&self) -> *const u32 {
self.vm.buffer.as_ptr()
}
}
// javascript
import memory from "wasmgb_bg"
const buffer = gameboy.get_buffer();
const pixels = new
Uint32Array(memory.buffer, buffer,
width*height);
Import WebAssembly from Javascript
<body>
<input type="file" id="file-uploader"/>
<canvas id="gameboy-canvas"></canvas>
<pre id="gameboy-log"></pre>
<script src="./bootstrap.js"></script>
</body>
Import WebAssembly from Javascript
reader.onload = function() {
const cartridge = gameboy.get_cartridge();
var bytes = new Uint8Array(reader.result);
const m_cartridge = new Uint8Array(memory.buffer, cartridge, 0x8000);
// set cartridge
for (let idx = 0; idx < 0x8000; idx++) {
m_cartridge[idx] = bytes[idx];
}
gameboy.set_cartridge();
Import WebAssembly from Javascript
const renderLoop = () => {
drawPixels();
gameboy.step();
}
const drawPixels = () => {
const buffer = gameboy.get_buffer();
const pixels = new Uint32Array(memory.buffer, buffer, width * height);
for (let row = 0; row < height; row++) {
for (let col = 0; col < width; col++) {
if (pixels[row * width + col] == WHITE) { //...
Done
Conclusion
Future Work
Features to implement:
● Right now only Tetris can work (゚д゚;)
● Implement Sound
Problem to solve:
● How to emulate program in correct timing?
● How to debug efficiently?
Conclusion
1. We learn how to build emulator by building it.
2. A Rust program can be migrated to WebAssembly really quick.
Thanks for Listening

More Related Content

What's hot

“Automation Testing for Embedded Systems”
“Automation Testing for Embedded Systems” “Automation Testing for Embedded Systems”
“Automation Testing for Embedded Systems” GlobalLogic Ukraine
 
Booting Android: bootloaders, fastboot and boot images
Booting Android: bootloaders, fastboot and boot imagesBooting Android: bootloaders, fastboot and boot images
Booting Android: bootloaders, fastboot and boot imagesChris Simmonds
 
Stefano Cordibella - An introduction to Yocto Project
Stefano Cordibella - An introduction to Yocto ProjectStefano Cordibella - An introduction to Yocto Project
Stefano Cordibella - An introduction to Yocto Projectlinuxlab_conf
 
a detailed study on babesiosis
a detailed study on babesiosisa detailed study on babesiosis
a detailed study on babesiosismartinshaji
 
Atlas de parasitología médica
Atlas de parasitología médicaAtlas de parasitología médica
Atlas de parasitología médicaRoger Lopez
 
Trypanosoma brucei rhodesiense
Trypanosoma brucei rhodesienseTrypanosoma brucei rhodesiense
Trypanosoma brucei rhodesienseNoe Mendez
 
Introduction to yocto
Introduction to yoctoIntroduction to yocto
Introduction to yoctoAlex Gonzalez
 
I2C Subsystem In Linux-2.6.24
I2C Subsystem In Linux-2.6.24I2C Subsystem In Linux-2.6.24
I2C Subsystem In Linux-2.6.24Varun Mahajan
 
For the Greater Good: Leveraging VMware's RPC Interface for fun and profit by...
For the Greater Good: Leveraging VMware's RPC Interface for fun and profit by...For the Greater Good: Leveraging VMware's RPC Interface for fun and profit by...
For the Greater Good: Leveraging VMware's RPC Interface for fun and profit by...CODE BLUE
 
Description of GRUB 2
Description of GRUB 2Description of GRUB 2
Description of GRUB 2iamumr
 
Vmlinux: anatomy of bzimage and how x86 64 processor is booted
Vmlinux: anatomy of bzimage and how x86 64 processor is bootedVmlinux: anatomy of bzimage and how x86 64 processor is booted
Vmlinux: anatomy of bzimage and how x86 64 processor is bootedAdrian Huang
 
Anatomy of the loadable kernel module (lkm)
Anatomy of the loadable kernel module (lkm)Anatomy of the loadable kernel module (lkm)
Anatomy of the loadable kernel module (lkm)Adrian Huang
 

What's hot (20)

gcc and friends
gcc and friendsgcc and friends
gcc and friends
 
“Automation Testing for Embedded Systems”
“Automation Testing for Embedded Systems” “Automation Testing for Embedded Systems”
“Automation Testing for Embedded Systems”
 
Booting Android: bootloaders, fastboot and boot images
Booting Android: bootloaders, fastboot and boot imagesBooting Android: bootloaders, fastboot and boot images
Booting Android: bootloaders, fastboot and boot images
 
Qemu Introduction
Qemu IntroductionQemu Introduction
Qemu Introduction
 
Stefano Cordibella - An introduction to Yocto Project
Stefano Cordibella - An introduction to Yocto ProjectStefano Cordibella - An introduction to Yocto Project
Stefano Cordibella - An introduction to Yocto Project
 
a detailed study on babesiosis
a detailed study on babesiosisa detailed study on babesiosis
a detailed study on babesiosis
 
Android JNI
Android JNIAndroid JNI
Android JNI
 
Atlas de parasitología médica
Atlas de parasitología médicaAtlas de parasitología médica
Atlas de parasitología médica
 
Trypanosoma brucei rhodesiense
Trypanosoma brucei rhodesienseTrypanosoma brucei rhodesiense
Trypanosoma brucei rhodesiense
 
Linux device drivers
Linux device drivers Linux device drivers
Linux device drivers
 
Introduction to yocto
Introduction to yoctoIntroduction to yocto
Introduction to yocto
 
Embedded Android : System Development - Part II (HAL)
Embedded Android : System Development - Part II (HAL)Embedded Android : System Development - Part II (HAL)
Embedded Android : System Development - Part II (HAL)
 
I2C Subsystem In Linux-2.6.24
I2C Subsystem In Linux-2.6.24I2C Subsystem In Linux-2.6.24
I2C Subsystem In Linux-2.6.24
 
Android Internals
Android InternalsAndroid Internals
Android Internals
 
For the Greater Good: Leveraging VMware's RPC Interface for fun and profit by...
For the Greater Good: Leveraging VMware's RPC Interface for fun and profit by...For the Greater Good: Leveraging VMware's RPC Interface for fun and profit by...
For the Greater Good: Leveraging VMware's RPC Interface for fun and profit by...
 
Description of GRUB 2
Description of GRUB 2Description of GRUB 2
Description of GRUB 2
 
Vmlinux: anatomy of bzimage and how x86 64 processor is booted
Vmlinux: anatomy of bzimage and how x86 64 processor is bootedVmlinux: anatomy of bzimage and how x86 64 processor is booted
Vmlinux: anatomy of bzimage and how x86 64 processor is booted
 
Cestodes
CestodesCestodes
Cestodes
 
Improve Android System Component Performance
Improve Android System Component PerformanceImprove Android System Component Performance
Improve Android System Component Performance
 
Anatomy of the loadable kernel module (lkm)
Anatomy of the loadable kernel module (lkm)Anatomy of the loadable kernel module (lkm)
Anatomy of the loadable kernel module (lkm)
 

Similar to Gameboy emulator in rust and web assembly

Introduction to .NET Micro Framework Development
Introduction to .NET Micro Framework DevelopmentIntroduction to .NET Micro Framework Development
Introduction to .NET Micro Framework Developmentchristopherfairbairn
 
Raspberry Pi tutorial
Raspberry Pi tutorialRaspberry Pi tutorial
Raspberry Pi tutorial艾鍗科技
 
U Boot or Universal Bootloader
U Boot or Universal BootloaderU Boot or Universal Bootloader
U Boot or Universal BootloaderSatpal Parmar
 
DEF CON 27 - HUBER AND ROSKOSCH - im on your phone listening attacking voip c...
DEF CON 27 - HUBER AND ROSKOSCH - im on your phone listening attacking voip c...DEF CON 27 - HUBER AND ROSKOSCH - im on your phone listening attacking voip c...
DEF CON 27 - HUBER AND ROSKOSCH - im on your phone listening attacking voip c...Felipe Prado
 
Let's trace Linux Lernel with KGDB @ COSCUP 2021
Let's trace Linux Lernel with KGDB @ COSCUP 2021Let's trace Linux Lernel with KGDB @ COSCUP 2021
Let's trace Linux Lernel with KGDB @ COSCUP 2021Jian-Hong Pan
 
Debugging GPU faults: QoL tools for your driver – XDC 2023
Debugging GPU faults: QoL tools for your driver – XDC 2023Debugging GPU faults: QoL tools for your driver – XDC 2023
Debugging GPU faults: QoL tools for your driver – XDC 2023Igalia
 
Revelation pyconuk2016
Revelation pyconuk2016Revelation pyconuk2016
Revelation pyconuk2016Sarah Mount
 
PVS-Studio, a solution for resource intensive applications development
PVS-Studio, a solution for resource intensive applications developmentPVS-Studio, a solution for resource intensive applications development
PVS-Studio, a solution for resource intensive applications developmentOOO "Program Verification Systems"
 
U-Boot Porting on New Hardware
U-Boot Porting on New HardwareU-Boot Porting on New Hardware
U-Boot Porting on New HardwareRuggedBoardGroup
 
Debugging node in prod
Debugging node in prodDebugging node in prod
Debugging node in prodYunong Xiao
 
Track c-High speed transaction-based hw-sw coverification -eve
Track c-High speed transaction-based hw-sw coverification -eveTrack c-High speed transaction-based hw-sw coverification -eve
Track c-High speed transaction-based hw-sw coverification -evechiportal
 
Study on Android Emulator
Study on Android EmulatorStudy on Android Emulator
Study on Android EmulatorSamael Wang
 
Writing Metasploit Plugins
Writing Metasploit PluginsWriting Metasploit Plugins
Writing Metasploit Pluginsamiable_indian
 
PVS-Studio 5.00, a solution for developers of modern resource-intensive appl...
PVS-Studio 5.00, a solution for developers of modern resource-intensive appl...PVS-Studio 5.00, a solution for developers of modern resource-intensive appl...
PVS-Studio 5.00, a solution for developers of modern resource-intensive appl...Andrey Karpov
 
Developing Applications for Beagle Bone Black, Raspberry Pi and SoC Single Bo...
Developing Applications for Beagle Bone Black, Raspberry Pi and SoC Single Bo...Developing Applications for Beagle Bone Black, Raspberry Pi and SoC Single Bo...
Developing Applications for Beagle Bone Black, Raspberry Pi and SoC Single Bo...ryancox
 

Similar to Gameboy emulator in rust and web assembly (20)

Introduction to .NET Micro Framework Development
Introduction to .NET Micro Framework DevelopmentIntroduction to .NET Micro Framework Development
Introduction to .NET Micro Framework Development
 
Raspberry Pi tutorial
Raspberry Pi tutorialRaspberry Pi tutorial
Raspberry Pi tutorial
 
There is more to C
There is more to CThere is more to C
There is more to C
 
U Boot or Universal Bootloader
U Boot or Universal BootloaderU Boot or Universal Bootloader
U Boot or Universal Bootloader
 
DEF CON 27 - HUBER AND ROSKOSCH - im on your phone listening attacking voip c...
DEF CON 27 - HUBER AND ROSKOSCH - im on your phone listening attacking voip c...DEF CON 27 - HUBER AND ROSKOSCH - im on your phone listening attacking voip c...
DEF CON 27 - HUBER AND ROSKOSCH - im on your phone listening attacking voip c...
 
Let's trace Linux Lernel with KGDB @ COSCUP 2021
Let's trace Linux Lernel with KGDB @ COSCUP 2021Let's trace Linux Lernel with KGDB @ COSCUP 2021
Let's trace Linux Lernel with KGDB @ COSCUP 2021
 
Debugging GPU faults: QoL tools for your driver – XDC 2023
Debugging GPU faults: QoL tools for your driver – XDC 2023Debugging GPU faults: QoL tools for your driver – XDC 2023
Debugging GPU faults: QoL tools for your driver – XDC 2023
 
Revelation pyconuk2016
Revelation pyconuk2016Revelation pyconuk2016
Revelation pyconuk2016
 
Exploiting buffer overflows
Exploiting buffer overflowsExploiting buffer overflows
Exploiting buffer overflows
 
PVS-Studio, a solution for resource intensive applications development
PVS-Studio, a solution for resource intensive applications developmentPVS-Studio, a solution for resource intensive applications development
PVS-Studio, a solution for resource intensive applications development
 
Shrink to grow
Shrink to growShrink to grow
Shrink to grow
 
Basic Linux kernel
Basic Linux kernelBasic Linux kernel
Basic Linux kernel
 
U-Boot Porting on New Hardware
U-Boot Porting on New HardwareU-Boot Porting on New Hardware
U-Boot Porting on New Hardware
 
Debugging node in prod
Debugging node in prodDebugging node in prod
Debugging node in prod
 
Track c-High speed transaction-based hw-sw coverification -eve
Track c-High speed transaction-based hw-sw coverification -eveTrack c-High speed transaction-based hw-sw coverification -eve
Track c-High speed transaction-based hw-sw coverification -eve
 
Study on Android Emulator
Study on Android EmulatorStudy on Android Emulator
Study on Android Emulator
 
Writing Metasploit Plugins
Writing Metasploit PluginsWriting Metasploit Plugins
Writing Metasploit Plugins
 
Qemu Pcie
Qemu PcieQemu Pcie
Qemu Pcie
 
PVS-Studio 5.00, a solution for developers of modern resource-intensive appl...
PVS-Studio 5.00, a solution for developers of modern resource-intensive appl...PVS-Studio 5.00, a solution for developers of modern resource-intensive appl...
PVS-Studio 5.00, a solution for developers of modern resource-intensive appl...
 
Developing Applications for Beagle Bone Black, Raspberry Pi and SoC Single Bo...
Developing Applications for Beagle Bone Black, Raspberry Pi and SoC Single Bo...Developing Applications for Beagle Bone Black, Raspberry Pi and SoC Single Bo...
Developing Applications for Beagle Bone Black, Raspberry Pi and SoC Single Bo...
 

More from Yodalee

COSCUP2023 RSA256 Verilator.pdf
COSCUP2023 RSA256 Verilator.pdfCOSCUP2023 RSA256 Verilator.pdf
COSCUP2023 RSA256 Verilator.pdfYodalee
 
rrxv6 Build a Riscv xv6 Kernel in Rust.pdf
rrxv6 Build a Riscv xv6 Kernel in Rust.pdfrrxv6 Build a Riscv xv6 Kernel in Rust.pdf
rrxv6 Build a Riscv xv6 Kernel in Rust.pdfYodalee
 
Make A Shoot ‘Em Up Game with Amethyst Framework
Make A Shoot ‘Em Up Game with Amethyst FrameworkMake A Shoot ‘Em Up Game with Amethyst Framework
Make A Shoot ‘Em Up Game with Amethyst FrameworkYodalee
 
Build Yourself a Nixie Tube Clock
Build Yourself a Nixie Tube ClockBuild Yourself a Nixie Tube Clock
Build Yourself a Nixie Tube ClockYodalee
 
Introduction to nand2 tetris
Introduction to nand2 tetrisIntroduction to nand2 tetris
Introduction to nand2 tetrisYodalee
 
Office word skills
Office word skillsOffice word skills
Office word skillsYodalee
 
Git: basic to advanced
Git: basic to advancedGit: basic to advanced
Git: basic to advancedYodalee
 

More from Yodalee (7)

COSCUP2023 RSA256 Verilator.pdf
COSCUP2023 RSA256 Verilator.pdfCOSCUP2023 RSA256 Verilator.pdf
COSCUP2023 RSA256 Verilator.pdf
 
rrxv6 Build a Riscv xv6 Kernel in Rust.pdf
rrxv6 Build a Riscv xv6 Kernel in Rust.pdfrrxv6 Build a Riscv xv6 Kernel in Rust.pdf
rrxv6 Build a Riscv xv6 Kernel in Rust.pdf
 
Make A Shoot ‘Em Up Game with Amethyst Framework
Make A Shoot ‘Em Up Game with Amethyst FrameworkMake A Shoot ‘Em Up Game with Amethyst Framework
Make A Shoot ‘Em Up Game with Amethyst Framework
 
Build Yourself a Nixie Tube Clock
Build Yourself a Nixie Tube ClockBuild Yourself a Nixie Tube Clock
Build Yourself a Nixie Tube Clock
 
Introduction to nand2 tetris
Introduction to nand2 tetrisIntroduction to nand2 tetris
Introduction to nand2 tetris
 
Office word skills
Office word skillsOffice word skills
Office word skills
 
Git: basic to advanced
Git: basic to advancedGit: basic to advanced
Git: basic to advanced
 

Recently uploaded

Extrusion Processes and Their Limitations
Extrusion Processes and Their LimitationsExtrusion Processes and Their Limitations
Extrusion Processes and Their Limitations120cr0395
 
chapter 5.pptx: drainage and irrigation engineering
chapter 5.pptx: drainage and irrigation engineeringchapter 5.pptx: drainage and irrigation engineering
chapter 5.pptx: drainage and irrigation engineeringmulugeta48
 
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Christo Ananth
 
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...Christo Ananth
 
data_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdfdata_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdfJiananWang21
 
KubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghlyKubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghlysanyuktamishra911
 
Glass Ceramics: Processing and Properties
Glass Ceramics: Processing and PropertiesGlass Ceramics: Processing and Properties
Glass Ceramics: Processing and PropertiesPrabhanshu Chaturvedi
 
Double rodded leveling 1 pdf activity 01
Double rodded leveling 1 pdf activity 01Double rodded leveling 1 pdf activity 01
Double rodded leveling 1 pdf activity 01KreezheaRecto
 
Thermal Engineering Unit - I & II . ppt
Thermal Engineering  Unit - I & II . pptThermal Engineering  Unit - I & II . ppt
Thermal Engineering Unit - I & II . pptDineshKumar4165
 
UNIT-III FMM. DIMENSIONAL ANALYSIS
UNIT-III FMM.        DIMENSIONAL ANALYSISUNIT-III FMM.        DIMENSIONAL ANALYSIS
UNIT-III FMM. DIMENSIONAL ANALYSISrknatarajan
 
Unit 1 - Soil Classification and Compaction.pdf
Unit 1 - Soil Classification and Compaction.pdfUnit 1 - Soil Classification and Compaction.pdf
Unit 1 - Soil Classification and Compaction.pdfRagavanV2
 
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...Call Girls in Nagpur High Profile
 
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdfONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdfKamal Acharya
 
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...roncy bisnoi
 
Java Programming :Event Handling(Types of Events)
Java Programming :Event Handling(Types of Events)Java Programming :Event Handling(Types of Events)
Java Programming :Event Handling(Types of Events)simmis5
 
PVC VS. FIBERGLASS (FRP) GRAVITY SEWER - UNI BELL
PVC VS. FIBERGLASS (FRP) GRAVITY SEWER - UNI BELLPVC VS. FIBERGLASS (FRP) GRAVITY SEWER - UNI BELL
PVC VS. FIBERGLASS (FRP) GRAVITY SEWER - UNI BELLManishPatel169454
 
Thermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - VThermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - VDineshKumar4165
 

Recently uploaded (20)

Extrusion Processes and Their Limitations
Extrusion Processes and Their LimitationsExtrusion Processes and Their Limitations
Extrusion Processes and Their Limitations
 
chapter 5.pptx: drainage and irrigation engineering
chapter 5.pptx: drainage and irrigation engineeringchapter 5.pptx: drainage and irrigation engineering
chapter 5.pptx: drainage and irrigation engineering
 
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
 
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
 
data_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdfdata_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdf
 
KubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghlyKubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghly
 
Glass Ceramics: Processing and Properties
Glass Ceramics: Processing and PropertiesGlass Ceramics: Processing and Properties
Glass Ceramics: Processing and Properties
 
Double rodded leveling 1 pdf activity 01
Double rodded leveling 1 pdf activity 01Double rodded leveling 1 pdf activity 01
Double rodded leveling 1 pdf activity 01
 
Thermal Engineering Unit - I & II . ppt
Thermal Engineering  Unit - I & II . pptThermal Engineering  Unit - I & II . ppt
Thermal Engineering Unit - I & II . ppt
 
UNIT-III FMM. DIMENSIONAL ANALYSIS
UNIT-III FMM.        DIMENSIONAL ANALYSISUNIT-III FMM.        DIMENSIONAL ANALYSIS
UNIT-III FMM. DIMENSIONAL ANALYSIS
 
Unit 1 - Soil Classification and Compaction.pdf
Unit 1 - Soil Classification and Compaction.pdfUnit 1 - Soil Classification and Compaction.pdf
Unit 1 - Soil Classification and Compaction.pdf
 
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
 
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdfONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
 
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
 
Java Programming :Event Handling(Types of Events)
Java Programming :Event Handling(Types of Events)Java Programming :Event Handling(Types of Events)
Java Programming :Event Handling(Types of Events)
 
(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7
(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7
(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7
 
PVC VS. FIBERGLASS (FRP) GRAVITY SEWER - UNI BELL
PVC VS. FIBERGLASS (FRP) GRAVITY SEWER - UNI BELLPVC VS. FIBERGLASS (FRP) GRAVITY SEWER - UNI BELL
PVC VS. FIBERGLASS (FRP) GRAVITY SEWER - UNI BELL
 
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar ≼🔝 Delhi door step de...
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar  ≼🔝 Delhi door step de...Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar  ≼🔝 Delhi door step de...
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar ≼🔝 Delhi door step de...
 
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort ServiceCall Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
 
Thermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - VThermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - V
 

Gameboy emulator in rust and web assembly

  • 1. Build Gameboy Emulator in Rust and WebAssembly Author: Yodalee <lc85301@gmail.com>
  • 2. Outline 1. Inside Gameboy 2. Gameboy Emulator in Rust 3. Migrate Rust to WebAssembly
  • 3. Star Me on Github! Source Code https://github.com/yodalee/ruGameboy Note: (Traditional Chinese) https://yodalee.me/tags/gameboy/
  • 5. Gameboy 4MHz 8-bit Sharp LR35902 32KB Cartridge 8KB SRAM 8KB Video RAM 160x144 LCD screen
  • 6. CPU Register D15..D8 D7..D0 A F B C D E H L D15..D0 SP (stack pointer) PC (program counter) Flag Register Z N H C 0 0 0 0 Z - Zero Flag N - Subtract Flag H - Half Carry Flag C - Carry Flag 0 - Not used, always zero
  • 7. CPU Instruction 4MHz CPU based on Intel 8080 and Z80. 245 instructions and another 256 extended (CB) instructions
  • 8. Memory Layout Start Size Description 0x0000 32 KB Cartridge ROM 0x8000 6 KB GPU Tile Content 0x9800 2 KB GPU Background Index 0xC000 8KB RAM 0xFE00 160 Bytes GPU Foreground Index
  • 9. GPU Tile 1 tile = 8x8 = 64 pixels. 256 256 2 bits/pixel 1 tile = 16 bytes Virtual Screen = 1024 Tiles
  • 10. GPU Background ... VRAM 0x8000-0xA000 (8K) 1. 0x8000-0x9000 or 0x8800-0x9800 => 4KB / 16B = 256 Tiles 2. 0x9800-0x9C00 or 0x9C00-A000 => 1KB = Tiles index 0x9800 - 0x9C00 Tile Index Table
  • 11. From 0xFE00 to 0xFE9F = 160 bytes 4 bytes per Sprite => 40 Sprite Sprite Size = 1 Tile = 8x8 GPU Sprite Foreground Byte 0 Offset X Byte 1 Offset Y Byte 2 Tile Index Byte 3 Flags: x flip, y flip, etc. Note the width: 8 pixels
  • 12. Line 0 Line 1 Line 2 Line 143 HBlank VBlank GPU Timing 160 144 Mode Cycle Scanline Sprite 80 Scanline BG 172 HBlank 204 VBlank 4560 (10 lines) Total 70224 4 MHz clock 70224 cycles ~= 0.0176s ~= 60 Hz
  • 14. Emulator Architecture GPU Cartridge RAM …. Bus Register VM CPU Display Buffer
  • 15. Implement Register F register All Register Interface pub struct FlagRegister { pub zero: bool, pub subtract: bool, pub half_carry: bool, pub carry: bool } pub struct Register { pub a: u8, pub b: u8, pub c: u8, pub d: u8, pub e: u8, pub f: FlagRegister, pub h: u8, pub l: u8, } impl Register { fn get_hl() -> u16 { (self.h as u16) << 8 | self.l as u16 } fn set_hl(&mut self, value: u16) { self.h = ((value >> 8) & 0xff) as u8; self.l = (value & 0xff) as u8; } //... }
  • 16. Encode Instruction to Enum Register X,Y Move Register X to Y Byte to Instruction enum Target { A, B, C, ... } enum Instruction { NOP LDRR(Target, Target) ADD(Target) ... } impl Instruction { fn from_byte(u8) -> Instruction { 0x00 => Instruction::NOP, 0x01 => //… 0x02 => //… //… } }
  • 17. Implement CPU CPU Step pub struct Cpu { regs: Register, sp: u16, pub pc: u16, pub bus: Bus, } let byte = self.load(self.pc); self.pc + 1; let inst = Instruction::from_byte(byte); match inst { Instruction::JPHL => self.pc = self.regs.get_hl(), Instruction::LDRR(source, target) => { match (&source, &target) { (&Target::C, &Target::B) => self.regs.b = self.regs.c, //...
  • 18. Implement Bus Device Load/Store pub trait Device { fn load(&self, addr: u16) -> Result<u8, ()>; fn store(&mut self, addr: u16, value: u8) -> Result<(), ()>; } impl Bus { fn load(&self, addr: u16) -> Result<u8, ()> { match addr { CATRIDGE_START ..= CATRIDGE_END => self.cartridge.load(addr), VRAM_START ..= VRAM_END => self.gpu.load(addr), RAM_START ..= RAM_END => self.ram.load(addr), //...
  • 19. Implement Gpu Sprite Gpu Render struct Sprite { tile_idx: u8, x: isize, y: isize, // flag... } struct Gpu { sprite: [Sprite:40] vram: Vec<u8>, oam: Vec<u8>, //... } impl Device for Gpu { //... fn build_background(&mut self, buffer: &mut Vec<u32>) { for row in 0..HEIGHT { for col in 0..WIDTH { let tile_addr = row * 32 + col; let tile_idx = self.vram[tile_addr]; let pixels = self.get_tile(tile_idx); buffer.splice(start..end, pixels.iter()...);
  • 20. VM Screen built with minifb. Loop: 1. run CPU until VBlank 2. Render Screen. Let GPU fill display buffer Vec<u32>
  • 21. Migrate Rust to WebAssembly
  • 22. Rust x WebAssembly https://rustwasm.github.io/book/ Tool needed: 1. rustup install wasm32-unknown-unknown 2. wasm-pack 3. cargo-generate 4. npm
  • 23. Migration Step 1. cargo generate --git https://github.com/rustwasm/wasm-pack-template 2. Expose Interface to Javascript 3. wasm-pack build 4. Import WebAssembly from Javascript Done https://github.com/yodalee/ wasm_gameboy
  • 24. Expose Interface to Javascript Magic Word #[wasm_bindgen]
  • 25. wasm_bindgen // rust #[wasm_bindgen] pub struct Gameboy { cartridge: Vec<u8>, vm: Option<Vm> } // javascript import Gameboy from "wasmgb" Gameboy.new()
  • 26. wasm_bindgen // rust #[wasm_bindgen] impl Gameboy { pub fn get_buffer(&self) -> *const u32 { self.vm.buffer.as_ptr() } } // javascript import memory from "wasmgb_bg" const buffer = gameboy.get_buffer(); const pixels = new Uint32Array(memory.buffer, buffer, width*height);
  • 27. Import WebAssembly from Javascript <body> <input type="file" id="file-uploader"/> <canvas id="gameboy-canvas"></canvas> <pre id="gameboy-log"></pre> <script src="./bootstrap.js"></script> </body>
  • 28. Import WebAssembly from Javascript reader.onload = function() { const cartridge = gameboy.get_cartridge(); var bytes = new Uint8Array(reader.result); const m_cartridge = new Uint8Array(memory.buffer, cartridge, 0x8000); // set cartridge for (let idx = 0; idx < 0x8000; idx++) { m_cartridge[idx] = bytes[idx]; } gameboy.set_cartridge();
  • 29. Import WebAssembly from Javascript const renderLoop = () => { drawPixels(); gameboy.step(); } const drawPixels = () => { const buffer = gameboy.get_buffer(); const pixels = new Uint32Array(memory.buffer, buffer, width * height); for (let row = 0; row < height; row++) { for (let col = 0; col < width; col++) { if (pixels[row * width + col] == WHITE) { //...
  • 30. Done
  • 32. Future Work Features to implement: ● Right now only Tetris can work (゚д゚;) ● Implement Sound Problem to solve: ● How to emulate program in correct timing? ● How to debug efficiently?
  • 33. Conclusion 1. We learn how to build emulator by building it. 2. A Rust program can be migrated to WebAssembly really quick.