Playground
Try TypeShade in your browser. Choose an example or write your own shader, then inspect the generated code and rendering results.
Start from an example
Each tile is one of the .shade.ts files in the compiler repository. Open one, change it, add files beside it, and bind your own images to its textures.
A fragment shader that reads time, resolution and mouse.
Learning path
-
Module and host.ts First colour The smallest program that draws: one fragment entry that returns one colour for every pixel. -
Module and host.ts UV gradient The positionbuiltin and a size uniform turn each pixel into a coordinate from 0 to 1, drawn as a gradient. -
Module and host.ts Moving wave A timeuniform field moves a wave, andanimate(canvas)draws it once a frame. -
Module and host.ts SDF shapes Functions that return the distance to a circle and to a box, with smoothstepfor a soft edge. -
Module and host.ts Tile pattern A forloop, anifandfractdraw a pattern that repeats in tiles. -
Module and host.ts Mandelbrot set A loop and breakcount how long a point stays near the origin, which colours the Mandelbrot set. -
Module and host.ts Palette A module constant array of four colours, blended with mixinto one smooth ramp. -
Module and host.ts Bouncing balls A class Ballwith a method that moves it and one that measures a pixel against it; a function that changes the ball changes the caller's ball. -
Module and host.ts Double an array The first compute kernel: a @computeentry doubles each number of a storage array. -
Module and host.ts Image blur A 2D @compute([8, 8])entry averages each pixel of an image with its eight neighbours. -
Module and host.ts Sum an array A function that takes an array and returns a number is a kernel function: its forloop runs on the GPU and the host awaits the sum. -
Module and host.ts Parallel sum One workgroup adds up an array, halving its partial sums in workgroupmemory withworkgroupBarrier(). -
Module and host.ts Histogram Many invocations count into shared bins with atomicAdd, so no count is lost. -
Module and host.ts Ray tracer A camera ray for each pixel, a class Sphere, a checkered floor and a shadow, built from the pieces of steps 1 to 8.
Works
-
Class-based Capsule Corp. spaceship on Namek A TypeShade class-based scene of the Capsule Corp. spaceship on Namek. -
Domain warping fbm fed its own output. -
Hillshade Shaded relief. -
Julia set Escape-time Julia fractal. -
Kaleidoscope The polar mirror fold. -
Mandelbrot set The Mandelbrot set with smooth escape-time colouring. -
Ocean horizon A seascape from first principles. -
Path tracer A small path tracer as ordinary TypeScript. -
Plasma The classic sum-of-sines plasma folded through an RGB palette. -
Class-based 3D SDF ray tracer A 3D signed-distance-field renderer built with an abstract SdfShape base class and concrete Sphere, Box, Torus and Plane subclasses. -
Starfield A textureless night sky. -
Tunnel The demoscene tunnel. -
Voronoi A moving Voronoi pattern written in TypeScript syntax.
High precision
-
fp64 Burning Ship The Burning Ship fractal (fold |Re z|, |Im z| before squaring) zoomed onto its needle spike. -
fp64 catastrophic cancellation The numerics-textbook plot on a GPU. -
fp64 checker plane A 1-unit checkerboard on a world plane. -
fp64 long-uptime clock The long-uptime animation bug. -
fp64 deep zoom Emulated double precision (two-f32 df64). -
fp64 Julia set The Julia-set face of the double-float technique. -
Emulated doubles A shader that compares emulated f64andf32precision at a large world coordinate. -
fp64 hyperbolic navigation A LORAN-style chart grid. -
fp64 distance estimate Mandelbrot boundary rendered by distance estimate (d = ½·|z|·ln|z|/|dz|) with precision split mid-formula. -
fp64 Newton fractal Newton’s method for z³ = 1, colour = which cube root a pixel falls into. -
fp64 relative-to-center Why planet-scale engines render relative-to-eye. -
fp64 sine sweep sin(x) for x = a large base + a small on-screen sweep.
Feature examples
-
Runtime array length A bounds check for a kernel that processes a runtime-sized storage array. -
Array literals A fullscreen triangle whose corners come from two array<f32, 3>lists and whose colour comes from anarray<vec3, 3>of stops weighted by anarray<i32, 3>. -
An array's methods Three lights in an array<Light, 3>, shaded with the array methods TypeScript developers commonly use. -
Atomic histogram Many invocations count into one bin at once with atomicAdd(bins[bin], 1), one indivisible step each; a storage struct field and a barestorage<atomic<u32>>binding show the other two shapes of location, and the value an atomic returns is what it held before. -
A vertex that returns only the position The smallest render pair. -
Builtin breadth reflect,refractandfaceForwardlight a bump,transposeanddeterminantread the host matrix, and the bit builtins (firstLeadingBit,reverseBits,countOneBits,extractBits,insertBits) band the screen, withfwidthCoarsemarking where a band starts. -
Bitfield bands A fullscreen triangle whose colour is chosen by a switchover a band index built with&=,|=,<<=,>>=and^=, withlet x: f32declared before it is assigned and the varyings returned as{ pos, uv }shorthand. -
Block scope Two sequential loops over i, apin a loop body beside apin anifarm, and an innerpthat shadows the outer one. -
Boolean vectors A comparison of two vectors is a vector of bools. -
A builder chain, super on accessors, and statics a subclass inherits Shows how return thiskeeps a builder chain on the same object, while a chain starting withnewuses a temporary. -
Objects inside objects, a const that holds one, a field that holds a function, and an interface as a contract ring.advance(dt)callsstepon itsMoverfield and passes the changed object by reference. -
Getters, setters, private names and parameter properties A class Ringwritten the way TypeScript classes are. -
User clip planes Four user clip planes through builtin<"clip_distances", ...>, the vertex output the rasterizer reads before it rasterizes. -
Local functions that read and write the variables around them ringreadspandwidthfrom the fragment entry and adds to itsglow, as a TypeScript closure does. -
Compute reduction A @workgroup_size compute kernel folding a window of an input storage buffer into one output element with reduce(). -
Compare-exchange, uniform load, texture barrier Three workgroup synchronization operations: compare-exchange, uniform load and texture barrier. -
Converting constructors A fullscreen triangle whose corner comes from vec2(vec2u(...))and whose colour comes from anf32→u32→f32round trip. -
The WGSL-only textures A colour ramp as a texture_1d<f32>, two environment maps as atexture_cube_array<f32>picked by layer, a hand-written percentage-closer filter fromtextureGatherCompare, atextureGatherof one channel from four texels, and a point light’s shadow as atexture_depth_cube_array. -
Cube and 3D textures, bias and gradients An environment map as a texture_cube<f32>looked up by direction, a colour-grading table as atexture_3d<f32>the shaded colour indexes,textureSampleBiasandtextureSampleGrad, and a point light’s shadow as atexture_depth_cubecompared by the direction from the light. -
Cutout (source language) discardin a helper the fragment entry calls, withfwidthsoftening the rim andsaturate,exp2and**shaping the falloff. -
Default parameter values Three helpers with default parameters, each called with a different argument omitted. -
Feedback trail A dot that leaves a trail. -
A generic class by monomorphisation A class Slot<T>used at f32 and at vec3, so the module carriesSlot_f32andSlot_vec3as separate structs, each with its own constructor and its own copy of every method. -
Generics by monomorphisation Three generic helpers, each compiled once per set of argument types the file calls it with. -
Console from the GPU console.log("i =", gid.x, p)inside a compute kernel. -
Gradient pass A two-colour vertical gradient with a biasable blend. -
Hello triangle The smallest complete TypeShade program. - No entry point Hello camera uniform A
Cameraclass ofmat4+vec3behinduniform<Camera>, read by a plain helper function. -
Hello uniform A bare declare const scale: uniform<f32>keeps the same numeric host value on both targets. -
Hello uniform block A Uniformsclass behinduniform<T>groups several values in one std140 block on both targets. -
Hello vertex attributes Vertex input from a buffer rather than from vertex_index. -
Hello varyings The triangle again, now carrying a uvvarying from the vertex stage into the fragment stage through a sharedVsOutinterface. -
Functions that take a function coverandaround4accept a distance-field function and compile a copy for each function passed to them. -
An integer varying, and the interpolation it has no choice about Entry IO as WGSL declares it. -
Imported noise Clouds drawn with the fbmof another shader file. -
Return types the body says Each function omits its return type, which TypeShade infers from the value its body returns. -
Integer abs and dot Integer absanddot, which GLSL ES 3.00 does not provide for these input types. -
Module and host.ts An array's methods in a kernel function sumOfSquares,scaleandfirstAboveuse array methods to reduce, write and search kernel data. - No entry point A kernel that writes an image
invertreads atexture_2d<f32>and writes the result to atexture_storage_2din a kernel loop. -
Module and host.ts A kernel that appends with push strongusesout.push(i)to append the index of each element above a threshold. -
Module and host.ts A kernel that collects unique labels in a Set labelscollects nonzero pixel labels in aSet<u32>, whilelatestkeeps each key's last value in aMap<u32, f32>. -
Module and host.ts A loop that runs as a kernel A terrain kernel that processes each element of a runtime-sized output array. - No entry point Loops that run on the CPU One loop for each rule of the independence proof (R1 to R6) that the proof refuses.
-
Module and host.ts Reductions in a loop A sum, a mean and a variance, and a histogram, each a loop over an array. - No entry point A loop over an array of structs The particle step as a loop over
array<Particle>. -
Loops over data The three loops a program over data writes, through Tint and a real WebGL2 context. -
The mixin pattern A function Tinted(Base)whose body is onereturn class extends Base { ... }, applied to two different geometry classes. -
Module constants A module-scope constant of every scalar type the compiler allows. -
A multisampled texture, resolved by hand An MSAA render target as a texture_multisampled_2d<f32>read one sample at a time withtextureLoad(t, coords, sampleIndex)and averaged overtextureNumSamples, and its depth attachment as atexture_depth_multisampled_2d. -
Matrices beyond mat4 Uses mat3for a normal matrix, and demonstrates matrix truncation, transpose and multiplication. -
Null, undefined and present values Nullable classes and members retain three states through optional chaining. -
Optional fields, elements and parameters A struct field, an array element and a parameter hold T | undefined(§76, change 0093). -
Optional values: T | undefined A function, a local and a callback hold T | undefined, and the compiler carries whether the value is there. -
A method that changes its object A class Bodywhosestep,turnandadvanceassign tothis, so each takes its object by reference. -
Packed 4x8 integer builtins The eight builtins that read a u32as four bytes or write four back. -
Packing, bitcast and the constructors Examples of packing, bitcast and constructor operations available to TypeShade shaders. -
Module vector and array constants A fullscreen triangle banded by a module-scope array<vec4, 3>palette and anarray<f32, 3>of stops, with avec3constant built from an earlier scalar one. -
Methods that change their object A class Particlewhosestep,bounceandtickassign tothis, called on a storage element. -
A conditional on a struct and on an array Two arms that are structs, and two that are fixed-length arrays, chosen at run time. -
Per-invocation state A plain top-level let seed: u32is WGSL'svar<private>, one copy per invocation that every function of the invocation shares. -
Class methods A class Raywith a constructor, a method and a static function, and aclass Spherewhosehit(ray)method returns the distance along the ray. -
Objects are passed as JavaScript passes them A function that writes a field or an element of its parameter changes the caller's object, with no mark on the parameter or at the call. -
A method that changes its object and returns a value A class Rngwhosenext()advances the generator's state and returns the draw. -
A sample under a branch, and the compiler rewrites it WGSL requires textureSampleto be called from uniform control flow. -
Separable blur A blur in two passes. -
A shadow map, read by comparison A depth texture read through a sampler_comparisonwithtextureSampleCompareandtextureSampleCompareLevel, on a plain 2D shadow map and on a cascade array. -
Inheritance An abstract class Shapewith a concrete method and an abstract one, two classes that extend it, and one that extends a subclass and callssuper. -
A storage texture An image a compute entry writes by texel coordinate, with no sampler and no filtering. -
Subgroup reduction before an atomic subgroupAddfolds each subgroup's values in one instruction andsubgroupElectpicks one lane to add the fold into the bin withatomicAdd. -
Texture, sampler and overrides A fullscreen triangle sampling a texture_2d<f32>through asampler, tinted by twooverride<f32>specialization constants. -
A tuple and a branded alias A tuple is a list of a length the type fixes, which is what array<T, N>is, so[f32, f32]isarray<f32, 2>. -
Twin IO structs Two IO structs with identical fields, a vertex output and a fragment input, with object literals in all three positions that declare which one they build. -
A uniform holding a list A uniformholdingarray<f32, 4>. -
Workgroup size override One override<u32>sets the compute entry's workgroup size and the outer length of its shared scratch array. -
Workgroup reduction 64 invocations sum 64 values into one through workgroup memory, with workgroupBarrier()ordering the rounds. -
Workgroup scratch memory let tile: workgroup<array<f32, 64>>is WGSL'svar<workgroup>, one copy per workgroup its invocations share, here as scratch each invocation owns a slot of, beside a workgroup array of atomics and a per-invocation counter. -
Two-dimensional workgroup @compute([8, 8])is WGSL's@workgroup_size(8, 8).
Host examples
-
Module and host.ts Draw into a canvas A full-screen @fragmententry and the host that draws it. -
Module and host.ts Dispatch a compute entry A @compute(...)entry and its host. -
Module and host.ts Call a kernel function Two kernel functions and the host that calls them. -
Module and host.ts Keep data on the GPU Three kernel functions and a host that chains them over Buffers thatarray()makes. -
Module and host.ts One helper on the CPU and the GPU A terrain heightfunction that the fragment entry draws on the GPU and the host calls on the CPU. -
Module and host.ts String keys and Record A fixed set of channel names becomes u32ids, and aRecordbecomes an array in id order. -
Module and host.ts Run the compiled program A vertex and a fragment entry, and a host that runs them as an engine does. -
Module and host.ts Fuse a chain of kernel calls Five kernel functions and a host that calls them inside fuse()fromtypeshade/fuse. -
Module and host.ts Collect into a Set and a Map Four kernel functions accept JavaScript SetandMapvalues, and a host calls them.
If VS Code did not open, the TypeShade extension may be missing. How to install it.
Compile a module with a vertex entry and a fragment entry to see it drawn.
host.ts is running in a sandboxed frame over the canvas. Its console lines are in the Console tab.
Run the fragment entry once per pixel, with no GPU.
Call console.log in a shader to see its lines here. A compute module logs every invocation. In a module that draws, click a pixel of the canvas, or record the whole frame on WebGPU.