-
Notifications
You must be signed in to change notification settings - Fork 60
Expand file tree
/
Copy pathuseWebGPU.ts
More file actions
74 lines (67 loc) · 2.03 KB
/
useWebGPU.ts
File metadata and controls
74 lines (67 loc) · 2.03 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
import { useEffect, useRef } from "react";
import { PixelRatio } from "react-native";
import {
useDevice,
type CanvasRef,
type NativeCanvas,
} from "react-native-wgpu";
interface SceneProps {
context: GPUCanvasContext;
device: GPUDevice;
gpu: GPU;
presentationFormat: GPUTextureFormat;
canvas: NativeCanvas;
}
type RenderScene = (timestamp: number) => void;
type Scene = (props: SceneProps) => RenderScene | void | Promise<RenderScene>;
export const useWebGPU = (scene: Scene) => {
const { device } = useDevice();
const ref = useRef<CanvasRef>(null);
const animationFrameId = useRef<number | null>(null);
useEffect(() => {
(async () => {
const context = ref.current?.getContext("webgpu");
if (!context || !device) {
return;
}
const canvas = context.canvas as HTMLCanvasElement;
const presentationFormat = navigator.gpu.getPreferredCanvasFormat();
canvas.width = canvas.clientWidth * PixelRatio.get();
canvas.height = canvas.clientHeight * PixelRatio.get();
context.configure({
device,
format: presentationFormat,
alphaMode: "premultiplied",
});
const sceneProps: SceneProps = {
context,
device,
gpu: navigator.gpu,
presentationFormat,
canvas: context.canvas as unknown as NativeCanvas,
};
const r = scene(sceneProps);
let renderScene: RenderScene;
if (r instanceof Promise) {
renderScene = await r;
} else {
renderScene = r as RenderScene;
}
if (typeof renderScene === "function") {
const render = () => {
const timestamp = Date.now();
renderScene(timestamp);
//context.present();
animationFrameId.current = requestAnimationFrame(render);
};
animationFrameId.current = requestAnimationFrame(render);
}
})();
return () => {
if (animationFrameId.current) {
cancelAnimationFrame(animationFrameId.current);
}
};
}, [ref, device, scene]);
return ref;
};