Programming with Spectra
Spectra's interface is one C99 header, spectra/spectra.h, and one static library. This
guide goes through it area by area, with code: every fragment here was compiled against the header, and the
listings with a file name are taken from programs that build and run. The header's comments remain the
reference for every field.
The library
A program makes four kinds of object, in this order, and releases them in the opposite one:
SpContextWhere the work runs: CPU threads or a GPU, memory, logging.SpSceneWhat is rendered: meshes, materials, textures, lights, camera, world.SpSessionA render in progress: add samples, look, add more. Optional.SpImageThe result: colour and the other buffers, as floats.Everything else is plain structs and integer indices. The interface keeps no pointer you give it after a call returns (borrowed texture pixels are the one exception), and needs no callback. That is why a whole scene can be written to bytes and rendered on another machine.
Conventions
- Defaults first. Every struct you fill has an
spXxxDefault()function. Call it before setting fields: fields added in later versions then get sensible values, and your code keeps compiling and meaning the same. New fields are only ever added at the end. - Indices. Functions that add something return its index, counted from 0, or −1 on failure. A material, texture or shader is referred to by that index.
- Colours are linear RGB in the scene's working space: Rec. 709 primaries unless the scene is set
to ACEScg (colour spaces). A colour picked on a screen is sRGB; convert it with
spColorFromSrgborspColorConvert. Textures are told which they are. - Space. Right-handed, +Y up by convention: the default camera looks down −Z with +Y up, the sky is built around +Y. Units are yours; they matter for lamps (light falls off with the square of the distance), volumes (density per unit) and subsurface (distance in units).
- Matrices are 4×4, column-major, as OpenGL has them: the translation is in elements 12, 13, 14.
- Texture coordinate (0, 0) is the top-left texel.
Building and linking
The library is written in a restricted C++ but needs no C++ runtime: no exceptions, no RTTI, no standard library. A C compiler links it, and a C program needs nothing else.
| Platform | Compiler | Link with |
|---|---|---|
| Windows x64 | Visual Studio 2022, static runtime (/MT) | lib/windows-x64-msvc/spectra.lib |
| Windows x64 | MinGW-w64 gcc | lib/windows-x64-gcc/libspectra.a |
| Linux | gcc, with -pthread | lib/linux/libspectra.a -lm -ldl |
| MorphOS | ppc-morphos-gcc-9 with -noixemul | lib/morphos-ppc/libspectra.a -lm |
cl /O2 /Iinclude examples\minimal.c lib\windows-x64-msvc\spectra.lib
gcc -O2 -Iinclude examples/minimal.c lib/windows-x64-gcc/libspectra.a -o minimal
gcc -O2 -pthread -Iinclude examples/minimal.c lib/linux/libspectra.a -lm -ldl -o minimal
ppc-morphos-gcc-9 -noixemul -O2 -Iinclude examples/minimal.c lib/morphos-ppc/libspectra.a -lm -o minimal
GPU Rendering on NVIDIA GPUs is in the Visual Studio library. It needs nothing at build time and no CUDA toolkit on the user's machine: the graphics driver is found when the program runs, and without one the library renders on the CPU.
MorphOS A MorphOS program starts with the stack its icon or the shell gives it, often 4 to 64 KB. Spectra needs about 28 KB while rendering and 6 KB more while loading a scene. With libnix, one line in the program asks for enough:
unsigned long __stack = 256 * 1024;
Every task of the host that calls Spectra (see parallel_for below) needs the same.
The first program
examples/minimal.c from the package, without its version check: a floor and a pyramid in sunlight, written to a PNG.
#include <stdio.h>
#include "spectra/spectra.h"
static SpVec3 vec(float x, float y, float z) { SpVec3 v; v.x = x; v.y = y; v.z = z; return v; }
/* One mesh of one colour. Returns the mesh's index. */
static int addMesh(SpScene *scene, const float *positions, int vertices, const int *indices, int triangles,
float r, float g, float b)
{
SpMaterial material;
SpMeshDesc mesh;
spMaterialDefault(&material);
material.base_color.r = r; material.base_color.g = g; material.base_color.b = b;
spMeshDescDefault(&mesh);
mesh.positions = positions;
mesh.vertex_count = vertices;
mesh.indices = indices;
mesh.triangle_count = triangles;
mesh.material = spSceneAddMaterial(scene, &material);
return spSceneAddMesh(scene, &mesh);
}
int main(void)
{
static const float floor_p[12] = { -8, 0, 8, 8, 0, 8, 8, 0, -8, -8, 0, -8 };
static const int floor_i[6] = { 0, 1, 2, 0, 2, 3 };
static const float pyramid_p[15] = { -1, 0, 1, 1, 0, 1, 1, 0, -1, -1, 0, -1, 0, 1.6f, 0 };
static const int pyramid_i[12] = { 0, 1, 4, 1, 2, 4, 2, 3, 4, 3, 0, 4 };
SpContext *ctx = spContextCreate(NULL); /* the CPU, all its threads */
SpScene *scene = spSceneCreate(ctx);
SpLight sun;
SpCamera camera;
SpRenderSettings settings;
SpImage *image = NULL;
addMesh(scene, floor_p, 4, floor_i, 2, 0.6f, 0.6f, 0.6f);
addMesh(scene, pyramid_p, 5, pyramid_i, 4, 0.8f, 0.3f, 0.1f);
spLightDefault(&sun);
sun.type = SP_LIGHT_SUN;
sun.direction = vec(1.0f, -0.6f, 0.3f); /* the way the light travels */
sun.intensity = 3.0f;
sun.radius = 1.0f; /* a little softness in the shadow */
spSceneAddLight(scene, &sun);
spCameraLookAt(&camera, vec(3.0f, 2.2f, 5.0f), vec(0.0f, 0.6f, 0.0f), vec(0, 1, 0), 40.0f);
spSceneSetCamera(scene, &camera);
if (spSceneCommit(scene) != SP_OK) return 1; /* builds the acceleration structure */
spRenderSettingsDefault(&settings);
settings.width = 320;
settings.height = 200;
settings.samples = 64;
if (spRender(scene, &settings, &image) == SP_OK)
spImageSavePNG(image, NULL, "minimal.png");
spImageRelease(image);
spSceneRelease(scene);
spContextRelease(ctx);
return 0;
}
The steps are those of every Spectra program: a context, a scene filled with materials and meshes, a light and
a camera, spSceneCommit, a render, an image saved, everything released.
The context
A context decides where rendering runs and how memory and messages are handled. spContextCreate(NULL)
gives the CPU with all its threads, malloc and silence.
static void onLog(int level, const char *message, void *user)
{
(void)user;
fprintf(stderr, "spectra %s: %s\n",
level == SP_LOG_ERROR ? "error" : level == SP_LOG_WARNING ? "warning" : "info", message);
}
SpContextDesc cd;
spContextDescDefault(&cd);
cd.device = SP_DEVICE_AUTO; /* an NVIDIA GPU if one can be used, else the CPU */
cd.log = onLog;
SpContext *ctx = spContextCreate(&cd);
printf("rendering on the %s\n", spContextDevice(ctx) == SP_DEVICE_CUDA ? "GPU" : "CPU");
Field of SpContextDesc | Default | Meaning |
|---|---|---|
device | SP_DEVICE_CPU | SP_DEVICE_CPU, SP_DEVICE_CUDA, SP_DEVICE_AUTO (SP_DEVICE_OPTIX falls back to CUDA). A device that cannot be used falls back to the CPU with a warning. |
device_index | 0 | Which GPU, counted among GPUs. |
threads | 0 | CPU threads; 0 or less = one per logical processor. |
allocator | malloc/free | All memory the library takes goes through it. |
log, log_user | NULL | Messages: what was chosen, what fell back, what went wrong. |
parallel_for, parallel_user | NULL | The host's own scheduler instead of the library's threads. |
Which devices there are
for (int i = 0; i < spDeviceCount(); i++) {
SpDeviceInfo info;
if (spDeviceGetInfo(i, &info) == SP_OK)
printf("%d: %s (%llu MB)\n", i, info.name, info.memory_bytes >> 20); /* entry 0 is the CPU */
}
printf("%s, features %x\n", spCpuArchitecture(), spCpuFeatures());
The host's own tasks
A program with a job system, or a MorphOS program, which has no threads inside the library, can hand its own
workers to Spectra. The function must call fn(i, arg) once for every i from 0 to
count − 1, on any tasks, and return when all calls have finished:
static void hostParallelFor(int count, SpTaskFn fn, void *arg, void *user)
{
Workers *w = (Workers *)user; /* your own task pool */
workersRun(w, count, fn, arg); /* returns when every fn(i, arg) is done */
}
cd.parallel_for = hostParallelFor;
cd.parallel_user = &my_workers;
The pictures do not depend on it: the same scene gives the same pixels on one thread, on all threads and on a host's scheduler.
Meshes
Everything Spectra renders is made of triangles. A mesh is added with an SpMeshDesc; its data is copied,
so your arrays may be freed afterwards.
float place[16] = { 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 2, 0, -3, 1 }; /* moved to (2, 0, -3) */
SpMeshDesc d;
spMeshDescDefault(&d);
d.positions = xyz; d.vertex_count = nv; /* 3 floats per vertex */
d.normals = nxyz; /* or NULL: flat shading */
d.uvs = uv; /* 2 floats per vertex, or NULL */
d.indices = idx; d.triangle_count = nt; /* or NULL: vertices in threes */
d.material = mat;
d.transform = place; /* or NULL */
int mesh = spSceneAddMesh(scene, &d);
Field of SpMeshDesc | Meaning |
|---|---|
positions, position_stride | xyz per vertex (required); stride in bytes, 0 = 12. Strides let you point into an interleaved vertex array. |
normals, normal_stride | xyz per vertex for smooth shading, or NULL. |
uvs, uv_stride | Texture coordinates, needed for textures, normal maps, anisotropy and displacement. |
colors, color_stride | Linear RGB per vertex; multiplies the base colour. |
indices, triangle_count | Three per triangle. |
material, triangle_materials | One material for all, and optionally one per triangle. |
transform | 4×4 column-major, object to world. |
instances_only | 1 = not shown where it stands; only where instances place it. |
subdivision, subdivision_smooth | Cut every triangle into four, this many times; with smooth the shape is rounded too (a cube becomes a pebble). |
dice_pixels, dice_levels, dice_eye, dice_pixel_size, dice_pixel_growth 1.23 | Cut finer where the camera sees it larger: after subdivision, an edge is cut in two as long as it would look longer than dice_pixels, at most dice_levels times (0 = 8). Only that edge, so the surface stays closed. Done once, when the mesh is added; for another view, add it anew. spMeshDescDiceFrom(&mesh, &camera, picture_height, pixels) fills them from a camera. Places given by instances are not looked at. |
displacement_texture, _scale, _midlevel | Move every vertex along its normal by a height texture. |
When the scene is complete (and after adding meshes or moving instances), call spSceneCommit: it builds
the trees that make finding triangles fast. Without it, rendering returns SP_ERR_NOT_COMMITTED.
Curves and points
curves · displacement
pointsLeft: 40 000 curves as fur, and a rock made from a ball by a height texture. Right: sixty thousand points, each a ball.
spSceneAddCurves turns runs of points into thin tubes (hair, fur, grass, wire); u runs along each
curve, so anisotropy stretches highlights along the strands. spSceneAddPoints puts a ball at every point,
storing one ball and placing it by instances, so a million points cost a million placements.
SpCurvesDesc c;
spCurvesDescDefault(&c); /* radius 0.01, 5 sides */
c.points = pts; c.point_count = total_points;
c.curve_points = per_curve; c.curve_count = curves; /* how many points each curve has */
c.radii = radii; /* 0 at a curve's last point makes a tip */
c.subdivisions = 2; /* smooth curves through the points */
c.material = hair;
int fur = spSceneAddCurves(scene, &c);
Instances and motion
An instance places a mesh again. The triangles are stored once; a copy costs its matrix, so a forest can be one tree placed thousands of times. Each instance may have its own material.
SpMeshDesc tree;
spMeshDescDefault(&tree);
/* ... positions, normals, indices, material ... */
tree.instances_only = 1; /* shown only where it is placed */
int t = spSceneAddMesh(scene, &tree);
for (int i = 0; i < 2500; i++) {
float m[16];
placeAt(m, x[i], 0.0f, z[i], size[i], turn[i]); /* your own helper: scale, turn, move */
spSceneAddInstance(scene, t, m, -1); /* -1: the mesh's own material */
}
spSceneCommit(scene);
spectra-cli --scene forestAn instance is moved with spSceneSetInstanceTransform and another spSceneCommit, which
rebuilds only the tree over the instances.
Motion blur
Things can move while the shutter is open. Each has a pose when it opens (its transform) and one when it closes:
| Function | What moves |
|---|---|
spSceneSetInstanceMotion(scene, i, at_close) | An instance, in a straight line between two placements (turns keep the object's size). |
spSceneSetInstanceMotionSteps(scene, i, count, m) | An instance through up to 64 placements at even moments: curves, stops, turns back. |
spSceneSetMeshMotion(scene, mesh, pos, nrm) | A mesh that changes shape: every vertex's place when the shutter closes. |
spSceneSetCameraMotion(scene, &cam) | The camera. |
spSceneSetLightMotion(scene, i, &lamp) | A lamp: position, direction, colour, intensity. |
SpRenderSettings.shutter_open and shutter_close choose which part of the movement (0 to 1) the
picture is exposed for; rolling_shutter exposes the rows one after another, as many video cameras do.
Materials
Spectra has one material, in the style of the Principled BSDF of Blender and of glTF: a matte base under a glossy layer, which metalness, transmission, a clear coat, sheen, subsurface scattering and a thin film change into almost anything.
SpMaterial m[12];
for (i = 0; i < 12; i++) spMaterialDefault(&m[i]); /* grey 0.8, roughness 0.5, specular 0.5 */
m[0].base_color = rgb(0.70f, 0.12f, 0.08f); /* matte */
m[0].specular = 0.0f; m[0].roughness = 1.0f;
m[1].base_color = rgb(0.05f, 0.25f, 0.65f); /* plastic */
m[1].roughness = 0.25f;
m[2].base_color = rgb(0.55f, 0.02f, 0.03f); /* car paint: clear coat */
m[2].roughness = 0.5f; m[2].clearcoat = 1.0f; m[2].clearcoat_roughness = 0.03f;
m[3].base_color = rgb(0.25f, 0.05f, 0.30f); /* velvet: sheen */
m[3].specular = 0.1f; m[3].roughness = 1.0f;
m[3].sheen = 1.0f; m[3].sheen_color = rgb(1.0f, 0.75f, 1.0f); m[3].sheen_roughness = 0.4f;
m[4].base_color = rgb(1.00f, 0.71f, 0.29f); /* gold */
m[4].metallic = 1.0f; m[4].roughness = 0.18f;
m[5].base_color = rgb(0.95f, 0.95f, 0.95f); /* chrome */
m[5].metallic = 1.0f; m[5].roughness = 0.0f;
m[6].base_color = rgb(0.80f, 0.80f, 0.82f); /* brushed steel: anisotropy (needs uvs) */
m[6].metallic = 1.0f; m[6].roughness = 0.35f; m[6].anisotropic = 0.9f;
m[7].base_color = rgb(0.02f, 0.02f, 0.02f); /* soap film on black */
m[7].roughness = 0.0f; m[7].specular = 1.0f;
m[7].thin_film_thickness = 380.0f; m[7].thin_film_ior = 1.33f;
m[8].base_color = rgb(1, 1, 1); /* clear glass */
m[8].transmission = 1.0f; m[8].roughness = 0.0f; m[8].ior = 1.5f;
m[9].base_color = rgb(0.85f, 0.95f, 1.0f); /* frosted glass */
m[9].transmission = 1.0f; m[9].roughness = 0.3f; m[9].ior = 1.5f;
m[10].base_color = rgb(1, 1, 1); /* a diamond: dispersion */
m[10].transmission = 1.0f; m[10].roughness = 0.0f; m[10].ior = 2.42f; m[10].dispersion = 0.36f;
m[11].base_color = rgb(0.95f, 0.85f, 0.65f); /* wax: subsurface scattering */
m[11].roughness = 0.4f; m[11].subsurface = 1.0f;
m[11].subsurface_radius = rgb(1.0f, 0.5f, 0.25f); m[11].subsurface_scale = 0.25f;
for (i = 0; i < 12; i++)
sphere(s, x[i], 0.9f, z[i], 0.9f, spSceneAddMaterial(s, &m[i]));
Roughness
roughness 0, 0.2, 0.4, 0.6, 0.8, 1 from left to right; copper (metallic = 1) behind,
plastic in front. A metal's reflection takes its colour; a plastic's stays white and lies over its colour.
1200×560 · 512 spp · path · denoised · filmicThe fields
| Field | Default | Meaning |
|---|---|---|
base_color | 0.8 | The colour of a matte surface, the tint of metal and of glass. |
metallic | 0 | 0 = dielectric (plastic, stone, wood), 1 = metal. |
roughness | 0.5 | 0 = mirror (stored as 0.03), 1 = fully rough. For glass: clear to frosted. |
specular | 0.5 | A dielectric's reflectivity: 0.5 = 4% (ior 1.5). 0 with roughness 1 = pure matte. |
emission, emission_strength | 0, 1 | Light the surface gives off. In the path tracer it lights the scene. |
alpha | 1 | Opacity; times the base colour texture's alpha. |
transmission, ior | 0, 1.5 | Glass, and its index of refraction. |
dispersion path | 0 | Glass that splits light into colours: 20 / Abbe number (window glass 0.3, diamond 0.36). |
clearcoat, clearcoat_roughness, coat_tint | 0, 0.03 | A clear glossy layer on top: car paint, varnish. |
sheen, sheen_roughness, sheen_color | 0, 0.5, 1 | The soft glow of cloth at grazing angles. |
anisotropic, anisotropic_rotation | 0, 0 | Highlights stretched along u: brushed metal, hair. |
subsurface, subsurface_radius, subsurface_scale | 0, (1, 0.2, 0.1), 0.05 | Light that travels under the surface: skin, wax, marble. Closed meshes. |
translucency | 0 | Matte light let through a thin sheet: leaves, paper, lampshades. |
thin_film_thickness, thin_film_ior | 0, 1.33 | A film of oil or soap: colours that change with the angle (nanometres). |
specular_tint | white | The colour of a dielectric's reflection seen straight on. |
hair, hair_azimuthal, hair_tilt 1.22 | 0, 0.3, 2 | 1 = a strand of hair or fur, for the tubes of spSceneAddCurves: light off its surface, through it, and off its far side (Chiang et al.'s model). base_color is the colour the hair ends up with, roughness the roughness along the strand, hair_azimuthal around it, hair_tilt the degrees the scales lean, ior the index (1.55 for hair). Both integrators' paths, CPU and GPU. |
toon_steps, toon_shadow, toon_rim, toon_rim_width 1.11 | 0, black, black, 0 | Toon (cel) shading: with toon_steps above 0 the light falls on the surface in that many flat tones (1 = lit or not), it glows with toon_shadow on its unlit side and with toon_rim where it turns away from the viewer (|N·V| at most the width), and it passes no light on. Cast shadows stay. |
base_color_texture, normal_texture, normal_strength, normal_space, metal_rough_texture, emission_texture | −1 | Texture maps; see textures. |
uv_scale_u/v, uv_rotation, uv_offset_u/v | 1, 0, 0 | Scale, turn and shift the texture coordinates of all its textures. |
shader | −1 | A graph of nodes; see node shaders. |
volume_* | The inside of a closed mesh; see volumes. |
For compositing and control
shadow_catcher = 1 | The camera sees only the shadows on this surface: lay a render over a photograph. |
holdout = 1 | The picture is empty where this surface is seen: a hole of its shape. |
hidden = SP_HIDE_CAMERA | Not in the picture, but still lights, shadows and reflects (a reflector panel). |
hidden = SP_HIDE_SHADOW | Throws no shadow. |
light_groups, shadow_groups | Bits matched with the lamps' groups and shadow_groups: which lamps light it, in whose light it throws shadows. |
A material can be replaced at any time with spSceneSetMaterial; no commit is needed, and a session in
progress starts over with it. spMaterialFromPhong converts an old fixed-function material (diffuse,
specular, shininess, reflectivity, opacity).
Textures
SpTextureDesc t;
spTextureDescDefault(&t); /* 3 channels, sRGB, copied */
t.width = w; t.height = h; t.channels = 4;
t.pixels = rgba; /* 8 bits per channel, rows top to bottom */
m.base_color = rgb(1, 1, 1); /* the texture multiplies it */
m.base_color_texture = spSceneAddTexture(scene, &t);
SpTextureDesc n;
spTextureDescDefault(&n);
n.width = w; n.height = h;
n.pixels = normal_map;
n.srgb = 0; /* data, not colour */
m.normal_texture = spSceneAddTexture(scene, &n);
Field of SpTextureDesc | Default | Meaning |
|---|---|---|
width, height, channels | –, –, 3 | 1 grey, 2 grey and alpha, 3 RGB, 4 RGBA. |
pixels | 8 bits per channel. | |
float_pixels | Instead: one linear float per channel, not limited to 0..1. For heights without steps and light brighter than white. | |
srgb | 1 | 1 for colours as pictures store them; 0 for data: normal maps, roughness, heights. |
copy | 1 | 0 = borrowed: the pixels must outlive the scene and not change. |
wrap_u, wrap_v | repeat | SP_WRAP_REPEAT, _CLAMP, _MIRROR: what lies past the edges. |
nearest | 0 | 1 = every texel a square of one colour (pixel art). |
uv_scale_u/v, uv_rotation, uv_offset_u/v 0.87 | 1, 0, 0 | The texture's own placement, after the material's (glTF's KHR_texture_transform). |
Smaller copies of every texture are made when it is added (a third more memory), so that a texture seen small or at a slant is averaged over what a pixel covers and does not shimmer.
UDIM sets 1.13
A model laid out over several UV tiles uses one texture made of a picture per tile: tile 1001 is u from 0 to 1, 1002 the next one to the right, 1011 the one above 1001 (1001 + U + 10 V). Each picture keeps its own size and its own smaller copies, and its edges are drawn out, so no tile bleeds into its neighbour; where the set has no tile it is black and transparent.
int pictures[3] = { spSceneAddTexture(scene, &skin_1001),
spSceneAddTexture(scene, &skin_1002),
spSceneAddTexture(scene, &skin_1011) };
int tiles[3] = { 1001, 1002, 1011 };
material.base_color_texture = spSceneAddTextureSet(scene, tiles, pictures, 3);
Patterns without pixels
A procedural texture is worked out where it is looked at: sharp at any distance, and no memory. It gets a texture index like any other, and can be a height for displacement too.
SpProceduralDesc checker;
spProceduralDescDefault(&checker);
checker.kind = SP_PROCEDURAL_CHECKER; /* or SP_PROCEDURAL_NOISE, with octaves */
checker.color_a = rgb(0.035f, 0.035f, 0.04f);
checker.color_b = rgb(0.09f, 0.09f, 0.10f);
checker.scale_u = checker.scale_v = 80.0f; /* fields per unit of u and v */
floor_mat.base_color = rgb(1, 1, 1);
floor_mat.base_color_texture = spSceneAddProcedural(s, &checker);
Node shaders
A shader works out values of a material at every point: from where the point is, its texture coordinates, its
vertex colours, pictures, patterns and arithmetic. It is an array of nodes; each node makes four numbers from up to
four inputs, and an input is either the result of an earlier node (link) or four numbers given
with the node (value). At the end the material takes its colour, roughness, glow and the rest from the
nodes named in SpShaderDesc; what a shader gives multiplies the material's own setting, as a texture does.
SpShaderNode n[6];
SpShaderDesc sh;
spShaderNodeDefault(&n[0], SP_NODE_POSITION); /* 0: the point, in the mesh's space */
spShaderNodeDefault(&n[1], SP_NODE_NOISE); /* 1: noise there */
n[1].link[0] = 0;
n[1].value[1][0] = 1.8f; /* scale */
n[1].value[2][0] = 6.0f; /* layers */
spShaderNodeDefault(&n[2], SP_NODE_MATH); /* 2: the noise made stronger */
n[2].param = SP_MATH_MULTIPLY;
n[2].link[0] = 1;
n[2].value[1][0] = 5.0f;
spShaderNodeDefault(&n[3], SP_NODE_WAVE); /* 3: bands across x, bent by it */
n[3].link[0] = 0;
n[3].value[1][0] = 1.4f;
n[3].link[2] = 2;
spShaderNodeDefault(&n[4], SP_NODE_MATH); /* 4: the bands made thin */
n[4].param = SP_MATH_POWER;
n[4].link[0] = 3;
n[4].value[1][0] = 8.0f;
spShaderNodeDefault(&n[5], SP_NODE_RAMP); /* 5: white, grey, the dark of the veins */
n[5].link[0] = 4;
n[5].value[1][0] = 0.92f; n[5].value[1][1] = 0.91f; n[5].value[1][2] = 0.88f;
n[5].value[2][0] = 0.60f; n[5].value[2][1] = 0.58f; n[5].value[2][2] = 0.55f;
n[5].value[3][0] = 0.06f; n[5].value[3][1] = 0.06f; n[5].value[3][2] = 0.07f;
n[5].param = 1; /* soft joins */
spShaderDescDefault(&sh);
sh.nodes = n;
sh.node_count = 6;
sh.base_color = 5; /* the colour comes from node 5 */
marble.base_color = rgb(1, 1, 1);
marble.roughness = 0.12f;
marble.shader = spSceneAddShader(s, &sh);
The nodes
| Kind | Nodes |
|---|---|
| What is known at the point | VALUE, TEXCOORD (uv, reflection or view direction), POSITION, NORMAL, VERTEX_COLOR, FACING, OBJECT_RANDOM, POINTINESS, WIREFRAME |
| Pictures and patterns | IMAGE (also laid on from three sides), CHECKER, NOISE, WHITE_NOISE, WAVE, VORONOI, GRADIENT, BRICK |
| Colour | RAMP, HSV, CONTRAST, BLEND (multiply, screen, overlay, ...), LUMINANCE, BLACKBODY, FRESNEL |
| Arithmetic | MATH (21 operations), VECTOR_MATH, MIX, MAP_RANGE, SEPARATE, COMBINE, MAPPING |
All names start with SP_NODE_; the header says what each input and param mean. A shader can
drive base_color, metallic, roughness, emission, alpha,
transmission, and the surface's direction: normal (as a normal map) or bump (as a
height, with bump_distance). At most SP_SHADER_MAX_NODES (64) nodes.
spSceneAddShader returns −1 for a graph it cannot run (a link to a later node, an unknown type, a picture
that is not in the scene).
Volumes path
A material with volume_density above 0 fills the inside of its closed mesh. With
transmission 0 the mesh's surface is not drawn at all; with transmission above 0 the surface is glass and
the volume is what it holds.
spectra-cli --scene volumesSpMaterial smoke;
spMaterialDefault(&smoke);
smoke.volume_density = 6.0f; /* light meets a particle every 1/6 units */
smoke.volume_color = rgb(0.7f, 0.7f, 0.7f); /* what a particle does to light: grey */
smoke.volume_anisotropy = 0.3f; /* scatters mostly onward */
SpVolumeGridDesc g; /* the density from a simulation */
spVolumeGridDescDefault(&g); /* 1.0; before it, memset to 0 */
g.nx = 64; g.ny = 128; g.nz = 64;
g.density = cells; /* nx * ny * nz floats, x fastest; copied */
g.bounds_min = vec(-1, 0, -1);
g.bounds_max = vec(1, 4, 1);
smoke.volume_grid = spSceneAddVolumeGrid(scene, &g);
SpMaterial fire = smoke;
fire.volume_color = rgb(0.2f, 0.2f, 0.2f);
fire.volume_temperature = 1600.0f; /* glows in the colour of heat */
fire.volume_emission_strength = 4.0f;
Volumes may overlap (up to four at a place) or lie inside one another; where they overlap, their particles mix,
unless volume_priority says that only the highest one is there (a glass of water standing in haze holds
water). The camera may be inside volumes.
Lights
SpLight lamp;
spLightDefault(&lamp); /* a white point lamp, intensity 1, inverse square */
lamp.type = SP_LIGHT_SPOT;
lamp.position = vec(0, 4, 2);
lamp.direction = vec(0, -1, -0.4f); /* the way the light travels */
lamp.intensity = 60.0f;
lamp.spot_cutoff = 25.0f; /* half-angle of the cone, degrees */
lamp.spot_blend = 0.3f; /* soft edge */
lamp.radius = 0.05f; /* soft shadows */
spSceneAddLight(scene, &lamp);
spLightDefault(&lamp);
lamp.type = SP_LIGHT_AREA; /* a softbox */
lamp.position = vec(-3, 3, 1);
lamp.direction = vec(1, -0.6f, -0.2f);
lamp.width = 2.0f; lamp.height = 1.2f;
lamp.intensity = 40.0f;
lamp.spread = 60.0f; /* a grid in front: shines into 60 degrees */
spSceneAddLight(scene, &lamp);
Field of SpLight | Meaning |
|---|---|
type | SP_LIGHT_POINT, _SPOT, _SUN, _AREA (a panel). |
position, direction | Where it is; where its light goes (spot, sun, panel). |
color, intensity, falloff | Its light; inverse square with distance, or none (old fixed-function scenes). |
radius | Point and spot: a size, for soft shadows. Sun: its angular radius in degrees. |
spot_cutoff, spot_exponent, spot_blend | The cone. |
tangent, width, height, shape, spread | Panels: orientation, size, rectangle or disk, and the angle they shine into. |
texture | A picture that colours the light: a spot throws it like a slide projector, a panel shows it, a point lamp wraps it around itself (a measured spread from an IES file). |
groups, shadow_groups | Bits: which surfaces it lights, whose shadows fall in its light. |
visible | 1 = the camera sees the lamp itself (a panel's face, a glowing ball). |
reach | Lights nothing farther than this: keeps the many lamps of a big scene to their own surroundings. |
cast_shadows | 0 = light passes through everything. |
Lamps and the camera are not geometry: they need no commit. spSceneSetLight replaces one. With very many
lamps, SpRenderSettings.light_sampling = SP_LIGHTS_ONE lets each point ask one lamp, chosen by what it is
likely to bring, instead of all of them. Any mesh whose material glows is a light too, in the path tracer.
With thousands of lamps or glowing triangles, SP_LIGHTS_TREE (1.16) finds that lamp in a tree, so the
time per point does not grow with their number, and picks the glowing triangle by the light it is likely to bring
to the point instead of by its share of all the light.
World, sky, environment
What lies beyond the scene lights it too. There are three kinds of world:
/* 1. a plain colour all round */
SpWorld w;
spWorldDefault(&w); /* background 0.05 */
w.background = rgb(0.3f, 0.35f, 0.4f);
spSceneSetWorld(scene, &w);
/* 2. a computed daylight sky, with the sun's disc in it */
SpSkyDesc sky;
spSkyDescDefault(&sky); /* physical model, sun 45 degrees up, haze 3 */
sky.sun_elevation = 25.0f;
sky.sun_azimuth = 140.0f; /* 0 = towards -Z, 90 = towards +X */
spSceneSetSky(scene, &sky);
/* 3. a photographed panorama (HDR, latitude-longitude, 2:1) */
SpEnvironmentDesc env;
spEnvironmentDescDefault(&env);
env.width = w2; env.height = h2;
env.pixels = rgb_floats; /* 3 linear floats per pixel, top row = straight up */
env.rotation = 90.0f;
spSceneSetEnvironment(scene, &env);
spSceneSetSky: sun 35° up, azimuth 140°.
spectra-cli --scene demo --sky 35,140SP_SKY_PHYSICALfollows sunlight through the atmosphere: blue days, red sunsets, dusk below the horizon.SP_SKY_PREETHAMis the older daytime formula.- With
sun_disc = 0the sky has no sun; add the lampspSkySunLightgives instead. SpWorldalso holds fog (fog_mode,fog_volumetricfor light shafts) and abackdrop: a plain colour the camera sees instead of the sky, while the sky still lights the scene.- 1.17 Light portals. A room lit by the sky through its windows is
noisy: most samples of the sky hit the walls.
spSceneAddPortalwith anSpPortal(its middle, the direction the light comes in, a tangent, width and height) marks a window, door or skylight; points inside then aim half their samples of the sky through the portals. Portals are not seen and cast no shadow; light coming in where there is none is still found, with more noise.spSceneSetPortalchanges one,spScenePortalCountcounts them.
The camera
SpCamera cam;
spCameraLookAt(&cam, vec(0, 1.6f, 6), vec(0, 1, 0), vec(0, 1, 0), 35.0f); /* focus on the target */
cam.aperture_radius = 0.05f; /* depth of field */
cam.aperture_blades = 6; /* six-sided out-of-focus lights */
spSceneSetCamera(scene, &cam);
spectra-cli --scene bokeh --blades 6Field of SpCamera | Meaning |
|---|---|
position, forward, up, right | Where it is and how it is turned; right zero = forward × up. |
fov_y | Vertical field of view, degrees. |
aperture_radius, focus_distance | Depth of field (perspective only). |
aperture_blades, aperture_rotation, aperture_ratio | The opening's shape: a polygon, turned, anamorphic. |
projection | SP_CAMERA_PERSPECTIVE, _ORTHOGRAPHIC (ortho_height), _PANORAMA, _FISHEYE, _FISHEYE_EQUISOLID (fisheye_fov), _MIRROR_BALL. |
clip_start, clip_end | Sees nothing nearer or farther. |
shift_x, shift_y | The view moved without turning: upright lines stay upright. |
stereo_eye, interocular, convergence | Pictures for two eyes; render once with each. |
spCameraFromViewEuler builds the camera of a fixed-function OpenGL program from its position and three
angles (Titler's convention).
Rendering
static int onProgress(int done, int total, void *user)
{
fprintf(stderr, "\r%3d%%", done * 100 / total);
return *(const volatile int *)user; /* non-zero cancels the render */
}
SpRenderSettings st;
spRenderSettingsDefault(&st); /* 640x360, path, 64 samples, 6 bounces */
st.width = 1920; st.height = 1080;
st.samples = 512;
st.adaptive_threshold = 0.01f; /* stop pixels that are clean */
st.denoise = 1;
st.progress = onProgress;
st.progress_user = &stop_requested;
SpImage *img = NULL;
SpStatus s = spRender(scene, &st, &img);
if (s != SP_OK) fprintf(stderr, "render: %s\n", spStatusString(s));
Field of SpRenderSettings | Default | Meaning |
|---|---|---|
width, height | 640×360 | Pixels. |
integrator | PATH | SP_INTEGRATOR_PATH or SP_INTEGRATOR_DIRECT (on the GPU too since 0.95). |
samples | 64 | Per pixel; with adaptive sampling, the most any pixel takes. |
max_bounces | 6 | Path: bounces. Direct: depth of mirrors and glass. |
max_diffuse/glossy/transmission_bounces | 0 | Limits for each kind within max_bounces; 0 = none of its own, negative = none at all. |
shadow_samples | 16 | Direct: rays per area light. |
clamp_indirect | 10 | Clamp on bounced light against fireflies; 0 = off. |
seed | 1 | Another seed, another (equally right) noise. |
adaptive_threshold, adaptive_min_samples | 0, 16 | Stop a pixel at that error relative to its brightness. |
caustics, caustic_photons, caustic_radius | 0 | Light followed from the lamps (1), also from the sky (2). |
denoise, denoise_strength | 0, 1 | Filter the finished picture. |
texture_filter | 1 | Average textures over what a pixel covers. |
pixel_filter, pixel_filter_width | BOX, 1.5 | Box, tent or gaussian. |
transparent_background | 0 | Empty background, coverage in SP_AOV_ALPHA. |
passes, ao_pass, id_passes, place_passes, cryptomatte 1.8, deep 1.10, outline 1.11, motion_vectors 1.14 | 0 | Extra buffers; see images. |
manifold 1.21 | 0 | 1 = the light of point and spot lamps through clear solid glass is found along the path that refracts (manifold next-event estimation) instead of passing straight and tinted: caustics at once, without the stored light of caustics, which turns this off. One path per lamp, the one nearest the straight line. Both integrators, CPU and GPU. |
guiding 1.20 | 0 | 1 = path guiding: over the first half of the samples the paths learn, in a grid over the scene, where the light comes from; half the bounces are then drawn from that. Less noise where bounces seldom find the light; the same picture on average, and the same bits for the same settings whatever the threads. The path tracer, CPU only for now; keep_pixels has no effect with it, and machines of a cluster learn apart, so such a picture is not one machine's bit for bit. |
light_paths[4][64] 1.18 | "" | Light path expressions, each giving a buffer SP_AOV_LIGHT_PATH0 + i: C, then bounces D G S (matte, glossy, sharp) or R T V (reflected, through, in a volume) or <RD>, and the source L O B (lamp, glowing thing, sky); . [ ] [^ ] * + ? ( ) | as in regular expressions. Path tracer, CPU only for now; one that cannot be read is refused. |
region_x0 ... region_y1 | 0 | Only that part of the picture. |
light_sampling | ALL | SP_LIGHTS_ONE: one lamp per point. SP_LIGHTS_TREE 1.16: one lamp per point found in a tree of the lamps (the suns are all asked), and glowing triangles picked by the light each is likely to bring to the point. |
sampler 1.15 | RANDOM | SP_SAMPLER_SOBOL: a pixel's samples spread out evenly in every pair of their random numbers (Sobol points, Owen-scrambled). The same picture on average with less noise; a different picture from RANDOM's, and like it the same bit for bit on every machine, in pieces and in sessions. |
shutter_open, shutter_close, rolling_shutter | 0, 0, 0 | The exposure of moving things. |
keep_pixels 1.2 | 0 | 1 = a session keeps the pixels a change of materials or placements did not reach (see Sessions). |
tile_size | 32 | Pixels per side of a tile of work. |
Determinism. On one device, the same scene, settings and seed give the same pixels, bit for bit, on any number of threads and in any number of session steps, and since 0.96 on the CPU and on a GPU alike (until 0.95 those two agreed up to noise). The MorphOS build is compiled the same way; that its pictures match too is still to be checked on a MorphOS machine.
Sessions
A session is a render in progress. A program with a window renders a few samples at a time and shows the picture as it clears up; when the user moves the camera, it starts over without rebuilding anything.
SpSession *ses = NULL;
if (spSessionCreate(scene, &st, &ses) == SP_OK) {
while (spSessionSamplesDone(ses) < spSessionSamplesTotal(ses)) {
SpImage *now = NULL;
spSessionRender(ses, 8); /* 8 more samples per pixel; blocks until done */
spSessionResolve(ses, &now); /* the picture so far, not denoised */
show(now);
spImageRelease(now);
if (user_moved_camera) spSessionSetCamera(ses, &new_camera); /* starts over */
}
spSessionRelease(ses);
}
- Rendering N samples in one call or in many gives the same pixels.
- The scene may be changed between calls: a material, a lamp, the sky, an instance's place. The session notices
at its next
spSessionRenderand starts over. Meshes and instances needspSceneCommitfirst. - With
keep_pixelsset 1.2, when only materials were replaced or instances moved, the session starts over only the pixels whose paths came near the change, and keeps the samples of the rest: an object moved in a corner leaves much of a converged picture as it was. The picture is still exactly that of a session started afresh. Lamps, the world, glowing materials, new meshes and caustics start every pixel again. Every ray then notes where it went, which costs a few percent, and with many bounces the paths pass nearly everywhere, so it is off by default. spSessionDevicesays where it renders; both integrators run on the GPU (the direct one since 0.95).- After
SP_ERR_CANCELLEDthe picture so far can be resolved;spSessionRestartbefore rendering again. - The scene must not be released while a session uses it.
spSessionSetRegion1.1 moves the session to another part of the picture and starts over, keeping what it built (the store of light for caustics, the GPU's copy of the scene). The part's pixels are those of the whole picture, bit for bit: this is howtools/common/sp_cluster.hshares one picture between machines, a band of rows each.spSessionSave1.19 writes what a session has rendered so far into a block of bytes (released withspDataRelease) to keep in a file;spSessionResumegives it to a new session made for the same scene, camera and settings, which then goes on where the saved one stopped. The picture is the one of a render without the break, bit for bit, on the CPU or the GPU, here or on another machine. A block of another scene or other settings is refused.
Colour spaces 1.9
A scene renders in its working space: linear Rec. 709 (SP_COLORSPACE_LINEAR, the default, the
primaries of sRGB) or ACEScg (SP_COLORSPACE_ACESCG, linear with the wider AP1 primaries, as film and
visual-effects pipelines use). Every colour you give - materials, lamps, the world, vertex colours - is read in it.
Pictures say their own space and are converted where they are looked up, so one texture serves scenes in either
space.
spSceneSetWorkingSpace(scene, SP_COLORSPACE_ACESCG); /* first: before the sky */
SpTextureDesc t;
spTextureDescDefault(&t);
t.color_space = SP_COLORSPACE_SRGB; /* a photograph, a painted colour map */
/* ... SP_COLORSPACE_RAW for normals, roughness, heights: never converted;
SP_COLORSPACE_LINEAR, _ACESCG, _ACES2065_1 for linear pictures */
float rec709[3] = { 0.8f, 0.35f, 0.1f }, cg[3];
spColorConvert(SP_COLORSPACE_LINEAR, SP_COLORSPACE_ACESCG, rec709, cg);
material.base_color.r = cg[0]; /* ... */
- The light the library makes itself is converted too: the colour of heat (blackbody), the colours glass splits
light into, the computed sky and its sun's disc.
spSkySunLightgives its lamp in Rec. 709: convert its colour for an ACEScg scene. - An environment map says its space in
SpEnvironmentDesc.color_space(linear Rec. 709 by default). - The picture comes out in the working space;
spImageColorSpacesays which. The display conversion (spImageToRGB8, PNG) turns it into Rec. 709 before the exposure and the tone curve, so an ACEScg render looks like the same scene rendered in Rec. 709. OpenEXR files of ACEScg pictures name their primaries (chromaticities). - Between spaces with different white points (D65 and the ACES white) colours are adapted with the Bradford transform, as OpenColorIO's ACES configuration does.
- A texture left at
SP_COLORSPACE_DEFAULTbehaves as before 1.9: decoded by itssrgbflag, never converted.
Images
An image holds float buffers, top row first. spImagePixels(img, aov) gives one, or NULL if the render did not
make it.
| Buffer | Floats | What it holds |
|---|---|---|
SP_AOV_COLOR | 3 | The picture: linear light. |
SP_AOV_ALBEDO, SP_AOV_NORMAL, SP_AOV_DEPTH | 3, 3, 1 | The first surface's colour, direction, and the ray's length (−1 = nothing). The denoiser's guides. |
SP_AOV_ALPHA | 1 | How much of the pixel the scene covers. |
SP_AOV_SAMPLES | 1 | Samples each pixel took. |
SP_AOV_EMISSION, _DIRECT, _INDIRECT | 3 each | With passes: the light in three parts that add up to the colour. |
SP_AOV_AO | 1 | With ao_pass: how open the first surface is. |
SP_AOV_MESH_ID, _INSTANCE_ID, _MATERIAL_ID | 1 each | With id_passes: what the pixel shows, by number. |
SP_AOV_POSITION, SP_AOV_UV | 3 each | With place_passes: where the surface is, and its texture coordinates. |
SP_AOV_CRYPTO_MESH, _INSTANCE, _MATERIAL 1.8 | 16 each | With cryptomatte: up to SP_CRYPTO_RANKS (8) pairs of number and coverage, the largest coverage first; unused pairs are (-1, 0). The coverage is the share of the pixel's samples that met that thing first. Written into OpenEXR as Cryptomatte layers with their manifest; the ids are made from the names given with spSceneSetName 1.12 (or mesh3, instance7, material2 without one). |
SP_AOV_OUTLINE 1.11 | 1 | With outline: how much of the pixel a line covers. Lines go where the depth jumps (outline_depth), the surface turns (outline_angle) or one object or material meets another (outline_ids), on the nearer side, outline_width pixels wide; with outline 2 they are drawn in outline_color after denoising. spImageOutline does it for a picture put together or denoised afterwards. |
SP_AOV_LIGHT_PATH0 ... 3 1.18 | 3 | With light_paths[i]: the light along the paths that expression names. Expressions that part the paths between them (C[LOB], C D.*, C G.*, C S.*) add up to the colour. |
SP_AOV_MOTION 1.14 | 2 | With motion_vectors: how far, in pixels, the point the pixel shows moves on the picture from the opening of the shutter to its closing (x right, y down), by its own motion and the camera's; averaged over the samples that met the scene. Perspective and orthographic cameras. |
SP_AOV_DEEP 1.10 | 40 | With deep: up to SP_DEEP_SAMPLES (8) deep samples per pixel, front to back, each Z, R, G, B (premultiplied) and A; unused ones have Z = -1. A deep sample is one thing at one depth; put together with "over" from the front they give the pixel exactly (the background is no sample). spImageSaveDeepEXR writes them as an OpenEXR deep file. |
SpDisplay look;
spDisplayDefault(&look); /* no tone curve, sRGB */
look.tonemap = SP_TONEMAP_ACES; /* or _FILMIC, _REINHARD */
look.exposure = 0.5f; /* stops */
look.temperature = 4500.0f; /* white balance */
spImageDenoise(img, 1.0f); /* guided by albedo, normal and depth */
spImageSavePNG(img, &look, "out.png"); /* the look applied, 8 bits */
spImageSaveEXR(img, "out.exr"); /* every buffer, linear floats */
spImageSaveHDR(img, "out.hdr"); /* the colour, Radiance RGBE */
unsigned char *rgb = malloc((size_t)spImageWidth(img) * spImageHeight(img) * 3);
spImageToRGB8(img, &look, rgb); /* for your own window */
void *file; size_t bytes; /* the same files, in memory (0.92) */
if (spImageEncode(img, SP_FILE_PNG, &look, &file, &bytes) == SP_OK) {
send_somewhere(file, bytes);
spDataRelease(ctx, file);
}
spImageCreate makes an image from pixels you have (a render from elsewhere) so that the denoiser, the
look and the writers can be used on it; spImageSetAlpha gives it a coverage, and
spImageSetPixels 1.6 any other buffer (the light in parts, AO, ids,
position, uv), so that a picture put together from parts has every buffer the render had. spImageEncode
0.92 gives the bytes the writers would put in a file (SP_FILE_PNG,
SP_FILE_EXR, SP_FILE_HDR), for a network, a database or a picture box.
Baking
Instead of what the camera sees, every texel of the picture shows the point of a mesh that its texture coordinates belong to: its light, its colour, its normal. The result can go back into the scene as a texture, or into a game.
SpBakeDesc b;
spBakeDescDefault(&b); /* 512x512, margin 4 */
b.mesh = room;
b.width = b.height = 2048;
SpImage *light = NULL;
if (spBake(scene, &st, &b, &light) == SP_OK) /* st: samples, bounces, denoise as usual */
spImageSaveEXR(light, "room-light.exr");
int tiles[16];
int n = spMeshUdimTiles(scene, statue, tiles, 16); /* a texture spread over UDIM tiles */
for (int i = 0; i < n && i < 16; i++) { b.mesh = statue; b.tile = tiles[i]; /* ... spBake ... */ }
SP_AOV_ALPHA is 1 where the mesh covers the texel; colours are carried margin texels past the
edge. spBakeMany bakes several meshes whose coordinates share one atlas into one picture. Baking runs on the
GPU when the context does (path integrator).
Ray queries
A committed scene answers questions about rays: for picking with the mouse, placing things on the ground, line of sight.
SpHit hit;
if (spSceneIntersect(scene, eye, direction, 0.0f, &hit)) /* 0 = no limit on the distance */
printf("triangle %d, material %d, instance %d, at %.3f\n", hit.triangle, hit.material, hit.instance, hit.t);
if (spSceneOccluded(scene, a, b))
printf("something stands between a and b\n");
SpHit gives the distance, the barycentric coordinates, the triangle (in the order it was added), its
material, the instance (−1 for a mesh shown where it stands), the point and the geometric normal. Queries see the
scene as the shutter opens. spSceneIntersectReference gives the same answer by testing every triangle,
for checking.
Scenes as bytes
spSceneSaveFile(scene, "scene.spectra");
SpScene *again = NULL;
if (spSceneLoadFile(ctx, "scene.spectra", &again) == SP_OK) {
/* committed if the saved scene was; renders the same picture */
}
void *data = NULL; size_t size = 0; /* the same in memory */
if (spSceneSave(scene, &data, &size) == SP_OK) {
sendElsewhere(data, size); /* your own */
spDataRelease(ctx, data);
}
The block holds everything put into the scene, not what spSceneCommit builds. It is the same on every
machine, whatever its byte order; blocks from older versions still load. This is what spectra-server
receives: a program that renders elsewhere sends its scene saved like this, then render settings, and gets the picture
back (the messages are described in the source distribution's tools/common/sp_remote.h).
The same scene always gives the same bytes, and a change moves only its own bytes. So when the scene changes,
the client in sp_remote.h sends only the difference to the last block 0.94:
a moved object in a 61 MB scene goes as a 38-byte patch. With a key the conversation is encrypted
0.93.
Several machines 1.7
A program can have one picture, or the frames of an animation, rendered by several machines: spectra-servers
elsewhere, started with the same key, and the program itself. This is a library of its own,
spectra-cluster, with its header spectra/spectra_cluster.h: it holds the network and the
threads, which the renderer does not have. Link it before the renderer (see the package's README for each
platform).
#include "spectra/spectra_cluster.h"
unsigned char key[256];
SpClusterDesc d;
SpCluster *cluster = NULL;
spClusterDescDefault(&d); /* SP_DEVICE_AUTO: a GPU where there is one */
d.key_size = spClusterKeyFile("render.key", key); /* the servers' --key-file */
d.key = key;
spClusterCreate(ctx, &d, &cluster);
spClusterAddServer(cluster, "192.168.1.20"); /* port 7878 */
spClusterAddServer(cluster, "192.168.1.21:7900");
spClusterAddLocal(cluster); /* this program renders too */
for (int i = 0; i < spClusterMachineCount(cluster); i++)
if (spClusterMachineState(cluster, i) != SP_MACHINE_READY)
printf("%s cannot be used\n", spClusterMachineName(cluster, i));
SpImage *image = NULL;
if (spClusterRender(cluster, scene, &settings, &image) == SP_OK) {
/* the picture one machine makes, bit for bit, with every buffer */
}
spClusterRelease(cluster);
A picture is cut into bands of rows that the machines take from a queue, so a faster machine takes more; an animation goes a whole frame to a machine. Your function gives each frame's scene when a machine takes it, and only what changed since that machine's last frame is sent:
static const SpScene *frameScene(int frame, void *user)
{
MyAnimation *a = user;
spSceneSetCamera(a->scene, &a->camera[frame]); /* or move objects, change materials */
return a->scene; /* saved before the next call */
}
static void frameDone(int frame, SpImage *image, void *user)
{
char name[64];
sprintf(name, "frame-%04d.exr", frame + 1);
spImageSaveEXR(image, name);
spImageRelease(image); /* yours */
}
spClusterRenderFrames(cluster, 250, frameScene, frameDone, &animation, &settings);
- Every picture, and every frame, is the one a single machine makes of it, bit for bit, whichever machine rendered which part, CPU or GPU. It has every buffer the render made (the light in parts, AO, ids, position, uv), except the count of samples a pixel took.
spClusterMachineStatesays what a machine is: ready, unreachable, refusing the key, dropped out during a render, or stopped.spClusterMachineName,spClusterMachineVersion,spClusterMachineDeviceandspClusterMachineWork(bands or frames in the last render) tell the rest. A machine keeps its number;spClusterRemovetakes it away,spClusterConnectconnects it again.- A machine that fails during a render drops out and the others render its part. When the queue is empty, a free machine also renders a part another is still on, and the first answer is kept; a machine still busy when all is done is stopped, not waited for.
- The settings' progress callback is called after each band or frame; returning non-zero, or
spClusterCancelfrom another thread, hands out nothing more, and the render returnsSP_ERR_CANCELLEDonce the parts being rendered are done. - One call at a time on a cluster (except
spClusterCancel); the callbacks are never called two at once. The library allocates withmalloc, not through the context. On MorphOS there is no network yet: onlyspClusterAddLocal.
examples/cluster.c renders a picture and an animation on the machines named on its command line (or
on two machines in itself) and checks both against one machine.
Errors, threads, memory
Status codes
SP_OK | Done. |
SP_ERR_INVALID_ARG | Something given does not exist or makes no sense; data that is not a scene. |
SP_ERR_OUT_OF_MEMORY | The allocator said no. Nothing half-made is left behind. |
SP_ERR_NOT_COMMITTED | Meshes or instances changed without spSceneCommit. |
SP_ERR_CANCELLED | The progress callback asked to stop. |
SP_ERR_IO | A file could not be read or written. |
SP_ERR_DEVICE | The GPU refused or failed; the log says why. |
spStatusString gives a short English text; with a log function in the context, the details are there.
Threads
- Building a scene is single-threaded: one thread at a time adds to a scene.
- After
spSceneCommit, a scene may be rendered from several threads at once. spRenderandspSessionRenderblock until done and use the context's threads (or itsparallel_for) inside.- The progress callback is called between tiles, never twice at once, possibly from a worker thread.
Memory
- All memory goes through the context's allocator, and the library keeps no global state.
- Everything given is copied, except texture pixels with
copy = 0, which are borrowed until the scene is released. - Release in the opposite order of making: images and sessions, then scenes, then the context.
Versions
spVersionString() gives the library's version as text. Since 1.0 the header also says its own
version in numbers that can be compared, and spVersion() gives the library's, which differ when a program
runs with another shared library than the one it was built with 1.0:
#if SPECTRA_VERSION >= SPECTRA_MAKE_VERSION(1, 0, 0)
/* ... something from 1.0 ... */
#endif
if (spVersion() < SPECTRA_VERSION)
printf("built for Spectra %d.%d, running with %s\n",
SPECTRA_VERSION_MAJOR, SPECTRA_VERSION_MINOR, spVersionString());
Structs only ever grow at their end, and every one has a default function: a program that calls them keeps working, unchanged, with later versions of the library.
Function index
Every function of spectra.h, by area. The header's comments say the rest.
| Area | Functions |
|---|---|
| Library | spVersionString spVersion spStatusString spCpuFeatures spCpuArchitecture spDeviceCount spDeviceGetInfo |
| Context | spContextDescDefault spContextCreate spContextRelease spContextDevice |
| Scene | spSceneCreate spSceneRelease spSceneCommit spSceneTriangleCount spSceneInstanceCount spSceneGetBounds |
| Geometry | spMeshDescDefault spSceneAddMesh spCurvesDescDefault spSceneAddCurves spPointsDescDefault spSceneAddPoints |
| Instances, motion | spSceneAddInstance spSceneSetInstanceTransform spSceneSetInstanceMotion spSceneSetInstanceMotionSteps spSceneSetMeshMotion spSceneSetCameraMotion spSceneSetLightMotion |
| Names | spSceneSetName spSceneName spImageSetName spImageName |
| Materials | spSceneMaterialCount spSceneGetMaterial spMaterialDefault spMaterialFromPhong spSceneAddMaterial spSceneSetMaterial |
| Textures | spTextureDescDefault spSceneAddTexture spSceneAddTextureSet spProceduralDescDefault spSceneAddProcedural |
| Shaders, volumes | spShaderNodeDefault spShaderDescDefault spSceneAddShader spVolumeGridDescDefault spSceneAddVolumeGrid spSceneVolumeGridFill |
| Lights | spLightDefault spSceneAddLight spSceneSetLight spSkySunLight |
| World | spWorldDefault spSceneSetWorld spEnvironmentDescDefault spSceneSetEnvironment spSkyDescDefault spSceneSetSky spPortalDefault spSceneAddPortal spSceneSetPortal spScenePortalCount |
| Camera | spCameraDefault spCameraLookAt spCameraFromViewEuler spSceneSetCamera spSceneGetCamera |
| Rendering | spRenderSettingsDefault spRender |
| Sessions | spSessionCreate spSessionRender spSessionResolve spSessionSamplesDone spSessionSamplesTotal spSessionDevice spSessionRestart spSessionSetCamera spSessionSetRegion spSessionSave spSessionResume spSessionRelease |
| Images | spImageCreate spImageSetAlpha spImageSetPixels spImageWidth spImageHeight spImagePixels spImageDenoise spDisplayDefault spImageToRGB8 spImageToRGBA8 spImageSavePNG spImageSaveEXR spImageSaveHDR spImageSaveDeepEXR spImageOutline spImageEncode spImageRelease |
| Baking | spBakeDescDefault spBake spBakeMany spMeshUdimTiles |
| Ray queries | spSceneIntersect spSceneOccluded spSceneIntersectReference |
| Scenes as bytes | spSceneSave spSceneLoad spSceneSaveFile spSceneLoadFile spDataRelease |
| Several machines (spectra_cluster.h) | spClusterDescDefault spClusterCreate spClusterRelease spClusterAddServer spClusterAddLocal spClusterConnect spClusterRemove spClusterMachineCount spClusterMachineState spClusterMachineName spClusterMachineVersion spClusterMachineDevice spClusterMachineWork spClusterRender spClusterRenderFrames spClusterCancel spClusterKeyFile |
| Colour | spSrgbToLinear spLinearToSrgb spColorFromSrgb spColorConvert spSceneSetWorkingSpace spSceneWorkingSpace spImageColorSpace spImageSetColorSpace |