summaryrefslogtreecommitdiff
path: root/src/vector/Drawing.zig
blob: 0a3b77bf44e4f13a27a6147c11ec3387cead8676 (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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
//! A vector drawing as plain data: shapes made of subpaths made of cubics.
//! Parsers and generators build these; the rasterizer and animations only
//! read and recombine them.
const Drawing = @This();
const std = @import("std");
const geom = @import("geom.zig");
const Vec = geom.Vec;
const Cubic = geom.Cubic;

cubics: []const Cubic = &.{},
subpaths: []const Subpath = &.{},
shapes: []const Shape = &.{},
gradients: []const Gradient = &.{},
/// The user-space rectangle the drawing occupies (SVG `viewBox`).
view: geom.Rect = .{},
/// Intended size in pixels (SVG `width`/`height`).
width: f32 = 0,
height: f32 = 0,

pub const Subpath = struct {
    first: u32,
    count: u32,
    closed: bool,
};

/// Straight (not premultiplied) RGBA in 0..1.
pub const Color = @Vector(4, f32);

pub const Paint = union(enum) {
    none,
    color: Color,
    /// Index into `gradients`.
    gradient: u32,
};

pub const Cap = enum { butt, round, square };
pub const Join = enum { miter, round, bevel };
pub const FillRule = enum { nonzero, evenodd };

pub const Style = struct {
    fill: Paint = .{ .color = .{ 0, 0, 0, 1 } },
    fill_rule: FillRule = .nonzero,
    fill_opacity: f32 = 1,
    stroke: Paint = .none,
    stroke_width: f32 = 1,
    stroke_opacity: f32 = 1,
    cap: Cap = .butt,
    join: Join = .miter,
    miter_limit: f32 = 4,
    dashes: [8]f32 = @splat(0),
    dash_count: u8 = 0,
    dash_offset: f32 = 0,
    /// Applied to fill and stroke alike.
    opacity: f32 = 1,
};

pub const Shape = struct {
    first: u32,
    count: u32,
    /// From the shape's own coordinates to the drawing's user space.
    transform: geom.Affine = .identity,
    style: Style = .{},
    /// A convex quad in the drawing's user space outside of which nothing
    /// shows (a symbol's viewport).
    clip: ?[4]Vec = null,
};

pub const Gradient = struct {
    kind: enum { linear, radial } = .linear,
    /// Linear: start and end. Radial: center and focus.
    p0: Vec = .{ 0, 0 },
    p1: Vec = .{ 1, 0 },
    radius: f32 = 0.5,
    /// Coordinates are fractions of the shape's bounds, not user space.
    bounding_box: bool = true,
    transform: geom.Affine = .identity,
    spread: enum { pad, reflect, repeat } = .pad,
    stops: []const Stop = &.{},

    pub const Stop = struct { offset: f32, color: Color };
};

pub fn subpathsOf(d: Drawing, shape: Shape) []const Subpath {
    return d.subpaths[shape.first..][0..shape.count];
}

pub fn cubicsOf(d: Drawing, subpath: Subpath) []const Cubic {
    return d.cubics[subpath.first..][0..subpath.count];
}

/// Bounds of `shape` in its own coordinates (control points: a little loose).
pub fn shapeBounds(d: Drawing, shape: Shape) geom.Bounds {
    var b: geom.Bounds = .{};
    for (d.subpathsOf(shape)) |sp| for (d.cubicsOf(sp)) |c| for (c) |p| b.add(p);
    return b;
}

/// Bounds of the whole drawing in user space.
pub fn bounds(d: Drawing) geom.Bounds {
    var b: geom.Bounds = .{};
    for (d.shapes) |shape| for (d.subpathsOf(shape)) |sp| for (d.cubicsOf(sp)) |c| for (c) |p| b.add(shape.transform.apply(p));
    return b;
}

/// Accumulates a drawing. Everything lands in one allocator (an arena, in
/// practice), so a drawing is freed all at once.
pub const Builder = struct {
    gpa: std.mem.Allocator,
    cubics: std.ArrayList(Cubic) = .empty,
    subpaths: std.ArrayList(Subpath) = .empty,
    shapes: std.ArrayList(Shape) = .empty,
    gradients: std.ArrayList(Gradient) = .empty,
    shape_start: u32 = 0,
    subpath_start: u32 = 0,

    pub fn init(gpa: std.mem.Allocator) Builder {
        return .{ .gpa = gpa };
    }

    pub fn cubic(b: *Builder, c: Cubic) !void {
        try b.cubics.append(b.gpa, c);
    }
    pub fn lineTo(b: *Builder, from: Vec, to: Vec) !void {
        try b.cubic(geom.line(from, to));
    }
    /// Ends the current subpath, if it has any segments.
    pub fn closeSubpath(b: *Builder, closed: bool) !void {
        const count: u32 = @intCast(b.cubics.items.len - b.subpath_start);
        if (count > 0) try b.subpaths.append(b.gpa, .{ .first = b.subpath_start, .count = count, .closed = closed });
        b.subpath_start = @intCast(b.cubics.items.len);
    }
    /// Ends the current shape, if it has any subpaths.
    pub fn endShape(b: *Builder, transform: geom.Affine, style: Style) !void {
        try b.closeSubpath(false);
        const count: u32 = @intCast(b.subpaths.items.len - b.shape_start);
        if (count > 0) try b.shapes.append(b.gpa, .{ .first = b.shape_start, .count = count, .transform = transform, .style = style });
        b.shape_start = @intCast(b.subpaths.items.len);
    }
    pub fn finish(b: *Builder, view: geom.Rect, width: f32, height: f32) !Drawing {
        return .{
            .cubics = try b.cubics.toOwnedSlice(b.gpa),
            .subpaths = try b.subpaths.toOwnedSlice(b.gpa),
            .shapes = try b.shapes.toOwnedSlice(b.gpa),
            .gradients = try b.gradients.toOwnedSlice(b.gpa),
            .view = view,
            .width = width,
            .height = height,
        };
    }

    // Primitive shapes, each a closed subpath of cubics.

    pub fn rect(b: *Builder, r: geom.Rect, radius: f32) !void {
        const rr = @min(radius, @min(r.w, r.h) / 2);
        if (rr <= 0) {
            const p = [4]Vec{ .{ r.x, r.y }, .{ r.x + r.w, r.y }, .{ r.x + r.w, r.y + r.h }, .{ r.x, r.y + r.h } };
            for (0..4) |i| try b.lineTo(p[i], p[(i + 1) % 4]);
        } else {
            try b.roundedRect(r, rr, rr);
        }
        try b.closeSubpath(true);
    }
    pub fn roundedRect(b: *Builder, r: geom.Rect, rx: f32, ry: f32) !void {
        const k = 0.5522847498;
        const x0 = r.x;
        const y0 = r.y;
        const x1 = r.x + r.w;
        const y1 = r.y + r.h;
        try b.lineTo(.{ x0 + rx, y0 }, .{ x1 - rx, y0 });
        try b.cubic(.{ .{ x1 - rx, y0 }, .{ x1 - rx + rx * k, y0 }, .{ x1, y0 + ry - ry * k }, .{ x1, y0 + ry } });
        try b.lineTo(.{ x1, y0 + ry }, .{ x1, y1 - ry });
        try b.cubic(.{ .{ x1, y1 - ry }, .{ x1, y1 - ry + ry * k }, .{ x1 - rx + rx * k, y1 }, .{ x1 - rx, y1 } });
        try b.lineTo(.{ x1 - rx, y1 }, .{ x0 + rx, y1 });
        try b.cubic(.{ .{ x0 + rx, y1 }, .{ x0 + rx - rx * k, y1 }, .{ x0, y1 - ry + ry * k }, .{ x0, y1 - ry } });
        try b.lineTo(.{ x0, y1 - ry }, .{ x0, y0 + ry });
        try b.cubic(.{ .{ x0, y0 + ry }, .{ x0, y0 + ry - ry * k }, .{ x0 + rx - rx * k, y0 }, .{ x0 + rx, y0 } });
    }
    pub fn ellipse(b: *Builder, center: Vec, rx: f32, ry: f32) !void {
        const k = 0.5522847498;
        const cx = center[0];
        const cy = center[1];
        // Clockwise from the right, like SVG's circle.
        try b.cubic(.{ .{ cx + rx, cy }, .{ cx + rx, cy + ry * k }, .{ cx + rx * k, cy + ry }, .{ cx, cy + ry } });
        try b.cubic(.{ .{ cx, cy + ry }, .{ cx - rx * k, cy + ry }, .{ cx - rx, cy + ry * k }, .{ cx - rx, cy } });
        try b.cubic(.{ .{ cx - rx, cy }, .{ cx - rx, cy - ry * k }, .{ cx - rx * k, cy - ry }, .{ cx, cy - ry } });
        try b.cubic(.{ .{ cx, cy - ry }, .{ cx + rx * k, cy - ry }, .{ cx + rx, cy - ry * k }, .{ cx + rx, cy } });
        try b.closeSubpath(true);
    }
    pub fn polyline(b: *Builder, points: []const Vec, closed: bool) !void {
        if (points.len < 2) return;
        for (points[0 .. points.len - 1], points[1..]) |p, q| try b.lineTo(p, q);
        if (closed and !@reduce(.And, points[0] == points[points.len - 1])) try b.lineTo(points[points.len - 1], points[0]);
        try b.closeSubpath(closed);
    }
};