Code Monkey home page Code Monkey logo

wasmgpu's Introduction

Go WASM GPU

This project aims to expose the WebGPU API as Go API that can be used in wasm projects.

Warning: The project is in early development and the API is likely to change in backward incompatible ways!

Getting Started

You need to add the project as a dependency.

go get github.com/mokiat/wasmgpu@latest

The implementation uses syscall/js calls and as such requires that client applications are compiled with the GOOS=js and GOARCH=wasm options.

If you are unfamiliar with how Go and WASM works, then you should have a look at the official WebAssembly with Go documentation.

Following is an example Go code that clears the canvas with a green color.

package main

import (
	"syscall/js"

	"github.com/mokiat/gog/opt"
	"github.com/mokiat/wasmgpu"
)

func main() {
	// You need to ensure that getContext and getDevice methods exist.
	jsContext := js.Global().Call("getContext")
	jsDevice := js.Global().Call("getDevice")

	context := wasmgpu.NewCanvasContext(jsContext)

	device := wasmgpu.NewDevice(jsDevice)
	commandEncoder := device.CreateCommandEncoder()

	renderPass := commandEncoder.BeginRenderPass(wasmgpu.GPURenderPassDescriptor{
		ColorAttachments: []wasmgpu.GPURenderPassColorAttachment{
			{
				View: context.GetCurrentTexture().CreateView(),
				ClearValue: opt.V(wasmgpu.GPUColor{
					R: 0.0,
					G: 1.0,
					B: 0.0,
					A: 1.0,
				}),
				LoadOp:  wasmgpu.GPULoadOpClear,
				StoreOp: wasmgpu.GPUStoreOPStore,
			},
		},
	})
	renderPass.End()

	device.Queue().Submit([]wasmgpu.GPUCommandBuffer{
		commandEncoder.Finish(),
	})
}

NOTE: In order to get this working, the code needs access to getContext and getDevice functions that don't exist by default. You need to expose those from your page's JavaScript.

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <title>Experiment</title>
    <script type="text/javascript" src="wasm_exec.js"></script>
  </head>
  <body>
    <canvas width="512" height="512"></canvas>
    <script type="module">
      // Prepare a Canvas with WebGPU support.
      if (!navigator.gpu) {
        throw new Error("WebGPU not suppored :(");
      }
      const adapter = await navigator.gpu.requestAdapter({
        powerPreference: "high-performance",
      });
      if (!adapter) {
        throw new Error("No WebGPU adapter available :(");
      }
      const device = await adapter.requestDevice();
      if (!device) {
        throw new Error("No Device available :(");
      }
      const canvas = document.querySelector("canvas");
      const context = canvas.getContext("webgpu");
      const canvasFormat = navigator.gpu.getPreferredCanvasFormat();
      context.configure({
        device: device,
        format: canvasFormat,
      });

      // The following functions are needed by the Go code to get access
      // to the context and device.
      window.getDevice = () => {
        return device;
      };
      window.getContext = () => {
        return context;
      };

      // This is the standard code to get WebAssembly going with Go.
      const go = new Go();
      const result = await WebAssembly.instantiateStreaming(
        fetch("main.wasm"),
        go.importObject
      );
      await go.run(result.instance);
    </script>
  </body>
</html>

Demo

The project includes a working Demo based on Google's Codelab Tutorial.

You can check it live on the GitHub page of this project. Alternatively, you can run it yourself. It is located in the demo folder of the repository.

Run the following script to build the WASM file.

demo/build

Run the following script to run an HTTP server to host the demo/web folder.

demo/run

Next, open http://localhost:8080 with a browser that supports WebGPU. You should see the Demo running.

Extending the API

If something is not available in the API, in some cases, you can extend it as a workaround by extracting the js.Value object using obj.ToJS().(js.Value) and assigning it to a wrapper structure.

Example:

func ExtendQueue(queue GPUQueue) GPUQueueExt {
  return GPUQueueExt {
    GPUQueue: queue,
    jsValue:  queue.ToJS().(js.Value),
  }
}

type GPUQueueExt struct {
  GPUQueue
  jsValue js.Value
}

func (g GPUQueueExt) DoSomethingNew() {
  g.jsValue.Call("somethingNew")
}

In the meantime you can open a Github Issue so that the actual implementation can be adjusted.

Contributing

The project is still very early in the design phase. At this point in time Issues would be the preferred contribution mechanism.

wasmgpu's People

Contributors

mokiat avatar

Stargazers

 avatar Noly Oh avatar Volker Schönefeld avatar irieda avatar

Watchers

 avatar  avatar

Forkers

hulkholden

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.