Browse Source

First World BNG support in the Browser

rexim 5 years ago
parent
commit
8bc673f476
4 changed files with 24 additions and 8 deletions
  1. 3 3
      2020-09-04/README.md
  2. 1 0
      2020-09-04/bng.html
  3. 7 1
      2020-09-04/bng.js
  4. 13 4
      2020-09-04/bng.wat

+ 3 - 3
2020-09-04/README.md

@@ -33,7 +33,7 @@
   - [ ] If we implement the image support in WASM can we make it feel like a native browser support
     - [x] [Implement png2bng](./png2bng.c)
     - [x] [Implement bngviewer](./bngviewer.c)
-    - [ ] Implement bng support in WASM
+    - [x] Implement bng support in WASM
       - [x] fetch("tsodinw.bng"):
         ```js
           fetch("./tsodinw.bng").then((x) => console.log(x.arrayBuffer()))
@@ -45,6 +45,6 @@
           let memory = new WebAssembly.Memory({initial: 10, maximum: 10});
           new Uint8Array(memory.buffer).set(new Uint8Array(fileData));
         ```
-      - [ ] Call a WASM function that turns the file into Image Data
-      - [ ] Take out the Image Data from WASM memory and display it
+      - [x] Call a WASM function that turns the file into Image Data
+      - [x] Take out the Image Data from WASM memory and display it
     - [ ] Add more interesting features to bng to test the support

+ 1 - 0
2020-09-04/bng.html

@@ -4,6 +4,7 @@
     <title>The First Website that support BNG natively Pog</title>
   </head>
   <body>
+    <canvas id="bng"></canvas>
     <script src='./bng.js'></script>
   </body>
 </html>

+ 7 - 1
2020-09-04/bng.js

@@ -6,7 +6,13 @@ async function bng() {
     let bngProgram = await WebAssembly.instantiateStreaming(
         fetch("bng.wasm"),
         { js: { mem: memory, print: arg => console.log(arg) } });
-    bngProgram.instance.exports.bng();
+    let size = bngProgram.instance.exports.bng_size();
+    let width = bngProgram.instance.exports.bng_width();
+    let height = bngProgram.instance.exports.bng_height();
+    let imageData = new ImageData(new Uint8ClampedArray(memory.buffer).slice(12, 12 + size), width, height);
+    let canvas = document.querySelector("#bng");
+    let context = canvas.getContext("2d");
+    context.putImageData(imageData, 0, 0);
 }
 
 bng().catch((e) => console.log(e));

+ 13 - 4
2020-09-04/bng.wat

@@ -1,7 +1,16 @@
 (module
  (memory (import "js" "mem") 1)
  (func $print (import "js" "print") (param i32))
- (func (export "bng")
-       (call $print (i32.load (i32.const 0)))
-       (call $print (i32.load (i32.const 4)))
-       (call $print (i32.load (i32.const 8)))))
+ (func (export "bng_size")
+       (result i32)
+       (i32.mul
+        (i32.mul
+         (i32.load (i32.const 4))
+         (i32.load (i32.const 8)))
+        (i32.const 4)))
+ (func (export "bng_width")
+       (result i32)
+       (i32.load (i32.const 4)))
+  (func (export "bng_height")
+       (result i32)
+       (i32.load (i32.const 8))))