Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 44 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -181,6 +181,50 @@ fun ThinkingOrb() {

The orb stops while it is scrolled off screen or its window is in the background, holds still when the platform asks for reduced motion, and is one labelled image to a screen reader — or hidden from one, without a label. Orbs in the same state share a clock, so a column of them breathes together. To drive a runtime and frame builder you already own, wrap them in `LiveFrameSource(runtime, builder)`; to play a recording from `:phosphor-trace`, open it with `asFrameSource()`. The snippet is compiled by `ReadmeLumosQuickStartTest`.

The orb answers the pointer on every target — hover where the platform has it, touch everywhere — and takes no gesture from its parents, so an orb in a scrolling column still scrolls it. Make the scene `interactive` and its cells part around the pointer; the projected frame carries the pointer in pixels for a material's light. A consumer drawing `LumosCanvas` directly gets the same plumbing from one modifier, `Modifier.lumosPointer`, which reports the pointer in the orb's view space and never consumes it:

```kotlin
import androidx.compose.foundation.layout.size
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.runtime.withFrameNanos
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import link.socket.phosphor.lumos.LiveFrameSource
import link.socket.phosphor.lumos.LumosRenderConfig
import link.socket.phosphor.lumos.compose.LumosCanvas
import link.socket.phosphor.lumos.compose.lumosPointer
import link.socket.phosphor.lumos.projection.PixelLattice
import link.socket.phosphor.palette.AtmospherePresets

@Composable
fun PointedCanvas() {
// 1. An interactive scene: its cells part around the pointer
val source = remember { LiveFrameSource(AtmospherePresets.THINKING, LumosRenderConfig(interactive = true)) }
val lattice = remember { PixelLattice(widthPx = 160, heightPx = 160, voxelRadiusPx = 4f) }

// 2. Your own clock: project each frame as it is stepped
var frame by remember { mutableStateOf(lattice.project(source.next(0f))) }
LaunchedEffect(source) {
var last = withFrameNanos { it }
while (true) {
withFrameNanos { now ->
frame = lattice.project(source.next((now - last) / 1_000_000_000f))
last = now
}
}
}

// 3. The pointer, in the orb's view space, from one modifier that never consumes it;
// the projected frame then carries it in pixels for a material's light
LumosCanvas(frame, Modifier.size(160.dp).lumosPointer { source.setInput(it) })
}
```

### The orb becomes a control

`:phosphor-lumos-surface` lets the orb's cells leave their slot, fly to a real layout element and become it, with the element keeping focus, click and semantics throughout and nothing ticking once it is solid:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,14 @@ import link.socket.phosphor.lumos.OrbStepper
import link.socket.phosphor.lumos.PlatformMotionPreference
import link.socket.phosphor.lumos.frame.LumosCanvasFrame
import link.socket.phosphor.lumos.probe.FrameProbe
import link.socket.phosphor.signal.LumosInput

/**
* [OrbStepper] behind [LumosOrb], with the frame it draws held in Compose state so the canvas
* follows it. The rules about time are the stepper's — the step, the cap, aligning on a rejoin
* ([LumosFrameSource.align]) and on a look change ([LumosFrameSource.alignLook]) — and this only
* hands each new frame to Compose.
* hands each new frame to Compose. The pointer is the stepper's too ([OrbStepper.setInput]): it
* goes to the source, and the latest one is laid over every frame published, live or recorded.
*
* Main-thread only, like the source it steps.
*/
Expand All @@ -36,6 +38,9 @@ internal class LumosDriver(
/** The frame callback a frame loop hands to `withFrameNanos`, allocated once. */
val onFrame: (Long) -> Unit = { frameTimeNanos -> step(frameTimeNanos) }

/** The input callback [lumosPointer] is given, allocated once. */
val onInput: (LumosInput) -> Unit = { input -> setInput(input) }

/** See [OrbStepper.update]. */
fun update(
config: LumosConfig,
Expand All @@ -60,6 +65,12 @@ internal class LumosDriver(
/** See [OrbStepper.pollHeld]. */
fun pollHeld() = publish(stepper.pollHeld())

/**
* See [OrbStepper.setInput]. Publishes nothing: a pointer move while the orb is paused or
* under reduced motion is lit on the next frame drawn for another reason.
*/
fun setInput(input: LumosInput) = stepper.setInput(input)

// Only a new projection is written, so an unchanged frame costs Compose nothing.
private fun publish(frame: LumosCanvasFrame?) {
if (frame != null) canvasFrame = frame
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
package link.socket.phosphor.lumos.compose

import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.size
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import link.socket.phosphor.lumos.LiveFrameSource
import link.socket.phosphor.lumos.LumosConfig
import link.socket.phosphor.lumos.LumosRenderConfig
import link.socket.phosphor.math.Vector2
import link.socket.phosphor.palette.AtmospherePresets
import link.socket.phosphor.signal.LumosInput

/**
* Preview composable for the pointer (PHO-83): three `interactive` THINKING orbs side by side —
* nothing pointing, a pointer at the centre, and a pointer upper right — each settled under its
* pointer, so the strip shows the cells parted around it. The pointer is handed to each scene
* directly, as [Modifier.lumosPointer] would hand it from a real pointer.
*
* Like [LumosOrbPreview], a preview for a host project's preview pane or sample app, not a test.
*/
@Composable
fun LumosInputPreview() {
Row(horizontalArrangement = Arrangement.spacedBy(INPUT_PREVIEW_GAP)) {
for (pointer in INPUT_PREVIEW_POINTERS) PreviewInputOrb(pointer)
}
}

@Composable
private fun PreviewInputOrb(pointer: Vector2?) {
val source =
remember(pointer) {
LiveFrameSource(AtmospherePresets.THINKING, INPUT_PREVIEW_RENDER_CONFIG).also { live ->
live.next(INPUT_PREVIEW_WARM_UP_SECONDS)
live.setInput(LumosInput(pointer = pointer))
// Long enough for the cells to part and come to rest around the pointer.
repeat(INPUT_PREVIEW_SETTLE_FRAMES) { live.next(INPUT_PREVIEW_FRAME_SECONDS) }
}
}
LumosOrb(
source = source,
config = LumosConfig(label = if (pointer == null) "Lumos, alone" else "Lumos, pointed at"),
modifier = Modifier.size(INPUT_PREVIEW_SIZE),
backgroundColor = INPUT_PREVIEW_BACKGROUND,
)
}

/** Where each orb of the strip is pointed at, in the orb's view space; null for nothing pointing. */
val INPUT_PREVIEW_POINTERS: List<Vector2?> = listOf(null, Vector2(0f, 0f), Vector2(0.5f, 0.5f))

/** Each orb's size. */
val INPUT_PREVIEW_SIZE: Dp = 200.dp

/** The gap between orbs. */
val INPUT_PREVIEW_GAP: Dp = 16.dp

/** The strip's background. */
val INPUT_PREVIEW_BACKGROUND: Color = Color(0xFF111111)

private val INPUT_PREVIEW_RENDER_CONFIG = LumosRenderConfig(interactive = true)
private const val INPUT_PREVIEW_WARM_UP_SECONDS = 1.5f
private const val INPUT_PREVIEW_FRAME_SECONDS = 1f / 30f
private const val INPUT_PREVIEW_SETTLE_FRAMES = 45
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package link.socket.phosphor.lumos.compose
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.ProvidableCompositionLocal
import androidx.compose.runtime.SideEffect
Expand Down Expand Up @@ -35,6 +36,7 @@ import link.socket.phosphor.lumos.Material
import link.socket.phosphor.lumos.PlatformMotionPreference
import link.socket.phosphor.lumos.SurfaceStyle
import link.socket.phosphor.lumos.probe.FrameProbe
import link.socket.phosphor.signal.LumosInput

/**
* The [LookClock] the orbs below share, so orbs of one look breathe together. One per process
Expand Down Expand Up @@ -69,6 +71,13 @@ val LocalLookClock: ProvidableCompositionLocal<LookClock> = staticCompositionLoc
* look's phase alone ([LumosFrameSource.alignLook]), so its spin never snaps.
* - **Screen readers.** With a [LumosConfig.label], the orb is one image described by it. Without
* one, screen readers skip it.
* - **The pointer.** The orb answers the pointer on every target — hover where the platform has
* it, touch everywhere — through [Modifier.lumosPointer], and takes no gesture from its parents:
* an orb in a scrolling column still scrolls it. What it reads goes to
* [LumosFrameSource.setInput], so a live scene that is `interactive` parts its cells around it,
* and the latest pointer is laid over every frame drawn, live or recorded, for a material's
* light. When the orb leaves composition, or its source is replaced, the source is told the
* pointer has gone.
*
* One orb per source: a source stepped by two orbs runs twice as fast. To show one orb in two
* places, project its frame once and draw it with two [LumosCanvas]es.
Expand Down Expand Up @@ -124,14 +133,21 @@ fun LumosOrb(
}
}

// A source left behind — replaced, or the orb gone — is told the pointer has gone, so no
// ghost pointer keeps its cells parted.
DisposableEffect(driver) {
onDispose { driver.setInput(LumosInput.NONE) }
}

Box(
modifier =
modifier
.lumosSemantics(config.label)
.onSizeChanged { driver.resize(it.width, it.height) }
.onGloballyPositioned { coordinates ->
onScreen = coordinates.isAttached && !coordinates.boundsInWindow().isEmpty
},
}
.lumosPointer(config.tiltDegrees, driver.onInput),
) {
HeldCanvas(driver, backgroundColor, showHalo, showGlyphOverlay, probe, config.style, config.material)
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,163 @@
package link.socket.phosphor.lumos.compose

import androidx.compose.ui.Modifier
import androidx.compose.ui.input.pointer.AwaitPointerEventScope
import androidx.compose.ui.input.pointer.PointerEvent
import androidx.compose.ui.input.pointer.PointerEventPass
import androidx.compose.ui.input.pointer.PointerEventType
import androidx.compose.ui.input.pointer.PointerInputChange
import androidx.compose.ui.input.pointer.PointerInputScope
import androidx.compose.ui.input.pointer.PointerType
import androidx.compose.ui.input.pointer.SuspendingPointerInputModifierNode
import androidx.compose.ui.node.DelegatingNode
import androidx.compose.ui.node.ModifierNodeElement
import androidx.compose.ui.platform.InspectorInfo
import kotlin.math.PI
import kotlin.math.cos
import kotlin.math.max
import kotlin.math.sin
import kotlin.math.sqrt
import link.socket.phosphor.math.Vector2
import link.socket.phosphor.signal.LumosInput

/**
* Report where the pointer is over this node, as a [LumosInput] in the orb's view space. Never
* consumes.
*
* [LumosOrb] carries this itself. It is for a consumer who draws [LumosCanvas] directly and wants
* the same plumbing: hand what it reports to the source's `setInput`, and the next frame answers
* it — the cells part when the scene is `interactive`, a gazing form looks, and the frame carries
* the pointer for a material's light.
*
* - **Hover where the platform has it, touch everywhere.** A mouse or stylus reports on `Enter`
* and every `Move`, and `NONE` on `Exit`; a button press does not end the hover, `pressed`
* follows the button. A touch reports on `Press` and `Move` with `pressed = true`, and `NONE` on
* `Release`.
* - **Never a gesture taken from a parent.** The node reads the final pass and consumes nothing,
* so an orb in a scrolling column still scrolls it. A change someone else consumed — a parent's
* scroll past touch slop — reports `NONE`, and the node then waits for every pointer to lift.
* - **No ghost pointer.** When the node leaves composition it reports `NONE`, so no cells stay
* parted around a pointer that is no longer there.
* - A new [onInput] on recomposition is taken up without restarting the handler.
*
* The mapping is the inverse of [link.socket.phosphor.lumos.projection.PixelLattice]'s projection:
* `x = 2·px / w − 1`, `y = 1 − 2·py / h`, with `+y` up, then — for a [tiltDegrees] other than 0 —
* un-tilted onto the front of the unit sphere, `y = sy·cos t + √(max(0, 1 − x² − sy²))·sin t`.
* That is exact on the front surface, and exact everywhere at the default tilt of 0. A point past
* the orb's square is reported as it is: the pointer can stray past the orb.
*
* Each pointer event allocates one [LumosInput] and one [Vector2].
*
* @param tiltDegrees The tilt the orb is projected with, `LumosConfig.tiltDegrees`, so the pointer
* is read on the surface the viewer sees. Must be finite.
* @param onInput Where the pointer is, each time it changes.
*/
fun Modifier.lumosPointer(
tiltDegrees: Float = 0f,
onInput: (LumosInput) -> Unit,
): Modifier {
require(tiltDegrees.isFinite()) { "tiltDegrees must be finite, was $tiltDegrees" }
return this then LumosPointerElement(tiltDegrees, onInput)
}

/**
* A pointer at ([px], [py]) on a node [width] × [height] pixels across, in the orb's view space:
* `[-1, 1]` across the node with `+y` up, un-tilted onto the front of the unit sphere by the tilt
* whose cosine and sine are [cosTilt] and [sinTilt]. See [Modifier.lumosPointer].
*/
internal fun viewSpacePointer(
px: Float,
py: Float,
width: Float,
height: Float,
cosTilt: Float = 1f,
sinTilt: Float = 0f,
): Vector2 {
val x = 2f * px / width - 1f
val sy = 1f - 2f * py / height
if (sinTilt == 0f) return Vector2(x, sy)
val z = sqrt(max(0f, 1f - x * x - sy * sy))
return Vector2(x, sy * cosTilt + z * sinTilt)
}

private data class LumosPointerElement(
val tiltDegrees: Float,
val onInput: (LumosInput) -> Unit,
) : ModifierNodeElement<LumosPointerNode>() {
override fun create(): LumosPointerNode = LumosPointerNode(tiltDegrees, onInput)

override fun update(node: LumosPointerNode) {
node.onInput = onInput
node.tilt(tiltDegrees)
}

override fun InspectorInfo.inspectableProperties() {
name = "lumosPointer"
properties["tiltDegrees"] = tiltDegrees
}
}

private class LumosPointerNode(
tiltDegrees: Float,
var onInput: (LumosInput) -> Unit,
) : DelegatingNode() {
private var tiltDegrees: Float = tiltDegrees
private var cosTilt: Float = cos(tiltDegrees * DEGREES_TO_RADIANS).toFloat()
private var sinTilt: Float = sin(tiltDegrees * DEGREES_TO_RADIANS).toFloat()

init {
delegate(SuspendingPointerInputModifierNode { track() })
}

// The handler reads the tilt on each event, so a new tilt never restarts it.
fun tilt(degrees: Float) {
if (degrees == tiltDegrees) return
tiltDegrees = degrees
cosTilt = cos(degrees * DEGREES_TO_RADIANS).toFloat()
sinTilt = sin(degrees * DEGREES_TO_RADIANS).toFloat()
}

private suspend fun PointerInputScope.track() {
awaitPointerEventScope {
try {
while (true) {
val event = awaitPointerEvent(PointerEventPass.Final)
val change = event.changes.firstOrNull() ?: continue
if (change.isConsumed) {
onInput(LumosInput.NONE)
awaitLift(event)
continue
}
val hovers = change.type == PointerType.Mouse || change.type == PointerType.Stylus
when (event.type) {
PointerEventType.Exit -> onInput(LumosInput.NONE)
PointerEventType.Release -> if (hovers) report(change) else onInput(LumosInput.NONE)
PointerEventType.Enter, PointerEventType.Move, PointerEventType.Press -> report(change)
else -> Unit
}
}
} finally {
onInput(LumosInput.NONE)
}
}
}

// Someone else took the gesture: say nothing more until every pointer has lifted.
private suspend fun AwaitPointerEventScope.awaitLift(consumed: PointerEvent) {
var event = consumed
while (event.changes.any { it.pressed }) event = awaitPointerEvent(PointerEventPass.Final)
}

private fun AwaitPointerEventScope.report(change: PointerInputChange) {
val width = size.width
val height = size.height
if (width <= 0 || height <= 0) return
val position = change.position
val pointer = viewSpacePointer(position.x, position.y, width.toFloat(), height.toFloat(), cosTilt, sinTilt)
onInput(LumosInput(pointer = pointer, pressed = change.pressed))
}

private companion object {
const val DEGREES_TO_RADIANS: Double = PI / 180.0
}
}
Loading
Loading