Deno 1.18 環境使用 WebGPU

支持 WebGPU API 的環境,可不止瀏覽器一個。

雖說 NodeJS 沒什麼消息說要支持,但是 Deno 這個 js/ts 運行時老早就支持了,能脫離瀏覽器直接在控制檯訪問 GPU,感覺十分有趣。

確保 Deno 版本

至少要高於 1.8,最好裝最新

> deno --version

deno 1.18.0 (release, x86_64-pc-windows-msvc)
v8 9.8.177.6
typescript 4.5.2

命令行交互式獲取 GPUDevice

發文時,WebGPU 尚未正式公佈,仍需要加上不安全標記來運行命令行交互式環境:

image

隨後就可以輕鬆地獲取 GPUDevice 了,只需兩行代碼(假如不檢查錯誤情況):

const adapter = await navigator.gpu.requestAdapter()
const device = await adapter.requestDevice()

代碼文件獲取 GPUDevice

源碼非常簡單

navigator.gpu.requestAdapter().then((adapter) => {
  if (adapter === null) {
    console.log('GPUAdapter 請求失敗')
    Deno.close(0)
  } else {
    return adapter.requestDevice()
  }
}).then((device) => {
  if (!device) {
    console.log('GPUDevice 請求失敗')
    Deno.close(0)
  } else {
    console.log(device.limits)
  }  
})

然後運行之:

image

Top-level Await 不生效

對於頂級 await 獲取的方式貌似不可行,不知道是不是 deno 的問題。

// gpu.ts
const adapter = await navigator.gpu.requestAdapter()
const device = await adapter.requestDevice()
console.log(device.limits)

image

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章