# Surfaces

> `@typegpu/kit` 0.1.0. If it is installed, read `node_modules/@typegpu/kit/docs/` instead.

A canvas configured for your root, with a drawing buffer that follows its layout, on the web and React Native.

> `import * as web from '@typegpu/kit/web'`: `web.surface(root, canvas, options?) → Surface`, `web.paced(queue, options?) → Schedule`, `web.orbitControls(orbit, element, options?) → OrbitControls`, `web.pointer(element, options?) → Pointer`, `web.host`, `web.video`. Hosts scenes on web canvases and provides surfaces, GPU pacing, pointer input and orbit controls. **kind** platform. **owns** the canvas's configuration and a resize observer; a hosted scene also owns the surface, its root and the device unless it was given them, the scene's stage and what its `attach` returned. **allocates** each frame: a view of the canvas's texture, which is new every frame; under `paced`, a promise of the frame's work; for `video`, an imported texture per read of a frame. **lifecycle** `destroy()`, `[Symbol.dispose]`. **platform** web only. **types** `CreateScene`, `Scene`, `FixedSize`, `OrbitGoal`, `PointerHandler`, `Stage`. `src/web.ts`.
>
> `SurfaceOptions`, taken by `surface`:
> - `size?: FixedSize` Fixes the drawing-buffer size before `surface` returns. Default the layout size multiplied by the capped pixel ratio, following layout changes.
> - `maxPixelRatio?: number` Caps drawing-buffer pixels per CSS pixel unless `size` is set. Default 2.
> - `format?: GPUTextureFormat` Sets the canvas texture format. Default `navigator.gpu.getPreferredCanvasFormat()`.
> - `alphaMode?: GPUCanvasAlphaMode` Controls canvas transparency. Default `opaque`.
> - `usage?: GPUTextureUsageFlags` Sets the canvas texture usage flags. Default `GPUTextureUsage.RENDER_ATTACHMENT`.
> - `colorSpace?: PredefinedColorSpace` Sets the colour space of canvas values. Default `'srgb'`.
> - `toneMapping?: GPUCanvasToneMapping` Controls the range of canvas values for display. Default `{ mode: 'standard' }`.
>
> `PacedOptions`, taken by `paced`:
> - `inFlight?: number` Limits the number of frames whose GPU work may be unfinished when the next frame starts. Default 2.
>
> `OrbitControlsOptions`, taken by `orbitControls`:
> - `sensitivity?: number` Sets rotation per dragged pixel, in radians. Default 0.008, as `cameras.turn`.
> - `zoomSpeed?: number` Sets wheel zoom speed. Default 0.001.
> - `button?: 'primary' | 'secondary' | 'middle'` Orbits with this mouse button. Default `'primary'`.
> - `pan?: boolean` Enables panning with the secondary button, or the middle one when the secondary orbits, and with two fingers moving together. Default false.
> - `page?: boolean` Allows page scrolling around an embedded view. Default false, so the element handles every drag and wheel input.
> - `pointer?: Pointer` Leaves the element's `touch-action` and pointer capture to this pointer on the same element, which sets them from its own `page`. Default none, so the controls set both.
> - `onChange?: () => void` Runs after each input that changes the goal, for views that draw on demand. Default none.
>
> `PointerOptions`, taken by `pointer`:
> - `move?: PointerHandler` Runs as the pointer moves over the element, or anywhere while it holds a button down. Default none.
> - `down?: PointerHandler` Runs as a button goes down on the element. Default none.
> - `up?: PointerHandler` Runs as a button comes up, or as the browser cancels the pointer. Default none.
> - `leave?: () => void` Runs as the pointer leaves the element with no button down. Default none.
> - `zoom?: (by: number) => void` Runs as the wheel turns or two fingers pinch on the element, with the factor to scale a distance by, above 1 farther: e^(deltaY × 0.001) for the wheel, and the ratio of the fingers' last spread to the new one for a pinch. Default none.
> - `page?: boolean` Allows page scrolling around an embedded element: touch drags scroll the page instead of reaching `move`, and only the wheel with Ctrl or Command held zooms. Default false, so the element takes every touch drag and wheel turn.
> - `menu?: boolean` Shows the context menu on a secondary click. Default true.
>
> `HostOptions`, taken by `host`:
> - `canvas: HTMLCanvasElement` Supplies the canvas for the scene.
> - `optionalFeatures?: Iterable<GPUFeatureName>` Requests these features when the adapter supports them, such as `timestamp-query`. Default none.
> - `device?: GPUDevice` Supplies a device that the host keeps alive. Default a device that the web host requests and destroys with the scene.
> - `root?: TgpuRoot` Supplies a root that the host keeps alive, so scenes can share it. Default a root that the host creates on `device` and destroys with the scene.
> - `schedule?: Schedule | false` Supplies animation frames. Default `requestAnimationFrame`, or display vsync on a React Native worker.
> - `onFrame?: (stage: Stage<S, Canvas>, frame: Frame) => void` Runs after the scene's `frame` each frame, for page work such as a HUD that reads scene state. Default none.
> - `attach?: (stage: Stage<S, Canvas>) => Detach | void` Connects page code, such as orbit controls, to the stage after scene creation. Default none.
> - `onError?: Callback<[unknown]>` Receives the first scene error, from `createScene`, a frame, `onFrame`, `ready` or the device, which stops the frames. Default `console.error`.
> - `format?: GPUTextureFormat` Sets the canvas texture format. Default `navigator.gpu.getPreferredCanvasFormat()`.
> - `alphaMode?: GPUCanvasAlphaMode` Controls canvas transparency. Default `opaque`.
> - `usage?: GPUTextureUsageFlags` Sets the canvas texture usage flags. Default `GPUTextureUsage.RENDER_ATTACHMENT`.
> - `colorSpace?: PredefinedColorSpace` Sets the colour space of canvas values. Default `'srgb'`.
> - `toneMapping?: GPUCanvasToneMapping` Controls the range of canvas values for display. Default `{ mode: 'standard' }`.
> - `size?: FixedSize` Fixes the drawing-buffer size before `surface` returns. Default the layout size multiplied by the capped pixel ratio, following layout changes.
> - `maxPixelRatio?: number` Caps drawing-buffer pixels per CSS pixel unless `size` is set. Default 2.
>
> `VideoOptions`, taken by `video`:
> - `mirrored?: boolean` Flips every frame left to right, as a mirror shows a front camera. Default false.
>
> `Surface`, from `surface`:
> - `context: GPUCanvasContext` Provides the canvas context for a TypeGPU colour attachment `view`.
> - `width: number` Reports the drawing-buffer size in pixels, from the fixed size or the layout size in device pixels.
> - `height: number` Reports the drawing-buffer height in pixels, as `width` does.
> - `pixelRatio: number` Reports the fixed size's pixel ratio, or follows zoom and screen changes when the size follows layout.
> - `paused: boolean` Reports whether the surface is paused, true between `pause` and `resume`.
> - `setSize(size)` Fixes the drawing-buffer size from the next `view()`, as `options.size` does.
> - `pause()` Pauses the surface for a canvas outside the viewport or a pause menu.
> - `resume()` Resumes the frames after `pause`.
> - `view(frame)` Returns a view of the current canvas texture, created once per texture.
> - `format: GPUTextureFormat` Reports the format of its textures, which pipelines that draw into it target.
> - `destroy()` Releases the drawing destination.
>
> `Schedule`, from `paced`:
> - `request(callback)` Calls `callback` with the time in milliseconds at the next frame and returns the request's id.
> - `cancel(request)` Cancels the request with this id.
>
> `OrbitControls`, from `orbitControls`:
> - `destroy()` Removes the listeners and restores the element's `touch-action`, unless a pointer set it.
>
> `Pointer`, from `pointer`:
> - `x: number` Holds the last position from 0 to 1 across the element, +y down.
> - `y: number` Holds the last position from 0 to 1 down the element, as `x` does.
> - `over: boolean` Tells whether the pointer is over the element or holds a button down that began on it.
> - `buttons: number` Holds the buttons held down, as `PointerEvent.buttons`: 1 primary, 2 secondary, 4 middle.
> - `destroy()` Removes the listeners and restores the element's `touch-action`.
>
> `Hosted`, from `host`:
> - `pause()` Stops frames and elapsed time for an app in the background, a canvas outside the viewport or a pause menu.
> - `resume()` Resumes the frames after `pause`.
> - `send(fn, ...args)` Runs `fn` with the value on its runtime, after earlier sent calls.
> - `run(fn, ...args)` Runs `fn` from React Native or the page, as `send` does, and copies its result back as `post` does.
> - `destroy()` Calls `destroy` on the value's runtime after earlier sent calls, then releases the value without waiting for their promises.
>
> `Video`, from `video`:
> - `destroy()` Stops watching the element for new frames.
> - `latest(device, seen?)` Imports the newest frame on `device`.

A page lays out a canvas in CSS pixels, while its drawing buffer measures `canvas.width` by `canvas.height` device pixels. Layout, screen and zoom changes can make those sizes disagree, blurring or stretching the picture. A **surface** configures the canvas for your root and keeps the drawing buffer matched to its layout.

**Web**

```ts
import * as web from '@typegpu/kit/web';

const canvas = document.querySelector('canvas')!;
const surface = web.surface(root, canvas);

const loop = frames.create(root, (frame) => {
  const pass = frame.encoder.beginRenderPass({ colorAttachments: { view: surface.view(frame) } });
  // draw
  pass.end();
});

frames.animate(loop); // runs the loop at every animation frame
```

**React Native**

```ts

// react-native-webgpu requests implicit-device-synchronization for every device
const root = await tgpu.init();

// `canvas` is the CanvasRef from <Canvas ref>; its onLayout calls surface.resize(width, height)
const surface = native.surface(root, canvas, { pixelRatio: PixelRatio.get() });
AppState.addEventListener('change', (state) =>
  state === 'active' ? surface.resume() : surface.pause(),
);

const loop = frames.create(root, (frame) => {
  const pass = frame.encoder.beginRenderPass({ colorAttachments: { view: surface.view(frame) } });
  // draw
  pass.end();
});

frames.animate(loop, { surface }); // runs no frames while the surface is paused
```

## How big the drawing buffer gets

- The drawing buffer is the layout size times the screen's pixel ratio, capped at `maxPixelRatio`, 2 by default. On a 3× phone that leaves about 44% of the full-resolution pixels, so full-size targets use less than half the memory.
- Multiply sizes in points, such as dots, hairlines and margins, by the surface's `pixelRatio`. The screen's own ratio can exceed the cap.
- `maxPixelRatio` caps the ratio but never raises it above the screen's ratio. To render more pixels, draw into a [target](targets.md) sized with `targets.scaled(surface, 2)` and filter it down. To use the same size on every screen, [fix the size](#a-fixed-size).
- The size is clamped to the device's `maxTextureDimension2D`.
- For fewer pixels, or a resolution that changes while the game runs, render at a [resolution](targets.md#resolution-scale) below the surface.

## A fixed size

A benchmark, GPU capture or offline render needs a fixed pixel size, such as 2560 × 1440. Pass `size` in pixels to set the drawing buffer before `surface` returns. Layout and pixel ratio changes leave it unchanged. The canvas's CSS size still scales the image on screen. The benchmark below [steps frames by hand](frames.md#stepping-by-hand):

```ts
import * as web from '@typegpu/kit/web';

const surface = web.surface(root, canvas, { size: { width: 2560, height: 1440 } });
const scene = createScene(root, surface);
const loop = frames.create(root, (frame) => scene.frame(frame));

for (let i = 0; i < 600; i++) loop.run(i / 60);
await root.device.queue.onSubmittedWorkDone();
```

- The surface's `pixelRatio` is then the `pixelRatio` you give in `size`, 1 by default. A size in points gives the same number of pixels on every screen. `maxPixelRatio` doesn't apply.
- Use `setSize` for a run at several resolutions. `web.host` takes `size` too, and its page reaches `setSize` through `send(({ surface }) => …)`.
- A size that isn't whole pixels from 1 to `maxTextureDimension2D` throws.
- On React Native, `native.surface` and the React Native `host` take `size` too. `resize` then changes nothing until `setSize(undefined)`, and `setSize` applies at once.

## When the size changes

- On the web, a `ResizeObserver` watches the canvas's device-pixel box, the screen pixels it covers, so the drawing buffer matches the screen pixel for pixel. Without that box, the size is the CSS size times the ratio, rounded.
- A size change reaches the canvas at the next `view()`, the frame in which your [render targets](targets.md) follow it through `fit()`. Waiting until then keeps the resize from clearing a frame already drawn.

> **Caution: WebKit**
>
> Safari has no device-pixel box. The size is rounded from CSS pixels, and a ratio change without a
> layout change, such as dragging the window to another screen, waits for the next layout change.

## Drawing to it

A pass that uses `surface.context` directly skips pending size changes, so take views from `view(frame)`.

Use the `Surface` type from `@typegpu/kit` for code shared by both platforms and its [tests](testing.md#a-frame-without-a-canvas). Pass the frame to `view` so React Native can present after submit.

```ts
import type { Frame, Surface } from '@typegpu/kit';

export function createScene(root: TgpuRoot, surface: Surface) {
  return {
    frame(frame: Frame) {
      const pass = frame.encoder.beginRenderPass({
        colorAttachments: { view: surface.view(frame) },
      });
      // draw
      pass.end();
    },
  };
}
```

## Pacing frames

With `--disable-gpu-vsync --disable-frame-rate-limit`, Chrome can schedule frames faster than the GPU finishes them. Use `web.paced(queue)` as `schedule` to bound queued work. It waits until at most `inFlight` frames remain, 2 by default, before scheduling another frame. Normal vsync needs no extra pacing.

```ts
frames.animate(loop, { schedule: web.paced(root.device.queue) });
```

## Pointer input

`web.pointer(element, options)` follows the mouse, touch or pen on an element in the coordinates a camera's [`rayAt`](cameras.md) takes:

```ts
import * as web from '@typegpu/kit/web';

const ray = { origin: [0, 0, 0], direction: [0, 0, 0] };
const ground = [0, 0, 0];

const mouse = web.pointer(canvas, {
  down(x, y, event) {
    if (event.button !== 0) return;
    view.rayAt(x, y, ray);
    if (cameras.hitHeight(ray, 0, ground) !== undefined) select(ground);
  },
});

// Each frame, the ground under the pointer
if (mouse.over) {
  view.rayAt(mouse.x, mouse.y, ray);
  cameras.hitHeight(ray, 0, ground);
}
```

- **Position** Read `x` and `y` each frame, or take them in `move`, `down` and `up`.
- **Zoom** `zoom(by)` runs as the wheel turns and as two fingers pinch. For the wheel, `by` is e<sup>deltaY·0.001</sup>. For a pinch, it is the old distance between the fingers divided by the new one. Multiply your distance by `by`. A value above 1 means farther away.
- **Drags** A press keeps the pointer until its button comes up, so a drag continues outside the element, with positions past 0 and 1. `up` also runs when the browser cancels a pointer.
- **Touch and menu** It sets the element's `touch-action` to `none`. With `page: true`, it sets `pan-y` so vertical touch drags can scroll the page. In that mode, the wheel zooms only while you hold Ctrl or ⌘. `menu: false` keeps the context menu shut for drags with the secondary button.
- **Hosted pages** Create the pointer in [`attach`](hosting.md#on-the-web) on a hosted page to dispose it with the scene.
- **React Native** On React Native, divide a gesture's position by the canvas's layout size for the same coordinates.

## React Native

> `import * as native from '@typegpu/kit/native'`: `native.surface(root, canvas, { pixelRatio, … }) → Surface`, `native.checkDevice(device)`. Provides a react-native-webgpu canvas surface that pauses in the background, and a check that two threads can share a device. **kind** platform. **owns** the canvas's configuration. **allocates** each frame: a view of the canvas's texture, which is new every frame. **lifecycle** `destroy()`, `[Symbol.dispose]`. **requires** `implicit-device-synchronization` required: react-native-webgpu requests it for every device; `checkDevice` throws without it. Devices used from two threads require it to avoid crashes. **platform** native only. **types** `FixedSize`, `Canvas`. `src/native.ts`.
>
> `SurfaceOptions`, taken by `surface`:
> - `pixelRatio: number` Sets the display pixel ratio from `PixelRatio.get()`.
> - `maxPixelRatio?: number` Caps drawing-buffer pixels per point unless `size` is set. Default 2.
> - `size?: FixedSize` Fixes the drawing-buffer size. Default the layout size in points multiplied by the capped pixel ratio.
> - `format?: GPUTextureFormat` Sets the canvas texture format. Default `navigator.gpu.getPreferredCanvasFormat()`.
> - `alphaMode?: GPUCanvasAlphaMode` Controls canvas transparency. Default `opaque`.
> - `usage?: GPUTextureUsageFlags` Sets the canvas texture usage flags. Default `GPUTextureUsage.RENDER_ATTACHMENT`.
> - `colorSpace?: PredefinedColorSpace` Sets the colour space of canvas values. Default `'srgb'`.
> - `toneMapping?: GPUCanvasToneMapping` Controls the range of canvas values for display. Default `{ mode: 'standard' }`.
>
> `Surface`, from `surface`:
> - `context: GPUCanvasContext` Provides the canvas context, configured for the root.
> - `paused: boolean` Reports whether the surface is paused.
> - `resize(width, height)` Sizes the drawing buffer from the canvas's layout size in points, as `onLayout` reports it.
> - `setSize(size)` Fixes the drawing-buffer size, as `options.size` does.
> - `pause()` Pauses frames while the app is in the background, where it must not submit GPU work.
> - `resume()` Resumes the surface and reconfigures its context with the same options.
> - `format: GPUTextureFormat` Reports the format of its textures, which pipelines that draw into it target.
> - `width: number` Reports the drawing-buffer size in pixels.
> - `height: number` Reports the drawing-buffer height in pixels.
> - `pixelRatio: number` Reports drawing-buffer pixels per CSS pixel or point after applying the cap.
> - `view(frame)` Returns a view of the current texture, created once per texture.
> - `destroy()` Releases the drawing destination.

`@typegpu/kit/native` has no React Native imports. Pass it the canvas, pixel ratio and layout.

- **The surface** `native.surface` takes the `CanvasRef` that `<Canvas ref>` holds, the web's canvas options and the `pixelRatio`. The drawing buffer's size is on its context's `canvas`.
- **Presenting** `view(frame)` schedules `context.present()` after submit. React Native requires an explicit present. Dawn rejects presenting without first acquiring the canvas texture.
- **Pausing** A backgrounded app must not submit GPU work. `pause()` sets `paused`, which [`frames.animate`](frames.md#running-the-loop) checks before every frame when you pass it the surface. `view()` throws while the surface is paused, so a loop of your own fails at once instead of submitting in the background.
- **Resuming** After a long background pause, the first `getCurrentTexture` after `resume()` can block the JS thread.
- **Device errors** `device.lost` and `uncapturederror` reach only the main JS runtime.
- **Features** `tgpu.init({ device: { optionalFeatures } })` keeps each feature the adapter has; `device.features` says which it got.

> **Caution: One device, two threads**
>
> A Dawn device used from two threads crashes on iOS in a Metal assertion unless it has the
> `implicit-device-synchronization` feature. react-native-webgpu requests it for every device, so
> don't pass `implicitDeviceSynchronization: false`. `native.checkDevice(device)` throws for a
> device without it, and so does a host that runs its scene off the JS thread.

## Limits

- Above the cap, the device-pixel size is scaled by `maxPixelRatio / ratio`, so the drawing buffer matches the screen pixel for pixel only at or below the cap.
- On React Native, a frame that takes the view and never finishes loses its present callback. The next frame that takes the view and reaches its after-submit callbacks presents the canvas.
- The web surface's `view()` doesn't throw while paused, since a submit from a paused page does no harm.
- `implicit-device-synchronization` costs one uncontended mutex per API call.
