Skip to content

Deprecation of SkiaView and <Drawing /> - #2041

Merged
wcandillon merged 8 commits into
mainfrom
deprecation
Dec 11, 2023
Merged

wcandillon merged 8 commits into
mainfrom
deprecation

Conversation

@wcandillon

@wcandillon wcandillon commented Dec 10, 2023 •

Copy link
Copy Markdown
Owner

This PR aims to streamline the usage of the imperative API in React Native Skia by soft deprecating two of its APIs: SkiaView and the <Drawing /> component.

Currently, the imperative API is available in the following ways:

  1. Using SkiaView
  2. Using the <Drawing /> component
  3. Using the Picture API
  4. Using the Offscreen API

The primary reasons for this deprecation are as follows:

  • Both SkiaView and the <Drawing /> component are dependent on the main JavaScript context. This dependency introduces complexity in the rendering pipeline. Specifically, SkiaView's reliance on the main JS context prevents us to have a first time to frame.
  • The <Drawing /> component breaks our scenegraph contract, which ideally should be serializable and executable across various environments.

Changes in this PR include:

  • An enhancement in the documentation for the Picture API, including a minor ergonomic improvement.
  • Soft deprecation of SkiaView.
  • Soft deprecation of the <Drawing /> component.

@wcandillon wcandillon changed the title Title: Soft Deprecation of SkiaView and <Drawing /> Soft Deprecation of SkiaView and <Drawing /> Dec 10, 2023
@wcandillon wcandillon changed the title Soft Deprecation of SkiaView and <Drawing /> Deprecation of SkiaView and <Drawing /> Dec 10, 2023
@wcandillon
wcandillon merged commit 9c2f039 into main Dec 11, 2023
@wcandillon wcandillon mentioned this pull request Dec 12, 2023
@wcandillon
wcandillon deleted the deprecation branch June 7, 2024 09:11
@samuelscheit

samuelscheit commented Sep 13, 2024 •

Copy link
Copy Markdown
Contributor

Hi @wcandillon first of all thank you for all your work on react-native-skia and other libraries.
I'm currently playing around with react-native-skia and wanted to compare different rendering approaches and their performance. Because I'm implementing a custom list component in skia and want to skip the react reconciler to update the items in the list.

I've had a look at the NativeSkiaDomView implementation and it seems like every time a react component rerenders the react-reconciler has to run to figure out the changes in the virtual dom and update the render calls.
Because of that I thought rn-skia could be sped up by skipping the reconciliation part and directly creating the nodes API:

The problem is the more nodes you render and the more often you have to update the node structure, the more the calculate intensive it gets.

Just by running this example for a minute and dragging your finger around, you can see the fps decreasing to a sub 30 fps:

Code example
import SkiaDomViewNativeComponent, { NativeProps } from "@shopify/react-native-skia/src/specs/SkiaDomViewNativeComponent";
import { SkiaViewNativeId } from "@shopify/react-native-skia/src/views/SkiaViewNativeId";
import { SkiaViewApi } from "@shopify/react-native-skia/src/views/api";

const Sk = new JsiSkDOM({ Skia }, true);

export default (props: Partial<NativeProps>) => {
	const _nativeId = useMemo(() => SkiaViewNativeId.current++, []);
	const group = Sk.Group({});
	let frames = useSharedValue(0);

	const SkiaDomApi = global.SkiaDomApi;

	function onDraw(stopped: SharedValue<boolean>, i = 0) {
		"worklet";

		if (stopped.value) return;
		if (i % 10 === 0) {
			// benchmark: every 10th frame, restructure the list
			const oldRow: RenderNode<GroupNode> = globalThis.row;
			if (oldRow) group.removeChild(oldRow);

			const rows = SkiaDomApi.GroupNode({});
			group.addChild(rows);

			for (let i = 0; i < 30; i++) {
				const cx = 100 + i * 5;
				const cy = 0 + i * 30;
				rows.addChild(SkiaDomApi.CircleNode({ color: Skia.Color("blue"), cx, cy, r: 10 }));
				rows.addChild(SkiaDomApi.TextNode({ font, text: "Hello", x: cx + 10, y: cy + 10, color: Skia.Color("black") }));
			}

			globalThis.rows = rows;
		}

		frames.value++;

		requestAnimationFrame(() => {
			onDraw(stopped, i + 1);
		});
	}

	useLayoutEffect(() => {
		const interval = setInterval(() => {
			console.log("FPS", frames.value);
			frames.value = 0;
		}, 1000);

		const stopped = makeMutable(false);

		runOnUIImmediately(onDraw)(stopped);

		return () => {
			clearInterval(interval);
			stopped.value = true;
		};
	}, []);

	SkiaViewApi.setJsiProperty(_nativeId, "root", group);
	const matrix = useSharedValue(Skia.Matrix().translate(0, 0).get());

	const gesture = Gesture.Pan().onChange((e) => {
		matrix.value[5] += e.changeY;
		matrix.value[2] += e.changeX;

		group.setProp("matrix", matrix.value);
		SkiaViewApi.requestRedraw(_nativeId);
	});

	return (
		<GestureDetector gesture={gesture}>
			<SkiaDomViewNativeComponent collapsable={false} nativeID={`${_nativeId}`} mode={"default"} debug={true} {...props} />
		</GestureDetector>
	);
};

So I had a look at the Picture API and was able to imperatively call paint functions and live update the canvas using continuous mode:
However, I was not able to .clear() or .save() and .restore() previous render states and was only able to draw on top of each layer.

I also looked at the Texture/Offscreen API and measured the memory of this approach and it seems like because every frame needs to be captured and saved as SkImage, the memory pressure is quite high with a peak at 1.6GB:

Code example
export function TestSkia() {
	const image = useSharedValue<SkImage | null>(null);
	let frames = useSharedValue(0);
	const forceUpdate = useForceUpdate();

	const surfaceShared = useSharedValue<SkSurface | null>(null);
	const canvasShared = useSharedValue<SkCanvas | null>(null);
	const paintShared = useSharedValue<SkPaint | null>(null);
	const stopped = useSharedValue(false);

	function onDraw(image: SharedValue<SkImage | null>, i = 0) {
		"worklet";
		if (stopped.value) return;
		if (!surfaceShared.value) surfaceShared.value = Skia.Surface.MakeOffscreen(200, 200)!;
		if (!canvasShared.value) canvasShared.value = surfaceShared.value.getCanvas();
		if (!paintShared.value) {
			paintShared.value = Skia.Paint();
			paintShared.value.setColor(Skia.Color("cyan"));
		}

		const surface = surfaceShared.value;
		const canvas = canvasShared.value;
		const paint = paintShared.value;

		canvas.clear(Skia.Color("white"));

		canvas.drawCircle(100, 100, 100 - i, paint);
		i = (i + 1) % 100;

		surface.flush();
		image.value = surface.makeImageSnapshot();

		frames.value++;

		requestAnimationFrame(() => onDraw(image, i));
	}

	useLayoutEffect(() => {
		runOnUIImmediately(onDraw)(image);

		const interval = setInterval(() => {
			console.log("FPS", frames.value);
			frames.value = 0;
		}, 1000);

		return () => {
			clearInterval(interval);
			stopped.value = true;
			console.log("stopped");
		};
	}, []);

	return (
		<SafeAreaView style={{ flex: 1 }}>
			<Canvas style={{ flex: 1 }} mode="continuous">
				<Image image={image} x={0} y={0} width={200} height={200} />
			</Canvas>

			<TouchableHighlight
				style={{ flex: 0, justifyContent: "flex-start", alignItems: "center", paddingBottom: 30, paddingTop: 10 }}
				onPress={() => {
					let start = performance.now();
					while (performance.now() - start < 1000) {}
				}}
			>
				<Text style={{ fontSize: 25, fontWeight: "600" }}>Block</Text>
			</TouchableHighlight>
		</SafeAreaView>
	);
}
image

What do you suggest to speed up the rendering pipeline?
Is there an imperative api (maybe internal) that one could use to directly paint on the canvas?

Another unrelated fixed question regarding the fps, which I'll leave here for other people:
I've installed the old version 0.1.229, and tested how often the onDraw callback was called and was surprised that it was only 60 times per second, instead of the expected 120, which my iPhone 13 Pro supports.
In the latest version I also tested to move objects around with the gesture handler and rendering with skia and it felt like 60 fps instead of the 120 fps like the native ScrollView.
I've also tested how often the gesture handler/animation is called per second and it was the expected 120 times, so it's related to skia.
I've also made sure to include CADisableMinimumFrameDurationOnPhone in the info.plist

Update: I fixed the fps issue by setting the preferred fps in the DisplayLink.mm like described here:
#1275 (comment) (thank you @chrfalch 🙏)

I was successful when trying to use the onDraw callback, however I wanted to separate the main JS thread from the rendering logic and tried to wrap the callback inside of runOnUI, which resulted in a crash. Is it even possible to call rendering logic in worklets and is it possible on the old 0.1.229 version?

Update: I was able to run the onDraw callback on the UI thread via reanimated worklets and the react-native-webgpu package. Here is an example on how to use it. Thank you @wcandillon for wgpu and the example 🙏

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants