From 46de27fa7e0c231470c422c0b6a15e2721743274 Mon Sep 17 00:00:00 2001 From: hassan-software-dev Date: Sun, 29 Nov 2026 15:25:59 +0500 Subject: [PATCH] Add an Animation tab for the Watch Pro 2's animated image (0x82, type 2) The editor kept these layers byte for byte but treated them as plain images. Decode the 0x5c body into a typed view (duration, start/end angle; the fields whose meaning isn't known stay raw, named by offset) with an encoder that reproduces the stock bytes, and edit it through a pure withAnim edit. - Animation tab in the right panel: the layer list, a timeline that plays or scrubs on its own clock, and the effect fields. - Preview: one geometry function (render/anim.ts) places the image by value and replays the wake sweep; the simulator can wake the screen, and a time, sunrise or sunset change replays it too. - "Animated layer" in the add menu, seeded with Sun Circle's exact body. - Selecting a layer no longer leaves the Animation tab. compat.ts and assertWatchCompat are untouched; types 0..3 were already allowed on a Pro 2. The geometry is a model that fits Sun Circle, to be checked on a watch. Sun Circle AOD is added as a round-trip fixture. Co-Authored-By: Claude Sonnet 5.5 --- .../editor/components/AnimationPanel.svelte | 120 ++++++++++++++++++ .../modules/editor/components/SimPanel.svelte | 6 + .../editor/components/TreePanel.svelte | 6 + .../editor/components/props/animation.svelte | 86 +++++++++++++ src/lib/modules/editor/core/document/edits.ts | 14 +- .../modules/editor/core/document/factory.ts | 16 +++ src/lib/modules/editor/core/document/proc.ts | 107 +++++++++++++++- .../modules/editor/core/document/sources.ts | 9 ++ src/lib/modules/editor/core/render/anim.ts | 49 +++++++ src/lib/modules/editor/core/render/pixels.ts | 4 +- src/lib/modules/editor/core/render/render.ts | 12 +- src/lib/modules/editor/i18n-inspector.ts | 83 ++++++++++++ src/lib/modules/editor/i18n.ts | 10 ++ src/lib/modules/editor/model/create.model.ts | 27 ++++ .../modules/editor/model/selection.model.ts | 6 +- src/lib/modules/editor/model/sim.model.ts | 25 +++- src/lib/modules/editor/model/ui.model.ts | 4 +- src/lib/modules/editor/pages/editor.svelte | 22 +++- tests/__fixtures__/Pro2__Sun_Circle_AOD.bin | Bin 0 -> 495957 bytes tests/doc-anim.test.ts | 109 ++++++++++++++++ 20 files changed, 697 insertions(+), 18 deletions(-) create mode 100644 src/lib/modules/editor/components/AnimationPanel.svelte create mode 100644 src/lib/modules/editor/components/props/animation.svelte create mode 100644 src/lib/modules/editor/core/render/anim.ts create mode 100644 tests/__fixtures__/Pro2__Sun_Circle_AOD.bin create mode 100644 tests/doc-anim.test.ts diff --git a/src/lib/modules/editor/components/AnimationPanel.svelte b/src/lib/modules/editor/components/AnimationPanel.svelte new file mode 100644 index 0000000..fc6e591 --- /dev/null +++ b/src/lib/modules/editor/components/AnimationPanel.svelte @@ -0,0 +1,120 @@ + + +
+ + {#if layers.length} +
+ {#each layers as l (l.id)} + + {/each} +
+ {:else} +

{$t.animNone}

+ {/if} +
+ + {#if current && anim} + +
+ + +
+ {$t.animAt} + + {$t.animValue} + +
+ + + + {/if} +
+ + diff --git a/src/lib/modules/editor/components/SimPanel.svelte b/src/lib/modules/editor/components/SimPanel.svelte index 4818ea3..34aeb76 100644 --- a/src/lib/modules/editor/components/SimPanel.svelte +++ b/src/lib/modules/editor/components/SimPanel.svelte @@ -4,6 +4,7 @@ import { Select } from "$lib/shared/components/select"; import { Switch } from "$lib/shared/components/switch"; import { Icon } from "$lib/shared/components/icon"; + import { Button } from "$lib/shared/components/button"; import { ACCENT_PALETTE, ID_METRIC, @@ -106,6 +107,11 @@ >{$t.slotPlaceholders} + + {#if $ids.some(({ id }) => id === 0x99)}
{$t.theme} diff --git a/src/lib/modules/editor/components/TreePanel.svelte b/src/lib/modules/editor/components/TreePanel.svelte index 72137a6..c4b57f9 100644 --- a/src/lib/modules/editor/components/TreePanel.svelte +++ b/src/lib/modules/editor/components/TreePanel.svelte @@ -34,6 +34,7 @@ widgetAdded, numberAdded, imageAdded, + animatedAdded, deleteRequested, duplicateRequested, copyRequested, @@ -295,6 +296,11 @@ {$t.emptyImage} + + animatedAdded()}> + + {$t.animatedLayer} + numberAdded()}> diff --git a/src/lib/modules/editor/components/props/animation.svelte b/src/lib/modules/editor/components/props/animation.svelte new file mode 100644 index 0000000..bf71771 --- /dev/null +++ b/src/lib/modules/editor/components/props/animation.svelte @@ -0,0 +1,86 @@ + + +{#if anim} +

{$t.animHint}

+
+ put({ duration: u16(v) })} + /> +
+
+ put({ start: Math.max(-3600, Math.min(3600, tenths(v))) })} + /> + put({ end: Math.max(-3600, Math.min(3600, tenths(v))) })} + /> +
+ {$t.animRaw} +
+ {#each RAW as f (f.key)} + put({ [f.key]: f.signed ? s16(v) : u16(v) })} + /> + {/each} +
+{/if} + + diff --git a/src/lib/modules/editor/core/document/edits.ts b/src/lib/modules/editor/core/document/edits.ts index bcdd972..e0faee4 100644 --- a/src/lib/modules/editor/core/document/edits.ts +++ b/src/lib/modules/editor/core/document/edits.ts @@ -5,7 +5,7 @@ // here is keyed by NodeId, which is what makes the layer identity survive an immutable update: // the old code compared node objects, so any rebuilt parent silently invalidated `sel`. import { hex, TAG, unhex } from "../format"; -import { PANELS, procOf, RINGS, type Proc } from "./proc"; +import { PANELS, procOf, RINGS, withAnimBody, animOf, type Anim, type Proc } from "./proc"; import { framesOf, isPlaced, @@ -387,3 +387,15 @@ export function usedAssets(doc: Doc) { doc.screens.forEach((s) => walk(s.layers)); return out; } + +/** Change fields of a type 2 (animated) layer's 0x5c body; the rest of the body stays as found. */ +export function withAnim(doc: Doc, id: NodeId, patch: Partial): Doc { + const l = findLayer(doc, id); + + if (!l || !animOf(l)) return doc; + const extra = withAnimBody(l, patch); + + return !extra || extra === (l as { extra?: unknown }).extra + ? doc + : patchLayer(doc, id, { extra } as Partial); +} diff --git a/src/lib/modules/editor/core/document/factory.ts b/src/lib/modules/editor/core/document/factory.ts index 5c9a075..1023d1f 100644 --- a/src/lib/modules/editor/core/document/factory.ts +++ b/src/lib/modules/editor/core/document/factory.ts @@ -23,6 +23,7 @@ import { type WidgetMeta, } from "./doc"; import { TAG, hex, unhex, type Resource } from "../format"; +import { ANIM_SEED } from "./proc"; const META0: WidgetMeta = { w: 0, @@ -51,6 +52,21 @@ export const newImage = (frames: readonly ImageId[]): ImageLayer => ({ frames, }); +/** The animated image (0x82, type 2), seeded with Sun Circle's exact 0x5c body: a full-screen + * 466x466 layer that sweeps in on wake and stops where daylight % puts it. Starting from bytes a + * Watch Pro 2 is known to play means a new layer is as safe as the stock one; edit from there. */ +export const newAnimated = (frames: readonly ImageId[]): ImageLayer => ({ + ...base(), + tag: 0x82, + kind: "image", + x: 0, + y: 0, + meta: metaWith({ w: 466, h: 466, source: 0x82, max: 0x3c }), + refType: 1, + frames, + extra: [{ tag: TAG.proc, hex: ANIM_SEED }], +}); + /** One frame per battery percent, 0..100: the image widget draws frames[value % count]. */ export const PROGRESS_STEPS = 101; diff --git a/src/lib/modules/editor/core/document/proc.ts b/src/lib/modules/editor/core/document/proc.ts index c911897..7e57e3d 100644 --- a/src/lib/modules/editor/core/document/proc.ts +++ b/src/lib/modules/editor/core/document/proc.ts @@ -1,7 +1,7 @@ // The Watch 3 Pro's procedural widgets as the document holds them: an image layer tagged 0x82 // whose 0x5c body (kept in `extra`) names the type. Types 0..3 are drawn like any image layer; // 4..7 draw themselves (core/render/proc.ts). -import { TAG, unhex } from "../format"; +import { TAG, hex, unhex } from "../format"; import type { Layer } from "./doc"; export const RINGS = 4; @@ -41,3 +41,108 @@ export function procSources(l: Layer): number[] { /** Whether any layer of the list, groups included, is a procedural widget of this type. */ export const hasProc = (layers: readonly Layer[], type: number): boolean => layers.some((l) => procOf(l)?.type === type || (l.kind === "group" && hasProc(l.children, type))); + +/** The animated image widget (0x82, type 2): a Watch Pro 2 plays it, so it stays an image layer. */ +export const ANIMATED = 2; +/** The fields end at byte 20; Sun Circle's body is 25 bytes, the rest zero padding. */ +export const ANIM_BODY = 21; +/** Sun Circle's sun body, as found on a Watch Pro 2 that plays it: what a new layer starts from. */ +export const ANIM_SEED = "0200d007efff000000000000550ac20ae90ee90e8800000000"; + +/** The type 2 body as a view. Fields the firmware reads but whose meaning isn't pinned down are + * kept raw (`rawA`..`rawE`, `flags`), named by offset, until tests on a watch settle them. */ +export interface Anim { + /** Offset 2: sweep duration, ms (inferred from the ~2 s seen on a watch). */ + duration: number; + /** Offset 12: angle at value 0, in 0.1 degrees (the parser wraps it into +-3600). */ + start: number; + /** Offset 14: angle at value 100, in 0.1 degrees. */ + end: number; + /** Offsets 4, 6, 8, 10 (s16): read by the firmware, meaning unknown. */ + raw4: number; + raw6: number; + raw8: number; + raw10: number; + /** Offsets 16, 18 (u16): read by the firmware, meaning unknown. */ + raw16: number; + raw18: number; + /** Offset 20: flags (0x41 takes a special branch). */ + flags: number; + /** Bytes from 21 on (4 zeros in Sun Circle), kept as found. */ + tail: readonly number[]; +} + +const s16 = (v: Uint8Array, o: number) => ((v[o] | (v[o + 1] << 8)) << 16) >> 16; +const u16 = (v: Uint8Array, o: number) => v[o] | (v[o + 1] << 8); + +type Extra = { readonly tag: number; readonly hex: string }; +const extraOf = (l: Layer): readonly Extra[] | undefined => + l.kind === "group" || l.kind === "raw" ? undefined : l.extra; +const animBody = (l: Layer) => + l.kind === "group" || l.kind === "raw" || l.tag !== 0x82 + ? undefined + : extraOf(l)?.find((e) => e.tag === TAG.proc); + +/** The body of a type 2 layer, or null for anything else. */ +export function animOf(l: Layer): Anim | null { + const body = animBody(l); + + if (!body) return null; + const v = unhex(body.hex); + + if (v.length < ANIM_BODY || u16(v, 0) !== ANIMATED) return null; + return { + duration: u16(v, 2), + raw4: s16(v, 4), + raw6: s16(v, 6), + raw8: s16(v, 8), + raw10: s16(v, 10), + start: s16(v, 12), + end: s16(v, 14), + raw16: u16(v, 16), + raw18: u16(v, 18), + flags: v[20], + tail: [...v.subarray(ANIM_BODY)], + }; +} + +/** The bytes of an Anim: `encodeAnim(animOf(l))` reproduces what was read. */ +export function encodeAnim(a: Anim): Uint8Array { + const v = new Uint8Array(ANIM_BODY + a.tail.length); + const put = (o: number, n: number) => { + v[o] = n & 0xff; + v[o + 1] = (n >> 8) & 0xff; + }; + + put(0, ANIMATED); + put(2, a.duration); + put(4, a.raw4); + put(6, a.raw6); + put(8, a.raw8); + put(10, a.raw10); + put(12, a.start); + put(14, a.end); + put(16, a.raw16); + put(18, a.raw18); + v[20] = a.flags; + a.tail.forEach((b, i) => (v[21 + i] = b)); + return v; +} + +/** The layer's extras with the type 2 body rewritten, or undefined when it isn't one. */ +export function withAnimBody(l: Layer, patch: Partial): readonly Extra[] | undefined { + const a = animOf(l); + const body = animBody(l); + + if (!a || !body) return undefined; + const next = hex(encodeAnim({ ...a, ...patch })); + + // unchanged bytes hand back the very same array, so a no-op edit can be told by reference + return next === body.hex + ? extraOf(l) + : extraOf(l)!.map((e) => (e === body ? { ...e, hex: next } : e)); +} + +/** The animated images of a layer list, groups included, in tree order. */ +export const animatedIn = (layers: readonly Layer[]): Layer[] => + layers.flatMap((l) => (l.kind === "group" ? animatedIn(l.children) : animOf(l) ? [l] : [])); diff --git a/src/lib/modules/editor/core/document/sources.ts b/src/lib/modules/editor/core/document/sources.ts index b7c3e8b..2b10db3 100644 --- a/src/lib/modules/editor/core/document/sources.ts +++ b/src/lib/modules/editor/core/document/sources.ts @@ -224,6 +224,11 @@ export interface Sim { /** The clip a tap started and when (type 5); no time = none played since it came to rest. */ clip: number; clipAt: number | null; + /** When the screen last "woke", for the animated image (0x82 type 2); null = at rest. */ + wakeAt: number | null; + /** The Animation tab's timeline: hold animated images at `ms` into the sweep, and at `value` + * (0..100, null = what their source reads). null = follow the clock and the simulator. */ + scrub: { ms: number; value: number | null } | null; // widget-slot (0x85) imgs[0] is an on-watch "tap to configure" placeholder — the real // device only draws it in its own edit mode, never during normal time-telling, so the // live sim skips it by default. This is an editor-only preview toggle, not real data. @@ -290,6 +295,8 @@ export function defaultSim(): Sim { touch: null, clip: 0, clipAt: null, + wakeAt: null, + scrub: null, showSlotPlaceholders: false, }; } @@ -308,6 +315,8 @@ export const previewSim = (sim: Sim): Sim => ({ touch: null, clip: 0, clipAt: null, + wakeAt: null, + scrub: null, overrides: {}, }); diff --git a/src/lib/modules/editor/core/render/anim.ts b/src/lib/modules/editor/core/render/anim.ts new file mode 100644 index 0000000..bd76541 --- /dev/null +++ b/src/lib/modules/editor/core/render/anim.ts @@ -0,0 +1,49 @@ +// Where the Watch Pro 2's animated image (0x82, type 2) sits at a given value and moment. +// +// ponytail: still a model, kept in this one function. Seen on a watch (Sun Circle): the sun's +// stop position runs bottom to top as daylight % goes 0 to 100 and the sun leaves the screen at +// the top; then the moon does the same on night %. Its art is a full-face disc. On wake the image also sweeps up from the +// bottom over `duration`. +// The model that fits: angles (body 12/14, 0.1 degree) are clockwise from straight up, so ~270 +// points left and the pivot sits far to the image's right; the image rides a circle of radius +// `raw16` PIXELS about it. 3817 px over 264.5..275.4 degrees is ~725 px of travel, more than the +// screen, which is why the sun can leave it. The art is undisplaced at 270 (checked against the +// real art: value 0 is the disc rising at the bottom, 100 leaving at the top). Not modelled: the image also turns by the swept angle +// about the pivot (invisible for a round sun). Replace the body, not the callers, once tests A..D +// on a watch pin the raw fields down. +import type { Anim } from "../document/proc"; +import { SCREEN } from "./screen"; + +export interface AnimPlace { + dx: number; + dy: number; +} + +/** Angle 270 degrees, clockwise from up: the pivot level with the image. */ +const LEVEL = (270 * Math.PI) / 180; +const clamp01 = (v: number) => Math.min(1, Math.max(0, v)); +const easeOut = (k: number) => 1 - (1 - k) ** 3; + +/** + * @param value 0..100, what the layer's source reads + * @param sinceWake ms since the screen woke, or Infinity at rest + */ +export function animPlace(a: Anim, value: number, sinceWake: number): AnimPlace { + const k = clamp01(value / 100); + const rad = (tenths: number) => (tenths / 10) * (Math.PI / 180); + const r = a.raw16; + const from = rad(a.start); + const to = rad(a.end); + const at = from + (to - from) * k; + // The art sits where it was drawn when the pivot is level with it, angle 270 (straight left). + // That is the middle of Sun Circle's 264.5..275.4, so value 50 is "centred", 0 is the disc just + // rising at the bottom and 100 is it leaving at the top. + const rest = { + dx: r * (Math.sin(at) - Math.sin(LEVEL)), + dy: -r * (Math.cos(at) - Math.cos(LEVEL)), + }; + const swept = a.duration > 0 ? easeOut(clamp01(sinceWake / a.duration)) : 1; + + // before it arrives the image is a full screen below its resting place + return { dx: rest.dx, dy: rest.dy + (1 - swept) * SCREEN }; +} diff --git a/src/lib/modules/editor/core/render/pixels.ts b/src/lib/modules/editor/core/render/pixels.ts index 8e9bc84..bb1f775 100644 --- a/src/lib/modules/editor/core/render/pixels.ts +++ b/src/lib/modules/editor/core/render/pixels.ts @@ -98,8 +98,8 @@ export async function resourceFromFile(file: File, cf: number): Promise { - const r = encodePixels(new Uint8ClampedArray(w * h * 4), w, h, 5); +export async function blankFrame(w: number, h: number, cf = 5): Promise { + const r = encodePixels(new Uint8ClampedArray(w * h * 4), w, h, cf); r.bitmap = await bitmapOf(r); return r; diff --git a/src/lib/modules/editor/core/render/render.ts b/src/lib/modules/editor/core/render/render.ts index bc95007..26422b1 100644 --- a/src/lib/modules/editor/core/render/render.ts +++ b/src/lib/modules/editor/core/render/render.ts @@ -32,7 +32,8 @@ import { } from "./canvas"; import { FULL_BLEED_R, drawProceduralArc, drawSector, hexRGB, progressFrac } from "./arc"; import { CENTER, SCREEN } from "./screen"; -import { procOf } from "../document/proc"; +import { animOf, procOf } from "../document/proc"; +import { animPlace } from "./anim"; import { drawProc } from "./proc"; /** One layer drawn at a scale or angle it doesn't have yet — what a corner or rotate drag shows @@ -308,7 +309,16 @@ function drawPicked( idx = ((v % frames.length) + frames.length) % frames.length; } const b = bmpOf(env.store, frames[idx]); + const anim = animOf(l); + if (anim && b) { + const { scrub, wakeAt } = env.sim; + const since = scrub ? scrub.ms : wakeAt === null ? Infinity : Date.now() - wakeAt; + const value = scrub?.value ?? idValue(source, env.sim, env.t); + const { dx, dy } = animPlace(anim, value, since); + + return blit(env, l, b, x + dx, y + dy); + } return b ? blit(env, l, b, x, y) : null; } diff --git a/src/lib/modules/editor/i18n-inspector.ts b/src/lib/modules/editor/i18n-inspector.ts index 8939c53..51f0716 100644 --- a/src/lib/modules/editor/i18n-inspector.ts +++ b/src/lib/modules/editor/i18n-inspector.ts @@ -71,6 +71,22 @@ const en = { `Watch 3 Pro widget (type ${type}): the watch lays it out itself. Replace its images; their count and size are fixed by the widget.`, panels: ["Weather", "Heart rate", "Blood oxygen", "Stress", "Sleep"], framesByValue: "frames · index = value", + animLayers: "animated images", + animNone: "No animated images on this screen. Add one from the layer menu: Animated layer.", + animSettings: "effect", + animTimeline: "timeline", + animPlay: "play", + animFollow: "follow simulator", + animAt: "time into the sweep, ms", + animValue: "value, % (the driving source)", + wakeScreen: "wake the screen", + animation: "Animation", + animDuration: "sweep duration, ms", + animStart: "start angle, ° (value 0)", + animEnd: "end angle, ° (value 100)", + animRaw: "raw fields", + animHint: + "Watch Pro 2 animated image (type 2): it sweeps in each time the screen wakes and stops where the driving source says. Angles are read from the firmware; the raw fields are read by it too, but what they do isn't known yet, so they are kept as found.", ringArt: "ring art", useRingBitmap: "use a ring bitmap", ringArtHint: "a full ring, drawn at 100% — the watch clips it to the filled sector", @@ -292,6 +308,23 @@ export const t = dict(en, { `Виджет Watch 3 Pro (тип ${type}): часы сами его раскладывают. Изображения можно заменять, их число и размер задаёт виджет.`, panels: ["Погода", "Пульс", "Кислород в крови", "Стресс", "Сон"], framesByValue: "кадры · индекс = значение", + animLayers: "анимированные изображения", + animNone: + "На этом экране нет анимированных изображений. Добавьте через меню слоёв: Анимированный слой.", + animSettings: "эффект", + animTimeline: "таймлайн", + animPlay: "играть", + animFollow: "следовать симулятору", + animAt: "время развёртки, мс", + animValue: "значение, % (источник данных)", + wakeScreen: "разбудить экран", + animation: "Анимация", + animDuration: "длительность, мс", + animStart: "начальный угол, ° (значение 0)", + animEnd: "конечный угол, ° (значение 100)", + animRaw: "сырые поля", + animHint: + "Анимированное изображение Watch Pro 2 (тип 2): выезжает при каждом пробуждении экрана и останавливается там, где указывает источник данных. Углы прочитаны из прошивки; сырые поля она тоже читает, но что они делают — пока неизвестно, поэтому они хранятся как есть.", ringArt: "графика кольца", useRingBitmap: "задать картинку кольца", ringArtHint: "полное кольцо на 100% — часы обрезают его до заполненного сектора", @@ -508,6 +541,23 @@ export const t = dict(en, { `Віджет Watch 3 Pro (тип ${type}): годинник сам його розкладає. Зображення можна замінювати, їхню кількість і розмір задає віджет.`, panels: ["Погода", "Пульс", "Кисень у крові", "Стрес", "Сон"], framesByValue: "кадри · індекс = значення", + animLayers: "анімовані зображення", + animNone: + "На цьому екрані немає анімованих зображень. Додайте через меню шарів: Анімований шар.", + animSettings: "ефект", + animTimeline: "таймлайн", + animPlay: "грати", + animFollow: "слідувати симулятору", + animAt: "час розгортання, мс", + animValue: "значення, % (джерело даних)", + wakeScreen: "розбудити екран", + animation: "Анімація", + animDuration: "тривалість, мс", + animStart: "початковий кут, ° (значення 0)", + animEnd: "кінцевий кут, ° (значення 100)", + animRaw: "сирі поля", + animHint: + "Анімоване зображення Watch Pro 2 (тип 2): виїжджає щоразу, коли екран прокидається, і зупиняється там, куди вказує джерело даних. Кути прочитані з прошивки; сирі поля вона теж читає, але що вони роблять — поки невідомо, тому вони зберігаються як є.", ringArt: "графіка кільця", useRingBitmap: "задати зображення кільця", ringArtHint: "повне кільце на 100% — годинник обрізає його до заповненого сектора", @@ -724,6 +774,23 @@ export const t = dict(en, { `Widget del Watch 3 Pro (tipo ${type}): el reloj lo compone por sí mismo. Puedes reemplazar sus imágenes; el número y el tamaño los fija el widget.`, panels: ["Tiempo", "Frecuencia cardíaca", "Oxígeno en sangre", "Estrés", "Sueño"], framesByValue: "fotogramas · índice = valor", + animLayers: "imágenes animadas", + animNone: + "No hay imágenes animadas en esta pantalla. Añade una desde el menú de capas: Capa animada.", + animSettings: "efecto", + animTimeline: "línea de tiempo", + animPlay: "reproducir", + animFollow: "seguir el simulador", + animAt: "tiempo del barrido, ms", + animValue: "valor, % (la fuente de datos)", + wakeScreen: "activar la pantalla", + animation: "Animación", + animDuration: "duración, ms", + animStart: "ángulo inicial, ° (valor 0)", + animEnd: "ángulo final, ° (valor 100)", + animRaw: "campos sin procesar", + animHint: + "Imagen animada del Watch Pro 2 (tipo 2): entra cada vez que se activa la pantalla y se detiene donde indica la fuente de datos. Los ángulos se leen del firmware; los campos sin procesar también los lee, pero aún no se sabe qué hacen, así que se conservan tal cual.", ringArt: "imagen del anillo", useRingBitmap: "usar imagen de anillo", ringArtHint: "un anillo completo, al 100% — el reloj lo recorta al sector lleno", @@ -940,6 +1007,22 @@ export const t = dict(en, { `Watch 3 Pro विजेट (टाइप ${type}): घड़ी इसका लेआउट खुद बनाती है। इमेज बदली जा सकती हैं; उनकी संख्या और साइज़ विजेट तय करता है।`, panels: ["मौसम", "हृदय गति", "ब्लड ऑक्सीजन", "तनाव", "नींद"], framesByValue: "फ़्रेम · इंडेक्स = मान", + animLayers: "एनिमेटेड इमेज", + animNone: "इस स्क्रीन पर कोई एनिमेटेड इमेज नहीं है। लेयर मेनू से जोड़ें: एनिमेटेड लेयर।", + animSettings: "प्रभाव", + animTimeline: "टाइमलाइन", + animPlay: "चलाएँ", + animFollow: "सिमुलेटर का अनुसरण", + animAt: "स्वीप में समय, ms", + animValue: "मान, % (डेटा स्रोत)", + wakeScreen: "स्क्रीन जगाएँ", + animation: "एनिमेशन", + animDuration: "अवधि, ms", + animStart: "प्रारंभ कोण, ° (मान 0)", + animEnd: "अंतिम कोण, ° (मान 100)", + animRaw: "रॉ फ़ील्ड", + animHint: + "Watch Pro 2 की एनिमेटेड इमेज (टाइप 2): हर बार स्क्रीन जागने पर अंदर आती है और डेटा स्रोत के बताए स्थान पर रुकती है। कोण फ़र्मवेयर से पढ़े गए हैं; रॉ फ़ील्ड भी वह पढ़ता है, पर वे क्या करते हैं यह अभी पता नहीं, इसलिए उन्हें जस का तस रखा गया है।", ringArt: "रिंग आर्ट", useRingBitmap: "रिंग इमेज लगाएं", ringArtHint: "पूरी रिंग, 100% पर — घड़ी इसे भरे हुए हिस्से तक काटती है", diff --git a/src/lib/modules/editor/i18n.ts b/src/lib/modules/editor/i18n.ts index e8e76ea..f18c314 100644 --- a/src/lib/modules/editor/i18n.ts +++ b/src/lib/modules/editor/i18n.ts @@ -84,6 +84,8 @@ export const t = dict( addLayer: "Add a layer", imageFile: "Image…", emptyImage: "Empty image", + animTab: "Animation", + animatedLayer: "Animated layer", handFile: "Hand…", progressLine: "Progress line", vProgressLine: "Vertical progress line", @@ -278,6 +280,8 @@ export const t = dict( addLayer: "Добавить слой", imageFile: "Изображение…", emptyImage: "Пустое изображение", + animTab: "Анимация", + animatedLayer: "Анимированный слой", handFile: "Стрелка…", progressLine: "Полоса прогресса", vProgressLine: "Вертикальная полоса прогресса", @@ -461,6 +465,8 @@ export const t = dict( addLayer: "Додати шар", imageFile: "Зображення…", emptyImage: "Порожнє зображення", + animTab: "Анімація", + animatedLayer: "Анімований шар", handFile: "Стрілка…", progressLine: "Смуга прогресу", vProgressLine: "Вертикальна смуга прогресу", @@ -643,6 +649,8 @@ export const t = dict( addLayer: "Añadir capa", imageFile: "Imagen…", emptyImage: "Imagen vacía", + animTab: "Animación", + animatedLayer: "Capa animada", handFile: "Manecilla…", progressLine: "Barra de progreso", vProgressLine: "Barra de progreso vertical", @@ -825,6 +833,8 @@ export const t = dict( addLayer: "लेयर जोड़ें", imageFile: "इमेज…", emptyImage: "खाली इमेज", + animTab: "एनिमेशन", + animatedLayer: "एनिमेटेड लेयर", handFile: "सुई…", progressLine: "प्रोग्रेस लाइन", vProgressLine: "खड़ी प्रोग्रेस लाइन", diff --git a/src/lib/modules/editor/model/create.model.ts b/src/lib/modules/editor/model/create.model.ts index e15246d..067a736 100644 --- a/src/lib/modules/editor/model/create.model.ts +++ b/src/lib/modules/editor/model/create.model.ts @@ -29,6 +29,7 @@ import { blankScreen, newGroup, newHand, + newAnimated, newImage, newNumber, newProgressLine, @@ -69,6 +70,8 @@ export const numberAdded = createEvent(); /** An image widget with no art yet: one transparent frame, replaced later by a dropped file or * the font generator — for when the picture doesn't exist at add time. */ export const imageAdded = createEvent(); +/** A Watch Pro 2 animated image (0x82, type 2), seeded from Sun Circle. */ +export const animatedAdded = createEvent(); export const slotAdded = createEvent(); /** A progress line: one pre-drawn frame per step of its source (see LINE_SOURCES). */ export const progressLineAdded = createEvent<{ dir: "horizontal" | "vertical"; on: LineSource }>(); @@ -152,6 +155,22 @@ const addImageFx = attach({ }, }); +// One transparent 466x466 frame (cf 4, as Sun Circle's): the art comes later. +const addAnimatedFx = attach({ + source: $screen, + async effect(screen) { + const r = await blankFrame(466, 466, 4); + const id = newImageId(); + + return { + screen, + assets: new Map([[id, { id, cf: r.cf, w: r.w, h: r.h, data: r.data }]]), + cache: new Map([[id, { bitmap: r.bitmap }]]), + layer: newAnimated([id]), + }; + }, +}); + // Ten transparent frames, one per digit: a number widget whose art comes later, from a font or // from PNGs dropped on the frames one at a time. The size is a placeholder — both paths bring // their own (replaceImageFx takes the file's, the generator the font cell's). @@ -395,6 +414,10 @@ sample({ clock: imageAdded, target: addImageFx, }); +sample({ + clock: animatedAdded, + target: addAnimatedFx, +}); sample({ clock: slotAdded, target: addSlotFx, @@ -407,6 +430,7 @@ sample({ clock: [ addWidgetFx.doneData, addImageFx.doneData, + addAnimatedFx.doneData, addNumberFx.doneData, addSlotFx.doneData, addProgressLineFx.doneData, @@ -421,6 +445,7 @@ sample({ clock: [ addWidgetFx.doneData, addImageFx.doneData, + addAnimatedFx.doneData, addNumberFx.doneData, addSlotFx.doneData, addProgressLineFx.doneData, @@ -433,6 +458,7 @@ sample({ clock: [ addWidgetFx.doneData, addImageFx.doneData, + addAnimatedFx.doneData, addNumberFx.doneData, addSlotFx.doneData, addProgressLineFx.doneData, @@ -610,6 +636,7 @@ sample({ clock: [ addWidgetFx.failData, addImageFx.failData, + addAnimatedFx.failData, addNumberFx.failData, glyphsFx.failData, addSlotFx.failData, diff --git a/src/lib/modules/editor/model/selection.model.ts b/src/lib/modules/editor/model/selection.model.ts index 55be1f9..ec3cecb 100644 --- a/src/lib/modules/editor/model/selection.model.ts +++ b/src/lib/modules/editor/model/selection.model.ts @@ -103,10 +103,12 @@ sample({ }, target: select, }); -// opening a layer's properties is what the user means by clicking it +// opening a layer's properties is what the user means by clicking it — except on the Animation +// tab, where picking a layer is how its list is used sample({ clock: [select, selectToggled], - filter: Boolean, + source: $rightPanel, + filter: (panel, picked) => Boolean(picked) && panel !== "anim", fn: () => "props" as const, target: $rightPanel, }); diff --git a/src/lib/modules/editor/model/sim.model.ts b/src/lib/modules/editor/model/sim.model.ts index 14fd5c1..00f479b 100644 --- a/src/lib/modules/editor/model/sim.model.ts +++ b/src/lib/modules/editor/model/sim.model.ts @@ -8,6 +8,7 @@ import { nextClip } from "../core/render/proc-scene"; import type { Point } from "../core/render/canvas"; import type { Doc } from "../core/document/doc"; import { $doc, docLoaded } from "./doc.model"; +import { rightPanelSet } from "./ui.model"; // ---- stores ---- export const $sim = createStore(defaultSim()); @@ -27,16 +28,28 @@ const answers = (doc: Doc | null, type: number) => Boolean(doc?.screens.some((s) => hasProc(s.layers, type))); // ---- business logic ---- +// What the animated image (0x82, type 2) reads is the daylight %, so moving the clock or the sun +// times replays its sweep, as waking the screen does. Harmless for a face without one. +const MOVES_SUN = ["time", "sunrise", "sunset", "live"] as const; + sample({ clock: simPatched, source: $sim, - fn: (sim, patch) => ({ ...sim, ...patch }), + fn: (sim, patch) => ({ + ...sim, + ...(MOVES_SUN.some((k) => k in patch) ? { wakeAt: Date.now() } : {}), + ...patch, + }), target: $sim, }); sample({ clock: overrideSet, source: $sim, - fn: (sim, { id, value }) => ({ ...sim, overrides: { ...sim.overrides, [id]: value } }), + fn: (sim, { id, value }) => ({ + ...sim, + wakeAt: Date.now(), + overrides: { ...sim.overrides, [id]: value }, + }), target: $sim, }); // the source list follows the document: a new layer can introduce a source, deleting one can @@ -76,3 +89,11 @@ sample({ fn: (sim) => ({ ...sim, touch: null, clip: 0, clipAt: null }), target: $sim, }); +// the timeline holds the canvas only while its tab is open (or until another face loads) +sample({ + clock: [rightPanelSet, docLoaded], + source: $sim, + filter: (sim, clock) => sim.scrub !== null && clock !== "anim", + fn: (sim) => ({ ...sim, scrub: null }), + target: $sim, +}); diff --git a/src/lib/modules/editor/model/ui.model.ts b/src/lib/modules/editor/model/ui.model.ts index 56b0e16..c9906e2 100644 --- a/src/lib/modules/editor/model/ui.model.ts +++ b/src/lib/modules/editor/model/ui.model.ts @@ -6,14 +6,14 @@ import { createEvent, createStore, sample } from "effector"; /** Right-side panel tab. Driven by the `select` event rather than derived from the selection: * the selection store also changes when a simulator tweak re-selects the same layer, and * deriving would flip the tab back to Properties on every input. */ -export const $rightPanel = createStore<"props" | "sim">("props"); +export const $rightPanel = createStore<"props" | "anim" | "sim">("props"); export const $err = createStore(""); /** Keep a resize proportional. One flag for both ways in: the props panel's link toggle and a * corner drag on the canvas (shift inverts it there, as everywhere else). */ export const $lockAspect = createStore(true); // ---- events ---- -export const rightPanelSet = createEvent<"props" | "sim">(); +export const rightPanelSet = createEvent<"props" | "anim" | "sim">(); export const errored = createEvent(); export const lockAspectToggled = createEvent(); diff --git a/src/lib/modules/editor/pages/editor.svelte b/src/lib/modules/editor/pages/editor.svelte index dda9b7b..45d1714 100644 --- a/src/lib/modules/editor/pages/editor.svelte +++ b/src/lib/modules/editor/pages/editor.svelte @@ -53,6 +53,7 @@ import TreePanel from "../components/TreePanel.svelte"; import PropsPanel from "../components/PropsPanel.svelte"; import SimPanel from "../components/SimPanel.svelte"; + import AnimationPanel from "../components/AnimationPanel.svelte"; import ShortcutsDialog from "../components/ShortcutsDialog.svelte"; import { t } from "../i18n"; import { t as deviceT } from "$lib/modules/device/i18n"; @@ -152,7 +153,7 @@ let dirInput = $state(); let binsInput = $state(); - let mobilePanel = $state<"tree" | "props" | "sim" | null>(null); // drawer on mobile + let mobilePanel = $state<"tree" | "props" | "anim" | "sim" | null>(null); // drawer on mobile let helpOpen = $state(false); // the `?` overlay let hits: LayerHit[] = []; @@ -540,6 +541,7 @@ ]); const panelItems = $derived([ { value: "props", label: $t.properties }, + { value: "anim", label: $t.animTab, disabled: !$doc }, { value: "sim", label: $t.simulator, disabled: !$doc }, ]); const mobileTitle = $derived( @@ -547,9 +549,11 @@ ? $t.tree : mobilePanel === "props" ? $t.properties - : mobilePanel === "sim" - ? $t.simulator - : undefined, + : mobilePanel === "anim" + ? $t.animTab + : mobilePanel === "sim" + ? $t.simulator + : undefined, ); @@ -859,12 +863,14 @@ full items={panelItems} value={$rightPanel} - onChange={(v) => rightPanelSet(v as "props" | "sim")} + onChange={(v) => rightPanelSet(v as "props" | "anim" | "sim")} />
{#if $rightPanel === "sim"} + {:else if $rightPanel === "anim"} + {:else} {/if} @@ -874,11 +880,11 @@ {#if $doc}
- {#each [["tree", "account_tree", $t.tree], ["props", "tune", $t.propsShort], ["sim", "play_arrow", $t.simShort]] as [id, icon, label] (id)} + {#each [["tree", "account_tree", $t.tree], ["props", "tune", $t.propsShort], ["anim", "wb_twilight", $t.animTab], ["sim", "play_arrow", $t.simShort]] as [id, icon, label] (id)}