This page lists what an AI assistant needs to write Apricot code: the rules, the import map, the components and the common mistakes. It is the first page in llms.txt.
Give your assistant the docs#
| You use | Give it |
|---|---|
| An assistant that can read URLs (Claude, ChatGPT, Cursor, Claude Code…) | https://matthiasbrandolin.dev/apricot/llms.txt: an index of every page, each linked as Markdown. |
| An assistant with a large context, or offline | https://matthiasbrandolin.dev/apricot/llms-full.txt: every page in one file. |
| One topic | Any page's Markdown: add .md to its URL (/apricot/guides/camera.md), or use Copy page at the top of the page. |
An example prompt:
Read https://matthiasbrandolin.dev/apricot/llms.txt and the pages it links
that matter for this task. Follow the rules in "Building with AI" exactly.
Build me: a product screen where a gold coin spins slowly, speeds up when I
swipe, and shows its name in a label above it. Expo SDK 57, TypeScript.Rules for writing Apricot code#
Follow all of these rules.
-
Import from the right entry point.
- Everything is imported from
@apricotjs/react-native, except:Model,useModel,useTexture,useTextureState,defineModelKit,download,isDownloaded,forgetDownloadsandmeasureModel, from@apricotjs/react-native/model;captureScene,captureUri,deleteCaptureandclearCaptures, from@apricotjs/react-native/capture.
- Ready-made objects (
MoneyStack,Coin,Apple,Peach,Car,Card,Trees,Ground,ContactShadow,Backdrop,StudioFloor,CARD_SIZE…) come from@apricotjs/assets. - Utilities without React (
seededRandom,disposeObject,Path,Trip) come from@apricotjs/core. - App code does not import
three. Use shapes, models, materials and refs instead. The exception is building custom geometry (see Custom geometry and behaviors).
- Everything is imported from
-
<Scene>needs a size. Give itstyle={{ flex: 1 }}or a height, like any view. Everything 3D goes inside a<Scene>. Hooks such asuseFrameanduseSceneonly work in components rendered inside one. -
Most
<Scene>props are read once, at mount. These arelook,camera,fog,environment,transparent,toneMapping,exposure,shadows,occlusion,lamps,lighting,maxPixelRatioandlinger. Changing them later does nothing. Instead:- change reflections with
<Environment>, - change the time of day with
<Daylight>, - move the camera with
<CameraRig>or<FitCamera>, - remount the scene with a new
keyfor anything else.
frameloop,backgroundandpausedare the Scene props that can change after mount. - change reflections with
-
Animate without React renders. Animatable props accept a plain value or a Reanimated shared value (
useSharedValue,useDerivedValue). Shared values needreact-native-reanimatedandreact-native-worklets. Both are optional: install them when the code uses shared values. Drive per-frame logic withuseFrame. Never callsetStateevery frame. -
The scene renders only when something changes (
frameloop="demand").- In
useFrame, returntruewhile something is still animating, andfalseor nothing when it is done. - After changing an object directly (through a ref) outside
useFrame, calluseScene().invalidate().
- In
-
Units and angles.
- Distances are scene units, meant as metres. Y is up. The camera looks down −z by default, so a model's front faces +z.
- Object
rotationis Euler angles in radians[x, y, z].<Spin speed>is radians per second. - Camera views (
azimuth,elevation), orbit limits and jointrangeare in degrees.fovis degrees. - Colours are CSS strings (
"#ff9f59") or anything three.js accepts.
-
Use one
<Instances>for many copies of the same thing, instead of a.map()of shapes. Each separate mesh costs about 80 µs per frame on a mid-range Android phone. -
Models are
.glbfiles bundled withrequire, as in<Model src={require("./car.glb")} />.- Optimise them first with
npx apricot-models ./models -o ./assets/models. Draco, meshopt and KTX2 cannot be decoded on the device. groundstands a model on y = 0.- Use a model kit (
defineModelKit) to name parts, then refer to those names inmaterialsandjoints.
- Optimise them first with
-
Gestures wrap the scene. For your own gestures, put
<Scene>inside aGestureDetector(react-native-gesture-handler) and write shared values in the gesture callbacks. The app root needsGestureHandlerRootView. Taps,<CameraRig orbit>and<Placement>need no gesture library. -
For an overlay,
<Scene transparent pointerEvents="none" style={StyleSheet.absoluteFill}>draws 3D over a screen and lets touches through to it. -
Order matters for cameras that follow. Put
<FollowCamera>(and<CameraRig follow>) after the object they follow, so they read this frame's position. -
Do not invent props. Every prop is listed in the API reference. If something is not there, build it with
useFrame, refs ordefineBehavior. -
Apricot needs a development build. Expo Go cannot run it.
-
Things people move by hand go in
<Placement>. Each is a<Placeable id position turn>whose place comes from state and goes back throughonChange. Keep that state withuseLayout. Build each piece standing on its origin and facing +z, and hung things with their back at z = 0.turnis in degrees. -
Bundled files need
expo-assetandexpo-file-system. Downloads andcaptureSceneneedexpo-file-system. If they are missing,<Model src={require(…)}>anduseTexture(require(…))throw an error naming them. URLs need neither. -
On the web, scenes draw with WebGPU, or WebGL 2 where WebGPU isn't available, with no code changes. Where neither exists, and in a phone app on a device without a WebGPU adapter, a scene fails with
[apricot] WebGPU isn't available on this device. To show something else there, checkgpuSupport()("webgpu","webgl"or"none") before rendering the scene.
Import map#
// Scenes, shapes, lights, cameras, motion, hooks, types
import {
Scene, Group, Primitive, Mesh, Box, Sphere, Cylinder, Cone, Plane, Torus, Capsule,
AmbientLight, HemisphereLight, DirectionalLight, PointLight, SpotLight,
Environment, Daylight, Lamp, LightBeam, WindowPane, Blur, Label, Instances, Merged, Bundle,
FitCamera, CameraRig, FollowCamera,
Spin, Vehicle, Pile, FollowPath,
Placement, Placeable, useLayout, leaveOutOfFootprint, Particles, BURSTS, EMITTERS,
Slab, Terrain, Water, useWaves, useShore, smoothOutline,
useFrame, useScene, useAnimatable, useDaylight, useBounds, NO_BOUNDS, usePath, useTrip, useTripStatus, useSceneTouches,
useMaterial, defineBehavior, definePreset, defineEnvironment, createMaterial, gpuSupport,
type SceneObject, type Vec3, type CameraRigHandle, type InstancesHandle, type PlacementHandle,
type LayoutItem, type Place, type Outline, type ParticlesHandle, type ApricotScene,
} from "@apricotjs/react-native";
// Models, textures and downloads
import { Model, defineModelKit, useModel, useTexture, download, measureModel, type PartPressEvent } from "@apricotjs/react-native/model";
// Capture
import { captureScene, captureUri, deleteCapture } from "@apricotjs/react-native/capture";
// Ready-made objects
import { MoneyStack, Coin, Apple, Peach, Car, Card, CARD_SIZE, Trees, Ground, ContactShadow, Backdrop, StudioFloor } from "@apricotjs/assets";
// Engine utilities
import { seededRandom, disposeObject } from "@apricotjs/core";Components at a glance#
| Need | Use | Page |
|---|---|---|
| A 3D view | <Scene> |
Scene |
| Basic shapes | <Box>, <Sphere>, <Cylinder>, <Cone>, <Plane>, <Torus>, <Capsule>, <Mesh geometry> |
Objects |
| Group and move things together | <Group position rotation scale> |
Objects |
| What things are made of | material="chrome" or { preset, color, roughness, metalness } |
Materials |
| Lighting | look, environment, <Environment>, <Daylight>, light components, shadows |
Lights |
| Sun through a window, lamps at dusk | <LightBeam sun>, <WindowPane>, <Lamp on="dark">, <Scene lamps> |
Lighting a room |
| Soft shadows and corners | <Scene occlusion toneMapping="neutral" shadows={{ softness }}>, shadowOnly |
Scene |
| Frame an object at any screen size | <FitCamera size> |
Cameras |
| Named views, flying between them, drag to orbit | <CameraRig view orbit> |
Cameras |
| Chase camera | <FollowCamera target> |
Cameras |
A .glb model: paint parts, open doors, play clips |
<Model kit materials joints animations> |
Model |
| Spin something | <Spin speed axis> |
Motion |
| Anything per frame | useFrame(({ delta }) => …) |
Hooks |
| A reusable behavior | defineBehavior({ name, defaults, frame }) |
Motion |
| Hundreds of copies, tappable | <Instances items onPress> |
Instances |
| Objects that fall and pile up | <Pile count> |
Motion |
| A drivable toy car | <Vehicle throttle steer> |
Motion |
| A vehicle on a route with stops | usePath, useTrip, <FollowPath> |
Motion |
| A React Native view pinned to a 3D point | <Label attach position> |
Labels and blur |
| Out-of-focus background | <Blur radius> |
Labels and blur |
| Furniture or props people pick up, drag and turn | <Placement> + <Placeable> (bounds for a rectangular room, walls for any other shape) |
Placement |
| Undo, redo and saving for a layout | useLayout(initial, { save }) |
Placement |
| An island, a beach, a sea | <Slab>, <Terrain>, <Water>, useWaves, useShore |
Ground and water |
| A piece made of many shapes, in one draw call | <Merged> |
Objects |
| Cheaper frames for a still room | <Bundle> |
Objects |
| Sparks, confetti, fireworks, smoke, snow | <Particles>: ref.burst("confetti"), emit="smoke" |
Particles |
| A catalog or shop: one item at a time, swapped smoothly | <Model src={item.src} onReady> with a <CameraRig> inside, scene.drawn(), <Group visible> |
Catalogs |
| Size or place something by an object (a shadow, a label) | useBounds(object), <ContactShadow under={object}> |
Hooks |
| A PNG of the scene to share or as a thumbnail | captureScene(scene, { maxSize }) from @apricotjs/react-native/capture |
Capture |
| Models from a server, downloaded up front | <Model src="https://…">, download(urls) |
Model |
| Room for something new in a layout | <Placeable findRoom> moves to the nearest free place as it arrives. To ask first, use placementRef.findFreePlace({ size or extent, on }) |
Placement |
| Parts that reach over others (fronds, a canopy) | <Group footprint={false}> inside the <Placeable>, or <Placeable footprint={[w, d]}> |
Placement |
| Pieces left outside after a room shrinks | <Placement onOutside>, placementRef.moveInside() |
Placement |
| Several scenes (a carousel), or a scene kept but not seen | <Scene paused={!visible}> |
Scene |
| A camera that idles gently, or frames rooms at one scale | <CameraRig sway fit="footprint"> |
Cameras |
| Jest tests of screens with a scene | jest.mock("@apricotjs/react-native", () => require("@apricotjs/react-native/mock")) |
Testing |
Common mistakes#
| Wrong | Right | Why |
|---|---|---|
import { Model } from "@apricotjs/react-native" |
import { Model } from "@apricotjs/react-native/model" |
Model is only exported from @apricotjs/react-native/model. |
rotation={[0, 90, 0]} |
rotation={[0, Math.PI / 2, 0]} |
Object rotations are radians. |
<CameraRig view={{ azimuth: Math.PI / 4 }} /> |
<CameraRig view={{ azimuth: 45 }} /> |
Camera angles are degrees. |
setState in useFrame or a gesture to move things |
A shared value passed to the prop, or a ref changed in useFrame |
A React render every frame is slow. |
useFrame(() => { ref.current.rotation.y += 0.01 }) |
useFrame(({ delta }) => { ref.current.rotation.y += delta; return true; }) |
Use delta (seconds) for frame-rate independence, and return true to keep rendering. |
{seats.map(s => <Box key={s.id} … />)} for hundreds of seats |
<Instances items={seats}><Box … /></Instances> |
One draw call instead of hundreds. |
<Scene look={dark ? "studio" : "soft"}> to switch looks |
<Scene key={dark ? "dark" : "light"} look={…}> or <Environment name={…} /> |
Scene options are read once at mount. |
<Scene> with no style |
<Scene style={{ flex: 1 }}> |
A view with no size draws nothing. |
<FollowCamera target={car} /> before <Vehicle ref={car}> |
Put it after the vehicle | It must read the car's position after the car moved this frame. |
src="./car.glb" |
src={require("./car.glb")} |
A string is fetched as a URL. |
Shiny metal under look="soft" with no environment |
look="none" environment="studio" |
Metals need something to reflect. |
<Placeable turn={Math.PI / 2}> |
<Placeable turn={90}> |
Placement turns are degrees. |
Moving a <Placeable> with position changes during a drag |
Let <Placement> move it, and store onChange's place (useLayout's place) |
Places go out through onChange and come back as props. |
A <Placeable> outside <Placement> |
Inside a <Placement> |
It throws <Placeable> must be inside a <Placement>. |
<Terrain height={(x, z) => …}> written inline |
A function defined outside the component | A new function rebuilds the terrain every render. |
| Fading a scene's view to opacity 0 to hide it | <Scene paused>, or fade to 2% |
A view at opacity 0 still draws, and on iOS it can hold up the app. |
<CameraRig subject={ref}> or fit={{ footprint: ref }} |
The object itself, kept in state from a ref callback: <Group ref={setFloor}> then fit={{ footprint: floor }} |
These props take objects, not refs. |
<Particles> inside a <Bundle> |
Outside it | A bundle is for things that don't move. |
A complete example to learn from#
A swipeable gold coin with a label, using rules 1, 2, 4, 6 and 9:
import { Coin } from "@apricotjs/assets";
import { Group, Label, Scene, Spin } from "@apricotjs/react-native";
import { Text } from "react-native";
import { Gesture, GestureDetector } from "react-native-gesture-handler";
import { cancelAnimation, useDerivedValue, useSharedValue, withDecay } from "react-native-reanimated";
export function CoinScreen() {
const angle = useSharedValue(0);
const rotation = useDerivedValue<readonly [number, number, number]>(() => [0, angle.value, 0]);
const swipe = Gesture.Pan()
.onBegin(() => cancelAnimation(angle))
.onChange((e) => {
angle.value += e.changeX * 0.012;
})
.onEnd((e) => {
angle.value = withDecay({ velocity: e.velocityX * 0.012, deceleration: 0.997 });
});
return (
<GestureDetector gesture={swipe}>
<Scene style={{ flex: 1 }} look="none" environment="studio" background="#0e0f12" camera={{ position: [0, 0, 4] }}>
<Spin speed={0.5}>
<Group rotation={rotation}>
{/* A coin lies flat; stand it up to face the camera. */}
<Coin radius={1} rotation={[Math.PI / 2, 0, 0]} />
</Group>
</Spin>
<Label position={[0, 1.3, 0]}>
<Text style={{ color: "#ffffff", fontWeight: "600" }}>Gold coin</Text>
</Label>
</Scene>
</GestureDetector>
);
}