|
| 1 | +/** |
| 2 | + * camera-array |
| 3 | + * R3F port of three.js `webgpu_camera_array`, running on WebGPU. |
| 4 | + * Original: https://threejs.org/examples/#webgpu_camera_array (~110 lines of JS) |
| 5 | + * |
| 6 | + * DEMONSTRATES |
| 7 | + * - `THREE.ArrayCamera` handed to `<Canvas camera={...}>` as fiber's own default |
| 8 | + * camera: WebGPURenderer natively multiplexes ONE `render(scene, camera)` call |
| 9 | + * across `camera.cameras[]`, each sub-camera drawn into its own `.viewport` rect — |
| 10 | + * no manual scissor/viewport loop or render-phase takeover needed. (Contrast |
| 11 | + * `camera/CameraRig.tsx`'s `{ phase: 'render' }` takeover, which exists because |
| 12 | + * THAT example is about the manual scissor mechanism itself — verified fiber's |
| 13 | + * default render job is exactly `renderer.render(state.scene, state.camera)`, |
| 14 | + * `packages/fiber/src/core/renderer.tsx`, so an ArrayCamera reproduces the |
| 15 | + * original's `renderer.render(scene, camera)` call unmodified.) |
| 16 | + * - `camera.manual = true` — fiber's per-camera escape hatch |
| 17 | + * (`ThreeCamera = (Orthographic|Perspective) & { manual?: boolean }`, |
| 18 | + * `packages/fiber/types/renderer.d.ts`) — so fiber's resize-driven aspect/ |
| 19 | + * projection update leaves the array's sub-camera projections alone; this |
| 20 | + * example's own effect owns them instead, exactly like the original's |
| 21 | + * `updateCameras()`. |
| 22 | + * - fiber's reactive `size` (via `useThree`) recomputing every sub-camera's |
| 23 | + * viewport + aspect on resize, replacing the original's manual |
| 24 | + * `window.addEventListener('resize', ...)` handler. |
| 25 | + * |
| 26 | + * DIVERGENCE from original |
| 27 | + * - Grid size (`AMOUNT`, 6 -> 36 sub-cameras) is a leva control instead of a |
| 28 | + * hardcoded constant. Changing sub-camera COUNT means a new `ArrayCamera` |
| 29 | + * instance, so the `<Canvas>` remounts via `key={amount}` alongside it — simpler |
| 30 | + * and safer than trying to hot-swap fiber's default camera object mid-session. |
| 31 | + * - Cylinder rotation is delta-scaled (`delta * rotationSpeed * ...`) instead of the |
| 32 | + * original's fixed per-tick increment (`+= 0.005`) — frame-rate independent, and |
| 33 | + * `rotationSpeed` is a leva control (default 1 reproduces the original's pace). |
| 34 | + * - Cylinder/background colors are leva controls instead of hardcoded hex — direct- |
| 35 | + * value controls over hidden state, per this repo's controls convention. |
| 36 | + * - Background plane and lights use the `*NodeMaterial` family |
| 37 | + * (`meshPhongNodeMaterial`) instead of the original's classic `MeshPhongMaterial` |
| 38 | + * — this repo's `/webgpu` convention (materials-basic.tsx, lights-pointlights.tsx), |
| 39 | + * auto-extended into JSX, not a behavior change. |
| 40 | + * - DemoHelpers' grid AND orbit camera-controls are both disabled (`grid={false} |
| 41 | + * controls={false}`): there is no single user-navigable camera here — the whole |
| 42 | + * point is the 36-camera grid rendered in one pass — so CameraControls has |
| 43 | + * nothing sensible to attach to (same rationale as `camera/camera.tsx`). |
| 44 | + * DemoHelpers stays mounted for the readiness signal. |
| 45 | + */ |
| 46 | +import { useEffect, useMemo, useRef } from 'react' |
| 47 | +import { useControls } from 'leva' |
| 48 | +import { Canvas, useFrame, useThree } from '@react-three/fiber/webgpu' |
| 49 | +import { ArrayCamera, PerspectiveCamera, Vector4 } from 'three/webgpu' |
| 50 | +import type { Mesh } from 'three/webgpu' |
| 51 | +import { DemoHelpers } from '../utils/DemoHelpers' |
| 52 | + |
| 53 | +const BACKGROUND_SIZE = 100 |
| 54 | + |
| 55 | +// fiber's `ThreeCamera` union types `.manual` on Orthographic/PerspectiveCamera; ArrayCamera |
| 56 | +// (a PerspectiveCamera subclass, `reference/three.js/src/cameras/ArrayCamera.js`) inherits the |
| 57 | +// runtime behavior but isn't itself in that union — same duck-typed-property cast family as |
| 58 | +// AGENTS.md's `*Node` field casts (UPSTREAM.md B11), local to this file. |
| 59 | +type ManualArrayCamera = ArrayCamera & { manual?: boolean } |
| 60 | + |
| 61 | +// Builds the ArrayCamera + its `amount * amount` sub-cameras (original's `init()`). Each |
| 62 | +// sub-camera gets its own `.viewport` — a plain bolt-on `Vector4`, exactly like the original; |
| 63 | +// `@types/three`'s base `Camera` declares `viewport?: Vector4` for it. Positions/aspect are |
| 64 | +// filled in reactively by `CameraArrayRig`'s size effect below. |
| 65 | +function createArrayCamera(amount: number): ManualArrayCamera { |
| 66 | + const subCameras: PerspectiveCamera[] = [] |
| 67 | + for (let i = 0; i < amount * amount; i++) { |
| 68 | + const subCamera = new PerspectiveCamera(40, 1, 0.1, 10) |
| 69 | + subCamera.viewport = new Vector4() |
| 70 | + subCameras.push(subCamera) |
| 71 | + } |
| 72 | + |
| 73 | + const arrayCamera = new ArrayCamera(subCameras) as ManualArrayCamera |
| 74 | + arrayCamera.position.z = 3 |
| 75 | + arrayCamera.manual = true |
| 76 | + |
| 77 | + return arrayCamera |
| 78 | +} |
| 79 | + |
| 80 | +interface CameraArrayRigProps { |
| 81 | + amount: number |
| 82 | + rotationSpeed: number |
| 83 | + cylinderColor: string |
| 84 | +} |
| 85 | + |
| 86 | +// Owns the two things the original's `updateCameras()`/`animate()` mutate every frame or |
| 87 | +// resize: sub-camera viewport+aspect (size-driven), and the tracked cylinder's spin. |
| 88 | +function CameraArrayRig({ amount, rotationSpeed, cylinderColor }: CameraArrayRigProps) { |
| 89 | + const camera = useThree((state) => state.camera) as ManualArrayCamera |
| 90 | + const size = useThree((state) => state.size) |
| 91 | + const meshRef = useRef<Mesh>(null) |
| 92 | + |
| 93 | + // Sub-camera viewport + aspect follow the CANVAS size — fiber's reactive `size` replaces |
| 94 | + // the original's manual `window.addEventListener('resize', ...)` handler. Positions/lookAt |
| 95 | + // don't actually depend on size, but the original recomputes them on every call to |
| 96 | + // `updateCameras()` too (init AND resize) — cheap, and keeps this the single source of |
| 97 | + // truth for the whole rig instead of splitting it across a one-time effect and a resize one. |
| 98 | + useEffect(() => { |
| 99 | + const aspect = size.width / size.height |
| 100 | + const width = size.width / amount |
| 101 | + const height = size.height / amount |
| 102 | + |
| 103 | + camera.aspect = aspect |
| 104 | + camera.updateProjectionMatrix() |
| 105 | + |
| 106 | + for (let y = 0; y < amount; y++) { |
| 107 | + for (let x = 0; x < amount; x++) { |
| 108 | + const subCamera = camera.cameras[amount * y + x] |
| 109 | + subCamera.copy(camera) // fov/aspect/near/far from the root camera |
| 110 | + |
| 111 | + // Non-null: every sub-camera got a `.viewport` in `createArrayCamera` above. |
| 112 | + subCamera.viewport!.set(Math.floor(x * width), Math.floor(y * height), Math.ceil(width), Math.ceil(height)) |
| 113 | + subCamera.updateProjectionMatrix() |
| 114 | + |
| 115 | + subCamera.position.x = x / amount - 0.5 |
| 116 | + subCamera.position.y = 0.5 - y / amount |
| 117 | + subCamera.position.z = 1.5 + (x + y) * 0.5 |
| 118 | + subCamera.position.multiplyScalar(2) |
| 119 | + |
| 120 | + subCamera.lookAt(0, 0, 0) |
| 121 | + subCamera.updateMatrixWorld() |
| 122 | + } |
| 123 | + } |
| 124 | + }, [camera, amount, size.width, size.height]) |
| 125 | + |
| 126 | + useFrame((_state, delta) => { |
| 127 | + const mesh = meshRef.current |
| 128 | + if (!mesh) return |
| 129 | + // 0.3/0.6 rad/s reproduces the original's fixed `+= 0.005`/`+= 0.01` per-frame pace at |
| 130 | + // 60fps, now frame-rate independent via `delta`. |
| 131 | + mesh.rotation.x += delta * rotationSpeed * 0.3 |
| 132 | + mesh.rotation.z += delta * rotationSpeed * 0.6 |
| 133 | + }) |
| 134 | + |
| 135 | + return ( |
| 136 | + <mesh ref={meshRef} castShadow receiveShadow> |
| 137 | + <cylinderGeometry args={[0.5, 0.5, 1, 32]} /> |
| 138 | + <meshPhongNodeMaterial color={cylinderColor} /> |
| 139 | + </mesh> |
| 140 | + ) |
| 141 | +} |
| 142 | + |
| 143 | +export default function CameraArrayExample() { |
| 144 | + const { amount, rotationSpeed, cylinderColor, backgroundColor } = useControls('camera-array', { |
| 145 | + amount: { value: 6, min: 2, max: 8, step: 1, label: 'Grid size (N×N)' }, |
| 146 | + rotationSpeed: { value: 1, min: 0, max: 3, step: 0.1 }, |
| 147 | + cylinderColor: { value: '#ff0000', label: 'cylinder color' }, |
| 148 | + backgroundColor: { value: '#000066', label: 'background color' }, |
| 149 | + }) |
| 150 | + |
| 151 | + // Rebuilt whenever `amount` changes — see DIVERGENCE for why the Canvas remounts |
| 152 | + // (`key={amount}`) alongside it rather than hot-swapping fiber's default camera. |
| 153 | + const camera = useMemo(() => createArrayCamera(amount), [amount]) |
| 154 | + |
| 155 | + return ( |
| 156 | + <Canvas key={amount} renderer shadows background="#000000" camera={camera}> |
| 157 | + <ambientLight color="#999999" /> |
| 158 | + <directionalLight position={[0.5, 0.5, 1]} intensity={3} castShadow shadow-camera-zoom={4} /> |
| 159 | + <mesh position={[0, 0, -1]} receiveShadow> |
| 160 | + <planeGeometry args={[BACKGROUND_SIZE, BACKGROUND_SIZE]} /> |
| 161 | + <meshPhongNodeMaterial color={backgroundColor} /> |
| 162 | + </mesh> |
| 163 | + <CameraArrayRig amount={amount} rotationSpeed={rotationSpeed} cylinderColor={cylinderColor} /> |
| 164 | + <DemoHelpers grid={false} controls={false} /> |
| 165 | + </Canvas> |
| 166 | + ) |
| 167 | +} |
0 commit comments