latentspace.

WASM


  • What is WebAssembly (WASM)
    • A binary instruction format that runs near-native-speed code in web browsers
    • Not a programming language — a compilation target for C, C++, Rust, Go, etc.
    • Runs in a sandboxed VM alongside JavaScript — W3C standard, all modern browsers
    • Also runs outside browsers — Cloudflare Workers, Node.js, Deno

  • Why WASM
    • Performance: near-native speed for compute-heavy tasks
    • Code reuse: bring existing C/C++ libraries to the web without rewriting in JS
    • Portability: compile once, run anywhere that supports WASM

  • How it works
    • C/C++ source → compiled to .wasm binary via Emscripten
    • Emscripten also generates a JS glue file (.js) that handles loading and binding
    • Browser fetches and instantiates the .wasm, exported functions become callable from JS
    • JS and WASM share a linear memory (ArrayBuffer) — data is copied into/out of this memory

  • Emscripten & Embind
    • Emscripten: the most widely used C/C++ → WASM compiler toolchain
    • Compile with emcc (C/C++) or em++ (forces C++ mode), produces .js (glue) + .wasm (binary)
    • Embind: Emscripten's binding system that maps C++ functions, structs, and types to JavaScript
    • After compilation, JS can call C++ functions as if they were native JS functions

  • Memory management
    • Embind objects live on the WASM heap, not managed by JS garbage collector
    • Must call .delete() on Embind class instances — forgetting causes memory leaks
    • WASM heap grows dynamically but never shrinks

  • Practical example: Instant Meshes as WASM
    • Instant Meshes — C++ tool for field-aligned quad-dominant remeshing, compiled to WASM (~485 KB)
    • Why WASM over rewriting in TS: research-grade algorithm, complex numerics, hard to validate a from-scratch port
    • Key decisions:
      • Single-threaded: TBB replaced with a shim — avoids SharedArrayBuffer / pthreads
      • No file I/O: stubbed out since WASM has no filesystem
      • Pinned versions: Emscripten, source commit, Eigen all pinned for reproducible builds

    • WASM
      Instant Meshes quad remeshing via WASM


  • Limitations
    • No DOM access — must call back to JS for browser APIs
    • No threads by default — requires SharedArrayBuffer + COOP/COEP headers
    • No filesystem — file I/O must be stubbed or use Emscripten's virtual FS
    • Debugging — Chrome DevTools supports WASM debugging via DWARF debug info, but limited compared to JS