diff options
Diffstat (limited to 'src/vector')
| -rw-r--r-- | src/vector/morph.zig | 60 | ||||
| -rw-r--r-- | src/vector/svg.zig | 96 |
2 files changed, 138 insertions, 18 deletions
diff --git a/src/vector/morph.zig b/src/vector/morph.zig index f285c7e..a05037d 100644 --- a/src/vector/morph.zig +++ b/src/vector/morph.zig @@ -2,7 +2,9 @@ //! in order; each pair's subpaths, then each subpath's cubics, are made equal //! in number by splitting the longest curves; then every control point and //! color is interpolated. A shape without a partner collapses to (or grows -//! from) the other drawing's center. +//! from) the other drawing's center. Outer contours pair with outer ones +//! and holes with holes, so a glyph's counter stays a counter; a hole +//! without a partner shrinks to nothing (or grows) inside its shape. const std = @import("std"); const geom = @import("math"); const Drawing = @import("Drawing.zig"); @@ -22,10 +24,14 @@ pub fn between(arena: std.mem.Allocator, a: Drawing, ma: geom.Affine, b: Drawing // The missing side is the other side, shrunk to a point. const pa = try placed(arena, a, sa, ma, sb, b, mb, cb); const pb = try placed(arena, b, sb, mb, sa, a, ma, ca); - const count = @max(pa.len, pb.len); - for (0..count) |k| { - const from = try pad(arena, pa, k, if (pa.len > 0) lastPoint(pa) else ca); - const to = try pad(arena, pb, k, if (pb.len > 0) lastPoint(pb) else cb); + // Outer contours pair up, then holes; a missing shape's subpaths + // are its partner's, in order. + const ha = if (sa != null and sb != null) try holesLast(arena, pa) else 0; + const hb = if (sa != null and sb != null) try holesLast(arena, pb) else 0; + const outers = @max(pa.len - ha, pb.len - hb); + for (0..outers + @max(ha, hb)) |k| { + const from = try side(arena, pa, ha, pb, hb, k, outers, ca); + const to = try side(arena, pb, hb, pa, ha, k, outers, cb); const aligned = try align2(arena, from.cubics, to.cubics); for (aligned[0], aligned[1]) |x, y| { var c: Cubic = undefined; @@ -78,6 +84,50 @@ fn pad(arena: std.mem.Allocator, paths: []const Path, k: usize, point: Vec) !Pat return .{ .cubics = one, .closed = false }; } +/// Puts the holes of `paths` (wound against the largest, as a font's +/// counters are) after its outer contours, each in order; returns how many. +fn holesLast(arena: std.mem.Allocator, paths: []Path) !usize { + const areas = try arena.alloc(f32, paths.len); + var main: f32 = 0; + for (areas, paths) |*area, p| { + area.* = geom.cross(p.cubics[p.cubics.len - 1][3], p.cubics[0][0]); + for (p.cubics) |c| area.* += geom.cross(c[0], c[1]) + geom.cross(c[1], c[2]) + geom.cross(c[2], c[3]); + if (@abs(area.*) > @abs(main)) main = area.*; + } + const all = try arena.dupe(Path, paths); + var n: usize = 0; + var holes: usize = 0; + for ([_]bool{ false, true }) |hole| for (all, areas) |p, area| if ((area * main < 0) == hole) { + paths[n] = p; + n += 1; + holes += @intFromBool(hole); + }; + return holes; +} + +/// One side's path for pair `k`: its outer contours, then its holes. One it +/// lacks is a point: an outer contour's where its last one ends (or at its +/// drawing's `middle`); a hole's where the other side's hole has its middle, +/// relative to the outer contours' bounds on each side, so that a hole with +/// no partner shrinks to nothing (or grows) inside its shape, moving with it. +fn side(arena: std.mem.Allocator, own: []const Path, holes: usize, other: []const Path, other_holes: usize, k: usize, outers: usize, middle: Vec) !Path { + const shell = own[0 .. own.len - holes]; + if (k < outers) return pad(arena, shell, k, if (shell.len > 0) lastPoint(shell) else middle); + const j = k - outers; + if (j < holes) return own[own.len - holes + j]; + const there = extent(other[0 .. other.len - other_holes]); + const here = extent(shell); + const hole = extent(other[other.len - other_holes + j ..][0..1]); + const at = ((hole.min + hole.max) / geom.splat(2) - there.min) / (there.max - there.min); + return pad(arena, &.{}, 0, here.min + at * (here.max - here.min)); +} + +fn extent(paths: []const Path) geom.Bounds { + var b: geom.Bounds = .{}; + for (paths) |p| for (p.cubics) |c| for (c) |q| b.add(q); + return b; +} + fn lastPoint(paths: []const Path) Vec { const last = paths[paths.len - 1].cubics; return last[last.len - 1][3]; diff --git a/src/vector/svg.zig b/src/vector/svg.zig index 31d9b15..f1b7daf 100644 --- a/src/vector/svg.zig +++ b/src/vector/svg.zig @@ -4,11 +4,12 @@ //! `ellipse`, `line`, `polyline`, `polygon`. Styling: presentation //! attributes and `style="..."`, inherited as SVG specifies; solid colors, //! linear and radial gradients; fill rules; stroke width, caps, joins, miter -//! limit and dashes; `opacity`, `fill-opacity`, `stroke-opacity`. +//! limit and dashes; `opacity`, `fill-opacity`, `stroke-opacity`. Images +//! that are SVG documents in base64 data URIs (Typst's SVG and PDF images). //! //! Not supported: text (Typst outlines it), filters, masks, clipping, -//! patterns, markers, images, CSS stylesheets. Group opacity is approximated -//! by multiplying it into each shape. +//! patterns, markers, raster images, CSS stylesheets. Group opacity is +//! approximated by multiplying it into each shape. const std = @import("std"); const geom = @import("math"); const Drawing = @import("Drawing.zig"); @@ -23,23 +24,26 @@ pub fn parse(arena: std.mem.Allocator, source: []const u8) Error!Drawing { const root = doc.root orelse return error.InvalidSvg; if (!std.mem.eql(u8, doc.nodes.items[root].name, "svg")) return error.InvalidSvg; - var p: Parser = .{ .doc = &doc, .b = .init(arena), .arena = arena, .view = .{} }; - const n = doc.nodes.items[root]; - const w = doc.attr(n, "width"); - const h = doc.attr(n, "height"); + const port = viewport(&doc, doc.nodes.items[root]); + var p: Parser = .{ .doc = &doc, .b = .init(arena), .arena = arena, .view = port.view }; + try p.children(root, .identity, .{}); + return p.b.finish(port.view, port.width, port.height); +} + +/// A root `svg` element's view box and size in pixels, each standing in +/// for the other when missing. +fn viewport(doc: *const Document, n: Node) struct { view: geom.Rect, width: f32, height: f32 } { var view: geom.Rect = .{}; if (doc.attr(n, "viewBox")) |vb| { var nums = Numbers{ .text = vb }; view = .{ .x = nums.next() orelse 0, .y = nums.next() orelse 0, .w = nums.next() orelse 0, .h = nums.next() orelse 0 }; } - var width = if (w) |v| lengthPx(v, view.w) else view.w; - var height = if (h) |v| lengthPx(v, view.h) else view.h; + var width = if (doc.attr(n, "width")) |v| lengthPx(v, view.w) else view.w; + var height = if (doc.attr(n, "height")) |v| lengthPx(v, view.h) else view.h; if (view.w <= 0 or view.h <= 0) view = .{ .w = width, .h = height }; if (width <= 0) width = view.w; if (height <= 0) height = view.h; - p.view = view; - try p.children(root, .identity, .{}); - return p.b.finish(view, width, height); + return .{ .view = view, .width = width, .height = height }; } // --------------------------------------------------------------------------- @@ -183,7 +187,7 @@ const Parser = struct { fn element(p: *Parser, index: u32, parent_transform: Affine, parent: Inherited) Error!void { const n = p.doc.nodes.items[index]; const name = n.name; - const skip = [_][]const u8{ "defs", "symbol", "linearGradient", "radialGradient", "clipPath", "mask", "pattern", "marker", "style", "title", "desc", "metadata", "filter", "text", "image", "foreignObject" }; + const skip = [_][]const u8{ "defs", "symbol", "linearGradient", "radialGradient", "clipPath", "mask", "pattern", "marker", "style", "title", "desc", "metadata", "filter", "text", "foreignObject" }; for (skip) |s| if (std.mem.eql(u8, name, s)) return; if (p.depth > 64) return; var inherited = parent; @@ -229,6 +233,52 @@ const Parser = struct { } return p.element(target, transform, inherited); } + if (std.mem.eql(u8, name, "image")) { + // An SVG as a base64 data URI, Typst's way to place an SVG or a + // PDF page: its document, mapped into the image's box. Raster + // images draw nothing. + const href = p.doc.attr(n, "href") orelse p.doc.attr(n, "xlink:href") orelse return; + const prefix = "data:image/svg+xml;base64,"; + if (!std.mem.startsWith(u8, href, prefix)) return; + const decoder = std.base64.standard.Decoder; + const bytes = try p.arena.alloc(u8, decoder.calcSizeForSlice(href[prefix.len..]) catch return); + decoder.decode(bytes, href[prefix.len..]) catch return; + var doc = Document.parse(p.arena, bytes) catch |err| switch (err) { + error.OutOfMemory => return err, + error.InvalidSvg => return, + }; + const root = doc.root orelse return; + if (!std.mem.eql(u8, doc.nodes.items[root].name, "svg")) return; + const port = viewport(&doc, doc.nodes.items[root]); + const v = port.view; + const w = if (p.doc.attr(n, "width")) |a| lengthPx(a, p.view.w) else port.width; + const h = if (p.doc.attr(n, "height")) |a| lengthPx(a, p.view.h) else port.height; + if (v.w <= 0 or v.h <= 0 or w <= 0 or h <= 0) return; + transform = transform.mul(.translate(p.number(n, "x"), p.number(n, "y"))); + // Stretched with `preserveAspectRatio="none"`, else centered at + // the largest scale that fits; drawn unclipped. + if (std.mem.startsWith(u8, std.mem.trim(u8, p.doc.attr(n, "preserveAspectRatio") orelse "", " "), "none")) { + transform = transform.mul(.scale(w / v.w, h / v.h)); + } else { + const s = @min(w / v.w, h / v.h); + transform = transform.mul(.translate((w - v.w * s) / 2, (h - v.h * s) / 2)).mul(.scale(s, s)); + } + transform = transform.mul(.translate(-v.x, -v.y)); + // A document of its own: its ids, gradients and percentages, and + // nothing inherited but opacity. + const outer = p.*; + defer { + p.doc = outer.doc; + p.view = outer.view; + p.gradients = outer.gradients; + } + p.doc = &doc; + p.view = v; + p.gradients = .empty; + p.depth += 1; + defer p.depth -= 1; + return p.children(root, transform, .{ .style = .{ .opacity = inherited.style.opacity } }); + } const b = &p.b; if (std.mem.eql(u8, name, "path")) { @@ -766,3 +816,23 @@ test "colors and lengths" { try std.testing.expectEqual(@as(f32, 20), parseLength("15pt")); try std.testing.expectEqual(@as(f32, 0.5), parseOpacity("50%")); } + +test "an SVG image in a data URI: its own ids, placed, stretched or fitted" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + // <svg viewBox="0 0 10 20"><defs><path id="p" d="M0 0h10v20h-10z"/></defs><use href="#p" fill="#00ff00"/></svg> + const inner = "data:image/svg+xml;base64,PHN2ZyB2aWV3Qm94PSIwIDAgMTAgMjAiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+PGRlZnM+PHBhdGggaWQ9InAiIGQ9Ik0wIDBoMTB2MjBoLTEweiIvPjwvZGVmcz48dXNlIGhyZWY9IiNwIiBmaWxsPSIjMDBmZjAwIi8+PC9zdmc+"; + const d = try parse(arena.allocator(), "<svg viewBox=\"0 0 100 100\"><defs><path id=\"p\" d=\"M0 0h1v1z\"/></defs>" ++ + "<image x=\"5\" y=\"5\" width=\"20\" height=\"20\" preserveAspectRatio=\"none\" href=\"" ++ inner ++ "\"/>" ++ + "<image x=\"5\" y=\"5\" width=\"20\" height=\"20\" xlink:href=\"" ++ inner ++ "\"/>" ++ + "<image href=\"data:image/png;base64,AAAA\"/></svg>"); + try std.testing.expectEqual(@as(usize, 2), d.shapes.len); + for (d.shapes) |shape| try std.testing.expectEqual(Drawing.Color{ 0, 1, 0, 1 }, shape.style.fill.color); + // The far corner (10, 20) of the image's own path: stretched to the + // box's corner, or fitted into its middle. + for (d.shapes, [_]geom.Vec{ .{ 25, 25 }, .{ 20, 25 } }) |shape, corner| { + const far = d.cubicsOf(d.subpathsOf(shape)[0])[1][3]; + try std.testing.expectEqual(geom.vec(10, 20), far); + try std.testing.expectEqual(corner, shape.transform.apply(far)); + } +} |
