004 Web Assembly康威遊戲之最佳化

linghuyichong發表於2021-08-23

影片地址:www.bilibili.com/video/BV1eg411g7c...
相關原始碼:github.com/anonymousGiga/Rust-and-...

在上一節的實現中,我們是在Rust中實現了填充的內容,然後讓wasm bindgen轉換為一個有效的js字串,這樣就產生了不必要的副本。因為js程式碼已經知道宇宙的寬度和高度,因此可以直接讀取構成cell的web assembly記憶體。另外我們將切換到Canvas API,而不是直接使用unicode文字。

本節直接上一節的內容之上進行修改。

在wasm-game-of-life/www/index.html中的body標籤內容修改為如下:

<body>
  <!--canvas標籤是表示影像或圖表-->
  <canvas id="game-of-life-canvas"></canvas>
  <script src='./bootstrap.js'></script>
</body>

接下來,我們在wasm-game-of-life/src/lib.rs中新增如下程式碼:


#![allow(unused_variables)]
fn main() {
/// Public methods, exported to JavaScript.
#[wasm_bindgen]
impl Universe {
    // ...

    pub fn width(&self) -> u32 {
        self.width
    }

    pub fn height(&self) -> u32 {
        self.height
    }

    pub fn cells(&self) -> *const Cell {
        self.cells.as_ptr()
    }
}
}

修改wasm-game-of-life/www/index.js中的程式碼如下:

//import { Universe } from "wasm-game-of-life";
import { Universe, Cell } from "wasm-game-of-life";
import { memory } from "wasm-game-of-life/wasm_game_of_life_bg";

const CELL_SIZE = 5; // px
const GRID_COLOR = "#CCCCCC";
const DEAD_COLOR = "#FFFFFF";
const ALIVE_COLOR = "#000000";

const universe = Universe.new();
const width = universe.width();
const height = universe.height();

const canvas = document.getElementById("game-of-life-canvas");
canvas.height = (CELL_SIZE + 1) * height + 1;
canvas.width = (CELL_SIZE + 1) * width + 1;

const ctx = canvas.getContext('2d');

function renderLoop() {
  universe.tick();

  drawGrid();
  drawCells();

  window.requestAnimationFrame(renderLoop);
}

function drawGrid() {
  ctx.beginPath();
  ctx.strokeStyle = GRID_COLOR;

  // Vertical lines.
  for (let i = 0; i <= width; i++) {
    ctx.moveTo(i * (CELL_SIZE + 1) + 1, 0);
    ctx.lineTo(i * (CELL_SIZE + 1) + 1, (CELL_SIZE + 1) * height + 1);
  }

  // Horizontal lines.
  for (let j = 0; j <= height; j++) {
    ctx.moveTo(0,                           j * (CELL_SIZE + 1) + 1);
    ctx.lineTo((CELL_SIZE + 1) * width + 1, j * (CELL_SIZE + 1) + 1);
  }

  ctx.stroke();
}

function getIndex(row, column) {
  return row * width + column;
}

function drawCells() {
  const cellsPtr = universe.cells();
  const cells = new Uint8Array(memory.buffer, cellsPtr, width * height);

  ctx.beginPath();

  for (let row = 0; row < height; row++) {
    for (let col = 0; col < width; col++) {
      const idx = getIndex(row, col);

      ctx.fillStyle = cells[idx] === Cell.Dead
        ? DEAD_COLOR
        : ALIVE_COLOR;

      ctx.fillRect(
        col * (CELL_SIZE + 1) + 1,
        row * (CELL_SIZE + 1) + 1,
        CELL_SIZE,
        CELL_SIZE
      );
    }
  }

  ctx.stroke();
}

window.requestAnimationFrame(renderLoop);

在wasm-game-of-life目錄下執行:

wasm-pack build

編譯rust程式碼。

在wasm-game-of-life/www目錄下執行:

npm run start

在瀏覽器中輸入:


127.0.0.1:8080
本作品採用《CC 協議》,轉載必須註明作者和本文連結
令狐一衝

相關文章