### Stand-alone HTML Rendering with Use.GPU Source: https://usegpu.live/docs/guides-getting-started Demonstrates how to render a Use.GPU application within a stand-alone HTML page. It requires importing React and the render function, then dynamically importing the application component and rendering it. This setup is useful for simple Use.GPU integrations without a framework. ```typescript import React, { render } from '@use-gpu/live'; window.onload = async () => { const { App } = await import('./app'); render(); } ``` -------------------------------- ### Webpack Configuration for WGSL Loader Source: https://usegpu.live/docs/guides-getting-started Provides an example of a webpack configuration snippet to integrate the '@use-gpu/wgsl-loader'. This configuration allows webpack to process `.wgsl` files, converting them into JavaScript modules that can be imported and used as shaders within the Use.GPU project. It also includes configuration for Babel loader. ```javascript { module: { rules: [ { test: /\.(ts|js)x?$/, exclude: [/node_modules/], loader: 'babel-loader', }, { test: /\.wgsl$/i, use: ['@use-gpu/wgsl-loader'], }, ], }, } ``` -------------------------------- ### @use-gpu/parse - Installation Source: https://usegpu.live/docs/reference-library-%40use-gpu-parse Instructions for installing the @use-gpu/parse library using npm or yarn. ```APIDOC ## Installation ### npm ```bash npm install --save @use-gpu/parse ``` ### yarn ```bash yarn add @use-gpu/parse ``` ``` -------------------------------- ### Install @use-gpu/shader using npm or yarn Source: https://usegpu.live/docs/reference-library-%40use-gpu-shader Instructions for installing the @use-gpu/shader library using package managers. ```bash npm install --save @use-gpu/shader ``` ```bash yarn add @use-gpu/shader ``` -------------------------------- ### Install @use-gpu/text Source: https://usegpu.live/docs/reference-live-%40use-gpu-traits Instructions for installing the @use-gpu/text library using npm or yarn. ```shell npm install --save @use-gpu/text ``` ```shell yarn add @use-gpu/text ``` -------------------------------- ### Install @use-gpu/react with npm Source: https://usegpu.live/docs/reference-components-%40use-gpu-react Install the @use-gpu/react package using npm for integrating Live and React components. ```bash npm install --save @use-gpu/react ``` -------------------------------- ### Install @use-gpu/react with yarn Source: https://usegpu.live/docs/reference-components-%40use-gpu-react Install the @use-gpu/react package using yarn for integrating Live and React components. ```bash yarn add @use-gpu/react ``` -------------------------------- ### Install @use-gpu/parse with npm Source: https://usegpu.live/docs/reference-library-%40use-gpu-parse Installs the @use-gpu/parse library using npm, a package manager for Node.js. This is the first step to include the parsing utilities in your project. ```bash npm install --save @use-gpu/parse ``` -------------------------------- ### Install @use-gpu/scene with npm Source: https://usegpu.live/docs/reference-components-%40use-gpu-scene Installs the @use-gpu/scene library using npm. This is a package manager for JavaScript, commonly used for installing and managing project dependencies. ```bash npm install --save @use-gpu/scene ``` -------------------------------- ### Install @use-gpu/layout with npm Source: https://usegpu.live/docs/reference-components-%40use-gpu-layout Installs the @use-gpu/layout package using npm. This package provides components for building 2D layouts in Use.GPU applications. ```bash npm install --save @use-gpu/layout ``` -------------------------------- ### Live Component Definition for Use.GPU Source: https://usegpu.live/docs/guides-getting-started Illustrates the structure of a Live component used within the Use.GPU ecosystem. It defines a component that accepts props, including the canvas element, and uses the LC type from '@use-gpu/live'. This pattern is key for building UIs with Use.GPU's declarative runtime. ```typescript import type { LC, PropsWithChildren } from '@use-gpu/live'; type ComponentProps = { canvas: HTMLCanvasElement, }; // This is a Live component export const Component: LC = (props: PropsWithChildren) => { const {canvas} = props; // ... return null; }; ``` -------------------------------- ### Install @use-gpu/glsl-loader with npm or yarn Source: https://usegpu.live/docs/reference-loader-%40use-gpu-glsl-loader Instructions for installing the @use-gpu/glsl-loader package using either npm or yarn package managers. This is the first step to using the loader in your project. ```bash npm install --save @use-gpu/glsl-loader ``` ```bash yarn add @use-gpu/glsl-loader ``` -------------------------------- ### WebGPU Canvas Setup and Drawing Source: https://usegpu.live/docs/reference-library-%40use-gpu-core-ArrayLike Demonstrates setting up a WebGPU canvas for drawing and animation. It covers the fundamental steps required to initialize WebGPU context and initiate rendering loops. ```typescript import { UseGPU } from "@use-gpu/core"; const gpu = new UseGPU(); const canvas = document.createElement('canvas'); document.body.appendChild(canvas); const adapter = await gpu.requestAdapter(); const device = await adapter.requestDevice(); const context = canvas.getContext("webgpu"); const format = navigator.gpu.getPreferredCanvasFormat(); context.configure({ device, format, alphaMode: "opaque" }); // ... drawing and animation logic ... ``` -------------------------------- ### Install @use-gpu/glyph with npm Source: https://usegpu.live/docs/reference-library-%40use-gpu-glyph Installs the @use-gpu/glyph library using npm. This is the first step to using the library's SDF and font glyph rendering capabilities. ```bash npm install --save @use-gpu/glyph ``` -------------------------------- ### Install @use-gpu/inspect-gpu with npm Source: https://usegpu.live/docs/reference-components-%40use-gpu-inspect-gpu This code snippet shows how to install the @use-gpu/inspect-gpu package using npm. This is the first step to integrate the WebGPU inspector into your project. ```bash npm install --save @use-gpu/inspect-gpu ``` -------------------------------- ### WebGPU Canvas Setup and Drawing Source: https://usegpu.live/docs/reference-library-%40use-gpu-core--makeDataBuffer Demonstrates how to set up a WebGPU canvas and perform basic drawing and animation operations. This involves initializing the WebGPU context and rendering frames. ```javascript const canvas = document.getElementById('gpu-canvas'); const adapter = await navigator.gpu.requestAdapter(); const device = await adapter.requestDevice(); const context = canvas.getContext('webgpu'); const presentationFormat = navigator.gpu.getPreferredCanvasFormat(); context.configure({ device: device, format: presentationFormat, alphaMode: 'premultiplied' }); // ... rendering logic ... function render() { const view = new Float32Array([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]); // Example view matrix const projection = new Float32Array([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]); // Example projection matrix const commandEncoder = device.createCommandEncoder(); const textureView = context.getCurrentTexture().createView(); const renderPassDescriptor = { colorAttachments: [ { view: textureView, clearValue: { r: 0.0, g: 0.0, b: 0.0, a: 1.0 }, loadOp: 'clear', storeOp: 'store' } ] }; const passEncoder = commandEncoder.beginRenderPass(renderPassDescriptor); // ... draw calls ... passEncoder.end(); device.queue.submit([commandEncoder.finish()]); } render(); setInterval(render, 16); // Approximately 60 FPS ``` -------------------------------- ### Install @use-gpu/layout with yarn Source: https://usegpu.live/docs/reference-components-%40use-gpu-layout Installs the @use-gpu/layout package using yarn. This package is essential for utilizing the 2D layout system within Use.GPU projects. ```bash yarn add @use-gpu/layout ``` -------------------------------- ### Install @use-gpu/parse with yarn Source: https://usegpu.live/docs/reference-library-%40use-gpu-parse Installs the @use-gpu/parse library using yarn, an alternative package manager for Node.js. This command adds the parsing utilities to your project's dependencies. ```bash yarn add @use-gpu/parse ``` -------------------------------- ### Install @use-gpu/glyph with yarn Source: https://usegpu.live/docs/reference-library-%40use-gpu-glyph Installs the @use-gpu/glyph library using yarn. This command adds the library as a dependency to your project, enabling its use in your application. ```bash yarn add @use-gpu/glyph ``` -------------------------------- ### Use.GPU React-like Component Structure Source: https://usegpu.live/docs/index Demonstrates the basic component tree structure in Use.GPU, similar to React, starting with an `` component and nesting Use.GPU components like `` and `` to create graphics. ```jsx ``` -------------------------------- ### Install @use-gpu/state using npm or yarn Source: https://usegpu.live/docs/reference-live-%40use-gpu-state Install the @use-gpu/state library using either npm or yarn package managers. This library is essential for state management operations within your project. ```bash npm install --save @use-gpu/state ``` ```bash yarn add @use-gpu/state ``` -------------------------------- ### Install @use-gpu/scene with yarn Source: https://usegpu.live/docs/reference-components-%40use-gpu-scene Installs the @use-gpu/scene library using yarn. Yarn is another popular JavaScript package manager that provides a faster and more reliable way to manage dependencies. ```bash yarn add @use-gpu/scene ``` -------------------------------- ### Webpack Hot Module Reloading Configuration Source: https://usegpu.live/docs/guides-getting-started Details the webpack configuration required to enable Hot Module Reloading (HMR) for Use.GPU projects using webpack-dev-server. This involves adding the HMR client to the entry point, enabling the hot option in devServer, and wrapping the application component with the hot function. ```javascript { entry: [ './src/index.tsx', 'webpack-dev-server/client/index.js?hot=true&live-reload=true', ], } { devServer: { // ... hot: true, }, } import React, { hot } from '@use-gpu/live'; export const App = hot(() => { // ... }, module); // or `import.meta` if using Vite ``` -------------------------------- ### React Component with LiveCanvas for Use.GPU Source: https://usegpu.live/docs/guides-getting-started Shows how to use the LiveCanvas component from '@use-gpu/react' to embed Use.GPU within a React application. The LiveCanvas acts as a bridge, allowing Live components to be rendered inside it, receiving the canvas element as a prop. This facilitates seamless integration between React and Use.GPU's Live runtime. ```typescript import React, { FC } from 'react'; import { LiveCanvas } from '@use-gpu/react'; import { Component } from './component'; // This is a React component const MyCanvas: FC = () => { return ( // These are Live children {(canvas) => } ); } ``` -------------------------------- ### Install @use-gpu/inspect-gpu with yarn Source: https://usegpu.live/docs/reference-components-%40use-gpu-inspect-gpu This code snippet shows how to install the @use-gpu/inspect-gpu package using yarn. This is an alternative to npm for package management. ```bash yarn add @use-gpu/inspect-gpu ``` -------------------------------- ### Install @use-gpu/inspect with npm Source: https://usegpu.live/docs/reference-components-%40use-gpu-inspect This snippet shows how to install the @use-gpu/inspect package using npm, a popular package manager for Node.js and the JavaScript runtime environment. This is a prerequisite for using the live inspector. ```bash npm install --save @use-gpu/inspect ``` -------------------------------- ### WGSL Dynamic Function Prototype Import Example Source: https://usegpu.live/docs/reference-library-%40use-gpu-shader Shows how to declare a function prototype for dynamic linking in WGSL, allowing the function definition to be provided at runtime. ```wgsl @link fn getColor() -> vec4 {}; ``` -------------------------------- ### WGSL Static Symbol Import Example Source: https://usegpu.live/docs/reference-library-%40use-gpu-shader Demonstrates how to import specific symbols (functions, declarations, types) from another WGSL module using static import syntax. ```wgsl use 'path/to/color'::{ getColor }; ``` -------------------------------- ### Install @use-gpu/inspect with yarn Source: https://usegpu.live/docs/reference-components-%40use-gpu-inspect This snippet demonstrates how to install the @use-gpu/inspect package using yarn, an alternative package manager for Node.js. This command adds the package as a dependency to your project. ```bash yarn add @use-gpu/inspect ``` -------------------------------- ### WGSL Shader Bundle Linking in JavaScript/TypeScript Source: https://usegpu.live/docs/reference-library-%40use-gpu-shader Example of importing a WGSL shader file in JS/TS and then linking it into a single bundle using the @use-gpu/shader library. ```javascript // WGSL in JS/TS import mainShader from 'path/to/main.wgsl'; import { linkBundle } from '@use-gpu/shader/wgsl'; const wgslCode = linkBundle(mainShader); ``` -------------------------------- ### GLSL Static Symbol Import Example Source: https://usegpu.live/docs/reference-library-%40use-gpu-shader Demonstrates how to import specific symbols (functions, declarations, types) from another GLSL module using the #pragma import directive. ```glsl #pragma import { getColor } from 'path/to/color' ``` -------------------------------- ### Install @use-gpu/wgsl-loader with npm or yarn Source: https://usegpu.live/docs/reference-loader-%40use-gpu-wgsl-loader Install the WGSL loader package using either npm or yarn. This package is essential for enabling the import of WGSL shader files directly into your JavaScript or TypeScript projects. ```bash npm install --save @use-gpu/wgsl-loader ``` ```bash yarn add @use-gpu/wgsl-loader ``` -------------------------------- ### State Management with @use-gpu/state Source: https://usegpu.live/docs/reference-live-%40use-gpu-traits--combine Provides examples of basic state management using the @use-gpu/state library. This includes creating and accessing stateful values. ```typescript import { use, State } from "@use-gpu/state"; const counterState = new State(0); function CounterComponent() { const count = use(counterState); return
Count: {count}
; } ``` -------------------------------- ### GLSL Shader Bundle Linking in JavaScript/TypeScript Source: https://usegpu.live/docs/reference-library-%40use-gpu-shader Example of importing a GLSL shader file in JS/TS and then linking it into a single bundle using the @use-gpu/shader library. ```javascript // GLSL in JS/TS import mainShader from 'path/to/main.glsl'; import { linkBundle } from '@use-gpu/shader/glsl'; const glslCode = linkBundle(mainShader); ``` -------------------------------- ### GLSL Dynamic Function Prototype Import Example Source: https://usegpu.live/docs/reference-library-%40use-gpu-shader Illustrates how to declare a function prototype for dynamic linking in GLSL, enabling the function definition to be resolved at runtime. ```glsl vec4 getColor(); ``` -------------------------------- ### Create a Context Provider in Live Source: https://usegpu.live/docs/guides-live-vs-react Provides an example of how to create a context provider using `makeContext` from '@use-gpu/live'. This includes defining the context's value type, a default value, and a display name for the context. ```typescript import { makeContext } from '@use-gpu/live'; type ContextValue = { foo: number }; const defaultValue = { foo: 1 }; const displayName = 'MyContext'; const MyContext = makeContext(defaultValue, displayName); ``` -------------------------------- ### WGSL Auto-Generated Getter Function Example Source: https://usegpu.live/docs/guides-shaders Shows an example of how Use.GPU might auto-generate WGSL code to bridge uniform data with getter functions. This illustrates the internal mechanism for handling data access, where `_VT_Uniform` provides the data to the `_VT_1_getSize` function. ```wgsl struct _VT_Type { _VT_1_getSize: f32, }; @group(1) @binding(0) var _VT_Uniform: _VT_Type; fn _VT_1_getSize(a: u32) -> vec4 { return _VT_Uniform._VT_1_getSize; } ``` -------------------------------- ### WGSL Shader Function Example Source: https://usegpu.live/docs/guides-shaders An example of a WGSL shader function that adjusts image exposure. It demonstrates the use of imports and exported functions within the WGSL syntax, suitable for custom material or data processing shaders. ```wgsl @link fn getGain() -> f32; @export fn adjustExposure(color: vec4) -> vec4 { var rgb = color.rgb * getGain(); return vec4(rgb, color.a); }; ``` -------------------------------- ### WGSL Shaders Source: https://usegpu.live/docs/reference-library-%40use-gpu-core-TYPED_ARRAYS This section covers WGSL shaders, the shading language used by WebGPU. It explains how to write and use shaders for rendering and computations within the Use.GPU framework. No specific code examples are provided in the text for this section. -------------------------------- ### JavaScript Usage Example: useUpdateState Source: https://usegpu.live/docs/reference-live-%40use-gpu-state--useUpdateState Demonstrates the basic usage of the useUpdateState hook in JavaScript, showing how to destructure the state and the update function from its return value. ```javascript const [state, updateState] = useUpdateState({ ... }); ``` -------------------------------- ### Static Import Example: GLSL Source: https://usegpu.live/docs/reference-library-%40use-gpu-shader Shows how to statically import symbols from another GLSL file using the `#pragma import` directive. Similar to WGSL, only exported symbols are importable and are typically namespaced. ```glsl #pragma import { getColor } from 'path/to/color' void main() { gl_FragColor = getColor(); } ``` -------------------------------- ### Configure NPM for Use.GPU Release Candidates Source: https://usegpu.live/docs/contributing This snippet shows how to configure your .npmrc file to use the GitLab registry for installing release candidate versions of Use.GPU packages. This is essential for testing pre-release versions. ```npm //@use-gpu:registry=https://gitlab.com/api/v4/projects/27922731/packages/npm/ ``` -------------------------------- ### Static Import Example: WGSL Source: https://usegpu.live/docs/reference-library-%40use-gpu-shader Demonstrates how to statically import symbols from another WGSL file using the `use` directive. Only exported symbols can be imported, and they are namespaced in the final linked result unless marked global. ```wgsl use 'path/to/color'::{ getColor }; fn main() -> vec4 { return getColor(); } ``` -------------------------------- ### Get GLSL Preamble with GLSLLinker Source: https://usegpu.live/docs/reference-library-%40use-gpu-shader-GLSLLinker Retrieves the current GLSL preamble string. The preamble often contains common utility functions or definitions included at the start of every shader. ```typescript const GLSLLinker: { getPreamble: () => string; // ... other methods }; ``` -------------------------------- ### Basic Webpack Development Server Command Source: https://usegpu.live/docs/contributing This command starts the top-level Webpack development server, which builds the entire Use.GPU workspace directly from TypeScript source files, enabling hot-reloading. This is the recommended method for development. ```shell yarn dev ``` -------------------------------- ### Integrate Use.GPU WebGPU Inspector in React Source: https://usegpu.live/docs/reference-components-%40use-gpu-inspect-gpu This example demonstrates how to integrate the Use.GPU WebGPU inspector into a React application. It uses the `useFiber` hook and `UseInspect` component, along with the `inspectGPU` extension, to enable debugging of WebGPU operations within the application's rendering context. Ensure that `@use-gpu/inspect` and `@use-gpu/workbench` are also installed and imported. ```jsx import { inspectGPU } from '@use-gpu/inspect-gpu'; import { useFiber } from '@use-gpu/live'; import { UseInspect } from '@use-gpu/inspect'; import { DebugProvider } from '@use-gpu/workbench'; import '@use-gpu/inspect/theme.css'; const Component = () => null; const App = () => { const view = ; const fiber = useFiber(); const root = document.body; return ( {view} ) } ``` -------------------------------- ### Initialize Live Application Source: https://usegpu.live/docs/guides-live-vs-react Sets up the main render entry point for a Live application, typically called on DOM load. It requires importing the `render` function and the root `App` component from '@use-gpu/live'. ```javascript import React from '@use-gpu/live'; import { render } from '@use-gpu/live'; import { App } from './app'; // e.g. on DOM load render(); ``` -------------------------------- ### WebGPU Canvas and Drawing with Use.GPU Source: https://usegpu.live/docs/reference-library-%40use-gpu-core--getVertexAttributeSize This section covers guides on using Use.GPU for WebGPU canvas operations, including drawing, animation, scene geometry, and 2D/3D plotting. It outlines how to set up and interact with WebGPU in a browser environment. ```javascript import * as usegpu from '@use-gpu/core'; // Example: Setting up a WebGPU canvas and drawing const canvas = document.getElementById('webgpu-canvas'); const gpu = await usegpu.createGPUContext(canvas); // Further drawing and animation examples would go here... ``` -------------------------------- ### MakeContext Interface Source: https://usegpu.live/docs/reference-live-%40use-gpu-live-MakeContext Documentation for the MakeContext interface, which is used to create a LiveContext. ```APIDOC ## MakeContext Interface ### Description The `MakeContext` interface defines the signature for creating a `LiveContext`. It allows for the creation of a context with an initial value, optionally providing a display name for debugging. ### Method `MakeContext` is a function that can be called to create a `LiveContext`. ### Parameters #### Function Parameters - **initialValue** (T | undefined | null) - Required - The initial value for the context. Can be of any type `T`, `undefined`, or `null`. - **displayName** (string) - Optional - A string name for the context, useful for debugging. ### Return Value - **LiveContext** - A `LiveContext` object that holds the state and allows for subscription. ### Example ```typescript // Example of creating a LiveContext const MyContext = MakeContext(0, 'MyNumberContext'); const contextInstance = MyContext(10); ``` ### Type Definition ```typescript interface MakeContext { (initialValue: T, displayName?: string) => LiveContext; (initialValue: undefined, displayName?: string) => LiveContext; (initialValue: null, displayName?: string) => LiveContext; } ``` ### Source `packages / live / src / builtin.ts` ``` -------------------------------- ### WebGPU Render Pipeline Configuration Source: https://usegpu.live/docs/reference-library-%40use-gpu-core--makeDataBuffer Shows how to configure and create a WebGPU render pipeline, including vertex state, fragment state, and the pipeline layout. ```javascript const vertexState = { module: shaderModule, entryPoint: 'vs_main', buffers: [ // Vertex buffer layout if applicable ] }; const fragmentState = { module: shaderModule, entryPoint: 'fs_main', targets: [ { format: presentationFormat } ] }; const renderPipelineDescriptor = { layout: pipelineLayout, vertex: vertexState, fragment: fragmentState, primitive: { topology: 'triangle-list' } }; const renderPipeline = device.createRenderPipeline(renderPipelineDescriptor); ``` -------------------------------- ### PresentAPI Methods Source: https://usegpu.live/docs/reference-components-%40use-gpu-present-PresentAPI This section details the methods available in the PresentAPI for controlling slide presentation, including navigation, state checking, and transition management. ```APIDOC ## PresentAPI ### Description Provides methods to control slide navigation, check visibility, and manage transitions within the presentation. ### Methods - **goTo** (x: number): Navigates to a specific slide identified by its index. - **goForward** (): Navigates to the next slide in the sequence. - **goBack** (): Navigates to the previous slide in the sequence. - **isThread** (id: number): Returns true if the slide with the given ID is part of a threaded presentation, false otherwise. - **isVisible** (id: number): Returns true if the slide with the given ID is currently visible, false otherwise. - **getVisibleState** (id: number): Returns the visibility state (number) of the slide with the given ID, or null if not applicable. - **useTransition** (id: number, enter: ParsedEffect, exit: ParsedEffect, initial?: number): A hook to manage the transition effect for a slide. It takes the slide ID, enter and exit effect configurations, and an optional initial state. It returns a number representing the current transition state. ``` -------------------------------- ### Basic Rendering Pass Setup with Pass Component Source: https://usegpu.live/docs/guides-drawing-animation This snippet demonstrates how to set up a basic rendering pass using the `` component within a ``. The `` component is responsible for gathering and scheduling draw calls for rendering to the screen. It can operate in 'forward' or 'deferred' modes. This code requires the '@use-gpu/workbench' library. ```javascript import { Pass } from '@use-gpu/workbench'; // ... return ( ); ``` -------------------------------- ### WebGPU Pipeline Layout and Bind Group Creation Source: https://usegpu.live/docs/reference-library-%40use-gpu-core--makeDataBuffer Illustrates the creation of WebGPU pipeline layouts and bind groups, which define how resources like uniform buffers and textures are bound to the pipeline. ```javascript // Example: Creating a uniform buffer and its layout const uniformBufferSize = 64; // Example size const uniformBuffer = device.createBuffer({ size: uniformBufferSize, usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST }); const uniformBindGroupLayoutEntry = { binding: 0, visibility: GPUShaderStage.VERTEX | GPUShaderStage.FRAGMENT, buffer: { type: 'uniform' } }; const uniformBindGroupLayout = device.createBindGroupLayout({ entries: [uniformBindGroupLayoutEntry] }); const pipelineLayout = device.createPipelineLayout({ bindGroupLayouts: [uniformBindGroupLayout] }); const uniformBindGroup = device.createBindGroup({ layout: uniformBindGroupLayout, entries: [ { binding: 0, resource: { buffer: uniformBuffer } } ] }); ``` -------------------------------- ### Render Pipeline Configuration Source: https://usegpu.live/docs/reference-library-%40use-gpu-core-ArrayLike Shows how to configure and create a render pipeline in Use.GPU. This includes setting up vertex and fragment stages, layout, and blend state. ```typescript import { UseGPU } from "@use-gpu/core"; const gpu = new UseGPU(); const device = await gpu.requestDevice(); const shaderModule = device.createShaderModule({ code: ` @vertex fn vs_main(@builtin(vertex_index) in_vertex_index: u32) -> @builtin(position) vec4 { // ... vertex shader code ... return vec4(0.0, 0.0, 0.0, 1.0); } @fragment fn fs_main() -> @location(0) vec4 { return vec4(1.0, 0.0, 0.0, 1.0); } ` }); const pipelineLayout = gpu.makePipelineLayout([]); const renderPipelineDescriptor = gpu.makeRenderPipelineDescriptor({ vertex: { module: shaderModule, entryPoint: "vs_main" }, fragment: { module: shaderModule, entryPoint: "fs_main", targets: [{ format: "bgra8unorm" }] }, layout: pipelineLayout }); const renderPipeline = device.createRenderPipeline(renderPipelineDescriptor); ``` -------------------------------- ### Parsing and Defaulting with parseTrait and Defaulted Source: https://usegpu.live/docs/reference-live-%40use-gpu-traits--combine Shows how to parse input values and provide defaults using parseTrait and Defaulted. This is useful for handling configuration and user inputs. ```typescript import { trait, parseTrait, Defaulted } from "@use-gpu/traits"; interface SettingsProps { timeout: number; } const TimeoutTrait = trait({ timeout: parseTrait(new Defaulted(5000, (v) => typeof v === 'number' && v > 0)) }); ``` -------------------------------- ### Initialize WebGPU Canvas with AutoCanvas Source: https://usegpu.live/docs/guides-webgpu-canvas This snippet demonstrates the basic setup for a WebGPU canvas using the `` and `` components. It shows how to import necessary components and structure the JSX for rendering. The `` component can accept a direct canvas element or use a CSS selector to find or create a canvas. ```jsx import { WebGPU, AutoCanvas } from '@use-gpu/webgpu'; const App = () => { return ( ) }; ``` -------------------------------- ### Define and Use Style Trait in React/Live Source: https://usegpu.live/docs/reference-live-%40use-gpu-traits Example of defining a 'StyleTrait' with size, rounded, and color properties using @use-gpu/traits. It shows how to create a hook 'useTraits' from this trait and how to infer component types. The example also demonstrates combining multiple traits. ```typescript import { trait, combine, TraitProps, makeUseTrait } from '@use-gpu/traits'; import { parseNumber, parseBoolean, parseColor } from '@use-gpu/core'; // Define a mix-in of 3 props const StyleTrait = trait({ // A parser is any function `(value?: A) => B`. size: parseNumber, rounded: parseBoolean, color: optional(parseColor), }, { // Specify defaults size: 1, rounded: true, }); // Make an invokable hook out of a trait const useTraits = makeUseTrait(StyleTrait); // OR Combine multiple traits const traits = combine(StyleTrait, ...); const useTraits = makeUseTrait(traits); // Infer complete component type type ComponentProps = TraitProps; // Use in a component const MyComponent = (props: ComponentProps) => { const {color, opacity} = useTraits(props); }; ``` -------------------------------- ### WGSL Shader Module Creation Source: https://usegpu.live/docs/reference-library-%40use-gpu-core--makeDataBuffer Defines how to create WGSL shader modules for use with WebGPU. This includes specifying shader stages (vertex and fragment) and their entry points. ```javascript const shaderModuleDescriptor = { code: ` @vertex fn vs_main(@builtin(vertex_index) in_vertex_index: u32) -> @builtin(position) vec4 { var pos = array, 3>( vec2(0.0, 0.75), vec2(-0.75, -0.75), vec2(0.75, -0.75) ); return vec4(pos[in_vertex_index], 0.0, 1.0); } @fragment fn fs_main() -> @location(0) vec4 { return vec4(1.0, 0.0, 0.0, 1.0); } `, hints: { // Optional hints for optimization } }; const shaderModule = device.createShaderModule(shaderModuleDescriptor); ``` -------------------------------- ### WebGPU Reconciliation and Quoting Example Source: https://usegpu.live/docs/guides-memoization Illustrates the reconciliation and quoting process in Use.GPU, where the CPU-side tree (Reconcile) sets up draw calls and the GPU-side tree (Resume) executes them using 'Yeet' components. This example shows how data changes trigger re-runs of downstream components. ```jsx // The CPU-side tree // quote-yeets `undefined` // quote-yeets the code to draw PointLayer & LineLayer // The GPU-side tree // empty signal - (does not actually appear in the tree) {() => { … }} // code from Resume(Pass) // gathers up all the draw calls and runs them ``` -------------------------------- ### JavaScript $patch Function Example Source: https://usegpu.live/docs/reference-live-%40use-gpu-state-%24patch Demonstrates how to use the $patch function to create nested updates within a state object. It shows how $patch can be combined with $apply and $delete for complex state transformations. The example illustrates updating nested properties and removing others. ```javascript const $patch: ( $patch: (t: T) => Update, ) => { $patch: (t: T) => Update } import { $patch, $apply, $delete } from "@use-gpu/state"; const value = { hello: {text: 'world', bar: 2, other: 1}, foo: 1, }; const update = { hello: $patch(({other}) => ({ text: $apply(text => other + ' !!!'), bar: $delete(), })), }; expect(patch(value, update)).toEqual({ hello: {text: '1 !!!', other: 1}, foo: 1, }); ``` -------------------------------- ### TypeScript SDFFontContextProps Type Definition Source: https://usegpu.live/docs/reference-components-%40use-gpu-workbench-SDFFontContextProps Defines the context properties for SDF (Signed Distance Field) font rendering. It includes debugging information, methods to get radius and scale, a function to retrieve glyph metrics and texture coordinates, and a method to get the font texture as a ShaderSource. ```typescript type SDFFontContextProps = { __debug: { atlas: Atlas, }, getRadius: () => number, getScale: (size: number) => number, getGlyph: ( font: number, id: number, size: number, ) => { glyph: GlyphMetrics, mapping: [number, number, number, number] }, getTexture: () => ShaderSource, } ``` -------------------------------- ### Exported WGSL Function Source: https://usegpu.live/docs/reference-library-%40use-gpu-shader Example of an exported WGSL function `getColor` in `path/to/color.wgsl`. This function can be imported by other modules. It also calls an internal `used` function. ```wgsl @export fn getColor() -> vec4 { return vec4(used(), 0.5, 0.0, 1.0); } fn used() -> f32 { return 1.0; } fn unused() { // ... } ``` -------------------------------- ### Untitled Source: https://usegpu.live/docs/reference-live-%40use-gpu-live--useNoAwait No description -------------------------------- ### GLSL Syntax for Imports and Exports Source: https://usegpu.live/docs/reference-library-%40use-gpu-shader Details the GLSL syntax using pragmas for importing symbols from files, exporting declarations, marking functions as optional, and designating global declarations. ```glsl // Import symbols from a .glsl file #pragma import { symbol, … } from "path/to/file" #pragma import { symbol as symbol, … } from "path/to/file" // Mark next declaration as exported #pragma export // Mark next function prototype as optional (e.g. inside an `#ifdef`) #pragma optional // Mark next declaration as global (don't namespace it) #pragma global ``` -------------------------------- ### Define VolatileAllocation Type Source: https://usegpu.live/docs/reference-library-%40use-gpu-core-VolatileAllocation Defines a TypeScript type alias 'VolatileAllocation' for GPU resource allocations that might change. It includes an optional method to get a GPUBindGroup. ```typescript type VolatileAllocation = { bindGroup?: () => GPUBindGroup } ``` -------------------------------- ### Memoization Comparison Strategies Source: https://usegpu.live/docs/reference-live-%40use-gpu-traits--combine Explains different memoization comparison strategies, including MemoCompare for custom logic, and default behaviors for primitive types and references. ```typescript import { UseMemo, MemoCompare } from "@use-gpu/state"; // Default comparison (===) const memo1 = new UseMemo(() => expensiveFn(), [dep1]); // Custom comparison for arrays const customArrayCompare: MemoCompare = (a, b) => { if (a.length !== b.length) return false; for (let i = 0; i < a.length; i++) { if (a[i] !== b[i]) return false; } return true; }; const memo2 = new UseMemo(() => computeArray(), [depArray], customArrayCompare); ``` -------------------------------- ### Define and Use Color Trait Source: https://usegpu.live/docs/reference-live-%40use-gpu-traits Example of defining a 'ColorTrait' using the 'trait' function from @use-gpu/traits. It also shows how to create a use-hook for this trait, both outside and inside a component context. ```typescript import { trait, } from '@use-gpu/traits'; const ColorTrait = trait({ color: parseColor, }, { color: '#808080', }); // Outside a component const useTrait = makeUseTrait(parsers, defaults); // Inside a component const {field} = useTrait(props); ``` -------------------------------- ### Create and Bind Shader Entry Point Source: https://usegpu.live/docs/reference-library-%40use-gpu-shader-WGSLLinker Binds an entry point to a shader module, typically defining the main function or specific shader stages to be executed. This function is key to setting up how a shader will be invoked within a rendering pass. ```typescript import { bindEntryPoint, ShaderModule, DataBinding } from "@use-gpu/core"; function bindShaderEntryPoint(module: ShaderModule, entryPointName: string, dataBinding: DataBinding): void { bindEntryPoint(module, entryPointName, dataBinding); } ``` -------------------------------- ### Shader Module Bundle Entry Retrieval Source: https://usegpu.live/docs/reference-library-%40use-gpu-shader-WGSLLinker Provides a function to get the entry point string for a given shader module. This is essential for understanding how to use a compiled shader module. ```typescript getBundleEntry: ( bundle: ShaderModule, ) => string | undefined ``` -------------------------------- ### WGSL Faux Pre-processor for Bindings Source: https://usegpu.live/docs/guides-shaders Explains WGSL's approach to manual bindings, mimicking pre-processor directives for substitutions. This allows for reusable hand-rolled bind groups and uniform variables by substituting placeholder attributes. ```WGSL struct ViewUniforms { projectionMatrix: mat4x4, viewMatrix: mat4x4, viewPosition: vec4, //... }; @export @group(VIEW) @binding(VIEW) var viewUniforms: ViewUniforms; ``` -------------------------------- ### Shader Module and Pipeline Creation Source: https://usegpu.live/docs/reference-library-%40use-gpu-core--clerp Functions for creating WebGPU shader modules and pipelines, including render pipelines and compute pipelines. This involves defining shader stage descriptors, layout configurations, and asynchronous pipeline creation. ```typescript import { makeShaderModuleDescriptor, makeShaderStage, makePipelineLayout, makeBindGroupLayout, makeRenderPipeline, makeComputePipeline, makeRenderPipelineAsync, makeComputePipelineAsync } from "@use-gpu/core"; // Example usage: const shaderModuleDesc = makeShaderModuleDescriptor({ code: "\n@vertex fn vs() -> @builtin(position) vec4 { return vec4(0.0, 0.0, 0.0, 1.0); }\n@fragment fn fs() -> @location(0) vec4 { return vec4(1.0, 0.0, 0.0, 1.0); }", source: "@use-gpu/wgsl" }); const shaderStage = makeShaderStage("vertex", shaderModuleDesc); const pipelineLayout = makePipelineLayout([makeBindGroupLayout([])]); const renderPipeline = makeRenderPipeline({ layout: pipelineLayout, vertex: { module: shaderModuleDesc, entryPoint: "vs" }, fragment: { module: shaderModuleDesc, entryPoint: "fs", targets: [{ format: "rgba8unorm" }] } }); const computePipeline = makeComputePipeline({ layout: pipelineLayout, compute: { module: shaderModuleDesc, entryPoint: "cs" } }); // Async versions are also available: // const renderPipelineAsync = makeRenderPipelineAsync(...); // const computePipelineAsync = makeComputePipelineAsync(...); ``` -------------------------------- ### WebGPU Pipeline Creation Source: https://usegpu.live/docs/reference-library-%40use-gpu-core--toTypeString Functions for creating render and compute pipelines in WebGPU. This includes defining pipeline layouts, shader modules, and various states for rendering and computation. ```typescript function makePipelineLayout(device: GPUDevice, entries: GPUPipelineLayoutEntry[]): GPUPipelineLayout; function makeBindGroupLayout(device: GPUDevice, entries: GPUBindGroupLayoutEntry[]): GPUBindGroupLayout; function makeBindGroupLayoutEntries(entries: GPUBindGroupLayoutEntry[]): GPUBindGroupLayoutEntry[]; function makeBindGroupLayoutEntry(descriptor: GPUBindGroupLayoutEntry): GPUBindGroupLayoutEntry; function makeShaderModuleDescriptor(code: string, options?: any): GPUShaderModuleDescriptor; function makeShaderStage(device: GPUDevice, descriptor: GPUShaderModuleDescriptor, entryPoint: string, stage: GPUShaderStageFlags): GPUProgrammableStage; function makeRenderPipeline(device: GPUDevice, descriptor: GPURenderPipelineDescriptor): GPURenderPipeline; function makeRenderPipelineAsync(device: GPUDevice, descriptor: GPURenderPipelineDescriptor): Promise; function makeComputePipeline(device: GPUDevice, descriptor: GPUComputePipelineDescriptor): GPUComputePipeline; function makeComputePipelineAsync(device: GPUDevice, descriptor: GPUComputePipelineDescriptor): Promise; ```