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
6 changes: 4 additions & 2 deletions ROADMAP.md
Original file line number Diff line number Diff line change
Expand Up @@ -184,8 +184,10 @@ 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).
- 🟠 Send values via a shared ArrayBuffer instead of a fresh `number[]` per frame
(the scene already travels this way; `setValues` still takes `number[]`).
- ✅ 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[])`.
- 🟡 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
64 changes: 64 additions & 0 deletions apps/example/src/imperative.harness.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
// Node handles and shared values: the two ways a scene changes without a React commit.
import React, { useRef } from 'react';
import { View } from 'react-native';
import { describe, expect, render, test } from 'react-native-harness';
import { useSharedValue } from 'react-native-reanimated';
import {
Expand Down Expand Up @@ -248,6 +249,69 @@ describe('tgfx shared values', () => {
expect(sameFrame(unwritten, await stageBytes(0))).toBe(false);
await snapshot('animated-shared-value-written');
});

test('a new shared value set keeps redrawing after the driver rebinds', async () => {
let grow: (() => void) | null = null;
let width: { value: number } | null = null;

function Scene() {
const r = useSharedValue(30);
const w = useSharedValue(40);
const [both, setBoth] = React.useState(false);
grow = () => setBoth(true);
width = w;
return (
<Stage>
<Fill color="white" />
<Circle cx={60} cy={60} r={r} color="#FF9500" />
{both ? (
<Rect x={20} y={120} width={w} height={40} color="#34C759" />
) : null}
</Stage>
);
}

await render(<Scene />);
// A second shared value changes the set, so the driver starts on a new mirror.
grow!();
await sleep(200);
const grown = await stageBytes(0);
width!.value = 160;
await sleep(200);
// Only a push from the new block carries the width slot.
expect(sameFrame(grown, await stageBytes(0))).toBe(false);
});

test('a canvas hidden and shown again keeps animating', async () => {
let hide: ((hidden: boolean) => void) | null = null;
let radius: { value: number } | null = null;

function Scene() {
const r = useSharedValue(30);
const [hidden, setHidden] = React.useState(false);
radius = r;
hide = setHidden;
return (
<View style={{ display: hidden ? 'none' : 'flex' }}>
<Stage>
<Fill color="white" />
<Circle cx={100} cy={100} r={r} color="#5856D6" />
</Stage>
</View>
);
}

await render(<Scene />);
// iOS unmounts a hidden view and recycles it, which drops its value binding.
hide!(true);
await sleep(200);
hide!(false);
await sleep(200);
const shown = await stageBytes(0);
radius!.value = 85;
await sleep(200);
expect(sameFrame(shown, await stageBytes(0))).toBe(false);
});
});

describe('tgfx canvas handle', () => {
Expand Down
21 changes: 21 additions & 0 deletions packages/react-native-tgfx/android/src/main/cpp/TgfxAndroid.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -311,6 +311,27 @@ Java_com_margelo_nitro_tgfx_TgfxNative_setValues(JNIEnv* env, jobject, jlong ptr
view->renderer.setValues(std::move(values));
}

JNIEXPORT void JNICALL
Java_com_margelo_nitro_tgfx_TgfxNative_bindValues(JNIEnv* env, jobject, jlong ptr,
jobject valuesBuffer) {
auto* view = asView(ptr);
if (view == nullptr) {
return;
}
// Read on every push, not copied here: TgfxRenderTarget holds the ArrayBuffer behind it.
auto* values = valuesBuffer != nullptr
? static_cast<const double*>(env->GetDirectBufferAddress(valuesBuffer))
: nullptr;
auto bytes = values != nullptr ? env->GetDirectBufferCapacity(valuesBuffer) : 0;
view->renderer.bindValues(values, bytes > 0 ? static_cast<size_t>(bytes) / sizeof(double) : 0);
}

JNIEXPORT jboolean JNICALL
Java_com_margelo_nitro_tgfx_TgfxNative_pushValues(JNIEnv*, jobject, jlong ptr) {
auto* view = asView(ptr);
return view != nullptr && view->renderer.pushValues() ? JNI_TRUE : JNI_FALSE;
}

JNIEXPORT void JNICALL
Java_com_margelo_nitro_tgfx_TgfxNative_setStringValues(JNIEnv* env, jobject, jlong ptr,
jdoubleArray indexArr,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,14 @@ class HybridTgfxView(private val context: ThemedReactContext) :
target.setValues(values)
}

override fun bindValues(values: ArrayBuffer) {
target.bindValues(values)
}

override fun pushValues(): Boolean {
return target.pushValues()
}

override fun setStringValues(indices: DoubleArray, values: Array<String>) {
target.setStringValues(indices, values)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,12 @@ internal object TgfxNative {
external fun clearScene(ptr: Long)
external fun setOpaque(ptr: Long, opaque: Boolean)
external fun setValues(ptr: Long, values: DoubleArray)

/** [values] is a direct buffer the renderer reads on every [pushValues]; keep it alive until the next bind. */
external fun bindValues(ptr: Long, values: ByteBuffer)

/** False when nothing is bound, so there is nothing to draw. */
external fun pushValues(ptr: Long): Boolean
external fun setStringValues(ptr: Long, indices: DoubleArray, values: Array<String>)

/** True when the viewport moved; an unchanged write must not wake the render thread. */
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import android.os.Process
import android.view.Surface
import android.view.View
import android.view.ViewTreeObserver
import com.margelo.nitro.core.ArrayBuffer
import java.nio.ByteBuffer
import java.util.concurrent.CountDownLatch

Expand Down Expand Up @@ -126,6 +127,28 @@ internal class TgfxRenderTarget {
requestRender()
}

// Guarded by [lock]: the renderer reads these bytes on every push, so the old block goes only after the new bind.
private var boundValues: ArrayBuffer? = null

fun bindValues(values: ArrayBuffer) {
// A JS-owned buffer dies with its runtime while the renderer keeps reading it.
require(values.isOwner) { "[tgfx] bindValues needs a native-owned buffer (a TgfxSlots values block)" }
val bytes = values.getBuffer(false)
withPtr {
TgfxNative.bindValues(it, bytes)
boundValues = values
}
}

fun pushValues(): Boolean {
var pushed = false
withPtr { pushed = TgfxNative.pushValues(it) }
if (pushed) {
requestRender()
}
return pushed
}

fun setStringValues(indices: DoubleArray, values: Array<String>) {
withPtr { TgfxNative.setStringValues(it, indices, values) }
requestRender()
Expand Down
15 changes: 10 additions & 5 deletions packages/react-native-tgfx/cpp/Core/HybridTgfxSlotsFactory.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -17,16 +17,21 @@ namespace margelo::nitro::tgfx {
class HybridTgfxSlots : public HybridTgfxSlotsSpec {
public:
explicit HybridTgfxSlots(size_t size, size_t valueCount, size_t stringCount)
: HybridObject(TAG), bytes_(size, 0), values_(valueCount, 0.0), strings_(stringCount) {}
: HybridObject(TAG),
bytes_(size, 0),
values_(std::make_shared<std::vector<double>>(valueCount, 0.0)),
strings_(stringCount) {}

std::shared_ptr<ArrayBuffer> getFlags() override {
// Borrowed, not owned: this object outlives every view, so a view must not free them.
// Borrowed, not owned: only JS typed-array views read the flags, and they hold this object.
return ArrayBuffer::wrap(bytes_.data(), bytes_.size(), []() {});
}

std::shared_ptr<ArrayBuffer> getValues() override {
return ArrayBuffer::wrap(reinterpret_cast<uint8_t*>(values_.data()), values_.size() * sizeof(double),
[]() {});
// Shared, not borrowed: a canvas binds these for its per-frame push and can outlive this object.
auto values = values_;
return ArrayBuffer::wrap(reinterpret_cast<uint8_t*>(values->data()), values->size() * sizeof(double),
[values]() {});
}

std::string getString(double at) override {
Expand All @@ -45,7 +50,7 @@ class HybridTgfxSlots : public HybridTgfxSlotsSpec {

private:
std::vector<uint8_t> bytes_;
std::vector<double> values_;
std::shared_ptr<std::vector<double>> values_;
std::vector<std::string> strings_;
// Doubles need no lock (an aligned 8-byte store is indivisible); strings do.
std::mutex stringsMutex_;
Expand Down
22 changes: 22 additions & 0 deletions packages/react-native-tgfx/cpp/Render/TgfxRenderer.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -160,6 +160,8 @@ void TgfxRenderer::clearScene() {
viewportZoom_ = 1.0f;
viewportX_ = 0.0f;
viewportY_ = 0.0f;
boundValues_ = nullptr;
boundCount_ = 0;
}
version_.fetch_add(1, std::memory_order_release);
}
Expand All @@ -178,6 +180,26 @@ void TgfxRenderer::setValues(std::vector<double> values) {
version_.fetch_add(1, std::memory_order_release);
}

void TgfxRenderer::bindValues(const double* values, size_t count) {
std::lock_guard<std::mutex> lock(mutex_);
boundValues_ = values;
boundCount_ = values != nullptr ? count : 0;
}

bool TgfxRenderer::pushValues() {
{
std::lock_guard<std::mutex> lock(mutex_);
if (boundValues_ == nullptr) {
return false;
}
// assign reuses values_'s storage, so a steady push allocates nothing.
values_.assign(boundValues_, boundValues_ + boundCount_);
valuesGen_++;
}
version_.fetch_add(1, std::memory_order_release);
return true;
}

void TgfxRenderer::setStringValues(const std::vector<double>& indices,
const std::vector<std::string>& values) {
{
Expand Down
11 changes: 10 additions & 1 deletion packages/react-native-tgfx/cpp/Render/TgfxRenderer.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ class TgfxRenderer {
void setWindow(std::shared_ptr<tgfx::Window> window);

/// Stage a draw program. `words` is copied; `packedStrings` is a delta, see SceneStrings.hpp.
/// With `awaitValues` the program is not drawn until a setValues lands after it: its slot
/// With `awaitValues` the program is not drawn until a value push lands after it: its slot
/// literals are placeholders that the driver's first push completes.
void setScene(std::span<const double> words,
const std::vector<std::string>& packedStrings,
Expand All @@ -63,6 +63,12 @@ class TgfxRenderer {

void setValues(std::vector<double> values);

/// Point pushValues at `count` doubles the caller keeps alive until the next bind or clearScene.
void bindValues(const double* values, size_t count);

/// setValues from the bound block, copied now; false when nothing is bound.
bool pushValues();

/// Sparse writes into the string-slot array (live text and path data).
void setStringValues(const std::vector<double>& indices,
const std::vector<std::string>& values);
Expand Down Expand Up @@ -151,6 +157,9 @@ class TgfxRenderer {
/// The FontRegistry epoch this command list was compiled against; a later face forces a recompile.
uint64_t compiledFontEpoch_ = 0;
std::vector<double> values_;
/// The block pushValues copies into values_, under mutex_; the platform view keeps it alive.
const double* boundValues_ = nullptr;
size_t boundCount_ = 0;
std::vector<double> drawValues_;
std::vector<std::string> stringValues_;
std::vector<std::string> drawStringValues_;
Expand Down
16 changes: 16 additions & 0 deletions packages/react-native-tgfx/ios/HybridTgfxView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ import UIKit
/** iOS `TgfxView`: a thin Swift shell over the Objective-C++ `TgfxMetalView`. */
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?

var view: UIView { metalView }

Expand Down Expand Up @@ -46,6 +48,20 @@ final class HybridTgfxView: HybridTgfxViewSpec, RecyclableView {
}
}

func bindValues(values: ArrayBuffer) throws {
// A JS-owned buffer dies with its runtime while the renderer keeps reading it.
guard values.isOwner else {
throw RuntimeError.error(withMessage: "[tgfx] bindValues needs a native-owned buffer (a TgfxSlots values block)")
}
let slots = UnsafeRawPointer(values.data).assumingMemoryBound(to: Double.self)
metalView.bindValues(slots, count: Int32(values.size / MemoryLayout<Double>.size))
boundValues = values
}

func pushValues() throws -> Bool {
return metalView.pushValues()
}

func setStringValues(indices: [Double], values: [String]) throws {
indices.withUnsafeBufferPointer { buffer in
guard let base = buffer.baseAddress else { return }
Expand Down
3 changes: 3 additions & 0 deletions packages/react-native-tgfx/ios/TgfxMetalView.h
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,9 @@ FOUNDATION_EXPORT void TgfxSnapshotRelease(void* _Nullable token);
- (void)setOpaqueSurface:(BOOL)opaque;

- (void)setValues:(const double*)values count:(int32_t)count;
/// The block `pushValues` copies from; the caller keeps it alive until the next bind.
- (void)bindValues:(const double* _Nullable)values count:(int32_t)count;
- (BOOL)pushValues;
- (void)setStringValues:(const double*)indices
count:(int32_t)count
values:(NSArray<NSString*>*)values;
Expand Down
14 changes: 14 additions & 0 deletions packages/react-native-tgfx/ios/TgfxMetalView.mm
Original file line number Diff line number Diff line change
Expand Up @@ -266,6 +266,20 @@ - (void)setValues:(const double*)values count:(int32_t)count {
[self wakeUp];
}

- (void)bindValues:(const double*)values count:(int32_t)count {
if (_renderer != nullptr) {
_renderer->bindValues(values, count > 0 ? static_cast<size_t>(count) : 0);
}
}

- (BOOL)pushValues {
if (_renderer == nullptr || !_renderer->pushValues()) {
return NO;
}
[self wakeUp];
return YES;
}

- (void)setStringValues:(const double*)indices
count:(int32_t)count
values:(NSArray<NSString*>*)values {
Expand Down

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading
Loading