Files
rosetta/src/Formats/vector/svg/Write.luau
T

204 lines
7.6 KiB
Luau

--!strict
-- vector/svg/Write: a Types.Vector to SVG text: <svg> with width / height / viewBox / preserveAspectRatio, gradients
-- and clip paths in <defs>, groups as nested <g opacity clip-path>, every path as <path d transform fill stroke ...>
-- (colour alpha as fill- / stroke-opacity). Never throws: bad values return nil, message.
local Xml = require("@formats/codecs/Xml")
local Types = require("@formats/Types")
local PathData = require("@formats/vector/svg/PathData")
local Write = {}
local num = PathData.num
local function el(name: string, attrs: { { any } }, children: { any }?): any
local o = Types.object()
for _, kv in attrs do
if kv[2] ~= nil then
Types.set(o, kv[1], if type(kv[2]) == "number" then num(kv[2]) else tostring(kv[2]))
end
end
return Xml.element(name, o :: any, children)
end
local function hex(c: { number }): string
return string.format("#%02x%02x%02x", math.clamp(math.floor(c[1] or 0), 0, 255), math.clamp(math.floor(c[2] or 0), 0, 255), math.clamp(math.floor(c[3] or 0), 0, 255))
end
local function matrix(m: any): string?
if type(m) ~= "table" or #m < 6 then
return nil
end
if m[1] == 1 and m[2] == 0 and m[3] == 0 and m[4] == 1 then
if m[5] == 0 and m[6] == 0 then
return nil
end
return "translate(" .. num(m[5]) .. " " .. num(m[6]) .. ")"
end
local parts = {}
for k = 1, 6 do
parts[k] = num(tonumber(m[k]) or 0)
end
return "matrix(" .. table.concat(parts, " ") .. ")"
end
-- write(v) -> SVG text | nil, message
function Write.vector(v: Types.Vector): (string?, string?)
if type(v) ~= "table" or type(v.paths) ~= "table" or type(v.width) ~= "number" or type(v.height) ~= "number" then
return nil, "needs a Vector value"
end
local meta: any = if type(v.meta) == "table" then v.meta else {}
local groups: { any } = if type(meta.groups) == "table" then meta.groups else {}
local clips: { any } = if type(meta.clips) == "table" then meta.clips else {}
local defs = {}
local gradients = 0
-- paints -> attribute values (gradients go to defs)
local function paintAttrs(p: any, which: string): { { any } }
if type(p) ~= "table" then
return { { which, "none" } }
end
if p.type == "color" and type(p.color) == "table" then
local a = p.color[4] or 255
return { { which, hex(p.color) }, { which .. "-opacity", if a < 255 then num(a / 255) else nil } }
end
if p.type ~= "linear" and p.type ~= "radial" then
return { { which, "none" } }
end
gradients += 1
local id = "g" .. gradients
local kids = {}
for _, s in (if type(p.stops) == "table" then p.stops else {}) do
local a = s[5] or 255
table.insert(kids, el("stop", { { "offset", s[1] or 0 }, { "stop-color", hex({ s[2], s[3], s[4] }) }, { "stop-opacity", if a < 255 then num(a / 255) else nil } }))
end
local attrs: { { any } } = { { "id", id }, { "gradientUnits", if p.units == "userSpaceOnUse" then "userSpaceOnUse" else nil } }
if p.type == "linear" then
table.insert(attrs, { "x1", p.x1 or 0 })
table.insert(attrs, { "y1", p.y1 or 0 })
table.insert(attrs, { "x2", p.x2 or 1 })
table.insert(attrs, { "y2", p.y2 or 0 })
else
table.insert(attrs, { "cx", p.cx or 0.5 })
table.insert(attrs, { "cy", p.cy or 0.5 })
table.insert(attrs, { "r", p.r or 0.5 })
table.insert(attrs, { "fx", p.fx })
table.insert(attrs, { "fy", p.fy })
if p.fr and p.fr ~= 0 then
table.insert(attrs, { "fr", p.fr })
end
end
table.insert(attrs, { "spreadMethod", if p.spread and p.spread ~= "pad" then p.spread else nil })
table.insert(attrs, { "gradientTransform", matrix(p.transform) })
table.insert(defs, el(if p.type == "linear" then "linearGradient" else "radialGradient", attrs, kids))
local op = tonumber(p.opacity) or 1
return { { which, "url(#" .. id .. ")" }, { which .. "-opacity", if op < 1 then num(op) else nil } }
end
local clipIds: { [number]: string } = {}
local function clipRef(id: number?): string?
if id == nil or type(clips[id]) ~= "table" then
return nil
end
if clipIds[id] == nil then
local cid = "c" .. id
clipIds[id] = cid
local kids = {}
for _, cp in (if type(clips[id].paths) == "table" then clips[id].paths else {}) do
table.insert(kids, el("path", { { "d", PathData.serialize(cp.d or {}) }, { "transform", matrix(cp.transform) }, { "clip-rule", if cp.rule == "evenodd" then "evenodd" else nil } }))
end
table.insert(defs, el("clipPath", { { "id", cid } }, kids))
end
return "url(#" .. clipIds[id] .. ")"
end
local root = {}
-- the open <g> stack: { id, children }
local stack: { { id: number?, kids: { any } } } = { { id = nil, kids = root } }
local function chain(g: number?): { number }
local out = {}
local guard = 0
while g ~= nil and guard < 256 do
table.insert(out, 1, g)
local gr = groups[g]
g = if type(gr) == "table" then gr.parent else nil
guard += 1
end
return out
end
for _, p in v.paths do
if type(p) ~= "table" or type(p.d) ~= "table" then
continue
end
local want = chain(p.group)
local keep = 1
while keep < #stack and stack[keep + 1].id == want[keep] do
keep += 1
end
while #stack > keep do
table.remove(stack)
end
for k = keep, #want do
local gr = groups[want[k]] or {}
local kids = {}
local op = tonumber(gr.opacity) or 1
table.insert(stack[#stack].kids, el("g", { { "opacity", if op < 1 then op else nil }, { "clip-path", clipRef(gr.clip) } }, kids))
table.insert(stack, { id = want[k], kids = kids })
end
local attrs: { { any } } = { { "id", p.id }, { "d", PathData.serialize(p.d) }, { "transform", matrix(p.transform) } }
for _, kv in paintAttrs(p.fill, "fill") do
table.insert(attrs, kv)
end
table.insert(attrs, { "fill-rule", if p.fillRule == "evenodd" then "evenodd" else nil })
for _, kv in paintAttrs(p.stroke, "stroke") do
if kv[2] ~= "none" then
table.insert(attrs, kv)
end
end
if type(p.stroke) == "table" then
local sw = tonumber(p.strokeWidth) or 1
table.insert(attrs, { "stroke-width", if sw ~= 1 then sw else nil })
table.insert(attrs, { "stroke-linejoin", if p.strokeLineJoin and p.strokeLineJoin ~= "miter" then p.strokeLineJoin else nil })
table.insert(attrs, { "stroke-linecap", if p.strokeLineCap and p.strokeLineCap ~= "butt" then p.strokeLineCap else nil })
local ml = tonumber(p.strokeMiterLimit)
table.insert(attrs, { "stroke-miterlimit", if ml and ml ~= 4 then ml else nil })
if type(p.strokeDashArray) == "table" and #p.strokeDashArray > 0 then
local parts = {}
for k, d in p.strokeDashArray do
parts[k] = num(tonumber(d) or 0)
end
table.insert(attrs, { "stroke-dasharray", table.concat(parts :: { string }, " ") })
local off = tonumber(p.strokeDashOffset)
table.insert(attrs, { "stroke-dashoffset", if off and off ~= 0 then off else nil })
end
end
local op = tonumber(p.opacity) or 1
table.insert(attrs, { "opacity", if op < 1 then op else nil })
local node = el("path", attrs)
local cr = clipRef(p.clip)
if cr then
node = el("g", { { "clip-path", cr } }, { node })
end
table.insert(stack[#stack].kids, node)
end
local children = {}
if #defs > 0 then
table.insert(children, el("defs", {}, defs))
end
for _, c in root do
table.insert(children, c)
end
local vb = v.viewBox
local vbText = if type(vb) == "table" and #vb == 4 then num(vb[1]) .. " " .. num(vb[2]) .. " " .. num(vb[3]) .. " " .. num(vb[4]) else nil
local svg = el("svg", {
{ "xmlns", "http://www.w3.org/2000/svg" },
{ "width", v.width },
{ "height", v.height },
{ "viewBox", vbText },
{ "preserveAspectRatio", meta.preserveAspectRatio },
}, children)
local s, err = Xml.encode(Xml.document(svg, { version = "1.0", encoding = "UTF-8" }), { indent = 1 })
if not s then
return nil, tostring(err)
end
return s .. "\n", nil
end
return Write