K-means Example

At this point, the guide transitions from a step by step tutorial to a high level overview of the source code demonstrating how the website was implemented. The demo portion of the website allows users to apply the k-means clustering algorithm to an image. The algorithm gives the resulting image a softened, painted look.

See the repositories Readme for instructions on building and running the project.

General Project Structure

The src directory of the-rusty-web project contains Rust source code and the website directory contains JavaScript source code. Ams.js or WebAssembly libraries are copied from the target directory (which is created after building the Rust code) into the website/dist directory. The website/dist directory contains all the necessary resources for serving the website.

Cargo Config

There are a few new parameters in this .cargo/config file:

  • -s EXPORT_NAME='AsmjsModuleInitializer'- the variable name which contains the asm.js export
  • -s MODULARIZE=1- export a function which creates an asm.js module opposed to exporting the module directly
  • -s ALLOW_MEMORY_GROWTH=1- allow the heap size of the asm.js module to grow

We do something similar for the WebAssembly target, but we do not use the -s MODULARIZE=1 flag.

K-means Clustering Algorithm

There are two implementations of the k-means clustering algorithm a Rust version and a JavaScript version. The k-means algorithm represents the CPU intensive portion of the webapp. I tried to keep the implementations of the algorithm as similar, yet idiomatic, as possible to present a fair comparison.

Painters

Painters provide an API for taking raw image data and painting it using the k-means algorithm. The raw image data is represented as a one dimensional Vector (Rust) or Array (JavaScript) of size image_width * image_height * 4. The 4 represents the four channels of a pixel: red, blue, green, and alpha.

The Rust implementation of a painter exposes itself through a series of FFI definitions in main.rs.

There are a total of three painters used by the webapp: a JavaScript wrapper around the asm.js library, a JavaScript wrapper around the WebAssembly library, and a native JavaScript version.

Putting it All Together

module.js is responsible for setting up the asm.js module (AsmjsModule) and the WebAssembly module (WasmModule). index.js uses these modules, the three painters, and image_memory.js.

results matching ""

    No results matching ""