|
| 1 | +import { useCallback, useEffect, useRef, useState } from "react"; |
| 2 | +import { Canvas, useCanvasEffect } from "react-native-wgpu"; |
| 3 | +import { useWindowDimensions } from "react-native"; |
| 4 | +import { useSharedValue } from "react-native-reanimated"; |
| 5 | +import { Gesture, GestureDetector } from "react-native-gesture-handler"; |
| 6 | + |
| 7 | +import { ComputeEngine } from "./engine"; |
| 8 | + |
| 9 | +export interface ComputeToy { |
| 10 | + shader: string; |
| 11 | + uniforms: Record<string, number>; |
| 12 | +} |
| 13 | + |
| 14 | +export const useComputeToy = (toyId: number) => { |
| 15 | + const [props, setProps] = useState<ComputeToy | null>(null); |
| 16 | + |
| 17 | + useEffect(() => { |
| 18 | + (async () => { |
| 19 | + const shaderURL = `https://compute.toys/view/${toyId}/wgsl`; |
| 20 | + const uniformsURL = `https://compute.toys/view/${toyId}/json`; |
| 21 | + |
| 22 | + // Execute both fetch requests in parallel |
| 23 | + const [shaderResponse, uniformsResponse] = await Promise.all([ |
| 24 | + fetch(shaderURL), |
| 25 | + fetch(uniformsURL), |
| 26 | + ]); |
| 27 | + |
| 28 | + // Process the responses in parallel |
| 29 | + const [shader, uniformsJSON] = await Promise.all([ |
| 30 | + shaderResponse.text(), |
| 31 | + uniformsResponse.json(), |
| 32 | + ]); |
| 33 | + const uniforms: Record<string, number> = {}; |
| 34 | + // eslint-disable-next-line @typescript-eslint/no-explicit-any |
| 35 | + uniformsJSON.body.uniforms.forEach((uniform: any) => { |
| 36 | + uniforms[uniform.name] = uniform.value; |
| 37 | + }); |
| 38 | + setProps({ shader, uniforms }); |
| 39 | + })(); |
| 40 | + }, [toyId]); |
| 41 | + return props; |
| 42 | +}; |
| 43 | + |
| 44 | +export interface ComputeToyProps { |
| 45 | + toy: ComputeToy; |
| 46 | +} |
| 47 | + |
| 48 | +export const ComputeToy = ({ toy: { shader, uniforms } }: ComputeToyProps) => { |
| 49 | + const mouse = useSharedValue({ pos: { x: 0, y: 0 }, click: false }); |
| 50 | + const { width, height } = useWindowDimensions(); |
| 51 | + const [engine, setEngine] = useState<ComputeEngine | null>(null); |
| 52 | + const animationRef = useRef<number | null>(null); |
| 53 | + const lastTimeRef = useRef<number>(0); |
| 54 | + |
| 55 | + // Initialize WebGPU and the compute engine |
| 56 | + const canvasRef = useCanvasEffect(() => { |
| 57 | + const initWebGPU = async () => { |
| 58 | + try { |
| 59 | + // Create the compute engine |
| 60 | + await ComputeEngine.create(); |
| 61 | + const eng = ComputeEngine.getInstance(); |
| 62 | + |
| 63 | + // Set the canvas surface |
| 64 | + if (canvasRef.current) { |
| 65 | + eng.setSurface(canvasRef.current!); |
| 66 | + |
| 67 | + // Set the canvas size based on your CANVAS constants |
| 68 | + // TODO: use PixelRatio.get()? |
| 69 | + eng.resize(width, height, 1); |
| 70 | + |
| 71 | + // Initialize render state |
| 72 | + eng.reset(); |
| 73 | + |
| 74 | + // Set callbacks for shader compilation |
| 75 | + eng.onSuccess((entryPoints) => { |
| 76 | + console.log( |
| 77 | + "Shader compiled successfully with entry points:", |
| 78 | + entryPoints, |
| 79 | + ); |
| 80 | + }); |
| 81 | + |
| 82 | + eng.onError((message, row, col) => { |
| 83 | + console.error(`Shader error at ${row}:${col} - ${message}`); |
| 84 | + }); |
| 85 | + eng.setCustomFloats( |
| 86 | + Object.keys(uniforms), |
| 87 | + new Float32Array(Object.values(uniforms)), |
| 88 | + ); |
| 89 | + // Process and compile the shader |
| 90 | + const preprocessed = await eng.preprocess(shader); |
| 91 | + if (preprocessed) { |
| 92 | + await eng.compile(preprocessed); |
| 93 | + } |
| 94 | + |
| 95 | + setEngine(eng); |
| 96 | + } |
| 97 | + } catch (error) { |
| 98 | + console.error("Failed to initialize WebGPU:", error); |
| 99 | + } |
| 100 | + }; |
| 101 | + |
| 102 | + initWebGPU(); |
| 103 | + |
| 104 | + return () => { |
| 105 | + if (animationRef.current !== null) { |
| 106 | + cancelAnimationFrame(animationRef.current); |
| 107 | + } |
| 108 | + }; |
| 109 | + }); |
| 110 | + |
| 111 | + // Animation/render loop |
| 112 | + const renderLoop = useCallback( |
| 113 | + (timestamp: number) => { |
| 114 | + if (!engine) { |
| 115 | + return; |
| 116 | + } |
| 117 | + |
| 118 | + // Calculate time delta |
| 119 | + const delta = lastTimeRef.current |
| 120 | + ? (timestamp - lastTimeRef.current) / 1000 |
| 121 | + : 0; |
| 122 | + lastTimeRef.current = timestamp; |
| 123 | + |
| 124 | + // Update time uniforms |
| 125 | + engine.setTimeElapsed(timestamp / 1000); |
| 126 | + engine.setTimeDelta(delta); |
| 127 | + if (mouse) { |
| 128 | + engine.setMousePos(mouse.value.pos.x, mouse.value.pos.y); |
| 129 | + engine.setMouseClick(mouse.value.click); |
| 130 | + } |
| 131 | + // Render frame |
| 132 | + |
| 133 | + engine.render(); |
| 134 | + // Schedule next frame |
| 135 | + animationRef.current = requestAnimationFrame(renderLoop); |
| 136 | + }, |
| 137 | + [engine, mouse], |
| 138 | + ); |
| 139 | + |
| 140 | + useEffect(() => { |
| 141 | + renderLoop(new Date().getTime()); |
| 142 | + }, [renderLoop]); |
| 143 | + |
| 144 | + const gesture = Gesture.Pan() |
| 145 | + .onChange((e) => { |
| 146 | + mouse.value = { |
| 147 | + pos: { |
| 148 | + x: e.absoluteX / width, |
| 149 | + y: e.absoluteY / height, |
| 150 | + }, |
| 151 | + click: true, |
| 152 | + }; |
| 153 | + }) |
| 154 | + .onEnd((e) => { |
| 155 | + mouse.value = { |
| 156 | + pos: { |
| 157 | + x: e.absoluteX / width, |
| 158 | + y: e.absoluteY / height, |
| 159 | + }, |
| 160 | + click: false, |
| 161 | + }; |
| 162 | + }); |
| 163 | + |
| 164 | + return ( |
| 165 | + <GestureDetector gesture={gesture}> |
| 166 | + <Canvas ref={canvasRef} style={{ width, height }} /> |
| 167 | + </GestureDetector> |
| 168 | + ); |
| 169 | +}; |
0 commit comments