### Basic Sandbox Setup with TypeScript Source: https://github.com/rosalana/sandbox/blob/master/CLAUDE.md Demonstrates the basic setup of the Rosalana Sandbox by creating an instance with a canvas element and shader source. This is the entry point for using the sandbox. ```typescript import { Sandbox } from "@rosalana/sandbox"; const sandbox = Sandbox.create(canvas, { fragment: myShaderSource, }); ``` -------------------------------- ### Vue.js Integration Example Source: https://github.com/rosalana/sandbox/blob/master/README.md This example demonstrates how to integrate Rosalana Sandbox with Vue.js's reactivity system using `shallowRef` for the Sandbox instance and managing its lifecycle with `onMounted` and `onUnmounted`. ```vue ``` -------------------------------- ### Controlling Time and Playback with TypeScript Source: https://github.com/rosalana/sandbox/blob/master/CLAUDE.md Demonstrates various methods for controlling the playback and time of the sandbox, including setting the current time, starting playback from a specific time, and setting auto-pause points. ```typescript sandbox.time(2.5); // Set time to 2.5s sandbox.playAt(10); // Start playing from 10s sandbox.pauseAt(20); // Auto-pause when time reaches 20s ``` -------------------------------- ### Setting Custom Uniforms with TypeScript Source: https://github.com/rosalana/sandbox/blob/master/CLAUDE.md Provides examples of how to set custom uniforms for shaders, both individually and as a group. This is essential for passing data from JavaScript to the shaders. ```typescript sandbox.setUniform("u_color", [1, 0.2, 0.3]); sandbox.setUniforms({ u_intensity: 0.75, u_colors: [[1, 0, 0], [0, 1, 0], [0, 0, 1]], }); ``` -------------------------------- ### GLSL Texture Usage Example Source: https://context7.com/rosalana/sandbox/llms.txt Example GLSL code demonstrating how to use `sampler2D` uniforms, which are typically set using the `setTexture` or `setTextures` functions in the Sandbox API. ```glsl // GLSL usage uniform sampler2D u_texture; uniform sampler2D u_mask; void main() { vec4 color = texture2D(u_texture, v_texcoord); float mask = texture2D(u_mask, v_texcoord).r; gl_FragColor = color * mask; } ``` -------------------------------- ### Install Rosalana Sandbox with npm Source: https://github.com/rosalana/sandbox/blob/master/README.md Installs the Rosalana Sandbox package using npm. This is the first step to integrating the library into your project. ```bash npm install @rosalana/sandbox ``` -------------------------------- ### Chainable API Example in TypeScript Source: https://github.com/rosalana/sandbox/blob/master/CLAUDE.md Demonstrates the chainable API pattern where mutating methods return 'this' to allow method chaining. This enhances code readability and conciseness for sequential operations. ```typescript sandbox.setUniforms({ u_color: [1, 0, 0] }).time(2.5).render(); ``` -------------------------------- ### Example Aurora Shader using Built-in Modules (GLSL) Source: https://context7.com/rosalana/sandbox/llms.txt An example GLSL shader demonstrating the use of imported modules from 'sandbox', 'sandbox/colors', and 'sandbox/filters' to create an aurora effect. It utilizes noise, gradients, and brightness adjustments. ```glsl #version 300 es precision highp float; #import noise from "sandbox" #import hex from "sandbox/colors" #import gradient3 from "sandbox/colors" #import brightness from "sandbox/filters" in vec2 v_texcoord; out vec4 fragColor; void main() { vec2 uv = v_texcoord; vec3 color = gradient3(hex(0x5227FF), hex(0x7CFF67), hex(0x5227FF), uv.x); float wave = (noise(vec2(uv.x * 4.0 + u_time * 0.1, u_time * 0.25)) * 2.0 - 1.0) * 0.5; float band = (uv.y * 2.0 - exp(wave) + 0.2) * 0.6; float alpha = smoothstep(-0.05, 0.45, band); color = brightness(color, band); fragColor = vec4(color * alpha, alpha); } ``` -------------------------------- ### Vue Integration with Rosalana Sandbox Source: https://context7.com/rosalana/sandbox/llms.txt A complete example demonstrating how to integrate Rosalana Sandbox within a Vue 3 application using the Composition API. It utilizes `ref` and `shallowRef` for reactivity and manages the Sandbox instance through Vue's lifecycle hooks (`onMounted`, `onUnmounted`). ```vue ``` -------------------------------- ### Sample Texture in GLSL Shader Source: https://github.com/rosalana/sandbox/blob/master/README.md Provides an example of how to sample a texture within a GLSL fragment shader. It uses the `texture2D` function with the texture sampler uniform and texture coordinates. ```glsl uniform sampler2D u_texture; void main() { vec4 color = texture2D(u_texture, v_texcoord); gl_FragColor = color; } ``` -------------------------------- ### Configuring Runtime Modules with TypeScript Source: https://github.com/rosalana/sandbox/blob/master/CLAUDE.md Demonstrates how to configure imported modules at runtime after the sandbox has been initialized. This allows for dynamic adjustments to module parameters. ```typescript sandbox.module("twist", { intensity: 0.5 }); sandbox.module("contrast", { intensity: 1.8 }); ``` -------------------------------- ### Build System Scripts Source: https://github.com/rosalana/sandbox/blob/master/CLAUDE.md Lists common npm scripts for building, developing, testing, and cleaning the project. These scripts leverage tools like Vite and TypeScript for efficient development and deployment. ```bash npm run build npm run dev npm run dev:vite npm run dev:tsc npm run typecheck npm run clean npm test npm run test:watch ``` -------------------------------- ### GLSL Import Syntax Source: https://github.com/rosalana/sandbox/blob/master/CLAUDE.md Demonstrates the syntax for importing functions from modules in GLSL. It shows how to import a function directly or with an alias, specifying the module name. ```glsl #import functionName from "moduleName" #import functionName as alias from "moduleName" ``` -------------------------------- ### GLSL Mention Syntax for Uniforms Source: https://github.com/rosalana/sandbox/blob/master/CLAUDE.md Illustrates the `@` syntax for referencing module uniforms dynamically within GLSL shaders. This allows uniforms to be controlled at runtime via the sandbox module configuration. ```glsl #import effect from "my_module" void main() { vec3 a = effect(uv, 2.0); // hardcoded vec3 b = effect(uv, @effect.intensity); // dynamic — controlled via sandbox.module() } ``` -------------------------------- ### Sandbox.create - Create a WebGL Shader Instance Source: https://context7.com/rosalana/sandbox/llms.txt Creates a new Sandbox instance attached to a canvas element. This is the primary entry point for the library. It initializes WebGL context, compiles shaders, sets up the render loop, and begins playback automatically (unless `autoplay: false`). ```APIDOC ## Sandbox.create - Create a WebGL Shader Instance ### Description Creates a new Sandbox instance attached to a canvas element. This is the primary entry point for the library. It initializes WebGL context, compiles shaders, sets up the render loop, and begins playback automatically (unless `autoplay: false`). ### Method `Sandbox.create(canvas: HTMLCanvasElement, options?: SandboxOptions): Sandbox` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **canvas** (HTMLCanvasElement) - The canvas element to attach the sandbox to. - **options** (SandboxOptions) - Configuration options for the sandbox instance. - **fragment** (string) - Fragment shader GLSL source. - **vertex** (string, optional) - Custom vertex shader GLSL source. - **autoplay** (boolean, optional) - Start rendering immediately (default: true). - **pauseWhenHidden** (boolean, optional) - Pause when scrolled out of view (default: true). - **dpr** (string | number, optional) - Device pixel ratio ("auto" | number). - **fps** (number, optional) - Max frame rate (0 = unlimited). - **preserveDrawingBuffer** (boolean, optional) - Keep buffer for screenshots. - **antialias** (boolean, optional) - Enable antialiasing. - **uniforms** (object, optional) - Initial uniform values. - **textures** (object, optional) - Initial textures. - **onLoad** (function, optional) - Callback when shader is compiled. - **onError** (function, optional) - Callback on shader compilation error. - **onBeforeRender** (function, optional) - Callback before each frame render. - **onAfterRender** (function, optional) - Callback after each frame render. ### Request Example ```typescript import { Sandbox } from "@rosalana/sandbox"; const canvas = document.querySelector("canvas"); const sandbox = Sandbox.create(canvas, { fragment: ` precision highp float; void main() { vec2 uv = gl_FragCoord.xy / u_resolution; vec3 color = vec3(uv.x, uv.y, sin(u_time) * 0.5 + 0.5); gl_FragColor = vec4(color, 1.0); } `, uniforms: { u_intensity: 0.8, }, onLoad: () => console.log("Shader compiled") }); ``` ### Response #### Success Response (200) - **Sandbox** (object) - The created Sandbox instance. #### Response Example (Returns a Sandbox instance, not a JSON object) ``` -------------------------------- ### Define a GLSL Module Source: https://github.com/rosalana/sandbox/blob/master/README.md Defines a reusable GLSL module that can be imported into shaders. Module names starting with 'sandbox' are reserved for built-in modules. ```typescript Sandbox.defineModule("my_effects", myGLSLSource); ``` -------------------------------- ### Dynamic Uniform Wiring in Modules Source: https://github.com/rosalana/sandbox/blob/master/README.md Demonstrates how to wire module uniforms dynamically using the '@' syntax. This allows GLSL uniforms to be controlled from JavaScript via `sandbox.module()`. ```glsl #import effect from "my_module" void main() { vec3 a = effect(v_texcoord, 2.0); // hardcoded value vec3 b = effect(v_texcoord, @effect.intensity); // dynamic — set via sandbox.module() fragColor = vec4(a + b, 1.0); } ``` -------------------------------- ### Get Custom Uniform Value Source: https://github.com/rosalana/sandbox/blob/master/README.md Reads the current value of a custom uniform from the shader. This is useful for debugging or synchronizing state between JavaScript and the shader. ```typescript const intensity = sandbox.getUniform("u_intensity"); ``` -------------------------------- ### Control Sandbox playback time Source: https://github.com/rosalana/sandbox/blob/master/README.md Allows precise control over the playback time of the Sandbox instance. You can start playback at a specific time or set an auto-pause. ```typescript sandbox.playAt(2.5); sandbox.pauseAt(10); ``` -------------------------------- ### Static Rendering with TypeScript Source: https://github.com/rosalana/sandbox/blob/master/CLAUDE.md Explains how to perform static rendering of a frame at a specific time point. This is useful for capturing specific frames or for non-animated content. ```typescript const sandbox = Sandbox.create(canvas, { fragment: myShader, autoplay: false, }); sandbox.renderAt(1.5); ``` -------------------------------- ### Defining Custom GLSL Modules with TypeScript Source: https://github.com/rosalana/sandbox/blob/master/CLAUDE.md Illustrates how to define a new custom GLSL module using TypeScript. This involves providing the GLSL source code and defining any configurable parameters for the module. ```typescript Sandbox.defineModule("my_effects", myGLSLSource, { myFunc: { speed: { uniform: "u_speed", default: 1.0 }, }, }); ``` -------------------------------- ### Importing Core GLSL Utilities from 'sandbox' Source: https://context7.com/rosalana/sandbox/llms.txt Demonstrates importing core GLSL utility functions from the 'sandbox' module. These functions handle UV coordinate manipulation, noise generation, and other fundamental graphics operations. ```glsl #import center from "sandbox" #import rotate from "sandbox" #import scale from "sandbox" #import tile from "sandbox" #import polar from "sandbox" #import hash from "sandbox" #import noise from "sandbox" #import fbm from "sandbox" #import worley from "sandbox" #import voronoi from "sandbox" #import waves from "sandbox" ``` -------------------------------- ### Control Sandbox Playback - TypeScript Source: https://context7.com/rosalana/sandbox/llms.txt Manages the animation render loop of a Sandbox instance. Provides methods to start, stop, toggle, and control playback at specific times. Useful for intro animations or time-based effects. ```typescript const sandbox = Sandbox.create(canvas, { fragment: shader }); // Basic playback control sandbox.play(); // Start render loop sandbox.pause(); // Stop render loop sandbox.toggle(); // Toggle play/pause state sandbox.isPlaying(); // Returns true if currently animating // Time-based playback sandbox.playAt(2.5); // Jump to 2.5 seconds and start playing sandbox.pauseAt(10); // Auto-pause when time reaches 10 seconds // Example: Intro animation that stops after 5 seconds const intro = Sandbox.create(canvas, { fragment: introShader, autoplay: true, }); intro.pauseAt(5); // Animation plays for 5 seconds then stops // Chained playback control sandbox.playAt(0).pauseAt(3); // Play from start, stop at 3 seconds ``` -------------------------------- ### List Available Modules Source: https://github.com/rosalana/sandbox/blob/master/README.md Retrieves a list of all currently registered GLSL modules, including built-in and user-defined ones. ```typescript Sandbox.availableModules(); ``` -------------------------------- ### Static Rendering - render, renderAt, time Source: https://context7.com/rosalana/sandbox/llms.txt Renders a single frame without starting the animation loop. Perfect for generating thumbnails, deterministic exports, or any use case where you need a specific frame without continuous animation. ```APIDOC ## Static Rendering - render, renderAt, time ### Description Renders a single frame without starting the animation loop. Perfect for generating thumbnails, deterministic exports, or any use case where you need a specific frame without continuous animation. ### Methods - **render(): Sandbox** - Renders the current state of the sandbox. - **renderAt(time: number): Sandbox** - Renders the sandbox at a specific time. - **time(time: number): Sandbox** - Sets the current time of the sandbox without rendering. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```typescript const sandbox = Sandbox.create(canvas, { fragment: shader, autoplay: false, // Don't start animation loop }); // Render current state (time = 0 initially) sandbox.render(); // Render at specific time for deterministic output sandbox.renderAt(1.5); // Set time separately then render sandbox.time(2.5).render(); // Generate multiple frames at different times for (let t = 0; t < 10; t += 0.5) { sandbox.renderAt(t); const url = sandbox.exportAsURL("image/png"); console.log(`Frame at ${t}s:`, url); } ``` ### Response #### Success Response (200) - **Sandbox** (object) - The Sandbox instance for chaining methods. #### Response Example (Returns a Sandbox instance, not a JSON object) ``` -------------------------------- ### Create a Sandbox instance with fragment shader Source: https://github.com/rosalana/sandbox/blob/master/README.md Initializes a new Sandbox instance with a given canvas element and a fragment shader source. It sets up the WebGL context and the render loop. ```typescript import { Sandbox } from "@rosalana/sandbox"; const sandbox = Sandbox.create(canvas, { fragment: fragSource, }); ``` -------------------------------- ### Importing Modules in GLSL Shaders Source: https://github.com/rosalana/sandbox/blob/master/CLAUDE.md Shows how to import and use custom modules for colors, effects, and filters within a GLSL fragment shader. This allows for modular shader development. ```glsl #import hex from "sandbox/colors" #import twist from "sandbox/effects" #import contrast from "sandbox/filters" void main() { vec2 uv = v_texcoord; uv = twist(uv, 0.3); vec3 color = hex(0xFF6600); color = contrast(color, @contrast.intensity); fragColor = vec4(color, 1.0); } ``` -------------------------------- ### TypeScript Module Options Definition Source: https://github.com/rosalana/sandbox/blob/master/CLAUDE.md Shows how to define configurable options for a GLSL module using TypeScript. It maps friendly option names to GLSL uniform names and provides default values, with support for function-specific overrides. ```typescript Sandbox.defineModule("my_effects", source, { default: { // shared by all functions intensity: { uniform: "u_intensity", default: 1.0 }, }, specialFunc: { // overrides for specific function intensity: { uniform: "u_intensity", default: 2.0 }, }, }); ``` -------------------------------- ### Implement Pre-Render Hook (JavaScript) Source: https://github.com/rosalana/sandbox/blob/master/README.md Shows how to implement a hook that runs before rendering. This hook can be used to pre-compute values on the CPU and set uniforms, such as 'u_intensity', based on the current time. ```javascript sandbox.hook(({ time }) => { const intensity = (Math.sin(time) + 1) / 2; sandbox.setUniform("u_intensity", intensity); }, "before"); ``` -------------------------------- ### Set Textures via Sandbox Options (JavaScript) Source: https://github.com/rosalana/sandbox/blob/master/README.md Illustrates setting textures during Sandbox initialization using the `textures` option. This allows defining textures, their sources, and specific configurations like wrapping. ```javascript Sandbox.create(canvas, { fragment: shader, textures: { u_photo: photoImg, u_mask: { source: maskImg, wrap: "repeat" }, }, }); ``` -------------------------------- ### Vue.js Integration with Sandbox Source: https://github.com/rosalana/sandbox/blob/master/CLAUDE.md Shows how to integrate the Rosalana Sandbox into a Vue.js application using `shallowRef` for reactivity and managing the sandbox lifecycle with `onMounted` and `onUnmounted` hooks. ```typescript const sandbox = shallowRef(null); onMounted(() => { sandbox.value = Sandbox.create(canvasRef.value!, { fragment: shader, onAfterRender: () => { isPlaying.value = sandbox.value?.isPlaying() ?? false; }, }); }); onUnmounted(() => { sandbox.value?.destroy(); }); ``` -------------------------------- ### Built-in GLSL Modules Source: https://context7.com/rosalana/sandbox/llms.txt Sandbox provides several built-in modules for common GLSL utilities. These modules are always available and can be imported using the '#import' directive. ```APIDOC ## Built-in GLSL Modules Sandbox ships with built-in modules providing common GLSL utilities. These are always available without defining them. ### `sandbox` - Core utilities - `#import center from "sandbox"` // Center UV coordinates - `#import rotate from "sandbox"` // Rotate UV by angle - `#import scale from "sandbox"` // Scale UV - `#import tile from "sandbox"` // Tile/repeat UV - `#import polar from "sandbox"` // Cartesian to polar - `#import hash from "sandbox"` // 2D random hash - `#import noise from "sandbox"` // Smooth value noise - `#import fbm from "sandbox"` // Fractal Brownian Motion (6 octaves) - `#import worley from "sandbox"` // Cellular/Voronoi noise - `#import voronoi from "sandbox"` // Voronoi cell lookup - `#import waves from "sandbox"` // Layered sine interference ### `sandbox/colors` - Color utilities - `#import hex from "sandbox/colors"` // Hex int to RGB: hex(0xFF6600) - `#import rgb255 from "sandbox/colors"` // RGB 0-255 to 0-1 - `#import hsv from "sandbox/colors"` // HSV to RGB - `#import hsl from "sandbox/colors"` // HSL to RGB - `#import gradient from "sandbox/colors"` // 2-color gradient - `#import gradient3 from "sandbox/colors"` // 3-stop gradient - `#import palette from "sandbox/colors"` // Inigo Quilez cosine palette - `#import iridescent from "sandbox/colors"` // Oil-slick rainbow effect ### `sandbox/filters` - Color post-processing - `#import contrast from "sandbox/filters"` // Adjust contrast - `#import brightness from "sandbox/filters"` // Multiply brightness - `#import saturate from "sandbox/filters"` // Adjust saturation - `#import posterize from "sandbox/filters"` // Reduce color levels - `#import invert from "sandbox/filters"` // Invert colors - `#import glow from "sandbox/filters"` // Luminance-based bloom - `#import grain from "sandbox/filters"` // Film grain noise - `#import vignette from "sandbox/filters"` // Darken edges - `#import sepia from "sandbox/filters"` // Sepia tone - `#import dither from "sandbox/filters"` // Ordered Bayer dithering ### `sandbox/effects` - UV distortions - `#import pixelate from "sandbox/effects"` // Blocky mosaic - `#import twist from "sandbox/effects"` // Spiral distortion - `#import ripple from "sandbox/effects"` // Water ripple waves - `#import fisheye from "sandbox/effects"` // Barrel distortion - `#import wobble from "sandbox/effects"` // Animated sine wobble - `#import glitch from "sandbox/effects"` // Digital glitch lines - `#import kaleidoscope from "sandbox/effects"` // Radial symmetry - `#import warp from "sandbox/effects"` // Domain warping (fbm) ### `sandbox/time` - Animation utilities - `#import loop from "sandbox/time"` // Repeating 0→1 sawtooth - `#import pingpong from "sandbox/time"` // Triangle wave 0→1→0 - `#import once from "sandbox/time"` // Single 0→1 then hold - `#import ease_in from "sandbox/time"` // Cubic acceleration - `#import ease_out from "sandbox/time"` // Cubic deceleration - `#import spring from "sandbox/time"` // Damped oscillation - `#import bounce from "sandbox/time"` // Bouncing ball - `#import elastic from "sandbox/time"` // Springy overshoot ### Example Usage ```glsl // Example: Aurora shader using built-in modules #version 300 es precision highp float; #import noise from "sandbox" #import hex from "sandbox/colors" #import gradient3 from "sandbox/colors" #import brightness from "sandbox/filters" in vec2 v_texcoord; out vec4 fragColor; void main() { vec2 uv = v_texcoord; vec3 color = gradient3(hex(0x5227FF), hex(0x7CFF67), hex(0x5227FF), uv.x); float wave = (noise(vec2(uv.x * 4.0 + u_time * 0.1, u_time * 0.25)) * 2.0 - 1.0) * 0.5; float band = (uv.y * 2.0 - exp(wave) + 0.2) * 0.6; float alpha = smoothstep(-0.05, 0.45, band); color = brightness(color, band); fragColor = vec4(color * alpha, alpha); } ``` ``` -------------------------------- ### Sandbox Configuration Options Source: https://github.com/rosalana/sandbox/blob/master/README.md This section details the various options available for configuring the Rosalana Sandbox, including shader paths, rendering behavior, and callback functions. ```APIDOC ## Sandbox Options ### Description Configuration options for the Rosalana Sandbox. ### Method N/A (Configuration object) ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body ##### `SandboxOptions` Interface - **vertex** (string) - Optional - Custom vertex shader path. - **fragment** (string) - Optional - Custom fragment shader path. - **autoplay** (boolean) - Optional - Start rendering immediately. Defaults to `true`. - **pauseWhenHidden** (boolean) - Optional - Pause rendering when the tab is hidden. Defaults to `true`. - **dpr** (number | "auto") - Optional - Device pixel ratio. Defaults to `"auto"`. - **fps** (number) - Optional - Maximum frame rate (approximate). Defaults to `0` (unlimited). - **preserveDrawingBuffer** (boolean) - Optional - Keep the drawing buffer for screenshots. Defaults to `false`. - **antialias** (boolean) - Optional - Enable antialiasing. Defaults to `true`. - **onError** (function) - Optional - Callback function for errors. Defaults to `console.error`. - **onLoad** (function) - Optional - Callback function called on each shader compilation. - **onBeforeRender** (HookCallback | null) - Optional - Hook called before each frame render. - **onAfterRender** (HookCallback | null) - Optional - Hook called after each frame render. - **uniforms** (object) - Optional - Initial uniform values. - **modules** (object) - Optional - Configure module options per imported function. - **textures** (object) - Optional - Initial textures to bind to sampler uniforms. ### Request Example ```json { "vertex": "/path/to/custom/vertex.glsl", "fragment": "/path/to/custom/fragment.glsl", "autoplay": false, "dpr": 2, "uniforms": { "time": 0, "resolution": [800, 600] } } ``` ### Response N/A (Configuration object) #### Success Response (200) N/A #### Response Example N/A ``` -------------------------------- ### Importing Color Utilities from 'sandbox/colors' Source: https://context7.com/rosalana/sandbox/llms.txt Shows how to import color manipulation functions from the 'sandbox/colors' module. These utilities convert between color formats (hex, RGB, HSV, HSL) and generate gradients. ```glsl #import hex from "sandbox/colors" #import rgb255 from "sandbox/colors" #import hsv from "sandbox/colors" #import hsl from "sandbox/colors" #import gradient from "sandbox/colors" #import gradient3 from "sandbox/colors" #import palette from "sandbox/colors" #import iridescent from "sandbox/colors" ``` -------------------------------- ### Importing Color Filter Utilities from 'sandbox/filters' Source: https://context7.com/rosalana/sandbox/llms.txt Illustrates importing color post-processing filters from the 'sandbox/filters' module. These functions adjust contrast, brightness, saturation, and apply effects like sepia and vignette. ```glsl #import contrast from "sandbox/filters" #import brightness from "sandbox/filters" #import saturate from "sandbox/filters" #import posterize from "sandbox/filters" #import invert from "sandbox/filters" #import glow from "sandbox/filters" #import grain from "sandbox/filters" #import vignette from "sandbox/filters" #import sepia from "sandbox/filters" #import dither from "sandbox/filters" ``` -------------------------------- ### Configure Module Options at Runtime with sandbox.module Source: https://context7.com/rosalana/sandbox/llms.txt Update GLSL module uniform values from JavaScript at runtime. This is achieved by using the `@module.option` syntax in GLSL, which exposes module parameters as dynamic uniforms controllable via the `sandbox.module()` method. This enables dynamic shader behavior and animations. ```typescript const sandbox = Sandbox.create(canvas, { fragment: ` #import gradient from "my_gradient" void main() { // Hardcoded value vec3 a = gradient(v_texcoord, 1.0); // Dynamic value - controllable via sandbox.module() vec3 b = gradient(v_texcoord, @gradient.speed); gl_FragColor = vec4(a + b, 1.0); } `, modules: { gradient: { speed: 2.0, intensity: 0.8 }, }, }); // Update module options at runtime sandbox.module("gradient", { speed: 1.5, intensity: 1.0, }); // Animate module parameters sandbox.hook(({ time }) => { sandbox.module("gradient", { speed: Math.sin(time) * 2.0 + 2.0, }); }, "before"); ``` -------------------------------- ### Implement Post-Render Hook (JavaScript) Source: https://github.com/rosalana/sandbox/blob/master/README.md Illustrates how to implement a hook that runs after rendering. This is useful for syncing state with reactive frameworks like Vue or React by checking conditions like 'sandbox.isPlaying()'. ```javascript const playing = ref(false); sandbox.hook(() => { playing.value = sandbox.isPlaying(); }, "after"); ``` -------------------------------- ### Importing Animation Utilities from 'sandbox/time' Source: https://context7.com/rosalana/sandbox/llms.txt Shows how to import time-based animation utilities from the 'sandbox/time' module. These functions generate repeating, oscillating, or easing values useful for animations. ```glsl #import loop from "sandbox/time" #import pingpong from "sandbox/time" #import once from "sandbox/time" #import ease_in from "sandbox/time" #import ease_out from "sandbox/time" #import spring from "sandbox/time" #import bounce from "sandbox/time" #import elastic from "sandbox/time" ``` -------------------------------- ### Create WebGL Sandbox Instance - TypeScript Source: https://context7.com/rosalana/sandbox/llms.txt Initializes a new Sandbox instance attached to a canvas element. This function sets up the WebGL context, compiles shaders, and configures the render loop. It accepts a canvas element and an options object for customization, including fragment/vertex shaders, autoplay, DPR, FPS, and event handlers. ```typescript import { Sandbox } from "@rosalana/sandbox"; // Basic usage - auto-playing animated shader const canvas = document.querySelector("canvas"); const sandbox = Sandbox.create(canvas, { fragment: ` precision highp float; void main() { vec2 uv = gl_FragCoord.xy / u_resolution; vec3 color = vec3(uv.x, uv.y, sin(u_time) * 0.5 + 0.5); gl_FragColor = vec4(color, 1.0); } `, }); // Full configuration with all options const sandbox = Sandbox.create(canvas, { fragment: shaderSource, // Fragment shader GLSL source vertex: customVertexSource, // Optional custom vertex shader autoplay: true, // Start rendering immediately (default: true) pauseWhenHidden: true, // Pause when scrolled out of view (default: true) dpr: "auto", // Device pixel ratio ("auto" | number) fps: 60, // Max frame rate (0 = unlimited) preserveDrawingBuffer: false, // Keep buffer for screenshots antialias: true, // Enable antialiasing uniforms: { // Initial uniform values u_intensity: 0.8, u_color: [1.0, 0.5, 0.2], }, textures: { // Initial textures u_photo: imageElement, u_mask: { source: maskImg, wrap: "repeat" }, }, onLoad: () => console.log("Shader compiled"), onError: (error) => console.error(error.code, error.message), onBeforeRender: ({ time }) => { /* pre-frame logic */ }, onAfterRender: ({ time, fps }) => { /* post-frame logic */ }, }); ``` -------------------------------- ### Adding a New Built-in Module in GLSL Source: https://github.com/rosalana/sandbox/blob/master/CLAUDE.md Steps for incorporating a new built-in GLSL module into the Rosalana Sandbox. This involves creating the shader file, importing it, registering it, and adding corresponding tests. ```glsl // 1. Create .glsl file in src/shaders/modules/ // 2. Import in src/globals.ts with ?raw suffix // 3. Register as new Module("sandbox/name", source, options) in the modules registry // 4. Add tests in tests/module_registry.test.ts and tests/integration.test.ts ``` -------------------------------- ### Define Module Options (TypeScript) Source: https://github.com/rosalana/sandbox/blob/master/README.md Demonstrates how to define supported options for functions within a Sandbox module. Options include GLSL uniform names and default values. Per-function options override default module options. ```typescript Sandbox.defineModule("my_gradient", gradientSource, { myFunc: { colors: { uniform: "u_colors", default: [ [1, 0, 0], [0, 0, 1], ], }, speed: { uniform: "u_speed", default: 1.0 }, }, }); ``` ```typescript Sandbox.defineModule("my_module", source, { default: { colors: { uniform: "u_colors", default: [ [1, 0, 0], [0, 0, 1], ], }, speed: { uniform: "u_speed", default: 1.0 }, }, specialFunc: { speed: { uniform: "u_speed", default: 2.0 }, // "colors" is inherited from default }, }); ``` -------------------------------- ### WebGL Shader Version Detection Logic Source: https://github.com/rosalana/sandbox/blob/master/CLAUDE.md Illustrates the logic used by the `Parser.detectVersion()` method to determine the target WebGL version for a shader. It prioritizes an explicit `#version 300 es` directive for WebGL2 and defaults to WebGL1 otherwise. It also handles automatic matching of vertex and fragment shaders when only one is provided. ```javascript class Parser { // ... other methods ... detectVersion(source) { if (source.trim().startsWith('#version 300 es')) { return 'webgl2'; } // Default to WebGL1 if no explicit WebGL2 directive is found return 'webgl1'; } // ... other methods ... } // Example usage: // const parser = new Parser(); // const shaderSource = "#version 300 es\nuniform ..."; // const version = parser.detectVersion(shaderSource); // console.log(version); // Output: 'webgl2' // const shaderSourceWebGL1 = "attribute vec4 a_position;"; // const versionWebGL1 = parser.detectVersion(shaderSourceWebGL1); // console.log(versionWebGL1); // Output: 'webgl1' ``` -------------------------------- ### Configure Module Options Source: https://github.com/rosalana/sandbox/blob/master/README.md Sets configurable options for an imported module. These options map to GLSL uniforms and allow dynamic customization without modifying GLSL code. ```typescript sandbox.module("effect", { intensity: 0.8, }); ``` -------------------------------- ### Using Built-in Uniforms in GLSL Shaders Source: https://context7.com/rosalana/sandbox/llms.txt Illustrates the usage of automatically provided uniforms in GLSL shaders, such as resolution, time, delta time, mouse position, and frame count. These uniforms are essential for dynamic shader behavior. ```glsl // Available in all shaders automatically: uniform vec2 u_resolution; uniform float u_time; uniform float u_delta; uniform vec2 u_mouse; uniform int u_frame; // Example usage void main() { vec2 uv = gl_FragCoord.xy / u_resolution; float pulse = sin(u_time * 2.0) * 0.5 + 0.5; vec2 mouse = u_mouse / u_resolution; gl_FragColor = vec4(uv, pulse, 1.0); } ``` -------------------------------- ### Importing Visual Effect Utilities from 'sandbox/effects' Source: https://context7.com/rosalana/sandbox/llms.txt Demonstrates importing functions for visual distortions and effects from the 'sandbox/effects' module. These include pixelation, ripples, fisheye distortion, and kaleidoscope effects. ```glsl #import pixelate from "sandbox/effects" #import twist from "sandbox/effects" #import ripple from "sandbox/effects" #import fisheye from "sandbox/effects" #import wobble from "sandbox/effects" #import glitch from "sandbox/effects" #import kaleidoscope from "sandbox/effects" #import warp from "sandbox/effects" ``` -------------------------------- ### Default WebGL Shaders Source: https://github.com/rosalana/sandbox/blob/master/CLAUDE.md Provides default vertex and fragment shaders for both WebGL1 and WebGL2 contexts. These shaders serve as a baseline for rendering operations when custom shaders are not provided. ```glsl // src/shaders/webgl1_shader.vert #version 100 attribute vec4 a_position; void main() { gl_Position = a_position; } ``` ```glsl // src/shaders/webgl1_shader.frag #version 100 precision mediump float; void main() { gl_FragColor = vec4(1.0, 1.0, 1.0, 1.0); } ``` ```glsl // src/shaders/webgl2_shader.vert #version 300 es in vec4 a_position; void main() { gl_Position = a_position; } ``` ```glsl // src/shaders/webgl2_shader.frag #version 300 es precision mediump float; out vec4 fragColor; void main() { fragColor = vec4(1.0, 1.0, 1.0, 1.0); } ``` -------------------------------- ### Set Multiple Textures (JavaScript) Source: https://github.com/rosalana/sandbox/blob/master/README.md Demonstrates setting multiple textures, each assigned to a unique uniform name. Sandbox automatically manages texture units for each texture. ```javascript sandbox.setTexture("u_photo", photoImg); sandbox.setTexture("u_mask", maskImg); ``` -------------------------------- ### Set Vertex and Fragment Shaders Source: https://github.com/rosalana/sandbox/blob/master/README.md Allows full control by providing both vertex and fragment shader source codes. Sandbox automatically handles WebGL version detection and fallback. ```typescript sandbox.setShader(vertexSource, fragmentSource); ``` -------------------------------- ### Import GLSL Module Functions Source: https://github.com/rosalana/sandbox/blob/master/README.md Imports functions from defined GLSL modules. Sandbox automatically handles namespacing and dependency resolution for imported code. ```glsl #import bloom from "my_effects" #import hex from "sandbox" void main() { vec3 color = hex(0xFF5733); fragColor = vec4(bloom(color), 1.0); } ``` -------------------------------- ### Built-in Sandbox GLSL Shader Modules Source: https://github.com/rosalana/sandbox/blob/master/CLAUDE.md A collection of built-in GLSL shader modules offering reusable functionality for graphics programming. These modules cover core math operations, UV transformations, noise generation, color manipulation, time-based effects, and image filtering. ```glsl // src/shaders/modules/sandbox.glsl // Core math, UV transforms, noise, constants // Example: Basic noise function (implementation omitted for brevity) float random(vec2 st) { return fract(sin(dot(st.xy, vec2(12.9898,78.233))) * 43758.5453123); } // Example: UV transform function (implementation omitted for brevity) vec2 rotateUV(vec2 uv, float angle) { vec2 center = vec2(0.5); uv -= center; float s = sin(angle); float c = cos(angle); vec2 rotated; rotated.x = uv.x * c - uv.y * s; rotated.y = uv.x * s + uv.y * c; return rotated + center; } const float PI = 3.14159265359; ``` ```glsl // src/shaders/modules/colors.glsl // Color conversion, gradients, palettes // Example: HSL to RGB conversion (implementation omitted for brevity) vec3 hsl2rgb(vec3 hsl) { // ... implementation ... return vec3(0.0); } // Example: Simple linear gradient (implementation omitted for brevity) vec3 linearGradient(vec2 uv, vec3 startColor, vec3 endColor) { // ... implementation ... return vec3(0.0); } ``` ```glsl // src/shaders/modules/time.glsl // Time shapers, easing curves // Example: Ease-in-out function (implementation omitted for brevity) float easeInOutQuad(float t) { // ... implementation ... return t; } // Example: Oscillating value based on time (implementation omitted for brevity) float oscillate(float time, float frequency, float amplitude) { return amplitude * sin(time * frequency); } ``` ```glsl // src/shaders/modules/effects.glsl // UV-space modifiers (pixelate, twist, ripple...) // Example: Pixelate effect (implementation omitted for brevity) vec2 pixelate(vec2 uv, float pixelSize) { // ... implementation ... return uv; } // Example: Twist effect (implementation omitted for brevity) vec2 twist(vec2 uv, float amount) { // ... implementation ... return uv; } ``` ```glsl // src/shaders/modules/filters.glsl // Color filters (contrast, grain, vignette...) // Example: Contrast adjustment (implementation omitted for brevity) vec3 contrast(vec3 color, float amount) { // ... implementation ... return color; } // Example: Vignette effect (implementation omitted for brevity) float vignette(vec2 uv, float sharpness, float darkness) { // ... implementation ... return 1.0; } ``` -------------------------------- ### Set Texture from Image (JavaScript) Source: https://github.com/rosalana/sandbox/blob/master/README.md Shows how to set a texture using an Image element. Sandbox handles the WebGL texture creation, binding, and uniform setting. The texture is applied after the image has loaded. ```javascript const img = new Image(); img.src = "photo.jpg"; img.onload = () => { sandbox.setTexture("u_texture", img); }; ``` -------------------------------- ### License Information Source: https://github.com/rosalana/sandbox/blob/master/README.md Details regarding the licensing of Rosalana Sandbox. ```APIDOC ## License ### Description Information about the open-source license under which Rosalana Sandbox is distributed. ### Method N/A ### Endpoint N/A ### Parameters None ### License Details - **License Type**: MIT License - **Permissions**: Freely use, modify, and distribute. - **Restrictions**: Minimal restrictions. ### Contribution Refer to individual repository guidelines for contribution details. For questions or feedback, open an issue or submit a pull request. ``` -------------------------------- ### Export Frames and Create Streams with Rosalana Sandbox Source: https://context7.com/rosalana/sandbox/llms.txt Demonstrates exporting the current frame as a data URL, Blob, or HTMLImageElement. It also shows how to create a MediaStream for video recording or WebRTC, requiring `preserveDrawingBuffer: true` for exports during animation. ```typescript const sandbox = Sandbox.create(canvas, { fragment: shader, preserveDrawingBuffer: true, // Required for export during playback }); // Export as data URL (synchronous) const url = sandbox.renderAt(1.5).exportAsURL("image/png"); const img = document.createElement("img"); img.src = url; // Export as Blob (async) - perfect for server uploads const blob = await sandbox.renderAt(1.5).exportAsBlob("image/jpeg", 0.9); await fetch("/upload", { method: "POST", body: blob }); // Export as HTMLImageElement const imgElement = sandbox.renderAt(1.5).exportAsImage("image/png"); document.body.appendChild(imgElement); // Create MediaStream for video recording const stream = sandbox.stream(30); // 30 FPS const recorder = new MediaRecorder(stream, { mimeType: "video/webm" }); const chunks: Blob[] = []; recorder.ondataavailable = (e) => chunks.push(e.data); recorder.onstop = () => { const videoBlob = new Blob(chunks, { type: "video/webm" }); const videoUrl = URL.createObjectURL(videoBlob); // Use videoUrl for download or playback }; recorder.start(); setTimeout(() => recorder.stop(), 5000); // Record 5 seconds // WebRTC - send shader output to video call const peerConnection = new RTCPeerConnection(); const stream = sandbox.stream(30); peerConnection.addTrack(stream.getVideoTracks()[0], stream); ``` -------------------------------- ### Static rendering with Sandbox Source: https://github.com/rosalana/sandbox/blob/master/README.md Configures Sandbox for static rendering without autoplay, useful for generating single frames or thumbnails. The render method can be called manually or at a specific time. ```typescript const sandbox = Sandbox.create(canvas, { fragment: fragSource, autoplay: false, }); sandbox.render(); sandbox.renderAt(1.5); ``` -------------------------------- ### Configure Texture Options (JavaScript) Source: https://github.com/rosalana/sandbox/blob/master/README.md Shows how to configure texture parameters like wrapping, filtering, and vertical flipping when setting a texture. These options control how the texture is sampled and displayed. ```javascript sandbox.setTexture("u_texture", img, { wrap: "repeat", // both axes (default: "clamp") minFilter: "nearest", // pixelated look (default: "linear") flipY: false, // disable vertical flip (default: true) }); ``` -------------------------------- ### Set Dynamic Texture from Video (JavaScript) Source: https://github.com/rosalana/sandbox/blob/master/README.md Demonstrates setting a texture from a video element. Sandbox automatically updates the texture each frame to match video playback. This is enabled by default for video elements. ```javascript // Video — dynamic by default sandbox.setTexture("u_video", videoElement); ```