Animations are mainly on the typescript side, not kotlin

This commit is contained in:
James Babcock committed 2026-09-23 22:05:06 -07:00
1 parent 063d8a0b03
commit 440674b261
26 files changed
+783 -128

No files matched your search

+84
View File
@@ -0,0 +1,84 @@
# TypeScript display lists
`GrayImage.drawDisplayList(list, x, y, width, height, depth)` retains a list alongside
the image's ordinary pixels. Existing frame submission (`prepareFrameDraws`) and
shell scene submission carry it to Kotlin. Bounds describe its footprint for plane
occlusion; draw coordinates are relative to its placement. Keep the list, its image
resources, and their pixel buffers immutable after submission.
```ts
import { DrawExpression as E } from './draw-expression';
import { DrawOp, type DisplayList } from './display-list';
const list: DisplayList = {
resources: [],
timeline: { token: animationId, startedAt: Date.now() },
calls: [{
op: DrawOp.ROUNDED_RECT,
x: E.progress(300).ease().lerp(E.f32(0), E.f32(100)).toInt(),
y: 0,
width: 40, height: 20, radius: 6,
background: 4, border: 15,
}],
};
frame.drawDisplayList(list, 20, 30, 140, 20, 0);
```
Supported calls in this first pass:
- `ROUNDED_RECT`: literal or expression `x`/`y`, literal dimensions/radius, and
4-bit colors (0–15). Border 16 means no border. Fill takes the maximum of the
background color and existing pixels.
- `IMAGE`: a local resource index, integer `x`/`y`, and `transparent`. Transparent
images skip pixels quantized to zero. Resources have `width`, `height`, and
gray8 `pixels`; a baked `GrayImage` can be used directly.
- `RECT_COPY`: a local resource index, integer source rectangle and destination
`dx`/`dy`. `SCREEN` reads the uncomposed frame; its source coordinates are also
relative to this list's placement. Each call may add its own `depth` to the
list's depth. A screen restore normally uses the negative of the list depth.
Kotlin allocates/cache-pins all image resources, resolves the local indices, applies
surface placement, and includes the calls in the root firmware display list. The
phone's existing display-list renderer consumes the same compiled calls. This uses
the current firmware protocol; no firmware update is needed for this bridge change.
## Expressions and time
`E.i32` and `E.f32` construct typed constants. Builders support arithmetic, min/max,
integer remainder, negation, explicit conversions, lerp, and the easing functions
in `ExprOp`. `ease()` defaults to smoothstep. Integers wrap at 32 bits; float
operations round to f32. The firmware's existing stack/error semantics apply.
Only rounded-rectangle x/y accept expressions in this first pass.
`maximum.time()` returns `min(milliseconds since PRESENT, maximum)`. The existing
45 ms repaint timer remains active while this is below maximum. `E.elapsed()` is
a bridge binding: Kotlin replaces it with the timeline's elapsed milliseconds when
building a new root list. It is a constant within that PRESENT, not a second clock.
`E.progress(durationMs)` combines the two and clamps to 0..1 so intervening frames
and PRESENTs continue an animation instead of restarting it.
Keep `timeline.token` and `timeline.startedAt` stable for an animation; use a new
token when restarting it. JS sends an elapsed duration, so JS and native clocks
need not share an epoch. Fingerprints include the token and expression code but
exclude the changing elapsed duration. Without a timeline, raw `time()` expressions
start at each PRESENT. Native compilation strips the bridge-only elapsed opcode.
`menu-selection-list.ts` authors both the rounded highlight and the transparent row
image using this API. Navigation eligibility, duration, and easing remain in
TypeScript. There is no animated-menu tag or menu animation policy in Kotlin.
## Bridge framing
Tag 7 is followed by a little-endian u32 byte length and a bounded body:
placement (i16 x/y, u16 width/height, i8 depth), timeline (u32 token/elapsed),
u16 resource count, gray8 images (u16 width/height followed by pixels), u16 call
count, then calls. Calls start with the firmware opcode and an i16 relative depth;
operands otherwise use their fixed-width fields, except rounded x/y which use
extended varints. Expressions use the firmware bytecode plus bridge-only
`ELAPSED = 128`. Resource indices are local to this record, never firmware IDs.
Rect-copy source x/y are signed here to permit relative SCREEN coordinates.
Limits: 256 images per record, 64 KiB per packed image, 4 MiB per bridge record,
4096 calls, and 900 input bytes per expression. Native validates the bound program
against the firmware's 1024-byte limit. The combined scene must also fit the
existing resource cache, root-list size, and VM stack limits.
+133
View File
@@ -0,0 +1,133 @@
import { DrawBytes, encodeValue, evaluate, integer, readValue, type DrawValue } from './draw-expression';
/** Local resources are assigned firmware cache IDs by Kotlin. SCREEN reads the uncomposed frame. */
export const SCREEN = 65535;
export const DrawOp = { RECT_COPY: 2, IMAGE: 4, ROUNDED_RECT: 8 } as const;
export const DISPLAY_LIST_RECORD = 7;
export type ListImage = { readonly width: number; readonly height: number; readonly pixels: Uint8Array };
export type ListCall = (
| { op: typeof DrawOp.ROUNDED_RECT; x: DrawValue; y: DrawValue; width: number; height: number; radius: number; background: number; border: number }
| { op: typeof DrawOp.IMAGE; resource: number; x: number; y: number; transparent: boolean }
| { op: typeof DrawOp.RECT_COPY; resource: number; x: number; y: number; width: number; height: number; dx: number; dy: number }
) & { depth?: number };
export type DisplayList = {
readonly resources: readonly ListImage[];
readonly calls: readonly ListCall[];
/** Stable identity plus JS clock origin. Native binds ELAPSED again for each PRESENT. */
/** Set by the decoder: the local PRESENT origin for software replay. */
readonly presentedAt?: number;
readonly timeline?: { readonly token: number; readonly startedAt: number };
};
export type PlacedDisplayList = { displayList: DisplayList; x: number; y: number; width: number; height: number; depth: number };
class Writer {
bytes: number[] = [];
u8(n: number): void { this.bytes.push(integer(n, 0, 255)); }
i8(n: number): void { this.u8(integer(n, -128, 127) & 255); }
u16(n: number): void { integer(n, 0, 65535); this.bytes.push(n & 255, n >>> 8); }
i16(n: number): void { this.u16(integer(n, -32768, 32767) & 65535); }
u32(n: number): void { integer(n, 0, 4294967295); this.u16(n & 65535); this.u16(n >>> 16); }
raw(bytes: ArrayLike<number>): void { for (let i = 0; i < bytes.length; i++) this.bytes.push(bytes[i]); }
}
/** Length-delimited bridge envelope; call operands use fixed widths except extended x/y. */
export function encodeDisplayList(placed: PlacedDisplayList, now = Date.now()): Uint8Array {
const { displayList: list } = placed, out = new Writer();
integer(placed.width, 1, 640); integer(placed.height, 1, 480);
out.i16(placed.x); out.i16(placed.y); out.u16(placed.width); out.u16(placed.height); out.i8(placed.depth);
out.u32(list.timeline?.token ?? 0);
out.u32(list.timeline ? Math.min(2147483647, Math.max(0, Math.trunc(now - list.timeline.startedAt))) : 0);
integer(list.resources.length, 0, 256); out.u16(list.resources.length);
for (const image of list.resources) {
integer(image.width, 1, 640); integer(image.height, 1, 480);
if (image.pixels.length !== image.width * image.height || 5 + Math.ceil(image.width / 2) * image.height > 65536) throw new Error('Invalid display-list image');
out.u16(image.width); out.u16(image.height); out.raw(image.pixels);
}
integer(list.calls.length, 0, 4096); out.u16(list.calls.length);
for (const call of list.calls) {
out.u8(call.op); out.i16(call.depth ?? 0);
integer(placed.depth + (call.depth ?? 0), -128, 127);
if (call.op === DrawOp.ROUNDED_RECT) {
out.raw(encodeValue(call.x)); out.raw(encodeValue(call.y));
out.u16(integer(call.width, 1, 640)); out.u16(integer(call.height, 1, 480)); out.u16(call.radius);
out.u8(integer(call.background, 0, 15)); out.u8(integer(call.border, 0, 16));
} else {
if (call.resource !== SCREEN) integer(call.resource, 0, list.resources.length - 1);
if (call.op === DrawOp.RECT_COPY && call.resource !== SCREEN && (call.x < 0 || call.y < 0)) throw new Error('Negative image source coordinate');
if (call.op === DrawOp.IMAGE && call.resource === SCREEN) throw new Error('Use rectCopy to read SCREEN');
out.u16(call.resource);
if (call.op === DrawOp.IMAGE) { out.i16(call.x); out.i16(call.y); out.u8(call.transparent ? 31 : 15); }
else {
out.i16(call.x); out.i16(call.y); out.u16(integer(call.width, 1, 640)); out.u16(integer(call.height, 1, 480)); out.i16(call.dx); out.i16(call.dy);
}
}
}
if (out.bytes.length > 4 * 1024 * 1024) throw new Error('Display list exceeds bridge limit');
const header = new Writer(); header.u8(DISPLAY_LIST_RECORD); header.u32(out.bytes.length); header.raw(out.bytes);
return Uint8Array.from(header.bytes);
}
export function readDisplayList(bytes: Uint8Array, offset: number, now = Date.now()): { placed: PlacedDisplayList; end: number } {
const envelope = new DrawBytes(bytes.subarray(offset));
if (envelope.u8() !== DISPLAY_LIST_RECORD) throw new Error('Invalid display-list record');
const length = envelope.u32(); integer(length, 0, 4 * 1024 * 1024);
const r = new DrawBytes(envelope.take(length));
const x = r.i16(), y = r.i16(), width = r.u16(), height = r.u16(), depth = r.u8() << 24 >> 24;
const token = r.u32(), elapsed = r.u32(), count = r.u16(); integer(count, 0, 256);
const resources: ListImage[] = [];
for (let i = 0; i < count; i++) { const width = r.u16(), height = r.u16(); resources.push({ width, height, pixels: r.take(width * height) }); }
const calls: ListCall[] = [], callCount = r.u16(); integer(callCount, 0, 4096);
for (let i = 0; i < callCount; i++) {
const op = r.u8(), depth = r.i16();
if (op === DrawOp.ROUNDED_RECT) calls.push({ op, depth, x: readValue(r), y: readValue(r), width: r.u16(), height: r.u16(), radius: r.u16(), background: r.u8(), border: r.u8() });
else if (op === DrawOp.IMAGE) calls.push({ op, depth, resource: r.u16(), x: r.i16(), y: r.i16(), transparent: (r.u8() & 16) !== 0 });
else if (op === DrawOp.RECT_COPY) calls.push({ op, depth, resource: r.u16(), x: r.i16(), y: r.i16(), width: r.u16(), height: r.u16(), dx: r.i16(), dy: r.i16() });
else throw new Error('Unsupported display-list call');
}
if (r.offset !== length) throw new Error('Trailing display-list bytes');
const placed = { x, y, width, height, depth, displayList: { resources, calls, presentedAt: now, timeline: { token, startedAt: now - elapsed } } };
// The writer is also the shared structural validator for software preview records.
encodeDisplayList(placed, now);
return { placed, end: offset + envelope.offset };
}
export function dimDisplayList(list: DisplayList, factor: number): DisplayList {
const dim = (v: number) => v === 0 ? 0 : Math.max(1, Math.round(v * factor));
return { ...list, resources: list.resources.map(r => ({ ...r, pixels: r.pixels.map(dim) })),
calls: list.calls.map(c => c.op === DrawOp.ROUNDED_RECT ? { ...c, background: Math.min(15, Math.round(c.background * factor)), border: c.border === 16 ? 16 : Math.min(15, Math.round(c.border * factor)) } : c) };
}
/** Fallback compositor; native preview and glasses replay the compiled list with their existing timers. */
export function paintDisplayList(output: Uint8Array, screen: Uint8Array, width: number, height: number, placed: PlacedDisplayList, right = false, now = Date.now()): void {
const q = (n: number) => Math.min(15, (n + 8) >> 4) * 16;
const list = placed.displayList;
const elapsed = list.timeline ? Math.max(0, (list.presentedAt ?? now) - list.timeline.startedAt) : 0;
const presentTime = list.presentedAt === undefined ? 0 : Math.max(0, now - list.presentedAt);
const inside = (x: number, y: number, w: number, h: number, radius: number) => {
if (x < 0 || y < 0 || x >= w || y >= h) return false;
const r = Math.min(radius, Math.floor(w / 2), Math.floor(h / 2));
const dx = Math.max(0, 2 * r - (2 * Math.min(x, w - 1 - x) + 1)), dy = Math.max(0, 2 * r - (2 * Math.min(y, h - 1 - y) + 1));
return dx * dx + dy * dy <= 4 * r * r;
};
for (const c of placed.displayList.calls) {
const depth = placed.depth + (c.depth ?? 0), shift = right ? -Math.floor((depth + 1) / 2) : Math.floor(depth / 2);
if (c.op === DrawOp.ROUNDED_RECT) {
const x = placed.x + evaluate(c.x, elapsed, presentTime).value + shift, y = placed.y + evaluate(c.y, elapsed, presentTime).value;
for (let yy = 0; yy < c.height; yy++) for (let xx = 0; xx < c.width; xx++) {
if (x + xx < 0 || y + yy < 0 || x + xx >= width || y + yy >= height || !inside(xx, yy, c.width, c.height, c.radius)) continue;
const p = (y + yy) * width + x + xx;
output[p] = c.border !== 16 && !inside(xx - 1, yy - 1, c.width - 2, c.height - 2, Math.max(0, c.radius - 1)) ? c.border * 16 : Math.max(output[p], c.background * 16);
}
} else {
const source = c.resource === SCREEN ? { width, height, pixels: screen } : placed.displayList.resources[c.resource];
const w = c.op === DrawOp.IMAGE ? source.width : c.width, h = c.op === DrawOp.IMAGE ? source.height : c.height;
const sx = c.op === DrawOp.IMAGE ? 0 : c.x + (c.resource === SCREEN ? placed.x : 0), sy = c.op === DrawOp.IMAGE ? 0 : c.y + (c.resource === SCREEN ? placed.y : 0);
const x = placed.x + (c.op === DrawOp.IMAGE ? c.x : c.dx) + shift, y = placed.y + (c.op === DrawOp.IMAGE ? c.y : c.dy);
for (let yy = 0; yy < h; yy++) for (let xx = 0; xx < w; xx++) {
if (x + xx < 0 || y + yy < 0 || x + xx >= width || y + yy >= height || sx + xx < 0 || sy + yy < 0 || sx + xx >= source.width || sy + yy >= source.height) continue;
const v = q(source.pixels[(sy + yy) * source.width + sx + xx]);
if (c.op !== DrawOp.IMAGE || !c.transparent || v !== 0) output[(y + yy) * width + x + xx] = v;
}
}
}
}
+152
View File
@@ -0,0 +1,152 @@
/** Revision 27 expression bytecode. ELAPSED is a bridge binding, never sent to firmware. */
export const ExprOp = {
I32: 1, F32: 2, DUP: 3, DROP: 4, SWAP: 5,
IADD: 16, ISUB: 17, IMUL: 18, IDIV: 19, IMOD: 20, INEG: 21, IMIN: 22, IMAX: 23,
FADD: 32, FSUB: 33, FMUL: 34, FDIV: 35, FNEG: 36, FMIN: 37, FMAX: 38,
I2F: 48, F2I: 49, TIME: 50, LERP: 64, SMOOTHSTEP: 65,
EASE_IN_QUAD: 66, EASE_OUT_QUAD: 67, EASE_IN_OUT_QUAD: 68,
EASE_IN_CUBIC: 69, EASE_OUT_CUBIC: 70, EASE_IN_OUT_CUBIC: 71,
ELAPSED: 128,
} as const;
export function integer(value: number, min: number, max: number): number {
if (!Number.isInteger(value) || value < min || value > max) throw new Error('Draw integer out of range');
return value;
}
export function varint(value: number, signed = true): number[] {
integer(value, signed ? -2147483648 : 0, signed ? 2147483647 : 4294967295);
const widths = [7, 14, 21, 28, 32], prefixes = [0, 128, 192, 224, 240];
const size = widths.findIndex(bits => bits === 32 || (signed
? value >= -(2 ** (bits - 1)) && value < 2 ** (bits - 1) : value < 2 ** bits)) + 1;
const bytes = [size === 5 ? 240 : prefixes[size - 1] | ((value >>> (8 * (size - 1))) & ((1 << (8 - size)) - 1))];
for (let i = 1; i < size; i++) bytes.push((value >>> (8 * (size - 1 - i))) & 255);
return bytes;
}
export class DrawBytes {
offset = 0;
constructor(readonly bytes: Uint8Array) {}
take(size: number): Uint8Array {
integer(size, 0, this.bytes.length - this.offset);
const result = this.bytes.slice(this.offset, this.offset + size); this.offset += size; return result;
}
u8(): number { return this.take(1)[0]; }
u16(): number { return this.u8() | this.u8() << 8; }
i16(): number { return this.u16() << 16 >> 16; }
u32(): number { return (this.u16() | this.u16() << 16) >>> 0; }
variable(signed = true): number {
const first = this.u8();
const size = first < 128 ? 1 : first < 192 ? 2 : first < 224 ? 3 : first < 240 ? 4 : first === 240 ? 5 : 0;
if (!size) throw new Error('Reserved extended-varint prefix');
let value = size === 5 ? 0 : first & ((1 << (8 - size)) - 1);
for (let i = 1; i < size; i++) value = (value << 8) | this.u8();
const bits = [7, 14, 21, 28, 32][size - 1];
return signed ? bits < 32 ? value << (32 - bits) >> (32 - bits) : value : value >>> 0;
}
}
/** Immutable, typed expression builder; operations use firmware i32/f32 semantics. */
export class DrawExpression<T extends 'i32' | 'f32'> {
private constructor(readonly type: T, readonly code: readonly number[]) {
// Leave room for native elapsed bindings and surface translation.
if (code.length > 900) throw new Error('Draw expression too large');
}
static i32(value: number): DrawExpression<'i32'> { return new DrawExpression('i32', [ExprOp.I32, ...varint(value)]); }
static f32(value: number): DrawExpression<'f32'> {
if (!Number.isFinite(Math.fround(value))) throw new Error('Invalid draw float');
const bytes = new Uint8Array(4); new DataView(bytes.buffer).setFloat32(0, value, true);
return new DrawExpression('f32', [ExprOp.F32, ...bytes]);
}
/** Time already elapsed on this list's timeline when the next PRESENT happens. */
static elapsed(): DrawExpression<'i32'> { return new DrawExpression('i32', [ExprOp.ELAPSED]); }
/** A 0..1 timeline fraction that survives subsequent PRESENT clock resets. */
static progress(durationMs: number): DrawExpression<'f32'> {
const duration = DrawExpression.i32(integer(durationMs, 1, 2147483647));
const elapsed = DrawExpression.elapsed().min(duration);
return duration.sub(elapsed).max(DrawExpression.i32(0)).time()
.add(elapsed).toFloat().div(duration.toFloat());
}
static decode(code: Uint8Array): DrawExpression<'i32'> { return new DrawExpression('i32', Array.from(code)); }
private binary(other: DrawExpression<T>, i: number, f: number): DrawExpression<T> {
if (other.type !== this.type) throw new Error('Draw expression type mismatch');
return new DrawExpression(this.type, [...this.code, ...other.code, this.type === 'i32' ? i : f]);
}
add(b: DrawExpression<T>): DrawExpression<T> { return this.binary(b, ExprOp.IADD, ExprOp.FADD); }
sub(b: DrawExpression<T>): DrawExpression<T> { return this.binary(b, ExprOp.ISUB, ExprOp.FSUB); }
mul(b: DrawExpression<T>): DrawExpression<T> { return this.binary(b, ExprOp.IMUL, ExprOp.FMUL); }
div(b: DrawExpression<T>): DrawExpression<T> { return this.binary(b, ExprOp.IDIV, ExprOp.FDIV); }
min(b: DrawExpression<T>): DrawExpression<T> { return this.binary(b, ExprOp.IMIN, ExprOp.FMIN); }
max(b: DrawExpression<T>): DrawExpression<T> { return this.binary(b, ExprOp.IMAX, ExprOp.FMAX); }
mod(this: DrawExpression<'i32'>, b: DrawExpression<'i32'>): DrawExpression<'i32'> { return this.binary(b, ExprOp.IMOD, ExprOp.IMOD); }
neg(): DrawExpression<T> { return new DrawExpression(this.type, [...this.code, this.type === 'i32' ? ExprOp.INEG : ExprOp.FNEG]); }
toFloat(this: DrawExpression<'i32'>): DrawExpression<'f32'> { return new DrawExpression('f32', [...this.code, ExprOp.I2F]); }
toInt(this: DrawExpression<'f32'>): DrawExpression<'i32'> { return new DrawExpression('i32', [...this.code, ExprOp.F2I]); }
time(this: DrawExpression<'i32'>): DrawExpression<'i32'> { return new DrawExpression('i32', [...this.code, ExprOp.TIME]); }
ease(this: DrawExpression<'f32'>, op: number = ExprOp.SMOOTHSTEP): DrawExpression<'f32'> {
integer(op, ExprOp.SMOOTHSTEP, ExprOp.EASE_IN_OUT_CUBIC);
return new DrawExpression('f32', [...this.code, op]);
}
lerp(this: DrawExpression<'f32'>, from: DrawExpression<'f32'>, to: DrawExpression<'f32'>): DrawExpression<'f32'> {
return new DrawExpression('f32', [...from.code, ...to.code, ...this.code, ExprOp.LERP]);
}
}
export type DrawValue = number | DrawExpression<'i32'>;
export function encodeValue(value: DrawValue): number[] {
return typeof value === 'number' ? varint(value) : [255, ...varint(value.code.length, false), ...value.code];
}
export function readValue(reader: DrawBytes): DrawValue {
if (reader.bytes[reader.offset] !== 255) return reader.variable();
reader.u8(); return DrawExpression.decode(reader.take(reader.variable(false)));
}
/** Software preview of the same VM; invalid programs return zero and discard pending animation. */
export function evaluate(value: DrawValue, elapsed: number, presentTime = 0): { value: number; pending: boolean } {
if (typeof value === 'number') return { value, pending: false };
const reader = new DrawBytes(Uint8Array.from(value.code)), stack: { value: number; float: boolean }[] = [];
let pending = false;
const push = (value: number, float = false) => {
value = float ? Math.fround(value) : value | 0;
if (!Number.isFinite(value) || stack.length === 32) throw new Error('Invalid expression stack');
stack.push({ value, float });
};
const pop = (float: boolean) => { const v = stack.pop(); if (!v || v.float !== float) throw new Error('Expression type mismatch'); return v.value; };
const toInt = (v: number) => { if (v < -2147483648 || v >= 2147483648) throw new Error('Invalid integer conversion'); return Math.trunc(v); };
try {
while (reader.offset < reader.bytes.length) {
const op = reader.u8();
if (op === ExprOp.I32) push(reader.variable());
else if (op === ExprOp.F32) { const b = reader.take(4); push(new DataView(b.buffer).getFloat32(0, true), true); }
else if (op === ExprOp.ELAPSED) push(Math.min(2147483647, Math.max(0, elapsed)));
else if (op === ExprOp.I2F) push(pop(false), true);
else if (op === ExprOp.F2I) push(toInt(pop(true)));
else if (op === ExprOp.TIME) { const max = pop(false); if (max < 0) throw new Error('Invalid time'); const t = Math.min(Math.max(0, presentTime), max); pending ||= t !== max; push(t); }
else if (op === ExprOp.INEG || op === ExprOp.FNEG) push(-pop(op === ExprOp.FNEG), op === ExprOp.FNEG);
else if (op >= ExprOp.IADD && op <= ExprOp.IMAX || op >= ExprOp.FADD && op <= ExprOp.FMAX) {
const float = op >= ExprOp.FADD, b = pop(float), a = pop(float);
const key = float ? op - ExprOp.FADD : op - ExprOp.IADD;
if ((key === 3 || !float && key === 4) && b === 0) throw new Error('Division by zero');
const result = key === 0 ? a + b : key === 1 ? a - b : key === 2 ? float ? a * b : Math.imul(a, b) : key === 3 ? a / b : !float && key === 4 ? a % b : key === (float ? 5 : 6) ? Math.min(a, b) : Math.max(a, b);
push(result, float);
} else if (op === ExprOp.LERP) { const t = pop(true), b = pop(true), a = pop(true); push(a + Math.fround(Math.fround(b - a) * t), true); }
else if (op >= ExprOp.SMOOTHSTEP && op <= ExprOp.EASE_IN_OUT_CUBIC) {
const t = Math.max(0, Math.min(1, pop(true))), u = Math.fround(1 - t), f = Math.fround;
let result: number;
switch (op) {
case ExprOp.SMOOTHSTEP: result = f(t * t) * f(3 - f(2 * t)); break;
case ExprOp.EASE_IN_QUAD: result = t * t; break;
case ExprOp.EASE_OUT_QUAD: result = 1 - f(u * u); break;
case ExprOp.EASE_IN_OUT_QUAD: result = t < .5 ? f(2 * t) * t : 1 - f(f(2 * u) * u); break;
case ExprOp.EASE_IN_CUBIC: result = f(t * t) * t; break;
case ExprOp.EASE_OUT_CUBIC: result = 1 - f(f(u * u) * u); break;
default: result = t < .5 ? f(f(4 * t) * t) * t : 1 - f(f(f(4 * u) * u) * u);
}
push(result, true);
} else if (op === ExprOp.DUP) { const a = stack[stack.length - 1]; if (!a) throw new Error('Underflow'); push(a.value, a.float); }
else if (op === ExprOp.DROP) { if (!stack.pop()) throw new Error('Underflow'); }
else if (op === ExprOp.SWAP) { if (stack.length < 2) throw new Error('Underflow'); const a = stack.pop()!, b = stack.pop()!; stack.push(a, b); }
else throw new Error('Unknown expression opcode');
}
const top = stack.pop(); if (!top) throw new Error('Empty expression');
return { value: top.float ? toInt(top.value) : top.value, pending };
} catch { return { value: 0, pending: false }; }
}
+3 -2
View File
@@ -159,6 +159,7 @@ export function prepareFrameDraws(draws: readonly DeferredDraw[]): ArrayBuffer |
// Pass 1: resolve ids, register unseen rasters, size the buffer.
let registration: Map<FontWireState, RegistrationGroup> | null = null;
const fwRunOk = new Map<PlacedFwText, boolean>();
const presentations = new Map<PlacedImage, Uint8Array>();
let bytes = 0;
for (const placed of draws) {
if (placed.kind === "glyph") {
@@ -177,7 +178,7 @@ export function prepareFrameDraws(draws: readonly DeferredDraw[]): ArrayBuffer |
(placed.glyph.coverage ? group.aaGlyphs : group.glyphs).push(placed.glyph);
} else if (placed.kind === "image") {
if (!inRange16(placed.x) || !inRange16(placed.y)) continue;
if (placed.presentation) bytes += encodePresentation(placed).length;
if (placed.presentation) { const record = encodePresentation(placed); presentations.set(placed, record); bytes += record.length; }
else if (imageId(placed) !== null) bytes += IMAGE_RECORD_BYTES;
} else {
const ok = prepareFwTextRun(placed);
@@ -210,7 +211,7 @@ export function prepareFrameDraws(draws: readonly DeferredDraw[]): ArrayBuffer |
offset += GLYPH_RECORD_BYTES;
} else if (placed.kind === "image") {
if (!inRange16(placed.x) || !inRange16(placed.y)) continue;
if (placed.presentation) { const bytes = encodePresentation(placed); new Uint8Array(out.buffer).set(bytes, offset); offset += bytes.length; continue; }
if (placed.presentation) { const bytes = presentations.get(placed)!; new Uint8Array(out.buffer).set(bytes, offset); offset += bytes.length; continue; }
const id = imageId(placed);
if (id === null) continue;
out.setUint8(offset, DrawRecordKind.TEXTURE_IMAGE);
+21 -5
View File
@@ -1,3 +1,5 @@
import { menuSelectionList } from "./menu-selection-list";
import { encodeDisplayList, dimDisplayList, paintDisplayList, type DisplayList } from "./display-list";
import type { MenuHighlightAnimation } from "../ui/menu-highlight-motion";
import { Glyph } from "./bdffont";
import { wrapText } from "./textwrap";
@@ -74,7 +76,7 @@ export type PlacedGlyph = {
* from the moment it is placed.
*/
export type PlacedImage = {
presentation?: { animation?: MenuHighlightAnimation; mode?: "image" | "masked-image"; radius: number; background: number; border: number; depth: number; occlusions?: readonly { x: number; y: number; width: number; height: number }[] };
presentation?: { displayList?: DisplayList; mode?: "image" | "masked-image"; radius: number; background: number; border: number; depth: number; occlusions?: readonly { x: number; y: number; width: number; height: number }[] };
kind: "image";
source: GrayImage;
x: number;
@@ -395,7 +397,9 @@ export class GrayImage {
hash = mixInt(hash, placed.source.width);
hash = mixInt(hash, placed.source.height);
hash = mixInt(hash, placed.source.sourceContentHash32());
if (placed.presentation) { const p = placed.presentation; for (const value of [p.radius, p.background, p.border, p.depth, p.mode === "image" ? 1 : p.mode === "masked-image" ? 2 : 0, p.animation?.token ?? 0, p.animation?.dx ?? 0, p.animation?.dy ?? 0, p.animation?.durationMs ?? 0]) hash = mixInt(hash, value); }
if (placed.presentation) { const p = placed.presentation; for (const value of [p.radius, p.background, p.border, p.depth, p.mode === "image" ? 1 : p.mode === "masked-image" ? 2 : 0]) hash = mixInt(hash, value);
if (p.displayList) for (const byte of encodeDisplayList({ displayList: p.displayList, x: 0, y: 0, width: placed.source.width, height: placed.source.height, depth: p.depth }, p.displayList.timeline?.startedAt ?? 0)) hash = mixInt(hash, byte);
}
} else {
hash = mixInt(hash, 0xf17e);
hash = mixInt(hash, placed.font.atlasTag);
@@ -508,8 +512,15 @@ export class GrayImage {
/** Retain the selected row separately from the menu surface for glasses-side composition. */
drawMenuSelection(source: GrayImage, x: number, y: number, background: number, border: number, radius = 8, depth = 2, animation?: MenuHighlightAnimation): void {
this.drawList.push({ kind: "image", source: source.withDrawsBaked(), x, y,
presentation: { radius, background, border, depth, animation } });
const baked = source.withDrawsBaked();
this.drawList.push({ kind: "image", source: baked, x, y,
presentation: { radius, background, border, depth, displayList: menuSelectionList(baked, background, border, radius, animation) } });
}
/** Submit a retained list alongside this frame; coordinates are relative to x/y. */
drawDisplayList(displayList: DisplayList, x: number, y: number, width: number, height: number, depth = 0): void {
this.drawList.push({ kind: "image", source: new GrayImage(width, height), x, y,
presentation: { radius: 0, background: 0, border: 0, depth, displayList } });
}
/** Replay an image at stereo depth. Masked images preserve intentional gray8 black (1). */
@@ -570,7 +581,7 @@ export class GrayImage {
for (const placed of this.drawList) {
if (placed.kind === "image" && placed.presentation) {
const p = placed.presentation;
copy.drawList.push({ ...placed, source: placed.source.dimmed(factor), presentation: { ...p, background: dimValue(p.background, scale), border: dimValue(p.border, scale) } });
copy.drawList.push({ ...placed, source: placed.source.dimmed(factor), presentation: { ...p, background: dimValue(p.background, scale), border: dimValue(p.border, scale), displayList: p.displayList && dimDisplayList(p.displayList, factor) } });
} else if (placed.kind !== "image") {
copy.drawList.push({ ...placed, value: dimValue(placed.value, scale) });
}
@@ -613,6 +624,11 @@ export class GrayImage {
} else if (placed.kind === "image") {
if (placed.presentation) {
if (!presentations) continue;
if (placed.presentation.displayList) {
paintDisplayList(target.pixels, target.pixels.slice(), target.width, target.height,
{ displayList: placed.presentation.displayList, x: placed.x + dx, y: placed.y + dy, width: placed.source.width, height: placed.source.height, depth: placed.presentation.depth });
continue;
}
if (placed.presentation.mode) {
target.bitBlt(placed.source, placed.x + dx, placed.y + dy, { transparentZero: true });
continue;
+18
View File
@@ -0,0 +1,18 @@
import type { MenuHighlightAnimation } from '../ui/menu-highlight-motion';
import { DrawExpression as E } from './draw-expression';
import { DrawOp, type DisplayList, type ListImage } from './display-list';
/** Menu policy and easing live in TypeScript; the bridge carries only generic calls/expressions. */
export function menuSelectionList(image: ListImage, background: number, border: number, radius: number, animation?: MenuHighlightAnimation): DisplayList {
const coordinate = (delta: number) => {
if (!animation || !delta) return 0;
const progress = E.progress(animation.durationMs).ease();
return progress.lerp(E.i32(delta).toFloat(), E.f32(0)).toInt();
};
const q = (n: number) => Math.min(15, (n + 8) >> 4);
return { resources: [image], timeline: animation,
calls: [
{ op: DrawOp.ROUNDED_RECT, x: coordinate(animation?.dx ?? 0), y: coordinate(animation?.dy ?? 0), width: image.width, height: image.height, radius, background: q(background), border: q(border) },
{ op: DrawOp.IMAGE, resource: 0, x: 0, y: 0, transparent: true },
] };
}
+22 -28
View File
@@ -1,5 +1,5 @@
import type { PlacedImage } from './image'
import type { MenuHighlightAnimation } from '../ui/menu-highlight-motion'
import { DISPLAY_LIST_RECORD, DrawOp, SCREEN, encodeDisplayList, readDisplayList, paintDisplayList, type DisplayList } from './display-list'
/** TS/native bridge tags, not firmware draw opcodes. Keep in sync with DrawRecordKind.kt. */
export const DrawRecordKind = {
@@ -9,38 +9,36 @@ export const DrawRecordKind = {
MENU_SELECTION: 3,
TRANSPARENT_IMAGE: 4,
MASKED_IMAGE: 5,
ANIMATED_MENU_SELECTION: 6,
DISPLAY_LIST: DISPLAY_LIST_RECORD,
} as const
export function isPresentationKind(kind: number | undefined): boolean {
return kind === DrawRecordKind.MENU_SELECTION || kind === DrawRecordKind.TRANSPARENT_IMAGE ||
kind === DrawRecordKind.MASKED_IMAGE || kind === DrawRecordKind.ANIMATED_MENU_SELECTION
kind === DrawRecordKind.MASKED_IMAGE || kind === DrawRecordKind.DISPLAY_LIST
}
/** Presentation record: tag, signed xy, u16 wh/radius, gray fill/stroke, signed depth, restore-count, optional animation, gray pixels, restore rectangles. */
/** Presentation record: tag, signed xy, u16 wh/radius, gray fill/stroke, signed depth, restore-count, gray pixels, restore rectangles. */
export function encodePresentation(draw: PlacedImage): Uint8Array {
const p = draw.presentation!
const { width, height, pixels } = draw.source
if (width < 1 || height < 1 || width > 640 || height > 480 || 5 + Math.ceil(width / 2) * height > 65536) throw new Error('Presentation image exceeds the resource size limit')
if (width < 1 || height < 1 || width > 640 || height > 480 || !p.displayList && 5 + Math.ceil(width / 2) * height > 65536) throw new Error('Presentation image exceeds the resource size limit')
if (!Number.isInteger(p.depth) || p.depth < -128 || p.depth > 127) throw new Error('Invalid menu depth')
if ((p.occlusions?.length ?? 0) > 2048) throw new Error('Too many menu occlusion rectangles')
const animation = p.animation;
if (animation && (!Number.isInteger(animation.durationMs) || animation.durationMs < 1 || animation.durationMs > 65535)) throw new Error('Invalid menu animation duration')
const header = animation ? 28 : 16;
if (p.displayList) {
const calls = [...p.displayList.calls, ...(p.occlusions ?? []).map(r => ({
op: DrawOp.RECT_COPY, resource: SCREEN, x: r.x - draw.x, y: r.y - draw.y,
width: r.width, height: r.height, dx: r.x - draw.x, dy: r.y - draw.y, depth: -p.depth,
}))];
return encodeDisplayList({ displayList: { ...p.displayList, calls }, x: draw.x, y: draw.y, width, height, depth: p.depth });
}
const header = 16;
const bytes = new Uint8Array(header + width * height + (p.occlusions?.length ?? 0) * 8), view = new DataView(bytes.buffer)
bytes[0] = animation ? DrawRecordKind.ANIMATED_MENU_SELECTION
: p.mode === "image" ? DrawRecordKind.TRANSPARENT_IMAGE
bytes[0] = p.mode === "image" ? DrawRecordKind.TRANSPARENT_IMAGE
: p.mode === "masked-image" ? DrawRecordKind.MASKED_IMAGE : DrawRecordKind.MENU_SELECTION
view.setInt16(1, draw.x, true); view.setInt16(3, draw.y, true)
view.setUint16(5, width, true); view.setUint16(7, height, true); view.setUint16(9, p.radius, true)
bytes[11] = p.background; bytes[12] = p.border; view.setInt8(13, p.depth)
view.setUint16(14, p.occlusions?.length ?? 0, true)
if (animation) {
view.setInt16(16, animation.dx, true); view.setInt16(18, animation.dy, true);
view.setUint16(20, Math.max(0, Math.min(animation.durationMs, Date.now() - animation.startedAt)), true);
view.setUint32(22, animation.token, true);
view.setUint16(26, animation.durationMs, true);
}
bytes.set(pixels, header)
let offset = header + pixels.length
for (const rect of p.occlusions ?? []) {
@@ -50,20 +48,18 @@ export function encodePresentation(draw: PlacedImage): Uint8Array {
return bytes
}
export type Selection = { animation?: MenuHighlightAnimation; mode?: "image" | "masked-image"; x: number; y: number; width: number; height: number; radius: number; background: number; border: number; depth: number; pixels: Uint8Array; occlusions: { x: number; y: number; width: number; height: number }[] }
export type Selection = { displayList?: DisplayList; mode?: "image" | "masked-image"; x: number; y: number; width: number; height: number; radius: number; background: number; border: number; depth: number; pixels: Uint8Array; occlusions: { x: number; y: number; width: number; height: number }[] }
export function readPresentation(bytes: Uint8Array, offset: number): { selection: Selection; end: number } {
if (bytes[offset] === DrawRecordKind.DISPLAY_LIST) {
const { placed, end } = readDisplayList(bytes, offset);
return { selection: { ...placed, radius: 0, background: 0, border: 0, pixels: new Uint8Array(0), occlusions: [] }, end };
}
const v = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength), w = v.getUint16(offset + 5, true), h = v.getUint16(offset + 7, true)
const kind = bytes[offset]
const header = kind === DrawRecordKind.ANIMATED_MENU_SELECTION ? 28 : 16
const header = 16
const selection: Selection = { mode: kind === DrawRecordKind.TRANSPARENT_IMAGE ? "image" : kind === DrawRecordKind.MASKED_IMAGE ? "masked-image" : undefined, x: v.getInt16(offset+1,true), y: v.getInt16(offset+3,true), width:w, height:h,
radius:v.getUint16(offset+9,true), background:bytes[offset+11]!, border:bytes[offset+12]!, depth:v.getInt8(offset+13),
pixels:bytes.slice(offset+header,offset+header+w*h), occlusions:[] }
if (kind === DrawRecordKind.ANIMATED_MENU_SELECTION) {
const durationMs = v.getUint16(offset+26,true), elapsed = v.getUint16(offset+20,true)
if (!durationMs || elapsed > durationMs) throw new Error('Invalid menu animation timing')
selection.animation = { dx:v.getInt16(offset+16,true), dy:v.getInt16(offset+18,true),
startedAt:Date.now()-elapsed, token:v.getUint32(offset+22,true), durationMs }
}
let end=offset+header+w*h
for(let i=0;i<v.getUint16(offset+14,true);i++) { selection.occlusions.push({x:v.getUint16(end,true),y:v.getUint16(end+2,true),width:v.getUint16(end+4,true),height:v.getUint16(end+6,true)});end+=8 }
return {selection,end}
@@ -81,6 +77,7 @@ export function presentationRecords(buffer: ArrayBuffer | null): Selection[] {
return result
}
export function paintPresentation(output: Uint8Array, screen: Uint8Array, width: number, height: number, row: Selection, right = false): void {
if (row.displayList) { paintDisplayList(output, screen, width, height, { ...row, displayList: row.displayList }, right); return; }
const q=(n:number)=>Math.min(15,(n+8)>>4), shift=right?-Math.floor((row.depth+1)/2):Math.floor(row.depth/2)
const inside=(x:number,y:number,w:number,h:number,r:number)=>{
if(x<0||y<0||x>=w||y>=h) return false
@@ -88,10 +85,7 @@ export function paintPresentation(output: Uint8Array, screen: Uint8Array, width:
const dx=Math.max(0,2*r-(2*Math.min(x,w-1-x)+1)),dy=Math.max(0,2*r-(2*Math.min(y,h-1-y)+1))
return dx*dx+dy*dy<=4*r*r
}
const t = row.animation ? Math.max(0, Math.min(1, (Date.now() - row.animation.startedAt) / row.animation.durationMs)) : 1
const remaining = 1 - t * t * (3 - 2 * t)
const highlightX = Math.trunc(row.x + (row.animation?.dx ?? 0) * remaining)
const highlightY = Math.trunc(row.y + (row.animation?.dy ?? 0) * remaining)
const highlightX = row.x, highlightY = row.y
if (!row.mode) for(let yy=0;yy<row.height;yy++) for(let xx=0;xx<row.width;xx++) {
const x=highlightX+xx+shift,y=highlightY+yy
if(x<0||y<0||x>=width||y>=height || !inside(xx,yy,row.width,row.height,row.radius)) continue
+1 -1
View File
@@ -93,7 +93,7 @@ export class SurfaceCompositor {
if(x+xx+shift>=0 && y+yy>=0 && x+xx+shift<this.width && y+yy<this.height) output[(y+yy)*this.width+x+xx+shift]=quantize(bytes[p+yy*w+xx])*16
}
p+=w*h
for(let j=0;j<selections;j++) { const record=readPresentation(bytes,p);p=record.end;if(record.selection.animation) record.selection.animation.startedAt -= Date.now()-this.shellReceivedAt;paintPresentation(output,screen,this.width,this.height,record.selection) }
for(let j=0;j<selections;j++) { const record=readPresentation(bytes,p);p=record.end;if(record.selection.displayList?.timeline) record.selection.displayList = { ...record.selection.displayList, presentedAt: this.shellReceivedAt, timeline: { ...record.selection.displayList.timeline, startedAt: record.selection.displayList.timeline.startedAt - (Date.now()-this.shellReceivedAt) } };paintPresentation(output,screen,this.width,this.height,record.selection) }
}
}
return output