summaryrefslogtreecommitdiff
path: root/src/vector/shaders/paint.frag
blob: 97eb5517dc8f828c27acde51a8c08da1453e31f8 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
#version 450
#extension GL_GOOGLE_include_directive : require
// Paints a fill: its solid color, or its gradient times its alpha. A draw
// holds many fills, so each vertex says which (paint.vert). Mirrors
// vector/Paint.zig: `param` gives the gradient parameter, `stop_color` the
// color at it. The Paint struct is generated from vector/layouts.zig.
layout(location = 0) flat in vec4 fill_color;
layout(location = 1) flat in int fill_gradient;
layout(location = 0) out vec4 out_color;

#include "Paint.glsl"
layout(set = 2, binding = 0, std430) readonly buffer Paints { Paint paints[]; };
#define paint paints[fill_gradient]

float offset_at(int i) {
    return paint.offsets[i / 4][i % 4];
}

vec4 premultiply(vec4 c) {
    return vec4(c.rgb * c.a, c.a);
}

float param(vec2 q) {
    vec2 g = vec2(dot(paint.row0.xyz, vec3(q, 1.0)), dot(paint.row1.xyz, vec3(q, 1.0)));
    vec2 p0 = paint.points.xy;
    vec2 p1 = paint.points.zw;
    float t = 0.0;
    if (paint.row0.w < 1.5) {
        vec2 dir = p1 - p0;
        float len2 = dot(dir, dir);
        t = len2 > 0.0 ? dot(g - p0, dir) / len2 : 0.0;
    } else {
        // Where the ray from the focus through g meets the circle.
        vec2 dq = g - p1;
        vec2 cf = p1 - p0;
        float a = dot(dq, dq);
        if (a > 0.0) {
            float b = dot(dq, cf);
            float c = dot(cf, cf) - paint.extra.x * paint.extra.x;
            float s = (-b + sqrt(max(b * b - a * c, 0.0))) / a;
            t = s > 0.0 ? 1.0 / s : 1.0;
        }
    }
    if (paint.row1.w < 0.5) return clamp(t, 0.0, 1.0);
    if (paint.row1.w < 1.5) {
        float r = mod(t, 2.0);
        return r > 1.0 ? 2.0 - r : r;
    }
    return t - floor(t);
}

vec4 stop_color(float t) {
    int count = int(paint.extra.z);
    if (count == 0) return vec4(0.0);
    if (t <= offset_at(0)) return premultiply(paint.colors[0]);
    for (int i = 1; i < count; i++) {
        float b = offset_at(i);
        if (t <= b) {
            float a = offset_at(i - 1);
            float u = b > a ? (t - a) / (b - a) : 1.0;
            return premultiply(mix(paint.colors[i - 1], paint.colors[i], u));
        }
    }
    return premultiply(paint.colors[count - 1]);
}

void main() {
    out_color = fill_gradient < 0 ? fill_color : stop_color(param(gl_FragCoord.xy)) * fill_color;
}