| 1 | #include "canvas.h" |
| 2 | |
| 3 | #include "css.h" |
| 4 | |
| 5 | #include <algorithm> |
| 6 | #include <cmath> |
| 7 | |
| 8 | using twidget::Json; |
| 9 | |
| 10 | namespace twlite { |
| 11 | |
| 12 | namespace { |
| 13 | |
| 14 | constexpr double PI = 3.14159265358979323846; |
| 15 | constexpr size_t MAX_OBJECTS = 4096; |
| 16 | constexpr size_t MAX_STOPS = 256; |
| 17 | constexpr size_t MAX_STACK = 512; |
| 18 | constexpr size_t MAX_TEXT = 4096; |
| 19 | |
| 20 | std::vector<uint8_t> base64(const std::string& in) { |
| 21 | static int8_t table[256]; |
| 22 | static bool ready = false; |
| 23 | if (!ready) { |
| 24 | std::fill(std::begin(table), std::end(table), int8_t(-1)); |
| 25 | const char* alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; |
| 26 | for (int i = 0; i < 64; i++) table[(unsigned char)alphabet[i]] = int8_t(i); |
| 27 | ready = true; |
| 28 | } |
| 29 | std::vector<uint8_t> out; |
| 30 | out.reserve(in.size() * 3 / 4); |
| 31 | int value = 0, bits = -8; |
| 32 | for (unsigned char c : in) { |
| 33 | if (table[c] < 0) continue; |
| 34 | value = (value << 6) | table[c]; |
| 35 | bits += 6; |
| 36 | if (bits >= 0) { |
| 37 | out.push_back(uint8_t((value >> bits) & 0xFF)); |
| 38 | bits -= 8; |
| 39 | } |
| 40 | } |
| 41 | return out; |
| 42 | } |
| 43 | |
| 44 | Composite composite_of(const std::string& name, bool& known) { |
| 45 | static const char* const NAMES[] = { |
| 46 | "source-over", "source-in", "source-out", "source-atop", "destination-over", "destination-in", "destination-out", "destination-atop", |
| 47 | "lighter", "copy", "xor", "multiply", "screen", "overlay", "darken", "lighten", "color-dodge", "color-burn", "hard-light", "soft-light", |
| 48 | "difference", "exclusion", "hue", "saturation", "color", "luminosity", |
| 49 | }; |
| 50 | for (size_t i = 0; i < std::size(NAMES); i++) { |
| 51 | if (name == NAMES[i]) { |
| 52 | known = true; |
| 53 | return Composite(i); |
| 54 | } |
| 55 | } |
| 56 | known = false; |
| 57 | return Composite::SourceOver; |
| 58 | } |
| 59 | |
| 60 | /// Appends an elliptical arc as cubic béziers (at most a quarter turn each), connecting from the |
| 61 | /// current point with a line when there is one. Angles in radians, y down, clockwise positive. |
| 62 | template <class Emit> |
| 63 | void arc_segments(double cx, double cy, double rx, double ry, double rotation, double start, double sweep |
| 64 | int segments = std::max(1, int(std::ceil(std::fabs(sweep) / (PI / 2) - 1e- |
| 65 | double step = sweep / segments; |
| 66 | double k = 4.0 / 3.0 * std::tan(step / 4); |
| 67 | double cr = std::cos(rotation), sr = std::sin(rotation); |
| 68 | auto point = [&](double x, double y, double& ox, double& oy) { |
| 69 | ox = cx + rx * x * cr - ry * y * sr; |
| 70 | oy = cy + rx * x * sr + ry * y * cr; |
| 71 | }; |
| 72 | double a = start; |
| 73 | for (int i = 0; i < segments; i++) { |
| 74 | double b = a + step; |
| 75 | double ca = std::cos(a), sa = std::sin(a), cb = std::cos(b), sb = std::sin(b); |
| 76 | double p1x, p1y, p2x, p2y, p3x, p3y; |
| 77 | point(ca - k * sa, sa + k * ca, p1x, p1y); |
| 78 | point(cb + k * sb, sb - k * cb, p2x, p2y); |
| 79 | point(cb, sb, p3x, p3y); |
| 80 | emit(p1x, p1y, p2x, p2y, p3x, p3y); |
| 81 | a = b; |
| 82 | } |
| 83 | } |
| 84 | |
| 85 | double sweep_of(double start, double end, bool anticlockwise) { |
| 86 | double sweep = end - start; |
| 87 | if (!anticlockwise) { |
| 88 | if (sweep >= 2 * PI) return 2 * PI; |
| 89 | sweep = std::fmod(sweep, 2 * PI); |
| 90 | if (sweep < 0) sweep += 2 * PI; |
| 91 | } else { |
| 92 | if (-sweep >= 2 * PI) return -2 * PI; |
| 93 | sweep = std::fmod(sweep, 2 * PI); |
| 94 | if (sweep > 0) sweep -= 2 * PI; |
| 95 | } |
| 96 | return sweep; |
| 97 | } |
| 98 | |
| 99 | /// Polylines of a geometry, curves flattened, for hit testing. |
| 100 | std::vector<std::vector<std::pair<double, double>>> flatten(const Geometry& g) { |
| 101 | std::vector<std::vector<std::pair<double, double>>> out; |
| 102 | const float* p = g.points.data(); |
| 103 | size_t n = g.points.size(), i = 0; |
| 104 | double cx = 0, cy = 0, sx = 0, sy = 0; |
| 105 | auto line = [&](double x, double y) { |
| 106 | if (out.empty()) out.push_back({{cx, cy}}); |
| 107 | out.back().emplace_back(x, y); |
| 108 | cx = x; |
| 109 | cy = y; |
| 110 | }; |
| 111 | for (auto op : g.ops) { |
| 112 | size_t need = op == Path::Cubic ? 6 : op == Path::Quad ? 4 : op == Path::Close ? |
| 113 | if (i + need > n) break; |
| 114 | switch (op) { |
| 115 | case Path::Move: |
| 116 | out.push_back({{p[i], p[i + 1]}}); |
| 117 | cx = sx = p[i]; |
| 118 | cy = sy = p[i + 1]; |
| 119 | break; |
| 120 | case Path::Line: line(p[i], p[i + 1]); break; |
| 121 | case Path::Quad: { |
| 122 | double x0 = cx, y0 = cy; |
| 123 | for (int s = 1; s <= 16; s++) { |
| 124 | double t = s / 16.0, u = 1 - t; |
| 125 | line(u * u * x0 + 2 * u * t * p[i] + t * t * p[i + 2], u * u * y0 |
| 126 | } |
| 127 | break; |
| 128 | } |
| 129 | case Path::Cubic: { |
| 130 | double x0 = cx, y0 = cy; |
| 131 | for (int s = 1; s <= 16; s++) { |
| 132 | double t = s / 16.0, u = 1 - t; |
| 133 | double a = u * u * u, b = 3 * u * u * t, c = 3 * u * t * t, d = t |
| 134 | line(a * x0 + b * p[i] + c * p[i + 2] + d * p[i + 4], a * y0 + b * p[i |
| 135 | } |
| 136 | break; |
| 137 | } |
| 138 | case Path::Close: |
| 139 | line(sx, sy); |
| 140 | break; |
| 141 | } |
| 142 | i += need; |
| 143 | } |
| 144 | return out; |
| 145 | } |
| 146 | |
| 147 | bool contains(const Geometry& g, double x, double y, bool evenodd) { |
| 148 | int winding = 0, crossings = 0; |
| 149 | for (const auto& poly : flatten(g)) { |
| 150 | if (poly.size() < 2) continue; |
| 151 | // Subpaths fill as if closed. |
| 152 | for (size_t k = 0; k < poly.size(); k++) { |
| 153 | auto [x0, y0] = poly[k]; |
| 154 | auto [x1, y1] = poly[(k + 1) % poly.size()]; |
| 155 | if ((y0 <= y) != (y1 <= y)) { |
| 156 | double at = x0 + (y - y0) * (x1 - x0) / (y1 - y0); |
| 157 | if (at > x) { |
| 158 | crossings++; |
| 159 | winding += y1 > y0 ? 1 : -1; |
| 160 | } |
| 161 | } |
| 162 | } |
| 163 | } |
| 164 | return evenodd ? (crossings & 1) != 0 : winding != 0; |
| 165 | } |
| 166 | |
| 167 | bool near_stroke(const Geometry& g, double x, double y, double half) { |
| 168 | for (const auto& poly : flatten(g)) { |
| 169 | for (size_t k = 0; k + 1 < poly.size(); k++) { |
| 170 | auto [x0, y0] = poly[k]; |
| 171 | auto [x1, y1] = poly[k + 1]; |
| 172 | double dx = x1 - x0, dy = y1 - y0, len = dx * dx + dy * dy; |
| 173 | double t = len > 0 ? std::clamp(((x - x0) * dx + (y - y0) * dy) / len, 0.0, 1.0) |
| 174 | if (std::hypot(x - (x0 + t * dx), y - (y0 + t * dy)) <= half) return true; |
| 175 | } |
| 176 | } |
| 177 | return false; |
| 178 | } |
| 179 | |
| 180 | } // namespace |
| 181 | |
| 182 | struct Canvas::Value { |
| 183 | enum Kind { Null, Number, String, List, Gradient, PathRef, Node, Pixels } kind = Null; |
| 184 | double number = 0; |
| 185 | std::string string; |
| 186 | std::vector<float> list; |
| 187 | int64_t ref = 0; |
| 188 | std::shared_ptr<const std::vector<uint8_t>> pixels; |
| 189 | int w = 0, h = 0; |
| 190 | |
| 191 | static Value of(const Json& j) { |
| 192 | Value v; |
| 193 | if (j.isNumber()) { v.kind = Number; v.number = j.asNumber(); } |
| 194 | else if (j.isBool()) { v.kind = Number; v.number = j.asBool() ? 1 : 0; } |
| 195 | else if (j.isString()) { v.kind = String; v.string = j.asString(); } |
| 196 | else if (j.isArray()) { |
| 197 | v.kind = List; |
| 198 | for (const Json& x : j.arr()) v.list.push_back(float(x.asNumber())); |
| 199 | } else if (j.isObject()) { |
| 200 | if (const Json* g = j.find("g")) { v.kind = Gradient; v.ref = int64_t(g->asNumber()); } |
| 201 | else if (const Json* p = j.find("p")) { v.kind = PathRef; v.ref = int64_t(p->asNumber()); } |
| 202 | else if (const Json* n = j.find("n")) { v.kind = Node; v.ref = int64_t(n->asNumber()); } |
| 203 | else if (const Json* b = j.find("b64"); b && b->isString()) { |
| 204 | v.kind = Pixels; |
| 205 | v.pixels = std::make_shared<std::vector<uint8_t>>(base64(b->asString())); |
| 206 | v.w = j["w"].asInt(); |
| 207 | v.h = j["h"].asInt(); |
| 208 | } |
| 209 | } |
| 210 | return v; |
| 211 | } |
| 212 | }; |
| 213 | |
| 214 | // ───────────────────────── matrices and geometry ───────────────────────── |
| 215 | |
| 216 | Canvas::Matrix Canvas::Matrix::then(const Matrix& m) const { |
| 217 | Matrix r; |
| 218 | r.a = a * m.a + b * m.c; |
| 219 | r.b = a * m.b + b * m.d; |
| 220 | r.c = c * m.a + d * m.c; |
| 221 | r.d = c * m.b + d * m.d; |
| 222 | r.e = e * m.a + f * m.c + m.e; |
| 223 | r.f = e * m.b + f * m.d + m.f; |
| 224 | return r; |
| 225 | } |
| 226 | |
| 227 | bool Canvas::Matrix::invert(Matrix& out) const { |
| 228 | double det = a * d - b * c; |
| 229 | if (det == 0 || !std::isfinite(det)) return false; |
| 230 | out.a = d / det; |
| 231 | out.b = -b / det; |
| 232 | out.c = -c / det; |
| 233 | out.d = a / det; |
| 234 | out.e = (c * f - d * e) / det; |
| 235 | out.f = (b * e - a * f) / det; |
| 236 | return true; |
| 237 | } |
| 238 | |
| 239 | Geometry Canvas::transformed(const Geometry& path, const Matrix& m) const { |
| 240 | Geometry g; |
| 241 | g.ops = path.ops; |
| 242 | g.points.resize(path.points.size()); |
| 243 | for (size_t i = 0; i + 1 < path.points.size(); i += 2) m.apply(path.points[i], path.points[i + 1], g.points[i], g.points[i + 1 |
| 244 | return g; |
| 245 | } |
| 246 | |
| 247 | Geometry Canvas::rect_geometry(double x, double y, double w, double h) const { |
| 248 | Builder b; |
| 249 | path_method(b, state_.matrix, "rect", {Value{Value::Number, x}, Value{Value::Number, y}, Value{Value::Number, w}, Value{Value::Number, h}}); |
| 250 | return std::move(b.geometry); |
| 251 | } |
| 252 | |
| 253 | // ───────────────────────── interpreter ───────────────────────── |
| 254 | |
| 255 | Canvas::Canvas(int id, int width, int height, CanvasHost& host) : id_(id), width_(0), height_(0), host_(host) { |
| 256 | std::vector<CanvasOp> ignored; |
| 257 | resize(width, height, ignored); |
| 258 | } |
| 259 | |
| 260 | void Canvas::resize(int width, int height, std::vector<CanvasOp>& out) { |
| 261 | width_ = std::clamp(width, 0, MAX_SIDE); |
| 262 | height_ = std::clamp(height, 0, MAX_SIDE); |
| 263 | int64_t budget = std::min<int64_t>(MAX_PIXELS, host_.canvas_allowance(id_)); |
| 264 | if (int64_t(width_) * height_ > budget) width_ = height_ = 0; |
| 265 | state_ = State(); |
| 266 | stack_.clear(); |
| 267 | path_ = Builder(); |
| 268 | CanvasOp reset; |
| 269 | reset.kind = CanvasOp::Reset; |
| 270 | out.push_back(std::move(reset)); |
| 271 | } |
| 272 | |
| 273 | void Canvas::run(const Json& cmds, std::vector<CanvasOp>& out) { |
| 274 | std::vector<Value> args; |
| 275 | for (const Json& cmd : cmds.arr()) { |
| 276 | const auto& list = cmd.arr(); |
| 277 | if (list.size() < 2 || !list[0].isString()) continue; |
| 278 | const std::string& kind = list[0].asString(); |
| 279 | args.clear(); |
| 280 | auto rest = [&](size_t from) { |
| 281 | for (size_t i = from; i < list.size(); i++) args.push_back(Value::of(list[i])); |
| 282 | }; |
| 283 | if (kind == "c") { |
| 284 | rest(2); |
| 285 | if (list[1].isString()) call_method(list[1].asString(), args, out); |
| 286 | } else if (kind == "s") { |
| 287 | rest(2); |
| 288 | if (list[1].isString() && !args.empty()) set(list[1].asString(), args[0]); |
| 289 | } else if (kind == "r") { |
| 290 | resize(list[1].asInt(), list.size() > 2 ? list[2].asInt() : 0, out); |
| 291 | } else if (kind == "g") { |
| 292 | int gid = list[1].asInt(); |
| 293 | if (list.size() < 3 || !list[2].isString() || (!gradients_.count(gid) && gradients_.size() >= MAX_OBJECTS)) continue |
| 294 | Gradient g; |
| 295 | g.kind = list[2].asString(); |
| 296 | for (size_t i = 3; i < list.size(); i++) g.args.push_back(float(list[i].asNumber())); |
| 297 | gradients_[gid] = std::move(g); |
| 298 | } else if (kind == "gs") { |
| 299 | auto it = gradients_.find(list[1].asInt()); |
| 300 | Color color; |
| 301 | if (it == gradients_.end() || list.size() < 4 || it->second.stops.size() >= MAX_STOPS || !css::parse_color(list[3]. |
| 302 | Stop stop{std::clamp(float(list[2].asNumber()), 0.0f, 1.0f), color}; |
| 303 | auto& stops = it->second.stops; |
| 304 | stops.insert(std::upper_bound(stops.begin(), stops.end(), stop, [](const Stop& a, const Stop& b) { return a.offset < b.offset; }), stop); |
| 305 | } else if (kind == "pn") { |
| 306 | int pid = list[1].asInt(); |
| 307 | if (!paths_.count(pid) && paths_.size() >= MAX_OBJECTS) continue; |
| 308 | Builder b; |
| 309 | if (list.size() > 2 && list[2].isString() && list[2].asString().size() <= (1u << 20 |
| 310 | append_svg_path(list[2].asString(), b.geometry); |
| 311 | // An SVG path ends where its last command did; later Path2D calls continue from there. |
| 312 | const auto& pts = b.geometry.points; |
| 313 | if (pts.size() >= 2) { |
| 314 | b.has_point = true; |
| 315 | b.open = b.geometry.ops.back() != Path::Close; |
| 316 | b.cx = pts[pts.size() - 2]; |
| 317 | b.cy = pts[pts.size() - 1]; |
| 318 | } |
| 319 | } |
| 320 | paths_[pid] = std::move(b); |
| 321 | } else if (kind == "pc") { |
| 322 | auto it = paths_.find(list[1].asInt()); |
| 323 | if (it == paths_.end() || list.size() < 3 || !list[2].isString()) continue; |
| 324 | rest(3); |
| 325 | path_method(it->second, Matrix(), list[2].asString(), args); |
| 326 | } |
| 327 | } |
| 328 | } |
| 329 | |
| 330 | void Canvas::set(const std::string& p, const Value& v) { |
| 331 | State& s = state_; |
| 332 | Color color; |
| 333 | if (p == "fillStyle" || p == "strokeStyle") { |
| 334 | Paint& paint = p == "fillStyle" ? s.fill : s.stroke; |
| 335 | if (v.kind == Value::String && css::parse_color(v.string, color)) paint = Paint{false, color, 0}; |
| 336 | else if (v.kind == Value::Gradient) paint = Paint{true, Color{}, int(v.ref)}; |
| 337 | } else if (p == "lineWidth") { |
| 338 | if (v.kind == Value::Number && v.number > 0 && std::isfinite(v.number)) s.line_width = float(v.number); |
| 339 | } else if (p == "lineCap") { |
| 340 | s.line_cap = v.string == "round" ? 1 : v.string == "square" ? 2 : v.string == "butt" ? 0 |
| 341 | } else if (p == "lineJoin") { |
| 342 | s.line_join = v.string == "round" ? 1 : v.string == "bevel" ? 2 : v.string == "miter" ? 0 |
| 343 | } else if (p == "miterLimit") { |
| 344 | if (v.kind == Value::Number && v.number > 0 && std::isfinite(v.number)) s.miter_limit = float(v.number); |
| 345 | } else if (p == "lineDashOffset") { |
| 346 | if (v.kind == Value::Number && std::isfinite(v.number)) s.dash_offset = float(v.number); |
| 347 | } else if (p == "font") { |
| 348 | if (v.kind == Value::String && !v.string.empty()) s.font = v.string; |
| 349 | } else if (p == "textAlign") { |
| 350 | if (v.kind == Value::String) s.align = v.string; |
| 351 | } else if (p == "textBaseline") { |
| 352 | if (v.kind == Value::String) s.baseline = v.string; |
| 353 | } else if (p == "globalAlpha") { |
| 354 | if (v.kind == Value::Number && v.number >= 0 && v.number <= 1) s.alpha = float(v.number); |
| 355 | } else if (p == "globalCompositeOperation") { |
| 356 | bool known; |
| 357 | Composite c = composite_of(v.string, known); |
| 358 | if (known) s.composite = c; |
| 359 | } else if (p == "shadowBlur") { |
| 360 | if (v.kind == Value::Number && v.number >= 0 && std::isfinite(v.number)) s.shadow_blur = float(std::min(v.number, 100.0)); |
| 361 | } else if (p == "shadowColor") { |
| 362 | if (v.kind == Value::String && css::parse_color(v.string, color)) s.shadow_color = color; |
| 363 | } else if (p == "shadowOffsetX") { |
| 364 | if (v.kind == Value::Number && std::isfinite(v.number)) s.shadow_x = float(v.number); |
| 365 | } else if (p == "shadowOffsetY") { |
| 366 | if (v.kind == Value::Number && std::isfinite(v.number)) s.shadow_y = float(v.number); |
| 367 | } else if (p == "imageSmoothingEnabled") { |
| 368 | if (v.kind == Value::Number) s.smoothing = v.number != 0; |
| 369 | } |
| 370 | } |
| 371 | |
| 372 | CanvasOp Canvas::op(CanvasOp::Kind kind) const { |
| 373 | CanvasOp o; |
| 374 | o.kind = kind; |
| 375 | const Matrix& m = state_.matrix; |
| 376 | o.matrix[0] = float(m.a); o.matrix[1] = float(m.b); o.matrix[2] = float(m.c); |
| 377 | o.matrix[3] = float(m.d); o.matrix[4] = float(m.e); o.matrix[5] = float(m.f); |
| 378 | o.alpha = state_.alpha; |
| 379 | o.composite = state_.composite; |
| 380 | o.shadow_color = state_.shadow_color; |
| 381 | o.shadow_blur = state_.shadow_blur; |
| 382 | o.shadow_x = state_.shadow_x; |
| 383 | o.shadow_y = state_.shadow_y; |
| 384 | o.clips = state_.clips; |
| 385 | o.smoothing = state_.smoothing; |
| 386 | return o; |
| 387 | } |
| 388 | |
| 389 | bool Canvas::paint_of(const Paint& paint, CanvasPaint& out) const { |
| 390 | if (!paint.gradient) { |
| 391 | out.kind = CanvasPaint::Solid; |
| 392 | out.color = paint.color; |
| 393 | return true; |
| 394 | } |
| 395 | auto it = gradients_.find(paint.id); |
| 396 | if (it == gradients_.end()) return false; |
| 397 | const Gradient& g = it->second; |
| 398 | out.stops = g.stops; |
| 399 | auto args = [&](size_t n) { |
| 400 | if (g.args.size() < n) return false; |
| 401 | for (size_t i = 0; i < n; i++) out.args[i] = std::isfinite(g.args[i]) ? g.args[i] : 0; |
| 402 | return true; |
| 403 | }; |
| 404 | if (g.kind == "linear" && args(4)) out.kind = CanvasPaint::Linear; |
| 405 | else if (g.kind == "radial" && args(6)) out.kind = CanvasPaint::Radial; |
| 406 | else if (g.kind == "conic" && args(3)) out.kind = CanvasPaint::Conic; |
| 407 | else return false; // patterns are not drawn |
| 408 | // A gradient without stops paints nothing, as in browsers. |
| 409 | if (out.stops.empty()) out = CanvasPaint{CanvasPaint::Solid, Color{0, 0, 0, 0}}; |
| 410 | return true; |
| 411 | } |
| 412 | |
| 413 | void Canvas::fill(const Geometry& path, bool evenodd, std::vector<CanvasOp>& out) { |
| 414 | if (path.empty()) return; |
| 415 | CanvasOp o = op(CanvasOp::Fill); |
| 416 | if (!paint_of(state_.fill, o.paint)) return; |
| 417 | o.path = path; |
| 418 | o.evenodd = evenodd; |
| 419 | out.push_back(std::move(o)); |
| 420 | } |
| 421 | |
| 422 | void Canvas::stroke(const Geometry& path, std::vector<CanvasOp>& out) { |
| 423 | if (path.empty()) return; |
| 424 | CanvasOp o = op(CanvasOp::Stroke); |
| 425 | if (!paint_of(state_.stroke, o.paint)) return; |
| 426 | o.path = path; |
| 427 | o.line_width = state_.line_width; |
| 428 | o.line_cap = state_.line_cap; |
| 429 | o.line_join = state_.line_join; |
| 430 | o.miter_limit = state_.miter_limit; |
| 431 | o.dashes = state_.dash; |
| 432 | o.dash_offset = state_.dash_offset; |
| 433 | out.push_back(std::move(o)); |
| 434 | } |
| 435 | |
| 436 | void Canvas::text(const std::string& full, double x, double y, const Value* max_width, bool |
| 437 | // Truncated at a UTF-8 boundary. |
| 438 | size_t cut = std::min(full.size(), MAX_TEXT); |
| 439 | while (cut < full.size() && cut > 0 && (uint8_t(full[cut]) & 0xC0) == 0x80) cut--; |
| 440 | std::string s = full.substr(0, cut); |
| 441 | FontMetrics m; |
| 442 | int font = host_.canvas_font(state_.font, m); |
| 443 | if (!font || s.empty()) return; |
| 444 | float width = host_.canvas_text_width(font, s); |
| 445 | CanvasOp o = op(CanvasOp::Text); |
| 446 | if (!paint_of(stroke_text ? state_.stroke : state_.fill, o.paint)) return; |
| 447 | const std::string& align = state_.align; |
| 448 | o.text_dx = align == "center" ? -width / 2 : (align == "right" || align == "end") ? -width |
| 449 | const std::string& baseline = state_.baseline; |
| 450 | float shift = 0; |
| 451 | if (baseline == "top" || baseline == "hanging") shift = m.ascent; |
| 452 | else if (baseline == "middle") shift = (m.ascent - m.descent) / 2; |
| 453 | else if (baseline == "bottom" || baseline == "ideographic") shift = -m.descent; |
| 454 | o.x = float(x); |
| 455 | o.y = float(y) + shift; |
| 456 | if (max_width && max_width->kind == Value::Number && max_width->number > 0 && width > max_width->number) o.scale_x = float(max_width->number / width); |
| 457 | else if (max_width && max_width->kind == Value::Number && max_width->number <= 0) return; |
| 458 | o.font = font; |
| 459 | o.text = std::move(s); |
| 460 | o.stroke_text = stroke_text; |
| 461 | o.line_width = state_.line_width; |
| 462 | out.push_back(std::move(o)); |
| 463 | } |
| 464 | |
| 465 | void Canvas::image(const std::vector<Value>& a, std::vector<CanvasOp>& out) { |
| 466 | if (a.empty() || a[0].kind != Value::Node) return; |
| 467 | int image = 0, canvas = 0; |
| 468 | float w = 0, h = 0; |
| 469 | if (!host_.canvas_source(a[0].ref, image, canvas, w, h) || w <= 0 || h <= 0) return; |
| 470 | auto n = [&](size_t i) { return i < a.size() && a[i].kind == Value::Number && std::isfinite(a[i].number) ? |
| 471 | CanvasOp o = op(CanvasOp::Image); |
| 472 | o.image = image; |
| 473 | o.canvas = canvas; |
| 474 | switch (a.size()) { |
| 475 | case 3: o.dx = n(1); o.dy = n(2); o.dw = w; o.dh = h; break; |
| 476 | case 5: o.dx = n(1); o.dy = n(2); o.dw = n(3); o.dh = n(4); break; |
| 477 | case 9: |
| 478 | o.sx = n(1); o.sy = n(2); o.sw = n(3); o.sh = n(4); |
| 479 | o.dx = n(5); o.dy = n(6); o.dw = n(7); o.dh = n(8); |
| 480 | break; |
| 481 | default: return; |
| 482 | } |
| 483 | if (o.dw == 0 || o.dh == 0 || (a.size() == 9 && (o.sw == 0 || o.sh == |
| 484 | out.push_back(std::move(o)); |
| 485 | } |
| 486 | |
| 487 | void Canvas::call_method(const std::string& method, const std::vector<Value>& a, std::vector< |
| 488 | if (width_ == 0 || height_ == 0) return; |
| 489 | auto n = [&](size_t i, double fallback = 0) { return i < a.size() && a[i].kind == Value::Number |
| 490 | auto evenodd = [&](size_t i) { return i < a.size() && a[i].kind == Value::String && a[i].string == "evenodd"; }; |
| 491 | auto path_arg = [&]() -> const Builder* { |
| 492 | if (a.empty() || a[0].kind != Value::PathRef) return nullptr; |
| 493 | auto it = paths_.find(int(a[0].ref)); |
| 494 | return it == paths_.end() ? nullptr : &it->second; |
| 495 | }; |
| 496 | State& s = state_; |
| 497 | if (method == "save") { |
| 498 | if (stack_.size() < MAX_STACK) stack_.push_back(s); |
| 499 | } else if (method == "restore") { |
| 500 | if (!stack_.empty()) { |
| 501 | s = std::move(stack_.back()); |
| 502 | stack_.pop_back(); |
| 503 | } |
| 504 | } else if (method == "scale") { |
| 505 | s.matrix = Matrix{n(0, 1), 0, 0, n(1, 1), 0, 0}.then(s.matrix); |
| 506 | } else if (method == "rotate") { |
| 507 | double r = n(0), c = std::cos(r), si = std::sin(r); |
| 508 | s.matrix = Matrix{c, si, -si, c, 0, 0}.then(s.matrix); |
| 509 | } else if (method == "translate") { |
| 510 | s.matrix = Matrix{1, 0, 0, 1, n(0), n(1)}.then(s.matrix); |
| 511 | } else if (method == "transform") { |
| 512 | s.matrix = Matrix{n(0, 1), n(1), n(2), n(3, 1), n(4), n(5)}. |
| 513 | } else if (method == "setTransform") { |
| 514 | if (!a.empty() && a[0].kind == Value::List && a[0].list.size() >= 6) { |
| 515 | const auto& l = a[0].list; |
| 516 | s.matrix = Matrix{l[0], l[1], l[2], l[3], l[4], l[5]}; |
| 517 | } else s.matrix = Matrix{n(0, 1), n(1), n(2), n(3, 1), n(4), n( |
| 518 | } else if (method == "resetTransform") { |
| 519 | s.matrix = Matrix(); |
| 520 | } else if (method == "clearRect") { |
| 521 | CanvasOp o = op(CanvasOp::Clear); |
| 522 | o.path = rect_geometry(n(0), n(1), n(2), n(3)); |
| 523 | out.push_back(std::move(o)); |
| 524 | } else if (method == "fillRect") { |
| 525 | fill(rect_geometry(n(0), n(1), n(2), n(3)), false, out); |
| 526 | } else if (method == "strokeRect") { |
| 527 | stroke(rect_geometry(n(0), n(1), n(2), n(3)), out); |
| 528 | } else if (method == "beginPath") { |
| 529 | path_ = Builder(); |
| 530 | } else if (method == "fill") { |
| 531 | if (const Builder* p = path_arg()) fill(transformed(p->geometry, s.matrix), evenodd(1), out); |
| 532 | else fill(path_.geometry, evenodd(0), out); |
| 533 | } else if (method == "stroke") { |
| 534 | if (const Builder* p = path_arg()) stroke(transformed(p->geometry, s.matrix), out); |
| 535 | else stroke(path_.geometry, out); |
| 536 | } else if (method == "clip") { |
| 537 | CanvasClip clip; |
| 538 | if (const Builder* p = path_arg()) { |
| 539 | clip.path = transformed(p->geometry, s.matrix); |
| 540 | clip.evenodd = evenodd(1); |
| 541 | } else { |
| 542 | clip.path = path_.geometry; |
| 543 | clip.evenodd = evenodd(0); |
| 544 | } |
| 545 | auto clips = s.clips ? std::make_shared<std::vector<CanvasClip>>(*s.clips) : std::make_shared<std::vector<CanvasClip |
| 546 | // An empty path clips everything away. |
| 547 | clips->push_back(std::move(clip)); |
| 548 | s.clips = std::move(clips); |
| 549 | } else if (method == "fillText" || method == "strokeText") { |
| 550 | if (!a.empty() && a[0].kind == Value::String) text(a[0].string, n(1), n(2), a.size() > |
| 551 | } else if (method == "setLineDash") { |
| 552 | if (!a.empty() && a[0].kind == Value::List && a[0].list.size() <= 64) { |
| 553 | const auto& v = a[0].list; |
| 554 | if (std::all_of(v.begin(), v.end(), [](float x) { return std::isfinite(x) && x >= 0; })) { |
| 555 | s.dash = v; |
| 556 | if (v.size() % 2 == 1) s.dash.insert(s.dash.end(), v.begin(), v.end()); |
| 557 | } |
| 558 | } |
| 559 | } else if (method == "putImageData") { |
| 560 | if (a.empty() || a[0].kind != Value::Pixels) return; |
| 561 | const Value& px = a[0]; |
| 562 | if (px.w <= 0 || px.h <= 0 || px.w > MAX_SIDE || px.h > MAX_SIDE || int64_t(px.w) * px.h > MAX_PIXELS || px.pixels-> |
| 563 | CanvasOp o; |
| 564 | o.kind = CanvasOp::PutImage; |
| 565 | o.rgba = px.pixels; |
| 566 | o.w = px.w; |
| 567 | o.h = px.h; |
| 568 | o.dx = float(n(1)); |
| 569 | o.dy = float(n(2)); |
| 570 | out.push_back(std::move(o)); |
| 571 | } else if (method == "drawImage") { |
| 572 | image(a, out); |
| 573 | } else { |
| 574 | path_method(path_, s.matrix, method, a); |
| 575 | } |
| 576 | } |
| 577 | |
| 578 | void Canvas::path_method(Builder& b, const Matrix& m, const std::string& method, const std:: |
| 579 | auto n = [&](size_t i, double fallback = 0) { return i < a.size() && a[i].kind == Value::Number |
| 580 | auto truthy = [&](size_t i) { |
| 581 | if (i >= a.size()) return false; |
| 582 | if (a[i].kind == Value::Number) return a[i].number != 0; |
| 583 | if (a[i].kind == Value::String) return !a[i].string.empty() && a[i].string != "false"; |
| 584 | return false; |
| 585 | }; |
| 586 | auto point = [&](double x, double y) { |
| 587 | float px, py; |
| 588 | m.apply(x, y, px, py); |
| 589 | b.geometry.points.push_back(px); |
| 590 | b.geometry.points.push_back(py); |
| 591 | return std::make_pair(px, py); |
| 592 | }; |
| 593 | auto move = [&](double x, double y) { |
| 594 | b.geometry.ops.push_back(Path::Move); |
| 595 | auto [px, py] = point(x, y); |
| 596 | b.sx = b.cx = px; |
| 597 | b.sy = b.cy = py; |
| 598 | b.open = b.has_point = true; |
| 599 | }; |
| 600 | // Canvas: a segment with no current point starts its subpath at its own first point; after |
| 601 | // closePath the next one starts where the closed figure did. |
| 602 | auto ensure = [&](double x, double y) { |
| 603 | if (b.open) return; |
| 604 | if (!b.has_point) { |
| 605 | move(x, y); |
| 606 | return; |
| 607 | } |
| 608 | b.geometry.ops.push_back(Path::Move); |
| 609 | b.geometry.points.push_back(b.cx); |
| 610 | b.geometry.points.push_back(b.cy); |
| 611 | b.sx = b.cx; |
| 612 | b.sy = b.cy; |
| 613 | b.open = true; |
| 614 | }; |
| 615 | auto close = [&] { |
| 616 | if (!b.open) return; |
| 617 | b.geometry.ops.push_back(Path::Close); |
| 618 | b.cx = b.sx; |
| 619 | b.cy = b.sy; |
| 620 | b.open = false; |
| 621 | }; |
| 622 | auto set_current = [&](double x, double y) { |
| 623 | m.apply(x, y, b.cx, b.cy); |
| 624 | b.has_point = true; |
| 625 | }; |
| 626 | auto line = [&](double x, double y) { |
| 627 | ensure(x, y); |
| 628 | b.geometry.ops.push_back(Path::Line); |
| 629 | auto [px, py] = point(x, y); |
| 630 | b.cx = px; |
| 631 | b.cy = py; |
| 632 | }; |
| 633 | auto cubic = [&](double x1, double y1, double x2, double y2, double x, double y) { |
| 634 | b.geometry.ops.push_back(Path::Cubic); |
| 635 | point(x1, y1); |
| 636 | point(x2, y2); |
| 637 | auto [px, py] = point(x, y); |
| 638 | b.cx = px; |
| 639 | b.cy = py; |
| 640 | }; |
| 641 | auto arc = [&](double cx, double cy, double rx, double ry, double rotation, double start, |
| 642 | double sweep = sweep_of(start, end, anticlockwise); |
| 643 | double cr = std::cos(rotation), sr = std::sin(rotation); |
| 644 | double x0 = cx + rx * std::cos(start) * cr - ry * std::sin(start) * sr; |
| 645 | double y0 = cy + rx * std::cos(start) * sr + ry * std::sin(start) * cr; |
| 646 | if (b.has_point) line(x0, y0); |
| 647 | else move(x0, y0); |
| 648 | if (sweep == 0) return; |
| 649 | arc_segments(cx, cy, rx, ry, rotation, start, sweep, [&](double x1, double y1, double x2, double y2, double x, double y) { cubic |
| 650 | }; |
| 651 | /// The current point in this path's own space. |
| 652 | auto current = [&](double& x, double& y) { |
| 653 | Matrix inverse; |
| 654 | if (!m.invert(inverse)) return false; |
| 655 | float fx, fy; |
| 656 | inverse.apply(b.cx, b.cy, fx, fy); |
| 657 | x = fx; |
| 658 | y = fy; |
| 659 | return true; |
| 660 | }; |
| 661 | if (method == "moveTo") move(n(0), n(1)); |
| 662 | else if (method == "lineTo") line(n(0), n(1)); |
| 663 | else if (method == "closePath") close(); |
| 664 | else if (method == "bezierCurveTo") { |
| 665 | ensure(n(0), n(1)); |
| 666 | cubic(n(0), n(1), n(2), n(3), n(4), n(5)); |
| 667 | } else if (method == "quadraticCurveTo") { |
| 668 | ensure(n(0), n(1)); |
| 669 | b.geometry.ops.push_back(Path::Quad); |
| 670 | point(n(0), n(1)); |
| 671 | auto [px, py] = point(n(2), n(3)); |
| 672 | b.cx = px; |
| 673 | b.cy = py; |
| 674 | } else if (method == "arc") { |
| 675 | arc(n(0), n(1), std::max(0.0, n(2)), std::max(0.0, n(2)), |
| 676 | } else if (method == "ellipse") { |
| 677 | if (n(2) < 0 || n(3) < 0) return; |
| 678 | arc(n(0), n(1), n(2), n(3), n(4), n(5), n(6), |
| 679 | } else if (method == "arcTo") { |
| 680 | double x1 = n(0), y1 = n(1), x2 = n(2), y2 = n(3), r = std:: |
| 681 | double x0, y0; |
| 682 | if (!b.has_point) { |
| 683 | move(x1, y1); |
| 684 | return; |
| 685 | } |
| 686 | if (!current(x0, y0)) return; |
| 687 | double ax = x0 - x1, ay = y0 - y1, bx = x2 - x1, by = y2 - y1; |
| 688 | double la = std::hypot(ax, ay), lb = std::hypot(bx, by); |
| 689 | double cross = ax * by - ay * bx; |
| 690 | if (r == 0 || la == 0 || lb == 0 || std::fabs(cross) < 1e-9 |
| 691 | line(x1, y1); |
| 692 | return; |
| 693 | } |
| 694 | double cosine = (ax * bx + ay * by) / (la * lb); |
| 695 | double angle = std::acos(std::clamp(cosine, -1.0, 1.0)); |
| 696 | double tangent = r / std::tan(angle / 2); |
| 697 | double t1x = x1 + ax / la * tangent, t1y = y1 + ay / la * tangent; |
| 698 | double t2x = x1 + bx / lb * tangent, t2y = y1 + by / lb * tangent; |
| 699 | double mx = ax / la + bx / lb, my = ay / la + by / lb, ml = std::hypot(mx, my); |
| 700 | double distance = r / std::sin(angle / 2); |
| 701 | double cx = x1 + mx / ml * distance, cy = y1 + my / ml * distance; |
| 702 | double start = std::atan2(t1y - cy, t1x - cx), end = std::atan2(t2y - cy, t2x - cx); |
| 703 | line(t1x, t1y); |
| 704 | arc(cx, cy, r, r, 0, start, end, cross > 0); |
| 705 | } else if (method == "rect") { |
| 706 | double x = n(0), y = n(1), w = n(2), h = n(3); |
| 707 | move(x, y); |
| 708 | line(x + w, y); |
| 709 | line(x + w, y + h); |
| 710 | line(x, y + h); |
| 711 | close(); |
| 712 | } else if (method == "roundRect") { |
| 713 | double x = n(0), y = n(1), w = n(2), h = n(3); |
| 714 | if (w < 0) { x += w; w = -w; } |
| 715 | if (h < 0) { y += h; h = -h; } |
| 716 | double r = 0; |
| 717 | if (a.size() > 4) { |
| 718 | if (a[4].kind == Value::Number) r = n(4); |
| 719 | else if (a[4].kind == Value::List && !a[4].list.empty() && std::isfinite(a[4].list[0])) r = a[ |
| 720 | } |
| 721 | r = std::max(0.0, std::min({r, w / 2, h / 2})); |
| 722 | if (r == 0) { |
| 723 | path_method(b, m, "rect", {Value{Value::Number, x}, Value{Value::Number, y}, Value{Value::Number, w}, Value{Value::Number, h}}); |
| 724 | return; |
| 725 | } |
| 726 | move(x + r, y); |
| 727 | line(x + w - r, y); |
| 728 | arc_segments(x + w - r, y + r, r, r, 0, -PI / 2, PI / 2, [&](double a1, double b1, |
| 729 | line(x + w, y + h - r); |
| 730 | arc_segments(x + w - r, y + h - r, r, r, 0, 0, PI / 2, [&](double a1, double b1, double |
| 731 | line(x + r, y + h); |
| 732 | arc_segments(x + r, y + h - r, r, r, 0, PI / 2, PI / 2, [&](double a1, double b1, double |
| 733 | line(x, y + r); |
| 734 | arc_segments(x + r, y + r, r, r, 0, PI, PI / 2, [&](double a1, double b1, double a2, double b2, |
| 735 | close(); |
| 736 | // The spec starts the next subpath at the rectangle's origin, not at the first corner arc. |
| 737 | set_current(x, y); |
| 738 | } else if (method == "addPath") { |
| 739 | if (a.empty() || a[0].kind != Value::PathRef) return; |
| 740 | auto it = paths_.find(int(a[0].ref)); |
| 741 | if (it == paths_.end() || &it->second == &b) return; |
| 742 | Geometry g = transformed(it->second.geometry, m); |
| 743 | b.geometry.ops.insert(b.geometry.ops.end(), g.ops.begin(), g.ops.end()); |
| 744 | b.geometry.points.insert(b.geometry.points.end(), g.points.begin(), g.points.end()); |
| 745 | b.open = it->second.open; |
| 746 | b.has_point = it->second.has_point; |
| 747 | if (g.points.size() >= 2) { |
| 748 | b.cx = g.points[g.points.size() - 2]; |
| 749 | b.cy = g.points.back(); |
| 750 | } |
| 751 | } |
| 752 | } |
| 753 | |
| 754 | Json Canvas::call(const std::string& method, const Json& args) const { |
| 755 | const auto& list = args.arr(); |
| 756 | std::vector<Value> a; |
| 757 | for (const Json& j : list) a.push_back(Value::of(j)); |
| 758 | const Matrix& m = state_.matrix; |
| 759 | if (method == "getTransform") { |
| 760 | Json out = Json::array(); |
| 761 | for (double v : {m.a, m.b, m.c, m.d, m.e, m.f}) out.push(v); |
| 762 | return out; |
| 763 | } |
| 764 | if (method == "getLineDash") { |
| 765 | Json out = Json::array(); |
| 766 | for (float v : state_.dash) out.push(double(v)); |
| 767 | return out; |
| 768 | } |
| 769 | if (method == "isPointInPath" || method == "isPointInStroke") { |
| 770 | Geometry path = path_.geometry; |
| 771 | size_t at = 0; |
| 772 | if (!a.empty() && a[0].kind == Value::PathRef) { |
| 773 | auto it = paths_.find(int(a[0].ref)); |
| 774 | if (it == paths_.end()) return false; |
| 775 | path = transformed(it->second.geometry, m); |
| 776 | at = 1; |
| 777 | } |
| 778 | auto n = [&](size_t i) { return i < a.size() && a[i].kind == Value::Number ? a[i].number : 0.0; }; |
| 779 | double x = n(at), y = n(at + 1); |
| 780 | if (method == "isPointInPath") return contains(path, x, y, at + 2 < a.size() && a[at + 2].string == "evenodd"); |
| 781 | double scale = std::sqrt(std::fabs(m.a * m.d - m.b * m.c)); |
| 782 | return near_stroke(path, x, y, state_.line_width * scale / 2); |
| 783 | } |
| 784 | return Json::object().set("error", "unsupported"); |
| 785 | } |
| 786 | |
| 787 | // ───────────────────────── SVG path data ───────────────────────── |
| 788 | |
| 789 | void append_svg_path(const std::string& d, Geometry& out) { |
| 790 | std::vector<std::string> tokens; |
| 791 | std::string current; |
| 792 | auto flush = [&] { |
| 793 | if (!current.empty()) tokens.push_back(std::move(current)); |
| 794 | current.clear(); |
| 795 | }; |
| 796 | for (char ch : d) { |
| 797 | bool letter = (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z'); |
| 798 | if (letter && ch != 'e' && ch != 'E') { |
| 799 | flush(); |
| 800 | tokens.emplace_back(1, ch); |
| 801 | } else if (ch == ',' || ch == ' ' || ch == '\n' || ch == '\t' |
| 802 | flush(); |
| 803 | } else if (ch == '-' && !current.empty() && current.back() != 'e' && current.back() != 'E') { |
| 804 | flush(); |
| 805 | current = "-"; |
| 806 | } else if (ch == '.' && current.find('.') != std::string::npos) { |
| 807 | flush(); |
| 808 | current = "."; |
| 809 | } else current.push_back(ch); |
| 810 | } |
| 811 | flush(); |
| 812 | size_t i = 0; |
| 813 | char command = 'M'; |
| 814 | double px = 0, py = 0, sx = 0, sy = 0; |
| 815 | bool has_control = false; |
| 816 | double lcx = 0, lcy = 0; |
| 817 | bool open = false; |
| 818 | auto next = [&](double& v) { |
| 819 | if (i >= tokens.size()) return false; |
| 820 | auto n = css::number(tokens[i]); |
| 821 | if (!n) return false; |
| 822 | v = *n; |
| 823 | i++; |
| 824 | return true; |
| 825 | }; |
| 826 | auto push = [&](Path::Op op, std::initializer_list<double> pts) { |
| 827 | out.ops.push_back(op); |
| 828 | for (double v : pts) out.points.push_back(float(v)); |
| 829 | }; |
| 830 | auto ensure = [&] { |
| 831 | if (!open) { |
| 832 | push(Path::Move, {px, py}); |
| 833 | open = true; |
| 834 | } |
| 835 | }; |
| 836 | while (i < tokens.size()) { |
| 837 | const std::string& t = tokens[i]; |
| 838 | if (t.size() == 1 && ((t[0] >= 'a' && t[0] <= 'z') || (t[0] >= |
| 839 | command = t[0]; |
| 840 | i++; |
| 841 | if (command == 'Z' || command == 'z') { |
| 842 | if (open) push(Path::Close, {}); |
| 843 | open = false; |
| 844 | px = sx; |
| 845 | py = sy; |
| 846 | has_control = false; |
| 847 | continue; |
| 848 | } |
| 849 | } |
| 850 | bool relative = command >= 'a' && command <= 'z'; |
| 851 | double ox = relative ? px : 0, oy = relative ? py : 0; |
| 852 | switch (command & ~0x20) { |
| 853 | case 'M': { |
| 854 | double x, y; |
| 855 | if (!next(x) || !next(y)) return; |
| 856 | px = ox + x; |
| 857 | py = oy + y; |
| 858 | push(Path::Move, {px, py}); |
| 859 | open = true; |
| 860 | sx = px; |
| 861 | sy = py; |
| 862 | command = relative ? 'l' : 'L'; |
| 863 | has_control = false; |
| 864 | break; |
| 865 | } |
| 866 | case 'L': { |
| 867 | double x, y; |
| 868 | if (!next(x) || !next(y)) return; |
| 869 | ensure(); |
| 870 | px = ox + x; |
| 871 | py = oy + y; |
| 872 | push(Path::Line, {px, py}); |
| 873 | has_control = false; |
| 874 | break; |
| 875 | } |
| 876 | case 'H': { |
| 877 | double x; |
| 878 | if (!next(x)) return; |
| 879 | ensure(); |
| 880 | px = (relative ? px : 0) + x; |
| 881 | push(Path::Line, {px, py}); |
| 882 | has_control = false; |
| 883 | break; |
| 884 | } |
| 885 | case 'V': { |
| 886 | double y; |
| 887 | if (!next(y)) return; |
| 888 | ensure(); |
| 889 | py = (relative ? py : 0) + y; |
| 890 | push(Path::Line, {px, py}); |
| 891 | has_control = false; |
| 892 | break; |
| 893 | } |
| 894 | case 'C': { |
| 895 | double x1, y1, x2, y2, x, y; |
| 896 | if (!next(x1) || !next(y1) || !next(x2) || !next(y2) || !next(x) || !next(y)) |
| 897 | ensure(); |
| 898 | push(Path::Cubic, {ox + x1, oy + y1, ox + x2, oy + y2, ox + x, oy + y}); |
| 899 | lcx = ox + x2; |
| 900 | lcy = oy + y2; |
| 901 | has_control = true; |
| 902 | px = ox + x; |
| 903 | py = oy + y; |
| 904 | break; |
| 905 | } |
| 906 | case 'S': { |
| 907 | double x2, y2, x, y; |
| 908 | if (!next(x2) || !next(y2) || !next(x) || !next(y)) return; |
| 909 | ensure(); |
| 910 | double c1x = has_control ? 2 * px - lcx : px, c1y = has_control ? 2 * py - lcy : py; |
| 911 | push(Path::Cubic, {c1x, c1y, ox + x2, oy + y2, ox + x, oy + y}); |
| 912 | lcx = ox + x2; |
| 913 | lcy = oy + y2; |
| 914 | has_control = true; |
| 915 | px = ox + x; |
| 916 | py = oy + y; |
| 917 | break; |
| 918 | } |
| 919 | case 'Q': { |
| 920 | double x1, y1, x, y; |
| 921 | if (!next(x1) || !next(y1) || !next(x) || !next(y)) return; |
| 922 | ensure(); |
| 923 | push(Path::Quad, {ox + x1, oy + y1, ox + x, oy + y}); |
| 924 | lcx = ox + x1; |
| 925 | lcy = oy + y1; |
| 926 | has_control = true; |
| 927 | px = ox + x; |
| 928 | py = oy + y; |
| 929 | break; |
| 930 | } |
| 931 | case 'T': { |
| 932 | double x, y; |
| 933 | if (!next(x) || !next(y)) return; |
| 934 | ensure(); |
| 935 | double cx = has_control ? 2 * px - lcx : px, cy = has_control ? 2 * py - lcy : py; |
| 936 | push(Path::Quad, {cx, cy, ox + x, oy + y}); |
| 937 | lcx = cx; |
| 938 | lcy = cy; |
| 939 | has_control = true; |
| 940 | px = ox + x; |
| 941 | py = oy + y; |
| 942 | break; |
| 943 | } |
| 944 | case 'A': { |
| 945 | double rx, ry, rotation, large, sweep_flag, x, y; |
| 946 | if (!next(rx) || !next(ry) || !next(rotation) || !next(large) || !next(sweep_flag) || !next(x) |
| 947 | ensure(); |
| 948 | double x2 = ox + x, y2 = oy + y; |
| 949 | rx = std::fabs(rx); |
| 950 | ry = std::fabs(ry); |
| 951 | if (rx == 0 || ry == 0 || (x2 == px && y2 == py)) { |
| 952 | push(Path::Line, {x2, y2}); |
| 953 | } else { |
| 954 | // SVG 1.1 F.6.5: endpoint to centre parameterisation. |
| 955 | double phi = rotation * PI / 180, c = std::cos(phi), s = std::sin(phi); |
| 956 | double dx = (px - x2) / 2, dy = (py - y2) / 2; |
| 957 | double x1p = c * dx + s * dy, y1p = -s * dx + c * dy; |
| 958 | double lambda = (x1p * x1p) / (rx * rx) + (y1p * y1p) / (ry * ry); |
| 959 | if (lambda > 1) { |
| 960 | rx *= std::sqrt(lambda); |
| 961 | ry *= std::sqrt(lambda); |
| 962 | } |
| 963 | double num = rx * rx * ry * ry - rx * rx * y1p * y1p - ry * ry * x1p * x1p; |
| 964 | double den = rx * rx * y1p * y1p + ry * ry * x1p * x1p; |
| 965 | double k = std::sqrt(std::max(0.0, num / den)) * ((large != 0) == (sweep_flag != 0) ? |
| 966 | double cxp = k * rx * y1p / ry, cyp = -k * ry * x1p / rx; |
| 967 | double cx = c * cxp - s * cyp + (px + x2) / 2, cy = s * cxp + c * cyp + (py + y2) |
| 968 | auto angle = [](double ux, double uy, double vx, double vy) { |
| 969 | double a = std::atan2(ux * vy - uy * vx, ux * vx + uy * vy); |
| 970 | return a; |
| 971 | }; |
| 972 | double theta = angle(1, 0, (x1p - cxp) / rx, (y1p - cyp) / ry); |
| 973 | double delta = angle((x1p - cxp) / rx, (y1p - cyp) / ry, (-x1p - cxp) / rx, (-y1p - cyp) / ry); |
| 974 | if (sweep_flag == 0 && delta > 0) delta -= 2 * PI; |
| 975 | else if (sweep_flag != 0 && delta < 0) delta += 2 * PI; |
| 976 | arc_segments(cx, cy, rx, ry, phi, theta, delta, [&](double a1, double b1, double a2, double b2, double a3, double b3) { |
| 977 | push(Path::Cubic, {a1, b1, a2, b2, a3, b3}); |
| 978 | }); |
| 979 | } |
| 980 | px = x2; |
| 981 | py = y2; |
| 982 | has_control = false; |
| 983 | break; |
| 984 | } |
| 985 | default: |
| 986 | return; |
| 987 | } |
| 988 | } |
| 989 | } |
| 990 | |
| 991 | } // namespace twlite |
| 992 | |