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
9 changes: 5 additions & 4 deletions ROADMAP.md
Original file line number Diff line number Diff line change
Expand Up @@ -184,10 +184,11 @@ Reducing per-op cost in tgfx's GL backend is where the remaining gap to

- 🟠 Re-subscribe the `useAnimatedReaction` mapper only when the value *set*
changes (currently re-subscribes on every commit due to new array identity).
- ✅ Values travel through a shared ArrayBuffer (#20): the `<Canvas>` driver and a
`Scene`'s mapper bind their mirror block once and copy it natively each frame,
so no `number[]` crosses JSI per frame. Still open: JS-thread `handle.set()`
writes and offscreen surfaces send `setValues(number[])`.
- ✅ Values travel through a shared ArrayBuffer (#20, #24): the `<Canvas>` driver
and a `Scene`'s mapper bind their mirror block once and copy it natively each
frame, and a JS-thread `handle.set()` writes the same block before it pushes,
so no `number[]` crosses JSI. Still open: offscreen surfaces send
`setValues(number[])`.
- 🟡 Examples + tests for gesture-driven (gesture-handler is installed but
unused), `withDecay`, `useDerivedValue`, `useClock`.
- 🟡 Document that animated `rotate`/`skew` expect radians (`'45deg'` strings are
Expand Down
4 changes: 4 additions & 0 deletions packages/react-native-tgfx/ios/HybridTgfxView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ final class HybridTgfxView: HybridTgfxViewSpec, RecyclableView {
private let metalView = TgfxMetalView()
// The renderer reads these bytes on every push, so they are released only by the next bind.
private var boundValues: ArrayBuffer?
// A JS-thread push and the UI-thread driver both bind, so the pointer and its buffer change together.
private let bindLock = NSLock()

var view: UIView { metalView }

Expand Down Expand Up @@ -54,6 +56,8 @@ final class HybridTgfxView: HybridTgfxViewSpec, RecyclableView {
throw RuntimeError.error(withMessage: "[tgfx] bindValues needs a native-owned buffer (a TgfxSlots values block)")
}
let slots = UnsafeRawPointer(values.data).assumingMemoryBound(to: Double.self)
bindLock.lock()
defer { bindLock.unlock() }
metalView.bindValues(slots, count: Int32(values.size / MemoryLayout<Double>.size))
boundValues = values
}
Expand Down
136 changes: 136 additions & 0 deletions packages/react-native-tgfx/src/__tests__/mirror.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -122,3 +122,139 @@ test('with a driver to follow, an unseen mutable is deferred and the program fla
expect(pushed).toEqual([[7]])
expect(x.reads()).toBe(0)
})

/** What a handle holds without Reanimated: a plain slot, read fresh on every push. */
const plainSlot = (value: number) => ({
value,
_isReanimatedSharedValue: true as const,
})

/** A mirror that logs its stores by index, to tell a write-back from an entry left alone. */
function loggedBlock(values: number[], written: boolean) {
const b = block(values, written)
const stores: number[] = []
b.values = new Proxy(b.values, {
set(target, key, value: number) {
stores.push(Number(key))
target[Number(key)] = value
return true
},
})
return { b, stores }
}

const rectAt = (x: unknown, y: unknown = 0): Node[] =>
[
{ type: NodeType.Rect, props: { x, y, width: 1, height: 1 }, children: [] },
] as Node[]

test('a JS-thread push writes its slots into the mirror and hands over the block', () => {
const slot = plainSlot(3)
const arrays: number[][] = []
const container = new TgfxContainer(() => {})
container.onValues = (values) => arrays.push(values.slice())
container.setRootDirect(rectAt(slot))
const mirror = block([0], false)
container.mirror = { values: [slot], block: mirror }
const offered: FlagBlock[] = []
container.onBlock = (b) => {
offered.push(b)
return true
}
slot.value = 8
container.pushValues()
expect(offered).toHaveLength(1)
expect(offered[0]).toBe(mirror)
expect(mirror.values[0]).toBe(8)
expect(arrays).toEqual([])
})

test('a JS-thread push leaves a mutable the driver wrote alone', () => {
const x = shared(5)
const slot = plainSlot(3)
const container = new TgfxContainer(() => {})
container.setRootDirect(rectAt(x.sv, slot))
const { b, stores } = loggedBlock([7, 0], true)
container.mirror = { values: [x.sv, slot], block: b }
container.onBlock = () => true
const before = x.reads()
container.pushValues()
expect(stores).toEqual([1])
expect([b.values[0], b.values[1]]).toEqual([7, 3])
expect(x.reads()).toBe(before)
})

test('before the driver writes the mirror, a JS-thread push stores the literal the program carries', () => {
const x = shared(5)
const container = new TgfxContainer(() => {})
container.setRootDirect(rectAt(x.sv))
const mirror = block([0], false)
container.mirror = { values: [x.sv], block: mirror }
container.onBlock = () => true
container.pushValues()
expect(mirror.values[0]).toBe(5)
expect(x.reads()).toBe(1)
})

test('a target that cannot take the block gets the array instead', () => {
const slot = plainSlot(3)
const arrays: number[][] = []
const container = new TgfxContainer(() => {})
container.onValues = (values) => arrays.push(values.slice())
container.setRootDirect(rectAt(slot))
container.mirror = { values: [slot], block: block([0], false) }
let offered = 0
container.onBlock = () => {
offered++
return false
}
container.pushValues()
expect(offered).toBe(1)
expect(arrays).toEqual([[3]])
})

test('without a mirror block a JS-thread push is an array', () => {
const slot = plainSlot(3)
const arrays: number[][] = []
const container = new TgfxContainer(() => {})
container.onValues = (values) => arrays.push(values.slice())
container.onBlock = () => {
throw new Error('no block to hand over')
}
container.setRootDirect(rectAt(slot))
expect(container.mirror).toBeNull()
container.pushValues()
expect(arrays).toEqual([[3]])
})

/** A handle's block slot: an accessor over shared bytes, plus the boxed block a reader can view itself. */
function blockSlot(value: number) {
const values = new ArrayBuffer(16)
const bytes = new Float64Array(values)
bytes[1] = value
let reads = 0
const slot = {
_isReanimatedSharedValue: true as const,
__tgfxBoxed: { unbox: () => ({ values }) },
__tgfxAt: 1,
get value(): number {
reads++
return bytes[1]!
},
}
return { slot, bytes, reads: () => reads }
}

test('a JS-thread push reads a block slot from its block, not through its accessor', () => {
const b = blockSlot(4)
const container = new TgfxContainer(() => {})
container.setRootDirect(rectAt(b.slot))
const mirror = block([0], false)
container.mirror = { values: [b.slot], block: mirror }
container.onBlock = () => true
b.bytes[1] = 9
const before = b.reads()
container.pushValues()
expect(mirror.values[0]).toBe(9)
expect(b.reads()).toBe(before)
})
55 changes: 51 additions & 4 deletions packages/react-native-tgfx/src/__tests__/scene.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -201,11 +201,13 @@ function mirrorScene(scene: Scene, count: number): ArrayBuffer {
function canvasTarget() {
let bound: ArrayBuffer | null = null
const received: number[][] = []
const binds: ArrayBuffer[] = []
const t: SceneTarget = {
setScene: () => {},
setValues: () => {},
bindValues: (buffer) => {
bound = buffer
binds.push(buffer)
},
pushValues: () => {
if (bound == null) {
Expand All @@ -215,7 +217,7 @@ function canvasTarget() {
return true
},
}
return { t, received, recycle: () => (bound = null) }
return { t, received, binds, recycle: () => (bound = null) }
}

/** A handle scene on a surface (no push) and a canvas, its mapper running on the mirror. */
Expand All @@ -231,7 +233,14 @@ function mirroredHandleScene() {
// Attaching recompiles with the same slots, so the mirror stays and the mapper restarts.
scene.attach(canvas.t)
expect(mappers.size).toBe(1)
return { box, surface, canvas, values, run: [...mappers.values()][0]! }
return {
scene,
box,
surface,
canvas,
values,
run: [...mappers.values()][0]!,
}
}

test('a mirrored mapper has a pushing target copy the block; the rest get the array', () => {
Expand All @@ -251,14 +260,52 @@ test('a mirrored mapper has a pushing target copy the block; the rest get the ar
})

test('a target that lost its binding to a recycle is bound again on the next frame', () => {
const { box, canvas, run } = mirroredHandleScene()
const { canvas, run } = mirroredHandleScene()
run()
canvas.recycle()
box.set({ x: 9 })
run()
expect(canvas.received).toEqual([
[1, 2, 3, 4],
[1, 2, 3, 4],
])
})

test('a JS-thread write has a pushing target copy the block; the rest get the array', () => {
const { box, surface, canvas, values } = mirroredHandleScene()
const before = surface.calls.values.length
box.set({ x: 9 })
expect(canvas.received).toEqual([[9, 2, 3, 4]])
expect(surface.calls.values.slice(before)).toEqual([[9, 2, 3, 4]])
expect(Array.from(new Float64Array(values))).toEqual([9, 2, 3, 4])
})

test('a JS-thread write binds a target once, and again after a recycle', () => {
const { box, canvas, values } = mirroredHandleScene()
box.set({ x: 9 })
box.set({ x: 10 })
canvas.recycle()
box.set({ x: 11 })
expect(canvas.binds).toHaveLength(2)
expect(canvas.binds[0]).toBe(values)
expect(canvas.binds[1]).toBe(values)
expect(canvas.received).toEqual([
[9, 2, 3, 4],
[10, 2, 3, 4],
[11, 2, 3, 4],
])
})

test('a JS-thread write after the mirror is replaced binds the new block', () => {
const { scene, box, canvas, values } = mirroredHandleScene()
box.set({ x: 9 })
const next = mirrorScene(scene, 4)
box.set({ x: 10 })
expect(canvas.binds).toHaveLength(2)
expect(canvas.binds[0]).toBe(values)
expect(canvas.binds[1]).toBe(next)
expect(canvas.received).toEqual([
[9, 2, 3, 4],
[10, 2, 3, 4],
])
})

Expand Down
17 changes: 16 additions & 1 deletion packages/react-native-tgfx/src/components/Canvas.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,11 @@ import { Fill } from './drawings'
import { AnimationDriver } from '../reanimated/AnimationDriver'
import { ViewportDriver } from '../reanimated/ViewportDriver'
import { isLive } from '../reanimated/liveValue'
import type { BoxedSlots } from '../reanimated/slotFlags'
import {
pushBlock,
type BoxedSlots,
type FlagBlock,
} from '../reanimated/slotFlags'
import { TgfxRoot } from '../reconciler/Reconciler'
import { directNodes } from '../reconciler/directNodes'
import { createNode, NodeType } from '../reconciler/types'
Expand Down Expand Up @@ -223,6 +227,8 @@ export function Canvas({
const [view, setView] = useState<TgfxViewRef | null>(null)
const rootRef = useRef<TgfxRoot | null>(null)
const viewRef = useRef<TgfxViewRef | null>(null)
// The mirror block a JS-thread push last bound the view to.
const boundBlock = useRef<FlagBlock | null>(null)
const scene = useRef<{
buffer: ArrayBuffer
strings: string[]
Expand All @@ -239,6 +245,7 @@ export function Canvas({
if (hybridRef.current == null) {
hybridRef.current = callback((ref: TgfxViewRef) => {
viewRef.current = ref
boundBlock.current = null
// Optional: a JS bundle newer than the native binary would otherwise throw here.
ref.setColorSpace?.(colorSpaceRef.current)
// Unconditional: a recycled view resets its viewport in clearScene(), but
Expand Down Expand Up @@ -345,6 +352,14 @@ export function Canvas({
rootRef.current.container.deferReads = AnimationDriver != null
rootRef.current.container.onValues = (vals) =>
viewRef.current?.setValues(vals)
rootRef.current.container.onBlock = (block) => {
const view = viewRef.current
if (view == null) {
return true
}
boundBlock.current = pushBlock(view, block, boundBlock.current)
return boundBlock.current != null
}
rootRef.current.container.onStrings = (indices, vals) =>
viewRef.current?.setStringValues?.(indices, vals)
}
Expand Down
13 changes: 13 additions & 0 deletions packages/react-native-tgfx/src/reanimated/liveValue.ts
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,19 @@ export function readLiveNumber(v: MaybeSharedValue<unknown>): number {
return Number(v.value)
}

/** A block slot's shared bytes and its index in them, for a reader that walks many slots; null for anything else. */
export function blockSource(
v: MaybeSharedValue<unknown>
): { view: Float64Array<ArrayBuffer>; at: number } | null {
'worklet'
const at = (v as Partial<BlockSlot>).__tgfxAt
const boxed = (v as Partial<BlockSlot>).__tgfxBoxed
if (at === undefined || boxed === undefined) {
return null
}
return { view: valuesOf(boxed), at }
}

/** Write a live number wherever it is; worklet-side block writes land in the shared bytes. */
export function writeLiveNumber(v: MaybeSharedValue<unknown>, x: number): void {
'worklet'
Expand Down
26 changes: 26 additions & 0 deletions packages/react-native-tgfx/src/reanimated/slotFlags.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,32 @@ export function makeFlagBlock(
}
}

/** A view or surface that can copy a value block natively instead of taking an array. */
export interface BlockTarget {
bindValues?(values: ArrayBuffer): void
pushValues?(): boolean
}

/** Has `target` copy `block`, binding it when it holds another or a recycle dropped it; null if it cannot. */
export function pushBlock(
target: BlockTarget,
block: FlagBlock,
bound: FlagBlock | null
): FlagBlock | null {
if (target.pushValues == null || target.bindValues == null) {
return null
}
const buffer = block.values.buffer as ArrayBuffer
if (bound !== block) {
target.bindValues(buffer)
}
if (target.pushValues() === false) {
target.bindValues(buffer)
target.pushValues()
}
return block
}

/** This runtime's view of the block, cached on its global: unboxing costs a JSI call. */
export function flagsOf(boxed: BoxedSlots): Uint8Array {
'worklet'
Expand Down
Loading
Loading