A 3D brush painting sketch that uses depth control for VR-style experiences. mapLocation() converts screen-space mouse coordinates and a depth slider value directly into world-space positions, so each brush stroke is placed precisely in 3D. Press r to toggle recording, c to clear, f to re-focus the camera on the world origin.


Screen-to-world mapping with mapLocation

The core of the brush is a single mapLocation call that lifts the 2D mouse position — together with a depth value from the slider — into 3D world space each frame:

points.push({
  pos: mapLocation([mouseX, mouseY, depthSlider.value()],
                   { from: p5.Tree.SCREEN, to: p5.Tree.WORLD }),
  color: brushColor.color()
})

The depth slider covers [0, 1] — the same NDC z range the depth buffer uses — so the slider moves strokes from the near to the far plane. Calibrating it to the world origin (so strokes pass through the scene centre) is a one-liner:

const o = mapLocation(p5.Tree.ORIGIN, { from: p5.Tree.WORLD, to: p5.Tree.SCREEN })
depthSlider.value(o.z)

mapLocation without an out option returns a freshly allocated p5.Vector, which is fine here since brush strokes are accumulated infrequently. For high-frequency hot paths (e.g. updating hundreds of positions per frame), pass a Float32Array(3) as out to avoid heap allocation.


Focusing on the origin

The focusOrigin function reorients the camera to look at the world origin without repositioning it, then recalibrates the depth slider so new strokes pass through the origin plane:

function focusOrigin() {
  const eye = mapLocation()           // camera world position (no args = EYE origin → WORLD)
  const up  = mapDirection(p5.Tree.j) // camera up axis in world space
  camera(eye.x, eye.y, eye.z, 0, 0, 0, up.x, up.y, up.z)
  const o = mapLocation(p5.Tree.ORIGIN, { from: p5.Tree.WORLD, to: p5.Tree.SCREEN })
  depthSlider.value(o.z)
}

mapDirection(p5.Tree.j) converts the camera’s local y axis from eye space to world space, giving camera() a stable up vector that doesn’t flip as the user orbits.


Further reading