Browse Source

Got a basic image drawing program working

master
Thomas Johnson 1 year ago
commit
881dd4a55e
  1. 4
      .cargo/config
  2. 2
      .gitignore
  3. 14
      Cargo.toml
  4. 8
      index.html
  5. 38
      index.js
  6. 52
      src/lib.rs
  7. 1
      wt.wasm

4
.cargo/config

@ -0,0 +1,4 @@
[build]
target = "wasm32-unknown-unknown"

2
.gitignore

@ -0,0 +1,2 @@
/target
Cargo.lock

14
Cargo.toml

@ -0,0 +1,14 @@
[package]
name = "wt"
version = "0.1.0"
authors = ["thajohns <thajohns@clarkson.edu>"]
edition = "2018"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
wee_alloc = "0.4.5"
#wasm-bindgen = "0.2.59"
[lib]
crate-type = ["cdylib"]

8
index.html

@ -0,0 +1,8 @@
<html>
<head>
<script defer src="index.js"></script>
</head>
<body id="body">
<canvas id="canvas" height=1000 width=1500></canvas>
</body>
</html>

38
index.js

@ -0,0 +1,38 @@
canvas = document.getElementById("canvas");
ctx = canvas.getContext("2d");
function get_string(memory, pointer, size)
{
var array = new Int8Array(memory.buffer, pointer, size);
return (new TextDecoder()).decode(array);
}
function paint(memory, pointer, width, height)
{
array = new Uint8ClampedArray(memory.buffer, pointer, 4 * width * height);
data = new ImageData(array, width, height);
ctx.putImageData(data, 0, 0);
}
fetch("wt.wasm").then(response => response.arrayBuffer()).then(bytes =>
{
var memory;
WebAssembly.instantiate(bytes, { env:
{
console_log: function(str, len)
{
console.log(get_string(memory, str, len));
},
extern_paint: function(pointer, width, height)
{
paint(memory, pointer, width, height);
}
} }).then(mod =>
{
memory = mod.instance.exports.memory;
mod.instance.exports.entrypoint();
mod.instance.exports.paint_red(canvas.width, canvas.height);
}
)
});

52
src/lib.rs

@ -0,0 +1,52 @@
extern crate wee_alloc;
use core::mem::transmute;
#[global_allocator]
pub static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeAlloc::INIT;
extern "C"
{
#[no_mangle]
fn console_log(_: *const u8, _: usize);
#[no_mangle]
fn extern_paint(ptr: *const u8, w: usize, h: usize);
}
fn log(string: &str)
{
unsafe
{
let (ptr, size) = transmute::<_, (*const u8, usize)>(string);
console_log(ptr, size);
}
}
fn paint(buffer: &[u8], w: usize, h: usize)
{
unsafe { extern_paint(buffer.as_ptr(), w, h); }
}
#[no_mangle]
pub extern "C" fn entrypoint()
{
log("Test from Rust");
}
#[no_mangle]
pub extern "C" fn paint_red(w: usize, h: usize)
{
let mut buffer = vec![0; 4 * w * h];
let mut c: (u8, u8, u8) = (0, 0, 0);
for ii in 0 .. w * h
{
buffer[4 * ii] = c.0;
buffer[4 * ii + 1] = c.1;
buffer[4 * ii + 2] = c.2;
buffer[4 * ii + 3] = 255;
c = (c.0.wrapping_add(1), c.1.wrapping_add(254), c.2.wrapping_add(2));
}
paint(&buffer, w, h);
}

1
wt.wasm

@ -0,0 +1 @@
/home/primary/rust/dabble/webasm/target/wasm32-unknown-unknown/debug/wt.wasm
Loading…
Cancel
Save