Luce packages
LuceLuce BaseLuciaOS

dymokomi/luce-browser-render

Source of release 0.6.2

0.6.2 / src / raster / shaders.lucb

#==============================================================================================
#
#   shaders - shaders, gradients, patterns
#
#   DESCRIPTION:
#       Port of tiny-skia shaders/mod.rs (SpreadMode, Shader), shaders/linear_gradient.rs,
#       shaders/sweep_gradient.rs and shaders/pattern.rs (FilterQuality, PixmapPaint,
#       Pattern), with the stages Skia m144's SkLinearGradient and SkSweepGradient append.
#       The stops and stages every gradient shares are in gradient_base_shader.lucb, the
#       pattern's stages in image_shader.lucb. Gradient shaders own their stops:
#       `Shader.release()` frees them and `Shader.clone()` copies them.
#
#==============================================================================================

## A shader spreading mode.
pub enum SpreadMode as u8:
    ## Replicate the edge color if the shader draws outside of its original bounds.
    pad_ = 0
    ## Repeat the shader's image horizontally and vertically, alternating mirror images so
    ## that adjacent images always seam.
    reflect = 1
    ## Repeat the shader's image horizontally and vertically.
    repeat = 2

## A shader specifies the source color(s) for what is being drawn. If a paint has no
## shader, then the paint's color is used. If the paint has a shader, then the shader's
## color(s) are use instead, but they are modulated by the paint's alpha.
pub enum Shader:
    ## A solid color shader.
    solid_color(color: Color)
    ## A linear gradient shader.
    linear_gradient(g: LinearGradient)
    ## A radial gradient shader.
    radial_gradient(g: RadialGradient)
    ## A sweep gradient shader.
    sweep_gradient(g: SweepGradient)
    ## A pattern shader.
    pattern(p: Pattern)

    ## Checks if the shader is guaranteed to produce only opaque colors.
    pub func is_opaque() -> bool:
        match self:
            .solid_color(c): return c.is_opaque()
            .linear_gradient(g): return g.base.colors_are_opaque
            # A simple radial gradient (SkRadialGradient) is opaque when its colors are; a
            # two-point conical one leaves the areas outside the cone untouched, so Skia
            # never treats it as opaque (SkConicalGradient::isOpaque).
            .radial_gradient(g): return g.is_simple_radial() and g.base.colors_are_opaque
            .sweep_gradient(g): return g.base.colors_are_opaque
            .pattern(_): return false

    ## Checks if the shader always produces one color (Skia's isConstant): a solid color,
    ## which degenerate gradients become.
    pub func is_constant() -> bool:
        match self:
            .solid_color(_): return true
            _: return false

    ## Sets how a gradient interpolates its colors (SkGradientShader::Interpolation: the
    ## color space, the hue method, premultiplied or not; Ladybird's CSS gradients
    ## interpolate premultiplied). Other shaders are unchanged.
    pub func set_interpolation(interpolation: GradientInterpolation):
        match self:
            .linear_gradient(g):
                var ng = g
                ng.base.interpolation = interpolation
                self = .linear_gradient(g = ng)
            .radial_gradient(g):
                var ng = g
                ng.base.interpolation = interpolation
                self = .radial_gradient(g = ng)
            .sweep_gradient(g):
                var ng = g
                ng.base.interpolation = interpolation
                self = .sweep_gradient(g = ng)
            _:
                return

    ## Makes a gradient interpolate its colors premultiplied (Interpolation::InPremul::kYes).
    pub func interpolate_in_premul():
        self.set_interpolation(GradientInterpolation(in_premul = true))

    func push_stages(cs: ColorSpace, p: RasterPipelineBuilder*) -> bool:
        match self:
            .solid_color(color):
                let c = colorspace_expand_color(cs, color).premultiply()
                p.push_uniform_color(c)
                return true
            .linear_gradient(g): return g.push_stages(cs, p)
            .radial_gradient(g): return g.push_stages(cs, p)
            .sweep_gradient(g): return g.push_stages(cs, p)
            .pattern(patt): return pattern_push_stages(&patt, cs, p)

    ## Transforms the shader.
    pub func transform(ts: Transform):
        match self:
            .solid_color(_):
                return
            .linear_gradient(g):
                var ng = g
                ng.base.transform = ng.base.transform.post_concat(ts)
                self = .linear_gradient(g = ng)
            .radial_gradient(g):
                var ng = g
                ng.base.transform = ng.base.transform.post_concat(ts)
                self = .radial_gradient(g = ng)
            .sweep_gradient(g):
                var ng = g
                ng.base.transform = ng.base.transform.post_concat(ts)
                self = .sweep_gradient(g = ng)
            .pattern(p):
                var np = p
                np.transform = np.transform.post_concat(ts)
                self = .pattern(p = np)

    ## Shifts shader's opacity. `opacity` will be clamped to the 0..=1 range. This is roughly
    ## the same as Skia's `SkPaint::setAlpha`. Unlike Skia, we do not support global alpha/opacity,
    ## which is in Skia is set via the alpha channel of the `SkPaint::fColor4f`. Instead, you can
    ## shift the opacity of the shader to whatever value you need.
    pub func apply_opacity(opacity: f32):
        match self:
            .solid_color(c):
                var nc = c
                nc.apply_opacity(opacity)
                self = .solid_color(color = nc)
            .linear_gradient(g):
                var ng = g
                ng.base.apply_opacity(opacity)
                self = .linear_gradient(g = ng)
            .radial_gradient(g):
                var ng = g
                ng.base.apply_opacity(opacity)
                self = .radial_gradient(g = ng)
            .sweep_gradient(g):
                var ng = g
                ng.base.apply_opacity(opacity)
                self = .sweep_gradient(g = ng)
            .pattern(p):
                var np = p
                np.opacity = normalized_new(np.opacity * bound(opacity, 0.0, 1.0)) else trap("unreachable")
                self = .pattern(p = np)

    ## A copy of the shader; a gradient's stops are copied (Rust's `Shader::clone`).
    pub func clone() -> Shader:
        match self:
            .linear_gradient(g):
                var ng = g
                ng.base.stops = g.base.stops.clone()
                return .linear_gradient(g = ng)
            .radial_gradient(g):
                var ng = g
                ng.base.stops = g.base.stops.clone()
                return .radial_gradient(g = ng)
            .sweep_gradient(g):
                var ng = g
                ng.base.stops = g.base.stops.clone()
                return .sweep_gradient(g = ng)
            _:
                return self

    ## Frees a gradient shader's stops (Rust's `Drop`).
    pub func release():
        match self:
            .linear_gradient(g):
                var ng = g
                ng.base.stops.release()
            .radial_gradient(g):
                var ng = g
                ng.base.stops.release()
            .sweep_gradient(g):
                var ng = g
                ng.base.stops.release()
            _:
                return
        self = .solid_color(color = Color.black())

# mark: LinearGradient ========================================================================

## A linear gradient shader.
pub struct LinearGradient:
    var base: Gradient

    ## Creates a new linear gradient shader. Returns `Shader.solid_color` when `stops`
    ## has a single stop, `start` and `end` are the same (degenerate), and none when there
    ## are no stops or the transform is not invertible. The stops are copied.
    pub static func new_(start: Point, end: Point, stops: const GradientStop[], mode: SpreadMode, transform: Transform) -> Shader?:
        if stops.length == 0:
            return none

        if stops.length == 1:
            return .solid_color(color = stops[0].color)

        let length = end.sub(start).length()
        if not math32.is_finite(length):
            return none

        if is_nearly_zero_within_tolerance(length, degenerate_threshold):
            # Degenerate gradient, the only tricky complication is when in clamp mode, the
            # limit of the gradient approaches two half planes of solid color (first and
            # last). However, they are divided by the line perpendicular to the start and end
            # point, which becomes undefined once start and end are exactly the same, so just
            # use the end color for a stable solution.

            # Except for special circumstances of clamped gradients, every gradient shape
            # (when degenerate) can be mapped to the same fallbacks. The specific shape
            # factories must account for special clamped conditions separately, this will
            # always return the last color for clamped gradients.
            match mode:
                .pad_:
                    # Depending on how the gradient shape degenerates, there may be a more
                    # specialized fallback representation for the factories to use, but this
                    # is a reasonable default.
                    return .solid_color(color = stops[stops.length - 1].color)
                _:
                    # repeat and mirror are treated the same: the border colors are never
                    # visible, but approximate the final color as infinite repetitions of the
                    # colors, so it can be represented as the average color of the gradient.
                    return .solid_color(color = average_gradient_color(stops))

        if transform.invert() == none:
            return none

        let unit_ts = points_to_unit_ts(start, end) else return none
        return .linear_gradient(g = LinearGradient(base = Gradient.new_(copy_stops(stops), mode, transform, unit_ts)))

    func push_stages(cs: ColorSpace, p: RasterPipelineBuilder*) -> bool:
        if not self.base.push_stages_pre(p):
            return false
        self.base.push_stages_body(p, cs)
        return true

func points_to_unit_ts(start: Point, end: Point) -> Transform?:
    var vec = end.sub(start)
    let mag = vec.length()
    let inv: f32 = invert(mag) if mag != 0.0 else 0.0

    vec.scale(inv)

    var ts = ts_from_sin_cos_at(-vec.y, vec.x, start.x, start.y)
    ts = ts.post_translate(-start.x, -start.y)
    ts = ts.post_scale(inv, inv)
    return ts

func ts_from_sin_cos_at(sin: f32, cos: f32, px: f32, py: f32) -> Transform:
    let cos_inv = 1.0 - cos
    return Transform.from_row(cos, sin, -sin, cos, sdot(sin, py, cos_inv, px), sdot(-sin, px, cos_inv, py))

func sdot(a: f32, b: f32, c: f32, d: f32) -> f32:
    return a * b + c * d

# mark: SweepGradient =========================================================================

## A sweep (conic) gradient shader, as Skia's SkSweepGradient.
pub struct SweepGradient:
    var base: Gradient
    var t0: f32
    var t1: f32

    ## Creates a new sweep gradient shader around `center`, from `start_angle` to
    ## `end_angle` in degrees. The stops are copied.
    pub static func new_(center: Point, start_angle: f32, end_angle: f32, stops: const GradientStop[], mode0: SpreadMode, transform: Transform) -> Shader?:
        var mode = mode0
        if not math32.is_finite(start_angle) or not math32.is_finite(end_angle) or start_angle > end_angle:
            return none

        if stops.length == 0:
            return none
        if stops.length == 1:
            return .solid_color(color = stops[0].color)

        if transform.invert() == none:
            return none
        if is_nearly_equal_within_tolerance(start_angle, end_angle, degenerate_threshold):
            if mode == .pad_ and end_angle > degenerate_threshold:
                # In this case, the first color is repeated from 0 to the angle, then a
                # hardstop switches to the last color (all other colors are compressed to the
                # infinitely thin interpolation region).
                let front_color = stops[0].color
                let back_color = stops[stops.length - 1].color
                let new_stops: GradientStop[3] = [GradientStop.new_(0.0, front_color), GradientStop.new_(1.0, front_color), GradientStop.new_(1.0, back_color)]
                return SweepGradient.new_(center, 0.0, end_angle, new_stops, mode, transform)
            # TODO: Consider making a degenerate fallback shader similar to Skia. Tiny Skia
            # currently opts to return `None` in some places.
            return none
        if start_angle <= 0.0 and end_angle >= 360.0:
            mode = .pad_
        let t0 = start_angle / 360.0
        let t1 = end_angle / 360.0
        return .sweep_gradient(g = SweepGradient(base = Gradient.new_(copy_stops(stops), mode, transform, Transform.from_translate(-center.x, -center.y)), t0 = t0, t1 = t1))

    ## SkSweepGradient::appendGradientStages: the angle, then the t scale and bias
    ## (Scale(tScale, 1) * Translate(tBias, 0)).
    func push_stages(cs: ColorSpace, p: RasterPipelineBuilder*) -> bool:
        let t_scale = 1.0 / (self.t1 - self.t0)
        let t_bias = -self.t0
        if not self.base.push_stages_pre(p):
            return false
        p.push(.xy_to_unit_angle)
        p.push_scale_translate_x(t_scale, t_scale * t_bias)
        self.base.push_stages_body(p, cs)
        return true

# mark: Pattern ===============================================================================

## Controls how much filtering to be done when transforming images.
pub enum FilterQuality as u8:
    ## Nearest-neighbor. Low quality, but fastest.
    nearest = 0
    ## Bilinear.
    bilinear = 1
    ## Bicubic. High quality, but slow.
    bicubic = 2

## Controls how a pixmap should be blended. Like `Paint`, but for `Pixmap`.
pub struct PixmapPaint:
    ## Pixmap opacity. Must be in 0..=1 range. Default: 1.0
    pub var opacity: f32 = 1.0

    ## Pixmap blending mode. Default: SourceOver
    pub var blend_mode: BlendMode = .source_over

    ## Specifies how much filtering to be done when transforming images. Default: Nearest
    pub var quality: FilterQuality = .nearest

## A pattern shader. Essentially, a `SkImageShader`, with SkMipmapMode kNone or, for
## `new_mipmapped`, kLinear.
pub struct Pattern:
    var pixmap: PixmapRef
    var quality: FilterQuality
    var spread_mode: SpreadMode
    var opacity: f32
    var transform: Transform
    ## SkMipmapMode::kLinear: a minified image samples two mip levels and blends them.
    var mipmap_linear: bool = false
    ## The image's pixels to the destination's color space after sampling (Skia's
    ## SkColorSpaceXformSteps of an SkImage with a color space); none when they are sRGB.
    var color_xform: ColorXform?

    ## Creates a new pattern shader. `opacity` will be clamped to the 0..=1 range.
    pub static func new_(pixmap: PixmapRef, spread_mode: SpreadMode, quality: FilterQuality, opacity: f32, transform: Transform) -> Shader:
        return .pattern(p = Pattern(pixmap = pixmap, spread_mode = spread_mode, quality = quality, opacity = normalized_clamped(opacity), transform = transform))

    ## A pattern sampled with SkSamplingOptions(kLinear, kLinear): bilinear in the two mip
    ## levels around the minification, blended linearly, then converted by `color_xform`.
    pub static func new_mipmapped(pixmap: PixmapRef, spread_mode: SpreadMode, opacity: f32, transform: Transform, color_xform: ColorXform? = none) -> Shader:
        return .pattern(p = Pattern(pixmap = pixmap, spread_mode = spread_mode, quality = .bilinear, opacity = normalized_clamped(opacity), transform = transform, mipmap_linear = true, color_xform = color_xform))

    ## A pattern of an image in another color space, converted after sampling by `color_xform`.
    pub static func new_color_managed(pixmap: PixmapRef, spread_mode: SpreadMode, quality: FilterQuality, opacity: f32, transform: Transform, color_xform: ColorXform?) -> Shader:
        return .pattern(p = Pattern(pixmap = pixmap, spread_mode = spread_mode, quality = quality, opacity = normalized_clamped(opacity), transform = transform, color_xform = color_xform))