diff --git a/.gitignore b/.gitignore index 966930b..e30ab14 100644 --- a/.gitignore +++ b/.gitignore @@ -12,3 +12,4 @@ host-wasm/target/ # moon rewrites these for whichever target was built last, so they differ run to run. A few # (app, gfx, renderer, scene) were committed early and stay tracked; the rest are not. compositor/*/pkg.generated.mbti +wasmhost/*/pkg.generated.mbti diff --git a/compositor/sys/sys_wasm.mbt b/compositor/sys/sys_wasm.mbt index 4d9b1ff..889016f 100644 --- a/compositor/sys/sys_wasm.mbt +++ b/compositor/sys/sys_wasm.mbt @@ -154,7 +154,23 @@ pub fn read_file_bytes(path : String) -> Bytes { ///| pub fn write_file_bytes(path : String, data : Bytes) -> Int { - @hostsys.write_file(path, to_fixed(data)) + // At most 1 MiB per call (see append-file in wit/host/sys.wit). + let chunk = 1 << 20 + if data.length() <= chunk { + return @hostsys.write_file(path, to_fixed(data)) + } + if @hostsys.write_file(path, to_fixed(data[0:chunk].to_owned())) != 0 { + return -1 + } + let mut at = chunk + while at < data.length() { + let end = if at + chunk < data.length() { at + chunk } else { data.length() } + if @hostsys.append_file(path, to_fixed(data[at:end].to_owned())) != 0 { + return -1 + } + at = end + } + 0 } ///| diff --git a/host-wasm/src/main.rs b/host-wasm/src/main.rs index 765fcb6..33455cd 100644 --- a/host-wasm/src/main.rs +++ b/host-wasm/src/main.rs @@ -698,6 +698,15 @@ impl Host for State { } } + fn append_file(&mut self, path: String, data: Vec) -> i32 { + use std::io::Write; + let f = std::fs::OpenOptions::new().append(true).create(true).open(path); + match f.and_then(|mut f| f.write_all(&data)) { + Ok(()) => 0, + Err(_) => -1, + } + } + fn read_proc(&mut self, path: String) -> Vec { // /proc and /sys files report size 0: read to EOF, capped at 64 KiB. let Ok(f) = std::fs::File::open(path) else { return Vec::new() }; diff --git a/interface/chandra/host/sys/ffi.mbt b/interface/chandra/host/sys/ffi.mbt index 6c44b88..5ac695d 100644 --- a/interface/chandra/host/sys/ffi.mbt +++ b/interface/chandra/host/sys/ffi.mbt @@ -48,6 +48,9 @@ fn wasmImportReadFile(p0 : Int, p1 : Int, p2 : Int) = "chandra:host/sys@0.1.0" ///| fn wasmImportWriteFile(p0 : Int, p1 : Int, p2 : Int, p3 : Int) -> Int = "chandra:host/sys@0.1.0" "write-file" +///| +fn wasmImportAppendFile(p0 : Int, p1 : Int, p2 : Int, p3 : Int) -> Int = "chandra:host/sys@0.1.0" "append-file" + ///| fn wasmImportReadProc(p0 : Int, p1 : Int, p2 : Int) = "chandra:host/sys@0.1.0" "read-proc" diff --git a/interface/chandra/host/sys/native_stub.mbt b/interface/chandra/host/sys/native_stub.mbt index 55bc1dc..4e350ed 100644 --- a/interface/chandra/host/sys/native_stub.mbt +++ b/interface/chandra/host/sys/native_stub.mbt @@ -80,6 +80,11 @@ fn wasmImportWriteFile(p0 : Int, p1 : Int, p2 : Int, p3 : Int) -> Int { abort("wasm-only host import") } +///| +fn wasmImportAppendFile(p0 : Int, p1 : Int, p2 : Int, p3 : Int) -> Int { + abort("wasm-only host import") +} + ///| fn wasmImportReadProc(p0 : Int, p1 : Int, p2 : Int) -> Unit { abort("wasm-only host import") diff --git a/interface/chandra/host/sys/pkg.generated.mbti b/interface/chandra/host/sys/pkg.generated.mbti index 374ef7e..70cb33c 100644 --- a/interface/chandra/host/sys/pkg.generated.mbti +++ b/interface/chandra/host/sys/pkg.generated.mbti @@ -2,6 +2,8 @@ package "chandra/desktop/interface/chandra/host/sys" // Values +pub fn append_file(String, FixedArray[Byte]) -> Int32 + pub fn close_fd(Int32) -> Unit pub fn getenv(String) -> String @@ -50,6 +52,8 @@ pub fn unix_listen(String) -> Int32 pub fn unlink(String) -> Unit +pub fn wait_readable(FixedArray[Int32], Int32) -> Int32 + pub fn wall_time_field(Int32) -> Int32 pub fn write_file(String, FixedArray[Byte]) -> Int32 diff --git a/interface/chandra/host/sys/top.mbt b/interface/chandra/host/sys/top.mbt index fad9065..8fd17cb 100644 --- a/interface/chandra/host/sys/top.mbt +++ b/interface/chandra/host/sys/top.mbt @@ -183,6 +183,21 @@ pub fn write_file(path : String, data : FixedArray[Byte]) -> Int { mbt_ffi_free(ptr0) return ret +} +///| +/// Append `data` to the file at `path` (created if missing): 0, or -1 on error. +pub fn append_file(path : String, data : FixedArray[Byte]) -> Int { + + let ptr = mbt_ffi_str2ptr(path) + + let ptr0 = mbt_ffi_bytes2ptr(data) + + let result : Int = wasmImportAppendFile(ptr, path.length(), ptr0, data.length()); + let ret = result + mbt_ffi_free(ptr) + mbt_ffi_free(ptr0) + return ret + } ///| /// Contents of a small /proc or /sys file ("" when unreadable). diff --git a/justfile b/justfile index 4579b59..e0a56ae 100644 --- a/justfile +++ b/justfile @@ -146,3 +146,8 @@ compositor-wasm: host-wasm: cd host-wasm && cargo build --release +# Build the MoonBit host for the compositor component (build/wasmhost): links the prebuilt wasmtime +# C API instead of compiling wasmtime. Work in progress: it will replace host-wasm. +wasmhost: + scripts/build-wasmhost.sh + diff --git a/scripts/build-wasmhost.sh b/scripts/build-wasmhost.sh new file mode 100755 index 0000000..92c374c --- /dev/null +++ b/scripts/build-wasmhost.sh @@ -0,0 +1,18 @@ +#!/usr/bin/env bash +# Build the MoonBit host for the compositor component: build/wasmhost. +# It links the prebuilt wasmtime C API (scripts/setup-toolchain.sh puts it in .tools/wasmtime-c-api) +# instead of compiling wasmtime, so a build takes seconds. Statically linked: nothing to install. +# scripts/build-wasmhost.sh +# build/wasmhost build/compositor.wasm --socket PATH [--window | --drm | --gfx-out PNG] +set -euo pipefail +ROOT="$(cd "$(dirname "$0")/.." && pwd)"; cd "$ROOT" +export PATH="$ROOT/.tools/bin:$HOME/.moon/bin:$PATH" +CAPI="$ROOT/.tools/wasmtime-c-api" +[ -f "$CAPI/lib/libwasmtime.a" ] || { echo "error: $CAPI missing; run scripts/setup-toolchain.sh" >&2; exit 1; } +command -v moon >/dev/null || { echo "error: moon not found" >&2; exit 1; } +export C_INCLUDE_PATH="$CAPI/include${C_INCLUDE_PATH:+:$C_INCLUDE_PATH}" +export LIBRARY_PATH="$CAPI/lib${LIBRARY_PATH:+:$LIBRARY_PATH}" +moon build --target native --release --warn-list -a wasmhost/bin +mkdir -p build +cp _build/native/release/build/wasmhost/bin/bin.exe build/wasmhost +echo "build/wasmhost $(stat -c %s build/wasmhost) bytes" diff --git a/scripts/setup-toolchain.sh b/scripts/setup-toolchain.sh index a77a543..60cd27d 100755 --- a/scripts/setup-toolchain.sh +++ b/scripts/setup-toolchain.sh @@ -30,5 +30,15 @@ if ! have wasmtime "$WASMTIME_VERSION"; then curl -fsSL "https://github.com/bytecodealliance/wasmtime/releases/download/v$WASMTIME_VERSION/wasmtime-v$WASMTIME_VERSION-x86_64-linux.tar.xz" | tar xJ -C "$tmp" cp "$tmp"/wasmtime-*/wasmtime "$BIN/" fi +# The wasmtime C API (libwasmtime + headers) for the MoonBit host (wasmhost/), linked instead of +# compiling wasmtime from source: .tools/wasmtime-c-api/{include,lib}. +CAPI="$ROOT/.tools/wasmtime-c-api" +if [ "$(cat "$CAPI/VERSION" 2>/dev/null)" != "$WASMTIME_VERSION" ]; then + echo ">> wasmtime C API $WASMTIME_VERSION" + curl -fsSL "https://github.com/bytecodealliance/wasmtime/releases/download/v$WASMTIME_VERSION/wasmtime-v$WASMTIME_VERSION-x86_64-linux-c-api.tar.xz" | tar xJ -C "$tmp" + rm -rf "$CAPI"; mkdir -p "$CAPI" + cp -r "$tmp"/wasmtime-*-c-api/include "$tmp"/wasmtime-*-c-api/lib "$CAPI/" + echo "$WASMTIME_VERSION" > "$CAPI/VERSION" +fi echo "installed into $BIN:" -"$BIN/wasm-tools" --version; "$BIN/wit-bindgen" --version; "$BIN/wasmtime" --version +"$BIN/wasm-tools" --version; "$BIN/wit-bindgen" --version; "$BIN/wasmtime" --version; echo "wasmtime C API $(cat "$CAPI/VERSION") in $CAPI" diff --git a/third_party/nanosvg/LICENSE.txt b/third_party/nanosvg/LICENSE.txt new file mode 100644 index 0000000..6fde401 --- /dev/null +++ b/third_party/nanosvg/LICENSE.txt @@ -0,0 +1,18 @@ +Copyright (c) 2013-14 Mikko Mononen memon@inside.org + +This software is provided 'as-is', without any express or implied +warranty. In no event will the authors be held liable for any damages +arising from the use of this software. + +Permission is granted to anyone to use this software for any purpose, +including commercial applications, and to alter it and redistribute it +freely, subject to the following restrictions: + +1. The origin of this software must not be misrepresented; you must not +claim that you wrote the original software. If you use this software +in a product, an acknowledgment in the product documentation would be +appreciated but is not required. +2. Altered source versions must be plainly marked as such, and must not be +misrepresented as being the original software. +3. This notice may not be removed or altered from any source distribution. + diff --git a/third_party/nanosvg/nanosvg.h b/third_party/nanosvg/nanosvg.h new file mode 100644 index 0000000..291ecbf --- /dev/null +++ b/third_party/nanosvg/nanosvg.h @@ -0,0 +1,3278 @@ +/* + * Copyright (c) 2013-14 Mikko Mononen memon@inside.org + * + * This software is provided 'as-is', without any express or implied + * warranty. In no event will the authors be held liable for any damages + * arising from the use of this software. + * + * Permission is granted to anyone to use this software for any purpose, + * including commercial applications, and to alter it and redistribute it + * freely, subject to the following restrictions: + * + * 1. The origin of this software must not be misrepresented; you must not + * claim that you wrote the original software. If you use this software + * in a product, an acknowledgment in the product documentation would be + * appreciated but is not required. + * 2. Altered source versions must be plainly marked as such, and must not be + * misrepresented as being the original software. + * 3. This notice may not be removed or altered from any source distribution. + * + * The SVG parser is based on Anti-Grain Geometry 2.4 SVG example + * Copyright (C) 2002-2004 Maxim Shemanarev (McSeem) (http://www.antigrain.com/) + * + * Arc calculation code based on canvg (https://code.google.com/p/canvg/) + * + * Bounding box calculation based on http://blog.hackers-cafe.net/2009/06/how-to-calculate-bezier-curves-bounding.html + * + */ + +#ifndef NANOSVG_H +#define NANOSVG_H + +#ifndef NANOSVG_CPLUSPLUS +#ifdef __cplusplus +extern "C" { +#endif +#endif + +// NanoSVG is a simple stupid single-header-file SVG parse. The output of the parser is a list of cubic bezier shapes. +// +// The library suits well for anything from rendering scalable icons in your editor application to prototyping a game. +// +// NanoSVG supports a wide range of SVG features, but something may be missing, feel free to create a pull request! +// +// The shapes in the SVG images are transformed by the viewBox and converted to specified units. +// That is, you should get the same looking data as your designed in your favorite app. +// +// NanoSVG can return the paths in few different units. For example if you want to render an image, you may choose +// to get the paths in pixels, or if you are feeding the data into a CNC-cutter, you may want to use millimeters. +// +// The units passed to NanoSVG should be one of: 'px', 'pt', 'pc' 'mm', 'cm', or 'in'. +// DPI (dots-per-inch) controls how the unit conversion is done. +// +// If you don't know or care about the units stuff, "px" and 96 should get you going. + + +/* Example Usage: + // Load SVG + NSVGimage* image; + image = nsvgParseFromFile("test.svg", "px", 96); + printf("size: %f x %f\n", image->width, image->height); + // Use... + for (NSVGshape *shape = image->shapes; shape != NULL; shape = shape->next) { + for (NSVGpath *path = shape->paths; path != NULL; path = path->next) { + for (int i = 0; i < path->npts-1; i += 3) { + float* p = &path->pts[i*2]; + drawCubicBez(p[0],p[1], p[2],p[3], p[4],p[5], p[6],p[7]); + } + } + } + // Delete + nsvgDelete(image); +*/ + +enum NSVGpaintType { + NSVG_PAINT_UNDEF = -1, + NSVG_PAINT_NONE = 0, + NSVG_PAINT_COLOR = 1, + NSVG_PAINT_LINEAR_GRADIENT = 2, + NSVG_PAINT_RADIAL_GRADIENT = 3 +}; + +enum NSVGspreadType { + NSVG_SPREAD_PAD = 0, + NSVG_SPREAD_REFLECT = 1, + NSVG_SPREAD_REPEAT = 2 +}; + +enum NSVGlineJoin { + NSVG_JOIN_MITER = 0, + NSVG_JOIN_ROUND = 1, + NSVG_JOIN_BEVEL = 2 +}; + +enum NSVGlineCap { + NSVG_CAP_BUTT = 0, + NSVG_CAP_ROUND = 1, + NSVG_CAP_SQUARE = 2 +}; + +enum NSVGfillRule { + NSVG_FILLRULE_NONZERO = 0, + NSVG_FILLRULE_EVENODD = 1 +}; + +enum NSVGflags { + NSVG_FLAGS_VISIBLE = 0x01 +}; + +enum NSVGpaintOrder { + NSVG_PAINT_FILL = 0x00, + NSVG_PAINT_MARKERS = 0x01, + NSVG_PAINT_STROKE = 0x02, +}; + +typedef struct NSVGgradientStop { + unsigned int color; + float offset; +} NSVGgradientStop; + +typedef struct NSVGgradient { + float xform[6]; + char spread; + float fx, fy; + int nstops; + NSVGgradientStop stops[1]; +} NSVGgradient; + +typedef struct NSVGpaint { + signed char type; + union { + unsigned int color; + NSVGgradient* gradient; + }; +} NSVGpaint; + +typedef struct NSVGpath +{ + float* pts; // Cubic bezier points: x0,y0, [cpx1,cpx1,cpx2,cpy2,x1,y1], ... + int npts; // Total number of bezier points. + char closed; // Flag indicating if shapes should be treated as closed. + float bounds[4]; // Tight bounding box of the shape [minx,miny,maxx,maxy]. + struct NSVGpath* next; // Pointer to next path, or NULL if last element. +} NSVGpath; + +typedef struct NSVGshape +{ + char id[64]; // Optional 'id' attr of the shape or its group + NSVGpaint fill; // Fill paint + NSVGpaint stroke; // Stroke paint + float opacity; // Opacity of the shape. + float strokeWidth; // Stroke width (scaled). + float strokeDashOffset; // Stroke dash offset (scaled). + float strokeDashArray[8]; // Stroke dash array (scaled). + char strokeDashCount; // Number of dash values in dash array. + char strokeLineJoin; // Stroke join type. + char strokeLineCap; // Stroke cap type. + float miterLimit; // Miter limit + char fillRule; // Fill rule, see NSVGfillRule. + unsigned char paintOrder; // Encoded paint order (3×2-bit fields) see NSVGpaintOrder + unsigned char flags; // Logical or of NSVG_FLAGS_* flags + float bounds[4]; // Tight bounding box of the shape [minx,miny,maxx,maxy]. + char fillGradient[64]; // Optional 'id' of fill gradient + char strokeGradient[64]; // Optional 'id' of stroke gradient + float xform[6]; // Root transformation for fill/stroke gradient + NSVGpath* paths; // Linked list of paths in the image. + struct NSVGshape* next; // Pointer to next shape, or NULL if last element. +} NSVGshape; + +typedef struct NSVGimage +{ + float width; // Width of the image. + float height; // Height of the image. + NSVGshape* shapes; // Linked list of shapes in the image. +} NSVGimage; + +// Parses SVG file from a file, returns SVG image as paths. +NSVGimage* nsvgParseFromFile(const char* filename, const char* units, float dpi); + +// Parses SVG file from a null terminated string, returns SVG image as paths. +// Important note: changes the string. +NSVGimage* nsvgParse(char* input, const char* units, float dpi); + +// Duplicates a path. +NSVGpath* nsvgDuplicatePath(NSVGpath* p); + +// Deletes an image. +void nsvgDelete(NSVGimage* image); + +#ifndef NANOSVG_CPLUSPLUS +#ifdef __cplusplus +} +#endif +#endif + +#ifdef NANOSVG_IMPLEMENTATION + +#include +#include +#include +#include + +#define NSVG_PI (3.14159265358979323846264338327f) +#define NSVG_KAPPA90 (0.5522847493f) // Length proportional to radius of a cubic bezier handle for 90deg arcs. + +#define NSVG_ALIGN_MIN 0 +#define NSVG_ALIGN_MID 1 +#define NSVG_ALIGN_MAX 2 +#define NSVG_ALIGN_NONE 0 +#define NSVG_ALIGN_MEET 1 +#define NSVG_ALIGN_SLICE 2 + +#define NSVG_NOTUSED(v) do { (void)(1 ? (void)0 : ( (void)(v) ) ); } while(0) +#define NSVG_RGB(r, g, b) (((unsigned int)r) | ((unsigned int)g << 8) | ((unsigned int)b << 16)) + +#ifdef _MSC_VER + #pragma warning (disable: 4996) // Switch off security warnings + #pragma warning (disable: 4100) // Switch off unreferenced formal parameter warnings + #ifdef __cplusplus + #define NSVG_INLINE inline + #else + #define NSVG_INLINE + #endif +#else + #define NSVG_INLINE inline +#endif + + +static int nsvg__isspace(char c) +{ + return strchr(" \t\n\v\f\r", c) != 0; +} + +static int nsvg__isdigit(char c) +{ + return c >= '0' && c <= '9'; +} + +static NSVG_INLINE float nsvg__minf(float a, float b) { return a < b ? a : b; } +static NSVG_INLINE float nsvg__maxf(float a, float b) { return a > b ? a : b; } + + +// Simple XML parser + +#define NSVG_XML_TAG 1 +#define NSVG_XML_CONTENT 2 +#define NSVG_XML_MAX_ATTRIBS 256 + +static void nsvg__parseContent(char* s, + void (*contentCb)(void* ud, const char* s), + void* ud) +{ + // Trim start white spaces + while (*s && nsvg__isspace(*s)) s++; + if (!*s) return; + + if (contentCb) + (*contentCb)(ud, s); +} + +static void nsvg__parseElement(char* s, + void (*startelCb)(void* ud, const char* el, const char** attr), + void (*endelCb)(void* ud, const char* el), + void* ud) +{ + const char* attr[NSVG_XML_MAX_ATTRIBS]; + int nattr = 0; + char* name; + int start = 0; + int end = 0; + char quote; + + // Skip white space after the '<' + while (*s && nsvg__isspace(*s)) s++; + + // Check if the tag is end tag + if (*s == '/') { + s++; + end = 1; + } else { + start = 1; + } + + // Skip comments, data and preprocessor stuff. + if (!*s || *s == '?' || *s == '!') + return; + + // Get tag name + name = s; + while (*s && !nsvg__isspace(*s)) s++; + if (*s) { *s++ = '\0'; } + + // Get attribs + while (!end && *s && nattr < NSVG_XML_MAX_ATTRIBS-3) { + char* name = NULL; + char* value = NULL; + + // Skip white space before the attrib name + while (*s && nsvg__isspace(*s)) s++; + if (!*s) break; + if (*s == '/') { + end = 1; + break; + } + name = s; + // Find end of the attrib name. + while (*s && !nsvg__isspace(*s) && *s != '=') s++; + if (*s) { *s++ = '\0'; } + // Skip until the beginning of the value. + while (*s && *s != '\"' && *s != '\'') s++; + if (!*s) break; + quote = *s; + s++; + // Store value and find the end of it. + value = s; + while (*s && *s != quote) s++; + if (*s) { *s++ = '\0'; } + + // Store only well formed attributes + if (name && value) { + attr[nattr++] = name; + attr[nattr++] = value; + } + } + + // List terminator + attr[nattr++] = 0; + attr[nattr++] = 0; + + // Call callbacks. + if (start && startelCb) + (*startelCb)(ud, name, attr); + if (end && endelCb) + (*endelCb)(ud, name); +} + +int nsvg__parseXML(char* input, + void (*startelCb)(void* ud, const char* el, const char** attr), + void (*endelCb)(void* ud, const char* el), + void (*contentCb)(void* ud, const char* s), + void* ud) +{ + char* s = input; + char* mark = s; + int state = NSVG_XML_CONTENT; + while (*s) { + if (*s == '<' && state == NSVG_XML_CONTENT) { + // Start of a tag + *s++ = '\0'; + nsvg__parseContent(mark, contentCb, ud); + mark = s; + state = NSVG_XML_TAG; + } else if (*s == '>' && state == NSVG_XML_TAG) { + // Start of a content or new tag. + *s++ = '\0'; + nsvg__parseElement(mark, startelCb, endelCb, ud); + mark = s; + state = NSVG_XML_CONTENT; + } else { + s++; + } + } + + return 1; +} + + +/* Simple SVG parser. */ + +#define NSVG_MAX_ATTR 128 + +enum NSVGgradientUnits { + NSVG_USER_SPACE = 0, + NSVG_OBJECT_SPACE = 1 +}; + +#define NSVG_MAX_DASHES 8 +#define NSVG_MAX_CLASSES 32 + +enum NSVGunits { + NSVG_UNITS_USER, + NSVG_UNITS_PX, + NSVG_UNITS_PT, + NSVG_UNITS_PC, + NSVG_UNITS_MM, + NSVG_UNITS_CM, + NSVG_UNITS_IN, + NSVG_UNITS_PERCENT, + NSVG_UNITS_EM, + NSVG_UNITS_EX +}; + +typedef struct NSVGcoordinate { + float value; + int units; +} NSVGcoordinate; + +typedef struct NSVGlinearData { + NSVGcoordinate x1, y1, x2, y2; +} NSVGlinearData; + +typedef struct NSVGradialData { + NSVGcoordinate cx, cy, r, fx, fy; +} NSVGradialData; + +typedef struct NSVGgradientData +{ + char id[64]; + char ref[64]; + signed char type; + union { + NSVGlinearData linear; + NSVGradialData radial; + }; + char spread; + char units; + float xform[6]; + int nstops; + NSVGgradientStop* stops; + struct NSVGgradientData* next; +} NSVGgradientData; + +typedef struct NSVGattrib +{ + char id[64]; + float xform[6]; + unsigned int fillColor; + unsigned int strokeColor; + float opacity; + float fillOpacity; + float strokeOpacity; + char fillGradient[64]; + char strokeGradient[64]; + float strokeWidth; + float strokeDashOffset; + float strokeDashArray[NSVG_MAX_DASHES]; + int strokeDashCount; + char strokeLineJoin; + char strokeLineCap; + float miterLimit; + char fillRule; + float fontSize; + unsigned int stopColor; + float stopOpacity; + float stopOffset; + char hasFill; + char hasStroke; + char visible; + unsigned char paintOrder; +} NSVGattrib; + +typedef struct NSVGstyleDeclaration +{ + char* className; + char* propertiesText; + struct NSVGstyleDeclaration* next; +} NSVGstyleDeclaration; + +typedef struct NSVGparser +{ + NSVGattrib attr[NSVG_MAX_ATTR]; + int attrHead; + float* pts; + int npts; + int cpts; + NSVGpath* plist; + NSVGimage* image; + NSVGstyleDeclaration* styles; + NSVGgradientData* gradients; + NSVGshape* shapesTail; + float viewMinx, viewMiny, viewWidth, viewHeight; + int alignX, alignY, alignType; + float dpi; + char pathFlag; + char defsFlag; + char styleFlag; +} NSVGparser; + +static void nsvg__xformIdentity(float* t) +{ + t[0] = 1.0f; t[1] = 0.0f; + t[2] = 0.0f; t[3] = 1.0f; + t[4] = 0.0f; t[5] = 0.0f; +} + +static void nsvg__xformSetTranslation(float* t, float tx, float ty) +{ + t[0] = 1.0f; t[1] = 0.0f; + t[2] = 0.0f; t[3] = 1.0f; + t[4] = tx; t[5] = ty; +} + +static void nsvg__xformSetScale(float* t, float sx, float sy) +{ + t[0] = sx; t[1] = 0.0f; + t[2] = 0.0f; t[3] = sy; + t[4] = 0.0f; t[5] = 0.0f; +} + +static void nsvg__xformSetSkewX(float* t, float a) +{ + t[0] = 1.0f; t[1] = 0.0f; + t[2] = tanf(a); t[3] = 1.0f; + t[4] = 0.0f; t[5] = 0.0f; +} + +static void nsvg__xformSetSkewY(float* t, float a) +{ + t[0] = 1.0f; t[1] = tanf(a); + t[2] = 0.0f; t[3] = 1.0f; + t[4] = 0.0f; t[5] = 0.0f; +} + +static void nsvg__xformSetRotation(float* t, float a) +{ + float cs = cosf(a), sn = sinf(a); + t[0] = cs; t[1] = sn; + t[2] = -sn; t[3] = cs; + t[4] = 0.0f; t[5] = 0.0f; +} + +static void nsvg__xformMultiply(float* t, float* s) +{ + float t0 = t[0] * s[0] + t[1] * s[2]; + float t2 = t[2] * s[0] + t[3] * s[2]; + float t4 = t[4] * s[0] + t[5] * s[2] + s[4]; + t[1] = t[0] * s[1] + t[1] * s[3]; + t[3] = t[2] * s[1] + t[3] * s[3]; + t[5] = t[4] * s[1] + t[5] * s[3] + s[5]; + t[0] = t0; + t[2] = t2; + t[4] = t4; +} + +static void nsvg__xformInverse(float* inv, float* t) +{ + double invdet, det = (double)t[0] * t[3] - (double)t[2] * t[1]; + if (det > -1e-6 && det < 1e-6) { + nsvg__xformIdentity(t); + return; + } + invdet = 1.0 / det; + inv[0] = (float)(t[3] * invdet); + inv[2] = (float)(-t[2] * invdet); + inv[4] = (float)(((double)t[2] * t[5] - (double)t[3] * t[4]) * invdet); + inv[1] = (float)(-t[1] * invdet); + inv[3] = (float)(t[0] * invdet); + inv[5] = (float)(((double)t[1] * t[4] - (double)t[0] * t[5]) * invdet); +} + +static void nsvg__xformPremultiply(float* t, float* s) +{ + float s2[6]; + memcpy(s2, s, sizeof(float)*6); + nsvg__xformMultiply(s2, t); + memcpy(t, s2, sizeof(float)*6); +} + +static void nsvg__xformPoint(float* dx, float* dy, float x, float y, float* t) +{ + *dx = x*t[0] + y*t[2] + t[4]; + *dy = x*t[1] + y*t[3] + t[5]; +} + +static void nsvg__xformVec(float* dx, float* dy, float x, float y, float* t) +{ + *dx = x*t[0] + y*t[2]; + *dy = x*t[1] + y*t[3]; +} + +#define NSVG_EPSILON (1e-12) + +static int nsvg__ptInBounds(float* pt, float* bounds) +{ + return pt[0] >= bounds[0] && pt[0] <= bounds[2] && pt[1] >= bounds[1] && pt[1] <= bounds[3]; +} + + +static double nsvg__evalBezier(double t, double p0, double p1, double p2, double p3) +{ + double it = 1.0-t; + return it*it*it*p0 + 3.0*it*it*t*p1 + 3.0*it*t*t*p2 + t*t*t*p3; +} + +static void nsvg__curveBounds(float* bounds, float* curve) +{ + int i, j, count; + double roots[2], a, b, c, b2ac, t, v; + float* v0 = &curve[0]; + float* v1 = &curve[2]; + float* v2 = &curve[4]; + float* v3 = &curve[6]; + + // Start the bounding box by end points + bounds[0] = nsvg__minf(v0[0], v3[0]); + bounds[1] = nsvg__minf(v0[1], v3[1]); + bounds[2] = nsvg__maxf(v0[0], v3[0]); + bounds[3] = nsvg__maxf(v0[1], v3[1]); + + // Bezier curve fits inside the convex hull of it's control points. + // If control points are inside the bounds, we're done. + if (nsvg__ptInBounds(v1, bounds) && nsvg__ptInBounds(v2, bounds)) + return; + + // Add bezier curve inflection points in X and Y. + for (i = 0; i < 2; i++) { + a = -3.0 * v0[i] + 9.0 * v1[i] - 9.0 * v2[i] + 3.0 * v3[i]; + b = 6.0 * v0[i] - 12.0 * v1[i] + 6.0 * v2[i]; + c = 3.0 * v1[i] - 3.0 * v0[i]; + count = 0; + if (fabs(a) < NSVG_EPSILON) { + if (fabs(b) > NSVG_EPSILON) { + t = -c / b; + if (t > NSVG_EPSILON && t < 1.0-NSVG_EPSILON) + roots[count++] = t; + } + } else { + b2ac = b*b - 4.0*c*a; + if (b2ac > NSVG_EPSILON) { + t = (-b + sqrt(b2ac)) / (2.0 * a); + if (t > NSVG_EPSILON && t < 1.0-NSVG_EPSILON) + roots[count++] = t; + t = (-b - sqrt(b2ac)) / (2.0 * a); + if (t > NSVG_EPSILON && t < 1.0-NSVG_EPSILON) + roots[count++] = t; + } + } + for (j = 0; j < count; j++) { + v = nsvg__evalBezier(roots[j], v0[i], v1[i], v2[i], v3[i]); + bounds[0+i] = nsvg__minf(bounds[0+i], (float)v); + bounds[2+i] = nsvg__maxf(bounds[2+i], (float)v); + } + } +} + +static unsigned char nsvg__encodePaintOrder(enum NSVGpaintOrder a, enum NSVGpaintOrder b, enum NSVGpaintOrder c) { + return (a & 0x03) | ((b & 0x03) << 2) | ((c & 0x03) << 4); +} + +static NSVGparser* nsvg__createParser(void) +{ + NSVGparser* p; + p = (NSVGparser*)malloc(sizeof(NSVGparser)); + if (p == NULL) goto error; + memset(p, 0, sizeof(NSVGparser)); + + p->image = (NSVGimage*)malloc(sizeof(NSVGimage)); + if (p->image == NULL) goto error; + memset(p->image, 0, sizeof(NSVGimage)); + + // Init style + nsvg__xformIdentity(p->attr[0].xform); + memset(p->attr[0].id, 0, sizeof p->attr[0].id); + p->attr[0].fillColor = NSVG_RGB(0,0,0); + p->attr[0].strokeColor = NSVG_RGB(0,0,0); + p->attr[0].opacity = 1; + p->attr[0].fillOpacity = 1; + p->attr[0].strokeOpacity = 1; + p->attr[0].stopOpacity = 1; + p->attr[0].strokeWidth = 1; + p->attr[0].strokeLineJoin = NSVG_JOIN_MITER; + p->attr[0].strokeLineCap = NSVG_CAP_BUTT; + p->attr[0].miterLimit = 4; + p->attr[0].fillRule = NSVG_FILLRULE_NONZERO; + p->attr[0].hasFill = 1; + p->attr[0].visible = 1; + p->attr[0].paintOrder = nsvg__encodePaintOrder(NSVG_PAINT_FILL, NSVG_PAINT_STROKE, NSVG_PAINT_MARKERS); + + return p; + +error: + if (p) { + if (p->image) free(p->image); + free(p); + } + return NULL; +} +static void nsvg__deleteStyles(NSVGstyleDeclaration* style) { + while (style) { + NSVGstyleDeclaration* next = style->next; + free(style->className); + free(style->propertiesText); + free(style); + style = next; + } +} + +static void nsvg__deletePaths(NSVGpath* path) +{ + while (path) { + NSVGpath *next = path->next; + if (path->pts != NULL) + free(path->pts); + free(path); + path = next; + } +} + +static void nsvg__deletePaint(NSVGpaint* paint) +{ + if (paint->type == NSVG_PAINT_LINEAR_GRADIENT || paint->type == NSVG_PAINT_RADIAL_GRADIENT) + free(paint->gradient); +} + +static void nsvg__deleteGradientData(NSVGgradientData* grad) +{ + NSVGgradientData* next; + while (grad != NULL) { + next = grad->next; + free(grad->stops); + free(grad); + grad = next; + } +} + +static void nsvg__deleteParser(NSVGparser* p) +{ + if (p != NULL) { + nsvg__deleteStyles(p->styles); + nsvg__deletePaths(p->plist); + nsvg__deleteGradientData(p->gradients); + nsvgDelete(p->image); + free(p->pts); + free(p); + } +} + +static void nsvg__resetPath(NSVGparser* p) +{ + p->npts = 0; +} + +static void nsvg__addPoint(NSVGparser* p, float x, float y) +{ + if (p->npts+1 > p->cpts) { + p->cpts = p->cpts ? p->cpts*2 : 8; + p->pts = (float*)realloc(p->pts, p->cpts*2*sizeof(float)); + if (!p->pts) return; + } + p->pts[p->npts*2+0] = x; + p->pts[p->npts*2+1] = y; + p->npts++; +} + +static void nsvg__moveTo(NSVGparser* p, float x, float y) +{ + if (p->npts > 0) { + p->pts[(p->npts-1)*2+0] = x; + p->pts[(p->npts-1)*2+1] = y; + } else { + nsvg__addPoint(p, x, y); + } +} + +static void nsvg__lineTo(NSVGparser* p, float x, float y) +{ + float px,py, dx,dy; + if (p->npts > 0) { + px = p->pts[(p->npts-1)*2+0]; + py = p->pts[(p->npts-1)*2+1]; + dx = x - px; + dy = y - py; + nsvg__addPoint(p, px + dx/3.0f, py + dy/3.0f); + nsvg__addPoint(p, x - dx/3.0f, y - dy/3.0f); + nsvg__addPoint(p, x, y); + } +} + +static void nsvg__cubicBezTo(NSVGparser* p, float cpx1, float cpy1, float cpx2, float cpy2, float x, float y) +{ + if (p->npts > 0) { + nsvg__addPoint(p, cpx1, cpy1); + nsvg__addPoint(p, cpx2, cpy2); + nsvg__addPoint(p, x, y); + } +} + +static NSVGattrib* nsvg__getAttr(NSVGparser* p) +{ + return &p->attr[p->attrHead]; +} + +static void nsvg__pushAttr(NSVGparser* p) +{ + if (p->attrHead < NSVG_MAX_ATTR-1) { + p->attrHead++; + memcpy(&p->attr[p->attrHead], &p->attr[p->attrHead-1], sizeof(NSVGattrib)); + } +} + +static void nsvg__popAttr(NSVGparser* p) +{ + if (p->attrHead > 0) + p->attrHead--; +} + +static float nsvg__actualOrigX(NSVGparser* p) +{ + return p->viewMinx; +} + +static float nsvg__actualOrigY(NSVGparser* p) +{ + return p->viewMiny; +} + +static float nsvg__actualWidth(NSVGparser* p) +{ + return p->viewWidth; +} + +static float nsvg__actualHeight(NSVGparser* p) +{ + return p->viewHeight; +} + +static float nsvg__actualLength(NSVGparser* p) +{ + float w = nsvg__actualWidth(p), h = nsvg__actualHeight(p); + return sqrtf(w*w + h*h) / sqrtf(2.0f); +} + +static float nsvg__convertToPixels(NSVGparser* p, NSVGcoordinate c, float orig, float length) +{ + NSVGattrib* attr = nsvg__getAttr(p); + switch (c.units) { + case NSVG_UNITS_USER: return c.value; + case NSVG_UNITS_PX: return c.value; + case NSVG_UNITS_PT: return c.value / 72.0f * p->dpi; + case NSVG_UNITS_PC: return c.value / 6.0f * p->dpi; + case NSVG_UNITS_MM: return c.value / 25.4f * p->dpi; + case NSVG_UNITS_CM: return c.value / 2.54f * p->dpi; + case NSVG_UNITS_IN: return c.value * p->dpi; + case NSVG_UNITS_EM: return c.value * attr->fontSize; + case NSVG_UNITS_EX: return c.value * attr->fontSize * 0.52f; // x-height of Helvetica. + case NSVG_UNITS_PERCENT: return orig + c.value / 100.0f * length; + default: return c.value; + } + return c.value; +} + +static NSVGgradientData* nsvg__findGradientData(NSVGparser* p, const char* id) +{ + NSVGgradientData* grad = p->gradients; + if (id == NULL || *id == '\0') + return NULL; + while (grad != NULL) { + if (strcmp(grad->id, id) == 0) + return grad; + grad = grad->next; + } + return NULL; +} + +static NSVGgradient* nsvg__createGradient(NSVGparser* p, const char* id, const float* localBounds, float *xform, signed char* paintType) +{ + NSVGgradientData* data = NULL; + NSVGgradientData* ref = NULL; + NSVGgradientStop* stops = NULL; + NSVGgradient* grad; + float ox, oy, sw, sh, sl; + int nstops = 0; + int refIter; + + data = nsvg__findGradientData(p, id); + if (data == NULL) return NULL; + + // TODO: use ref to fill in all unset values too. + ref = data; + refIter = 0; + while (ref != NULL) { + NSVGgradientData* nextRef = NULL; + if (stops == NULL && ref->stops != NULL) { + stops = ref->stops; + nstops = ref->nstops; + break; + } + nextRef = nsvg__findGradientData(p, ref->ref); + if (nextRef == ref) break; // prevent infite loops on malformed data + ref = nextRef; + refIter++; + if (refIter > 32) break; // prevent infite loops on malformed data + } + if (stops == NULL) return NULL; + + grad = (NSVGgradient*)malloc(sizeof(NSVGgradient) + sizeof(NSVGgradientStop)*(nstops-1)); + if (grad == NULL) return NULL; + + // The shape width and height. + if (data->units == NSVG_OBJECT_SPACE) { + ox = localBounds[0]; + oy = localBounds[1]; + sw = localBounds[2] - localBounds[0]; + sh = localBounds[3] - localBounds[1]; + } else { + ox = nsvg__actualOrigX(p); + oy = nsvg__actualOrigY(p); + sw = nsvg__actualWidth(p); + sh = nsvg__actualHeight(p); + } + sl = sqrtf(sw*sw + sh*sh) / sqrtf(2.0f); + + if (data->type == NSVG_PAINT_LINEAR_GRADIENT) { + float x1, y1, x2, y2, dx, dy; + x1 = nsvg__convertToPixels(p, data->linear.x1, ox, sw); + y1 = nsvg__convertToPixels(p, data->linear.y1, oy, sh); + x2 = nsvg__convertToPixels(p, data->linear.x2, ox, sw); + y2 = nsvg__convertToPixels(p, data->linear.y2, oy, sh); + // Calculate transform aligned to the line + dx = x2 - x1; + dy = y2 - y1; + grad->xform[0] = dy; grad->xform[1] = -dx; + grad->xform[2] = dx; grad->xform[3] = dy; + grad->xform[4] = x1; grad->xform[5] = y1; + } else { + float cx, cy, fx, fy, r; + cx = nsvg__convertToPixels(p, data->radial.cx, ox, sw); + cy = nsvg__convertToPixels(p, data->radial.cy, oy, sh); + fx = nsvg__convertToPixels(p, data->radial.fx, ox, sw); + fy = nsvg__convertToPixels(p, data->radial.fy, oy, sh); + r = nsvg__convertToPixels(p, data->radial.r, 0, sl); + // Calculate transform aligned to the circle + grad->xform[0] = r; grad->xform[1] = 0; + grad->xform[2] = 0; grad->xform[3] = r; + grad->xform[4] = cx; grad->xform[5] = cy; + grad->fx = fx / r; + grad->fy = fy / r; + } + + nsvg__xformMultiply(grad->xform, data->xform); + nsvg__xformMultiply(grad->xform, xform); + + grad->spread = data->spread; + memcpy(grad->stops, stops, nstops*sizeof(NSVGgradientStop)); + grad->nstops = nstops; + + *paintType = data->type; + + return grad; +} + +static float nsvg__getAverageScale(float* t) +{ + float sx = sqrtf(t[0]*t[0] + t[2]*t[2]); + float sy = sqrtf(t[1]*t[1] + t[3]*t[3]); + return (sx + sy) * 0.5f; +} + +static void nsvg__getLocalBounds(float* bounds, NSVGshape *shape, float* xform) +{ + NSVGpath* path; + float curve[4*2], curveBounds[4]; + int i, first = 1; + for (path = shape->paths; path != NULL; path = path->next) { + nsvg__xformPoint(&curve[0], &curve[1], path->pts[0], path->pts[1], xform); + for (i = 0; i < path->npts-1; i += 3) { + nsvg__xformPoint(&curve[2], &curve[3], path->pts[(i+1)*2], path->pts[(i+1)*2+1], xform); + nsvg__xformPoint(&curve[4], &curve[5], path->pts[(i+2)*2], path->pts[(i+2)*2+1], xform); + nsvg__xformPoint(&curve[6], &curve[7], path->pts[(i+3)*2], path->pts[(i+3)*2+1], xform); + nsvg__curveBounds(curveBounds, curve); + if (first) { + bounds[0] = curveBounds[0]; + bounds[1] = curveBounds[1]; + bounds[2] = curveBounds[2]; + bounds[3] = curveBounds[3]; + first = 0; + } else { + bounds[0] = nsvg__minf(bounds[0], curveBounds[0]); + bounds[1] = nsvg__minf(bounds[1], curveBounds[1]); + bounds[2] = nsvg__maxf(bounds[2], curveBounds[2]); + bounds[3] = nsvg__maxf(bounds[3], curveBounds[3]); + } + curve[0] = curve[6]; + curve[1] = curve[7]; + } + } +} + +static void nsvg__addShape(NSVGparser* p) +{ + NSVGattrib* attr = nsvg__getAttr(p); + float scale = 1.0f; + NSVGshape* shape; + NSVGpath* path; + int i; + + if (p->plist == NULL) + return; + + shape = (NSVGshape*)malloc(sizeof(NSVGshape)); + if (shape == NULL) goto error; + memset(shape, 0, sizeof(NSVGshape)); + + memcpy(shape->id, attr->id, sizeof shape->id); + memcpy(shape->fillGradient, attr->fillGradient, sizeof shape->fillGradient); + memcpy(shape->strokeGradient, attr->strokeGradient, sizeof shape->strokeGradient); + memcpy(shape->xform, attr->xform, sizeof shape->xform); + scale = nsvg__getAverageScale(attr->xform); + shape->strokeWidth = attr->strokeWidth * scale; + shape->strokeDashOffset = attr->strokeDashOffset * scale; + shape->strokeDashCount = (char)attr->strokeDashCount; + for (i = 0; i < attr->strokeDashCount; i++) + shape->strokeDashArray[i] = attr->strokeDashArray[i] * scale; + shape->strokeLineJoin = attr->strokeLineJoin; + shape->strokeLineCap = attr->strokeLineCap; + shape->miterLimit = attr->miterLimit; + shape->fillRule = attr->fillRule; + shape->opacity = attr->opacity; + shape->paintOrder = attr->paintOrder; + + shape->paths = p->plist; + p->plist = NULL; + + // Calculate shape bounds + shape->bounds[0] = shape->paths->bounds[0]; + shape->bounds[1] = shape->paths->bounds[1]; + shape->bounds[2] = shape->paths->bounds[2]; + shape->bounds[3] = shape->paths->bounds[3]; + for (path = shape->paths->next; path != NULL; path = path->next) { + shape->bounds[0] = nsvg__minf(shape->bounds[0], path->bounds[0]); + shape->bounds[1] = nsvg__minf(shape->bounds[1], path->bounds[1]); + shape->bounds[2] = nsvg__maxf(shape->bounds[2], path->bounds[2]); + shape->bounds[3] = nsvg__maxf(shape->bounds[3], path->bounds[3]); + } + + // Set fill + if (attr->hasFill == 0) { + shape->fill.type = NSVG_PAINT_NONE; + } else if (attr->hasFill == 1) { + shape->fill.type = NSVG_PAINT_COLOR; + shape->fill.color = attr->fillColor; + shape->fill.color |= (unsigned int)(attr->fillOpacity*255) << 24; + } else if (attr->hasFill == 2) { + shape->fill.type = NSVG_PAINT_UNDEF; + } + + // Set stroke + if (attr->hasStroke == 0) { + shape->stroke.type = NSVG_PAINT_NONE; + } else if (attr->hasStroke == 1) { + shape->stroke.type = NSVG_PAINT_COLOR; + shape->stroke.color = attr->strokeColor; + shape->stroke.color |= (unsigned int)(attr->strokeOpacity*255) << 24; + } else if (attr->hasStroke == 2) { + shape->stroke.type = NSVG_PAINT_UNDEF; + } + + // Set flags + shape->flags = (attr->visible ? NSVG_FLAGS_VISIBLE : 0x00); + + // Add to tail + if (p->image->shapes == NULL) + p->image->shapes = shape; + else + p->shapesTail->next = shape; + p->shapesTail = shape; + + return; + +error: + if (shape) free(shape); +} + +static void nsvg__addPath(NSVGparser* p, char closed) +{ + NSVGattrib* attr = nsvg__getAttr(p); + NSVGpath* path = NULL; + float bounds[4]; + float* curve; + int i; + + if (p->npts < 4) + return; + + if (closed) + nsvg__lineTo(p, p->pts[0], p->pts[1]); + + // Expect 1 + N*3 points (N = number of cubic bezier segments). + if ((p->npts % 3) != 1) + return; + + path = (NSVGpath*)malloc(sizeof(NSVGpath)); + if (path == NULL) goto error; + memset(path, 0, sizeof(NSVGpath)); + + path->pts = (float*)malloc(p->npts*2*sizeof(float)); + if (path->pts == NULL) goto error; + path->closed = closed; + path->npts = p->npts; + + // Transform path. + for (i = 0; i < p->npts; ++i) + nsvg__xformPoint(&path->pts[i*2], &path->pts[i*2+1], p->pts[i*2], p->pts[i*2+1], attr->xform); + + // Find bounds + for (i = 0; i < path->npts-1; i += 3) { + curve = &path->pts[i*2]; + nsvg__curveBounds(bounds, curve); + if (i == 0) { + path->bounds[0] = bounds[0]; + path->bounds[1] = bounds[1]; + path->bounds[2] = bounds[2]; + path->bounds[3] = bounds[3]; + } else { + path->bounds[0] = nsvg__minf(path->bounds[0], bounds[0]); + path->bounds[1] = nsvg__minf(path->bounds[1], bounds[1]); + path->bounds[2] = nsvg__maxf(path->bounds[2], bounds[2]); + path->bounds[3] = nsvg__maxf(path->bounds[3], bounds[3]); + } + } + + path->next = p->plist; + p->plist = path; + + return; + +error: + if (path != NULL) { + if (path->pts != NULL) free(path->pts); + free(path); + } +} + +// We roll our own string to float because the std library one uses locale and messes things up. +static double nsvg__atof(const char* s) +{ + char* cur = (char*)s; + char* end = NULL; + double res = 0.0, sign = 1.0; + long long intPart = 0, fracPart = 0; + char hasIntPart = 0, hasFracPart = 0; + + // Parse optional sign + if (*cur == '+') { + cur++; + } else if (*cur == '-') { + sign = -1; + cur++; + } + + // Parse integer part + if (nsvg__isdigit(*cur)) { + // Parse digit sequence + intPart = strtoll(cur, &end, 10); + if (cur != end) { + res = (double)intPart; + hasIntPart = 1; + cur = end; + } + } + + // Parse fractional part. + if (*cur == '.') { + cur++; // Skip '.' + if (nsvg__isdigit(*cur)) { + // Parse digit sequence + fracPart = strtoll(cur, &end, 10); + if (cur != end) { + res += (double)fracPart / pow(10.0, (double)(end - cur)); + hasFracPart = 1; + cur = end; + } + } + } + + // A valid number should have integer or fractional part. + if (!hasIntPart && !hasFracPart) + return 0.0; + + // Parse optional exponent + if (*cur == 'e' || *cur == 'E') { + long expPart = 0; + cur++; // skip 'E' + expPart = strtol(cur, &end, 10); // Parse digit sequence with sign + if (cur != end) { + res *= pow(10.0, (double)expPart); + } + } + + return res * sign; +} + + +static const char* nsvg__parseNumber(const char* s, char* it, const int size) +{ + const int last = size-1; + int i = 0; + + // sign + if (*s == '-' || *s == '+') { + if (i < last) it[i++] = *s; + s++; + } + // integer part + while (*s && nsvg__isdigit(*s)) { + if (i < last) it[i++] = *s; + s++; + } + if (*s == '.') { + // decimal point + if (i < last) it[i++] = *s; + s++; + // fraction part + while (*s && nsvg__isdigit(*s)) { + if (i < last) it[i++] = *s; + s++; + } + } + // exponent + if ((*s == 'e' || *s == 'E') && (s[1] != 'm' && s[1] != 'x')) { + if (i < last) it[i++] = *s; + s++; + if (*s == '-' || *s == '+') { + if (i < last) it[i++] = *s; + s++; + } + while (*s && nsvg__isdigit(*s)) { + if (i < last) it[i++] = *s; + s++; + } + } + it[i] = '\0'; + + return s; +} + +static const char* nsvg__getNextPathItemWhenArcFlag(const char* s, char* it) +{ + it[0] = '\0'; + while (*s && (nsvg__isspace(*s) || *s == ',')) s++; + if (!*s) return s; + if (*s == '0' || *s == '1') { + it[0] = *s++; + it[1] = '\0'; + return s; + } + return s; +} + +static const char* nsvg__getNextPathItem(const char* s, char* it) +{ + it[0] = '\0'; + // Skip white spaces and commas + while (*s && (nsvg__isspace(*s) || *s == ',')) s++; + if (!*s) return s; + if (*s == '-' || *s == '+' || *s == '.' || nsvg__isdigit(*s)) { + s = nsvg__parseNumber(s, it, 64); + } else { + // Parse command + it[0] = *s++; + it[1] = '\0'; + return s; + } + + return s; +} + +static unsigned int nsvg__parseColorHex(const char* str) +{ + unsigned int r=0, g=0, b=0; + if (sscanf(str, "#%2x%2x%2x", &r, &g, &b) == 3 ) // 2 digit hex + return NSVG_RGB(r, g, b); + if (sscanf(str, "#%1x%1x%1x", &r, &g, &b) == 3 ) // 1 digit hex, e.g. #abc -> 0xccbbaa + return NSVG_RGB(r*17, g*17, b*17); // same effect as (r<<4|r), (g<<4|g), .. + return NSVG_RGB(128, 128, 128); +} + +// Parse rgb color. The pointer 'str' must point at "rgb(" (4+ characters). +// This function returns gray (rgb(128, 128, 128) == '#808080') on parse errors +// for backwards compatibility. Note: other image viewers return black instead. + +static unsigned int nsvg__parseColorRGB(const char* str) +{ + int i; + unsigned int rgbi[3]; + float rgbf[3]; + // try decimal integers first + if (sscanf(str, "rgb(%u, %u, %u)", &rgbi[0], &rgbi[1], &rgbi[2]) != 3) { + // integers failed, try percent values (float, locale independent) + const char delimiter[3] = {',', ',', ')'}; + str += 4; // skip "rgb(" + for (i = 0; i < 3; i++) { + while (*str && (nsvg__isspace(*str))) str++; // skip leading spaces + if (*str == '+') str++; // skip '+' (don't allow '-') + if (!*str) break; + rgbf[i] = nsvg__atof(str); + + // Note 1: it would be great if nsvg__atof() returned how many + // bytes it consumed but it doesn't. We need to skip the number, + // the '%' character, spaces, and the delimiter ',' or ')'. + + // Note 2: The following code does not allow values like "33.%", + // i.e. a decimal point w/o fractional part, but this is consistent + // with other image viewers, e.g. firefox, chrome, eog, gimp. + + while (*str && nsvg__isdigit(*str)) str++; // skip integer part + if (*str == '.') { + str++; + if (!nsvg__isdigit(*str)) break; // error: no digit after '.' + while (*str && nsvg__isdigit(*str)) str++; // skip fractional part + } + if (*str == '%') str++; else break; + while (*str && nsvg__isspace(*str)) str++; + if (*str == delimiter[i]) str++; + else break; + } + if (i == 3) { + rgbi[0] = roundf(rgbf[0] * 2.55f); + rgbi[1] = roundf(rgbf[1] * 2.55f); + rgbi[2] = roundf(rgbf[2] * 2.55f); + } else { + rgbi[0] = rgbi[1] = rgbi[2] = 128; + } + } + // clip values as the CSS spec requires + for (i = 0; i < 3; i++) { + if (rgbi[i] > 255) rgbi[i] = 255; + } + return NSVG_RGB(rgbi[0], rgbi[1], rgbi[2]); +} + +typedef struct NSVGNamedColor { + const char* name; + unsigned int color; +} NSVGNamedColor; + +NSVGNamedColor nsvg__colors[] = { + + { "red", NSVG_RGB(255, 0, 0) }, + { "green", NSVG_RGB( 0, 128, 0) }, + { "blue", NSVG_RGB( 0, 0, 255) }, + { "yellow", NSVG_RGB(255, 255, 0) }, + { "cyan", NSVG_RGB( 0, 255, 255) }, + { "magenta", NSVG_RGB(255, 0, 255) }, + { "black", NSVG_RGB( 0, 0, 0) }, + { "grey", NSVG_RGB(128, 128, 128) }, + { "gray", NSVG_RGB(128, 128, 128) }, + { "white", NSVG_RGB(255, 255, 255) }, + +#ifdef NANOSVG_ALL_COLOR_KEYWORDS + { "aliceblue", NSVG_RGB(240, 248, 255) }, + { "antiquewhite", NSVG_RGB(250, 235, 215) }, + { "aqua", NSVG_RGB( 0, 255, 255) }, + { "aquamarine", NSVG_RGB(127, 255, 212) }, + { "azure", NSVG_RGB(240, 255, 255) }, + { "beige", NSVG_RGB(245, 245, 220) }, + { "bisque", NSVG_RGB(255, 228, 196) }, + { "blanchedalmond", NSVG_RGB(255, 235, 205) }, + { "blueviolet", NSVG_RGB(138, 43, 226) }, + { "brown", NSVG_RGB(165, 42, 42) }, + { "burlywood", NSVG_RGB(222, 184, 135) }, + { "cadetblue", NSVG_RGB( 95, 158, 160) }, + { "chartreuse", NSVG_RGB(127, 255, 0) }, + { "chocolate", NSVG_RGB(210, 105, 30) }, + { "coral", NSVG_RGB(255, 127, 80) }, + { "cornflowerblue", NSVG_RGB(100, 149, 237) }, + { "cornsilk", NSVG_RGB(255, 248, 220) }, + { "crimson", NSVG_RGB(220, 20, 60) }, + { "darkblue", NSVG_RGB( 0, 0, 139) }, + { "darkcyan", NSVG_RGB( 0, 139, 139) }, + { "darkgoldenrod", NSVG_RGB(184, 134, 11) }, + { "darkgray", NSVG_RGB(169, 169, 169) }, + { "darkgreen", NSVG_RGB( 0, 100, 0) }, + { "darkgrey", NSVG_RGB(169, 169, 169) }, + { "darkkhaki", NSVG_RGB(189, 183, 107) }, + { "darkmagenta", NSVG_RGB(139, 0, 139) }, + { "darkolivegreen", NSVG_RGB( 85, 107, 47) }, + { "darkorange", NSVG_RGB(255, 140, 0) }, + { "darkorchid", NSVG_RGB(153, 50, 204) }, + { "darkred", NSVG_RGB(139, 0, 0) }, + { "darksalmon", NSVG_RGB(233, 150, 122) }, + { "darkseagreen", NSVG_RGB(143, 188, 143) }, + { "darkslateblue", NSVG_RGB( 72, 61, 139) }, + { "darkslategray", NSVG_RGB( 47, 79, 79) }, + { "darkslategrey", NSVG_RGB( 47, 79, 79) }, + { "darkturquoise", NSVG_RGB( 0, 206, 209) }, + { "darkviolet", NSVG_RGB(148, 0, 211) }, + { "deeppink", NSVG_RGB(255, 20, 147) }, + { "deepskyblue", NSVG_RGB( 0, 191, 255) }, + { "dimgray", NSVG_RGB(105, 105, 105) }, + { "dimgrey", NSVG_RGB(105, 105, 105) }, + { "dodgerblue", NSVG_RGB( 30, 144, 255) }, + { "firebrick", NSVG_RGB(178, 34, 34) }, + { "floralwhite", NSVG_RGB(255, 250, 240) }, + { "forestgreen", NSVG_RGB( 34, 139, 34) }, + { "fuchsia", NSVG_RGB(255, 0, 255) }, + { "gainsboro", NSVG_RGB(220, 220, 220) }, + { "ghostwhite", NSVG_RGB(248, 248, 255) }, + { "gold", NSVG_RGB(255, 215, 0) }, + { "goldenrod", NSVG_RGB(218, 165, 32) }, + { "greenyellow", NSVG_RGB(173, 255, 47) }, + { "honeydew", NSVG_RGB(240, 255, 240) }, + { "hotpink", NSVG_RGB(255, 105, 180) }, + { "indianred", NSVG_RGB(205, 92, 92) }, + { "indigo", NSVG_RGB( 75, 0, 130) }, + { "ivory", NSVG_RGB(255, 255, 240) }, + { "khaki", NSVG_RGB(240, 230, 140) }, + { "lavender", NSVG_RGB(230, 230, 250) }, + { "lavenderblush", NSVG_RGB(255, 240, 245) }, + { "lawngreen", NSVG_RGB(124, 252, 0) }, + { "lemonchiffon", NSVG_RGB(255, 250, 205) }, + { "lightblue", NSVG_RGB(173, 216, 230) }, + { "lightcoral", NSVG_RGB(240, 128, 128) }, + { "lightcyan", NSVG_RGB(224, 255, 255) }, + { "lightgoldenrodyellow", NSVG_RGB(250, 250, 210) }, + { "lightgray", NSVG_RGB(211, 211, 211) }, + { "lightgreen", NSVG_RGB(144, 238, 144) }, + { "lightgrey", NSVG_RGB(211, 211, 211) }, + { "lightpink", NSVG_RGB(255, 182, 193) }, + { "lightsalmon", NSVG_RGB(255, 160, 122) }, + { "lightseagreen", NSVG_RGB( 32, 178, 170) }, + { "lightskyblue", NSVG_RGB(135, 206, 250) }, + { "lightslategray", NSVG_RGB(119, 136, 153) }, + { "lightslategrey", NSVG_RGB(119, 136, 153) }, + { "lightsteelblue", NSVG_RGB(176, 196, 222) }, + { "lightyellow", NSVG_RGB(255, 255, 224) }, + { "lime", NSVG_RGB( 0, 255, 0) }, + { "limegreen", NSVG_RGB( 50, 205, 50) }, + { "linen", NSVG_RGB(250, 240, 230) }, + { "maroon", NSVG_RGB(128, 0, 0) }, + { "mediumaquamarine", NSVG_RGB(102, 205, 170) }, + { "mediumblue", NSVG_RGB( 0, 0, 205) }, + { "mediumorchid", NSVG_RGB(186, 85, 211) }, + { "mediumpurple", NSVG_RGB(147, 112, 219) }, + { "mediumseagreen", NSVG_RGB( 60, 179, 113) }, + { "mediumslateblue", NSVG_RGB(123, 104, 238) }, + { "mediumspringgreen", NSVG_RGB( 0, 250, 154) }, + { "mediumturquoise", NSVG_RGB( 72, 209, 204) }, + { "mediumvioletred", NSVG_RGB(199, 21, 133) }, + { "midnightblue", NSVG_RGB( 25, 25, 112) }, + { "mintcream", NSVG_RGB(245, 255, 250) }, + { "mistyrose", NSVG_RGB(255, 228, 225) }, + { "moccasin", NSVG_RGB(255, 228, 181) }, + { "navajowhite", NSVG_RGB(255, 222, 173) }, + { "navy", NSVG_RGB( 0, 0, 128) }, + { "oldlace", NSVG_RGB(253, 245, 230) }, + { "olive", NSVG_RGB(128, 128, 0) }, + { "olivedrab", NSVG_RGB(107, 142, 35) }, + { "orange", NSVG_RGB(255, 165, 0) }, + { "orangered", NSVG_RGB(255, 69, 0) }, + { "orchid", NSVG_RGB(218, 112, 214) }, + { "palegoldenrod", NSVG_RGB(238, 232, 170) }, + { "palegreen", NSVG_RGB(152, 251, 152) }, + { "paleturquoise", NSVG_RGB(175, 238, 238) }, + { "palevioletred", NSVG_RGB(219, 112, 147) }, + { "papayawhip", NSVG_RGB(255, 239, 213) }, + { "peachpuff", NSVG_RGB(255, 218, 185) }, + { "peru", NSVG_RGB(205, 133, 63) }, + { "pink", NSVG_RGB(255, 192, 203) }, + { "plum", NSVG_RGB(221, 160, 221) }, + { "powderblue", NSVG_RGB(176, 224, 230) }, + { "purple", NSVG_RGB(128, 0, 128) }, + { "rosybrown", NSVG_RGB(188, 143, 143) }, + { "royalblue", NSVG_RGB( 65, 105, 225) }, + { "saddlebrown", NSVG_RGB(139, 69, 19) }, + { "salmon", NSVG_RGB(250, 128, 114) }, + { "sandybrown", NSVG_RGB(244, 164, 96) }, + { "seagreen", NSVG_RGB( 46, 139, 87) }, + { "seashell", NSVG_RGB(255, 245, 238) }, + { "sienna", NSVG_RGB(160, 82, 45) }, + { "silver", NSVG_RGB(192, 192, 192) }, + { "skyblue", NSVG_RGB(135, 206, 235) }, + { "slateblue", NSVG_RGB(106, 90, 205) }, + { "slategray", NSVG_RGB(112, 128, 144) }, + { "slategrey", NSVG_RGB(112, 128, 144) }, + { "snow", NSVG_RGB(255, 250, 250) }, + { "springgreen", NSVG_RGB( 0, 255, 127) }, + { "steelblue", NSVG_RGB( 70, 130, 180) }, + { "tan", NSVG_RGB(210, 180, 140) }, + { "teal", NSVG_RGB( 0, 128, 128) }, + { "thistle", NSVG_RGB(216, 191, 216) }, + { "tomato", NSVG_RGB(255, 99, 71) }, + { "turquoise", NSVG_RGB( 64, 224, 208) }, + { "violet", NSVG_RGB(238, 130, 238) }, + { "wheat", NSVG_RGB(245, 222, 179) }, + { "whitesmoke", NSVG_RGB(245, 245, 245) }, + { "yellowgreen", NSVG_RGB(154, 205, 50) }, +#endif +}; + +static unsigned int nsvg__parseColorName(const char* str) +{ + int i, ncolors = sizeof(nsvg__colors) / sizeof(NSVGNamedColor); + + for (i = 0; i < ncolors; i++) { + if (strcmp(nsvg__colors[i].name, str) == 0) { + return nsvg__colors[i].color; + } + } + + return NSVG_RGB(128, 128, 128); +} + +static unsigned int nsvg__parseColor(const char* str) +{ + size_t len = 0; + while(*str == ' ') ++str; + len = strlen(str); + if (len >= 1 && *str == '#') + return nsvg__parseColorHex(str); + else if (len >= 4 && str[0] == 'r' && str[1] == 'g' && str[2] == 'b' && str[3] == '(') + return nsvg__parseColorRGB(str); + return nsvg__parseColorName(str); +} + +static float nsvg__parseOpacity(const char* str) +{ + float val = nsvg__atof(str); + if (val < 0.0f) val = 0.0f; + if (val > 1.0f) val = 1.0f; + return val; +} + +static float nsvg__parseMiterLimit(const char* str) +{ + float val = nsvg__atof(str); + if (val < 0.0f) val = 0.0f; + return val; +} + +static int nsvg__parseUnits(const char* units) +{ + if (units[0] == 'p' && units[1] == 'x') + return NSVG_UNITS_PX; + else if (units[0] == 'p' && units[1] == 't') + return NSVG_UNITS_PT; + else if (units[0] == 'p' && units[1] == 'c') + return NSVG_UNITS_PC; + else if (units[0] == 'm' && units[1] == 'm') + return NSVG_UNITS_MM; + else if (units[0] == 'c' && units[1] == 'm') + return NSVG_UNITS_CM; + else if (units[0] == 'i' && units[1] == 'n') + return NSVG_UNITS_IN; + else if (units[0] == '%') + return NSVG_UNITS_PERCENT; + else if (units[0] == 'e' && units[1] == 'm') + return NSVG_UNITS_EM; + else if (units[0] == 'e' && units[1] == 'x') + return NSVG_UNITS_EX; + return NSVG_UNITS_USER; +} + +static int nsvg__isCoordinate(const char* s) +{ + // optional sign + if (*s == '-' || *s == '+') + s++; + // must have at least one digit, or start by a dot + return (nsvg__isdigit(*s) || *s == '.'); +} + +static NSVGcoordinate nsvg__parseCoordinateRaw(const char* str) +{ + NSVGcoordinate coord = {0, NSVG_UNITS_USER}; + char buf[64]; + coord.units = nsvg__parseUnits(nsvg__parseNumber(str, buf, 64)); + coord.value = nsvg__atof(buf); + return coord; +} + +static NSVGcoordinate nsvg__coord(float v, int units) +{ + NSVGcoordinate coord = {v, units}; + return coord; +} + +static float nsvg__parseCoordinate(NSVGparser* p, const char* str, float orig, float length) +{ + NSVGcoordinate coord = nsvg__parseCoordinateRaw(str); + return nsvg__convertToPixels(p, coord, orig, length); +} + +static int nsvg__parseTransformArgs(const char* str, float* args, int maxNa, int* na) +{ + const char* end; + const char* ptr; + char it[64]; + + *na = 0; + ptr = str; + while (*ptr && *ptr != '(') ++ptr; + if (*ptr == 0) + return 1; + end = ptr; + while (*end && *end != ')') ++end; + if (*end == 0) + return 1; + + while (ptr < end) { + if (*ptr == '-' || *ptr == '+' || *ptr == '.' || nsvg__isdigit(*ptr)) { + if (*na >= maxNa) return 0; + ptr = nsvg__parseNumber(ptr, it, 64); + args[(*na)++] = (float)nsvg__atof(it); + } else { + ++ptr; + } + } + return (int)(end - str); +} + + +static int nsvg__parseMatrix(float* xform, const char* str) +{ + float t[6]; + int na = 0; + int len = nsvg__parseTransformArgs(str, t, 6, &na); + if (na != 6) return len; + memcpy(xform, t, sizeof(float)*6); + return len; +} + +static int nsvg__parseTranslate(float* xform, const char* str) +{ + float args[2]; + float t[6]; + int na = 0; + int len = nsvg__parseTransformArgs(str, args, 2, &na); + if (na == 1) args[1] = 0.0; + + nsvg__xformSetTranslation(t, args[0], args[1]); + memcpy(xform, t, sizeof(float)*6); + return len; +} + +static int nsvg__parseScale(float* xform, const char* str) +{ + float args[2]; + int na = 0; + float t[6]; + int len = nsvg__parseTransformArgs(str, args, 2, &na); + if (na == 1) args[1] = args[0]; + nsvg__xformSetScale(t, args[0], args[1]); + memcpy(xform, t, sizeof(float)*6); + return len; +} + +static int nsvg__parseSkewX(float* xform, const char* str) +{ + float args[1]; + int na = 0; + float t[6]; + int len = nsvg__parseTransformArgs(str, args, 1, &na); + nsvg__xformSetSkewX(t, args[0]/180.0f*NSVG_PI); + memcpy(xform, t, sizeof(float)*6); + return len; +} + +static int nsvg__parseSkewY(float* xform, const char* str) +{ + float args[1]; + int na = 0; + float t[6]; + int len = nsvg__parseTransformArgs(str, args, 1, &na); + nsvg__xformSetSkewY(t, args[0]/180.0f*NSVG_PI); + memcpy(xform, t, sizeof(float)*6); + return len; +} + +static int nsvg__parseRotate(float* xform, const char* str) +{ + float args[3]; + int na = 0; + float m[6]; + float t[6]; + int len = nsvg__parseTransformArgs(str, args, 3, &na); + if (na == 1) + args[1] = args[2] = 0.0f; + nsvg__xformIdentity(m); + + if (na > 1) { + nsvg__xformSetTranslation(t, -args[1], -args[2]); + nsvg__xformMultiply(m, t); + } + + nsvg__xformSetRotation(t, args[0]/180.0f*NSVG_PI); + nsvg__xformMultiply(m, t); + + if (na > 1) { + nsvg__xformSetTranslation(t, args[1], args[2]); + nsvg__xformMultiply(m, t); + } + + memcpy(xform, m, sizeof(float)*6); + + return len; +} + +static void nsvg__parseTransform(float* xform, const char* str) +{ + float t[6]; + int len; + nsvg__xformIdentity(xform); + while (*str) + { + if (strncmp(str, "matrix", 6) == 0) + len = nsvg__parseMatrix(t, str); + else if (strncmp(str, "translate", 9) == 0) + len = nsvg__parseTranslate(t, str); + else if (strncmp(str, "scale", 5) == 0) + len = nsvg__parseScale(t, str); + else if (strncmp(str, "rotate", 6) == 0) + len = nsvg__parseRotate(t, str); + else if (strncmp(str, "skewX", 5) == 0) + len = nsvg__parseSkewX(t, str); + else if (strncmp(str, "skewY", 5) == 0) + len = nsvg__parseSkewY(t, str); + else{ + ++str; + continue; + } + if (len != 0) { + str += len; + } else { + ++str; + continue; + } + + nsvg__xformPremultiply(xform, t); + } +} + +static void nsvg__parseUrl(char* id, const char* str) +{ + int i = 0; + str += 4; // "url("; + if (*str && *str == '#') + str++; + while (i < 63 && *str && *str != ')') { + id[i] = *str++; + i++; + } + id[i] = '\0'; +} + +static char nsvg__parseLineCap(const char* str) +{ + if (strcmp(str, "butt") == 0) + return NSVG_CAP_BUTT; + else if (strcmp(str, "round") == 0) + return NSVG_CAP_ROUND; + else if (strcmp(str, "square") == 0) + return NSVG_CAP_SQUARE; + // TODO: handle inherit. + return NSVG_CAP_BUTT; +} + +static char nsvg__parseLineJoin(const char* str) +{ + if (strcmp(str, "miter") == 0) + return NSVG_JOIN_MITER; + else if (strcmp(str, "round") == 0) + return NSVG_JOIN_ROUND; + else if (strcmp(str, "bevel") == 0) + return NSVG_JOIN_BEVEL; + // TODO: handle inherit. + return NSVG_JOIN_MITER; +} + +static char nsvg__parseFillRule(const char* str) +{ + if (strcmp(str, "nonzero") == 0) + return NSVG_FILLRULE_NONZERO; + else if (strcmp(str, "evenodd") == 0) + return NSVG_FILLRULE_EVENODD; + // TODO: handle inherit. + return NSVG_FILLRULE_NONZERO; +} + +static unsigned char nsvg__parsePaintOrder(const char* str) +{ + if (strcmp(str, "normal") == 0 || strcmp(str, "fill stroke markers") == 0) + return nsvg__encodePaintOrder(NSVG_PAINT_FILL, NSVG_PAINT_STROKE, NSVG_PAINT_MARKERS); + else if (strcmp(str, "fill markers stroke") == 0) + return nsvg__encodePaintOrder(NSVG_PAINT_FILL, NSVG_PAINT_MARKERS, NSVG_PAINT_STROKE); + else if (strcmp(str, "markers fill stroke") == 0) + return nsvg__encodePaintOrder(NSVG_PAINT_MARKERS, NSVG_PAINT_FILL, NSVG_PAINT_STROKE); + else if (strcmp(str, "markers stroke fill") == 0) + return nsvg__encodePaintOrder(NSVG_PAINT_MARKERS, NSVG_PAINT_STROKE, NSVG_PAINT_FILL); + else if (strcmp(str, "stroke fill markers") == 0) + return nsvg__encodePaintOrder(NSVG_PAINT_STROKE, NSVG_PAINT_FILL, NSVG_PAINT_MARKERS); + else if (strcmp(str, "stroke markers fill") == 0) + return nsvg__encodePaintOrder(NSVG_PAINT_STROKE, NSVG_PAINT_MARKERS, NSVG_PAINT_FILL); + // TODO: handle inherit. + return nsvg__encodePaintOrder(NSVG_PAINT_FILL, NSVG_PAINT_STROKE, NSVG_PAINT_MARKERS); +} + +static const char* nsvg__getNextDashItem(const char* s, char* it) +{ + int n = 0; + it[0] = '\0'; + // Skip white spaces and commas + while (*s && (nsvg__isspace(*s) || *s == ',')) s++; + // Advance until whitespace, comma or end. + while (*s && (!nsvg__isspace(*s) && *s != ',')) { + if (n < 63) + it[n++] = *s; + s++; + } + it[n++] = '\0'; + return s; +} + +static int nsvg__parseStrokeDashArray(NSVGparser* p, const char* str, float* strokeDashArray) +{ + char item[64]; + int count = 0, i; + float sum = 0.0f; + + // Handle "none" + if (str[0] == 'n') + return 0; + + // Parse dashes + while (*str) { + str = nsvg__getNextDashItem(str, item); + if (!*item) break; + if (count < NSVG_MAX_DASHES) + strokeDashArray[count++] = fabsf(nsvg__parseCoordinate(p, item, 0.0f, nsvg__actualLength(p))); + } + + for (i = 0; i < count; i++) + sum += strokeDashArray[i]; + if (sum <= 1e-6f) + count = 0; + + return count; +} + +static void nsvg__parseStyle(NSVGparser* p, const char* str); + +// Apply any matching class styles for a "class" attribute value. We support only simple class +// selectors. The class attribute may contain multiple space-separated class names. +static void nsvg__applyClassStyles(NSVGparser* p, const char* value) +{ + const char* cur = value; + while (*cur) { + const char* classStart; + size_t classLen; + NSVGstyleDeclaration* style; + + while (*cur && nsvg__isspace(*cur)) + cur++; + if (!*cur) + break; + + classStart = cur; + while (*cur && !nsvg__isspace(*cur)) + cur++; + classLen = (size_t)(cur - classStart); + + for (style = p->styles; style != NULL; style = style->next) { + if (strncmp(style->className, classStart, classLen) == 0 && style->className[classLen] == '\0') { + nsvg__parseStyle(p, style->propertiesText); + } + } + } +} + +static int nsvg__parseAttr(NSVGparser* p, const char* name, const char* value) +{ + float xform[6]; + NSVGattrib* attr = nsvg__getAttr(p); + if (!attr) return 0; + + if (strcmp(name, "style") == 0) { + nsvg__parseStyle(p, value); + } else if (strcmp(name, "display") == 0) { + if (strcmp(value, "none") == 0) + attr->visible = 0; + // Don't reset ->visible on display:inline, one display:none hides the whole subtree + + } else if (strcmp(name, "fill") == 0) { + if (strcmp(value, "none") == 0) { + attr->hasFill = 0; + } else if (strncmp(value, "url(", 4) == 0) { + attr->hasFill = 2; + nsvg__parseUrl(attr->fillGradient, value); + } else { + attr->hasFill = 1; + attr->fillColor = nsvg__parseColor(value); + } + } else if (strcmp(name, "opacity") == 0) { + attr->opacity = nsvg__parseOpacity(value); + } else if (strcmp(name, "fill-opacity") == 0) { + attr->fillOpacity = nsvg__parseOpacity(value); + } else if (strcmp(name, "stroke") == 0) { + if (strcmp(value, "none") == 0) { + attr->hasStroke = 0; + } else if (strncmp(value, "url(", 4) == 0) { + attr->hasStroke = 2; + nsvg__parseUrl(attr->strokeGradient, value); + } else { + attr->hasStroke = 1; + attr->strokeColor = nsvg__parseColor(value); + } + } else if (strcmp(name, "stroke-width") == 0) { + attr->strokeWidth = nsvg__parseCoordinate(p, value, 0.0f, nsvg__actualLength(p)); + } else if (strcmp(name, "stroke-dasharray") == 0) { + attr->strokeDashCount = nsvg__parseStrokeDashArray(p, value, attr->strokeDashArray); + } else if (strcmp(name, "stroke-dashoffset") == 0) { + attr->strokeDashOffset = nsvg__parseCoordinate(p, value, 0.0f, nsvg__actualLength(p)); + } else if (strcmp(name, "stroke-opacity") == 0) { + attr->strokeOpacity = nsvg__parseOpacity(value); + } else if (strcmp(name, "stroke-linecap") == 0) { + attr->strokeLineCap = nsvg__parseLineCap(value); + } else if (strcmp(name, "stroke-linejoin") == 0) { + attr->strokeLineJoin = nsvg__parseLineJoin(value); + } else if (strcmp(name, "stroke-miterlimit") == 0) { + attr->miterLimit = nsvg__parseMiterLimit(value); + } else if (strcmp(name, "fill-rule") == 0) { + attr->fillRule = nsvg__parseFillRule(value); + } else if (strcmp(name, "font-size") == 0) { + attr->fontSize = nsvg__parseCoordinate(p, value, 0.0f, nsvg__actualLength(p)); + } else if (strcmp(name, "transform") == 0) { + nsvg__parseTransform(xform, value); + nsvg__xformPremultiply(attr->xform, xform); + } else if (strcmp(name, "stop-color") == 0) { + attr->stopColor = nsvg__parseColor(value); + } else if (strcmp(name, "stop-opacity") == 0) { + attr->stopOpacity = nsvg__parseOpacity(value); + } else if (strcmp(name, "offset") == 0) { + attr->stopOffset = nsvg__parseCoordinate(p, value, 0.0f, 1.0f); + } else if (strcmp(name, "paint-order") == 0) { + attr->paintOrder = nsvg__parsePaintOrder(value); + } else if (strcmp(name, "id") == 0) { + strncpy(attr->id, value, 63); + attr->id[63] = '\0'; + } else if (strcmp(name, "class") == 0) { + nsvg__applyClassStyles(p, value); + } + else { + return 0; + } + return 1; +} + +static int nsvg__parseNameValue(NSVGparser* p, const char* start, const char* end) +{ + const char* str; + const char* val; + char name[512]; + char value[512]; + int n; + + str = start; + while (str < end && *str != ':') ++str; + + val = str; + + // Right Trim + while (str > start && (*str == ':' || nsvg__isspace(*str))) --str; + ++str; + + n = (int)(str - start); + if (n > 511) n = 511; + if (n) memcpy(name, start, n); + name[n] = 0; + + while (val < end && (*val == ':' || nsvg__isspace(*val))) ++val; + + n = (int)(end - val); + if (n > 511) n = 511; + if (n) memcpy(value, val, n); + value[n] = 0; + + return nsvg__parseAttr(p, name, value); +} + +static void nsvg__parseStyle(NSVGparser* p, const char* str) +{ + const char* start; + const char* end; + + while (*str) { + // Left Trim + while(*str && nsvg__isspace(*str)) ++str; + start = str; + while(*str && *str != ';') ++str; + end = str; + + // Right Trim + while (end > start && (*end == ';' || nsvg__isspace(*end))) --end; + ++end; + + nsvg__parseNameValue(p, start, end); + if (*str) ++str; + } +} + +static void nsvg__parseAttribs(NSVGparser* p, const char** attr) +{ + int i; + for (i = 0; attr[i]; i += 2) + { + if (strcmp(attr[i], "style") == 0) + nsvg__parseStyle(p, attr[i + 1]); + else + nsvg__parseAttr(p, attr[i], attr[i + 1]); + } +} + +static int nsvg__getArgsPerElement(char cmd) +{ + switch (cmd) { + case 'v': + case 'V': + case 'h': + case 'H': + return 1; + case 'm': + case 'M': + case 'l': + case 'L': + case 't': + case 'T': + return 2; + case 'q': + case 'Q': + case 's': + case 'S': + return 4; + case 'c': + case 'C': + return 6; + case 'a': + case 'A': + return 7; + case 'z': + case 'Z': + return 0; + } + return -1; +} + +static void nsvg__pathMoveTo(NSVGparser* p, float* cpx, float* cpy, float* args, int rel) +{ + if (rel) { + *cpx += args[0]; + *cpy += args[1]; + } else { + *cpx = args[0]; + *cpy = args[1]; + } + nsvg__moveTo(p, *cpx, *cpy); +} + +static void nsvg__pathLineTo(NSVGparser* p, float* cpx, float* cpy, float* args, int rel) +{ + if (rel) { + *cpx += args[0]; + *cpy += args[1]; + } else { + *cpx = args[0]; + *cpy = args[1]; + } + nsvg__lineTo(p, *cpx, *cpy); +} + +static void nsvg__pathHLineTo(NSVGparser* p, float* cpx, float* cpy, float* args, int rel) +{ + if (rel) + *cpx += args[0]; + else + *cpx = args[0]; + nsvg__lineTo(p, *cpx, *cpy); +} + +static void nsvg__pathVLineTo(NSVGparser* p, float* cpx, float* cpy, float* args, int rel) +{ + if (rel) + *cpy += args[0]; + else + *cpy = args[0]; + nsvg__lineTo(p, *cpx, *cpy); +} + +static void nsvg__pathCubicBezTo(NSVGparser* p, float* cpx, float* cpy, + float* cpx2, float* cpy2, float* args, int rel) +{ + float x2, y2, cx1, cy1, cx2, cy2; + + if (rel) { + cx1 = *cpx + args[0]; + cy1 = *cpy + args[1]; + cx2 = *cpx + args[2]; + cy2 = *cpy + args[3]; + x2 = *cpx + args[4]; + y2 = *cpy + args[5]; + } else { + cx1 = args[0]; + cy1 = args[1]; + cx2 = args[2]; + cy2 = args[3]; + x2 = args[4]; + y2 = args[5]; + } + + nsvg__cubicBezTo(p, cx1,cy1, cx2,cy2, x2,y2); + + *cpx2 = cx2; + *cpy2 = cy2; + *cpx = x2; + *cpy = y2; +} + +static void nsvg__pathCubicBezShortTo(NSVGparser* p, float* cpx, float* cpy, + float* cpx2, float* cpy2, float* args, int rel) +{ + float x1, y1, x2, y2, cx1, cy1, cx2, cy2; + + x1 = *cpx; + y1 = *cpy; + if (rel) { + cx2 = *cpx + args[0]; + cy2 = *cpy + args[1]; + x2 = *cpx + args[2]; + y2 = *cpy + args[3]; + } else { + cx2 = args[0]; + cy2 = args[1]; + x2 = args[2]; + y2 = args[3]; + } + + cx1 = 2*x1 - *cpx2; + cy1 = 2*y1 - *cpy2; + + nsvg__cubicBezTo(p, cx1,cy1, cx2,cy2, x2,y2); + + *cpx2 = cx2; + *cpy2 = cy2; + *cpx = x2; + *cpy = y2; +} + +static void nsvg__pathQuadBezTo(NSVGparser* p, float* cpx, float* cpy, + float* cpx2, float* cpy2, float* args, int rel) +{ + float x1, y1, x2, y2, cx, cy; + float cx1, cy1, cx2, cy2; + + x1 = *cpx; + y1 = *cpy; + if (rel) { + cx = *cpx + args[0]; + cy = *cpy + args[1]; + x2 = *cpx + args[2]; + y2 = *cpy + args[3]; + } else { + cx = args[0]; + cy = args[1]; + x2 = args[2]; + y2 = args[3]; + } + + // Convert to cubic bezier + cx1 = x1 + 2.0f/3.0f*(cx - x1); + cy1 = y1 + 2.0f/3.0f*(cy - y1); + cx2 = x2 + 2.0f/3.0f*(cx - x2); + cy2 = y2 + 2.0f/3.0f*(cy - y2); + + nsvg__cubicBezTo(p, cx1,cy1, cx2,cy2, x2,y2); + + *cpx2 = cx; + *cpy2 = cy; + *cpx = x2; + *cpy = y2; +} + +static void nsvg__pathQuadBezShortTo(NSVGparser* p, float* cpx, float* cpy, + float* cpx2, float* cpy2, float* args, int rel) +{ + float x1, y1, x2, y2, cx, cy; + float cx1, cy1, cx2, cy2; + + x1 = *cpx; + y1 = *cpy; + if (rel) { + x2 = *cpx + args[0]; + y2 = *cpy + args[1]; + } else { + x2 = args[0]; + y2 = args[1]; + } + + cx = 2*x1 - *cpx2; + cy = 2*y1 - *cpy2; + + // Convert to cubix bezier + cx1 = x1 + 2.0f/3.0f*(cx - x1); + cy1 = y1 + 2.0f/3.0f*(cy - y1); + cx2 = x2 + 2.0f/3.0f*(cx - x2); + cy2 = y2 + 2.0f/3.0f*(cy - y2); + + nsvg__cubicBezTo(p, cx1,cy1, cx2,cy2, x2,y2); + + *cpx2 = cx; + *cpy2 = cy; + *cpx = x2; + *cpy = y2; +} + +static float nsvg__sqr(float x) { return x*x; } +static float nsvg__vmag(float x, float y) { return sqrtf(x*x + y*y); } + +static float nsvg__vecrat(float ux, float uy, float vx, float vy) +{ + return (ux*vx + uy*vy) / (nsvg__vmag(ux,uy) * nsvg__vmag(vx,vy)); +} + +static float nsvg__vecang(float ux, float uy, float vx, float vy) +{ + float r = nsvg__vecrat(ux,uy, vx,vy); + if (r < -1.0f) r = -1.0f; + if (r > 1.0f) r = 1.0f; + return ((ux*vy < uy*vx) ? -1.0f : 1.0f) * acosf(r); +} + +static void nsvg__pathArcTo(NSVGparser* p, float* cpx, float* cpy, float* args, int rel) +{ + // Ported from canvg (https://code.google.com/p/canvg/) + float rx, ry, rotx; + float x1, y1, x2, y2, cx, cy, dx, dy, d; + float x1p, y1p, cxp, cyp, s, sa, sb; + float ux, uy, vx, vy, a1, da; + float x, y, tanx, tany, a, px = 0, py = 0, ptanx = 0, ptany = 0, t[6]; + float sinrx, cosrx; + int fa, fs; + int i, ndivs; + float hda, kappa; + + rx = fabsf(args[0]); // y radius + ry = fabsf(args[1]); // x radius + rotx = args[2] / 180.0f * NSVG_PI; // x rotation angle + fa = fabsf(args[3]) > 1e-6 ? 1 : 0; // Large arc + fs = fabsf(args[4]) > 1e-6 ? 1 : 0; // Sweep direction + x1 = *cpx; // start point + y1 = *cpy; + if (rel) { // end point + x2 = *cpx + args[5]; + y2 = *cpy + args[6]; + } else { + x2 = args[5]; + y2 = args[6]; + } + + dx = x1 - x2; + dy = y1 - y2; + d = sqrtf(dx*dx + dy*dy); + if (d < 1e-6f || rx < 1e-6f || ry < 1e-6f) { + // The arc degenerates to a line + nsvg__lineTo(p, x2, y2); + *cpx = x2; + *cpy = y2; + return; + } + + sinrx = sinf(rotx); + cosrx = cosf(rotx); + + // Convert to center point parameterization. + // http://www.w3.org/TR/SVG11/implnote.html#ArcImplementationNotes + // 1) Compute x1', y1' + x1p = cosrx * dx / 2.0f + sinrx * dy / 2.0f; + y1p = -sinrx * dx / 2.0f + cosrx * dy / 2.0f; + d = nsvg__sqr(x1p)/nsvg__sqr(rx) + nsvg__sqr(y1p)/nsvg__sqr(ry); + if (d > 1) { + d = sqrtf(d); + rx *= d; + ry *= d; + } + // 2) Compute cx', cy' + s = 0.0f; + sa = nsvg__sqr(rx)*nsvg__sqr(ry) - nsvg__sqr(rx)*nsvg__sqr(y1p) - nsvg__sqr(ry)*nsvg__sqr(x1p); + sb = nsvg__sqr(rx)*nsvg__sqr(y1p) + nsvg__sqr(ry)*nsvg__sqr(x1p); + if (sa < 0.0f) sa = 0.0f; + if (sb > 0.0f) + s = sqrtf(sa / sb); + if (fa == fs) + s = -s; + cxp = s * rx * y1p / ry; + cyp = s * -ry * x1p / rx; + + // 3) Compute cx,cy from cx',cy' + cx = (x1 + x2)/2.0f + cosrx*cxp - sinrx*cyp; + cy = (y1 + y2)/2.0f + sinrx*cxp + cosrx*cyp; + + // 4) Calculate theta1, and delta theta. + ux = (x1p - cxp) / rx; + uy = (y1p - cyp) / ry; + vx = (-x1p - cxp) / rx; + vy = (-y1p - cyp) / ry; + a1 = nsvg__vecang(1.0f,0.0f, ux,uy); // Initial angle + da = nsvg__vecang(ux,uy, vx,vy); // Delta angle + +// if (vecrat(ux,uy,vx,vy) <= -1.0f) da = NSVG_PI; +// if (vecrat(ux,uy,vx,vy) >= 1.0f) da = 0; + + if (fs == 0 && da > 0) + da -= 2 * NSVG_PI; + else if (fs == 1 && da < 0) + da += 2 * NSVG_PI; + + // Approximate the arc using cubic spline segments. + t[0] = cosrx; t[1] = sinrx; + t[2] = -sinrx; t[3] = cosrx; + t[4] = cx; t[5] = cy; + + // Split arc into max 90 degree segments. + // The loop assumes an iteration per end point (including start and end), this +1. + ndivs = (int)(fabsf(da) / (NSVG_PI*0.5f) + 1.0f); + hda = (da / (float)ndivs) / 2.0f; + // Fix for ticket #179: division by 0: avoid cotangens around 0 (infinite) + if ((hda < 1e-3f) && (hda > -1e-3f)) + hda *= 0.5f; + else + hda = (1.0f - cosf(hda)) / sinf(hda); + kappa = fabsf(4.0f / 3.0f * hda); + if (da < 0.0f) + kappa = -kappa; + + for (i = 0; i <= ndivs; i++) { + a = a1 + da * ((float)i/(float)ndivs); + dx = cosf(a); + dy = sinf(a); + nsvg__xformPoint(&x, &y, dx*rx, dy*ry, t); // position + nsvg__xformVec(&tanx, &tany, -dy*rx * kappa, dx*ry * kappa, t); // tangent + if (i > 0) + nsvg__cubicBezTo(p, px+ptanx,py+ptany, x-tanx, y-tany, x, y); + px = x; + py = y; + ptanx = tanx; + ptany = tany; + } + + *cpx = x2; + *cpy = y2; +} + +static void nsvg__parsePath(NSVGparser* p, const char** attr) +{ + const char* s = NULL; + char cmd = '\0'; + float args[10]; + int nargs; + int rargs = 0; + char initPoint; + float cpx, cpy, cpx2, cpy2; + const char* tmp[4]; + char closedFlag; + int i; + char item[64]; + + for (i = 0; attr[i]; i += 2) { + if (strcmp(attr[i], "d") == 0) { + s = attr[i + 1]; + } else { + tmp[0] = attr[i]; + tmp[1] = attr[i + 1]; + tmp[2] = 0; + tmp[3] = 0; + nsvg__parseAttribs(p, tmp); + } + } + + if (s) { + nsvg__resetPath(p); + cpx = 0; cpy = 0; + cpx2 = 0; cpy2 = 0; + initPoint = 0; + closedFlag = 0; + nargs = 0; + + while (*s) { + item[0] = '\0'; + if ((cmd == 'A' || cmd == 'a') && (nargs == 3 || nargs == 4)) + s = nsvg__getNextPathItemWhenArcFlag(s, item); + if (!*item) + s = nsvg__getNextPathItem(s, item); + if (!*item) break; + if (cmd != '\0' && nsvg__isCoordinate(item)) { + if (nargs < 10) + args[nargs++] = (float)nsvg__atof(item); + if (nargs >= rargs) { + switch (cmd) { + case 'm': + case 'M': + nsvg__pathMoveTo(p, &cpx, &cpy, args, cmd == 'm' ? 1 : 0); + // Moveto can be followed by multiple coordinate pairs, + // which should be treated as linetos. + cmd = (cmd == 'm') ? 'l' : 'L'; + rargs = nsvg__getArgsPerElement(cmd); + cpx2 = cpx; cpy2 = cpy; + initPoint = 1; + break; + case 'l': + case 'L': + nsvg__pathLineTo(p, &cpx, &cpy, args, cmd == 'l' ? 1 : 0); + cpx2 = cpx; cpy2 = cpy; + break; + case 'H': + case 'h': + nsvg__pathHLineTo(p, &cpx, &cpy, args, cmd == 'h' ? 1 : 0); + cpx2 = cpx; cpy2 = cpy; + break; + case 'V': + case 'v': + nsvg__pathVLineTo(p, &cpx, &cpy, args, cmd == 'v' ? 1 : 0); + cpx2 = cpx; cpy2 = cpy; + break; + case 'C': + case 'c': + nsvg__pathCubicBezTo(p, &cpx, &cpy, &cpx2, &cpy2, args, cmd == 'c' ? 1 : 0); + break; + case 'S': + case 's': + nsvg__pathCubicBezShortTo(p, &cpx, &cpy, &cpx2, &cpy2, args, cmd == 's' ? 1 : 0); + break; + case 'Q': + case 'q': + nsvg__pathQuadBezTo(p, &cpx, &cpy, &cpx2, &cpy2, args, cmd == 'q' ? 1 : 0); + break; + case 'T': + case 't': + nsvg__pathQuadBezShortTo(p, &cpx, &cpy, &cpx2, &cpy2, args, cmd == 't' ? 1 : 0); + break; + case 'A': + case 'a': + nsvg__pathArcTo(p, &cpx, &cpy, args, cmd == 'a' ? 1 : 0); + cpx2 = cpx; cpy2 = cpy; + break; + default: + if (nargs >= 2) { + cpx = args[nargs-2]; + cpy = args[nargs-1]; + cpx2 = cpx; cpy2 = cpy; + } + break; + } + nargs = 0; + } + } else { + cmd = item[0]; + if (cmd == 'M' || cmd == 'm') { + // Commit path. + if (p->npts > 0) + nsvg__addPath(p, closedFlag); + // Start new subpath. + nsvg__resetPath(p); + closedFlag = 0; + nargs = 0; + } else if (initPoint == 0) { + // Do not allow other commands until initial point has been set (moveTo called once). + cmd = '\0'; + } + if (cmd == 'Z' || cmd == 'z') { + closedFlag = 1; + // Commit path. + if (p->npts > 0) { + // Move current point to first point + cpx = p->pts[0]; + cpy = p->pts[1]; + cpx2 = cpx; cpy2 = cpy; + nsvg__addPath(p, closedFlag); + } + // Start new subpath. + nsvg__resetPath(p); + nsvg__moveTo(p, cpx, cpy); + closedFlag = 0; + nargs = 0; + } + rargs = nsvg__getArgsPerElement(cmd); + if (rargs == -1) { + // Command not recognized + cmd = '\0'; + rargs = 0; + } + } + } + // Commit path. + if (p->npts) + nsvg__addPath(p, closedFlag); + } + + nsvg__addShape(p); +} + +static void nsvg__parseRect(NSVGparser* p, const char** attr) +{ + float x = 0.0f; + float y = 0.0f; + float w = 0.0f; + float h = 0.0f; + float rx = -1.0f; // marks not set + float ry = -1.0f; + int i; + + for (i = 0; attr[i]; i += 2) { + if (!nsvg__parseAttr(p, attr[i], attr[i + 1])) { + if (strcmp(attr[i], "x") == 0) x = nsvg__parseCoordinate(p, attr[i+1], nsvg__actualOrigX(p), nsvg__actualWidth(p)); + if (strcmp(attr[i], "y") == 0) y = nsvg__parseCoordinate(p, attr[i+1], nsvg__actualOrigY(p), nsvg__actualHeight(p)); + if (strcmp(attr[i], "width") == 0) w = nsvg__parseCoordinate(p, attr[i+1], 0.0f, nsvg__actualWidth(p)); + if (strcmp(attr[i], "height") == 0) h = nsvg__parseCoordinate(p, attr[i+1], 0.0f, nsvg__actualHeight(p)); + if (strcmp(attr[i], "rx") == 0) rx = fabsf(nsvg__parseCoordinate(p, attr[i+1], 0.0f, nsvg__actualWidth(p))); + if (strcmp(attr[i], "ry") == 0) ry = fabsf(nsvg__parseCoordinate(p, attr[i+1], 0.0f, nsvg__actualHeight(p))); + } + } + + if (rx < 0.0f && ry > 0.0f) rx = ry; + if (ry < 0.0f && rx > 0.0f) ry = rx; + if (rx < 0.0f) rx = 0.0f; + if (ry < 0.0f) ry = 0.0f; + if (rx > w/2.0f) rx = w/2.0f; + if (ry > h/2.0f) ry = h/2.0f; + + if (w != 0.0f && h != 0.0f) { + nsvg__resetPath(p); + + if (rx < 0.00001f || ry < 0.0001f) { + nsvg__moveTo(p, x, y); + nsvg__lineTo(p, x+w, y); + nsvg__lineTo(p, x+w, y+h); + nsvg__lineTo(p, x, y+h); + } else { + // Rounded rectangle + nsvg__moveTo(p, x+rx, y); + nsvg__lineTo(p, x+w-rx, y); + nsvg__cubicBezTo(p, x+w-rx*(1-NSVG_KAPPA90), y, x+w, y+ry*(1-NSVG_KAPPA90), x+w, y+ry); + nsvg__lineTo(p, x+w, y+h-ry); + nsvg__cubicBezTo(p, x+w, y+h-ry*(1-NSVG_KAPPA90), x+w-rx*(1-NSVG_KAPPA90), y+h, x+w-rx, y+h); + nsvg__lineTo(p, x+rx, y+h); + nsvg__cubicBezTo(p, x+rx*(1-NSVG_KAPPA90), y+h, x, y+h-ry*(1-NSVG_KAPPA90), x, y+h-ry); + nsvg__lineTo(p, x, y+ry); + nsvg__cubicBezTo(p, x, y+ry*(1-NSVG_KAPPA90), x+rx*(1-NSVG_KAPPA90), y, x+rx, y); + } + + nsvg__addPath(p, 1); + + nsvg__addShape(p); + } +} + +static void nsvg__parseCircle(NSVGparser* p, const char** attr) +{ + float cx = 0.0f; + float cy = 0.0f; + float r = 0.0f; + int i; + + for (i = 0; attr[i]; i += 2) { + if (!nsvg__parseAttr(p, attr[i], attr[i + 1])) { + if (strcmp(attr[i], "cx") == 0) cx = nsvg__parseCoordinate(p, attr[i+1], nsvg__actualOrigX(p), nsvg__actualWidth(p)); + if (strcmp(attr[i], "cy") == 0) cy = nsvg__parseCoordinate(p, attr[i+1], nsvg__actualOrigY(p), nsvg__actualHeight(p)); + if (strcmp(attr[i], "r") == 0) r = fabsf(nsvg__parseCoordinate(p, attr[i+1], 0.0f, nsvg__actualLength(p))); + } + } + + if (r > 0.0f) { + nsvg__resetPath(p); + + nsvg__moveTo(p, cx+r, cy); + nsvg__cubicBezTo(p, cx+r, cy+r*NSVG_KAPPA90, cx+r*NSVG_KAPPA90, cy+r, cx, cy+r); + nsvg__cubicBezTo(p, cx-r*NSVG_KAPPA90, cy+r, cx-r, cy+r*NSVG_KAPPA90, cx-r, cy); + nsvg__cubicBezTo(p, cx-r, cy-r*NSVG_KAPPA90, cx-r*NSVG_KAPPA90, cy-r, cx, cy-r); + nsvg__cubicBezTo(p, cx+r*NSVG_KAPPA90, cy-r, cx+r, cy-r*NSVG_KAPPA90, cx+r, cy); + + nsvg__addPath(p, 1); + + nsvg__addShape(p); + } +} + +static void nsvg__parseEllipse(NSVGparser* p, const char** attr) +{ + float cx = 0.0f; + float cy = 0.0f; + float rx = 0.0f; + float ry = 0.0f; + int i; + + for (i = 0; attr[i]; i += 2) { + if (!nsvg__parseAttr(p, attr[i], attr[i + 1])) { + if (strcmp(attr[i], "cx") == 0) cx = nsvg__parseCoordinate(p, attr[i+1], nsvg__actualOrigX(p), nsvg__actualWidth(p)); + if (strcmp(attr[i], "cy") == 0) cy = nsvg__parseCoordinate(p, attr[i+1], nsvg__actualOrigY(p), nsvg__actualHeight(p)); + if (strcmp(attr[i], "rx") == 0) rx = fabsf(nsvg__parseCoordinate(p, attr[i+1], 0.0f, nsvg__actualWidth(p))); + if (strcmp(attr[i], "ry") == 0) ry = fabsf(nsvg__parseCoordinate(p, attr[i+1], 0.0f, nsvg__actualHeight(p))); + } + } + + if (rx > 0.0f && ry > 0.0f) { + + nsvg__resetPath(p); + + nsvg__moveTo(p, cx+rx, cy); + nsvg__cubicBezTo(p, cx+rx, cy+ry*NSVG_KAPPA90, cx+rx*NSVG_KAPPA90, cy+ry, cx, cy+ry); + nsvg__cubicBezTo(p, cx-rx*NSVG_KAPPA90, cy+ry, cx-rx, cy+ry*NSVG_KAPPA90, cx-rx, cy); + nsvg__cubicBezTo(p, cx-rx, cy-ry*NSVG_KAPPA90, cx-rx*NSVG_KAPPA90, cy-ry, cx, cy-ry); + nsvg__cubicBezTo(p, cx+rx*NSVG_KAPPA90, cy-ry, cx+rx, cy-ry*NSVG_KAPPA90, cx+rx, cy); + + nsvg__addPath(p, 1); + + nsvg__addShape(p); + } +} + +static void nsvg__parseLine(NSVGparser* p, const char** attr) +{ + float x1 = 0.0; + float y1 = 0.0; + float x2 = 0.0; + float y2 = 0.0; + int i; + + for (i = 0; attr[i]; i += 2) { + if (!nsvg__parseAttr(p, attr[i], attr[i + 1])) { + if (strcmp(attr[i], "x1") == 0) x1 = nsvg__parseCoordinate(p, attr[i + 1], nsvg__actualOrigX(p), nsvg__actualWidth(p)); + if (strcmp(attr[i], "y1") == 0) y1 = nsvg__parseCoordinate(p, attr[i + 1], nsvg__actualOrigY(p), nsvg__actualHeight(p)); + if (strcmp(attr[i], "x2") == 0) x2 = nsvg__parseCoordinate(p, attr[i + 1], nsvg__actualOrigX(p), nsvg__actualWidth(p)); + if (strcmp(attr[i], "y2") == 0) y2 = nsvg__parseCoordinate(p, attr[i + 1], nsvg__actualOrigY(p), nsvg__actualHeight(p)); + } + } + + nsvg__resetPath(p); + + nsvg__moveTo(p, x1, y1); + nsvg__lineTo(p, x2, y2); + + nsvg__addPath(p, 0); + + nsvg__addShape(p); +} + +static void nsvg__parsePoly(NSVGparser* p, const char** attr, int closeFlag) +{ + int i; + const char* s; + float args[2]; + int nargs, npts = 0; + char item[64]; + + nsvg__resetPath(p); + + for (i = 0; attr[i]; i += 2) { + if (!nsvg__parseAttr(p, attr[i], attr[i + 1])) { + if (strcmp(attr[i], "points") == 0) { + s = attr[i + 1]; + nargs = 0; + while (*s) { + s = nsvg__getNextPathItem(s, item); + args[nargs++] = (float)nsvg__atof(item); + if (nargs >= 2) { + if (npts == 0) + nsvg__moveTo(p, args[0], args[1]); + else + nsvg__lineTo(p, args[0], args[1]); + nargs = 0; + npts++; + } + } + } + } + } + + nsvg__addPath(p, (char)closeFlag); + + nsvg__addShape(p); +} + +static void nsvg__parseSVG(NSVGparser* p, const char** attr) +{ + int i; + for (i = 0; attr[i]; i += 2) { + if (!nsvg__parseAttr(p, attr[i], attr[i + 1])) { + if (strcmp(attr[i], "width") == 0) { + p->image->width = nsvg__parseCoordinate(p, attr[i + 1], 0.0f, 0.0f); + } else if (strcmp(attr[i], "height") == 0) { + p->image->height = nsvg__parseCoordinate(p, attr[i + 1], 0.0f, 0.0f); + } else if (strcmp(attr[i], "viewBox") == 0) { + const char *s = attr[i + 1]; + char buf[64]; + s = nsvg__parseNumber(s, buf, 64); + p->viewMinx = nsvg__atof(buf); + while (*s && (nsvg__isspace(*s) || *s == '%' || *s == ',')) s++; + if (!*s) return; + s = nsvg__parseNumber(s, buf, 64); + p->viewMiny = nsvg__atof(buf); + while (*s && (nsvg__isspace(*s) || *s == '%' || *s == ',')) s++; + if (!*s) return; + s = nsvg__parseNumber(s, buf, 64); + p->viewWidth = nsvg__atof(buf); + while (*s && (nsvg__isspace(*s) || *s == '%' || *s == ',')) s++; + if (!*s) return; + s = nsvg__parseNumber(s, buf, 64); + p->viewHeight = nsvg__atof(buf); + } else if (strcmp(attr[i], "preserveAspectRatio") == 0) { + if (strstr(attr[i + 1], "none") != 0) { + // No uniform scaling + p->alignType = NSVG_ALIGN_NONE; + } else { + // Parse X align + if (strstr(attr[i + 1], "xMin") != 0) + p->alignX = NSVG_ALIGN_MIN; + else if (strstr(attr[i + 1], "xMid") != 0) + p->alignX = NSVG_ALIGN_MID; + else if (strstr(attr[i + 1], "xMax") != 0) + p->alignX = NSVG_ALIGN_MAX; + // Parse X align + if (strstr(attr[i + 1], "yMin") != 0) + p->alignY = NSVG_ALIGN_MIN; + else if (strstr(attr[i + 1], "yMid") != 0) + p->alignY = NSVG_ALIGN_MID; + else if (strstr(attr[i + 1], "yMax") != 0) + p->alignY = NSVG_ALIGN_MAX; + // Parse meet/slice + p->alignType = NSVG_ALIGN_MEET; + if (strstr(attr[i + 1], "slice") != 0) + p->alignType = NSVG_ALIGN_SLICE; + } + } + } + } +} + +static void nsvg__parseGradient(NSVGparser* p, const char** attr, signed char type) +{ + int i; + NSVGgradientData* grad = (NSVGgradientData*)malloc(sizeof(NSVGgradientData)); + if (grad == NULL) return; + memset(grad, 0, sizeof(NSVGgradientData)); + grad->units = NSVG_OBJECT_SPACE; + grad->type = type; + if (grad->type == NSVG_PAINT_LINEAR_GRADIENT) { + grad->linear.x1 = nsvg__coord(0.0f, NSVG_UNITS_PERCENT); + grad->linear.y1 = nsvg__coord(0.0f, NSVG_UNITS_PERCENT); + grad->linear.x2 = nsvg__coord(100.0f, NSVG_UNITS_PERCENT); + grad->linear.y2 = nsvg__coord(0.0f, NSVG_UNITS_PERCENT); + } else if (grad->type == NSVG_PAINT_RADIAL_GRADIENT) { + grad->radial.cx = nsvg__coord(50.0f, NSVG_UNITS_PERCENT); + grad->radial.cy = nsvg__coord(50.0f, NSVG_UNITS_PERCENT); + grad->radial.r = nsvg__coord(50.0f, NSVG_UNITS_PERCENT); + } + + nsvg__xformIdentity(grad->xform); + + for (i = 0; attr[i]; i += 2) { + if (strcmp(attr[i], "id") == 0) { + strncpy(grad->id, attr[i+1], 63); + grad->id[63] = '\0'; + } else if (!nsvg__parseAttr(p, attr[i], attr[i + 1])) { + if (strcmp(attr[i], "gradientUnits") == 0) { + if (strcmp(attr[i+1], "objectBoundingBox") == 0) + grad->units = NSVG_OBJECT_SPACE; + else + grad->units = NSVG_USER_SPACE; + } else if (strcmp(attr[i], "gradientTransform") == 0) { + nsvg__parseTransform(grad->xform, attr[i + 1]); + } else if (strcmp(attr[i], "cx") == 0) { + grad->radial.cx = nsvg__parseCoordinateRaw(attr[i + 1]); + } else if (strcmp(attr[i], "cy") == 0) { + grad->radial.cy = nsvg__parseCoordinateRaw(attr[i + 1]); + } else if (strcmp(attr[i], "r") == 0) { + grad->radial.r = nsvg__parseCoordinateRaw(attr[i + 1]); + } else if (strcmp(attr[i], "fx") == 0) { + grad->radial.fx = nsvg__parseCoordinateRaw(attr[i + 1]); + } else if (strcmp(attr[i], "fy") == 0) { + grad->radial.fy = nsvg__parseCoordinateRaw(attr[i + 1]); + } else if (strcmp(attr[i], "x1") == 0) { + grad->linear.x1 = nsvg__parseCoordinateRaw(attr[i + 1]); + } else if (strcmp(attr[i], "y1") == 0) { + grad->linear.y1 = nsvg__parseCoordinateRaw(attr[i + 1]); + } else if (strcmp(attr[i], "x2") == 0) { + grad->linear.x2 = nsvg__parseCoordinateRaw(attr[i + 1]); + } else if (strcmp(attr[i], "y2") == 0) { + grad->linear.y2 = nsvg__parseCoordinateRaw(attr[i + 1]); + } else if (strcmp(attr[i], "spreadMethod") == 0) { + if (strcmp(attr[i+1], "pad") == 0) + grad->spread = NSVG_SPREAD_PAD; + else if (strcmp(attr[i+1], "reflect") == 0) + grad->spread = NSVG_SPREAD_REFLECT; + else if (strcmp(attr[i+1], "repeat") == 0) + grad->spread = NSVG_SPREAD_REPEAT; + } else if (strcmp(attr[i], "xlink:href") == 0) { + const char *href = attr[i+1]; + strncpy(grad->ref, href+1, 62); + grad->ref[62] = '\0'; + } + } + } + + grad->next = p->gradients; + p->gradients = grad; +} + +static void nsvg__parseGradientStop(NSVGparser* p, const char** attr) +{ + NSVGattrib* curAttr = nsvg__getAttr(p); + NSVGgradientData* grad; + NSVGgradientStop* stop; + int i, idx; + + curAttr->stopOffset = 0; + curAttr->stopColor = 0; + curAttr->stopOpacity = 1.0f; + + for (i = 0; attr[i]; i += 2) { + nsvg__parseAttr(p, attr[i], attr[i + 1]); + } + + // Add stop to the last gradient. + grad = p->gradients; + if (grad == NULL) return; + + grad->nstops++; + grad->stops = (NSVGgradientStop*)realloc(grad->stops, sizeof(NSVGgradientStop)*grad->nstops); + if (grad->stops == NULL) return; + + // Insert + idx = grad->nstops-1; + for (i = 0; i < grad->nstops-1; i++) { + if (curAttr->stopOffset < grad->stops[i].offset) { + idx = i; + break; + } + } + if (idx != grad->nstops-1) { + for (i = grad->nstops-1; i > idx; i--) + grad->stops[i] = grad->stops[i-1]; + } + + stop = &grad->stops[idx]; + stop->color = curAttr->stopColor; + stop->color |= (unsigned int)(curAttr->stopOpacity*255) << 24; + stop->offset = curAttr->stopOffset; +} + +static void nsvg__startElement(void* ud, const char* el, const char** attr) +{ + NSVGparser* p = (NSVGparser*)ud; + + if (p->defsFlag) { + // Skip everything but gradients and styles in defs + if (strcmp(el, "linearGradient") == 0) { + nsvg__parseGradient(p, attr, NSVG_PAINT_LINEAR_GRADIENT); + } else if (strcmp(el, "radialGradient") == 0) { + nsvg__parseGradient(p, attr, NSVG_PAINT_RADIAL_GRADIENT); + } else if (strcmp(el, "stop") == 0) { + nsvg__parseGradientStop(p, attr); + } else if (strcmp(el, "style") == 0) { + p->styleFlag = 1; + } + return; + } + + if (strcmp(el, "g") == 0) { + nsvg__pushAttr(p); + nsvg__parseAttribs(p, attr); + } else if (strcmp(el, "path") == 0) { + if (p->pathFlag) // Do not allow nested paths. + return; + nsvg__pushAttr(p); + nsvg__parsePath(p, attr); + nsvg__popAttr(p); + } else if (strcmp(el, "rect") == 0) { + nsvg__pushAttr(p); + nsvg__parseRect(p, attr); + nsvg__popAttr(p); + } else if (strcmp(el, "circle") == 0) { + nsvg__pushAttr(p); + nsvg__parseCircle(p, attr); + nsvg__popAttr(p); + } else if (strcmp(el, "ellipse") == 0) { + nsvg__pushAttr(p); + nsvg__parseEllipse(p, attr); + nsvg__popAttr(p); + } else if (strcmp(el, "line") == 0) { + nsvg__pushAttr(p); + nsvg__parseLine(p, attr); + nsvg__popAttr(p); + } else if (strcmp(el, "polyline") == 0) { + nsvg__pushAttr(p); + nsvg__parsePoly(p, attr, 0); + nsvg__popAttr(p); + } else if (strcmp(el, "polygon") == 0) { + nsvg__pushAttr(p); + nsvg__parsePoly(p, attr, 1); + nsvg__popAttr(p); + } else if (strcmp(el, "linearGradient") == 0) { + nsvg__parseGradient(p, attr, NSVG_PAINT_LINEAR_GRADIENT); + } else if (strcmp(el, "radialGradient") == 0) { + nsvg__parseGradient(p, attr, NSVG_PAINT_RADIAL_GRADIENT); + } else if (strcmp(el, "stop") == 0) { + nsvg__parseGradientStop(p, attr); + } else if (strcmp(el, "defs") == 0) { + p->defsFlag = 1; + } else if (strcmp(el, "svg") == 0) { + nsvg__parseSVG(p, attr); + } else if (strcmp(el, "style") == 0) { + p->styleFlag = 1; + } +} + +static void nsvg__endElement(void* ud, const char* el) +{ + NSVGparser* p = (NSVGparser*)ud; + + if (strcmp(el, "g") == 0) { + nsvg__popAttr(p); + } else if (strcmp(el, "path") == 0) { + p->pathFlag = 0; + } else if (strcmp(el, "defs") == 0) { + p->defsFlag = 0; + } else if (strcmp(el, "style") == 0) { + p->styleFlag = 0; + } +} + +static char *nsvg__strndup(const char *s, size_t n) +{ + char *result = (char *)malloc(n + 1); + if (result == NULL) + return NULL; + + memcpy(result, s, n); + result[n] = '\0'; + return result; +} + +static void nsvg__content(void* ud, const char* s) +{ + NSVGparser* p = (NSVGparser*)ud; + if (!p->styleFlag) + return; + + // Parse all the styles inside the style block. Each style's content will be later processed using nsvg__parseStyle(). + // Note: We only support selector lists of simple class selectors (e.g. ".foo, .bar { ... }"). + while (*s) { + NSVGstyleDeclaration* styles[NSVG_MAX_CLASSES]; + int nstyles = 0; + const char* propsStart; + const char* propsEnd; + int i; + + // 1) Parse the selector list up to '{'. For each simple class selector ('.name'), + // allocate a new NSVGstyleDeclaration into the local staging array. Styles are + // only committed to p->styles in step 3 below, once their propertiesText has + // also been allocated successfully. + while (*s && *s != '{') { + const char* selStart; + const char* selEnd; + NSVGstyleDeclaration* style; + + while (*s && (nsvg__isspace(*s) || *s == ',')) + s++; + if (!*s || *s == '{') + break; + + selStart = s; + while (*s && !nsvg__isspace(*s) && *s != ',' && *s != '{') + s++; + selEnd = s; + + if (*selStart != '.' || nstyles >= NSVG_MAX_CLASSES) + continue; // unsupported selector, or staging array full + selStart++; // strip leading '.' + + style = (NSVGstyleDeclaration*)malloc(sizeof(NSVGstyleDeclaration)); + if (style == NULL) + continue; + style->className = nsvg__strndup(selStart, (size_t)(selEnd - selStart)); + if (style->className == NULL) { + free(style); + continue; + } + style->propertiesText = NULL; + style->next = NULL; + styles[nstyles++] = style; + } + if (!*s) { + // No '{' found - discard pending styles and stop. + for (i = 0; i < nstyles; i++) { + free(styles[i]->className); + free(styles[i]); + } + break; + } + s++; // advance past '{' + + // 2) Find the end of the properties block (up to '}'). + propsStart = s; + while (*s && *s != '}') + s++; + propsEnd = s; + + // 3) Allocate propertiesText for each pending style. Commit successful ones to + // p->styles (head-insertion); free any whose allocation fails. + for (i = 0; i < nstyles; i++) { + styles[i]->propertiesText = nsvg__strndup(propsStart, (size_t)(propsEnd - propsStart)); + if (styles[i]->propertiesText == NULL) { + free(styles[i]->className); + free(styles[i]); + } else { + styles[i]->next = p->styles; + p->styles = styles[i]; + } + } + + if (*s) + s++; // advance past '}' + } +} + +static void nsvg__imageBounds(NSVGparser* p, float* bounds) +{ + NSVGshape* shape; + shape = p->image->shapes; + if (shape == NULL) { + bounds[0] = bounds[1] = bounds[2] = bounds[3] = 0.0; + return; + } + bounds[0] = shape->bounds[0]; + bounds[1] = shape->bounds[1]; + bounds[2] = shape->bounds[2]; + bounds[3] = shape->bounds[3]; + for (shape = shape->next; shape != NULL; shape = shape->next) { + bounds[0] = nsvg__minf(bounds[0], shape->bounds[0]); + bounds[1] = nsvg__minf(bounds[1], shape->bounds[1]); + bounds[2] = nsvg__maxf(bounds[2], shape->bounds[2]); + bounds[3] = nsvg__maxf(bounds[3], shape->bounds[3]); + } +} + +static float nsvg__viewAlign(float content, float container, int type) +{ + if (type == NSVG_ALIGN_MIN) + return 0; + else if (type == NSVG_ALIGN_MAX) + return container - content; + // mid + return (container - content) * 0.5f; +} + +static void nsvg__scaleGradient(NSVGgradient* grad, float tx, float ty, float sx, float sy) +{ + float t[6]; + nsvg__xformSetTranslation(t, tx, ty); + nsvg__xformMultiply (grad->xform, t); + + nsvg__xformSetScale(t, sx, sy); + nsvg__xformMultiply (grad->xform, t); +} + +static void nsvg__scaleToViewbox(NSVGparser* p, const char* units) +{ + NSVGshape* shape; + NSVGpath* path; + float tx, ty, sx, sy, us, bounds[4], t[6], avgs; + int i; + float* pt; + + // Guess image size if not set completely. + nsvg__imageBounds(p, bounds); + + if (p->viewWidth == 0) { + if (p->image->width > 0) { + p->viewWidth = p->image->width; + } else { + p->viewMinx = bounds[0]; + p->viewWidth = bounds[2] - bounds[0]; + } + } + if (p->viewHeight == 0) { + if (p->image->height > 0) { + p->viewHeight = p->image->height; + } else { + p->viewMiny = bounds[1]; + p->viewHeight = bounds[3] - bounds[1]; + } + } + if (p->image->width == 0) + p->image->width = p->viewWidth; + if (p->image->height == 0) + p->image->height = p->viewHeight; + + tx = -p->viewMinx; + ty = -p->viewMiny; + sx = p->viewWidth > 0 ? p->image->width / p->viewWidth : 0; + sy = p->viewHeight > 0 ? p->image->height / p->viewHeight : 0; + // Unit scaling + us = 1.0f / nsvg__convertToPixels(p, nsvg__coord(1.0f, nsvg__parseUnits(units)), 0.0f, 1.0f); + + // Fix aspect ratio + if (p->alignType == NSVG_ALIGN_MEET) { + // fit whole image into viewbox + sx = sy = nsvg__minf(sx, sy); + tx += nsvg__viewAlign(p->viewWidth*sx, p->image->width, p->alignX) / sx; + ty += nsvg__viewAlign(p->viewHeight*sy, p->image->height, p->alignY) / sy; + } else if (p->alignType == NSVG_ALIGN_SLICE) { + // fill whole viewbox with image + sx = sy = nsvg__maxf(sx, sy); + tx += nsvg__viewAlign(p->viewWidth*sx, p->image->width, p->alignX) / sx; + ty += nsvg__viewAlign(p->viewHeight*sy, p->image->height, p->alignY) / sy; + } + + // Transform + sx *= us; + sy *= us; + avgs = (sx+sy) / 2.0f; + for (shape = p->image->shapes; shape != NULL; shape = shape->next) { + shape->bounds[0] = (shape->bounds[0] + tx) * sx; + shape->bounds[1] = (shape->bounds[1] + ty) * sy; + shape->bounds[2] = (shape->bounds[2] + tx) * sx; + shape->bounds[3] = (shape->bounds[3] + ty) * sy; + for (path = shape->paths; path != NULL; path = path->next) { + path->bounds[0] = (path->bounds[0] + tx) * sx; + path->bounds[1] = (path->bounds[1] + ty) * sy; + path->bounds[2] = (path->bounds[2] + tx) * sx; + path->bounds[3] = (path->bounds[3] + ty) * sy; + for (i =0; i < path->npts; i++) { + pt = &path->pts[i*2]; + pt[0] = (pt[0] + tx) * sx; + pt[1] = (pt[1] + ty) * sy; + } + } + + if (shape->fill.type == NSVG_PAINT_LINEAR_GRADIENT || shape->fill.type == NSVG_PAINT_RADIAL_GRADIENT) { + nsvg__scaleGradient(shape->fill.gradient, tx,ty, sx,sy); + memcpy(t, shape->fill.gradient->xform, sizeof(float)*6); + nsvg__xformInverse(shape->fill.gradient->xform, t); + } + if (shape->stroke.type == NSVG_PAINT_LINEAR_GRADIENT || shape->stroke.type == NSVG_PAINT_RADIAL_GRADIENT) { + nsvg__scaleGradient(shape->stroke.gradient, tx,ty, sx,sy); + memcpy(t, shape->stroke.gradient->xform, sizeof(float)*6); + nsvg__xformInverse(shape->stroke.gradient->xform, t); + } + + shape->strokeWidth *= avgs; + shape->strokeDashOffset *= avgs; + for (i = 0; i < shape->strokeDashCount; i++) + shape->strokeDashArray[i] *= avgs; + } +} + +static void nsvg__createGradients(NSVGparser* p) +{ + NSVGshape* shape; + + for (shape = p->image->shapes; shape != NULL; shape = shape->next) { + if (shape->fill.type == NSVG_PAINT_UNDEF) { + if (shape->fillGradient[0] != '\0') { + float inv[6], localBounds[4]; + nsvg__xformInverse(inv, shape->xform); + nsvg__getLocalBounds(localBounds, shape, inv); + shape->fill.gradient = nsvg__createGradient(p, shape->fillGradient, localBounds, shape->xform, &shape->fill.type); + } + if (shape->fill.type == NSVG_PAINT_UNDEF) { + shape->fill.type = NSVG_PAINT_NONE; + } + } + if (shape->stroke.type == NSVG_PAINT_UNDEF) { + if (shape->strokeGradient[0] != '\0') { + float inv[6], localBounds[4]; + nsvg__xformInverse(inv, shape->xform); + nsvg__getLocalBounds(localBounds, shape, inv); + shape->stroke.gradient = nsvg__createGradient(p, shape->strokeGradient, localBounds, shape->xform, &shape->stroke.type); + } + if (shape->stroke.type == NSVG_PAINT_UNDEF) { + shape->stroke.type = NSVG_PAINT_NONE; + } + } + } +} + +NSVGimage* nsvgParse(char* input, const char* units, float dpi) +{ + NSVGparser* p; + NSVGimage* ret = 0; + + p = nsvg__createParser(); + if (p == NULL) { + return NULL; + } + p->dpi = dpi; + + nsvg__parseXML(input, nsvg__startElement, nsvg__endElement, nsvg__content, p); + + // Create gradients after all definitions have been parsed + nsvg__createGradients(p); + + // Scale to viewBox + nsvg__scaleToViewbox(p, units); + + ret = p->image; + p->image = NULL; + + nsvg__deleteParser(p); + + return ret; +} + +NSVGimage* nsvgParseFromFile(const char* filename, const char* units, float dpi) +{ + FILE* fp = NULL; + size_t size; + char* data = NULL; + NSVGimage* image = NULL; + + fp = fopen(filename, "rb"); + if (!fp) goto error; + if (fseek(fp, 0, SEEK_END)) goto error; + size = ftell(fp); + if (size == -1l) goto error; + if (fseek(fp, 0, SEEK_SET)) goto error; + data = (char*)malloc(size+1); + if (data == NULL) goto error; + if (fread(data, 1, size, fp) != size) goto error; + data[size] = '\0'; // Must be null terminated. + fclose(fp); + image = nsvgParse(data, units, dpi); + free(data); + + return image; + +error: + if (fp) fclose(fp); + if (data) free(data); + if (image) nsvgDelete(image); + return NULL; +} + +NSVGpath* nsvgDuplicatePath(NSVGpath* p) +{ + NSVGpath* res = NULL; + + if (p == NULL) + return NULL; + + res = (NSVGpath*)malloc(sizeof(NSVGpath)); + if (res == NULL) goto error; + memset(res, 0, sizeof(NSVGpath)); + + res->pts = (float*)malloc(p->npts*2*sizeof(float)); + if (res->pts == NULL) goto error; + memcpy(res->pts, p->pts, p->npts * sizeof(float) * 2); + res->npts = p->npts; + + memcpy(res->bounds, p->bounds, sizeof(p->bounds)); + + res->closed = p->closed; + + return res; + +error: + if (res != NULL) { + free(res->pts); + free(res); + } + return NULL; +} + +void nsvgDelete(NSVGimage* image) +{ + NSVGshape *snext, *shape; + if (image == NULL) return; + shape = image->shapes; + while (shape != NULL) { + snext = shape->next; + nsvg__deletePaths(shape->paths); + nsvg__deletePaint(&shape->fill); + nsvg__deletePaint(&shape->stroke); + free(shape); + shape = snext; + } + free(image); +} + +#endif // NANOSVG_IMPLEMENTATION + +#endif // NANOSVG_H diff --git a/third_party/nanosvg/nanosvgrast.h b/third_party/nanosvg/nanosvgrast.h new file mode 100644 index 0000000..ba512c7 --- /dev/null +++ b/third_party/nanosvg/nanosvgrast.h @@ -0,0 +1,1472 @@ +/* + * Copyright (c) 2013-14 Mikko Mononen memon@inside.org + * + * This software is provided 'as-is', without any express or implied + * warranty. In no event will the authors be held liable for any damages + * arising from the use of this software. + * + * Permission is granted to anyone to use this software for any purpose, + * including commercial applications, and to alter it and redistribute it + * freely, subject to the following restrictions: + * + * 1. The origin of this software must not be misrepresented; you must not + * claim that you wrote the original software. If you use this software + * in a product, an acknowledgment in the product documentation would be + * appreciated but is not required. + * 2. Altered source versions must be plainly marked as such, and must not be + * misrepresented as being the original software. + * 3. This notice may not be removed or altered from any source distribution. + * + * The polygon rasterization is heavily based on stb_truetype rasterizer + * by Sean Barrett - http://nothings.org/ + * + */ + +#ifndef NANOSVGRAST_H +#define NANOSVGRAST_H + +#include "nanosvg.h" + +#ifndef NANOSVGRAST_CPLUSPLUS +#ifdef __cplusplus +extern "C" { +#endif +#endif + +typedef struct NSVGrasterizer NSVGrasterizer; + +/* Example Usage: + // Load SVG + NSVGimage* image; + image = nsvgParseFromFile("test.svg", "px", 96); + + // Create rasterizer (can be used to render multiple images). + struct NSVGrasterizer* rast = nsvgCreateRasterizer(); + // Allocate memory for image + unsigned char* img = malloc(w*h*4); + // Rasterize + nsvgRasterize(rast, image, 0,0,1, img, w, h, w*4); +*/ + +// Allocated rasterizer context. +NSVGrasterizer* nsvgCreateRasterizer(void); + +// Rasterizes SVG image, returns RGBA image (non-premultiplied alpha) +// r - pointer to rasterizer context +// image - pointer to image to rasterize +// tx,ty - image offset (applied after scaling) +// scale - image scale +// dst - pointer to destination image data, 4 bytes per pixel (RGBA) +// w - width of the image to render +// h - height of the image to render +// stride - number of bytes per scaleline in the destination buffer +void nsvgRasterize(NSVGrasterizer* r, + NSVGimage* image, float tx, float ty, float scale, + unsigned char* dst, int w, int h, int stride); + +// Deletes rasterizer context. +void nsvgDeleteRasterizer(NSVGrasterizer*); + + +#ifndef NANOSVGRAST_CPLUSPLUS +#ifdef __cplusplus +} +#endif +#endif + +#ifdef NANOSVGRAST_IMPLEMENTATION + +#include +#include +#include + +#define NSVG__SUBSAMPLES 5 +#define NSVG__FIXSHIFT 10 +#define NSVG__FIX (1 << NSVG__FIXSHIFT) +#define NSVG__FIXMASK (NSVG__FIX-1) +#define NSVG__MEMPAGE_SIZE 1024 + +typedef struct NSVGedge { + float x0,y0, x1,y1; + int dir; + struct NSVGedge* next; +} NSVGedge; + +typedef struct NSVGpoint { + float x, y; + float dx, dy; + float len; + float dmx, dmy; + unsigned char flags; +} NSVGpoint; + +typedef struct NSVGactiveEdge { + int x,dx; + float ey; + int dir; + struct NSVGactiveEdge *next; +} NSVGactiveEdge; + +typedef struct NSVGmemPage { + unsigned char mem[NSVG__MEMPAGE_SIZE]; + int size; + struct NSVGmemPage* next; +} NSVGmemPage; + +typedef struct NSVGcachedPaint { + signed char type; + char spread; + float xform[6]; + unsigned int colors[256]; +} NSVGcachedPaint; + +struct NSVGrasterizer +{ + float px, py; + + float tessTol; + float distTol; + + NSVGedge* edges; + int nedges; + int cedges; + + NSVGpoint* points; + int npoints; + int cpoints; + + NSVGpoint* points2; + int npoints2; + int cpoints2; + + NSVGactiveEdge* freelist; + NSVGmemPage* pages; + NSVGmemPage* curpage; + + unsigned char* scanline; + int cscanline; + + unsigned char* bitmap; + int width, height, stride; +}; + +NSVGrasterizer* nsvgCreateRasterizer(void) +{ + NSVGrasterizer* r = (NSVGrasterizer*)malloc(sizeof(NSVGrasterizer)); + if (r == NULL) goto error; + memset(r, 0, sizeof(NSVGrasterizer)); + + r->tessTol = 0.25f; + r->distTol = 0.01f; + + return r; + +error: + nsvgDeleteRasterizer(r); + return NULL; +} + +void nsvgDeleteRasterizer(NSVGrasterizer* r) +{ + NSVGmemPage* p; + + if (r == NULL) return; + + p = r->pages; + while (p != NULL) { + NSVGmemPage* next = p->next; + free(p); + p = next; + } + + if (r->edges) free(r->edges); + if (r->points) free(r->points); + if (r->points2) free(r->points2); + if (r->scanline) free(r->scanline); + + free(r); +} + +static NSVGmemPage* nsvg__nextPage(NSVGrasterizer* r, NSVGmemPage* cur) +{ + NSVGmemPage *newp; + + // If using existing chain, return the next page in chain + if (cur != NULL && cur->next != NULL) { + return cur->next; + } + + // Alloc new page + newp = (NSVGmemPage*)malloc(sizeof(NSVGmemPage)); + if (newp == NULL) return NULL; + memset(newp, 0, sizeof(NSVGmemPage)); + + // Add to linked list + if (cur != NULL) + cur->next = newp; + else + r->pages = newp; + + return newp; +} + +static void nsvg__resetPool(NSVGrasterizer* r) +{ + NSVGmemPage* p = r->pages; + while (p != NULL) { + p->size = 0; + p = p->next; + } + r->curpage = r->pages; +} + +static unsigned char* nsvg__alloc(NSVGrasterizer* r, int size) +{ + unsigned char* buf; + if (size > NSVG__MEMPAGE_SIZE) return NULL; + if (r->curpage == NULL || r->curpage->size+size > NSVG__MEMPAGE_SIZE) { + r->curpage = nsvg__nextPage(r, r->curpage); + } + buf = &r->curpage->mem[r->curpage->size]; + r->curpage->size += size; + return buf; +} + +static int nsvg__ptEquals(float x1, float y1, float x2, float y2, float tol) +{ + float dx = x2 - x1; + float dy = y2 - y1; + return dx*dx + dy*dy < tol*tol; +} + +static void nsvg__addPathPoint(NSVGrasterizer* r, float x, float y, int flags) +{ + NSVGpoint* pt; + + if (r->npoints > 0) { + pt = &r->points[r->npoints-1]; + if (nsvg__ptEquals(pt->x,pt->y, x,y, r->distTol)) { + pt->flags = (unsigned char)(pt->flags | flags); + return; + } + } + + if (r->npoints+1 > r->cpoints) { + r->cpoints = r->cpoints > 0 ? r->cpoints * 2 : 64; + r->points = (NSVGpoint*)realloc(r->points, sizeof(NSVGpoint) * r->cpoints); + if (r->points == NULL) return; + } + + pt = &r->points[r->npoints]; + pt->x = x; + pt->y = y; + pt->flags = (unsigned char)flags; + r->npoints++; +} + +static void nsvg__appendPathPoint(NSVGrasterizer* r, NSVGpoint pt) +{ + if (r->npoints+1 > r->cpoints) { + r->cpoints = r->cpoints > 0 ? r->cpoints * 2 : 64; + r->points = (NSVGpoint*)realloc(r->points, sizeof(NSVGpoint) * r->cpoints); + if (r->points == NULL) return; + } + r->points[r->npoints] = pt; + r->npoints++; +} + +static void nsvg__duplicatePoints(NSVGrasterizer* r) +{ + if (r->npoints > r->cpoints2) { + r->cpoints2 = r->npoints; + r->points2 = (NSVGpoint*)realloc(r->points2, sizeof(NSVGpoint) * r->cpoints2); + if (r->points2 == NULL) return; + } + + memcpy(r->points2, r->points, sizeof(NSVGpoint) * r->npoints); + r->npoints2 = r->npoints; +} + +static void nsvg__addEdge(NSVGrasterizer* r, float x0, float y0, float x1, float y1) +{ + NSVGedge* e; + + // Skip horizontal edges + if (y0 == y1) + return; + + if (r->nedges+1 > r->cedges) { + r->cedges = r->cedges > 0 ? r->cedges * 2 : 64; + r->edges = (NSVGedge*)realloc(r->edges, sizeof(NSVGedge) * r->cedges); + if (r->edges == NULL) return; + } + + e = &r->edges[r->nedges]; + r->nedges++; + + if (y0 < y1) { + e->x0 = x0; + e->y0 = y0; + e->x1 = x1; + e->y1 = y1; + e->dir = 1; + } else { + e->x0 = x1; + e->y0 = y1; + e->x1 = x0; + e->y1 = y0; + e->dir = -1; + } +} + +static float nsvg__normalize(float *x, float* y) +{ + float d = sqrtf((*x)*(*x) + (*y)*(*y)); + if (d > 1e-6f) { + float id = 1.0f / d; + *x *= id; + *y *= id; + } + return d; +} + +static float nsvg__absf(float x) { return x < 0 ? -x : x; } +static float nsvg__roundf(float x) { return (x >= 0) ? floorf(x + 0.5) : ceilf(x - 0.5); } + +static void nsvg__flattenCubicBez(NSVGrasterizer* r, + float x1, float y1, float x2, float y2, + float x3, float y3, float x4, float y4, + int level, int type) +{ + float x12,y12,x23,y23,x34,y34,x123,y123,x234,y234,x1234,y1234; + float dx,dy,d2,d3; + + if (level > 10) return; + + x12 = (x1+x2)*0.5f; + y12 = (y1+y2)*0.5f; + x23 = (x2+x3)*0.5f; + y23 = (y2+y3)*0.5f; + x34 = (x3+x4)*0.5f; + y34 = (y3+y4)*0.5f; + x123 = (x12+x23)*0.5f; + y123 = (y12+y23)*0.5f; + + dx = x4 - x1; + dy = y4 - y1; + d2 = nsvg__absf((x2 - x4) * dy - (y2 - y4) * dx); + d3 = nsvg__absf((x3 - x4) * dy - (y3 - y4) * dx); + + if ((d2 + d3)*(d2 + d3) < r->tessTol * (dx*dx + dy*dy)) { + nsvg__addPathPoint(r, x4, y4, type); + return; + } + + x234 = (x23+x34)*0.5f; + y234 = (y23+y34)*0.5f; + x1234 = (x123+x234)*0.5f; + y1234 = (y123+y234)*0.5f; + + nsvg__flattenCubicBez(r, x1,y1, x12,y12, x123,y123, x1234,y1234, level+1, 0); + nsvg__flattenCubicBez(r, x1234,y1234, x234,y234, x34,y34, x4,y4, level+1, type); +} + +static void nsvg__flattenShape(NSVGrasterizer* r, NSVGshape* shape, float scale) +{ + int i, j; + NSVGpath* path; + + for (path = shape->paths; path != NULL; path = path->next) { + r->npoints = 0; + // Flatten path + nsvg__addPathPoint(r, path->pts[0]*scale, path->pts[1]*scale, 0); + for (i = 0; i < path->npts-1; i += 3) { + float* p = &path->pts[i*2]; + nsvg__flattenCubicBez(r, p[0]*scale,p[1]*scale, p[2]*scale,p[3]*scale, p[4]*scale,p[5]*scale, p[6]*scale,p[7]*scale, 0, 0); + } + // Close path + nsvg__addPathPoint(r, path->pts[0]*scale, path->pts[1]*scale, 0); + // Build edges + for (i = 0, j = r->npoints-1; i < r->npoints; j = i++) + nsvg__addEdge(r, r->points[j].x, r->points[j].y, r->points[i].x, r->points[i].y); + } +} + +enum NSVGpointFlags +{ + NSVG_PT_CORNER = 0x01, + NSVG_PT_BEVEL = 0x02, + NSVG_PT_LEFT = 0x04 +}; + +static void nsvg__initClosed(NSVGpoint* left, NSVGpoint* right, NSVGpoint* p0, NSVGpoint* p1, float lineWidth) +{ + float w = lineWidth * 0.5f; + float dx = p1->x - p0->x; + float dy = p1->y - p0->y; + float len = nsvg__normalize(&dx, &dy); + float px = p0->x + dx*len*0.5f, py = p0->y + dy*len*0.5f; + float dlx = dy, dly = -dx; + float lx = px - dlx*w, ly = py - dly*w; + float rx = px + dlx*w, ry = py + dly*w; + left->x = lx; left->y = ly; + right->x = rx; right->y = ry; +} + +static void nsvg__buttCap(NSVGrasterizer* r, NSVGpoint* left, NSVGpoint* right, NSVGpoint* p, float dx, float dy, float lineWidth, int connect) +{ + float w = lineWidth * 0.5f; + float px = p->x, py = p->y; + float dlx = dy, dly = -dx; + float lx = px - dlx*w, ly = py - dly*w; + float rx = px + dlx*w, ry = py + dly*w; + + nsvg__addEdge(r, lx, ly, rx, ry); + + if (connect) { + nsvg__addEdge(r, left->x, left->y, lx, ly); + nsvg__addEdge(r, rx, ry, right->x, right->y); + } + left->x = lx; left->y = ly; + right->x = rx; right->y = ry; +} + +static void nsvg__squareCap(NSVGrasterizer* r, NSVGpoint* left, NSVGpoint* right, NSVGpoint* p, float dx, float dy, float lineWidth, int connect) +{ + float w = lineWidth * 0.5f; + float px = p->x - dx*w, py = p->y - dy*w; + float dlx = dy, dly = -dx; + float lx = px - dlx*w, ly = py - dly*w; + float rx = px + dlx*w, ry = py + dly*w; + + nsvg__addEdge(r, lx, ly, rx, ry); + + if (connect) { + nsvg__addEdge(r, left->x, left->y, lx, ly); + nsvg__addEdge(r, rx, ry, right->x, right->y); + } + left->x = lx; left->y = ly; + right->x = rx; right->y = ry; +} + +#ifndef NSVG_PI +#define NSVG_PI (3.14159265358979323846264338327f) +#endif + +static void nsvg__roundCap(NSVGrasterizer* r, NSVGpoint* left, NSVGpoint* right, NSVGpoint* p, float dx, float dy, float lineWidth, int ncap, int connect) +{ + int i; + float w = lineWidth * 0.5f; + float px = p->x, py = p->y; + float dlx = dy, dly = -dx; + float lx = 0, ly = 0, rx = 0, ry = 0, prevx = 0, prevy = 0; + + for (i = 0; i < ncap; i++) { + float a = (float)i/(float)(ncap-1)*NSVG_PI; + float ax = cosf(a) * w, ay = sinf(a) * w; + float x = px - dlx*ax - dx*ay; + float y = py - dly*ax - dy*ay; + + if (i > 0) + nsvg__addEdge(r, prevx, prevy, x, y); + + prevx = x; + prevy = y; + + if (i == 0) { + lx = x; ly = y; + } else if (i == ncap-1) { + rx = x; ry = y; + } + } + + if (connect) { + nsvg__addEdge(r, left->x, left->y, lx, ly); + nsvg__addEdge(r, rx, ry, right->x, right->y); + } + + left->x = lx; left->y = ly; + right->x = rx; right->y = ry; +} + +static void nsvg__bevelJoin(NSVGrasterizer* r, NSVGpoint* left, NSVGpoint* right, NSVGpoint* p0, NSVGpoint* p1, float lineWidth) +{ + float w = lineWidth * 0.5f; + float dlx0 = p0->dy, dly0 = -p0->dx; + float dlx1 = p1->dy, dly1 = -p1->dx; + float lx0 = p1->x - (dlx0 * w), ly0 = p1->y - (dly0 * w); + float rx0 = p1->x + (dlx0 * w), ry0 = p1->y + (dly0 * w); + float lx1 = p1->x - (dlx1 * w), ly1 = p1->y - (dly1 * w); + float rx1 = p1->x + (dlx1 * w), ry1 = p1->y + (dly1 * w); + + nsvg__addEdge(r, lx0, ly0, left->x, left->y); + nsvg__addEdge(r, lx1, ly1, lx0, ly0); + + nsvg__addEdge(r, right->x, right->y, rx0, ry0); + nsvg__addEdge(r, rx0, ry0, rx1, ry1); + + left->x = lx1; left->y = ly1; + right->x = rx1; right->y = ry1; +} + +static void nsvg__miterJoin(NSVGrasterizer* r, NSVGpoint* left, NSVGpoint* right, NSVGpoint* p0, NSVGpoint* p1, float lineWidth) +{ + float w = lineWidth * 0.5f; + float dlx0 = p0->dy, dly0 = -p0->dx; + float dlx1 = p1->dy, dly1 = -p1->dx; + float lx0, rx0, lx1, rx1; + float ly0, ry0, ly1, ry1; + + if (p1->flags & NSVG_PT_LEFT) { + lx0 = lx1 = p1->x - p1->dmx * w; + ly0 = ly1 = p1->y - p1->dmy * w; + nsvg__addEdge(r, lx1, ly1, left->x, left->y); + + rx0 = p1->x + (dlx0 * w); + ry0 = p1->y + (dly0 * w); + rx1 = p1->x + (dlx1 * w); + ry1 = p1->y + (dly1 * w); + nsvg__addEdge(r, right->x, right->y, rx0, ry0); + nsvg__addEdge(r, rx0, ry0, rx1, ry1); + } else { + lx0 = p1->x - (dlx0 * w); + ly0 = p1->y - (dly0 * w); + lx1 = p1->x - (dlx1 * w); + ly1 = p1->y - (dly1 * w); + nsvg__addEdge(r, lx0, ly0, left->x, left->y); + nsvg__addEdge(r, lx1, ly1, lx0, ly0); + + rx0 = rx1 = p1->x + p1->dmx * w; + ry0 = ry1 = p1->y + p1->dmy * w; + nsvg__addEdge(r, right->x, right->y, rx1, ry1); + } + + left->x = lx1; left->y = ly1; + right->x = rx1; right->y = ry1; +} + +static void nsvg__roundJoin(NSVGrasterizer* r, NSVGpoint* left, NSVGpoint* right, NSVGpoint* p0, NSVGpoint* p1, float lineWidth, int ncap) +{ + int i, n; + float w = lineWidth * 0.5f; + float dlx0 = p0->dy, dly0 = -p0->dx; + float dlx1 = p1->dy, dly1 = -p1->dx; + float a0 = atan2f(dly0, dlx0); + float a1 = atan2f(dly1, dlx1); + float da = a1 - a0; + float lx, ly, rx, ry; + + if (da < NSVG_PI) da += NSVG_PI*2; + if (da > NSVG_PI) da -= NSVG_PI*2; + + n = (int)ceilf((nsvg__absf(da) / NSVG_PI) * (float)ncap); + if (n < 2) n = 2; + if (n > ncap) n = ncap; + + lx = left->x; + ly = left->y; + rx = right->x; + ry = right->y; + + for (i = 0; i < n; i++) { + float u = (float)i/(float)(n-1); + float a = a0 + u*da; + float ax = cosf(a) * w, ay = sinf(a) * w; + float lx1 = p1->x - ax, ly1 = p1->y - ay; + float rx1 = p1->x + ax, ry1 = p1->y + ay; + + nsvg__addEdge(r, lx1, ly1, lx, ly); + nsvg__addEdge(r, rx, ry, rx1, ry1); + + lx = lx1; ly = ly1; + rx = rx1; ry = ry1; + } + + left->x = lx; left->y = ly; + right->x = rx; right->y = ry; +} + +static void nsvg__straightJoin(NSVGrasterizer* r, NSVGpoint* left, NSVGpoint* right, NSVGpoint* p1, float lineWidth) +{ + float w = lineWidth * 0.5f; + float lx = p1->x - (p1->dmx * w), ly = p1->y - (p1->dmy * w); + float rx = p1->x + (p1->dmx * w), ry = p1->y + (p1->dmy * w); + + nsvg__addEdge(r, lx, ly, left->x, left->y); + nsvg__addEdge(r, right->x, right->y, rx, ry); + + left->x = lx; left->y = ly; + right->x = rx; right->y = ry; +} + +static int nsvg__curveDivs(float r, float arc, float tol) +{ + float da = acosf(r / (r + tol)) * 2.0f; + int divs = (int)ceilf(arc / da); + if (divs < 2) divs = 2; + return divs; +} + +static void nsvg__expandStroke(NSVGrasterizer* r, NSVGpoint* points, int npoints, int closed, int lineJoin, int lineCap, float lineWidth) +{ + int ncap = nsvg__curveDivs(lineWidth*0.5f, NSVG_PI, r->tessTol); // Calculate divisions per half circle. + NSVGpoint left = {0,0,0,0,0,0,0,0}, right = {0,0,0,0,0,0,0,0}, firstLeft = {0,0,0,0,0,0,0,0}, firstRight = {0,0,0,0,0,0,0,0}; + NSVGpoint* p0, *p1; + int j, s, e; + + // Build stroke edges + if (closed) { + // Looping + p0 = &points[npoints-1]; + p1 = &points[0]; + s = 0; + e = npoints; + } else { + // Add cap + p0 = &points[0]; + p1 = &points[1]; + s = 1; + e = npoints-1; + } + + if (closed) { + nsvg__initClosed(&left, &right, p0, p1, lineWidth); + firstLeft = left; + firstRight = right; + } else { + // Add cap + float dx = p1->x - p0->x; + float dy = p1->y - p0->y; + nsvg__normalize(&dx, &dy); + if (lineCap == NSVG_CAP_BUTT) + nsvg__buttCap(r, &left, &right, p0, dx, dy, lineWidth, 0); + else if (lineCap == NSVG_CAP_SQUARE) + nsvg__squareCap(r, &left, &right, p0, dx, dy, lineWidth, 0); + else if (lineCap == NSVG_CAP_ROUND) + nsvg__roundCap(r, &left, &right, p0, dx, dy, lineWidth, ncap, 0); + } + + for (j = s; j < e; ++j) { + if (p1->flags & NSVG_PT_CORNER) { + if (lineJoin == NSVG_JOIN_ROUND) + nsvg__roundJoin(r, &left, &right, p0, p1, lineWidth, ncap); + else if (lineJoin == NSVG_JOIN_BEVEL || (p1->flags & NSVG_PT_BEVEL)) + nsvg__bevelJoin(r, &left, &right, p0, p1, lineWidth); + else + nsvg__miterJoin(r, &left, &right, p0, p1, lineWidth); + } else { + nsvg__straightJoin(r, &left, &right, p1, lineWidth); + } + p0 = p1++; + } + + if (closed) { + // Loop it + nsvg__addEdge(r, firstLeft.x, firstLeft.y, left.x, left.y); + nsvg__addEdge(r, right.x, right.y, firstRight.x, firstRight.y); + } else { + // Add cap + float dx = p1->x - p0->x; + float dy = p1->y - p0->y; + nsvg__normalize(&dx, &dy); + if (lineCap == NSVG_CAP_BUTT) + nsvg__buttCap(r, &right, &left, p1, -dx, -dy, lineWidth, 1); + else if (lineCap == NSVG_CAP_SQUARE) + nsvg__squareCap(r, &right, &left, p1, -dx, -dy, lineWidth, 1); + else if (lineCap == NSVG_CAP_ROUND) + nsvg__roundCap(r, &right, &left, p1, -dx, -dy, lineWidth, ncap, 1); + } +} + +static void nsvg__prepareStroke(NSVGrasterizer* r, float miterLimit, int lineJoin) +{ + int i, j; + NSVGpoint* p0, *p1; + + p0 = &r->points[r->npoints-1]; + p1 = &r->points[0]; + for (i = 0; i < r->npoints; i++) { + // Calculate segment direction and length + p0->dx = p1->x - p0->x; + p0->dy = p1->y - p0->y; + p0->len = nsvg__normalize(&p0->dx, &p0->dy); + // Advance + p0 = p1++; + } + + // calculate joins + p0 = &r->points[r->npoints-1]; + p1 = &r->points[0]; + for (j = 0; j < r->npoints; j++) { + float dlx0, dly0, dlx1, dly1, dmr2, cross; + dlx0 = p0->dy; + dly0 = -p0->dx; + dlx1 = p1->dy; + dly1 = -p1->dx; + // Calculate extrusions + p1->dmx = (dlx0 + dlx1) * 0.5f; + p1->dmy = (dly0 + dly1) * 0.5f; + dmr2 = p1->dmx*p1->dmx + p1->dmy*p1->dmy; + if (dmr2 > 0.000001f) { + float s2 = 1.0f / dmr2; + if (s2 > 600.0f) { + s2 = 600.0f; + } + p1->dmx *= s2; + p1->dmy *= s2; + } + + // Clear flags, but keep the corner. + p1->flags = (p1->flags & NSVG_PT_CORNER) ? NSVG_PT_CORNER : 0; + + // Keep track of left turns. + cross = p1->dx * p0->dy - p0->dx * p1->dy; + if (cross > 0.0f) + p1->flags |= NSVG_PT_LEFT; + + // Check to see if the corner needs to be beveled. + if (p1->flags & NSVG_PT_CORNER) { + if ((dmr2 * miterLimit*miterLimit) < 1.0f || lineJoin == NSVG_JOIN_BEVEL || lineJoin == NSVG_JOIN_ROUND) { + p1->flags |= NSVG_PT_BEVEL; + } + } + + p0 = p1++; + } +} + +static void nsvg__flattenShapeStroke(NSVGrasterizer* r, NSVGshape* shape, float scale) +{ + int i, j, closed; + NSVGpath* path; + NSVGpoint* p0, *p1; + float miterLimit = shape->miterLimit; + int lineJoin = shape->strokeLineJoin; + int lineCap = shape->strokeLineCap; + float lineWidth = shape->strokeWidth * scale; + + for (path = shape->paths; path != NULL; path = path->next) { + // Flatten path + r->npoints = 0; + nsvg__addPathPoint(r, path->pts[0]*scale, path->pts[1]*scale, NSVG_PT_CORNER); + for (i = 0; i < path->npts-1; i += 3) { + float* p = &path->pts[i*2]; + nsvg__flattenCubicBez(r, p[0]*scale,p[1]*scale, p[2]*scale,p[3]*scale, p[4]*scale,p[5]*scale, p[6]*scale,p[7]*scale, 0, NSVG_PT_CORNER); + } + if (r->npoints < 2) + continue; + + closed = path->closed; + + // If the first and last points are the same, remove the last, mark as closed path. + p0 = &r->points[r->npoints-1]; + p1 = &r->points[0]; + if (nsvg__ptEquals(p0->x,p0->y, p1->x,p1->y, r->distTol)) { + r->npoints--; + p0 = &r->points[r->npoints-1]; + closed = 1; + } + + if (shape->strokeDashCount > 0) { + int idash = 0, dashState = 1; + float totalDist = 0, dashLen, allDashLen, dashOffset; + NSVGpoint cur; + + if (closed) + nsvg__appendPathPoint(r, r->points[0]); + + // Duplicate points -> points2. + nsvg__duplicatePoints(r); + + r->npoints = 0; + cur = r->points2[0]; + nsvg__appendPathPoint(r, cur); + + // Figure out dash offset. + allDashLen = 0; + for (j = 0; j < shape->strokeDashCount; j++) + allDashLen += shape->strokeDashArray[j]; + if (shape->strokeDashCount & 1) + allDashLen *= 2.0f; + // Find location inside pattern + dashOffset = fmodf(shape->strokeDashOffset, allDashLen); + if (dashOffset < 0.0f) + dashOffset += allDashLen; + + while (dashOffset > shape->strokeDashArray[idash]) { + dashOffset -= shape->strokeDashArray[idash]; + idash = (idash + 1) % shape->strokeDashCount; + } + dashLen = (shape->strokeDashArray[idash] - dashOffset) * scale; + + for (j = 1; j < r->npoints2; ) { + float dx = r->points2[j].x - cur.x; + float dy = r->points2[j].y - cur.y; + float dist = sqrtf(dx*dx + dy*dy); + + if ((totalDist + dist) > dashLen) { + // Calculate intermediate point + float d = (dashLen - totalDist) / dist; + float x = cur.x + dx * d; + float y = cur.y + dy * d; + nsvg__addPathPoint(r, x, y, NSVG_PT_CORNER); + + // Stroke + if (r->npoints > 1 && dashState) { + nsvg__prepareStroke(r, miterLimit, lineJoin); + nsvg__expandStroke(r, r->points, r->npoints, 0, lineJoin, lineCap, lineWidth); + } + // Advance dash pattern + dashState = !dashState; + idash = (idash+1) % shape->strokeDashCount; + dashLen = shape->strokeDashArray[idash] * scale; + // Restart + cur.x = x; + cur.y = y; + cur.flags = NSVG_PT_CORNER; + totalDist = 0.0f; + r->npoints = 0; + nsvg__appendPathPoint(r, cur); + } else { + totalDist += dist; + cur = r->points2[j]; + nsvg__appendPathPoint(r, cur); + j++; + } + } + // Stroke any leftover path + if (r->npoints > 1 && dashState) { + nsvg__prepareStroke(r, miterLimit, lineJoin); + nsvg__expandStroke(r, r->points, r->npoints, 0, lineJoin, lineCap, lineWidth); + } + } else { + nsvg__prepareStroke(r, miterLimit, lineJoin); + nsvg__expandStroke(r, r->points, r->npoints, closed, lineJoin, lineCap, lineWidth); + } + } +} + +static int nsvg__cmpEdge(const void *p, const void *q) +{ + const NSVGedge* a = (const NSVGedge*)p; + const NSVGedge* b = (const NSVGedge*)q; + + if (a->y0 < b->y0) return -1; + if (a->y0 > b->y0) return 1; + return 0; +} + + +static NSVGactiveEdge* nsvg__addActive(NSVGrasterizer* r, NSVGedge* e, float startPoint) +{ + NSVGactiveEdge* z; + + if (r->freelist != NULL) { + // Restore from freelist. + z = r->freelist; + r->freelist = z->next; + } else { + // Alloc new edge. + z = (NSVGactiveEdge*)nsvg__alloc(r, sizeof(NSVGactiveEdge)); + if (z == NULL) return NULL; + } + + float dxdy = (e->x1 - e->x0) / (e->y1 - e->y0); +// STBTT_assert(e->y0 <= start_point); + // round dx down to avoid going too far + if (dxdy < 0) + z->dx = (int)(-nsvg__roundf(NSVG__FIX * -dxdy)); + else + z->dx = (int)nsvg__roundf(NSVG__FIX * dxdy); + z->x = (int)nsvg__roundf(NSVG__FIX * (e->x0 + dxdy * (startPoint - e->y0))); +// z->x -= off_x * FIX; + z->ey = e->y1; + z->next = 0; + z->dir = e->dir; + + return z; +} + +static void nsvg__freeActive(NSVGrasterizer* r, NSVGactiveEdge* z) +{ + z->next = r->freelist; + r->freelist = z; +} + +static void nsvg__fillScanline(unsigned char* scanline, int len, int x0, int x1, int maxWeight, int* xmin, int* xmax) +{ + int i = x0 >> NSVG__FIXSHIFT; + int j = x1 >> NSVG__FIXSHIFT; + if (i < *xmin) *xmin = i; + if (j > *xmax) *xmax = j; + if (i < len && j >= 0) { + if (i == j) { + // x0,x1 are the same pixel, so compute combined coverage + scanline[i] = (unsigned char)(scanline[i] + ((x1 - x0) * maxWeight >> NSVG__FIXSHIFT)); + } else { + if (i >= 0) // add antialiasing for x0 + scanline[i] = (unsigned char)(scanline[i] + (((NSVG__FIX - (x0 & NSVG__FIXMASK)) * maxWeight) >> NSVG__FIXSHIFT)); + else + i = -1; // clip + + if (j < len) // add antialiasing for x1 + scanline[j] = (unsigned char)(scanline[j] + (((x1 & NSVG__FIXMASK) * maxWeight) >> NSVG__FIXSHIFT)); + else + j = len; // clip + + for (++i; i < j; ++i) // fill pixels between x0 and x1 + scanline[i] = (unsigned char)(scanline[i] + maxWeight); + } + } +} + +// note: this routine clips fills that extend off the edges... ideally this +// wouldn't happen, but it could happen if the truetype glyph bounding boxes +// are wrong, or if the user supplies a too-small bitmap +static void nsvg__fillActiveEdges(unsigned char* scanline, int len, NSVGactiveEdge* e, int maxWeight, int* xmin, int* xmax, char fillRule) +{ + // non-zero winding fill + int x0 = 0, w = 0; + + if (fillRule == NSVG_FILLRULE_NONZERO) { + // Non-zero + while (e != NULL) { + if (w == 0) { + // if we're currently at zero, we need to record the edge start point + x0 = e->x; w += e->dir; + } else { + int x1 = e->x; w += e->dir; + // if we went to zero, we need to draw + if (w == 0) + nsvg__fillScanline(scanline, len, x0, x1, maxWeight, xmin, xmax); + } + e = e->next; + } + } else if (fillRule == NSVG_FILLRULE_EVENODD) { + // Even-odd + while (e != NULL) { + if (w == 0) { + // if we're currently at zero, we need to record the edge start point + x0 = e->x; w = 1; + } else { + int x1 = e->x; w = 0; + nsvg__fillScanline(scanline, len, x0, x1, maxWeight, xmin, xmax); + } + e = e->next; + } + } +} + +static float nsvg__clampf(float a, float mn, float mx) { + if (isnan(a)) + return mn; + return a < mn ? mn : (a > mx ? mx : a); +} + +static unsigned int nsvg__RGBA(unsigned char r, unsigned char g, unsigned char b, unsigned char a) +{ + return ((unsigned int)r) | ((unsigned int)g << 8) | ((unsigned int)b << 16) | ((unsigned int)a << 24); +} + +static unsigned int nsvg__lerpRGBA(unsigned int c0, unsigned int c1, float u) +{ + int iu = (int)(nsvg__clampf(u, 0.0f, 1.0f) * 256.0f); + int r = (((c0) & 0xff)*(256-iu) + (((c1) & 0xff)*iu)) >> 8; + int g = (((c0>>8) & 0xff)*(256-iu) + (((c1>>8) & 0xff)*iu)) >> 8; + int b = (((c0>>16) & 0xff)*(256-iu) + (((c1>>16) & 0xff)*iu)) >> 8; + int a = (((c0>>24) & 0xff)*(256-iu) + (((c1>>24) & 0xff)*iu)) >> 8; + return nsvg__RGBA((unsigned char)r, (unsigned char)g, (unsigned char)b, (unsigned char)a); +} + +static unsigned int nsvg__applyOpacity(unsigned int c, float u) +{ + int iu = (int)(nsvg__clampf(u, 0.0f, 1.0f) * 256.0f); + int r = (c) & 0xff; + int g = (c>>8) & 0xff; + int b = (c>>16) & 0xff; + int a = (((c>>24) & 0xff)*iu) >> 8; + return nsvg__RGBA((unsigned char)r, (unsigned char)g, (unsigned char)b, (unsigned char)a); +} + +static inline int nsvg__div255(int x) +{ + return ((x+1) * 257) >> 16; +} + +static void nsvg__scanlineSolid(unsigned char* dst, int count, unsigned char* cover, int x, int y, + float tx, float ty, float scale, NSVGcachedPaint* cache) +{ + + if (cache->type == NSVG_PAINT_COLOR) { + int i, cr, cg, cb, ca; + cr = cache->colors[0] & 0xff; + cg = (cache->colors[0] >> 8) & 0xff; + cb = (cache->colors[0] >> 16) & 0xff; + ca = (cache->colors[0] >> 24) & 0xff; + + for (i = 0; i < count; i++) { + int r,g,b; + int a = nsvg__div255((int)cover[0] * ca); + int ia = 255 - a; + // Premultiply + r = nsvg__div255(cr * a); + g = nsvg__div255(cg * a); + b = nsvg__div255(cb * a); + + // Blend over + r += nsvg__div255(ia * (int)dst[0]); + g += nsvg__div255(ia * (int)dst[1]); + b += nsvg__div255(ia * (int)dst[2]); + a += nsvg__div255(ia * (int)dst[3]); + + dst[0] = (unsigned char)r; + dst[1] = (unsigned char)g; + dst[2] = (unsigned char)b; + dst[3] = (unsigned char)a; + + cover++; + dst += 4; + } + } else if (cache->type == NSVG_PAINT_LINEAR_GRADIENT) { + // TODO: spread modes. + // TODO: plenty of opportunities to optimize. + float fx, fy, dx, gy; + float* t = cache->xform; + int i, cr, cg, cb, ca; + unsigned int c; + + fx = ((float)x - tx) / scale; + fy = ((float)y - ty) / scale; + dx = 1.0f / scale; + + for (i = 0; i < count; i++) { + int r,g,b,a,ia; + gy = fx*t[1] + fy*t[3] + t[5]; + c = cache->colors[(int)nsvg__clampf(gy*255.0f, 0, 255.0f)]; + cr = (c) & 0xff; + cg = (c >> 8) & 0xff; + cb = (c >> 16) & 0xff; + ca = (c >> 24) & 0xff; + + a = nsvg__div255((int)cover[0] * ca); + ia = 255 - a; + + // Premultiply + r = nsvg__div255(cr * a); + g = nsvg__div255(cg * a); + b = nsvg__div255(cb * a); + + // Blend over + r += nsvg__div255(ia * (int)dst[0]); + g += nsvg__div255(ia * (int)dst[1]); + b += nsvg__div255(ia * (int)dst[2]); + a += nsvg__div255(ia * (int)dst[3]); + + dst[0] = (unsigned char)r; + dst[1] = (unsigned char)g; + dst[2] = (unsigned char)b; + dst[3] = (unsigned char)a; + + cover++; + dst += 4; + fx += dx; + } + } else if (cache->type == NSVG_PAINT_RADIAL_GRADIENT) { + // TODO: spread modes. + // TODO: plenty of opportunities to optimize. + // TODO: focus (fx,fy) + float fx, fy, dx, gx, gy, gd; + float* t = cache->xform; + int i, cr, cg, cb, ca; + unsigned int c; + + fx = ((float)x - tx) / scale; + fy = ((float)y - ty) / scale; + dx = 1.0f / scale; + + for (i = 0; i < count; i++) { + int r,g,b,a,ia; + gx = fx*t[0] + fy*t[2] + t[4]; + gy = fx*t[1] + fy*t[3] + t[5]; + gd = sqrtf(gx*gx + gy*gy); + c = cache->colors[(int)nsvg__clampf(gd*255.0f, 0, 255.0f)]; + cr = (c) & 0xff; + cg = (c >> 8) & 0xff; + cb = (c >> 16) & 0xff; + ca = (c >> 24) & 0xff; + + a = nsvg__div255((int)cover[0] * ca); + ia = 255 - a; + + // Premultiply + r = nsvg__div255(cr * a); + g = nsvg__div255(cg * a); + b = nsvg__div255(cb * a); + + // Blend over + r += nsvg__div255(ia * (int)dst[0]); + g += nsvg__div255(ia * (int)dst[1]); + b += nsvg__div255(ia * (int)dst[2]); + a += nsvg__div255(ia * (int)dst[3]); + + dst[0] = (unsigned char)r; + dst[1] = (unsigned char)g; + dst[2] = (unsigned char)b; + dst[3] = (unsigned char)a; + + cover++; + dst += 4; + fx += dx; + } + } +} + +static void nsvg__rasterizeSortedEdges(NSVGrasterizer *r, float tx, float ty, float scale, NSVGcachedPaint* cache, char fillRule) +{ + NSVGactiveEdge *active = NULL; + int y, s; + int e = 0; + int maxWeight = (255 / NSVG__SUBSAMPLES); // weight per vertical scanline + int xmin, xmax; + + for (y = 0; y < r->height; y++) { + memset(r->scanline, 0, r->width); + xmin = r->width; + xmax = 0; + for (s = 0; s < NSVG__SUBSAMPLES; ++s) { + // find center of pixel for this scanline + float scany = (float)(y*NSVG__SUBSAMPLES + s) + 0.5f; + NSVGactiveEdge **step = &active; + + // update all active edges; + // remove all active edges that terminate before the center of this scanline + while (*step) { + NSVGactiveEdge *z = *step; + if (z->ey <= scany) { + *step = z->next; // delete from list +// NSVG__assert(z->valid); + nsvg__freeActive(r, z); + } else { + z->x += z->dx; // advance to position for current scanline + step = &((*step)->next); // advance through list + } + } + + // resort the list if needed + for (;;) { + int changed = 0; + step = &active; + while (*step && (*step)->next) { + if ((*step)->x > (*step)->next->x) { + NSVGactiveEdge* t = *step; + NSVGactiveEdge* q = t->next; + t->next = q->next; + q->next = t; + *step = q; + changed = 1; + } + step = &(*step)->next; + } + if (!changed) break; + } + + // insert all edges that start before the center of this scanline -- omit ones that also end on this scanline + while (e < r->nedges && r->edges[e].y0 <= scany) { + if (r->edges[e].y1 > scany) { + NSVGactiveEdge* z = nsvg__addActive(r, &r->edges[e], scany); + if (z == NULL) break; + // find insertion point + if (active == NULL) { + active = z; + } else if (z->x < active->x) { + // insert at front + z->next = active; + active = z; + } else { + // find thing to insert AFTER + NSVGactiveEdge* p = active; + while (p->next && p->next->x < z->x) + p = p->next; + // at this point, p->next->x is NOT < z->x + z->next = p->next; + p->next = z; + } + } + e++; + } + + // now process all active edges in non-zero fashion + if (active != NULL) + nsvg__fillActiveEdges(r->scanline, r->width, active, maxWeight, &xmin, &xmax, fillRule); + } + // Blit + if (xmin < 0) xmin = 0; + if (xmax > r->width-1) xmax = r->width-1; + if (xmin <= xmax) { + nsvg__scanlineSolid(&r->bitmap[y * r->stride] + xmin*4, xmax-xmin+1, &r->scanline[xmin], xmin, y, tx,ty, scale, cache); + } + } + +} + +static void nsvg__unpremultiplyAlpha(unsigned char* image, int w, int h, int stride) +{ + int x,y; + + // Unpremultiply + for (y = 0; y < h; y++) { + unsigned char *row = &image[y*stride]; + for (x = 0; x < w; x++) { + int r = row[0], g = row[1], b = row[2], a = row[3]; + if (a != 0) { + row[0] = (unsigned char)(r*255/a); + row[1] = (unsigned char)(g*255/a); + row[2] = (unsigned char)(b*255/a); + } + row += 4; + } + } + + // Defringe + for (y = 0; y < h; y++) { + unsigned char *row = &image[y*stride]; + for (x = 0; x < w; x++) { + int r = 0, g = 0, b = 0, a = row[3], n = 0; + if (a == 0) { + if (x-1 > 0 && row[-1] != 0) { + r += row[-4]; + g += row[-3]; + b += row[-2]; + n++; + } + if (x+1 < w && row[7] != 0) { + r += row[4]; + g += row[5]; + b += row[6]; + n++; + } + if (y-1 > 0 && row[-stride+3] != 0) { + r += row[-stride]; + g += row[-stride+1]; + b += row[-stride+2]; + n++; + } + if (y+1 < h && row[stride+3] != 0) { + r += row[stride]; + g += row[stride+1]; + b += row[stride+2]; + n++; + } + if (n > 0) { + row[0] = (unsigned char)(r/n); + row[1] = (unsigned char)(g/n); + row[2] = (unsigned char)(b/n); + } + } + row += 4; + } + } +} + + +static void nsvg__initPaint(NSVGcachedPaint* cache, NSVGpaint* paint, float opacity) +{ + int i, j; + NSVGgradient* grad; + + cache->type = paint->type; + + if (paint->type == NSVG_PAINT_COLOR) { + cache->colors[0] = nsvg__applyOpacity(paint->color, opacity); + return; + } + + grad = paint->gradient; + + cache->spread = grad->spread; + memcpy(cache->xform, grad->xform, sizeof(float)*6); + + if (grad->nstops == 0) { + for (i = 0; i < 256; i++) + cache->colors[i] = 0; + } else if (grad->nstops == 1) { + unsigned int color = nsvg__applyOpacity(grad->stops[0].color, opacity); + for (i = 0; i < 256; i++) + cache->colors[i] = color; + } else { + unsigned int ca, cb = 0; + float ua, ub, du, u; + int ia, ib, count; + + ca = nsvg__applyOpacity(grad->stops[0].color, opacity); + ua = nsvg__clampf(grad->stops[0].offset, 0, 1); + ub = nsvg__clampf(grad->stops[grad->nstops-1].offset, ua, 1); + ia = (int)(ua * 255.0f); + ib = (int)(ub * 255.0f); + for (i = 0; i < ia; i++) { + cache->colors[i] = ca; + } + + for (i = 0; i < grad->nstops-1; i++) { + ca = nsvg__applyOpacity(grad->stops[i].color, opacity); + cb = nsvg__applyOpacity(grad->stops[i+1].color, opacity); + ua = nsvg__clampf(grad->stops[i].offset, 0, 1); + ub = nsvg__clampf(grad->stops[i+1].offset, 0, 1); + ia = (int)(ua * 255.0f); + ib = (int)(ub * 255.0f); + count = ib - ia; + if (count <= 0) continue; + u = 0; + du = 1.0f / (float)count; + for (j = 0; j < count; j++) { + cache->colors[ia+j] = nsvg__lerpRGBA(ca,cb,u); + u += du; + } + } + + for (i = ib; i < 256; i++) + cache->colors[i] = cb; + } + +} + +/* +static void dumpEdges(NSVGrasterizer* r, const char* name) +{ + float xmin = 0, xmax = 0, ymin = 0, ymax = 0; + NSVGedge *e = NULL; + int i; + if (r->nedges == 0) return; + FILE* fp = fopen(name, "w"); + if (fp == NULL) return; + + xmin = xmax = r->edges[0].x0; + ymin = ymax = r->edges[0].y0; + for (i = 0; i < r->nedges; i++) { + e = &r->edges[i]; + xmin = nsvg__minf(xmin, e->x0); + xmin = nsvg__minf(xmin, e->x1); + xmax = nsvg__maxf(xmax, e->x0); + xmax = nsvg__maxf(xmax, e->x1); + ymin = nsvg__minf(ymin, e->y0); + ymin = nsvg__minf(ymin, e->y1); + ymax = nsvg__maxf(ymax, e->y0); + ymax = nsvg__maxf(ymax, e->y1); + } + + fprintf(fp, "", xmin, ymin, (xmax - xmin), (ymax - ymin)); + + for (i = 0; i < r->nedges; i++) { + e = &r->edges[i]; + fprintf(fp ,"", e->x0,e->y0, e->x1,e->y1); + } + + for (i = 0; i < r->npoints; i++) { + if (i+1 < r->npoints) + fprintf(fp ,"", r->points[i].x, r->points[i].y, r->points[i+1].x, r->points[i+1].y); + fprintf(fp ,"", r->points[i].x, r->points[i].y, r->points[i].flags == 0 ? "#f00" : "#0f0"); + } + + fprintf(fp, ""); + fclose(fp); +} +*/ + +void nsvgRasterize(NSVGrasterizer* r, + NSVGimage* image, float tx, float ty, float scale, + unsigned char* dst, int w, int h, int stride) +{ + NSVGshape *shape = NULL; + NSVGedge *e = NULL; + NSVGcachedPaint cache; + int i; + int j; + unsigned char paintOrder; + + r->bitmap = dst; + r->width = w; + r->height = h; + r->stride = stride; + + if (w > r->cscanline) { + r->cscanline = w; + r->scanline = (unsigned char*)realloc(r->scanline, w); + if (r->scanline == NULL) return; + } + + for (i = 0; i < h; i++) + memset(&dst[i*stride], 0, w*4); + + for (shape = image->shapes; shape != NULL; shape = shape->next) { + if (!(shape->flags & NSVG_FLAGS_VISIBLE)) + continue; + + for (j = 0; j < 3; j++) { + paintOrder = (shape->paintOrder >> (2 * j)) & 0x03; + + if (paintOrder == NSVG_PAINT_FILL && shape->fill.type != NSVG_PAINT_NONE) { + nsvg__resetPool(r); + r->freelist = NULL; + r->nedges = 0; + + nsvg__flattenShape(r, shape, scale); + + // Scale and translate edges + for (i = 0; i < r->nedges; i++) { + e = &r->edges[i]; + e->x0 = tx + e->x0; + e->y0 = (ty + e->y0) * NSVG__SUBSAMPLES; + e->x1 = tx + e->x1; + e->y1 = (ty + e->y1) * NSVG__SUBSAMPLES; + } + + // Rasterize edges + if (r->nedges != 0) + qsort(r->edges, r->nedges, sizeof(NSVGedge), nsvg__cmpEdge); + + // now, traverse the scanlines and find the intersections on each scanline, use non-zero rule + nsvg__initPaint(&cache, &shape->fill, shape->opacity); + + nsvg__rasterizeSortedEdges(r, tx,ty,scale, &cache, shape->fillRule); + } + if (paintOrder == NSVG_PAINT_STROKE && shape->stroke.type != NSVG_PAINT_NONE && (shape->strokeWidth * scale) > 0.01f) { + nsvg__resetPool(r); + r->freelist = NULL; + r->nedges = 0; + + nsvg__flattenShapeStroke(r, shape, scale); + + // dumpEdges(r, "edge.svg"); + + // Scale and translate edges + for (i = 0; i < r->nedges; i++) { + e = &r->edges[i]; + e->x0 = tx + e->x0; + e->y0 = (ty + e->y0) * NSVG__SUBSAMPLES; + e->x1 = tx + e->x1; + e->y1 = (ty + e->y1) * NSVG__SUBSAMPLES; + } + + // Rasterize edges + if (r->nedges != 0) + qsort(r->edges, r->nedges, sizeof(NSVGedge), nsvg__cmpEdge); + + // now, traverse the scanlines and find the intersections on each scanline, use non-zero rule + nsvg__initPaint(&cache, &shape->stroke, shape->opacity); + + nsvg__rasterizeSortedEdges(r, tx,ty,scale, &cache, NSVG_FILLRULE_NONZERO); + } + } + } + + nsvg__unpremultiplyAlpha(dst, w, h, stride); + + r->bitmap = NULL; + r->width = 0; + r->height = 0; + r->stride = 0; +} + +#endif // NANOSVGRAST_IMPLEMENTATION + +#endif // NANOSVGRAST_H diff --git a/wasmhost/README.md b/wasmhost/README.md new file mode 100644 index 0000000..375007e --- /dev/null +++ b/wasmhost/README.md @@ -0,0 +1,27 @@ +# wasmhost + +The MoonBit host for the compositor component (`build/compositor.wasm`), replacing the Rust +`host-wasm/`. It links wasmtime as the prebuilt C API library (`libwasmtime.a` from the upstream +`wasmtime-v$WASMTIME_VERSION-x86_64-linux-c-api` release, fetched by `scripts/setup-toolchain.sh` +into `.tools/wasmtime-c-api`) instead of compiling wasmtime, so a cold build takes about 4 s +instead of about 2 minutes. + +``` +scripts/build-wasmhost.sh # or: just wasmhost -> build/wasmhost +build/wasmhost build/compositor.wasm --socket PATH --gfx-out frame.png +``` + +- `wt/`: the wasmtime C API (`wt_stub.c`) and the value encoding host calls cross as (`val.mbt`). + wasmtime's C API has no bindgen: every call goes through one callback with dynamic values, so + each import is a small handler from values to values. A `list` crosses as one dynamic value + per byte and wasmtime caps how much one call may copy (about 2.7 MB of `list`), so large + files are written as `write-file` plus `append-file` chunks. +- `bin/`: the interfaces of `wit/host`. Most of it is the native compositor's own packages: + `sys` is compositor/sys, glyphs come from compositor/font (stb_truetype). The rasteriser + (`raster.mbt`, pixel work in `raster_stub.c`) is a port of `host-wasm/src/raster.rs`; SVG icons + use nanosvg (`third_party/nanosvg`) where the Rust host used resvg. + +Status: sys, font and raster work (`--gfx-out` frames match the Rust host's). Panel modules +(plasmoids), the login-session display (`--drm`) and the nested window are still to come. + +`WASMHOST_TRACE=1` logs every host call. diff --git a/wasmhost/bin/host_stub.c b/wasmhost/bin/host_stub.c new file mode 100644 index 0000000..680bfac --- /dev/null +++ b/wasmhost/bin/host_stub.c @@ -0,0 +1,37 @@ +/* Small pieces of the MoonBit host that need C. */ +#include +#include +#include +#include +#include +#include "moonbit.h" + +/* A line on stderr (the compositor's log). */ +void wh_eprint(moonbit_bytes_t s) { + fwrite(s, 1, (size_t)Moonbit_array_length(s), stderr); + fputc('\n', stderr); + fflush(stderr); +} + +/* No zombies from launched apps. */ +void wh_ignore_sigchld(void) { signal(SIGCHLD, SIG_IGN); } + +void wh_exit(int32_t code) { + fflush(stdout); + fflush(stderr); + exit(code); +} + +/* Append `data` to the file at `path` (created if missing): 0, or -1 on error. */ +int32_t wh_append_file(moonbit_bytes_t path, moonbit_bytes_t data) { + char p[4096]; + size_t n = (size_t)Moonbit_array_length(path); + if (n >= sizeof p) return -1; + memcpy(p, path, n); + p[n] = 0; + FILE *f = fopen(p, "ab"); + if (!f) return -1; + size_t len = (size_t)Moonbit_array_length(data); + int ok = fwrite(data, 1, len, f) == len; + return fclose(f) == 0 && ok ? 0 : -1; +} diff --git a/wasmhost/bin/main.mbt b/wasmhost/bin/main.mbt new file mode 100644 index 0000000..45f5c05 --- /dev/null +++ b/wasmhost/bin/main.mbt @@ -0,0 +1,109 @@ +///| The MoonBit host for the compositor component (build/compositor.wasm). +/// +/// It runs the component with wasmtime, linked as the prebuilt C API library, and implements the +/// interfaces the component imports (wit/host): sys, font, raster, display and plasmoids. Most of +/// it is the native compositor's own packages (compositor/sys, font, kms, wasm, renderer), so the +/// native and wasm builds share one implementation of each. +/// +/// wasmhost build/compositor.wasm --socket PATH [--window | --drm | --gfx-out PNG [--serve]] + +///| +#borrow(s) +extern "C" fn c_eprint(s : Bytes) = "wh_eprint" + +///| +extern "C" fn c_ignore_sigchld() = "wh_ignore_sigchld" + +///| +extern "C" fn c_exit(code : Int) = "wh_exit" + +///| +fn exit(code : Int) -> Unit { + c_exit(code) +} + +///| +fn eprint(s : String) -> Unit { + c_eprint(@utf8.encode(s)) +} + +///| Every host function, by interface, in registration order (its id is its index). +let handlers : Array[(Array[@wt.Val]) -> Array[@wt.Val]] = [] + +///| "interface.function" of each handler, for WASMHOST_TRACE. +let handler_names : Array[String] = [] + +///| +fn register( + iface : String, + funcs : Array[(String, (Array[@wt.Val]) -> Array[@wt.Val])], +) -> Unit { + let first = handlers.length() + for f in funcs { + handlers.push(f.1) + handler_names.push(iface + "." + f.0) + } + match @wt.define_funcs(iface, funcs.map(f => f.0), first) { + Ok(_) => () + Err(e) => { + eprint("error: " + e) + exit(1) + } + } +} + +///| +fn main { + let argv = @env.args() + let args : Array[String] = if argv.length() > 1 { + argv[1:].to_array() + } else { + [] + } + // First argument may be the component path; otherwise use the default build location. + let path = if args.length() > 0 && args[0].has_suffix(".wasm") { + args.remove(0) + } else { + "build/compositor.wasm" + } + if args.length() > 0 && args[0] == "--" { + args.remove(0) |> ignore + } + c_ignore_sigchld() + match @wt.load(path) { + Ok(_) => () + Err(e) => { + eprint( + "error: cannot load \{path}: \{e}\n build it with `just compositor-wasm`", + ) + exit(1) + } + } + if @sys.getenv("WASMHOST_TRACE") != "" { + @wt.set_handler(fn(id, a) { + eprint("> " + handler_names[id] + " " + a.length().to_string()) + handlers[id](a) + }) + } else { + @wt.set_handler(fn(id, a) { handlers[id](a) }) + } + register("chandra:host/sys@0.1.0", sys_funcs()) + register("chandra:host/font@0.1.0", font_funcs()) + register("chandra:host/raster@0.1.0", raster_funcs()) + register("chandra:host/display@0.1.0", display_funcs()) + register("chandra:host/plasmoids@0.1.0", plasmoid_funcs()) + match @wt.instantiate() { + Ok(_) => () + Err(e) => { + eprint("error: " + e) + exit(1) + } + } + match @wt.call("", "run", [@wt.Val::strings(args)]) { + Ok(r) => exit(if r.length() > 0 { r[0].to_int() } else { 0 }) + Err(e) => { + eprint("error: " + e) + exit(1) + } + } +} diff --git a/wasmhost/bin/moon.pkg b/wasmhost/bin/moon.pkg new file mode 100644 index 0000000..fa64c37 --- /dev/null +++ b/wasmhost/bin/moon.pkg @@ -0,0 +1,25 @@ +import { + "moonbitlang/core/builtin", + "moonbitlang/core/env" @env, + "moonbitlang/core/encoding/utf8" @utf8, + "moonbitlang/core/cmp" @cmp, + "chandra/desktop/compositor/sys" @sys, + "chandra/desktop/compositor/font" @font, + "chandra/desktop/compositor/renderer" @renderer, + "chandra/desktop/wasmhost/wt" @wt, +} + +supported_targets = "-all+native" + +pkgtype(kind: "executable") + +// libwasmtime comes prebuilt (scripts/setup-toolchain.sh); scripts/build-wasmhost.sh puts it on +// the compiler's and linker's search paths. Linked statically: the binary needs nothing at runtime. +options( + "native-stub": [ "host_stub.c", "raster_stub.c" ], + link: { + "native": { + "cc-link-flags": "-l:libwasmtime.a -lpthread -ldl -lm", + }, + }, +) diff --git a/wasmhost/bin/raster.mbt b/wasmhost/bin/raster.mbt new file mode 100644 index 0000000..1f7cd1d --- /dev/null +++ b/wasmhost/bin/raster.mbt @@ -0,0 +1,774 @@ +///| `chandra:host/raster` and `chandra:host/font`: the compositor sends draw operations and window +/// surface ids; the pixels live here (raster_stub.c) and never cross the component boundary. +/// What to draw where (layers, the wallpaper cache, damage) is decided here, as in +/// host-wasm/src/raster.rs. + +///| +extern "C" fn rs_resize(w : Int, h : Int) -> Int = "rs_resize" + +///| +extern "C" fn rs_clear() = "rs_clear" + +///| +extern "C" fn rs_set_clip(on : Int, x : Int, y : Int, w : Int, h : Int) = "rs_set_clip" + +///| +extern "C" fn rs_fill_rect( + x : Int, + y : Int, + w : Int, + h : Int, + r : Int, + g : Int, + b : Int, + a : Int, + radius : Int, +) = "rs_fill_rect" + +///| +extern "C" fn rs_stroke_rect( + x : Int, + y : Int, + w : Int, + h : Int, + r : Int, + g : Int, + b : Int, + a : Int, + width : Int, + radius : Int, +) = "rs_stroke_rect" + +///| +extern "C" fn rs_line( + x0 : Int, + y0 : Int, + x1 : Int, + y1 : Int, + r : Int, + g : Int, + b : Int, + a : Int, + width : Int, +) = "rs_line" + +///| +extern "C" fn rs_circle( + cx : Int, + cy : Int, + radius : Int, + r : Int, + g : Int, + b : Int, + a : Int, + filled : Int, +) = "rs_circle" + +///| compositor/font's shim (stb_truetype); 0 on success. +#borrow(path) +extern "C" fn mp_font_load(slot : Int, path : Bytes) -> Int = "mp_font_load" + +///| +extern "C" fn rs_font_loaded(slot : Int) = "rs_font_loaded" + +///| Load the TTF file at `path` into `slot` (0..3). +fn font_load(slot : Int, path : String) -> Bool { + if slot < 0 || slot >= 4 { + return false + } + if mp_font_load(slot, @utf8.encode(path)) != 0 { + return false + } + rs_font_loaded(slot) + true +} + +///| +extern "C" fn rs_font_has(slot : Int) -> Int = "rs_font_has" + +///| +#borrow(info) +extern "C" fn rs_glyph_info( + slot : Int, + cp : Int, + size : Int, + info : FixedArray[Int], +) = "rs_glyph_info" + +///| +#borrow(out) +extern "C" fn rs_glyph_coverage( + slot : Int, + cp : Int, + size : Int, + out : FixedArray[Byte], +) = "rs_glyph_coverage" + +///| +extern "C" fn rs_draw_glyph( + slot : Int, + cp : Int, + size : Int, + pen : Int, + baseline : Int, + r : Int, + g : Int, + b : Int, + a : Int, + embolden : Int, +) = "rs_draw_glyph" + +///| +#borrow(rgba) +extern "C" fn rs_image_put( + reuse : Int, + w : Int, + h : Int, + rgba : FixedArray[Byte], +) -> Int = "rs_image_put" + +///| +#borrow(data) +extern "C" fn rs_image_svg(data : Bytes) -> Int = "rs_image_svg" + +///| +extern "C" fn rs_draw_image(handle : Int, x : Int, y : Int, w : Int, h : Int) = "rs_draw_image" + +///| +extern "C" fn rs_capture( + fd : Int, + offset : Int, + stride : Int, + w : Int, + h : Int, + format : Int, +) -> UInt = "rs_capture" + +///| +extern "C" fn rs_release(id : UInt) = "rs_release" + +///| +extern "C" fn rs_thumbnail(id : UInt, w : Int, h : Int, reuse : Int) -> Int = "rs_thumbnail" + +///| +extern "C" fn rs_blit_surface(id : UInt, x : Int, y : Int, w : Int, h : Int) -> Int = "rs_blit_surface" + +///| +extern "C" fn rs_save_backdrop() = "rs_save_backdrop" + +///| +extern "C" fn rs_has_backdrop() -> Int = "rs_has_backdrop" + +///| +extern "C" fn rs_copy_backdrop() = "rs_copy_backdrop" + +///| +extern "C" fn rs_width() -> Int = "rs_width" + +///| +extern "C" fn rs_height() -> Int = "rs_height" + +///| +#borrow(out) +extern "C" fn rs_read_frame(out : FixedArray[Byte]) = "rs_read_frame" + +///| +extern "C" fn rs_export_memfd() -> Int = "rs_export_memfd" + +// ---------------------------------------------------------------- geometry + +///| +struct R { + x : Int + y : Int + w : Int + h : Int +} derive(Eq, Show) + +///| +fn R::empty(self : R) -> Bool { + self.w <= 0 || self.h <= 0 +} + +///| +fn rect_of(v : @wt.Val) -> R { + { + x: v.field("x").to_int(), + y: v.field("y").to_int(), + w: v.field("w").to_int(), + h: v.field("h").to_int(), + } +} + +///| The overlap of two clips (None: no clip). +fn intersect(a : R?, b : R?) -> R? { + match (a, b) { + (None, k) | (k, None) => k + (Some(a), Some(b)) => { + let x0 = @cmp.maximum(a.x, b.x) + let y0 = @cmp.maximum(a.y, b.y) + let x1 = @cmp.minimum(a.x + a.w, b.x + b.w) + let y1 = @cmp.minimum(a.y + a.h, b.y + b.h) + Some({ + x: x0, + y: y0, + w: @cmp.maximum(x1 - x0, 0), + h: @cmp.maximum(y1 - y0, 0), + }) + } + } +} + +///| The bounding box of two rectangles (an empty one counts for nothing). +fn union(a : R, b : R) -> R { + if a.empty() { + return b + } + if b.empty() { + return a + } + let x0 = @cmp.minimum(a.x, b.x) + let y0 = @cmp.minimum(a.y, b.y) + let x1 = @cmp.maximum(a.x + a.w, b.x + b.w) + let y1 = @cmp.maximum(a.y + a.h, b.y + b.h) + { x: x0, y: y0, w: x1 - x0, h: y1 - y0 } +} + +///| +fn set_clip(k : R?) -> Unit { + match k { + Some(r) => rs_set_clip(1, r.x, r.y, r.w, r.h) + None => rs_set_clip(0, 0, 0, 0, 0) + } +} + +// ---------------------------------------------------------------- text + +///| The font slot for (bold, mono), and whether its glyphs must be emboldened (a face with no +/// bold instance gets drawn a pixel wider). Slots: 0 mono, 1 mono bold, 2 sans. None when no +/// face is loaded at all. +fn pick_face(bold : Bool, mono : Bool) -> (Int, Bool)? { + let has_mono = rs_font_has(0) != 0 + let has_sans = rs_font_has(2) != 0 + if !has_mono && !has_sans { + return None + } + let has_bold = has_mono && rs_font_has(1) != 0 + Some( + if mono && has_mono { + if bold && has_bold { + (1, false) + } else { + (0, bold) + } + } else if has_sans { + (2, bold) + } else { + (0, bold) + }, + ) +} + +///| +let glyph_info : FixedArray[Int] = FixedArray::make(5, 0) + +///| Advance of `cp` in `slot`. +fn advance(slot : Int, cp : Int, size : Int) -> Int { + rs_glyph_info(slot, cp, size, glyph_info) + glyph_info[4] +} + +///| +fn draw_text(l : @wt.Val, ox : Int, oy : Int) -> Unit { + let text = l.field("text").to_string() + let col = l.field("color") + let ca = col.field("a").to_int() + if text == "" || ca == 0 { + return + } + let size = @cmp.maximum(l.field("size").to_int(), 0) + let bold = l.field("bold").to_bool() + let mono = l.field("mono").to_bool() + let (slot, embolden) = match pick_face(bold, mono) { + Some(f) => f + None => return // no face loaded: nothing to draw with + } + let extra = if embolden { 1 } else { 0 } + let cps : Array[Int] = [] + let mut total_w = 0 + for ch in text { + let cp = ch.to_int() + cps.push(cp) + total_w += advance(slot, cp, size) + extra + } + let x = l.field("x").to_int() + ox + let start_x = match l.field("align").to_int() { + 1 => x - total_w / 2 + 2 => x - total_w + _ => x + } + // `y` is the vertical centre of the text; centre the capital height ('H') on it. + let (cap_slot, _) = match pick_face(false, mono) { + Some(f) => f + None => return + } + rs_glyph_info(cap_slot, 72, size, glyph_info) + let baseline = l.field("y").to_int() + oy + -glyph_info[3] / 2 + let r = col.field("r").to_int() + let g = col.field("g").to_int() + let b = col.field("b").to_int() + let mut pen = start_x + for cp in cps { + rs_draw_glyph(slot, cp, size, pen, baseline, r, g, b, ca, extra) + pen += advance(slot, cp, size) + extra + } +} + +// ---------------------------------------------------------------- ops + +///| +fn rgba(c : @wt.Val) -> (Int, Int, Int, Int) { + ( + c.field("r").to_int(), + c.field("g").to_int(), + c.field("b").to_int(), + c.field("a").to_int(), + ) +} + +///| Draw `ops` offset by (ox, oy). `base` limits everything (the frame's damaged area); a +/// push-clip op replaces the clip within it. +fn draw_ops(ops : Array[@wt.Val], ox : Int, oy : Int, base : R?) -> Unit { + let stack : Array[R] = [] + set_clip(base) + for op in ops { + guard op is Variant(name, payload) + match (name, payload) { + ("fill-rect", Some(f)) => { + let a = rect_of(f.field("area")) + let (r, g, b, al) = rgba(f.field("color")) + rs_fill_rect( + a.x + ox, + a.y + oy, + a.w, + a.h, + r, + g, + b, + al, + f.field("radius").to_int(), + ) + } + ("stroke-rect", Some(s)) => { + let a = rect_of(s.field("area")) + let (r, g, b, al) = rgba(s.field("color")) + rs_stroke_rect( + a.x + ox, + a.y + oy, + a.w, + a.h, + r, + g, + b, + al, + s.field("width").to_int(), + s.field("radius").to_int(), + ) + } + ("draw-line", Some(s)) => { + let (r, g, b, al) = rgba(s.field("color")) + rs_line( + s.field("x0").to_int() + ox, + s.field("y0").to_int() + oy, + s.field("x1").to_int() + ox, + s.field("y1").to_int() + oy, + r, + g, + b, + al, + s.field("width").to_int(), + ) + } + ("draw-circle", Some(d)) => { + let (r, g, b, al) = rgba(d.field("color")) + rs_circle( + d.field("cx").to_int() + ox, + d.field("cy").to_int() + oy, + d.field("radius").to_int(), + r, + g, + b, + al, + if d.field("filled").to_bool() { + 1 + } else { + 0 + }, + ) + } + ("draw-text", Some(l)) => draw_text(l, ox, oy) + ("push-clip", Some(k)) => { + let k = rect_of(k) + stack.push({ x: k.x + ox, y: k.y + oy, w: k.w, h: k.h }) + set_clip(intersect(Some(stack[stack.length() - 1]), base)) + } + ("pop-clip", _) => { + stack.pop() |> ignore + set_clip( + if stack.length() > 0 { + intersect(Some(stack[stack.length() - 1]), base) + } else { + base + }, + ) + } + ("draw-image", Some(p)) => { + let a = rect_of(p.field("area")) + rs_draw_image(p.field("image").to_int(), a.x + ox, a.y + oy, a.w, a.h) + } + _ => () + } + } +} + +// ---------------------------------------------------------------- frames + +///| A frame as the compositor sent it (the parts compared to find what changed). +struct Frame { + width : Int + height : Int + wallpaper : @wt.Val? // Some(ops) when sent with this frame + background : @wt.Val + windows : Array[@wt.Val] + panel : @wt.Val + popups : @wt.Val +} + +///| The last frame drawn, and the wallpaper ops the cached backdrop was drawn from. +let prev_frame : Ref[Frame?] = Ref(None) + +///| +let backdrop_ops : Ref[@wt.Val?] = Ref(None) + +///| Room around a window for its drop shadow (4 px right, 6 px down) and a little slack. +const SHADOW_PAD : Int = 8 + +///| What a window covers on screen: its decoration and drop shadow, or just itself when fullscreen. +fn window_footprint(win : @wt.Val) -> R { + let g = rect_of(win.field("geometry")) + if win.field("fullscreen").to_bool() { + return g + } + let it = win.field("inset-top").to_int() + let ir = win.field("inset-right").to_int() + let ib = win.field("inset-bottom").to_int() + let il = win.field("inset-left").to_int() + { + x: g.x - il - SHADOW_PAD, + y: g.y - it - SHADOW_PAD, + w: g.w + il + ir + 2 * SHADOW_PAD, + h: g.h + it + ib + 2 * SHADOW_PAD, + } +} + +///| The part of the screen `f` changes over `prev`, as one rectangle; None when all of it must +/// be redrawn. Only window changes are narrowed down: any change to the wallpaper, desktop card, +/// panel or the set of windows redraws everything. +fn damage(prev : Frame, f : Frame) -> R? { + if prev.width != f.width || + prev.height != f.height || + prev.windows.length() != f.windows.length() { + return None + } + if f.background != prev.background || f.panel != prev.panel { + return None + } + if f.wallpaper is Some(ops) && prev.wallpaper != Some(ops) { + return None + } + let mut d : R = { x: 0, y: 0, w: 0, h: 0 } + for i, a in prev.windows { + let b = f.windows[i] + if a == b { + continue + } + d = union(d, union(window_footprint(a), window_footprint(b))) + } + if prev.popups != f.popups { + for p in prev.popups.to_list() { + d = union(d, rect_of(p.field("area"))) + } + for p in f.popups.to_list() { + d = union(d, rect_of(p.field("area"))) + } + } + Some(d) +} + +///| Remember `f` as the last frame. Its wallpaper ops are kept from the frame that sent them, so +/// a later frame that resends the same wallpaper still compares equal. +fn keep_prev(f : Frame) -> Unit { + let wallpaper = match f.wallpaper { + Some(_) => f.wallpaper + None => + match prev_frame.val { + Some(p) => p.wallpaper + None => None + } + } + prev_frame.val = Some({ ..f, wallpaper, }) +} + +///| Pixels redrawn by the last submit (for --profile). +let last_drawn : Ref[Int] = Ref(0) + +///| Draw a frame into the framebuffer: wallpaper (cached), background, windows bottom to top, +/// panel, then client popups. The same layering as the software renderer's `render_scene`. Only +/// the part that differs from the last frame is redrawn. +fn submit(v : @wt.Val) -> Unit { + let f : Frame = { + width: @cmp.maximum(v.field("width").to_int(), 1), + height: @cmp.maximum(v.field("height").to_int(), 1), + wallpaper: v.field("wallpaper").to_option(), + background: v.field("background"), + windows: v.field("windows").to_list(), + panel: v.field("panel"), + popups: v.field("popups"), + } + let w = f.width + let h = f.height + let resized = rs_resize(w, h) != 0 + // The frame starts from the cached backdrop (which covers every pixel), so the buffer is only + // cleared when there is none. + let backdrop_ready = rs_has_backdrop() != 0 && + (match (f.wallpaper, backdrop_ops.val) { + (None, Some(_)) => true + (Some(ops), Some(o)) => o == ops + _ => false + }) + let clip : R? = match prev_frame.val { + Some(prev) if !resized && backdrop_ready => + match damage(prev, f) { + Some(d) => + match intersect(Some(d), Some({ x: 0, y: 0, w, h })) { + Some(k) if !k.empty() => Some(k) + _ => { + // Nothing on screen changed (a window off screen, say). + last_drawn.val = 0 + keep_prev(f) + return + } + } + None => None + } + _ => None + } + if !resized && !backdrop_ready { + rs_clear() + } + last_drawn.val = match clip { + Some(k) => k.w * k.h + None => w * h + } + + // 1. Wallpaper: drawn once, copied back while unchanged (only the damaged part). + match f.wallpaper { + Some(ops) => + if backdrop_ready { + set_clip(clip) + rs_copy_backdrop() + } else { + draw_ops(ops.to_list(), 0, 0, None) + rs_save_backdrop() + backdrop_ops.val = Some(ops) + } + None => + if rs_has_backdrop() != 0 { + set_clip(clip) + rs_copy_backdrop() + } + } + draw_ops(f.background.to_list(), 0, 0, clip) + + // 2. Windows, bottom to top. + for win in f.windows { + let g = rect_of(win.field("geometry")) + if clip is Some(_) { + match intersect(Some(window_footprint(win)), clip) { + Some(r) if !r.empty() => () + _ => continue + } + } + if !win.field("fullscreen").to_bool() { + let it = win.field("inset-top").to_int() + let ir = win.field("inset-right").to_int() + let ib = win.field("inset-bottom").to_int() + let il = win.field("inset-left").to_int() + let outer_x = g.x - il + let outer_y = g.y - it + let outer_w = g.w + il + ir + let outer_h = g.h + it + ib + // Subtle drop shadow: only the strips that stick out from under the window (and the part + // under the translucent title bar) are blended. + let strips : Array[R] = [ + { x: outer_x + outer_w, y: outer_y, w: 4, h: outer_h + 6 }, + { x: outer_x, y: outer_y + outer_h, w: outer_w + 4, h: 6 }, + { x: outer_x, y: outer_y, w: outer_w, h: it + 2 }, + ] + for s in strips { + match intersect(Some(s), clip) { + Some(k) if !k.empty() => { + set_clip(Some(k)) + rs_fill_rect(outer_x + 4, outer_y + 6, outer_w, outer_h, 0, 0, 0, 80, 8) + } + _ => () + } + } + draw_ops(win.field("deco").to_list(), outer_x, outer_y, clip) + } + set_clip(clip) + if rs_blit_surface(win.field("surface").to_uint(), g.x, g.y, g.w, g.h) == 0 { + rs_fill_rect(g.x, g.y, g.w, g.h, 0x1e, 0x29, 0x3b, 0xff, 0) + } + } + + // 3. Panel (and its popups, menus and notices), then 4. client popups above everything. + draw_ops(f.panel.to_list(), 0, 0, clip) + set_clip(clip) + for p in f.popups.to_list() { + let a = rect_of(p.field("area")) + rs_blit_surface(p.field("surface").to_uint(), a.x, a.y, a.w, a.h) |> ignore + } + keep_prev(f) +} + +// ---------------------------------------------------------------- images + +///| Image handles by path (0: it failed, don't try again). +let image_paths : Map[String, Int] = {} + +///| Biggest image side accepted from a file. +const MAX_IMAGE : Int = 1024 + +///| Load the PNG or SVG at `path` (an app icon); the same path gives the same handle. 0 on failure. +fn load_image(path : String) -> Int { + match image_paths.get(path) { + Some(h) => return h + None => () + } + let b = @sys.read_file_bytes(path) + let h = if b.length() > 8 && b[0] == b'\x89' && b[1] == b'P' && b[2] == b'N' { + match @renderer.decode_png(b) { + Some(p) if p.width <= MAX_IMAGE && p.height <= MAX_IMAGE => + rs_image_put(0, p.width, p.height, p.data) + _ => 0 + } + } else if path.has_suffix(".svg") && b.length() > 0 { + rs_image_svg(b) + } else { + 0 + } + image_paths.set(path, h) + h +} + +///| +fn is_path_image(h : Int) -> Bool { + for _, v in image_paths { + if v == h { + return true + } + } + false +} + +// ---------------------------------------------------------------- the interfaces + +///| +fn font_funcs() -> Array[(String, (Array[@wt.Val]) -> Array[@wt.Val])] { + [ + ( + "load", + a => boolean(font_load(a[0].to_int(), a[1].to_string())), + ), + ( + "rasterise", + a => { + let (slot, cp, size) = (a[0].to_int(), a[1].to_int(), a[2].to_int()) + let info = FixedArray::make(5, 0) + rs_glyph_info(slot, cp, size, info) + let cov = FixedArray::make(info[0] * info[1], b'\x00') + if cov.length() > 0 { + rs_glyph_coverage(slot, cp, size, cov) + } + [ + Record([ + ("width", S32(info[0])), + ("height", S32(info[1])), + ("xoff", S32(info[2])), + ("yoff", S32(info[3])), + ("advance", S32(info[4])), + ("coverage", @wt.Val::bytes(Bytes::from_fixedarray(cov))), + ]), + ] + }, + ), + ] +} + +///| +fn raster_funcs() -> Array[(String, (Array[@wt.Val]) -> Array[@wt.Val])] { + [ + ( + "capture", + a => [ + U32( + rs_capture( + a[0].to_int(), + a[1].to_int(), + a[2].to_int(), + a[3].to_int(), + a[4].to_int(), + a[5].to_int(), + ), + ), + ], + ), + ( + "release", + a => { + rs_release(a[0].to_uint()) + none + }, + ), + ("load-image", a => [U32(load_image(a[0].to_string()).reinterpret_as_uint())]), + ( + "thumbnail", + a => { + let reuse = a[3].to_int() + let reuse = if is_path_image(reuse) { 0 } else { reuse } + [ + U32( + rs_thumbnail(a[0].to_uint(), a[1].to_int(), a[2].to_int(), reuse).reinterpret_as_uint(), + ), + ] + }, + ), + ( + "submit", + a => { + submit(a[0]) + none + }, + ), + ( + "read-frame", + _ => { + let out = FixedArray::make(rs_width() * rs_height() * 4, b'\x00') + rs_read_frame(out) + [@wt.Val::bytes(Bytes::from_fixedarray(out))] + }, + ), + ("export-memfd", _ => s32(rs_export_memfd())), + ] +} diff --git a/wasmhost/bin/raster_stub.c b/wasmhost/bin/raster_stub.c new file mode 100644 index 0000000..e4df32d --- /dev/null +++ b/wasmhost/bin/raster_stub.c @@ -0,0 +1,600 @@ +/* The host's rasteriser (chandra:host/raster), pixel work in C. + * + * A port of host-wasm/src/raster.rs, itself a port of compositor/renderer, so a frame comes out + * pixel for pixel the same. raster.mbt decides what to draw (layers, damage, the wallpaper cache); + * this file owns the framebuffer, the captured client surfaces, the images and the glyph cache, + * and draws one primitive per call, inside the current clip. + * + * Glyphs come from stb_truetype through compositor/font's shim (mp_font_*); SVG icons from + * nanosvg (third_party/nanosvg). */ +#define _GNU_SOURCE +#include +#include +#include +#include +#include +#include +#include +#include +#include "moonbit.h" + +#define NANOSVG_IMPLEMENTATION +#define NANOSVGRAST_IMPLEMENTATION +#include "../../third_party/nanosvg/nanosvg.h" +#include "../../third_party/nanosvg/nanosvgrast.h" + +/* compositor/font/font_stub.c */ +int32_t mp_font_load(int32_t slot, moonbit_bytes_t path_bytes); +void mp_font_metrics(int32_t slot, int32_t cp, int32_t size, int32_t *info); +void mp_font_bitmap(int32_t slot, int32_t cp, int32_t size, int32_t w, int32_t h, moonbit_bytes_t buf); + +/* ------------------------------------------------------------------ canvas */ + +static int32_t fb_w, fb_h; +static uint8_t *fb; /* RGBA8888 */ + +static int clip_on; +static int32_t clip_x, clip_y, clip_w, clip_h; + +static inline int clamp_u8(int v) { return v < 0 ? 0 : v > 255 ? 255 : v; } +static inline int imin(int a, int b) { return a < b ? a : b; } +static inline int imax(int a, int b) { return a > b ? a : b; } + +/* Resize the framebuffer (zeroed). 1 when the size changed. */ +int32_t rs_resize(int32_t w, int32_t h) { + if (w < 1) w = 1; + if (h < 1) h = 1; + if (fb && w == fb_w && h == fb_h) return 0; + free(fb); + fb = calloc((size_t)w * h, 4); + fb_w = w; + fb_h = h; + return 1; +} + +void rs_clear(void) { if (fb) memset(fb, 0, (size_t)fb_w * fb_h * 4); } + +void rs_set_clip(int32_t on, int32_t x, int32_t y, int32_t w, int32_t h) { + clip_on = on; + clip_x = x; clip_y = y; clip_w = w; clip_h = h; +} + +static inline void blend_pixel(int x, int y, int r, int g, int b, int a) { + if (x < 0 || y < 0 || x >= fb_w || y >= fb_h || a <= 0) return; + if (clip_on && (x < clip_x || y < clip_y || x >= clip_x + clip_w || y >= clip_y + clip_h)) return; + uint8_t *d = fb + ((size_t)y * fb_w + x) * 4; + if (a >= 255) { + d[0] = (uint8_t)r; d[1] = (uint8_t)g; d[2] = (uint8_t)b; d[3] = 0xff; + return; + } + int inv = 255 - a; + d[0] = (uint8_t)((r * a + d[0] * inv + 127) / 255); + d[1] = (uint8_t)((g * a + d[1] * inv + 127) / 255); + d[2] = (uint8_t)((b * a + d[2] * inv + 127) / 255); + d[3] = (uint8_t)clamp_u8(a + (d[3] * inv + 127) / 255); +} + +/* Blend a colour over pixels [xa, xb) of row y; the span is already clipped. */ +static void blend_span(int y, int xa, int xb, int r, int g, int b, int a) { + if (xa >= xb || a <= 0) return; + uint8_t *p = fb + ((size_t)y * fb_w + xa) * 4, *end = fb + ((size_t)y * fb_w + xb) * 4; + if (a >= 255) { + for (; p < end; p += 4) { p[0] = (uint8_t)r; p[1] = (uint8_t)g; p[2] = (uint8_t)b; p[3] = 0xff; } + return; + } + int inv = 255 - a, ra = r * a + 127, ga = g * a + 127, ba = b * a + 127; + for (; p < end; p += 4) { + p[0] = (uint8_t)((ra + p[0] * inv) / 255); + p[1] = (uint8_t)((ga + p[1] * inv) / 255); + p[2] = (uint8_t)((ba + p[2] * inv) / 255); + p[3] = (uint8_t)clamp_u8(a + (p[3] * inv + 127) / 255); + } +} + +static int in_rounded_rect(int px, int py, int rx, int ry, int rw, int rh, int rad) { + if (px < rx || py < ry || px >= rx + rw || py >= ry + rh) return 0; + if (rad <= 0) return 1; + int r = imin(rad, imin(rw, rh) / 2); + if (r <= 0) return 1; + int x_left = rx + r, x_right = rx + rw - r - 1, y_top = ry + r, y_bot = ry + rh - r - 1; +#define CORNER(dx, dy) ((dx) * (dx) + (dy) * (dy) <= r * r) + if (px < x_left && py < y_top) return CORNER(x_left - px, y_top - py); + if (px > x_right && py < y_top) return CORNER(px - x_right, y_top - py); + if (px < x_left && py > y_bot) return CORNER(x_left - px, py - y_bot); + if (px > x_right && py > y_bot) return CORNER(px - x_right, py - y_bot); +#undef CORNER + return 1; +} + +/* The part of the rect on the canvas and inside the clip. 0 when empty. */ +static int visible(int x, int y, int w, int h, int *x0, int *y0, int *x1, int *y1) { + *x0 = imax(x, 0); *y0 = imax(y, 0); + *x1 = imin(x + w, fb_w); *y1 = imin(y + h, fb_h); + if (clip_on) { + *x0 = imax(*x0, clip_x); *y0 = imax(*y0, clip_y); + *x1 = imin(*x1, clip_x + clip_w); *y1 = imin(*y1, clip_y + clip_h); + } + return *x0 < *x1 && *y0 < *y1; +} + +void rs_fill_rect(int32_t x, int32_t y, int32_t w, int32_t h, int32_t cr, int32_t cg, int32_t cb, int32_t ca, + int32_t radius) { + if (!fb || w <= 0 || h <= 0 || ca == 0) return; + int x0, y0, x1, y1; + if (!visible(x, y, w, h, &x0, &y0, &x1, &y1)) return; + if (radius <= 0) { + for (int yy = y0; yy < y1; yy++) blend_span(yy, x0, x1, cr, cg, cb, ca); + return; + } + int r = imin(radius, imin(w, h) / 2); + int x_left = x + r, x_right = x + w - r - 1, y_top = y + r, y_bot = y + h - r - 1; + for (int yy = y0; yy < y1; yy++) { + if (yy >= y_top && yy <= y_bot) { blend_span(yy, x0, x1, cr, cg, cb, ca); continue; } + int xx = x0; + while (xx < x1 && xx < x_left) { + if (in_rounded_rect(xx, yy, x, y, w, h, radius)) blend_span(yy, xx, xx + 1, cr, cg, cb, ca); + xx++; + } + int mid_a = imax(x_left, x0), mid_b = imin(x_right + 1, x1); + blend_span(yy, mid_a, mid_b, cr, cg, cb, ca); + xx = imax(imax(x_right + 1, x0), mid_a); + while (xx < x1) { + if (in_rounded_rect(xx, yy, x, y, w, h, radius)) blend_span(yy, xx, xx + 1, cr, cg, cb, ca); + xx++; + } + } +} + +void rs_stroke_rect(int32_t x, int32_t y, int32_t w, int32_t h, int32_t cr, int32_t cg, int32_t cb, int32_t ca, + int32_t width, int32_t radius) { + if (!fb || w <= 0 || h <= 0 || width <= 0 || ca == 0) return; + int x0 = imax(x, 0), y0 = imax(y, 0), x1 = imin(x + w, fb_w), y1 = imin(y + h, fb_h); + int inner_x = x + width, inner_y = y + width, inner_w = w - width * 2, inner_h = h - width * 2; + int inner_r = radius > width ? radius - width : 0; + int cx0 = clip_on ? clip_x : 0, cx1 = clip_on ? clip_x + clip_w : fb_w; + int cy0 = clip_on ? clip_y : 0, cy1 = clip_on ? clip_y + clip_h : fb_h; + int mid_a = inner_y + inner_r, mid_b = inner_y + inner_h - inner_r; + for (int yy = y0; yy < y1; yy++) { + if (inner_w > 0 && inner_h > 0 && yy >= mid_a && yy < mid_b) { + if (yy >= cy0 && yy < cy1) { + int l0 = imax(x0, cx0), l1 = imin(imin(inner_x, x1), cx1); + blend_span(yy, l0, l1, cr, cg, cb, ca); + int r0 = imax(imax(inner_x + inner_w, x0), cx0); + blend_span(yy, r0, imin(x1, cx1), cr, cg, cb, ca); + } + continue; + } + for (int xx = x0; xx < x1; xx++) { + int in_outer = in_rounded_rect(xx, yy, x, y, w, h, radius); + int in_inner = inner_w > 0 && inner_h > 0 && in_rounded_rect(xx, yy, inner_x, inner_y, inner_w, inner_h, inner_r); + if (in_outer && !in_inner) blend_pixel(xx, yy, cr, cg, cb, ca); + } + } +} + +void rs_line(int32_t x0, int32_t y0, int32_t x1, int32_t y1, int32_t cr, int32_t cg, int32_t cb, int32_t ca, + int32_t width) { + if (!fb) return; + int half = width <= 1 ? 0 : width / 2; + int dx = abs(x1 - x0), sx = x0 < x1 ? 1 : -1; + int dy = -abs(y1 - y0), sy = y0 < y1 ? 1 : -1; + int err = dx + dy; + for (;;) { + for (int oy = -half; oy <= half; oy++) + for (int ox = -half; ox <= half; ox++) blend_pixel(x0 + ox, y0 + oy, cr, cg, cb, ca); + if (x0 == x1 && y0 == y1) break; + int e2 = 2 * err; + if (e2 >= dy) { err += dy; x0 += sx; } + if (e2 <= dx) { err += dx; y0 += sy; } + } +} + +void rs_circle(int32_t cx, int32_t cy, int32_t radius, int32_t cr, int32_t cg, int32_t cb, int32_t ca, + int32_t filled) { + if (!fb || radius <= 0) return; + double rad = radius; + for (int dy = -radius - 1; dy <= radius + 1; dy++) { + for (int dx = -radius - 1; dx <= radius + 1; dx++) { + double dist = sqrt((double)(dx * dx + dy * dy)); + double outer = rad + 0.5 - dist; + double cov = outer > 1.0 ? 1.0 : outer; + if (!filled) { + double inner = dist - (rad - 1.0 - 0.5); + double ic = inner > 1.0 ? 1.0 : inner; + if (ic < cov) cov = ic; + } + if (cov > 0.02) blend_pixel(cx + dx, cy + dy, cr, cg, cb, (int)round(ca * cov)); + } + } +} + +/* ------------------------------------------------------------------ glyphs */ + +typedef struct Glyph { + int32_t slot, cp, size; + int32_t w, h, xoff, yoff, advance; + uint8_t *coverage; + struct Glyph *next; +} Glyph; + +#define GLYPH_BUCKETS 4096 +static Glyph *glyphs[GLYPH_BUCKETS]; +static int font_loaded[4]; + +static Glyph *glyph(int32_t slot, int32_t cp, int32_t size) { + uint32_t hsh = ((uint32_t)slot * 2654435761u) ^ ((uint32_t)cp * 40503u) ^ ((uint32_t)size * 977u); + Glyph **b = &glyphs[hsh % GLYPH_BUCKETS]; + for (Glyph *g = *b; g; g = g->next) + if (g->slot == slot && g->cp == cp && g->size == size) return g; + Glyph *g = calloc(1, sizeof *g); + g->slot = slot; g->cp = cp; g->size = size; + int32_t info[5] = {0}; + if (slot >= 0 && slot < 4 && font_loaded[slot]) mp_font_metrics(slot, cp, size, info); + g->w = info[0]; g->h = info[1]; g->xoff = info[2]; g->yoff = info[3]; g->advance = info[4]; + if (g->w > 0 && g->h > 0) { + /* The shim checks the buffer's MoonBit length: hand it a real MoonBit byte string. */ + moonbit_bytes_t buf = moonbit_make_bytes(g->w * g->h, 0); + mp_font_bitmap(slot, cp, size, g->w, g->h, buf); + g->coverage = malloc((size_t)g->w * g->h); + memcpy(g->coverage, buf, (size_t)g->w * g->h); + moonbit_decref(buf); + } else { + g->w = g->h = 0; + } + g->next = *b; + *b = g; + return g; +} + +static void drop_glyphs(int32_t slot) { + for (int i = 0; i < GLYPH_BUCKETS; i++) { + Glyph **p = &glyphs[i]; + while (*p) { + Glyph *g = *p; + if (g->slot == slot) { *p = g->next; free(g->coverage); free(g); } + else p = &g->next; + } + } +} + +/* Slot `slot` now holds a newly loaded face (raster.mbt loads it with mp_font_load, which also + * links compositor/font's shim in). */ +void rs_font_loaded(int32_t slot) { + if (slot < 0 || slot >= 4) return; + font_loaded[slot] = 1; + drop_glyphs(slot); +} + +int32_t rs_font_has(int32_t slot) { return slot >= 0 && slot < 4 && font_loaded[slot]; } + +/* Metrics into info: width, height, xoff, yoff, advance. */ +void rs_glyph_info(int32_t slot, int32_t cp, int32_t size, int32_t *info) { + Glyph *g = glyph(slot, cp, size); + info[0] = g->w; info[1] = g->h; info[2] = g->xoff; info[3] = g->yoff; info[4] = g->advance; +} + +/* The coverage bitmap (w * h bytes) into `out`. */ +void rs_glyph_coverage(int32_t slot, int32_t cp, int32_t size, moonbit_bytes_t out) { + Glyph *g = glyph(slot, cp, size); + size_t n = (size_t)g->w * g->h, cap = (size_t)Moonbit_array_length(out); + if (g->coverage && n <= cap) memcpy(out, g->coverage, n); +} + +void rs_draw_glyph(int32_t slot, int32_t cp, int32_t size, int32_t pen, int32_t baseline, int32_t cr, int32_t cg, + int32_t cb, int32_t ca, int32_t embolden) { + if (!fb) return; + Glyph *g = glyph(slot, cp, size); + for (int row = 0; row < g->h; row++) { + for (int col = 0; col < g->w; col++) { + int cov = g->coverage[row * g->w + col]; + if (cov > 0) { + int px = pen + g->xoff + col, py = baseline + g->yoff + row; + blend_pixel(px, py, cr, cg, cb, ca * cov / 255); + if (embolden) blend_pixel(px + 1, py, cr, cg, cb, ca * cov / 255); + } + } + } +} + +/* ------------------------------------------------------------------ images */ + +#define MAX_IMAGE 1024 + +typedef struct Sized { int32_t w, h; uint8_t *rgba; struct Sized *next; } Sized; +typedef struct { + int used; + int32_t w, h; + uint8_t *rgba; /* pixels, or NULL for an SVG */ + NSVGimage *svg; + Sized *sized; /* the image at the sizes it was drawn at */ +} Image; + +static Image *images; +static int32_t n_images, cap_images; + +/* Scale RGBA src (sw x sh) to w x h: average of the covered source pixels (alpha weighted), the + * nearest one when enlarging. Same as the software renderer. */ +static uint8_t *scale_rgba(const uint8_t *src, int sw, int sh, int w, int h) { + uint8_t *out = calloc((size_t)w * h, 4); + for (int y = 0; y < h; y++) { + int y0 = y * sh / h, y1 = imax((y + 1) * sh / h, y0 + 1); + for (int x = 0; x < w; x++) { + int x0 = x * sw / w, x1 = imax((x + 1) * sw / w, x0 + 1); + int64_t r = 0, g = 0, b = 0, a = 0, n = 0; + for (int sy = y0; sy < y1; sy++) { + for (int sx = x0; sx < x1; sx++) { + const uint8_t *p = src + ((size_t)sy * sw + sx) * 4; + int64_t pa = p[3]; + r += p[0] * pa; g += p[1] * pa; b += p[2] * pa; a += pa; n++; + } + } + if (a > 0) { + uint8_t *o = out + ((size_t)y * w + x) * 4; + o[0] = (uint8_t)(r / a); o[1] = (uint8_t)(g / a); o[2] = (uint8_t)(b / a); o[3] = (uint8_t)(a / n); + } + } + } + return out; +} + +static void image_reset(Image *im) { + free(im->rgba); + if (im->svg) nsvgDelete(im->svg); + for (Sized *s = im->sized; s;) { Sized *n = s->next; free(s->rgba); free(s); s = n; } + memset(im, 0, sizeof *im); +} + +static int32_t image_slot(int32_t reuse) { + if (reuse > 0 && reuse <= n_images) { + image_reset(&images[reuse - 1]); + images[reuse - 1].used = 1; + return reuse; + } + if (n_images == cap_images) { + cap_images = cap_images ? cap_images * 2 : 64; + images = realloc(images, sizeof(Image) * (size_t)cap_images); + } + memset(&images[n_images], 0, sizeof(Image)); + images[n_images].used = 1; + return ++n_images; +} + +/* Store w x h RGBA pixels as an image: overwrite `reuse` when it is an earlier handle, else add one. */ +int32_t rs_image_put(int32_t reuse, int32_t w, int32_t h, moonbit_bytes_t rgba) { + if (w <= 0 || h <= 0 || w > MAX_IMAGE || h > MAX_IMAGE) return 0; + if ((size_t)Moonbit_array_length(rgba) < (size_t)w * h * 4) return 0; + int32_t id = image_slot(reuse); + Image *im = &images[id - 1]; + im->w = w; im->h = h; + im->rgba = malloc((size_t)w * h * 4); + memcpy(im->rgba, rgba, (size_t)w * h * 4); + return id; +} + +/* An SVG document (its bytes) as an image, rendered sharp at each size it is drawn at. 0 when it + * doesn't parse. */ +int32_t rs_image_svg(moonbit_bytes_t data) { + size_t n = (size_t)Moonbit_array_length(data); + char *text = malloc(n + 1); + memcpy(text, data, n); + text[n] = 0; + NSVGimage *svg = nsvgParse(text, "px", 96.0f); + free(text); + if (!svg) return 0; + if (svg->width <= 0 || svg->height <= 0 || !svg->shapes) { nsvgDelete(svg); return 0; } + int32_t id = image_slot(0); + images[id - 1].svg = svg; + return id; +} + +static uint8_t *render_svg(NSVGimage *svg, int w, int h) { + static NSVGrasterizer *rast; + if (!rast) rast = nsvgCreateRasterizer(); + uint8_t *out = calloc((size_t)w * h, 4); + float k = fminf((float)w / svg->width, (float)h / svg->height); + float dx = ((float)w - svg->width * k) / 2.0f, dy = ((float)h - svg->height * k) / 2.0f; + nsvgRasterize(rast, svg, dx, dy, k, out, w, h, w * 4); /* straight (not premultiplied) RGBA */ + return out; +} + +static const uint8_t *image_sized(int32_t handle, int w, int h) { + if (w <= 0 || h <= 0 || w > MAX_IMAGE || h > MAX_IMAGE) return NULL; + if (handle <= 0 || handle > n_images || !images[handle - 1].used) return NULL; + Image *im = &images[handle - 1]; + if (im->rgba && im->w == w && im->h == h) return im->rgba; + for (Sized *s = im->sized; s; s = s->next) + if (s->w == w && s->h == h) return s->rgba; + uint8_t *px = im->svg ? render_svg(im->svg, w, h) : im->rgba ? scale_rgba(im->rgba, im->w, im->h, w, h) : NULL; + if (!px) return NULL; + Sized *s = malloc(sizeof *s); + s->w = w; s->h = h; s->rgba = px; s->next = im->sized; + im->sized = s; + return px; +} + +void rs_draw_image(int32_t handle, int32_t x0, int32_t y0, int32_t w, int32_t h) { + if (!fb) return; + const uint8_t *px = image_sized(handle, w, h); + if (!px) return; + for (int y = 0; y < h; y++) + for (int x = 0; x < w; x++) { + const uint8_t *p = px + ((size_t)y * w + x) * 4; + blend_pixel(x0 + x, y0 + y, p[0], p[1], p[2], p[3]); + } +} + +/* ------------------------------------------------------------------ surfaces */ + +typedef struct Surface { + uint32_t id; + int32_t w, h; + uint8_t *rgba; + int opaque; /* every pixel has alpha 255: blits copy rows */ + struct Surface *next; +} Surface; + +#define SURF_BUCKETS 256 +static Surface *surfaces[SURF_BUCKETS]; +static uint32_t next_surface; + +static Surface *surface(uint32_t id) { + for (Surface *s = surfaces[id % SURF_BUCKETS]; s; s = s->next) + if (s->id == id) return s; + return NULL; +} + +/* Copy a client buffer (stride * height bytes at `offset` of the file behind fd, little-endian + * B, G, R, A/X) into a surface. 0 on failure. */ +uint32_t rs_capture(int32_t fd, int32_t offset, int32_t stride, int32_t w, int32_t h, int32_t format) { + if (fd < 0 || offset < 0 || stride <= 0 || w <= 0 || h <= 0 || stride < w * 4) return 0; + int64_t len = (int64_t)stride * h, end = offset + len; + struct stat st; + if (fstat(fd, &st) < 0 || st.st_size < end) return 0; + /* Mapping a large pool only reserves address space; just the pages copied are touched. */ + uint8_t *p = mmap(NULL, (size_t)end, PROT_READ, MAP_SHARED, fd, 0); + if (p == MAP_FAILED) return 0; + const uint8_t *src = p + offset; + uint8_t *rgba = malloc((size_t)w * h * 4); + int opaque = 1, xrgb = format == 1; + for (int y = 0; y < h; y++) { + const uint8_t *s = src + (size_t)y * stride; + uint8_t *d = rgba + (size_t)y * w * 4; + for (int x = 0; x < w; x++, s += 4, d += 4) { + d[0] = s[2]; d[1] = s[1]; d[2] = s[0]; + d[3] = xrgb ? 0xff : s[3]; + opaque &= d[3] == 0xff; + } + } + munmap(p, (size_t)end); + do { next_surface++; } while (next_surface == 0 || surface(next_surface)); + Surface *sf = malloc(sizeof *sf); + sf->id = next_surface; sf->w = w; sf->h = h; sf->rgba = rgba; sf->opaque = opaque; + sf->next = surfaces[sf->id % SURF_BUCKETS]; + surfaces[sf->id % SURF_BUCKETS] = sf; + return sf->id; +} + +void rs_release(uint32_t id) { + Surface **p = &surfaces[id % SURF_BUCKETS]; + while (*p) { + if ((*p)->id == id) { Surface *s = *p; *p = s->next; free(s->rgba); free(s); return; } + p = &(*p)->next; + } +} + +int32_t rs_surface_count(void) { + int n = 0; + for (int i = 0; i < SURF_BUCKETS; i++) for (Surface *s = surfaces[i]; s; s = s->next) n++; + return n; +} + +/* A w x h scaled copy of surface `id` as an image (see rs_image_put for `reuse`). */ +int32_t rs_thumbnail(uint32_t id, int32_t w, int32_t h, int32_t reuse) { + if (w <= 0 || h <= 0 || w > MAX_IMAGE || h > MAX_IMAGE) return 0; + Surface *s = surface(id); + if (!s) return 0; + uint8_t *px = scale_rgba(s->rgba, s->w, s->h, w, h); + int32_t img = image_slot(reuse); + images[img - 1].w = w; images[img - 1].h = h; images[img - 1].rgba = px; + return img; +} + +/* Draw surface `id` into (x, y, w, h). While a client catches up with a resize its buffer is + * smaller than the window: the buffer's bottom-right colour is extended over the rest. + * 0 when there is no such surface. */ +int32_t rs_blit_surface(uint32_t id, int32_t dx, int32_t dy, int32_t dw, int32_t dh) { + Surface *s = surface(id); + if (!s) return 0; + if (!fb || s->w <= 0 || s->h <= 0 || dw <= 0 || dh <= 0) return 1; + if (s->w < dw || s->h < dh) { + const uint8_t *o = s->rgba + ((size_t)(s->h - 1) * s->w + (s->w - 1)) * 4; + rs_fill_rect(dx, dy, dw, dh, o[0], o[1], o[2], o[3], 0); + } + int copy_w = imin(s->w, dw), copy_h = imin(s->h, dh); + int c0 = imax(-dx, 0), c1 = imin(copy_w, fb_w - dx); + int r0 = imax(-dy, 0), r1 = imin(copy_h, fb_h - dy); + if (clip_on) { + c0 = imax(c0, clip_x - dx); c1 = imin(c1, clip_x + clip_w - dx); + r0 = imax(r0, clip_y - dy); r1 = imin(r1, clip_y + clip_h - dy); + } + if (c0 >= c1 || r0 >= r1) return 1; + for (int row = r0; row < r1; row++) { + const uint8_t *src = s->rgba + ((size_t)row * s->w + c0) * 4; + uint8_t *dst = fb + ((size_t)(dy + row) * fb_w + dx + c0) * 4; + size_t n = (size_t)(c1 - c0) * 4; + if (s->opaque) { memcpy(dst, src, n); continue; } + for (size_t i = 0; i < n; i += 4) { + int a = src[i + 3]; + if (a >= 255) memcpy(dst + i, src + i, 4); + else if (a > 0) { + /* wl_shm ARGB8888 is premultiplied: the colour already carries its alpha. */ + int inv = 255 - a; + dst[i] = (uint8_t)clamp_u8(src[i] + (dst[i] * inv + 127) / 255); + dst[i + 1] = (uint8_t)clamp_u8(src[i + 1] + (dst[i + 1] * inv + 127) / 255); + dst[i + 2] = (uint8_t)clamp_u8(src[i + 2] + (dst[i + 2] * inv + 127) / 255); + dst[i + 3] = (uint8_t)clamp_u8(a + (dst[i + 3] * inv + 127) / 255); + } + } + } + return 1; +} + +/* ------------------------------------------------------------------ backdrop and output */ + +static uint8_t *backdrop; +static int32_t backdrop_w, backdrop_h; + +/* Keep the framebuffer as the backdrop (wallpaper and desktop card). */ +void rs_save_backdrop(void) { + free(backdrop); + backdrop = malloc((size_t)fb_w * fb_h * 4); + memcpy(backdrop, fb, (size_t)fb_w * fb_h * 4); + backdrop_w = fb_w; + backdrop_h = fb_h; +} + +/* 1 when a backdrop of the framebuffer's size is kept. */ +int32_t rs_has_backdrop(void) { return backdrop && backdrop_w == fb_w && backdrop_h == fb_h; } + +/* Copy the backdrop back into the clip (or everywhere). */ +void rs_copy_backdrop(void) { + if (!rs_has_backdrop()) return; + if (!clip_on) { memcpy(fb, backdrop, (size_t)fb_w * fb_h * 4); return; } + int x0 = imax(clip_x, 0), x1 = imin(clip_x + clip_w, fb_w); + int y0 = imax(clip_y, 0), y1 = imin(clip_y + clip_h, fb_h); + if (x0 >= x1) return; + for (int y = y0; y < y1; y++) { + size_t a = ((size_t)y * fb_w + x0) * 4; + memcpy(fb + a, backdrop + a, (size_t)(x1 - x0) * 4); + } +} + +int32_t rs_width(void) { return fb_w; } +int32_t rs_height(void) { return fb_h; } +uint8_t *rs_pixels(void) { return fb; } + +/* The framebuffer as RGBA8888 into `out` (w * h * 4 bytes). */ +void rs_read_frame(moonbit_bytes_t out) { + size_t n = (size_t)fb_w * fb_h * 4; + if (fb && (size_t)Moonbit_array_length(out) >= n) memcpy(out, fb, n); +} + +/* A new memfd holding the framebuffer as little-endian ARGB8888 (B, G, R, 255). -1 on failure. */ +int32_t rs_export_memfd(void) { + if (!fb) return -1; + size_t n = (size_t)fb_w * fb_h * 4; + uint8_t *data = malloc(n); + for (size_t i = 0; i < n; i += 4) { + data[i] = fb[i + 2]; data[i + 1] = fb[i + 1]; data[i + 2] = fb[i]; data[i + 3] = 0xff; + } + int fd = memfd_create("chandra-frame", MFD_CLOEXEC); + if (fd < 0) { free(data); return -1; } + size_t done = 0; + while (done < n) { + ssize_t w = write(fd, data + done, n - done); + if (w <= 0) { close(fd); free(data); return -1; } + done += (size_t)w; + } + free(data); + return fd; +} diff --git a/wasmhost/bin/stubs.mbt b/wasmhost/bin/stubs.mbt new file mode 100644 index 0000000..056ed94 --- /dev/null +++ b/wasmhost/bin/stubs.mbt @@ -0,0 +1,48 @@ +///| Interfaces not served yet (filled in stage by stage). + +///| +fn display_wait_fds() -> Array[Int] { + [] +} + + + +///| +fn display_funcs() -> Array[(String, (Array[@wt.Val]) -> Array[@wt.Val])] { + [ + ("open", _ => [Option(None)]), + ("poll", _ => [Bool(false)]), + ("frame-ready", _ => [Bool(false)]), + ("present", _ => none), + ("present-frame", _ => none), + ("set-cursor-shape", _ => none), + ("take-input", _ => [List([])]), + ("close", _ => none), + ] +} + +///| +fn plasmoid_funcs() -> Array[(String, (Array[@wt.Val]) -> Array[@wt.Val])] { + [ + ("load", _ => [Result(false, Some(Str("not yet")))]), + ("unload", _ => none), + ("set-tokens", _ => none), + ("render", _ => [List([])]), + ("popup", _ => [Option(None)]), + ("on-event", _ => [Bool(false)]), + ("config-items", _ => [List([])]), + ("set-config", _ => [Bool(false)]), + ("publish-table", _ => none), + ("publish-state", _ => none), + ("publish-wallpaper", _ => none), + ("publish-session-settings", _ => none), + ("publish-screenshot", _ => none), + ("publish-system", _ => none), + ("publish-windows", _ => none), + ("next-request", _ => [Option(None)]), + ("take-focus-request", _ => [Option(None)]), + ("list-wasm-files", _ => [List([])]), + ("picker-start", _ => [Bool(false)]), + ("picker-poll", _ => [Variant("cancelled", None)]), + ] +} diff --git a/wasmhost/bin/sys.mbt b/wasmhost/bin/sys.mbt new file mode 100644 index 0000000..8844ce7 --- /dev/null +++ b/wasmhost/bin/sys.mbt @@ -0,0 +1,211 @@ +///| `chandra:host/sys`: the OS surface, over compositor/sys's native implementation (the same +/// C shim the native compositor uses). + +///| +#borrow(path, data) +extern "C" fn c_append_file(path : Bytes, data : Bytes) -> Int = "wh_append_file" + +///| Fds beyond the first that arrived with the last `recvmsg` on a socket, for `take-fd`. +let extra_fds : Map[Int, Array[Int]] = {} + +///| +fn drop_extra_fds(sock : Int) -> Unit { + match extra_fds.get(sock) { + Some(left) => { + for f in left { + @sys.close_fd(f) + } + extra_fds.remove(sock) + } + None => () + } +} + +///| +fn s32(v : Int) -> Array[@wt.Val] { + [S32(v)] +} + +///| +fn boolean(b : Bool) -> Array[@wt.Val] { + [Bool(b)] +} + +///| +let none : Array[@wt.Val] = [] + +///| +fn sys_funcs() -> Array[(String, (Array[@wt.Val]) -> Array[@wt.Val])] { + [ + ("unix-listen", a => s32(@sys.unix_listen(a[0].to_string()))), + ("unix-accept", a => s32(@sys.unix_accept(a[0].to_int()))), + ("unix-connect", a => s32(@sys.unix_connect(a[0].to_string()))), + ( + "close-fd", + a => { + let fd = a[0].to_int() + if fd >= 0 { + // A closed client socket's number is reused by the next one: drop what it left. + drop_extra_fds(fd) + @sys.close_fd(fd) + } + none + }, + ), + ( + "unlink", + a => { + @sys.unlink(a[0].to_string()) + none + }, + ), + ("poll-read", a => s32(@sys.poll_read(a[0].to_int(), a[1].to_int()))), + ( + "wait-readable", + a => { + let fds = a[0].to_list().map(v => v.to_int()) + for f in display_wait_fds() { + fds.push(f) + } + s32(@sys.wait_readable(fds, a[1].to_int())) + }, + ), + ( + "recvmsg", + a => { + let fd = a[0].to_int() + // Fds from the previous read nobody took would leak: close them. + drop_extra_fds(fd) + let max_len = a[1].to_int() + let received = fn(count : Int, got : Int, data : Bytes) -> Array[@wt.Val] { + [ + Record([ + ("count", S32(count)), + ("fd", S32(got)), + ("data", @wt.Val::bytes(data)), + ]), + ] + } + if max_len <= 0 { + return received(0, -1, b"") + } + let buf = FixedArray::make(max_len, b'\x00') + let (n, fds) = @sys.recvmsg_fds(fd, buf, max_len) + if n < 0 { + for f in fds { + @sys.close_fd(f) + } + return received(n, -1, b"") + } + let got = if fds.length() > 0 { fds[0] } else { -1 } + if fds.length() > 1 { + extra_fds.set(fd, fds[1:].to_array()) + } + received(n, got, Bytes::from_fixedarray(buf, len=n)) + }, + ), + ( + "take-fd", + a => { + let sock = a[0].to_int() + match extra_fds.get(sock) { + Some(q) if q.length() > 0 => { + let f = q.remove(0) + if q.length() == 0 { + extra_fds.remove(sock) + } + s32(f) + } + _ => s32(-1) + } + }, + ), + ( + "sendmsg", + a => { + let data = a[1].to_bytes() + if data.length() == 0 { + return s32(0) + } + s32(@sys.sendmsg_fd(a[0].to_int(), data, a[2].to_int())) + }, + ), + ("memfd-create", a => s32(@sys.memfd_create(a[0].to_string(), a[1].to_int()))), + ( + "pwrite", + a => { + let fd = a[0].to_int() + let data = a[1].to_bytes() + let off = a[2].to_int() + s32( + if off < 0 { + @sys.write_nonblock(fd, data) + } else { + @sys.pwrite_bytes(fd, data, off) + }, + ) + }, + ), + ( + "mmap-read", + a => [@wt.Val::bytes(@sys.mmap_read(a[0].to_int(), a[1].to_int()))], + ), + ( + "mmap-read-at", + a => { + let (fd, off, len) = (a[0].to_int(), a[1].to_int(), a[2].to_int()) + if fd < 0 || off < 0 || len <= 0 { + return [@wt.Val::bytes(b"")] + } + [@wt.Val::bytes(@sys.mmap_read_at(fd, off, len))] + }, + ), + ( + "read-file", + a => [@wt.Val::bytes(@sys.read_file_bytes(a[0].to_string()))], + ), + ( + "write-file", + a => s32(@sys.write_file_bytes(a[0].to_string(), a[1].to_bytes())), + ), + ( + "append-file", + a => s32(c_append_file(@utf8.encode(a[0].to_string()), a[1].to_bytes())), + ), + ( + "read-proc", + a => [@wt.Val::bytes(@sys.read_proc_bytes(a[0].to_string()))], + ), + ("mkdir-p", a => boolean(@sys.mkdir_p(a[0].to_string()))), + ( + "list-desktop-files", + a => [@wt.Val::strings(@sys.list_desktop_files(a[0].to_string()))], + ), + ( + "sleep-ms", + a => { + let ms = a[0].to_int() + if ms > 0 { + @sys.sleep_ms(ms) + } + none + }, + ), + ("monotonic-ms", _ => [U64(@sys.monotonic_ms())]), + ( + "log", + a => { + eprint(a[0].to_string()) + none + }, + ), + ("getpid", _ => s32(@sys.getpid())), + ("wall-time-field", a => s32(@sys.wall_time_field(a[0].to_int()))), + ("getenv", a => [Str(@sys.getenv(a[0].to_string()))]), + ("has-exe", a => boolean(@sys.has_exe(a[0].to_string()))), + ( + "spawn", + a => boolean(@sys.spawn(a[0].to_string(), a[1].to_string())), + ), + ] +} diff --git a/wasmhost/wt/moon.pkg b/wasmhost/wt/moon.pkg new file mode 100644 index 0000000..c4437ff --- /dev/null +++ b/wasmhost/wt/moon.pkg @@ -0,0 +1,13 @@ +import { + "moonbitlang/core/builtin", + "moonbitlang/core/buffer" @buffer, + "moonbitlang/core/encoding/utf8" @utf8, +} + +supported_targets = "-all+native" + +// The wasmtime C API comes prebuilt from setup-toolchain.sh (.tools/wasmtime-c-api); build with +// scripts/build-wasmhost.sh, which points the C compiler and linker at it. +options( + "native-stub": [ "wt_stub.c" ], +) diff --git a/wasmhost/wt/val.mbt b/wasmhost/wt/val.mbt new file mode 100644 index 0000000..280e8cb --- /dev/null +++ b/wasmhost/wt/val.mbt @@ -0,0 +1,365 @@ +///| A component-model value as it crosses to and from wasmtime (encoding in wt_stub.c). +pub(all) enum Val { + Bool(Bool) + S8(Int) + U8(Int) + S16(Int) + U16(Int) + S32(Int) + U32(UInt) + S64(Int64) + U64(UInt64) + F32(Float) + F64(Double) + Char(Char) + Str(String) + List(Array[Val]) + Record(Array[(String, Val)]) + Tuple(Array[Val]) + Variant(String, Val?) + Enum(String) + Option(Val?) + Result(Bool, Val?) + Flags(Array[String]) + /// A `list` (encoded as one blob rather than a value per byte). + Blob(Bytes) +} derive(Show, Eq) + +///| A list of u8 (`list`) from bytes. +pub fn Val::bytes(b : Bytes) -> Val { + Blob(b) +} + +///| A `list`. +pub fn Val::strings(a : Array[String]) -> Val { + List(a.map(Str(_))) +} + +///| Record field `name` (records are looked up by name, not position). +pub fn Val::field(self : Val, name : String) -> Val { + match self { + Record(fs) => { + for f in fs { + if f.0 == name { + return f.1 + } + } + abort("record has no field \{name}") + } + _ => abort("not a record: field \{name}") + } +} + +///| +pub fn Val::to_int(self : Val) -> Int { + match self { + S8(v) | U8(v) | S16(v) | U16(v) | S32(v) => v + U32(v) => v.reinterpret_as_int() + S64(v) => v.to_int() + U64(v) => v.to_int() + Bool(b) => if b { 1 } else { 0 } + Char(c) => c.to_int() + _ => abort("not an integer: \{self}") + } +} + +///| +pub fn Val::to_uint(self : Val) -> UInt { + match self { + U32(v) => v + _ => self.to_int().reinterpret_as_uint() + } +} + +///| +pub fn Val::to_bool(self : Val) -> Bool { + match self { + Bool(b) => b + _ => self.to_int() != 0 + } +} + +///| +pub fn Val::to_double(self : Val) -> Double { + match self { + F64(d) => d + F32(f) => f.to_double() + _ => self.to_int().to_double() + } +} + +///| +pub fn Val::to_string(self : Val) -> String { + match self { + Str(s) | Enum(s) => s + _ => abort("not a string: \{self}") + } +} + +///| +pub fn Val::to_list(self : Val) -> Array[Val] { + match self { + List(a) | Tuple(a) => a + _ => abort("not a list: \{self}") + } +} + +///| A `list` as bytes. +pub fn Val::to_bytes(self : Val) -> Bytes { + if self is Blob(b) { + return b + } + let a = self.to_list() + let out = FixedArray::make(a.length(), b'\x00') + for i, v in a { + out[i] = v.to_int().to_byte() + } + Bytes::from_fixedarray(out) +} + +///| +pub fn Val::to_option(self : Val) -> Val? { + match self { + Option(o) => o + _ => abort("not an option: \{self}") + } +} + +// ---- encoding ---- + +///| +fn put_u32(buf : @buffer.Buffer, v : Int) -> Unit { + buf.write_int_le(v) +} + +///| +fn put_str(buf : @buffer.Buffer, s : String) -> Unit { + let b = @utf8.encode(s) + put_u32(buf, b.length()) + buf.write_bytes(b) +} + +///| +fn kind(v : Val) -> Byte { + match v { + Bool(_) => 0 + S8(_) => 1 + U8(_) => 2 + S16(_) => 3 + U16(_) => 4 + S32(_) => 5 + U32(_) => 6 + S64(_) => 7 + U64(_) => 8 + F32(_) => 9 + F64(_) => 10 + Char(_) => 11 + Str(_) => 12 + List(_) => 13 + Record(_) => 14 + Tuple(_) => 15 + Variant(_, _) => 16 + Enum(_) => 17 + Option(_) => 18 + Result(_, _) => 19 + Flags(_) => 20 + Blob(_) => 0x80 + } +} + +///| +fn enc(buf : @buffer.Buffer, v : Val) -> Unit { + buf.write_byte(kind(v)) + match v { + Bool(b) => buf.write_byte(if b { b'\x01' } else { b'\x00' }) + S8(x) | U8(x) => buf.write_byte(x.to_byte()) + S16(x) | U16(x) => { + buf.write_byte(x.to_byte()) + buf.write_byte((x >> 8).to_byte()) + } + S32(x) => buf.write_int_le(x) + U32(x) => buf.write_uint_le(x) + S64(x) => buf.write_int64_le(x) + U64(x) => buf.write_uint64_le(x) + F32(x) => buf.write_float_le(x) + F64(x) => buf.write_double_le(x) + Char(c) => buf.write_int_le(c.to_int()) + Str(s) | Enum(s) => put_str(buf, s) + List(a) | Tuple(a) => { + put_u32(buf, a.length()) + for x in a { + enc(buf, x) + } + } + Record(fs) => { + put_u32(buf, fs.length()) + for f in fs { + put_str(buf, f.0) + enc(buf, f.1) + } + } + Variant(name, p) => { + put_str(buf, name) + match p { + Some(x) => { + buf.write_byte(b'\x01') + enc(buf, x) + } + None => buf.write_byte(b'\x00') + } + } + Option(p) => + match p { + Some(x) => { + buf.write_byte(b'\x01') + enc(buf, x) + } + None => buf.write_byte(b'\x00') + } + Result(ok, p) => { + buf.write_byte(if ok { b'\x01' } else { b'\x00' }) + match p { + Some(x) => { + buf.write_byte(b'\x01') + enc(buf, x) + } + None => buf.write_byte(b'\x00') + } + } + Flags(names) => { + put_u32(buf, names.length()) + for n in names { + put_str(buf, n) + } + } + Blob(b) => { + put_u32(buf, b.length()) + buf.write_bytes(b) + } + } +} + +///| Encode a message (a list of values: arguments or results). +pub fn encode(vals : Array[Val]) -> Bytes { + let buf = @buffer.new(size_hint=64) + put_u32(buf, vals.length()) + for v in vals { + enc(buf, v) + } + buf.to_bytes() +} + +// ---- decoding ---- + +///| +struct Reader { + b : Bytes + mut pos : Int +} + +///| +fn Reader::u8(self : Reader) -> Int { + let v = self.b[self.pos].to_int() + self.pos += 1 + v +} + +///| +fn Reader::u32(self : Reader) -> UInt { + let p = self.pos + let v = self.b[p].to_uint() | + (self.b[p + 1].to_uint() << 8) | + (self.b[p + 2].to_uint() << 16) | + (self.b[p + 3].to_uint() << 24) + self.pos += 4 + v +} + +///| +fn Reader::u64(self : Reader) -> UInt64 { + let lo = self.u32().to_uint64() + let hi = self.u32().to_uint64() + lo | (hi << 32) +} + +///| +fn Reader::str(self : Reader) -> String { + let n = self.u32().reinterpret_as_int() + let s = @utf8.decode_lossy(self.b[self.pos:self.pos + n]) + self.pos += n + s +} + +///| +fn Reader::val(self : Reader) -> Val { + match self.u8() { + 0 => Bool(self.u8() != 0) + 1 => { + let x = self.u8() + S8(if x >= 128 { x - 256 } else { x }) + } + 2 => U8(self.u8()) + 3 => { + let x = self.u8() | (self.u8() << 8) + S16(if x >= 32768 { x - 65536 } else { x }) + } + 4 => U16(self.u8() | (self.u8() << 8)) + 5 => S32(self.u32().reinterpret_as_int()) + 6 => U32(self.u32()) + 7 => S64(self.u64().reinterpret_as_int64()) + 8 => U64(self.u64()) + 9 => F32(Float::reinterpret_from_uint(self.u32())) + 10 => F64(self.u64().reinterpret_as_double()) + 11 => Char(Int::unsafe_to_char(self.u32().reinterpret_as_int())) + 12 => Str(self.str()) + 13 | 15 as k => { + let n = self.u32().reinterpret_as_int() + let a = Array::new(capacity=n) + for _ in 0.. { + let n = self.u32().reinterpret_as_int() + let a = Array::new(capacity=n) + for _ in 0.. { + let name = self.str() + Variant(name, if self.u8() != 0 { Some(self.val()) } else { None }) + } + 17 => Enum(self.str()) + 18 => Option(if self.u8() != 0 { Some(self.val()) } else { None }) + 19 => { + let ok = self.u8() != 0 + Result(ok, if self.u8() != 0 { Some(self.val()) } else { None }) + } + 20 => { + let n = self.u32().reinterpret_as_int() + Flags(Array::makei(n, _ => self.str())) + } + 0x80 => { + let n = self.u32().reinterpret_as_int() + let b = self.b[self.pos:self.pos + n].to_owned() + self.pos += n + Blob(b) + } + k => abort("unknown value kind \{k}") + } +} + +///| Decode a message. +pub fn decode(b : Bytes) -> Array[Val] { + let r = { b, pos: 0 } + let n = r.u32().reinterpret_as_int() + Array::makei(n, _ => r.val()) +} diff --git a/wasmhost/wt/wt.mbt b/wasmhost/wt/wt.mbt new file mode 100644 index 0000000..e308944 --- /dev/null +++ b/wasmhost/wt/wt.mbt @@ -0,0 +1,109 @@ +///| Running a component with wasmtime (its C API, linked as a prebuilt library; see wt_stub.c). +/// +/// The host registers its functions by interface with `define`, each under an id; calls from the +/// component reach the one handler given to `set_handler` as (id, arguments). + +///| +extern "C" fn c_set_dispatch(f : FuncRef[(Int, Bytes) -> Bytes]) = "wt_set_dispatch" + +///| +extern "C" fn c_last_error() -> Bytes = "wt_last_error" + +///| +extern "C" fn c_init() -> Int = "wt_init" + +///| +#borrow(path) +extern "C" fn c_load(path : Bytes) -> Int = "wt_load" + +///| +#borrow(iface, names) +extern "C" fn c_define(iface : Bytes, names : Bytes, first_id : Int) -> Int = "wt_define" + +///| +extern "C" fn c_instantiate() -> Int = "wt_instantiate" + +///| +#borrow(iface, name, args) +extern "C" fn c_call(iface : Bytes, name : Bytes, args : Bytes) -> Bytes = "wt_call" + +///| What a host function returns: its results (zero or one value). +let handler : Ref[(Int, Array[Val]) -> Array[Val]] = Ref(fn(id, _) { + abort("no handler for host function \{id}") +}) + +///| +fn dispatch(id : Int, args : Bytes) -> Bytes { + encode((handler.val)(id, decode(args))) +} + +///| +fn last_error() -> String { + @utf8.decode_lossy(c_last_error()) +} + +///| +fn cstr(s : String) -> Bytes { + @utf8.encode(s) +} + +///| Create the engine and load the component at `path`. +pub fn load(path : String) -> Result[Unit, String] { + if c_init() != 0 { + return Err(last_error()) + } + c_set_dispatch(fn(id, args) { dispatch(id, args) }) + if c_load(cstr(path)) != 0 { + return Err(last_error()) + } + Ok(()) +} + +///| The function that serves every host import. +pub fn set_handler(f : (Int, Array[Val]) -> Array[Val]) -> Unit { + handler.val = f +} + +///| Define functions `names` of interface `iface` ("" for root imports) with ids `first_id`, +/// `first_id + 1`, ... +pub fn define_funcs( + iface : String, + names : Array[String], + first_id : Int, +) -> Result[Unit, String] { + let joined = names.iter().fold(init="", fn(acc, n) { + if acc == "" { + n + } else { + acc + "\n" + n + } + }) + if c_define(cstr(iface), cstr(joined), first_id) != 0 { + Err(last_error()) + } else { + Ok(()) + } +} + +///| +pub fn instantiate() -> Result[Unit, String] { + if c_instantiate() != 0 { + Err(last_error()) + } else { + Ok(()) + } +} + +///| Call export `name` (of interface `iface`, "" for a root export). +pub fn call( + iface : String, + name : String, + args : Array[Val], +) -> Result[Array[Val], String] { + let out = c_call(cstr(iface), cstr(name), encode(args)) + if out.length() == 0 { + Err(last_error()) + } else { + Ok(decode(out)) + } +} diff --git a/wasmhost/wt/wt_stub.c b/wasmhost/wt/wt_stub.c new file mode 100644 index 0000000..331273e --- /dev/null +++ b/wasmhost/wt/wt_stub.c @@ -0,0 +1,414 @@ +/* The wasmtime C API (component model) for the MoonBit host. + * + * One engine, store and linker. Host functions are registered by interface; every call from the + * component lands in one callback that encodes the arguments into bytes, calls the MoonBit + * dispatcher with them and decodes the bytes it returns into the results. Calling an export works + * the same way in reverse. MoonBit never sees a wasmtime value, only this encoding (see val.mbt): + * + * value = kind:u8 payload (kind is WASMTIME_COMPONENT_*) + * bool/s8/u8: 1 byte; s16/u16: 2; s32/u32/f32/char: 4; s64/u64/f64: 8 (little endian) + * string/enum: u32 length + UTF-8 + * list/tuple: u32 n + n values + * record: u32 n + n (string name, value) + * variant: string case + u8 has-payload + [value] + * option: u8 is-some + [value] + * result: u8 is-ok + u8 has-payload + [value] + * flags: u32 n + n strings + * blob: u32 n + n bytes (kind 0x80: a list, both ways) + * message = u32 count + count values + */ +#include +#include +#include +#include +#include +#include "moonbit.h" + +#define KIND_BLOB 0x80 + +typedef moonbit_bytes_t (*wt_dispatch_t)(int32_t id, moonbit_bytes_t args); + +static wasm_engine_t *engine; +static wasmtime_store_t *store; +static wasmtime_context_t *ctx; +static wasmtime_component_linker_t *linker; +static wasmtime_component_t *component; +static wasmtime_component_instance_t instance; +static int have_instance; +static wt_dispatch_t dispatch; +static char last_error[1024]; + +static void set_error(const char *what, wasmtime_error_t *e) { + if (!e) { + snprintf(last_error, sizeof last_error, "%s", what); + return; + } + wasm_byte_vec_t m; + wasmtime_error_message(e, &m); + snprintf(last_error, sizeof last_error, "%s: %.*s", what, (int)m.size, m.data); + wasm_byte_vec_delete(&m); + wasmtime_error_delete(e); +} + +/* ---- encoding ---- */ + +typedef struct { uint8_t *p; size_t len, cap; } Buf; + +static void put(Buf *b, const void *src, size_t n) { + if (b->len + n > b->cap) { + size_t c = b->cap ? b->cap * 2 : 256; + while (c < b->len + n) c *= 2; + b->p = realloc(b->p, c); + b->cap = c; + } + memcpy(b->p + b->len, src, n); + b->len += n; +} +static void put_u8(Buf *b, uint8_t v) { put(b, &v, 1); } +static void put_u32(Buf *b, uint32_t v) { put(b, &v, 4); } +static void put_name(Buf *b, const wasm_name_t *s) { + put_u32(b, (uint32_t)s->size); + if (s->size) put(b, s->data, s->size); +} + +static void enc(Buf *b, const wasmtime_component_val_t *v) { + put_u8(b, v->kind); + switch (v->kind) { + case WASMTIME_COMPONENT_BOOL: put_u8(b, v->of.boolean ? 1 : 0); break; + case WASMTIME_COMPONENT_S8: put(b, &v->of.s8, 1); break; + case WASMTIME_COMPONENT_U8: put(b, &v->of.u8, 1); break; + case WASMTIME_COMPONENT_S16: put(b, &v->of.s16, 2); break; + case WASMTIME_COMPONENT_U16: put(b, &v->of.u16, 2); break; + case WASMTIME_COMPONENT_S32: put(b, &v->of.s32, 4); break; + case WASMTIME_COMPONENT_U32: put(b, &v->of.u32, 4); break; + case WASMTIME_COMPONENT_S64: put(b, &v->of.s64, 8); break; + case WASMTIME_COMPONENT_U64: put(b, &v->of.u64, 8); break; + case WASMTIME_COMPONENT_F32: put(b, &v->of.f32, 4); break; + case WASMTIME_COMPONENT_F64: put(b, &v->of.f64, 8); break; + case WASMTIME_COMPONENT_CHAR: put(b, &v->of.character, 4); break; + case WASMTIME_COMPONENT_STRING: put_name(b, &v->of.string); break; + case WASMTIME_COMPONENT_ENUM: put_name(b, &v->of.enumeration); break; + case WASMTIME_COMPONENT_LIST: + if (v->of.list.size && v->of.list.data[0].kind == WASMTIME_COMPONENT_U8) { + b->p[b->len - 1] = KIND_BLOB; + put_u32(b, (uint32_t)v->of.list.size); + for (size_t i = 0; i < v->of.list.size; i++) put_u8(b, v->of.list.data[i].of.u8); + break; + } + put_u32(b, (uint32_t)v->of.list.size); + for (size_t i = 0; i < v->of.list.size; i++) enc(b, &v->of.list.data[i]); + break; + case WASMTIME_COMPONENT_TUPLE: + put_u32(b, (uint32_t)v->of.tuple.size); + for (size_t i = 0; i < v->of.tuple.size; i++) enc(b, &v->of.tuple.data[i]); + break; + case WASMTIME_COMPONENT_RECORD: + put_u32(b, (uint32_t)v->of.record.size); + for (size_t i = 0; i < v->of.record.size; i++) { + put_name(b, &v->of.record.data[i].name); + enc(b, &v->of.record.data[i].val); + } + break; + case WASMTIME_COMPONENT_VARIANT: + put_name(b, &v->of.variant.discriminant); + put_u8(b, v->of.variant.val ? 1 : 0); + if (v->of.variant.val) enc(b, v->of.variant.val); + break; + case WASMTIME_COMPONENT_OPTION: + put_u8(b, v->of.option ? 1 : 0); + if (v->of.option) enc(b, v->of.option); + break; + case WASMTIME_COMPONENT_RESULT: + put_u8(b, v->of.result.is_ok ? 1 : 0); + put_u8(b, v->of.result.val ? 1 : 0); + if (v->of.result.val) enc(b, v->of.result.val); + break; + case WASMTIME_COMPONENT_FLAGS: + put_u32(b, (uint32_t)v->of.flags.size); + for (size_t i = 0; i < v->of.flags.size; i++) put_name(b, &v->of.flags.data[i]); + break; + default: + break; /* resources and maps: our WIT has none */ + } +} + +static moonbit_bytes_t to_moonbit(const Buf *b) { + moonbit_bytes_t out = moonbit_make_bytes((int32_t)b->len, 0); + if (b->len) memcpy(out, b->p, b->len); + return out; +} + +static moonbit_bytes_t enc_message(const wasmtime_component_val_t *vals, size_t n) { + Buf b = {0}; + put_u32(&b, (uint32_t)n); + for (size_t i = 0; i < n; i++) enc(&b, &vals[i]); + moonbit_bytes_t out = to_moonbit(&b); + free(b.p); + return out; +} + +/* ---- decoding ---- */ + +typedef struct { const uint8_t *p; size_t len, pos; int bad; } Rd; + +static int take(Rd *r, void *dst, size_t n) { + if (r->bad || r->pos + n > r->len) { r->bad = 1; memset(dst, 0, n); return 0; } + memcpy(dst, r->p + r->pos, n); + r->pos += n; + return 1; +} +static uint8_t get_u8(Rd *r) { uint8_t v; take(r, &v, 1); return v; } +static uint32_t get_u32(Rd *r) { uint32_t v; take(r, &v, 4); return v; } +static void get_name(Rd *r, wasm_name_t *out) { + uint32_t n = get_u32(r); + if (r->bad || r->pos + n > r->len) { r->bad = 1; wasm_byte_vec_new_empty(out); return; } + wasm_byte_vec_new(out, n, (const wasm_byte_t *)(r->p + r->pos)); + r->pos += n; +} + +static void dec(Rd *r, wasmtime_component_val_t *v); + +static wasmtime_component_val_t *dec_boxed(Rd *r) { + wasmtime_component_val_t tmp; + dec(r, &tmp); + return wasmtime_component_val_new(&tmp); +} + +static void dec(Rd *r, wasmtime_component_val_t *v) { + memset(v, 0, sizeof *v); + uint8_t kind = get_u8(r); + if (r->bad) { v->kind = WASMTIME_COMPONENT_BOOL; return; } + v->kind = kind; + switch (kind) { + case WASMTIME_COMPONENT_BOOL: v->of.boolean = get_u8(r) != 0; break; + case WASMTIME_COMPONENT_S8: take(r, &v->of.s8, 1); break; + case WASMTIME_COMPONENT_U8: take(r, &v->of.u8, 1); break; + case WASMTIME_COMPONENT_S16: take(r, &v->of.s16, 2); break; + case WASMTIME_COMPONENT_U16: take(r, &v->of.u16, 2); break; + case WASMTIME_COMPONENT_S32: take(r, &v->of.s32, 4); break; + case WASMTIME_COMPONENT_U32: take(r, &v->of.u32, 4); break; + case WASMTIME_COMPONENT_S64: take(r, &v->of.s64, 8); break; + case WASMTIME_COMPONENT_U64: take(r, &v->of.u64, 8); break; + case WASMTIME_COMPONENT_F32: take(r, &v->of.f32, 4); break; + case WASMTIME_COMPONENT_F64: take(r, &v->of.f64, 8); break; + case WASMTIME_COMPONENT_CHAR: take(r, &v->of.character, 4); break; + case WASMTIME_COMPONENT_STRING: get_name(r, &v->of.string); break; + case WASMTIME_COMPONENT_ENUM: get_name(r, &v->of.enumeration); break; + case WASMTIME_COMPONENT_LIST: + case WASMTIME_COMPONENT_TUPLE: { + uint32_t n = get_u32(r); + if (r->bad || n > r->len) { r->bad = 1; n = 0; } + wasmtime_component_vallist_t *l = kind == WASMTIME_COMPONENT_LIST + ? &v->of.list : (wasmtime_component_vallist_t *)&v->of.tuple; + wasmtime_component_vallist_new_uninit(l, n); + for (uint32_t i = 0; i < n; i++) dec(r, &l->data[i]); + break; + } + case KIND_BLOB: { + uint32_t n = get_u32(r); + if (r->bad || r->pos + n > r->len) { r->bad = 1; n = 0; } + v->kind = WASMTIME_COMPONENT_LIST; + wasmtime_component_vallist_new_uninit(&v->of.list, n); + for (uint32_t i = 0; i < n; i++) { + memset(&v->of.list.data[i], 0, sizeof v->of.list.data[i]); + v->of.list.data[i].kind = WASMTIME_COMPONENT_U8; + v->of.list.data[i].of.u8 = r->p[r->pos + i]; + } + r->pos += n; + break; + } + case WASMTIME_COMPONENT_RECORD: { + uint32_t n = get_u32(r); + if (r->bad || n > r->len) { r->bad = 1; n = 0; } + wasmtime_component_valrecord_new_uninit(&v->of.record, n); + for (uint32_t i = 0; i < n; i++) { + get_name(r, &v->of.record.data[i].name); + dec(r, &v->of.record.data[i].val); + } + break; + } + case WASMTIME_COMPONENT_VARIANT: + get_name(r, &v->of.variant.discriminant); + v->of.variant.val = get_u8(r) ? dec_boxed(r) : NULL; + break; + case WASMTIME_COMPONENT_OPTION: + v->of.option = get_u8(r) ? dec_boxed(r) : NULL; + break; + case WASMTIME_COMPONENT_RESULT: + v->of.result.is_ok = get_u8(r) != 0; + v->of.result.val = get_u8(r) ? dec_boxed(r) : NULL; + break; + case WASMTIME_COMPONENT_FLAGS: { + uint32_t n = get_u32(r); + if (r->bad || n > r->len) { r->bad = 1; n = 0; } + wasmtime_component_valflags_new_uninit(&v->of.flags, n); + for (uint32_t i = 0; i < n; i++) get_name(r, &v->of.flags.data[i]); + break; + } + default: + r->bad = 1; + v->kind = WASMTIME_COMPONENT_BOOL; + break; + } +} + +/* Decode a message into `out` (n slots). 0 on success. */ +static int dec_message(moonbit_bytes_t bytes, wasmtime_component_val_t *out, size_t n) { + Rd r = { (const uint8_t *)bytes, (size_t)Moonbit_array_length(bytes), 0, 0 }; + uint32_t count = get_u32(&r); + if (r.bad || count != n) { + for (size_t i = 0; i < n; i++) { memset(&out[i], 0, sizeof out[i]); out[i].kind = WASMTIME_COMPONENT_BOOL; } + return -1; + } + for (size_t i = 0; i < n; i++) dec(&r, &out[i]); + return r.bad ? -1 : 0; +} + +/* ---- host functions ---- */ + +static wasmtime_error_t *host_call(void *env, wasmtime_context_t *c, const wasmtime_component_func_type_t *ty, + wasmtime_component_val_t *args, size_t nargs, + wasmtime_component_val_t *results, size_t nresults) { + (void)c; (void)ty; + int32_t id = (int32_t)(intptr_t)env; + moonbit_bytes_t in = enc_message(args, nargs); + moonbit_bytes_t out = dispatch(id, in); /* takes `in` */ + int bad = dec_message(out, results, nresults); + moonbit_decref(out); + if (bad) { + char msg[96]; + snprintf(msg, sizeof msg, "host function %d returned a malformed result", id); + return wasmtime_error_new(msg); + } + return NULL; +} + +void wt_set_dispatch(wt_dispatch_t f) { dispatch = f; } + +moonbit_bytes_t wt_last_error(void) { + size_t n = strlen(last_error); + moonbit_bytes_t out = moonbit_make_bytes((int32_t)n, 0); + memcpy(out, last_error, n); + return out; +} + +int32_t wt_init(void) { + if (engine) return 0; + wasm_config_t *cfg = wasm_config_new(); + wasmtime_config_wasm_component_model_set(cfg, true); + engine = wasm_engine_new_with_config(cfg); + if (!engine) { set_error("cannot create the wasmtime engine", NULL); return -1; } + store = wasmtime_store_new(engine, NULL, NULL); + ctx = wasmtime_store_context(store); + linker = wasmtime_component_linker_new(engine); + return 0; +} + +int32_t wt_load(moonbit_bytes_t path) { + char p[4096]; + size_t n = (size_t)Moonbit_array_length(path); + if (n >= sizeof p) n = sizeof p - 1; + memcpy(p, path, n); + p[n] = 0; + FILE *f = fopen(p, "rb"); + if (!f) { snprintf(last_error, sizeof last_error, "cannot open %s", p); return -1; } + fseek(f, 0, SEEK_END); + long len = ftell(f); + rewind(f); + uint8_t *data = malloc(len > 0 ? (size_t)len : 1); + size_t got = fread(data, 1, (size_t)len, f); + fclose(f); + wasmtime_error_t *e = wasmtime_component_new(engine, data, got, &component); + free(data); + if (e) { set_error("cannot compile the component", e); return -1; } + return 0; +} + +/* Define the functions `names` (newline separated) of interface `iface` ("" for the root), with + * ids first_id, first_id + 1, ... in order. */ +int32_t wt_define(moonbit_bytes_t iface, moonbit_bytes_t names, int32_t first_id) { + wasmtime_component_linker_instance_t *root = wasmtime_component_linker_root(linker); + wasmtime_component_linker_instance_t *li = root; + size_t ilen = (size_t)Moonbit_array_length(iface); + wasmtime_error_t *e = NULL; + if (ilen) { + e = wasmtime_component_linker_instance_add_instance(root, (const char *)iface, ilen, &li); + if (e) { set_error("cannot define the instance", e); wasmtime_component_linker_instance_delete(root); return -1; } + } + const char *s = (const char *)names; + size_t len = (size_t)Moonbit_array_length(names), start = 0; + int32_t id = first_id; + for (size_t i = 0; i <= len; i++) { + if (i == len || s[i] == '\n') { + if (i > start) { + e = wasmtime_component_linker_instance_add_func(li, s + start, i - start, host_call, + (void *)(intptr_t)id, NULL); + if (e) { + char what[160]; + snprintf(what, sizeof what, "cannot define %.*s", (int)(i - start), s + start); + set_error(what, e); + break; + } + id++; + } + start = i + 1; + } + } + if (li != root) wasmtime_component_linker_instance_delete(li); + wasmtime_component_linker_instance_delete(root); + return e ? -1 : 0; +} + +int32_t wt_instantiate(void) { + wasmtime_error_t *e = wasmtime_component_linker_instantiate(linker, ctx, component, &instance); + if (e) { set_error("cannot instantiate the component", e); return -1; } + have_instance = 1; + return 0; +} + +/* Call export `name` of interface `iface` ("" for a root export) with the encoded `args`. The + * encoded results, or an empty byte string on failure (wt_last_error says why). */ +moonbit_bytes_t wt_call(moonbit_bytes_t iface, moonbit_bytes_t name, moonbit_bytes_t args) { + moonbit_bytes_t fail = moonbit_make_bytes(0, 0); + if (!have_instance) { set_error("no instance", NULL); return fail; } + wasmtime_component_export_index_t *parent = NULL; + size_t ilen = (size_t)Moonbit_array_length(iface); + if (ilen) { + parent = wasmtime_component_instance_get_export_index(&instance, ctx, NULL, (const char *)iface, ilen); + if (!parent) { set_error("no such exported interface", NULL); return fail; } + } + wasmtime_component_export_index_t *idx = wasmtime_component_instance_get_export_index( + &instance, ctx, parent, (const char *)name, (size_t)Moonbit_array_length(name)); + if (parent) wasmtime_component_export_index_delete(parent); + if (!idx) { set_error("no such export", NULL); return fail; } + wasmtime_component_func_t func; + int ok = wasmtime_component_instance_get_func(&instance, ctx, idx, &func); + wasmtime_component_export_index_delete(idx); + if (!ok) { set_error("the export is not a function", NULL); return fail; } + + wasmtime_component_func_type_t *ty = wasmtime_component_func_type(&func, ctx); + size_t nparams = wasmtime_component_func_type_param_count(ty); + wasmtime_component_valtype_t rty; + size_t nresults = wasmtime_component_func_type_result(ty, &rty) ? 1 : 0; + if (nresults) wasmtime_component_valtype_delete(&rty); + wasmtime_component_func_type_delete(ty); + + wasmtime_component_val_t *a = calloc(nparams ? nparams : 1, sizeof *a); + if (dec_message(args, a, nparams)) { + for (size_t i = 0; i < nparams; i++) wasmtime_component_val_delete(&a[i]); + free(a); + set_error("malformed arguments", NULL); + return fail; + } + wasmtime_component_val_t res[1]; + memset(res, 0, sizeof res); + wasmtime_error_t *e = wasmtime_component_func_call(&func, ctx, a, nparams, res, nresults); + for (size_t i = 0; i < nparams; i++) wasmtime_component_val_delete(&a[i]); + free(a); + if (e) { set_error("call failed", e); return fail; } + moonbit_bytes_t out = enc_message(res, nresults); + for (size_t i = 0; i < nresults; i++) wasmtime_component_val_delete(&res[i]); + wasmtime_component_func_post_return(&func, ctx); + moonbit_decref(fail); + return out; +} diff --git a/wit/host/sys.wit b/wit/host/sys.wit index a81567c..4c66baf 100644 --- a/wit/host/sys.wit +++ b/wit/host/sys.wit @@ -44,6 +44,10 @@ interface sys { read-file: func(path: string) -> list; write-file: func(path: string, data: list) -> s32; + /// Append `data` to the file at `path` (created if missing): 0, or -1 on error. Large files go + /// out as write-file plus appends of at most 1 MiB, because a host built on wasmtime's C API + /// moves list as one dynamic value per byte and wasmtime caps what one call may copy. + append-file: func(path: string, data: list) -> s32; /// Contents of a small /proc or /sys file ("" when unreadable). read-proc: func(path: string) -> list; mkdir-p: func(path: string) -> bool;