Luce packages
LuceLuce BaseLuciaOS

dymokomi/luce-prism

Source of release 0.6.0

0.6.0 / src / animation.lucb

## Keyframe storage and value interpolation.
from luce_std import math
from storage import Buffer, List, copy_list
from names import Name
from types import DType, Interpolation, invalid
from value import ValueData, equal_values, append_number, floating, same_shape, value_header

pub struct Sample:
    pub var time: f64
    pub var value: ValueData = ValueData()
    pub var interpolation: Interpolation = Interpolation.linear
    pub var handle: u8
    pub var left: List[f64]
    pub var right: List[f64]

    pub func copy() -> Sample!:
        var output = Sample(time = self.time, interpolation = self.interpolation, handle = self.handle)
        errdefer output.close()
        output.value = try self.value.copy()
        output.left = try copy_list(&self.left)
        output.right = try copy_list(&self.right)
        return output

    pub func close():
        self.value.close()
        self.left.close()
        self.right.close()

pub struct Property:
    ## Shared with every other property of the same name (see names).
    pub var name: Name
    pub var value: ValueData = ValueData()
    pub var type_name: Name
    pub var samples: List[Sample]

    pub func copy() -> Property!:
        var output = Property()
        errdefer output.close()
        output.name = try self.name.copy()
        output.value = try self.value.copy()
        output.type_name = try self.type_name.copy()
        try output.samples.reserve(self.samples.count)
        for sample in self.samples.span():
            try output.samples.push(try sample.copy())
        return output

    pub func close():
        self.name.close()
        self.value.close()
        self.type_name.close()
        for i in 0..<self.samples.count:
            self.samples.items[i].close()
        self.samples.close()

pub func insert_sample(prop: Property*, sample: Sample) -> !:
    for i in 0..<prop.samples.count:
        if prop.samples.items[i].time == sample.time:
            prop.samples.items[i].close()
            prop.samples.items[i] = sample
            return
    try prop.samples.push(sample)
    var i = prop.samples.count - 1
    while i > 0 and prop.samples.items[i].time < prop.samples.items[i - 1].time:
        let previous = prop.samples.items[i - 1]
        prop.samples.items[i - 1] = prop.samples.items[i]
        prop.samples.items[i] = previous
        i -= 1

# The legacy interpolator applies cubic handles to its original scalar/vector
# families; general float arrays (including f64 and f16) use element-wise lerp.
func cubic_kind(value: const ValueData*) -> bool:
    if value.shape.count == 0:
        return value.kind == DType.float32 or value.kind == DType.int64
    if value.kind != DType.float32:
        return false
    if value.shape.count == 1:
        let size = value.shape.items[0]
        return size == 2 or size == 3 or size == 32
    return value.shape.count == 2 and value.shape.items[0] == 2 and value.shape.items[1] == 3

func cubic(a: f64, b: f64, c: f64, d: f64, u: f64) -> f64:
    let v = 1.0 - u
    return v * v * v * a + 3.0 * v * v * u * b + 3.0 * v * u * u * c + u * u * u * d

func cubic_derivative(a: f64, b: f64, c: f64, d: f64, u: f64) -> f64:
    let v = 1.0 - u
    return 3.0 * v * v * (b - a) + 6.0 * v * u * (c - b) + 3.0 * u * u * (d - c)

func solve_time(a: f64, b: f64, c: f64, d: f64, time: f64) -> f64:
    if d == a:
        return 0.0
    var u = math.clamp((time - a) / (d - a), 0.0, 1.0)
    for i in 0..<8:
        let residual = cubic(a, b, c, d, u) - time
        if math.abs(residual) < 0.0000001:
            return u
        let derivative = cubic_derivative(a, b, c, d, u)
        if math.abs(derivative) < 0.000000001:
            break
        let next = u - residual / derivative
        if next < 0.0 or next > 1.0:
            break
        u = next
    var low = 0.0
    var high = 1.0
    for i in 0..<32:
        let middle = 0.5 * (low + high)
        if cubic(a, b, c, d, middle) < time:
            low = middle
        else:
            high = middle
    return 0.5 * (low + high)

func neighbour(value: const ValueData*, component: usize) -> f64!:
    if cubic_kind(value) or (value.kind == DType.boolean and value.shape.count == 0):
        return try value.number(component if component < value.count() else 0)
    return 0.0

func tangent(samples: const Sample[], index: usize, component: usize, right: bool) -> f64[2]!:
    let previous = &samples[index - 1 if index > 0 else index]
    let next = &samples[index + 1 if index + 1 < samples.length else index]
    let segment = next.time - samples[index].time if right else samples[index].time - previous.time
    if segment <= 0.0:
        return [0.0, 0.0]
    let distance = next.time - previous.time
    if distance <= 0.0:
        return [segment / 3.0, 0.0]
    let slope = ((try neighbour(&next.value, component)) - (try neighbour(&previous.value, component))) / distance
    let dt = segment / 3.0 if right else -segment / 3.0
    return [dt, slope * dt]

func bezier_component(samples: const Sample[], index: usize, component: usize, time: f64, left: f64, right: f64) -> f64!:
    let a = &samples[index]
    let b = &samples[index + 1]
    var r = try tangent(samples, index, component, true)
    var l = try tangent(samples, index + 1, component, false)
    if component < a.right.count // 2:
        r = [a.right.items[component * 2], a.right.items[component * 2 + 1]]
    if component < b.left.count // 2:
        l = [b.left.items[component * 2], b.left.items[component * 2 + 1]]
    var x1 = math.clamp(a.time + r[0], a.time, b.time)
    var x2 = math.clamp(b.time + l[0], a.time, b.time)
    let length = b.time - a.time
    if (x1 - a.time) + (b.time - x2) > length:
        let scale = length / ((x1 - a.time) + (b.time - x2))
        x1 = a.time + (x1 - a.time) * scale
        x2 = b.time - (b.time - x2) * scale
    let u = solve_time(a.time, x1, x2, b.time, time)
    return cubic(left, left + r[1], right + l[1], right, u)

pub func resolve_property(prop: const Property*, time: f64) -> ValueData!:
    if prop.samples.count == 0:
        return try prop.value.copy()
    let samples = prop.samples.span()
    if time <= samples[0].time:
        return try samples[0].value.copy()
    for i in 1..<samples.length:
        if time == samples[i].time:
            return try samples[i].value.copy()
        if time < samples[i].time:
            let a = &samples[i - 1]
            let b = &samples[i]
            let bezier = a.interpolation == Interpolation.bezier and cubic_kind(&a.value) and same_shape(&a.value, &b.value)
            if a.interpolation == Interpolation.held or not same_shape(&a.value, &b.value) or (not bezier and not floating(a.value.kind)):
                return try a.value.copy()
            var output = try value_header(a.value.kind, a.value.shape.span())
            errdefer output.close()
            let ratio = (time - a.time) / (b.time - a.time)
            for component in 0..<a.value.count():
                let left = try a.value.number(component)
                let right = try b.value.number(component)
                var number: f64
                if bezier:
                    number = try bezier_component(samples, i - 1, component, time, left, right)
                else:
                    let delta = right - left if a.value.kind == DType.float64 else (f64)((f32)right - (f32)left)
                    number = left + delta * ratio
                if output.kind == DType.int64:
                    let rounded = math.round(number)
                    if rounded < -9223372036854775808.0 or rounded >= 9223372036854775808.0:
                        error(invalid, "Prism integer animation exceeds int64")
                    try output.payload.uint((u64)(i64)rounded, 8)
                else:
                    try append_number(&output.payload, output.kind, number)
            return output
    return try samples[samples.length - 1].value.copy()

pub func equal_properties(a: const Property*, b: const Property*) -> bool:
    if a.type_name.view() != b.type_name.view() or not equal_values(&a.value, &b.value) or a.samples.count != b.samples.count:
        return false
    for i in 0..<a.samples.count:
        let x = &a.samples.items[i]
        let y = &b.samples.items[i]
        if x.time != y.time or x.interpolation != y.interpolation or x.handle != y.handle or not equal_values(&x.value, &y.value):
            return false
        if x.left.count != y.left.count or x.right.count != y.right.count:
            return false
        for j in 0..<x.left.count:
            if x.left.items[j] != y.left.items[j]:
                return false
        for j in 0..<x.right.count:
            if x.right.items[j] != y.right.items[j]:
                return false
    return true