### Install TypeGPU with yarn Source: https://github.com/software-mansion/typegpu/blob/main/apps/typegpu-docs/src/content/docs/getting-started.mdx Install the TypeGPU package using yarn. This is the first step to begin using the library. ```sh yarn add typegpu ``` -------------------------------- ### Install @typegpu/react Source: https://github.com/software-mansion/typegpu/blob/main/apps/typegpu-docs/src/content/docs/ecosystem/typegpu-react/index.mdx Install the @typegpu/react package using your preferred package manager. ```sh npm install @typegpu/react ``` ```sh pnpm add @typegpu/react ``` ```sh yarn add @typegpu/react ``` -------------------------------- ### Install TypeGPU and WebGPU Types Source: https://context7.com/software-mansion/typegpu/llms.txt Install the core TypeGPU package and the necessary WebGPU type declarations for TypeScript. ```bash npm install typegpu npm install --save-dev @webgpu/types ``` -------------------------------- ### Install TypeGPU with npm Source: https://github.com/software-mansion/typegpu/blob/main/apps/typegpu-docs/src/content/docs/getting-started.mdx Install the TypeGPU package using npm. This is the first step to begin using the library. ```sh npm install typegpu ``` -------------------------------- ### Install TypeGPU with pnpm Source: https://github.com/software-mansion/typegpu/blob/main/apps/typegpu-docs/src/content/docs/getting-started.mdx Install the TypeGPU package using pnpm. This is the first step to begin using the library. ```sh pnpm add typegpu ``` -------------------------------- ### TypeGPU Lint Plugin Examples Source: https://github.com/software-mansion/typegpu/blob/main/apps/typegpu-docs/src/content/docs/blog/typegpu-0.11/index.mdx These examples demonstrate how the TypeGPU lint plugin catches common errors in WGSL code. Ensure 'use gpu' is present and refer to the plugin documentation for setup and rules. ```typescript import tgpu, { d } from 'typegpu'; function increment(n: number) { 'use gpu'; return n++; // ^^^ // Cannot assign to 'n' since WGSL parameters are immutable. // If you're using d.ref, please either use '.$' or disable this rule } ``` ```typescript function createBoid() { 'use gpu'; const boid = { pos: d.vec2f(), size: 1 }; // ^^^^^^^^^^^^^^^^^^^^^^^^^^^ // { pos: d.vec2f(), size: 1 } must be wrapped in a schema call return boid; } ``` ```typescript function clampTo0(n: number) { 'use gpu'; let result; // ^^^^^^^^ // 'result' must have an initial value if (n < 0) { result = 0; } else { result = n; } return result; } ``` -------------------------------- ### TypeGPU and WebGPU Code Examples Source: https://github.com/software-mansion/typegpu/blob/main/apps/typegpu-docs/src/content/docs/tutorials/triangle-to-boids/index.mdx Provides complete code examples for both TypeGPU and WebGPU implementations, allowing for direct comparison and usage. ```ts import step5typegpu from 'code/step5-typegpu.ts?raw'; import step5webgpu from 'code/step5-webgpu.ts?raw';
Show code
Show code
``` -------------------------------- ### Pipeline Creation Examples Source: https://github.com/software-mansion/typegpu/blob/main/apps/typegpu-docs/src/content/docs/apis/pipelines.mdx Demonstrates the creation of render and compute pipelines using TypeGPU's root object methods. ```APIDOC ## Pipeline Creation A pipeline can be defined with one of the following methods on the [root](/TypeGPU/apis/roots) object: - `createRenderPipeline` - `createComputePipeline` - `createGuardedComputePipeline` ```ts twoslash import tgpu, { d } from 'typegpu'; const root = await tgpu.init(); const presentationFormat = 'rgba8unorm'; const mainVertex = tgpu.vertexFn({ in: { vertexIndex: d.builtin.vertexIndex }, out: { pos: d.builtin.position }, })((input) => { const pos = [d.vec2f(-1, -1), d.vec2f(3, -1), d.vec2f(-1, 3)]; return { pos: d.vec4f(pos[input.vertexIndex], 0, 1), }; }); const mainFragment = tgpu.fragmentFn({ out: d.vec4f })(() => d.vec4f(1, 0, 0, 1)); const mainCompute = tgpu.computeFn({ workgroupSize: [1] })(() => {}); // ---cut--- const renderPipeline = root.createRenderPipeline({ vertex: mainVertex, fragment: mainFragment, targets: { format: presentationFormat }, }); const computePipeline1 = root.createComputePipeline({ compute: mainCompute, }); const computePipeline2 = root.createGuardedComputePipeline((x, y, z) => { 'use gpu'; // ... }); ``` ``` -------------------------------- ### WebGPU Playground Example Source: https://github.com/software-mansion/typegpu/blob/main/apps/typegpu-docs/src/content/docs/tutorials/triangle-to-boids/index.mdx A complete WebGPU code example for rendering triangles with gradients, ready to be tested in the playground. ```typescript import step4webgpu from 'code/step4-webgpu.ts?raw'; ``` -------------------------------- ### Run Local Development Server Source: https://github.com/software-mansion/typegpu/blob/main/CONTRIBUTING.md Start a local development server for the docs/examples/benchmarking app. This command is useful for previewing changes during development. ```bash pnpm dev ``` -------------------------------- ### TypeGPU Playground Example Source: https://github.com/software-mansion/typegpu/blob/main/apps/typegpu-docs/src/content/docs/tutorials/triangle-to-boids/index.mdx A complete TypeGPU code example for rendering triangles with gradients, ready to be tested in the playground. ```typescript import step4typegpu from 'code/step4-typegpu.ts?raw'; ``` -------------------------------- ### Install Three.js and @typegpu/three with npm Source: https://github.com/software-mansion/typegpu/blob/main/apps/typegpu-docs/src/content/docs/ecosystem/typegpu-three/index.mdx Use this command to install the necessary packages for integrating TypeGPU with Three.js using npm. ```sh npm install three @typegpu/three ``` -------------------------------- ### Install Three.js and @typegpu/three with pnpm Source: https://github.com/software-mansion/typegpu/blob/main/apps/typegpu-docs/src/content/docs/ecosystem/typegpu-three/index.mdx Use this command to install the necessary packages for integrating TypeGPU with Three.js using pnpm. ```sh pnpm add three @typegpu/three ``` -------------------------------- ### Install wesl-ext-typegpu with npm Source: https://github.com/software-mansion/typegpu/blob/main/apps/typegpu-docs/src/content/docs/integration/wesl-interoperability.mdx Install the TypeGPU extension for WESL using npm. This package extends the capabilities of wesl-plugin. ```sh npm add --save-dev wesl-ext-typegpu ``` -------------------------------- ### Install unplugin-typegpu Source: https://github.com/software-mansion/typegpu/blob/main/packages/unplugin-typegpu/README.md Install the unplugin-typegpu package using npm. ```sh npm install unplugin-typegpu ``` -------------------------------- ### Initialize a Root with Default Requirements Source: https://github.com/software-mansion/typegpu/blob/main/apps/typegpu-docs/src/content/docs/apis/roots.mdx Use `tgpu.init` to create a root, requesting a GPU device with default requirements. This is the primary way to start using TypeGPU. ```ts import tgpu from 'typegpu'; const root = await tgpu.init(); ``` -------------------------------- ### Install wesl-ext-typegpu with pnpm Source: https://github.com/software-mansion/typegpu/blob/main/apps/typegpu-docs/src/content/docs/integration/wesl-interoperability.mdx Install the TypeGPU extension for WESL using pnpm. This package extends the capabilities of wesl-plugin. ```sh pnpm add -D wesl-ext-typegpu ``` -------------------------------- ### Install and Configure unplugin-typegpu for Shaders Source: https://context7.com/software-mansion/typegpu/llms.txt Install the unplugin-typegpu build plugin for Vite to process 'use gpu' directives and generate WGSL. ```bash npm install --save-dev unplugin-typegpu ``` -------------------------------- ### Install Three.js and @typegpu/three with yarn Source: https://github.com/software-mansion/typegpu/blob/main/apps/typegpu-docs/src/content/docs/ecosystem/typegpu-three/index.mdx Use this command to install the necessary packages for integrating TypeGPU with Three.js using yarn. ```sh yarn add three @typegpu/three ``` -------------------------------- ### Install wesl-ext-typegpu with yarn Source: https://github.com/software-mansion/typegpu/blob/main/apps/typegpu-docs/src/content/docs/integration/wesl-interoperability.mdx Install the TypeGPU extension for WESL using yarn. This package extends the capabilities of wesl-plugin. ```sh yarn add -D wesl-ext-typegpu ``` -------------------------------- ### Install and Run tgpu-gen Globally Source: https://github.com/software-mansion/typegpu/blob/main/apps/typegpu-docs/src/content/docs/tooling/tgpu-gen.mdx Install the tgpu-gen package globally using npm and then run the command with the path to your WGSL shader file. ```bash npm install -g tgpu-gen tgpu-gen path/to/shader.wgsl ``` -------------------------------- ### Accessor Creation Examples Source: https://github.com/software-mansion/typegpu/blob/main/apps/typegpu-docs/src/content/docs/apis/accessors.mdx Demonstrates different ways to create accessors, highlighting the preferred method for flexibility. The `tgpu.accessor(schema)` is recommended for reusable functions. ```typescript import tgpu, { type TgpuUniform, d } from 'typegpu'; // ---cut--- // 👎 only works with JS literals const staticColorSlot = tgpu.slot(); // 👎 requires a uniform binding that only carries that value const uniformColorSlot = tgpu.slot>(); // 👎 requires the value to be returned from a function const getColorSlot = tgpu.slot<() => d.v3f>(); // 💜 works with any value that matches the schema const colorAccess = tgpu.accessor(d.vec3f); ``` -------------------------------- ### Initialize TypeGPU and Canvas Context Source: https://github.com/software-mansion/typegpu/blob/main/apps/typegpu-docs/src/content/docs/tutorials/triangle-to-boids/index.mdx Sets up the TypeGPU root, accesses the HTML canvas, and configures the WebGPU canvas context. This is a common setup for rendering applications. ```typescript import tgpu from 'typegpu'; // Create the root const root = await tgpu.init(); // Access the HTML canvas const canvas = document.getElementById('canvas'); const context = canvas.getContext('webgpu') as GPUCanvasContext; // Configure the canvas context const presentationFormat = navigator.gpu.getPreferredCanvasFormat(); context.configure({ device: root.device, format: presentationFormat, alphaMode: 'premultiplied', }); ``` -------------------------------- ### Complete TypeGPU React Shader Example Source: https://github.com/software-mansion/typegpu/blob/main/apps/typegpu-docs/src/content/docs/ecosystem/typegpu-react/index.mdx A full example integrating `useRoot`, `useUniform`, `useMemo`, and `useFrame` to create a dynamic, animated shader effect within a React component. ```tsx import React from 'react'; // ---cut--- import { useMemo } from 'react'; import { d, common } from 'typegpu'; import { useConfigureContext, useFrame, useRoot, useUniform } from '@typegpu/react'; function MyEffect() { const root = useRoot(); const time = useUniform(d.f32); const renderPipeline = useMemo( () => root.createRenderPipeline({ vertex: common.fullScreenTriangle, fragment: ({ uv }) => { 'use gpu'; return d.vec4f((uv * 5 + time.$) % 1, 0, 1); }, }), [root, time], ); const { ref, ctxRef } = useConfigureContext(); useFrame(({ elapsedSeconds }) => { if (!ctxRef.current) return; time.write(elapsedSeconds); renderPipeline.withColorAttachment({ view: ctxRef.current }).draw(3); }); return ; } ``` -------------------------------- ### Resolving resources with a pipeline Source: https://github.com/software-mansion/typegpu/blob/main/apps/typegpu-docs/src/content/docs/apis/resolve.mdx This example demonstrates resolving a compute pipeline and its dependencies, including storage buffers and compute functions. ```APIDOC ### Example with a pipeline ```ts import tgpu, { d } from 'typegpu'; const root = await tgpu.init(); const dataMutable = root .createMutable(d.arrayOf(d.u32, 8), [1, 2, 3, 4, 5, 6, 7, 8]); const computeMain = tgpu.computeFn({ workgroupSize: [1], in: { gid: d.builtin.globalInvocationId }, })((input) => { const index = input.gid.x; dataMutable.$[index] *= 2; }); const multiplyPipeline = root.createComputePipeline({ compute: computeMain }); const resolved = tgpu.resolve([multiplyPipeline]); ``` ### Resolved WGSL ```wgsl @group(0) @binding(0) var dataMutable_1: array; struct computeMain_Input_2 { @builtin(global_invocation_id) gid: vec3u, } @compute @workgroup_size(1) fn computeMain_0(input: computeMain_Input_2) { var index = input.gid.x; dataMutable_1[index] *= 2u; } ``` ``` -------------------------------- ### HTML Canvas Setup Source: https://github.com/software-mansion/typegpu/blob/main/apps/typegpu-docs/src/content/docs/tutorials/triangle-to-boids/index.mdx Basic HTML structure to include a canvas element, which is essential for WebGPU rendering. ```html Making Triangles Fly ``` -------------------------------- ### Resolving resources with functions Source: https://github.com/software-mansion/typegpu/blob/main/apps/typegpu-docs/src/content/docs/apis/resolve.mdx The first tgpu.resolve overload takes in an array of items to resolve, and an optional argument with options. This example demonstrates resolving functions and their dependencies. ```APIDOC ## Resolving resources The `tgpu.resolve` API takes in TypeGPU resources (and optionally a WGSL template) and generates a ready-to-use WGSL bundle containing all transitive dependencies of the passed in objects. ### Example with functions ```ts import tgpu, { d } from 'typegpu'; const Boid = d.struct({ size: d.f32, color: d.vec4f, }); const createSmallBoid = tgpu.fn([], Boid)(() => { return Boid({ size: 1, color: d.vec4f(0, 1, 0, 1) }); }); const createBigBoid = tgpu.fn([], Boid)(() => { return Boid({ size: 10, color: d.vec4f(1, 0, 0, 1) }); }); const resolved = tgpu.resolve([createSmallBoid, createBigBoid]); ``` ### Resolved WGSL ```wgsl struct Boid_1 { size: f32, color: vec4f, } fn createSmallBoid_0() -> Boid_1 { return Boid_1(1f, vec4f(0, 1, 0, 1)); } fn createBigBoid_2() -> Boid_1 { return Boid_1(10f, vec4f(1, 0, 0, 1)); } ``` ``` -------------------------------- ### Write Slice to Buffer with Offset Source: https://github.com/software-mansion/typegpu/blob/main/apps/typegpu-docs/src/content/docs/apis/buffers.mdx Write a contiguous slice of data into a buffer starting at a specific byte offset. Use `d.memoryLayoutOf` to get the correct byte offset for schema elements. ```typescript import tgpu, { d } from 'typegpu'; const root = await tgpu.init(); // ---cut--- const schema = d.arrayOf(d.u32, 6); const buffer = root.createBuffer(schema, [0, 1, 2, 0, 0, 0]); // Get the byte offset of element [3] const layout = d.memoryLayoutOf(schema, (a) => a[3]); // Write [4, 5, 6] starting at element [3], leaving [0, 1, 2] untouched buffer.write([4, 5, 6], { startOffset: layout.offset }); const data = await buffer.read(); // will be [0, 1, 2, 4, 5, 6] ``` -------------------------------- ### Install Native Dependencies Source: https://github.com/software-mansion/typegpu/blob/main/apps/typegpu-docs/src/content/docs/integration/react-native/index.mdx Install native dependencies for iOS after prebuilding the project. This involves navigating to the ios directory and running 'pod install'. ```sh cd ios && pod install && cd .. ``` -------------------------------- ### Initialize a Root from an Existing Device Source: https://github.com/software-mansion/typegpu/blob/main/apps/typegpu-docs/src/content/docs/apis/roots.mdx Use `tgpu.initFromDevice` when you already have a `GPUDevice` instance and want to wrap it with TypeGPU's root functionality. ```ts import tgpu from 'typegpu'; const adapter = await navigator.gpu.requestAdapter(); const device = await adapter?.requestDevice() as GPUDevice; // using a preexisting device const root = tgpu.initFromDevice({ device }); ``` -------------------------------- ### Install eslint-plugin-typegpu with yarn Source: https://github.com/software-mansion/typegpu/blob/main/apps/typegpu-docs/src/content/docs/tooling/eslint-plugin-typegpu.mdx Install the plugin as a development dependency using yarn. ```sh yarn add -D eslint-plugin-typegpu ``` -------------------------------- ### tgpu.init / tgpu.initFromDevice - Creating a Root Source: https://context7.com/software-mansion/typegpu/llms.txt Initializes a TypeGPU root, which is the entry point for all resource allocation. It can automatically request a GPUDevice or wrap an existing one. The root can also be used to configure a canvas context and unwrap TypeGPU resources to their underlying WebGPU objects. ```APIDOC ## `tgpu.init` / `tgpu.initFromDevice` — Creating a Root A **root** is the entry point for all resource allocation. It wraps a `GPUDevice` and exposes `root.create*` methods for typed buffers, textures, pipelines, and bind groups. Call `tgpu.init()` to request a device automatically, or `tgpu.initFromDevice({ device })` to wrap an existing one. ```ts import tgpu from 'typegpu'; // Automatic device acquisition const root = await tgpu.init(); console.log(root.device); // GPUDevice // From an existing device const adapter = await navigator.gpu.requestAdapter(); const device = await adapter!.requestDevice(); const root2 = tgpu.initFromDevice({ device }); // Configure a canvas context (defaults to preferred format) const canvas = document.querySelector('canvas') as HTMLCanvasElement; const ctx = root.configureContext({ canvas, alphaMode: 'premultiplied' }); // Unwrap any TypeGPU resource to get the underlying WebGPU object const rawDevice: GPUDevice = root.device; // Clean up (calls device.destroy() unless initFromDevice was used) root.destroy(); ``` ``` -------------------------------- ### Install eslint-plugin-typegpu with pnpm Source: https://github.com/software-mansion/typegpu/blob/main/apps/typegpu-docs/src/content/docs/tooling/eslint-plugin-typegpu.mdx Install the plugin as a development dependency using pnpm. ```sh pnpm add -D eslint-plugin-typegpu ``` -------------------------------- ### Install eslint-plugin-typegpu with npm Source: https://github.com/software-mansion/typegpu/blob/main/apps/typegpu-docs/src/content/docs/tooling/eslint-plugin-typegpu.mdx Install the plugin as a development dependency using npm. ```sh npm add -D eslint-plugin-typegpu ``` -------------------------------- ### Install unplugin-typegpu Source: https://github.com/software-mansion/typegpu/blob/main/apps/typegpu-docs/src/content/docs/tooling/unplugin-typegpu.mdx Install the unplugin-typegpu package as a development dependency using your preferred package manager. ```sh npm install --save-dev unplugin-typegpu ``` ```sh pnpm add -D unplugin-typegpu ``` ```sh yarn add -D unplugin-typegpu ``` -------------------------------- ### Function Shell with WGSL Implementation Source: https://github.com/software-mansion/typegpu/blob/main/apps/typegpu-docs/src/content/docs/apis/functions/index.mdx Illustrates how to use `tgpu.fn` to create a function shell and provide an implementation directly in WGSL. ```APIDOC ## Function Shell with WGSL Implementation ### Description This example demonstrates defining a TypeGPU function by providing a WGSL code snippet directly to a function shell created with `tgpu.fn`. This allows for writing shader logic directly in WGSL. ### Method Signature `tgpu.fn([argument_schemas], return_schema)\`wgsl_code\`` ### Parameters - `argument_schemas`: An array of TypeGPU schemas representing the types of the function's arguments. - `return_schema`: A TypeGPU schema representing the function's return type. - `wgsl_code`: A tagged template literal containing the WGSL code for the function. ### Example 1: With explicit WGSL types ```ts import tgpu, { d } from 'typegpu'; const neighborhood = tgpu.fn([d.f32, d.f32], d.vec2f)`(a: f32, r: f32) -> vec2f { return vec2f(a - r, a + r); }`; ``` ### Example 2: Simplified WGSL header (types inferred from shell) ```ts import tgpu, { d } from 'typegpu'; const neighborhood = tgpu.fn([d.f32, d.f32], d.vec2f)`(a, r) { return vec2f(a - r, a + r); }`; ``` ### Example 3: With VS Code syntax highlighting hint ```ts import tgpu, { d } from 'typegpu'; const neighborhood = tgpu.fn([d.f32, d.f32], d.vec2f)/* wgsl */`(a, r) { return vec2f(a - r, a + r); }`; ``` ``` -------------------------------- ### Texture Creation and Initialization Source: https://github.com/software-mansion/typegpu/blob/main/apps/typegpu-docs/src/content/docs/apis/textures.mdx Demonstrates the basic creation of a texture with specified size and format, and setting its usage flags. ```APIDOC ## root.createTexture ### Description Creates a new texture with the specified properties and usage flags. ### Method ```typescript root.createTexture(descriptor: GPUTextureDescriptor) ``` ### Parameters #### Texture Descriptor - **size** (readonly number[]) - Required - The dimensions of the texture. - **format** (GPUTextureFormat) - Required - The pixel format of the texture. - **viewFormats** (GPUTextureFormat[] | undefined) - Optional - Specifies the view formats. - **dimension** (GPUTextureDimension | undefined) - Optional - The dimension of the texture (e.g., '2d', '3d'). - **mipLevelCount** (number | undefined) - Optional - The number of mip levels. - **sampleCount** (number | undefined) - Optional - The sample count for multi-sampling. ### Usage Flags Textures require usage flags to define their purpose. These are set using the `.$usage()` method. #### `.$usage(flag: 'sampled' | 'storage' | 'render', ...flags: ('sampled' | 'storage' | 'render')[])` Adds one or more usage flags to the texture. ### Request Example ```ts import tgpu from 'typegpu'; const root = await tgpu.init(); const texture = root.createTexture({ size: [256, 256], format: 'rgba8unorm', }).$usage('sampled', 'storage', 'render'); ``` ``` -------------------------------- ### Creating Buffers with Initializer Callback Source: https://github.com/software-mansion/typegpu/blob/main/apps/typegpu-docs/src/content/docs/apis/buffers.mdx Shows how to use a callback function to populate a newly created buffer. ```APIDOC ## createBuffer with Initializer Callback ### Description Creates a buffer and uses a callback function to populate its initial data. ### Method `root.createBuffer(type, initializerCallback)` ### Parameters - **type**: The TypeGPU data type for the buffer. - **initializerCallback**: A function that receives the mapped buffer and can write data to it. ### Request Example ```ts const Schema = d.arrayOf(d.u32, 6); const firstChunk = d.memoryLayoutOf(Schema, (a) => a[1]); const secondChunk = d.memoryLayoutOf(Schema, (a) => a[4]); const buffer = root.createBuffer(Schema, (mappedBuffer) => { mappedBuffer.write([10, 20], { startOffset: firstChunk.offset }); mappedBuffer.write([30, 40], { startOffset: secondChunk.offset }); }); ``` ``` -------------------------------- ### Create Vertex and Fragment Entry Points in TypeGPU Source: https://context7.com/software-mansion/typegpu/llms.txt Define vertex and fragment shader entry points using `tgpu.vertexFn` and `tgpu.fragmentFn`. This example sets up vertex positions and UV coordinates. ```typescript // --- @vertex + @fragment entry functions --- const mainVertex = tgpu.vertexFn({ in: { vertexIndex: d.builtin.vertexIndex }, out: { pos: d.builtin.position, uv: d.vec2f }, })((input) => { 'use gpu'; const positions = [d.vec2f(-1, -1), d.vec2f(3, -1), d.vec2f(-1, 3)]; const uvCoords = [d.vec2f(0, 0), d.vec2f(2, 0), d.vec2f(0, 2)]; return { pos: d.vec4f(positions[input.vertexIndex], 0, 1), uv: uvCoords[input.vertexIndex], }; }); const mainFragment = tgpu.fragmentFn({ in: { uv: d.vec2f }, out: d.vec4f, })((input) => { 'use gpu'; return d.vec4f(input.uv, 0, 1); }); ``` -------------------------------- ### Initialize TypeGPU Source: https://github.com/software-mansion/typegpu/blob/main/apps/typegpu-docs/src/content/docs/integration/webgpu-interoperability.mdx Initialize TypeGPU with a root object, either automatically or by providing an existing WebGPU device. ```ts import tgpu, { d } from 'typegpu'; const root = await tgpu.init(); // ...or pass in an existing WebGPU device const root = tgpu.initFromDevice({ device }); ``` -------------------------------- ### Function Shell with JavaScript Implementation Source: https://github.com/software-mansion/typegpu/blob/main/apps/typegpu-docs/src/content/docs/apis/functions/index.mdx Demonstrates creating a function shell using `tgpu.fn` and providing a JavaScript implementation for the function. ```APIDOC ## Function Shell with JavaScript Implementation ### Description This example shows how to define a function shell using `tgpu.fn` to strictly type function arguments and return values. A JavaScript function is then provided to this shell. ### Method Signature `tgpu.fn([argument_schemas], return_schema)(javascript_function)` ### Parameters - `argument_schemas`: An array of TypeGPU schemas representing the types of the function's arguments. - `return_schema`: A TypeGPU schema representing the function's return type. - `javascript_function`: The JavaScript function to be wrapped by the shell. ### Example 1: Separate Definition ```ts import tgpu, { d } from 'typegpu'; const neighborhood = (a: number, r: number) => { 'use gpu'; return d.vec2f(a - r, a + r); }; const neighborhoodShell = tgpu.fn([d.f32, d.f32], d.vec2f); // Works the same as `neighborhood`, but more strictly typed const neighborhoodF32 = neighborhoodShell(neighborhood); ``` ### Example 2: Immediate Wrapping ```ts import tgpu, { d } from 'typegpu'; const neighborhood = tgpu.fn([d.f32, d.f32], d.vec2f)((a, r) => { 'use gpu'; return d.vec2f(a - r, a + r); }); ``` ``` -------------------------------- ### Install Dependencies for React Native Source: https://github.com/software-mansion/typegpu/blob/main/apps/typegpu-docs/src/content/docs/integration/react-native/index.mdx Install the necessary packages for TypeGPU and react-native-wgpu. Includes development dependencies for type checking. ```sh npm i react-native-wgpu typegpu @typegpu/react npm i --save-dev unplugin-typegpu @webgpu/types ``` -------------------------------- ### Resource Binding with `with` Source: https://github.com/software-mansion/typegpu/blob/main/apps/typegpu-docs/src/content/docs/apis/pipelines.mdx Demonstrates how to bind resources like vertex layouts, vertex buffers, and bind groups to pipelines before execution using the `with` method. ```APIDOC ## Resource Binding Before executing pipelines, it is necessary to bind all of the utilized resources, like bind groups, vertex buffers and slots. It is done using the `with` method. It accepts either [a bind group](/TypeGPU/apis/bind-groups) (render and compute pipelines) or [a vertex layout and a vertex buffer](/TypeGPU/apis/vertex-layouts) (render pipelines only). ```ts // vertex layout const vertexLayout = tgpu.vertexLayout( d.disarrayOf(d.float16), 'vertex', ); const vertexBuffer = root .createBuffer(d.disarrayOf(d.float16, 8), [0, 0, 1, 0, 0, 1, 1, 1]) .$usage('vertex'); // bind group layout const bindGroupLayout = tgpu.bindGroupLayout({ size: { uniform: d.vec2u }, }); const sizeBuffer = root .createBuffer(d.vec2u, d.vec2u(64, 64)) .$usage('uniform'); const bindGroup = root.createBindGroup(bindGroupLayout, { size: sizeBuffer, }); // binding and execution renderPipeline .with(vertexLayout, vertexBuffer) .with(bindGroup) .draw(8); computePipeline .with(bindGroup) .dispatchWorkgroups(1); ``` ``` -------------------------------- ### Get TypeGPU Root in React Source: https://github.com/software-mansion/typegpu/blob/main/apps/typegpu-docs/src/content/docs/ecosystem/typegpu-react/index.mdx Use the `useRoot` hook to get a reference to the TypeGPU root within your React component. ```tsx import { useRoot } from '@typegpu/react'; function MyEffect() { const root = useRoot(); // the rest of our code will be here } ``` -------------------------------- ### Create and Use a Render Pipeline with TypeGPU Source: https://github.com/software-mansion/typegpu/blob/main/apps/typegpu-docs/src/content/docs/apis/functions/index.mdx Demonstrates how to create a render pipeline using defined vertex and fragment shaders and then use it to draw geometry. This example shows a simple triangle rendering. ```typescript import tgpu, { d } from 'typegpu'; const context = undefined as any; const presentationFormat = "rgba8unorm"; const root = await tgpu.init(); const getGradientColor = tgpu.fn([d.f32], d.vec4f)/* wgsl */``; const mainVertex = tgpu.vertexFn({ in: { vertexIndex: d.builtin.vertexIndex }, out: { outPos: d.builtin.position, uv: d.vec2f }, })``; const mainFragment = tgpu.fragmentFn({ in: { uv: d.vec2f }, out: d.vec4f, })``; // ---cut--- const pipeline = root.createRenderPipeline({ vertex: mainVertex, fragment: mainFragment, }); pipeline .withColorAttachment({ view: context }) .draw(3); ``` -------------------------------- ### Creating and Initializing a Buffer Source: https://github.com/software-mansion/typegpu/blob/main/apps/typegpu-docs/src/content/docs/apis/buffers.mdx Demonstrates how to create a buffer for storing particles, define its schema using `d.struct` and `d.arrayOf`, initialize it with data, and set its usage to 'storage'. ```APIDOC ## Creating and Initializing a Buffer To create a buffer, you will need to define its schema by composing data types imported from `typegpu/data`. Every WGSL data-type can be represented as JS schemas, including structs and arrays. ```ts twoslash import tgpu, { d } from 'typegpu'; // Defining a struct type const Particle = d.struct({ position: d.vec3f, velocity: d.vec3f, health: d.f32, }); // Utility for creating a random particle function createParticle(): d.InferInput { return { position: d.vec3f(Math.random(), 2, Math.random()), velocity: d.vec3f(0, 9.8, 0), health: 100, }; } const root = await tgpu.init(); // Creating and initializing a buffer. const buffer = root .createBuffer( d.arrayOf(Particle, 100), // <- holds 100 particles Array.from({ length: 100 }).map(createParticle), // <- initial value ) .$usage('storage'); // <- can be used as a "storage buffer" // Reading back from the buffer const value = await buffer.read(); ``` ``` -------------------------------- ### Install WebGPU types with yarn Source: https://github.com/software-mansion/typegpu/blob/main/apps/typegpu-docs/src/content/docs/getting-started.mdx Install the @webgpu/types package as a development dependency using yarn. TypeScript does not include WebGPU types by default. ```sh yarn add -D @webgpu/types ``` -------------------------------- ### Install WebGPU types with pnpm Source: https://github.com/software-mansion/typegpu/blob/main/apps/typegpu-docs/src/content/docs/getting-started.mdx Install the @webgpu/types package as a development dependency using pnpm. TypeScript does not include WebGPU types by default. ```sh pnpm add -D @webgpu/types ``` -------------------------------- ### Create Basic Render Pipeline Source: https://context7.com/software-mansion/typegpu/llms.txt Configures a WebGPU context and creates a basic render pipeline with vertex and fragment shaders. The pipeline is used to draw a full-screen triangle. ```typescript import tgpu, { d } from 'typegpu'; const root = await tgpu.init(); const canvas = document.querySelector('canvas') as HTMLCanvasElement; const ctx = root.configureContext({ canvas }); const vertex = tgpu.vertexFn({ in: { vertexIndex: d.builtin.vertexIndex }, out: { pos: d.builtin.position, uv: d.vec2f }, })((input) => { 'use gpu'; const pos = [d.vec2f(-1, -1), d.vec2f(3, -1), d.vec2f(-1, 3)]; const uv = [d.vec2f(0, 0), d.vec2f(2, 0), d.vec2f(0, 2)]; return { pos: d.vec4f(pos[input.vertexIndex], 0, 1), uv: uv[input.vertexIndex] }; }); const fragment = tgpu.fragmentFn({ in: { uv: d.vec2f }, out: d.vec4f, })((input) => { 'use gpu'; return d.vec4f(input.uv, 0, 1); }); // --- Basic render pipeline --- const renderPipeline = root.createRenderPipeline({ vertex, fragment, targets: { format: navigator.gpu.getPreferredCanvasFormat() }, }); function frame() { renderPipeline .withColorAttachment({ view: ctx, clearValue: [0, 0, 0, 1], loadOp: 'clear', storeOp: 'store', }) .draw(3); // 3 vertices of full-screen triangle requestAnimationFrame(frame); } requestAnimationFrame(frame); ``` -------------------------------- ### Install WebGPU types with npm Source: https://github.com/software-mansion/typegpu/blob/main/apps/typegpu-docs/src/content/docs/getting-started.mdx Install the @webgpu/types package as a development dependency using npm. TypeScript does not include WebGPU types by default. ```sh npm install --save-dev @webgpu/types ``` -------------------------------- ### Initialize TypeGPU Root Source: https://context7.com/software-mansion/typegpu/llms.txt Create a TypeGPU root, which is the entry point for resource allocation. It can automatically acquire a GPUDevice or wrap an existing one. Configure a canvas context for rendering. ```typescript import tgpu from 'typegpu'; // Automatic device acquisition const root = await tgpu.init(); console.log(root.device); // GPUDevice // From an existing device const adapter = await navigator.gpu.requestAdapter(); const device = await adapter!.requestDevice(); const root2 = tgpu.initFromDevice({ device }); // Configure a canvas context (defaults to preferred format) const canvas = document.querySelector('canvas') as HTMLCanvasElement; const ctx = root.configureContext({ canvas, alphaMode: 'premultiplied' }); // Unwrap any TypeGPU resource to get the underlying WebGPU object const rawDevice: GPUDevice = root.device; // Clean up (calls device.destroy() unless initFromDevice was used) root.destroy(); ``` -------------------------------- ### Standard Library Function Example Source: https://github.com/software-mansion/typegpu/blob/main/apps/typegpu-docs/src/content/docs/apis/functions/index.mdx Example of using a standard library function like `std.abs` and `std.max` within a TypeGPU function marked with 'use gpu'. ```APIDOC ## Standard Library Function Example ### Description This example demonstrates how to use functions from the `typegpu/std` library, such as `std.abs` and `std.max`, within a TypeGPU function. The function is marked with `'use gpu'` to indicate it can be compiled for the GPU. ### Code ```ts import { d, std } from 'typegpu'; function manhattanDistance(a: d.v3f, b: d.v3f) { 'use gpu'; const dx = std.abs(a.x - b.x); const dy = std.abs(a.y - b.y); const dz = std.abs(a.z - b.z); return std.max(dx, dy, dz); } ``` ``` -------------------------------- ### Creating Buffers from Existing WebGPU Buffers Source: https://github.com/software-mansion/typegpu/blob/main/apps/typegpu-docs/src/content/docs/apis/buffers.mdx Explains how to create a TypeGPU buffer that wraps an existing WebGPU buffer. ```APIDOC ## createBuffer from Existing WebGPU Buffer ### Description Creates a TypeGPU buffer instance from an existing `GPUBuffer`. ### Method `root.createBuffer(type, existingGpuBuffer)` ### Parameters - **type**: The TypeGPU data type that the `existingGpuBuffer` conforms to. - **existingGpuBuffer**: An existing `GPUBuffer` object. ### Request Example ```ts // A raw WebGPU buffer const existingBuffer = root.device.createBuffer({ size: 4, usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_DST, }); const buffer = root.createBuffer(d.u32, existingBuffer); buffer.write(12); // Writing to `existingBuffer` through a type-safe API ``` :::caution[WebGPU Interoperability] Since the buffer is already created, you are responsible for the buffer's lifecycle and ensuring the type matches the buffer's contents. ::: ``` -------------------------------- ### Get Help with tgpu-gen CLI Source: https://github.com/software-mansion/typegpu/blob/main/apps/typegpu-docs/src/content/docs/tooling/tgpu-gen.mdx Run `tgpu-gen --help` to get a quick overview of the generator's arguments and options. The `-h` option is a shorthand for `--help`. ```bash tgpu-gen --help ``` -------------------------------- ### Initialize and Get TypeGPU Root Source: https://github.com/software-mansion/typegpu/blob/main/apps/typegpu-docs/src/content/docs/apis/roots.mdx Use this utility to get an existing TgpuRoot for a GPUDevice or initialize a new one if it doesn't exist. This ensures a single root is used per device, facilitating resource sharing. ```typescript const deviceToRootMap = new WeakMap(); function getOrInitRoot(device: GPUDevice): TgpuRoot { let root = deviceToRootMap.get(device); if (!root) { root = tgpu.initFromDevice({ device }); deviceToRootMap.set(device, root); } return root; } ``` -------------------------------- ### Enable WebGPU in Deno via CLI flag Source: https://github.com/software-mansion/typegpu/blob/main/apps/typegpu-docs/src/content/docs/blog/troubleshooting.md Run your Deno script with the --unstable-webgpu flag to enable WebGPU support. ```bash deno run --unstable-webgpu your_script.ts ``` -------------------------------- ### Creating a Bind Group Source: https://github.com/software-mansion/typegpu/blob/main/apps/typegpu-docs/src/content/docs/apis/bind-groups.mdx Example of defining a bind group layout and creating a bind group with specified resources. ```APIDOC ## Creating a Bind Group ### Description This example demonstrates how to define the layout for resources accessible by a shader and then create a bind group that fulfills this layout. ### Code Example ```ts import tgpu, { d } from 'typegpu'; // Defining the layout of resources we want the shader to // have access to. const fooLayout = tgpu.bindGroupLayout({ foo: { uniform: d.vec3f }, bar: { texture: d.texture2d(d.f32) }, }); const fooBuffer = ...; const barTexture = ...; // Create a bind group that can fulfill the required layout. const fooBindGroup = root.createBindGroup(fooLayout, { foo: fooBuffer, bar: barTexture, }); ``` ### Usage in Command Encoding ### Description Once a bind group is created, it can be assigned to a shader stage during command encoding. ### Code Example ```ts // Assuming group index is 0... pass.setBindGroup(0, root.unwrap(fooBindGroup)); ``` ``` -------------------------------- ### Dispatch Compute Shader Threads Source: https://github.com/software-mansion/typegpu/blob/main/apps/typegpu-docs/src/content/docs/fundamentals/your-first-gpu-program.mdx Executes the compute shader program. This example dispatches threads for a program that increments a counter. ```typescript import tgpu, { d } from 'typegpu'; const root = await tgpu.init(); // ---cut--- const stateMutable = root.createMutable( d.struct({ counter: d.u32, incrementBy: d.u32 }), ); const initializeBuffer = root.createGuardedComputePipeline(() => { 'use gpu'; stateMutable.$.incrementBy = 10; }); const program = root.createGuardedComputePipeline(() => { 'use gpu'; stateMutable.$.counter += stateMutable.$.incrementBy; }); initializeBuffer.dispatchThreads(); program.dispatchThreads(); ``` -------------------------------- ### Initialize a Matrix as Identity with wgpu-matrix Source: https://github.com/software-mansion/typegpu/blob/main/apps/typegpu-docs/src/content/docs/integration/working-with-wgpu-matrix.mdx Shows how to initialize a TypeGPU matrix as an identity matrix using wgpu-matrix utilities. ```typescript import { d } from 'typegpu'; import { mat4 } from 'wgpu-matrix'; const m = mat4.identity(d.mat4x4f()); // returns a mat4x4f console.log(m[0]); // 1 ``` -------------------------------- ### Define WGSL struct in a .wesl file Source: https://github.com/software-mansion/typegpu/blob/main/apps/typegpu-docs/src/content/docs/integration/wesl-interoperability.mdx Example of defining a struct in a WESL file. This struct will be reflected into TypeScript definitions. ```wgsl struct BoidState { position: vec3f, velocity: vec3f, } struct Fish { kind: u32, state: BoidState, } ``` -------------------------------- ### Create Render and Compute Pipelines with TypeGPU Source: https://github.com/software-mansion/typegpu/blob/main/apps/typegpu-docs/src/content/docs/apis/pipelines.mdx Demonstrates the creation of render, compute, and guarded compute pipelines using the TypeGPU root object. This is the primary method for setting up GPU operations. ```typescript /// import tgpu, { d } from 'typegpu'; const root = await tgpu.init(); const presentationFormat = 'rgba8unorm'; const mainVertex = tgpu.vertexFn({ in: { vertexIndex: d.builtin.vertexIndex }, out: { pos: d.builtin.position }, })((input) => { const pos = [d.vec2f(-1, -1), d.vec2f(3, -1), d.vec2f(-1, 3)]; return { pos: d.vec4f(pos[input.vertexIndex], 0, 1), }; }); const mainFragment = tgpu.fragmentFn({ out: d.vec4f })(() => d.vec4f(1, 0, 0, 1)); const mainCompute = tgpu.computeFn({ workgroupSize: [1] })(() => {}); // ---cut--- const renderPipeline = root.createRenderPipeline({ vertex: mainVertex, fragment: mainFragment, targets: { format: presentationFormat }, }); const computePipeline1 = root.createComputePipeline({ compute: mainCompute, }); const computePipeline2 = root.createGuardedComputePipeline((x, y, z) => { 'use gpu'; // ... }); ``` -------------------------------- ### Recreate Root and Resources in React Component Source: https://github.com/software-mansion/typegpu/blob/main/apps/typegpu-docs/src/content/docs/apis/roots.mdx Example demonstrating how to create a new root and associated resources within a React component's lifecycle hook when the GPU device is provided externally. ```tsx // example.tsx import React from 'react'; function SceneView() { const ref = useWebGPU(({ context, device, presentationFormat }) => { const root = tgpu.initFromDevice({ device }); // create all resources... }); // ... } ``` -------------------------------- ### Interoperability Example with TypeGPU Source: https://github.com/software-mansion/typegpu/blob/main/README.md Demonstrates passing typed WebGPU buffers between different libraries without data copying. Imports are required from TypeGPU, a procedural generation library, and a plotting library. ```typescript import tgpu from 'typegpu'; import gen from '@xyz/gen'; import plot from '@abc/plot'; // common root for allocating resources const root = await tgpu.init(); const terrainBuffer = await gen.generateHeightMap(root, { ... }); // ^? TgpuBuffer>> & StorageFlag // ERROR: Argument of type 'TgpuBuffer>>' is // not assignable to parameter of type 'TgpuBuffer>>' plot.array1d(root, terrainBuffer); // SUCCESS! plot.array2d(root, terrainBuffer); ``` -------------------------------- ### Generated WGSL from TypeGPU Function Source: https://github.com/software-mansion/typegpu/blob/main/apps/typegpu-docs/src/content/docs/apis/functions/index.mdx This is an example of the WGSL code generated from a TypeGPU function. It demonstrates how operators and TS types are translated. ```wgsl // Generated WGSL fn neighborhood(a: f32, r: f32) -> vec2f { return vec2f(a - r, a + r); } fn main() -> vec2f { return neighborhood(1.1, 0.5); } // ... ``` -------------------------------- ### Configure WebGPU Context Source: https://github.com/software-mansion/typegpu/blob/main/apps/typegpu-docs/src/content/docs/ecosystem/typegpu-react/index.mdx Use `useConfigureContext` to get a ref for the canvas element and access to the WebGPU context. This hook is essential for rendering. ```tsx // ... const { ref, ctxRef } = useConfigureContext(); return ; } ``` -------------------------------- ### Publish Package Source: https://github.com/software-mansion/typegpu/blob/main/CONTRIBUTING.md Publish the TypeGPU package to the registry. Use the `--tag alpha` option for alpha releases. ```bash cd packages/typegpu pnpm publish # (if alpha, --tag alpha) ``` -------------------------------- ### Create Compute Entry Point with WGSL Body in TypeGPU Source: https://context7.com/software-mansion/typegpu/llms.txt Define a compute shader entry point using `tgpu.computeFn` with a WGSL implementation provided via template literals. This example updates particle data based on delta time. ```typescript // --- @compute entry (WGSL body) --- const particleData = root.createMutable(d.arrayOf(d.f32, 100)); const deltaTime = root.createUniform(d.f32); const simulateCompute = tgpu.computeFn({ in: { gid: d.builtin.globalInvocationId }, workgroupSize: [1], })/* wgsl */`{ let idx = in.gid.x; particleData[idx] += deltaTime * 0.01; }`.$uses({ particleData: particleData.as('mutable'), deltaTime }); ```