Shading
The @ripl/3d package includes flat shading utilities that compute face brightness based on surface normals and a light direction vector. Built-in 3D shapes apply shading automatically during rendering — you just set context.lightDirection and each face is colored based on its angle to the light. For custom geometry, three helper functions let you compute normals, brightness, and shaded colors directly.
NOTE
For the full API, see the 3D API Reference.
Demo
Two cubes rendered with different light directions to illustrate how shading changes.
Functions
computeFaceNormal
Computes the surface normal of a face from its vertices using the cross product of two edges.
import {
computeFaceNormal,
} from '@ripl/3d';
const normal = computeFaceNormal([
[0, 0, 0],
[1, 0, 0],
[0, 1, 0],
]);
// [0, 0, 1]computeFaceBrightness
Returns a brightness value between 0 and 1 based on the angle between the face normal and the light direction.
import {
computeFaceBrightness,
} from '@ripl/3d';
const brightness = computeFaceBrightness(
[0, 0, -1], // face normal
[0, 0, 1] // light direction
);
// 1.0 (face directly facing the light)shadeFaceColor
Scales an RGB color string by a brightness factor.
import {
shadeFaceColor,
} from '@ripl/3d';
const color = shadeFaceColor('rgb(200, 100, 50)', 0.5);
// 'rgb(100, 50, 25)'Automatic Shading
Shape3D elements automatically apply flat shading during rendering. The light direction is read from context.lightDirection (defaults to [0, 0, -1]).
context.lightDirection = [1, -1, -1]; // top-right light