antvis / g-webgl-compute

A GPGPU implementation based on WebGL.
MIT License
145 stars 15 forks source link

WebGL 模式下支持 OffscreenCanvas #23

Closed xiaoiver closed 4 years ago

xiaoiver commented 4 years ago

问题背景

目前在仅支持 WebGL 的浏览器中运行时,会出现主线程卡住的情况。

https://caniuse.com/#feat=offscreencanvas 在独立线程中进行渲染,将结果同步给主线程。

Babylon.js 中的应用:https://doc.babylonjs.com/how_to/using_offscreen_canvas

目前 WebGPU 还不支持:https://github.com/gpuweb/gpuweb/issues/403 regl 已经支持:https://github.com/regl-project/regl/issues/536

解决方案

参考 Babylon.js 的做法,让用户自己完成 OffscreenCanvas 的创建以及 transfer:

const offscreen = canvas.transferControlToOffscreen();
const worker = new Worker("worker.js"); 
worker.postMessage({canvas: offscreen}, [offscreen]);

在 worker 中用户需要自行完成主线程通信,将计算结果送回:

onmessage = function(evt) {
    canvas = evt.data.canvas;
    const world = new World({ canvas });
}

因此需要确保 GWebGPU 能完全在 Worker 内运行。 好在已经可以在 Worker 中使用 rAF:https://developers.google.com/web/updates/2018/08/offscreen-canvas

已知问题

  1. 在 Worker 中无法使用 window,因此像 hammer.js 这样的库是无法使用的。
  2. 目前 workerize-loader 还不支持 postMessage 第二个参数 transferable ISSUE。因此推荐使用 worker-loader
xiaoiver commented 4 years ago

使用文档: https://gwebgpu.antv.vision/zh/docs/tutorial/fruchterman#%E5%9C%A8-webworker-%E4%B8%AD%E5%AE%8C%E6%88%90%E8%AE%A1%E7%AE%97%EF%BC%88%E6%B8%B2%E6%9F%93%EF%BC%89

Online DEMO:https://xiaoiver.github.io/FruchtermanWorkerDemo/

GitHub:https://github.com/xiaoiver/FruchtermanWorkerDemo/