skia-motion-runtime 3.3.1 → 3.4.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +6 -0
- package/package.json +4 -1
- package/runtime/asset-draw.ts +420 -24
- package/runtime/asset-ink.ts +199 -0
- package/runtime/asset-load.ts +4 -2
- package/runtime/asset-roll.ts +195 -0
- package/runtime/asset-unicode.ts +343 -0
- package/runtime/asset.ts +71 -3
- package/runtime/mobile.tsx +4 -2
- package/runtime/useMachine.ts +18 -3
package/README.md
CHANGED
|
@@ -61,7 +61,13 @@ export function LessonReward() {
|
|
|
61
61
|
|
|
62
62
|
- Attach a `MotionPlayerHandle` ref to call `set(name, value)`, `setValues(values)`, or `fire(name)` using the asset's named inputs. Handle asset cues with `onMarker` and `onAudio`.
|
|
63
63
|
- Call the mounted handle's `setOnUI(name, value)` from a Reanimated worklet. A host-formatted string can update the digits in a bound text node during a count-up.
|
|
64
|
+
- A `row` group places an icon and its count by their ink on a plate that never resizes. It measures the ink with `SkParagraph.extendedVisit` (react-native-skia 3.10.2 or later); older react-native-skia and React Native Web fall back to advances and cap height, which is approximate.
|
|
65
|
+
- For a rolling count, give the text node `roll: { progress, from }`: set the old and new strings with `setValues`, then `fire` the trigger whose clip runs `progress` from 0 to 1. Each digit place turns in its own column.
|
|
64
66
|
- Use `live={false}` to pause a mounted player. The player uses system reduced motion by default and accepts a `reduced` override.
|
|
67
|
+
- The player pauses by itself only when the app is in the background. iOS 'inactive' (permission prompts, StoreKit and sign-in sheets, the app switcher, Notification Center) keeps it playing, as on Android.
|
|
68
|
+
- A stalled frame (an image decode, a sheet opening) delays motion instead of skipping a clip's start; a steadily slow device keeps real time.
|
|
69
|
+
- Images drawn smaller than their size are filtered through mip levels. `preloadMotionAsset(text, { uploadImages: true })` uploads textures with their mip levels.
|
|
70
|
+
- Bound text, rows and rolling numbers are laid out once per distinct string, so updating a counter is cheap; a string that changes every frame is laid out every frame.
|
|
65
71
|
- Select a board by name with the `artboard` option when loading a multi-artboard file.
|
|
66
72
|
- Prepare a shared file with `loadMotionAsset(text)` or `await preloadMotionAsset(text)`. Each player keeps its own state while sharing prepared artwork and image handles.
|
|
67
73
|
- Use `MotionPicture` for a named clip in an existing Skia Canvas at a shared `timeMs`. Provide `width` and `height` to draw without a separate player layout pass. Use `MotionPlayer` when the asset owns transitions and markers.
|
package/package.json
CHANGED
|
@@ -39,7 +39,10 @@
|
|
|
39
39
|
"runtime/asset-image.ts",
|
|
40
40
|
"runtime/asset-layout.ts",
|
|
41
41
|
"runtime/asset-load.ts",
|
|
42
|
+
"runtime/asset-ink.ts",
|
|
42
43
|
"runtime/asset-mesh.ts",
|
|
44
|
+
"runtime/asset-unicode.ts",
|
|
45
|
+
"runtime/asset-roll.ts",
|
|
43
46
|
"runtime/asset.ts",
|
|
44
47
|
"runtime/base64.ts",
|
|
45
48
|
"runtime/expo.ts",
|
|
@@ -55,7 +58,7 @@
|
|
|
55
58
|
"templates/motion/machine.ts",
|
|
56
59
|
"templates/motion/motion.ts"
|
|
57
60
|
],
|
|
58
|
-
"version": "3.
|
|
61
|
+
"version": "3.4.1",
|
|
59
62
|
"license": "MIT",
|
|
60
63
|
"repository": {
|
|
61
64
|
"type": "git",
|
package/runtime/asset-draw.ts
CHANGED
|
@@ -6,6 +6,8 @@ import { MAX_FEATHER, resolveAssetColor, resolveAssetFonts, usedAssetImages, typ
|
|
|
6
6
|
import type { AssetResource } from './asset-binary';
|
|
7
7
|
import { fitAsset, fittedAnchorOffset, type AssetLayoutOptions } from './asset-layout';
|
|
8
8
|
import { meshPinPosition, meshPosition, type MeshNode, type MeshPin } from './asset-mesh';
|
|
9
|
+
import { digitText, restText, rollFrame, rollSpan, rollTextStyle, rollWidthShare, SMEAR_SIGMA, type RollTiming } from './asset-roll';
|
|
10
|
+
import { blendInk, plateBox, rowItems, rowLayout, textInk, type Box, type RowChild, type TextInk } from './asset-ink';
|
|
9
11
|
|
|
10
12
|
type Channels = Readonly<Record<string, number>>;
|
|
11
13
|
type Palette = Readonly<Record<string, string>>;
|
|
@@ -20,6 +22,8 @@ type DrawableNode =
|
|
|
20
22
|
| (Omit<Extract<AssetNode, { kind: 'group' }>, 'children'> & {
|
|
21
23
|
children: readonly DrawableNode[];
|
|
22
24
|
preparedClip?: SkPath;
|
|
25
|
+
/** A row's embedded images' ink, as fractions of their boxes, by child; none for a host image slot. */
|
|
26
|
+
rowParts?: readonly (Box | undefined)[];
|
|
23
27
|
})
|
|
24
28
|
| DrawableMesh
|
|
25
29
|
| (AssetTextNode & { paragraph?: SkParagraph })
|
|
@@ -31,6 +35,8 @@ type TextValues = Readonly<Record<string, string>>;
|
|
|
31
35
|
export type DrawableAsset = Pick<MotionAsset, 'channels'> & {
|
|
32
36
|
artboard: Omit<MotionAsset['artboard'], 'nodes'> & { nodes: readonly DrawableNode[] };
|
|
33
37
|
meshShaders?: AssetMeshShaders;
|
|
38
|
+
/** Each image's shader for image nodes, sampled through its mip levels (drawImageRect's strict constraint would turn them off). */
|
|
39
|
+
imageShaders?: AssetImageShaders;
|
|
34
40
|
fontProvider?: SkTypefaceFontProvider;
|
|
35
41
|
textBindings?: readonly string[];
|
|
36
42
|
palette?: Palette;
|
|
@@ -38,6 +44,9 @@ export type DrawableAsset = Pick<MotionAsset, 'channels'> & {
|
|
|
38
44
|
export type AssetImages = Readonly<Record<string, SkImage>>;
|
|
39
45
|
export type AssetFontSlots = Readonly<Record<string, SkTypeface>>;
|
|
40
46
|
export type AssetMeshShaders = Readonly<Record<string, SkShader>>;
|
|
47
|
+
/** An image node's shader with the image it samples, so a different image passed at draw time is not drawn with it. */
|
|
48
|
+
export type AssetImageShaders = Readonly<Record<string, { image: SkImage; shader: SkShader }>>;
|
|
49
|
+
type DrawShaders = { mesh: AssetMeshShaders; image: AssetImageShaders };
|
|
41
50
|
|
|
42
51
|
function skiaData(resource: AssetResource): SkData {
|
|
43
52
|
if (typeof resource === 'string') return Skia.Data.fromBase64(resource.slice(resource.indexOf(',') + 1));
|
|
@@ -140,10 +149,69 @@ function meshTextureCoords(node: MeshNode | DrawableMesh, image: SkImage): Point
|
|
|
140
149
|
|
|
141
150
|
function meshShader(image: SkImage): SkShader {
|
|
142
151
|
'worklet';
|
|
143
|
-
|
|
152
|
+
// Mip levels keep art drawn below its size from aliasing.
|
|
153
|
+
return image.makeShaderOptions(TileMode.Decal, TileMode.Decal, FilterMode.Linear, MipmapMode.Linear);
|
|
144
154
|
}
|
|
145
155
|
|
|
146
|
-
|
|
156
|
+
/**
|
|
157
|
+
* An image node's shader. react-native-skia's drawImageRectOptions draws with SkCanvas::kStrict_SrcRectConstraint, under which Skia
|
|
158
|
+
* samples no mip levels, so art drawn small aliased whatever mipmap mode it asked for. A shader samples them; Clamp keeps the edges as
|
|
159
|
+
* drawImageRect drew them.
|
|
160
|
+
*/
|
|
161
|
+
function imageShader(image: SkImage): SkShader {
|
|
162
|
+
'worklet';
|
|
163
|
+
return image.makeShaderOptions(TileMode.Clamp, TileMode.Clamp, FilterMode.Linear, MipmapMode.Linear);
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
function imageShaders(images: AssetImages): AssetImageShaders {
|
|
167
|
+
const byImage = new Map<SkImage, SkShader>();
|
|
168
|
+
return Object.fromEntries(Object.entries(images).map(([name, image]) => {
|
|
169
|
+
const shader = byImage.get(image) ?? imageShader(image);
|
|
170
|
+
byImage.set(image, shader);
|
|
171
|
+
return [name, { image, shader }];
|
|
172
|
+
}));
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/** The most laid-out paragraphs, row inks and image paints the drawing thread keeps; the oldest unused one goes first. */
|
|
176
|
+
const CACHE_LIMIT = 256;
|
|
177
|
+
type CacheStore = Map<string, unknown>;
|
|
178
|
+
|
|
179
|
+
/**
|
|
180
|
+
* The value under `key` on this thread, made once. Each thread (the UI thread, or Node for asset frame) has its own store on its global
|
|
181
|
+
* object: drawing worklets get a copy of every captured object, so a cache held by the drawing would start empty each frame.
|
|
182
|
+
*/
|
|
183
|
+
function cached<T>(key: string | undefined, make: () => T): T {
|
|
184
|
+
'worklet';
|
|
185
|
+
if (key === undefined) return make();
|
|
186
|
+
const holder = globalThis as unknown as { __skiaMotionCache?: CacheStore };
|
|
187
|
+
const store = holder.__skiaMotionCache ?? (holder.__skiaMotionCache = new Map());
|
|
188
|
+
if (store.has(key)) {
|
|
189
|
+
const hit = store.get(key) as T;
|
|
190
|
+
store.delete(key);
|
|
191
|
+
store.set(key, hit);
|
|
192
|
+
return hit;
|
|
193
|
+
}
|
|
194
|
+
const value = make();
|
|
195
|
+
if (store.size >= CACHE_LIMIT) store.delete(store.keys().next().value as string);
|
|
196
|
+
store.set(key, value);
|
|
197
|
+
return value;
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
let nextNodeKey = 0;
|
|
201
|
+
|
|
202
|
+
/** A text's layout key: the node (unique per prepared drawing, so per font provider), the style variant and the text runs. */
|
|
203
|
+
function paragraphKey(node: AssetTextNode & { cacheKey?: string }, text: string | readonly (readonly [string, boolean])[]): string | undefined {
|
|
204
|
+
'worklet';
|
|
205
|
+
if (node.cacheKey === undefined) return undefined;
|
|
206
|
+
let runs = '';
|
|
207
|
+
if (typeof text === 'string') runs = text;
|
|
208
|
+
else for (const [content, shown] of text) runs += (shown ? '\x01' : '\x02') + content;
|
|
209
|
+
return `${node.cacheKey}|${node.align ?? ''}|${node.direction ?? ''}|${node.maxLines ?? 1}|${node.fontFeatures?.length ?? 0}|${runs}`;
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
function layOut(
|
|
213
|
+
node: AssetTextNode, text: string | readonly (readonly [string, boolean])[], provider?: SkTypefaceFontProvider,
|
|
214
|
+
): SkParagraph {
|
|
147
215
|
'worklet';
|
|
148
216
|
const builder = Skia.ParagraphBuilder.Make({
|
|
149
217
|
textDirection: node.direction === 'rtl' ? TextDirection.RTL : TextDirection.LTR,
|
|
@@ -151,24 +219,153 @@ function makeParagraph(node: AssetTextNode, text: string, provider?: SkTypefaceF
|
|
|
151
219
|
maxLines: node.maxLines ?? 1,
|
|
152
220
|
ellipsis: '…',
|
|
153
221
|
}, node.fonts?.length ? provider : undefined);
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
222
|
+
const runs = typeof text === 'string' ? [[text, true] as const] : text;
|
|
223
|
+
for (const [content, shown] of runs) {
|
|
224
|
+
if (!content) continue;
|
|
225
|
+
builder.pushStyle({
|
|
226
|
+
color: Skia.Color(shown ? node.fill : 'rgba(0,0,0,0)'), fontSize: node.fontSize,
|
|
227
|
+
...(node.fonts?.length ? { fontFamilies: [...node.fonts] } : {}),
|
|
228
|
+
...(node.fontFeatures?.length ? { fontFeatures: [...node.fontFeatures] } : {}),
|
|
229
|
+
});
|
|
230
|
+
builder.addText(content);
|
|
231
|
+
builder.pop();
|
|
232
|
+
}
|
|
160
233
|
const paragraph = builder.build();
|
|
161
234
|
paragraph.layout(node.width);
|
|
162
235
|
return paragraph;
|
|
163
236
|
}
|
|
164
237
|
|
|
238
|
+
/**
|
|
239
|
+
* Lay out a text node's paragraph. `text` is the whole string, or runs of it each shown or laid out unseen (a rolling number keeps its
|
|
240
|
+
* digits' place in the line while it draws them itself).
|
|
241
|
+
*/
|
|
242
|
+
function makeParagraph(
|
|
243
|
+
node: AssetTextNode, text: string | readonly (readonly [string, boolean])[], provider?: SkTypefaceFontProvider,
|
|
244
|
+
): SkParagraph {
|
|
245
|
+
'worklet';
|
|
246
|
+
return cached(paragraphKey(node, text), () => layOut(node, text, provider));
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
|
|
250
|
+
/** The baseline of a paragraph's first line, from its top. */
|
|
251
|
+
function baselineOf(paragraph: SkParagraph): number {
|
|
252
|
+
'worklet';
|
|
253
|
+
return paragraph.getLineMetrics()[0]?.baseline ?? 0;
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
/** The left edge of a range of a laid-out paragraph, in its own coordinates. */
|
|
257
|
+
function rangeLeft(paragraph: SkParagraph, start: number, end: number): number {
|
|
258
|
+
'worklet';
|
|
259
|
+
let left = Infinity;
|
|
260
|
+
for (const rect of paragraph.getRectsForRange(start, end)) left = Math.min(left, rect.x);
|
|
261
|
+
return left === Infinity ? 0 : left;
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
// A roll as drawn: its timing, and the ASCII digit columns prepareAssetDrawing laid out once.
|
|
265
|
+
type RollDrawing = { progress: string; from: string; digits?: readonly SkParagraph[] } & RollTiming;
|
|
266
|
+
|
|
267
|
+
/**
|
|
268
|
+
* A rolling number (`roll` on a text node). At rest it is the plain paragraph of the number it shows, with tabular figures. While it rolls,
|
|
269
|
+
* Skia lays out the same paragraph with zeros in the digit places, which places the prefix, the digit run and the suffix by the node's own
|
|
270
|
+
* alignment and direction; each digit place is then a column clipped to one line, the current digit leaving upward as the next comes in
|
|
271
|
+
* from below. A blank leading place opens as its digit arrives, so the layout eases between the shorter and the longer number. Values the
|
|
272
|
+
* odometer cannot roll (two runs of digits, different prefixes) cut from one to the other at half way.
|
|
273
|
+
*/
|
|
274
|
+
function drawRoll(
|
|
275
|
+
canvas: SkCanvas, node: AssetTextNode & { roll: RollDrawing }, channels: Channels, values: TextValues,
|
|
276
|
+
fonts: SkTypefaceFontProvider | undefined, text: string,
|
|
277
|
+
): void {
|
|
278
|
+
'worklet';
|
|
279
|
+
const progress = read(node.roll.progress, channels);
|
|
280
|
+
const from = values[node.roll.from] ?? '';
|
|
281
|
+
const x = read(node.x, channels);
|
|
282
|
+
const y = read(node.y, channels);
|
|
283
|
+
const styled = rollTextStyle(node);
|
|
284
|
+
const frame = rollFrame(from, text, progress, node.roll);
|
|
285
|
+
if (!frame) {
|
|
286
|
+
const content = progress < 0.5 ? from : text;
|
|
287
|
+
if (content) makeParagraph(styled, content, fonts).paint(canvas, x, y);
|
|
288
|
+
return;
|
|
289
|
+
}
|
|
290
|
+
let full = 0;
|
|
291
|
+
let opening = 0;
|
|
292
|
+
for (const { current, turn } of frame.places) {
|
|
293
|
+
if (current >= 0) full++;
|
|
294
|
+
else opening = Math.max(opening, turn);
|
|
295
|
+
}
|
|
296
|
+
// At rest (no place turning or smearing) the roll is its plain text. A fast roll passing a whole value still smears.
|
|
297
|
+
if (!opening && frame.places.every(({ turn, smear }) => turn === 0 && smear === 0)) {
|
|
298
|
+
// At either end it is exactly the string the host set (zero padding and all); between whole values, the value it rests on.
|
|
299
|
+
makeParagraph(styled, progress <= 0 ? from : progress >= 1 ? text : restText(frame), fonts).paint(canvas, x, y);
|
|
300
|
+
return;
|
|
301
|
+
}
|
|
302
|
+
const zero = digitText(0, frame.zero);
|
|
303
|
+
const start = frame.prefix.length;
|
|
304
|
+
// The number laid out with zeros in its digit places, unseen; the prefix and suffix are drawn in it, so they keep their shaping in context.
|
|
305
|
+
const layoutOf = (count: number, prefix: boolean, suffix: boolean) => {
|
|
306
|
+
let zeros = '';
|
|
307
|
+
for (let i = 0; i < count; i++) zeros += zero;
|
|
308
|
+
const paragraph = makeParagraph(styled, [[frame.prefix, prefix], [zeros, false], [frame.suffix, suffix]], fonts);
|
|
309
|
+
const end = start + count * zero.length;
|
|
310
|
+
return {
|
|
311
|
+
paragraph,
|
|
312
|
+
baseline: baselineOf(paragraph),
|
|
313
|
+
height: paragraph.getHeight(),
|
|
314
|
+
prefix: frame.prefix ? rangeLeft(paragraph, 0, start) : 0,
|
|
315
|
+
digits: rangeLeft(paragraph, start, end),
|
|
316
|
+
suffix: frame.suffix ? rangeLeft(paragraph, end, end + frame.suffix.length) : 0,
|
|
317
|
+
};
|
|
318
|
+
};
|
|
319
|
+
const now = layoutOf(full, true, !opening);
|
|
320
|
+
const then = opening > 0 ? layoutOf(full + 1, false, false) : now;
|
|
321
|
+
const at = (key: 'prefix' | 'digits' | 'suffix') => x + now[key] + (then[key] - now[key]) * opening;
|
|
322
|
+
// While a place opens, the prefix and the suffix move apart by different amounts, so each is drawn from its own copy of the layout.
|
|
323
|
+
now.paragraph.paint(canvas, at('prefix') - now.prefix, y);
|
|
324
|
+
if (opening && frame.suffix) layoutOf(full, false, true).paragraph.paint(canvas, at('suffix') - now.suffix, y);
|
|
325
|
+
// Digits draw left to right in their own paragraphs, the layout having put the run in reading order. Each sits on the whole number's
|
|
326
|
+
// baseline: a digit alone can take a different line box.
|
|
327
|
+
const baseline = y + now.baseline;
|
|
328
|
+
const line = now.height;
|
|
329
|
+
const plain: AssetTextNode = { ...styled, align: 'start', direction: 'ltr', maxLines: 1 };
|
|
330
|
+
// ASCII digits come from the columns prepared once; another digit system lays its digit out here.
|
|
331
|
+
const prepared = frame.zero === 48 ? node.roll.digits : undefined;
|
|
332
|
+
const column = (digit: number) => prepared?.[digit] ?? makeParagraph(plain, digitText(digit, frame.zero), fonts);
|
|
333
|
+
const piece = (digit: number, left: number, drop = 0) => {
|
|
334
|
+
const paragraph = column(digit);
|
|
335
|
+
paragraph.paint(canvas, left, baseline - baselineOf(paragraph) + drop);
|
|
336
|
+
};
|
|
337
|
+
const advance = column(0).getLongestLine();
|
|
338
|
+
let edge = at('digits');
|
|
339
|
+
frame.places.forEach(({ current, next, turn, smear }) => {
|
|
340
|
+
const width = current < 0 ? turn * advance : advance;
|
|
341
|
+
edge += width;
|
|
342
|
+
if (width <= 0) return;
|
|
343
|
+
// Each digit sits against its column's right edge, so an opening place slides in beside the digit after it.
|
|
344
|
+
const left = edge - advance;
|
|
345
|
+
canvas.save();
|
|
346
|
+
canvas.clipRect(Skia.XYWHRect(edge - width, y, width, line), ClipOp.Intersect, true);
|
|
347
|
+
// A place turning too fast to read is drawn as a vertical blur of its column; it sharpens as it slows into the value.
|
|
348
|
+
if (smear > 0) {
|
|
349
|
+
const blur = Skia.Paint();
|
|
350
|
+
blur.setImageFilter(Skia.ImageFilter.MakeBlur(0, smear * line * SMEAR_SIGMA, TileMode.Decal, null));
|
|
351
|
+
canvas.saveLayer(blur);
|
|
352
|
+
}
|
|
353
|
+
if (current >= 0) piece(current, left, -turn * line);
|
|
354
|
+
if (turn > 0 && next >= 0) piece(next, left, (1 - turn) * line);
|
|
355
|
+
if (smear > 0) canvas.restore();
|
|
356
|
+
canvas.restore();
|
|
357
|
+
});
|
|
358
|
+
}
|
|
359
|
+
|
|
165
360
|
function prepareNode(
|
|
166
361
|
node: AssetNode, images: AssetImages, shaders: Record<string, SkShader>, shadersByImage: Map<SkImage, SkShader>,
|
|
167
362
|
provider: SkTypefaceFontProvider | undefined, textBindings: Set<string>, palette: Palette,
|
|
168
363
|
): DrawableNode {
|
|
169
364
|
if (node.kind === 'text') {
|
|
170
365
|
if (typeof node.text === 'string') return { ...node, paragraph: makeParagraph(node, node.text, provider) };
|
|
366
|
+
node = { ...node, cacheKey: `n${nextNodeKey++}` } as AssetTextNode;
|
|
171
367
|
textBindings.add(node.text.value);
|
|
368
|
+
if (node.roll) textBindings.add(node.roll.from);
|
|
172
369
|
return node;
|
|
173
370
|
}
|
|
174
371
|
const commands = node.kind === 'group' ? node.clip : node.kind === 'path' ? node.commands : undefined;
|
|
@@ -198,13 +395,42 @@ function prepareNode(
|
|
|
198
395
|
textureCoords: image ? meshTextureCoords(node, image) : undefined,
|
|
199
396
|
};
|
|
200
397
|
}
|
|
398
|
+
if (node.kind === 'image') return { ...node, cacheKey: `n${nextNodeKey++}` } as DrawableNode;
|
|
201
399
|
return { ...node, preparedPath: prepared, preparedPaint: preparePaint(node, palette) };
|
|
202
400
|
}
|
|
203
401
|
|
|
204
|
-
|
|
402
|
+
declare const __DEV__: boolean | undefined;
|
|
403
|
+
const warnedFontSlots = new Set<string>();
|
|
404
|
+
|
|
405
|
+
/** The nodes with the named font slots taken out of every text's fonts: a text left with none draws in the platform's default face. */
|
|
406
|
+
function withoutFonts(nodes: readonly AssetNode[], gone: ReadonlySet<string>): AssetNode[] {
|
|
407
|
+
return nodes.map((node) => {
|
|
408
|
+
if (node.kind === 'text') return node.fonts?.some((name) => gone.has(name)) ? { ...node, fonts: node.fonts.filter((name) => !gone.has(name)) } : node;
|
|
409
|
+
if (node.kind === 'group') return { ...node, children: withoutFonts(node.children, gone) };
|
|
410
|
+
if (node.kind === 'mesh' && node.pins) {
|
|
411
|
+
return { ...node, pins: Object.fromEntries(Object.entries(node.pins).map(([name, pin]) => [name, pin.children ? { ...pin, children: withoutFonts(pin.children, gone) } : pin])) };
|
|
412
|
+
}
|
|
413
|
+
return node;
|
|
414
|
+
});
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
/**
|
|
418
|
+
* Build fixed geometry and paints once. Channel-driven paths and clips are still evaluated for each pose.
|
|
419
|
+
* A motion asset never takes the screen down over a font: a declared slot the host does not pass (with no embedded fallback) draws in the
|
|
420
|
+
* platform's default face, and a slot the asset does not declare is ignored. Each case warns once in development, naming the slots;
|
|
421
|
+
* `asset frame` and `asset preview` report the same as font-slot-fallback.
|
|
422
|
+
*/
|
|
205
423
|
export function prepareAssetDrawing(asset: DrawableMotionAsset, images: AssetImages = {}, fontSlots?: AssetFontSlots): DrawableAsset {
|
|
206
|
-
const
|
|
207
|
-
|
|
424
|
+
const declared = asset.fontSlots ?? {};
|
|
425
|
+
const unknown = fontSlots ? Object.keys(fontSlots).filter((name) => !Object.hasOwn(declared, name)) : [];
|
|
426
|
+
const known = unknown.length ? Object.fromEntries(Object.entries(fontSlots!).filter(([name]) => Object.hasOwn(declared, name))) : fontSlots;
|
|
427
|
+
const { fonts, missing } = resolveAssetFonts(asset, known);
|
|
428
|
+
const key = `${asset.name}|${missing.join(',')}|${unknown.join(',')}`;
|
|
429
|
+
if ((missing.length || unknown.length) && !warnedFontSlots.has(key) && (typeof __DEV__ === 'undefined' || __DEV__)) {
|
|
430
|
+
warnedFontSlots.add(key);
|
|
431
|
+
console.warn(`skia-motion: ${asset.name}${missing.length ? `: font slots ${missing.join(', ')} were not passed, so their text draws in the platform's default face` : ''}${unknown.length ? `${missing.length ? ';' : ':'} font slots ${unknown.join(', ')} are not declared by the asset and were ignored` : ''}`);
|
|
432
|
+
}
|
|
433
|
+
if (missing.length) asset = { ...asset, artboard: { ...asset.artboard, nodes: withoutFonts(asset.artboard.nodes, new Set(missing)) } };
|
|
208
434
|
const shaders: Record<string, SkShader> = {};
|
|
209
435
|
const shadersByImage = new Map<SkImage, SkShader>();
|
|
210
436
|
let fontProvider: SkTypefaceFontProvider | undefined;
|
|
@@ -232,9 +458,26 @@ export function prepareAssetDrawing(asset: DrawableMotionAsset, images: AssetIma
|
|
|
232
458
|
}
|
|
233
459
|
const textBindings = new Set<string>();
|
|
234
460
|
const palette = asset.palette ?? {};
|
|
235
|
-
|
|
461
|
+
// A row's embedded images carry their alpha ink (pack writes it); a host image slot is placed by its box, as check places it.
|
|
462
|
+
const withParts = (node: DrawableNode): DrawableNode => {
|
|
463
|
+
// A roll smears by how fast its places turn, which needs the time its progress channel takes (rollSpan).
|
|
464
|
+
// Its ASCII digit columns are laid out once here, so a frame of the roll builds only the number's own layout, not a paragraph per place.
|
|
465
|
+
if (node.kind === 'text' && node.roll) {
|
|
466
|
+
const plain = { ...rollTextStyle(node), align: 'start', direction: 'ltr', maxLines: 1 } as AssetTextNode;
|
|
467
|
+
const digits = Array.from({ length: 10 }, (_, digit) => makeParagraph(plain, String(digit), fontProvider));
|
|
468
|
+
return { ...node, roll: { ...node.roll, ms: rollSpan(asset.clips, node.roll.progress), digits } } as DrawableNode;
|
|
469
|
+
}
|
|
470
|
+
// Nodes on a mesh pin are drawn like a group's children, so they are prepared the same way.
|
|
471
|
+
if (node.kind === 'mesh') return node.pins ? { ...node, pins: node.pins.map((pin) => ({ ...pin, children: pin.children.map(withParts) })) } : node;
|
|
472
|
+
if (node.kind !== 'group') return node;
|
|
473
|
+
const children = node.children.map(withParts);
|
|
474
|
+
if (!node.row) return { ...node, children };
|
|
475
|
+
const rowParts = node.children.map((child) => (child.kind === 'image' && !asset.imageSlots?.[child.image] ? asset.imageInk?.[child.image] as Box | undefined : undefined));
|
|
476
|
+
return { ...node, children, rowParts };
|
|
477
|
+
};
|
|
478
|
+
const nodes = asset.artboard.nodes.map((node) => withParts(prepareNode(node, images, shaders, shadersByImage, fontProvider, textBindings, palette)));
|
|
236
479
|
return {
|
|
237
|
-
channels: asset.channels, artboard: { ...asset.artboard, nodes }, meshShaders: shaders,
|
|
480
|
+
channels: asset.channels, artboard: { ...asset.artboard, nodes }, meshShaders: shaders, imageShaders: imageShaders(images),
|
|
238
481
|
...(fontProvider && { fontProvider }),
|
|
239
482
|
...(textBindings.size && { textBindings: [...textBindings] }),
|
|
240
483
|
...(asset.palette && { palette }),
|
|
@@ -243,6 +486,8 @@ export function prepareAssetDrawing(asset: DrawableMotionAsset, images: AssetIma
|
|
|
243
486
|
|
|
244
487
|
/** Warmed images may be different native objects. Prepare their shaders with the same geometry. */
|
|
245
488
|
export function rebindAssetMeshShaders(drawing: DrawableAsset, images: AssetImages): DrawableAsset {
|
|
489
|
+
const shown = Object.keys(drawing.imageShaders ?? {});
|
|
490
|
+
if (shown.length) drawing = { ...drawing, imageShaders: imageShaders(Object.fromEntries(shown.map((name) => [name, images[name]!]))) };
|
|
246
491
|
const names = Object.keys(drawing.meshShaders ?? {});
|
|
247
492
|
if (!names.length) return drawing;
|
|
248
493
|
const byImage = new Map<SkImage, SkShader>();
|
|
@@ -291,8 +536,131 @@ function drawStroke(
|
|
|
291
536
|
canvas.drawPath(trimmed, paint);
|
|
292
537
|
}
|
|
293
538
|
|
|
539
|
+
/** One run of glyphs as `SkParagraph.extendedVisit` (react-native-skia 3.10.2 and later) reports it: typed here, so the runtime typechecks
|
|
540
|
+
* against older react-native-skia, which lacks the method. */
|
|
541
|
+
type VisitedRun = {
|
|
542
|
+
font: { measureText(text: string): { y: number } };
|
|
543
|
+
origin: { x: number; y: number };
|
|
544
|
+
glyphs: ArrayLike<number>;
|
|
545
|
+
positions: ArrayLike<{ x: number; y: number }>;
|
|
546
|
+
bounds: ArrayLike<{ x: number; y: number; width: number; height: number }>;
|
|
547
|
+
};
|
|
548
|
+
type WithVisit = { extendedVisit?: (visitor: (line: number, run: VisitedRun | null) => void) => void };
|
|
549
|
+
type WithMatch = { matchFamilyStyle?: (name: string, style: Record<string, never>) => SkTypeface | null };
|
|
550
|
+
/** A face's cap height, when the font is not known, as a share of the font size. */
|
|
551
|
+
const CAP_SHARE = 0.7;
|
|
552
|
+
|
|
553
|
+
/**
|
|
554
|
+
* A laid-out text's ink and optical band, from the glyphs Skia placed and the first run's face: asset-ink.ts's rule, as check uses it.
|
|
555
|
+
* Without extendedVisit (react-native-skia before 3.10.2, or React Native Web, where it throws) the ink is approximate: the line's
|
|
556
|
+
* advance boxes from the cap height above the baseline down to it, the cap height read from the node's first font (asset check warns
|
|
557
|
+
* row-approx).
|
|
558
|
+
*/
|
|
559
|
+
function paragraphInk(paragraph: SkParagraph, text: string, node: AssetTextNode, fonts: SkTypefaceFontProvider | undefined): TextInk | undefined {
|
|
560
|
+
'worklet';
|
|
561
|
+
const lines = paragraph.getLineMetrics();
|
|
562
|
+
const first = lines[0]?.baseline ?? 0;
|
|
563
|
+
const last = lines[lines.length - 1]?.baseline ?? 0;
|
|
564
|
+
const glyphs: Box[] = [];
|
|
565
|
+
let heights = { cap: 0, x: 0 };
|
|
566
|
+
const visit = (paragraph as unknown as WithVisit).extendedVisit;
|
|
567
|
+
if (typeof visit === 'function') {
|
|
568
|
+
try {
|
|
569
|
+
let faced = false;
|
|
570
|
+
visit.call(paragraph, (_line, info) => {
|
|
571
|
+
if (!info) return;
|
|
572
|
+
if (!faced) {
|
|
573
|
+
faced = true;
|
|
574
|
+
heights = { cap: Math.max(0, -info.font.measureText('H').y), x: Math.max(0, -info.font.measureText('x').y) };
|
|
575
|
+
}
|
|
576
|
+
for (let i = 0; i < info.glyphs.length; i++) {
|
|
577
|
+
const at = info.positions[i]!;
|
|
578
|
+
const bounds = info.bounds[i]!;
|
|
579
|
+
const x = info.origin.x + at.x + bounds.x;
|
|
580
|
+
const y = info.origin.y + at.y + bounds.y;
|
|
581
|
+
glyphs.push([x, y, x + bounds.width, y + bounds.height]);
|
|
582
|
+
}
|
|
583
|
+
});
|
|
584
|
+
return textInk(glyphs, first, last, text, heights);
|
|
585
|
+
} catch {
|
|
586
|
+
glyphs.length = 0; // React Native Web: the method is there and throws
|
|
587
|
+
}
|
|
588
|
+
}
|
|
589
|
+
const match = (fonts as unknown as WithMatch | undefined)?.matchFamilyStyle;
|
|
590
|
+
const family = node.fonts?.[0];
|
|
591
|
+
const face = typeof match === 'function' && family ? match.call(fonts, family, {}) : null;
|
|
592
|
+
if (face) {
|
|
593
|
+
const font = Skia.Font(face, node.fontSize);
|
|
594
|
+
heights = { cap: Math.max(0, -font.measureText('H').y), x: Math.max(0, -font.measureText('x').y) };
|
|
595
|
+
}
|
|
596
|
+
if (!heights.cap) heights = { cap: node.fontSize * CAP_SHARE, x: 0 };
|
|
597
|
+
for (const rect of paragraph.getRectsForRange(0, text.length)) {
|
|
598
|
+
if (rect.width > 0) glyphs.push([rect.x, first - heights.cap, rect.x + rect.width, last]);
|
|
599
|
+
}
|
|
600
|
+
return textInk(glyphs, first, last, text, heights);
|
|
601
|
+
}
|
|
602
|
+
|
|
603
|
+
/** A text's ink as a row places it, measured once per text. */
|
|
604
|
+
function inkFor(node: AssetTextNode, text: string, fonts: SkTypefaceFontProvider | undefined): TextInk | undefined {
|
|
605
|
+
'worklet';
|
|
606
|
+
const key = paragraphKey(node, text);
|
|
607
|
+
return cached(key === undefined ? undefined : `ink|${key}`, () => paragraphInk(makeParagraph(node, text, fonts), text, node, fonts));
|
|
608
|
+
}
|
|
609
|
+
|
|
610
|
+
type RowGroup = Extract<DrawableNode, { kind: 'group' }> & { row: NonNullable<Extract<AssetNode, { kind: 'group' }>['row']> };
|
|
611
|
+
|
|
612
|
+
/**
|
|
613
|
+
* Lay out a `row` group by its children's ink and optical centres (asset-ink.ts) and draw its plate; drawNodes then draws each child moved
|
|
614
|
+
* by its move (Worklets capture helpers when they are defined, so this one cannot call drawNodes back).
|
|
615
|
+
*/
|
|
616
|
+
function layoutRow(
|
|
617
|
+
canvas: SkCanvas, node: RowGroup, channels: Channels, values: TextValues, fonts: SkTypefaceFontProvider | undefined, palette: Palette,
|
|
618
|
+
): { moves: [number, number][]; paragraphs: (SkParagraph | undefined)[] } {
|
|
619
|
+
'worklet';
|
|
620
|
+
const { row } = node;
|
|
621
|
+
const align = row.align ?? 'start';
|
|
622
|
+
const rtl = row.direction === 'rtl';
|
|
623
|
+
const paragraphs: (SkParagraph | undefined)[] = [];
|
|
624
|
+
const children = node.children as unknown as readonly RowChild[];
|
|
625
|
+
const { items, widest, bands } = rowItems(children, (value, fallback) => read(value, channels, fallback), (child, index, wide) => {
|
|
626
|
+
const drawn = node.children[index] as AssetTextNode & { paragraph?: SkParagraph };
|
|
627
|
+
const text = wide ? row.plate!.widest! : typeof drawn.text === 'string' ? drawn.text : values[drawn.text.value] ?? '';
|
|
628
|
+
if (drawn.roll && !wide) {
|
|
629
|
+
// A rolling count is placed between its old value's ink and its new one's, so at rest it is placed by the value it shows.
|
|
630
|
+
const styled = rollTextStyle(drawn);
|
|
631
|
+
const from = values[drawn.roll.from] ?? '';
|
|
632
|
+
const inkOf = (value: string) => (value ? inkFor(styled, value, fonts) : undefined);
|
|
633
|
+
return blendInk(inkOf(from), inkOf(text), rollWidthShare(from, text, read(drawn.roll.progress, channels), drawn.roll));
|
|
634
|
+
}
|
|
635
|
+
if (!text) return undefined;
|
|
636
|
+
const paragraph = !wide && drawn.paragraph ? drawn.paragraph : makeParagraph(rollTextStyle(drawn), text, fonts);
|
|
637
|
+
if (!wide) paragraphs[index] = paragraph;
|
|
638
|
+
const key = paragraphKey(rollTextStyle(drawn), text);
|
|
639
|
+
return cached(key === undefined ? undefined : `ink|${key}`, () => paragraphInk(paragraph, text, drawn, fonts));
|
|
640
|
+
}, (index) => node.rowParts?.[index], Boolean(row.plate?.widest));
|
|
641
|
+
const { moves } = rowLayout(items, row.gap, align, rtl);
|
|
642
|
+
if (row.plate) {
|
|
643
|
+
const box = plateBox(widest, bands, row.gap, align, rtl, row.plate.padding);
|
|
644
|
+
const rect = Skia.XYWHRect(box[0], box[1], box[2] - box[0], box[3] - box[1]);
|
|
645
|
+
const radius = Math.min(row.plate.radius ?? Infinity, (box[2] - box[0]) / 2, (box[3] - box[1]) / 2);
|
|
646
|
+
const paint = Skia.Paint();
|
|
647
|
+
paint.setAntiAlias(true);
|
|
648
|
+
paint.setColor(Skia.Color(resolveAssetColor(row.plate.fill, palette)));
|
|
649
|
+
canvas.drawRRect(Skia.RRectXY(rect, radius, radius), paint);
|
|
650
|
+
if (row.plate.stroke && row.plate.stroke.width > 0) {
|
|
651
|
+
const edge = Skia.Paint();
|
|
652
|
+
edge.setAntiAlias(true);
|
|
653
|
+
edge.setStyle(PaintStyle.Stroke);
|
|
654
|
+
edge.setStrokeWidth(row.plate.stroke.width);
|
|
655
|
+
edge.setColor(Skia.Color(resolveAssetColor(row.plate.stroke.color, palette)));
|
|
656
|
+
canvas.drawRRect(Skia.RRectXY(rect, radius, radius), edge);
|
|
657
|
+
}
|
|
658
|
+
}
|
|
659
|
+
return { moves, paragraphs };
|
|
660
|
+
}
|
|
661
|
+
|
|
294
662
|
function drawNodes(
|
|
295
|
-
canvas: SkCanvas, nodes: readonly DrawableNode[], channels: Channels, images: AssetImages, shaders:
|
|
663
|
+
canvas: SkCanvas, nodes: readonly DrawableNode[], channels: Channels, images: AssetImages, shaders: DrawShaders,
|
|
296
664
|
values: TextValues, fonts: SkTypefaceFontProvider | undefined, palette: Palette, layout?: ReturnType<typeof fitAsset>,
|
|
297
665
|
): void {
|
|
298
666
|
'worklet';
|
|
@@ -304,12 +672,26 @@ function drawNodes(
|
|
|
304
672
|
canvas.rotate(read(node.rotation, channels), 0, 0);
|
|
305
673
|
canvas.scale(read(node.scaleX, channels, 1), read(node.scaleY, channels, 1));
|
|
306
674
|
if (node.clip) canvas.clipPath(node.preparedClip ?? makePath(node.clip, channels), ClipOp.Intersect, true);
|
|
307
|
-
|
|
675
|
+
if (node.row) {
|
|
676
|
+
const { moves, paragraphs } = layoutRow(canvas, node as RowGroup, channels, values, fonts, palette);
|
|
677
|
+
node.children.forEach((child, index) => {
|
|
678
|
+
canvas.save();
|
|
679
|
+
canvas.translate(moves[index]![0], moves[index]![1]);
|
|
680
|
+
const paragraph = paragraphs[index];
|
|
681
|
+
if (child.kind === 'text' && !child.roll && paragraph) paragraph.paint(canvas, read(child.x, channels), read(child.y, channels));
|
|
682
|
+
else drawNodes(canvas, [child], channels, images, shaders, values, fonts, palette);
|
|
683
|
+
canvas.restore();
|
|
684
|
+
});
|
|
685
|
+
} else drawNodes(canvas, node.children, channels, images, shaders, values, fonts, palette);
|
|
308
686
|
canvas.restore();
|
|
309
687
|
continue;
|
|
310
688
|
}
|
|
311
689
|
if (node.kind === 'text') {
|
|
312
690
|
const content = typeof node.text === 'string' ? node.text : values[node.text.value] ?? '';
|
|
691
|
+
if (node.roll) {
|
|
692
|
+
drawRoll(canvas, node as AssetTextNode & { roll: RollDrawing }, channels, values, fonts, content);
|
|
693
|
+
continue;
|
|
694
|
+
}
|
|
313
695
|
if (content) {
|
|
314
696
|
const paragraph = node.paragraph ?? makeParagraph(node, content, fonts);
|
|
315
697
|
paragraph.paint(canvas, read(node.x, channels), read(node.y, channels));
|
|
@@ -319,7 +701,7 @@ function drawNodes(
|
|
|
319
701
|
const alpha = Math.min(1, Math.max(0, read(node.opacity, channels, 1)));
|
|
320
702
|
if (node.kind === 'mesh') {
|
|
321
703
|
const image = images[node.image];
|
|
322
|
-
if (image && alpha) drawMesh(canvas, node, channels, image, alpha, shaders[node.image]);
|
|
704
|
+
if (image && alpha) drawMesh(canvas, node, channels, image, alpha, shaders.mesh[node.image]);
|
|
323
705
|
if (node.pins) {
|
|
324
706
|
for (const pin of node.pins) {
|
|
325
707
|
const { x, y } = meshPinPosition(node, pin, channels);
|
|
@@ -338,20 +720,33 @@ function drawNodes(
|
|
|
338
720
|
if (node.stroke) drawStroke(canvas, path, node.stroke, alpha, Math.min(MAX_FEATHER, read(node.feather, channels)), channels, palette);
|
|
339
721
|
continue;
|
|
340
722
|
}
|
|
341
|
-
const paint = node.preparedPaint ?? makePaint(node, alpha, channels, palette);
|
|
342
723
|
if (node.kind === 'image') {
|
|
343
724
|
const image = images[node.image];
|
|
344
725
|
const width = read(node.width, channels);
|
|
345
726
|
const height = read(node.height, channels);
|
|
346
727
|
if (!image || width <= 0 || height <= 0) continue;
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
);
|
|
728
|
+
const imageWidth = image.width();
|
|
729
|
+
const imageHeight = image.height();
|
|
730
|
+
// The prepared shader only for the image it was made from: a host can pass other images to drawAsset.
|
|
731
|
+
const prepared = shaders.image[node.image];
|
|
732
|
+
const shader = prepared && prepared.image === image ? prepared.shader : imageShader(image);
|
|
733
|
+
const key = (node as { cacheKey?: string }).cacheKey;
|
|
734
|
+
// One paint per image node, reset each frame: a picture records a copy of the paint it draws with.
|
|
735
|
+
const filled = cached(key === undefined ? undefined : `paint|${key}`, () => {
|
|
736
|
+
const paint = Skia.Paint();
|
|
737
|
+
paint.setAntiAlias(true);
|
|
738
|
+
return paint;
|
|
739
|
+
});
|
|
740
|
+
filled.setAlphaf(alpha);
|
|
741
|
+
filled.setShader(shader);
|
|
742
|
+
canvas.save();
|
|
743
|
+
canvas.translate(read(node.x, channels), read(node.y, channels));
|
|
744
|
+
canvas.scale(width / imageWidth, height / imageHeight);
|
|
745
|
+
canvas.drawRect(Skia.XYWHRect(0, 0, imageWidth, imageHeight), filled);
|
|
746
|
+
canvas.restore();
|
|
353
747
|
continue;
|
|
354
748
|
}
|
|
749
|
+
const paint = node.preparedPaint ?? makePaint(node, alpha, channels, palette);
|
|
355
750
|
const w = read(node.width, channels);
|
|
356
751
|
const h = read(node.height, channels);
|
|
357
752
|
if (w <= 0 || h <= 0) continue;
|
|
@@ -383,6 +778,7 @@ export function drawAsset(
|
|
|
383
778
|
? Skia.XYWHRect(-offsetX, -offsetY, board.width + spaceX, board.height + spaceY)
|
|
384
779
|
: Skia.XYWHRect(0, 0, board.width, board.height);
|
|
385
780
|
canvas.clipRect(bounds, ClipOp.Intersect, true);
|
|
386
|
-
drawNodes(canvas, board.nodes, { ...asset.channels, ...pose }, images, asset.meshShaders ?? {},
|
|
781
|
+
drawNodes(canvas, board.nodes, { ...asset.channels, ...pose }, images, { mesh: asset.meshShaders ?? {}, image: asset.imageShaders ?? {} },
|
|
782
|
+
values, asset.fontProvider, asset.palette ?? {}, layout);
|
|
387
783
|
canvas.restore();
|
|
388
784
|
}
|