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

Similar to Gameboy emulator in rust and web assembly

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
 
Jagan Teki - U-boot from scratch
Jagan Teki - U-boot from scratchJagan Teki - U-boot from scratch
Jagan Teki - U-boot from scratchlinuxlab_conf
 
Virtual platform
Virtual platformVirtual platform
Virtual platformsean chen
 

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

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...
 
Jagan Teki - U-boot from scratch
Jagan Teki - U-boot from scratchJagan Teki - U-boot from scratch
Jagan Teki - U-boot from scratch
 
Virtual platform
Virtual platformVirtual platform
Virtual platform
 

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
 
Use PEG to Write a Programming Language Parser
Use PEG to Write a Programming Language ParserUse PEG to Write a Programming Language Parser
Use PEG to Write a Programming Language ParserYodalee
 
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 (8)

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
 
Use PEG to Write a Programming Language Parser
Use PEG to Write a Programming Language ParserUse PEG to Write a Programming Language Parser
Use PEG to Write a Programming Language Parser
 
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

Bhosari ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready For ...
Bhosari ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready For ...Bhosari ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready For ...
Bhosari ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready For ...tanu pandey
 
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 In Bangalore ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Bangalore ☎ 7737669865 🥵 Book Your One night StandCall Girls In Bangalore ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Bangalore ☎ 7737669865 🥵 Book Your One night Standamitlee9823
 
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
 
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
 
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...SUHANI PANDEY
 
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
 
Intro To Electric Vehicles PDF Notes.pdf
Intro To Electric Vehicles PDF Notes.pdfIntro To Electric Vehicles PDF Notes.pdf
Intro To Electric Vehicles PDF Notes.pdfrs7054576148
 
Call Girls Wakad Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Wakad Call Me 7737669865 Budget Friendly No Advance BookingCall Girls Wakad Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Wakad Call Me 7737669865 Budget Friendly No Advance Bookingroncy bisnoi
 
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 banking management system project.pdf
Online banking management system project.pdfOnline banking management system project.pdf
Online banking management system project.pdfKamal Acharya
 
University management System project report..pdf
University management System project report..pdfUniversity management System project report..pdf
University management System project report..pdfKamal Acharya
 
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
 
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
 

Recently uploaded (20)

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
 
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak HamilCara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
 
Bhosari ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready For ...
Bhosari ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready For ...Bhosari ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready For ...
Bhosari ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready For ...
 
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
 
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 In Bangalore ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Bangalore ☎ 7737669865 🥵 Book Your One night StandCall Girls In Bangalore ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Bangalore ☎ 7737669865 🥵 Book Your One night Stand
 
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...
 
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
 
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
 
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
 
Intro To Electric Vehicles PDF Notes.pdf
Intro To Electric Vehicles PDF Notes.pdfIntro To Electric Vehicles PDF Notes.pdf
Intro To Electric Vehicles PDF Notes.pdf
 
Call Girls Wakad Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Wakad Call Me 7737669865 Budget Friendly No Advance BookingCall Girls Wakad Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Wakad Call Me 7737669865 Budget Friendly No Advance Booking
 
(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
 
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 banking management system project.pdf
Online banking management system project.pdfOnline banking management system project.pdf
Online banking management system project.pdf
 
(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7
(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7
(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7
 
University management System project report..pdf
University management System project report..pdfUniversity management System project report..pdf
University management System project report..pdf
 
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
 
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
 

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.