Skip to content

Placing objects ​

Put things where they belong without guessing numbers: drop an object until it touches what's under it, stick it onto a surface facing out, line objects up, space them out. Like snapping and aligning in Blender.

js
import { dropOnto, attachTo, alignObjects, distributeObjects } from "./trid/index.js";
a table dropped onto the floor · books spaced side by side, then dropped on it · a box on top of a ball · crates stacked · frames attached to the wall — drag to orbit
js
import { Scene, makeShape, dropOnto, attachTo, alignObjects, distributeObjects, WebGLRenderer, OrbitCamera } from "./trid/index.js";

const box = (w, h, d, fill, pos = {}, rot = {}) => ({
  mesh: makeShape("box", { w, h, d }),
  pos: { x: 0, y: 0, z: 0, ...pos }, rot: { x: 0, y: 0, z: 0, ...rot },
  material: { fill },
});

const floor = box(2, 0.05, 1.2, "#3b4252", { y: -0.4 });
const wall = box(2, 1, 0.05, "#d8cbb8", { y: 0.075, z: 0.45 });

// A table built anywhere, then dropped onto the floor as one group
const legs = [-1, 1].flatMap((x) => [-1, 1].map((z) => box(0.04, 0.32, 0.04, "#8a5a3c", { x: x * 0.33, y: -0.18, z: z * 0.14 })));
const table = { pos: { x: -0.3, y: 0.6, z: 0.1 }, children: [box(0.76, 0.04, 0.34, "#a0704a"), ...legs] };
dropOnto(table, floor);

// Books of different sizes: spaced side by side, touching, then dropped onto the table
const colors = ["#E9806E", "#5f8fd8", "#e5c07b", "#98c379", "#c678dd", "#56b6c2"];
const books = colors.map((fill, i) => box(0.035 + (i % 3) * 0.012, 0.16 + ((i * 7) % 5) * 0.025, 0.12, fill, { x: -0.6 + i * 0.1, y: 0.8, z: 0.15 }));
distributeObjects(books, { axis: "x", gap: 0 });
for (const book of books) dropOnto(book, table);

// A ball on the table, and a box dropped onto its very top
const ball = { mesh: makeShape("sphere", { r: 0.07 }), pos: { x: -0.05, y: 0.8, z: 0.05 }, material: { fill: "#e06c75", smooth: true } };
dropOnto(ball, table);
const cube = box(0.05, 0.05, 0.05, "#e5c07b", { x: -0.05, y: 1, z: 0.05 }, { y: 0.6 });
dropOnto(cube, ball);

// Crates stacked on the floor: each dropped onto the floor and the crates already there
const crates = [];
for (const [x, z, s, turn] of [[0.5, 0.1, 0.24, 0.2], [0.53, 0.1, 0.19, -0.35], [0.49, 0.12, 0.13, 0.5], [0.8, 0.0, 0.16, 0.3]]) {
  const crate = box(s, s, s, "#b48a5a", { x, y: 1.2, z }, { y: turn });
  dropOnto(crate, [floor, ...crates]);
  crates.push(crate);
}

// Frames on the wall: snapped onto it facing out, spaced evenly, their tops level
const frames = [[0.3, 0.22], [0.18, 0.26], [0.24, 0.18]].map(([w, h], i) => box(w, h, 0.02, ["#5f8fd8", "#98c379", "#E9806E"][i], { x: -0.6 + i * 0.5, y: 0.3, z: 0 }));
for (const frame of frames) attachTo(frame, wall, { axis: "-z" }); // its back on the wall
alignObjects(frames, { axis: "y", to: "max", reference: 0.45 });
distributeObjects(frames, { axis: "x" });

export default function (canvas) {
  // Shadows show what rests on what
  const scene = new Scene(canvas, {
    width: 800, height: 360, camera: { fov: 0.6 },
    renderer: WebGLRenderer.isSupported() ? new WebGLRenderer() : undefined,
    lights: [{ type: "ambient", intensity: 0.4 }, { type: "directional", direction: { x: -0.5, y: 1, z: -0.7 }, intensity: 0.7, shadows: true }],
  });
  for (const obj of [floor, wall, table, ...books, ball, cube, ...crates, ...frames]) scene.add(obj);
  scene.use(new OrbitCamera({ target: { x: 0, y: -0.05, z: 0.1 }, distance: 2.7, yaw: -0.25, pitch: -0.3 }));
  scene.start();
  return () => scene.destroy();
}

These functions move the object (its pos, and its rot for attachTo); meshes are never changed. They work in world space, through groups: an object inside a group is moved in its parent's space so it ends up where asked. Objects inside groups need their parent link, which scene.add sets (or call worldObjects on the group).

Targets are a Scene, an object, or a list of objects. Every visible object with faces under them counts, except the object being placed and its own children, so dropOnto(cup, scene) works.

dropOnto(obj, targets, opts?) ​

Moves an object along a direction (down by default) until its surface touches a target's: a cup onto a table, a rock onto terrain, a crate pushed against a wall.

js
dropOnto(cup, table);                                          // rests on the table
dropOnto(rock, [ground, ...rocks]);                            // on the ground, or on the rocks already there
dropOnto(crate, scene, { direction: { x: 1, y: 0, z: 0 } });  // pushed right until it meets something
OptionDefaultMeaning
direction{ x: 0, y: -1, z: 0 }Which way it moves, any length
gap0Stop this far before touching
maxDistanceInfinityDon't move further than this

The contact is exact for flat-faced meshes: corners against faces both ways, and edges against edges, so two crossed beams meet ridge on ridge and a box rests on the very top of a sphere. Nothing floats and nothing sinks.

If the object is already sunk into a target, it's lifted back out (against direction) and set on top: the usual fix for a part placed a bit too low. It returns { distance, point, object }: how far it moved along the direction (negative when lifted), where it touches, and what. When nothing is in the way, it returns null and the object doesn't move.

Big meshes

Each call prepares the meshes involved for fast questions (see meshQuery). With a few thousand faces that's well under a millisecond; an 8,000-face rock onto a 22,000-face terrain takes about a quarter of a second. Pass only the targets that matter, not the whole scene, when the scene is big.

attachTo(obj, targets, opts?) ​

Puts an object on the nearest surface of the targets, turned to follow it: horns on a head, a handle on a mug, a window on a wall, spikes on a ball. Place it roughly first, or pass at, and it snaps onto the surface there.

js
attachTo(horn, head, { offset: -0.02 });                             // grows out of the head
attachTo(eye, head, { at: { x: 0.1, y: 0.2, z: 0.5 }, axis: "z" });  // its z faces out of the face
attachTo(painting, wall, { axis: "-z" });                            // its back against the wall
OptionDefaultMeaning
atits positionFind the surface point nearest to this world point
axis"y"The object's axis that points out of the surface: "x", "y", "z", or "-x", "-y", "-z"
aligntrueTurn the object so axis follows the surface's normal (the shortest turn from how it was). false keeps its turn
anchor"base"The point of the object put on the surface: "base" is the middle of its box's side opposite axis (the bottom, for "y"); "origin" its origin; or a point in its own space
offset0Distance out along the normal. Negative sinks it in, so a horn grows out of the head instead of sitting on it

It returns { point, normal, object, distance }: the surface point, its normal (pointing out), the object it's on, and how far the surface was from at. null when there's no surface.

alignObjects(objects, opts?) ​

Lines objects up by their boxes, like Blender's Align.

js
alignObjects(legs, { axis: "y", to: "min" });                                       // all on the same floor
alignObjects([lamp, vase], { axis: ["x", "z"], to: "center", reference: table });   // centered over the table
alignObjects([shelf], { axis: "y", to: "max", reference: 1.8 });                    // its top at 1.8
OptionDefaultMeaning
axis"y"Axis, or a list of them
to"min"Which side lines up: "min" (the low sides: bottoms for "y"), "center" or "max"
referencethe box around all of themLine up with a world coordinate (a number), or with an object's box

distributeObjects(objects, opts?) ​

Spreads objects out along an axis by their boxes, in the order they're already in along it.

js
distributeObjects(posts, { axis: "z" });           // the end posts stay, equal spaces between
distributeObjects(books, { axis: "x", gap: 0 });   // side by side, touching

Without gap, the first and last objects stay and the ones between move so every space between neighbors is the same. With gap, the first stays and each next one starts gap after the one before it ends.