Appearance
Shaders
A shader is a short piece of code that decides how something looks or moves. You write it in the editor, and the scene shows each change as you type.
There are four kinds:
- Material shader draws the surface of an object.
- Effect shader changes the picture of the whole scene.
- Texture shader paints a texture, step by step.
- Mesh shader moves the points of a mesh, step by step.
Creating a shader
- Open Library > Shaders.
- Choose New Shader, then Material Shader, Effect Shader, Texture Shader or Mesh Shader.
The new shader opens with commented starter code that already draws something, plus a few parameters to play with. It is named after its kind; rename it in the list.
A new shader belongs to the open experience. It appears under This Experience. Shaders you share across experiences appear under My Assets (see Sharing).
Editing
Select a shader in the list to open its code. The Parameters panel sits beside the code.
- Typing updates the scene. After a short pause, the editor rebuilds the shader and every object or effect in the scene that uses it shows the change.
- A mistake keeps the last working version. While the code has a problem, the scene keeps drawing the last version that worked.
- Changes save on their own. A moment after you stop typing, the shader is saved for every platform, and other devices, viewers and the App Clip get the change. Code with a problem is saved once the problem is fixed.
- Discard Changes shows while changes are not saved, for example while the code has a problem or you are offline. It goes back to the last saved shader. It asks first.
- Changes that are not saved yet stay on this device. They survive closing the editor or the app, and come back the next time you open the shader on the same device. If the shader was saved since then, they wait until you edit it again, so they don't replace the newer version by accident.
When you open a shader, the viewport frames the objects that use it. For a material shader, Isolate shows only those objects, and Show Whole Scene brings the rest back.
When nothing in the scene uses the shader yet, the viewport hides the scene and shows the shader on a preview object instead: a sphere for a material shader and a grid for a mesh shader. The button with the shape's name above the code switches to the next shape (a material shader also previews on a cube or a plane, a mesh shader on points or a strip), and the shader keeps the choice. Selecting a shader texture in Library > Textures that no object shows yet puts it on a preview plane. The preview object is never saved into the experience, and it goes away once an object uses the shader or you leave the Library.
TIP
- Open Documentation (the question mark above the code) brings you to this page.
- Shaders uploaded as files made outside Scenery can still be used, but their code can't be edited here.
Parameters
Parameters are the values a shader reads that you can change without touching the code. The Parameters panel lists them, and Add Parameter adds one of these kinds:
| Type | What the code reads |
|---|---|
| Decimal | A float. |
| Integer | An int. |
| On/Off | A bool. |
| Color | A float4: red, green, blue and alpha. |
| Vector | A float2, float3 or float4: two to four numbers. A new one has three. |
| Matrix | A float4x4. |
| Dropdown | An int: the index of the chosen option, from 0. Options lists the texts to choose from, and Add Option adds one. |
| Texture | An image, read with sample(parameters.name, uv). |
| Environment Map | A 360° picture, read with sample(parameters.name, direction), where direction points from the centre of the picture outwards. Material and effect shaders only. Its kind can't be changed. To use another kind, remove the parameter and add a new one. |
Each parameter has a Name of letters, digits and underscores that does not start with a digit. The code reads it as parameters.name, so parameters.tint for a parameter named tint. The value you set in the panel is the parameter's default. Drag a parameter by its name to reorder the list.
Limit Range keeps a Decimal, Integer or Vector between a Minimum and a Maximum, and shows a number as a slider.
In a material or an effect, an Environment Map parameter takes an Environment Map from your assets. The shader reads a picture six faces wide, six faces tall, or a cross four faces wide and three tall, as the six faces of a cube. It reads any other picture as a 360° panorama. A script sets one with material.shaderTexture(name, 'ASSET_ID') or effect.shaderTexture(name, 'ASSET_ID').
A texture's Contains is Color for photos and artwork, and Data for normal, roughness or mask maps, which the shader reads unchanged. When Empty is what the shader reads while no picture is set: Black, White, Transparent, or for Data also Flat Normal.
A material shader also has a Blend Mode: Opaque, Transparent or Additive, or Set in Material to let each material choose. Use Transparent when the code writes surface.opacity below 1. It also has a Lighting Model: Lit, Unlit or Clearcoat, as on the Materials page. An Unlit shader also has an Enable Tone Mapping switch. Turn it off to show colours exactly as the shader writes them, without the scene's tone curve, for interface graphics that must match their source. Leave it on for a Scene Background texture and sceneColor, which then match what is behind the object.
In the material and effect inspectors
A material or effect that uses the shader shows its parameters in its own inspector, so each one can have its own values:
- A material: choose the Custom Shaders kind and pick the shader in Select a Shader.
- An effect: create a Shader effect in Post-FX and pick the shader in Select a Shader.
Numbers stay within the range the shader gives them. A texture parameter picks a picture from your assets. A texture a script fills shows as set by a script.
While you drag a colour or a vector, the scene shows each value at once. The value is stored once you stop, as one undo step.
The inspector also lists where the shader runs, with a note for each platform that runs it differently or not at all.
Texture shaders in Library > Textures
A texture shader draws a texture that any texture slot can show:
- Open Library > Textures and choose New Texture, then Shader Texture.
- Pick the shader under Shader.
- Choose the Size, from 256 to 2048 pixels; 512 is the default.
- Choose whether it Runs Every Frame or Once, and its Clear Color, what it shows until the shader draws: Black, White, Transparent or Flat Normal.
The texture then shows in the texture slots of every material and every effect, next to your pictures.
A texture or mesh shader's texture parameters show under Parameters too. Each takes a picture, another Shader Texture or the Scene Background; an Environment Map parameter takes an Environment Map. When one Shader Texture reads another, the one it reads runs first in the same frame. A texture never reads itself. When two textures read each other, one of them sees the other's result from the frame before. A Library Image or Video is not offered there: choose its picture instead.
Scene Background
In Library > Textures, New Texture, then Scene Background adds a texture that shows what is behind the scene. In AR on iPhone and iPad it is the live camera image; on Mac it is the scene's background. A material or effect shows it from a texture slot, and the shader reads it at context.backgroundUV, so it lines up with the view behind the object. With tone mapping on, it also matches the brightness of what is behind the object. Every material shader has tone mapping on, except an Unlit one with Enable Tone Mapping off. Bright parts of the image read above 1. With a texture parameter named camera:
cpp
surface.emissiveColor = sample(parameters.camera, context.backgroundUV).rgb;Check features.background before relying on it (see Features).
Textures
Library > Textures holds the textures several materials and effects can share. New Texture makes one of four kinds:
- Shader Texture, drawn by a texture shader (see above).
- Image, a picture from your assets.
- Video, a video from your assets, with Autoplays, Loops and Audio Volume.
- Scene Background, the camera image or the scene's background (see above).
An Image, a Video or the Scene Background can run Processing steps, in order, before a material shows it. Add Step offers Size (Full, Half or Quarter of the picture), Blur with a Radius from 0 to 64 pixels, Threshold to Zero, which turns everything darker than its Value black, Radial Zoom Blur with an Amount, and Shader, which runs a texture shader on the picture. A texture runs up to three steps besides Size. Drag a step by its title to reorder it, or use its buttons to move it up or down and to remove it.
A texture slot's menu also gives the slot a texture of its own: Choose Image…, Choose Video… or Shader Texture, or one from Library Textures. A shader's texture inputs also offer Scene Background, since only a shader can line it up with what is behind the object. A texture of its own shows its options under the slot. The slot's ⋯ adds processing steps to its picture, and Add to Library… names the texture so other slots can use it. A slot showing a Library texture shows a link and how many places use it; its ⋯ offers Edit in Library, Rename… and Detach, which gives the slot its own copy to change.
Mesh shaders on a Dynamic Mesh or a Gaussian Splat
A mesh shader moves the points of a mesh, with no script:
- Insert a Dynamic Mesh (a Grid, Points or a Strip) or a Gaussian Splat.
- In its inspector, pick the shader under Shader.
- Choose whether it Runs Every Frame or Once, and set its parameters, texture parameters included (see Texture shaders).
- On a Grid or Strip, turn on Recalculate Normals when the shader moves only
position. After each run the normals follow the new shape, so the light matches it. A shader that writesnormalitself, as the Waves starter does, doesn't need it.
A script can set or stop the shader of a mesh or splat with setShader, as described in Compute Kernels.
Problems
Problems are written in plain words: what is wrong and what to do about it.
- Errors are marked at their line in the code and listed under it, for example "Line 7: speed is not defined. Declare it first or check the spelling."
- Platform notes say where a saved shader does not run, or runs differently. A note about one line is marked there. A note about the whole shader shows under the code, for example "Does not run on Apple Vision Pro. Effects are not available there."
If a platform could not be stored when the shader saved, a message under the code says which. If saving fails, a message under the code says why, and the editor tries again with your next change or when you are back online.
Where each kind runs
| Kind | Runs on |
|---|---|
| Material | iPhone and iPad, Mac, the App Clip. Apple Vision Pro and the web when the shader can be converted for them. |
| Effect | iPhone and iPad, Mac, the App Clip, the web when the shader can be converted for it. Not on Apple Vision Pro. |
| Texture | iPhone and iPad, Mac, the App Clip, Apple Vision Pro. The web when the shader can be converted for it. |
| Mesh | iPhone and iPad, Mac, the App Clip, Apple Vision Pro. The web when the shader can be converted for it. |
On iPhone and iPad with an A12 chip or earlier, a material shader gets its textures through the slots of the material it replaces: at most 8, fewer for each …Image field it reads, and only 2D images. A material shader beyond that does not draw on those devices, and a platform note at line 1 says why.
Whether a particular shader converts depends on its code. Its platform notes and the list in the inspector say where it runs.
Currently
- Post-FX is hidden in an experience that targets Apple Vision Pro.
Sharing
- This Experience lists the shaders that belong to the open experience.
- My Assets lists the shaders you can use in any of your experiences.
Move to My Assets (above the code of one of this experience's shaders) makes it available to all your experiences.
When a shader from My Assets is used in your other experiences, Used in N Other Experiences shows above the code. Tap it to see which.
The first time you change such a shader, the editor asks how:
- Edit for All changes the shader everywhere it is used. Your changes save as you type and show in those experiences too. Renamed or removed parameters, and parameters whose kind you change, reach them when you leave the shader.
- Copy into This Experience makes a copy that belongs to this experience and points this experience at it. Your change goes into the copy, and the other experiences keep the original. Scripts that name the original keep using it, and the prompt says how many there are.
- Cancel drops the change.
Reference
Shaders are written in the Metal Shading Language, with types such as float, float2, float3, float4, int and bool (GLSL names such as vec3 don't work). Metal's math functions, such as sin, mix, smoothstep, fract and length, and constants such as M_PI_F work in every kind. Each kind defines one function that Scenery calls. Positions are in metres, times in seconds, and colours are linear from 0 to 1.
Every kind can also use these helpers:
| Helper | Returns |
|---|---|
noise(p) | Smooth noise from 0 to 1, for a float2 or float3 position. |
perlinNoise(p) | Perlin noise, about -1 to 1. |
cellNoise(p) | One random number from 0 to 1 for the whole-number cell p falls in, for a float2 or float3 position. |
hash(p) | Random numbers from 0 to 1 for the cell p falls in, one for each component of p, the same on every device. |
remap(value, low, high) | value mapped from low–high to 0–1, not clamped. |
inverse(m) | The inverse of a float3x3 or float4x4 matrix. A matrix without one gives infinities. |
Your own functions and types can reuse these names: in your shader, yours replace Scenery's. A type can't take the name of one your function receives or returns, such as SurfaceContext or Parameters.
Object is an object in the scene. A material reads the one it is on as context.object, an effect the ones bound to it as context.objects[i]:
| Field | Meaning |
|---|---|
modelToWorld | Turns a point in the object's own space into the world. |
position | The object's origin in metres, in the world. |
size | The object's bounding box in metres, in its own space. Zero while it loads. |
radius | Half the diagonal of the object's bounding box in the world, in metres. |
opacity | How far the object has faded in, from 0 to 1. |
Features
Not every device can do everything. A shader asks with features.<name> and keeps code that needs a feature inside if (features.<name>), with a fallback in else. Each platform runs the branch that fits it, and a shader that uses such code outside a check does not run where the feature is missing. A call to backgroundBlur(context) or sceneColor(context, level) outside its check is refused when the shader is saved.
| Feature | True where |
|---|---|
features.background | A Scene Background texture shows the camera image or the scene's background: iPhone and iPad, the App Clip, and Mac on macOS 26 or later. |
features.sceneColor | sceneColor(context, level) works: iPhone, iPad and Mac, outside the App Clip. |
features.backgroundBlur | backgroundBlur(context) works: iPhone and iPad, Mac, the App Clip and Apple Vision Pro. |
features.arDepth | sampleARDepth measures the real surroundings: iPhone and iPad with LiDAR, in AR, in the app and the App Clip. |
features.postProcessing | Effects run: everywhere except Apple Vision Pro. |
features.compute | Texture and mesh shaders run: iPhone, iPad and Mac with an A14 or M1 chip or later, Apple Vision Pro and the web. |
features.atomics, features.scatter, features.threadgroupMemory | A texture or mesh shader can use atomic operations, write to other elements, or share memory between threads. True where features.compute is. |
Material shader
cpp
Surface surface(SurfaceContext context, Parameters parameters)surface runs for every pixel of the surface and returns how it looks.
SurfaceContext is the pixel being drawn:
| Field | Meaning |
|---|---|
uv, uv1 | The mesh's first and second texture coordinates. (0, 0) is the bottom left, v grows upward. |
uvTransform | The material's texture transform: (uvTransform * float3(uv, 1.0)).xy places uv as the material's own textures are placed. |
screenUV | Where the pixel is on screen, 0 to 1. (0, 0) is the bottom left. |
backgroundUV | Where the pixel is in the camera image, for reading a Scene Background texture with sample. The same as screenUV where there is no camera image. |
position, modelPosition | The point's position in metres, in the world and in the object's own space. |
normal, tangent, bitangent | Surface directions in the world, unit length. |
viewDirection | From the point towards the camera, in the world, unit length. |
cameraPosition | The camera's position in metres, in the world. |
object | The object this material is on, as an Object. |
vertexColor | The mesh's vertex colour, (0, 0, 0, 1) when it has none. |
payload | What geometry handed over (below), or 0. |
time | Seconds. |
startTime | The time the object joined the scene, in seconds. |
ambientIntensity | The estimated light of the real surroundings, in lumens. 1000 without an estimate, as on Mac, Apple Vision Pro, the web and outside AR. |
ambientColorTemperature | The estimated colour of that light, in kelvin. 6500 without an estimate. |
hover.isActive, hover.intensity, hover.position, hover.time | A gaze or pointer resting on the object, on Apple Vision Pro. Nothing is hovered elsewhere. |
instanceID | Which copy of the mesh is being drawn. |
material | The values of the material this shader replaced, such as material.baseColorTint. |
material.baseColorImage, material.normalImage, material.roughnessImage and the other …Image fields of material | The images of the material this shader replaced, read with sample(context.material.baseColorImage, uv). |
modelToWorld, worldToView and the other matrices | Transforms between the object, the world, the view and the screen. |
worldToModel | Turns a world position into the object's own space, for example (context.worldToModel * float4(context.position, 1.0)).xyz to raymarch inside the object. |
normalToModel | Turns a world direction or normal into the object's own space, not normalised. |
Surface is how the pixel looks. Every field starts at its default, so set only the ones you need:
| Field | Meaning |
|---|---|
baseColor | The surface colour, 0 to 1. Default white. |
emissiveColor | Light of its own. Above 1 is brighter. An unlit material draws only this. Default black. |
normal | The surface direction relative to the mesh. (0, 0, 1) keeps the mesh's own. |
roughness | 0 is a mirror, 1 is matte. Default 0. |
metallic | 0 to 1. Default 0. |
ambientOcclusion | 1 is unshadowed. Default 1. |
specular | How much a non-metal reflects. 0.5 is 4 percent. Default 0. |
opacity | 0 to 1. Default 1. It does not remove the pixel. |
isCutOut | true removes the pixel. |
clearcoat, clearcoatRoughness, clearcoatNormal | The glossy top layer, with the Clearcoat lighting model only. |
rim(context, power) returns 0 where the surface faces the camera and rises to 1 at its outline. A higher power makes the edge thinner.
environment(context, roughness) returns the scene's environment light reflected at the pixel, as blurred as a surface of that roughness (0 mirror, 1 matte) blurs it, or black where the scene has no environment light.
backgroundBlur(context) returns the scene behind the pixel, blurred, as frosted glass shows it. Call it only inside if (features.backgroundBlur), with a fallback in else for platforms without it (see Features). An Unlit material draws it through emissiveColor:
cpp
if (features.backgroundBlur) {
surface.emissiveColor = backgroundBlur(context).rgb;
} else {
surface.emissiveColor = parameters.tint.rgb;
}Previewing such a material in the editor needs iOS 27 or macOS 27.
sceneColor(context, level) returns the scene behind the pixel, as drawn before transparent objects, in linear colour with alpha 1. In AR it includes the camera image. level sets how sharp it is: 0 is sharp, and each step up halves the detail, so a higher level reads like frosted glass. Call it only inside if (features.sceneColor), with a fallback in else; a call outside the check is refused when the shader is saved. sceneColor only shows the scene behind the object when the shader's Blend Mode is Transparent; with Opaque, the else branch draws:
cpp
Surface surface(SurfaceContext context, Parameters parameters) {
Surface surface;
if (features.sceneColor) {
surface.emissiveColor = sceneColor(context, 2.0).rgb;
} else {
surface.emissiveColor = float3(0.5);
}
return surface;
}sceneColor(context, screenUV, level) returns the scene at another point on screen, which makes refraction possible. screenUV is a screen position like context.screenUV, from (0, 0) at the bottom left to (1, 1) at the top right. Shift the pixel's own context.screenUV to bend the view through the object, for example along the normal as the camera sees it: sceneColor(context, context.screenUV + (context.worldToView * float4(context.normal, 0.0)).xy * 0.02, 1.0). In AR the camera image shifts with it. It needs the same features.sceneColor check.
A material shader can also move the object's points with a second function:
cpp
Geometry geometry(GeometryContext context, Parameters parameters)GeometryContext has the same kind of fields as SurfaceContext, for the point being moved (uv, position, modelPosition, normal, modelNormal, vertexColor, time, vertexID and more). Geometry returns modelOffset (metres, added to the point's position in the object's own space), modelNormal and modelBitangent (in the object's own space), uvOffset, uv1Offset, and payload, which reaches surface as context.payload.
A material shader with only geometry and no surface keeps the model's own surface and only moves its points. It runs on iPhone, iPad and Mac. It does not run on Apple Vision Pro or the web, and on iPhone and iPad with an A12 chip or earlier its texture parameters don't draw.
A plane or sphere moves smoothly only with Subdivisions above 1, set in its Model section. A 3D model moves with the points it already has.
Moving a point doesn't turn its normal, so the light still falls as on the unmoved surface. To light the new shape, move two neighbouring points the same way. Then return the normal of the triangle they make with the moved point, as the Wobble starter does:
cpp
// Where a point at position ends up: pushed along the surface's normal by noise that drifts over time.
float3 displaced(float3 position, float3 normal, float time, float amplitude, float scale, float rate) {
return position + normal * noise(position * scale + time * rate) * amplitude;
}
Geometry geometry(GeometryContext context, Parameters parameters) {
Geometry geometry;
float3 position = context.modelPosition;
float3 normal = normalize(context.modelNormal);
float3 moved = displaced(position, normal, context.time, parameters.amplitude, parameters.scale, parameters.rate);
geometry.modelOffset = moved - position;
if (parameters.correctNormals) {
float3 axis = mix(float3(1.0, 0.0, 0.0), float3(0.0, 1.0, 0.0), abs(normal.x));
float3 tangent = normalize(cross(axis, normal));
float3 bitangent = normalize(cross(tangent, normal));
float neighbourDistance = 0.01;
float3 alongTangent = displaced(position + tangent * neighbourDistance, normal, context.time, parameters.amplitude, parameters.scale, parameters.rate);
float3 alongBitangent = displaced(position + bitangent * neighbourDistance, normal, context.time, parameters.amplitude, parameters.scale, parameters.rate);
geometry.modelNormal = normalize(cross(alongBitangent - moved, alongTangent - moved));
}
return geometry;
}Parameters: color (Color, white), roughness (Decimal, 0.5, range 0 to 1), amplitude (Decimal, 0.025, range 0 to 0.1), scale (Decimal, 10, range 0 to 40), rate (Decimal, 1, range 0 to 5), correctNormals (On/Off, on). Turn correctNormals off to see the lumps lit as if the surface were still smooth.
Starter code:
cpp
// A rainbow flowing over the surface, with a glowing edge. Change the parameters beside this code, or the code itself.
// context is the point being drawn: context.uv, context.time, context.normal and more.
// Return a Surface. Every field you leave alone keeps its default.
Surface surface(SurfaceContext context, Parameters parameters) {
Surface surface;
// Each colour channel is a cosine wave, the three about a third of a turn apart, so together they cycle
// through the rainbow across the surface and over time.
float phase = (context.uv.x + context.uv.y) * 2.0 * M_PI_F + context.time * parameters.speed;
float3 rainbow = 0.5 + 0.5 * cos(phase + float3(0.0, 2.0, 4.0));
surface.baseColor = rainbow * parameters.tint.rgb;
// 0 where the surface faces the camera, 1 at its outline. Raising it to a power keeps the glow near the edge.
float edge = 1.0 - saturate(dot(context.normal, context.viewDirection));
surface.emissiveColor = rainbow * pow(edge, 3.0) * parameters.glow;
return surface;
}Parameters: tint (Color, white), speed (Decimal, 1, range 0 to 5), glow (Decimal, 1, range 0 to 4).
Effect shader
cpp
float4 screen(ScreenContext context, Parameters parameters)screen runs for every pixel of the picture and returns its new colour.
ScreenContext is the picture at one pixel:
| Field | Meaning |
|---|---|
uv | The pixel's centre. (0, 0) is the bottom left, 1 at the far edges. |
backgroundUV | Where the pixel is in the camera image, for reading a Scene Background texture with sample. The same as uv where there is no camera image. |
coord | The pixel. (0, 0) is the top left. |
size | The picture's size in pixels. |
color | The picture's colour at this pixel. |
time | Seconds. |
startTime | The time at this effect's first frame, in seconds. |
cameraPosition | The camera's position in metres, in the world. |
ambientIntensity | The estimated light of the real surroundings, in lumens. 1000 without an estimate, as on Mac, Apple Vision Pro, the web and outside AR. |
ambientColorTemperature | The estimated colour of that light, in kelvin. 6500 without an estimate. |
floorToWorld | The detected floor, or no transform when there is none. |
worldToView, viewToWorld, viewToProjection, projectionToView | Transforms between the world, the camera's view and the screen, as in materials. |
objectCount, objects | The objects bound to this effect, each an Object, in the order of the effect's Object Transform Bindings list in the Post-FX panel. Each scene keeps its own list. objectCount is 0 with none. |
colorImage | The picture, as an image. |
depthImage | The virtual scene's depth, as an image: the near plane over the distance, 0 where nothing was drawn. sampleDepth gives metres. |
arDepthImage | The real surroundings' depth measured by LiDAR, in metres. Empty without LiDAR or outside AR. |
environmentImage | The surroundings as a cube image. Empty when there is none. |
previousFrame | What this effect drew on the frame before, for trails and feedback. Empty on its first frame and after the view changes size. |
Every image takes the usual texture methods: read an exact pixel, sample with your own sampler, gather, and its size and levels.
Helpers to read the scene:
| Helper | Returns |
|---|---|
sampleFrame(context, uv) | The picture's colour at uv, smoothed between pixels. |
backgroundImageUV(context, uv) | Where uv is in the camera image, like context.backgroundUV for another point. |
sampleDepth(context, uv) | The scene's distance from the camera at uv, in metres. |
sampleDepthFiltered(context, uv) | The same, smoothed between pixels. |
sampleARDepth(context, uv) | The real surroundings' distance from the camera at uv, in metres, measured by LiDAR. 0 without LiDAR or outside AR. |
sampleEnvironment(context, direction) | The surroundings' colour in a direction, or black when there is none. |
rayDirection(context, uv) | The direction from the camera through uv, in the world, unit length. |
scenePosition(context, uv) | Where the scene is at uv, in metres, in the world. |
project(context, position) | Where a world position is on screen: xy its uv, z its distance from the camera in metres, negative behind the camera. |
Starter code:
cpp
// A vignette: the picture darkens towards its edges.
// sampleFrame(context, uv) reads the picture's colour, and context.uv is this pixel's position.
float4 screen(ScreenContext context, Parameters parameters) {
float4 color = sampleFrame(context, context.uv);
// 0 at the centre of the screen, about 0.7 in its corners.
float distanceFromCentre = length(context.uv - 0.5);
float darkening = smoothstep(parameters.radius, parameters.radius + parameters.softness, distanceFromCentre);
color.rgb *= 1.0 - darkening * parameters.strength;
return color;
}Parameters: radius (0.3), softness (0.4), strength (0.8), each a Decimal from 0 to 1.
Texture shader
cpp
float4 texel(TexelContext context, Parameters parameters)texel runs once for every texel of the texture, every step, and returns its new value.
TexelContext is the texel being painted:
| Field | Meaning |
|---|---|
coord | The texel, a uint2. (0, 0) is the top left, y grows downward. |
uv | The texel's centre, a float2 from 0 to 1. (0, 0) is the bottom left, v grows upward. |
size | The texture's size in texels, a float2. Convert it with int2(context.size) to compare it with coord. |
time | Seconds the scene has run. |
deltaTime | Seconds since the previous step. |
previous | This texel's value from the previous step. It holds data, not necessarily a colour. |
previousImage | The whole texture as the previous step left it. read a texel, or sample it smoothed between texels. |
neighbor(context, offset) returns the previous step's value a few texels away, clamped to the edges. offset.y grows downward, so int2(0, 1) is the texel below.
Because each step can read the last one, a texture shader can run a simulation, such as ripples spreading on water. Each texel holds four 16-bit floating-point values, so it can store negative numbers and values above 1, such as heights, and keep the last step's value in another channel.
Starter code:
cpp
// A soft spot of colour, centred on touch: (0, 0) is the texture's bottom left, (1, 1) its top right.
// A script moves touch where the surface is touched, with scene.createSurfaceInput.
// texel runs once for every texel, every step, and returns its new colour.
float4 texel(TexelContext context, Parameters parameters) {
float distanceFromTouch = length(context.uv - parameters.touch);
float spot = 1.0 - smoothstep(0.0, parameters.size, distanceFromTouch);
return mix(parameters.outer, parameters.inner, spot);
}Parameters: touch (Vector of two, (0.5, 0.5), range 0 to 1), inner (Color, white), outer (Color, black), size (Decimal, 0.4, range 0 to 1).
Mesh shader
cpp
Element element(ElementContext context, Parameters parameters)element runs once for every point of the mesh, every step, and returns the point's new values.
ElementContext is what the engine passes in:
| Field | Meaning |
|---|---|
previous | The point as the last step left it. Starts at the mesh's own values. |
index | The point's place in the mesh, from 0 to count - 1. |
count | The number of points. |
time | Seconds the scene has run. |
deltaTime | Seconds since the previous step. |
Element is one point. Use the fields you need: the editor reads them from your code when it saves.
| Field | Type | Meaning |
|---|---|---|
position | float3 | The point's position in metres. |
normal | float3 | The direction the surface faces at the point, which lighting reads. |
tangent | float3 | The direction the texture's x coordinate grows in along the surface. |
uv | float2 | The point's texture coordinate. |
color | float4 | The point's colour, linear. |
scale | float3 | A splat's size along each axis. |
rotation | float4 | A splat's orientation, as a quaternion. |
opacity | float | A splat's opacity, 0 to 1. |
restPosition | float3 | Where the point was before any shader moved it, in metres. Read only: write position to move the point. |
A shader that uses outputIndices (uint) and no other field writes a Dynamic Mesh's indices instead, one element per index, on a mesh with 32-bit indices. Any other field is the error "Unknown element field".
Move points from restPosition instead of from context.previous.position when the shape should follow a parameter: a ripple added to the rest position goes back to the exact start when its height is 0, while one added step after step on top of the last position keeps every change you made while it ran. restPosition is the same for every shader the object runs, so changing the shader keeps it.
Writing normal needs the shape's slope, which only a shape given by a formula has. For any other shape, write only position and turn on Recalculate Normals under Shader. Each point then faces the way the triangles around it face. Points have no triangles, so the switch isn't offered there.
A Dynamic Mesh that lacks normal, tangent, uv or color gains it when the shader runs, also when a script sets the shader; scale, rotation and opacity are for splats only. A Grid or Strip starts the new field from its own surface: normals face up, tangents run along x. Any other new field, such as the normal of Points, starts at zero. Of these fields a Gaussian Splat has only position, scale, rotation, opacity and restPosition, so the Shader picker offers a splat only shaders that use those, and New Shader offers it the Ripple starter, which moves each point up and down from its restPosition.
Starter code:
cpp
// A wave rolling across a grid. element runs once for every point of the mesh, every step.
// context.previous is the point as the last step left it, with its position in metres; change a copy and return it.
Element element(ElementContext context, Parameters parameters) {
Element result = context.previous;
// The height follows the point's distance from the grid's centre, so the wave spreads in rings.
float distanceFromCentre = length(result.position.xz);
float phase = (distanceFromCentre / parameters.wavelength - context.time * parameters.speed) * 2.0 * M_PI_F;
result.position.y = sin(phase) * parameters.height;
// The wave's slope away from the centre, the derivative of the height, tilts the normal so a lit material
// shades the wave. The centre point has no direction away from itself, so it keeps facing up.
float slope = cos(phase) * 2.0 * M_PI_F / parameters.wavelength * parameters.height;
float2 outward = distanceFromCentre > 0.0 ? result.position.xz / distanceFromCentre : float2(0.0);
result.normal = normalize(float3(-slope * outward.x, 1.0, -slope * outward.y));
return result;
}Parameters: height (0.05, range 0 to 0.5), wavelength (0.5, range 0.05 to 2), speed (1, range 0 to 5), each a Decimal.
Every kind runs the function its reference shows, with the parameters the panel lists.