Initial Commit
This commit is contained in:
69 files changed
+7703
No files matched your search
@@ -0,0 +1,62 @@
|
||||
#! Contains the canvas: its pixels, and the layers drawn apart before they're
|
||||
#! composited onto it, as a group with opacity, a clip, or a mask is, each of
|
||||
#! premultiplied RGBA.
|
||||
|
||||
module image::svg;
|
||||
|
||||
|
||||
# The canvas: its pixels, and the layers drawn apart before they're composited
|
||||
# onto it, as a group with opacity, a clip, or a mask is, each premultiplied.
|
||||
struct canvas {
|
||||
var width: u64;
|
||||
var height: u64;
|
||||
var layers: vector<vector<u8>>;
|
||||
var raster: raster;
|
||||
}
|
||||
|
||||
def canvas::new(width: u64, height: u64): canvas {
|
||||
var made := canvas { width = width, height = height, layers = vector::<vector<u8>>::new(), raster = raster::new(width, height) };
|
||||
made.push();
|
||||
return made;
|
||||
}
|
||||
|
||||
# Begins a layer, clear, which what's drawn goes onto until it's popped.
|
||||
def canvas::push(&mut this): void {
|
||||
var layer := vector::<u8>::new();
|
||||
layer.resize(this.width * this.height * 4);
|
||||
this.layers.append(move(layer));
|
||||
}
|
||||
|
||||
# Takes the top layer off.
|
||||
def canvas::pop(&mut this): vector<u8> {
|
||||
var taken := move(this.layers.last());
|
||||
this.layers.truncate();
|
||||
return taken;
|
||||
}
|
||||
|
||||
def canvas::fill(&mut this, shape: &outline, even_odd: bool, paint: &painter): void {
|
||||
val target := this.layers.last().slice();
|
||||
this.raster.fill(shape, even_odd, paint, target);
|
||||
}
|
||||
|
||||
# Draws a layer over the top one, scaled by an opacity, and by a mask's alpha,
|
||||
# or its luminance, where there is one.
|
||||
def canvas::composite(&mut this, layer: span<u8>, opacity: f64, mask: span<u8>, luminance: bool): void {
|
||||
val target := this.layers.last().slice();
|
||||
val scale := opacity as f32 / 255;
|
||||
var at: u64 = 0;
|
||||
while at < layer.length {
|
||||
if layer[at + 3] != 0 {
|
||||
var factor := scale;
|
||||
if mask.length != 0 {
|
||||
val masked: f32 = luminance
|
||||
? mask[at] as f32 * 0.2125 + mask[at + 1] as f32 * 0.7154 + mask[at + 2] as f32 * 0.0721
|
||||
: mask[at + 3] as f32;
|
||||
factor *= masked / 255;
|
||||
}
|
||||
val color: f32[4] = [layer[at] as f32 * factor, layer[at + 1] as f32 * factor, layer[at + 2] as f32 * factor, layer[at + 3] as f32 * factor];
|
||||
blend(target, at, color, 1);
|
||||
}
|
||||
at += 4;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,156 @@
|
||||
#! Contains colors, as CSS writes them: by name, by hexadecimal digits, and by
|
||||
#! `rgb()`, `rgba()`, `hsl()`, and `hsla()`.
|
||||
|
||||
import std::math;
|
||||
module image::svg;
|
||||
|
||||
|
||||
# A color, each channel from 0 to 1, its alpha straight.
|
||||
struct color {
|
||||
var r: f64;
|
||||
var g: f64;
|
||||
var b: f64;
|
||||
var a: f64 = 1;
|
||||
}
|
||||
|
||||
# Reads a color as CSS writes one: by name, `#` and 3, 4, 6, or 8 hexadecimal
|
||||
# digits, `rgb()` and `rgba()`, or `hsl()` and `hsla()`.
|
||||
def parse_color(text: strview): maybe<color> {
|
||||
val trimmed := text.trim();
|
||||
if trimmed.length == 0 {
|
||||
return nothing {};
|
||||
}
|
||||
if trimmed[0] == '#' {
|
||||
return hex_color(trimmed.substr(1, trimmed.length - 1));
|
||||
}
|
||||
val open := trimmed.find("(");
|
||||
if open is some(paren) {
|
||||
if trimmed[trimmed.length - 1] != ')' {
|
||||
return nothing {};
|
||||
}
|
||||
val name := trimmed.substr(0, paren).trim().lower();
|
||||
val inside := trimmed.substr(paren + 1, trimmed.length - paren - 2);
|
||||
if name.view() == "rgb" || name.view() == "rgba" {
|
||||
return functional_color(inside, false);
|
||||
}
|
||||
if name.view() == "hsl" || name.view() == "hsla" {
|
||||
return functional_color(inside, true);
|
||||
}
|
||||
return nothing {};
|
||||
}
|
||||
|
||||
val name := trimmed.lower();
|
||||
if name.view() == "transparent" {
|
||||
return color { a = 0 };
|
||||
}
|
||||
for &each in named_colors {
|
||||
if each.name == name.view() {
|
||||
return color {
|
||||
r = ((each.rgb >> 16) & 0xFF) as f64 / 255,
|
||||
g = ((each.rgb >> 8) & 0xFF) as f64 / 255,
|
||||
b = (each.rgb & 0xFF) as f64 / 255
|
||||
};
|
||||
}
|
||||
}
|
||||
return nothing {};
|
||||
}
|
||||
|
||||
def hex_color(digits: strview): maybe<color> {
|
||||
for byte in digits {
|
||||
if !byte.is_hex {
|
||||
return nothing {};
|
||||
}
|
||||
}
|
||||
var values: f64[4] = [0, 0, 0, 1];
|
||||
if digits.length == 3 || digits.length == 4 {
|
||||
for index in 0..digits.length {
|
||||
values[index] = (digits[index].digit_value * 17) as f64 / 255;
|
||||
}
|
||||
} else if digits.length == 6 || digits.length == 8 {
|
||||
for index in 0..digits.length / 2 {
|
||||
values[index] = (digits[index * 2].digit_value * 16 + digits[index * 2 + 1].digit_value) as f64 / 255;
|
||||
}
|
||||
} else {
|
||||
return nothing {};
|
||||
}
|
||||
return color { r = values[0], g = values[1], b = values[2], a = values[3] };
|
||||
}
|
||||
|
||||
# Reads what's within `rgb()` or `hsl()`: three values, then perhaps an alpha,
|
||||
# split by commas, spaces, or a `/` before the alpha.
|
||||
def functional_color(inside: strview, hsl: bool): maybe<color> {
|
||||
var values: f64[4] = [0, 0, 0, 1];
|
||||
var count: u64 = 0;
|
||||
var at: u64 = 0;
|
||||
while at < inside.length {
|
||||
val byte := inside[at];
|
||||
if byte.is_space || byte == ',' || byte == '/' {
|
||||
at++;
|
||||
continue;
|
||||
}
|
||||
if count >= 4 {
|
||||
return nothing {};
|
||||
}
|
||||
val read := number_at(inside, at) else { return nothing {}; };
|
||||
at = read.end;
|
||||
var value := read.value;
|
||||
val percent := at < inside.length && inside[at] == '%';
|
||||
if percent {
|
||||
at++;
|
||||
}
|
||||
if count == 3 {
|
||||
value = percent ? value / 100 : value;
|
||||
} else if hsl {
|
||||
value = count == 0 ? value : value / 100;
|
||||
} else {
|
||||
value = percent ? value / 100 : value / 255;
|
||||
}
|
||||
values[count] = value;
|
||||
count++;
|
||||
}
|
||||
if count < 3 {
|
||||
return nothing {};
|
||||
}
|
||||
val alpha := math::clamp(values[3], 0.0, 1.0);
|
||||
if !hsl {
|
||||
return color {
|
||||
r = math::clamp(values[0], 0.0, 1.0),
|
||||
g = math::clamp(values[1], 0.0, 1.0),
|
||||
b = math::clamp(values[2], 0.0, 1.0),
|
||||
a = alpha
|
||||
};
|
||||
}
|
||||
|
||||
# Hue, saturation, and lightness, as CSS makes them RGB.
|
||||
val hue := (values[0] % 360 + 360) % 360 / 360;
|
||||
val saturation := math::clamp(values[1], 0.0, 1.0);
|
||||
val lightness := math::clamp(values[2], 0.0, 1.0);
|
||||
val high := lightness <= 0.5 ? lightness * (saturation + 1) : lightness + saturation - lightness * saturation;
|
||||
val low := lightness * 2 - high;
|
||||
return color {
|
||||
r = hue_channel(low, high, hue + 1.0 / 3),
|
||||
g = hue_channel(low, high, hue),
|
||||
b = hue_channel(low, high, hue - 1.0 / 3),
|
||||
a = alpha
|
||||
};
|
||||
}
|
||||
|
||||
def hue_channel(low: f64, high: f64, given: f64): f64 {
|
||||
var hue := given;
|
||||
if hue < 0 {
|
||||
hue += 1;
|
||||
}
|
||||
if hue > 1 {
|
||||
hue -= 1;
|
||||
}
|
||||
if hue * 6 < 1 {
|
||||
return low + (high - low) * hue * 6;
|
||||
}
|
||||
if hue * 2 < 1 {
|
||||
return high;
|
||||
}
|
||||
if hue * 3 < 2 {
|
||||
return low + (high - low) * (2.0 / 3 - hue) * 6;
|
||||
}
|
||||
return low;
|
||||
}
|
||||
@@ -0,0 +1,170 @@
|
||||
#! Contains the document walked: every ID found and each style sheet read, then
|
||||
#! each element drawn in its user space, in its style, those with opacity, a
|
||||
#! clip, or a mask on a layer of their own.
|
||||
|
||||
import std::xml;
|
||||
module image::svg;
|
||||
|
||||
|
||||
# Finds every element's ID, the first of each kept, and reads each style sheet.
|
||||
def renderer::index(&mut this, at: &xml::element): void {
|
||||
if at.attribute("id") is some(id) {
|
||||
_ = this.ids.insert(id, copy(at));
|
||||
}
|
||||
if at.local == "style" && is_svg(at) {
|
||||
val kind := at.attribute("type") else "text/css";
|
||||
if kind.length == 0 || kind == "text/css" {
|
||||
val text := at.text();
|
||||
this.sheet.add(text.view());
|
||||
}
|
||||
}
|
||||
for child in at.elements() {
|
||||
this.index(&child);
|
||||
}
|
||||
}
|
||||
|
||||
# The style of an element: its presentation attributes, then the rules matching
|
||||
# it, then its `style` attribute, over what it inherits.
|
||||
def renderer::style_of(&this, at: &xml::element, parent: &style): style {
|
||||
var made := parent.inherited();
|
||||
for each in at.attributes() {
|
||||
if each.namespace.length == 0 && is_presentation(each.local) {
|
||||
made.set(each.local, each.value, parent, &this.view);
|
||||
}
|
||||
}
|
||||
this.sheet.apply(at, &mut made, parent, &this.view);
|
||||
if at.attribute("style") is some(declared) {
|
||||
made.declare(declared, parent, &this.view);
|
||||
}
|
||||
return made;
|
||||
}
|
||||
|
||||
# Draws an element, and what it holds, in a user space.
|
||||
def renderer::draw(&mut this, at: &xml::element, parent: &style, outer: &matrix): void {
|
||||
if !is_svg(at) || this.depth >= deepest {
|
||||
return;
|
||||
}
|
||||
val name := at.local;
|
||||
for never in undrawn {
|
||||
if name == never {
|
||||
return;
|
||||
}
|
||||
}
|
||||
val own := this.style_of(at, parent);
|
||||
if !own.displayed {
|
||||
return;
|
||||
}
|
||||
|
||||
var placed := copy(outer);
|
||||
if at.attribute("transform") is some(written) {
|
||||
if parse_transform(written) is some(own_transform) {
|
||||
placed = own_transform.then(outer);
|
||||
}
|
||||
}
|
||||
|
||||
# A shape's opacity, where it's only filled or only stroked, scales its paint;
|
||||
# anything else with opacity, a clip, or a mask is drawn on a layer of its own.
|
||||
val shape := is_shape(name);
|
||||
val painted_twice := own.fill.kind != paint_kind::none && own.stroke.kind != paint_kind::none && own.stroke_width > 0;
|
||||
val clip := this.reference(own.clip_path, "clipPath");
|
||||
val mask := this.reference(own.mask, "mask");
|
||||
val layered := !this.clipping && ((own.opacity < 1 && (!shape || painted_twice)) || clip is some(_) || mask is some(_));
|
||||
if layered {
|
||||
this.canvas.push();
|
||||
}
|
||||
|
||||
this.depth++;
|
||||
var bounds: maybe<point[2]> = nothing {};
|
||||
if shape {
|
||||
bounds = this.shape(at, &own, &placed, layered ? 1.0 : own.opacity);
|
||||
} else if name == "g" || name == "a" {
|
||||
this.children(at, &own, &placed);
|
||||
} else if name == "svg" {
|
||||
if this.depth == 1 {
|
||||
this.children(at, &own, &placed);
|
||||
} else {
|
||||
this.viewport(at, &own, &placed, at, nothing {}, nothing {});
|
||||
}
|
||||
} else if name == "use" {
|
||||
this.use_element(at, &own, &placed);
|
||||
} else if name == "switch" {
|
||||
# The first child that would be drawn, its conditions taken as met.
|
||||
for child in at.elements() {
|
||||
if is_svg(&child) && (is_shape(child.local) || child.local == "g" || child.local == "svg" || child.local == "use") {
|
||||
this.draw(&child, &own, &placed);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
this.depth--;
|
||||
|
||||
if !layered {
|
||||
return;
|
||||
}
|
||||
var content := this.canvas.pop();
|
||||
var masking := vector::<u8>::new();
|
||||
if clip is some(clip_element) {
|
||||
masking = this.clip_mask(&clip_element, &placed, bounds);
|
||||
}
|
||||
if mask is some(mask_element) {
|
||||
var luminance := this.luminance_mask(&mask_element, &placed, bounds);
|
||||
if masking.is_empty {
|
||||
masking = move(luminance);
|
||||
} else {
|
||||
# Both: the clip's coverage times the mask's.
|
||||
var at_pixel: u64 = 3;
|
||||
while at_pixel < masking.length {
|
||||
masking[at_pixel] = ((masking[at_pixel] as u32 * luminance[at_pixel] as u32 + 127) / 255) as u8;
|
||||
at_pixel += 4;
|
||||
}
|
||||
}
|
||||
}
|
||||
this.canvas.composite(content.view(), own.opacity, masking.view(), false);
|
||||
}
|
||||
|
||||
def renderer::children(&mut this, at: &xml::element, own: &style, placed: &matrix): void {
|
||||
for child in at.elements() {
|
||||
this.draw(&child, own, placed);
|
||||
}
|
||||
}
|
||||
|
||||
# The element an ID names, where it's of a kind.
|
||||
def renderer::reference(&this, id: strview, kind: strview): maybe<xml::element> {
|
||||
if id.length == 0 {
|
||||
return nothing {};
|
||||
}
|
||||
val found := this.ids.get(&id) else { return nothing {}; };
|
||||
if found.local != kind {
|
||||
return nothing {};
|
||||
}
|
||||
return found;
|
||||
}
|
||||
|
||||
# What an element refers to, by `xlink:href` or SVG 2's `href`, or empty.
|
||||
def href_of(at: &xml::element): strview {
|
||||
if at.attribute(xlink_namespace, "href") is some(linked) {
|
||||
return linked;
|
||||
}
|
||||
return at.attribute("href") else "";
|
||||
}
|
||||
|
||||
# Whether an element is SVG's: in its namespace, or in none, as SVG written
|
||||
# without `xmlns` is.
|
||||
def is_svg(at: &xml::element): bool {
|
||||
val namespace := at.namespace;
|
||||
return namespace.length == 0 || namespace == svg_namespace;
|
||||
}
|
||||
|
||||
def is_shape(name: strview): bool {
|
||||
return name == "path" || name == "rect" || name == "circle" || name == "ellipse" || name == "line"
|
||||
|| name == "polyline" || name == "polygon";
|
||||
}
|
||||
|
||||
def is_presentation(name: strview): bool {
|
||||
for each in presentation {
|
||||
if each == name {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
@@ -0,0 +1,184 @@
|
||||
#! Contains what paints a fill or a stroke: its color, or its gradient, linear
|
||||
#! or radial, made of its attributes and stops and those of the gradients it
|
||||
#! refers to by `href`, a table of its colors along it.
|
||||
|
||||
import std::math;
|
||||
import std::xml;
|
||||
module image::svg;
|
||||
|
||||
|
||||
# What paints a fill or stroke: its color, or its gradient, scaled by an
|
||||
# opacity, or `nothing` where it paints nothing.
|
||||
def renderer::painter_for(&this, given: &paint, own: &style, opacity: f64, bounds: &point[2], placed: &matrix): maybe<painter> {
|
||||
match given.kind {
|
||||
none => return nothing {};
|
||||
color => return painter::solid(&given.color, opacity);
|
||||
current => return painter::solid(&own.color, opacity);
|
||||
url => {
|
||||
if this.ids.get(&given.url) is some(target) {
|
||||
if target.local == "linearGradient" || target.local == "radialGradient" {
|
||||
return this.gradient(&target, opacity, bounds, placed);
|
||||
}
|
||||
}
|
||||
# Where the gradient can't be found, what's given after it paints.
|
||||
return match given.fallback {
|
||||
color => painter::solid(&given.color, opacity),
|
||||
current => painter::solid(&own.color, opacity),
|
||||
else => nothing {},
|
||||
};
|
||||
}
|
||||
}
|
||||
return nothing {};
|
||||
}
|
||||
|
||||
# The painter of a gradient: its attributes, and its stops, from it or the
|
||||
# gradients it refers to by `href`, the nearest giving each.
|
||||
def renderer::gradient(&this, at: &xml::element, opacity: f64, bounds: &point[2], placed: &matrix): maybe<painter> {
|
||||
var chain := vector::<xml::element>::new();
|
||||
chain.append(copy(at));
|
||||
while chain.length < 16 {
|
||||
val href := href_of(&chain.last());
|
||||
if !href.starts_with("#") {
|
||||
break;
|
||||
}
|
||||
val id := href.substr(1, href.length - 1);
|
||||
val next := this.ids.get(&id) else { break; };
|
||||
if next.local != "linearGradient" && next.local != "radialGradient" {
|
||||
break;
|
||||
}
|
||||
chain.append(next);
|
||||
}
|
||||
|
||||
val radial := at.local == "radialGradient";
|
||||
val user_space := attribute_of(&chain, "gradientUnits") is some(units) && units == "userSpaceOnUse";
|
||||
var made := painter { by = radial ? paint_by::radial : paint_by::linear };
|
||||
val spread_written := attribute_of(&chain, "spreadMethod") else "pad";
|
||||
made.spread = spread_written == "reflect" ? spread::reflect : (spread_written == "repeat" ? spread::repeat : spread::pad);
|
||||
|
||||
# Coordinates: fractions of the bounds, or lengths in user space.
|
||||
if radial {
|
||||
made.x1 = this.gradient_length(&chain, "cx", user_space, axis::x, 0.5);
|
||||
made.y1 = this.gradient_length(&chain, "cy", user_space, axis::y, 0.5);
|
||||
made.r = this.gradient_length(&chain, "r", user_space, axis::diagonal, 0.5);
|
||||
# The focus is the center, where it's not given.
|
||||
made.x2 = attribute_of(&chain, "fx") is some(_) ? this.gradient_length(&chain, "fx", user_space, axis::x, 0.5) : made.x1;
|
||||
made.y2 = attribute_of(&chain, "fy") is some(_) ? this.gradient_length(&chain, "fy", user_space, axis::y, 0.5) : made.y1;
|
||||
# A focus outside the circle is moved onto it, as SVG 1.1 says.
|
||||
val dx := made.x2 - made.x1;
|
||||
val dy := made.y2 - made.y1;
|
||||
val distance := math::hypot(dx, dy);
|
||||
if distance > made.r * 0.999 && distance > 0 {
|
||||
made.x2 = made.x1 + dx * made.r * 0.999 / distance;
|
||||
made.y2 = made.y1 + dy * made.r * 0.999 / distance;
|
||||
}
|
||||
if made.r <= 0 {
|
||||
return nothing {};
|
||||
}
|
||||
} else {
|
||||
made.x1 = this.gradient_length(&chain, "x1", user_space, axis::x, 0);
|
||||
made.y1 = this.gradient_length(&chain, "y1", user_space, axis::y, 0);
|
||||
made.x2 = this.gradient_length(&chain, "x2", user_space, axis::x, 1);
|
||||
made.y2 = this.gradient_length(&chain, "y2", user_space, axis::y, 0);
|
||||
}
|
||||
|
||||
# The space it's in, then the canvas.
|
||||
var space := matrix {};
|
||||
if attribute_of(&chain, "gradientTransform") is some(written) {
|
||||
space = parse_transform(written) else matrix {};
|
||||
}
|
||||
if !user_space {
|
||||
val width := bounds[1].x - bounds[0].x;
|
||||
val height := bounds[1].y - bounds[0].y;
|
||||
if width <= 0 || height <= 0 {
|
||||
return nothing {};
|
||||
}
|
||||
space = space.then(&matrix { a = width, d = height, e = bounds[0].x, f = bounds[0].y });
|
||||
}
|
||||
made.inverse = space.then(placed).inverse() else { return nothing {}; };
|
||||
|
||||
# The stops, of the nearest gradient that has any, each offset no less than
|
||||
# the one before.
|
||||
var offsets := vector::<f64>::new();
|
||||
var colors := vector::<f32>::new();
|
||||
for linked in chain {
|
||||
for stop in linked.elements() {
|
||||
if stop.local != "stop" || !is_svg(&stop) {
|
||||
continue;
|
||||
}
|
||||
val stop_style := this.style_of(&stop, &style {});
|
||||
var offset := parse_fraction(stop.attribute("offset") else "0") else 0.0;
|
||||
offset = math::clamp(offset, 0.0, 1.0);
|
||||
if !offsets.is_empty && offset < offsets.last() {
|
||||
offset = offsets.last();
|
||||
}
|
||||
offsets.append(offset);
|
||||
colors.append(stop_style.stop_color.r as f32);
|
||||
colors.append(stop_style.stop_color.g as f32);
|
||||
colors.append(stop_style.stop_color.b as f32);
|
||||
colors.append((stop_style.stop_color.a * stop_style.stop_opacity * opacity) as f32);
|
||||
}
|
||||
if !offsets.is_empty {
|
||||
break;
|
||||
}
|
||||
}
|
||||
if offsets.is_empty {
|
||||
return nothing {};
|
||||
}
|
||||
|
||||
# The table: each stop's color up to the next, blended between them before
|
||||
# they're premultiplied, as browsers blend them.
|
||||
var stop: u64 = 0;
|
||||
for slot in 0u..256u {
|
||||
val t := slot as f64 / 255;
|
||||
while stop + 1 < offsets.length && offsets[stop + 1] <= t {
|
||||
stop++;
|
||||
}
|
||||
var mix: f64 = 0;
|
||||
var next := stop;
|
||||
if t > offsets[stop] && stop + 1 < offsets.length {
|
||||
next = stop + 1;
|
||||
val gap := offsets[next] - offsets[stop];
|
||||
mix = gap <= 0 ? 1.0 : (t - offsets[stop]) / gap;
|
||||
}
|
||||
if t < offsets[0] {
|
||||
mix = 0;
|
||||
next = 0;
|
||||
}
|
||||
var blended: f64[4];
|
||||
for channel in 0u..4u {
|
||||
val from := colors[stop * 4 + channel] as f64;
|
||||
val to := colors[next * 4 + channel] as f64;
|
||||
blended[channel] = from + (to - from) * mix;
|
||||
}
|
||||
for channel in 0u..3u {
|
||||
made.table[slot * 4 + channel] = (blended[channel] * blended[3]) as f32;
|
||||
}
|
||||
made.table[slot * 4 + 3] = blended[3] as f32;
|
||||
}
|
||||
return made;
|
||||
}
|
||||
|
||||
# A gradient's coordinate: a fraction of the bounds, or a length in user space,
|
||||
# where what it is when left out is a fraction of the bounds or the viewport.
|
||||
def renderer::gradient_length(&this, chain: &vector<xml::element>, name: strview, user_space: bool, along: axis, fallback: f64): f64 {
|
||||
val written := attribute_of(chain, name) else { return user_space && fallback != 0 ? this.percent(fallback, along) : fallback; };
|
||||
if user_space {
|
||||
return parse_length(written, &this.view, along) else fallback;
|
||||
}
|
||||
return parse_fraction(written) else fallback;
|
||||
}
|
||||
|
||||
# A fraction of the viewport along an axis, as a percentage of it is.
|
||||
def renderer::percent(&this, fraction: f64, along: axis): f64 {
|
||||
return fraction * (along == axis::x ? this.view.width : (along == axis::y ? this.view.height : this.view.diagonal()));
|
||||
}
|
||||
|
||||
# The first of a chain of gradients to give an attribute.
|
||||
def attribute_of(chain: &vector<xml::element>, name: strview): maybe<strview> {
|
||||
for linked in chain {
|
||||
if linked.attribute(name) is some(value) {
|
||||
return value;
|
||||
}
|
||||
}
|
||||
return nothing {};
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
#! Contains lengths, in user units: numbers, with a unit or as a percentage of
|
||||
#! the viewport, and fractions, as offsets and opacities are written.
|
||||
|
||||
import std::math;
|
||||
module image::svg;
|
||||
|
||||
|
||||
# The size percentages are of, and that of the viewport's diagonal, as the user
|
||||
# space being drawn in measures them.
|
||||
struct viewport {
|
||||
var width: f64;
|
||||
var height: f64;
|
||||
}
|
||||
|
||||
def viewport::diagonal(&this): f64 {
|
||||
return math::sqrt((this.width * this.width + this.height * this.height) / 2);
|
||||
}
|
||||
|
||||
# Which length a percentage is of.
|
||||
enum axis: u8 {
|
||||
x,
|
||||
y,
|
||||
diagonal,
|
||||
}
|
||||
|
||||
# Reads a length, in user units: a number, with a unit or a percentage of the
|
||||
# viewport.
|
||||
def parse_length(text: strview, view: &viewport, along: axis): maybe<f64> {
|
||||
val trimmed := text.trim();
|
||||
val read := number_at(trimmed, 0) else { return nothing {}; };
|
||||
val unit := trimmed.substr(read.end, trimmed.length - read.end).trim();
|
||||
val scale: f64 = match unit {
|
||||
"" => 1.0,
|
||||
"px" => 1.0,
|
||||
"pt" => 4.0 / 3.0,
|
||||
"pc" => 16.0,
|
||||
"mm" => 96.0 / 25.4,
|
||||
"cm" => 96.0 / 2.54,
|
||||
"in" => 96.0,
|
||||
"em" => 16.0,
|
||||
"ex" => 8.0,
|
||||
"%" => (along == axis::x ? view.width : (along == axis::y ? view.height : view.diagonal())) / 100,
|
||||
else => -1.0,
|
||||
};
|
||||
if scale < 0 {
|
||||
return nothing {};
|
||||
}
|
||||
return read.value * scale;
|
||||
}
|
||||
|
||||
# Reads a number, or a percentage of 1, as offsets and opacities are written.
|
||||
def parse_fraction(text: strview): maybe<f64> {
|
||||
val trimmed := text.trim();
|
||||
val read := number_at(trimmed, 0) else { return nothing {}; };
|
||||
val rest := trimmed.substr(read.end, trimmed.length - read.end).trim();
|
||||
if rest == "%" {
|
||||
return read.value / 100;
|
||||
}
|
||||
return rest.length == 0 ? read.value : nothing {};
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
#! Contains clips and masks: the coverage a `clipPath`'s shapes give, each solid,
|
||||
#! and the luminance a `mask`'s content gives, each drawn as a layer of its own.
|
||||
|
||||
import std::xml;
|
||||
module image::svg;
|
||||
|
||||
|
||||
# A clip path's coverage, drawn as a layer of its shapes, each solid.
|
||||
def renderer::clip_mask(&mut this, clip: &xml::element, placed: &matrix, bounds: maybe<point[2]>): vector<u8> {
|
||||
var space := copy(placed);
|
||||
if clip.attribute("clipPathUnits") is some(units) && units == "objectBoundingBox" {
|
||||
val box := bounds else {
|
||||
var empty := vector::<u8>::new();
|
||||
empty.resize(this.canvas.width * this.canvas.height * 4);
|
||||
return empty;
|
||||
};
|
||||
space = matrix { a = box[1].x - box[0].x, d = box[1].y - box[0].y, e = box[0].x, f = box[0].y }.then(placed);
|
||||
}
|
||||
if clip.attribute("transform") is some(written) {
|
||||
if parse_transform(written) is some(own_transform) {
|
||||
space = own_transform.then(&space);
|
||||
}
|
||||
}
|
||||
val clip_style := this.style_of(clip, &style {});
|
||||
this.canvas.push();
|
||||
val saved := this.clipping;
|
||||
this.clipping = true;
|
||||
for child in clip.elements() {
|
||||
if is_shape(child.local) || child.local == "use" {
|
||||
this.draw(&child, &clip_style, &space);
|
||||
}
|
||||
}
|
||||
this.clipping = saved;
|
||||
return this.canvas.pop();
|
||||
}
|
||||
|
||||
# A mask's coverage: its content drawn as a layer, its luminance taken as alpha.
|
||||
def renderer::luminance_mask(&mut this, mask: &xml::element, placed: &matrix, bounds: maybe<point[2]>): vector<u8> {
|
||||
var space := copy(placed);
|
||||
if mask.attribute("maskContentUnits") is some(units) && units == "objectBoundingBox" {
|
||||
if bounds is some(box) {
|
||||
space = matrix { a = box[1].x - box[0].x, d = box[1].y - box[0].y, e = box[0].x, f = box[0].y }.then(placed);
|
||||
}
|
||||
}
|
||||
val mask_style := this.style_of(mask, &style {});
|
||||
this.canvas.push();
|
||||
this.children(mask, &mask_style, &space);
|
||||
var made := this.canvas.pop();
|
||||
var at: u64 = 0;
|
||||
while at < made.length {
|
||||
val luminance := made[at] as f32 * 0.2125 + made[at + 1] as f32 * 0.7154 + made[at + 2] as f32 * 0.0721;
|
||||
made[at + 3] = (luminance + 0.5) as u8;
|
||||
at += 4;
|
||||
}
|
||||
return made;
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
#! Contains points and the affine transforms between SVG's spaces, and the
|
||||
#! lists of transforms an element's `transform` gives.
|
||||
|
||||
import std::math;
|
||||
module image::svg;
|
||||
|
||||
|
||||
# A point, in whatever space it's in.
|
||||
struct point {
|
||||
var x: f64;
|
||||
var y: f64;
|
||||
}
|
||||
|
||||
# An affine transform, mapping (x, y) to (a x + c y + e, b x + d y + f), as SVG's
|
||||
# `matrix(a b c d e f)` does.
|
||||
struct matrix {
|
||||
var a: f64 = 1;
|
||||
var b: f64 = 0;
|
||||
var c: f64 = 0;
|
||||
var d: f64 = 1;
|
||||
var e: f64 = 0;
|
||||
var f: f64 = 0;
|
||||
}
|
||||
|
||||
# The transform that applies this one, then another.
|
||||
def matrix::then(&this, outer: &matrix): matrix {
|
||||
return matrix {
|
||||
a = outer.a * this.a + outer.c * this.b,
|
||||
b = outer.b * this.a + outer.d * this.b,
|
||||
c = outer.a * this.c + outer.c * this.d,
|
||||
d = outer.b * this.c + outer.d * this.d,
|
||||
e = outer.a * this.e + outer.c * this.f + outer.e,
|
||||
f = outer.b * this.e + outer.d * this.f + outer.f
|
||||
};
|
||||
}
|
||||
|
||||
def matrix::apply(&this, at: point): point {
|
||||
return point { x = this.a * at.x + this.c * at.y + this.e, y = this.b * at.x + this.d * at.y + this.f };
|
||||
}
|
||||
|
||||
# The transform undoing this one, or `nothing` where it flattens everything.
|
||||
def matrix::inverse(&this): maybe<matrix> {
|
||||
val det := this.a * this.d - this.b * this.c;
|
||||
if math::abs(det) < 1e-12 {
|
||||
return nothing {};
|
||||
}
|
||||
return matrix {
|
||||
a = this.d / det,
|
||||
b = -this.b / det,
|
||||
c = -this.c / det,
|
||||
d = this.a / det,
|
||||
e = (this.c * this.f - this.d * this.e) / det,
|
||||
f = (this.b * this.e - this.a * this.f) / det
|
||||
};
|
||||
}
|
||||
|
||||
# How much the transform stretches lengths at most, which tolerances in user
|
||||
# space are divided by.
|
||||
def matrix::stretch(&this): f64 {
|
||||
val across := math::sqrt(this.a * this.a + this.b * this.b);
|
||||
val down := math::sqrt(this.c * this.c + this.d * this.d);
|
||||
return across > down ? across : down;
|
||||
}
|
||||
|
||||
def translation(x: f64, y: f64): matrix {
|
||||
return matrix { e = x, f = y };
|
||||
}
|
||||
|
||||
def scaling(x: f64, y: f64): matrix {
|
||||
return matrix { a = x, d = y };
|
||||
}
|
||||
|
||||
def rotation(degrees: f64): matrix {
|
||||
val angle := degrees * math::pi / 180;
|
||||
val cos := math::cos(angle);
|
||||
val sin := math::sin(angle);
|
||||
return matrix { a = cos, b = sin, c = -sin, d = cos };
|
||||
}
|
||||
|
||||
# Reads SVG's list of transforms, each applied after those after it, as an
|
||||
# element's `transform` gives them.
|
||||
# @returns The transform, or `nothing` where the list is broken, which SVG takes
|
||||
# as none at all.
|
||||
def parse_transform(text: strview): maybe<matrix> {
|
||||
var made := matrix {};
|
||||
var at: u64 = 0;
|
||||
while true {
|
||||
while at < text.length && (text[at].is_space || text[at] == ',') {
|
||||
at++;
|
||||
}
|
||||
if at >= text.length {
|
||||
break;
|
||||
}
|
||||
var name_end := at;
|
||||
while name_end < text.length && text[name_end].is_alpha {
|
||||
name_end++;
|
||||
}
|
||||
val name := text.substr(at, name_end - at);
|
||||
val open := text.substr(name_end, text.length - name_end).find("(") else { return nothing {}; };
|
||||
val close := text.substr(name_end, text.length - name_end).find(")") else { return nothing {}; };
|
||||
if close < open {
|
||||
return nothing {};
|
||||
}
|
||||
var values: f64[6];
|
||||
var count: u64 = 0;
|
||||
var read := numbers::of(text.substr(name_end + open + 1, close - open - 1));
|
||||
while !read.at_end() {
|
||||
val value := read.next() else { return nothing {}; };
|
||||
if count >= 6 {
|
||||
return nothing {};
|
||||
}
|
||||
values[count] = value;
|
||||
count++;
|
||||
}
|
||||
at = name_end + close + 1;
|
||||
|
||||
var step := matrix {};
|
||||
if name == "matrix" && count == 6 {
|
||||
step = matrix { a = values[0], b = values[1], c = values[2], d = values[3], e = values[4], f = values[5] };
|
||||
} else if name == "translate" && (count == 1 || count == 2) {
|
||||
step = translation(values[0], count == 2 ? values[1] : 0);
|
||||
} else if name == "scale" && (count == 1 || count == 2) {
|
||||
step = scaling(values[0], count == 2 ? values[1] : values[0]);
|
||||
} else if name == "rotate" && count == 1 {
|
||||
step = rotation(values[0]);
|
||||
} else if name == "rotate" && count == 3 {
|
||||
step = translation(-values[1], -values[2]).then(&rotation(values[0])).then(&translation(values[1], values[2]));
|
||||
} else if name == "skewX" && count == 1 {
|
||||
step = matrix { c = math::tan(values[0] * math::pi / 180) };
|
||||
} else if name == "skewY" && count == 1 {
|
||||
step = matrix { b = math::tan(values[0] * math::pi / 180) };
|
||||
} else {
|
||||
return nothing {};
|
||||
}
|
||||
made = step.then(&made);
|
||||
}
|
||||
return made;
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
#! Contains the colors CSS names, and the RGB of each.
|
||||
|
||||
module image::svg;
|
||||
|
||||
|
||||
# A color CSS names, and its RGB.
|
||||
struct named_color {
|
||||
var name: strview;
|
||||
var rgb: u32;
|
||||
}
|
||||
|
||||
const named_colors: named_color[147] = [
|
||||
named_color { name = "aliceblue", rgb = 0xF0F8FF }, named_color { name = "antiquewhite", rgb = 0xFAEBD7 },
|
||||
named_color { name = "aqua", rgb = 0x00FFFF }, named_color { name = "aquamarine", rgb = 0x7FFFD4 },
|
||||
named_color { name = "azure", rgb = 0xF0FFFF }, named_color { name = "beige", rgb = 0xF5F5DC },
|
||||
named_color { name = "bisque", rgb = 0xFFE4C4 }, named_color { name = "black", rgb = 0x000000 },
|
||||
named_color { name = "blanchedalmond", rgb = 0xFFEBCD }, named_color { name = "blue", rgb = 0x0000FF },
|
||||
named_color { name = "blueviolet", rgb = 0x8A2BE2 }, named_color { name = "brown", rgb = 0xA52A2A },
|
||||
named_color { name = "burlywood", rgb = 0xDEB887 }, named_color { name = "cadetblue", rgb = 0x5F9EA0 },
|
||||
named_color { name = "chartreuse", rgb = 0x7FFF00 }, named_color { name = "chocolate", rgb = 0xD2691E },
|
||||
named_color { name = "coral", rgb = 0xFF7F50 }, named_color { name = "cornflowerblue", rgb = 0x6495ED },
|
||||
named_color { name = "cornsilk", rgb = 0xFFF8DC }, named_color { name = "crimson", rgb = 0xDC143C },
|
||||
named_color { name = "cyan", rgb = 0x00FFFF }, named_color { name = "darkblue", rgb = 0x00008B },
|
||||
named_color { name = "darkcyan", rgb = 0x008B8B }, named_color { name = "darkgoldenrod", rgb = 0xB8860B },
|
||||
named_color { name = "darkgray", rgb = 0xA9A9A9 }, named_color { name = "darkgreen", rgb = 0x006400 },
|
||||
named_color { name = "darkgrey", rgb = 0xA9A9A9 }, named_color { name = "darkkhaki", rgb = 0xBDB76B },
|
||||
named_color { name = "darkmagenta", rgb = 0x8B008B }, named_color { name = "darkolivegreen", rgb = 0x556B2F },
|
||||
named_color { name = "darkorange", rgb = 0xFF8C00 }, named_color { name = "darkorchid", rgb = 0x9932CC },
|
||||
named_color { name = "darkred", rgb = 0x8B0000 }, named_color { name = "darksalmon", rgb = 0xE9967A },
|
||||
named_color { name = "darkseagreen", rgb = 0x8FBC8F }, named_color { name = "darkslateblue", rgb = 0x483D8B },
|
||||
named_color { name = "darkslategray", rgb = 0x2F4F4F }, named_color { name = "darkslategrey", rgb = 0x2F4F4F },
|
||||
named_color { name = "darkturquoise", rgb = 0x00CED1 }, named_color { name = "darkviolet", rgb = 0x9400D3 },
|
||||
named_color { name = "deeppink", rgb = 0xFF1493 }, named_color { name = "deepskyblue", rgb = 0x00BFFF },
|
||||
named_color { name = "dimgray", rgb = 0x696969 }, named_color { name = "dimgrey", rgb = 0x696969 },
|
||||
named_color { name = "dodgerblue", rgb = 0x1E90FF }, named_color { name = "firebrick", rgb = 0xB22222 },
|
||||
named_color { name = "floralwhite", rgb = 0xFFFAF0 }, named_color { name = "forestgreen", rgb = 0x228B22 },
|
||||
named_color { name = "fuchsia", rgb = 0xFF00FF }, named_color { name = "gainsboro", rgb = 0xDCDCDC },
|
||||
named_color { name = "ghostwhite", rgb = 0xF8F8FF }, named_color { name = "gold", rgb = 0xFFD700 },
|
||||
named_color { name = "goldenrod", rgb = 0xDAA520 }, named_color { name = "gray", rgb = 0x808080 },
|
||||
named_color { name = "grey", rgb = 0x808080 }, named_color { name = "green", rgb = 0x008000 },
|
||||
named_color { name = "greenyellow", rgb = 0xADFF2F }, named_color { name = "honeydew", rgb = 0xF0FFF0 },
|
||||
named_color { name = "hotpink", rgb = 0xFF69B4 }, named_color { name = "indianred", rgb = 0xCD5C5C },
|
||||
named_color { name = "indigo", rgb = 0x4B0082 }, named_color { name = "ivory", rgb = 0xFFFFF0 },
|
||||
named_color { name = "khaki", rgb = 0xF0E68C }, named_color { name = "lavender", rgb = 0xE6E6FA },
|
||||
named_color { name = "lavenderblush", rgb = 0xFFF0F5 }, named_color { name = "lawngreen", rgb = 0x7CFC00 },
|
||||
named_color { name = "lemonchiffon", rgb = 0xFFFACD }, named_color { name = "lightblue", rgb = 0xADD8E6 },
|
||||
named_color { name = "lightcoral", rgb = 0xF08080 }, named_color { name = "lightcyan", rgb = 0xE0FFFF },
|
||||
named_color { name = "lightgoldenrodyellow", rgb = 0xFAFAD2 }, named_color { name = "lightgray", rgb = 0xD3D3D3 },
|
||||
named_color { name = "lightgreen", rgb = 0x90EE90 }, named_color { name = "lightgrey", rgb = 0xD3D3D3 },
|
||||
named_color { name = "lightpink", rgb = 0xFFB6C1 }, named_color { name = "lightsalmon", rgb = 0xFFA07A },
|
||||
named_color { name = "lightseagreen", rgb = 0x20B2AA }, named_color { name = "lightskyblue", rgb = 0x87CEFA },
|
||||
named_color { name = "lightslategray", rgb = 0x778899 }, named_color { name = "lightslategrey", rgb = 0x778899 },
|
||||
named_color { name = "lightsteelblue", rgb = 0xB0C4DE }, named_color { name = "lightyellow", rgb = 0xFFFFE0 },
|
||||
named_color { name = "lime", rgb = 0x00FF00 }, named_color { name = "limegreen", rgb = 0x32CD32 },
|
||||
named_color { name = "linen", rgb = 0xFAF0E6 }, named_color { name = "magenta", rgb = 0xFF00FF },
|
||||
named_color { name = "maroon", rgb = 0x800000 }, named_color { name = "mediumaquamarine", rgb = 0x66CDAA },
|
||||
named_color { name = "mediumblue", rgb = 0x0000CD }, named_color { name = "mediumorchid", rgb = 0xBA55D3 },
|
||||
named_color { name = "mediumpurple", rgb = 0x9370DB }, named_color { name = "mediumseagreen", rgb = 0x3CB371 },
|
||||
named_color { name = "mediumslateblue", rgb = 0x7B68EE }, named_color { name = "mediumspringgreen", rgb = 0x00FA9A },
|
||||
named_color { name = "mediumturquoise", rgb = 0x48D1CC }, named_color { name = "mediumvioletred", rgb = 0xC71585 },
|
||||
named_color { name = "midnightblue", rgb = 0x191970 }, named_color { name = "mintcream", rgb = 0xF5FFFA },
|
||||
named_color { name = "mistyrose", rgb = 0xFFE4E1 }, named_color { name = "moccasin", rgb = 0xFFE4B5 },
|
||||
named_color { name = "navajowhite", rgb = 0xFFDEAD }, named_color { name = "navy", rgb = 0x000080 },
|
||||
named_color { name = "oldlace", rgb = 0xFDF5E6 }, named_color { name = "olive", rgb = 0x808000 },
|
||||
named_color { name = "olivedrab", rgb = 0x6B8E23 }, named_color { name = "orange", rgb = 0xFFA500 },
|
||||
named_color { name = "orangered", rgb = 0xFF4500 }, named_color { name = "orchid", rgb = 0xDA70D6 },
|
||||
named_color { name = "palegoldenrod", rgb = 0xEEE8AA }, named_color { name = "palegreen", rgb = 0x98FB98 },
|
||||
named_color { name = "paleturquoise", rgb = 0xAFEEEE }, named_color { name = "palevioletred", rgb = 0xDB7093 },
|
||||
named_color { name = "papayawhip", rgb = 0xFFEFD5 }, named_color { name = "peachpuff", rgb = 0xFFDAB9 },
|
||||
named_color { name = "peru", rgb = 0xCD853F }, named_color { name = "pink", rgb = 0xFFC0CB },
|
||||
named_color { name = "plum", rgb = 0xDDA0DD }, named_color { name = "powderblue", rgb = 0xB0E0E6 },
|
||||
named_color { name = "purple", rgb = 0x800080 }, named_color { name = "red", rgb = 0xFF0000 },
|
||||
named_color { name = "rosybrown", rgb = 0xBC8F8F }, named_color { name = "royalblue", rgb = 0x4169E1 },
|
||||
named_color { name = "saddlebrown", rgb = 0x8B4513 }, named_color { name = "salmon", rgb = 0xFA8072 },
|
||||
named_color { name = "sandybrown", rgb = 0xF4A460 }, named_color { name = "seagreen", rgb = 0x2E8B57 },
|
||||
named_color { name = "seashell", rgb = 0xFFF5EE }, named_color { name = "sienna", rgb = 0xA0522D },
|
||||
named_color { name = "silver", rgb = 0xC0C0C0 }, named_color { name = "skyblue", rgb = 0x87CEEB },
|
||||
named_color { name = "slateblue", rgb = 0x6A5ACD }, named_color { name = "slategray", rgb = 0x708090 },
|
||||
named_color { name = "slategrey", rgb = 0x708090 }, named_color { name = "snow", rgb = 0xFFFAFA },
|
||||
named_color { name = "springgreen", rgb = 0x00FF7F }, named_color { name = "steelblue", rgb = 0x4682B4 },
|
||||
named_color { name = "tan", rgb = 0xD2B48C }, named_color { name = "teal", rgb = 0x008080 },
|
||||
named_color { name = "thistle", rgb = 0xD8BFD8 }, named_color { name = "tomato", rgb = 0xFF6347 },
|
||||
named_color { name = "turquoise", rgb = 0x40E0D0 }, named_color { name = "violet", rgb = 0xEE82EE },
|
||||
named_color { name = "wheat", rgb = 0xF5DEB3 }, named_color { name = "white", rgb = 0xFFFFFF },
|
||||
named_color { name = "whitesmoke", rgb = 0xF5F5F5 }, named_color { name = "yellow", rgb = 0xFFFF00 },
|
||||
named_color { name = "yellowgreen", rgb = 0x9ACD32 },
|
||||
];
|
||||
@@ -0,0 +1,127 @@
|
||||
#! Contains the numbers of attributes' text, as CSS and SVG write them, and the
|
||||
#! separators between them.
|
||||
|
||||
import std::math;
|
||||
module image::svg;
|
||||
|
||||
|
||||
# Reads numbers, and the separators between them, from attributes' text.
|
||||
struct numbers {
|
||||
var text: strview;
|
||||
var at: u64;
|
||||
}
|
||||
|
||||
def numbers::of(text: strview): numbers {
|
||||
return numbers { text = text };
|
||||
}
|
||||
|
||||
# Moves past whitespace, and a comma among it.
|
||||
def numbers::skip(&mut this): void {
|
||||
var comma := false;
|
||||
while this.at < this.text.length {
|
||||
val byte := this.text[this.at];
|
||||
if byte == ',' && !comma {
|
||||
comma = true;
|
||||
} else if !byte.is_space {
|
||||
return;
|
||||
}
|
||||
this.at++;
|
||||
}
|
||||
}
|
||||
|
||||
def numbers::at_end(&mut this): bool {
|
||||
this.skip();
|
||||
return this.at >= this.text.length;
|
||||
}
|
||||
|
||||
# Reads a number, as CSS and SVG write them: a sign, digits with or without a
|
||||
# point, and an exponent, so `1.5.5` is two, and `-1-2` too.
|
||||
def numbers::next(&mut this): maybe<f64> {
|
||||
this.skip();
|
||||
val read := number_at(this.text, this.at) else { return nothing {}; };
|
||||
this.at = read.end;
|
||||
return read.value;
|
||||
}
|
||||
|
||||
# Reads a flag of an arc, `0` or `1`, which needs nothing after it.
|
||||
def numbers::flag(&mut this): maybe<bool> {
|
||||
this.skip();
|
||||
if this.at >= this.text.length {
|
||||
return nothing {};
|
||||
}
|
||||
val byte := this.text[this.at];
|
||||
if byte != '0' && byte != '1' {
|
||||
return nothing {};
|
||||
}
|
||||
this.at++;
|
||||
return byte == '1';
|
||||
}
|
||||
|
||||
def numbers::point(&mut this): maybe<point> {
|
||||
val x := this.next() else { return nothing {}; };
|
||||
val y := this.next() else { return nothing {}; };
|
||||
return point { x = x, y = y };
|
||||
}
|
||||
|
||||
# A number read, and where it ends.
|
||||
struct read_number {
|
||||
var value: f64;
|
||||
var end: u64;
|
||||
}
|
||||
|
||||
# Reads a number beginning at a byte.
|
||||
def number_at(text: strview, from: u64): maybe<read_number> {
|
||||
var at := from;
|
||||
var negative := false;
|
||||
if at < text.length && (text[at] == '+' || text[at] == '-') {
|
||||
negative = text[at] == '-';
|
||||
at++;
|
||||
}
|
||||
var mantissa: f64 = 0;
|
||||
var digits := 0u;
|
||||
var scale: i64 = 0;
|
||||
while at < text.length && text[at].is_digit {
|
||||
mantissa = mantissa * 10 + (text[at] - '0') as f64;
|
||||
digits++;
|
||||
at++;
|
||||
}
|
||||
if at < text.length && text[at] == '.' {
|
||||
var fraction := at + 1;
|
||||
while fraction < text.length && text[fraction].is_digit {
|
||||
mantissa = mantissa * 10 + (text[fraction] - '0') as f64;
|
||||
scale--;
|
||||
digits++;
|
||||
fraction++;
|
||||
}
|
||||
if fraction > at + 1 || digits > 0 {
|
||||
at = fraction;
|
||||
}
|
||||
}
|
||||
if digits == 0 {
|
||||
return nothing {};
|
||||
}
|
||||
if at < text.length && (text[at] == 'e' || text[at] == 'E') {
|
||||
var exponent_at := at + 1;
|
||||
var exponent_negative := false;
|
||||
if exponent_at < text.length && (text[exponent_at] == '+' || text[exponent_at] == '-') {
|
||||
exponent_negative = text[exponent_at] == '-';
|
||||
exponent_at++;
|
||||
}
|
||||
if exponent_at < text.length && text[exponent_at].is_digit {
|
||||
var exponent: i64 = 0;
|
||||
while exponent_at < text.length && text[exponent_at].is_digit {
|
||||
if exponent < 10000 {
|
||||
exponent = exponent * 10 + (text[exponent_at] - '0') as i64;
|
||||
}
|
||||
exponent_at++;
|
||||
}
|
||||
scale += exponent_negative ? -exponent : exponent;
|
||||
at = exponent_at;
|
||||
}
|
||||
}
|
||||
var value := mantissa;
|
||||
if scale != 0 {
|
||||
value = mantissa * math::pow(10.0, scale as f64);
|
||||
}
|
||||
return read_number { value = negative ? -value : value, end = at };
|
||||
}
|
||||
@@ -0,0 +1,155 @@
|
||||
#! Contains outlines: the polygons and polylines paths are flattened to, and
|
||||
#! strokes made, before they're filled.
|
||||
|
||||
import std::math;
|
||||
module image::svg;
|
||||
|
||||
|
||||
# How far, in pixels, a flattened curve may stray from the curve.
|
||||
const tolerance: f64 = 0.2;
|
||||
|
||||
# A polygon or polyline of an outline, by its points in the outline's.
|
||||
struct contour {
|
||||
var start: u64;
|
||||
var count: u64;
|
||||
var closed: bool;
|
||||
}
|
||||
|
||||
# Polygons and polylines, as paths are flattened to, and strokes made.
|
||||
struct outline {
|
||||
var points: vector<point>;
|
||||
var contours: vector<contour>;
|
||||
var begun: u64; #! Where the contour being added began.
|
||||
}
|
||||
|
||||
def outline::new(): outline {
|
||||
return outline { points = vector::<point>::new(), contours = vector::<contour>::new() };
|
||||
}
|
||||
|
||||
def outline::begin(&mut this): void {
|
||||
this.begun = this.points.length;
|
||||
}
|
||||
|
||||
def outline::add(&mut this, at: point): void {
|
||||
this.points.append(at);
|
||||
}
|
||||
|
||||
# Ends the contour being added, keeping it where it has a point.
|
||||
def outline::finish(&mut this, closed: bool): void {
|
||||
if this.points.length > this.begun {
|
||||
this.contours.append(contour { start = this.begun, count = this.points.length - this.begun, closed = closed });
|
||||
}
|
||||
this.begun = this.points.length;
|
||||
}
|
||||
|
||||
# Adds a closed polygon, its points turning the same way as every other the
|
||||
# stroker adds, so filling them all by the nonzero rule fills where any is.
|
||||
def outline::polygon(&mut this, corners: span<point>): void {
|
||||
var area: f64 = 0;
|
||||
for index in 0..corners.length {
|
||||
val a := corners[index];
|
||||
val b := corners[(index + 1) % corners.length];
|
||||
area += a.x * b.y - b.x * a.y;
|
||||
}
|
||||
this.begin();
|
||||
if area >= 0 {
|
||||
for corner in corners {
|
||||
this.add(corner);
|
||||
}
|
||||
} else {
|
||||
var index := corners.length;
|
||||
while index > 0 {
|
||||
index--;
|
||||
this.add(corners[index]);
|
||||
}
|
||||
}
|
||||
this.finish(true);
|
||||
}
|
||||
|
||||
# The outline with each point transformed.
|
||||
def outline::transformed(&this, by: &matrix): outline {
|
||||
var made := outline::new();
|
||||
for at in this.points {
|
||||
made.points.append(by.apply(at));
|
||||
}
|
||||
for held in this.contours {
|
||||
made.contours.append(held);
|
||||
}
|
||||
return made;
|
||||
}
|
||||
|
||||
# The smallest rectangle holding every point, as its least and greatest corners.
|
||||
def outline::bounds(&this): point[2] {
|
||||
if this.points.is_empty {
|
||||
return [point {}, point {}];
|
||||
}
|
||||
var low := this.points[0];
|
||||
var high := low;
|
||||
for at in this.points {
|
||||
low.x = at.x < low.x ? at.x : low.x;
|
||||
low.y = at.y < low.y ? at.y : low.y;
|
||||
high.x = at.x > high.x ? at.x : high.x;
|
||||
high.y = at.y > high.y ? at.y : high.y;
|
||||
}
|
||||
return [low, high];
|
||||
}
|
||||
|
||||
# Flattens a path, transformed, into polylines: each curve into as many lines
|
||||
# as keep it within a distance, by Wang's formula.
|
||||
def flatten(shape: &path, by: &matrix, within: f64): outline {
|
||||
var made := outline::new();
|
||||
var open := false;
|
||||
var at: u64 = 0;
|
||||
var last := point {};
|
||||
for each in shape.verbs {
|
||||
match each {
|
||||
move => {
|
||||
if open {
|
||||
made.finish(false);
|
||||
}
|
||||
made.begin();
|
||||
last = by.apply(shape.points[at]);
|
||||
made.add(last);
|
||||
at++;
|
||||
open = true;
|
||||
}
|
||||
line => {
|
||||
last = by.apply(shape.points[at]);
|
||||
made.add(last);
|
||||
at++;
|
||||
}
|
||||
cubic => {
|
||||
val p0 := last;
|
||||
val p1 := by.apply(shape.points[at]);
|
||||
val p2 := by.apply(shape.points[at + 1]);
|
||||
val p3 := by.apply(shape.points[at + 2]);
|
||||
at += 3;
|
||||
val bend1 := math::hypot(p0.x - 2 * p1.x + p2.x, p0.y - 2 * p1.y + p2.y);
|
||||
val bend2 := math::hypot(p1.x - 2 * p2.x + p3.x, p1.y - 2 * p2.y + p3.y);
|
||||
val bend := bend1 > bend2 ? bend1 : bend2;
|
||||
var pieces := math::ceil(math::sqrt(bend * 0.75 / within));
|
||||
pieces = pieces < 1 ? 1 : (pieces > 1000 ? 1000 : pieces);
|
||||
val count := pieces as u64;
|
||||
for step in 1..count {
|
||||
val t := step as f64 / pieces;
|
||||
val u := 1 - t;
|
||||
val a := u * u * u;
|
||||
val b := 3 * u * u * t;
|
||||
val c := 3 * u * t * t;
|
||||
val d := t * t * t;
|
||||
made.add(point { x = a * p0.x + b * p1.x + c * p2.x + d * p3.x, y = a * p0.y + b * p1.y + c * p2.y + d * p3.y });
|
||||
}
|
||||
made.add(p3);
|
||||
last = p3;
|
||||
}
|
||||
close => {
|
||||
made.finish(true);
|
||||
open = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
if open {
|
||||
made.finish(false);
|
||||
}
|
||||
return made;
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
#! Contains paints, as a fill or stroke gives one: none, the element's own
|
||||
#! color, a color, or a gradient by its ID, with what paints where it can't be
|
||||
#! found.
|
||||
|
||||
module image::svg;
|
||||
|
||||
|
||||
# What paints a fill or stroke.
|
||||
enum paint_kind: u8 {
|
||||
none,
|
||||
color,
|
||||
current, #! The element's `color`.
|
||||
url, #! A gradient, by its ID, or the fallback after it.
|
||||
}
|
||||
|
||||
struct paint {
|
||||
var kind: paint_kind;
|
||||
var color: color;
|
||||
var url: strview;
|
||||
var fallback: paint_kind = paint_kind::none; #! What paints where the gradient can't: none, a color, or `currentColor`.
|
||||
}
|
||||
|
||||
# Reads a paint: `none`, `currentColor`, a color, or `url(#id)` and what paints
|
||||
# where it can't.
|
||||
def parse_paint(text: strview): maybe<paint> {
|
||||
val trimmed := text.trim();
|
||||
if trimmed == "none" {
|
||||
return paint { kind = paint_kind::none };
|
||||
}
|
||||
if same_letters(trimmed, "currentColor") {
|
||||
return paint { kind = paint_kind::current };
|
||||
}
|
||||
if trimmed.starts_with("url(") {
|
||||
val close := trimmed.find(")") else { return nothing {}; };
|
||||
var target := trimmed.substr(4, close - 4).trim();
|
||||
if target.length >= 2 && (target[0] == '"' || target[0] == '\'') {
|
||||
target = target.substr(1, target.length - 2);
|
||||
}
|
||||
if !target.starts_with("#") {
|
||||
return nothing {};
|
||||
}
|
||||
var made := paint { kind = paint_kind::url, url = target.substr(1, target.length - 1) };
|
||||
val rest := trimmed.substr(close + 1, trimmed.length - close - 1).trim();
|
||||
if rest.length != 0 {
|
||||
val fallback := parse_paint(rest) else { return nothing {}; };
|
||||
made.fallback = fallback.kind;
|
||||
made.color = fallback.color;
|
||||
}
|
||||
return made;
|
||||
}
|
||||
val found := parse_color(trimmed) else { return nothing {}; };
|
||||
return paint { kind = paint_kind::color, color = found };
|
||||
}
|
||||
|
||||
# The ID `url(#id)` names, or empty for `none` or what isn't one.
|
||||
def url_of(text: strview): strview {
|
||||
val read := parse_paint(text) else { return ""; };
|
||||
return read.kind == paint_kind::url ? read.url : "";
|
||||
}
|
||||
|
||||
# Whether two words are the same but for the case of their letters.
|
||||
def same_letters(a: strview, b: strview): bool {
|
||||
if a.length != b.length {
|
||||
return false;
|
||||
}
|
||||
for index in 0..a.length {
|
||||
if a[index].to_lower != b[index].to_lower {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
#! Contains painters, which give the color each pixel is painted: a color, or a
|
||||
#! gradient's, from a table of 256 of them, premultiplied, along it, as far
|
||||
#! along it as the pixel is, spread past its ends.
|
||||
|
||||
import std::math;
|
||||
module image::svg;
|
||||
|
||||
|
||||
# What paints: a color, or a gradient, whose colors a table of 256 holds,
|
||||
# premultiplied, along it.
|
||||
enum paint_by: u8 {
|
||||
color,
|
||||
linear,
|
||||
radial,
|
||||
}
|
||||
|
||||
enum spread: u8 {
|
||||
pad,
|
||||
reflect,
|
||||
repeat,
|
||||
}
|
||||
|
||||
struct painter {
|
||||
var by: paint_by;
|
||||
var color: f32[4]; #! Premultiplied, already scaled by the opacity.
|
||||
var table: f32[1024]; #! A gradient's colors, premultiplied, already scaled by the opacity.
|
||||
var inverse: matrix; #! From the canvas to the gradient's own space.
|
||||
var spread: spread;
|
||||
var x1: f64; #! A linear gradient's ends, or a radial one's center and focus.
|
||||
var y1: f64;
|
||||
var x2: f64;
|
||||
var y2: f64;
|
||||
var r: f64;
|
||||
}
|
||||
|
||||
def painter::solid(paint: &color, opacity: f64): painter {
|
||||
val alpha := (paint.a * opacity) as f32;
|
||||
return painter { color = [paint.r as f32 * alpha, paint.g as f32 * alpha, paint.b as f32 * alpha, alpha] };
|
||||
}
|
||||
|
||||
# The premultiplied color at the center of a pixel.
|
||||
def painter::at(&this, x: u64, y: u64): f32[4] {
|
||||
if this.by == paint_by::color {
|
||||
return this.color;
|
||||
}
|
||||
val here := this.inverse.apply(point { x = x as f64 + 0.5, y = y as f64 + 0.5 });
|
||||
var t: f64 = 0;
|
||||
if this.by == paint_by::linear {
|
||||
val dx := this.x2 - this.x1;
|
||||
val dy := this.y2 - this.y1;
|
||||
val length := dx * dx + dy * dy;
|
||||
t = length == 0 ? 1 : ((here.x - this.x1) * dx + (here.y - this.y1) * dy) / length;
|
||||
} else {
|
||||
# Along the line from the focus through the pixel, as far as the circle is.
|
||||
val dx := here.x - this.x2;
|
||||
val dy := here.y - this.y2;
|
||||
val ex := this.x2 - this.x1;
|
||||
val ey := this.y2 - this.y1;
|
||||
val a := dx * dx + dy * dy;
|
||||
if a == 0 {
|
||||
t = 0;
|
||||
} else {
|
||||
val b := ex * dx + ey * dy;
|
||||
val c := ex * ex + ey * ey - this.r * this.r;
|
||||
val reach := (-b + math::sqrt(math::max(0.0, b * b - a * c))) / a;
|
||||
t = reach <= 0 ? 1 : 1 / reach;
|
||||
}
|
||||
}
|
||||
if this.spread == spread::repeat {
|
||||
t = t - math::floor(t);
|
||||
} else if this.spread == spread::reflect {
|
||||
t = t % 2;
|
||||
t = t < 0 ? t + 2 : t;
|
||||
t = t > 1 ? 2 - t : t;
|
||||
}
|
||||
t = t < 0 ? 0 : (t > 1 ? 1 : t);
|
||||
val slot := (t * 255 + 0.5) as u64 * 4;
|
||||
return [this.table[slot], this.table[slot + 1], this.table[slot + 2], this.table[slot + 3]];
|
||||
}
|
||||
@@ -0,0 +1,199 @@
|
||||
#! Contains paths: subpaths of lines and cubic curves, quadratics and arcs made
|
||||
#! cubics, and the rectangles and ellipses SVG's shapes are made of.
|
||||
|
||||
import std::math;
|
||||
module image::svg;
|
||||
|
||||
|
||||
# What a path is made of: moves to begin each subpath, lines, cubic curves, each
|
||||
# with its points after it, and closes.
|
||||
enum verb: u8 {
|
||||
move,
|
||||
line,
|
||||
cubic,
|
||||
close,
|
||||
}
|
||||
|
||||
# A path: subpaths of lines and cubic curves, quadratics and arcs made cubics.
|
||||
struct path {
|
||||
var verbs: vector<verb>;
|
||||
var points: vector<point>;
|
||||
var start: point; #! Where the subpath being made began.
|
||||
var last: point; #! Where the path is.
|
||||
var open: bool; #! Whether a subpath has begun, which a line or curve needs.
|
||||
}
|
||||
|
||||
def path::new(): path {
|
||||
return path { verbs = vector::<verb>::new(), points = vector::<point>::new() };
|
||||
}
|
||||
|
||||
def path::move_to(&mut this, to: point): void {
|
||||
this.verbs.append(verb::move);
|
||||
this.points.append(to);
|
||||
this.start = to;
|
||||
this.last = to;
|
||||
this.open = true;
|
||||
}
|
||||
|
||||
def path::line_to(&mut this, to: point): void {
|
||||
this.begin();
|
||||
this.verbs.append(verb::line);
|
||||
this.points.append(to);
|
||||
this.last = to;
|
||||
}
|
||||
|
||||
def path::cubic_to(&mut this, first: point, second: point, to: point): void {
|
||||
this.begin();
|
||||
this.verbs.append(verb::cubic);
|
||||
this.points.append(first);
|
||||
this.points.append(second);
|
||||
this.points.append(to);
|
||||
this.last = to;
|
||||
}
|
||||
|
||||
def path::quad_to(&mut this, control: point, to: point): void {
|
||||
val from := this.last;
|
||||
this.cubic_to(
|
||||
point { x = from.x + (control.x - from.x) * 2 / 3, y = from.y + (control.y - from.y) * 2 / 3 },
|
||||
point { x = to.x + (control.x - to.x) * 2 / 3, y = to.y + (control.y - to.y) * 2 / 3 },
|
||||
to
|
||||
);
|
||||
}
|
||||
|
||||
def path::close(&mut this): void {
|
||||
if this.open {
|
||||
this.verbs.append(verb::close);
|
||||
this.last = this.start;
|
||||
this.open = false;
|
||||
}
|
||||
}
|
||||
|
||||
# Begins a subpath where the path is, after a close, which a line or curve needs.
|
||||
def path::begin(&mut this): void {
|
||||
if !this.open {
|
||||
this.move_to(this.last);
|
||||
}
|
||||
}
|
||||
|
||||
def path::is_empty(&this): bool {
|
||||
return this.verbs.is_empty;
|
||||
}
|
||||
|
||||
# Appends an elliptical arc to a point, as SVG's `A` gives it: radii, the
|
||||
# ellipse's rotation, and which of the four arcs, made cubics of at most a
|
||||
# quarter turn each, as SVG's implementation notes say.
|
||||
def path::arc_to(&mut this, radius_x: f64, radius_y: f64, degrees: f64, large: bool, sweep: bool, to: point): void {
|
||||
val from := this.last;
|
||||
if from.x == to.x && from.y == to.y {
|
||||
return;
|
||||
}
|
||||
var rx := math::abs(radius_x);
|
||||
var ry := math::abs(radius_y);
|
||||
if rx == 0 || ry == 0 {
|
||||
this.line_to(to);
|
||||
return;
|
||||
}
|
||||
|
||||
val angle := degrees * math::pi / 180;
|
||||
val cos := math::cos(angle);
|
||||
val sin := math::sin(angle);
|
||||
val half_x := (from.x - to.x) / 2;
|
||||
val half_y := (from.y - to.y) / 2;
|
||||
val x1 := cos * half_x + sin * half_y;
|
||||
val y1 := -sin * half_x + cos * half_y;
|
||||
|
||||
# Radii too small to reach are made just large enough.
|
||||
val reach := (x1 * x1) / (rx * rx) + (y1 * y1) / (ry * ry);
|
||||
if reach > 1 {
|
||||
rx *= math::sqrt(reach);
|
||||
ry *= math::sqrt(reach);
|
||||
}
|
||||
val numerator := rx * rx * ry * ry - rx * rx * y1 * y1 - ry * ry * x1 * x1;
|
||||
val denominator := rx * rx * y1 * y1 + ry * ry * x1 * x1;
|
||||
var scale := denominator == 0 ? 0.0 : math::sqrt(math::max(0.0, numerator / denominator));
|
||||
if large == sweep {
|
||||
scale = -scale;
|
||||
}
|
||||
val center_x1 := scale * rx * y1 / ry;
|
||||
val center_y1 := -scale * ry * x1 / rx;
|
||||
val center := point {
|
||||
x = cos * center_x1 - sin * center_y1 + (from.x + to.x) / 2,
|
||||
y = sin * center_x1 + cos * center_y1 + (from.y + to.y) / 2
|
||||
};
|
||||
|
||||
val begin := math::atan2((y1 - center_y1) / ry, (x1 - center_x1) / rx);
|
||||
var turn := math::atan2((-y1 - center_y1) / ry, (-x1 - center_x1) / rx) - begin;
|
||||
if sweep && turn < 0 {
|
||||
turn += 2 * math::pi;
|
||||
} else if !sweep && turn > 0 {
|
||||
turn -= 2 * math::pi;
|
||||
}
|
||||
|
||||
val pieces := math::ceil(math::abs(turn) / (math::pi / 2) - 1e-9);
|
||||
val count := pieces < 1 ? 1u : pieces as u64;
|
||||
val step := turn / count as f64;
|
||||
val handle := 4.0 / 3.0 * math::tan(step / 4);
|
||||
for index in 0..count {
|
||||
val t1 := begin + step * index as f64;
|
||||
val t2 := t1 + step;
|
||||
val c1 := math::cos(t1);
|
||||
val s1 := math::sin(t1);
|
||||
val c2 := math::cos(t2);
|
||||
val s2 := math::sin(t2);
|
||||
var end := on_ellipse(¢er, rx, ry, cos, sin, c2, s2);
|
||||
if index == count - 1 {
|
||||
end = to;
|
||||
}
|
||||
this.cubic_to(
|
||||
on_ellipse(¢er, rx, ry, cos, sin, c1 - handle * s1, s1 + handle * c1),
|
||||
on_ellipse(¢er, rx, ry, cos, sin, c2 + handle * s2, s2 - handle * c2),
|
||||
end
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
# A point of the unit circle's plane, put on a rotated ellipse.
|
||||
def on_ellipse(center: &point, rx: f64, ry: f64, cos: f64, sin: f64, x: f64, y: f64): point {
|
||||
return point { x = center.x + rx * cos * x - ry * sin * y, y = center.y + rx * sin * x + ry * cos * y };
|
||||
}
|
||||
|
||||
# The handles of a cubic making a quarter of a circle, for a radius of 1.
|
||||
const kappa: f64 = 0.5522847498307936;
|
||||
|
||||
# Appends an ellipse, clockwise from its right.
|
||||
def path::ellipse(&mut this, cx: f64, cy: f64, rx: f64, ry: f64): void {
|
||||
val kx := rx * kappa;
|
||||
val ky := ry * kappa;
|
||||
this.move_to(point { x = cx + rx, y = cy });
|
||||
this.cubic_to(point { x = cx + rx, y = cy + ky }, point { x = cx + kx, y = cy + ry }, point { x = cx, y = cy + ry });
|
||||
this.cubic_to(point { x = cx - kx, y = cy + ry }, point { x = cx - rx, y = cy + ky }, point { x = cx - rx, y = cy });
|
||||
this.cubic_to(point { x = cx - rx, y = cy - ky }, point { x = cx - kx, y = cy - ry }, point { x = cx, y = cy - ry });
|
||||
this.cubic_to(point { x = cx + kx, y = cy - ry }, point { x = cx + rx, y = cy - ky }, point { x = cx + rx, y = cy });
|
||||
this.close();
|
||||
}
|
||||
|
||||
# Appends a rectangle, its corners rounded by radii, as SVG's `rect` is.
|
||||
def path::rectangle(&mut this, x: f64, y: f64, width: f64, height: f64, rx: f64, ry: f64): void {
|
||||
if rx <= 0 || ry <= 0 {
|
||||
this.move_to(point { x = x, y = y });
|
||||
this.line_to(point { x = x + width, y = y });
|
||||
this.line_to(point { x = x + width, y = y + height });
|
||||
this.line_to(point { x = x, y = y + height });
|
||||
this.close();
|
||||
return;
|
||||
}
|
||||
val kx := rx * kappa;
|
||||
val ky := ry * kappa;
|
||||
val right := x + width;
|
||||
val bottom := y + height;
|
||||
this.move_to(point { x = x + rx, y = y });
|
||||
this.line_to(point { x = right - rx, y = y });
|
||||
this.cubic_to(point { x = right - rx + kx, y = y }, point { x = right, y = y + ry - ky }, point { x = right, y = y + ry });
|
||||
this.line_to(point { x = right, y = bottom - ry });
|
||||
this.cubic_to(point { x = right, y = bottom - ry + ky }, point { x = right - rx + kx, y = bottom }, point { x = right - rx, y = bottom });
|
||||
this.line_to(point { x = x + rx, y = bottom });
|
||||
this.cubic_to(point { x = x + rx - kx, y = bottom }, point { x = x, y = bottom - ry + ky }, point { x = x, y = bottom - ry });
|
||||
this.line_to(point { x = x, y = y + ry });
|
||||
this.cubic_to(point { x = x, y = y + ry - ky }, point { x = x + rx - kx, y = y }, point { x = x + rx, y = y });
|
||||
this.close();
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
#! Contains SVG's path data, as a `path` element's `d` writes it, read into a
|
||||
#! path.
|
||||
|
||||
module image::svg;
|
||||
|
||||
|
||||
# Reads SVG's path data into a path, as far as it's written correctly, as SVG
|
||||
# says to draw a path broken partway.
|
||||
def parse_path(text: strview): path {
|
||||
var made := path::new();
|
||||
var read := numbers::of(text);
|
||||
var command: u8 = 0;
|
||||
var control := point {}; # The last curve's second control point, which `S` and `T` reflect.
|
||||
var curved: u8 = 0; # Whether the last command was a cubic, `C`, or a quadratic, `Q`.
|
||||
while !read.at_end() {
|
||||
val byte := read.text[read.at];
|
||||
if byte.is_alpha {
|
||||
command = byte;
|
||||
read.at++;
|
||||
if command == 'Z' || command == 'z' {
|
||||
made.close();
|
||||
curved = 0;
|
||||
continue;
|
||||
}
|
||||
} else if command == 0 {
|
||||
break;
|
||||
}
|
||||
|
||||
val relative := command >= 'a';
|
||||
val origin := relative ? made.last : point {};
|
||||
val upper := command.to_upper;
|
||||
var next_curved: u8 = 0;
|
||||
if upper == 'M' {
|
||||
val to := read.point() else { break; };
|
||||
made.move_to(offset(to, &origin));
|
||||
# Pairs after a move's first are lines.
|
||||
command = relative ? 'l' : 'L';
|
||||
} else if upper == 'L' {
|
||||
val to := read.point() else { break; };
|
||||
made.line_to(offset(to, &origin));
|
||||
} else if upper == 'H' {
|
||||
val x := read.next() else { break; };
|
||||
made.line_to(point { x = relative ? made.last.x + x : x, y = made.last.y });
|
||||
} else if upper == 'V' {
|
||||
val y := read.next() else { break; };
|
||||
made.line_to(point { x = made.last.x, y = relative ? made.last.y + y : y });
|
||||
} else if upper == 'C' || upper == 'S' {
|
||||
var first := made.last;
|
||||
if upper == 'C' {
|
||||
val given := read.point() else { break; };
|
||||
first = offset(given, &origin);
|
||||
} else if curved == 'C' {
|
||||
first = point { x = 2 * made.last.x - control.x, y = 2 * made.last.y - control.y };
|
||||
}
|
||||
val second := read.point() else { break; };
|
||||
val to := read.point() else { break; };
|
||||
control = offset(second, &origin);
|
||||
made.cubic_to(first, control, offset(to, &origin));
|
||||
next_curved = 'C';
|
||||
} else if upper == 'Q' || upper == 'T' {
|
||||
var middle := made.last;
|
||||
if upper == 'Q' {
|
||||
val given := read.point() else { break; };
|
||||
middle = offset(given, &origin);
|
||||
} else if curved == 'Q' {
|
||||
middle = point { x = 2 * made.last.x - control.x, y = 2 * made.last.y - control.y };
|
||||
}
|
||||
val to := read.point() else { break; };
|
||||
control = middle;
|
||||
made.quad_to(middle, offset(to, &origin));
|
||||
next_curved = 'Q';
|
||||
} else if upper == 'A' {
|
||||
val rx := read.next() else { break; };
|
||||
val ry := read.next() else { break; };
|
||||
val degrees := read.next() else { break; };
|
||||
val large := read.flag() else { break; };
|
||||
val sweep := read.flag() else { break; };
|
||||
val to := read.point() else { break; };
|
||||
made.arc_to(rx, ry, degrees, large, sweep, offset(to, &origin));
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
curved = next_curved;
|
||||
}
|
||||
return made;
|
||||
}
|
||||
|
||||
def offset(at: point, by: &point): point {
|
||||
return point { x = at.x + by.x, y = at.y + by.y };
|
||||
}
|
||||
@@ -0,0 +1,200 @@
|
||||
#! Contains the rasterizer, which fills polygons, by either rule, with sixteen
|
||||
#! rows of samples down each pixel and each span's coverage across it worked
|
||||
#! out exactly, painting each pixel by how much it's covered.
|
||||
|
||||
import std::math;
|
||||
module image::svg;
|
||||
|
||||
|
||||
# How many rows of samples each row of pixels is covered by.
|
||||
const samples: u64 = 16;
|
||||
|
||||
# An edge of a polygon, from its top to its bottom, and which way it went.
|
||||
struct edge {
|
||||
var x0: f64;
|
||||
var y0: f64;
|
||||
var y1: f64;
|
||||
var slope: f64; #! How far across it goes each row down.
|
||||
var winding: i32;
|
||||
}
|
||||
|
||||
struct crossing {
|
||||
var x: f64;
|
||||
var winding: i32;
|
||||
}
|
||||
|
||||
# What the rasterizer keeps between polygons, so it allocates little.
|
||||
struct raster {
|
||||
var width: u64;
|
||||
var height: u64;
|
||||
var edges: vector<edge>;
|
||||
var active: vector<u64>;
|
||||
var crossings: vector<crossing>;
|
||||
var cover: vector<f32>; #! How much more each pixel is covered than the one before, by spans across it.
|
||||
var area: vector<f32>; #! How much of each pixel spans end within.
|
||||
}
|
||||
|
||||
def raster::new(width: u64, height: u64): raster {
|
||||
var made := raster {
|
||||
width = width, height = height,
|
||||
edges = vector::<edge>::new(), active = vector::<u64>::new(), crossings = vector::<crossing>::new(),
|
||||
cover = vector::<f32>::new(), area = vector::<f32>::new()
|
||||
};
|
||||
made.cover.resize(width + 2);
|
||||
made.area.resize(width + 2);
|
||||
return made;
|
||||
}
|
||||
|
||||
# Fills the polygons of an outline, each contour closed, by the nonzero rule or
|
||||
# the even-odd one, painting each pixel by how much it covers.
|
||||
def raster::fill(&mut this, shape: &outline, even_odd: bool, paint: &painter, target: slice<u8>): void {
|
||||
this.edges.clear();
|
||||
var top := math::infinity::<f64>();
|
||||
var bottom := -math::infinity::<f64>();
|
||||
for held in shape.contours {
|
||||
if held.count < 2 {
|
||||
continue;
|
||||
}
|
||||
for index in 0..held.count {
|
||||
val a := shape.points[held.start + index];
|
||||
val b := shape.points[held.start + (index + 1) % held.count];
|
||||
if a.y == b.y || !math::is_finite(a.x) || !math::is_finite(a.y) || !math::is_finite(b.x) || !math::is_finite(b.y) {
|
||||
continue;
|
||||
}
|
||||
val down := a.y < b.y;
|
||||
val upper := down ? a : b;
|
||||
val lower := down ? b : a;
|
||||
this.edges.append(edge {
|
||||
x0 = upper.x, y0 = upper.y, y1 = lower.y,
|
||||
slope = (lower.x - upper.x) / (lower.y - upper.y),
|
||||
winding = down ? 1 : -1
|
||||
});
|
||||
top = upper.y < top ? upper.y : top;
|
||||
bottom = lower.y > bottom ? lower.y : bottom;
|
||||
}
|
||||
}
|
||||
if this.edges.is_empty || bottom <= 0 || top >= this.height as f64 {
|
||||
return;
|
||||
}
|
||||
this.edges.sort_by(def(a: &edge, b: &edge): bool => a.y0 < b.y0);
|
||||
|
||||
val first_row: u64 = top <= 0 ? 0 : math::floor(top) as u64;
|
||||
val end_row: u64 = bottom >= this.height as f64 ? this.height : math::ceil(bottom) as u64;
|
||||
val weight: f32 = 1.0 / samples as f32;
|
||||
var next: u64 = 0;
|
||||
this.active.clear();
|
||||
for row in first_row..end_row {
|
||||
# Edges begin above the row's bottom, and end below its top.
|
||||
while next < this.edges.length && this.edges[next].y0 < (row + 1) as f64 {
|
||||
this.active.append(next);
|
||||
next++;
|
||||
}
|
||||
var kept: u64 = 0;
|
||||
for index in 0..this.active.length {
|
||||
val which := this.active[index];
|
||||
if this.edges[which].y1 > row as f64 {
|
||||
this.active[kept] = which;
|
||||
kept++;
|
||||
}
|
||||
}
|
||||
this.active.resize(kept);
|
||||
|
||||
var left := this.width;
|
||||
var right: u64 = 0;
|
||||
for sample in 0..samples {
|
||||
val y := row as f64 + (sample as f64 + 0.5) / samples as f64;
|
||||
this.crossings.clear();
|
||||
for index in 0..this.active.length {
|
||||
val held := &this.edges[this.active[index]];
|
||||
if held.y0 <= y && y < held.y1 {
|
||||
this.crossings.append(crossing { x = held.x0 + (y - held.y0) * held.slope, winding = held.winding });
|
||||
}
|
||||
}
|
||||
if this.crossings.length < 2 {
|
||||
continue;
|
||||
}
|
||||
# Few cross a row, so they're ordered by insertion.
|
||||
for index in 1..this.crossings.length {
|
||||
var back := index;
|
||||
while back > 0 && this.crossings[back].x < this.crossings[back - 1].x {
|
||||
val swap := this.crossings[back];
|
||||
this.crossings[back] = this.crossings[back - 1];
|
||||
this.crossings[back - 1] = swap;
|
||||
back--;
|
||||
}
|
||||
}
|
||||
var winding: i32 = 0;
|
||||
for index in 0..this.crossings.length - 1 {
|
||||
winding += this.crossings[index].winding;
|
||||
val inside := even_odd ? (winding & 1) != 0 : winding != 0;
|
||||
if inside {
|
||||
val span := this.span(this.crossings[index].x, this.crossings[index + 1].x, weight);
|
||||
left = span[0] < left ? span[0] : left;
|
||||
right = span[1] > right ? span[1] : right;
|
||||
}
|
||||
}
|
||||
}
|
||||
if left <= right && left < this.width {
|
||||
this.paint_row(row, left, right, paint, target);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
# Covers a span of a row of samples, from one place across it to another.
|
||||
# @returns The first and last pixels it touches.
|
||||
def raster::span(&mut this, from: f64, to: f64, weight: f32): u64[2] {
|
||||
val width := this.width as f64;
|
||||
val start := from < 0 ? 0.0 : from;
|
||||
val end := to > width ? width : to;
|
||||
if end <= start {
|
||||
return [this.width, 0];
|
||||
}
|
||||
val first := start as u64;
|
||||
val last := end as u64;
|
||||
if first == last {
|
||||
this.area[first] += (end - start) as f32 * weight;
|
||||
return [first, last];
|
||||
}
|
||||
this.area[first] += (first as f64 + 1 - start) as f32 * weight;
|
||||
this.cover[first + 1] += weight;
|
||||
this.cover[last] -= weight;
|
||||
if last < this.width {
|
||||
this.area[last] += (end - last as f64) as f32 * weight;
|
||||
}
|
||||
return [first, last];
|
||||
}
|
||||
|
||||
# Paints a row's pixels by how much they're covered, and clears its coverage.
|
||||
def raster::paint_row(&mut this, row: u64, left: u64, right: u64, paint: &painter, target: slice<u8>): void {
|
||||
var running: f32 = 0;
|
||||
val last := right < this.width ? right : this.width - 1;
|
||||
for x in left..=last {
|
||||
running += this.cover[x];
|
||||
var covered := running + this.area[x];
|
||||
this.cover[x] = 0;
|
||||
this.area[x] = 0;
|
||||
if covered > 0.001 {
|
||||
covered = covered > 1 ? 1 : covered;
|
||||
blend(target, (row * this.width + x) * 4, paint.at(x, row), covered);
|
||||
}
|
||||
}
|
||||
for x in (last + 1)..(right + 2) {
|
||||
if x < this.cover.length {
|
||||
this.cover[x] = 0;
|
||||
this.area[x] = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
# Draws a premultiplied color over a pixel, as much as covers it.
|
||||
def blend(target: slice<u8>, at: u64, color: f32[4], covered: f32): void {
|
||||
val alpha := color[3] * covered;
|
||||
if alpha <= 0 {
|
||||
return;
|
||||
}
|
||||
val keep := 1 - alpha;
|
||||
for channel in 0u..4u {
|
||||
val value := color[channel] * covered * 255 + target[at + channel] as f32 * keep;
|
||||
target[at + channel] = (value + 0.5) as u8;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
#! Contains SVG's shapes: the path of each kind of shape element, and a shape
|
||||
#! drawn, filled and then stroked.
|
||||
|
||||
import std::math;
|
||||
import std::xml;
|
||||
module image::svg;
|
||||
|
||||
|
||||
# Draws a shape: its fill, then its stroke.
|
||||
# @returns Its bounds in its user space, which gradients, clips, and masks may
|
||||
# be measured by.
|
||||
def renderer::shape(&mut this, at: &xml::element, own: &style, placed: &matrix, opacity: f64): maybe<point[2]> {
|
||||
val geometry := this.geometry_of(at);
|
||||
if geometry.is_empty() {
|
||||
return nothing {};
|
||||
}
|
||||
val stretch := placed.stretch();
|
||||
if stretch <= 0 || !math::is_finite(stretch) {
|
||||
return nothing {};
|
||||
}
|
||||
val user := flatten(&geometry, &matrix {}, tolerance / stretch);
|
||||
val bounds := user.bounds();
|
||||
if !own.visible {
|
||||
return bounds;
|
||||
}
|
||||
|
||||
if this.clipping {
|
||||
this.canvas.fill(&user.transformed(placed), own.clip_even_odd, &painter::solid(&color { r = 1, g = 1, b = 1 }, 1));
|
||||
return bounds;
|
||||
}
|
||||
if this.painter_for(&own.fill, own, own.fill_opacity * opacity, &bounds, placed) is some(fill) {
|
||||
this.canvas.fill(&user.transformed(placed), own.even_odd, &fill);
|
||||
}
|
||||
if own.stroke_width > 0 {
|
||||
if this.painter_for(&own.stroke, own, own.stroke_opacity * opacity, &bounds, placed) is some(stroke_paint) {
|
||||
val with := pen {
|
||||
half = own.stroke_width / 2,
|
||||
cap = own.cap,
|
||||
join = own.join,
|
||||
miter_limit = own.miter_limit,
|
||||
dashes = own.dashes,
|
||||
dash_count = own.dash_count,
|
||||
dash_offset = own.dash_offset,
|
||||
within = tolerance / stretch
|
||||
};
|
||||
val outlined := stroke(&user, &with);
|
||||
this.canvas.fill(&outlined.transformed(placed), false, &stroke_paint);
|
||||
}
|
||||
}
|
||||
return bounds;
|
||||
}
|
||||
|
||||
# The path of a shape element, in its user space, or an empty one where it has
|
||||
# no area or length, as a rectangle of no width hasn't.
|
||||
def renderer::geometry_of(&this, at: &xml::element): path {
|
||||
var made := path::new();
|
||||
val name := at.local;
|
||||
if name == "path" {
|
||||
val data := at.attribute("d") else { return made; };
|
||||
return parse_path(data);
|
||||
}
|
||||
if name == "rect" {
|
||||
val x := this.length_of(at, "x", axis::x, 0);
|
||||
val y := this.length_of(at, "y", axis::y, 0);
|
||||
val width := this.length_of(at, "width", axis::x, 0);
|
||||
val height := this.length_of(at, "height", axis::y, 0);
|
||||
if width <= 0 || height <= 0 {
|
||||
return made;
|
||||
}
|
||||
var rx := this.length_of(at, "rx", axis::x, -1);
|
||||
var ry := this.length_of(at, "ry", axis::y, -1);
|
||||
if rx < 0 {
|
||||
rx = ry;
|
||||
}
|
||||
if ry < 0 {
|
||||
ry = rx;
|
||||
}
|
||||
rx = math::min(math::max(rx, 0.0), width / 2);
|
||||
ry = math::min(math::max(ry, 0.0), height / 2);
|
||||
made.rectangle(x, y, width, height, rx, ry);
|
||||
} else if name == "circle" {
|
||||
val r := this.length_of(at, "r", axis::diagonal, 0);
|
||||
if r > 0 {
|
||||
made.ellipse(this.length_of(at, "cx", axis::x, 0), this.length_of(at, "cy", axis::y, 0), r, r);
|
||||
}
|
||||
} else if name == "ellipse" {
|
||||
var rx := this.length_of(at, "rx", axis::x, -1);
|
||||
var ry := this.length_of(at, "ry", axis::y, -1);
|
||||
rx = rx < 0 ? ry : rx;
|
||||
ry = ry < 0 ? rx : ry;
|
||||
if rx > 0 && ry > 0 {
|
||||
made.ellipse(this.length_of(at, "cx", axis::x, 0), this.length_of(at, "cy", axis::y, 0), rx, ry);
|
||||
}
|
||||
} else if name == "line" {
|
||||
made.move_to(point { x = this.length_of(at, "x1", axis::x, 0), y = this.length_of(at, "y1", axis::y, 0) });
|
||||
made.line_to(point { x = this.length_of(at, "x2", axis::x, 0), y = this.length_of(at, "y2", axis::y, 0) });
|
||||
} else if name == "polyline" || name == "polygon" {
|
||||
val written := at.attribute("points") else { return made; };
|
||||
var read := numbers::of(written);
|
||||
var first := true;
|
||||
while true {
|
||||
val at_point := read.point() else { break; };
|
||||
if first {
|
||||
made.move_to(at_point);
|
||||
first = false;
|
||||
} else {
|
||||
made.line_to(at_point);
|
||||
}
|
||||
}
|
||||
if name == "polygon" && !first {
|
||||
made.close();
|
||||
}
|
||||
}
|
||||
return made;
|
||||
}
|
||||
@@ -0,0 +1,276 @@
|
||||
#! Contains the rules of an SVG's `<style>` sheets: each selector of types,
|
||||
#! classes, and IDs, and descendant and child combinators, read with how
|
||||
#! specific it is, and those matching an element applied the least specific
|
||||
#! first.
|
||||
|
||||
import std::xml;
|
||||
module image::svg;
|
||||
|
||||
|
||||
# How a selector's compound relates to the one before it.
|
||||
enum combinator: u8 {
|
||||
none, #! It's the first.
|
||||
descendant, #! Within it, however deep, as a space says.
|
||||
child, #! Within it directly, as `>` says.
|
||||
}
|
||||
|
||||
# A compound selector: a type, an ID, and classes, each of which may be left out.
|
||||
struct compound {
|
||||
var tag: strview; #! Empty, or `*`, for any.
|
||||
var id: strview;
|
||||
var classes: strview; #! As written, as `.a.b`.
|
||||
var combinator: combinator;
|
||||
}
|
||||
|
||||
# A rule of a style sheet: one of its selectors, how specific it is, where it
|
||||
# stands, and its declarations.
|
||||
struct rule {
|
||||
var first: u64; #! Its compounds, in the sheet's.
|
||||
var count: u64;
|
||||
var specificity: u64;
|
||||
var order: u64;
|
||||
var body: strview;
|
||||
}
|
||||
|
||||
# The rules of an SVG's `<style>` sheets.
|
||||
struct sheet {
|
||||
var texts: vector<string>; #! Each sheet's text, without its comments, which the rules view.
|
||||
var compounds: vector<compound>;
|
||||
var rules: vector<rule>;
|
||||
}
|
||||
|
||||
def sheet::new(): sheet {
|
||||
return sheet { texts = vector::<string>::new(), compounds = vector::<compound>::new(), rules = vector::<rule>::new() };
|
||||
}
|
||||
|
||||
# Reads a style sheet's rules, skipping at-rules, and selectors of what isn't
|
||||
# matched: attributes, pseudo-classes, and siblings.
|
||||
def sheet::add(&mut this, written: strview): void {
|
||||
# Comments are taken out first.
|
||||
var text := string::new(nothing {});
|
||||
var at: u64 = 0;
|
||||
while at < written.length {
|
||||
if written.substr(at, 2) == "/*" {
|
||||
val end := written.substr(at + 2, written.length - at - 2).find("*/") else { break; };
|
||||
at += end + 4;
|
||||
text.push(' ');
|
||||
continue;
|
||||
}
|
||||
text.push(written[at]);
|
||||
at++;
|
||||
}
|
||||
this.texts.append(move(text));
|
||||
val source := this.texts.last().view();
|
||||
|
||||
at = 0;
|
||||
while at < source.length {
|
||||
while at < source.length && source[at].is_space {
|
||||
at++;
|
||||
}
|
||||
if at >= source.length {
|
||||
break;
|
||||
}
|
||||
val open := source.substr(at, source.length - at).find("{") else { break; };
|
||||
val prelude := source.substr(at, open).trim();
|
||||
val body_start := at + open + 1;
|
||||
# The body ends at the brace matching its own, past any within.
|
||||
var end := body_start;
|
||||
var depth := 1;
|
||||
while end < source.length && depth > 0 {
|
||||
if source[end] == '{' {
|
||||
depth++;
|
||||
} else if source[end] == '}' {
|
||||
depth--;
|
||||
}
|
||||
end++;
|
||||
}
|
||||
val body := source.substr(body_start, end - body_start - 1);
|
||||
at = end;
|
||||
if prelude.starts_with("@") {
|
||||
continue;
|
||||
}
|
||||
|
||||
var from: u64 = 0;
|
||||
while from <= prelude.length {
|
||||
val comma := prelude.substr(from, prelude.length - from).find(",") else prelude.length - from;
|
||||
this.add_selector(prelude.substr(from, comma).trim(), body);
|
||||
from += comma + 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
def sheet::add_selector(&mut this, selector: strview, body: strview): void {
|
||||
if selector.length == 0 || selector.find_any("[:+~") is some(_) {
|
||||
return;
|
||||
}
|
||||
val first := this.compounds.length;
|
||||
var specificity: u64 = 0;
|
||||
var next := combinator::none;
|
||||
var at: u64 = 0;
|
||||
while at < selector.length {
|
||||
while at < selector.length && selector[at].is_space {
|
||||
if next == combinator::none && this.compounds.length > first {
|
||||
next = combinator::descendant;
|
||||
}
|
||||
at++;
|
||||
}
|
||||
if at >= selector.length {
|
||||
break;
|
||||
}
|
||||
if selector[at] == '>' {
|
||||
next = combinator::child;
|
||||
at++;
|
||||
continue;
|
||||
}
|
||||
|
||||
# A compound: a type or `*`, then `#id` and `.class` in any order.
|
||||
var made := compound { combinator = this.compounds.length > first ? next : combinator::none };
|
||||
var end := at;
|
||||
while end < selector.length && !selector[end].is_space && selector[end] != '>' {
|
||||
end++;
|
||||
}
|
||||
val written := selector.substr(at, end - at);
|
||||
var part := 0u;
|
||||
while part < written.length && written[part] != '#' && written[part] != '.' {
|
||||
part++;
|
||||
}
|
||||
made.tag = written.substr(0, part);
|
||||
if made.tag.length != 0 && made.tag != "*" {
|
||||
specificity += 1;
|
||||
}
|
||||
var classes_start := part;
|
||||
var classes_end := part;
|
||||
while part < written.length {
|
||||
var stop := part + 1;
|
||||
while stop < written.length && written[stop] != '#' && written[stop] != '.' {
|
||||
stop++;
|
||||
}
|
||||
if written[part] == '#' {
|
||||
made.id = written.substr(part + 1, stop - part - 1);
|
||||
specificity += 10000;
|
||||
} else {
|
||||
if classes_end == classes_start {
|
||||
classes_start = part;
|
||||
}
|
||||
classes_end = stop;
|
||||
specificity += 100;
|
||||
}
|
||||
part = stop;
|
||||
}
|
||||
made.classes = written.substr(classes_start, classes_end - classes_start);
|
||||
this.compounds.append(made);
|
||||
next = combinator::none;
|
||||
at = end;
|
||||
}
|
||||
if this.compounds.length == first {
|
||||
return;
|
||||
}
|
||||
this.rules.append(rule {
|
||||
first = first,
|
||||
count = this.compounds.length - first,
|
||||
specificity = specificity,
|
||||
order = this.rules.length,
|
||||
body = body
|
||||
});
|
||||
}
|
||||
|
||||
# Sets the properties of the rules matching an element, the least specific
|
||||
# first, and of those equally specific, the first written first.
|
||||
def sheet::apply(&this, at: &xml::element, made: &mut style, parent: &style, view: &viewport): void {
|
||||
var matched := vector::<u64>::new();
|
||||
for index in 0..this.rules.length {
|
||||
val held := &this.rules[index];
|
||||
if this.matches(held, held.count - 1, at) {
|
||||
matched.append(index);
|
||||
}
|
||||
}
|
||||
# Few match any element, so they're ordered by insertion.
|
||||
for index in 1..matched.length {
|
||||
var back := index;
|
||||
while back > 0 && this.before(matched[back], matched[back - 1]) {
|
||||
val swap := matched[back];
|
||||
matched[back] = matched[back - 1];
|
||||
matched[back - 1] = swap;
|
||||
back--;
|
||||
}
|
||||
}
|
||||
for index in matched {
|
||||
made.declare(this.rules[index].body, parent, view);
|
||||
}
|
||||
}
|
||||
|
||||
def sheet::before(&this, first: u64, second: u64): bool {
|
||||
val a := &this.rules[first];
|
||||
val b := &this.rules[second];
|
||||
return a.specificity < b.specificity || (a.specificity == b.specificity && a.order < b.order);
|
||||
}
|
||||
|
||||
# Whether an element matches a rule's compounds up to one, from the last back.
|
||||
def sheet::matches(&this, held: &rule, last: u64, at: &xml::element): bool {
|
||||
val part := &this.compounds[held.first + last];
|
||||
if !matches_compound(part, at) {
|
||||
return false;
|
||||
}
|
||||
if last == 0 {
|
||||
return true;
|
||||
}
|
||||
var above := at.parent;
|
||||
if part.combinator == combinator::child {
|
||||
val parent := above else { return false; };
|
||||
return this.matches(held, last - 1, &parent);
|
||||
}
|
||||
while above is some(ancestor) {
|
||||
if this.matches(held, last - 1, &ancestor) {
|
||||
return true;
|
||||
}
|
||||
above = ancestor.parent;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
def matches_compound(part: &compound, at: &xml::element): bool {
|
||||
if part.tag.length != 0 && part.tag != "*" && part.tag != at.local {
|
||||
return false;
|
||||
}
|
||||
if part.id.length != 0 {
|
||||
val id := at.attribute("id") else { return false; };
|
||||
if id != part.id {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
if part.classes.length == 0 {
|
||||
return true;
|
||||
}
|
||||
val classes := at.attribute("class") else { return false; };
|
||||
var from: u64 = 1;
|
||||
while from < part.classes.length {
|
||||
var stop := from;
|
||||
while stop < part.classes.length && part.classes[stop] != '.' {
|
||||
stop++;
|
||||
}
|
||||
if !has_word(classes, part.classes.substr(from, stop - from)) {
|
||||
return false;
|
||||
}
|
||||
from = stop + 1;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
# Whether whitespace-separated words hold one.
|
||||
def has_word(words: strview, word: strview): bool {
|
||||
var at: u64 = 0;
|
||||
while at < words.length {
|
||||
while at < words.length && words[at].is_space {
|
||||
at++;
|
||||
}
|
||||
var end := at;
|
||||
while end < words.length && !words[end].is_space {
|
||||
end++;
|
||||
}
|
||||
if end > at && words.substr(at, end - at) == word {
|
||||
return true;
|
||||
}
|
||||
at = end;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
@@ -0,0 +1,244 @@
|
||||
#! Contains the stroker, which makes a stroke of an outline the polygons it
|
||||
#! covers: a quadrilateral along each line, the joins between them, and the
|
||||
#! caps at the ends of polylines, dashed first.
|
||||
|
||||
import std::math;
|
||||
module image::svg;
|
||||
|
||||
|
||||
# What strokes an outline: half its width, and how its ends, corners, and dashes
|
||||
# are drawn.
|
||||
struct pen {
|
||||
var half: f64;
|
||||
var cap: line_cap;
|
||||
var join: line_join;
|
||||
var miter_limit: f64;
|
||||
var dashes: f64[16];
|
||||
var dash_count: u64;
|
||||
var dash_offset: f64;
|
||||
var within: f64; #! How far round ends and corners may stray from a circle.
|
||||
}
|
||||
|
||||
# The polygons a stroke of an outline covers: a quadrilateral along each line,
|
||||
# the corners between them, and the ends of polylines, dashed first.
|
||||
def stroke(shape: &outline, with: &pen): outline {
|
||||
var made := outline::new();
|
||||
var piece := vector::<point>::new();
|
||||
for held in shape.contours {
|
||||
val points := shape.points.view()[held.start:held.count];
|
||||
if with.dash_count == 0 {
|
||||
stroke_polyline(points, held.closed, with, &mut made);
|
||||
continue;
|
||||
}
|
||||
dash(points, held.closed, with, &mut piece, &mut made);
|
||||
}
|
||||
return made;
|
||||
}
|
||||
|
||||
# Strokes the dashes of a polyline, the pattern begun again at each, at its
|
||||
# offset.
|
||||
def dash(points: span<point>, closed: bool, with: &pen, piece: &mut vector<point>, made: &mut outline): void {
|
||||
var total: f64 = 0;
|
||||
for index in 0..with.dash_count {
|
||||
total += with.dashes[index];
|
||||
}
|
||||
# Where in the pattern the polyline begins.
|
||||
var which: u64 = 0;
|
||||
var offset := with.dash_offset % total;
|
||||
if offset < 0 {
|
||||
offset += total;
|
||||
}
|
||||
while offset >= with.dashes[which] {
|
||||
offset -= with.dashes[which];
|
||||
which = (which + 1) % with.dash_count;
|
||||
}
|
||||
var left := with.dashes[which] - offset;
|
||||
|
||||
piece.clear();
|
||||
if which % 2 == 0 {
|
||||
piece.append(points[0]);
|
||||
}
|
||||
val segments := closed ? points.length : points.length - 1;
|
||||
for index in 0..segments {
|
||||
val a := points[index];
|
||||
val b := points[(index + 1) % points.length];
|
||||
val length := math::hypot(b.x - a.x, b.y - a.y);
|
||||
var along: f64 = 0;
|
||||
while length - along > left {
|
||||
along += left;
|
||||
val at := point { x = a.x + (b.x - a.x) * along / length, y = a.y + (b.y - a.y) * along / length };
|
||||
if which % 2 == 0 {
|
||||
piece.append(at);
|
||||
stroke_polyline(piece.view(), false, with, made);
|
||||
piece.clear();
|
||||
} else {
|
||||
piece.append(at);
|
||||
}
|
||||
which = (which + 1) % with.dash_count;
|
||||
left = with.dashes[which];
|
||||
}
|
||||
left -= length - along;
|
||||
if which % 2 == 0 {
|
||||
piece.append(b);
|
||||
}
|
||||
}
|
||||
if which % 2 == 0 && !piece.is_empty {
|
||||
stroke_polyline(piece.view(), false, with, made);
|
||||
}
|
||||
piece.clear();
|
||||
}
|
||||
|
||||
# Strokes a polyline, or a polygon.
|
||||
def stroke_polyline(given: span<point>, closed_given: bool, with: &pen, made: &mut outline): void {
|
||||
# Points the same as the one before add nothing.
|
||||
var points := vector::<point>::new();
|
||||
for at in given {
|
||||
if points.is_empty || !same_point(at, points.last()) {
|
||||
points.append(at);
|
||||
}
|
||||
}
|
||||
var closed := closed_given;
|
||||
if closed && points.length > 1 && same_point(points[0], points.last()) {
|
||||
points.truncate();
|
||||
}
|
||||
if points.length == 0 {
|
||||
return;
|
||||
}
|
||||
if points.length == 1 {
|
||||
# A path of no length is drawn by its caps alone.
|
||||
if with.cap == line_cap::round {
|
||||
circle(points[0], with.half, with, made);
|
||||
} else if with.cap == line_cap::square {
|
||||
val at := points[0];
|
||||
val h := with.half;
|
||||
made.polygon([point { x = at.x - h, y = at.y - h }, point { x = at.x + h, y = at.y - h },
|
||||
point { x = at.x + h, y = at.y + h }, point { x = at.x - h, y = at.y + h }]);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if points.length == 2 {
|
||||
closed = false;
|
||||
}
|
||||
|
||||
val count := points.length;
|
||||
val segments := closed ? count : count - 1;
|
||||
for index in 0..segments {
|
||||
val a := points[index];
|
||||
val b := points[(index + 1) % count];
|
||||
val across := normal(a, b, with.half);
|
||||
made.polygon([offset(a, &across), offset(b, &across), point { x = b.x - across.x, y = b.y - across.y },
|
||||
point { x = a.x - across.x, y = a.y - across.y }]);
|
||||
}
|
||||
|
||||
val first_corner: u64 = closed ? 0 : 1;
|
||||
val last_corner := closed ? count : count - 1;
|
||||
for index in first_corner..last_corner {
|
||||
val before := points[(index + count - 1) % count];
|
||||
val here := points[index];
|
||||
val after := points[(index + 1) % count];
|
||||
corner(before, here, after, with, made);
|
||||
}
|
||||
if !closed {
|
||||
end_cap(points[1], points[0], with, made);
|
||||
end_cap(points[count - 2], points[count - 1], with, made);
|
||||
}
|
||||
}
|
||||
|
||||
# The corner where a line from one point to another turns to a third: a miter,
|
||||
# where it's no longer than the limit, a bevel, or a round, on its outer side.
|
||||
def corner(before: point, here: point, after: point, with: &pen, made: &mut outline): void {
|
||||
val in_length := math::hypot(here.x - before.x, here.y - before.y);
|
||||
val out_length := math::hypot(after.x - here.x, after.y - here.y);
|
||||
val in_x := (here.x - before.x) / in_length;
|
||||
val in_y := (here.y - before.y) / in_length;
|
||||
val out_x := (after.x - here.x) / out_length;
|
||||
val out_y := (after.y - here.y) / out_length;
|
||||
val cross := in_x * out_y - in_y * out_x;
|
||||
val dot := in_x * out_x + in_y * out_y;
|
||||
if math::abs(cross) < 1e-12 && dot > 0 {
|
||||
return;
|
||||
}
|
||||
|
||||
# The outer side is the one the line turns from.
|
||||
val side := cross > 0 ? -with.half : with.half;
|
||||
val first := point { x = -in_y * side, y = in_x * side };
|
||||
val second := point { x = -out_y * side, y = out_x * side };
|
||||
val a := offset(here, &first);
|
||||
val b := offset(here, &second);
|
||||
if with.join == line_join::round {
|
||||
var fan := vector::<point>::new();
|
||||
fan.append(here);
|
||||
arc(here, first, second, with, &mut fan);
|
||||
made.polygon(fan.view());
|
||||
return;
|
||||
}
|
||||
if with.join == line_join::miter && dot > -0.999999 && 1 / math::sqrt((1 + dot) / 2) <= with.miter_limit {
|
||||
val tip := point { x = here.x + (first.x + second.x) / (1 + dot), y = here.y + (first.y + second.y) / (1 + dot) };
|
||||
made.polygon([here, a, tip, b]);
|
||||
return;
|
||||
}
|
||||
made.polygon([here, a, b]);
|
||||
}
|
||||
|
||||
# The cap at the end of a polyline, from the point before it.
|
||||
def end_cap(before: point, end: point, with: &pen, made: &mut outline): void {
|
||||
if with.cap == line_cap::round {
|
||||
circle(end, with.half, with, made);
|
||||
return;
|
||||
}
|
||||
if with.cap == line_cap::square {
|
||||
val across := normal(before, end, with.half);
|
||||
val ahead := point { x = across.y, y = -across.x };
|
||||
made.polygon([offset(end, &across), point { x = end.x + across.x + ahead.x, y = end.y + across.y + ahead.y },
|
||||
point { x = end.x - across.x + ahead.x, y = end.y - across.y + ahead.y },
|
||||
point { x = end.x - across.x, y = end.y - across.y }]);
|
||||
}
|
||||
}
|
||||
|
||||
# The normal of a line, at a length, to its left as it goes.
|
||||
def normal(from: point, to: point, length: f64): point {
|
||||
val size := math::hypot(to.x - from.x, to.y - from.y);
|
||||
return point { x = -(to.y - from.y) / size * length, y = (to.x - from.x) / size * length };
|
||||
}
|
||||
|
||||
def same_point(a: point, b: point): bool {
|
||||
return math::abs(a.x - b.x) < 1e-9 && math::abs(a.y - b.y) < 1e-9;
|
||||
}
|
||||
|
||||
# How many steps a whole circle of a radius takes to stay within the pen's
|
||||
# distance of it.
|
||||
def circle_steps(radius: f64, with: &pen): f64 {
|
||||
if radius <= with.within {
|
||||
return 8;
|
||||
}
|
||||
val steps := math::ceil(math::pi / math::acos(1 - with.within / radius));
|
||||
return steps < 8 ? 8 : (steps > 360 ? 360 : steps);
|
||||
}
|
||||
|
||||
def circle(center: point, radius: f64, with: &pen, made: &mut outline): void {
|
||||
val steps := circle_steps(radius, with);
|
||||
var round := vector::<point>::new();
|
||||
for step in 0..steps as u64 {
|
||||
val angle := 2 * math::pi * step as f64 / steps;
|
||||
round.append(point { x = center.x + radius * math::cos(angle), y = center.y + radius * math::sin(angle) });
|
||||
}
|
||||
made.polygon(round.view());
|
||||
}
|
||||
|
||||
# Appends the points of the shorter arc from one offset of a center to another.
|
||||
def arc(center: point, from: point, to: point, with: &pen, into: &mut vector<point>): void {
|
||||
val radius := math::hypot(from.x, from.y);
|
||||
val begin := math::atan2(from.y, from.x);
|
||||
var turn := math::atan2(to.y, to.x) - begin;
|
||||
if turn > math::pi {
|
||||
turn -= 2 * math::pi;
|
||||
} else if turn < -math::pi {
|
||||
turn += 2 * math::pi;
|
||||
}
|
||||
var steps := math::ceil(math::abs(turn) / (2 * math::pi) * circle_steps(radius, with));
|
||||
steps = steps < 1 ? 1 : steps;
|
||||
for step in 0..=steps as u64 {
|
||||
val angle := begin + turn * step as f64 / steps;
|
||||
into.append(point { x = center.x + radius * math::cos(angle), y = center.y + radius * math::sin(angle) });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,276 @@
|
||||
#! Contains SVG's styling: the properties each element has, which its
|
||||
#! presentation attributes, the rules of `<style>` sheets, and its `style`
|
||||
#! attribute set, in that order, over what it inherits.
|
||||
|
||||
import std::math;
|
||||
module image::svg;
|
||||
|
||||
|
||||
enum line_cap: u8 {
|
||||
butt,
|
||||
round,
|
||||
square,
|
||||
}
|
||||
|
||||
enum line_join: u8 {
|
||||
miter,
|
||||
round,
|
||||
bevel,
|
||||
}
|
||||
|
||||
# The most dashes a stroke's pattern holds.
|
||||
const most_dashes: u64 = 16;
|
||||
|
||||
# The properties of an element, after its own and what it inherits.
|
||||
struct style {
|
||||
# Those inherited.
|
||||
var fill: paint = paint { kind = paint_kind::color };
|
||||
var fill_opacity: f64 = 1;
|
||||
var even_odd: bool;
|
||||
var stroke: paint;
|
||||
var stroke_opacity: f64 = 1;
|
||||
var stroke_width: f64 = 1;
|
||||
var cap: line_cap;
|
||||
var join: line_join;
|
||||
var miter_limit: f64 = 4;
|
||||
var dashes: f64[16];
|
||||
var dash_count: u64;
|
||||
var dash_offset: f64;
|
||||
var color: color;
|
||||
var visible: bool = true;
|
||||
var clip_even_odd: bool;
|
||||
# Those not.
|
||||
var opacity: f64 = 1;
|
||||
var displayed: bool = true;
|
||||
var clip_path: strview;
|
||||
var mask: strview;
|
||||
var stop_color: color;
|
||||
var stop_opacity: f64 = 1;
|
||||
}
|
||||
|
||||
# The properties an element's presentation attributes may set.
|
||||
const presentation: strview[20] = [
|
||||
"fill", "fill-opacity", "fill-rule", "stroke", "stroke-width", "stroke-opacity", "stroke-linecap",
|
||||
"stroke-linejoin", "stroke-miterlimit", "stroke-dasharray", "stroke-dashoffset", "opacity", "color",
|
||||
"display", "visibility", "clip-path", "clip-rule", "mask", "stop-color", "stop-opacity",
|
||||
];
|
||||
|
||||
# The style a child begins with: what its parent's is that's inherited, and the
|
||||
# rest as it begins.
|
||||
def style::inherited(&this): style {
|
||||
var made := copy(this);
|
||||
made.opacity = 1;
|
||||
made.displayed = true;
|
||||
made.clip_path = "";
|
||||
made.mask = "";
|
||||
made.stop_color = color {};
|
||||
made.stop_opacity = 1;
|
||||
return made;
|
||||
}
|
||||
|
||||
# Sets a property of a style by its name and its value as written, leaving it as
|
||||
# it was where either isn't one known, or the value is wrong, as CSS does.
|
||||
def style::set(&mut this, name: strview, given: strview, parent: &style, view: &viewport): void {
|
||||
val value := given.trim();
|
||||
if value == "inherit" {
|
||||
this.inherit(name, parent);
|
||||
return;
|
||||
}
|
||||
|
||||
if name == "fill" {
|
||||
this.fill = parse_paint(value) else { return; };
|
||||
} else if name == "stroke" {
|
||||
this.stroke = parse_paint(value) else { return; };
|
||||
} else if name == "fill-opacity" || name == "stroke-opacity" || name == "opacity" || name == "stop-opacity" {
|
||||
val read := parse_fraction(value) else { return; };
|
||||
val clamped := math::clamp(read, 0.0, 1.0);
|
||||
if name == "fill-opacity" {
|
||||
this.fill_opacity = clamped;
|
||||
} else if name == "stroke-opacity" {
|
||||
this.stroke_opacity = clamped;
|
||||
} else if name == "opacity" {
|
||||
this.opacity = clamped;
|
||||
} else {
|
||||
this.stop_opacity = clamped;
|
||||
}
|
||||
} else if name == "fill-rule" {
|
||||
if value == "evenodd" || value == "nonzero" {
|
||||
this.even_odd = value == "evenodd";
|
||||
}
|
||||
} else if name == "clip-rule" {
|
||||
if value == "evenodd" || value == "nonzero" {
|
||||
this.clip_even_odd = value == "evenodd";
|
||||
}
|
||||
} else if name == "stroke-width" {
|
||||
val width := parse_length(value, view, axis::diagonal) else { return; };
|
||||
if width >= 0 {
|
||||
this.stroke_width = width;
|
||||
}
|
||||
} else if name == "stroke-linecap" {
|
||||
if value == "butt" {
|
||||
this.cap = line_cap::butt;
|
||||
} else if value == "round" {
|
||||
this.cap = line_cap::round;
|
||||
} else if value == "square" {
|
||||
this.cap = line_cap::square;
|
||||
}
|
||||
} else if name == "stroke-linejoin" {
|
||||
if value == "miter" || value == "miter-clip" || value == "arcs" {
|
||||
this.join = line_join::miter;
|
||||
} else if value == "round" {
|
||||
this.join = line_join::round;
|
||||
} else if value == "bevel" {
|
||||
this.join = line_join::bevel;
|
||||
}
|
||||
} else if name == "stroke-miterlimit" {
|
||||
val limit := parse_fraction(value) else { return; };
|
||||
if limit >= 1 {
|
||||
this.miter_limit = limit;
|
||||
}
|
||||
} else if name == "stroke-dasharray" {
|
||||
this.set_dashes(value, view);
|
||||
} else if name == "stroke-dashoffset" {
|
||||
this.dash_offset = parse_length(value, view, axis::diagonal) else { return; };
|
||||
} else if name == "color" {
|
||||
this.color = parse_color(value) else { return; };
|
||||
} else if name == "stop-color" {
|
||||
if same_letters(value, "currentColor") {
|
||||
this.stop_color = this.color;
|
||||
return;
|
||||
}
|
||||
this.stop_color = parse_color(value) else { return; };
|
||||
} else if name == "display" {
|
||||
this.displayed = value != "none";
|
||||
} else if name == "visibility" {
|
||||
this.visible = value == "visible";
|
||||
} else if name == "clip-path" {
|
||||
this.clip_path = url_of(value);
|
||||
} else if name == "mask" {
|
||||
this.mask = url_of(value);
|
||||
}
|
||||
}
|
||||
|
||||
# Reads a dash pattern, a list repeated where it's odd, which with any length
|
||||
# below zero, or none above it, dashes nothing.
|
||||
def style::set_dashes(&mut this, value: strview, view: &viewport): void {
|
||||
this.dash_count = 0;
|
||||
if value == "none" {
|
||||
return;
|
||||
}
|
||||
var read: f64[16];
|
||||
var count: u64 = 0;
|
||||
var total: f64 = 0;
|
||||
var at: u64 = 0;
|
||||
while at < value.length {
|
||||
while at < value.length && (value[at].is_space || value[at] == ',') {
|
||||
at++;
|
||||
}
|
||||
if at >= value.length {
|
||||
break;
|
||||
}
|
||||
var end := at;
|
||||
while end < value.length && !value[end].is_space && value[end] != ',' {
|
||||
end++;
|
||||
}
|
||||
val length := parse_length(value.substr(at, end - at), view, axis::diagonal) else { return; };
|
||||
if length < 0 || count >= most_dashes / 2 {
|
||||
return;
|
||||
}
|
||||
read[count] = length;
|
||||
total += length;
|
||||
count++;
|
||||
at = end;
|
||||
}
|
||||
if total <= 0 {
|
||||
return;
|
||||
}
|
||||
for index in 0..count {
|
||||
this.dashes[index] = read[index];
|
||||
this.dashes[index + count] = read[index];
|
||||
}
|
||||
this.dash_count = count % 2 == 1 ? count * 2 : count;
|
||||
}
|
||||
|
||||
# Takes a property from the parent's style, as `inherit` says.
|
||||
def style::inherit(&mut this, name: strview, parent: &style): void {
|
||||
if name == "fill" {
|
||||
this.fill = parent.fill;
|
||||
} else if name == "stroke" {
|
||||
this.stroke = parent.stroke;
|
||||
} else if name == "fill-opacity" {
|
||||
this.fill_opacity = parent.fill_opacity;
|
||||
} else if name == "stroke-opacity" {
|
||||
this.stroke_opacity = parent.stroke_opacity;
|
||||
} else if name == "opacity" {
|
||||
this.opacity = parent.opacity;
|
||||
} else if name == "fill-rule" {
|
||||
this.even_odd = parent.even_odd;
|
||||
} else if name == "clip-rule" {
|
||||
this.clip_even_odd = parent.clip_even_odd;
|
||||
} else if name == "stroke-width" {
|
||||
this.stroke_width = parent.stroke_width;
|
||||
} else if name == "stroke-linecap" {
|
||||
this.cap = parent.cap;
|
||||
} else if name == "stroke-linejoin" {
|
||||
this.join = parent.join;
|
||||
} else if name == "stroke-miterlimit" {
|
||||
this.miter_limit = parent.miter_limit;
|
||||
} else if name == "stroke-dasharray" {
|
||||
this.dashes = parent.dashes;
|
||||
this.dash_count = parent.dash_count;
|
||||
} else if name == "stroke-dashoffset" {
|
||||
this.dash_offset = parent.dash_offset;
|
||||
} else if name == "color" {
|
||||
this.color = parent.color;
|
||||
} else if name == "stop-color" {
|
||||
this.stop_color = parent.stop_color;
|
||||
} else if name == "stop-opacity" {
|
||||
this.stop_opacity = parent.stop_opacity;
|
||||
} else if name == "display" {
|
||||
this.displayed = parent.displayed;
|
||||
} else if name == "visibility" {
|
||||
this.visible = parent.visible;
|
||||
} else if name == "clip-path" {
|
||||
this.clip_path = parent.clip_path;
|
||||
} else if name == "mask" {
|
||||
this.mask = parent.mask;
|
||||
}
|
||||
}
|
||||
|
||||
# Sets each property a list of declarations sets, as `name: value;` writes each.
|
||||
def style::declare(&mut this, declarations: strview, parent: &style, view: &viewport): void {
|
||||
var at: u64 = 0;
|
||||
while at < declarations.length {
|
||||
# A declaration ends at a `;` not within parentheses or quotes.
|
||||
var end := at;
|
||||
var depth := 0;
|
||||
var quote: u8 = 0;
|
||||
while end < declarations.length {
|
||||
val byte := declarations[end];
|
||||
if quote != 0 {
|
||||
if byte == quote {
|
||||
quote = 0;
|
||||
}
|
||||
} else if byte == '"' || byte == '\'' {
|
||||
quote = byte;
|
||||
} else if byte == '(' {
|
||||
depth++;
|
||||
} else if byte == ')' {
|
||||
depth--;
|
||||
} else if byte == ';' && depth <= 0 {
|
||||
break;
|
||||
}
|
||||
end++;
|
||||
}
|
||||
val declaration := declarations.substr(at, end - at);
|
||||
at = end + 1;
|
||||
val colon := declaration.find(":") else { continue; };
|
||||
val name := declaration.substr(0, colon).trim();
|
||||
var value := declaration.substr(colon + 1, declaration.length - colon - 1).trim();
|
||||
if value.find("!important") is some(important) {
|
||||
value = value.substr(0, important).trim();
|
||||
}
|
||||
val lowered := name.lower();
|
||||
this.set(lowered.view(), value, parent, view);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
#! Contains SVG's renderer, which draws the static part of SVG 1.1 that icons and
|
||||
#! illustrations are made of: paths and the basic shapes; groups, `use`, and
|
||||
#! `symbol`; nested `svg` viewports, with `viewBox` and `preserveAspectRatio`;
|
||||
#! fills by either rule and strokes with their caps, joins, miter limits, and
|
||||
#! dashes; colors, linear and radial gradients with every spread, `opacity`,
|
||||
#! `clip-path`, and `mask`. Styles come from presentation attributes, `<style>`
|
||||
#! sheets of type, class, and ID selectors, and `style` attributes.
|
||||
#!
|
||||
#! Left undrawn: text, embedded images, patterns, markers, filters, and nested
|
||||
#! viewports' clipping. Animation and scripts are ignored. SVG is drawn, and not
|
||||
#! written.
|
||||
|
||||
import std::containers;
|
||||
import std::math;
|
||||
import std::xml;
|
||||
module image::svg;
|
||||
|
||||
|
||||
const svg_namespace: strview = "http://www.w3.org/2000/svg";
|
||||
const xlink_namespace: strview = "http://www.w3.org/1999/xlink";
|
||||
|
||||
# How deep elements, and references from `use`, may nest before what's deeper is
|
||||
# left undrawn, against a `use` within what it refers to.
|
||||
const deepest: u32 = 64;
|
||||
|
||||
# Elements drawn only by reference, or never.
|
||||
const undrawn: strview[17] = [
|
||||
"defs", "symbol", "clipPath", "mask", "linearGradient", "radialGradient", "pattern", "marker", "style",
|
||||
"title", "desc", "metadata", "script", "filter", "text", "image", "foreignObject",
|
||||
];
|
||||
|
||||
# What drawing a document keeps.
|
||||
struct renderer {
|
||||
var ids: dict<strview, xml::element>;
|
||||
var sheet: sheet;
|
||||
var canvas: canvas;
|
||||
var view: viewport; #! The viewport percentages are of, in the current user space.
|
||||
var clipping: bool; #! Whether shapes are drawn as a clip path's, each solid.
|
||||
var depth: u32;
|
||||
}
|
||||
|
||||
#! Draws an SVG.
|
||||
#! @param bytes The SVG's text.
|
||||
#! @param size The size to draw it at.
|
||||
#! @returns The image, or `malformed` where the text isn't XML whose root is an
|
||||
#! SVG element, or whose size is none, and `too_large` where it would
|
||||
#! be drawn with too many pixels.
|
||||
pub def render(bytes: span<u8>, size: svg_size): result<image, image_error> {
|
||||
val doc := xml::parse(bytes) else (_) { return image_error::malformed; };
|
||||
val root := doc.root;
|
||||
if root.local != "svg" || !is_svg(&root) {
|
||||
return image_error::malformed;
|
||||
}
|
||||
|
||||
# The SVG's own size: its width and height, or its view box's, either making
|
||||
# the other keep the view box's shape.
|
||||
val fixed := viewport { width = 100, height = 100 };
|
||||
val box := view_box(&root);
|
||||
var width := absolute_length(&root, "width", &fixed);
|
||||
var height := absolute_length(&root, "height", &fixed);
|
||||
if box is some(seen) {
|
||||
if width is none && height is none {
|
||||
width = seen[2];
|
||||
height = seen[3];
|
||||
} else if width is none {
|
||||
width = height.unwrap() * seen[2] / seen[3];
|
||||
} else if height is none {
|
||||
height = width.unwrap() * seen[3] / seen[2];
|
||||
}
|
||||
}
|
||||
val own_width := width else 100.0;
|
||||
val own_height := height else 100.0;
|
||||
if own_width <= 0 || own_height <= 0 {
|
||||
return image_error::malformed;
|
||||
}
|
||||
|
||||
# The size asked for, which keeps the SVG's shape where only one side is.
|
||||
var out_width := own_width;
|
||||
var out_height := own_height;
|
||||
if size.width != 0 && size.height != 0 {
|
||||
out_width = size.width as f64;
|
||||
out_height = size.height as f64;
|
||||
} else if size.width != 0 {
|
||||
out_width = size.width as f64;
|
||||
out_height = own_height * out_width / own_width;
|
||||
} else if size.height != 0 {
|
||||
out_height = size.height as f64;
|
||||
out_width = own_width * out_height / own_height;
|
||||
}
|
||||
out_width *= size.scale;
|
||||
out_height *= size.scale;
|
||||
val pixels_wide := math::max(1.0, math::round(out_width));
|
||||
val pixels_high := math::max(1.0, math::round(out_height));
|
||||
if !math::is_finite(pixels_wide) || !math::is_finite(pixels_high) || pixels_wide * pixels_high > image::max_pixels as f64 {
|
||||
return image_error::too_large;
|
||||
}
|
||||
val columns := pixels_wide as u64;
|
||||
val rows := pixels_high as u64;
|
||||
|
||||
var drawing := renderer {
|
||||
ids = dict::<strview, xml::element>::new(),
|
||||
sheet = sheet::new(),
|
||||
canvas = canvas::new(columns, rows)
|
||||
};
|
||||
drawing.index(&root);
|
||||
|
||||
# User space: the view box's, fit to the image, or the SVG's own units scaled.
|
||||
var placed := scaling(columns as f64 / own_width, rows as f64 / own_height);
|
||||
drawing.view = viewport { width = own_width, height = own_height };
|
||||
if box is some(seen) {
|
||||
placed = fit_view_box(seen, root.attribute("preserveAspectRatio") else "", 0, 0, columns as f64, rows as f64);
|
||||
drawing.view = viewport { width = seen[2], height = seen[3] };
|
||||
}
|
||||
drawing.draw(&root, &style {}, &placed);
|
||||
|
||||
# The canvas is premultiplied, and the image straight.
|
||||
var made := image::blank(columns as u32, rows as u32) else (e) { return e; };
|
||||
val drawn := drawing.canvas.layers[0].view();
|
||||
var at: u64 = 0;
|
||||
while at < drawn.length {
|
||||
val alpha := drawn[at + 3] as u32;
|
||||
if alpha != 0 {
|
||||
for channel in 0u..3u {
|
||||
val straight := (drawn[at + channel] as u32 * 255 + alpha / 2) / alpha;
|
||||
made.pixels[at + channel] = (straight > 255 ? 255 : straight) as u8;
|
||||
}
|
||||
made.pixels[at + 3] = alpha as u8;
|
||||
}
|
||||
at += 4;
|
||||
}
|
||||
return move(made);
|
||||
}
|
||||
@@ -0,0 +1,164 @@
|
||||
#! Contains viewports: nested `svg`s, and the `symbol`s and `svg`s a `use`
|
||||
#! draws, each a place and size its view box is fit within, as
|
||||
#! `preserveAspectRatio` says, and the lengths measured in them.
|
||||
|
||||
import std::math;
|
||||
import std::xml;
|
||||
module image::svg;
|
||||
|
||||
|
||||
# Draws an `svg` within another, or a `symbol` or `svg` a `use` draws: a viewport
|
||||
# at its place and size, its view box fit within it.
|
||||
def renderer::viewport(&mut this, at: &xml::element, own: &style, placed: &matrix, sized: &xml::element,
|
||||
width_given: maybe<f64>, height_given: maybe<f64>): void {
|
||||
val x := this.length_of(sized, "x", axis::x, 0);
|
||||
val y := this.length_of(sized, "y", axis::y, 0);
|
||||
val width := width_given else this.length_of(sized, "width", axis::x, this.view.width);
|
||||
val height := height_given else this.length_of(sized, "height", axis::y, this.view.height);
|
||||
if width <= 0 || height <= 0 {
|
||||
return;
|
||||
}
|
||||
var inner := translation(x, y);
|
||||
var view := viewport { width = width, height = height };
|
||||
if view_box(at) is some(box) {
|
||||
inner = fit_view_box(box, at.attribute("preserveAspectRatio") else "", x, y, width, height);
|
||||
view = viewport { width = box[2], height = box[3] };
|
||||
}
|
||||
val saved := this.view;
|
||||
this.view = view;
|
||||
this.children(at, own, &inner.then(placed));
|
||||
this.view = saved;
|
||||
}
|
||||
|
||||
# Draws what a `use` refers to, moved by its `x` and `y`, inheriting the `use`'s
|
||||
# style.
|
||||
def renderer::use_element(&mut this, at: &xml::element, own: &style, placed: &matrix): void {
|
||||
val href := href_of(at);
|
||||
if !href.starts_with("#") {
|
||||
return;
|
||||
}
|
||||
val id := href.substr(1, href.length - 1);
|
||||
val target := this.ids.get(&id) else { return; };
|
||||
val x := this.length_of(at, "x", axis::x, 0);
|
||||
val y := this.length_of(at, "y", axis::y, 0);
|
||||
val moved := translation(x, y).then(placed);
|
||||
|
||||
if target.local == "symbol" || target.local == "svg" {
|
||||
# Its viewport takes the `use`'s width and height, where it gives them.
|
||||
val symbol_style := this.style_of(&target, own);
|
||||
if !symbol_style.displayed {
|
||||
return;
|
||||
}
|
||||
var width: maybe<f64> = nothing {};
|
||||
var height: maybe<f64> = nothing {};
|
||||
if at.attribute("width") is some(_) {
|
||||
width = this.length_of(at, "width", axis::x, 0);
|
||||
}
|
||||
if at.attribute("height") is some(_) {
|
||||
height = this.length_of(at, "height", axis::y, 0);
|
||||
}
|
||||
if target.local == "symbol" {
|
||||
this.symbol(&target, &symbol_style, &moved, width, height);
|
||||
} else {
|
||||
this.depth++;
|
||||
this.viewport(&target, &symbol_style, &moved, &target, width, height);
|
||||
this.depth--;
|
||||
}
|
||||
return;
|
||||
}
|
||||
this.draw(&target, own, &moved);
|
||||
}
|
||||
|
||||
# Draws a symbol's children in the viewport a `use` gives it, of 100% each way
|
||||
# where it gives none.
|
||||
def renderer::symbol(&mut this, at: &xml::element, own: &style, placed: &matrix, width_given: maybe<f64>, height_given: maybe<f64>): void {
|
||||
val width := width_given else this.view.width;
|
||||
val height := height_given else this.view.height;
|
||||
if width <= 0 || height <= 0 {
|
||||
return;
|
||||
}
|
||||
var inner := matrix {};
|
||||
var view := viewport { width = width, height = height };
|
||||
if view_box(at) is some(box) {
|
||||
inner = fit_view_box(box, at.attribute("preserveAspectRatio") else "", 0, 0, width, height);
|
||||
view = viewport { width = box[2], height = box[3] };
|
||||
}
|
||||
val saved := this.view;
|
||||
this.view = view;
|
||||
this.depth++;
|
||||
this.children(at, own, &inner.then(placed));
|
||||
this.depth--;
|
||||
this.view = saved;
|
||||
}
|
||||
|
||||
# A length attribute, in user units, or what it is where it's left out or wrong.
|
||||
def renderer::length_of(&this, at: &xml::element, name: strview, along: axis, fallback: f64): f64 {
|
||||
val written := at.attribute(name) else { return fallback; };
|
||||
return parse_length(written, &this.view, along) else fallback;
|
||||
}
|
||||
|
||||
# A length of the root, where it's given in absolute units rather than a
|
||||
# percentage, which has nothing to be of.
|
||||
def absolute_length(at: &xml::element, name: strview, view: &viewport): maybe<f64> {
|
||||
val written := at.attribute(name) else { return nothing {}; };
|
||||
if written.find("%") is some(_) {
|
||||
return nothing {};
|
||||
}
|
||||
return parse_length(written, view, axis::x);
|
||||
}
|
||||
|
||||
# An element's `viewBox`: its least x and y, and its width and height, which
|
||||
# must be more than none.
|
||||
def view_box(at: &xml::element): maybe<f64[4]> {
|
||||
val written := at.attribute("viewBox") else { return nothing {}; };
|
||||
var read := numbers::of(written);
|
||||
var box: f64[4];
|
||||
for index in 0u..4u {
|
||||
box[index] = read.next() else { return nothing {}; };
|
||||
}
|
||||
if box[2] <= 0 || box[3] <= 0 {
|
||||
return nothing {};
|
||||
}
|
||||
return box;
|
||||
}
|
||||
|
||||
# The transform fitting a view box within a viewport, as `preserveAspectRatio`
|
||||
# says: stretched, or scaled the same each way to meet or slice it, and aligned.
|
||||
def fit_view_box(box: f64[4], aspect: strview, x: f64, y: f64, width: f64, height: f64): matrix {
|
||||
var words := aspect.trim();
|
||||
if words.starts_with("defer") {
|
||||
words = words.substr(5, words.length - 5).trim();
|
||||
}
|
||||
var align := words;
|
||||
var slice := false;
|
||||
if words.find(" ") is some(space) {
|
||||
align = words.substr(0, space);
|
||||
slice = words.substr(space, words.length - space).trim() == "slice";
|
||||
}
|
||||
if align.length == 0 {
|
||||
align = "xMidYMid";
|
||||
}
|
||||
|
||||
var sx := width / box[2];
|
||||
var sy := height / box[3];
|
||||
if align != "none" {
|
||||
val scale := slice ? math::max(sx, sy) : math::min(sx, sy);
|
||||
sx = scale;
|
||||
sy = scale;
|
||||
}
|
||||
var tx := x - box[0] * sx;
|
||||
var ty := y - box[1] * sy;
|
||||
val spare_x := width - box[2] * sx;
|
||||
val spare_y := height - box[3] * sy;
|
||||
if align.find("xMid") is some(_) {
|
||||
tx += spare_x / 2;
|
||||
} else if align.find("xMax") is some(_) {
|
||||
tx += spare_x;
|
||||
}
|
||||
if align.find("YMid") is some(_) {
|
||||
ty += spare_y / 2;
|
||||
} else if align.find("YMax") is some(_) {
|
||||
ty += spare_y;
|
||||
}
|
||||
return matrix { a = sx, d = sy, e = tx, f = ty };
|
||||
}
|
||||
Reference in new issue
Block a user