diff --git a/ROADMAP.md b/ROADMAP.md index 2a26ef82..09738a7f 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -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 `` 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 diff --git a/apps/example/src/imperative.harness.tsx b/apps/example/src/imperative.harness.tsx index c28cd2e7..80354eca 100644 --- a/apps/example/src/imperative.harness.tsx +++ b/apps/example/src/imperative.harness.tsx @@ -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 { @@ -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 ( + + + + {both ? ( + + ) : null} + + ); + } + + await render(); + // 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 ( + + ); + } + + await render(); + // 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', () => { diff --git a/packages/react-native-tgfx/android/src/main/cpp/TgfxAndroid.cpp b/packages/react-native-tgfx/android/src/main/cpp/TgfxAndroid.cpp index 3effef5d..53469e15 100644 --- a/packages/react-native-tgfx/android/src/main/cpp/TgfxAndroid.cpp +++ b/packages/react-native-tgfx/android/src/main/cpp/TgfxAndroid.cpp @@ -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(env->GetDirectBufferAddress(valuesBuffer)) + : nullptr; + auto bytes = values != nullptr ? env->GetDirectBufferCapacity(valuesBuffer) : 0; + view->renderer.bindValues(values, bytes > 0 ? static_cast(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, diff --git a/packages/react-native-tgfx/android/src/main/java/com/margelo/nitro/tgfx/HybridTgfxView.kt b/packages/react-native-tgfx/android/src/main/java/com/margelo/nitro/tgfx/HybridTgfxView.kt index 6818de4c..5dc1b493 100644 --- a/packages/react-native-tgfx/android/src/main/java/com/margelo/nitro/tgfx/HybridTgfxView.kt +++ b/packages/react-native-tgfx/android/src/main/java/com/margelo/nitro/tgfx/HybridTgfxView.kt @@ -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) { target.setStringValues(indices, values) } diff --git a/packages/react-native-tgfx/android/src/main/java/com/margelo/nitro/tgfx/TgfxNative.kt b/packages/react-native-tgfx/android/src/main/java/com/margelo/nitro/tgfx/TgfxNative.kt index 3daaab85..6d9ab7bb 100644 --- a/packages/react-native-tgfx/android/src/main/java/com/margelo/nitro/tgfx/TgfxNative.kt +++ b/packages/react-native-tgfx/android/src/main/java/com/margelo/nitro/tgfx/TgfxNative.kt @@ -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) /** True when the viewport moved; an unchanged write must not wake the render thread. */ diff --git a/packages/react-native-tgfx/android/src/main/java/com/margelo/nitro/tgfx/TgfxRenderTarget.kt b/packages/react-native-tgfx/android/src/main/java/com/margelo/nitro/tgfx/TgfxRenderTarget.kt index ee182ff6..380416b7 100644 --- a/packages/react-native-tgfx/android/src/main/java/com/margelo/nitro/tgfx/TgfxRenderTarget.kt +++ b/packages/react-native-tgfx/android/src/main/java/com/margelo/nitro/tgfx/TgfxRenderTarget.kt @@ -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 @@ -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) { withPtr { TgfxNative.setStringValues(it, indices, values) } requestRender() diff --git a/packages/react-native-tgfx/cpp/Core/HybridTgfxSlotsFactory.hpp b/packages/react-native-tgfx/cpp/Core/HybridTgfxSlotsFactory.hpp index 07565d6c..bfa692b5 100644 --- a/packages/react-native-tgfx/cpp/Core/HybridTgfxSlotsFactory.hpp +++ b/packages/react-native-tgfx/cpp/Core/HybridTgfxSlotsFactory.hpp @@ -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>(valueCount, 0.0)), + strings_(stringCount) {} std::shared_ptr 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 getValues() override { - return ArrayBuffer::wrap(reinterpret_cast(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(values->data()), values->size() * sizeof(double), + [values]() {}); } std::string getString(double at) override { @@ -45,7 +50,7 @@ class HybridTgfxSlots : public HybridTgfxSlotsSpec { private: std::vector bytes_; - std::vector values_; + std::shared_ptr> values_; std::vector strings_; // Doubles need no lock (an aligned 8-byte store is indivisible); strings do. std::mutex stringsMutex_; diff --git a/packages/react-native-tgfx/cpp/Render/TgfxRenderer.cpp b/packages/react-native-tgfx/cpp/Render/TgfxRenderer.cpp index 1b470a78..c8ee4386 100644 --- a/packages/react-native-tgfx/cpp/Render/TgfxRenderer.cpp +++ b/packages/react-native-tgfx/cpp/Render/TgfxRenderer.cpp @@ -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); } @@ -178,6 +180,26 @@ void TgfxRenderer::setValues(std::vector values) { version_.fetch_add(1, std::memory_order_release); } +void TgfxRenderer::bindValues(const double* values, size_t count) { + std::lock_guard lock(mutex_); + boundValues_ = values; + boundCount_ = values != nullptr ? count : 0; +} + +bool TgfxRenderer::pushValues() { + { + std::lock_guard 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& indices, const std::vector& values) { { diff --git a/packages/react-native-tgfx/cpp/Render/TgfxRenderer.hpp b/packages/react-native-tgfx/cpp/Render/TgfxRenderer.hpp index 277d0bdd..0b647bcd 100644 --- a/packages/react-native-tgfx/cpp/Render/TgfxRenderer.hpp +++ b/packages/react-native-tgfx/cpp/Render/TgfxRenderer.hpp @@ -51,7 +51,7 @@ class TgfxRenderer { void setWindow(std::shared_ptr 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 words, const std::vector& packedStrings, @@ -63,6 +63,12 @@ class TgfxRenderer { void setValues(std::vector 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& indices, const std::vector& values); @@ -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 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 drawValues_; std::vector stringValues_; std::vector drawStringValues_; diff --git a/packages/react-native-tgfx/ios/HybridTgfxView.swift b/packages/react-native-tgfx/ios/HybridTgfxView.swift index 39803235..53e43ce3 100644 --- a/packages/react-native-tgfx/ios/HybridTgfxView.swift +++ b/packages/react-native-tgfx/ios/HybridTgfxView.swift @@ -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 } @@ -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.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 } diff --git a/packages/react-native-tgfx/ios/TgfxMetalView.h b/packages/react-native-tgfx/ios/TgfxMetalView.h index f6074666..f2a67eb1 100644 --- a/packages/react-native-tgfx/ios/TgfxMetalView.h +++ b/packages/react-native-tgfx/ios/TgfxMetalView.h @@ -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*)values; diff --git a/packages/react-native-tgfx/ios/TgfxMetalView.mm b/packages/react-native-tgfx/ios/TgfxMetalView.mm index eacb8f2d..7d9799f9 100644 --- a/packages/react-native-tgfx/ios/TgfxMetalView.mm +++ b/packages/react-native-tgfx/ios/TgfxMetalView.mm @@ -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(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*)values { diff --git a/packages/react-native-tgfx/nitrogen/generated/android/c++/JHybridTgfxViewSpec.cpp b/packages/react-native-tgfx/nitrogen/generated/android/c++/JHybridTgfxViewSpec.cpp index 1bc39ed3..d6b8a5dd 100644 --- a/packages/react-native-tgfx/nitrogen/generated/android/c++/JHybridTgfxViewSpec.cpp +++ b/packages/react-native-tgfx/nitrogen/generated/android/c++/JHybridTgfxViewSpec.cpp @@ -101,6 +101,15 @@ namespace margelo::nitro::tgfx { return __array; }()); } + void JHybridTgfxViewSpec::bindValues(const std::shared_ptr& values) { + static const auto method = _javaPart->javaClassStatic()->getMethod /* values */)>("bindValues"); + method(_javaPart, JArrayBuffer::wrap(values)); + } + bool JHybridTgfxViewSpec::pushValues() { + static const auto method = _javaPart->javaClassStatic()->getMethod("pushValues"); + auto __result = method(_javaPart); + return static_cast(__result); + } void JHybridTgfxViewSpec::setStringValues(const std::vector& indices, const std::vector& values) { static const auto method = _javaPart->javaClassStatic()->getMethod /* indices */, jni::alias_ref> /* values */)>("setStringValues"); method(_javaPart, [&]() { diff --git a/packages/react-native-tgfx/nitrogen/generated/android/c++/JHybridTgfxViewSpec.hpp b/packages/react-native-tgfx/nitrogen/generated/android/c++/JHybridTgfxViewSpec.hpp index 82932d36..966f84f9 100644 --- a/packages/react-native-tgfx/nitrogen/generated/android/c++/JHybridTgfxViewSpec.hpp +++ b/packages/react-native-tgfx/nitrogen/generated/android/c++/JHybridTgfxViewSpec.hpp @@ -60,6 +60,8 @@ namespace margelo::nitro::tgfx { void setScene(const std::shared_ptr& scene, const std::vector& strings, std::optional awaitValues) override; void invalidate() override; void setValues(const std::vector& values) override; + void bindValues(const std::shared_ptr& values) override; + bool pushValues() override; void setStringValues(const std::vector& indices, const std::vector& values) override; void setViewport(const std::vector& viewport) override; void setColorSpace(const std::string& colorSpace) override; diff --git a/packages/react-native-tgfx/nitrogen/generated/android/kotlin/com/margelo/nitro/tgfx/HybridTgfxViewSpec.kt b/packages/react-native-tgfx/nitrogen/generated/android/kotlin/com/margelo/nitro/tgfx/HybridTgfxViewSpec.kt index cf7ff8fc..eddef428 100644 --- a/packages/react-native-tgfx/nitrogen/generated/android/kotlin/com/margelo/nitro/tgfx/HybridTgfxViewSpec.kt +++ b/packages/react-native-tgfx/nitrogen/generated/android/kotlin/com/margelo/nitro/tgfx/HybridTgfxViewSpec.kt @@ -53,6 +53,14 @@ abstract class HybridTgfxViewSpec: HybridView() { @Keep abstract fun setValues(values: DoubleArray): Unit + @DoNotStrip + @Keep + abstract fun bindValues(values: ArrayBuffer): Unit + + @DoNotStrip + @Keep + abstract fun pushValues(): Boolean + @DoNotStrip @Keep abstract fun setStringValues(indices: DoubleArray, values: Array): Unit diff --git a/packages/react-native-tgfx/nitrogen/generated/ios/NitroTgfx-Swift-Cxx-Bridge.hpp b/packages/react-native-tgfx/nitrogen/generated/ios/NitroTgfx-Swift-Cxx-Bridge.hpp index fc35db56..d22fc0e2 100644 --- a/packages/react-native-tgfx/nitrogen/generated/ios/NitroTgfx-Swift-Cxx-Bridge.hpp +++ b/packages/react-native-tgfx/nitrogen/generated/ios/NitroTgfx-Swift-Cxx-Bridge.hpp @@ -274,6 +274,15 @@ namespace margelo::nitro::tgfx::bridge::swift { using std__weak_ptr_HybridTgfxViewSpec_ = std::weak_ptr; inline std__weak_ptr_HybridTgfxViewSpec_ weakify_std__shared_ptr_HybridTgfxViewSpec_(const std::shared_ptr& strong) noexcept { return strong; } + // pragma MARK: Result + using Result_bool_ = Result; + inline Result_bool_ create_Result_bool_(bool value) noexcept { + return Result::withValue(std::move(value)); + } + inline Result_bool_ create_Result_bool_(const std::exception_ptr& error) noexcept { + return Result::withError(error); + } + // pragma MARK: Result> using Result_std__vector_double__ = Result>; inline Result_std__vector_double__ create_Result_std__vector_double__(const std::vector& value) noexcept { diff --git a/packages/react-native-tgfx/nitrogen/generated/ios/c++/HybridTgfxViewSpecSwift.hpp b/packages/react-native-tgfx/nitrogen/generated/ios/c++/HybridTgfxViewSpecSwift.hpp index 83e5d901..1f3c519b 100644 --- a/packages/react-native-tgfx/nitrogen/generated/ios/c++/HybridTgfxViewSpecSwift.hpp +++ b/packages/react-native-tgfx/nitrogen/generated/ios/c++/HybridTgfxViewSpecSwift.hpp @@ -107,6 +107,20 @@ namespace margelo::nitro::tgfx { std::rethrow_exception(__result.error()); } } + inline void bindValues(const std::shared_ptr& values) override { + auto __result = _swiftPart.bindValues(ArrayBufferHolder(values)); + if (__result.hasError()) [[unlikely]] { + std::rethrow_exception(__result.error()); + } + } + inline bool pushValues() override { + auto __result = _swiftPart.pushValues(); + if (__result.hasError()) [[unlikely]] { + std::rethrow_exception(__result.error()); + } + auto __value = std::move(__result.value()); + return __value; + } inline void setStringValues(const std::vector& indices, const std::vector& values) override { auto __result = _swiftPart.setStringValues(indices, values); if (__result.hasError()) [[unlikely]] { diff --git a/packages/react-native-tgfx/nitrogen/generated/ios/swift/HybridTgfxViewSpec.swift b/packages/react-native-tgfx/nitrogen/generated/ios/swift/HybridTgfxViewSpec.swift index 8cf972b6..2f1d78d9 100644 --- a/packages/react-native-tgfx/nitrogen/generated/ios/swift/HybridTgfxViewSpec.swift +++ b/packages/react-native-tgfx/nitrogen/generated/ios/swift/HybridTgfxViewSpec.swift @@ -17,6 +17,8 @@ public protocol HybridTgfxViewSpec_protocol: HybridObject, HybridView { func setScene(scene: ArrayBuffer, strings: [String], awaitValues: Bool?) throws -> Void func invalidate() throws -> Void func setValues(values: [Double]) throws -> Void + func bindValues(values: ArrayBuffer) throws -> Void + func pushValues() throws -> Bool func setStringValues(indices: [Double], values: [String]) throws -> Void func setViewport(viewport: [Double]) throws -> Void func setColorSpace(colorSpace: String) throws -> Void diff --git a/packages/react-native-tgfx/nitrogen/generated/ios/swift/HybridTgfxViewSpec_cxx.swift b/packages/react-native-tgfx/nitrogen/generated/ios/swift/HybridTgfxViewSpec_cxx.swift index 315c0de1..ea5f37a5 100644 --- a/packages/react-native-tgfx/nitrogen/generated/ios/swift/HybridTgfxViewSpec_cxx.swift +++ b/packages/react-native-tgfx/nitrogen/generated/ios/swift/HybridTgfxViewSpec_cxx.swift @@ -184,6 +184,29 @@ open class HybridTgfxViewSpec_cxx { } } + @inline(__always) + public final func bindValues(values: ArrayBuffer) -> bridge.Result_void_ { + do { + try self.__implementation.bindValues(values: values) + return bridge.create_Result_void_() + } catch (let __error) { + let __exceptionPtr = __error.toCpp() + return bridge.create_Result_void_(__exceptionPtr) + } + } + + @inline(__always) + public final func pushValues() -> bridge.Result_bool_ { + do { + let __result = try self.__implementation.pushValues() + let __resultCpp = __result + return bridge.create_Result_bool_(__resultCpp) + } catch (let __error) { + let __exceptionPtr = __error.toCpp() + return bridge.create_Result_bool_(__exceptionPtr) + } + } + @inline(__always) public final func setStringValues(indices: bridge.std__vector_double_, values: bridge.std__vector_std__string_) -> bridge.Result_void_ { do { diff --git a/packages/react-native-tgfx/nitrogen/generated/shared/c++/HybridTgfxViewSpec.cpp b/packages/react-native-tgfx/nitrogen/generated/shared/c++/HybridTgfxViewSpec.cpp index 63f4dfbc..8d4b63a8 100644 --- a/packages/react-native-tgfx/nitrogen/generated/shared/c++/HybridTgfxViewSpec.cpp +++ b/packages/react-native-tgfx/nitrogen/generated/shared/c++/HybridTgfxViewSpec.cpp @@ -21,6 +21,8 @@ namespace margelo::nitro::tgfx { prototype.registerHybridMethod("setScene", &HybridTgfxViewSpec::setScene); prototype.registerHybridMethod("invalidate", &HybridTgfxViewSpec::invalidate); prototype.registerHybridMethod("setValues", &HybridTgfxViewSpec::setValues); + prototype.registerHybridMethod("bindValues", &HybridTgfxViewSpec::bindValues); + prototype.registerHybridMethod("pushValues", &HybridTgfxViewSpec::pushValues); prototype.registerHybridMethod("setStringValues", &HybridTgfxViewSpec::setStringValues); prototype.registerHybridMethod("setViewport", &HybridTgfxViewSpec::setViewport); prototype.registerHybridMethod("setColorSpace", &HybridTgfxViewSpec::setColorSpace); diff --git a/packages/react-native-tgfx/nitrogen/generated/shared/c++/HybridTgfxViewSpec.hpp b/packages/react-native-tgfx/nitrogen/generated/shared/c++/HybridTgfxViewSpec.hpp index c7ac0134..45a09686 100644 --- a/packages/react-native-tgfx/nitrogen/generated/shared/c++/HybridTgfxViewSpec.hpp +++ b/packages/react-native-tgfx/nitrogen/generated/shared/c++/HybridTgfxViewSpec.hpp @@ -63,6 +63,8 @@ namespace margelo::nitro::tgfx { virtual void setScene(const std::shared_ptr& scene, const std::vector& strings, std::optional awaitValues) = 0; virtual void invalidate() = 0; virtual void setValues(const std::vector& values) = 0; + virtual void bindValues(const std::shared_ptr& values) = 0; + virtual bool pushValues() = 0; virtual void setStringValues(const std::vector& indices, const std::vector& values) = 0; virtual void setViewport(const std::vector& viewport) = 0; virtual void setColorSpace(const std::string& colorSpace) = 0; diff --git a/packages/react-native-tgfx/src/__tests__/AnimationDriver.test.ts b/packages/react-native-tgfx/src/__tests__/AnimationDriver.test.ts index 30686fd7..c4f9659b 100644 --- a/packages/react-native-tgfx/src/__tests__/AnimationDriver.test.ts +++ b/packages/react-native-tgfx/src/__tests__/AnimationDriver.test.ts @@ -1,4 +1,9 @@ import { expect, mock, test } from 'bun:test' +import { createElement } from 'react' +import TestRenderer, { act } from 'react-test-renderer' +;( + globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean } +).IS_REACT_ACT_ENVIRONMENT = true // A renamed export must not look like an absent package, and it throws where the driver renders. test('Reanimated present but missing an export throws on render', async () => { @@ -10,3 +15,158 @@ test('Reanimated present but missing an export throws on render', async () => { /does not export startMapper/ ) }) + +/** A driver whose live mappers all run when the test calls `frame()`, as Reanimated's would. */ +async function driverWithFrames() { + const mappers = new Map void>() + let next = 1 + mock.module('react-native-reanimated', () => ({ + startMapper: (worklet: () => void) => { + mappers.set(next, worklet) + return next++ + }, + stopMapper: (id: number) => mappers.delete(id), + })) + const { AnimationDriver } = + (await import('../reanimated/AnimationDriver?frames')) as typeof import('../reanimated/AnimationDriver') + return { + Driver: AnimationDriver!, + frame: () => { + for (const run of mappers.values()) { + run() + } + }, + } +} + +/** The native contract: a bind keeps the buffer, a push copies it now, and a recycle unbinds. */ +function nativeView() { + let bound: ArrayBuffer | null = null + const received: number[][] = [] + const arrays: number[][] = [] + return { + received, + arrays, + recycle: () => { + bound = null + }, + setValues: (values: number[]) => { + arrays.push(values.slice()) + }, + bindValues: (values: ArrayBuffer) => { + bound = values + }, + pushValues: () => { + if (bound == null) { + return false + } + received.push(Array.from(new Float64Array(bound))) + return true + }, + } +} + +const shared = (value: number) => ({ + value, + _isReanimatedSharedValue: true as const, +}) + +/** A mirror block as the driver sees it: boxed, unboxing to the slots' buffers. */ +function block(count: number) { + const values = new ArrayBuffer(count * 8) + const flags = new ArrayBuffer(1) + return { values, flags, boxed: { unbox: () => ({ flags, values }) } } +} + +function driverProps( + view: object, + values: object[], + mirror: { boxed: object } | null +) { + return { + view, + values, + strings: [], + gens: [], + mirror: mirror?.boxed ?? null, + } as never +} + +test('each frame the view copies that frame values from the mirror', async () => { + const { Driver, frame } = await driverWithFrames() + const mirror = block(2) + const view = nativeView() + const x = shared(3) + act(() => { + TestRenderer.create( + createElement(Driver, driverProps(view, [x, shared(4)], mirror)) + ) + }) + frame() + x.value = 5 + frame() + expect(view.received).toEqual([ + [3, 4], + [5, 4], + ]) + expect(view.arrays).toEqual([]) + expect(new Uint8Array(mirror.flags)[0]).toBe(1) +}) + +test('a new value set binds its own mirror before its first push', async () => { + const { Driver, frame } = await driverWithFrames() + const view = nativeView() + const x = shared(1) + let tree: TestRenderer.ReactTestRenderer | null = null + act(() => { + tree = TestRenderer.create( + createElement(Driver, driverProps(view, [x], block(1))) + ) + }) + frame() + act(() => { + tree!.update( + createElement(Driver, driverProps(view, [x, shared(20)], block(2))) + ) + }) + frame() + expect(view.received).toEqual([[1], [1, 20]]) +}) + +test('a view that lost its binding to a recycle is bound again on the next frame', async () => { + const { Driver, frame } = await driverWithFrames() + const view = nativeView() + const x = shared(1) + act(() => { + TestRenderer.create(createElement(Driver, driverProps(view, [x], block(1)))) + }) + frame() + view.recycle() + x.value = 2 + frame() + expect(view.received).toEqual([[1], [2]]) +}) + +test('a native view without pushValues, or no mirror, still gets the slot array', async () => { + const { Driver, frame } = await driverWithFrames() + const pushed: number[][] = [] + const older = { setValues: (values: number[]) => pushed.push(values.slice()) } + let first: TestRenderer.ReactTestRenderer | null = null + act(() => { + first = TestRenderer.create( + createElement(Driver, driverProps(older, [shared(3)], block(1))) + ) + }) + frame() + act(() => { + first!.unmount() + }) + const unmirrored = { ...nativeView(), setValues: older.setValues } + act(() => { + TestRenderer.create( + createElement(Driver, driverProps(unmirrored, [shared(7)], null)) + ) + }) + frame() + expect(pushed).toEqual([[3], [7]]) +}) diff --git a/packages/react-native-tgfx/src/__tests__/scene.test.ts b/packages/react-native-tgfx/src/__tests__/scene.test.ts index cd6c9f2b..3145c0f8 100644 --- a/packages/react-native-tgfx/src/__tests__/scene.test.ts +++ b/packages/react-native-tgfx/src/__tests__/scene.test.ts @@ -177,6 +177,91 @@ test('a scene runs its own mapper so handle writes land without a driver', () => expect(mappers.size).toBe(0) // no targets left, nothing to push to }) +/** The test runner has no Nitro, so stand in for the mirror block the container would make. */ +function mirrorScene(scene: Scene, count: number): ArrayBuffer { + const values = new ArrayBuffer(count * 8) + const flags = new ArrayBuffer(1) + const internals = scene as unknown as { + container: { mirror: unknown } + lastValues: unknown[] + } + internals.container.mirror = { + values: internals.lastValues.slice(), + block: { + bytes: new Uint8Array(flags), + values: new Float64Array(values), + slots: {}, + boxed: { unbox: () => ({ flags, values }) }, + }, + } + return values +} + +/** A canvas as native behaves: a bind keeps the buffer, a push copies it now, and a recycle unbinds. */ +function canvasTarget() { + let bound: ArrayBuffer | null = null + const received: number[][] = [] + const t: SceneTarget = { + setScene: () => {}, + setValues: () => {}, + bindValues: (buffer) => { + bound = buffer + }, + pushValues: () => { + if (bound == null) { + return false + } + received.push(Array.from(new Float64Array(bound))) + return true + }, + } + return { t, received, recycle: () => (bound = null) } +} + +/** A handle scene on a surface (no push) and a canvas, its mapper running on the mirror. */ +function mirroredHandleScene() { + const scene = Scene.create() + const box = createHandle() + scene.add(rect({ ref: box, x: 1, y: 2, width: 3, height: 4 })) + const surface = target() + scene.attach(surface.t) + scene.flush() + const values = mirrorScene(scene, 4) + const canvas = canvasTarget() + // 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]! } +} + +test('a mirrored mapper has a pushing target copy the block; the rest get the array', () => { + const { surface, canvas, values, run } = mirroredHandleScene() + const before = surface.calls.values.length + run() + run() + expect(canvas.received).toEqual([ + [1, 2, 3, 4], + [1, 2, 3, 4], + ]) + expect(surface.calls.values.slice(before)).toEqual([ + [1, 2, 3, 4], + [1, 2, 3, 4], + ]) + expect(Array.from(new Float64Array(values))).toEqual([1, 2, 3, 4]) +}) + +test('a target that lost its binding to a recycle is bound again on the next frame', () => { + const { box, canvas, run } = mirroredHandleScene() + run() + canvas.recycle() + box.set({ x: 9 }) + run() + expect(canvas.received).toEqual([ + [1, 2, 3, 4], + [9, 2, 3, 4], + ]) +}) + test('dispose stops the mapper', () => { const { t } = target() const scene = Scene.create() diff --git a/packages/react-native-tgfx/src/imperative.ts b/packages/react-native-tgfx/src/imperative.ts index 9f6a9c5b..44497841 100644 --- a/packages/react-native-tgfx/src/imperative.ts +++ b/packages/react-native-tgfx/src/imperative.ts @@ -166,8 +166,8 @@ export interface NodeOwner { * box.set({ x: 120 }) * ``` * - * A prop the program keeps a value slot for is patched in place: one - * `setValues`, no re-encode, and it works **inside a worklet**, so a gesture can + * A prop the program keeps a value slot for is patched in place: one value + * push, no re-encode, and it works **inside a worklet**, so a gesture can * drive it without ever waking the JS thread. That covers the geometry props * (`x`, `y`, `width`, `height`, `cx`, `cy`, `r`, `rx`, `ry`, `x1`, `y1`, `x2`, * `y2`), `strokeWidth`, `strokeMiter`, `opacity`, `fontSize`, `visible`, diff --git a/packages/react-native-tgfx/src/reanimated/AnimationDriver.tsx b/packages/react-native-tgfx/src/reanimated/AnimationDriver.tsx index 5179d8dd..8b9bfcb0 100644 --- a/packages/react-native-tgfx/src/reanimated/AnimationDriver.tsx +++ b/packages/react-native-tgfx/src/reanimated/AnimationDriver.tsx @@ -26,6 +26,8 @@ function Driver({ view, values, strings, gens, mirror }: DriverProps): null { const slots = new Array(values.length) // Last pushed per string slot: only changes cross, so an idle frame is free. const sent = new Array(strings.length).fill(null) + // Set once this mapper has bound its mirror, from the thread that writes it. + const bound = [false] // A block slot cannot be a mapper input; the handle's gen stands in for it. const listenable = [...values, ...strings].filter((v) => !isBlockSlot(v)) for (const gen of gens) { @@ -37,9 +39,13 @@ function Driver({ view, values, strings, gens, mirror }: DriverProps): null { const mapperId = start(() => { 'worklet' const mirrored = mirror != null ? valuesOf(mirror) : null + // The view copies the mirror natively, so no array is marshalled. Optional: an older binary lacks it. + const direct = mirrored != null && view.pushValues != null for (let i = 0; i < values.length; i++) { const v = readLiveNumber(values[i]!) - slots[i] = v + if (!direct) { + slots[i] = v + } if (mirrored != null) { mirrored[i] = v } @@ -47,7 +53,19 @@ function Driver({ view, values, strings, gens, mirror }: DriverProps): null { if (mirror != null) { flagsOf(mirror)[0] = 1 } - view.setValues(slots) + if (direct) { + if (!bound[0]) { + view.bindValues(mirrored.buffer) + bound[0] = true + } + // A recycled view comes back unbound (iOS unmounts a hidden one), so bind again. + if (view.pushValues() === false) { + view.bindValues(mirrored.buffer) + view.pushValues() + } + } else { + view.setValues(slots) + } if (strings.length > 0) { let indices: number[] | null = null let out: string[] | null = null diff --git a/packages/react-native-tgfx/src/reanimated/liveValue.ts b/packages/react-native-tgfx/src/reanimated/liveValue.ts index 02a61ccc..13b05d6e 100644 --- a/packages/react-native-tgfx/src/reanimated/liveValue.ts +++ b/packages/react-native-tgfx/src/reanimated/liveValue.ts @@ -154,7 +154,7 @@ export function isBlockSlot(v: unknown): boolean { /** * A value the compiled program can patch in place: it is written as a value slot - * exactly like an animated prop, so writing it again costs one `setValues` + * exactly like an animated prop, so writing it again costs one value push * instead of a re-encode. * * A real SharedValue whenever Reanimated is installed, because it has to be diff --git a/packages/react-native-tgfx/src/reanimated/slotFlags.ts b/packages/react-native-tgfx/src/reanimated/slotFlags.ts index c0acc089..91fd7936 100644 --- a/packages/react-native-tgfx/src/reanimated/slotFlags.ts +++ b/packages/react-native-tgfx/src/reanimated/slotFlags.ts @@ -84,14 +84,14 @@ export function flagsOf(boxed: BoxedSlots): Uint8Array { } /** This runtime's `Float64` view of the block's value slots, cached like {@link flagsOf}. */ -export function valuesOf(boxed: BoxedSlots): Float64Array { +export function valuesOf(boxed: BoxedSlots): Float64Array { 'worklet' const scope = globalThis as { - __tgfxValueViews?: WeakMap + __tgfxValueViews?: WeakMap> } let views = scope.__tgfxValueViews if (views === undefined) { - views = new WeakMap() + views = new WeakMap>() scope.__tgfxValueViews = views } let view = views.get(boxed) diff --git a/packages/react-native-tgfx/src/scene.ts b/packages/react-native-tgfx/src/scene.ts index 42c6118c..ee3998c2 100644 --- a/packages/react-native-tgfx/src/scene.ts +++ b/packages/react-native-tgfx/src/scene.ts @@ -49,6 +49,10 @@ export interface SceneTarget { setScene(scene: ArrayBuffer, strings: string[]): void setValues(values: number[]): void setStringValues?(indices: number[], values: string[]): void + /** @internal bound once by the mapper, which then has the target push the mirror block. */ + bindValues?(values: ArrayBuffer): void + /** @internal false while nothing is bound, as after a recycle. */ + pushValues?(): boolean } interface Attachment { @@ -392,6 +396,10 @@ export class Scene { const mirror = this.container.mirror?.block.boxed ?? null const slots = new Array(values.length) const sent = new Array(stringValues.length).fill(null) + // Per target: set once it has bound the mirror, from the thread that writes it. + const bound = views.map(() => false) + // Only a target that cannot push, or a scene without a mirror, still reads the array. + const fillSlots = mirror == null || views.some((v) => v.pushValues == null) // Block slots have no listeners, so they cannot be mapper inputs; the // handles' gen values - bumped once per worklet-side set() - stand in. const listenable = [...values, ...stringValues].filter( @@ -408,7 +416,9 @@ export class Scene { const mirrored = mirror != null ? valuesOf(mirror) : null for (let i = 0; i < values.length; i++) { const v = readLiveNumber(values[i]!) - slots[i] = v + if (fillSlots) { + slots[i] = v + } if (mirrored != null) { mirrored[i] = v } @@ -416,8 +426,22 @@ export class Scene { if (mirror != null) { flagsOf(mirror)[0] = 1 } - for (const view of views) { - view.setValues(slots) + for (let t = 0; t < views.length; t++) { + const view = views[t]! + // An offscreen surface or an older binary has no push, so it takes the array. + if (mirrored != null && view.pushValues != null) { + if (!bound[t]) { + view.bindValues?.(mirrored.buffer) + bound[t] = true + } + // A recycled view comes back unbound, so bind again. + if (view.pushValues() === false) { + view.bindValues?.(mirrored.buffer) + view.pushValues() + } + } else { + view.setValues(slots) + } } if (stringValues.length > 0) { let indices: number[] | null = null diff --git a/packages/react-native-tgfx/src/specs/TgfxView.nitro.ts b/packages/react-native-tgfx/src/specs/TgfxView.nitro.ts index 902abed5..b4843882 100644 --- a/packages/react-native-tgfx/src/specs/TgfxView.nitro.ts +++ b/packages/react-native-tgfx/src/specs/TgfxView.nitro.ts @@ -77,7 +77,7 @@ export interface TgfxViewMethods extends HybridViewMethods { * The buffer is only valid for the duration of the call; the engine copies it. * * `awaitValues`: the program's slot literals are placeholders, so hold it - * until the next `setValues` lands and draw the two together. The driver + * until the next value push lands and draw the two together. The driver * pushes one frame later; the frames in between keep the previous program. */ setScene(scene: ArrayBuffer, strings: string[], awaitValues?: boolean): void @@ -86,11 +86,18 @@ export interface TgfxViewMethods extends HybridViewMethods { invalidate(): void /** - * Update the scene's `{ "__s": index }` value slots. Called every frame from a - * Reanimated worklet, so it runs natively on the UI thread. + * Replace the scene's value slots, in slot order. The animation driver + * copies its shared slot block natively instead; JS-thread handle writes + * and an older native binary use this. */ setValues(values: number[]): void + /** @internal points pushValues at a native-owned Float64 slot block (a TgfxSlots values buffer), held until the next bind. */ + bindValues(values: ArrayBuffer): void + + /** @internal setValues from the bound block, copied natively; false while nothing is bound, as after a recycle. */ + pushValues(): boolean + /** * Update the scene's string slots - live `text` and `path` content. Sparse: * `indices[i]` names the slot `values[i]` replaces, and only changed slots are