Documentation / @ripl/3d
@ripl/3d ​
3D rendering for Ripl: shapes, lights, materials and textures, drawn onto a 2D canvas with a depth-sorted painter's algorithm, or on the GPU through
@ripl/webgpu.
Features ​
- Nine shapes — cube, sphere, cylinder, cone, plane, torus, mesh (raw faces), parametric (a tessellated surface function) and bezier surface (bicubic patches).
- Five light types —
createAmbientLight,createHemisphereLight,createDirectionalLight,createPointLightandcreateSpotLight, each with colour, intensity and anenabledflag; directed lights are fixed in world space or locked to the camera. Point and spot lights add distance falloff (distance,decay) and spot lights a cone (angle,penumbra). - Materials —
color,opacity,emissive,emissiveIntensity,specular,shininess,side('front' | 'back' | 'double'),wireframe,flatShading,vertexColorsandmap. Every property is optional; an element with only afillshades as it always did. - Textures —
createTexturefrom anImageBitmap,<img>,<canvas>,<video>,OffscreenCanvasorImageData, orloadTexturefrom a URL. Per-axis wrapping ('clamp' | 'repeat' | 'mirror'), separate magnification and minification filters ('nearest' | 'linear'), and a UV transform ofrepeat,offsetandflipY. Every built-in shape emits the coordinates, and both backends sample them the same way. - Perspective and orthographic camera —
createCameradrives the context's view and projection, batches changes through a microtask, and handles orbit, pan and pinch/wheel zoom with per-interaction sensitivity. - Fog —
'linear'or'exponential'haze blending distant geometry towards a colour, computed identically on both backends. - Triangle raycasting —
context.raycast(x, y)builds a world-space ray andcontext.raycastAll(scene, x, y)returns every shape it meets, nearest first, with the hit point, face, interpolated normal and UV. Group3D— a group whose transform composes into the model matrix of every shape beneath it, so a subtree orbits, tilts and scales as a unit.- Animation and events — shapes are Ripl elements, so
renderer.transition, pointer events and scene querying all apply.interpolateVector3tweens 3D positions — declare it in a custom element'sinterpolatorsto animate a vector-valued property.
Installation ​
bash
# npm
npm install @ripl/3d @ripl/web
# yarn
yarn add @ripl/3d @ripl/web
# pnpm
pnpm add @ripl/3d @ripl/webThe scene and renderer come from @ripl/web; this package supplies the 3D context, camera, lights and shapes. For GPU rasterization, add @ripl/webgpu and import createContext from there instead.
Quick start ​
typescript
import {
createCamera,
createContext,
createDirectionalLight,
createTorus,
} from '@ripl/3d';
import {
createRenderer,
createScene,
} from '@ripl/web';
const context = createContext('.mount-element');
const scene = createScene(context);
createCamera(context, {
position: [0, 2, 5],
target: [0, 0, 0],
interactions: true,
});
context.lights.add(createDirectionalLight({
direction: [-1, -1, -0.5],
intensity: 0.8,
}));
scene.add(createTorus({
radius: 1.2,
tube: 0.4,
material: {
color: '#4488ff',
specular: '#ffffff',
shininess: 48,
},
}));
createRenderer(scene, {
autoStop: false,
});Key API ​
| Export | What it does |
|---|---|
createContext | Canvas-backed Context3D that projects and depth-sorts faces |
createCamera | Perspective or orthographic camera with orbit, pan and zoom |
createAmbientLight … createSpotLight | The five light constructors, added via context.lights |
createMaterial | How a surface responds to light |
createTexture / loadTexture | Images mapped across a surface |
createCube … createBezierSurface | The nine built-in shapes |
createGroup3D | A group carrying a 3D transform for its subtree |
Context3D.raycastAll | Every shape under a point, nearest first |
computeFaceNormal / shadeFaceColor | Shading helpers for custom geometry |
Related packages ​
@ripl/web— the browser entry point supplying the scene, renderer and animation@ripl/webgpu— GPU backend for the sameShape3Delements@ripl/core— the element, scene and animation model these shapes build on
Documentation ​
Guides, live demos and the full API reference are at ripl.run/docs/3d.
License ​
Classes ​
| Class | Description |
|---|---|
| AmbientLight | A light that reaches every surface equally, regardless of orientation. |
| BezierSurface | A surface tessellated from one or more bicubic Bézier patches. |
| Camera | An interactive camera controlling the 3D context's view and projection, with mouse/touch orbit, pan, and zoom. |
| CanvasContext3D | Canvas 2D–backed 3D rendering context with face buffer and painter's algorithm sorting. |
| Cone | A 3D cone shape with configurable radius, height, and segment resolution. |
| Context3D | Base 3D rendering context providing view/projection matrices, camera, lighting, and projection. Subclassed by CanvasContext3D and WebGPUContext3D. |
| Cube | A 3D cube shape with uniform edge size. |
| Cylinder | A 3D cylinder shape with independent top and bottom radii for truncated cones. |
| DirectionalLight | A light infinitely far away, casting parallel rays in a single direction. |
| Group3D | A group whose transform composes into the model matrix of every Shape3D beneath it. |
| HemisphereLight | A two-colour light that fades from Light.color overhead to groundColor underfoot. |
| Light | Base class for every light, carrying the colour, intensity and enabled state they share. |
| LightList | An ordered, mutable collection of the lights illuminating a scene. |
| Mesh | A mesh built from an explicit list of faces. |
| Parametric | A surface tessellated from a function of two parameters. |
| Plane | A flat rectangular 3D plane oriented along the XY plane. |
| PointLight | A light radiating equally in every direction from a point. |
| PositionalLight | Base class for lights that radiate from a position and fall off with distance. |
| Shape3D | Base class for 3D shapes, handling model transforms, face projection, shading, and hit testing. |
| Sphere | A 3D sphere shape tessellated with configurable segments and rings. |
| SpotLight | A light radiating from a point, confined to a cone with an optionally soft edge. |
| Texture | An image mapped onto a surface, usable by either backend. |
| Torus | A 3D torus (donut) shape with configurable major radius, tube radius, and tessellation. |
Interfaces ​
| Interface | Description |
|---|---|
| BezierSurfaceOptions | Options for constructing a BezierSurface. |
| BezierSurfaceState | State for a surface tessellated from Bézier patches. |
| CameraInteractionConfig | Fine-grained configuration for a single camera interaction. |
| CameraInteractions | Configures which camera interactions (zoom, pivot, pan) are enabled. |
| CameraOptions | Options for constructing a camera, including position, projection type, and interaction config. |
| ConeState | State interface for a cone, defining radius, height, and segment count. |
| Context3DMeta | Typed metadata for 3D contexts. |
| Context3DOptions | Options for the 3D rendering context, extending the base context options with camera parameters. |
| CubeState | State interface for a cube, defining uniform edge size. |
| CylinderState | State interface for a cylinder, defining top/bottom radii, height, and segment count. |
| DirectedLightOptions | Options for a light that has an orientation. |
| Face3D | A single face of a 3D mesh, defined by its vertices and an optional precomputed normal. |
| Fog | Atmospheric haze blending distant geometry towards a colour. |
| Group3DOptions | Options for constructing a Group3D. |
| HemisphereLightOptions | Options for HemisphereLight. |
| Intersection3D | Where a ray met a shape's geometry. |
| LightOptions | Options shared by every light. |
| Material | How a surface responds to light. |
| MeshOptions | Options for constructing a Mesh. |
| MeshState | State for a mesh built from an explicit face list. |
| MeshSubmission | A mesh submission queued for a single frame. |
| ModelUniformInput | Everything the per-model uniform needs, independent of any particular backend. |
| ParametricOptions | Options for constructing a Parametric. |
| ParametricState | State for a surface tessellated from a parametric function. |
| PlaneState | State interface for a plane, defining width and height. |
| PositionalLightOptions | Options for a light that radiates from a point. |
| ProjectedFace3D | A projected face ready for 2D rendering with screen-space points, fill/stroke styles, and depth. |
| ProjectedFaceState3D | The 2D drawing state resolved for an element at the moment its faces were projected. |
| Ray | A half-line in world space, used for picking and intersection queries. |
| Raycast3DOptions | Options for a raycast against 3D geometry. |
| RayTriangleHit | Where a Ray met a triangle, in both distance and barycentric terms. |
| ResolvedFog | Fog reduced to the numeric form the scene uniform carries. |
| ResolvedLight | A light reduced to the flat numeric form both the CPU painter and the WGSL shader consume. |
| ResolvedMaterial | A material with every property resolved, as the render path consumes it. |
| ResolvedSurface | A surface reduced to the numeric material terms the shading maths consumes. |
| SceneUniformInput | Everything the scene uniform needs, independent of any particular backend. |
| Shape3DState | State interface for a 3D shape, defining position and rotation around each axis. |
| SphereState | State interface for a sphere, defining radius, longitudinal segments, and latitudinal rings. |
| SpotLightOptions | Options for SpotLight. |
| SurfaceIllumination | The light arriving at a surface, split so the diffuse term stays a plain multiplier. |
| TextureOptions | Options for creating a Texture. |
| TexturePattern | The tile geometry and repetition a Texture maps onto, and the pattern built from it. |
| TorusState | State interface for a torus, defining major radius, tube radius, and segment counts. |
| UniformField | A single field within a uniform struct. |
| Viewport | Viewport dimensions used for projection. |
Type Aliases ​
| Type Alias | Description |
|---|---|
| AmbientLightOptions | Options for AmbientLight. |
| BezierPatch | The sixteen control points of a bicubic Bézier patch, in row-major order. |
| CameraInteractionOption | A camera interaction can be enabled/disabled with a boolean or configured with sensitivity. |
| ColorUnitRGB | Linear RGB triple with each channel in the 0–1 range. |
| ColorUnitRGBA | RGBA quad with each channel in the 0–1 range. |
| DirectionalLightOptions | Options for DirectionalLight. |
| FogMode | How fog thickens with distance from the camera. |
| LightMode | Determines whether the light direction is fixed in world space or follows the camera. |
| LightSpace | Whether a light's orientation is fixed in world space or follows the camera. |
| LightType | The kind of illumination a Light contributes. |
| MaterialSide | Which faces of a surface are drawn, relative to their counter-clockwise winding. |
| Matrix4 | A column-major 4×4 matrix stored as a 16-element Float64Array. |
| ParametricSurface | Evaluates a surface at a point in its parameter domain. |
| PointLightOptions | Options for PointLight. |
| ProjectedPoint | A 2D screen-space point with a depth component for z-ordering. |
| RenderStrategy | The rendering strategy used by a 3D context. |
| Shape3DDefaults | Class-level defaults for a 3D shape. Excludes scale, which Shape3D expands itself, and zIndex, which it derives from projected depth. |
| Shape3DOptions | Options for constructing a 3D shape, with all state properties optional. |
| TextureFilter | How a texture is sampled between texels. |
| TexturePatternRepetition | The createPattern repetition modes a texture's wrap modes resolve to. |
| TextureSource | An image a Texture can be built from. |
| TextureWrap | How a texture coordinate outside the 0–1 range is resolved. |
| Vector2 | A 2-component vector represented as a labeled tuple [x, y]. |
| Vector3 | A 3-component vector represented as a labeled tuple [x, y, z]. |
Variables ​
| Variable | Description |
|---|---|
| DEFAULT_SURFACE_COLOR | The colour used when an element has no fill and no material colour. |
| FOG_MODE_CODE | Numeric discriminators for each fog mode, shared by the packer and the shader. |
| interpolateVector3 | Interpolator factory for Vector3 values, using component-wise linear interpolation. |
| LIGHT_DIRECTION | Pre-normalized light direction vectors for common light positions. |
| LIGHT_STRUCT_SIZE | Floats occupied by one light in the scene uniform. |
| LIGHT_TYPE_CODE | Numeric discriminators for each light type, shared by the packer and the shader. |
| LIGHT_UNIFORM_FIELDS | The per-light fields, in declaration order. |
| MATERIAL_SIDE_CODE | Numeric discriminators for each material side, shared by the packer and the shader. |
| MAX_LIGHTS | The maximum number of lights a single render pass can carry. |
| MODEL_UNIFORM_BYTES | Size in bytes of the model uniform buffer. |
| MODEL_UNIFORM_FIELDS | The per-model fields, in declaration order. |
| MODEL_UNIFORM_FLOATS | Floats occupied by the whole model uniform. |
| MODEL_UNIFORM_WGSL | The WGSL declaration of the per-model uniform, generated from MODEL_UNIFORM_FIELDS. |
| PLAIN_SURFACE | A surface with no specular response and no emission — the default for an element with only a fill. |
| SCENE_CAMERA_POSITION_OFFSET | Float offset of the camera position within the scene uniform. |
| SCENE_FOG_COLOR_OFFSET | Float offset of the fog colour and mode within the scene uniform. |
| SCENE_FOG_PARAMS_OFFSET | Float offset of the fog distance parameters within the scene uniform. |
| SCENE_LIGHT_COUNT_OFFSET | Float offset of the light count, packed into the camera position's unused w component. |
| SCENE_LIGHTS_OFFSET | Float offset of the first light within the scene uniform. |
| SCENE_UNIFORM_BYTES | Size in bytes of the scene uniform buffer. |
| SCENE_UNIFORM_FIELDS | The scene uniform fields, in declaration order. |
| SCENE_UNIFORM_FLOATS | Floats occupied by the whole scene uniform. |
| SCENE_UNIFORM_WGSL | The WGSL declaration of the scene uniform, generated from SCENE_UNIFORM_FIELDS. |
| VERTEX_FLOATS | Floats per interleaved vertex: position(3), normal(3), colour(4), uv(2). |
Functions ​
| Function | Description |
|---|---|
| bernstein3 | Evaluates the four cubic Bernstein basis functions at t. |
| composeSurfaceColor | Composes a shaded CSS colour from a surface's base colour and the light reaching it. |
| computeDistanceAttenuation | Computes distance falloff for a positional light. |
| computeFaceBrightness | Computes a 0–1 brightness value for a face given its normal and a light direction. |
| computeFaceNormal | Computes the surface normal of a face from its first three vertices via the cross product. |
| computeFogFactor | Computes how far a surface has faded towards the fog colour. |
| computeSpotAttenuation | Computes the cone falloff for a spot light. |
| contextIsContext3D | Type guard that checks whether a rendering context is a Context3D. |
| createAmbientLight | Creates an AmbientLight. |
| createBezierSurface | Creates a BezierSurface. |
| createCamera | Factory function that creates a new Camera bound to a 3D context. |
| createCone | Factory function that creates a new Cone instance. |
| createContext | Creates a Canvas 2D–backed 3D rendering context attached to the given DOM target. |
| createCube | Factory function that creates a new Cube instance. |
| createCylinder | Factory function that creates a new Cylinder instance. |
| createDirectionalLight | Creates a DirectionalLight. |
| createGroup3D | Creates a Group3D. |
| createHemisphereLight | Creates a HemisphereLight. |
| createMaterial | Creates a Material, filling in the defaults. |
| createMesh | Creates a Mesh from an explicit face list. |
| createParametric | Creates a Parametric surface. |
| createPlane | Factory function that creates a new Plane instance. |
| createPointLight | Creates a PointLight. |
| createRay | Creates a ray from an origin and a direction, normalising the direction. |
| createShape3D | Factory function that creates a new Shape3D instance. |
| createSphere | Factory function that creates a new Sphere instance. |
| createSpotLight | Creates a SpotLight. |
| createSurfaceIllumination | Creates a zeroed SurfaceIllumination for shadeSurface to write into. |
| createTexture | Creates a Texture from an image source. |
| createTorus | Factory function that creates a new Torus instance. |
| elementIsBezierSurface | Type guard that checks whether a value is a BezierSurface instance. |
| elementIsCone | Type guard that checks whether a value is a Cone instance. |
| elementIsCube | Type guard that checks whether a value is a Cube instance. |
| elementIsCylinder | Type guard that checks whether a value is a Cylinder instance. |
| elementIsGroup3D | Type guard that checks whether a value is a Group3D. |
| elementIsMesh | Type guard that checks whether a value is a Mesh instance. |
| elementIsParametric | Type guard that checks whether a value is a Parametric instance. |
| elementIsPlane | Type guard that checks whether a value is a Plane instance. |
| elementIsShape3D | Type guard that checks whether a value is a Shape3D instance. |
| elementIsSphere | Type guard that checks whether a value is a Sphere instance. |
| elementIsTorus | Type guard that checks whether a value is a Torus instance. |
| evaluateBezierPatch | Evaluates a bicubic Bézier patch at (u, v). |
| lightIsAmbient | Type guard that narrows a light to an AmbientLight. |
| lightIsCameraSpace | Whether a light's orientation follows the camera rather than being fixed in world space. |
| lightIsDirectional | Type guard that narrows a light to a DirectionalLight. |
| lightIsHemisphere | Type guard that narrows a light to a HemisphereLight. |
| lightIsPoint | Type guard that narrows a light to a PointLight. |
| lightIsPositional | Type guard that narrows a light to one that radiates from a position. |
| lightIsSpot | Type guard that narrows a light to a SpotLight. |
| loadTexture | Loads an image from a URL and wraps it in a Texture. |
| mat4Clone | Returns a copy of the given matrix. |
| mat4Compose | Composes a transform from translation, per-axis rotation and scale, applied in that order. |
| mat4Create | Creates a zeroed 4×4 matrix. |
| mat4Identity | Creates a 4×4 identity matrix. |
| mat4Invert | Inverts a 4×4 matrix, or returns null when it is singular. |
| mat4LookAt | Constructs a view matrix looking from eye toward target with the given up direction. |
| mat4Multiply | Multiplies two 4×4 matrices. |
| mat4NormalMatrix | Builds the normal matrix for a model matrix — the inverse transpose of its upper-3×3. |
| mat4Orthographic | Constructs an orthographic projection matrix. |
| mat4Perspective | Constructs a perspective projection matrix. |
| mat4RotateX | Applies a rotation around the X axis to a matrix. |
| mat4RotateY | Applies a rotation around the Y axis to a matrix. |
| mat4RotateZ | Applies a rotation around the Z axis to a matrix. |
| mat4Scale | Applies a scale transform to a matrix. |
| mat4TransformDirection | Transforms a direction vector by the upper-3×3 of a 4×4 matrix, ignoring translation. |
| mat4TransformDirectionInverse | Transforms a direction vector by the transposed upper-3×3 of a 4×4 matrix, ignoring translation. For a rigid transform (rotation plus translation, such as a view matrix) the transposed rotation is its inverse, so this undoes mat4TransformDirection — use it to carry a direction from view space back into world space. |
| mat4TransformPoint | Transforms a 3D point by a 4×4 matrix, performing the perspective divide. |
| mat4Translate | Applies a translation to a matrix. |
| mat4Transpose | Returns the transpose of a 4×4 matrix. |
| materialDrawsFace | Whether a face wound counter-clockwise should be drawn, given its signed screen area. |
| materialSideCode | The numeric discriminator for a material side, as the model uniform carries it. |
| packModelUniform | Writes the per-model uniform into a Float32Array laid out per MODEL_UNIFORM_FIELDS. |
| packSceneUniform | Writes the scene uniform into a Float32Array laid out per SCENE_UNIFORM_FIELDS. |
| parametricNormal | Approximates a parametric surface's normal at (u, v) from its numeric partial derivatives. |
| projectPoint | Projects a 3D world-space point onto 2D screen-space via a view-projection matrix and viewport. |
| rayAt | Returns the point at distance along a ray. |
| rayFromScreen | Builds the world-space ray passing through a screen-space point. |
| rayHitBarycentric | Reconstructs a point on a triangle from the barycentric weights of a RayTriangleHit. |
| rayIntersectsBox | Tests a ray against an axis-aligned bounding box using the slab method. |
| rayIntersectTriangle | Intersects a ray with a triangle using the Möller–Trumbore algorithm. |
| rayIntersectTriangleBuffer | Intersects a ray with a triangle read straight out of a packed vertex buffer. |
| releaseTexturePatternCache | Drops every texture pattern cached against a context, together with the offscreen tile canvases the mirrored and ImageData-backed ones hold. Call it when the context is torn down. |
| resolveColor | Parses a CSS colour into 0–255 RGBA channels, caching the result. |
| resolveColorUnitRGB | Parses a CSS colour straight into unit-range RGB, falling back to fallback when unparseable. |
| resolveFog | Resolves fog into the numeric form the scene uniform and the CPU painter consume. |
| resolveLight | Flattens a light into the numeric form shadeSurface and the scene uniform consume. |
| resolveLightColor | Resolves a light's colour and intensity into the premultiplied unit RGB the shading maths uses. |
| resolveMaterial | Resolves a material and an element's fill into the numeric form the render path consumes. |
| resolveTexturePattern | Builds the repeating CanvasPattern that maps a texture across a surface, caching it per context and texture version. |
| rgbaToUnit | Converts 0–255 RGBA channels to the 0–1 range the shading maths and GPU buffers use. |
| rgbToUnit | Converts 0–255 RGB channels to the 0–1 range the shading maths and GPU buffers use. |
| sampleTexture | Samples a texture on the CPU, honouring its wrap modes, filter, flip and transform. |
| shadeFaceColor | Shades a color by a brightness factor (0–1), darkening or lightening the RGB channels. |
| shadeSurface | Resolves the light arriving at a surface point, writing into out rather than allocating. |
| tessellateParametric | Tessellates a parametric surface into a grid of quads with normals and UVs. |
| texturePatternRepetition | Maps a texture's wrap modes onto the createPattern repetition that reproduces them. |
| textureSourceHeight | Returns an image source's height in pixels, or 0 when it has no intrinsic size yet. |
| textureSourceWidth | Returns an image source's width in pixels, or 0 when it has no intrinsic size yet. |
| textureTransformUV | Applies a texture's repeat and offset to a raw surface coordinate. |
| textureWrapCoordinate | Resolves a coordinate outside the unit range according to a wrap mode. |
| triangulateFacesFlat | Flattens faces into the interleaved vertex buffer a GPU backend uploads. |
| triangulateFacesIndices | Fan-triangulates faces into an index buffer addressing triangulateFacesFlat's vertices. |
| typeIsLight | Type guard that checks whether a value is any kind of Light. |
| typeIsTexture | Type guard that checks whether a value is a Texture. |
| typeIsVector2 | Type guard that checks whether a value is a Vector2 tuple. |
| typeIsVector3 | Type guard that checks whether a value is a Vector3 tuple. |
| unprojectPoint | Reverses projectPoint, mapping a screen-space point at a given clip depth back into world space. |
| vec2Add | Returns the component-wise sum of two vectors. |
| vec2Dot | Computes the dot product of two vectors. |
| vec2Length | Returns the Euclidean length of a vector. |
| vec2Lerp | Linearly interpolates between two vectors by factor t. |
| vec2Multiply | Returns the component-wise product of two vectors. |
| vec2Normalize | Returns the unit-length direction of a vector, or the zero vector if length is 0. |
| vec2Scale | Scales a vector by a scalar. |
| vec2Sub | Returns the component-wise difference of two vectors. |
| vec3Add | Returns the component-wise sum of two vectors. |
| vec3Cross | Computes the cross product of two vectors. |
| vec3Distance | Returns the Euclidean distance between two points. |
| vec3Dot | Computes the dot product of two vectors. |
| vec3Length | Returns the Euclidean length of a vector. |
| vec3Lerp | Linearly interpolates between two vectors by factor t. |
| vec3Negate | Negates all components of a vector. |
| vec3Normalize | Returns the unit-length direction of a vector, or the zero vector if length is 0. |
| vec3Scale | Scales a vector by a scalar. |
| vec3Sub | Returns the component-wise difference of two vectors. |
| vec3TriangleNormal | Returns the unit-length normal of the triangle a → b → c, wound counter-clockwise. |