Add modular Kryon motion and restore native ZX parity
This commit is contained in:
1 parent
458f222a19
commit
da94e6ad6d
19 files changed
+491
-28
No files matched your search
@@ -2,6 +2,12 @@
|
||||
|
||||
## Unreleased
|
||||
|
||||
- `kryon/motion` provides CSS easing, timed keyframes, and interruptible
|
||||
value transitions for native widgets and charts. Samples tell apps when
|
||||
their values have settled so they can stop requesting animation frames.
|
||||
- The ZX desktop player clears to the guest's default canvas color.
|
||||
Retained paint keeps its text styling state usable without a glyph
|
||||
measurement host.
|
||||
- The dashboard starter ships a locked dependency set and a quick start for
|
||||
rendering its first preview.
|
||||
- Smoothly scaled image meshes preserve the opacity of thin textures and
|
||||
|
||||
+29
@@ -83,6 +83,35 @@ their existing contracts. Pointer hover/press and keyboard focus draw state
|
||||
layers; keyboard focus adds a ring. `compact` retains the scrolling dock/rail
|
||||
layout used by Breeze, including its footer and drag/close behavior.
|
||||
|
||||
## Timed motion and keyframes
|
||||
|
||||
Import `kryon/motion` for a timed scalar transition or keyframe track.
|
||||
The module takes time and state from the caller and depends only on scalar
|
||||
math. Apply a sample to opacity, position, size, or several chart points.
|
||||
|
||||
- `Motion.TimingFor(.EaseOut)` creates a CSS timing preset. The choices are
|
||||
`.Linear`, `.Ease`, `.EaseIn`, `.EaseOut`, and `.EaseInOut`.
|
||||
`Motion.CubicBezier(x1, y1, x2, y2)` accepts CSS control points, including
|
||||
overshoot. Invalid control points yield linear timing. Use `Motion.Progress`
|
||||
to ease a unit interval directly.
|
||||
- `Motion.BuildTrack(frames)` validates a borrowed slice of `Motion.Keyframe`
|
||||
records. Start at offset `0`, end at `1`, and place any other offsets in
|
||||
increasing order. A keyframe's timing governs the segment leaving it.
|
||||
Keep the slice alive and unchanged. `Motion.At(track, progress)` samples
|
||||
by normalized progress. `Motion.Sample(track, elapsed, duration, iterations,
|
||||
alternate, reduced_motion)` samples by seconds and reports `.value` and
|
||||
`.active`. Reduced motion settles at the same endpoint as ordinary playback.
|
||||
- `Motion.TweenTo(*state, target, now, duration, timing, reduced_motion)`
|
||||
starts an implicit transition when the target changes. Give each value its
|
||||
own zero-initialized `Motion.TweenState`. The first call initializes at the
|
||||
supplied target. Changing targets mid-flight starts at the current value.
|
||||
Pass monotonic seconds and request motion frames while `.active` is true.
|
||||
|
||||
The [checked usage example](../src/ui/motion_api_example.zi) samples a whole
|
||||
series with one easing calculation per frame and shows an interrupted hover
|
||||
transition. Keep the chart's scale and the input series stable while they
|
||||
interpolate. Pass the resulting values to your usual chart drawing code.
|
||||
|
||||
## Widget motion
|
||||
|
||||
`Menu.Props`, `TabBar.Props`, `Navigation.Props`, and `Collapsible.Props`
|
||||
|
||||
@@ -159,6 +159,30 @@ Bind selectors on widgets via `props.class_name = CSS.StyleClass("primary")` and
|
||||
- **At-rules**: `@import` (before rules), `@layer`, `@keyframes`, `@media` (`prefers-color-scheme`, `prefers-contrast`, `prefers-reduced-motion`, `pointer`, `min-width`, `max-width`, `-kryon-theme`, `-kryon-density`, `-kryon-pointer`, `-kryon-platform`).
|
||||
- **Web-only pass-through properties** (accepted by parser for `kryon/Dom`, ignored by native widgets): `width`, `height`, `min-width`, `max-width`, `max-height`, `margin*`, `display`, `flex*`, `justify-content`, `align-items`, `align-self`, `grid-*`, `text-align`, `text-decoration`, `text-transform`, `white-space`, `cursor`, `box-shadow`, `transition`, `animation`, `overflow`, `z-index`, `visibility`.
|
||||
|
||||
Use `color-mix(in srgb, #2076c0 35%, transparent)` in a native color
|
||||
declaration or custom property to derive a tint from two literal colors.
|
||||
For native `@media (prefers-reduced-motion: reduce)` rules, set
|
||||
`env.reduced_motion` from `Theme.CurrentTheme().motion.reduced_motion` and
|
||||
reinstall the parsed sheet when that preference changes. DOM output uses
|
||||
the browser's live preference.
|
||||
|
||||
### Map CSS motion to native values
|
||||
|
||||
| CSS authoring pattern | Native Kryon equivalent |
|
||||
| --- | --- |
|
||||
| `transition: opacity 180ms ease-out` | `Motion.TweenTo(*opacity, target, now, 0.18, Motion.TimingFor(.EaseOut), reduce)` |
|
||||
| `@keyframes` with `0%`, `40%`, `100%` | `Motion.Keyframe` offsets `0.0`, `0.4`, `1.0` passed to `Motion.BuildTrack` |
|
||||
| `cubic-bezier(.2,.8,.2,1)` | `Motion.CubicBezier(0.2, 0.8, 0.2, 1.0)` |
|
||||
| `animation-duration` and `animation-iteration-count` | `Motion.Sample` with elapsed time, duration in seconds, and iteration count |
|
||||
| `animation-direction: alternate` | `alternate = true` in `Motion.Sample` |
|
||||
| `prefers-reduced-motion: reduce` | Pass the app or theme's reduced-motion setting to `TweenTo` and `Sample` |
|
||||
|
||||
Import `Motion :: #import "kryon/motion";`. The app owns the clock, the values
|
||||
it animates, and each transition's state. A chart can sample one track and use
|
||||
its `.value` to interpolate every point. Request animation frames while any
|
||||
sample is `.active`. See the [checked example](../src/ui/motion_api_example.zi)
|
||||
and the [motion API](API.md#timed-motion-and-keyframes).
|
||||
|
||||
---
|
||||
|
||||
## 5. Runnable Example: Searchable Card with Real CSS
|
||||
|
||||
+3
-2
@@ -10,7 +10,8 @@ KRYON_SOURCES := $(shell find ../src/ui ../src/backend -type f -name '*.zi' -pri
|
||||
BUILD_DIR ?= ../build/examples
|
||||
NATIVE_LIB := ../build/ziran/libkryon.a
|
||||
PROGRAMS := hello window
|
||||
NATIVE_PROGRAMS := $(addprefix $(BUILD_DIR)/,$(PROGRAMS))
|
||||
DESKTOP_PROGRAMS := $(PROGRAMS) motion_chart
|
||||
NATIVE_PROGRAMS := $(addprefix $(BUILD_DIR)/,$(DESKTOP_PROGRAMS))
|
||||
GO_PROGRAMS := $(addsuffix .go.stamp,$(addprefix $(BUILD_DIR)/matrix/,$(PROGRAMS)))
|
||||
WEB_PROGRAMS := $(addsuffix .web.stamp,$(addprefix $(BUILD_DIR)/matrix/,$(PROGRAMS)))
|
||||
ZX_PROGRAMS := $(addsuffix .zx,$(addprefix $(BUILD_DIR)/matrix/,$(PROGRAMS)))
|
||||
@@ -73,7 +74,7 @@ $(BUILD_DIR)/matrix/$(1).zx: $(1).zi $(KRYON_SOURCES) ../ziran.toml Makefile
|
||||
--entry $(1):main -o $$@ $(1).zi
|
||||
endef
|
||||
|
||||
$(foreach program,$(PROGRAMS),$(eval $(call PROGRAM_RULES,$(program))))
|
||||
$(foreach program,$(DESKTOP_PROGRAMS),$(eval $(call PROGRAM_RULES,$(program))))
|
||||
|
||||
.PHONY: widget-catalog widget-catalog-web
|
||||
widget-catalog:
|
||||
|
||||
@@ -78,6 +78,11 @@ button, pointer, capture, or test-driver code. Button behavior remains covered
|
||||
by the dedicated button examples and widget regression tests. The `test`
|
||||
target also compiles both programs for Go, C/Web, and portable ZX.
|
||||
|
||||
`make -C examples ../build/examples/motion_chart` builds the animated revenue
|
||||
chart. Run `build/examples/motion_chart` from the repository root and click
|
||||
**Switch week**. One `kryon/motion` tween drives the full series. Clicking again
|
||||
mid-animation reverses smoothly from the currently displayed values.
|
||||
|
||||
`make -C examples desktop-image-test` renders the canonical
|
||||
`Image.Draw(Image.Props)` with a path-backed PNG and red tint, then writes
|
||||
`build/examples/image-desktop.png`. The host imports Ziran's generic
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
App :: #import "kryon/app";
|
||||
Box :: #import "kryon/box";
|
||||
Button :: #import "kryon/button";
|
||||
Desktop :: #import "kryon/desktop_runtime";
|
||||
Motion :: #import "kryon/motion";
|
||||
Shape :: #import "kryon/shape";
|
||||
Text :: #import "kryon/text";
|
||||
Theme :: #import "kryon/theme";
|
||||
#import "kryon/drawing_props"
|
||||
#import "kryon/frame_snapshot"
|
||||
#import "kryon/geometry"
|
||||
#import "kryon/session"
|
||||
#import "kryon/tree"
|
||||
|
||||
week: Motion.TweenState;
|
||||
week_easing: Motion.Timing;
|
||||
current_week: bool = true;
|
||||
|
||||
// Each frame samples one value. The whole series moves on a fixed scale.
|
||||
DrawSeries :: (session: Session, bounds: Rectangle, phase: float32, palette: Theme.Palette) {
|
||||
grid := ColorFromPacked(palette.subtle_border)
|
||||
line := ColorFromPacked(palette.accent)
|
||||
shade := line
|
||||
shade.a = 28
|
||||
previous: [6]float32 = .{0.16, 0.26, 0.22, 0.38, 0.32, 0.42}
|
||||
current: [6]float32 = .{0.20, 0.48, 0.34, 0.69, 0.63, 0.91}
|
||||
points: [6]Vector2
|
||||
bottom := bounds.y + bounds.height
|
||||
for index: 0..4 {
|
||||
y := bounds.y + bounds.height * cast(float32)index / 4.0
|
||||
unused Shape.Draw(session, Shape.Props.{.key = cast(u64)(20 + index),
|
||||
.start = .{bounds.x, y}, .end = .{bounds.x + bounds.width, y}, .color = grid})
|
||||
}
|
||||
for index: 0..5 {
|
||||
value := previous[index] + (current[index] - previous[index]) * phase
|
||||
points[index] = .{bounds.x + bounds.width * cast(float32)index / 5.0,
|
||||
bottom - bounds.height * value}
|
||||
}
|
||||
for index: 0..4 {
|
||||
from := points[index]
|
||||
to := points[index + 1]
|
||||
left := Vector2.{from.x, bottom}
|
||||
right := Vector2.{to.x, bottom}
|
||||
key := cast(u64)(30 + index * 3)
|
||||
unused Shape.Triangle(session, Shape.TriangleProps.{.key = key,
|
||||
.first = from, .second = to, .third = right, .color = shade})
|
||||
unused Shape.Triangle(session, Shape.TriangleProps.{.key = key + 1,
|
||||
.first = from, .second = right, .third = left, .color = shade})
|
||||
unused Shape.Draw(session, Shape.Props.{.key = key + 2,
|
||||
.start = from, .end = to, .thickness = 2.5, .color = line})
|
||||
}
|
||||
unused Shape.Circle(session, Shape.CircleProps.{.key = 50,
|
||||
.center = points[5], .radius = 4.5, .fill = line})
|
||||
}
|
||||
|
||||
Draw :: (frame: App.Frame) {
|
||||
session := Session.{.slot = frame.slot, .epoch = frame.epoch}
|
||||
bounds := TreeRootBounds(session)
|
||||
if bounds.width < 280.0 || bounds.height < 240.0 { return }
|
||||
theme := Theme.CurrentTheme()
|
||||
x := bounds.x + 48.0
|
||||
y := bounds.y + 46.0
|
||||
unused Box.Draw(session, Box.Props.{.key = 1, .bounds = bounds,
|
||||
.fill = ColorFromPacked(theme.colors.background)})
|
||||
unused Box.Draw(session, Box.Props.{.key = 2, .radius = 18.0,
|
||||
.bounds = .{x - 24.0, y - 22.0, bounds.width - 48.0, bounds.height - 48.0},
|
||||
.fill = ColorFromPacked(theme.colors.surface_raised), .border = ColorFromPacked(theme.colors.border)})
|
||||
Text.Draw(session, Text.Props.{.key = 3, .bounds = .{x, y, 104.0, 36.0}, .text = "Revenue", .size = 25})
|
||||
if Button.Draw(session, Button.Props.{.key = 4, .label = "Switch week",
|
||||
.bounds = .{bounds.x + bounds.width - 158.0, y, 110.0, 36.0}}) != 0 {
|
||||
current_week = !current_week
|
||||
}
|
||||
Text.Draw(session, Text.Props.{.key = 5, .bounds = .{x, y + 42.0, 165.0, 24.0},
|
||||
.text = ifx current_week then "Current week" else "Previous week", .size = 14})
|
||||
now := cast(float64)CaptureFrameInput(session).elapsed_ms / 1000.0
|
||||
target: float32 = ifx current_week then 1.0 else 0.0
|
||||
phase := Motion.TweenTo(*week, target, now, 0.42 * cast(float64)theme.motion.multiplier,
|
||||
week_easing, theme.motion.reduced_motion)
|
||||
DrawSeries(session, .{x, y + 82.0, bounds.width - 96.0, bounds.height - 181.0}, phase.value, theme.colors)
|
||||
if phase.active { Desktop.DesktopRequestFrame() }
|
||||
}
|
||||
|
||||
main :: () -> s32 {
|
||||
week_easing = Motion.TimingFor(.EaseOut)
|
||||
return App.Run(App.Window.{.title = "Animated revenue chart", .width = 600, .height = 360}, Draw)
|
||||
}
|
||||
@@ -20,7 +20,6 @@ ImageSchema :: #import "image_props";
|
||||
#import "page_core"
|
||||
#import "canvas_window"
|
||||
#import "web"
|
||||
Metrics :: #import "font_metrics";
|
||||
|
||||
libm :: #system_library "m";
|
||||
CanvasSqrt :: (value: float32) -> float32 #foreign libm "sqrtf";
|
||||
@@ -107,7 +106,7 @@ MeasureGlyphWidth :: (value: string, font: s32,
|
||||
defer { unused TextTypefaceUse(previous) }
|
||||
face: s32 = 0
|
||||
if canvas_font_loaded { face = CanvasFontFace(canvas_font) }
|
||||
glyphs := Metrics.text_glyph_style
|
||||
glyphs := text_glyph_style
|
||||
width := PageTextWidth(face, value, font, glyphs.weight, cast(s32)glyphs.style, glyphs.letter_spacing)
|
||||
return ifx width > 0.0 then cast(s32)(width + 0.5) else 0
|
||||
}
|
||||
@@ -165,7 +164,7 @@ RasterText :: (value: string, x: s32, y: s32,
|
||||
font: s32, color: Color) {
|
||||
face: s32 = 0
|
||||
if canvas_font_loaded { face = CanvasFontFace(canvas_font) }
|
||||
glyphs := Metrics.text_glyph_style
|
||||
glyphs := text_glyph_style
|
||||
PageTextDraw(face, value, x, y, font, color.r, color.g, color.b, color.a,
|
||||
glyphs.weight, cast(s32)glyphs.style, glyphs.letter_spacing)
|
||||
}
|
||||
|
||||
@@ -1062,7 +1062,7 @@ PixmapMeasureCaret :: (value: string, byte: s32, font: s32, typeface: string) ->
|
||||
}
|
||||
|
||||
PixmapMeasureWidth :: (value: string, font: s32, trailing: bool) -> s32 {
|
||||
glyphs := Metrics.text_glyph_style
|
||||
glyphs := Typeface.text_glyph_style
|
||||
tracking := PixmapTracking(glyphs.letter_spacing)
|
||||
bounded: bool = value.count <= PixmapMeasureBytes
|
||||
units: s64 = 0
|
||||
@@ -1288,7 +1288,7 @@ PixmapDrawText :: (value: string, x: s32, y: s32, font: s32, pen_font: s64, colo
|
||||
baseline: s64 = cast(s64)y * 256 + PixmapTextBaseline(font)
|
||||
pen: s64 = 0
|
||||
shift: s64 = 0
|
||||
glyphs := Metrics.text_glyph_style
|
||||
glyphs := Typeface.text_glyph_style
|
||||
tracking := PixmapTracking(glyphs.letter_spacing, pixmap_scale_x)
|
||||
next_cluster: s32 = 0
|
||||
if tracking != 0 { next_cluster = Grapheme.Next(value, 0) }
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
#import "font_metrics"
|
||||
#import "math"
|
||||
#import "paint_queue"
|
||||
#import "text_typeface"
|
||||
#import "utf8"
|
||||
#import "std/byte_text_linux"
|
||||
CString :: #import "std/c_string";
|
||||
|
||||
+6
-14
@@ -1,14 +1,9 @@
|
||||
#import "control_props"
|
||||
Typeface :: #import "text_typeface";
|
||||
host_api :: #system_library "host_api";
|
||||
|
||||
// Native text scopes its glyph inputs around a synchronous host call. Hosts
|
||||
// that draw the default face keep the existing measurement/raster ABI.
|
||||
text_glyph_style: TextGlyphStyle;
|
||||
|
||||
UseTextGlyphStyle :: (style: TextGlyphStyle) -> TextGlyphStyle {
|
||||
previous := text_glyph_style
|
||||
if !SameTextGlyphStyle(style, previous) { text_glyph_style = style }
|
||||
return previous
|
||||
return Typeface.SetTextGlyphStyle(style)
|
||||
}
|
||||
|
||||
// Font rasterizers report physical glyph measurements. UI layout stays in Kryon.
|
||||
@@ -18,11 +13,6 @@ MeasureGlyphWidth :: (value: string, font: s32,
|
||||
typeface: string) -> s32 #reads #foreign host_api;
|
||||
MeasureGlyphLineHeight :: (font: s32, typeface: string) -> s32 #reads #foreign host_api;
|
||||
|
||||
// Zero keeps layout uncached for hosts whose font services may change without
|
||||
// notification. A host opts in by publishing its initial metrics, then calls
|
||||
// GlyphMetricsChanged whenever it replaces fonts or changes their advances.
|
||||
glyph_metrics_revision: u64;
|
||||
|
||||
// A shaping host can measure a caret in the full run, preserving ligatures
|
||||
// and bidi context. Other hosts keep their existing prefix measurements.
|
||||
CaretMeasure :: #type (string, s32, s32, string) -> s32 #reads;
|
||||
@@ -101,12 +91,14 @@ GlyphCaret :: (value: string, byte: s32, font: s32, typeface: string,
|
||||
return MeasureGlyphWidth(value[:byte], font, typeface)
|
||||
}
|
||||
|
||||
// Zero keeps layout uncached. A host publishes its initial metrics, then
|
||||
// calls GlyphMetricsChanged when it replaces fonts or changes their advances.
|
||||
#program_export
|
||||
GlyphMetricsRevision :: () -> u64 { return glyph_metrics_revision }
|
||||
GlyphMetricsRevision :: () -> u64 { return Typeface.glyph_metrics_revision }
|
||||
|
||||
#program_export
|
||||
GlyphMetricsChanged :: () {
|
||||
glyph_metrics_revision += cast(u64)1
|
||||
Typeface.glyph_metrics_revision += cast(u64)1
|
||||
}
|
||||
|
||||
#program_export
|
||||
|
||||
@@ -0,0 +1,185 @@
|
||||
// Scalar motion sampled on the caller's clock, with no host or drawing imports.
|
||||
|
||||
Easing :: enum {
|
||||
Linear :: 0
|
||||
Ease :: 1
|
||||
EaseIn :: 2
|
||||
EaseOut :: 3
|
||||
EaseInOut :: 4
|
||||
}
|
||||
|
||||
Timing :: struct {
|
||||
curved: bool
|
||||
x1: float64
|
||||
y1: float64
|
||||
x2: float64
|
||||
y2: float64
|
||||
}
|
||||
|
||||
Keyframe :: struct {
|
||||
offset: float32
|
||||
value: float32
|
||||
timing: Timing
|
||||
}
|
||||
|
||||
Track :: struct {
|
||||
keyframes: []Keyframe
|
||||
}
|
||||
|
||||
SampleResult :: struct {
|
||||
value: float32
|
||||
active: bool
|
||||
}
|
||||
|
||||
TweenState :: struct {
|
||||
initialized: bool
|
||||
active: bool
|
||||
now: float64
|
||||
started: float64
|
||||
value: float32
|
||||
from: float32
|
||||
target: float32
|
||||
duration: float64
|
||||
timing: Timing
|
||||
}
|
||||
|
||||
#scope_file
|
||||
|
||||
MaxSeconds :: 1.7976931348623157e308
|
||||
|
||||
FiniteValue :: (value: float32) -> bool {
|
||||
return value >= -3.402823466e38 && value <= 3.402823466e38
|
||||
}
|
||||
|
||||
BezierValue :: (first: float64, second: float64, t: float64) -> float64 {
|
||||
inverse := 1.0 - t
|
||||
return 3.0 * inverse * t * (inverse * first + t * second) + t * t * t
|
||||
}
|
||||
|
||||
Interpolate :: (from: float32, to: float32, progress: float32) -> float32 {
|
||||
if progress == 0.0 { return from }
|
||||
if progress == 1.0 { return to }
|
||||
first := cast(float64)from
|
||||
value := first + (cast(float64)to - first) * cast(float64)progress
|
||||
if value > 3.402823466e38 { return 3.402823466e38 }
|
||||
if value < -3.402823466e38 { return -3.402823466e38 }
|
||||
return cast(float32)value
|
||||
}
|
||||
|
||||
#scope_export
|
||||
|
||||
// Invalid control points leave the timing linear. CSS permits y to overshoot.
|
||||
CubicBezier :: (x1: float32, y1: float32, x2: float32, y2: float32) -> Timing {
|
||||
if !(x1 >= 0.0 && x1 <= 1.0 && x2 >= 0.0 && x2 <= 1.0) ||
|
||||
!FiniteValue(y1) || !FiniteValue(y2) || (x1 == y1 && x2 == y2) {
|
||||
return Timing.{}
|
||||
}
|
||||
return Timing.{true, cast(float64)x1, cast(float64)y1, cast(float64)x2, cast(float64)y2}
|
||||
}
|
||||
|
||||
TimingFor :: (ease: Easing) -> Timing {
|
||||
if ease == .Ease { return CubicBezier(0.25, 0.1, 0.25, 1.0) }
|
||||
if ease == .EaseIn { return CubicBezier(0.42, 0.0, 1.0, 1.0) }
|
||||
if ease == .EaseOut { return CubicBezier(0.0, 0.0, 0.58, 1.0) }
|
||||
if ease == .EaseInOut { return CubicBezier(0.42, 0.0, 0.58, 1.0) }
|
||||
return Timing.{}
|
||||
}
|
||||
|
||||
Progress :: (timing: Timing, progress: float32) -> float32 {
|
||||
if !(progress > 0.0) { return 0.0 }
|
||||
if progress >= 1.0 { return 1.0 }
|
||||
if !timing.curved { return progress }
|
||||
// Bezier x is monotonic for valid CSS x control points. A fixed search
|
||||
// also converges on near-flat portions where Newton iteration is unstable.
|
||||
x := cast(float64)progress
|
||||
low: float64 = 0.0
|
||||
high: float64 = 1.0
|
||||
for iteration: 0..19 {
|
||||
middle := (low + high) * 0.5
|
||||
if BezierValue(timing.x1, timing.x2, middle) < x { low = middle }
|
||||
else { high = middle }
|
||||
}
|
||||
return cast(float32)BezierValue(timing.y1, timing.y2, (low + high) * 0.5)
|
||||
}
|
||||
|
||||
// Validate once. Keep the borrowed frames alive and unchanged while using the track.
|
||||
BuildTrack :: (keyframes: []Keyframe) -> Track {
|
||||
if keyframes.count < 2 || keyframes[0].offset != 0.0 ||
|
||||
keyframes[keyframes.count - 1].offset != 1.0 { return Track.{} }
|
||||
previous: float32 = -1.0
|
||||
for frame: keyframes {
|
||||
if !(frame.offset > previous && frame.offset <= 1.0) ||
|
||||
!FiniteValue(frame.value) { return Track.{} }
|
||||
previous = frame.offset
|
||||
}
|
||||
return Track.{keyframes}
|
||||
}
|
||||
|
||||
// Timing belongs to the outgoing segment. Search only the enclosing pair.
|
||||
At :: (track: Track, progress: float32) -> float32 {
|
||||
frames := track.keyframes
|
||||
if frames.count < 2 { return 0.0 }
|
||||
if !(progress > 0.0) { return frames[0].value }
|
||||
last := frames.count - 1
|
||||
if progress >= 1.0 { return frames[last].value }
|
||||
low := 0
|
||||
high := last
|
||||
while high - low > 1 {
|
||||
middle := low + (high - low) / 2
|
||||
if progress < frames[middle].offset { high = middle }
|
||||
else { low = middle }
|
||||
}
|
||||
first := frames[low]
|
||||
second := frames[high]
|
||||
part := (progress - first.offset) / (second.offset - first.offset)
|
||||
return Interpolate(first.value, second.value, Progress(first.timing, part))
|
||||
}
|
||||
|
||||
// Request another frame only while active. Negative elapsed is before playback.
|
||||
Sample :: (track: Track, elapsed: float64, duration: float64,
|
||||
iterations: s32 = 1, alternate: bool = false, reduced_motion: bool = false) -> SampleResult {
|
||||
if track.keyframes.count < 2 { return SampleResult.{} }
|
||||
if !reduced_motion && iterations > 0 && duration > 0.0 && duration <= MaxSeconds {
|
||||
cycles := elapsed / duration
|
||||
if !(cycles >= 0.0) { return SampleResult.{At(track, 0.0), false} }
|
||||
if cycles < cast(float64)iterations {
|
||||
iteration := cast(s32)cycles
|
||||
phase := cast(float32)(cycles - cast(float64)iteration)
|
||||
if alternate && iteration % 2 != 0 { phase = 1.0 - phase }
|
||||
return SampleResult.{At(track, phase), true}
|
||||
}
|
||||
}
|
||||
final: float32 = ifx alternate && iterations > 0 && iterations % 2 == 0 then 0.0 else 1.0
|
||||
return SampleResult.{At(track, final), false}
|
||||
}
|
||||
|
||||
// Use one zero-initialized state per animated value. A new target starts at
|
||||
// the value sampled at the current time, including on reversals.
|
||||
TweenTo :: (state: *TweenState, target: float32, now: float64,
|
||||
duration: float64, timing: Timing, reduced_motion: bool = false) -> SampleResult {
|
||||
if !FiniteValue(target) { target = ifx state == null then 0.0 else state.target }
|
||||
if state == null { return SampleResult.{target, false} }
|
||||
if now >= state.now && now <= MaxSeconds { state.now = now }
|
||||
if !state.initialized || reduced_motion || !(duration > 0.0 && duration <= MaxSeconds) {
|
||||
state.initialized = true
|
||||
state.value = target
|
||||
state.target = target
|
||||
state.active = false
|
||||
return SampleResult.{target, false}
|
||||
}
|
||||
if state.active {
|
||||
progress := cast(float32)((state.now - state.started) / state.duration)
|
||||
state.active = progress < 1.0
|
||||
eased := Progress(state.timing, progress)
|
||||
state.value = Interpolate(state.from, state.target, eased)
|
||||
}
|
||||
if state.target != target {
|
||||
state.from = state.value
|
||||
state.target = target
|
||||
state.started = state.now
|
||||
state.duration = duration
|
||||
state.timing = timing
|
||||
state.active = state.from != target
|
||||
}
|
||||
return SampleResult.{state.value, state.active}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
ziran-api-examples-v1
|
||||
function TimingFor motion_api_example.zi
|
||||
function BuildTrack motion_api_example.zi
|
||||
function Sample motion_api_example.zi
|
||||
function TweenTo motion_api_example.zi
|
||||
@@ -0,0 +1,41 @@
|
||||
Motion :: #import "motion";
|
||||
|
||||
#scope_file
|
||||
|
||||
// Keep frames and the output samples in the caller's state. One eased phase
|
||||
// moves every point on a fixed chart scale, including the final sample.
|
||||
ChartValues :: (track: Motion.Track, elapsed: float64, reduced: bool,
|
||||
values: []float32) -> bool {
|
||||
from: [3]float32 = .{0.20, 0.24, 0.42}
|
||||
to: [3]float32 = .{0.35, 0.30, 0.91}
|
||||
phase := Motion.Sample(track, elapsed, 0.6, 1, false, reduced)
|
||||
for index: 0..2 {
|
||||
values[index] = ifx phase.value == 1.0 then to[index] else from[index] + (to[index] - from[index]) * phase.value
|
||||
}
|
||||
return phase.active
|
||||
}
|
||||
|
||||
#scope_export
|
||||
|
||||
#program_export
|
||||
main :: () -> s32 {
|
||||
// Validate the track once, after placing the keyframes in their storage.
|
||||
keyframes: [2]Motion.Keyframe = .{
|
||||
Motion.Keyframe.{.offset = 0.0, .value = 0.0,
|
||||
.timing = Motion.TimingFor(.EaseOut)},
|
||||
Motion.Keyframe.{.offset = 1.0, .value = 1.0}
|
||||
}
|
||||
track := Motion.BuildTrack(keyframes[:])
|
||||
values: [3]float32
|
||||
if !ChartValues(track, 0.3, false, values[:]) || values[2] <= 0.42 || values[2] >= 0.91 { return 1 }
|
||||
if ChartValues(track, 0.0, true, values[:]) || values[2] != 0.91 { return 2 }
|
||||
|
||||
// Treat a target change like a CSS transition of a single property.
|
||||
hover: Motion.TweenState
|
||||
easing := Motion.TimingFor(.EaseOut)
|
||||
unused Motion.TweenTo(*hover, 0.0, 0.0, 0.18, easing)
|
||||
unused Motion.TweenTo(*hover, 1.0, 1.0, 0.18, easing)
|
||||
reversed := Motion.TweenTo(*hover, 0.0, 1.09, 0.18, easing)
|
||||
if !reversed.active || reversed.value <= 0.5 || reversed.value >= 1.0 { return 3 }
|
||||
return 0
|
||||
}
|
||||
@@ -3,7 +3,6 @@ Bitmaps :: #import "bitmap_store";
|
||||
#import "drawing_props"
|
||||
#import "control_props"
|
||||
#import "geometry"
|
||||
Metrics :: #import "font_metrics";
|
||||
#import "elevation"
|
||||
#import "image_behavior"
|
||||
#import "paint_texture"
|
||||
@@ -659,8 +658,8 @@ EmitLabel :: (command: PaintCommand) {
|
||||
previous_name := text_raster_typeface
|
||||
text_raster_typeface = command.asset_path
|
||||
defer { text_raster_typeface = previous_name }
|
||||
previous_style := Metrics.UseTextGlyphStyle(command.glyph_style)
|
||||
defer { unused Metrics.UseTextGlyphStyle(previous_style) }
|
||||
previous_style := SetTextGlyphStyle(command.glyph_style)
|
||||
defer { unused SetTextGlyphStyle(previous_style) }
|
||||
if command.rotation != 0.0 {
|
||||
PaintTextRotated(command.value,command.x,command.y,command.font,command.color,
|
||||
command.clip,command.origin,command.rotation,command.text_outer_clip,
|
||||
@@ -1293,7 +1292,7 @@ PaintCommandEqual :: (slot: s32, current: PaintCommand,
|
||||
current.italic != previous.data.italic { return false }
|
||||
if !SameTextGlyphStyle(current.glyph_style, previous.data.glyph_style) { return false }
|
||||
if (current.kind == PaintKindText || current.kind == PaintKindClippedText) &&
|
||||
previous.text_revision != Metrics.GlyphMetricsRevision() { return false }
|
||||
previous.text_revision != glyph_metrics_revision { return false }
|
||||
if !SnapshotAssetEqual(slot, current.asset_path, previous.asset_start,
|
||||
previous.asset_count) { return false }
|
||||
if current.texture_id != previous.data.texture_id ||
|
||||
@@ -1376,7 +1375,7 @@ PaintSnapshotStore :: (session: Session) -> bool {
|
||||
previous.data = current
|
||||
previous.bitmap_revision = PaintBitmapRevision(current.texture_id)
|
||||
if current.kind == PaintKindText || current.kind == PaintKindClippedText {
|
||||
previous.text_revision = Metrics.GlyphMetricsRevision()
|
||||
previous.text_revision = glyph_metrics_revision
|
||||
}
|
||||
previous.emit = pending_paint[slot].items[index].emit
|
||||
previous.has_emitter = pending_paint[slot].items[index].has_emitter
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
#import "control_props"
|
||||
|
||||
// A raster host selects a font only for the current measurement or label.
|
||||
// Names and font asset paths share the same bounded resource identity.
|
||||
TextTypefaceSelector :: #type (name: string) -> string #reads;
|
||||
@@ -8,6 +10,17 @@ text_typeface_installed: bool;
|
||||
// name from the same queued command.
|
||||
text_raster_typeface: string;
|
||||
|
||||
// Paint and measurement share these inputs without depending on each other's
|
||||
// host functions. A synchronous host call borrows the current glyph style.
|
||||
text_glyph_style: TextGlyphStyle;
|
||||
glyph_metrics_revision: u64;
|
||||
|
||||
SetTextGlyphStyle :: (style: TextGlyphStyle) -> TextGlyphStyle {
|
||||
previous := text_glyph_style
|
||||
if !SameTextGlyphStyle(style, previous) { text_glyph_style = style }
|
||||
return previous
|
||||
}
|
||||
|
||||
#program_export
|
||||
SetTextTypefaceSelector :: (select: TextTypefaceSelector) {
|
||||
text_typeface_selector = select
|
||||
|
||||
@@ -8,17 +8,84 @@ work=$(mktemp -d)
|
||||
trap 'rm -rf "$work"' EXIT HUP INT TERM
|
||||
|
||||
cp "$repo/src/ui/transition.zi" "$work/transition.zi"
|
||||
cp "$repo/src/ui/motion.zi" "$work/motion.zi"
|
||||
cp "$repo/src/ui/drawing_props.zi" "$work/drawing_props.zi"
|
||||
cp "$repo/src/ui/geometry.zi" "$work/geometry.zi"
|
||||
cp "$repo/src/ui/text_align.zi" "$work/text_align.zi"
|
||||
cp "$ziran_root/std/math.zi" "$work/math.zi"
|
||||
cat > "$work/use_transition.zi" <<'EOF'
|
||||
#import "transition"
|
||||
Motion :: #import "motion";
|
||||
|
||||
using TransitionPhase;
|
||||
|
||||
Near :: (value: float32, expected: float32) -> bool {
|
||||
return value > expected - 0.00002 && value < expected + 0.00002
|
||||
}
|
||||
|
||||
TimedTracksWork :: () -> bool {
|
||||
if Motion.Progress(Motion.TimingFor(.Linear), 0.5) != 0.5 ||
|
||||
!Near(Motion.Progress(Motion.TimingFor(.Ease), 0.5), 0.8024034) ||
|
||||
!Near(Motion.Progress(Motion.TimingFor(.EaseIn), 0.5), 0.3153568) ||
|
||||
!Near(Motion.Progress(Motion.TimingFor(.EaseOut), 0.5), 0.6846432) ||
|
||||
!Near(Motion.Progress(Motion.TimingFor(.EaseInOut), 0.5), 0.5) { return false }
|
||||
if Motion.Progress(Motion.CubicBezier(-1.0, 0.0, 1.0, 1.0), 0.5) != 0.5 ||
|
||||
Motion.Progress(Motion.CubicBezier(0.2, 1.4, 0.8, 1.4), 0.5) <= 1.0 ||
|
||||
!Near(Motion.Progress(Motion.CubicBezier(1.0, 0.0, 0.0, 1.0), 0.5), 0.5) {
|
||||
return false
|
||||
}
|
||||
frames: [3]Motion.Keyframe = .{
|
||||
Motion.Keyframe.{.offset = 0.0, .value = 4.0},
|
||||
Motion.Keyframe.{.offset = 0.25, .value = 16.0, .timing = Motion.TimingFor(.Ease)},
|
||||
Motion.Keyframe.{.offset = 1.0, .value = 8.0}
|
||||
}
|
||||
track := Motion.BuildTrack(frames[:])
|
||||
if Motion.At(track, 0.125) != 10.0 ||
|
||||
Motion.At(track, 0.25) != 16.0 ||
|
||||
!Near(Motion.At(track, 0.625), 9.580773) { return false }
|
||||
before := Motion.Sample(track, -0.25, 1.0)
|
||||
moving := Motion.Sample(track, 0.25, 2.0)
|
||||
repeated := Motion.Sample(track, 1.125, 1.0, 2)
|
||||
reversed := Motion.Sample(track, 1.375, 1.0, 2, true)
|
||||
ended := Motion.Sample(track, 2.0, 1.0, 2, true)
|
||||
decimal_end := Motion.Sample(track, 0.6, 0.6)
|
||||
reduced := Motion.Sample(track, 0.0, 1.0, 1, false, true)
|
||||
instant := Motion.Sample(track, 0.0, 0.0)
|
||||
if before.active || before.value != 4.0 || !moving.active || moving.value != 10.0 ||
|
||||
!repeated.active || repeated.value != 10.0 || !reversed.active ||
|
||||
!Near(reversed.value, 9.580773) || ended.active || ended.value != 4.0 ||
|
||||
decimal_end.active || decimal_end.value != 8.0 ||
|
||||
reduced.active || reduced.value != 8.0 || instant.active || instant.value != 8.0 {
|
||||
return false
|
||||
}
|
||||
frames[1].offset = 1.0
|
||||
invalid := Motion.Sample(Motion.BuildTrack(frames[:]), 0.0, 1.0)
|
||||
return !invalid.active && invalid.value == 0.0
|
||||
}
|
||||
|
||||
TweenWorks :: () -> bool {
|
||||
state: Motion.TweenState
|
||||
timing := Motion.TimingFor(.Linear)
|
||||
initial := Motion.TweenTo(*state, 0.0, 50.0, 1.0, timing)
|
||||
started := Motion.TweenTo(*state, 10.0, 51.0, 1.0, timing)
|
||||
moving := Motion.TweenTo(*state, 10.0, 51.25, 1.0, timing)
|
||||
backward := Motion.TweenTo(*state, 10.0, 51.1, 1.0, timing)
|
||||
reversal := Motion.TweenTo(*state, 0.0, 51.5, 1.0, timing)
|
||||
reversed := Motion.TweenTo(*state, 0.0, 52.0, 1.0, timing)
|
||||
settled := Motion.TweenTo(*state, 0.0, 52.5, 1.0, timing)
|
||||
reduced := Motion.TweenTo(*state, 6.0, 53.0, 1.0, timing, true)
|
||||
immediate := Motion.TweenTo(null, 8.0, 0.0, 1.0, timing)
|
||||
return !initial.active && initial.value == 0.0 && started.active && started.value == 0.0 &&
|
||||
moving.active && moving.value == 2.5 && backward.active && backward.value == 2.5 &&
|
||||
reversal.active && reversal.value == 5.0 && reversed.active && reversed.value == 2.5 &&
|
||||
!settled.active && settled.value == 0.0 && !reduced.active && reduced.value == 6.0 &&
|
||||
!immediate.active && immediate.value == 8.0
|
||||
}
|
||||
|
||||
#program_export
|
||||
Answer :: () -> s32 {
|
||||
if !TimedTracksWork() { return 9 }
|
||||
if !TweenWorks() { return 10 }
|
||||
if TransitionClampProgress(-2.0) != 0.0 { return 0 }
|
||||
if TransitionClampProgress(2.0) != 1.0 { return 0 }
|
||||
if TransitionSmoothProgress(0.5) != 0.5 { return 0 }
|
||||
|
||||
@@ -17,7 +17,7 @@ OUTPUT = ROOT / "build/zx-test"
|
||||
def environment():
|
||||
env = os.environ.copy()
|
||||
for key in ("DISPLAY", "WAYLAND_DISPLAY", "XAUTHORITY",
|
||||
"DBUS_SESSION_BUS_ADDRESS", "SESSION_MANAGER"):
|
||||
"DBUS_SESSION_BUS_ADDRESS", "SESSION_MANAGER", "GTK_THEME"):
|
||||
env.pop(key, None)
|
||||
env["PATH"] = str(ROOT / "build/bin") + os.pathsep + str(ZIRAN_ROOT / "build/bin") + os.pathsep + env["PATH"]
|
||||
env["ZIRAN_ROOT"] = str(ZIRAN_ROOT)
|
||||
@@ -155,7 +155,7 @@ backend = "desktop"
|
||||
png = png_pixels(shot)
|
||||
assert png[:2] == (960, 600)
|
||||
assert rgb(png, 550, 130) == (230, 30, 40), "downloaded asset did not render"
|
||||
assert rgb(png, 10, 10) == (248, 250, 252), "background did not render"
|
||||
assert rgb(png, 10, 10) == (255, 255, 255), "default canvas did not render"
|
||||
assert any(sum(rgb(png, x, y)) < 400 for y in range(128, 165)
|
||||
for x in range(40, 350)), "text did not render"
|
||||
|
||||
|
||||
@@ -17,6 +17,7 @@
|
||||
#import "bundle_app"
|
||||
Video :: #import "video_linux";
|
||||
Bitmaps :: #import "bitmap_image";
|
||||
UiTheme :: #import "theme";
|
||||
#if OS == .LINUX {
|
||||
Service :: #import "service_linux";
|
||||
Theme :: #import "system_theme_host_linux";
|
||||
@@ -401,9 +402,17 @@ RemoveAssetDirectory :: (path: string) -> bool {
|
||||
return CopyCString(path, bytes[:]) && RemoveDirectory(*bytes[0]) == 0 && ok
|
||||
}
|
||||
|
||||
BundleThemeBackground :: (refresh: bool) -> u32 {
|
||||
// The bundle owns its palette. Match its default canvas without applying
|
||||
// a desktop palette to the clear color alone.
|
||||
unused refresh
|
||||
return UiTheme.CurrentBackground()
|
||||
}
|
||||
|
||||
RunFrame :: (instance: *void, player: *Player) -> bool {
|
||||
BundleMediaTick(*player.media)
|
||||
BeginDesktopFrame()
|
||||
SetRasterBackground(BundleThemeBackground)
|
||||
result: s64
|
||||
has_result: s32
|
||||
if RunBundleInstance(instance, *result, *has_result) == 0 { return false }
|
||||
|
||||
@@ -321,6 +321,7 @@ system_clipboard_windows = "src/backend/system_clipboard_windows.zi"
|
||||
background_window_windows = "src/backend/background_window_windows.zi"
|
||||
toggle_measure = "src/ui/toggle/toggle_measure.zi"
|
||||
transition = "src/ui/transition.zi"
|
||||
motion = "src/ui/motion.zi"
|
||||
text_selection = "src/ui/text_selection_widget.zi"
|
||||
|
||||
box = "src/ui/box/box.zi"
|
||||
|
||||
Reference in new issue
Block a user