From b1773b88c216daabf7956e60d1837643f5352b5f Mon Sep 17 00:00:00 2001 From: Divyam Ahuja Date: Tue, 10 Nov 2026 01:08:36 +0530 Subject: [PATCH] Update blog: add CHIP-8 and Snake Wasm posts, clean up placeholders --- content/posts/hello-webassembly-c.md | 16 +- .../i-built-a-chip8-emulator-in-javascript.md | 149 +++++++++++++++++ .../posts/networking-part-1-the-osi-model.md | 42 ++--- ...etworking-part-2-physical-and-data-link.md | 9 -- .../networking-part-3-the-network-layer.md | 9 -- ...orking-part-4-transport-and-application.md | 9 -- .../snake-game-in-cpp-and-webassembly.md | 152 ++++++++++++++++++ 7 files changed, 329 insertions(+), 57 deletions(-) create mode 100644 content/posts/i-built-a-chip8-emulator-in-javascript.md delete mode 100644 content/posts/networking-part-2-physical-and-data-link.md delete mode 100644 content/posts/networking-part-3-the-network-layer.md delete mode 100644 content/posts/networking-part-4-transport-and-application.md create mode 100644 content/posts/snake-game-in-cpp-and-webassembly.md diff --git a/content/posts/hello-webassembly-c.md b/content/posts/hello-webassembly-c.md index 2e999d0..a127d78 100644 --- a/content/posts/hello-webassembly-c.md +++ b/content/posts/hello-webassembly-c.md @@ -5,17 +5,15 @@ draft: false tags: ["WebAssembly", "C", "C++", "Emscripten"] --- -If you've spent any time working on performance-critical web applications, you've probably hit the performance ceiling of JavaScript. I ran into this heavily during my Google Summer of Code project working on Chromium's audio processing pipeline. We needed near-native speeds to process audio without stuttering, and standard JavaScript just wasn't going to cut it. +If you've spent any time working on performance-critical web applications, you've probably hit the performance ceiling of JavaScript. I ran into this heavily during my Google Summer of Code project working on Chromium's audio processing pipeline. We needed near-native speeds to process audio buffers without dropping frames, and standard JavaScript just wasn't going to cut it. -Enter **WebAssembly** (Wasm). +That's where **WebAssembly** (Wasm) comes in. It's a low-level bytecode format designed to run inside the browser sandbox at near-native speeds. It lets you write performance-sensitive routines in C, C++, or Rust, compile them to a `.wasm` module, and call them directly from your JavaScript frontend. -WebAssembly is essentially a low-level binary format that runs directly in the browser at near-native speeds. It lets us write code in systems languages like C, C++, or Rust, compile it, and run it right alongside our JavaScript. +Here's a minimal walkthrough of taking a plain C program, compiling it to Wasm, and running it in a browser. -Today, I want to walk you through the absolute basics: taking a simple C program and running it in your browser. +## The Toolchain: Emscripten -## The Magic Tool: Emscripten - -To bridge the gap between C/C++ and the web, we need a toolchain. The undisputed heavyweight champion here is **Emscripten**. It takes your C/C++ code, compiles it into a `.wasm` binary, and even generates the JavaScript "glue" code needed to load it into the browser. +To compile C or C++ targeting the web, you need an LLVM toolchain that outputs WebAssembly instead of native x86/ARM machine code. The standard toolchain for this is **Emscripten**. It takes your C/C++ source, compiles it into a `.wasm` binary, and generates the JavaScript loader code that allocates memory and boots up the module. Let's get it installed. Open your terminal and run: @@ -77,8 +75,8 @@ Now, open your browser and head to `http://localhost:8000/hello.html`. If everyt ## Wrapping up -This is obviously just the tip of the iceberg. Printing a string is fun, but the real power of WebAssembly comes from porting massive C++ codebases (like audio engines, physics simulators, or databases) directly into the browser. +This is obviously just the tip of the iceberg. Printing a string is fun, but the real power of WebAssembly comes from porting real C++ codebases (like game engines, audio processors, or physics simulators) directly into the browser. -In future posts, I'll dive into more realistic use cases—like how I used Wasm and WebWorkers to build lock-free ring buffers for Chromium, passing complex memory structures back and forth between JavaScript and C++. +If you want to see a full interactive project in action, check out my follow-up post on [Porting a C++ Snake Game to the Browser with WebAssembly](/posts/snake-game-in-cpp-and-webassembly/). Until then, happy hacking! diff --git a/content/posts/i-built-a-chip8-emulator-in-javascript.md b/content/posts/i-built-a-chip8-emulator-in-javascript.md new file mode 100644 index 0000000..498cfee --- /dev/null +++ b/content/posts/i-built-a-chip8-emulator-in-javascript.md @@ -0,0 +1,149 @@ +--- +title: "I Built a CHIP-8 Emulator in JavaScript" +date: 2024-03-15T10:00:00Z +draft: false +tags: ["JavaScript", "Emulators", "Canvas", "WebAudio"] +--- + +If you've ever wanted to understand how computers actually work — not the "how to center a div" kind, but the "how does a CPU fetch and execute instructions" kind — building an emulator is one of the best ways to do it. + +A while back I built a [CHIP-8 emulator](https://github.com/ahujadivyam/chip_eight.js) in vanilla JavaScript. No frameworks, no build tools, no npm install. Just the browser's Canvas API, Web Audio API, and a few hundred lines of code pretending to be a computer from 1977. + +## What's a CHIP-8? + +CHIP-8 is an interpreted programming language from the mid-1970s, originally designed for hobbyist microcomputers like the COSMAC VIP. It's not a real CPU — it's more like a virtual machine spec. But it has all the things that make a real system interesting: memory, registers, a stack, timers, input, graphics, and sound. + +It's also the "hello world" of emulator development. The instruction set is small (35 opcodes), the display is tiny (64×32 pixels), and there's a massive community of ROMs and documentation. If you can emulate CHIP-8, you'll have the foundation to tackle Game Boy, NES, or anything else. + +## The Architecture + +Here's what you're emulating: + +- **4KB of RAM** — that's it. The entire address space is `0x000` to `0xFFF`. +- **16 general-purpose 8-bit registers** (V0–VF). VF doubles as a flag register. +- **A 16-bit index register (I)** for pointing at memory locations. +- **A program counter (PC)** that starts at `0x200` — because the first 512 bytes are reserved for the interpreter itself (and the built-in font sprites). +- **A stack** for subroutine return addresses (16 levels deep). +- **Two timers** — a delay timer and a sound timer, both counting down at 60Hz. +- **A 16-key hex keypad** for input. +- **A 64×32 monochrome display** where pixels are either on or off. + +I modeled each of these as a separate JavaScript class: `CPU`, `Renderer`, `Keyboard`, and `Speaker`. Clean separation of concerns, and it makes the code easy to reason about. + +## The Core Loop + +The CPU instruction cycle is straightforward: every tick, you fetch, decode, and execute. + +Because CHIP-8 opcodes are two bytes long (big-endian), fetching means grabbing two consecutive bytes from memory at the current program counter and combining them into a 16-bit number: + +```javascript +let opcode = (this.memory[this.pc] << 8) | this.memory[this.pc + 1]; +this.pc += 2; +``` + +Decoding is just bit-masking. The highest 4 bits tell you the instruction category, and the remaining 12 bits hold register indices or memory offsets: + +```javascript +let x = (opcode & 0x0F00) >> 8; // register index +let y = (opcode & 0x00F0) >> 4; // register index +let nn = opcode & 0x00FF; // 8-bit constant +let nnn = opcode & 0x0FFF; // 12-bit address +``` + +Execution is a switch statement. `6XNN` sets register `Vx = nn`. `1NNN` sets `PC = nnn`. `DXYN` draws a sprite. If the sound timer is greater than zero, you buzz the speaker. That's essentially it. + +## Drawing Sprites + +The most interesting opcode is `DXYN` — the draw instruction. CHIP-8 graphics are XOR-based. You don't "set" pixels, you *toggle* them. + +Each sprite is 8 pixels wide and N pixels tall. The sprite data lives in memory at whatever address the I register points to. Each byte represents one row of 8 pixels, where each bit is a pixel: + +```javascript +for (let row = 0; row < height; row++) { + let spriteByte = this.memory[this.I + row]; + for (let col = 0; col < 8; col++) { + if (spriteByte & (0x80 >> col)) { + let px = (x + col) % 64; + let py = (y + row) % 32; + // Toggle pixel — if it was ON and gets turned OFF, set VF = 1 + if (this.display[py * 64 + px]) { + this.registers[0xF] = 1; // collision! + } + this.display[py * 64 + px] ^= 1; + } + } +} +``` + +That VF collision flag is how games detect when things hit each other. Pong uses it to know when the ball hits a paddle. It's elegant — one bit of state doing the job of a physics engine. + +The display buffer is a flat array of 2048 values (64 × 32). Each frame, I iterate over it and draw scaled-up rectangles on an HTML5 Canvas: + +```javascript +render() { + this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height); + for (let i = 0; i < this.display.length; i++) { + if (this.display[i]) { + let x = (i % 64) * this.scale; + let y = Math.floor(i / 64) * this.scale; + this.ctx.fillRect(x, y, this.scale, this.scale); + } + } +} +``` + +At 10× scale, you get a nice chunky 640×320 canvas that looks properly retro. + +## The Keyboard Problem + +CHIP-8 has a 16-key hex keypad (0–F). Obviously we don't have one of those lying around, so I mapped it to a 4×4 grid on a QWERTY keyboard: + +``` +CHIP-8 Keypad Keyboard +┌───┬───┬───┬───┐ ┌───┬───┬───┬───┐ +│ 1 │ 2 │ 3 │ C │ │ 1 │ 2 │ 3 │ 4 │ +├───┼───┼───┼───┤ ├───┼───┼───┼───┤ +│ 4 │ 5 │ 6 │ D │ │ Q │ W │ E │ R │ +├───┼───┼───┼───┤ ├───┼───┼───┼───┤ +│ 7 │ 8 │ 9 │ E │ │ A │ S │ D │ F │ +├───┼───┼───┼───┤ ├───┼───┼───┼───┤ +│ A │ 0 │ B │ F │ │ Z │ X │ C │ V │ +└───┴───┴───┴───┘ └───┴───┴───┴───┘ +``` + +One interesting edge case: the `FX0A` instruction. It's a *blocking* key wait — the CPU literally halts until the user presses a key. In a real system that's just a busy loop. In JavaScript, you can't block the main thread (and you shouldn't), so I used a callback pattern. When the CPU hits `FX0A`, it registers an `onNextKeyPress` callback and stops cycling. When a keydown event fires, the callback resolves, stores the key in the target register, and the CPU resumes. + +## Sound + +CHIP-8 sound is delightfully simple. There's one sound: a buzzer. It plays when the sound timer is greater than zero. + +I used the Web Audio API to create a square wave oscillator at 440Hz — a nice harsh beep that feels appropriately retro. The only tricky part is dealing with browser autoplay policies: you can't start an `AudioContext` without user interaction, so the first keypress initializes the audio. + +## The Game Loop + +Everything comes together in a `requestAnimationFrame` loop: + +```javascript +function step() { + for (let i = 0; i < 10; i++) { + cpu.cycle(); + } + renderer.render(); + requestAnimationFrame(step); +} +``` + +Running ~10 CPU cycles per frame at 60fps gives you roughly 600 instructions per second, which is in the ballpark of original CHIP-8 speed. ROMs load via the Fetch API as `ArrayBuffer`, get written into memory starting at `0x200`, and away you go. + +Pong, Space Invaders, Tetris, Breakout — they all just work. + +## Why Build This + +I won't pretend this is useful software. Nobody needs another CHIP-8 emulator. But that's not the point. + +The point is that after building this, I understood things I'd only read about before: how program counters work, why instructions are fixed-width, how XOR collision detection works, what "memory-mapped I/O" actually means in practice. You read about fetch-decode-execute in a textbook and it's abstract. You implement it and it clicks. + +If you're into systems programming and want a weekend project that'll teach you more about machine architecture than a month of tutorials, build one yourself. Cowgod's [CHIP-8 technical reference](http://devernay.free.fr/hacks/chip8/C8TECH10.HTM) is the canonical spec and has everything you need. + +The full code is on GitHub: [github.com/ahujadivyam/chip_eight.js](https://github.com/ahujadivyam/chip_eight.js) + diff --git a/content/posts/networking-part-1-the-osi-model.md b/content/posts/networking-part-1-the-osi-model.md index 5c9518a..2a5baed 100644 --- a/content/posts/networking-part-1-the-osi-model.md +++ b/content/posts/networking-part-1-the-osi-model.md @@ -1,12 +1,11 @@ --- -title: "Networking Part 1: Why We Need Rules (and the OSI Model)" -date: 2026-05-10T10:00:00Z +title: "Demystifying Networking: The OSI Model from a Developer's Perspective" +date: 2024-01-10T10:00:00Z draft: false tags: ["Networking", "OSI Model", "Fundamentals"] -series: ["Networking Fundamentals"] --- -Computer networking is often taught in the most dry, academic way possible. You're immediately thrown a diagram with seven colored boxes (the OSI model) and told to memorize them for a test. +Computer networking is often taught in the most dry, academic way possible. You're immediately thrown a diagram with seven colored boxes (the OSI model) and told to memorize them for an exam. But if you actually build software, understanding *why* networks work the way they do changes how you write code. It changes how you debug timeouts, why you pick UDP over TCP for streaming, and why certain architectures scale while others crash under load. @@ -27,28 +26,29 @@ If *any* of those layers break—if we're in a vacuum, if I speak Russian and yo Computers face the exact same problem, but they are infinitely dumber than we are. They need explicit, rigidly defined rules for every single step of communication. These rules are called **protocols**. -## The Stack of Rules (The OSI Model) +## The Seven Layers (and the Three You Actually Care About) -When a computer engineers in the 1970s and 80s were trying to get computers from different manufacturers to talk to each other, it was a nightmare. IBM computers couldn't talk to DEC computers because they didn't agree on the "language." +In textbooks, you're taught all seven layers: -To fix this, the International Organization for Standardization (ISO) created a theoretical framework called the **OSI (Open Systems Interconnection) Model**. It breaks the massive problem of "getting a piece of data from Computer A to Computer B" into seven distinct, manageable layers. +1. **Physical:** Bits on a wire, fiber pulse, or radio wave. +2. **Data Link:** Ethernet frames, MAC addresses, local switches. +3. **Network:** IP packets, routing, subnets. +4. **Transport:** TCP, UDP, port numbers. +5. **Session:** Session management (rarely distinct in modern protocols). +6. **Presentation:** Serialization, encoding, TLS (now handled at the app level). +7. **Application:** HTTP, DNS, SSH, and the code you write. -Here they are, from the physical hardware up to the software you write: +In practice, almost nobody distinguishes layers 5 and 6 anymore—the practical internet collapsed them into the application layer decades ago. But engineers still use the OSI numbers as universal shorthand: -1. **Physical Layer:** How do we send raw 1s and 0s over a wire, fiber optic cable, or radio wave? (Voltage levels, light pulses). -2. **Data Link Layer:** How do two devices directly connected on the same physical network talk without talking over each other? (MAC addresses, Ethernet). -3. **Network Layer:** How do we send a message to a computer on a *completely different* network on the other side of the world? (IP addresses, Routers). -4. **Transport Layer:** How do we make sure the message actually arrived, and if it broke into pieces, how do we put it back together? (TCP, UDP). -5. **Session Layer:** How do we maintain an ongoing "conversation" between two computers? -6. **Presentation Layer:** How is the data formatted or encrypted? (ASCII, JPEG, TLS). -7. **Application Layer:** What is the actual software trying to do? (HTTP for web browsing, SMTP for email). +- **Layer 3 (Network):** Can packets find their way from machine A to machine B? When your cloud VPC routing table is misconfigured or an MTU mismatch drops packets silently, that's an L3 problem. +- **Layer 4 (Transport):** Are connections establishing and staying alive? When someone talks about an "L4 load balancer," they mean routing raw TCP connections based on IP and port without decrypting or parsing the payload. +- **Layer 7 (Application):** What does the data actually say? An "L7 load balancer" terminates TLS, inspects HTTP headers or path prefixes, and routes `/api` to one cluster and `/static` to an S3 bucket. -### Why do we care? +## Why Leaky Abstractions Matter -You might look at that list and think, *"I'm a web developer, I only care about Layer 7 (HTTP)."* +You might spend 99% of your time writing application code at Layer 7. But networking abstractions are notoriously leaky: -But abstraction is a leaky bucket. When your API call drops, is it a Layer 7 problem (your server returned a 500 error)? Is it a Layer 4 problem (the TCP connection timed out)? Or is it a Layer 3 problem (the router dropped the packet because of a bad subnet configuration)? +- When an API request hangs for exactly 30 seconds, is it an application deadlock (L7), an unhandled timeout on a pool of sockets (L4), or a firewall silently dropping packets rather than rejecting them (L3)? +- When connections randomly reset under heavy traffic, did your backend crash, or did an intermediate NAT gateway run out of connection tracking table entries? -Knowing how the layers stack on top of each other turns networking from "black magic" into a logical, debuggable system. - -In the next part of this series, we're going to dive into the bottom of the stack: **Layers 1 and 2**. We'll look at how your computer actually blasts electricity down an Ethernet cable to talk to your local router. +Having a concrete mental model of the stack changes how you debug. You stop randomly restarting pods or tweaking application timeouts, and you start isolating the specific layer where the failure is actually happening. diff --git a/content/posts/networking-part-2-physical-and-data-link.md b/content/posts/networking-part-2-physical-and-data-link.md deleted file mode 100644 index 4d0428b..0000000 --- a/content/posts/networking-part-2-physical-and-data-link.md +++ /dev/null @@ -1,9 +0,0 @@ ---- -title: "Networking Part 2: Sending Electrons over Wires (Physical & Data Link)" -date: 2026-05-11T10:00:00Z -draft: false -tags: ["Networking", "Ethernet", "MAC"] -series: ["Networking Fundamentals"] ---- - -*Coming soon! In this post, we will cover MAC addresses, switches, Ethernet frames, and how electrons physically move data from NIC to NIC.* diff --git a/content/posts/networking-part-3-the-network-layer.md b/content/posts/networking-part-3-the-network-layer.md deleted file mode 100644 index eab1fe4..0000000 --- a/content/posts/networking-part-3-the-network-layer.md +++ /dev/null @@ -1,9 +0,0 @@ ---- -title: "Networking Part 3: Crossing the Internet (The Network Layer)" -date: 2026-05-12T10:00:00Z -draft: false -tags: ["Networking", "IP", "Routing", "Subnets"] -series: ["Networking Fundamentals"] ---- - -*Coming soon! In this post, we will cover IP addresses, routers, subnets, and how packets travel across the global internet using BGP.* diff --git a/content/posts/networking-part-4-transport-and-application.md b/content/posts/networking-part-4-transport-and-application.md deleted file mode 100644 index d9bd51f..0000000 --- a/content/posts/networking-part-4-transport-and-application.md +++ /dev/null @@ -1,9 +0,0 @@ ---- -title: "Networking Part 4: Delivering the Payload (Transport & Application)" -date: 2026-05-13T10:00:00Z -draft: false -tags: ["Networking", "TCP", "UDP", "HTTP"] -series: ["Networking Fundamentals"] ---- - -*Coming soon! In this post, we will cover TCP vs UDP, ports, and how the applications we write (like HTTP or WebSockets) actually consume this data.* diff --git a/content/posts/snake-game-in-cpp-and-webassembly.md b/content/posts/snake-game-in-cpp-and-webassembly.md new file mode 100644 index 0000000..673e35b --- /dev/null +++ b/content/posts/snake-game-in-cpp-and-webassembly.md @@ -0,0 +1,152 @@ +--- +title: "Running a C++ Snake Game in the Browser with WebAssembly" +date: 2024-06-20T10:00:00Z +draft: false +tags: ["WebAssembly", "C++", "GameDev", "Emscripten"] +--- + +Compiling "hello world" from C to WebAssembly is fun for five minutes, but printing text to an emulated terminal doesn't really tell you what it feels like to build something interactive in Wasm. + +I wanted to see what happens when you take real desktop C++ game code and shove it into a browser tab. So I built [snake_wasm](https://github.com/ahujadivyam/snake_wasm)—a classic Snake clone written in C++17 using `olcPixelGameEngine`, compiled via Emscripten into a `.wasm` binary that draws directly to an HTML5 canvas at 60 fps. No JavaScript game logic, no hand-written canvas glue. + +Here are the parts of the build that were actually interesting to solve. + +## The Engine: olcPixelGameEngine + +If you've ever set up a C++ graphics project from scratch, you know how annoying dependency management can get. Linking SDL2 or GLFW, hunting down OpenGL loaders, and fighting CMake configurations across OSes gets old fast. + +For this, I used **olcPixelGameEngine** (by David Barr / Javidx9). It's an entire 2D game engine packed into a single header file (`olcPixelGameEngine.h`). You `#define OLC_PGE_APPLICATION`, include the header in one `.cpp` file, and you get windowing, keyboard polling, and primitive drawing without installing ten different system packages: + +```cpp +#define OLC_PGE_APPLICATION +#include "olcPixelGameEngine.h" + +class Snake : public olc::PixelGameEngine { +public: + Snake() { + sAppName = "Snake WASM"; + } + + bool OnUserCreate() override { + ResetGame(); + return true; + } + + bool OnUserUpdate(float fElapsedTime) override { + HandleInput(); + UpdateState(fElapsedTime); + Render(); + return true; + } +}; +``` + +You inherit from `olc::PixelGameEngine`, override `OnUserCreate()` for initialization and `OnUserUpdate()` for your frame step, and that's the whole harness. Even better: PGE has built-in support for Emscripten. + +## Why Your Desktop Game Loop Freezes the Browser + +On desktop, your game owns the thread. You typically write a blocking `while` loop that runs until the user closes the window: + +```cpp +// Works on desktop. Freezes your browser tab instantly. +while (bGameRunning) { + ProcessInput(); + UpdatePhysics(); + RenderFrame(); +} +``` + +If you compile that loop straight to WebAssembly, your browser tab dies immediately. + +Browsers are single-threaded and event-driven. If your WASM module sits in a tight `while(true)` loop, execution never returns to the browser's JavaScript engine. That means the browser can't process DOM events, can't repaint the canvas, and can't even close the tab cleanly. + +To make C++ play nice with the browser, you have to hand control back to the browser on every single frame. Emscripten does this through `emscripten_set_main_loop()`: + +```cpp +#ifdef __EMSCRIPTEN__ +#include + +void MainLoop() { + game.Step(); +} + +int main() { + emscripten_set_main_loop(MainLoop, 0, 1); + return 0; +} +#endif +``` + +Passing `0` as the frame rate tells Emscripten to hook directly into the browser's `requestAnimationFrame` loop. Each time the screen is ready to paint (~60 times a second on a standard display), the browser calls your C++ frame step, lets you update positions and draw pixels, and then immediately reclaims the thread to do the actual layout and render. + +PGE wraps this internally when compiling with `-s __EMSCRIPTEN__`, but understanding *why* you can't have an infinite loop in Wasm saves a lot of head-scratching when porting desktop code. + +## A Couple of Annoying Bugs Worth Mentioning + +### The 180-Degree Neck Snap +If you store the player's direction and update it immediately on keypress, you run into a classic Snake bug: +Suppose the snake is moving **Right**. The player quickly taps **Up**, then **Left** before the next game tick fires. Both key events process, so `dir` becomes `Left`. The game tick fires, the snake tries to move left into its own neck, and you die instantly. + +The fix is buffering the desired direction and only committing it when the logical game tick advances: + +```cpp +// In HandleInput(): +if (GetKey(olc::Key::UP).bPressed && currentDir != DOWN) nextDir = UP; +if (GetKey(olc::Key::LEFT).bPressed && currentDir != RIGHT) nextDir = LEFT; + +// In TickGameLogic(): +currentDir = nextDir; +``` + +### Tick Rate vs. Refresh Rate +Your monitor might refresh at 60Hz, 120Hz, or 144Hz. If you advance the snake's position on every `OnUserUpdate()`, the game runs at twice the speed on a high-refresh monitor. + +You have to decouple drawing from game logic by accumulating elapsed time: + +```cpp +fSnakeTimer += fElapsedTime; +if (fSnakeTimer >= fSnakeSpeed) { // e.g. 0.12s per grid step + fSnakeTimer -= fSnakeSpeed; + TickGameLogic(); +} +``` + +The game renders at the monitor's native framerate, but the snake only moves once every 120ms. + +## How C++ Pixels Actually Reach the Canvas + +When you call `FillRect()` or `Draw()` in PGE, how does that reach an HTML ``? + +1. PGE translates the draw call into standard OpenGL ES 2.0/3.0 commands. +2. Emscripten's runtime intercepts those GLES calls and translates them 1:1 into browser **WebGL 2** calls. +3. The browser passes the WebGL commands directly to your GPU. + +So you aren't manually poking an array of RGBA bytes across the WASM boundary into an HTML canvas context. The graphics pipeline is hardware-accelerated the whole way through. + +## The Emscripten Build Command + +Here is the compiler invocation that puts it all together: + +```bash +em++ -std=c++17 -O2 \ + -s ALLOW_MEMORY_GROWTH=1 \ + -s MAX_WEBGL_VERSION=2 \ + -s MIN_WEBGL_VERSION=2 \ + main.cpp \ + -o snake.html +``` + +A few flags that matter: +- `-s ALLOW_MEMORY_GROWTH=1`: Emscripten allocates a fixed 16MB heap by default. If your heap usage exceeds that, the app crashes with an out-of-memory error. This flag lets the linear memory page expand dynamically. +- `-s MAX_WEBGL_VERSION=2 -s MIN_WEBGL_VERSION=2`: Forces Emscripten to target WebGL 2 exclusively, stripping out old WebGL 1 fallback glue. +- `-o snake.html`: Emscripten generates `snake.wasm`, `snake.js` (the loader runtime), and a default HTML shell containing the ``. + +Start a quick static server: + +```bash +python3 -m http.server +``` + +Open `localhost:8000/snake.html`, and you have a native C++ binary running inside a browser tab. + +The full source is on GitHub: [github.com/ahujadivyam/snake_wasm](https://github.com/ahujadivyam/snake_wasm)