From 5ee624b384923d0a05c37b312a6553aa331596ea Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 27 Nov 2026 13:17:31 -0800 Subject: [PATCH 1/3] kurbo: keep a copy of the crates.io 0.13.1 package in vendor/ Add the kurbo 0.13.1 package to vendor/ with no file changed, so that a fix to it can reach the Craft apps through this repository. The package was published from the v0.13.1 tag of linebender/kurbo, and every file of the archive is kept. Add a workspace exclude, a [patch.crates-io] entry, SOURCE.json with the archive hash and per-file hashes, a NOTICE section, and the package's tests in the backend test script, whose other backends now also build against the copy. Every workspace crate that uses kurbo 0.13 builds against the copy, so Cargo.lock drops the package's registry source and checksum. --- Cargo.lock | 2 - Cargo.toml | 3 +- NOTICE | 7 + scripts/test-pdf-backends.sh | 3 +- vendor/kurbo/.cargo_vcs_info.json | 6 + vendor/kurbo/Cargo.lock | 705 +++++++ vendor/kurbo/Cargo.toml | 230 +++ vendor/kurbo/Cargo.toml.orig | 81 + vendor/kurbo/LICENSE-APACHE | 202 ++ vendor/kurbo/LICENSE-MIT | 25 + vendor/kurbo/README.craft.md | 43 + vendor/kurbo/README.md | 94 + vendor/kurbo/SOURCE.json | 67 + vendor/kurbo/benches/cubic.rs | 25 + vendor/kurbo/benches/cubic_arclen.rs | 36 + vendor/kurbo/benches/nearest.rs | 53 + vendor/kurbo/benches/quad_arclen.rs | 170 ++ vendor/kurbo/benches/quartic.rs | 26 + vendor/kurbo/benches/rect_expand.rs | 56 + vendor/kurbo/examples/arclen_accuracy.rs | 248 +++ vendor/kurbo/examples/circle.rs | 27 + vendor/kurbo/examples/cubic_arclen.rs | 256 +++ vendor/kurbo/examples/ellipse.rs | 28 + vendor/kurbo/examples/fit_poly.rs | 76 + vendor/kurbo/examples/quad_intersect.rs | 92 + vendor/kurbo/examples/simplify.rs | 52 + vendor/kurbo/examples/stroke.rs | 183 ++ vendor/kurbo/src/affine.rs | 865 ++++++++ vendor/kurbo/src/arc.rs | 341 ++++ vendor/kurbo/src/axis.rs | 72 + vendor/kurbo/src/bezpath.rs | 2311 ++++++++++++++++++++++ vendor/kurbo/src/circle.rs | 428 ++++ vendor/kurbo/src/common.rs | 1121 +++++++++++ vendor/kurbo/src/cubicbez.rs | 1257 ++++++++++++ vendor/kurbo/src/ellipse.rs | 554 ++++++ vendor/kurbo/src/expand.rs | 604 ++++++ vendor/kurbo/src/fit.rs | 719 +++++++ vendor/kurbo/src/insets.rs | 404 ++++ vendor/kurbo/src/interop_euclid.rs | 91 + vendor/kurbo/src/lib.rs | 189 ++ vendor/kurbo/src/line.rs | 448 +++++ vendor/kurbo/src/mindist.rs | 359 ++++ vendor/kurbo/src/moments.rs | 594 ++++++ vendor/kurbo/src/offset.rs | 668 +++++++ vendor/kurbo/src/param_curve.rs | 221 +++ vendor/kurbo/src/point.rs | 398 ++++ vendor/kurbo/src/quadbez.rs | 594 ++++++ vendor/kurbo/src/quadspline.rs | 130 ++ vendor/kurbo/src/rect.rs | 1053 ++++++++++ vendor/kurbo/src/rounded_rect.rs | 489 +++++ vendor/kurbo/src/rounded_rect_radii.rs | 124 ++ vendor/kurbo/src/shape.rs | 229 +++ vendor/kurbo/src/simplify.rs | 396 ++++ vendor/kurbo/src/size.rs | 492 +++++ vendor/kurbo/src/stroke.rs | 1181 +++++++++++ vendor/kurbo/src/svg.rs | 692 +++++++ vendor/kurbo/src/translate_scale.rs | 345 ++++ vendor/kurbo/src/triangle.rs | 373 ++++ vendor/kurbo/src/vec2.rs | 568 ++++++ 59 files changed, 21102 insertions(+), 4 deletions(-) create mode 100644 vendor/kurbo/.cargo_vcs_info.json create mode 100644 vendor/kurbo/Cargo.lock create mode 100644 vendor/kurbo/Cargo.toml create mode 100644 vendor/kurbo/Cargo.toml.orig create mode 100644 vendor/kurbo/LICENSE-APACHE create mode 100644 vendor/kurbo/LICENSE-MIT create mode 100644 vendor/kurbo/README.craft.md create mode 100644 vendor/kurbo/README.md create mode 100644 vendor/kurbo/SOURCE.json create mode 100644 vendor/kurbo/benches/cubic.rs create mode 100644 vendor/kurbo/benches/cubic_arclen.rs create mode 100644 vendor/kurbo/benches/nearest.rs create mode 100644 vendor/kurbo/benches/quad_arclen.rs create mode 100644 vendor/kurbo/benches/quartic.rs create mode 100644 vendor/kurbo/benches/rect_expand.rs create mode 100644 vendor/kurbo/examples/arclen_accuracy.rs create mode 100644 vendor/kurbo/examples/circle.rs create mode 100644 vendor/kurbo/examples/cubic_arclen.rs create mode 100644 vendor/kurbo/examples/ellipse.rs create mode 100644 vendor/kurbo/examples/fit_poly.rs create mode 100644 vendor/kurbo/examples/quad_intersect.rs create mode 100644 vendor/kurbo/examples/simplify.rs create mode 100644 vendor/kurbo/examples/stroke.rs create mode 100644 vendor/kurbo/src/affine.rs create mode 100644 vendor/kurbo/src/arc.rs create mode 100644 vendor/kurbo/src/axis.rs create mode 100644 vendor/kurbo/src/bezpath.rs create mode 100644 vendor/kurbo/src/circle.rs create mode 100644 vendor/kurbo/src/common.rs create mode 100644 vendor/kurbo/src/cubicbez.rs create mode 100644 vendor/kurbo/src/ellipse.rs create mode 100644 vendor/kurbo/src/expand.rs create mode 100644 vendor/kurbo/src/fit.rs create mode 100644 vendor/kurbo/src/insets.rs create mode 100644 vendor/kurbo/src/interop_euclid.rs create mode 100644 vendor/kurbo/src/lib.rs create mode 100644 vendor/kurbo/src/line.rs create mode 100644 vendor/kurbo/src/mindist.rs create mode 100644 vendor/kurbo/src/moments.rs create mode 100644 vendor/kurbo/src/offset.rs create mode 100644 vendor/kurbo/src/param_curve.rs create mode 100644 vendor/kurbo/src/point.rs create mode 100644 vendor/kurbo/src/quadbez.rs create mode 100644 vendor/kurbo/src/quadspline.rs create mode 100644 vendor/kurbo/src/rect.rs create mode 100644 vendor/kurbo/src/rounded_rect.rs create mode 100644 vendor/kurbo/src/rounded_rect_radii.rs create mode 100644 vendor/kurbo/src/shape.rs create mode 100644 vendor/kurbo/src/simplify.rs create mode 100644 vendor/kurbo/src/size.rs create mode 100644 vendor/kurbo/src/stroke.rs create mode 100644 vendor/kurbo/src/svg.rs create mode 100644 vendor/kurbo/src/translate_scale.rs create mode 100644 vendor/kurbo/src/triangle.rs create mode 100644 vendor/kurbo/src/vec2.rs diff --git a/Cargo.lock b/Cargo.lock index 1eb7e98ead..fd3889790a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -8346,8 +8346,6 @@ dependencies = [ [[package]] name = "kurbo" version = "0.13.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4b60dfc32f652b926df6192e55525b16d186c69d47876c3ead4da5cc9f8450e2" dependencies = [ "arrayvec", "euclid", diff --git a/Cargo.toml b/Cargo.toml index 3af86eaf40..31c89f8893 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,7 +1,7 @@ [workspace] resolver = "3" members = ["crates/*"] -exclude = ["vendor/krilla", "vendor/hayro", "vendor/hayro-interpret", "vendor/hayro-syntax", "vendor/hayro-jbig2", "vendor/hayro-cmap", "vendor/hayro-postscript", "vendor/linesweeper", "vendor/vello_common", "vendor/vello_cpu"] +exclude = ["vendor/krilla", "vendor/hayro", "vendor/hayro-interpret", "vendor/hayro-syntax", "vendor/hayro-jbig2", "vendor/hayro-cmap", "vendor/hayro-postscript", "vendor/linesweeper", "vendor/vello_common", "vendor/vello_cpu", "vendor/kurbo"] [workspace.package] version = "0.1.0" @@ -321,6 +321,7 @@ hayro-postscript = { path = "vendor/hayro-postscript" } linesweeper = { path = "vendor/linesweeper" } vello_common = { path = "vendor/vello_common" } vello_cpu = { path = "vendor/vello_cpu" } +kurbo = { path = "vendor/kurbo" } ecolor = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" } emath = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" } epaint = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" } diff --git a/NOTICE b/NOTICE index 4a2d1084e4..c71d5321e4 100644 --- a/NOTICE +++ b/NOTICE @@ -294,6 +294,13 @@ manifest names Joe Neeman as author, and its LICENSE-MIT reads "Copyright (c) 20 vendor/linesweeper/README.craft.md and vendor/linesweeper/SOURCE.json for provenance, the local patches and the files left out. +kurbo + +kurbo 0.13.1 (https://crates.io/crates/kurbo/0.13.1, https://github.com/linebender/kurbo), MIT OR +Apache-2.0, is stored in vendor/kurbo with its upstream license files. Its sources read "Copyright +2018 the Kurbo Authors", and its LICENSE-MIT reads "Copyright (c) 2018 Raph Levien". See +vendor/kurbo/README.craft.md and vendor/kurbo/SOURCE.json for provenance. + Platform lifecycle source provenance The optional crates/platform services adapt the preserved local platform candidate diff --git a/scripts/test-pdf-backends.sh b/scripts/test-pdf-backends.sh index 37566c3564..3b33bdcab2 100644 --- a/scripts/test-pdf-backends.sh +++ b/scripts/test-pdf-backends.sh @@ -7,7 +7,7 @@ test_root=$(mktemp -d "${TMPDIR:-/tmp}/craft-pdf-backends.XXXXXX") trap 'rm -rf "$test_root"' EXIT export CARGO_TARGET_DIR="${CARGO_TARGET_DIR:-$root/target}" patches=() -for backend in hayro hayro-interpret hayro-syntax hayro-jbig2 hayro-cmap hayro-postscript vello_common vello_cpu; do +for backend in hayro hayro-interpret hayro-syntax hayro-jbig2 hayro-cmap hayro-postscript vello_common vello_cpu kurbo; do cp -R "$root/vendor/$backend" "$test_root/$backend" patches+=(--config "patch.crates-io.$backend.path=\"$test_root/$backend\"") done @@ -21,3 +21,4 @@ cargo test --manifest-path "$test_root/hayro-syntax/Cargo.toml" --lib --no-defau cp -R "$root/vendor/linesweeper" "$test_root/linesweeper" cargo test --manifest-path "$test_root/linesweeper/Cargo.toml" --locked --lib --test regression cargo test --manifest-path "$test_root/linesweeper/Cargo.toml" --locked --doc +cargo test --manifest-path "$test_root/kurbo/Cargo.toml" --locked --all-features diff --git a/vendor/kurbo/.cargo_vcs_info.json b/vendor/kurbo/.cargo_vcs_info.json new file mode 100644 index 0000000000..62d1f1c7c9 --- /dev/null +++ b/vendor/kurbo/.cargo_vcs_info.json @@ -0,0 +1,6 @@ +{ + "git": { + "sha1": "838b69ef35f3381cefc007d86aa8364f5a6dc673" + }, + "path_in_vcs": "kurbo" +} \ No newline at end of file diff --git a/vendor/kurbo/Cargo.lock b/vendor/kurbo/Cargo.lock new file mode 100644 index 0000000000..1a7cd90d87 --- /dev/null +++ b/vendor/kurbo/Cargo.lock @@ -0,0 +1,705 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "aho-corasick" +version = "1.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ddd31a130427c27518df266943a5308ed92d4b226cc639f5a8f1002816174301" +dependencies = [ + "memchr", +] + +[[package]] +name = "anes" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4b46cbb362ab8752921c97e041f5e366ee6297bd428a31275b9fcf1e380f7299" + +[[package]] +name = "anstyle" +version = "1.0.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000" + +[[package]] +name = "arrayvec" +version = "0.7.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7c02d123df017efcdfbd739ef81735b36c5ba83ec3c59c80a9d7ecc718f92e50" + +[[package]] +name = "autocfg" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c08606f8c3cbf4ce6ec8e28fb0014a2c086708fe954eaa885384a6165172e7e8" + +[[package]] +name = "bumpalo" +version = "3.20.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d20789868f4b01b2f2caec9f5c4e0213b41e3e5702a50157d699ae31ced2fcb" + +[[package]] +name = "cast" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "37b2a672a2cb129a2e41c10b1224bb368f9f37a2b16b612598138befd7b37eb5" + +[[package]] +name = "cfg-if" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" + +[[package]] +name = "ciborium" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "42e69ffd6f0917f5c029256a24d0161db17cea3997d185db0d35926308770f0e" +dependencies = [ + "ciborium-io", + "ciborium-ll", + "serde", +] + +[[package]] +name = "ciborium-io" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "05afea1e0a06c9be33d539b876f1ce3692f4afea2cb41f740e7743225ed1c757" + +[[package]] +name = "ciborium-ll" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "57663b653d948a338bfb3eeba9bb2fd5fcfaecb9e199e87e1eda4d9e8b240fd9" +dependencies = [ + "ciborium-io", + "half", +] + +[[package]] +name = "clap" +version = "4.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ddb117e43bbf7dacf0a4190fef4d345b9bad68dfc649cb349e7d17d28428e51" +dependencies = [ + "clap_builder", +] + +[[package]] +name = "clap_builder" +version = "4.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "714a53001bf66416adb0e2ef5ac857140e7dc3a0c48fb28b2f10762fc4b5069f" +dependencies = [ + "anstyle", + "clap_lex", +] + +[[package]] +name = "clap_lex" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c8d4a3bb8b1e0c1050499d1815f5ab16d04f0959b233085fb31653fbfc9d98f9" + +[[package]] +name = "criterion" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e1c047a62b0cc3e145fa84415a3191f628e980b194c2755aa12300a4e6cbd928" +dependencies = [ + "anes", + "cast", + "ciborium", + "clap", + "criterion-plot", + "itertools", + "num-traits", + "oorandom", + "plotters", + "regex", + "serde", + "serde_json", + "tinytemplate", + "walkdir", +] + +[[package]] +name = "criterion-plot" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b1bcc0dc7dfae599d84ad0b1a55f80cde8af3725da8313b528da95ef783e338" +dependencies = [ + "cast", + "itertools", +] + +[[package]] +name = "crunchy" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5" + +[[package]] +name = "dyn-clone" +version = "1.0.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d0881ea181b1df73ff77ffaaf9c7544ecc11e82fba9b5f27b262a3c73a332555" + +[[package]] +name = "either" +version = "1.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "48c757948c5ede0e46177b7add2e67155f70e33c07fea8284df6576da70b3719" + +[[package]] +name = "euclid" +version = "0.22.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1a05365e3b1c6d1650318537c7460c6923f1abdd272ad6842baa2b509957a06" +dependencies = [ + "num-traits", +] + +[[package]] +name = "futures-core" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e3450815272ef58cec6d564423f6e755e25379b217b0bc688e295ba24df6b1d" + +[[package]] +name = "futures-task" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "037711b3d59c33004d3856fbdc83b99d4ff37a24768fa1be9ce3538a1cde4393" + +[[package]] +name = "futures-util" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "389ca41296e6190b48053de0321d02a77f32f8a5d2461dd38762c0593805c6d6" +dependencies = [ + "futures-core", + "futures-task", + "pin-project-lite", + "slab", +] + +[[package]] +name = "getrandom" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd" +dependencies = [ + "cfg-if", + "js-sys", + "libc", + "r-efi", + "wasip2", + "wasm-bindgen", +] + +[[package]] +name = "half" +version = "2.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ea2d84b969582b4b1864a92dc5d27cd2b77b622a8d79306834f1be5ba20d84b" +dependencies = [ + "cfg-if", + "crunchy", + "zerocopy", +] + +[[package]] +name = "itertools" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "413ee7dfc52ee1a4949ceeb7dbc8a33f2d6c088194d9f922fb8318faf1f01186" +dependencies = [ + "either", +] + +[[package]] +name = "itoa" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" + +[[package]] +name = "js-sys" +version = "0.3.98" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67df7112613f8bfd9150013a0314e196f4800d3201ae742489d999db2f979f08" +dependencies = [ + "cfg-if", + "futures-util", + "once_cell", + "wasm-bindgen", +] + +[[package]] +name = "kurbo" +version = "0.13.1" +dependencies = [ + "arrayvec", + "criterion", + "euclid", + "getrandom", + "libm", + "mint", + "polycool", + "rand", + "schemars", + "serde", + "smallvec", +] + +[[package]] +name = "libc" +version = "0.2.186" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "68ab91017fe16c622486840e4c83c9a37afeff978bd239b5293d61ece587de66" + +[[package]] +name = "libm" +version = "0.2.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981" + +[[package]] +name = "memchr" +version = "2.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8ca58f447f06ed17d5fc4043ce1b10dd205e060fb3ce5b979b8ed8e59ff3f79" + +[[package]] +name = "mint" +version = "0.5.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e53debba6bda7a793e5f99b8dacf19e626084f525f7829104ba9898f367d85ff" + +[[package]] +name = "num-traits" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" +dependencies = [ + "autocfg", + "libm", +] + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "oorandom" +version = "11.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6790f58c7ff633d8771f42965289203411a5e5c68388703c06e14f24770b41e" + +[[package]] +name = "pin-project-lite" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" + +[[package]] +name = "plotters" +version = "0.3.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5aeb6f403d7a4911efb1e33402027fc44f29b5bf6def3effcc22d7bb75f2b747" +dependencies = [ + "num-traits", + "plotters-backend", + "plotters-svg", + "wasm-bindgen", + "web-sys", +] + +[[package]] +name = "plotters-backend" +version = "0.3.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df42e13c12958a16b3f7f4386b9ab1f3e7933914ecea48da7139435263a4172a" + +[[package]] +name = "plotters-svg" +version = "0.3.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "51bae2ac328883f7acdfea3d66a7c35751187f870bc81f94563733a154d7a670" +dependencies = [ + "plotters-backend", +] + +[[package]] +name = "polycool" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "50596ddc09eb5ad5f75cacd40209568e66df71baf86e1499a0e99c4cff12a5a6" +dependencies = [ + "arrayvec", + "libm", +] + +[[package]] +name = "ppv-lite86" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9" +dependencies = [ + "zerocopy", +] + +[[package]] +name = "proc-macro2" +version = "1.0.106" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.45" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41f2619966050689382d2b44f664f4bc593e129785a36d6ee376ddf37259b924" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "r-efi" +version = "5.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f" + +[[package]] +name = "rand" +version = "0.9.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "44c5af06bb1b7d3216d91932aed5265164bf384dc89cd6ba05cf59a35f5f76ea" +dependencies = [ + "rand_chacha", + "rand_core", +] + +[[package]] +name = "rand_chacha" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb" +dependencies = [ + "ppv-lite86", + "rand_core", +] + +[[package]] +name = "rand_core" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c" +dependencies = [ + "getrandom", +] + +[[package]] +name = "regex" +version = "1.12.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e10754a14b9137dd7b1e3e5b0493cc9171fdd105e0ab477f51b72e7f3ac0e276" +dependencies = [ + "aho-corasick", + "memchr", + "regex-automata", + "regex-syntax", +] + +[[package]] +name = "regex-automata" +version = "0.4.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e1dd4122fc1595e8162618945476892eefca7b88c52820e74af6262213cae8f" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", +] + +[[package]] +name = "regex-syntax" +version = "0.8.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc897dd8d9e8bd1ed8cdad82b5966c3e0ecae09fb1907d58efaa013543185d0a" + +[[package]] +name = "rustversion" +version = "1.0.22" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b39cdef0fa800fc44525c84ccb54a029961a8215f9619753635a9c0d2538d46d" + +[[package]] +name = "same-file" +version = "1.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502" +dependencies = [ + "winapi-util", +] + +[[package]] +name = "schemars" +version = "0.8.22" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3fbf2ae1b8bc8e02df939598064d22402220cd5bbcca1c76f7d6a310974d5615" +dependencies = [ + "dyn-clone", + "schemars_derive", + "serde", + "serde_json", + "smallvec", +] + +[[package]] +name = "schemars_derive" +version = "0.8.22" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32e265784ad618884abaea0600a9adf15393368d840e0222d101a072f3f7534d" +dependencies = [ + "proc-macro2", + "quote", + "serde_derive_internals", + "syn", +] + +[[package]] +name = "serde" +version = "1.0.228" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a8e94ea7f378bd32cbbd37198a4a91436180c5bb472411e48b5ec2e2124ae9e" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.228" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41d385c7d4ca58e59fc732af25c3983b67ac852c1a25000afe1175de458b67ad" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.228" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "serde_derive_internals" +version = "0.29.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "18d26a20a969b9e3fdf2fc2d9f21eda6c40e2de84c9408bb5d3b05d499aae711" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "serde_json" +version = "1.0.149" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "83fc039473c5595ace860d8c4fafa220ff474b3fc6bfdb4293327f1a37e94d86" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "slab" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" + +[[package]] +name = "smallvec" +version = "1.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67b1b7a3b5fe4f1376887184045fcf45c69e92af734b7aaddc05fb777b6fbd03" +dependencies = [ + "serde", +] + +[[package]] +name = "syn" +version = "2.0.117" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e665b8803e7b1d2a727f4023456bbbbe74da67099c585258af0ad9c5013b9b99" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "tinytemplate" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "be4d6b5f19ff7664e8c98d03e2139cb510db9b0a60b55f8e8709b689d939b6bc" +dependencies = [ + "serde", + "serde_json", +] + +[[package]] +name = "unicode-ident" +version = "1.0.24" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75" + +[[package]] +name = "walkdir" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29790946404f91d9c5d06f9874efddea1dc06c5efe94541a7d6863108e3a5e4b" +dependencies = [ + "same-file", + "winapi-util", +] + +[[package]] +name = "wasip2" +version = "1.0.3+wasi-0.2.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20064672db26d7cdc89c7798c48a0fdfac8213434a1186e5ef29fd560ae223d6" +dependencies = [ + "wit-bindgen", +] + +[[package]] +name = "wasm-bindgen" +version = "0.2.121" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "49ace1d07c165b0864824eee619580c4689389afa9dc9ed3a4c75040d82e6790" +dependencies = [ + "cfg-if", + "once_cell", + "rustversion", + "wasm-bindgen-macro", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.121" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e68e6f4afd367a562002c05637acb8578ff2dea1943df76afb9e83d177c8578" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.121" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d95a9ec35c64b2a7cb35d3fead40c4238d0940c86d107136999567a4703259f2" +dependencies = [ + "bumpalo", + "proc-macro2", + "quote", + "syn", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.121" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c4e0100b01e9f0d03189a92b96772a1fb998639d981193d7dbab487302513441" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "web-sys" +version = "0.3.98" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4b572dff8bcf38bad0fa19729c89bb5748b2b9b1d8be70cf90df697e3a8f32aa" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "winapi-util" +version = "0.1.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" +dependencies = [ + "windows-sys", +] + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + +[[package]] +name = "wit-bindgen" +version = "0.57.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e" + +[[package]] +name = "zerocopy" +version = "0.8.48" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eed437bf9d6692032087e337407a86f04cd8d6a16a37199ed57949d415bd68e9" +dependencies = [ + "zerocopy-derive", +] + +[[package]] +name = "zerocopy-derive" +version = "0.8.48" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "70e3cd084b1788766f53af483dd21f93881ff30d7320490ec3ef7526d203bad4" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "zmij" +version = "1.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8848ee67ecc8aedbaf3e4122217aff892639231befc6a1b58d29fff4c2cabaa" diff --git a/vendor/kurbo/Cargo.toml b/vendor/kurbo/Cargo.toml new file mode 100644 index 0000000000..470c3d394d --- /dev/null +++ b/vendor/kurbo/Cargo.toml @@ -0,0 +1,230 @@ +# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO +# +# When uploading crates to the registry Cargo will automatically +# "normalize" Cargo.toml files for maximal compatibility +# with all versions of Cargo and also rewrite `path` dependencies +# to registry (e.g., crates.io) dependencies. +# +# If you are reading this file be aware that the original Cargo.toml +# will likely look very different (and much more reasonable). +# See Cargo.toml.orig for the original contents. + +[package] +edition = "2024" +rust-version = "1.85" +name = "kurbo" +version = "0.13.1" +build = false +autolib = false +autobins = false +autoexamples = false +autotests = false +autobenches = false +description = "A 2D curves library" +readme = "README.md" +keywords = [ + "graphics", + "curve", + "curves", + "bezier", + "geometry", +] +categories = ["graphics"] +license = "Apache-2.0 OR MIT" +repository = "https://github.com/linebender/kurbo" +resolver = "2" + +[package.metadata.docs.rs] +all-features = true +default-target = "x86_64-unknown-linux-gnu" +targets = [] + +[features] +default = ["std"] +euclid = ["dep:euclid"] +libm = [ + "dep:libm", + "polycool/libm", + "euclid?/libm", +] +mint = ["dep:mint"] +schemars = [ + "schemars/smallvec", + "dep:schemars", +] +serde = [ + "smallvec/serde", + "dep:serde", +] +std = [ + "polycool/std", + "euclid?/std", +] + +[lib] +name = "kurbo" +path = "src/lib.rs" + +[[example]] +name = "arclen_accuracy" +path = "examples/arclen_accuracy.rs" + +[[example]] +name = "circle" +path = "examples/circle.rs" + +[[example]] +name = "cubic_arclen" +path = "examples/cubic_arclen.rs" + +[[example]] +name = "ellipse" +path = "examples/ellipse.rs" + +[[example]] +name = "fit_poly" +path = "examples/fit_poly.rs" + +[[example]] +name = "quad_intersect" +path = "examples/quad_intersect.rs" + +[[example]] +name = "simplify" +path = "examples/simplify.rs" + +[[example]] +name = "stroke" +path = "examples/stroke.rs" + +[[bench]] +name = "cubic" +path = "benches/cubic.rs" +harness = false + +[[bench]] +name = "cubic_arclen" +path = "benches/cubic_arclen.rs" +harness = false + +[[bench]] +name = "nearest" +path = "benches/nearest.rs" +harness = false + +[[bench]] +name = "quad_arclen" +path = "benches/quad_arclen.rs" +harness = false + +[[bench]] +name = "quartic" +path = "benches/quartic.rs" +harness = false + +[[bench]] +name = "rect_expand" +path = "benches/rect_expand.rs" +harness = false + +[dependencies.arrayvec] +version = "0.7.6" +default-features = false + +[dependencies.euclid] +version = "0.22" +optional = true +default-features = false + +[dependencies.libm] +version = "0.2.16" +optional = true + +[dependencies.mint] +version = "0.5.9" +optional = true + +[dependencies.polycool] +version = "0.4.0" +default-features = false + +[dependencies.schemars] +version = "0.8.22" +optional = true + +[dependencies.serde] +version = "1.0.228" +features = [ + "alloc", + "derive", +] +optional = true +default-features = false + +[dependencies.smallvec] +version = "1.15.1" +features = ["const_new"] + +[dev-dependencies.criterion] +version = "0.7.0" +features = [ + "plotters", + "cargo_bench_support", +] +default-features = false + +[dev-dependencies.rand] +version = "0.9.4" + +[target.wasm32-unknown-unknown.dev-dependencies.getrandom] +version = "0.3.4" +features = ["wasm_js"] + +[lints.clippy] +allow_attributes_without_reason = "warn" +cargo_common_metadata = "warn" +cast_possible_truncation = "warn" +cast_possible_wrap = "warn" +collection_is_never_read = "warn" +dbg_macro = "warn" +debug_assert_with_mut_call = "warn" +default_trait_access = "warn" +doc_markdown = "warn" +fn_to_numeric_cast_any = "warn" +infinite_loop = "warn" +large_stack_arrays = "warn" +mismatching_type_param_order = "warn" +missing_assert_message = "warn" +missing_fields_in_debug = "warn" +negative_feature_names = "warn" +redundant_feature_names = "warn" +same_functions_in_if_condition = "warn" +semicolon_if_nothing_returned = "warn" +should_panic_without_expect = "warn" +todo = "warn" +too_many_arguments = "allow" +unseparated_literal_suffix = "warn" +use_self = "warn" +wildcard_dependencies = "warn" + +[lints.rust] +elided_lifetimes_in_paths = "warn" +keyword_idents_2024 = "forbid" +missing_debug_implementations = "warn" +missing_docs = "warn" +non_ascii_idents = "forbid" +non_local_definitions = "forbid" +trivial_numeric_casts = "warn" +unnameable_types = "warn" +unreachable_pub = "warn" +unsafe_code = "forbid" +unsafe_op_in_unsafe_fn = "forbid" +unused_import_braces = "warn" +unused_lifetimes = "warn" +unused_macro_rules = "warn" +unused_qualifications = "warn" + +[lints.rust.unexpected_cfgs] +level = "warn" +priority = 0 +check-cfg = ["cfg(nightly)"] diff --git a/vendor/kurbo/Cargo.toml.orig b/vendor/kurbo/Cargo.toml.orig new file mode 100644 index 0000000000..f82a576fda --- /dev/null +++ b/vendor/kurbo/Cargo.toml.orig @@ -0,0 +1,81 @@ +[package] +name = "kurbo" +version.workspace = true +license.workspace = true +edition.workspace = true +description = "A 2D curves library" +keywords = ["graphics", "curve", "curves", "bezier", "geometry"] +categories = ["graphics"] +repository.workspace = true +rust-version.workspace = true + +[package.metadata.docs.rs] +all-features = true +# There are no platform specific docs. +default-target = "x86_64-unknown-linux-gnu" +targets = [] + +[features] +default = ["std"] +# Get floating point functions from the standard library (likely using your target's libc) +std = ["polycool/std", "euclid?/std"] +# Use floating point implementations from libm +libm = ["dep:libm", "polycool/libm", "euclid?/libm"] +# Enable `From`/`Into` conversion of Kurbo and [mint] types, enabling interoperability +# with other graphics libraries +mint = ["dep:mint"] +# Enable `From`/`Into` conversion of Kurbo and euclid types +euclid = ["dep:euclid"] +# Implement `serde::Deserialize` and `serde::Serialize` on various types +serde = ["smallvec/serde", "dep:serde"] +# Add best-effort support for using Kurbo types in JSON schemas using schemars +schemars = ["schemars/smallvec", "dep:schemars"] + +[dependencies] +arrayvec = { workspace = true } +euclid = { workspace = true, optional = true } +libm = { workspace = true, optional = true } +mint = { workspace = true, optional = true } +polycool = { workspace = true } +schemars = { workspace = true, optional = true } +serde = { workspace = true, optional = true, features = ["alloc", "derive"] } +smallvec = { workspace = true, features = ["const_new"] } + +[dev-dependencies] +# This is used for research but not really needed; maybe refactor. +rand = { workspace = true } +# wasm doesn't support rayon, so disable criterion's rayon support. (In +# principle we could make it target-dependent.) +criterion = { workspace = true, features = ["plotters", "cargo_bench_support"] } + +[target.wasm32-unknown-unknown.dev-dependencies] +# We have a transitive dependency on getrandom and it does not automatically +# support wasm32-unknown-unknown. We need to enable the wasm_js feature. +getrandom = { version = "0.3.4", features = ["wasm_js"] } + +[lints] +workspace = true + +[[bench]] +name = "cubic" +harness = false + +[[bench]] +name = "cubic_arclen" +harness = false + +[[bench]] +name = "quad_arclen" +harness = false + +[[bench]] +name = "quartic" +harness = false + +[[bench]] +name = "nearest" +harness = false + +[[bench]] +name = "rect_expand" +harness = false diff --git a/vendor/kurbo/LICENSE-APACHE b/vendor/kurbo/LICENSE-APACHE new file mode 100644 index 0000000000..d645695673 --- /dev/null +++ b/vendor/kurbo/LICENSE-APACHE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/vendor/kurbo/LICENSE-MIT b/vendor/kurbo/LICENSE-MIT new file mode 100644 index 0000000000..f3d84348c6 --- /dev/null +++ b/vendor/kurbo/LICENSE-MIT @@ -0,0 +1,25 @@ +Copyright (c) 2018 Raph Levien + +Permission is hereby granted, free of charge, to any +person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the +Software without restriction, including without +limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software +is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice +shall be included in all copies or substantial portions +of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. diff --git a/vendor/kurbo/README.craft.md b/vendor/kurbo/README.craft.md new file mode 100644 index 0000000000..431f05d267 --- /dev/null +++ b/vendor/kurbo/README.craft.md @@ -0,0 +1,43 @@ +# Local kurbo 0.13.1 copy + +This is the crates.io kurbo 0.13.1 package (MIT OR Apache-2.0) with no file changed. +`.cargo_vcs_info.json` names the commit it was packaged from, +`838b69ef35f3381cefc007d86aa8364f5a6dc673`, the `v0.13.1` tag of +[linebender/kurbo](https://github.com/linebender/kurbo/tree/838b69ef35f3381cefc007d86aa8364f5a6dc673/kurbo). + +Every file here except this one and `SOURCE.json` is byte for byte the file in the `.crate` archive. +`SOURCE.json` records the hash of the `.crate` download (`source_archive_sha256`) and, for every file +kept, the hash in the package (`source_sha256`) and the hash here (`sha256`). `local_patches` is +empty, and no file of the package is left out. + +## Using it + +The directory is excluded from the workspace. With the root manifest's `[patch.crates-io]` entry, +every crate here that depends on kurbo 0.13 builds against this copy. Cargo ignores a dependency's +patches, so a consuming workspace adds its own entry: + +```toml +[patch.crates-io] +kurbo = { git = "https://github.com/storytold/craft-libs", rev = "" } +``` + +The entry applies to kurbo 0.13 only. A dependency on another kurbo version, such as 0.11, still +resolves to crates.io. + +## Tests + +`scripts/test-pdf-backends.sh` runs the package's unit and doc tests with every feature, and its +other backend tests build against this copy. The workspace's own tests also build against it through +the patch entry. No workflow runs clippy on this copy. Run the tests and the builds without `std` and +for Wasm from this directory: + +```sh +cargo test --locked --all-features +cargo check --locked --no-default-features --features libm +cargo test --locked --all-features --target wasm32-unknown-unknown --no-run +``` + +The package's tests need the `std` feature. Clippy 1.100.0 with `-D warnings` stops at one lint in the +package as published, `needless_late_init` in `src/common.rs`; the copy keeps that code unchanged. + +Cargo writes to `target/` in this directory, which the root `.gitignore` excludes. diff --git a/vendor/kurbo/README.md b/vendor/kurbo/README.md new file mode 100644 index 0000000000..40035b1419 --- /dev/null +++ b/vendor/kurbo/README.md @@ -0,0 +1,94 @@ +
+ +# Kurbo + +**A Rust 2D curves library** + +[![Linebender Zulip, #kurbo channel](https://img.shields.io/badge/Linebender-%23kurbo-blue?logo=Zulip)](https://xi.zulipchat.com/#narrow/channel/260979-kurbo) +[![dependency status](https://deps.rs/repo/github/linebender/kurbo/status.svg)](https://deps.rs/repo/github/linebender/kurbo) +[![Apache 2.0 or MIT license.](https://img.shields.io/badge/license-Apache--2.0_OR_MIT-blue.svg)](#license) +[![Build status](https://github.com/linebender/kurbo/workflows/CI/badge.svg)](https://github.com/linebender/kurbo/actions) +[![Crates.io](https://img.shields.io/crates/v/kurbo.svg)](https://crates.io/crates/kurbo) +[![Docs](https://docs.rs/kurbo/badge.svg)](https://docs.rs/kurbo) + +
+ +The Kurbo library contains data structures and algorithms for curves and vector paths. +It is probably most appropriate for creative tools, but is general enough it might be useful for other applications. + +The name "kurbo" is Esperanto for "curve". + +There is a focus on accuracy and good performance in high-accuracy conditions. +Thus, the library might be useful in engineering and science contexts as well, as opposed to visual arts where rough approximations are often sufficient. +Many approximate functions come with an accuracy parameter, and analytical solutions are used where they are practical. +An example is area calculation, which is done using Green's theorem. + +The library is still in fairly early development stages. +There are traits intended to be useful for general curves (not just Béziers), but these will probably be reorganized. + +## Minimum supported Rust Version (MSRV) + +This version of Kurbo has been verified to compile with **Rust 1.85** and later. + +Future versions of Kurbo might increase the Rust version requirement. +It will not be treated as a breaking change and as such can even happen with small patch releases. + +
+Click here if compiling fails. + +As time has passed, some of Kurbo's dependencies could have released versions with a higher Rust requirement. +If you encounter a compilation issue due to a dependency and don't want to upgrade your Rust toolchain, then you could downgrade the dependency. + +```sh +# Use the problematic dependency's name and version +cargo update -p package_name --precise 0.1.1 +``` + +
+ +## Similar crates + +Here we mention a few other curves libraries and touch on some of the decisions made differently here. + +* [lyon_geom] has a lot of very good vector algorithms. It's most focused on rendering. + +* [flo_curves] has good Bézier primitives, and seems tuned for animation. It's generic on the coordinate type, while we use `f64` for everything. + +* [vek] has both 2D and 3D Béziers among other things, and is tuned for game engines. + +Some code has been copied from lyon_geom with adaptation, thus the author of lyon_geom, Nicolas Silva, is credited in the [AUTHORS] file. + +## More info + +To learn more about Bézier curves, [A Primer on Bézier Curves] by Pomax is indispensable. + +## Community + +[![Linebender Zulip](https://img.shields.io/badge/Linebender-%23kurbo-blue?logo=Zulip)](https://xi.zulipchat.com/#narrow/channel/260979-kurbo) + +Discussion of Kurbo development happens in the [Linebender Zulip](https://xi.zulipchat.com/), specifically the [#kurbo channel](https://xi.zulipchat.com/#narrow/channel/260979-kurbo). +All public content can be read without logging in. + +## License + +Licensed under either of + +- Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or ) +- MIT license ([LICENSE-MIT](LICENSE-MIT) or ) + +at your option. + +## Contribution + +Contributions are welcome by pull request. The [Rust code of conduct] applies. +Please feel free to add your name to the [AUTHORS] file in any substantive pull request. + +Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be licensed as above, without any additional terms or conditions. + +[Rust Code of Conduct]: https://www.rust-lang.org/policies/code-of-conduct +[lyon_geom]: https://crates.io/crates/lyon_geom +[flo_curves]: https://crates.io/crates/flo_curves +[vek]: https://crates.io/crates/vek +[A Primer on Bézier Curves]: https://pomax.github.io/bezierinfo/ +[AUTHORS]: ./AUTHORS +[CHANGELOG.md]: ./CHANGELOG.md diff --git a/vendor/kurbo/SOURCE.json b/vendor/kurbo/SOURCE.json new file mode 100644 index 0000000000..8d8dde697f --- /dev/null +++ b/vendor/kurbo/SOURCE.json @@ -0,0 +1,67 @@ +{ + "crate": "kurbo", + "source_repository": "https://crates.io/api/v1/crates/kurbo/0.13.1/download", + "source_revision": "0.13.1", + "source_directory": "kurbo-0.13.1", + "source_archive_sha256": "4b60dfc32f652b926df6192e55525b16d186c69d47876c3ead4da5cc9f8450e2", + "upstream_repository": "https://github.com/linebender/kurbo", + "upstream_revision": "838b69ef35f3381cefc007d86aa8364f5a6dc673", + "upstream_directory": "kurbo", + "local_patches": [], + "files": [ + { "path": ".cargo_vcs_info.json", "source_sha256": "4bfe3d4ab606efdb8e558db546ae666decc53fa3caa34865b4f66ffa67449a66", "source_git_blob": null, "sha256": "4bfe3d4ab606efdb8e558db546ae666decc53fa3caa34865b4f66ffa67449a66" }, + { "path": "Cargo.lock", "source_sha256": "1f13e8fcd58e548bb2130320c3ed5addb20ff658722d3f20b697c2a6a0b27e90", "source_git_blob": null, "sha256": "1f13e8fcd58e548bb2130320c3ed5addb20ff658722d3f20b697c2a6a0b27e90" }, + { "path": "Cargo.toml", "source_sha256": "3c5b41c42b588b750fbca3109b48438288586c2b22fdda571ea0fc188b6e08b0", "source_git_blob": null, "sha256": "3c5b41c42b588b750fbca3109b48438288586c2b22fdda571ea0fc188b6e08b0" }, + { "path": "Cargo.toml.orig", "source_sha256": "20e9fc1c17fd24b20c7eba09b657f999cc503999b18051dcdf7770e581fab175", "source_git_blob": null, "sha256": "20e9fc1c17fd24b20c7eba09b657f999cc503999b18051dcdf7770e581fab175" }, + { "path": "LICENSE-APACHE", "source_sha256": "cfc7749b96f63bd31c3c42b5c471bf756814053e847c10f3eb003417bc523d30", "source_git_blob": null, "sha256": "cfc7749b96f63bd31c3c42b5c471bf756814053e847c10f3eb003417bc523d30" }, + { "path": "LICENSE-MIT", "source_sha256": "23c23145f6eac25c28cdcc03d38506a5712a9a8cffb5bd5301457f6173ea696e", "source_git_blob": null, "sha256": "23c23145f6eac25c28cdcc03d38506a5712a9a8cffb5bd5301457f6173ea696e" }, + { "path": "README.md", "source_sha256": "d731f0edd82b188d9156cfbd909a1fdce6dd7424299b5d9ab540135d20693aab", "source_git_blob": null, "sha256": "d731f0edd82b188d9156cfbd909a1fdce6dd7424299b5d9ab540135d20693aab" }, + { "path": "benches/cubic.rs", "source_sha256": "753d2822c69a8684032a3b4a5f40e3b03ea4b4553cd8aba39fe6afd159711ab9", "source_git_blob": null, "sha256": "753d2822c69a8684032a3b4a5f40e3b03ea4b4553cd8aba39fe6afd159711ab9" }, + { "path": "benches/cubic_arclen.rs", "source_sha256": "93ad92e94f421ef9b7ee60ed3b59909a59554ade76a18279ccacf8bfcd715477", "source_git_blob": null, "sha256": "93ad92e94f421ef9b7ee60ed3b59909a59554ade76a18279ccacf8bfcd715477" }, + { "path": "benches/nearest.rs", "source_sha256": "8cbf5ead45bce5ea79d1234f72fae704042162a934228b3af9611cf0932ef5fd", "source_git_blob": null, "sha256": "8cbf5ead45bce5ea79d1234f72fae704042162a934228b3af9611cf0932ef5fd" }, + { "path": "benches/quad_arclen.rs", "source_sha256": "f447a066c32703cbbba14bed66f419841cca1cb83e01ca7511e6f09a5d115e20", "source_git_blob": null, "sha256": "f447a066c32703cbbba14bed66f419841cca1cb83e01ca7511e6f09a5d115e20" }, + { "path": "benches/quartic.rs", "source_sha256": "3535c44734c559992b3f62077e5d933300777e248251b883b1451457280df1f3", "source_git_blob": null, "sha256": "3535c44734c559992b3f62077e5d933300777e248251b883b1451457280df1f3" }, + { "path": "benches/rect_expand.rs", "source_sha256": "496b987a239680b61b2d65b0ab91cbfab55c807cc1831476bcb08129c092f8de", "source_git_blob": null, "sha256": "496b987a239680b61b2d65b0ab91cbfab55c807cc1831476bcb08129c092f8de" }, + { "path": "examples/arclen_accuracy.rs", "source_sha256": "7bf354d4d34b42e915e082774d74177209b2997b09ee6972a38cb32dfaf385b2", "source_git_blob": null, "sha256": "7bf354d4d34b42e915e082774d74177209b2997b09ee6972a38cb32dfaf385b2" }, + { "path": "examples/circle.rs", "source_sha256": "1416fe74c7a82b15b1d2ee4166d09a75cf8cc9ac6744dddc7df338881258ded3", "source_git_blob": null, "sha256": "1416fe74c7a82b15b1d2ee4166d09a75cf8cc9ac6744dddc7df338881258ded3" }, + { "path": "examples/cubic_arclen.rs", "source_sha256": "467bcf52b26e3480ad05dddbd06374ce219df54b7dc1fa7fb96367eed41e1d5b", "source_git_blob": null, "sha256": "467bcf52b26e3480ad05dddbd06374ce219df54b7dc1fa7fb96367eed41e1d5b" }, + { "path": "examples/ellipse.rs", "source_sha256": "22db083067328d2d4f80a2be1ba1cf7e5478950ecde99142563a4cd9fa6dfaca", "source_git_blob": null, "sha256": "22db083067328d2d4f80a2be1ba1cf7e5478950ecde99142563a4cd9fa6dfaca" }, + { "path": "examples/fit_poly.rs", "source_sha256": "ed1d8adaf2e0adcee445cfd4fd06a110f064455ef382354ec2a99d3450442654", "source_git_blob": null, "sha256": "ed1d8adaf2e0adcee445cfd4fd06a110f064455ef382354ec2a99d3450442654" }, + { "path": "examples/quad_intersect.rs", "source_sha256": "56becf3a522316e1c54eaae7d2d75365fa275bbfc17bb2bf6884d63bf887d88a", "source_git_blob": null, "sha256": "56becf3a522316e1c54eaae7d2d75365fa275bbfc17bb2bf6884d63bf887d88a" }, + { "path": "examples/simplify.rs", "source_sha256": "7bd3fdcfd60fe9094b9f5da51be4a70061f3df760a62a0ae62e7e8c77f649558", "source_git_blob": null, "sha256": "7bd3fdcfd60fe9094b9f5da51be4a70061f3df760a62a0ae62e7e8c77f649558" }, + { "path": "examples/stroke.rs", "source_sha256": "f055edc18fc05c55c2a3f9ad2e3caa6b997e2d9cd7c5781959d752182afe1b90", "source_git_blob": null, "sha256": "f055edc18fc05c55c2a3f9ad2e3caa6b997e2d9cd7c5781959d752182afe1b90" }, + { "path": "src/affine.rs", "source_sha256": "7288c89bb5ce16acd7d1b046f189df5855cfafa0454d667fc7b0dc4454fa2663", "source_git_blob": null, "sha256": "7288c89bb5ce16acd7d1b046f189df5855cfafa0454d667fc7b0dc4454fa2663" }, + { "path": "src/arc.rs", "source_sha256": "f1479f3e54c7e4717424920f128ebfda59ea2984c08b43291411072072eb1475", "source_git_blob": null, "sha256": "f1479f3e54c7e4717424920f128ebfda59ea2984c08b43291411072072eb1475" }, + { "path": "src/axis.rs", "source_sha256": "6ccf1f4cca904fa43f54d9d71a6511927fdab171a8d00382ab311cd2776ef781", "source_git_blob": null, "sha256": "6ccf1f4cca904fa43f54d9d71a6511927fdab171a8d00382ab311cd2776ef781" }, + { "path": "src/bezpath.rs", "source_sha256": "6d9d5769715dfc4c10f90c1de500fca7a2ca35c0d673d2e05d7ddd615a987be4", "source_git_blob": null, "sha256": "6d9d5769715dfc4c10f90c1de500fca7a2ca35c0d673d2e05d7ddd615a987be4" }, + { "path": "src/circle.rs", "source_sha256": "434d23a89e13ad22be300c383cdf027e41a9ccfbd8a3f9152c1e97a5ad330491", "source_git_blob": null, "sha256": "434d23a89e13ad22be300c383cdf027e41a9ccfbd8a3f9152c1e97a5ad330491" }, + { "path": "src/common.rs", "source_sha256": "5d32994b9832dc34738a0d34464d9b2435398404bfd576c838584c301359d062", "source_git_blob": null, "sha256": "5d32994b9832dc34738a0d34464d9b2435398404bfd576c838584c301359d062" }, + { "path": "src/cubicbez.rs", "source_sha256": "de793f84444c55467a4669de64b4a06209f97540362c2da1fe0ad2b2367f5b80", "source_git_blob": null, "sha256": "de793f84444c55467a4669de64b4a06209f97540362c2da1fe0ad2b2367f5b80" }, + { "path": "src/ellipse.rs", "source_sha256": "991e9830a32643d2aa5c34c57330323e65f3b15231c80b086eb715b0665fc41d", "source_git_blob": null, "sha256": "991e9830a32643d2aa5c34c57330323e65f3b15231c80b086eb715b0665fc41d" }, + { "path": "src/expand.rs", "source_sha256": "f0ef21c91790097498bfacd2cc624f6ac86b32bc2600aa78c57583e46c5d0ae6", "source_git_blob": null, "sha256": "f0ef21c91790097498bfacd2cc624f6ac86b32bc2600aa78c57583e46c5d0ae6" }, + { "path": "src/fit.rs", "source_sha256": "3d7dace4a4452ce6a5eff3186a48f8dc0d0d625029feae78c24017fb5b68695b", "source_git_blob": null, "sha256": "3d7dace4a4452ce6a5eff3186a48f8dc0d0d625029feae78c24017fb5b68695b" }, + { "path": "src/insets.rs", "source_sha256": "cf6019c2ab0783ede641ef61677b60d4c2cf4f721317024a0944e8c66373dc98", "source_git_blob": null, "sha256": "cf6019c2ab0783ede641ef61677b60d4c2cf4f721317024a0944e8c66373dc98" }, + { "path": "src/interop_euclid.rs", "source_sha256": "bc94da5023b455df685b74cd942d569e1ee5025191c64ff4217f068d845b9418", "source_git_blob": null, "sha256": "bc94da5023b455df685b74cd942d569e1ee5025191c64ff4217f068d845b9418" }, + { "path": "src/lib.rs", "source_sha256": "f513dc1a758bc061cc2a177fa98a1d566003d6c83e36d3befbc9bbea2e4349e7", "source_git_blob": null, "sha256": "f513dc1a758bc061cc2a177fa98a1d566003d6c83e36d3befbc9bbea2e4349e7" }, + { "path": "src/line.rs", "source_sha256": "66fba2df6d9653aa03adfda457a5059a7cbdd1ae29fa2c2db4ba5aefb1d4db28", "source_git_blob": null, "sha256": "66fba2df6d9653aa03adfda457a5059a7cbdd1ae29fa2c2db4ba5aefb1d4db28" }, + { "path": "src/mindist.rs", "source_sha256": "3f6e98e5cc25395e042bcd3138abd237176034cbddb13d48a11b66f581d724e4", "source_git_blob": null, "sha256": "3f6e98e5cc25395e042bcd3138abd237176034cbddb13d48a11b66f581d724e4" }, + { "path": "src/moments.rs", "source_sha256": "decf10b9116aacab2bab47c8b331a6a5e3ba16b3c63527710289cedc5df930a0", "source_git_blob": null, "sha256": "decf10b9116aacab2bab47c8b331a6a5e3ba16b3c63527710289cedc5df930a0" }, + { "path": "src/offset.rs", "source_sha256": "8999fdb31334a6c08c260f2ae360aba3b091652e26454b735ea985c99a545cd9", "source_git_blob": null, "sha256": "8999fdb31334a6c08c260f2ae360aba3b091652e26454b735ea985c99a545cd9" }, + { "path": "src/param_curve.rs", "source_sha256": "5cac1495643a9cb5f4af7ea618265a9deb87e7f82ee9628fdb46c49fd970a553", "source_git_blob": null, "sha256": "5cac1495643a9cb5f4af7ea618265a9deb87e7f82ee9628fdb46c49fd970a553" }, + { "path": "src/point.rs", "source_sha256": "4311047b9497b4fbd38022eb62ebaa9771c05e55e1bafb9431f2243949515ca7", "source_git_blob": null, "sha256": "4311047b9497b4fbd38022eb62ebaa9771c05e55e1bafb9431f2243949515ca7" }, + { "path": "src/quadbez.rs", "source_sha256": "37ab1037750d32eed6b3664b250a8c14c78419a1567e790695c0e46544263bbd", "source_git_blob": null, "sha256": "37ab1037750d32eed6b3664b250a8c14c78419a1567e790695c0e46544263bbd" }, + { "path": "src/quadspline.rs", "source_sha256": "cfa129dd52d23a7852be3a1103e8022cc792cb2bd481440d3ebc1221a635e28d", "source_git_blob": null, "sha256": "cfa129dd52d23a7852be3a1103e8022cc792cb2bd481440d3ebc1221a635e28d" }, + { "path": "src/rect.rs", "source_sha256": "20c0bca0e79ab1b69321bf5d7e2db618cb4582bb29f47854faa5979a38a9ff2a", "source_git_blob": null, "sha256": "20c0bca0e79ab1b69321bf5d7e2db618cb4582bb29f47854faa5979a38a9ff2a" }, + { "path": "src/rounded_rect.rs", "source_sha256": "495d08f409456a97cd8c228f84624383922c4ef01e4d2edf624a40765a12b3c4", "source_git_blob": null, "sha256": "495d08f409456a97cd8c228f84624383922c4ef01e4d2edf624a40765a12b3c4" }, + { "path": "src/rounded_rect_radii.rs", "source_sha256": "ac42ee920ff31c6b5524ea9ae22e9da8ad2a8d17572e9ade1c369d827b8004d7", "source_git_blob": null, "sha256": "ac42ee920ff31c6b5524ea9ae22e9da8ad2a8d17572e9ade1c369d827b8004d7" }, + { "path": "src/shape.rs", "source_sha256": "226a32a1996d298e9587cc921b7cc8644ca6e04b2c740732e0a63ab00d3351ae", "source_git_blob": null, "sha256": "226a32a1996d298e9587cc921b7cc8644ca6e04b2c740732e0a63ab00d3351ae" }, + { "path": "src/simplify.rs", "source_sha256": "771fc68a2dd0a00d994906176641bcb17c9351b3d1205e037a78a5893b51a684", "source_git_blob": null, "sha256": "771fc68a2dd0a00d994906176641bcb17c9351b3d1205e037a78a5893b51a684" }, + { "path": "src/size.rs", "source_sha256": "645a1f7ba1528b1b10e5881d53019eac428e556c1d9bdea8d3f42ce351c00950", "source_git_blob": null, "sha256": "645a1f7ba1528b1b10e5881d53019eac428e556c1d9bdea8d3f42ce351c00950" }, + { "path": "src/stroke.rs", "source_sha256": "9ae69c57571d653a34ded745e176869ef587e4ff5c3dcb1607a398df7e029498", "source_git_blob": null, "sha256": "9ae69c57571d653a34ded745e176869ef587e4ff5c3dcb1607a398df7e029498" }, + { "path": "src/svg.rs", "source_sha256": "b403a258614b3e287c3e5210b0745814f08acda92e95696bdddbf50e341fa3be", "source_git_blob": null, "sha256": "b403a258614b3e287c3e5210b0745814f08acda92e95696bdddbf50e341fa3be" }, + { "path": "src/translate_scale.rs", "source_sha256": "8b82eb5f46744cb9a044263e200d79d797270616320337e4230356942ab85f1a", "source_git_blob": null, "sha256": "8b82eb5f46744cb9a044263e200d79d797270616320337e4230356942ab85f1a" }, + { "path": "src/triangle.rs", "source_sha256": "27a6cddb109ae36ef55c470261c689d085502ab72a47f3a32ca22e771df7b03e", "source_git_blob": null, "sha256": "27a6cddb109ae36ef55c470261c689d085502ab72a47f3a32ca22e771df7b03e" }, + { "path": "src/vec2.rs", "source_sha256": "05b37bf834417a040012fef380aa9eb10925324ea1a07fba3328839a56c9a060", "source_git_blob": null, "sha256": "05b37bf834417a040012fef380aa9eb10925324ea1a07fba3328839a56c9a060" } + ], + "omitted_files": [] +} diff --git a/vendor/kurbo/benches/cubic.rs b/vendor/kurbo/benches/cubic.rs new file mode 100644 index 0000000000..17ad29b9f4 --- /dev/null +++ b/vendor/kurbo/benches/cubic.rs @@ -0,0 +1,25 @@ +// Copyright 2022 the Kurbo Authors +// SPDX-License-Identifier: Apache-2.0 OR MIT + +//! Benchmarks of the cubic equation solver. + +#![allow(missing_docs, reason = "criterion emits undocumented functions")] + +use criterion::{Criterion, criterion_group, criterion_main}; +use std::hint::black_box; + +use kurbo::common::solve_cubic; + +fn bench_cubic(cc: &mut Criterion) { + let (x1, x2, x3) = (1.0, 2.0, 3.0); + let a = -(x1 + x2 + x3); + let b = x1 * x2 + x1 * x3 + x2 * x3; + let c = -x1 * x2 * x3; + + cc.bench_function("cubic roots", |bb| { + bb.iter(|| solve_cubic(black_box(c), black_box(b), black_box(a), 1.0)); + }); +} + +criterion_group!(benches, bench_cubic); +criterion_main!(benches); diff --git a/vendor/kurbo/benches/cubic_arclen.rs b/vendor/kurbo/benches/cubic_arclen.rs new file mode 100644 index 0000000000..c8c93a02b3 --- /dev/null +++ b/vendor/kurbo/benches/cubic_arclen.rs @@ -0,0 +1,36 @@ +// Copyright 2018 the Kurbo Authors +// SPDX-License-Identifier: Apache-2.0 OR MIT + +//! Benchmarks of cubic arclength approaches. + +#![allow(missing_docs, reason = "criterion emits undocumented functions")] + +use criterion::{BenchmarkId, Criterion, criterion_group, criterion_main}; +use std::hint::black_box; + +use kurbo::{CubicBez, ParamCurveArclen}; + +fn bench_cubic_arclen(cc: &mut Criterion) { + { + let mut group = cc.benchmark_group("cubic_arclen"); + for accuracy in [1e-4, 1e-5, 1e-6, 1e-7, 1e-8, 1e-9] { + group.bench_with_input( + BenchmarkId::from_parameter(accuracy), + &accuracy, + |b, &accuracy| { + let c = + CubicBez::new((0.0, 0.0), (1.0 / 3.0, 0.0), (2.0 / 3.0, 1.0), (1.0, 1.0)); + b.iter(|| black_box(c).arclen(accuracy)); + }, + ); + } + } + + cc.bench_function("cubic_arclen degenerate", |b| { + let c = CubicBez::new((0.0, 0.0), (0.0, 0.0), (0.0, 0.0), (0.0, 0.0)); + b.iter(|| black_box(c).arclen(1e-6)); + }); +} + +criterion_group!(benches, bench_cubic_arclen); +criterion_main!(benches); diff --git a/vendor/kurbo/benches/nearest.rs b/vendor/kurbo/benches/nearest.rs new file mode 100644 index 0000000000..73e9fcbb59 --- /dev/null +++ b/vendor/kurbo/benches/nearest.rs @@ -0,0 +1,53 @@ +// Copyright 2022 the Kurbo Authors +// SPDX-License-Identifier: Apache-2.0 OR MIT + +//! Benchmarks of the quartic equation solver. + +#![allow(missing_docs, reason = "criterion emits undocumented functions")] + +use criterion::{BenchmarkId, Criterion, criterion_group, criterion_main}; +use std::hint::black_box; + +use kurbo::{CubicBez, ParamCurveNearest as _, Point, QuadBez}; + +fn bench_nearest_quadratic(cc: &mut Criterion) { + let q = QuadBez { + p0: (-1.0, -1.0).into(), + p1: (0.0, 2.0).into(), + p2: (1.0, -1.0).into(), + }; + let p = Point::new(0.0, 0.0); + + for acc in [1e-3, 1e-6, 1e-12] { + cc.bench_with_input( + BenchmarkId::new("quadratic nearest point", acc), + &acc, + |bb, acc| { + bb.iter(|| black_box(q).nearest(black_box(p), *acc)); + }, + ); + } +} + +fn bench_nearest_cubic(cc: &mut Criterion) { + let c = CubicBez { + p0: (-1.0, -1.0).into(), + p1: (0.0, 2.0).into(), + p2: (1.0, -1.0).into(), + p3: (2.0, 2.0).into(), + }; + let p = Point::new(0.0, 0.0); + + for acc in [1e-3, 1e-6, 1e-12] { + cc.bench_with_input( + BenchmarkId::new("cubic nearest point", acc), + &acc, + |bb, acc| { + bb.iter(|| black_box(c).nearest(black_box(p), *acc)); + }, + ); + } +} + +criterion_group!(benches, bench_nearest_quadratic, bench_nearest_cubic); +criterion_main!(benches); diff --git a/vendor/kurbo/benches/quad_arclen.rs b/vendor/kurbo/benches/quad_arclen.rs new file mode 100644 index 0000000000..208c8ce2ab --- /dev/null +++ b/vendor/kurbo/benches/quad_arclen.rs @@ -0,0 +1,170 @@ +// Copyright 2018 the Kurbo Authors +// SPDX-License-Identifier: Apache-2.0 OR MIT + +//! Benchmarks of quadratic arclength approaches. + +#![allow(missing_docs, reason = "criterion emits undocumented functions")] + +// TODO: organize so there's less cut'n'paste from arclen_accuracy example. + +use criterion::{Criterion, criterion_group, criterion_main}; +use std::hint::black_box; + +use kurbo::{ParamCurve, ParamCurveArclen, ParamCurveDeriv, QuadBez}; + +// Based on http://www.malczak.linuxpl.com/blog/quadratic-bezier-curve-length/ +fn quad_arclen_analytical(q: QuadBez) -> f64 { + let d2 = q.p0.to_vec2() - 2.0 * q.p1.to_vec2() + q.p2.to_vec2(); + let a = d2.hypot2(); + let d1 = q.p1 - q.p0; + let b = 2.0 * d2.dot(d1); + let c = d1.hypot2(); + + let sabc = (a + b + c).sqrt(); + let a2 = a.powf(-0.5); + let a32 = a2.powi(3); + let c2 = 2.0 * c.sqrt(); + let ba = b * a2; + + sabc + 0.25 + * (a2 * a2 * b * (2.0 * sabc - c2) + + a32 * (4.0 * c * a - b * b) * (((2.0 * a + b) * a2 + 2.0 * sabc) / (ba + c2)).ln()) +} + +/// Calculate arclength using Gauss-Legendre quadrature using formula from Behdad +/// in +fn gauss_arclen_3(q: QuadBez) -> f64 { + let v0 = (-0.492943519233745 * q.p0.to_vec2() + + 0.430331482911935 * q.p1.to_vec2() + + 0.0626120363218102 * q.p2.to_vec2()) + .hypot(); + let v1 = ((q.p2 - q.p0) * 0.4444444444444444).hypot(); + let v2 = (-0.0626120363218102 * q.p0.to_vec2() - 0.430331482911935 * q.p1.to_vec2() + + 0.492943519233745 * q.p2.to_vec2()) + .hypot(); + v0 + v1 + v2 +} + +fn awesome_quad_arclen3(q: QuadBez, accuracy: f64, depth: usize) -> f64 { + let pm = q.p0.midpoint(q.p2); + let d1 = q.p1 - pm; + let d = q.p2 - q.p0; + let dhypot2 = d.hypot2(); + let x = 2.0 * d.dot(d1) / dhypot2; + let y = 2.0 * d.cross(d1) / dhypot2; + let lc = (q.p2 - q.p0).hypot(); + let lp = (q.p1 - q.p0).hypot() + (q.p2 - q.p1).hypot(); + let est_err = 0.06 * (lp - lc) * (x * x + y * y).powf(2.0); + if est_err < accuracy || depth == 16 { + gauss_arclen_3(q) + } else { + let (q0, q1) = q.subdivide(); + awesome_quad_arclen3(q0, accuracy * 0.5, depth + 1) + + awesome_quad_arclen3(q1, accuracy * 0.5, depth + 1) + } +} + +/// Another implementation, using weights from +/// +fn gauss_arclen_n(q: QuadBez, coeffs: &[(f64, f64)]) -> f64 { + let d = q.deriv(); + coeffs + .iter() + .map(|(wi, xi)| wi * d.eval(0.5 * (xi + 1.0)).to_vec2().hypot()) + .sum::() + * 0.5 +} + +fn gauss_arclen_7(q: QuadBez) -> f64 { + gauss_arclen_n( + q, + &[ + (0.4179591836734694, 0.0000000000000000), + (0.3818300505051189, 0.4058451513773972), + (0.3818300505051189, -0.4058451513773972), + (0.2797053914892766, -0.7415311855993945), + (0.2797053914892766, 0.7415311855993945), + (0.1294849661688697, -0.9491079123427585), + (0.1294849661688697, 0.9491079123427585), + ], + ) +} + +fn gauss_arclen_24(q: QuadBez) -> f64 { + gauss_arclen_n( + q, + &[ + (0.1279381953467522, -0.0640568928626056), + (0.1279381953467522, 0.0640568928626056), + (0.1258374563468283, -0.1911188674736163), + (0.1258374563468283, 0.1911188674736163), + (0.1216704729278034, -0.3150426796961634), + (0.1216704729278034, 0.3150426796961634), + (0.1155056680537256, -0.4337935076260451), + (0.1155056680537256, 0.4337935076260451), + (0.1074442701159656, -0.5454214713888396), + (0.1074442701159656, 0.5454214713888396), + (0.0976186521041139, -0.6480936519369755), + (0.0976186521041139, 0.6480936519369755), + (0.0861901615319533, -0.7401241915785544), + (0.0861901615319533, 0.7401241915785544), + (0.0733464814110803, -0.820001985973903), + (0.0733464814110803, 0.820001985973903), + (0.0592985849154368, -0.8864155270044011), + (0.0592985849154368, 0.8864155270044011), + (0.0442774388174198, -0.9382745520027328), + (0.0442774388174198, 0.9382745520027328), + (0.0285313886289337, -0.9747285559713095), + (0.0285313886289337, 0.9747285559713095), + (0.0123412297999872, -0.9951872199970213), + (0.0123412297999872, 0.9951872199970213), + ], + ) +} + +fn awesome_quad_arclen7(q: QuadBez, accuracy: f64, depth: usize) -> f64 { + let pm = q.p0.midpoint(q.p2); + let d1 = q.p1 - pm; + let d = q.p2 - q.p0; + let dhypot2 = d.hypot2(); + let x = 2.0 * d.dot(d1) / dhypot2; + let y = 2.0 * d.cross(d1) / dhypot2; + let lc = dhypot2.sqrt(); + let lp = (q.p1 - q.p0).hypot() + (q.p2 - q.p1).hypot(); + let est_err = 2.5e-2 * (lp - lc) * (x * x + y * y).powf(8.0).tanh(); + if est_err < accuracy || depth == 16 { + gauss_arclen_7(q) + } else { + let (q0, q1) = q.subdivide(); + awesome_quad_arclen7(q0, accuracy * 0.5, depth + 1) + + awesome_quad_arclen7(q1, accuracy * 0.5, depth + 1) + } +} + +const ACCURACY: f64 = 1e-6; +fn bench_quad_arclen(cc: &mut Criterion) { + let q = QuadBez::new((0.0, 0.0), (1.0, 0.0), (1.0, 1.0)); + + cc.bench_function("quad_arclen_analytical", |b| { + b.iter(|| quad_arclen_analytical(black_box(q))); + }); + cc.bench_function("quad_arclen", |b| b.iter(|| black_box(q).arclen(ACCURACY))); + cc.bench_function("quad_arclen_gauss3", |b| { + b.iter(|| awesome_quad_arclen3(black_box(q), ACCURACY, 0)); + }); + cc.bench_function("quad_arclen_gauss7", |b| { + b.iter(|| awesome_quad_arclen7(black_box(q), ACCURACY, 0)); + }); + cc.bench_function("quad_arclen_gauss3_one", |b| { + b.iter(|| gauss_arclen_3(black_box(q))); + }); + cc.bench_function("quad_arclen_gauss7_one", |b| { + b.iter(|| gauss_arclen_7(black_box(q))); + }); + cc.bench_function("quad_arclen_gauss24_one", |b| { + b.iter(|| gauss_arclen_24(black_box(q))); + }); +} + +criterion_group!(benches, bench_quad_arclen); +criterion_main!(benches); diff --git a/vendor/kurbo/benches/quartic.rs b/vendor/kurbo/benches/quartic.rs new file mode 100644 index 0000000000..b75bff3a58 --- /dev/null +++ b/vendor/kurbo/benches/quartic.rs @@ -0,0 +1,26 @@ +// Copyright 2022 the Kurbo Authors +// SPDX-License-Identifier: Apache-2.0 OR MIT + +//! Benchmarks of the quartic equation solver. + +#![allow(missing_docs, reason = "criterion emits undocumented functions")] + +use criterion::{Criterion, criterion_group, criterion_main}; +use std::hint::black_box; + +use kurbo::common::solve_quartic; + +fn bench_quartic(cc: &mut Criterion) { + let (x1, x2, x3, x4) = (1.0, 2.0, 3.0, 4.0); + let a = -(x1 + x2 + x3 + x4); + let b = x1 * (x2 + x3) + x2 * (x3 + x4) + x4 * (x1 + x3); + let c = -x1 * x2 * (x3 + x4) - x3 * x4 * (x1 + x2); + let d = x1 * x2 * x3 * x4; + + cc.bench_function("quartic roots", |bb| { + bb.iter(|| solve_quartic(black_box(d), black_box(c), black_box(b), black_box(a), 1.0)); + }); +} + +criterion_group!(benches, bench_quartic); +criterion_main!(benches); diff --git a/vendor/kurbo/benches/rect_expand.rs b/vendor/kurbo/benches/rect_expand.rs new file mode 100644 index 0000000000..0b9d51a0d3 --- /dev/null +++ b/vendor/kurbo/benches/rect_expand.rs @@ -0,0 +1,56 @@ +// Copyright 2020 the Kurbo Authors +// SPDX-License-Identifier: Apache-2.0 OR MIT + +//! Benchmarks of rect expansion. + +#![allow(missing_docs, reason = "criterion emits undocumented functions")] + +use criterion::{Criterion, criterion_group, criterion_main}; +use std::hint::black_box; + +use kurbo::Rect; + +// In positive space +static RECT_POS: Rect = Rect::new(3.3, 3.6, 5.6, 4.1); +// In both positive and negative space +static RECT_PAN: Rect = Rect::new(-3.3, -3.6, 5.6, 4.1); +// In negative space +static RECT_NEG: Rect = Rect::new(-5.6, -4.1, -3.3, -3.6); +// In positive space reverse +static RECT_POR: Rect = Rect::new(5.6, 4.1, 3.3, 3.6); +// In both positive and negative space reverse +static RECT_PNR: Rect = Rect::new(5.6, 4.1, -3.3, -3.6); +// In negative space reverse +static RECT_NER: Rect = Rect::new(-3.3, -3.6, -5.6, -4.1); +// In positive space mixed +static RECT_POM: Rect = Rect::new(3.3, 4.1, 5.6, 3.6); +// In both positive and negative space mixed +static RECT_PNM: Rect = Rect::new(-3.3, 4.1, 5.6, -3.6); +// In negative space mixed +static RECT_NEM: Rect = Rect::new(-5.6, -3.6, -3.3, -4.1); + +#[inline] +fn expand(rects: &[Rect; 9]) { + black_box(rects[0].expand()); + black_box(rects[1].expand()); + black_box(rects[2].expand()); + + black_box(rects[3].expand()); + black_box(rects[4].expand()); + black_box(rects[5].expand()); + + black_box(rects[6].expand()); + black_box(rects[7].expand()); + black_box(rects[8].expand()); +} + +fn bench_expand(c: &mut Criterion) { + // Creating the array here to prevent the compiler from optimizing all of it to NOP. + let rects: [Rect; 9] = [ + RECT_POS, RECT_PAN, RECT_NEG, RECT_POR, RECT_PNR, RECT_NER, RECT_POM, RECT_PNM, RECT_NEM, + ]; + c.bench_function("expand", |b| b.iter(|| expand(&rects))); +} + +criterion_group!(benches, bench_expand); +criterion_main!(benches); diff --git a/vendor/kurbo/examples/arclen_accuracy.rs b/vendor/kurbo/examples/arclen_accuracy.rs new file mode 100644 index 0000000000..7c47d87ce3 --- /dev/null +++ b/vendor/kurbo/examples/arclen_accuracy.rs @@ -0,0 +1,248 @@ +// Copyright 2018 the Kurbo Authors +// SPDX-License-Identifier: Apache-2.0 OR MIT + +//! A test program to plot the error of arclength approximation. + +#![allow(unused, reason = "a bunch of experiments in the code")] + +// TODO: make more functionality accessible from command line rather than uncommenting. + +use std::env; +use std::time::{Duration, Instant}; + +use kurbo::{ParamCurve, ParamCurveArclen, ParamCurveDeriv, QuadBez}; + +use kurbo::common::{GAUSS_LEGENDRE_COEFFS_5, GAUSS_LEGENDRE_COEFFS_7, GAUSS_LEGENDRE_COEFFS_24}; + +/// Calculate arclength using Gauss-Legendre quadrature using formula from Behdad +/// in +fn gauss_arclen_3(q: QuadBez) -> f64 { + let v0 = (-0.492943519233745 * q.p0.to_vec2() + + 0.430331482911935 * q.p1.to_vec2() + + 0.0626120363218102 * q.p2.to_vec2()) + .hypot(); + let v1 = ((q.p2 - q.p0) * 0.4444444444444444).hypot(); + let v2 = (-0.0626120363218102 * q.p0.to_vec2() - 0.430331482911935 * q.p1.to_vec2() + + 0.492943519233745 * q.p2.to_vec2()) + .hypot(); + v0 + v1 + v2 +} + +fn awesome_quad_arclen(q: QuadBez, accuracy: f64, depth: usize, count: &mut usize) -> f64 { + let pm = q.p0.midpoint(q.p2); + let d1 = q.p1 - pm; + let d = q.p2 - q.p0; + let dhypot2 = d.hypot2(); + let x = 2.0 * d.dot(d1) / dhypot2; + let y = 2.0 * d.cross(d1) / dhypot2; + let lc = (q.p2 - q.p0).hypot(); + let lp = (q.p1 - q.p0).hypot() + (q.p2 - q.p1).hypot(); + let est_err = 0.06 * (lp - lc) * (x * x + y * y).powf(2.0); + if est_err < accuracy || depth == 16 { + *count += 1; + gauss_arclen_3(q) + } else { + let (q0, q1) = q.subdivide(); + awesome_quad_arclen(q0, accuracy * 0.5, depth + 1, count) + + awesome_quad_arclen(q1, accuracy * 0.5, depth + 1, count) + } +} + +const MAX_DEPTH: usize = 16; +fn gravesen_rec(q: &QuadBez, l0: f64, accuracy: f64, depth: usize, count: &mut usize) -> f64 { + let (q0, q1) = q.subdivide(); + let l0_q0 = calc_l0(q0); + let l0_q1 = calc_l0(q1); + let l1 = l0_q0 + l0_q1; + let error = (l0 - l1) * (1.0 / 15.0); + if error.abs() < accuracy || depth == MAX_DEPTH { + *count += 1; + l1 - error + } else { + gravesen_rec(&q0, l0_q0, accuracy * 0.5, depth + 1, count) + + gravesen_rec(&q1, l0_q1, accuracy * 0.5, depth + 1, count) + } +} + +fn gauss_arclen_5(q: QuadBez) -> f64 { + q.gauss_arclen(GAUSS_LEGENDRE_COEFFS_5) +} + +fn gauss_arclen_7(q: QuadBez) -> f64 { + q.gauss_arclen(GAUSS_LEGENDRE_COEFFS_7) +} + +fn gauss_arclen_24(q: QuadBez) -> f64 { + q.gauss_arclen(GAUSS_LEGENDRE_COEFFS_24) +} + +fn awesome_quad_arclen7(q: QuadBez, accuracy: f64, depth: usize, count: &mut usize) -> f64 { + let pm = q.p0.midpoint(q.p2); + let d1 = q.p1 - pm; + let d = q.p2 - q.p0; + let dhypot2 = d.hypot2(); + let x = 2.0 * d.dot(d1) / dhypot2; + let y = 2.0 * d.cross(d1) / dhypot2; + let lc = (q.p2 - q.p0).hypot(); + let lp = (q.p1 - q.p0).hypot() + (q.p2 - q.p1).hypot(); + let est_err = 2.5e-2 * (lp - lc) * (x * x + y * y).powf(8.0).tanh(); + // Increase depth, so we can be an accurate baseline for comparison. + if est_err < accuracy || depth == 22 { + *count += 1; + gauss_arclen_7(q) + } else { + let (q0, q1) = q.subdivide(); + awesome_quad_arclen7(q0, accuracy * 0.5, depth + 1, count) + + awesome_quad_arclen7(q1, accuracy * 0.5, depth + 1, count) + } +} + +fn awesome_quad_arclen24(q: QuadBez, accuracy: f64, depth: usize, count: &mut usize) -> f64 { + let pm = q.p0.midpoint(q.p2); + let d1 = q.p1 - pm; + let d = q.p2 - q.p0; + let dhypot2 = d.hypot2(); + let x = 2.0 * d.dot(d1) / dhypot2; + let y = 2.0 * d.cross(d1) / dhypot2; + let lc = (q.p2 - q.p0).hypot(); + let lp = (q.p1 - q.p0).hypot() + (q.p2 - q.p1).hypot(); + // This isn't quite right near (1.1, 0) + let est_err = 1.0 * (lp - lc) * (0.5 * x * x + 0.1 * y * y).powf(16.0).tanh(); + if est_err < accuracy || depth == 16 { + *count += 1; + gauss_arclen_24(q) + } else { + let (q0, q1) = q.subdivide(); + awesome_quad_arclen24(q0, accuracy * 0.5, depth + 1, count) + + awesome_quad_arclen24(q1, accuracy * 0.5, depth + 1, count) + } +} + +// Based on http://www.malczak.linuxpl.com/blog/quadratic-bezier-curve-length/ +fn quad_arclen_analytical(q: QuadBez) -> f64 { + let d2 = q.p0.to_vec2() - 2.0 * q.p1.to_vec2() + q.p2.to_vec2(); + let a = d2.hypot2(); + let d1 = q.p1 - q.p0; + let c = d1.hypot2(); + if a < 5e-4 * c { + return gauss_arclen_3(q); + } + let b = 2.0 * d2.dot(d1); + + let sabc = (a + b + c).sqrt(); + let a2 = a.powf(-0.5); + let a32 = a2.powi(3); + let c2 = 2.0 * c.sqrt(); + let ba_c2 = b * a2 + c2; + + let v0 = 0.25 * a2 * a2 * b * (2.0 * sabc - c2) + sabc; + // TODO: justify and fine-tune this exact constant. + if ba_c2 < 1e-13 { + // This case happens for Béziers with a sharp kink. + v0 + } else { + v0 + 0.25 * a32 * (4.0 * c * a - b * b) * (((2.0 * a + b) * a2 + 2.0 * sabc) / ba_c2).ln() + } +} + +/// Calculate the L0 metric from "Adaptive subdivision and the length and +/// energy of Bézier curves" by Jens Gravesen. +fn calc_l0(q: QuadBez) -> f64 { + let lc = (q.p2 - q.p0).hypot(); + let lp = (q.p1 - q.p0).hypot() + (q.p2 - q.p1).hypot(); + (2.0 / 3.0) * lc + (1.0 / 3.0) * lp +} + +fn with_subdiv(q: QuadBez, f: &dyn Fn(QuadBez) -> f64, depth: usize) -> f64 { + if depth == 0 { + f(q) + } else { + let (q0, q1) = q.subdivide(); + with_subdiv(q0, f, depth - 1) + with_subdiv(q1, f, depth - 1) + } +} + +fn duration_to_time(d: Duration) -> f64 { + 1e-9 * (d.subsec_nanos() as f64) + (d.as_secs() as f64) +} + +fn run_simple() { + let q = QuadBez::new((0.0, 0.0), (0.0, 0.5), (1.0, 1.0)); + let true_len = q.arclen(1e-13); + for i in 0..20 { + let n = 1 << i; + let start_time = Instant::now(); + let mut est = 0.0; + let mut last = q.start(); + let dt = (n as f64).recip(); + for j in 0..n { + let t = ((j + 1) as f64) * dt; + let p = q.eval(t); + est += (p - last).hypot(); + last = p; + } + let elapsed = duration_to_time(start_time.elapsed()); + let err = true_len - est; + if i > 0 { + println!("{elapsed} {err}"); + } + } +} + +/// Generate map data suitable for plotting in Gnuplot. +fn main() { + let mut n_subdiv = 0; + let mut func: &dyn Fn(QuadBez) -> f64 = &gauss_arclen_3; + for arg in env::args().skip(1) { + if arg == "gauss3" { + func = &gauss_arclen_3; + } else if arg == "gauss5" { + func = &gauss_arclen_5; + } else if arg == "gauss7" { + func = &gauss_arclen_7; + } else if arg == "gauss24" { + func = &gauss_arclen_24; + } else if arg == "l0" { + func = &calc_l0; + } else if arg == "simple" { + run_simple(); + return; + } else if let Ok(n) = arg.parse() { + n_subdiv = n; + } else { + println!("usage: arclen_accuracy [func] n_subdiv"); + std::process::exit(1); + } + } + let n = 400; + let accuracy = 1e-6; + for i in 0..=n { + let x = 2.0 * (i as f64) * (n as f64).recip(); + for j in 0..=n { + let y = 2.0 * (j as f64) * (n as f64).recip(); + let q = QuadBez::new((-1.0, 0.0), (x, y), (1.0, 0.0)); + let mut count = 0; + let accurate_arclen = awesome_quad_arclen7(q, 1e-15, 0, &mut count); + //count = 0; + let start_time = Instant::now(); + //let est = awesome_quad_arclen7(q, accuracy, 0, &mut count); + let est = quad_arclen_analytical(q); + let elapsed = start_time.elapsed(); + //let est = gravesen_rec(&q, calc_l0(q), accuracy, 0, &mut count); + //let est = with_subdiv(q, func, n_subdiv); + let error = est - accurate_arclen; + println!("{} {} {}", x, y, (error.abs() + 1e-18).log10()); + //println!("{} {} {}", x, y, count); + //println!("{} {} {}", x, y, elapsed.subsec_nanos()); + //let accurate_arclen = with_subdiv(q, &gauss_arclen_5, 8); + //let error = est - accurate_arclen; + /* + let lc = (q.p2 - q.p0).hypot(); + let lp = (q.p1 - q.p0).hypot() + (q.p2 - q.p1).hypot(); + let est_err = 1.0 * (lp - lc) * (0.5 * x * x + 0.1 * y * y).powf(16.0).tanh(); + println!("{} {} {}", x, y, (est_err/error.abs() + 1e-15).log10()); + */ + } + println!(); + } +} diff --git a/vendor/kurbo/examples/circle.rs b/vendor/kurbo/examples/circle.rs new file mode 100644 index 0000000000..207eaa37aa --- /dev/null +++ b/vendor/kurbo/examples/circle.rs @@ -0,0 +1,27 @@ +// Copyright 2019 the Kurbo Authors +// SPDX-License-Identifier: Apache-2.0 OR MIT + +//! Example of circle + +#[cfg(feature = "std")] +fn main() { + use kurbo::{Circle, Shape}; + + let circle = Circle::new((400.0, 400.0), 380.0); + println!(""); + println!(""); + println!(""); + println!(""); + let black_path = circle.to_path(1e-3).to_svg(); + println!(" "); + let red_path = circle.to_path(1.0).to_svg(); + println!(" "); + println!(""); + println!(""); + println!(""); +} + +#[cfg(not(feature = "std"))] +fn main() { + println!("This example requires the standard library"); +} diff --git a/vendor/kurbo/examples/cubic_arclen.rs b/vendor/kurbo/examples/cubic_arclen.rs new file mode 100644 index 0000000000..b019884d7f --- /dev/null +++ b/vendor/kurbo/examples/cubic_arclen.rs @@ -0,0 +1,256 @@ +// Copyright 2018 the Kurbo Authors +// SPDX-License-Identifier: Apache-2.0 OR MIT + +//! Research testbed for arclengths of cubic Bézier segments. + +#![allow(unused, reason = "a bunch of experiments in the code")] + +use kurbo::common::{GAUSS_LEGENDRE_COEFFS_7, GAUSS_LEGENDRE_COEFFS_9, GAUSS_LEGENDRE_COEFFS_11}; +use kurbo::{ + CubicBez, ParamCurve, ParamCurveArclen, ParamCurveCurvature, ParamCurveDeriv, Point, Vec2, +}; + +/// Calculate arclength using Gauss-Legendre quadrature using formula from Behdad +/// in +fn gauss_arclen_5(c: CubicBez) -> f64 { + let v0 = (c.p1 - c.p0).hypot() * 0.15; + let v1 = (-0.558983582205757 * c.p0.to_vec2() + + 0.325650248872424 * c.p1.to_vec2() + + 0.208983582205757 * c.p2.to_vec2() + + 0.024349751127576 * c.p3.to_vec2()) + .hypot(); + let v2 = (c.p3 - c.p0 + (c.p2 - c.p1)).hypot() * 0.26666666666666666; + let v3 = (-0.024349751127576 * c.p0.to_vec2() + - 0.208983582205757 * c.p1.to_vec2() + - 0.325650248872424 * c.p2.to_vec2() + + 0.558983582205757 * c.p3.to_vec2()) + .hypot(); + let v4 = (c.p3 - c.p2).hypot() * 0.15; + + v0 + v1 + v2 + v3 + v4 +} + +fn gauss_arclen_7(c: C) -> f64 { + c.gauss_arclen(GAUSS_LEGENDRE_COEFFS_7) +} + +fn est_gauss5_error(c: CubicBez) -> f64 { + let lc = (c.p3 - c.p0).hypot(); + let lp = (c.p1 - c.p0).hypot() + (c.p2 - c.p1).hypot() + (c.p3 - c.p2).hypot(); + + let d2 = c.deriv().deriv(); + let d3 = d2.deriv(); + let lmi = 2.0 / (lp + lc); + 7e-8 * (d3.eval(0.5).to_vec2().hypot() * lmi + 5.0 * d2.eval(0.5).to_vec2().hypot() * lmi) + .powi(5) + * lp +} + +fn gauss_errnorm_n(c: C, coeffs: &[(f64, f64)]) -> f64 +where + C::DerivResult: ParamCurveDeriv, +{ + let d = c.deriv().deriv(); + coeffs + .iter() + .map(|(wi, xi)| wi * d.eval(0.5 * (xi + 1.0)).to_vec2().hypot2()) + .sum::() +} + +// Squared L2 norm of the second derivative of the cubic. +fn cubic_errnorm(c: CubicBez) -> f64 { + let d = c.deriv().deriv(); + let dd = d.end() - d.start(); + d.start().to_vec2().hypot2() + d.start().to_vec2().dot(dd) + dd.hypot2() * (1.0 / 3.0) +} + +fn est_gauss7_error(c: CubicBez) -> f64 { + let lc = (c.p3 - c.p0).hypot(); + let lp = (c.p1 - c.p0).hypot() + (c.p2 - c.p1).hypot() + (c.p3 - c.p2).hypot(); + + 8e-9 * (2.0 * cubic_errnorm(c) / lc.powi(2)).powi(6) * lp +} + +fn gauss_arclen_9(c: C) -> f64 { + c.gauss_arclen(GAUSS_LEGENDRE_COEFFS_9) +} + +fn gauss_arclen_11(c: C) -> f64 { + c.gauss_arclen(GAUSS_LEGENDRE_COEFFS_11) +} + +fn est_gauss9_error(c: CubicBez) -> f64 { + let lc = (c.p3 - c.p0).hypot(); + let lp = (c.p1 - c.p0).hypot() + (c.p2 - c.p1).hypot() + (c.p3 - c.p2).hypot(); + + 1e-10 * (2.0 * cubic_errnorm(c) / lc.powi(2)).powi(8) * lp +} + +fn est_gauss11_error(c: CubicBez) -> f64 { + let lc = (c.p3 - c.p0).hypot(); + let lp = (c.p1 - c.p0).hypot() + (c.p2 - c.p1).hypot() + (c.p3 - c.p2).hypot(); + + 1e-12 * (2.0 * cubic_errnorm(c) / lc.powi(2)).powi(11) * lp +} + +// A new approach based on integrating local error. +fn est_gauss11_error_2(c: CubicBez) -> f64 { + let d = c.deriv(); + let d2 = d.deriv(); + GAUSS_LEGENDRE_COEFFS_11 + .iter() + .map(|(wi, xi)| { + wi * { + let t = 0.5 * (xi + 1.0); + let v = d.eval(t).to_vec2().hypot(); + let a2 = d2.eval(t).to_vec2().hypot2(); + a2.powi(3) / v.powi(5) + } + }) + .sum::() +} + +#[expect( + clippy::neg_cmp_op_on_partial_ord, + reason = "probably IEEE semantics nuance" +)] +fn est_max_curvature(c: CubicBez) -> f64 { + let n = 100; + let mut max = 0.0; + for i in 0..=n { + let t = (i as f64) * (n as f64).recip(); + let k = c.curvature(t).abs(); + if !(k < max) { + max = k; + } + } + max +} + +fn est_min_deriv_norm2(c: CubicBez) -> f64 { + let d = c.deriv(); + let n = 100; + let mut min = d.eval(1.0).to_vec2().hypot2(); + for i in 0..n { + let t = (i as f64) * (n as f64).recip(); + min = min.min(d.eval(t).to_vec2().hypot2()); + } + min +} + +fn est_gauss11_error_3(c: CubicBez) -> f64 { + let lc = (c.p3 - c.p0).hypot(); + let lp = (c.p1 - c.p0).hypot() + (c.p2 - c.p1).hypot() + (c.p3 - c.p2).hypot(); + let pc_err = (lp - lc) * 0.02; + let ks = est_max_curvature(c) * lp; + let est = ks.powi(3) * lp * 8e-9; + if est < pc_err { est } else { pc_err } +} + +fn est_gauss9_error_3(c: CubicBez) -> f64 { + let lc = (c.p3 - c.p0).hypot(); + let lp = (c.p1 - c.p0).hypot() + (c.p2 - c.p1).hypot() + (c.p3 - c.p2).hypot(); + let pc_err = (lp - lc) * 0.02; + let ks = est_max_curvature(c) * lp; + let est = ks.powi(3) * lp * 5e-8; + if est < pc_err { est } else { pc_err } +} + +// A new approach based on integrating local error; the cost of evaluating the +// error metric is likely to dominate unless the accuracy buys a lot of subdivisions. +fn est_gauss9_error_2(c: CubicBez) -> f64 { + let d = c.deriv(); + let d2 = d.deriv(); + let p = 10; + GAUSS_LEGENDRE_COEFFS_9 + .iter() + .map(|(wi, xi)| { + wi * { + let t = 0.5 * (xi + 1.0); + let v = d.eval(t).to_vec2().hypot(); + let a = d2.eval(t).to_vec2().hypot(); + (1.0e-1 * a / v).tanh().powi(p) * v + } + }) + .sum::() + * 3.0 +} + +fn my_arclen(c: CubicBez, accuracy: f64, depth: usize, count: &mut usize) -> f64 { + if depth == 16 || est_gauss5_error(c) < accuracy { + *count += 1; + gauss_arclen_5(c) + } else { + let (c0, c1) = c.subdivide(); + my_arclen(c0, accuracy * 0.5, depth + 1, count) + + my_arclen(c1, accuracy * 0.5, depth + 1, count) + } +} + +fn my_arclen7(c: CubicBez, accuracy: f64, depth: usize, count: &mut usize) -> f64 { + if depth == 16 || est_gauss7_error(c) < accuracy { + *count += 1; + gauss_arclen_7(c) + } else { + let (c0, c1) = c.subdivide(); + my_arclen7(c0, accuracy * 0.5, depth + 1, count) + + my_arclen7(c1, accuracy * 0.5, depth + 1, count) + } +} + +// Should make this generic instead of copy+paste, but we need only one when we're done. +fn my_arclen9(c: CubicBez, accuracy: f64, depth: usize, count: &mut usize) -> f64 { + if depth == 16 || est_gauss9_error(c) < accuracy { + *count += 1; + gauss_arclen_9(c) + } else { + let (c0, c1) = c.subdivide(); + my_arclen9(c0, accuracy * 0.5, depth + 1, count) + + my_arclen9(c1, accuracy * 0.5, depth + 1, count) + } +} + +// This doesn't help; we can't really get a more accurate error bound, so all this +// does is overkill the accuracy. +fn my_arclen11(c: CubicBez, accuracy: f64, depth: usize, count: &mut usize) -> f64 { + if depth == 16 || est_gauss9_error(c) < accuracy { + *count += 1; + gauss_arclen_11(c) + } else { + let (c0, c1) = c.subdivide(); + my_arclen11(c0, accuracy * 0.5, depth + 1, count) + + my_arclen11(c1, accuracy * 0.5, depth + 1, count) + } +} + +fn randpt() -> Point { + Point::new(rand::random(), rand::random()) +} + +fn randbez() -> CubicBez { + CubicBez::new(randpt(), randpt(), randpt(), randpt()) +} + +fn main() { + let accuracy = 1e-4; + for _ in 0..10_000 { + let c = randbez(); + let t: f64 = rand::random(); + let c = c.subsegment(0.0..t); + //let accurate_arclen = c.arclen(1e-12); + let mut count = 0; + let accurate_arclen = my_arclen9(c, 1e-15, 0, &mut count); + + let est = gauss_arclen_9(c); + let est_err = est_gauss9_error_3(c); + let err = (accurate_arclen - est).abs(); + println!("{est_err} {err}"); + + /* + let mut count = 0; + let est = my_arclen9(c, accuracy, 0, &mut count); + let err = (accurate_arclen - est).abs(); + println!("{err} {count}"); + */ + } +} diff --git a/vendor/kurbo/examples/ellipse.rs b/vendor/kurbo/examples/ellipse.rs new file mode 100644 index 0000000000..62ad0def5f --- /dev/null +++ b/vendor/kurbo/examples/ellipse.rs @@ -0,0 +1,28 @@ +// Copyright 2020 the Kurbo Authors +// SPDX-License-Identifier: Apache-2.0 OR MIT + +//! Example of ellipse + +#[cfg(feature = "std")] +fn main() { + use kurbo::{Ellipse, Shape}; + use std::f64::consts::PI; + + let ellipse = Ellipse::new((400.0, 400.0), (200.0, 100.0), 0.25 * PI); + println!(""); + println!(""); + println!(""); + println!(""); + let black_path = ellipse.to_path(1e-3).to_svg(); + println!(" "); + let red_path = ellipse.to_path(1.0).to_svg(); + println!(" "); + println!(""); + println!(""); + println!(""); +} + +#[cfg(not(feature = "std"))] +fn main() { + println!("This example requires the standard library"); +} diff --git a/vendor/kurbo/examples/fit_poly.rs b/vendor/kurbo/examples/fit_poly.rs new file mode 100644 index 0000000000..4fba08380d --- /dev/null +++ b/vendor/kurbo/examples/fit_poly.rs @@ -0,0 +1,76 @@ +// Copyright 2022 the Kurbo Authors +// SPDX-License-Identifier: Apache-2.0 OR MIT + +//! A test case for the cubic Bézier path simplifier, generating a very +//! efficient and accurate SVG file to plot a quartic polynomial. This +//! file was used to generate the image for the Wikipedia article on +//! quartic polynomials. + +use std::{io::Write, ops::Range}; + +use kurbo::{BezPath, CurveFitSample, ParamCurveFit, PathEl, Point, Vec2}; + +struct MyPoly; + +fn eval_mypoly(x: f64) -> f64 { + (x + 4.) * (x + 1.) * (x - 1.) * (x - 3.) / 14. + 0.5 +} + +fn eval_mypoly_deriv(x: f64) -> f64 { + (((4. * x + 3.) * x - 26.) * x - 1.) / 14. +} + +impl ParamCurveFit for MyPoly { + fn sample_pt_deriv(&self, t: f64) -> (Point, Vec2) { + const S: f64 = 336.; + let x = 37. + t * S; + let math_x = (x - 220.) / 40.; + let y = -eval_mypoly(math_x) * 40. + 260.; + let dx = S; + let dy = -dx * eval_mypoly_deriv(math_x); + (Point::new(x, y), Vec2::new(dx, dy)) + } + + fn sample_pt_tangent(&self, t: f64, _: f64) -> CurveFitSample { + let (p, tangent) = self.sample_pt_deriv(t); + CurveFitSample { p, tangent } + } + + fn break_cusp(&self, _: Range) -> Option { + None + } +} + +fn to_svg_economical(path: &BezPath) -> String { + let mut buffer = Vec::new(); + write_to(path, &mut buffer).unwrap(); + String::from_utf8(buffer).unwrap() +} + +/// Write the SVG representation of this path to the provided buffer. +fn write_to(path: &BezPath, mut writer: W) -> std::io::Result<()> { + for el in path.elements() { + match *el { + PathEl::MoveTo(p) => write!(writer, "M{:.2} {:.2}", p.x, p.y)?, + PathEl::LineTo(p) => write!(writer, "L{} {}", p.x, p.y)?, + PathEl::QuadTo(p1, p2) => write!(writer, "Q{} {} {} {}", p1.x, p1.y, p2.x, p2.y)?, + PathEl::CurveTo(p1, p2, p3) => write!( + writer, + "C{:.2} {:.2} {:.2} {:.2} {:.2} {:.2}", + p1.x, p1.y, p2.x, p2.y, p3.x, p3.y + )?, + PathEl::ClosePath => write!(writer, "Z")?, + } + } + Ok(()) +} + +fn main() { + println!(""); + let path = kurbo::fit_to_bezpath_opt(&MyPoly, 0.1); + println!( + " ", + to_svg_economical(&path) + ); + println!(""); +} diff --git a/vendor/kurbo/examples/quad_intersect.rs b/vendor/kurbo/examples/quad_intersect.rs new file mode 100644 index 0000000000..8911d787ec --- /dev/null +++ b/vendor/kurbo/examples/quad_intersect.rs @@ -0,0 +1,92 @@ +// Copyright 2022 the Kurbo Authors +// SPDX-License-Identifier: Apache-2.0 OR MIT + +//! Test case that demonstrates quadratic/quadratic intersection using +//! new quartic solver. + +use arrayvec::ArrayVec; +use kurbo::{ParamCurve, Point, QuadBez, Shape, common::solve_quartic}; +use rand::Rng; + +fn rand_point() -> Point { + let mut rng = rand::rng(); + Point::new(rng.random_range(0.0..500.0), rng.random_range(0.0..500.0)) +} + +fn rand_quad() -> QuadBez { + QuadBez::new(rand_point(), rand_point(), rand_point()) +} + +struct ImplicitQuad { + x2: f64, + xy: f64, + y2: f64, + x: f64, + y: f64, + c: f64, +} + +impl ImplicitQuad { + fn from_quad(q: QuadBez) -> Self { + let Point { x: ax, y: ay } = q.p0; + let Point { x: bx, y: by } = q.p1; + let Point { x: cx, y: cy } = q.p2; + let (u0, u1, u2) = (by - cy, cx - bx, bx * cy - by * cx); + let (v0, v1, v2) = (cy - ay, ax - cx, cx * ay - cy * ax); + let (w0, w1, w2) = (ay - by, bx - ax, ax * by - ay * bx); + Self { + x2: 4. * u0 * w0 - v0 * v0, + xy: 4. * (u0 * w1 + u1 * w0) - 2. * v0 * v1, + y2: 4. * u1 * w1 - v1 * v1, + x: 4. * (u0 * w2 + u2 * w0) - 2. * v0 * v2, + y: 4. * (u1 * w2 + u2 * w1) - 2. * v1 * v2, + c: 4. * u2 * w2 - v2 * v2, + } + } + + fn eval(&self, x: f64, y: f64) -> f64 { + self.x2 * x * x + self.xy * x * y + self.y2 * y * y + self.x * x + self.y * y + self.c + } +} + +fn intersect_quads(q0: QuadBez, q1: QuadBez) -> ArrayVec { + let iq = ImplicitQuad::from_quad(q0); + let c = q1.p0.to_vec2(); + let b = (q1.p1 - q1.p0) * 2.0; + let a = c - q1.p1.to_vec2() * 2.0 + q1.p2.to_vec2(); + let c0 = iq.eval(c.x, c.y); + let c1 = iq.x * b.x + + iq.y * b.y + + 2. * iq.x2 * (b.x * c.x) + + 2. * iq.y2 * (b.y * c.y) + + iq.xy * (b.x * c.y + b.y * c.x); + let c2 = iq.x * a.x + + iq.y * a.y + + iq.x2 * (2. * a.x * c.x + b.x * b.x) + + iq.xy * (a.x * c.y + b.x * b.y + a.y * c.x) + + iq.y2 * (2. * a.y * c.y + b.y * b.y); + let c3 = iq.x2 * 2. * a.x * b.x + iq.xy * (a.x * b.y + b.x * a.y) + iq.y2 * 2. * a.y * b.y; + let c4 = iq.x2 * a.x * a.x + iq.xy * a.x * a.y + iq.y2 * a.y * a.y; + let ts = solve_quartic(c0, c1, c2, c3, c4); + println!("ts: {ts:?}"); + ts +} + +fn main() { + let q0 = rand_quad(); + let q1 = rand_quad(); + println!( + " ", + q0.to_path(1e-9).to_svg() + ); + println!( + " ", + q1.to_path(1e-9).to_svg() + ); + for t in intersect_quads(q0, q1) { + if (0.0..=1.0).contains(&t) { + let p = q1.eval(t); + println!(" ", p.x, p.y); + } + } +} diff --git a/vendor/kurbo/examples/simplify.rs b/vendor/kurbo/examples/simplify.rs new file mode 100644 index 0000000000..1227f7e5bb --- /dev/null +++ b/vendor/kurbo/examples/simplify.rs @@ -0,0 +1,52 @@ +// Copyright 2022 the Kurbo Authors +// SPDX-License-Identifier: Apache-2.0 OR MIT + +//! Test case showing simplification of a Bézier path. In this case, the +//! source path is a simple mathematical function, but it should work for +//! more general cases as well. + +use kurbo::{BezPath, Point}; + +fn plot_fn(f: &dyn Fn(f64) -> f64, d: &dyn Fn(f64) -> f64, xa: f64, xb: f64, n: usize) -> BezPath { + let width = 800.; + let dx = (xb - xa) / n as f64; + let xs = width / (xb - xa); + let ys = 250.; + let y_origin = 300.; + let plot = |x, y| Point::new((x - xa) * xs, y_origin - y * ys); + let mut x0 = xa; + let mut y0 = f(xa); + let mut d0 = d(xa); + let mut path = BezPath::new(); + path.move_to(plot(x0, y0)); + for i in 0..n { + let x3 = xa + dx * (i + 1) as f64; + let y3 = f(x3); + let d3 = d(x3); + let x1 = x0 + (1. / 3.) * dx; + let x2 = x3 - (1. / 3.) * dx; + let y1 = y0 + d0 * (1. / 3.) * dx; + let y2 = y3 - d3 * (1. / 3.) * dx; + path.curve_to(plot(x1, y1), plot(x2, y2), plot(x3, y3)); + x0 = x3; + y0 = y3; + d0 = d3; + } + path +} + +fn main() { + println!(""); + let path = plot_fn(&|x| x.sin(), &|x| x.cos(), -8., 8., 20); + println!( + " ", + path.to_svg() + ); + let simpl = kurbo::simplify::SimplifyBezPath::new(path); + let simplified_path = kurbo::fit_to_bezpath_opt(&simpl, 0.1); + println!( + " ", + simplified_path.to_svg() + ); + println!(""); +} diff --git a/vendor/kurbo/examples/stroke.rs b/vendor/kurbo/examples/stroke.rs new file mode 100644 index 0000000000..f6b7170390 --- /dev/null +++ b/vendor/kurbo/examples/stroke.rs @@ -0,0 +1,183 @@ +// Copyright 2025 the Kurbo Authors +// SPDX-License-Identifier: Apache-2.0 OR MIT + +//! Stroke example. +//! +//! This example has been lightly adapted from Vello, which in turn has +//! been adapted from the Skia "tricky stroke" test. + +use kurbo::{Affine, BezPath, Cap, Join, Rect, Shape, Stroke, StrokeOpts, stroke}; + +fn tricky_strokes() { + const CELL_SIZE: f64 = 200.; + const STROKE_WIDTH: f64 = 30.; + const NUM_COLS: usize = 5; + + fn stroke_bounds(pts: &[(f64, f64); 4]) -> Rect { + use kurbo::CubicBez; + CubicBez::new(pts[0], pts[1], pts[2], pts[3]) + .bounding_box() + .inflate(STROKE_WIDTH, STROKE_WIDTH) + } + + fn map_rect_to_rect(src: &Rect, dst: &Rect) -> (Affine, f64) { + let (scale, x_larger) = { + let sx = dst.width() / src.width(); + let sy = dst.height() / src.height(); + (sx.min(sy), sx > sy) + }; + let tx = dst.x0 - src.x0 * scale; + let ty = dst.y0 - src.y0 * scale; + let (tx, ty) = if x_larger { + (tx + 0.5 * (dst.width() - src.width() * scale), ty) + } else { + (tx, ty + 0.5 * (dst.height() - src.height() * scale)) + }; + (Affine::new([scale, 0.0, 0.0, scale, tx, ty]), scale) + } + + let tricky_cubics = [ + [(122., 737.), (348., 553.), (403., 761.), (400., 760.)], + [(244., 520.), (244., 518.), (1141., 634.), (394., 688.)], + [(550., 194.), (138., 130.), (1035., 246.), (288., 300.)], + [(226., 733.), (556., 779.), (-43., 471.), (348., 683.)], + [(268., 204.), (492., 304.), (352., 23.), (433., 412.)], + [(172., 480.), (396., 580.), (256., 299.), (338., 677.)], + [(731., 340.), (318., 252.), (1026., -64.), (367., 265.)], + [(475., 708.), (62., 620.), (770., 304.), (220., 659.)], + [(0., 0.), (128., 128.), (128., 0.), (0., 128.)], // Perfect cusp + [(0., 0.01), (128., 127.999), (128., 0.01), (0., 127.99)], // Near-cusp + [(0., -0.01), (128., 128.001), (128., -0.01), (0., 128.001)], // Near-cusp + [(0., 0.), (0., -10.), (0., -10.), (0., 10.)], // Flat line with 180 + [(10., 0.), (0., 0.), (20., 0.), (10., 0.)], // Flat line with 2 180s + [(39., -39.), (40., -40.), (40., -40.), (0., 0.)], // Flat diagonal with 180 + [(40., 40.), (0., 0.), (200., 200.), (0., 0.)], // Diag w/ an internal 180 + [(0., 0.), (1e-2, 0.), (-1e-2, 0.), (0., 0.)], // Circle + // Flat line with no turns: + [ + (400.75, 100.05), + (400.75, 100.05), + (100.05, 300.95), + (100.05, 300.95), + ], + [(0.5, 0.), (0., 0.), (20., 0.), (10., 0.)], // Flat line with 2 180s + [(10., 0.), (0., 0.), (10., 0.), (10., 0.)], // Flat line with a 180 + ]; + + // Flat conic with a cusp: (1,1) (2,1) (1,1), weight: 1 + let flat_quad = [ + // moveTo(1., 1.), + [(2., 1.), (1., 1.)], + ]; + // Flat conic with a cusp: (1,1) (100,1) (25,1), weight: 0.3 + let flat_conic_as_quads = [ + // moveTo(1., 1.), + [(2.232486, 1.000000), (3.471740, 1.000000)], + [(4.710995, 1.000000), (5.949262, 1.000000)], + [(7.187530, 1.000000), (8.417061, 1.000000)], + [(9.646591, 1.000000), (10.859690, 1.000000)], + [(12.072789, 1.000000), (13.261865, 1.000000)], + [(14.450940, 1.000000), (15.608549, 1.000000)], + [(16.766161, 1.000000), (17.885059, 1.000000)], + [(19.003958, 1.000000), (20.077141, 1.000000)], + [(21.150328, 1.000000), (22.171083, 1.000000)], + [(23.191839, 1.000000), (24.153776, 1.000000)], + [(25.115715, 1.000000), (26.012812, 1.000000)], + [(26.909912, 1.000000), (27.736557, 1.000000)], + [(28.563202, 1.000000), (29.314220, 1.000000)], + [(30.065239, 1.000000), (30.735928, 1.000000)], + [(31.406620, 1.000000), (31.992788, 1.000000)], + [(32.578957, 1.000000), (33.076927, 1.000000)], + [(33.574905, 1.000000), (33.981567, 1.000000)], + [(34.388233, 1.000000), (34.701038, 1.000000)], + [(35.013851, 1.000000), (35.230850, 1.000000)], + [(35.447845, 1.000000), (35.567669, 1.000000)], + [(35.687500, 1.000000), (35.709404, 1.000000)], + [(35.731312, 1.000000), (35.655155, 1.000000)], + [(35.579006, 1.000000), (35.405273, 1.000000)], + [(35.231541, 1.000000), (34.961311, 1.000000)], + [(34.691086, 1.000000), (34.326057, 1.000000)], + [(33.961029, 1.000000), (33.503479, 1.000000)], + [(33.045937, 1.000000), (32.498734, 1.000000)], + [(31.951530, 1.000000), (31.318098, 1.000000)], + [(30.684669, 1.000000), (29.968971, 1.000000)], + [(29.253277, 1.000000), (28.459791, 1.000000)], + [(27.666309, 1.000000), (26.800005, 1.000000)], + [(25.933704, 1.000000), (25.000000, 1.000000)], + ]; + // Flat conic with a cusp: (1,1) (100,1) (25,1), weight: 1.5 + let bigger_flat_conic_as_quads = [ + // moveTo(1., 1.), + [(8.979845, 1.000000), (15.795975, 1.000000)], + [(22.612104, 1.000000), (28.363287, 1.000000)], + [(34.114471, 1.000000), (38.884045, 1.000000)], + [(43.653618, 1.000000), (47.510696, 1.000000)], + [(51.367767, 1.000000), (54.368233, 1.000000)], + [(57.368698, 1.000000), (59.556030, 1.000000)], + [(61.743366, 1.000000), (63.149269, 1.000000)], + [(64.555168, 1.000000), (65.200005, 1.000000)], + [(65.844841, 1.000000), (65.737961, 1.000000)], + [(65.631073, 1.000000), (64.770912, 1.000000)], + [(63.910763, 1.000000), (62.284878, 1.000000)], + [(60.658997, 1.000000), (58.243816, 1.000000)], + [(55.828640, 1.000000), (52.589172, 1.000000)], + [(49.349705, 1.000000), (45.239006, 1.000000)], + [(41.128315, 1.000000), (36.086826, 1.000000)], + [(31.045338, 1.000000), (25.000000, 1.000000)], + ]; + + let mut idx = 0; + let tolerance = 0.25; + for cubic in &tricky_cubics { + let x = (idx % NUM_COLS) as f64 * CELL_SIZE; + let y = (idx / NUM_COLS) as f64 * CELL_SIZE; + let cell = Rect::new(x, y, x + CELL_SIZE, y + CELL_SIZE); + let bounds = stroke_bounds(cubic); + let (t, s) = map_rect_to_rect(&bounds, &cell); + let style = Stroke::new(STROKE_WIDTH / s) + .with_caps(Cap::Butt) + .with_join(Join::Miter); + let mut path = BezPath::new(); + path.move_to(cubic[0]); + path.curve_to(cubic[1], cubic[2], cubic[3]); + let stroked = stroke(path, &style, &StrokeOpts::default(), tolerance); + println!( + " ", + (t * stroked).to_svg() + ); + idx += 1; + } + + let flat_curves = [ + flat_quad.as_slice(), + flat_conic_as_quads.as_slice(), + bigger_flat_conic_as_quads.as_slice(), + ]; + for quads in flat_curves.iter() { + let mut path = BezPath::new(); + path.move_to((1., 1.)); + for quad in quads.iter() { + path.quad_to(quad[0], quad[1]); + } + let x = (idx % NUM_COLS) as f64 * CELL_SIZE; + let y = (idx / NUM_COLS) as f64 * CELL_SIZE; + let cell = Rect::new(x, y, x + CELL_SIZE, y + CELL_SIZE); + let bounds = path.bounding_box().inflate(STROKE_WIDTH, STROKE_WIDTH); + let (t, s) = map_rect_to_rect(&bounds, &cell); + let style = Stroke::new(STROKE_WIDTH / s) + .with_caps(Cap::Butt) + .with_join(Join::Miter); + let stroked = stroke(path, &style, &StrokeOpts::default(), tolerance); + println!( + " ", + (t * stroked).to_svg() + ); + idx += 1; + } +} + +fn main() { + println!(""); + tricky_strokes(); + println!(""); +} diff --git a/vendor/kurbo/src/affine.rs b/vendor/kurbo/src/affine.rs new file mode 100644 index 0000000000..80b25430e3 --- /dev/null +++ b/vendor/kurbo/src/affine.rs @@ -0,0 +1,865 @@ +// Copyright 2018 the Kurbo Authors +// SPDX-License-Identifier: Apache-2.0 OR MIT + +//! Affine transforms. + +use core::ops::{Mul, MulAssign}; + +use crate::{Point, Rect, Vec2}; + +#[cfg(not(feature = "std"))] +use crate::common::FloatFuncs; + +/// A 2D affine transform. +#[derive(Clone, Copy, Debug, PartialEq)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +pub struct Affine([f64; 6]); + +impl Affine { + /// The identity transform. + pub const IDENTITY: Affine = Affine::scale(1.0); + + /// A transform that is flipped on the y-axis. Useful for converting between + /// y-up and y-down spaces. + pub const FLIP_Y: Affine = Affine::new([1.0, 0., 0., -1.0, 0., 0.]); + + /// A transform that is flipped on the x-axis. + pub const FLIP_X: Affine = Affine::new([-1.0, 0., 0., 1.0, 0., 0.]); + + /// Construct an affine transform from coefficients. + /// + /// If the coefficients are `(a, b, c, d, e, f)`, then the resulting + /// transformation represents this augmented matrix: + /// + /// ```text + /// | a c e | + /// | b d f | + /// | 0 0 1 | + /// ``` + /// + /// Note that this convention is transposed from PostScript and + /// Direct2D, but is consistent with the + /// [Wikipedia](https://en.wikipedia.org/wiki/Affine_transformation) + /// formulation of affine transformation as augmented matrix. The + /// idea is that `(A * B) * v == A * (B * v)`, where `*` is the + /// [`Mul`] trait. + #[inline(always)] + pub const fn new(c: [f64; 6]) -> Affine { + Affine(c) + } + + /// An affine transform representing uniform scaling. + #[inline(always)] + pub const fn scale(s: f64) -> Affine { + Affine([s, 0.0, 0.0, s, 0.0, 0.0]) + } + + /// An affine transform representing non-uniform scaling + /// with different scale values for x and y + #[inline(always)] + pub const fn scale_non_uniform(s_x: f64, s_y: f64) -> Affine { + Affine([s_x, 0.0, 0.0, s_y, 0.0, 0.0]) + } + + /// An affine transform representing a scale of `scale` about `center`. + /// + /// Useful for a view transform that zooms at a specific point, + /// while keeping that point fixed in the result space. + /// + /// See [`Affine::scale()`] for more info. + #[inline] + pub fn scale_about(s: f64, center: impl Into) -> Affine { + let center = center.into().to_vec2(); + Self::translate(-center) + .then_scale(s) + .then_translate(center) + } + + /// An affine transform representing rotation. + /// + /// The convention for rotation is that a positive angle rotates a + /// positive X direction into positive Y. Thus, in a Y-down coordinate + /// system (as is common for graphics), it is a clockwise rotation, and + /// in Y-up (traditional for math), it is anti-clockwise. + /// + /// The angle, `th`, is expressed in radians. + #[inline] + pub fn rotate(th: f64) -> Affine { + let (s, c) = th.sin_cos(); + Affine([c, s, -s, c, 0.0, 0.0]) + } + + /// An affine transform representing a rotation of `th` radians about `center`. + /// + /// See [`Affine::rotate()`] for more info. + #[inline] + pub fn rotate_about(th: f64, center: impl Into) -> Affine { + let center = center.into().to_vec2(); + Self::translate(-center) + .then_rotate(th) + .then_translate(center) + } + + /// An affine transform representing translation. + #[inline(always)] + pub fn translate>(p: V) -> Affine { + let p = p.into(); + Affine([1.0, 0.0, 0.0, 1.0, p.x, p.y]) + } + + /// An affine transformation representing a skew. + /// + /// The `skew_x` and `skew_y` parameters represent skew factors for the + /// horizontal and vertical directions, respectively. + /// + /// This is commonly used to generate a faux oblique transform for + /// font rendering. In this case, you can slant the glyph 20 degrees + /// clockwise in the horizontal direction (assuming a Y-up coordinate + /// system): + /// + /// ``` + /// let oblique_transform = kurbo::Affine::skew(20f64.to_radians().tan(), 0.0); + /// ``` + #[inline(always)] + pub const fn skew(skew_x: f64, skew_y: f64) -> Affine { + Affine([1.0, skew_y, skew_x, 1.0, 0.0, 0.0]) + } + + /// Create an affine transform that represents reflection about the line `point + direction * t, t in (-infty, infty)` + /// + /// # Examples + /// + /// ``` + /// # use kurbo::{Point, Vec2, Affine}; + /// # fn assert_near(p0: Point, p1: Point) { + /// # assert!((p1 - p0).hypot() < 1e-9, "{p0:?} != {p1:?}"); + /// # } + /// let point = Point::new(1., 0.); + /// let vec = Vec2::new(1., 1.); + /// let map = Affine::reflect(point, vec); + /// assert_near(map * Point::new(1., 0.), Point::new(1., 0.)); + /// assert_near(map * Point::new(2., 1.), Point::new(2., 1.)); + /// assert_near(map * Point::new(2., 2.), Point::new(3., 1.)); + /// ``` + #[inline] + #[must_use] + pub fn reflect(point: impl Into, direction: impl Into) -> Self { + let point = point.into(); + let direction = direction.into(); + + let n = Vec2 { + x: direction.y, + y: -direction.x, + } + .normalize(); + + // Compute Householder reflection matrix + let x2 = n.x * n.x; + let xy = n.x * n.y; + let y2 = n.y * n.y; + // Here we also add in the post translation, because it doesn't require any further calc. + let aff = Affine::new([ + 1. - 2. * x2, + -2. * xy, + -2. * xy, + 1. - 2. * y2, + point.x, + point.y, + ]); + aff.pre_translate(-point.to_vec2()) + } + + /// A [rotation] by `th` followed by `self`. + /// + /// Equivalent to `self * Affine::rotate(th)` + /// + /// [rotation]: Affine::rotate + #[inline] + #[must_use] + pub fn pre_rotate(self, th: f64) -> Self { + self * Affine::rotate(th) + } + + /// A [rotation] by `th` about `center` followed by `self`. + /// + /// Equivalent to `self * Affine::rotate_about(th, center)` + /// + /// [rotation]: Affine::rotate_about + #[inline] + #[must_use] + pub fn pre_rotate_about(self, th: f64, center: impl Into) -> Self { + self * Affine::rotate_about(th, center) + } + + /// A [scale] by `scale` followed by `self`. + /// + /// Equivalent to `self * Affine::scale(scale)` + /// + /// [scale]: Affine::scale + #[inline] + #[must_use] + pub fn pre_scale(self, scale: f64) -> Self { + self * Affine::scale(scale) + } + + /// A [scale] by `(scale_x, scale_y)` followed by `self`. + /// + /// Equivalent to `self * Affine::scale_non_uniform(scale_x, scale_y)` + /// + /// [scale]: Affine::scale_non_uniform + #[inline] + #[must_use] + pub fn pre_scale_non_uniform(self, scale_x: f64, scale_y: f64) -> Self { + self * Affine::scale_non_uniform(scale_x, scale_y) + } + + /// A [translation] of `trans` followed by `self`. + /// + /// Equivalent to `self * Affine::translate(trans)` + /// + /// [translation]: Affine::translate + #[inline] + #[must_use] + pub fn pre_translate(self, trans: Vec2) -> Self { + self * Affine::translate(trans) + } + + /// A [skew] of `(skew_x, skew_y)` followed by `self`. + /// + /// Equivalent to `self * Affine::skew(skew_x, skew_y)` + /// + /// [skew]: Affine::skew + #[inline] + #[must_use] + pub fn pre_skew(self, skew_x: f64, skew_y: f64) -> Self { + self * Affine::skew(skew_x, skew_y) + } + + /// A [reflection] about the line through `point` in `direction` followed by `self`. + /// + /// Equivalent to `self * Affine::reflect(point, direction)` + /// + /// [reflection]: Affine::reflect + #[inline] + #[must_use] + pub fn pre_reflect(self, point: impl Into, direction: impl Into) -> Self { + self * Affine::reflect(point, direction) + } + + /// `self` followed by a [rotation] of `th`. + /// + /// Equivalent to `Affine::rotate(th) * self` + /// + /// [rotation]: Affine::rotate + #[inline] + #[must_use] + pub fn then_rotate(self, th: f64) -> Self { + Affine::rotate(th) * self + } + + /// `self` followed by a [rotation] of `th` about `center`. + /// + /// Equivalent to `Affine::rotate_about(th, center) * self` + /// + /// [rotation]: Affine::rotate_about + #[inline] + #[must_use] + pub fn then_rotate_about(self, th: f64, center: impl Into) -> Self { + Affine::rotate_about(th, center) * self + } + + /// `self` followed by a [scale] of `scale`. + /// + /// Equivalent to `Affine::scale(scale) * self` + /// + /// [scale]: Affine::scale + #[inline] + #[must_use] + pub fn then_scale(self, scale: f64) -> Self { + Affine::scale(scale) * self + } + + /// `self` followed by a [scale] of `(scale_x, scale_y)`. + /// + /// Equivalent to `Affine::scale_non_uniform(scale_x, scale_y) * self` + /// + /// [scale]: Affine::scale_non_uniform + #[inline] + #[must_use] + pub fn then_scale_non_uniform(self, scale_x: f64, scale_y: f64) -> Self { + Affine::scale_non_uniform(scale_x, scale_y) * self + } + + /// `self` followed by a [scale] of `scale` about `center`. + /// + /// Equivalent to `Affine::scale_about(scale) * self` + /// + /// [scale]: Affine::scale_about + #[inline] + #[must_use] + pub fn then_scale_about(self, scale: f64, center: impl Into) -> Self { + Affine::scale_about(scale, center) * self + } + + /// `self` followed by a [skew] of `(skew_x, skew_y)`. + /// + /// Equivalent to `Affine::skew(skew_x, skew_y) * self` + /// + /// [skew]: Affine::skew + #[inline] + #[must_use] + pub fn then_skew(self, skew_x: f64, skew_y: f64) -> Self { + Affine::skew(skew_x, skew_y) * self + } + + /// `self` followed by a [reflection] about the line through `point` in `direction`. + /// + /// Equivalent to `Affine::reflect(point, direction) * self` + /// + /// [reflection]: Affine::reflect + #[inline] + #[must_use] + pub fn then_reflect(self, point: impl Into, direction: impl Into) -> Self { + Affine::reflect(point, direction) * self + } + + /// `self` followed by a translation of `trans`. + /// + /// Equivalent to `Affine::translate(trans) * self` + /// + /// [translation]: Affine::translate + #[inline] + #[must_use] + pub const fn then_translate(mut self, trans: Vec2) -> Self { + self.0[4] += trans.x; + self.0[5] += trans.y; + self + } + + /// Creates an affine transformation that takes the unit square to the given rectangle. + /// + /// Useful when you want to draw into the unit square but have your output fill any rectangle. + /// In this case push the `Affine` onto the transform stack. + pub const fn map_unit_square(rect: Rect) -> Affine { + Affine([rect.width(), 0., 0., rect.height(), rect.x0, rect.y0]) + } + + /// Get the coefficients of the transform. + #[inline(always)] + pub const fn as_coeffs(self) -> [f64; 6] { + self.0 + } + + /// Compute the determinant of this transform. + /// + /// # Geometric interpretation + /// + /// Consider a region transformed by this affine. The transformed region's area is the area of + /// the original region scaled by the absolute value of the determinant. A negative determinant + /// indicates orientation reversal. + #[inline] + pub const fn determinant(self) -> f64 { + self.0[0] * self.0[3] - self.0[1] * self.0[2] + } + + /// Compute the square of the nuclear norm of this transform. + /// + /// This is the square of the [Schatten p-norm][schatten] with `p=1`, also known as the "trace norm." + /// + /// Returns the squared norm for efficiency; take the square root as necessary. + /// + /// # Geometric interpretation + /// + /// Consider a unit circle transformed by this affine. The nuclear norm is the sum of the + /// resulting ellipse's radii (semi axes). That sum multiplied by π is a first-order + /// approximation of the ellipse's perimeter. + /// + /// [schatten]: + #[inline] + pub const fn nuclear_norm_squared(self) -> f64 { + self.frobenius_norm_squared() + 2. * self.determinant().abs() + } + + /// Compute the square of the Frobenius norm of this transform. + /// + /// This is the square of the [Schatten p-norm][schatten] with `p=2`. + /// + /// Returns the squared norm for efficiency; take the square root as necessary. + /// + /// # Geometric interpretation + /// + /// Consider a unit circle transformed by this affine. The squared Frobenius norm is twice the + /// mean squared radius of the resulting ellipse. Alternatively, it is equal to the squared + /// distance from the ellipse's center to a corner of the rectangle spanned by the ellipse's + /// axes. + /// + /// [schatten]: + #[inline] + pub const fn frobenius_norm_squared(self) -> f64 { + let [a, b, c, d, _, _] = self.as_coeffs(); + a * a + b * b + c * c + d * d + } + + /// Compute the spectral norm of this transform. + /// + /// This is the [Schatten p-norm][schatten] with `p=∞`. + /// + /// # Geometric interpretation + /// + /// Consider a unit circle transformed by this affine. The spectral norm is the major radius + /// (semi-major axis) of the Ellipse. + /// + /// [schatten]: + #[inline] + pub fn spectral_norm(self) -> f64 { + // Note a different calculation, returning the `_squared` form like our nuclear and + // Frobenius norms, could be `0.5 (frob^2 + sqrt(frob^4 - 4 det^2))`. In terms of operations + // it's a wash: one fewer sqrt if the user actually wants the squared form, but it uses more + // muls. More importantly, that form has worse numeric conditioning. + self.svd().0.x + } + + /// Compute the inverse transform. + /// + /// Produces NaN values when the determinant is zero. + pub const fn inverse(self) -> Affine { + let inv_det = self.determinant().recip(); + Affine([ + inv_det * self.0[3], + -inv_det * self.0[1], + -inv_det * self.0[2], + inv_det * self.0[0], + inv_det * (self.0[2] * self.0[5] - self.0[3] * self.0[4]), + inv_det * (self.0[1] * self.0[4] - self.0[0] * self.0[5]), + ]) + } + + /// Compute the bounding box of a transformed rectangle. + /// + /// Returns the minimal `Rect` that encloses the given `Rect` after affine transformation. + /// If the transform is axis-aligned, then this bounding box is "tight", in other words the + /// returned `Rect` is the transformed rectangle. + /// + /// The returned rectangle always has non-negative width and height. + pub fn transform_rect_bbox(self, rect: Rect) -> Rect { + let p00 = self * Point::new(rect.x0, rect.y0); + let p01 = self * Point::new(rect.x0, rect.y1); + let p10 = self * Point::new(rect.x1, rect.y0); + let p11 = self * Point::new(rect.x1, rect.y1); + Rect::from_points(p00, p01).union(Rect::from_points(p10, p11)) + } + + /// Is this map [finite]? + /// + /// [finite]: f64::is_finite + #[inline] + pub const fn is_finite(&self) -> bool { + self.0[0].is_finite() + && self.0[1].is_finite() + && self.0[2].is_finite() + && self.0[3].is_finite() + && self.0[4].is_finite() + && self.0[5].is_finite() + } + + /// Is this map [NaN]? + /// + /// [NaN]: f64::is_nan + #[inline] + pub const fn is_nan(&self) -> bool { + self.0[0].is_nan() + || self.0[1].is_nan() + || self.0[2].is_nan() + || self.0[3].is_nan() + || self.0[4].is_nan() + || self.0[5].is_nan() + } + + /// Compute the singular value decomposition of the linear transformation (ignoring the + /// translation). + /// + /// All non-degenerate linear transformations can be represented as + /// + /// 1. a rotation about the origin. + /// 2. a scaling along the x and y axes + /// 3. another rotation about the origin + /// + /// composed together. Decomposing a 2x2 matrix in this way is called a "singular value + /// decomposition" and is written `U Σ V^T`, where U and V^T are orthogonal (rotations) and Σ + /// is a diagonal matrix (a scaling). + /// + /// Since currently this function is used to calculate ellipse radii and rotation from an + /// affine map on the unit circle, we don't calculate V^T, since a rotation of the unit (or + /// any) circle about its center always results in the same circle. This is the reason that an + /// ellipse mapped using an affine map is always an ellipse. + /// + /// Will return NaNs if the matrix (or equivalently the linear map) is non-finite. + /// + /// The first part of the returned tuple is the scaling, the second part is the angle of + /// rotation (in radians). The scaling along the x-axis is guaranteed to be greater than or + /// equal to the scaling along the y-axis. + // + // Note: though this does quite some computation, we are often interested only in specific + // components of the result. Hence this is marked `#[inline(always)]`, to give the compiler a + // good chance at eliminating dead code. + #[inline(always)] + pub(crate) fn svd(self) -> (Vec2, f64) { + let [a, b, c, d, _, _] = self.0; + let a2 = a * a; + let b2 = b * b; + let c2 = c * c; + let d2 = d * d; + let ab = a * b; + let cd = c * d; + let angle = 0.5 * (2.0 * (ab + cd)).atan2(a2 - b2 + c2 - d2); + + // Given matrix A = [ a c ] + // [ b d ] + // + // The two singular values σ1, σ2 of A are the square roots of the two eigen values λ1, λ2 + // of M = A^T A. The common formula for 2x2 eigenvalues requires evaluating a square root, + // but we'd like to compute the singular values of the matrix without nested square roots. + // + // M = A^T A = [ aa+cc ab+cd ] + // [ ab+cd bb+dd ] + // + // We have + // λ = 1/2 (tr(M) ± sqrt(tr(M)^2 - 4 det(M))). + // + // Note det(M) = det(A^T A) = det(A)^2. + // => 2λ = tr(M) ± sqrt(tr(M)^2 - 4 det(A)^2) + // => 2λ = tr(M) ± sqrt[(a^2+b^2+c^2+d^2)^2 - 4 (ad-bc)^2] + // By factorizing the inner term, + // => 2λ = tr(M) ± sqrt[((a+d)^2 + (b-c)^2) ((a-d)^2 + (b+c)^2)] + // => 2λ = tr(M) ± sqrt[(a+d)^2 + (b-c)^2] sqrt[(a-d)^2 + (b+c)^2] + // + // Define S1 = sqrt[(a+d)^2 + (b-c)^2] + // S2 = sqrt[(a-d)^2 + (b+c)^2]. + // + // => 2λ = tr(M) ± S1 S2 + // => 2λ = 1/2 (S1^2 + S2^2) ± S1 S2 + // => λ = 1/4 (S1^2 + S2^2 ± 2 S1 S2) + // => λ = 1/4 (S1 ± S2)^2 + // + // Note we're interested in + // σ = sqrt(λ). + // + // => σ1 = 1/2 (S1 + S2) + // and similarly σ2 = 1/2 |S1 - S2| + let s1 = ((a + d).powi(2) + (b - c).powi(2)).sqrt(); + let s2 = ((a - d).powi(2) + (b + c).powi(2)).sqrt(); + ( + Vec2 { + x: 0.5 * (s1 + s2), + y: 0.5 * (s1 - s2).abs(), + }, + angle, + ) + } + + /// Returns the translation part of this affine map (`(self.0[4], self.0[5])`). + #[inline(always)] + pub const fn translation(self) -> Vec2 { + Vec2 { + x: self.0[4], + y: self.0[5], + } + } + + /// Replaces the translation portion of this affine map + /// + /// The translation can be seen as being applied after the linear part of the map. + #[must_use] + #[inline(always)] + pub const fn with_translation(mut self, trans: Vec2) -> Affine { + self.0[4] = trans.x; + self.0[5] = trans.y; + self + } +} + +impl Default for Affine { + #[inline(always)] + fn default() -> Affine { + Affine::IDENTITY + } +} + +impl Mul for Affine { + type Output = Point; + + #[inline] + fn mul(self, other: Point) -> Point { + Point::new( + self.0[0] * other.x + self.0[2] * other.y + self.0[4], + self.0[1] * other.x + self.0[3] * other.y + self.0[5], + ) + } +} + +impl Mul for Affine { + type Output = Affine; + + #[inline] + fn mul(self, other: Affine) -> Affine { + Affine([ + self.0[0] * other.0[0] + self.0[2] * other.0[1], + self.0[1] * other.0[0] + self.0[3] * other.0[1], + self.0[0] * other.0[2] + self.0[2] * other.0[3], + self.0[1] * other.0[2] + self.0[3] * other.0[3], + self.0[0] * other.0[4] + self.0[2] * other.0[5] + self.0[4], + self.0[1] * other.0[4] + self.0[3] * other.0[5] + self.0[5], + ]) + } +} + +impl MulAssign for Affine { + #[inline] + fn mul_assign(&mut self, other: Affine) { + *self = self.mul(other); + } +} + +impl Mul for f64 { + type Output = Affine; + + #[inline] + fn mul(self, other: Affine) -> Affine { + Affine([ + self * other.0[0], + self * other.0[1], + self * other.0[2], + self * other.0[3], + self * other.0[4], + self * other.0[5], + ]) + } +} + +// Conversions to and from mint +#[cfg(feature = "mint")] +impl From for mint::ColumnMatrix2x3 { + #[inline(always)] + fn from(a: Affine) -> mint::ColumnMatrix2x3 { + mint::ColumnMatrix2x3 { + x: mint::Vector2 { + x: a.0[0], + y: a.0[1], + }, + y: mint::Vector2 { + x: a.0[2], + y: a.0[3], + }, + z: mint::Vector2 { + x: a.0[4], + y: a.0[5], + }, + } + } +} + +#[cfg(feature = "mint")] +impl From> for Affine { + #[inline(always)] + fn from(m: mint::ColumnMatrix2x3) -> Affine { + Affine([m.x.x, m.x.y, m.y.x, m.y.y, m.z.x, m.z.y]) + } +} + +#[cfg(test)] +mod tests { + use crate::{Affine, Point, Vec2}; + use std::f64::consts::PI; + + fn assert_near(p0: Point, p1: Point) { + assert!((p1 - p0).hypot() < 1e-9, "{p0:?} != {p1:?}"); + } + + fn affine_assert_near(a0: Affine, a1: Affine) { + for i in 0..6 { + assert!((a0.0[i] - a1.0[i]).abs() < 1e-9, "{a0:?} != {a1:?}"); + } + } + + #[test] + fn affine_basic() { + let p = Point::new(3.0, 4.0); + + assert_near(Affine::default() * p, p); + assert_near(Affine::scale(2.0) * p, Point::new(6.0, 8.0)); + assert_near(Affine::rotate(0.0) * p, p); + assert_near(Affine::rotate(PI / 2.0) * p, Point::new(-4.0, 3.0)); + assert_near(Affine::translate((5.0, 6.0)) * p, Point::new(8.0, 10.0)); + assert_near(Affine::skew(0.0, 0.0) * p, p); + assert_near(Affine::skew(2.0, 4.0) * p, Point::new(11.0, 16.0)); + } + + #[test] + fn affine_mul() { + let a1 = Affine::new([1.0, 2.0, 3.0, 4.0, 5.0, 6.0]); + let a2 = Affine::new([0.1, 1.2, 2.3, 3.4, 4.5, 5.6]); + + let px = Point::new(1.0, 0.0); + let py = Point::new(0.0, 1.0); + let pxy = Point::new(1.0, 1.0); + assert_near(a1 * (a2 * px), (a1 * a2) * px); + assert_near(a1 * (a2 * py), (a1 * a2) * py); + assert_near(a1 * (a2 * pxy), (a1 * a2) * pxy); + } + + #[test] + fn affine_inv() { + let a = Affine::new([0.1, 1.2, 2.3, 3.4, 4.5, 5.6]); + let a_inv = a.inverse(); + + let px = Point::new(1.0, 0.0); + let py = Point::new(0.0, 1.0); + let pxy = Point::new(1.0, 1.0); + assert_near(a * (a_inv * px), px); + assert_near(a * (a_inv * py), py); + assert_near(a * (a_inv * pxy), pxy); + assert_near(a_inv * (a * px), px); + assert_near(a_inv * (a * py), py); + assert_near(a_inv * (a * pxy), pxy); + } + + #[test] + fn reflection() { + affine_assert_near( + Affine::reflect(Point::ZERO, (1., 0.)), + Affine::new([1., 0., 0., -1., 0., 0.]), + ); + affine_assert_near( + Affine::reflect(Point::ZERO, (0., 1.)), + Affine::new([-1., 0., 0., 1., 0., 0.]), + ); + // y = x + affine_assert_near( + Affine::reflect(Point::ZERO, (1., 1.)), + Affine::new([0., 1., 1., 0., 0., 0.]), + ); + + // no translate + let point = Point::new(0., 0.); + let vec = Vec2::new(1., 1.); + let map = Affine::reflect(point, vec); + assert_near(map * Point::new(0., 0.), Point::new(0., 0.)); + assert_near(map * Point::new(1., 1.), Point::new(1., 1.)); + assert_near(map * Point::new(1., 2.), Point::new(2., 1.)); + + // with translate + let point = Point::new(1., 0.); + let vec = Vec2::new(1., 1.); + let map = Affine::reflect(point, vec); + assert_near(map * Point::new(1., 0.), Point::new(1., 0.)); + assert_near(map * Point::new(2., 1.), Point::new(2., 1.)); + assert_near(map * Point::new(2., 2.), Point::new(3., 1.)); + } + + #[test] + fn svd() { + let a = Affine::new([1., 2., 3., 4., 5., 6.]); + let a_no_translate = a.with_translation(Vec2::ZERO); + + // translation should have no effect + let (scale, rotation) = a.svd(); + let (scale_no_translate, rotation_no_translate) = a_no_translate.svd(); + assert_near(scale.to_point(), scale_no_translate.to_point()); + assert!((rotation - rotation_no_translate).abs() <= 1e-9); + + assert_near( + scale.to_point(), + Point::new(5.4649857042190427, 0.36596619062625782), + ); + assert!((rotation - 0.95691013360780001).abs() <= 1e-9); + + // singular affine + let a = Affine::new([0., 0., 0., 0., 5., 6.]); + assert_eq!(a.determinant(), 0.); + let (scale, rotation) = a.svd(); + assert_eq!(scale, Vec2::new(0., 0.)); + assert_eq!(rotation, 0.); + } + + #[test] + fn svd_singular_values() { + // Test a few known singular values. + let mat = |a, b, c, d| Affine::new([a, b, c, d, 0., 0.]); + + let s = mat(1., 0., 0., 1.).svd().0; + assert_near(s.to_point(), Point::new(1., 1.)); + + let s = mat(1., 0., 0., -1.).svd().0; + assert_near(s.to_point(), Point::new(1., 1.)); + + let s = mat(1., 1., 1., 1.).svd().0; + assert_near(s.to_point(), Point::new(2., 0.)); + + let s = mat(1., 1., 1., 1.).svd().0; + assert_near(s.to_point(), Point::new(2., 0.)); + + let s = mat(0., 0., 1., 0.).svd().0; + assert_near(s.to_point(), Point::new(1., 0.)); + + // The singular values are the scaling of the affine map. So let's test that. + let s = Affine::scale_non_uniform(4., 8.) + .then_rotate_about(42_f64.to_radians(), (-2., 50.)) + .svd() + .0; + assert_near(s.to_point(), Point::new(8., 4.)); + + // Correctly handles negative scaling (singular values are necessarily non-negative). + let s = Affine::scale_non_uniform(-20., 3.).svd().0; + assert_near(s.to_point(), Point::new(20., 3.)); + let s = Affine::scale_non_uniform(-20., -3.).svd().0; + assert_near(s.to_point(), Point::new(20., 3.)); + let s = Affine::scale_non_uniform(20., -3.).svd().0; + assert_near(s.to_point(), Point::new(20., 3.)); + + // One more property: given a full-rank transform, the product of its singular values + // should be equal to its absolute determinant. + let m = mat(10., 9., -2.5, 3.3333); + let s = m.svd().0; + let prod = s.x * s.y; + let det = m.determinant().abs(); + assert!( + (prod - det) < 1e-9, + "The product of the singular values {s:?} ({prod}) should be equal to the absolute determinant {det}.", + ); + } + + #[test] + fn rotate_about_composition() { + let theta = core::f64::consts::FRAC_PI_2; + let center = Point::new(-1., 0.); + let translation = Vec2::new(0., 1.); + let probe = Point::ORIGIN; + + let rotate_about = Affine::rotate_about(theta, center); + let translate = Affine::translate(translation); + + // Establish baselines with raw matrix composition + // (also a sanity check to ensure the order of ops matters for this contrived test) + let rotate_then_translate = translate * rotate_about; + let translate_then_rotate = rotate_about * translate; + assert_near(rotate_then_translate * probe, Point::new(-1., 2.)); + assert_near(translate_then_rotate * probe, Point::new(-2., 1.)); + + // Check .then_* semantics + affine_assert_near( + rotate_about.then_translate(translation), + rotate_then_translate, + ); + affine_assert_near( + translate.then_rotate_about(theta, center), + translate_then_rotate, + ); + + // Check .pre_rotate_about semantics + affine_assert_near( + translate.pre_rotate_about(theta, center), + rotate_then_translate, + ); + } +} diff --git a/vendor/kurbo/src/arc.rs b/vendor/kurbo/src/arc.rs new file mode 100644 index 0000000000..0704deb156 --- /dev/null +++ b/vendor/kurbo/src/arc.rs @@ -0,0 +1,341 @@ +// Copyright 2019 the Kurbo Authors +// SPDX-License-Identifier: Apache-2.0 OR MIT + +//! An ellipse arc. + +use crate::{Affine, Ellipse, ParamCurve, PathEl, Point, Rect, Shape, Vec2}; +use core::{ + f64::consts::{FRAC_PI_2, PI}, + iter, + ops::{Mul, Range}, +}; + +#[cfg(not(feature = "std"))] +use crate::common::FloatFuncs; + +/// A single elliptical arc segment. +#[derive(Clone, Copy, Debug, PartialEq)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +pub struct Arc { + /// The arc's centre point. + pub center: Point, + /// The arc's radii, where the vector's x-component is the radius in the + /// positive x direction after applying `x_rotation`. + pub radii: Vec2, + /// The start angle in radians. + pub start_angle: f64, + /// The angle between the start and end of the arc, in radians. + pub sweep_angle: f64, + /// How much the arc is rotated, in radians. + pub x_rotation: f64, +} + +impl Arc { + /// Create a new `Arc`. + #[inline(always)] + pub fn new( + center: impl Into, + radii: impl Into, + start_angle: f64, + sweep_angle: f64, + x_rotation: f64, + ) -> Self { + Self { + center: center.into(), + radii: radii.into(), + start_angle, + sweep_angle, + x_rotation, + } + } + + /// Returns a copy of this `Arc` in the opposite direction. + /// + /// The new `Arc` will sweep towards the original `Arc`s + /// start angle. + #[must_use] + #[inline] + pub fn reversed(&self) -> Arc { + Self { + center: self.center, + radii: self.radii, + start_angle: self.start_angle + self.sweep_angle, + sweep_angle: -self.sweep_angle, + x_rotation: self.x_rotation, + } + } + + #[inline] + fn angle_at(&self, t: f64) -> f64 { + self.start_angle + self.sweep_angle * t + } + + /// Create an iterator generating Bezier path elements. + /// + /// The generated elements can be appended to an existing bezier path. + pub fn append_iter(&self, tolerance: f64) -> ArcAppendIter { + let sign = self.sweep_angle.signum(); + let scaled_err = self.radii.x.max(self.radii.y) / tolerance; + // Number of subdivisions per ellipse based on error tolerance. + // Note: this may slightly underestimate the error for quadrants. + let n_err = (1.1163 * scaled_err).powf(1.0 / 6.0).max(3.999_999); + let n = (n_err * self.sweep_angle.abs() * (1.0 / (2.0 * PI))).ceil(); + let angle_step = self.sweep_angle / n; + let n = n as usize; + let arm_len = (4.0 / 3.0) * (0.25 * angle_step).abs().tan() * sign; + let angle0 = self.start_angle; + let p0 = sample_ellipse(self.radii, self.x_rotation, angle0); + + ArcAppendIter { + idx: 0, + + center: self.center, + radii: self.radii, + x_rotation: self.x_rotation, + n, + arm_len, + angle_step, + + p0, + angle0, + } + } + + /// Converts an `Arc` into a series of cubic bezier segments. + /// + /// The closure `p` will be invoked with the control points for each segment. + pub fn to_cubic_beziers

(self, tolerance: f64, mut p: P) + where + P: FnMut(Point, Point, Point), + { + let mut path = self.append_iter(tolerance); + while let Some(PathEl::CurveTo(p1, p2, p3)) = path.next() { + p(p1, p2, p3); + } + } +} + +#[doc(hidden)] +pub struct ArcAppendIter { + idx: usize, + + center: Point, + radii: Vec2, + x_rotation: f64, + n: usize, + arm_len: f64, + angle_step: f64, + + p0: Vec2, + angle0: f64, +} + +impl Iterator for ArcAppendIter { + type Item = PathEl; + + fn next(&mut self) -> Option { + if self.idx >= self.n { + return None; + } + + let angle1 = self.angle0 + self.angle_step; + let p0 = self.p0; + let p1 = p0 + + self.arm_len * sample_ellipse(self.radii, self.x_rotation, self.angle0 + FRAC_PI_2); + let p3 = sample_ellipse(self.radii, self.x_rotation, angle1); + let p2 = + p3 - self.arm_len * sample_ellipse(self.radii, self.x_rotation, angle1 + FRAC_PI_2); + + self.angle0 = angle1; + self.p0 = p3; + self.idx += 1; + + Some(PathEl::CurveTo( + self.center + p1, + self.center + p2, + self.center + p3, + )) + } +} + +/// Take the ellipse radii, how the radii are rotated, and the sweep angle, and return a point on +/// the ellipse. +fn sample_ellipse(radii: Vec2, x_rotation: f64, angle: f64) -> Vec2 { + let (angle_sin, angle_cos) = angle.sin_cos(); + let u = radii.x * angle_cos; + let v = radii.y * angle_sin; + rotate_pt(Vec2::new(u, v), x_rotation) +} + +/// Rotate `pt` about the origin by `angle` radians. +fn rotate_pt(pt: Vec2, angle: f64) -> Vec2 { + let (angle_sin, angle_cos) = angle.sin_cos(); + Vec2::new( + pt.x * angle_cos - pt.y * angle_sin, + pt.x * angle_sin + pt.y * angle_cos, + ) +} + +impl ParamCurve for Arc { + fn eval(&self, t: f64) -> Point { + self.center + sample_ellipse(self.radii, self.x_rotation, self.angle_at(t)) + } + + fn subsegment(&self, range: Range) -> Self { + Self { + center: self.center, + radii: self.radii, + start_angle: self.angle_at(range.start), + sweep_angle: self.sweep_angle * (range.end - range.start), + x_rotation: self.x_rotation, + } + } +} + +impl Shape for Arc { + type PathElementsIter<'iter> = iter::Chain, ArcAppendIter>; + + fn path_elements(&self, tolerance: f64) -> Self::PathElementsIter<'_> { + iter::once(PathEl::MoveTo(self.start())).chain(self.append_iter(tolerance)) + } + + /// Note: shape isn't closed so area is not well defined. + #[inline] + fn area(&self) -> f64 { + let Vec2 { x, y } = self.radii; + PI * x * y + } + + /// The perimeter of the arc. + /// + /// For now we just approximate by using the bezier curve representation. + #[inline] + fn perimeter(&self, accuracy: f64) -> f64 { + self.path_segments(0.1).perimeter(accuracy) + } + + /// Note: shape isn't closed, so a point's winding number is not well defined. + #[inline] + fn winding(&self, pt: Point) -> i32 { + self.path_segments(0.1).winding(pt) + } + + #[inline] + fn bounding_box(&self) -> Rect { + self.path_segments(0.1).bounding_box() + } +} + +impl Mul for Affine { + type Output = Arc; + + fn mul(self, arc: Arc) -> Self::Output { + let ellipse = self * Ellipse::new(arc.center, arc.radii, arc.x_rotation); + let center = ellipse.center(); + let (radii, rotation) = ellipse.radii_and_rotation(); + Arc { + center, + radii, + x_rotation: rotation, + start_angle: arc.start_angle, + sweep_angle: arc.sweep_angle, + } + } +} + +#[cfg(test)] +mod tests { + use core::f64::consts::{FRAC_PI_4, FRAC_PI_6}; + + use crate::ParamCurve; + + use super::*; + + fn assert_point_near(actual: Point, expected: Point) { + let epsilon = 1e-12; + assert!( + actual.distance(expected) <= epsilon, + "expected {expected:?}, got {actual:?}" + ); + } + + fn assert_subsegment_matches(arc: Arc, range: Range) { + let subsegment = arc.subsegment(range.clone()); + for t in [0.0, 0.25, 0.5, 1.0] { + let expected_t = range.start + (range.end - range.start) * t; + assert_point_near(subsegment.eval(t), arc.eval(expected_t)); + } + assert_point_near(subsegment.start(), arc.eval(range.start)); + assert_point_near(subsegment.end(), arc.eval(range.end)); + } + + #[test] + fn reversed_arc() { + let a = Arc::new((0., 0.), (1., 0.), 0., PI, 0.); + let f = a.reversed(); + + // Most fields should be unchanged: + assert_eq!(a.center, f.center); + assert_eq!(a.radii, f.radii); + assert_eq!(a.x_rotation, f.x_rotation); + + // Sweep angle should be in reverse + assert_eq!(a.sweep_angle, -f.sweep_angle); + + // Reversing it again should result in the original arc + assert_eq!(a, f.reversed()); + } + + #[test] + fn eval_endpoints_and_midpoint() { + let arc = Arc::new((3.0, -2.0), (4.0, 1.5), FRAC_PI_6, PI, 0.0); + assert_point_near(arc.eval(0.0), arc.start()); + assert_point_near(arc.eval(1.0), arc.end()); + assert_point_near( + arc.eval(0.5), + arc.center + sample_ellipse(arc.radii, arc.x_rotation, arc.angle_at(0.5)), + ); + } + + #[test] + fn eval_rotated_ellipse() { + let arc = Arc::new((5.0, 7.0), (3.0, 2.0), FRAC_PI_6, PI / 3.0, FRAC_PI_4); + assert_point_near( + arc.start(), + arc.center + sample_ellipse(arc.radii, arc.x_rotation, arc.start_angle), + ); + assert_point_near( + arc.end(), + arc.center + + sample_ellipse(arc.radii, arc.x_rotation, arc.start_angle + arc.sweep_angle), + ); + } + + #[test] + fn eval_reversed_arc() { + let arc = Arc::new((2.0, 3.0), (4.0, 1.0), FRAC_PI_6, PI / 2.0, FRAC_PI_4); + let reversed = arc.reversed(); + assert_point_near(reversed.start(), arc.end()); + assert_point_near(reversed.end(), arc.start()); + assert_point_near(reversed.eval(0.5), arc.eval(0.5)); + } + + #[test] + fn subsegment_matches_original() { + let arc = Arc::new((1.0, -4.0), (3.0, 2.0), -FRAC_PI_4, PI, FRAC_PI_6); + assert_subsegment_matches(arc, 0.2..0.7); + } + + #[test] + fn subsegment_negative_sweep_matches_original() { + let arc = Arc::new((1.0, 2.0), (5.0, 3.0), PI, -0.75 * PI, FRAC_PI_6); + assert_subsegment_matches(arc, 0.1..0.8); + } + + #[test] + fn subsegment_tiny_sweep_matches_original() { + let arc = Arc::new((0.0, 0.0), (2.0, 1.0), 1.0, 1e-9, FRAC_PI_4); + assert_subsegment_matches(arc, 0.25..0.75); + } +} diff --git a/vendor/kurbo/src/axis.rs b/vendor/kurbo/src/axis.rs new file mode 100644 index 0000000000..91a802e1b8 --- /dev/null +++ b/vendor/kurbo/src/axis.rs @@ -0,0 +1,72 @@ +// Copyright 2025 the Kurbo Authors +// SPDX-License-Identifier: Apache-2.0 OR MIT + +use crate::{Point, Size, Vec2}; + +/// An axis in the plane. +#[derive(Copy, Clone, PartialEq, Eq, Debug, Hash)] +pub enum Axis { + /// The x axis. + Horizontal, + /// The y axis. + Vertical, +} + +impl Axis { + /// Get the axis perpendicular to this one. + #[inline] + pub const fn cross(self) -> Self { + match self { + Self::Horizontal => Self::Vertical, + Self::Vertical => Self::Horizontal, + } + } + + /// Create a new [`Point`] by arranging the given magnitudes. + /// + /// The axis value is the one matching the axis (e.g. `y` for [`Self::Vertical`]). + /// The cross value is the other one. + #[inline] + pub const fn pack_point(self, axis_value: f64, cross_value: f64) -> Point { + match self { + Self::Horizontal => Point::new(axis_value, cross_value), + Self::Vertical => Point::new(cross_value, axis_value), + } + } + + /// Create a new [`Size`] by arranging the given magnitudes. + /// + /// The axis value is the one matching the axis (e.g. `height` for [`Self::Vertical`]). + /// The cross value is the other one. + #[inline] + pub const fn pack_size(self, axis_value: f64, cross_value: f64) -> Size { + match self { + Self::Horizontal => Size::new(axis_value, cross_value), + Self::Vertical => Size::new(cross_value, axis_value), + } + } + + /// Create a new [`Vec2`] by arranging the given magnitudes. + /// + /// The axis value is the one matching the axis (e.g. `y` for [`Self::Vertical`]). + /// The cross value is the other one. + #[inline] + pub const fn pack_vec2(self, axis_value: f64, cross_value: f64) -> Vec2 { + match self { + Self::Horizontal => Vec2::new(axis_value, cross_value), + Self::Vertical => Vec2::new(cross_value, axis_value), + } + } + + /// Create a new `(x, y)` pair by arranging the given magnitudes. + /// + /// The axis value is the one matching the axis (e.g. `y` for [`Self::Vertical`]). + /// The cross value is the other one. + #[inline] + pub const fn pack_xy(self, axis_value: f64, cross_value: f64) -> (f64, f64) { + match self { + Self::Horizontal => (axis_value, cross_value), + Self::Vertical => (cross_value, axis_value), + } + } +} diff --git a/vendor/kurbo/src/bezpath.rs b/vendor/kurbo/src/bezpath.rs new file mode 100644 index 0000000000..a290df1f4e --- /dev/null +++ b/vendor/kurbo/src/bezpath.rs @@ -0,0 +1,2311 @@ +// Copyright 2018 the Kurbo Authors +// SPDX-License-Identifier: Apache-2.0 OR MIT + +//! Bézier paths (up to cubic). + +#![allow(clippy::many_single_char_names)] + +use core::iter::{Extend, FromIterator}; +use core::mem; +use core::ops::{Mul, Range}; + +use alloc::vec::Vec; + +use arrayvec::ArrayVec; + +use crate::MAX_EXTREMA; +use crate::common::{solve_cubic, solve_quadratic}; +use crate::{ + Affine, CubicBez, Line, Nearest, ParamCurve, ParamCurveArclen, ParamCurveArea, + ParamCurveExtrema, ParamCurveNearest, Point, QuadBez, Rect, Shape, TranslateScale, Vec2, +}; + +#[cfg(not(feature = "std"))] +use crate::common::FloatFuncs; + +/// A Bézier path. +/// +/// These docs assume basic familiarity with Bézier curves; for an introduction, +/// see Pomax's wonderful [A Primer on Bézier Curves]. +/// +/// This path can contain lines, quadratics ([`QuadBez`]) and cubics +/// ([`CubicBez`]), and may contain multiple subpaths. +/// +/// # Elements and Segments +/// +/// A Bézier path can be represented in terms of either 'elements' ([`PathEl`]) +/// or 'segments' ([`PathSeg`]). Elements map closely to how Béziers are +/// generally used in PostScript-style drawing APIs; they can be thought of as +/// instructions for drawing the path. Segments more directly describe the +/// path itself, with each segment being an independent line or curve. +/// +/// These different representations are useful in different contexts. +/// For tasks like drawing, elements are a natural fit, but when doing +/// hit-testing or subdividing, we need to have access to the segments. +/// +/// Conceptually, a `BezPath` contains zero or more subpaths. Each subpath +/// *always* begins with a `MoveTo`, then has zero or more `LineTo`, `QuadTo`, +/// and `CurveTo` elements, and optionally ends with a `ClosePath`. +/// +/// Internally, a `BezPath` is a list of [`PathEl`]s; as such it implements +/// [`FromIterator`] and [`Extend`]: +/// +/// ``` +/// use kurbo::{BezPath, Rect, Shape, Vec2}; +/// let accuracy = 0.1; +/// let rect = Rect::from_origin_size((0., 0.,), (10., 10.)); +/// // these are equivalent +/// let path1 = rect.to_path(accuracy); +/// let path2: BezPath = rect.path_elements(accuracy).collect(); +/// +/// // extend a path with another path: +/// let mut path = rect.to_path(accuracy); +/// let shifted_rect = rect + Vec2::new(5.0, 10.0); +/// path.extend(shifted_rect.to_path(accuracy)); +/// ``` +/// +/// You can iterate the elements of a `BezPath` with the [`iter`] method, +/// and the segments with the [`segments`] method: +/// +/// ``` +/// use kurbo::{BezPath, Line, PathEl, PathSeg, Point, Rect, Shape}; +/// let accuracy = 0.1; +/// let rect = Rect::from_origin_size((0., 0.,), (10., 10.)); +/// // these are equivalent +/// let path = rect.to_path(accuracy); +/// let first_el = PathEl::MoveTo(Point::ZERO); +/// let first_seg = PathSeg::Line(Line::new((0., 0.), (10., 0.))); +/// assert_eq!(path.iter().next(), Some(first_el)); +/// assert_eq!(path.segments().next(), Some(first_seg)); +/// ``` +/// In addition, if you have some other type that implements +/// `Iterator`, you can adapt that to an iterator of segments with +/// the [`segments` free function]. +/// +/// # Advanced functionality +/// +/// In addition to the basic API, there are several useful pieces of advanced +/// functionality available on `BezPath`: +/// +/// - [`flatten`] does Bézier flattening, converting a curve to a series of +/// line segments +/// - [`intersect_line`] computes intersections of a path with a line, useful +/// for things like subdividing +/// +/// [A Primer on Bézier Curves]: https://pomax.github.io/bezierinfo/ +/// [`iter`]: BezPath::iter +/// [`segments`]: BezPath::segments +/// [`flatten`]: flatten +/// [`intersect_line`]: PathSeg::intersect_line +/// [`segments` free function]: segments +/// [`FromIterator`]: std::iter::FromIterator +/// [`Extend`]: std::iter::Extend +#[derive(Clone, Default, Debug, PartialEq)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +pub struct BezPath(Vec); + +/// The element of a Bézier path. +/// +/// A valid path has `MoveTo` at the beginning of each subpath. +#[derive(Clone, Copy, Debug, PartialEq)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +pub enum PathEl { + /// Move directly to the point without drawing anything, starting a new + /// subpath. + MoveTo(Point), + /// Draw a line from the current location to the point. + LineTo(Point), + /// Draw a quadratic Bézier using the current location and the two points. + /// + /// The first point is the Bézier's control point, the second is its end point. + QuadTo(Point, Point), + /// Draw a cubic Bézier using the current location and the three points. + /// + /// The first two points are the Bézier's control points, the last point is its end point. + CurveTo(Point, Point, Point), + /// Close off the path. + ClosePath, +} + +/// A segment of a Bézier path. +#[derive(Clone, Copy, Debug, PartialEq)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +pub enum PathSeg { + /// A line segment. + Line(Line), + /// A quadratic Bézier segment. + Quad(QuadBez), + /// A cubic Bézier segment. + Cubic(CubicBez), +} + +/// An intersection of a [`Line`] and a [`PathSeg`]. +/// +/// This can be generated with the [`PathSeg::intersect_line`] method. +#[derive(Debug, Clone, Copy)] +pub struct LineIntersection { + /// The 'time' that the intersection occurs, on the line. + /// + /// This value is in the range 0..1. + pub line_t: f64, + + /// The 'time' that the intersection occurs, on the path segment. + /// + /// This value is nominally in the range 0..1, although it may slightly exceed + /// that range at the boundaries of segments. + pub segment_t: f64, +} + +/// The minimum distance between two Bézier curves. +pub struct MinDistance { + /// The shortest distance between any two points on the two curves. + pub distance: f64, + /// The position of the nearest point on the first curve, as a parameter. + /// + /// To resolve this to a [`Point`], use [`ParamCurve::eval`]. + /// + /// [`ParamCurve::eval`]: crate::ParamCurve::eval + pub t1: f64, + /// The position of the nearest point on the second curve, as a parameter. + /// + /// To resolve this to a [`Point`], use [`ParamCurve::eval`]. + /// + /// [`ParamCurve::eval`]: crate::ParamCurve::eval + pub t2: f64, +} + +impl BezPath { + /// Create a new path. + #[inline(always)] + pub fn new() -> BezPath { + BezPath::default() + } + + /// Create a new path with the specified capacity. + /// + /// This can be useful if you already know how many path elements the path + /// will consist of, to prevent reallocations. + pub fn with_capacity(capacity: usize) -> BezPath { + BezPath(Vec::with_capacity(capacity)) + } + + /// Create a path from a vector of path elements. + /// + /// `BezPath` also implements `FromIterator`, so it works with `collect`: + /// + /// ``` + /// // a very contrived example: + /// use kurbo::{BezPath, PathEl}; + /// + /// let path = BezPath::new(); + /// let as_vec: Vec = path.into_iter().collect(); + /// let back_to_path: BezPath = as_vec.into_iter().collect(); + /// ``` + pub fn from_vec(v: Vec) -> BezPath { + debug_assert!( + v.is_empty() || matches!(v.first(), Some(PathEl::MoveTo(_))), + "BezPath must begin with MoveTo" + ); + BezPath(v) + } + + /// Removes the last [`PathEl`] from the path and returns it, or `None` if the path is empty. + pub fn pop(&mut self) -> Option { + self.0.pop() + } + + /// Push a generic path element onto the path. + pub fn push(&mut self, el: PathEl) { + self.0.push(el); + debug_assert!( + matches!(self.0.first(), Some(PathEl::MoveTo(_))), + "BezPath must begin with MoveTo" + ); + } + + /// Push a "move to" element onto the path. + pub fn move_to>(&mut self, p: P) { + self.push(PathEl::MoveTo(p.into())); + } + + /// Push a "line to" element onto the path. + /// + /// Will panic with a debug assert when the path is empty and there is no + /// "move to" element on the path. + /// + /// If `line_to` is called immediately after `close_path` then the current + /// subpath starts at the initial point of the previous subpath. + pub fn line_to>(&mut self, p: P) { + debug_assert!(!self.0.is_empty(), "uninitialized subpath (missing MoveTo)"); + self.push(PathEl::LineTo(p.into())); + } + + /// Push a "quad to" element onto the path. + /// + /// Will panic with a debug assert when the path is empty and there is no + /// "move to" element on the path. + /// + /// If `quad_to` is called immediately after `close_path` then the current + /// subpath starts at the initial point of the previous subpath. + pub fn quad_to>(&mut self, p1: P, p2: P) { + debug_assert!(!self.0.is_empty(), "uninitialized subpath (missing MoveTo)"); + self.push(PathEl::QuadTo(p1.into(), p2.into())); + } + + /// Push a "curve to" element onto the path. + /// + /// Will panic with a debug assert when the path is empty and there is no + /// "move to" element on the path. + /// + /// If `curve_to` is called immediately after `close_path` then the current + /// subpath starts at the initial point of the previous subpath. + pub fn curve_to>(&mut self, p1: P, p2: P, p3: P) { + debug_assert!(!self.0.is_empty(), "uninitialized subpath (missing MoveTo)"); + self.push(PathEl::CurveTo(p1.into(), p2.into(), p3.into())); + } + + /// Push a "close path" element onto the path. + /// + /// Will panic with a debug assert when the path is empty and there is no + /// "move to" element on the path. + pub fn close_path(&mut self) { + debug_assert!(!self.0.is_empty(), "uninitialized subpath (missing MoveTo)"); + self.push(PathEl::ClosePath); + } + + /// Consumes the `BezPath` and returns a vector of [`PathEl`]s. + #[inline(always)] + pub fn into_elements(self) -> Vec { + self.0 + } + + /// Get the path elements. + /// + /// For owned elements, see [`into_elements`]. + /// + /// [`into_elements`]: Self::into_elements + #[inline(always)] + pub fn elements(&self) -> &[PathEl] { + &self.0 + } + + /// Get the path elements (mut version). + #[inline(always)] + pub fn elements_mut(&mut self) -> &mut [PathEl] { + &mut self.0 + } + + /// Returns an iterator over the path's elements. + pub fn iter(&self) -> impl Iterator + Clone + '_ { + self.0.iter().copied() + } + + /// Iterate over the path segments. + pub fn segments(&self) -> impl Iterator + Clone + '_ { + segments(self.iter()) + } + + /// Shorten the path, keeping the first `len` elements. + pub fn truncate(&mut self, len: usize) { + self.0.truncate(len); + } + + /// Get the segment at the given element index. + /// + /// If you need to access all segments, [`segments`] provides a better + /// API. This is intended for random access of specific elements, for clients + /// that require this specifically. + /// + /// **note**: This returns the segment that ends at the provided element + /// index. In effect this means it is *1-indexed*: since no segment ends at + /// the first element (which is presumed to be a `MoveTo`) `get_seg(0)` will + /// always return `None`. + pub fn get_seg(&self, ix: usize) -> Option { + if ix == 0 || ix >= self.0.len() { + return None; + } + let last = match self.0[ix - 1] { + PathEl::MoveTo(p) => p, + PathEl::LineTo(p) => p, + PathEl::QuadTo(_, p2) => p2, + PathEl::CurveTo(_, _, p3) => p3, + PathEl::ClosePath => return None, + }; + match self.0[ix] { + PathEl::LineTo(p) => Some(PathSeg::Line(Line::new(last, p))), + PathEl::QuadTo(p1, p2) => Some(PathSeg::Quad(QuadBez::new(last, p1, p2))), + PathEl::CurveTo(p1, p2, p3) => Some(PathSeg::Cubic(CubicBez::new(last, p1, p2, p3))), + PathEl::ClosePath => self.0[..ix].iter().rev().find_map(|el| match *el { + PathEl::MoveTo(start) if start != last => { + Some(PathSeg::Line(Line::new(last, start))) + } + _ => None, + }), + PathEl::MoveTo(_) => None, + } + } + + /// Returns `true` if the path contains no segments. + pub fn is_empty(&self) -> bool { + self.0 + .iter() + .all(|el| matches!(el, PathEl::MoveTo(..) | PathEl::ClosePath)) + } + + /// Apply an affine transform to the path. + pub fn apply_affine(&mut self, affine: Affine) { + for el in self.0.iter_mut() { + *el = affine * (*el); + } + } + + /// Is this path finite? + #[inline] + pub fn is_finite(&self) -> bool { + self.0.iter().all(|v| v.is_finite()) + } + + /// Is this path NaN? + #[inline] + pub fn is_nan(&self) -> bool { + self.0.iter().any(|v| v.is_nan()) + } + + /// Returns a rectangle that conservatively encloses the path. + /// + /// Unlike the `bounding_box` method, this uses control points directly + /// rather than computing tight bounds for curve elements. + pub fn control_box(&self) -> Rect { + let mut cbox: Option = None; + let mut add_pts = |pts: &[Point]| { + for pt in pts { + cbox = match cbox { + Some(cbox) => Some(cbox.union_pt(*pt)), + _ => Some(Rect::from_points(*pt, *pt)), + }; + } + }; + for &el in self.elements() { + match el { + PathEl::MoveTo(p0) | PathEl::LineTo(p0) => add_pts(&[p0]), + PathEl::QuadTo(p0, p1) => add_pts(&[p0, p1]), + PathEl::CurveTo(p0, p1, p2) => add_pts(&[p0, p1, p2]), + PathEl::ClosePath => {} + } + } + cbox.unwrap_or_default() + } + + /// Returns current position in the path, if path is not empty. + /// + /// This is different from calling [`PathEl::end_point`] on the last entry of [`BezPath::elements`]: + /// this method handles [`PathEl::ClosePath`], + /// by finding the first point of our last subpath, hence the time complexity is O(n). + pub fn current_position(&self) -> Option { + match self.0.last()? { + PathEl::MoveTo(p) => Some(*p), + PathEl::LineTo(p1) => Some(*p1), + PathEl::QuadTo(_, p2) => Some(*p2), + PathEl::CurveTo(_, _, p3) => Some(*p3), + PathEl::ClosePath => self + .elements() + .iter() + .rev() + .skip(1) + .take_while(|el| !matches!(el, PathEl::ClosePath)) + .last() + .and_then(|el| el.end_point()), + } + } + + /// Returns an iterator over the subpaths of this path. See [Elements and Segments](#elements-and-segments) for more information. + pub fn subpaths(&self) -> impl Iterator { + let elements = self.elements(); + let mut i = 0; + + core::iter::from_fn(move || { + if i >= elements.len() { + return None; + } + let start = i; + i += 1; + while i < elements.len() && !matches!(elements[i], PathEl::MoveTo(_)) { + i += 1; + } + Some(&elements[start..i]) + }) + } + + /// Returns a new path with the winding direction of all subpaths reversed. + pub fn reverse_subpaths(&self) -> BezPath { + let elements = self.elements(); + let mut start_ix = 1; + let mut start_pt = Point::default(); + let mut reversed = BezPath(Vec::with_capacity(elements.len())); + // Pending move is used to capture degenerate subpaths that should + // remain in the reversed output. + let mut pending_move = false; + for (ix, el) in elements.iter().enumerate() { + match el { + PathEl::MoveTo(pt) => { + if pending_move { + reversed.push(PathEl::MoveTo(start_pt)); + } + if start_ix < ix { + reverse_subpath(start_pt, &elements[start_ix..ix], &mut reversed); + } + pending_move = true; + start_pt = *pt; + start_ix = ix + 1; + } + PathEl::ClosePath => { + if start_ix <= ix { + reverse_subpath(start_pt, &elements[start_ix..ix], &mut reversed); + } + reversed.push(PathEl::ClosePath); + start_ix = ix + 1; + pending_move = false; + } + _ => { + pending_move = false; + } + } + } + if start_ix < elements.len() { + reverse_subpath(start_pt, &elements[start_ix..], &mut reversed); + } else if pending_move { + reversed.push(PathEl::MoveTo(start_pt)); + } + reversed + } +} + +/// Helper for reversing a subpath. +/// +/// The `els` parameter must not contain any `MoveTo` or `ClosePath` elements. +fn reverse_subpath(start_pt: Point, els: &[PathEl], reversed: &mut BezPath) { + let end_pt = els.last().and_then(|el| el.end_point()).unwrap_or(start_pt); + reversed.push(PathEl::MoveTo(end_pt)); + for (ix, el) in els.iter().enumerate().rev() { + let end_pt = if ix > 0 { + els[ix - 1].end_point().unwrap() + } else { + start_pt + }; + match el { + PathEl::LineTo(_) => reversed.push(PathEl::LineTo(end_pt)), + PathEl::QuadTo(c0, _) => reversed.push(PathEl::QuadTo(*c0, end_pt)), + PathEl::CurveTo(c0, c1, _) => reversed.push(PathEl::CurveTo(*c1, *c0, end_pt)), + _ => panic!("reverse_subpath expects MoveTo and ClosePath to be removed"), + } + } +} + +impl FromIterator for BezPath { + fn from_iter>(iter: T) -> Self { + let el_vec: Vec<_> = iter.into_iter().collect(); + BezPath::from_vec(el_vec) + } +} + +/// Allow iteration over references to `BezPath`. +/// +/// Note: the semantics are slightly different from simply iterating over the +/// slice, as it returns `PathEl` items, rather than references. +impl<'a> IntoIterator for &'a BezPath { + type Item = PathEl; + type IntoIter = core::iter::Cloned>; + + fn into_iter(self) -> Self::IntoIter { + self.elements().iter().cloned() + } +} + +impl IntoIterator for BezPath { + type Item = PathEl; + type IntoIter = alloc::vec::IntoIter; + + fn into_iter(self) -> Self::IntoIter { + self.0.into_iter() + } +} + +impl Extend for BezPath { + /// Add the items from the iterator to this path. + /// + ///

+ /// + /// Note that if you're attempting to make a continuous path, you will generally + /// want to ensure that the iterator does not contain any [`MoveTo`](PathEl::MoveTo) + /// or [`ClosePath`](PathEl::ClosePath) elements. + /// Note especially that many (open) [shapes](Shape) will start with a `MoveTo` if + /// you use their [`path_elements`](Shape::path_elements) function. + /// Some shapes have alternatives for this use case, such as [`Arc::append_iter`](crate::Arc::append_iter). + /// + ///
+ fn extend>(&mut self, iter: I) { + self.0.extend(iter); + } +} + +/// Proportion of tolerance budget that goes to cubic to quadratic conversion. +const TO_QUAD_TOL: f64 = 0.1; + +/// Flatten the path, invoking the callback repeatedly. +/// +/// Flattening is the action of approximating a curve with a succession of line segments. +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// → +/// +/// +/// +/// The tolerance value controls the maximum distance between the curved input +/// segments and their polyline approximations. (In technical terms, this is the +/// Hausdorff distance). The algorithm attempts to bound this distance between +/// by `tolerance` but this is not absolutely guaranteed. The appropriate value +/// depends on the use, but for antialiased rendering, a value of 0.25 has been +/// determined to give good results. The number of segments tends to scale as the +/// inverse square root of tolerance. +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// The callback will be called in order with each element of the generated +/// path. Because the result is made of polylines, these will be straight-line +/// path elements only, no curves. +/// +/// This algorithm is based on the blog post [Flattening quadratic Béziers] +/// but with some refinements. For one, there is a more careful approximation +/// at cusps. For two, the algorithm is extended to work with cubic Béziers +/// as well, by first subdividing into quadratics and then computing the +/// subdivision of each quadratic. However, as a clever trick, these quadratics +/// are subdivided fractionally, and their endpoints are not included. +/// +/// TODO: write a paper explaining this in more detail. +/// +/// [Flattening quadratic Béziers]: https://raphlinus.github.io/graphics/curves/2019/12/23/flatten-quadbez.html +pub fn flatten( + path: impl IntoIterator, + tolerance: f64, + mut callback: impl FnMut(PathEl), +) { + let sqrt_tol = tolerance.sqrt(); + let mut last_pt = None; + let mut quad_buf = Vec::new(); + for el in path { + match el { + PathEl::MoveTo(p) => { + last_pt = Some(p); + callback(PathEl::MoveTo(p)); + } + PathEl::LineTo(p) => { + last_pt = Some(p); + callback(PathEl::LineTo(p)); + } + PathEl::QuadTo(p1, p2) => { + if let Some(p0) = last_pt { + let q = QuadBez::new(p0, p1, p2); + let params = q.estimate_subdiv(sqrt_tol); + let n = ((0.5 * params.val / sqrt_tol).ceil() as usize).max(1); + let step = 1.0 / (n as f64); + for i in 1..n { + let u = (i as f64) * step; + let t = q.determine_subdiv_t(¶ms, u); + let p = q.eval(t); + callback(PathEl::LineTo(p)); + } + callback(PathEl::LineTo(p2)); + } + last_pt = Some(p2); + } + PathEl::CurveTo(p1, p2, p3) => { + if let Some(p0) = last_pt { + let c = CubicBez::new(p0, p1, p2, p3); + + // Subdivide into quadratics, and estimate the number of + // subdivisions required for each, summing to arrive at an + // estimate for the number of subdivisions for the cubic. + // Also retain these parameters for later. + let iter = c.to_quads(tolerance * TO_QUAD_TOL); + quad_buf.clear(); + quad_buf.reserve(iter.size_hint().0); + let sqrt_remain_tol = sqrt_tol * (1.0 - TO_QUAD_TOL).sqrt(); + let mut sum = 0.0; + for (_, _, q) in iter { + let params = q.estimate_subdiv(sqrt_remain_tol); + sum += params.val; + quad_buf.push((q, params)); + } + let n = ((0.5 * sum / sqrt_remain_tol).ceil() as usize).max(1); + + // Iterate through the quadratics, outputting the points of + // subdivisions that fall within that quadratic. + let step = sum / (n as f64); + let mut i = 1; + let mut val_sum = 0.0; + for (q, params) in &quad_buf { + let mut target = (i as f64) * step; + let recip_val = params.val.recip(); + while target < val_sum + params.val { + let u = (target - val_sum) * recip_val; + let t = q.determine_subdiv_t(params, u); + let p = q.eval(t); + callback(PathEl::LineTo(p)); + i += 1; + if i == n + 1 { + break; + } + target = (i as f64) * step; + } + val_sum += params.val; + } + callback(PathEl::LineTo(p3)); + } + last_pt = Some(p3); + } + PathEl::ClosePath => { + last_pt = None; + callback(PathEl::ClosePath); + } + } + } +} + +impl Mul for Affine { + type Output = PathEl; + + // TODO: Inlining this leads to a huge performance benefit, perhaps the same should be done for + // other methods. + #[inline(always)] + fn mul(self, other: PathEl) -> PathEl { + match other { + PathEl::MoveTo(p) => PathEl::MoveTo(self * p), + PathEl::LineTo(p) => PathEl::LineTo(self * p), + PathEl::QuadTo(p1, p2) => PathEl::QuadTo(self * p1, self * p2), + PathEl::CurveTo(p1, p2, p3) => PathEl::CurveTo(self * p1, self * p2, self * p3), + PathEl::ClosePath => PathEl::ClosePath, + } + } +} + +impl Mul for Affine { + type Output = PathSeg; + + fn mul(self, other: PathSeg) -> PathSeg { + match other { + PathSeg::Line(line) => PathSeg::Line(self * line), + PathSeg::Quad(quad) => PathSeg::Quad(self * quad), + PathSeg::Cubic(cubic) => PathSeg::Cubic(self * cubic), + } + } +} + +impl Mul for Affine { + type Output = BezPath; + + fn mul(self, other: BezPath) -> BezPath { + BezPath(other.0.iter().map(|&el| self * el).collect()) + } +} + +impl Mul<&BezPath> for Affine { + type Output = BezPath; + + fn mul(self, other: &BezPath) -> BezPath { + BezPath(other.0.iter().map(|&el| self * el).collect()) + } +} + +impl Mul for TranslateScale { + type Output = PathEl; + + fn mul(self, other: PathEl) -> PathEl { + match other { + PathEl::MoveTo(p) => PathEl::MoveTo(self * p), + PathEl::LineTo(p) => PathEl::LineTo(self * p), + PathEl::QuadTo(p1, p2) => PathEl::QuadTo(self * p1, self * p2), + PathEl::CurveTo(p1, p2, p3) => PathEl::CurveTo(self * p1, self * p2, self * p3), + PathEl::ClosePath => PathEl::ClosePath, + } + } +} + +impl Mul for TranslateScale { + type Output = PathSeg; + + fn mul(self, other: PathSeg) -> PathSeg { + match other { + PathSeg::Line(line) => PathSeg::Line(self * line), + PathSeg::Quad(quad) => PathSeg::Quad(self * quad), + PathSeg::Cubic(cubic) => PathSeg::Cubic(self * cubic), + } + } +} + +impl Mul for TranslateScale { + type Output = BezPath; + + fn mul(self, other: BezPath) -> BezPath { + BezPath(other.0.iter().map(|&el| self * el).collect()) + } +} + +impl Mul<&BezPath> for TranslateScale { + type Output = BezPath; + + fn mul(self, other: &BezPath) -> BezPath { + BezPath(other.0.iter().map(|&el| self * el).collect()) + } +} + +/// Close all open subpaths in a path, expressed as iterator transform. +pub(crate) fn close_subpaths(elements: I) -> CloseSubpaths +where + I: IntoIterator, +{ + CloseSubpaths { + elements: elements.into_iter(), + state: CloseSubpathState::Start, + } +} + +/// An iterator that closes all open subpaths. +/// +/// This struct is created by the [`close_subpaths`] function. +#[derive(Clone)] +pub(crate) struct CloseSubpaths> { + elements: I, + state: CloseSubpathState, +} + +#[derive(Clone)] +enum CloseSubpathState { + Start, + InSubpath, + ClosedLast, + PendingMoveTo(Point), +} + +impl> Iterator for CloseSubpaths { + type Item = PathEl; + + fn next(&mut self) -> Option { + match self.state { + CloseSubpathState::Start => { + let el = self.elements.next(); + if !matches!(el, Some(PathEl::ClosePath) | None) { + self.state = CloseSubpathState::InSubpath; + } + el + } + CloseSubpathState::InSubpath => { + let el = self.elements.next(); + match el { + None => { + self.state = CloseSubpathState::ClosedLast; + Some(PathEl::ClosePath) + } + Some(PathEl::MoveTo(point)) => { + self.state = CloseSubpathState::PendingMoveTo(point); + Some(PathEl::ClosePath) + } + Some(PathEl::ClosePath) => { + self.state = CloseSubpathState::Start; + el + } + _ => el, + } + } + CloseSubpathState::ClosedLast => None, + CloseSubpathState::PendingMoveTo(point) => { + self.state = CloseSubpathState::Start; + Some(PathEl::MoveTo(point)) + } + } + } +} + +/// Transform an iterator over path elements into one over path +/// segments. +/// +/// See also [`BezPath::segments`]. +/// This signature is a bit more general, allowing `&[PathEl]` slices +/// and other iterators yielding `PathEl`. +pub fn segments(elements: I) -> Segments +where + I: IntoIterator, +{ + Segments { + elements: elements.into_iter(), + start_last: None, + } +} + +/// An iterator that transforms path elements to path segments. +/// +/// This struct is created by the [`segments`] function. +#[derive(Clone)] +pub struct Segments> { + elements: I, + start_last: Option<(Point, Point)>, +} + +impl> Iterator for Segments { + type Item = PathSeg; + + #[inline] + fn next(&mut self) -> Option { + for el in &mut self.elements { + // We first need to check whether this is the first + // path element we see to fill in the start position. + let (start, last) = self.start_last.get_or_insert_with(|| { + let point = match el { + PathEl::MoveTo(p) => p, + PathEl::LineTo(p) => p, + PathEl::QuadTo(_, p2) => p2, + PathEl::CurveTo(_, _, p3) => p3, + PathEl::ClosePath => panic!("Can't start a segment on a ClosePath"), + }; + (point, point) + }); + + return Some(match el { + PathEl::MoveTo(p) => { + *start = p; + *last = p; + continue; + } + PathEl::LineTo(p) => PathSeg::Line(Line::new(mem::replace(last, p), p)), + PathEl::QuadTo(p1, p2) => { + PathSeg::Quad(QuadBez::new(mem::replace(last, p2), p1, p2)) + } + PathEl::CurveTo(p1, p2, p3) => { + PathSeg::Cubic(CubicBez::new(mem::replace(last, p3), p1, p2, p3)) + } + PathEl::ClosePath => { + if *last != *start { + PathSeg::Line(Line::new(mem::replace(last, *start), *start)) + } else { + continue; + } + } + }); + } + + None + } +} + +impl> Segments { + /// Here, `accuracy` specifies the accuracy for each Bézier segment. At worst, + /// the total error is `accuracy` times the number of Bézier segments. + // TODO: pub? Or is this subsumed by method of &[PathEl]? + pub(crate) fn perimeter(self, accuracy: f64) -> f64 { + self.map(|seg| seg.arclen(accuracy)).sum() + } + + // Same + pub(crate) fn area(self) -> f64 { + self.map(|seg| seg.signed_area()).sum() + } + + // Same + pub(crate) fn winding(self, p: Point) -> i32 { + self.map(|seg| seg.winding(p)).sum() + } + + // Same + pub(crate) fn bounding_box(self) -> Rect { + let mut bbox: Option = None; + for seg in self { + let seg_bb = ParamCurveExtrema::bounding_box(&seg); + if let Some(bb) = bbox { + bbox = Some(bb.union(seg_bb)); + } else { + bbox = Some(seg_bb); + } + } + bbox.unwrap_or_default() + } +} + +impl ParamCurve for PathSeg { + fn eval(&self, t: f64) -> Point { + match *self { + PathSeg::Line(line) => line.eval(t), + PathSeg::Quad(quad) => quad.eval(t), + PathSeg::Cubic(cubic) => cubic.eval(t), + } + } + + fn subsegment(&self, range: Range) -> PathSeg { + match *self { + PathSeg::Line(line) => PathSeg::Line(line.subsegment(range)), + PathSeg::Quad(quad) => PathSeg::Quad(quad.subsegment(range)), + PathSeg::Cubic(cubic) => PathSeg::Cubic(cubic.subsegment(range)), + } + } + + fn start(&self) -> Point { + match *self { + PathSeg::Line(line) => line.start(), + PathSeg::Quad(quad) => quad.start(), + PathSeg::Cubic(cubic) => cubic.start(), + } + } + + fn end(&self) -> Point { + match *self { + PathSeg::Line(line) => line.end(), + PathSeg::Quad(quad) => quad.end(), + PathSeg::Cubic(cubic) => cubic.end(), + } + } +} + +impl ParamCurveArclen for PathSeg { + fn arclen(&self, accuracy: f64) -> f64 { + match *self { + PathSeg::Line(line) => line.arclen(accuracy), + PathSeg::Quad(quad) => quad.arclen(accuracy), + PathSeg::Cubic(cubic) => cubic.arclen(accuracy), + } + } + + fn inv_arclen(&self, arclen: f64, accuracy: f64) -> f64 { + match *self { + PathSeg::Line(line) => line.inv_arclen(arclen, accuracy), + PathSeg::Quad(quad) => quad.inv_arclen(arclen, accuracy), + PathSeg::Cubic(cubic) => cubic.inv_arclen(arclen, accuracy), + } + } +} + +impl ParamCurveArea for PathSeg { + fn signed_area(&self) -> f64 { + match *self { + PathSeg::Line(line) => line.signed_area(), + PathSeg::Quad(quad) => quad.signed_area(), + PathSeg::Cubic(cubic) => cubic.signed_area(), + } + } +} + +impl ParamCurveNearest for PathSeg { + fn nearest(&self, p: Point, accuracy: f64) -> Nearest { + match *self { + PathSeg::Line(line) => line.nearest(p, accuracy), + PathSeg::Quad(quad) => quad.nearest(p, accuracy), + PathSeg::Cubic(cubic) => cubic.nearest(p, accuracy), + } + } +} + +impl ParamCurveExtrema for PathSeg { + fn extrema(&self) -> ArrayVec { + match *self { + PathSeg::Line(line) => line.extrema(), + PathSeg::Quad(quad) => quad.extrema(), + PathSeg::Cubic(cubic) => cubic.extrema(), + } + } +} + +impl PathSeg { + /// Get the [`PathEl`] that is equivalent to discarding the segment start point. + pub fn as_path_el(&self) -> PathEl { + match self { + PathSeg::Line(line) => PathEl::LineTo(line.p1), + PathSeg::Quad(q) => PathEl::QuadTo(q.p1, q.p2), + PathSeg::Cubic(c) => PathEl::CurveTo(c.p1, c.p2, c.p3), + } + } + + /// Returns a new `PathSeg` describing the same path as `self`, but with + /// the points reversed. + pub fn reverse(&self) -> PathSeg { + match self { + PathSeg::Line(Line { p0, p1 }) => PathSeg::Line(Line::new(*p1, *p0)), + PathSeg::Quad(q) => PathSeg::Quad(QuadBez::new(q.p2, q.p1, q.p0)), + PathSeg::Cubic(c) => PathSeg::Cubic(CubicBez::new(c.p3, c.p2, c.p1, c.p0)), + } + } + + /// Convert this segment to a cubic Bézier. + pub fn to_cubic(&self) -> CubicBez { + match *self { + PathSeg::Line(Line { p0, p1 }) => CubicBez::new(p0, p0, p1, p1), + PathSeg::Cubic(c) => c, + PathSeg::Quad(q) => q.raise(), + } + } + + /// A single-segment "winding" number. + /// + /// Assume that `self` is monotonic in `y`, and take a ray pointing + /// left from `p`. If `self` crosses that ray, returns 1 (if we're + /// decreasing in y) or -1 (if we're increasing in y). Otherwise, returns 0. + /// + /// Handling of endpoints is a little subtle, just to make sure that + /// we correctly handle consecutive segments: we consider `self` to + /// contain the endpoint with smaller y, and not contain the endpoint + /// with larger y. + fn winding_inner(&self, p: Point) -> i32 { + let start = self.start(); + let end = self.end(); + let sign = if end.y > start.y { + if p.y < start.y || p.y >= end.y { + return 0; + } + -1 + } else if end.y < start.y { + if p.y < end.y || p.y >= start.y { + return 0; + } + 1 + } else { + return 0; + }; + match *self { + PathSeg::Line(_line) => { + if p.x < start.x.min(end.x) { + return 0; + } + if p.x >= start.x.max(end.x) { + return sign; + } + // line equation ax + by = c + let a = end.y - start.y; + let b = start.x - end.x; + let c = a * start.x + b * start.y; + if (a * p.x + b * p.y - c) * (sign as f64) <= 0.0 { + sign + } else { + 0 + } + } + PathSeg::Quad(quad) => { + let p1 = quad.p1; + if p.x < start.x.min(end.x).min(p1.x) { + return 0; + } + if p.x >= start.x.max(end.x).max(p1.x) { + return sign; + } + let t = quad.solve_monotonic_for_y(p.y); + let x = quad.eval(t).x; + if p.x >= x { sign } else { 0 } + } + PathSeg::Cubic(cubic) => { + let p1 = cubic.p1; + let p2 = cubic.p2; + if p.x < start.x.min(end.x).min(p1.x).min(p2.x) { + return 0; + } + if p.x >= start.x.max(end.x).max(p1.x).max(p2.x) { + return sign; + } + let t = cubic.solve_monotonic_for_y(p.y); + let x = cubic.eval(t).x; + if p.x >= x { sign } else { 0 } + } + } + } + + /// Compute the winding number contribution of a single segment. + /// + /// Cast a ray to the left and count intersections. + fn winding(&self, p: Point) -> i32 { + self.extrema_ranges() + .into_iter() + .map(|range| self.subsegment(range).winding_inner(p)) + .sum() + } + + /// Compute intersections against a line. + /// + /// Returns a vector of the intersections. For each intersection, + /// the `t` value of the segment and line are given. + /// + /// Note: This test is designed to be inclusive of points near the endpoints + /// of the segment. This is so that testing a line against multiple + /// contiguous segments of a path will be guaranteed to catch at least one + /// of them. In such cases, use higher level logic to coalesce the hits + /// (the `t` value may be slightly outside the range of 0..1). + /// + /// # Examples + /// + /// ``` + /// # use kurbo::*; + /// let seg = PathSeg::Line(Line::new((0.0, 0.0), (2.0, 0.0))); + /// let line = Line::new((1.0, 2.0), (1.0, -2.0)); + /// let intersection = seg.intersect_line(line); + /// assert_eq!(intersection.len(), 1); + /// let intersection = intersection[0]; + /// assert_eq!(intersection.segment_t, 0.5); + /// assert_eq!(intersection.line_t, 0.5); + /// + /// let point = seg.eval(intersection.segment_t); + /// assert_eq!(point, Point::new(1.0, 0.0)); + /// ``` + pub fn intersect_line(&self, line: Line) -> ArrayVec { + const EPSILON: f64 = 1e-9; + let p0 = line.p0; + let p1 = line.p1; + let dx = p1.x - p0.x; + let dy = p1.y - p0.y; + let mut result = ArrayVec::new(); + match self { + PathSeg::Line(l) => { + let det = dx * (l.p1.y - l.p0.y) - dy * (l.p1.x - l.p0.x); + if det.abs() < EPSILON { + // Lines are coincident (or nearly so). + return result; + } + let t = dx * (p0.y - l.p0.y) - dy * (p0.x - l.p0.x); + // t = position on self + let t = t / det; + if (-EPSILON..=(1.0 + EPSILON)).contains(&t) { + // u = position on probe line + let u = + (l.p0.x - p0.x) * (l.p1.y - l.p0.y) - (l.p0.y - p0.y) * (l.p1.x - l.p0.x); + let u = u / det; + if (0.0..=1.0).contains(&u) { + result.push(LineIntersection::new(u, t)); + } + } + } + PathSeg::Quad(q) => { + // The basic technique here is to determine x and y as a quadratic polynomial + // as a function of t. Then plug those values into the line equation for the + // probe line (giving a sort of signed distance from the probe line) and solve + // that for t. + let (px0, px1, px2) = quadratic_bez_coefs(q.p0.x, q.p1.x, q.p2.x); + let (py0, py1, py2) = quadratic_bez_coefs(q.p0.y, q.p1.y, q.p2.y); + let c0 = dy * (px0 - p0.x) - dx * (py0 - p0.y); + let c1 = dy * px1 - dx * py1; + let c2 = dy * px2 - dx * py2; + let invlen2 = (dx * dx + dy * dy).recip(); + for t in solve_quadratic(c0, c1, c2) { + if (-EPSILON..=(1.0 + EPSILON)).contains(&t) { + let x = px0 + t * px1 + t * t * px2; + let y = py0 + t * py1 + t * t * py2; + let u = ((x - p0.x) * dx + (y - p0.y) * dy) * invlen2; + if (0.0..=1.0).contains(&u) { + result.push(LineIntersection::new(u, t)); + } + } + } + } + PathSeg::Cubic(c) => { + // Same technique as above, but cubic polynomial. + let (px0, px1, px2, px3) = cubic_bez_coefs(c.p0.x, c.p1.x, c.p2.x, c.p3.x); + let (py0, py1, py2, py3) = cubic_bez_coefs(c.p0.y, c.p1.y, c.p2.y, c.p3.y); + let c0 = dy * (px0 - p0.x) - dx * (py0 - p0.y); + let c1 = dy * px1 - dx * py1; + let c2 = dy * px2 - dx * py2; + let c3 = dy * px3 - dx * py3; + let invlen2 = (dx * dx + dy * dy).recip(); + for t in solve_cubic(c0, c1, c2, c3) { + if (-EPSILON..=(1.0 + EPSILON)).contains(&t) { + let x = px0 + t * px1 + t * t * px2 + t * t * t * px3; + let y = py0 + t * py1 + t * t * py2 + t * t * t * py3; + let u = ((x - p0.x) * dx + (y - p0.y) * dy) * invlen2; + if (0.0..=1.0).contains(&u) { + result.push(LineIntersection::new(u, t)); + } + } + } + } + } + result + } + + /// Is this Bézier path finite? + #[inline] + pub fn is_finite(&self) -> bool { + match self { + PathSeg::Line(line) => line.is_finite(), + PathSeg::Quad(quad_bez) => quad_bez.is_finite(), + PathSeg::Cubic(cubic_bez) => cubic_bez.is_finite(), + } + } + + /// Is this Bézier path NaN? + #[inline] + pub fn is_nan(&self) -> bool { + match self { + PathSeg::Line(line) => line.is_nan(), + PathSeg::Quad(quad_bez) => quad_bez.is_nan(), + PathSeg::Cubic(cubic_bez) => cubic_bez.is_nan(), + } + } + + #[inline] + fn as_vec2_vec(&self) -> ArrayVec { + let mut a = ArrayVec::new(); + match self { + PathSeg::Line(l) => { + a.push(l.p0.to_vec2()); + a.push(l.p1.to_vec2()); + } + PathSeg::Quad(q) => { + a.push(q.p0.to_vec2()); + a.push(q.p1.to_vec2()); + a.push(q.p2.to_vec2()); + } + PathSeg::Cubic(c) => { + a.push(c.p0.to_vec2()); + a.push(c.p1.to_vec2()); + a.push(c.p2.to_vec2()); + a.push(c.p3.to_vec2()); + } + } + a + } + + /// Minimum distance between two [`PathSeg`]s. + /// + /// Returns a tuple of the distance, the path time `t1` of the closest point + /// on the first `PathSeg`, and the path time `t2` of the closest point on the + /// second `PathSeg`. + pub fn min_dist(&self, other: PathSeg, accuracy: f64) -> MinDistance { + let (distance, t1, t2) = crate::mindist::min_dist_param( + &self.as_vec2_vec(), + &other.as_vec2_vec(), + (0.0, 1.0), + (0.0, 1.0), + accuracy, + None, + ); + MinDistance { + distance: distance.sqrt(), + t1, + t2, + } + } + + /// Compute endpoint tangents of a path segment. + /// + /// This version is robust to the path segment not being a regular curve. + pub(crate) fn tangents(&self) -> (Vec2, Vec2) { + const EPS: f64 = 1e-12; + match self { + PathSeg::Line(l) => { + let d = l.p1 - l.p0; + (d, d) + } + PathSeg::Quad(q) => { + let d01 = q.p1 - q.p0; + let d0 = if d01.hypot2() > EPS { d01 } else { q.p2 - q.p0 }; + let d12 = q.p2 - q.p1; + let d1 = if d12.hypot2() > EPS { d12 } else { q.p2 - q.p0 }; + (d0, d1) + } + PathSeg::Cubic(c) => { + let d01 = c.p1 - c.p0; + let d0 = if d01.hypot2() > EPS { + d01 + } else { + let d02 = c.p2 - c.p0; + if d02.hypot2() > EPS { d02 } else { c.p3 - c.p0 } + }; + let d23 = c.p3 - c.p2; + let d1 = if d23.hypot2() > EPS { + d23 + } else { + let d13 = c.p3 - c.p1; + if d13.hypot2() > EPS { d13 } else { c.p3 - c.p0 } + }; + (d0, d1) + } + } + } +} + +impl LineIntersection { + #[inline(always)] + fn new(line_t: f64, segment_t: f64) -> Self { + LineIntersection { line_t, segment_t } + } + + /// Is this line intersection finite? + #[inline] + pub fn is_finite(self) -> bool { + self.line_t.is_finite() && self.segment_t.is_finite() + } + + /// Is this line intersection NaN? + #[inline] + pub fn is_nan(self) -> bool { + self.line_t.is_nan() || self.segment_t.is_nan() + } +} + +// Return polynomial coefficients given cubic Bézier coordinates. +fn quadratic_bez_coefs(x0: f64, x1: f64, x2: f64) -> (f64, f64, f64) { + let p0 = x0; + let p1 = 2.0 * x1 - 2.0 * x0; + let p2 = x2 - 2.0 * x1 + x0; + (p0, p1, p2) +} + +// Return polynomial coefficients given cubic Bézier coordinates. +fn cubic_bez_coefs(x0: f64, x1: f64, x2: f64, x3: f64) -> (f64, f64, f64, f64) { + let p0 = x0; + let p1 = 3.0 * x1 - 3.0 * x0; + let p2 = 3.0 * x2 - 6.0 * x1 + 3.0 * x0; + let p3 = x3 - 3.0 * x2 + 3.0 * x1 - x0; + (p0, p1, p2, p3) +} + +impl From for PathSeg { + #[inline(always)] + fn from(cubic_bez: CubicBez) -> PathSeg { + PathSeg::Cubic(cubic_bez) + } +} + +impl From for PathSeg { + #[inline(always)] + fn from(line: Line) -> PathSeg { + PathSeg::Line(line) + } +} + +impl From for PathSeg { + #[inline(always)] + fn from(quad_bez: QuadBez) -> PathSeg { + PathSeg::Quad(quad_bez) + } +} + +impl Shape for BezPath { + type PathElementsIter<'iter> = core::iter::Copied>; + + fn path_elements(&self, _tolerance: f64) -> Self::PathElementsIter<'_> { + self.0.iter().copied() + } + + fn to_path(&self, _tolerance: f64) -> BezPath { + self.clone() + } + + #[inline(always)] + fn into_path(self, _tolerance: f64) -> BezPath { + self + } + + /// Signed area. + fn area(&self) -> f64 { + self.elements().area() + } + + fn perimeter(&self, accuracy: f64) -> f64 { + self.elements().perimeter(accuracy) + } + + /// Winding number of point. + fn winding(&self, pt: Point) -> i32 { + self.elements().winding(pt) + } + + fn bounding_box(&self) -> Rect { + self.elements().bounding_box() + } + + #[inline(always)] + fn as_path_slice(&self) -> Option<&[PathEl]> { + Some(&self.0) + } +} + +impl PathEl { + /// Is this path element finite? + #[inline] + pub fn is_finite(&self) -> bool { + match self { + PathEl::MoveTo(p) => p.is_finite(), + PathEl::LineTo(p) => p.is_finite(), + PathEl::QuadTo(p, p2) => p.is_finite() && p2.is_finite(), + PathEl::CurveTo(p, p2, p3) => p.is_finite() && p2.is_finite() && p3.is_finite(), + PathEl::ClosePath => true, + } + } + + /// Is this path element NaN? + #[inline] + pub fn is_nan(&self) -> bool { + match self { + PathEl::MoveTo(p) => p.is_nan(), + PathEl::LineTo(p) => p.is_nan(), + PathEl::QuadTo(p, p2) => p.is_nan() || p2.is_nan(), + PathEl::CurveTo(p, p2, p3) => p.is_nan() || p2.is_nan() || p3.is_nan(), + PathEl::ClosePath => false, + } + } + + /// Get the end point of the path element, if it exists. + pub fn end_point(&self) -> Option { + match self { + PathEl::MoveTo(p) => Some(*p), + PathEl::LineTo(p1) => Some(*p1), + PathEl::QuadTo(_, p2) => Some(*p2), + PathEl::CurveTo(_, _, p3) => Some(*p3), + PathEl::ClosePath => None, + } + } +} + +/// Implements [`Shape`] for a slice of [`PathEl`], provided that the first element of the slice is +/// not a `PathEl::ClosePath`. If it is, several of these functions will panic. +/// +/// If the slice starts with `LineTo`, `QuadTo`, or `CurveTo`, it will be treated as a `MoveTo`. +impl<'a> Shape for &'a [PathEl] { + type PathElementsIter<'iter> + = core::iter::Copied> + where + 'a: 'iter; + + #[inline] + fn path_elements(&self, _tolerance: f64) -> Self::PathElementsIter<'_> { + self.iter().copied() + } + + fn to_path(&self, _tolerance: f64) -> BezPath { + BezPath::from_vec(self.to_vec()) + } + + /// Signed area. + fn area(&self) -> f64 { + segments(self.iter().copied()).area() + } + + fn perimeter(&self, accuracy: f64) -> f64 { + segments(self.iter().copied()).perimeter(accuracy) + } + + /// Winding number of point. + fn winding(&self, pt: Point) -> i32 { + segments(self.iter().copied()).winding(pt) + } + + fn bounding_box(&self) -> Rect { + segments(self.iter().copied()).bounding_box() + } + + #[inline(always)] + fn as_path_slice(&self) -> Option<&[PathEl]> { + Some(self) + } +} + +/// Implements [`Shape`] for an array of [`PathEl`], provided that the first element of the array is +/// not a `PathEl::ClosePath`. If it is, several of these functions will panic. +/// +/// If the array starts with `LineTo`, `QuadTo`, or `CurveTo`, it will be treated as a `MoveTo`. +impl Shape for [PathEl; N] { + type PathElementsIter<'iter> = core::iter::Copied>; + + #[inline] + fn path_elements(&self, _tolerance: f64) -> Self::PathElementsIter<'_> { + self.iter().copied() + } + + fn to_path(&self, _tolerance: f64) -> BezPath { + BezPath::from_vec(self.to_vec()) + } + + /// Signed area. + fn area(&self) -> f64 { + segments(self.iter().copied()).area() + } + + fn perimeter(&self, accuracy: f64) -> f64 { + segments(self.iter().copied()).perimeter(accuracy) + } + + /// Winding number of point. + fn winding(&self, pt: Point) -> i32 { + segments(self.iter().copied()).winding(pt) + } + + fn bounding_box(&self) -> Rect { + segments(self.iter().copied()).bounding_box() + } + + #[inline(always)] + fn as_path_slice(&self) -> Option<&[PathEl]> { + Some(self) + } +} + +/// An iterator for path segments. +pub struct PathSegIter { + seg: PathSeg, + ix: usize, +} + +impl Shape for PathSeg { + type PathElementsIter<'iter> = PathSegIter; + + #[inline(always)] + fn path_elements(&self, _tolerance: f64) -> PathSegIter { + PathSegIter { seg: *self, ix: 0 } + } + + /// The area under the curve. + /// + /// We could just return `0`, but this seems more useful. + fn area(&self) -> f64 { + self.signed_area() + } + + #[inline] + fn perimeter(&self, accuracy: f64) -> f64 { + self.arclen(accuracy) + } + + #[inline(always)] + fn winding(&self, _pt: Point) -> i32 { + 0 + } + + #[inline] + fn bounding_box(&self) -> Rect { + ParamCurveExtrema::bounding_box(self) + } + + fn as_line(&self) -> Option { + if let PathSeg::Line(line) = self { + Some(*line) + } else { + None + } + } +} + +impl Iterator for PathSegIter { + type Item = PathEl; + + fn next(&mut self) -> Option { + self.ix += 1; + match (self.ix, self.seg) { + // yes I could do some fancy bindings thing here but... :shrug: + (1, PathSeg::Line(seg)) => Some(PathEl::MoveTo(seg.p0)), + (1, PathSeg::Quad(seg)) => Some(PathEl::MoveTo(seg.p0)), + (1, PathSeg::Cubic(seg)) => Some(PathEl::MoveTo(seg.p0)), + (2, PathSeg::Line(seg)) => Some(PathEl::LineTo(seg.p1)), + (2, PathSeg::Quad(seg)) => Some(PathEl::QuadTo(seg.p1, seg.p2)), + (2, PathSeg::Cubic(seg)) => Some(PathEl::CurveTo(seg.p1, seg.p2, seg.p3)), + _ => None, + } + } +} + +#[cfg(test)] +mod tests { + use crate::{Circle, DEFAULT_ACCURACY}; + + use super::*; + + fn assert_approx_eq(x: f64, y: f64) { + assert!((x - y).abs() < 1e-8, "{x} != {y}"); + } + + #[test] + #[should_panic(expected = "uninitialized subpath")] + fn test_elements_to_segments_starts_on_closepath() { + let mut path = BezPath::new(); + path.close_path(); + path.segments().next(); + } + + #[test] + fn test_elements_to_segments_closepath_refers_to_last_moveto() { + let mut path = BezPath::new(); + path.move_to((5.0, 5.0)); + path.line_to((15.0, 15.0)); + path.move_to((10.0, 10.0)); + path.line_to((15.0, 15.0)); + path.close_path(); + assert_eq!( + path.segments().collect::>().last(), + Some(&Line::new((15.0, 15.0), (10.0, 10.0)).into()), + ); + } + + #[test] + #[should_panic(expected = "uninitialized subpath")] + fn test_must_not_start_on_quad() { + let mut path = BezPath::new(); + path.quad_to((5.0, 5.0), (10.0, 10.0)); + path.line_to((15.0, 15.0)); + path.close_path(); + } + + #[test] + fn test_intersect_line() { + let h_line = Line::new((0.0, 0.0), (100.0, 0.0)); + let v_line = Line::new((10.0, -10.0), (10.0, 10.0)); + let intersection = PathSeg::Line(h_line).intersect_line(v_line)[0]; + assert_approx_eq(intersection.segment_t, 0.1); + assert_approx_eq(intersection.line_t, 0.5); + + let v_line = Line::new((-10.0, -10.0), (-10.0, 10.0)); + assert!(PathSeg::Line(h_line).intersect_line(v_line).is_empty()); + + let v_line = Line::new((10.0, 10.0), (10.0, 20.0)); + assert!(PathSeg::Line(h_line).intersect_line(v_line).is_empty()); + } + + #[test] + fn test_intersect_qad() { + let q = QuadBez::new((0.0, -10.0), (10.0, 20.0), (20.0, -10.0)); + let v_line = Line::new((10.0, -10.0), (10.0, 10.0)); + assert_eq!(PathSeg::Quad(q).intersect_line(v_line).len(), 1); + let intersection = PathSeg::Quad(q).intersect_line(v_line)[0]; + assert_approx_eq(intersection.segment_t, 0.5); + assert_approx_eq(intersection.line_t, 0.75); + + let h_line = Line::new((0.0, 0.0), (100.0, 0.0)); + assert_eq!(PathSeg::Quad(q).intersect_line(h_line).len(), 2); + } + + #[test] + fn test_intersect_cubic() { + let c = CubicBez::new((0.0, -10.0), (10.0, 20.0), (20.0, -20.0), (30.0, 10.0)); + let v_line = Line::new((10.0, -10.0), (10.0, 10.0)); + assert_eq!(PathSeg::Cubic(c).intersect_line(v_line).len(), 1); + let intersection = PathSeg::Cubic(c).intersect_line(v_line)[0]; + assert_approx_eq(intersection.segment_t, 0.333333333); + assert_approx_eq(intersection.line_t, 0.592592592); + + let h_line = Line::new((0.0, 0.0), (100.0, 0.0)); + assert_eq!(PathSeg::Cubic(c).intersect_line(h_line).len(), 3); + } + + #[test] + fn test_contains() { + let mut path = BezPath::new(); + path.move_to((0.0, 0.0)); + path.line_to((1.0, 1.0)); + path.line_to((2.0, 0.0)); + path.close_path(); + assert_eq!(path.winding(Point::new(1.0, 0.5)), -1); + assert!(path.contains(Point::new(1.0, 0.5))); + } + + // get_seg(i) should produce the same results as path_segments().nth(i - 1). + #[test] + fn test_get_seg() { + let circle = Circle::new((10.0, 10.0), 2.0).to_path(DEFAULT_ACCURACY); + let segments = circle.path_segments(DEFAULT_ACCURACY).collect::>(); + let get_segs = (1..usize::MAX) + .map_while(|i| circle.get_seg(i)) + .collect::>(); + assert_eq!(segments, get_segs); + } + + #[test] + fn test_control_box() { + // a sort of map ping looking thing drawn with a single cubic + // cbox is wildly different than tight box + let path = BezPath::from_svg("M200,300 C50,50 350,50 200,300").unwrap(); + assert_eq!(Rect::new(50.0, 50.0, 350.0, 300.0), path.control_box()); + assert!(path.control_box().area() > path.bounding_box().area()); + } + + #[test] + fn test_subpaths() { + let path = BezPath::from_svg("M10,10 L0,10 L0,0 L10,0 Z M100,100 M30,0 Q35,10,40,0 L30,0") + .unwrap(); + assert_eq!( + vec![ + BezPath::from_svg("M10,10 L0,10 L0,0 L10,0 Z").unwrap(), + BezPath::from_svg("M100,100").unwrap(), + BezPath::from_svg("M30,0 Q35,10,40,0 L30,0").unwrap(), + ], + path.subpaths() + .map(|sp| BezPath::from_vec(sp.to_vec())) + .collect::>() + ); + } + + #[test] + fn test_reverse_unclosed() { + let path = BezPath::from_svg("M10,10 Q40,40 60,10 L100,10 C125,10 150,50 125,60").unwrap(); + let reversed = path.reverse_subpaths(); + assert_eq!( + "M125,60 C150,50 125,10 100,10 L60,10 Q40,40 10,10", + reversed.to_svg() + ); + } + + #[test] + fn test_reverse_closed_triangle() { + let path = BezPath::from_svg("M100,100 L150,200 L50,200 Z").unwrap(); + let reversed = path.reverse_subpaths(); + assert_eq!("M50,200 L150,200 L100,100 Z", reversed.to_svg()); + } + + #[test] + fn test_reverse_closed_shape() { + let path = BezPath::from_svg( + "M125,100 Q200,150 175,300 C150,150 50,150 25,300 Q0,150 75,100 L100,50 Z", + ) + .unwrap(); + let reversed = path.reverse_subpaths(); + assert_eq!( + "M100,50 L75,100 Q0,150 25,300 C50,150 150,150 175,300 Q200,150 125,100 Z", + reversed.to_svg() + ); + } + + #[test] + fn test_reverse_multiple_subpaths() { + let svg = "M10,10 Q40,40 60,10 L100,10 C125,10 150,50 125,60 M100,100 L150,200 L50,200 Z M125,100 Q200,150 175,300 C150,150 50,150 25,300 Q0,150 75,100 L100,50 Z"; + let expected_svg = "M125,60 C150,50 125,10 100,10 L60,10 Q40,40 10,10 M50,200 L150,200 L100,100 Z M100,50 L75,100 Q0,150 25,300 C50,150 150,150 175,300 Q200,150 125,100 Z"; + let path = BezPath::from_svg(svg).unwrap(); + let reversed = path.reverse_subpaths(); + assert_eq!(expected_svg, reversed.to_svg()); + } + + // https://github.com/fonttools/fonttools/blob/bf265ce49e0cae6f032420a4c80c31d8e16285b8/Tests/pens/reverseContourPen_test.py#L7 + #[test] + fn test_reverse_lines() { + let mut path = BezPath::new(); + path.move_to((0.0, 0.0)); + path.line_to((1.0, 1.0)); + path.line_to((2.0, 2.0)); + path.line_to((3.0, 3.0)); + path.close_path(); + let rev = path.reverse_subpaths(); + assert_eq!("M3,3 L2,2 L1,1 L0,0 Z", rev.to_svg()); + } + + #[test] + fn test_reverse_multiple_moves() { + reverse_test_helper( + vec![ + PathEl::MoveTo((2.0, 2.0).into()), + PathEl::MoveTo((3.0, 3.0).into()), + PathEl::ClosePath, + PathEl::MoveTo((4.0, 4.0).into()), + ], + vec![ + PathEl::MoveTo((2.0, 2.0).into()), + PathEl::MoveTo((3.0, 3.0).into()), + PathEl::ClosePath, + PathEl::MoveTo((4.0, 4.0).into()), + ], + ); + } + + // The following are direct port of fonttools' + // reverseContourPen_test.py::test_reverse_pen, adapted to rust, excluding + // test cases that don't apply because we don't implement + // outputImpliedClosingLine=False. + // https://github.com/fonttools/fonttools/blob/85c80be/Tests/pens/reverseContourPen_test.py#L6-L467 + + #[test] + fn test_reverse_closed_last_line_not_on_move() { + reverse_test_helper( + vec![ + PathEl::MoveTo((0.0, 0.0).into()), + PathEl::LineTo((1.0, 1.0).into()), + PathEl::LineTo((2.0, 2.0).into()), + PathEl::LineTo((3.0, 3.0).into()), + PathEl::ClosePath, + ], + vec![ + PathEl::MoveTo((3.0, 3.0).into()), + PathEl::LineTo((2.0, 2.0).into()), + PathEl::LineTo((1.0, 1.0).into()), + PathEl::LineTo((0.0, 0.0).into()), // closing line NOT implied + PathEl::ClosePath, + ], + ); + } + + #[test] + fn test_reverse_closed_last_line_overlaps_move() { + reverse_test_helper( + vec![ + PathEl::MoveTo((0.0, 0.0).into()), + PathEl::LineTo((1.0, 1.0).into()), + PathEl::LineTo((2.0, 2.0).into()), + PathEl::LineTo((0.0, 0.0).into()), + PathEl::ClosePath, + ], + vec![ + PathEl::MoveTo((0.0, 0.0).into()), + PathEl::LineTo((2.0, 2.0).into()), + PathEl::LineTo((1.0, 1.0).into()), + PathEl::LineTo((0.0, 0.0).into()), // closing line NOT implied + PathEl::ClosePath, + ], + ); + } + + #[test] + fn test_reverse_closed_duplicate_line_following_move() { + reverse_test_helper( + vec![ + PathEl::MoveTo((0.0, 0.0).into()), + PathEl::LineTo((0.0, 0.0).into()), + PathEl::LineTo((1.0, 1.0).into()), + PathEl::LineTo((2.0, 2.0).into()), + PathEl::ClosePath, + ], + vec![ + PathEl::MoveTo((2.0, 2.0).into()), + PathEl::LineTo((1.0, 1.0).into()), + PathEl::LineTo((0.0, 0.0).into()), // duplicate line retained + PathEl::LineTo((0.0, 0.0).into()), + PathEl::ClosePath, + ], + ); + } + + #[test] + fn test_reverse_closed_two_lines() { + reverse_test_helper( + vec![ + PathEl::MoveTo((0.0, 0.0).into()), + PathEl::LineTo((1.0, 1.0).into()), + PathEl::ClosePath, + ], + vec![ + PathEl::MoveTo((1.0, 1.0).into()), + PathEl::LineTo((0.0, 0.0).into()), // closing line NOT implied + PathEl::ClosePath, + ], + ); + } + + #[test] + fn test_reverse_closed_last_curve_overlaps_move() { + reverse_test_helper( + vec![ + PathEl::MoveTo((0.0, 0.0).into()), + PathEl::CurveTo((1.0, 1.0).into(), (2.0, 2.0).into(), (3.0, 3.0).into()), + PathEl::CurveTo((4.0, 4.0).into(), (5.0, 5.0).into(), (0.0, 0.0).into()), + PathEl::ClosePath, + ], + vec![ + PathEl::MoveTo((0.0, 0.0).into()), // no extra lineTo added here + PathEl::CurveTo((5.0, 5.0).into(), (4.0, 4.0).into(), (3.0, 3.0).into()), + PathEl::CurveTo((2.0, 2.0).into(), (1.0, 1.0).into(), (0.0, 0.0).into()), + PathEl::ClosePath, + ], + ); + } + + #[test] + fn test_reverse_closed_last_curve_not_on_move() { + reverse_test_helper( + vec![ + PathEl::MoveTo((0.0, 0.0).into()), + PathEl::CurveTo((1.0, 1.0).into(), (2.0, 2.0).into(), (3.0, 3.0).into()), + PathEl::CurveTo((4.0, 4.0).into(), (5.0, 5.0).into(), (6.0, 6.0).into()), + PathEl::ClosePath, + ], + vec![ + PathEl::MoveTo((6.0, 6.0).into()), // the previously implied line + PathEl::CurveTo((5.0, 5.0).into(), (4.0, 4.0).into(), (3.0, 3.0).into()), + PathEl::CurveTo((2.0, 2.0).into(), (1.0, 1.0).into(), (0.0, 0.0).into()), + PathEl::ClosePath, + ], + ); + } + + #[test] + fn test_reverse_closed_line_curve_line() { + reverse_test_helper( + vec![ + PathEl::MoveTo((0.0, 0.0).into()), + PathEl::LineTo((1.0, 1.0).into()), // this line... + PathEl::CurveTo((2.0, 2.0).into(), (3.0, 3.0).into(), (4.0, 4.0).into()), + PathEl::CurveTo((5.0, 5.0).into(), (6.0, 6.0).into(), (7.0, 7.0).into()), + PathEl::ClosePath, + ], + vec![ + PathEl::MoveTo((7.0, 7.0).into()), + PathEl::CurveTo((6.0, 6.0).into(), (5.0, 5.0).into(), (4.0, 4.0).into()), + PathEl::CurveTo((3.0, 3.0).into(), (2.0, 2.0).into(), (1.0, 1.0).into()), + PathEl::LineTo((0.0, 0.0).into()), // ... does NOT become implied + PathEl::ClosePath, + ], + ); + } + + #[test] + fn test_reverse_closed_last_quad_overlaps_move() { + reverse_test_helper( + vec![ + PathEl::MoveTo((0.0, 0.0).into()), + PathEl::QuadTo((1.0, 1.0).into(), (2.0, 2.0).into()), + PathEl::QuadTo((3.0, 3.0).into(), (0.0, 0.0).into()), + PathEl::ClosePath, + ], + vec![ + PathEl::MoveTo((0.0, 0.0).into()), // no extra lineTo added here + PathEl::QuadTo((3.0, 3.0).into(), (2.0, 2.0).into()), + PathEl::QuadTo((1.0, 1.0).into(), (0.0, 0.0).into()), + PathEl::ClosePath, + ], + ); + } + + #[test] + fn test_reverse_closed_last_quad_not_on_move() { + reverse_test_helper( + vec![ + PathEl::MoveTo((0.0, 0.0).into()), + PathEl::QuadTo((1.0, 1.0).into(), (2.0, 2.0).into()), + PathEl::QuadTo((3.0, 3.0).into(), (4.0, 4.0).into()), + PathEl::ClosePath, + ], + vec![ + PathEl::MoveTo((4.0, 4.0).into()), // the previously implied line + PathEl::QuadTo((3.0, 3.0).into(), (2.0, 2.0).into()), + PathEl::QuadTo((1.0, 1.0).into(), (0.0, 0.0).into()), + PathEl::ClosePath, + ], + ); + } + + #[test] + fn test_reverse_closed_line_quad_line() { + reverse_test_helper( + vec![ + PathEl::MoveTo((0.0, 0.0).into()), + PathEl::LineTo((1.0, 1.0).into()), // this line... + PathEl::QuadTo((2.0, 2.0).into(), (3.0, 3.0).into()), + PathEl::ClosePath, + ], + vec![ + PathEl::MoveTo((3.0, 3.0).into()), + PathEl::QuadTo((2.0, 2.0).into(), (1.0, 1.0).into()), + PathEl::LineTo((0.0, 0.0).into()), // ... does NOT become implied + PathEl::ClosePath, + ], + ); + } + + #[test] + fn test_reverse_empty() { + reverse_test_helper(vec![], vec![]); + } + + #[test] + fn test_reverse_single_point() { + reverse_test_helper( + vec![PathEl::MoveTo((0.0, 0.0).into())], + vec![PathEl::MoveTo((0.0, 0.0).into())], + ); + } + + #[test] + fn test_reverse_single_point_closed() { + reverse_test_helper( + vec![PathEl::MoveTo((0.0, 0.0).into()), PathEl::ClosePath], + vec![PathEl::MoveTo((0.0, 0.0).into()), PathEl::ClosePath], + ); + } + + #[test] + fn test_reverse_single_line_open() { + reverse_test_helper( + vec![ + PathEl::MoveTo((0.0, 0.0).into()), + PathEl::LineTo((1.0, 1.0).into()), + ], + vec![ + PathEl::MoveTo((1.0, 1.0).into()), + PathEl::LineTo((0.0, 0.0).into()), + ], + ); + } + + #[test] + fn test_reverse_single_curve_open() { + reverse_test_helper( + vec![ + PathEl::MoveTo((0.0, 0.0).into()), + PathEl::CurveTo((1.0, 1.0).into(), (2.0, 2.0).into(), (3.0, 3.0).into()), + ], + vec![ + PathEl::MoveTo((3.0, 3.0).into()), + PathEl::CurveTo((2.0, 2.0).into(), (1.0, 1.0).into(), (0.0, 0.0).into()), + ], + ); + } + + #[test] + fn test_reverse_curve_line_open() { + reverse_test_helper( + vec![ + PathEl::MoveTo((0.0, 0.0).into()), + PathEl::CurveTo((1.0, 1.0).into(), (2.0, 2.0).into(), (3.0, 3.0).into()), + PathEl::LineTo((4.0, 4.0).into()), + ], + vec![ + PathEl::MoveTo((4.0, 4.0).into()), + PathEl::LineTo((3.0, 3.0).into()), + PathEl::CurveTo((2.0, 2.0).into(), (1.0, 1.0).into(), (0.0, 0.0).into()), + ], + ); + } + + #[test] + fn test_reverse_line_curve_open() { + reverse_test_helper( + vec![ + PathEl::MoveTo((0.0, 0.0).into()), + PathEl::LineTo((1.0, 1.0).into()), + PathEl::CurveTo((2.0, 2.0).into(), (3.0, 3.0).into(), (4.0, 4.0).into()), + ], + vec![ + PathEl::MoveTo((4.0, 4.0).into()), + PathEl::CurveTo((3.0, 3.0).into(), (2.0, 2.0).into(), (1.0, 1.0).into()), + PathEl::LineTo((0.0, 0.0).into()), + ], + ); + } + + #[test] + fn test_reverse_duplicate_point_after_move() { + // Test case from: https://github.com/googlei18n/cu2qu/issues/51#issue-179370514 + // Simplified to only use atomic PathEl::QuadTo (no QuadSplines). + reverse_test_helper( + vec![ + PathEl::MoveTo((848.0, 348.0).into()), + PathEl::LineTo((848.0, 348.0).into()), + PathEl::QuadTo((848.0, 526.0).into(), (449.0, 704.0).into()), + PathEl::QuadTo((848.0, 171.0).into(), (848.0, 348.0).into()), + PathEl::ClosePath, + ], + vec![ + PathEl::MoveTo((848.0, 348.0).into()), + PathEl::QuadTo((848.0, 171.0).into(), (449.0, 704.0).into()), + PathEl::QuadTo((848.0, 526.0).into(), (848.0, 348.0).into()), + PathEl::LineTo((848.0, 348.0).into()), + PathEl::ClosePath, + ], + ); + } + + #[test] + fn test_reverse_duplicate_point_at_end() { + // Test case from: https://github.com/googlefonts/fontmake/issues/572 + reverse_test_helper( + vec![ + PathEl::MoveTo((0.0, 651.0).into()), + PathEl::LineTo((0.0, 101.0).into()), + PathEl::LineTo((0.0, 101.0).into()), + PathEl::LineTo((0.0, 651.0).into()), + PathEl::LineTo((0.0, 651.0).into()), + PathEl::ClosePath, + ], + vec![ + PathEl::MoveTo((0.0, 651.0).into()), + PathEl::LineTo((0.0, 651.0).into()), + PathEl::LineTo((0.0, 101.0).into()), + PathEl::LineTo((0.0, 101.0).into()), + PathEl::LineTo((0.0, 651.0).into()), + PathEl::ClosePath, + ], + ); + } + + fn reverse_test_helper(contour: Vec, expected: Vec) { + assert_eq!(BezPath(contour).reverse_subpaths().0, expected); + } + + #[test] + fn test_rect_segments() { + // Ensure that `from_path_segments` does not insert spurious MoveTos in + // the middle of a path. + let x0 = 25.189500810000002; + let x1 = 568.18950081; + let y0 = -105.0; + let y1 = 176.0; + let r = Rect::from_points((x0, y0), (x1, y1)); + + let path0 = r.into_path(0.0); + assert!( + path0 + .elements() + .iter() + .skip(1) + .all(|el| !matches!(el, PathEl::MoveTo(_))) + ); + + let path1 = BezPath::from_path_segments(path0.segments()); + assert!( + path1 + .elements() + .iter() + .skip(1) + .all(|el| !matches!(el, PathEl::MoveTo(_))) + ); + } + + #[test] + fn test_current_position() { + let mut path = BezPath::new(); + assert_eq!(path.current_position(), None); + path.move_to((0., 0.)); + assert_eq!(path.current_position(), Some(Point::new(0., 0.))); + path.line_to((10., 10.)); + assert_eq!(path.current_position(), Some(Point::new(10., 10.))); + path.line_to((10., 0.)); + assert_eq!(path.current_position(), Some(Point::new(10., 0.))); + path.close_path(); + assert_eq!(path.current_position(), Some(Point::new(0., 0.))); + + path.close_path(); + assert_eq!(path.current_position(), None); + + path.move_to((0., 10.)); + assert_eq!(path.current_position(), Some(Point::new(0., 10.))); + path.close_path(); + assert_eq!(path.current_position(), Some(Point::new(0., 10.))); + path.close_path(); + assert_eq!(path.current_position(), None); + } + + // Regression test for #531 + // + // When testing the winding number of a point whose y coordinate is very + // close (or equal to) the y coordinate of a segment's start or end, we need + // to be consistent about how we treat it. In particular, in #531 we noticed + // that the point was within the y range of a monotonic segment, but because + // of rounding errors the cubic solver disagreed. + #[test] + fn winding_endpoints() { + let bez = BezPath::from_vec(vec![ + PathEl::MoveTo((200.0, 410.0).into()), + PathEl::CurveTo( + (139.0, 410.0).into(), + (90.0, 360.8772277832031).into(), + (90.0, 300.0).into(), + ), + PathEl::CurveTo( + (90.0, 239.0).into(), + (139.0, 190.0).into(), + (200.0, 190.0).into(), + ), + PathEl::CurveTo( + (150.0, 210.0).into(), + (110.0, 250.0).into(), + (110.0, 300.0).into(), + ), + PathEl::CurveTo( + (110.0, 349.0).into(), + (150.0, 390.0).into(), + (200.0, 390.0).into(), + ), + PathEl::ClosePath, + ]); + + assert!(bez.contains((100.0, 300.1).into())); + assert!(bez.contains((100.0, 299.9).into())); + assert!(bez.contains((100.0, 300.0).into())); + } + + #[test] + fn check_close_subpaths() { + let mut bez = BezPath::new(); + bez.move_to((10.0, 10.0)); + bez.line_to((100.0, 20.0)); + bez.line_to((60.0, 100.0)); + let elements = close_subpaths(&bez).collect::>(); + bez.close_path(); + assert_eq!(&elements, bez.elements()); + + // Test implicit closepath in middle of path + let mut bez2 = BezPath::new(); + bez2.move_to((10.0, 10.0)); + bez2.line_to((100.0, 20.0)); + bez2.line_to((60.0, 100.0)); + bez2.move_to((110.0, 10.0)); + bez2.line_to((200.0, 20.0)); + bez2.line_to((160.0, 100.0)); + let elements2 = close_subpaths(&bez2).collect::>(); + let mut bez3 = BezPath::new(); + bez3.move_to((10.0, 10.0)); + bez3.line_to((100.0, 20.0)); + bez3.line_to((60.0, 100.0)); + bez3.close_path(); + bez3.move_to((110.0, 10.0)); + bez3.line_to((200.0, 20.0)); + bez3.line_to((160.0, 100.0)); + bez3.close_path(); + assert_eq!(&elements2, bez3.elements()); + } + + #[test] + fn close_subpaths_does_not_duplicate_existing_closepath() { + let path = BezPath::from_vec(vec![ + PathEl::MoveTo((0.0, 0.0).into()), + PathEl::LineTo((10.0, 0.0).into()), + PathEl::LineTo((10.0, 10.0).into()), + PathEl::ClosePath, + PathEl::MoveTo((20.0, 0.0).into()), + PathEl::LineTo((30.0, 0.0).into()), + ]); + + let closed = close_subpaths(path.iter()).collect::>(); + + assert_eq!( + closed, + vec![ + PathEl::MoveTo((0.0, 0.0).into()), + PathEl::LineTo((10.0, 0.0).into()), + PathEl::LineTo((10.0, 10.0).into()), + PathEl::ClosePath, + PathEl::MoveTo((20.0, 0.0).into()), + PathEl::LineTo((30.0, 0.0).into()), + PathEl::ClosePath, + ] + ); + } +} diff --git a/vendor/kurbo/src/circle.rs b/vendor/kurbo/src/circle.rs new file mode 100644 index 0000000000..046d22b54c --- /dev/null +++ b/vendor/kurbo/src/circle.rs @@ -0,0 +1,428 @@ +// Copyright 2019 the Kurbo Authors +// SPDX-License-Identifier: Apache-2.0 OR MIT + +//! Implementation of circle shape. + +use core::{ + f64::consts::{FRAC_PI_2, PI}, + iter, + ops::{Add, Mul, Sub}, +}; + +use crate::{Affine, Arc, ArcAppendIter, Ellipse, PathEl, Point, Rect, Shape, Vec2}; + +#[cfg(not(feature = "std"))] +use crate::common::FloatFuncs; + +/// A circle. +#[derive(Clone, Copy, Default, Debug, PartialEq)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +pub struct Circle { + /// The center. + pub center: Point, + /// The radius. + pub radius: f64, +} + +impl Circle { + /// A new circle from center and radius. + #[inline(always)] + pub fn new(center: impl Into, radius: f64) -> Circle { + Circle { + center: center.into(), + radius, + } + } + + /// Create a [`CircleSegment`] by cutting out parts of this circle. + #[inline(always)] + pub fn segment(self, inner_radius: f64, start_angle: f64, sweep_angle: f64) -> CircleSegment { + CircleSegment { + center: self.center, + outer_radius: self.radius, + inner_radius, + start_angle, + sweep_angle, + } + } + + /// Is this circle [finite]? + /// + /// [finite]: f64::is_finite + #[inline] + pub fn is_finite(&self) -> bool { + self.center.is_finite() && self.radius.is_finite() + } + + /// Is this circle [NaN]? + /// + /// [NaN]: f64::is_nan + #[inline] + pub fn is_nan(&self) -> bool { + self.center.is_nan() || self.radius.is_nan() + } +} + +impl Add for Circle { + type Output = Circle; + + #[inline] + fn add(self, v: Vec2) -> Circle { + Circle { + center: self.center + v, + radius: self.radius, + } + } +} + +impl Sub for Circle { + type Output = Circle; + + #[inline] + fn sub(self, v: Vec2) -> Circle { + Circle { + center: self.center - v, + radius: self.radius, + } + } +} + +impl Mul for Affine { + type Output = Ellipse; + fn mul(self, other: Circle) -> Self::Output { + self * Ellipse::from(other) + } +} + +#[doc(hidden)] +pub struct CirclePathIter { + circle: Circle, + delta_th: f64, + arm_len: f64, + ix: usize, + n: usize, +} + +impl Shape for Circle { + type PathElementsIter<'iter> = CirclePathIter; + + fn path_elements(&self, tolerance: f64) -> CirclePathIter { + let scaled_err = self.radius.abs() / tolerance; + let (n, arm_len) = if scaled_err < 1.0 / 1.9608e-4 { + // Solution from http://spencermortensen.com/articles/bezier-circle/ + (4, 0.551915024494) + } else { + // This is empirically determined to fall within error tolerance. + let n = (1.1163 * scaled_err).powf(1.0 / 6.0).ceil() as usize; + // Note: this isn't minimum error, but it is simple and we can easily + // estimate the error. + let arm_len = (4.0 / 3.0) * (FRAC_PI_2 / (n as f64)).tan(); + (n, arm_len) + }; + CirclePathIter { + circle: *self, + delta_th: 2.0 * PI / (n as f64), + arm_len, + ix: 0, + n, + } + } + + #[inline] + fn area(&self) -> f64 { + PI * self.radius.powi(2) + } + + #[inline] + fn perimeter(&self, _accuracy: f64) -> f64 { + (2.0 * PI * self.radius).abs() + } + + fn winding(&self, pt: Point) -> i32 { + if (pt - self.center).hypot2() < self.radius.powi(2) { + 1 + } else { + 0 + } + } + + #[inline] + fn bounding_box(&self) -> Rect { + let r = self.radius.abs(); + let (x, y) = self.center.into(); + Rect::new(x - r, y - r, x + r, y + r) + } + + #[inline(always)] + fn as_circle(&self) -> Option { + Some(*self) + } +} + +impl Iterator for CirclePathIter { + type Item = PathEl; + + fn next(&mut self) -> Option { + let a = self.arm_len; + let r = self.circle.radius; + let (x, y) = self.circle.center.into(); + let ix = self.ix; + self.ix += 1; + if ix == 0 { + Some(PathEl::MoveTo(Point::new(x + r, y))) + } else if ix <= self.n { + let th1 = self.delta_th * (ix as f64); + let th0 = th1 - self.delta_th; + let (s0, c0) = th0.sin_cos(); + let (s1, c1) = if ix == self.n { + (0.0, 1.0) + } else { + th1.sin_cos() + }; + Some(PathEl::CurveTo( + Point::new(x + r * (c0 - a * s0), y + r * (s0 + a * c0)), + Point::new(x + r * (c1 + a * s1), y + r * (s1 - a * c1)), + Point::new(x + r * c1, y + r * s1), + )) + } else if ix == self.n + 1 { + Some(PathEl::ClosePath) + } else { + None + } + } +} + +/// A segment of a circle. +/// +/// If `inner_radius > 0`, then the shape will be a doughnut segment. +#[derive(Clone, Copy, Debug, PartialEq)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +pub struct CircleSegment { + /// The center. + pub center: Point, + /// The outer radius. + pub outer_radius: f64, + /// The inner radius. + pub inner_radius: f64, + /// The angle to start drawing the segment (in radians). + pub start_angle: f64, + /// The arc length of the segment (in radians). + pub sweep_angle: f64, +} + +impl CircleSegment { + /// Create a `CircleSegment` out of its constituent parts. + #[inline(always)] + pub fn new( + center: impl Into, + outer_radius: f64, + inner_radius: f64, + start_angle: f64, + sweep_angle: f64, + ) -> Self { + CircleSegment { + center: center.into(), + outer_radius, + inner_radius, + start_angle, + sweep_angle, + } + } + + /// Return an arc representing the outer radius. + #[must_use] + #[inline(always)] + pub fn outer_arc(&self) -> Arc { + Arc { + center: self.center, + radii: Vec2::new(self.outer_radius, self.outer_radius), + start_angle: self.start_angle, + sweep_angle: self.sweep_angle, + x_rotation: 0.0, + } + } + + /// Return an arc representing the inner radius. + /// + /// This is [reversed] from the outer arc, so that it is in the + /// same direction as the arc that would be drawn (as the path + /// elements for this circle segment produce a closed path). + /// + /// [reversed]: Arc::reversed + #[must_use] + #[inline] + pub fn inner_arc(&self) -> Arc { + Arc { + center: self.center, + radii: Vec2::new(self.inner_radius, self.inner_radius), + start_angle: self.start_angle + self.sweep_angle, + sweep_angle: -self.sweep_angle, + x_rotation: 0.0, + } + } + + /// Is this circle segment [finite]? + /// + /// [finite]: f64::is_finite + #[inline] + pub const fn is_finite(&self) -> bool { + self.center.is_finite() + && self.outer_radius.is_finite() + && self.inner_radius.is_finite() + && self.start_angle.is_finite() + && self.sweep_angle.is_finite() + } + + /// Is this circle segment [NaN]? + /// + /// [NaN]: f64::is_nan + #[inline] + pub const fn is_nan(&self) -> bool { + self.center.is_nan() + || self.outer_radius.is_nan() + || self.inner_radius.is_nan() + || self.start_angle.is_nan() + || self.sweep_angle.is_nan() + } +} + +impl Add for CircleSegment { + type Output = CircleSegment; + + #[inline] + fn add(self, v: Vec2) -> Self { + Self { + center: self.center + v, + ..self + } + } +} + +impl Sub for CircleSegment { + type Output = CircleSegment; + + #[inline] + fn sub(self, v: Vec2) -> Self { + Self { + center: self.center - v, + ..self + } + } +} + +type CircleSegmentPathIter = iter::Chain< + iter::Chain< + iter::Chain, iter::Once>, ArcAppendIter>, + iter::Once, + >, + ArcAppendIter, +>; + +impl Shape for CircleSegment { + type PathElementsIter<'iter> = CircleSegmentPathIter; + + fn path_elements(&self, tolerance: f64) -> CircleSegmentPathIter { + iter::once(PathEl::MoveTo(point_on_circle( + self.center, + self.inner_radius, + self.start_angle, + ))) + // First radius + .chain(iter::once(PathEl::LineTo(point_on_circle( + self.center, + self.outer_radius, + self.start_angle, + )))) + // outer arc + .chain(self.outer_arc().append_iter(tolerance)) + // second radius + .chain(iter::once(PathEl::LineTo(point_on_circle( + self.center, + self.inner_radius, + self.start_angle + self.sweep_angle, + )))) + // inner arc + .chain(self.inner_arc().append_iter(tolerance)) + } + + #[inline] + fn area(&self) -> f64 { + 0.5 * (self.outer_radius.powi(2) - self.inner_radius.powi(2)).abs() * self.sweep_angle + } + + #[inline] + fn perimeter(&self, _accuracy: f64) -> f64 { + 2.0 * (self.outer_radius - self.inner_radius).abs() + + self.sweep_angle * (self.inner_radius + self.outer_radius) + } + + fn winding(&self, pt: Point) -> i32 { + let angle = (pt - self.center).atan2(); + if angle < self.start_angle || angle > self.start_angle + self.sweep_angle { + return 0; + } + let dist2 = (pt - self.center).hypot2(); + if (dist2 < self.outer_radius.powi(2) && dist2 > self.inner_radius.powi(2)) || + // case where outer_radius < inner_radius + (dist2 < self.inner_radius.powi(2) && dist2 > self.outer_radius.powi(2)) + { + 1 + } else { + 0 + } + } + + #[inline] + fn bounding_box(&self) -> Rect { + // todo this is currently not tight + let r = self.inner_radius.max(self.outer_radius); + let (x, y) = self.center.into(); + Rect::new(x - r, y - r, x + r, y + r) + } +} + +#[inline] +fn point_on_circle(center: Point, radius: f64, angle: f64) -> Point { + let (angle_sin, angle_cos) = angle.sin_cos(); + center + + Vec2 { + x: angle_cos * radius, + y: angle_sin * radius, + } +} + +#[cfg(test)] +mod tests { + use crate::{Circle, Point, Shape}; + use std::f64::consts::PI; + + fn assert_approx_eq(x: f64, y: f64) { + // Note: we might want to be more rigorous in testing the accuracy + // of the conversion into Béziers. But this seems good enough. + assert!((x - y).abs() < 1e-7, "{x} != {y}"); + } + + #[test] + fn area_sign() { + let center = Point::new(5.0, 5.0); + let c = Circle::new(center, 5.0); + assert_approx_eq(c.area(), 25.0 * PI); + + assert_eq!(c.winding(center), 1); + + let p = c.to_path(1e-9); + assert_approx_eq(c.area(), p.area()); + assert_eq!(c.winding(center), p.winding(center)); + + let c_neg_radius = Circle::new(center, -5.0); + assert_approx_eq(c_neg_radius.area(), 25.0 * PI); + + assert_eq!(c_neg_radius.winding(center), 1); + + let p_neg_radius = c_neg_radius.to_path(1e-9); + assert_approx_eq(c_neg_radius.area(), p_neg_radius.area()); + assert_eq!(c_neg_radius.winding(center), p_neg_radius.winding(center)); + } +} diff --git a/vendor/kurbo/src/common.rs b/vendor/kurbo/src/common.rs new file mode 100644 index 0000000000..9df3fc7914 --- /dev/null +++ b/vendor/kurbo/src/common.rs @@ -0,0 +1,1121 @@ +// Copyright 2018 the Kurbo Authors +// SPDX-License-Identifier: Apache-2.0 OR MIT + +//! Common mathematical operations + +#![allow(missing_docs)] + +#[cfg(not(feature = "std"))] +mod sealed { + /// A [sealed trait](https://predr.ag/blog/definitive-guide-to-sealed-traits-in-rust/) + /// which stops [`super::FloatFuncs`] from being implemented outside kurbo. This could + /// be relaxed in the future if there is are good reasons to allow external impls. + /// The benefit from being sealed is that we can add methods without breaking downstream + /// implementations. + pub trait FloatFuncsSealed {} +} + +use arrayvec::ArrayVec; + +/// Defines a trait that chooses between libstd or libm implementations of float methods. +/// +/// Some methods will eventually became available in core by +/// [`core_float_math`](https://github.com/rust-lang/rust/issues/137578) +macro_rules! define_float_funcs { + ($( + fn $name:ident(self $(,$arg:ident: $arg_ty:ty)*) -> $ret:ty + => $lname:ident/$lfname:ident; + )+) => { + + /// Since core doesn't depend upon libm, this provides libm implementations + /// of float functions which are typically provided by the std library, when + /// the `std` feature is not enabled. + /// + /// For documentation see the respective functions in the std library. + #[cfg(not(feature = "std"))] + pub trait FloatFuncs : Sized + sealed::FloatFuncsSealed { + /// For documentation see + /// + /// Special implementation, because libm doesn't have it. + fn signum(self) -> Self; + + /// For documentation see + /// + /// Special implementation, because libm doesn't have it. + fn rem_euclid(self, rhs: Self) -> Self; + + $(fn $name(self $(,$arg: $arg_ty)*) -> $ret;)+ + } + + #[cfg(not(feature = "std"))] + impl sealed::FloatFuncsSealed for f32 {} + + #[cfg(not(feature = "std"))] + impl FloatFuncs for f32 { + #[inline] + fn signum(self) -> f32 { + if self.is_nan() { + f32::NAN + } else { + 1.0_f32.copysign(self) + } + } + + #[inline] + fn rem_euclid(self, rhs: Self) -> Self { + let r = self % rhs; + if r < 0.0 { + r + rhs.abs() + } else { + r + } + } + + $(fn $name(self $(,$arg: $arg_ty)*) -> $ret { + #[cfg(feature = "libm")] + return libm::$lfname(self $(,$arg as _)*); + + #[cfg(not(feature = "libm"))] + compile_error!("kurbo requires either the `std` or `libm` feature") + })+ + } + + #[cfg(not(feature = "std"))] + impl sealed::FloatFuncsSealed for f64 {} + #[cfg(not(feature = "std"))] + impl FloatFuncs for f64 { + #[inline] + fn signum(self) -> f64 { + if self.is_nan() { + f64::NAN + } else { + 1.0_f64.copysign(self) + } + } + + #[inline] + fn rem_euclid(self, rhs: Self) -> Self { + let r = self % rhs; + if r < 0.0 { + r + rhs.abs() + } else { + r + } + } + + $(fn $name(self $(,$arg: $arg_ty)*) -> $ret { + #[cfg(feature = "libm")] + return libm::$lname(self $(,$arg as _)*); + + #[cfg(not(feature = "libm"))] + compile_error!("kurbo requires either the `std` or `libm` feature") + })+ + } + } +} + +define_float_funcs! { + fn abs(self) -> Self => fabs/fabsf; + fn acos(self) -> Self => acos/acosf; + fn atan2(self, other: Self) -> Self => atan2/atan2f; + fn cbrt(self) -> Self => cbrt/cbrtf; + fn ceil(self) -> Self => ceil/ceilf; + fn cos(self) -> Self => cos/cosf; + fn copysign(self, sign: Self) -> Self => copysign/copysignf; + fn floor(self) -> Self => floor/floorf; + fn hypot(self, other: Self) -> Self => hypot/hypotf; + fn ln(self) -> Self => log/logf; + fn log2(self) -> Self => log2/log2f; + fn mul_add(self, a: Self, b: Self) -> Self => fma/fmaf; + fn powi(self, n: i32) -> Self => pow/powf; + fn powf(self, n: Self) -> Self => pow/powf; + fn round(self) -> Self => round/roundf; + fn sin(self) -> Self => sin/sinf; + fn sin_cos(self) -> (Self, Self) => sincos/sincosf; + fn sqrt(self) -> Self => sqrt/sqrtf; + fn tan(self) -> Self => tan/tanf; + fn trunc(self) -> Self => trunc/truncf; +} + +/// Adds convenience methods to `f32` and `f64`. +pub trait FloatExt { + /// Rounds to the nearest integer away from zero, + /// unless the provided value is already an integer. + /// + /// It is to `ceil` what `trunc` is to `floor`. + /// + /// # Examples + /// + /// ``` + /// use kurbo::common::FloatExt; + /// + /// let f = 3.7_f64; + /// let g = 3.0_f64; + /// let h = -3.7_f64; + /// let i = -5.1_f32; + /// + /// assert_eq!(f.expand(), 4.0); + /// assert_eq!(g.expand(), 3.0); + /// assert_eq!(h.expand(), -4.0); + /// assert_eq!(i.expand(), -6.0); + /// ``` + fn expand(&self) -> T; +} + +impl FloatExt for f64 { + #[inline] + fn expand(&self) -> f64 { + self.abs().ceil().copysign(*self) + } +} + +impl FloatExt for f32 { + #[inline] + fn expand(&self) -> f32 { + self.abs().ceil().copysign(*self) + } +} + +/// Find real roots of cubic equation. +/// +/// The implementation is not (yet) fully robust, but it does handle the case +/// where `c3` is zero (in that case, solving the quadratic equation). +/// +/// See: +/// +/// That implementation is in turn based on Jim Blinn's "How to Solve a Cubic +/// Equation", which is masterful. +/// +/// Return values of x for which c0 + c1 x + c2 x² + c3 x³ = 0. +pub fn solve_cubic(c0: f64, c1: f64, c2: f64, c3: f64) -> ArrayVec { + let mut result = ArrayVec::new(); + let c3_recip = c3.recip(); + const ONETHIRD: f64 = 1. / 3.; + let scaled_c2 = c2 * (ONETHIRD * c3_recip); + let scaled_c1 = c1 * (ONETHIRD * c3_recip); + let scaled_c0 = c0 * c3_recip; + if !(scaled_c0.is_finite() && scaled_c1.is_finite() && scaled_c2.is_finite()) { + // cubic coefficient is zero or nearly so. + return solve_quadratic(c0, c1, c2).iter().copied().collect(); + } + let (c0, c1, c2) = (scaled_c0, scaled_c1, scaled_c2); + // (d0, d1, d2) is called "Delta" in article + let d0 = (-c2).mul_add(c2, c1); + let d1 = (-c1).mul_add(c2, c0); + let d2 = c2 * c0 - c1 * c1; + // d is called "Discriminant" + let d = 4.0 * d0 * d2 - d1 * d1; + // de is called "Depressed.x", Depressed.y = d0 + let de = (-2.0 * c2).mul_add(d0, d1); + // TODO: handle the cases where these intermediate results overflow. + if d < 0.0 { + let sq = (-0.25 * d).sqrt(); + let r = -0.5 * de; + let t1 = (r + sq).cbrt() + (r - sq).cbrt(); + result.push(t1 - c2); + } else if d == 0.0 { + let t1 = (-d0).sqrt().copysign(de); + result.push(t1 - c2); + result.push(-2.0 * t1 - c2); + } else { + let th = d.sqrt().atan2(-de) * ONETHIRD; + // (th_cos, th_sin) is called "CubicRoot" + let (th_sin, th_cos) = th.sin_cos(); + // (r0, r1, r2) is called "Root" + let r0 = th_cos; + let ss3 = th_sin * 3.0f64.sqrt(); + let r1 = 0.5 * (-th_cos + ss3); + let r2 = 0.5 * (-th_cos - ss3); + let t = 2.0 * (-d0).sqrt(); + result.push(t.mul_add(r0, -c2)); + result.push(t.mul_add(r1, -c2)); + result.push(t.mul_add(r2, -c2)); + } + result +} + +/// Find real roots of quadratic equation. +/// +/// Return values of x for which c0 + c1 x + c2 x² = 0. +/// +/// This function tries to be quite numerically robust. If the equation +/// is nearly linear, it will return the root ignoring the quadratic term; +/// the other root might be out of representable range. In the degenerate +/// case where all coefficients are zero, so that all values of x satisfy +/// the equation, a single `0.0` is returned. +pub fn solve_quadratic(c0: f64, c1: f64, c2: f64) -> ArrayVec { + let mut result = ArrayVec::new(); + let sc0 = c0 * c2.recip(); + let sc1 = c1 * c2.recip(); + if !sc0.is_finite() || !sc1.is_finite() { + // c2 is zero or very small, treat as linear eqn + let root = -c0 / c1; + if root.is_finite() { + result.push(root); + } else if c0 == 0.0 && c1 == 0.0 { + // Degenerate case + result.push(0.0); + } + return result; + } + let arg = sc1 * sc1 - 4. * sc0; + let root1 = if !arg.is_finite() { + // Likely, calculation of sc1 * sc1 overflowed. Find one root + // using sc1 x + x² = 0, other root as sc0 / root1. + -sc1 + } else { + if arg < 0.0 { + return result; + } else if arg == 0.0 { + result.push(-0.5 * sc1); + return result; + } + // See https://math.stackexchange.com/questions/866331 + -0.5 * (sc1 + arg.sqrt().copysign(sc1)) + }; + let root2 = sc0 / root1; + if root2.is_finite() { + // Sort just to be friendly and make results deterministic. + if root2 > root1 { + result.push(root1); + result.push(root2); + } else { + result.push(root2); + result.push(root1); + } + } else { + result.push(root1); + } + result +} + +/// Compute epsilon relative to coefficient. +/// +/// A helper function from the Orellana and De Michele paper. +fn eps_rel(raw: f64, a: f64) -> f64 { + if a == 0.0 { + raw.abs() + } else { + ((raw - a) / a).abs() + } +} + +/// Find real roots of a quartic equation. +/// +/// This is a fairly literal implementation of the method described in: +/// Algorithm 1010: Boosting Efficiency in Solving Quartic Equations with +/// No Compromise in Accuracy, Orellana and De Michele, ACM +/// Transactions on Mathematical Software, Vol. 46, No. 2, May 2020. +pub fn solve_quartic(c0: f64, c1: f64, c2: f64, c3: f64, c4: f64) -> ArrayVec { + if c4 == 0.0 { + return solve_cubic(c0, c1, c2, c3).iter().copied().collect(); + } + if c0 == 0.0 { + // Note: appends 0 root at end, doesn't sort. We might want to do that. + return solve_cubic(c1, c2, c3, c4) + .iter() + .copied() + .chain(Some(0.0)) + .collect(); + } + let a = c3 / c4; + let b = c2 / c4; + let c = c1 / c4; + let d = c0 / c4; + if let Some(result) = solve_quartic_inner(a, b, c, d, false) { + return result; + } + // Do polynomial rescaling + const K_Q: f64 = 7.16e76; + for rescale in [false, true] { + if let Some(result) = solve_quartic_inner( + a / K_Q, + b / K_Q.powi(2), + c / K_Q.powi(3), + d / K_Q.powi(4), + rescale, + ) { + return result.iter().map(|x| x * K_Q).collect(); + } + } + // Overflow happened, just return no roots. + //println!("overflow, no roots returned"); + ArrayVec::default() +} + +fn solve_quartic_inner(a: f64, b: f64, c: f64, d: f64, rescale: bool) -> Option> { + factor_quartic_inner(a, b, c, d, rescale).map(|quadratics| { + quadratics + .iter() + .flat_map(|(a, b)| solve_quadratic(*b, *a, 1.0)) + .collect() + }) +} + +/// Factor a quartic into two quadratics. +/// +/// Attempt to factor a quartic equation into two quadratic equations. Returns `None` either if there +/// is overflow (in which case rescaling might succeed) or the factorization would result in +/// complex coefficients. +/// +/// Discussion question: distinguish the two cases in return value? +pub fn factor_quartic_inner( + a: f64, + b: f64, + c: f64, + d: f64, + rescale: bool, +) -> Option> { + let calc_eps_q = |a1, b1, a2, b2| { + let eps_a = eps_rel(a1 + a2, a); + let eps_b = eps_rel(b1 + a1 * a2 + b2, b); + let eps_c = eps_rel(b1 * a2 + a1 * b2, c); + eps_a + eps_b + eps_c + }; + let calc_eps_t = |a1, b1, a2, b2| calc_eps_q(a1, b1, a2, b2) + eps_rel(b1 * b2, d); + let disc = 9. * a * a - 24. * b; + let s = if disc >= 0.0 { + -2. * b / (3. * a + disc.sqrt().copysign(a)) + } else { + -0.25 * a + }; + let a_prime = a + 4. * s; + let b_prime = b + 3. * s * (a + 2. * s); + let c_prime = c + s * (2. * b + s * (3. * a + 4. * s)); + let d_prime = d + s * (c + s * (b + s * (a + s))); + let g_prime; + let h_prime; + const K_C: f64 = 3.49e102; + if rescale { + let a_prime_s = a_prime / K_C; + let b_prime_s = b_prime / K_C; + let c_prime_s = c_prime / K_C; + let d_prime_s = d_prime / K_C; + g_prime = a_prime_s * c_prime_s - (4. / K_C) * d_prime_s - (1. / 3.) * b_prime_s.powi(2); + h_prime = (a_prime_s * c_prime_s + (8. / K_C) * d_prime_s - (2. / 9.) * b_prime_s.powi(2)) + * (1. / 3.) + * b_prime_s + - c_prime_s * (c_prime_s / K_C) + - a_prime_s.powi(2) * d_prime_s; + } else { + g_prime = a_prime * c_prime - 4. * d_prime - (1. / 3.) * b_prime.powi(2); + h_prime = + (a_prime * c_prime + 8. * d_prime - (2. / 9.) * b_prime.powi(2)) * (1. / 3.) * b_prime + - c_prime.powi(2) + - a_prime.powi(2) * d_prime; + } + if !(g_prime.is_finite() && h_prime.is_finite()) { + return None; + } + let phi = depressed_cubic_dominant(g_prime, h_prime); + let phi = if rescale { phi * K_C } else { phi }; + let l_1 = a * 0.5; + let l_3 = (1. / 6.) * b + 0.5 * phi; + let delt_2 = c - a * l_3; + let d_2_cand_1 = (2. / 3.) * b - phi - l_1 * l_1; + let l_2_cand_1 = 0.5 * delt_2 / d_2_cand_1; + let l_2_cand_2 = 2. * (d - l_3 * l_3) / delt_2; + let d_2_cand_2 = 0.5 * delt_2 / l_2_cand_2; + let d_2_cand_3 = d_2_cand_1; + let l_2_cand_3 = l_2_cand_2; + let mut d_2_best = 0.0; + let mut l_2_best = 0.0; + let mut eps_l_best = 0.0; + for (i, (d_2, l_2)) in [ + (d_2_cand_1, l_2_cand_1), + (d_2_cand_2, l_2_cand_2), + (d_2_cand_3, l_2_cand_3), + ] + .iter() + .enumerate() + { + let eps_0 = eps_rel(d_2 + l_1 * l_1 + 2. * l_3, b); + let eps_1 = eps_rel(2. * (d_2 * l_2 + l_1 * l_3), c); + let eps_2 = eps_rel(d_2 * l_2 * l_2 + l_3 * l_3, d); + let eps_l = eps_0 + eps_1 + eps_2; + if i == 0 || eps_l < eps_l_best { + d_2_best = *d_2; + l_2_best = *l_2; + eps_l_best = eps_l; + } + } + let d_2 = d_2_best; + let l_2 = l_2_best; + let mut alpha_1; + let mut beta_1; + let mut alpha_2; + let mut beta_2; + //println!("phi = {}, d_2 = {}", phi, d_2); + if d_2 < 0.0 { + let sq = (-d_2).sqrt(); + alpha_1 = l_1 + sq; + beta_1 = l_3 + sq * l_2; + alpha_2 = l_1 - sq; + beta_2 = l_3 - sq * l_2; + if beta_2.abs() < beta_1.abs() { + beta_2 = d / beta_1; + } else if beta_2.abs() > beta_1.abs() { + beta_1 = d / beta_2; + } + let cands; + if alpha_1.abs() != alpha_2.abs() { + if alpha_1.abs() < alpha_2.abs() { + let a1_cand_1 = (c - beta_1 * alpha_2) / beta_2; + let a1_cand_2 = (b - beta_2 - beta_1) / alpha_2; + let a1_cand_3 = a - alpha_2; + // Note: cand 3 is first because it is infallible, simplifying logic + cands = [ + (a1_cand_3, alpha_2), + (a1_cand_1, alpha_2), + (a1_cand_2, alpha_2), + ]; + } else { + let a2_cand_1 = (c - alpha_1 * beta_2) / beta_1; + let a2_cand_2 = (b - beta_2 - beta_1) / alpha_1; + let a2_cand_3 = a - alpha_1; + cands = [ + (alpha_1, a2_cand_3), + (alpha_1, a2_cand_1), + (alpha_1, a2_cand_2), + ]; + } + let mut eps_q_best = 0.0; + for (i, (a1, a2)) in cands.iter().enumerate() { + if a1.is_finite() && a2.is_finite() { + let eps_q = calc_eps_q(*a1, beta_1, *a2, beta_2); + if i == 0 || eps_q < eps_q_best { + alpha_1 = *a1; + alpha_2 = *a2; + eps_q_best = eps_q; + } + } + } + } + } else if d_2 == 0.0 { + let d_3 = d - l_3 * l_3; + alpha_1 = l_1; + beta_1 = l_3 + (-d_3).sqrt(); + alpha_2 = l_1; + beta_2 = l_3 - (-d_3).sqrt(); + if beta_1.abs() > beta_2.abs() { + beta_2 = d / beta_1; + } else if beta_2.abs() > beta_1.abs() { + beta_1 = d / beta_2; + } + // TODO: handle case d_2 is very small? + } else { + // This case means no real roots; in the most general case we might want + // to factor into quadratic equations with complex coefficients. + return None; + } + // Newton-Raphson iteration on alpha/beta coeff's. + let mut eps_t = calc_eps_t(alpha_1, beta_1, alpha_2, beta_2); + for _ in 0..8 { + //println!("a1 {} b1 {} a2 {} b2 {}", alpha_1, beta_1, alpha_2, beta_2); + //println!("eps_t = {:e}", eps_t); + if eps_t == 0.0 { + break; + } + let f_0 = beta_1 * beta_2 - d; + let f_1 = beta_1 * alpha_2 + alpha_1 * beta_2 - c; + let f_2 = beta_1 + alpha_1 * alpha_2 + beta_2 - b; + let f_3 = alpha_1 + alpha_2 - a; + let c_1 = alpha_1 - alpha_2; + let det_j = beta_1 * beta_1 - beta_1 * (alpha_2 * c_1 + 2. * beta_2) + + beta_2 * (alpha_1 * c_1 + beta_2); + if det_j == 0.0 { + break; + } + let inv = det_j.recip(); + let c_2 = beta_2 - beta_1; + let c_3 = beta_1 * alpha_2 - alpha_1 * beta_2; + let dz_0 = c_1 * f_0 + c_2 * f_1 + c_3 * f_2 - (beta_1 * c_2 + alpha_1 * c_3) * f_3; + let dz_1 = (alpha_1 * c_1 + c_2) * f_0 + - beta_1 * c_1 * f_1 + - beta_1 * c_2 * f_2 + - beta_1 * c_3 * f_3; + let dz_2 = -c_1 * f_0 - c_2 * f_1 - c_3 * f_2 + (alpha_2 * c_3 + beta_2 * c_2) * f_3; + let dz_3 = -(alpha_2 * c_1 + c_2) * f_0 + + beta_2 * c_1 * f_1 + + beta_2 * c_2 * f_2 + + beta_2 * c_3 * f_3; + let a1 = alpha_1 - inv * dz_0; + let b1 = beta_1 - inv * dz_1; + let a2 = alpha_2 - inv * dz_2; + let b2 = beta_2 - inv * dz_3; + let new_eps_t = calc_eps_t(a1, b1, a2, b2); + // We break if the new eps is equal, paper keeps going + if new_eps_t < eps_t { + alpha_1 = a1; + beta_1 = b1; + alpha_2 = a2; + beta_2 = b2; + eps_t = new_eps_t; + } else { + //println!("new_eps_t got worse: {:e}", new_eps_t); + break; + } + } + Some([(alpha_1, beta_1), (alpha_2, beta_2)].into()) +} + +/// Dominant root of depressed cubic x^3 + gx + h = 0. +/// +/// Section 2.2 of Orellana and De Michele. +// Note: some of the techniques in here might be useful to improve the +// cubic solver, and vice versa. +fn depressed_cubic_dominant(g: f64, h: f64) -> f64 { + let q = (-1. / 3.) * g; + let r = 0.5 * h; + let phi_0; + let k = if q.abs() < 1e102 && r.abs() < 1e154 { + None + } else if q.abs() < r.abs() { + Some(1. - q * (q / r).powi(2)) + } else { + Some(q.signum() * ((r / q).powi(2) / q - 1.0)) + }; + if k.is_some() && r == 0.0 { + if g > 0.0 { + phi_0 = 0.0; + } else { + phi_0 = (-g).sqrt(); + } + } else if k.map(|k| k < 0.0).unwrap_or_else(|| r * r < q.powi(3)) { + let t = if k.is_some() { + r / q / q.sqrt() + } else { + r / q.powi(3).sqrt() + }; + phi_0 = -2. * q.sqrt() * (t.abs().acos() * (1. / 3.)).cos().copysign(t); + } else { + let a = if let Some(k) = k { + if q.abs() < r.abs() { + -r * (1. + k.sqrt()) + } else { + -r - (q.abs().sqrt() * q * k.sqrt()).copysign(r) + } + } else { + -r - (r * r - q.powi(3)).sqrt().copysign(r) + } + .cbrt(); + let b = if a == 0.0 { 0.0 } else { q / a }; + phi_0 = a + b; + } + // Refine with Newton-Raphson iteration + let mut x = phi_0; + let mut f = (x * x + g) * x + h; + //println!("g = {:e}, h = {:e}, x = {:e}, f = {:e}", g, h, x, f); + const EPS_M: f64 = 2.22045e-16; + if f.abs() < EPS_M * x.powi(3).max(g * x).max(h) { + return x; + } + for _ in 0..8 { + let delt_f = 3. * x * x + g; + if delt_f == 0.0 { + break; + } + let new_x = x - f / delt_f; + let new_f = (new_x * new_x + g) * new_x + h; + //println!("delt_f = {:e}, new_f = {:e}", delt_f, new_f); + if new_f == 0.0 { + return new_x; + } + if new_f.abs() >= f.abs() { + break; + } + x = new_x; + f = new_f; + } + x +} + +/// Solve an arbitrary function for a zero-crossing. +/// +/// This uses the [ITP method], as described in the paper +/// [An Enhancement of the Bisection Method Average Performance Preserving Minmax Optimality]. +/// +/// The values of `ya` and `yb` are given as arguments rather than +/// computed from `f`, as the values may already be known, or they may +/// be less expensive to compute as special cases. +/// +/// It is assumed that `ya < 0.0` and `yb > 0.0`, otherwise unexpected +/// results may occur. +/// +/// The value of `epsilon` must be larger than 2^-63 times `b - a`, +/// otherwise integer overflow may occur. The `a` and `b` parameters +/// represent the lower and upper bounds of the bracket searched for a +/// solution. +/// +/// The ITP method has tuning parameters. This implementation hardwires +/// k2 to 2, both because it avoids an expensive floating point +/// exponentiation, and because this value has been tested to work well +/// with curve fitting problems. +/// +/// The `n0` parameter controls the relative impact of the bisection and +/// secant components. When it is 0, the number of iterations is +/// guaranteed to be no more than the number required by bisection (thus, +/// this method is strictly superior to bisection). However, when the +/// function is smooth, a value of 1 gives the secant method more of a +/// chance to engage, so the average number of iterations is likely +/// lower, though there can be one more iteration than bisection in the +/// worst case. +/// +/// The `k1` parameter is harder to characterize, and interested users +/// are referred to the paper, as well as encouraged to do empirical +/// testing. To match the paper, a value of `0.2 / (b - a)` is +/// suggested, and this is confirmed to give good results. +/// +/// When the function is monotonic, the returned result is guaranteed to +/// be within `epsilon` of the zero crossing. For more detailed analysis, +/// again see the paper. +/// +/// [ITP method]: https://en.wikipedia.org/wiki/ITP_Method +/// [An Enhancement of the Bisection Method Average Performance Preserving Minmax Optimality]: https://dl.acm.org/doi/10.1145/3423597 +#[allow(clippy::too_many_arguments)] +pub fn solve_itp( + mut f: impl FnMut(f64) -> f64, + a: f64, + b: f64, + epsilon: f64, + n0: usize, + k1: f64, + ya: f64, + yb: f64, +) -> f64 { + use core::convert::Infallible; + let (a, b) = solve_itp_fallible(|x| Ok::<_, Infallible>(f(x)), a, b, epsilon, n0, k1, ya, yb) + .expect("Infallible `f` never returns `Err`"); + + // Return the midpoint of the bracket returned by `solve_itp_fallible`. If that found an exact + // zero, it returns `(a, a)`, and the following will result in exactly `a` (except for harmless + // negative zero subtlety or when `a + b` overflows ~1e308). + 0.5 * (a + b) +} + +/// A variant ITP solver that allows fallible functions. +/// +/// Another difference: it returns the bracket that contains the root, +/// which may be important if the function has a discontinuity. +#[allow(clippy::too_many_arguments)] +pub(crate) fn solve_itp_fallible( + mut f: impl FnMut(f64) -> Result, + mut a: f64, + mut b: f64, + epsilon: f64, + n0: usize, + k1: f64, + mut ya: f64, + mut yb: f64, +) -> Result<(f64, f64), E> { + let n1_2 = (((b - a) / epsilon).log2().ceil() - 1.0).max(0.0) as usize; + let nmax = n0 + n1_2; + let mut scaled_epsilon = epsilon * (1u64 << nmax) as f64; + while b - a > 2.0 * epsilon { + let x1_2 = 0.5 * (a + b); + let r = scaled_epsilon - 0.5 * (b - a); + let xf = (yb * a - ya * b) / (yb - ya); + let sigma = x1_2 - xf; + // This has k2 = 2 hardwired for efficiency. + let delta = k1 * (b - a).powi(2); + let xt = if delta <= (x1_2 - xf).abs() { + xf + delta.copysign(sigma) + } else { + x1_2 + }; + let xitp = if (xt - x1_2).abs() <= r { + xt + } else { + x1_2 - r.copysign(sigma) + }; + let yitp = f(xitp)?; + if yitp > 0.0 { + b = xitp; + yb = yitp; + } else if yitp < 0.0 { + a = xitp; + ya = yitp; + } else { + return Ok((xitp, xitp)); + } + scaled_epsilon *= 0.5; + } + Ok((a, b)) +} + +// Tables of Legendre-Gauss quadrature coefficients, adapted from: +// + +pub const GAUSS_LEGENDRE_COEFFS_3: &[(f64, f64)] = &[ + (0.8888888888888888, 0.0000000000000000), + (0.5555555555555556, -0.7745966692414834), + (0.5555555555555556, 0.7745966692414834), +]; + +pub const GAUSS_LEGENDRE_COEFFS_4: &[(f64, f64)] = &[ + (0.6521451548625461, -0.3399810435848563), + (0.6521451548625461, 0.3399810435848563), + (0.3478548451374538, -0.8611363115940526), + (0.3478548451374538, 0.8611363115940526), +]; + +pub const GAUSS_LEGENDRE_COEFFS_5: &[(f64, f64)] = &[ + (0.5688888888888889, 0.0000000000000000), + (0.4786286704993665, -0.5384693101056831), + (0.4786286704993665, 0.5384693101056831), + (0.2369268850561891, -0.9061798459386640), + (0.2369268850561891, 0.9061798459386640), +]; + +pub const GAUSS_LEGENDRE_COEFFS_6: &[(f64, f64)] = &[ + (0.3607615730481386, 0.6612093864662645), + (0.3607615730481386, -0.6612093864662645), + (0.4679139345726910, -0.2386191860831969), + (0.4679139345726910, 0.2386191860831969), + (0.1713244923791704, -0.9324695142031521), + (0.1713244923791704, 0.9324695142031521), +]; + +pub const GAUSS_LEGENDRE_COEFFS_7: &[(f64, f64)] = &[ + (0.4179591836734694, 0.0000000000000000), + (0.3818300505051189, 0.4058451513773972), + (0.3818300505051189, -0.4058451513773972), + (0.2797053914892766, -0.7415311855993945), + (0.2797053914892766, 0.7415311855993945), + (0.1294849661688697, -0.9491079123427585), + (0.1294849661688697, 0.9491079123427585), +]; + +pub const GAUSS_LEGENDRE_COEFFS_8: &[(f64, f64)] = &[ + (0.3626837833783620, -0.1834346424956498), + (0.3626837833783620, 0.1834346424956498), + (0.3137066458778873, -0.5255324099163290), + (0.3137066458778873, 0.5255324099163290), + (0.2223810344533745, -0.7966664774136267), + (0.2223810344533745, 0.7966664774136267), + (0.1012285362903763, -0.9602898564975363), + (0.1012285362903763, 0.9602898564975363), +]; + +pub const GAUSS_LEGENDRE_COEFFS_8_HALF: &[(f64, f64)] = &[ + (0.3626837833783620, 0.1834346424956498), + (0.3137066458778873, 0.5255324099163290), + (0.2223810344533745, 0.7966664774136267), + (0.1012285362903763, 0.9602898564975363), +]; + +pub const GAUSS_LEGENDRE_COEFFS_9: &[(f64, f64)] = &[ + (0.3302393550012598, 0.0000000000000000), + (0.1806481606948574, -0.8360311073266358), + (0.1806481606948574, 0.8360311073266358), + (0.0812743883615744, -0.9681602395076261), + (0.0812743883615744, 0.9681602395076261), + (0.3123470770400029, -0.3242534234038089), + (0.3123470770400029, 0.3242534234038089), + (0.2606106964029354, -0.6133714327005904), + (0.2606106964029354, 0.6133714327005904), +]; + +pub const GAUSS_LEGENDRE_COEFFS_11: &[(f64, f64)] = &[ + (0.2729250867779006, 0.0000000000000000), + (0.2628045445102467, -0.2695431559523450), + (0.2628045445102467, 0.2695431559523450), + (0.2331937645919905, -0.5190961292068118), + (0.2331937645919905, 0.5190961292068118), + (0.1862902109277343, -0.7301520055740494), + (0.1862902109277343, 0.7301520055740494), + (0.1255803694649046, -0.8870625997680953), + (0.1255803694649046, 0.8870625997680953), + (0.0556685671161737, -0.9782286581460570), + (0.0556685671161737, 0.9782286581460570), +]; + +pub const GAUSS_LEGENDRE_COEFFS_16: &[(f64, f64)] = &[ + (0.1894506104550685, -0.0950125098376374), + (0.1894506104550685, 0.0950125098376374), + (0.1826034150449236, -0.2816035507792589), + (0.1826034150449236, 0.2816035507792589), + (0.1691565193950025, -0.4580167776572274), + (0.1691565193950025, 0.4580167776572274), + (0.1495959888165767, -0.6178762444026438), + (0.1495959888165767, 0.6178762444026438), + (0.1246289712555339, -0.7554044083550030), + (0.1246289712555339, 0.7554044083550030), + (0.0951585116824928, -0.8656312023878318), + (0.0951585116824928, 0.8656312023878318), + (0.0622535239386479, -0.9445750230732326), + (0.0622535239386479, 0.9445750230732326), + (0.0271524594117541, -0.9894009349916499), + (0.0271524594117541, 0.9894009349916499), +]; + +// Just the positive x_i values. +pub const GAUSS_LEGENDRE_COEFFS_16_HALF: &[(f64, f64)] = &[ + (0.1894506104550685, 0.0950125098376374), + (0.1826034150449236, 0.2816035507792589), + (0.1691565193950025, 0.4580167776572274), + (0.1495959888165767, 0.6178762444026438), + (0.1246289712555339, 0.7554044083550030), + (0.0951585116824928, 0.8656312023878318), + (0.0622535239386479, 0.9445750230732326), + (0.0271524594117541, 0.9894009349916499), +]; + +pub const GAUSS_LEGENDRE_COEFFS_24: &[(f64, f64)] = &[ + (0.1279381953467522, -0.0640568928626056), + (0.1279381953467522, 0.0640568928626056), + (0.1258374563468283, -0.1911188674736163), + (0.1258374563468283, 0.1911188674736163), + (0.1216704729278034, -0.3150426796961634), + (0.1216704729278034, 0.3150426796961634), + (0.1155056680537256, -0.4337935076260451), + (0.1155056680537256, 0.4337935076260451), + (0.1074442701159656, -0.5454214713888396), + (0.1074442701159656, 0.5454214713888396), + (0.0976186521041139, -0.6480936519369755), + (0.0976186521041139, 0.6480936519369755), + (0.0861901615319533, -0.7401241915785544), + (0.0861901615319533, 0.7401241915785544), + (0.0733464814110803, -0.8200019859739029), + (0.0733464814110803, 0.8200019859739029), + (0.0592985849154368, -0.8864155270044011), + (0.0592985849154368, 0.8864155270044011), + (0.0442774388174198, -0.9382745520027328), + (0.0442774388174198, 0.9382745520027328), + (0.0285313886289337, -0.9747285559713095), + (0.0285313886289337, 0.9747285559713095), + (0.0123412297999872, -0.9951872199970213), + (0.0123412297999872, 0.9951872199970213), +]; + +pub const GAUSS_LEGENDRE_COEFFS_24_HALF: &[(f64, f64)] = &[ + (0.1279381953467522, 0.0640568928626056), + (0.1258374563468283, 0.1911188674736163), + (0.1216704729278034, 0.3150426796961634), + (0.1155056680537256, 0.4337935076260451), + (0.1074442701159656, 0.5454214713888396), + (0.0976186521041139, 0.6480936519369755), + (0.0861901615319533, 0.7401241915785544), + (0.0733464814110803, 0.8200019859739029), + (0.0592985849154368, 0.8864155270044011), + (0.0442774388174198, 0.9382745520027328), + (0.0285313886289337, 0.9747285559713095), + (0.0123412297999872, 0.9951872199970213), +]; + +pub const GAUSS_LEGENDRE_COEFFS_32: &[(f64, f64)] = &[ + (0.0965400885147278, -0.0483076656877383), + (0.0965400885147278, 0.0483076656877383), + (0.0956387200792749, -0.1444719615827965), + (0.0956387200792749, 0.1444719615827965), + (0.0938443990808046, -0.2392873622521371), + (0.0938443990808046, 0.2392873622521371), + (0.0911738786957639, -0.3318686022821277), + (0.0911738786957639, 0.3318686022821277), + (0.0876520930044038, -0.4213512761306353), + (0.0876520930044038, 0.4213512761306353), + (0.0833119242269467, -0.5068999089322294), + (0.0833119242269467, 0.5068999089322294), + (0.0781938957870703, -0.5877157572407623), + (0.0781938957870703, 0.5877157572407623), + (0.0723457941088485, -0.6630442669302152), + (0.0723457941088485, 0.6630442669302152), + (0.0658222227763618, -0.7321821187402897), + (0.0658222227763618, 0.7321821187402897), + (0.0586840934785355, -0.7944837959679424), + (0.0586840934785355, 0.7944837959679424), + (0.0509980592623762, -0.8493676137325700), + (0.0509980592623762, 0.8493676137325700), + (0.0428358980222267, -0.8963211557660521), + (0.0428358980222267, 0.8963211557660521), + (0.0342738629130214, -0.9349060759377397), + (0.0342738629130214, 0.9349060759377397), + (0.0253920653092621, -0.9647622555875064), + (0.0253920653092621, 0.9647622555875064), + (0.0162743947309057, -0.9856115115452684), + (0.0162743947309057, 0.9856115115452684), + (0.0070186100094701, -0.9972638618494816), + (0.0070186100094701, 0.9972638618494816), +]; + +pub const GAUSS_LEGENDRE_COEFFS_32_HALF: &[(f64, f64)] = &[ + (0.0965400885147278, 0.0483076656877383), + (0.0956387200792749, 0.1444719615827965), + (0.0938443990808046, 0.2392873622521371), + (0.0911738786957639, 0.3318686022821277), + (0.0876520930044038, 0.4213512761306353), + (0.0833119242269467, 0.5068999089322294), + (0.0781938957870703, 0.5877157572407623), + (0.0723457941088485, 0.6630442669302152), + (0.0658222227763618, 0.7321821187402897), + (0.0586840934785355, 0.7944837959679424), + (0.0509980592623762, 0.8493676137325700), + (0.0428358980222267, 0.8963211557660521), + (0.0342738629130214, 0.9349060759377397), + (0.0253920653092621, 0.9647622555875064), + (0.0162743947309057, 0.9856115115452684), + (0.0070186100094701, 0.9972638618494816), +]; + +#[cfg(test)] +mod tests { + use crate::common::*; + use arrayvec::ArrayVec; + + fn verify(mut roots: ArrayVec, expected: &[f64]) { + assert_eq!(expected.len(), roots.len()); + let epsilon = 1e-12; + roots.sort_by(|a, b| a.partial_cmp(b).unwrap()); + for i in 0..expected.len() { + assert!((roots[i] - expected[i]).abs() < epsilon); + } + } + + #[test] + fn test_solve_cubic() { + verify(solve_cubic(-5.0, 0.0, 0.0, 1.0), &[5.0f64.cbrt()]); + verify(solve_cubic(-5.0, -1.0, 0.0, 1.0), &[1.90416085913492]); + verify(solve_cubic(0.0, -1.0, 0.0, 1.0), &[-1.0, 0.0, 1.0]); + verify(solve_cubic(-2.0, -3.0, 0.0, 1.0), &[-1.0, 2.0]); + verify(solve_cubic(2.0, -3.0, 0.0, 1.0), &[-2.0, 1.0]); + verify( + solve_cubic(2.0 - 1e-12, 5.0, 4.0, 1.0), + &[ + -1.9999999999989995, + -1.0000010000848456, + -0.9999989999161546, + ], + ); + verify(solve_cubic(2.0 + 1e-12, 5.0, 4.0, 1.0), &[-2.0]); + } + + #[test] + fn test_solve_quadratic() { + verify( + solve_quadratic(-5.0, 0.0, 1.0), + &[-(5.0f64.sqrt()), 5.0f64.sqrt()], + ); + verify(solve_quadratic(5.0, 0.0, 1.0), &[]); + verify(solve_quadratic(5.0, 1.0, 0.0), &[-5.0]); + verify(solve_quadratic(1.0, 2.0, 1.0), &[-1.0]); + } + + #[test] + fn test_solve_quartic() { + // These test cases are taken from Orellana and De Michele paper (Table 1). + fn test_with_roots(coeffs: [f64; 4], roots: &[f64], rel_err: f64) { + // Note: in paper, coefficients are in decreasing order. + let mut actual = solve_quartic(coeffs[3], coeffs[2], coeffs[1], coeffs[0], 1.0); + actual.sort_by(f64::total_cmp); + assert_eq!(actual.len(), roots.len()); + for (actual, expected) in actual.iter().zip(roots) { + assert!( + (actual - expected).abs() < rel_err * expected.abs(), + "actual {:e}, expected {:e}, err {:e}", + actual, + expected, + actual - expected + ); + } + } + + fn test_vieta_roots(x1: f64, x2: f64, x3: f64, x4: f64, roots: &[f64], rel_err: f64) { + let a = -(x1 + x2 + x3 + x4); + let b = x1 * (x2 + x3) + x2 * (x3 + x4) + x4 * (x1 + x3); + let c = -x1 * x2 * (x3 + x4) - x3 * x4 * (x1 + x2); + let d = x1 * x2 * x3 * x4; + test_with_roots([a, b, c, d], roots, rel_err); + } + + fn test_vieta(x1: f64, x2: f64, x3: f64, x4: f64, rel_err: f64) { + test_vieta_roots(x1, x2, x3, x4, &[x1, x2, x3, x4], rel_err); + } + + // case 1 + test_vieta(1., 1e3, 1e6, 1e9, 1e-16); + // case 2 + test_vieta(2., 2.001, 2.002, 2.003, 1e-6); + // case 3 + test_vieta(1e47, 1e49, 1e50, 1e53, 2e-16); + // case 4 + test_vieta(-1., 1., 2., 1e14, 1e-16); + // case 5 + test_vieta(-2e7, -1., 1., 1e7, 1e-16); + // case 6 + test_with_roots( + [-9000002.0, -9999981999998.0, 19999982e6, -2e13], + &[-1e6, 1e7], + 1e-16, + ); + // case 7 + test_with_roots( + [2000011.0, 1010022000028.0, 11110056e6, 2828e10], + &[-7., -4.], + 1e-16, + ); + // case 8 + test_with_roots( + [-100002011.0, 201101022001.0, -102200111000011.0, 11000011e8], + &[11., 1e8], + 1e-16, + ); + // cases 9-13 have no real roots + // case 14 + test_vieta_roots(1000., 1000., 1000., 1000., &[1000., 1000.], 1e-16); + // case 15 + test_vieta_roots(1e-15, 1000., 1000., 1000., &[1e-15, 1000., 1000.], 1e-15); + // case 16 no real roots + // case 17 + test_vieta(10000., 10001., 10010., 10100., 1e-6); + // case 19 + test_vieta_roots(1., 1e30, 1e30, 1e44, &[1., 1e30, 1e44], 1e-16); + // case 20 + // FAILS, error too big + test_vieta(1., 1e7, 1e7, 1e14, 1e-7); + // case 21 doesn't pick up double root + // case 22 + test_vieta(1., 10., 1e152, 1e154, 3e-16); + // case 23 + test_with_roots( + [1., 1., 3. / 8., 1e-3], + &[-0.497314148060048, -0.00268585193995149], + 2e-15, + ); + // case 24 + const S: f64 = 1e30; + test_with_roots( + [-(1. + 1. / S), 1. / S - S * S, S * S + S, -S], + &[-S, 1e-30, 1., S], + 2e-16, + ); + } + + #[test] + fn test_solve_itp() { + let f = |x: f64| x.powi(3) - x - 2.0; + let x = solve_itp(f, 1., 2., 1e-12, 0, 0.2, f(1.), f(2.)); + assert!(f(x).abs() < 6e-12); + } + + #[test] + fn test_inv_arclen() { + use crate::{ParamCurve, ParamCurveArclen}; + let c = crate::CubicBez::new( + (0.0, 0.0), + (100.0 / 3.0, 0.0), + (200.0 / 3.0, 100.0 / 3.0), + (100.0, 100.0), + ); + let target = 100.0; + let _ = solve_itp( + |t| c.subsegment(0.0..t).arclen(1e-9) - target, + 0., + 1., + 1e-6, + 1, + 0.2, + -target, + c.arclen(1e-9) - target, + ); + } +} diff --git a/vendor/kurbo/src/cubicbez.rs b/vendor/kurbo/src/cubicbez.rs new file mode 100644 index 0000000000..533256fb52 --- /dev/null +++ b/vendor/kurbo/src/cubicbez.rs @@ -0,0 +1,1257 @@ +// Copyright 2018 the Kurbo Authors +// SPDX-License-Identifier: Apache-2.0 OR MIT + +//! Cubic Bézier segments. + +use alloc::vec; +use alloc::vec::Vec; +use core::ops::{Mul, Range}; + +use crate::MAX_EXTREMA; +use crate::{Line, QuadSpline, Vec2}; +use arrayvec::ArrayVec; + +use crate::common::{ + GAUSS_LEGENDRE_COEFFS_8, GAUSS_LEGENDRE_COEFFS_8_HALF, GAUSS_LEGENDRE_COEFFS_16_HALF, + GAUSS_LEGENDRE_COEFFS_24_HALF, solve_cubic, solve_quadratic, solve_quartic, +}; +use crate::{ + Affine, Nearest, ParamCurve, ParamCurveArclen, ParamCurveArea, ParamCurveCurvature, + ParamCurveDeriv, ParamCurveExtrema, ParamCurveNearest, PathEl, Point, QuadBez, Rect, Shape, +}; + +#[cfg(not(feature = "std"))] +use crate::common::FloatFuncs; + +const MAX_SPLINE_SPLIT: usize = 100; + +/// A single cubic Bézier segment. +#[derive(Clone, Copy, Debug, PartialEq)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +#[allow(missing_docs)] +pub struct CubicBez { + pub p0: Point, + pub p1: Point, + pub p2: Point, + pub p3: Point, +} + +/// An iterator which produces quadratic Bézier segments. +struct ToQuads { + c: CubicBez, + i: usize, + n: usize, +} + +/// Classification result for cusp detection. +#[derive(Debug)] +pub enum CuspType { + /// Cusp is a loop. + Loop, + /// Cusp has two closely spaced inflection points. + DoubleInflection, +} + +impl CubicBez { + /// Create a new cubic Bézier segment. + #[inline(always)] + pub fn new>(p0: P, p1: P, p2: P, p3: P) -> CubicBez { + CubicBez { + p0: p0.into(), + p1: p1.into(), + p2: p2.into(), + p3: p3.into(), + } + } + + /// Convert to quadratic Béziers. + /// + /// The iterator returns the start and end parameter in the cubic of each quadratic + /// segment, along with the quadratic. + /// + /// Note that the resulting quadratic Béziers are not in general G1 continuous; + /// they are optimized for minimizing distance error. + /// + /// This iterator will always produce at least one `QuadBez`. + #[inline] + pub fn to_quads(&self, accuracy: f64) -> impl Iterator { + // The maximum error, as a vector from the cubic to the best approximating + // quadratic, is proportional to the third derivative, which is constant + // across the segment. Thus, the error scales down as the third power of + // the number of subdivisions. Our strategy then is to subdivide `t` evenly. + // + // This is an overestimate of the error because only the component + // perpendicular to the first derivative is important. But the simplicity is + // appealing. + + // This magic number is the square of 36 / sqrt(3). + // See: http://caffeineowl.com/graphics/2d/vectorial/cubic2quad01.html + let max_hypot2 = 432.0 * accuracy * accuracy; + let p1x2 = 3.0 * self.p1.to_vec2() - self.p0.to_vec2(); + let p2x2 = 3.0 * self.p2.to_vec2() - self.p3.to_vec2(); + let err = (p2x2 - p1x2).hypot2(); + let n = ((err / max_hypot2).powf(1. / 6.0).ceil() as usize).max(1); + + ToQuads { c: *self, n, i: 0 } + } + + /// Return a [`QuadSpline`] approximating this cubic Bézier. + /// + /// Returns `None` if no suitable approximation is found within the given + /// tolerance. + pub fn approx_spline(&self, accuracy: f64) -> Option { + (1..=MAX_SPLINE_SPLIT).find_map(|n| self.approx_spline_n(n, accuracy)) + } + + // Approximate a cubic curve with a quadratic spline of `n` curves + fn approx_spline_n(&self, n: usize, accuracy: f64) -> Option { + if n == 1 { + return self + .try_approx_quadratic(accuracy) + .map(|quad| QuadSpline::new(vec![quad.p0, quad.p1, quad.p2])); + } + let mut cubics = self.split_into_n(n); + + // The above function guarantees that the iterator returns n items, + // which is why we're unwrapping things with wild abandon. + let mut next_cubic = cubics.next().unwrap(); + let mut next_q1: Point = next_cubic.approx_quad_control(0.0); + let mut q2 = self.p0; + let mut d1 = Vec2::ZERO; + let mut spline = vec![self.p0, next_q1]; + for i in 1..=n { + let current_cubic: CubicBez = next_cubic; + let q0 = q2; + let q1 = next_q1; + q2 = if i < n { + next_cubic = cubics.next().unwrap(); + next_q1 = next_cubic.approx_quad_control(i as f64 / (n - 1) as f64); + + spline.push(next_q1); + q1.midpoint(next_q1) + } else { + current_cubic.p3 + }; + let d0 = d1; + d1 = q2.to_vec2() - current_cubic.p3.to_vec2(); + + if d1.hypot() > accuracy + || !CubicBez::new( + d0.to_point(), + q0.lerp(q1, 2.0 / 3.0) - current_cubic.p1.to_vec2(), + q2.lerp(q1, 2.0 / 3.0) - current_cubic.p2.to_vec2(), + d1.to_point(), + ) + .fit_inside(accuracy) + { + return None; + } + } + spline.push(self.p3); + Some(QuadSpline::new(spline)) + } + + fn approx_quad_control(&self, t: f64) -> Point { + let p1 = self.p0 + (self.p1 - self.p0) * 1.5; + let p2 = self.p3 + (self.p2 - self.p3) * 1.5; + p1.lerp(p2, t) + } + + /// Approximate a cubic with a single quadratic + /// + /// Returns a quadratic approximating the given cubic that maintains + /// endpoint tangents if that is within tolerance, or `None` otherwise. + fn try_approx_quadratic(&self, accuracy: f64) -> Option { + if let Some(q1) = Line::new(self.p0, self.p1) + .crossing_point(Line::new(self.p2, self.p3)) + .or_else(|| { + // with 3 to 4 consecutive equal points (with no valid crossing_point), + // we can try to use the common point as the quadratic control point. + // This matches fonttools' cu2qu: https://github.com/fonttools/fonttools/pull/3904 + (self.p1 == self.p2 && (self.p0 == self.p1 || self.p2 == self.p3)) + .then_some(self.p1) + }) + { + let c1 = self.p0.lerp(q1, 2.0 / 3.0); + let c2 = self.p3.lerp(q1, 2.0 / 3.0); + if !CubicBez::new( + Point::ZERO, + c1 - self.p1.to_vec2(), + c2 - self.p2.to_vec2(), + Point::ZERO, + ) + .fit_inside(accuracy) + { + return None; + } + return Some(QuadBez::new(self.p0, q1, self.p3)); + } + None + } + + fn split_into_n(&self, n: usize) -> impl Iterator { + // for certain small values of `n` we precompute all our values. + // if we have six or fewer items we precompute them. + let mut storage = ArrayVec::<_, 6>::new(); + + match n { + 1 => storage.push(*self), + 2 => { + let (l, r) = self.subdivide(); + storage.try_extend_from_slice(&[r, l]).unwrap(); + } + 3 => { + let (left, mid, right) = self.subdivide_3(); + storage.try_extend_from_slice(&[right, mid, left]).unwrap(); + } + 4 => { + let (l, r) = self.subdivide(); + let (ll, lr) = l.subdivide(); + let (rl, rr) = r.subdivide(); + storage.try_extend_from_slice(&[rr, rl, lr, ll]).unwrap(); + } + 6 => { + let (l, r) = self.subdivide(); + let (l1, l2, l3) = l.subdivide_3(); + let (r1, r2, r3) = r.subdivide_3(); + storage + .try_extend_from_slice(&[r3, r2, r1, l3, l2, l1]) + .unwrap(); + } + _ => (), + } + + // a limitation of returning 'impl Trait' is that the implementation + // can only return a single concrete type; that is you cannot return + // Vec::into_iter() from one branch, and then HashSet::into_iter from + // another branch. + // + // This means we have to get a bit fancy, and have a single concrete + // type that represents both of our possible cases. + + let mut storage = if storage.is_empty() { + None + } else { + Some(storage) + }; + + // used in the fallback case + let mut i = 0; + let (a, b, c, d) = self.parameters(); + let dt = 1.0 / n as f64; + let delta_2 = dt * dt; + let delta_3 = dt * delta_2; + + core::iter::from_fn(move || { + // if storage exists, we use it exclusively + if let Some(storage) = storage.as_mut() { + return storage.pop(); + } + + // if storage does not exist, we are exclusively working down here. + if i >= n { + return None; + } + + let t1 = i as f64 * dt; + let t1_2 = t1 * t1; + let a1 = a * delta_3; + let b1 = (3.0 * a * t1 + b) * delta_2; + let c1 = (2.0 * b * t1 + c + 3.0 * a * t1_2) * dt; + let d1 = a * t1 * t1_2 + b * t1_2 + c * t1 + d; + let result = CubicBez::from_parameters(a1, b1, c1, d1); + i += 1; + Some(result) + }) + } + + fn parameters(&self) -> (Vec2, Vec2, Vec2, Vec2) { + let c = (self.p1 - self.p0) * 3.0; + let b = (self.p2 - self.p1) * 3.0 - c; + let d = self.p0.to_vec2(); + let a = self.p3.to_vec2() - d - c - b; + (a, b, c, d) + } + + /// Rust port of cu2qu [calc_cubic_points](https://github.com/fonttools/fonttools/blob/3b9a73ff8379ab49d3ce35aaaaf04b3a7d9d1655/Lib/fontTools/cu2qu/cu2qu.py#L63-L68) + fn from_parameters(a: Vec2, b: Vec2, c: Vec2, d: Vec2) -> Self { + let p0 = d.to_point(); + let p1 = c.div_exact(3.0).to_point() + d; + let p2 = (b + c).div_exact(3.0).to_point() + p1.to_vec2(); + let p3 = (a + d + c + b).to_point(); + CubicBez::new(p0, p1, p2, p3) + } + + fn subdivide_3(&self) -> (CubicBez, CubicBez, CubicBez) { + let (p0, p1, p2, p3) = ( + self.p0.to_vec2(), + self.p1.to_vec2(), + self.p2.to_vec2(), + self.p3.to_vec2(), + ); + // The original Python cu2qu code here does not use division operator to divide by 27 but + // instead uses multiplication by the reciprocal 1 / 27. We want to match it exactly + // to avoid any floating point differences, hence in this particular case we do not use div_exact. + // I could directly use the Vec2 Div trait (also implemented as multiplication by reciprocal) + // but I prefer to be explicit here. + // Source: https://github.com/fonttools/fonttools/blob/85c80be/Lib/fontTools/cu2qu/cu2qu.py#L215-L218 + // See also: https://github.com/linebender/kurbo/issues/272 + let one_27th = 27.0_f64.recip(); + let mid1 = ((8.0 * p0 + 12.0 * p1 + 6.0 * p2 + p3) * one_27th).to_point(); + let deriv1 = (p3 + 3.0 * p2 - 4.0 * p0) * one_27th; + let mid2 = ((p0 + 6.0 * p1 + 12.0 * p2 + 8.0 * p3) * one_27th).to_point(); + let deriv2 = (4.0 * p3 - 3.0 * p1 - p0) * one_27th; + + let left = CubicBez::new( + self.p0, + (2.0 * p0 + p1).div_exact(3.0).to_point(), + mid1 - deriv1, + mid1, + ); + let mid = CubicBez::new(mid1, mid1 + deriv1, mid2 - deriv2, mid2); + let right = CubicBez::new( + mid2, + mid2 + deriv2, + (p2 + 2.0 * p3).div_exact(3.0).to_point(), + self.p3, + ); + (left, mid, right) + } + + /// Does this curve fit inside the given distance from the origin? + /// + /// Rust port of cu2qu [cubic_farthest_fit_inside](https://github.com/fonttools/fonttools/blob/3b9a73ff8379ab49d3ce35aaaaf04b3a7d9d1655/Lib/fontTools/cu2qu/cu2qu.py#L281) + fn fit_inside(&self, distance: f64) -> bool { + if self.p2.to_vec2().hypot() <= distance && self.p1.to_vec2().hypot() <= distance { + return true; + } + let mid = + (self.p0.to_vec2() + 3.0 * (self.p1.to_vec2() + self.p2.to_vec2()) + self.p3.to_vec2()) + * 0.125; + if mid.hypot() > distance { + return false; + } + // Split in two. Note that cu2qu here uses a 3/8 subdivision. I don't know why. + let (left, right) = self.subdivide(); + left.fit_inside(distance) && right.fit_inside(distance) + } + + /// Is this cubic Bezier curve finite? + #[inline] + pub const fn is_finite(&self) -> bool { + self.p0.is_finite() && self.p1.is_finite() && self.p2.is_finite() && self.p3.is_finite() + } + + /// Is this cubic Bezier curve NaN? + #[inline] + pub const fn is_nan(&self) -> bool { + self.p0.is_nan() || self.p1.is_nan() || self.p2.is_nan() || self.p3.is_nan() + } + + /// Determine the inflection points. + /// + /// Return value is t parameter for the inflection points of the curve segment. + /// There are a maximum of two for a cubic Bézier. + /// + /// See + /// for the theory. + pub fn inflections(&self) -> ArrayVec { + let a = self.p1 - self.p0; + let b = (self.p2 - self.p1) - a; + let c = (self.p3 - self.p0) - 3. * (self.p2 - self.p1); + solve_quadratic(a.cross(b), a.cross(c), b.cross(c)) + .iter() + .copied() + .filter(|t| *t >= 0.0 && *t <= 1.0) + .collect() + } + + /// Find points on the curve where the tangent line passes through the + /// given point. + /// + /// Result is array of t values such that the tangent line from the curve + /// evaluated at that point goes through the argument point. + pub fn tangents_to_point(&self, p: Point) -> ArrayVec { + let (a, b, c, d_orig) = self.parameters(); + let d = d_orig - p.to_vec2(); + // coefficients of x(t) \cross x'(t) + let c4 = b.cross(a); + let c3 = 2.0 * c.cross(a); + let c2 = c.cross(b) + 3.0 * d.cross(a); + let c1 = 2.0 * d.cross(b); + let c0 = d.cross(c); + solve_quartic(c0, c1, c2, c3, c4) + .iter() + .copied() + .filter(|t| *t >= 0.0 && *t <= 1.0) + .collect() + } + + /// Preprocess a cubic Bézier to ease numerical robustness. + /// + /// If the cubic Bézier segment has zero or near-zero derivatives as an interior + /// cusp, perturb the control points to make curvature finite, avoiding + /// numerical robustness problems in offset and stroke. + pub(crate) fn regularize_cusp(&self, dimension: f64) -> CubicBez { + let mut c = *self; + // First step: if control point is too near the endpoint, nudge it away + // along the tangent. + if let Some(cusp_type) = self.detect_cusp(dimension) { + let d01 = c.p1 - c.p0; + let d01h = d01.hypot(); + let d23 = c.p3 - c.p2; + let d23h = d23.hypot(); + match cusp_type { + CuspType::Loop => { + c.p1 += (dimension / d01h) * d01; + c.p2 -= (dimension / d23h) * d23; + } + CuspType::DoubleInflection => { + // Avoid making control distance smaller than dimension + if d01h > 2.0 * dimension { + c.p1 -= (dimension / d01h) * d01; + } + if d23h > 2.0 * dimension { + c.p2 += (dimension / d23h) * d23; + } + } + } + } + c + } + + /// Detect whether there is a cusp. + /// + /// Return a cusp classification if there is a cusp with curvature greater than + /// the reciprocal of the given dimension. + fn detect_cusp(&self, dimension: f64) -> Option { + let d01 = self.p1 - self.p0; + let d02 = self.p2 - self.p0; + let d03 = self.p3 - self.p0; + let d12 = self.p2 - self.p1; + let d23 = self.p3 - self.p2; + let det_012 = d01.cross(d02); + let det_123 = d12.cross(d23); + let det_013 = d01.cross(d03); + let det_023 = d02.cross(d03); + if det_012 * det_123 > 0.0 && det_012 * det_013 < 0.0 && det_012 * det_023 < 0.0 { + let q = self.deriv(); + // accuracy isn't used for quadratic nearest + let nearest = q.nearest(Point::ORIGIN, 1e-9); + // detect whether curvature at minimum derivative exceeds 1/dimension, + // without division. + let d = q.eval(nearest.t); + let d2 = q.deriv().eval(nearest.t); + let cross = d.to_vec2().cross(d2.to_vec2()); + if nearest.distance_sq.powi(3) <= (cross * dimension).powi(2) { + let a = 3. * det_012 + det_023 - 2. * det_013; + let b = -3. * det_012 + det_013; + let c = det_012; + let d = b * b - 4. * a * c; + if d > 0.0 { + return Some(CuspType::DoubleInflection); + } else { + return Some(CuspType::Loop); + } + } + } + None + } + + /// Finds the value of `t` for which `self.eval(t)` is about `y`. + /// + /// Assumes that this segment is monotonic in `y` and that it crosses + /// the height `y`. (Under these assumptions, there is a unique answer.) + pub(crate) fn solve_monotonic_for_y(&self, y: f64) -> f64 { + let start = self.start(); + let end = self.end(); + + debug_assert!(start.y.min(end.y) <= y && y <= start.y.max(end.y)); + + let p1 = self.p1; + let p2 = self.p2; + let a = end.y - 3.0 * p2.y + 3.0 * p1.y - start.y; + let b = 3.0 * (p2.y - 2.0 * p1.y + start.y); + let c = 3.0 * (p1.y - start.y); + let d = start.y - y; + for t in solve_cubic(d, c, b, a) { + if (0.0..=1.0).contains(&t) { + return t; + } + } + + // Even though we asserted that our y range contains `y`, it's possible + // that we failed to find a solution numerically. (For example, rounding + // of a, b, or c might have pushed the root outside of [0.0, 1.0].) + // If we failed to find a solution, the real solution should be close + // to one of the endpoints. So just find whichever endpoint was closer. + if (start.y - y).abs() <= (end.y - y).abs() { + 0.0 + } else { + 1.0 + } + } +} + +/// An iterator for cubic beziers. +pub struct CubicBezIter { + cubic: CubicBez, + ix: usize, +} + +impl Shape for CubicBez { + type PathElementsIter<'iter> = CubicBezIter; + + #[inline] + fn path_elements(&self, _tolerance: f64) -> CubicBezIter { + CubicBezIter { + cubic: *self, + ix: 0, + } + } + + #[inline(always)] + fn area(&self) -> f64 { + 0.0 + } + + #[inline] + fn perimeter(&self, accuracy: f64) -> f64 { + self.arclen(accuracy) + } + + #[inline(always)] + fn winding(&self, _pt: Point) -> i32 { + 0 + } + + #[inline] + fn bounding_box(&self) -> Rect { + ParamCurveExtrema::bounding_box(self) + } +} + +impl Iterator for CubicBezIter { + type Item = PathEl; + + fn next(&mut self) -> Option { + self.ix += 1; + match self.ix { + 1 => Some(PathEl::MoveTo(self.cubic.p0)), + 2 => Some(PathEl::CurveTo(self.cubic.p1, self.cubic.p2, self.cubic.p3)), + _ => None, + } + } +} + +impl ParamCurve for CubicBez { + #[inline] + fn eval(&self, t: f64) -> Point { + let mt = 1.0 - t; + let v = self.p0.to_vec2() * (mt * mt * mt) + + (self.p1.to_vec2() * (mt * mt * 3.0) + + (self.p2.to_vec2() * (mt * 3.0) + self.p3.to_vec2() * t) * t) + * t; + v.to_point() + } + + fn subsegment(&self, range: Range) -> CubicBez { + let (t0, t1) = (range.start, range.end); + let p0 = self.eval(t0); + let p3 = self.eval(t1); + let d = self.deriv(); + let scale = (t1 - t0) * (1.0 / 3.0); + let p1 = p0 + scale * d.eval(t0).to_vec2(); + let p2 = p3 - scale * d.eval(t1).to_vec2(); + CubicBez { p0, p1, p2, p3 } + } + + /// Subdivide into halves, using de Casteljau. + #[inline] + fn subdivide(&self) -> (CubicBez, CubicBez) { + let pm = self.eval(0.5); + ( + CubicBez::new( + self.p0, + self.p0.midpoint(self.p1), + ((self.p0.to_vec2() + self.p1.to_vec2() * 2.0 + self.p2.to_vec2()) * 0.25) + .to_point(), + pm, + ), + CubicBez::new( + pm, + ((self.p1.to_vec2() + self.p2.to_vec2() * 2.0 + self.p3.to_vec2()) * 0.25) + .to_point(), + self.p2.midpoint(self.p3), + self.p3, + ), + ) + } + + #[inline(always)] + fn start(&self) -> Point { + self.p0 + } + + #[inline(always)] + fn end(&self) -> Point { + self.p3 + } +} + +impl ParamCurveDeriv for CubicBez { + type DerivResult = QuadBez; + + #[inline] + fn deriv(&self) -> QuadBez { + QuadBez::new( + (3.0 * (self.p1 - self.p0)).to_point(), + (3.0 * (self.p2 - self.p1)).to_point(), + (3.0 * (self.p3 - self.p2)).to_point(), + ) + } +} + +fn arclen_quadrature_core(coeffs: &[(f64, f64)], dm: Vec2, dm1: Vec2, dm2: Vec2) -> f64 { + coeffs + .iter() + .map(|&(wi, xi)| { + let d = dm + dm2 * (xi * xi); + let dpx = (d + dm1 * xi).hypot(); + let dmx = (d - dm1 * xi).hypot(); + (2.25f64.sqrt() * wi) * (dpx + dmx) + }) + .sum::() +} + +fn arclen_rec(c: &CubicBez, accuracy: f64, depth: usize) -> f64 { + let d03 = c.p3 - c.p0; + let d01 = c.p1 - c.p0; + let d12 = c.p2 - c.p1; + let d23 = c.p3 - c.p2; + let lp_lc = d01.hypot() + d12.hypot() + d23.hypot() - d03.hypot(); + let dd1 = d12 - d01; + let dd2 = d23 - d12; + // It might be faster to do direct multiplies, the data dependencies would be shorter. + // The following values don't have the factor of 3 for first deriv + let dm = 0.25 * (d01 + d23) + 0.5 * d12; // first derivative at midpoint + let dm1 = 0.5 * (dd2 + dd1); // second derivative at midpoint + let dm2 = 0.25 * (dd2 - dd1); // 0.5 * (third derivative at midpoint) + + let est = GAUSS_LEGENDRE_COEFFS_8 + .iter() + .map(|&(wi, xi)| { + wi * { + let d_norm2 = (dm + dm1 * xi + dm2 * (xi * xi)).hypot2(); + let dd_norm2 = (dm1 + dm2 * (2.0 * xi)).hypot2(); + dd_norm2 / d_norm2 + } + }) + .sum::(); + let est_gauss8_error = (est.powi(3) * 2.5e-6).min(3e-2) * lp_lc; + if est_gauss8_error < accuracy { + return arclen_quadrature_core(GAUSS_LEGENDRE_COEFFS_8_HALF, dm, dm1, dm2); + } + let est_gauss16_error = (est.powi(6) * 1.5e-11).min(9e-3) * lp_lc; + if est_gauss16_error < accuracy { + return arclen_quadrature_core(GAUSS_LEGENDRE_COEFFS_16_HALF, dm, dm1, dm2); + } + let est_gauss24_error = (est.powi(9) * 3.5e-16).min(3.5e-3) * lp_lc; + if est_gauss24_error < accuracy || depth >= 20 { + return arclen_quadrature_core(GAUSS_LEGENDRE_COEFFS_24_HALF, dm, dm1, dm2); + } + let (c0, c1) = c.subdivide(); + arclen_rec(&c0, accuracy * 0.5, depth + 1) + arclen_rec(&c1, accuracy * 0.5, depth + 1) +} + +impl ParamCurveArclen for CubicBez { + /// Arclength of a cubic Bézier segment. + /// + /// This is an adaptive subdivision approach using Legendre-Gauss quadrature + /// in the base case, and an error estimate to decide when to subdivide. + fn arclen(&self, accuracy: f64) -> f64 { + arclen_rec(self, accuracy, 0) + } +} + +impl ParamCurveArea for CubicBez { + #[inline] + fn signed_area(&self) -> f64 { + (self.p0.x * (6.0 * self.p1.y + 3.0 * self.p2.y + self.p3.y) + + 3.0 + * (self.p1.x * (-2.0 * self.p0.y + self.p2.y + self.p3.y) + - self.p2.x * (self.p0.y + self.p1.y - 2.0 * self.p3.y)) + - self.p3.x * (self.p0.y + 3.0 * self.p1.y + 6.0 * self.p2.y)) + * (1.0 / 20.0) + } +} + +impl ParamCurveNearest for CubicBez { + /// Find the nearest point using a quintic solver. + /// + /// The polynomial `|self - p|^2` has degree 6, so we find its critical + /// points and evaluate them all to find the best one. + fn nearest(&self, p: Point, accuracy: f64) -> Nearest { + fn eval_t(p: Point, t_best: &mut f64, r_best: &mut Option, t: f64, p0: Point) { + let r = (p0 - p).hypot2(); + if r_best.map(|r_best| r < r_best).unwrap_or(true) { + *r_best = Some(r); + *t_best = t; + } + } + + let mut r_best = None; + let mut t_best = 0.0; + + // Reparameterize `self - p` as q0 + q1 t + q2 t^2 + q3 t^3. + let q0 = self.p0 - p; + let q1 = 3.0 * (self.p1 - self.p0); + let q2 = 3.0 * (self.p0.to_vec2() - 2.0 * self.p1.to_vec2() + self.p2.to_vec2()); + let q3 = -self.p0.to_vec2() + 3.0 * self.p1.to_vec2() - 3.0 * self.p2.to_vec2() + + self.p3.to_vec2(); + + // Coefficients of the degree-5 polynomial (self - p) \cdot tangent. + let c0 = q0.dot(q1); + let c1 = q1.hypot2() + 2.0 * q2.dot(q0); + let c2 = 3.0 * (q2.dot(q1) + q3.dot(q0)); + let c3 = 4.0 * q3.dot(q1) + 2.0 * q2.hypot2(); + let c4 = 5.0 * q3.dot(q2); + let c5 = 3.0 * q3.hypot2(); + + let roots = polycool::Poly::new([c0, c1, c2, c3, c4, c5]).roots_between(0.0, 1.0, accuracy); + + for &t in &roots { + eval_t(p, &mut t_best, &mut r_best, t, self.eval(t)); + } + + // If we found all 5 critical points, we can skip evaluating the endpoints. + if roots.len() != 5 { + eval_t(p, &mut t_best, &mut r_best, 0.0, self.p0); + eval_t(p, &mut t_best, &mut r_best, 1.0, self.p3); + } + + Nearest { + t: t_best, + distance_sq: r_best.unwrap(), + } + } +} + +impl ParamCurveCurvature for CubicBez {} + +impl ParamCurveExtrema for CubicBez { + fn extrema(&self) -> ArrayVec { + fn one_coord(result: &mut ArrayVec, d0: f64, d1: f64, d2: f64) { + let a = d0 - 2.0 * d1 + d2; + let b = 2.0 * (d1 - d0); + let c = d0; + let roots = solve_quadratic(c, b, a); + for &t in &roots { + if t > 0.0 && t < 1.0 { + result.push(t); + } + } + } + let mut result = ArrayVec::new(); + let d0 = self.p1 - self.p0; + let d1 = self.p2 - self.p1; + let d2 = self.p3 - self.p2; + one_coord(&mut result, d0.x, d1.x, d2.x); + one_coord(&mut result, d0.y, d1.y, d2.y); + result.sort_by(|a, b| a.partial_cmp(b).unwrap()); + result + } +} + +impl Mul for Affine { + type Output = CubicBez; + + #[inline] + fn mul(self, c: CubicBez) -> CubicBez { + CubicBez { + p0: self * c.p0, + p1: self * c.p1, + p2: self * c.p2, + p3: self * c.p3, + } + } +} + +impl Iterator for ToQuads { + type Item = (f64, f64, QuadBez); + + #[inline] + fn next(&mut self) -> Option<(f64, f64, QuadBez)> { + if self.i == self.n { + return None; + } + let t0 = self.i as f64 / self.n as f64; + let t1 = (self.i + 1) as f64 / self.n as f64; + let seg = self.c.subsegment(t0..t1); + let p1x2 = 3.0 * seg.p1.to_vec2() - seg.p0.to_vec2(); + let p2x2 = 3.0 * seg.p2.to_vec2() - seg.p3.to_vec2(); + let result = QuadBez::new(seg.p0, ((p1x2 + p2x2) / 4.0).to_point(), seg.p3); + self.i += 1; + Some((t0, t1, result)) + } + + fn size_hint(&self) -> (usize, Option) { + let remaining = self.n - self.i; + (remaining, Some(remaining)) + } +} + +/// Convert multiple cubic Bézier curves to quadratic splines. +/// +/// Ensures that the resulting splines have the same number of control points. +/// +/// Rust port of cu2qu [cubic_approx_quadratic](https://github.com/fonttools/fonttools/blob/3b9a73ff8379ab49d3ce35aaaaf04b3a7d9d1655/Lib/fontTools/cu2qu/cu2qu.py#L322) +pub fn cubics_to_quadratic_splines(curves: &[CubicBez], accuracy: f64) -> Option> { + let mut result = Vec::new(); + let mut split_order = 0; + + while split_order <= MAX_SPLINE_SPLIT { + split_order += 1; + result.clear(); + + for curve in curves { + match curve.approx_spline_n(split_order, accuracy) { + Some(spline) => result.push(spline), + None => break, + } + } + + if result.len() == curves.len() { + return Some(result); + } + } + None +} +#[cfg(test)] +mod tests { + use crate::{ + Affine, CubicBez, Nearest, ParamCurve, ParamCurveArclen, ParamCurveArea, ParamCurveDeriv, + ParamCurveExtrema, ParamCurveNearest, Point, QuadBez, QuadSpline, + cubics_to_quadratic_splines, + }; + + #[test] + fn cubicbez_deriv() { + // y = x^2 + let c = CubicBez::new( + (0.0, 0.0), + (1.0 / 3.0, 0.0), + (2.0 / 3.0, 1.0 / 3.0), + (1.0, 1.0), + ); + let deriv = c.deriv(); + + let n = 10; + for i in 0..=n { + let t = (i as f64) * (n as f64).recip(); + let delta = 1e-6; + let p = c.eval(t); + let p1 = c.eval(t + delta); + let d_approx = (p1 - p) * delta.recip(); + let d = deriv.eval(t).to_vec2(); + assert!((d - d_approx).hypot() < delta * 2.0); + } + } + + #[test] + fn cubicbez_arclen() { + // y = x^2 + let c = CubicBez::new( + (0.0, 0.0), + (1.0 / 3.0, 0.0), + (2.0 / 3.0, 1.0 / 3.0), + (1.0, 1.0), + ); + let true_arclen = 0.5 * 5.0f64.sqrt() + 0.25 * (2.0 + 5.0f64.sqrt()).ln(); + for i in 0..12 { + let accuracy = 0.1f64.powi(i); + let error = c.arclen(accuracy) - true_arclen; + assert!(error.abs() < accuracy); + } + } + + #[test] + fn cubicbez_inv_arclen() { + // y = x^2 / 100 + let c = CubicBez::new( + (0.0, 0.0), + (100.0 / 3.0, 0.0), + (200.0 / 3.0, 100.0 / 3.0), + (100.0, 100.0), + ); + let true_arclen = 100.0 * (0.5 * 5.0f64.sqrt() + 0.25 * (2.0 + 5.0f64.sqrt()).ln()); + for i in 0..12 { + let accuracy = 0.1f64.powi(i); + let n = 10; + for j in 0..=n { + let arc = (j as f64) * ((n as f64).recip() * true_arclen); + let t = c.inv_arclen(arc, accuracy * 0.5); + let actual_arc = c.subsegment(0.0..t).arclen(accuracy * 0.5); + assert!( + (arc - actual_arc).abs() < accuracy, + "at accuracy {accuracy:e}, wanted {actual_arc} got {arc}" + ); + } + } + // corner case: user passes accuracy larger than total arc length + let accuracy = true_arclen * 1.1; + let arc = true_arclen * 0.5; + let t = c.inv_arclen(arc, accuracy); + let actual_arc = c.subsegment(0.0..t).arclen(accuracy); + assert!( + (arc - actual_arc).abs() < 2.0 * accuracy, + "at accuracy {accuracy:e}, want {actual_arc} got {arc}" + ); + } + + #[test] + fn cubicbez_inv_arclen_accuracy() { + let c = CubicBez::new((0.2, 0.73), (0.35, 1.08), (0.85, 1.08), (1.0, 0.73)); + let true_t = c.inv_arclen(0.5, 1e-12); + for i in 1..12 { + let accuracy = (0.1f64).powi(i); + let approx_t = c.inv_arclen(0.5, accuracy); + assert!((approx_t - true_t).abs() <= accuracy); + } + } + + #[test] + #[allow(clippy::float_cmp)] + fn cubicbez_signed_area_linear() { + // y = 1 - x + let c = CubicBez::new( + (1.0, 0.0), + (2.0 / 3.0, 1.0 / 3.0), + (1.0 / 3.0, 2.0 / 3.0), + (0.0, 1.0), + ); + let epsilon = 1e-12; + assert_eq!((Affine::rotate(0.5) * c).signed_area(), 0.5); + assert!(((Affine::rotate(0.5) * c).signed_area() - 0.5).abs() < epsilon); + assert!(((Affine::translate((0.0, 1.0)) * c).signed_area() - 1.0).abs() < epsilon); + assert!(((Affine::translate((1.0, 0.0)) * c).signed_area() - 1.0).abs() < epsilon); + } + + #[test] + fn cubicbez_signed_area() { + // y = 1 - x^3 + let c = CubicBez::new((1.0, 0.0), (2.0 / 3.0, 1.0), (1.0 / 3.0, 1.0), (0.0, 1.0)); + let epsilon = 1e-12; + assert!((c.signed_area() - 0.75).abs() < epsilon); + assert!(((Affine::rotate(0.5) * c).signed_area() - 0.75).abs() < epsilon); + assert!(((Affine::translate((0.0, 1.0)) * c).signed_area() - 1.25).abs() < epsilon); + assert!(((Affine::translate((1.0, 0.0)) * c).signed_area() - 1.25).abs() < epsilon); + } + + #[test] + fn cubicbez_nearest() { + fn verify(result: Nearest, expected: f64) { + assert!( + (result.t - expected).abs() < 1e-6, + "got {result:?} expected {expected}" + ); + } + // y = x^3 + let c = CubicBez::new((0.0, 0.0), (1.0 / 3.0, 0.0), (2.0 / 3.0, 0.0), (1.0, 1.0)); + verify(c.nearest((0.1, 0.001).into(), 1e-6), 0.1); + verify(c.nearest((0.2, 0.008).into(), 1e-6), 0.2); + verify(c.nearest((0.3, 0.027).into(), 1e-6), 0.3); + verify(c.nearest((0.4, 0.064).into(), 1e-6), 0.4); + verify(c.nearest((0.5, 0.125).into(), 1e-6), 0.5); + verify(c.nearest((0.6, 0.216).into(), 1e-6), 0.6); + verify(c.nearest((0.7, 0.343).into(), 1e-6), 0.7); + verify(c.nearest((0.8, 0.512).into(), 1e-6), 0.8); + verify(c.nearest((0.9, 0.729).into(), 1e-6), 0.9); + verify(c.nearest((1.0, 1.0).into(), 1e-6), 1.0); + verify(c.nearest((1.1, 1.1).into(), 1e-6), 1.0); + verify(c.nearest((-0.1, 0.0).into(), 1e-6), 0.0); + let a = Affine::rotate(0.5); + verify((a * c).nearest(a * Point::new(0.1, 0.001), 1e-6), 0.1); + + // Here's a case that tripped up the old solver because the start is close to + // degenerate and the end is actually degenerate; see #446. + let curve = CubicBez::new( + (461.0, 123.0), + (460.99999999999994, 123.00000000000004), + (111.0, 319.0), + (111.0, 319.0), + ); + let p = Point::new(282.0379003395483, 223.21877580985594); + let eps = 0.0005; + let nearest = curve.nearest(p, eps); + let q = curve.eval(nearest.t); + let r = curve.eval(0.5075474297354187); + + assert!((q - p).hypot() <= (r - p).hypot() + eps); + } + + // ensure to_quads returns something given collinear points + #[test] + fn degenerate_to_quads() { + let c = CubicBez::new((0., 9.), (6., 6.), (12., 3.0), (18., 0.0)); + let quads = c.to_quads(1e-6).collect::>(); + assert_eq!(quads.len(), 1, "{:?}", &quads); + } + + #[test] + fn cubicbez_extrema() { + // y = x^2 + let q = CubicBez::new((0.0, 0.0), (0.0, 1.0), (1.0, 1.0), (1.0, 0.0)); + let extrema = q.extrema(); + assert_eq!(extrema.len(), 1); + assert!((extrema[0] - 0.5).abs() < 1e-6); + + let q = CubicBez::new((0.4, 0.5), (0.0, 1.0), (1.0, 0.0), (0.5, 0.4)); + let extrema = q.extrema(); + assert_eq!(extrema.len(), 4); + } + + #[test] + fn cubicbez_toquads() { + // y = x^3 + let c = CubicBez::new((0.0, 0.0), (1.0 / 3.0, 0.0), (2.0 / 3.0, 0.0), (1.0, 1.0)); + for i in 0..10 { + let accuracy = 0.1f64.powi(i); + let mut worst: f64 = 0.0; + for (t0, t1, q) in c.to_quads(accuracy) { + let epsilon = 1e-12; + assert!((q.start() - c.eval(t0)).hypot() < epsilon); + assert!((q.end() - c.eval(t1)).hypot() < epsilon); + let n = 4; + for j in 0..=n { + let t = (j as f64) * (n as f64).recip(); + let p = q.eval(t); + let err = (p.y - p.x.powi(3)).abs(); + worst = worst.max(err); + assert!(err < accuracy, "got {err} wanted {accuracy}"); + } + } + } + } + + #[test] + fn cubicbez_approx_spline() { + let c1 = CubicBez::new( + (550.0, 258.0), + (1044.0, 482.0), + (2029.0, 1841.0), + (1934.0, 1554.0), + ); + + let quad = c1.try_approx_quadratic(344.0); + let expected = QuadBez::new( + Point::new(550.0, 258.0), + Point::new(1673.665720592873, 767.5164401068898), + Point::new(1934.0, 1554.0), + ); + assert!(quad.is_some()); + assert_eq!(quad.unwrap(), expected); + + let quad = c1.try_approx_quadratic(343.0); + assert!(quad.is_none()); + + let spline = c1.approx_spline_n(2, 343.0); + assert!(spline.is_some()); + let spline = spline.unwrap(); + let expected = [ + Point::new(550.0, 258.0), + Point::new(920.5, 426.0), + Point::new(2005.25, 1769.25), + Point::new(1934.0, 1554.0), + ]; + assert_eq!(spline.points().len(), expected.len()); + for (got, &wanted) in spline.points().iter().zip(expected.iter()) { + assert!(got.distance(wanted) < 5.0); + } + + let spline = c1.approx_spline(5.0); + let expected = [ + Point::new(550.0, 258.0), + Point::new(673.5, 314.0), + Point::new(984.8777777777776, 584.2666666666667), + Point::new(1312.6305555555557, 927.825), + Point::new(1613.1194444444443, 1267.425), + Point::new(1842.7055555555555, 1525.8166666666666), + Point::new(1957.75, 1625.75), + Point::new(1934.0, 1554.0), + ]; + assert!(spline.is_some()); + let spline = spline.unwrap(); + assert_eq!(spline.points().len(), expected.len()); + for (got, &wanted) in spline.points().iter().zip(expected.iter()) { + assert!(got.distance(wanted) < 5.0); + } + } + + #[test] + fn cubicbez_cubics_to_quadratic_splines() { + let curves = vec![ + CubicBez::new( + (550.0, 258.0), + (1044.0, 482.0), + (2029.0, 1841.0), + (1934.0, 1554.0), + ), + CubicBez::new( + (859.0, 384.0), + (1998.0, 116.0), + (1596.0, 1772.0), + (8.0, 1824.0), + ), + CubicBez::new( + (1090.0, 937.0), + (418.0, 1300.0), + (125.0, 91.0), + (104.0, 37.0), + ), + ]; + let converted = cubics_to_quadratic_splines(&curves, 5.0); + assert!(converted.is_some()); + let converted = converted.unwrap(); + assert_eq!(converted[0].points().len(), 8); + assert_eq!(converted[1].points().len(), 8); + assert_eq!(converted[2].points().len(), 8); + assert!(converted[0].points()[1].distance(Point::new(673.5, 314.0)) < 0.0001); + assert!( + converted[0].points()[2].distance(Point::new(88639.0 / 90.0, 52584.0 / 90.0)) < 0.0001 + ); + } + + #[test] + fn cubicbez_approx_spline_div_exact() { + // Ensure rounding behavior for division matches fonttools + // cu2qu. + // See + let cubic = CubicBez::new( + Point::new(408.0, 321.0), + Point::new(408.0, 452.0), + Point::new(342.0, 560.0), + Point::new(260.0, 560.0), + ); + let spline = cubic.approx_spline(1.0).unwrap(); + assert_eq!( + spline.points(), + &[ + Point::new(408.0, 321.0), + // Previous behavior produced 386.49999999999994 for the + // y coordinate leading to inconsistent rounding. + Point::new(408.0, 386.5), + Point::new(368.16666666666663, 495.0833333333333), + Point::new(301.0, 560.0), + Point::new(260.0, 560.0) + ] + ); + } + + #[test] + fn cubicbez_inflections() { + let c = CubicBez::new((0., 0.), (0.8, 1.), (0.2, 1.), (1., 0.)); + let inflections = c.inflections(); + assert_eq!(inflections.len(), 2); + assert!((inflections[0] - 0.311018).abs() < 1e-6); + assert!((inflections[1] - 0.688982).abs() < 1e-6); + let c = CubicBez::new((0., 0.), (1., 1.), (2., -1.), (3., 0.)); + let inflections = c.inflections(); + assert_eq!(inflections.len(), 1); + assert!((inflections[0] - 0.5).abs() < 1e-6); + let c = CubicBez::new((0., 0.), (1., 1.), (2., 1.), (3., 0.)); + let inflections = c.inflections(); + assert_eq!(inflections.len(), 0); + } + + #[test] + fn cubic_to_quadratic_matches_python() { + // from https://github.com/googlefonts/fontmake-rs/issues/217 + let cubic = CubicBez { + p0: (796.0, 319.0).into(), + p1: (727.0, 314.0).into(), + p2: (242.0, 303.0).into(), + p3: (106.0, 303.0).into(), + }; + + // FontTools can approximate this curve successfully in 7 splits, we can too + assert!(cubic.approx_spline_n(7, 1.0).is_some()); + + // FontTools can solve this with accuracy 0.001, we can too + assert!(cubics_to_quadratic_splines(&[cubic], 0.001).is_some()); + } + + #[test] + fn cubic_to_quadratic_all_points_equal() { + let pt = Point::new(5.0, 5.0); + let cubic = CubicBez::new(pt, pt, pt, pt); + let quads = cubics_to_quadratic_splines(&[cubic], 0.1).unwrap(); + assert_eq!(quads, [QuadSpline::new(vec![pt, pt, pt])]); + } + + #[test] + fn cubic_to_quadratic_3_points_equal_single_quad_within_tolerance() { + let p0 = Point::new(5.0, 5.0); + let p1 = Point::new(5.0, 5.1); + let cubic = CubicBez::new(p0, p0, p0, p1); + let quads = cubics_to_quadratic_splines(&[cubic], 0.1).unwrap(); + // a single quadratic bezier approximates this cubic for the given tolerance + assert_eq!(quads, [QuadSpline::new(vec![p0, p0, p1])]); + } + + #[test] + fn cubic_to_quadratic_3_points_equal_exceeding_tolerance() { + let p0 = Point::new(5.0, 5.0); + let p1 = Point::new(5.0, 5.1); + let cubic = CubicBez::new(p0, p0, p0, p1); + let quads = cubics_to_quadratic_splines(&[cubic], 0.01).unwrap(); + // 2 quadratic off-curves are required to approximate the same cubic + // given the smaller tolerance + assert_eq!( + quads, + [QuadSpline::new(vec![p0, p0, (5.0, 5.025).into(), p1])] + ); + } + + #[test] + fn cubics_to_quadratic_splines_matches_python() { + // https://github.com/linebender/kurbo/pull/273 + let light = CubicBez::new((378., 608.), (378., 524.), (355., 455.), (266., 455.)); + let regular = CubicBez::new((367., 607.), (367., 511.), (338., 472.), (243., 472.)); + let bold = CubicBez::new( + (372.425, 593.05), + (372.425, 524.95), + (355.05, 485.95), + (274., 485.95), + ); + let qsplines = cubics_to_quadratic_splines(&[light, regular, bold], 1.0).unwrap(); + assert_eq!( + qsplines, + [ + QuadSpline::new(vec![ + (378.0, 608.0).into(), + (378.0, 566.0).into(), + (359.0833333333333, 496.5).into(), + (310.5, 455.0).into(), + (266.0, 455.0).into(), + ]), + QuadSpline::new(vec![ + (367.0, 607.0).into(), + (367.0, 559.0).into(), + // Previous behavior produced 496.5 for the y coordinate + (344.5833333333333, 499.49999999999994).into(), + (290.5, 472.0).into(), + (243.0, 472.0).into(), + ]), + QuadSpline::new(vec![ + (372.425, 593.05).into(), + (372.425, 559.0).into(), + (356.98333333333335, 511.125).into(), + (314.525, 485.95).into(), + (274.0, 485.95).into(), + ]), + ] + ); + } +} diff --git a/vendor/kurbo/src/ellipse.rs b/vendor/kurbo/src/ellipse.rs new file mode 100644 index 0000000000..7eea2b4906 --- /dev/null +++ b/vendor/kurbo/src/ellipse.rs @@ -0,0 +1,554 @@ +// Copyright 2020 the Kurbo Authors +// SPDX-License-Identifier: Apache-2.0 OR MIT + +//! Implementation of ellipse shape. + +use core::f64::consts::PI; +use core::{ + iter, + ops::{Add, Mul, Sub}, +}; + +use crate::{Affine, Arc, ArcAppendIter, Circle, PathEl, Point, Rect, Shape, Size, Vec2}; + +#[cfg(not(feature = "std"))] +use crate::common::FloatFuncs; + +/// An ellipse. +#[derive(Clone, Copy, Default, Debug, PartialEq)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +pub struct Ellipse { + /// All ellipses can be represented as an affine map of the unit circle, + /// centred at (0, 0). Therefore we can store the ellipse as an affine map, + /// with the implication that it be applied to the unit circle to recover the + /// actual shape. + inner: Affine, +} + +impl Ellipse { + /// Create A new ellipse with a given center, radii, and rotation. + /// + /// The returned ellipse will be the result of taking a circle, stretching + /// it by the `radii` along the x and y axes, then rotating it from the + /// x axis by `rotation` radians, before finally translating the center + /// to `center`. + /// + /// Rotation is clockwise in a y-down coordinate system. For more on + /// rotation, see [`Affine::rotate`]. + #[inline] + pub fn new(center: impl Into, radii: impl Into, x_rotation: f64) -> Ellipse { + let Point { x: cx, y: cy } = center.into(); + let Vec2 { x: rx, y: ry } = radii.into(); + Ellipse::private_new(Vec2 { x: cx, y: cy }, rx, ry, x_rotation) + } + + /// Returns the largest ellipse that can be bounded by this [`Rect`]. + /// + /// This uses the absolute width and height of the rectangle. + /// + /// This ellipse is always axis-aligned; to apply rotation you can call + /// [`with_rotation`] with the result. + /// + /// [`with_rotation`]: Ellipse::with_rotation + #[inline] + pub fn from_rect(rect: Rect) -> Self { + let center = rect.center().to_vec2(); + let Size { width, height } = rect.size() / 2.0; + Ellipse::private_new(center, width, height, 0.0) + } + + /// Create an ellipse from an affine transformation of the unit circle. + #[inline(always)] + pub const fn from_affine(affine: Affine) -> Self { + Ellipse { inner: affine } + } + + /// Create a new `Ellipse` centered on the provided point. + #[inline] + #[must_use] + pub fn with_center(self, new_center: impl Into) -> Ellipse { + let Point { x: cx, y: cy } = new_center.into(); + Ellipse { + inner: self.inner.with_translation(Vec2 { x: cx, y: cy }), + } + } + + /// Create a new `Ellipse` with the provided radii. + #[inline] + #[must_use] + pub fn with_radii(self, new_radii: Vec2) -> Ellipse { + let rotation = self.inner.svd().1; + let translation = self.inner.translation(); + Ellipse::private_new(translation, new_radii.x, new_radii.y, rotation) + } + + /// Create a new `Ellipse`, with the rotation replaced by `rotation` + /// radians. + /// + /// The rotation is clockwise, for a y-down coordinate system. For more + /// on rotation, See [`Affine::rotate`]. + #[inline] + #[must_use] + pub fn with_rotation(self, rotation: f64) -> Ellipse { + let scale = self.inner.svd().0; + let translation = self.inner.translation(); + Ellipse::private_new(translation, scale.x, scale.y, rotation) + } + + /// This gives us an internal method without any type conversions. + #[inline] + fn private_new(center: Vec2, scale_x: f64, scale_y: f64, x_rotation: f64) -> Ellipse { + // Since the circle is symmetric about the x and y axes, using absolute values for the + // radii results in the same ellipse. For simplicity we make this change here. + Ellipse { + inner: Affine::translate(center) + * Affine::rotate(x_rotation) + * Affine::scale_non_uniform(scale_x.abs(), scale_y.abs()), + } + } + + // Getters and setters. + + /// Returns the center of this ellipse. + #[inline(always)] + pub fn center(&self) -> Point { + self.inner.translation().to_point() + } + + /// Returns the two radii of this ellipse. + /// + /// The first number is the horizontal radius and the second is the vertical + /// radius, before rotation. + /// + /// If you are only interested in the value of the greatest or smallest radius of this ellipse, + /// consider using [`Ellipse::major_radius`] or [`Ellipse::minor_radius`] instead. + #[inline] + pub fn radii(&self) -> Vec2 { + self.inner.svd().0 + } + + /// Returns the major radius of this ellipse. + /// + /// This metric is also known as the semi-major axis. + #[inline] + pub fn major_radius(&self) -> f64 { + self.inner.svd().0.x + } + + /// Returns the minor radius of this ellipse. + /// + /// This metric is also known as the semi-minor axis. + #[inline] + pub fn minor_radius(&self) -> f64 { + self.inner.svd().0.y + } + + /// The ellipse's rotation, in radians. + /// + /// This allows all possible ellipses to be drawn by always starting with + /// an ellipse with the two radii on the x and y axes. + #[inline] + pub fn rotation(&self) -> f64 { + self.inner.svd().1 + } + + /// Returns the radii and the rotation of this ellipse. + /// + /// Equivalent to `(self.radii(), self.rotation())` but more efficient. + #[inline] + pub fn radii_and_rotation(&self) -> (Vec2, f64) { + self.inner.svd() + } + + /// Is this ellipse [finite]? + /// + /// [finite]: f64::is_finite + #[inline] + pub const fn is_finite(&self) -> bool { + self.inner.is_finite() + } + + /// Is this ellipse [NaN]? + /// + /// [NaN]: f64::is_nan + #[inline] + pub const fn is_nan(&self) -> bool { + self.inner.is_nan() + } +} + +impl Add for Ellipse { + type Output = Ellipse; + + /// In this context adding a `Vec2` applies the corresponding translation to the ellipse. + #[inline] + #[allow(clippy::suspicious_arithmetic_impl)] + fn add(self, v: Vec2) -> Ellipse { + Ellipse { + inner: Affine::translate(v) * self.inner, + } + } +} + +impl Sub for Ellipse { + type Output = Ellipse; + + /// In this context subtracting a `Vec2` applies the corresponding translation to the ellipse. + #[inline] + fn sub(self, v: Vec2) -> Ellipse { + Ellipse { + inner: Affine::translate(-v) * self.inner, + } + } +} + +impl Mul for Affine { + type Output = Ellipse; + #[inline] + fn mul(self, other: Ellipse) -> Self::Output { + Ellipse { + inner: self * other.inner, + } + } +} + +impl From for Ellipse { + #[inline] + fn from(circle: Circle) -> Self { + Ellipse::new(circle.center, Vec2::splat(circle.radius), 0.0) + } +} + +impl Shape for Ellipse { + type PathElementsIter<'iter> = iter::Chain, ArcAppendIter>; + + fn path_elements(&self, tolerance: f64) -> Self::PathElementsIter<'_> { + let (radii, x_rotation) = self.inner.svd(); + Arc { + center: self.center(), + radii, + start_angle: 0.0, + sweep_angle: 2.0 * PI, + x_rotation, + } + .path_elements(tolerance) + } + + /// The area of the ellipse. + /// + /// This is always positive if the result is finite. + /// + /// If non-finite, this will be [`f64::INFINITY`] or [`f64::NAN`] depending on whether the + /// inner affine's [determinant](Affine::determinant) is [`f64::INFINITY`] (either positive or + /// negative) or [`f64::NAN`]. + #[inline] + fn area(&self) -> f64 { + // `Ellipse` is represented as a unit circle transformed by `Affine`. The transformed area + // of a region is `area * |det(affine)|`, see + // . + // + // A unit circle has area `PI`. Therefore, the area of this ellipse is PI multiplied by the + // affine's determinant. + PI * self.inner.determinant().abs() + } + + /// Approximate the ellipse perimeter. + /// + /// This uses a numerical approximation. The absolute error between the calculated perimeter + /// and the true perimeter is bounded by `accuracy` (modulo floating point rounding errors). + /// + /// For circular ellipses (equal horizontal and vertical radii), the calculated perimeter is + /// exact. + #[inline] + fn perimeter(&self, accuracy: f64) -> f64 { + let radii = self.radii(); + + // Note: the radii are calculated from an inner affine map (`self.inner`), and may be NaN. + // Currently, constructing an ellipse with infinite radii will produce an ellipse whose + // calculated radii are NaN. + if !radii.is_finite() { + return f64::NAN; + } + + // Check for the trivial case where the ellipse has one of its radii equal to 0, i.e., + // where it describes a line, as the numerical method used breaks down with this extreme. + if radii.x == 0. || radii.y == 0. { + return 4. * f64::max(radii.x, radii.y); + } + + // Evaluate an approximation based on a truncated infinite series. If it returns a good + // enough value, we do not need to iterate. + if kummer_elliptic_perimeter_range(radii) <= accuracy { + return kummer_elliptic_perimeter(radii); + } + + agm_elliptic_perimeter(accuracy, radii) + } + + #[inline] + fn winding(&self, pt: Point) -> i32 { + // Strategy here is to apply the inverse map to the point and see if it is in the unit + // circle. + let inv = self.inner.inverse(); + if (inv * pt).to_vec2().hypot2() < 1.0 { + 1 + } else { + 0 + } + } + + // Compute a tight bounding box of the ellipse. + // + // See https://www.iquilezles.org/www/articles/ellipses/ellipses.htm. We can get the two + // radius vectors by applying the affine map to the two impulses (1, 0) and (0, 1) which gives + // (a, b) and (c, d) if the affine map is + // + // a | c | e + // ----------- + // b | d | f + // + // We can then use the method in the link with the translation to get the bounding box. + #[inline] + fn bounding_box(&self) -> Rect { + let aff = self.inner.as_coeffs(); + let a2 = aff[0] * aff[0]; + let b2 = aff[1] * aff[1]; + let c2 = aff[2] * aff[2]; + let d2 = aff[3] * aff[3]; + let cx = aff[4]; + let cy = aff[5]; + let range_x = (a2 + c2).sqrt(); + let range_y = (b2 + d2).sqrt(); + Rect { + x0: cx - range_x, + y0: cy - range_y, + x1: cx + range_x, + y1: cy + range_y, + } + } +} + +/// Calculates circumference C of an ellipse with radii (x, y) as the infinite series +/// +/// C = pi (x+y) * ∑ binom(1/2, n)^2 * h^n from n = 0 to inf +/// with h = (x - y)^2 / (x + y)^2 +/// and binom(.,.) the binomial coefficient +/// +/// as described by Kummer ("Über die Hypergeometrische Reihe", 1837) and rediscovered by +/// Linderholm and Segal ("An Overlooked Series for the Elliptic Perimeter", 1995). +/// +/// The series converges very quickly for ellipses with only moderate eccentricity (`h` not close +/// to 1). +/// +/// The series is truncated to the sixth power, meaning a lower bound on the true value is +/// returned. Adding the value of [`kummer_elliptic_perimeter_range`] to the value returned by this +/// function calculates an upper bound on the true value. +#[inline] +fn kummer_elliptic_perimeter(radii: Vec2) -> f64 { + let Vec2 { x, y } = radii; + let h = ((x - y) / (x + y)).powi(2); + let h2 = h * h; + let h3 = h2 * h; + let h4 = h3 * h; + let h5 = h4 * h; + let h6 = h5 * h; + + let lower = PI + + h * (PI / 4.) + + h2 * (PI / 64.) + + h3 * (PI / 256.) + + h4 * (PI * 25. / 16384.) + + h5 * (PI * 49. / 65536.) + + h6 * (PI * 441. / 1048576.); + + (x + y) * lower +} + +/// This calculates the error range of [`kummer_elliptic_perimeter`]. That function returns a lower +/// bound on the true value, and though we do not know what the remainder of the infinite series +/// sums to, we can calculate an upper bound: +/// +/// ∑ binom(1/2, n)^2 for n = 0 to inf +/// = 1 + (1 / 2!!)^2 + (1!! / 4!!)^2 + (3!! / 6!!)^2 + (5!! / 8!!)^2 + .. +/// = 4 / pi +/// with !! the double factorial +/// (equation 274 in "Summation of Series", L. B. W. Jolley, 1961). +/// +/// This means the remainder of the infinite series for C, assuming the series was truncated to the +/// mth term and h = 1, sums to +/// 4 / pi - ∑ binom(1/2, n)^2 for n = 0 to m-1 +/// +/// As 0 ≤ h ≤ 1, this is an upper bound. +#[inline] +fn kummer_elliptic_perimeter_range(radii: Vec2) -> f64 { + let Vec2 { x, y } = radii; + let h = ((x - y) / (x + y)).powi(2); + + const BINOM_SQUARED_REMAINDER: f64 = 0.00101416479131503; + // = 4. / PI - (1. + 1. / 4. + 1. / 64. + 1. / 256. + 25. / 16384. + 49. / 65536. + 441. / 1048576.) + + PI * BINOM_SQUARED_REMAINDER * h.powi(7) * (x + y) +} + +/// Calculates circumference C of an ellipse with radii (x, y) using the arithmetic-geometric mean, +/// as described in equation 19.8.6 of +/// . +fn agm_elliptic_perimeter(accuracy: f64, radii: Vec2) -> f64 { + let Vec2 { x, y } = if radii.x >= radii.y { + radii + } else { + Vec2::new(radii.y, radii.x) + }; + + let accuracy = accuracy / (2. * PI * x); + + let mut sum = 1.; + let mut a = 1.; + let mut g = y / x; + let mut c = (1. - g.powi(2)).sqrt(); + let mut mul = 0.5; + + loop { + let c2 = c.powi(2); + // term = 2^(n-1) c_n^2 + let term = mul * c2; + sum -= term; + + // We have c_(n+1) ≤ 1/2 c_n + // (for a derivation, see e.g. section 2.1 of "Elliptic integrals, the + // arithmetic-geometric mean and the Brent-Salamin algorithm for π" by G.J.O. Jameson: + // ) + // + // Therefore + // ∑ 2^(i-1) c_i^2 from i = 1 ≤ ∑ 2^(i-1) ((1/2)^i c_0)^2 from i = 1 + // = ∑ 2^-(i+1) c_0^2 from i = 1 + // = 1/2 c_0^2 + // + // or, for arbitrary starting point i = n+1: + // ∑ 2^(i-1) c_i^2 from i = n+1 ≤ ∑ 2^(i-1) ((1/2)^(i-n) c_n)^2 from i = n+1 + // = ∑ 2^(2n - i - 1) c_n^2 from i = n+1 + // = 2^(2n) ∑ 2^(-(i+1)) c_n^2 from i = n+1 + // = 2^(2n) 2^(-(n+1)) c_n^2 + // = 2^(n-1) c_n^2 + // + // Therefore, the remainder of the series sums to less than or equal to 2^(n-1) c_n^2, + // which is exactly the value of the nth term. + // + // Furthermore, a_m ≥ g_n, and g_n ≤ 1, for all m, n. + if term <= accuracy * g { + // `sum` currently overestimates the true value - subtract the upper bound of the + // remaining series. We will then underestimate the true value, but by no more than + // `accuracy`. + sum -= term; + break; + } + + mul *= 2.; + // This is equal to c_next = c^2 / (4 * a_next) + c = (a - g) / 2.; + let a_next = (a + g) / 2.; + g = (a * g).sqrt(); + a = a_next; + } + + 2. * PI * x / a * sum +} + +#[cfg(test)] +mod tests { + use crate::{Circle, Ellipse, Point, Shape}; + use std::f64::consts::PI; + + fn assert_approx_eq(x: f64, y: f64) { + // Note: we might want to be more rigorous in testing the accuracy + // of the conversion into Béziers. But this seems good enough. + assert!((x - y).abs() < 1e-7, "{x} != {y}"); + } + + #[test] + fn circular_perimeter() { + for radius in [1.0, 0., 1.5, PI, 10.0, -1.0, 1_234_567_890.1] { + let circle = Circle::new((0., 0.), radius); + let ellipse = Ellipse::new((0., 0.), (radius, radius), 0.); + + let circle_p = circle.perimeter(0.); + let ellipse_p = ellipse.perimeter(0.1); + + // We expect the results to be identical, modulo potential roundoff errors. Compare + // with a very small relative epsilon. + let epsilon = f64::EPSILON * 8. * circle_p.max(ellipse_p); + assert!( + (circle_p - ellipse_p).abs() <= epsilon, + "Expected circular ellipse radius {ellipse_p} to be equal to circle radius {circle_p} for radius {radius}" + ); + } + } + + #[test] + fn compare_perimeter_with_bez() { + const EPSILON: f64 = 0.000_002; + + for radii in [ + (0.5, 1.), + (2., 1.), + (0.000_000_1, 1.), + (0., 1.), + (1., 0.), + (-0.5, 1.), + (-0.000_000_1, -1.), + ] { + let ellipse = Ellipse::new((0., 0.), radii, 0.); + + let ellipse_p = ellipse.perimeter(0.000_001); + let bez_p = ellipse.path_segments(0.000_000_25).perimeter(0.000_000_25); + + assert!( + (ellipse_p - bez_p).abs() < EPSILON, + "Numerically approximated ellipse perimeter ({ellipse_p}) does not match bezier segment perimeter length ({bez_p}) for radii {radii:?}" + ); + } + } + + #[test] + fn known_perimeter() { + const ACCURACY: f64 = 0.000_000_000_001; + + for (radii, perimeter) in [ + ((0.5, 1.), 4.844_224_110_273_838), + ((0.001, 1.), 4.000_015_588_104_688), + ] { + let ellipse = Ellipse::new((0., 0.), radii, 0.); + + let ellipse_p = ellipse.perimeter(ACCURACY); + assert!( + (ellipse_p - perimeter).abs() <= ACCURACY, + "Numerically approximated ellipse perimeter ({ellipse_p}) does not match known perimeter ({perimeter}) radii {radii:?}" + ); + } + } + + #[test] + fn area_sign() { + let center = Point::new(5.0, 5.0); + let e = Ellipse::new(center, (5.0, 5.0), 1.0); + assert_approx_eq(e.area(), 25.0 * PI); + let e = Ellipse::new(center, (5.0, 10.0), 1.0); + assert_approx_eq(e.area(), 50.0 * PI); + + assert_eq!(e.winding(center), 1); + + let p = e.to_path(1e-9); + assert_approx_eq(e.area(), p.area()); + assert_eq!(e.winding(center), p.winding(center)); + + let e_neg_radius = Ellipse::new(center, (-5.0, 10.0), 1.0); + assert_approx_eq(e_neg_radius.area(), 50.0 * PI); + + assert_eq!(e_neg_radius.winding(center), 1); + + let p_neg_radius = e_neg_radius.to_path(1e-9); + assert_approx_eq(e_neg_radius.area(), p_neg_radius.area()); + assert_eq!(e_neg_radius.winding(center), p_neg_radius.winding(center)); + } +} diff --git a/vendor/kurbo/src/expand.rs b/vendor/kurbo/src/expand.rs new file mode 100644 index 0000000000..284d7f1c7c --- /dev/null +++ b/vendor/kurbo/src/expand.rs @@ -0,0 +1,604 @@ +// Copyright 2026 the Kurbo Authors +// SPDX-License-Identifier: Apache-2.0 OR MIT + +use crate::{ + Affine, Arc, BezPath, CubicBez, Join, ParamCurve, ParamCurveDeriv, PathEl, PathSeg, Point, + QuadBez, Shape, Vec2, bezpath::close_subpaths, segments, +}; + +#[cfg(not(feature = "std"))] +use crate::common::FloatFuncs; + +/// A diagonal matrix, suitable for representing anisotropic scaling. +#[derive(Clone, Copy, Debug, PartialEq)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +pub struct Diagonal2 { + /// The horizontal expansion factor. + pub xx: f64, + /// The vertical expansion factor. + pub yy: f64, +} + +struct ExpandCtx { + expand: Diagonal2, + join: Join, + miter_limit: f64, + tolerance: f64, + result: BezPath, + first_n: Option, + first_tan: Vec2, + last_pt: Point, + last_n: Option, + last_tan: Vec2, +} + +struct CubicCtx { + q: QuadBez, + utan0: Vec2, + utan1: Vec2, +} + +struct TwoPointSample { + a_n: f64, + b_n: f64, + c_n: f64, +} + +impl Diagonal2 { + /// Create a diagonal matrix. + pub const fn new(xx: f64, yy: f64) -> Self { + Self { xx, yy } + } + + /// Matrix inverse. + /// + /// Will of course produce infinities if a component is zero. + pub const fn inv(self) -> Self { + Diagonal2::new(1.0 / self.xx, 1.0 / self.yy) + } + + /// Absolute value of transform components. + pub const fn abs(self) -> Self { + Self::new(self.xx.abs(), self.yy.abs()) + } + + /// Scale a normal vector. + /// + /// This is mathematically equivalent to `self * (self * n).normalize()` + /// for positive transforms, but handles zeros and gets the sign correct + /// when negative. + /// + /// Note that `n` need not be unit length. + pub fn scale_normal(self, n: Vec2) -> Vec2 { + let z = self * n; + let z_hypot2 = z.hypot2(); + if z_hypot2 == 0.0 { + Vec2::ZERO + } else { + let inv_scale = 1.0 / z_hypot2.sqrt(); + self.abs() * z * inv_scale + } + } +} + +impl core::ops::Neg for Diagonal2 { + type Output = Self; + + fn neg(self) -> Self { + Diagonal2::new(-self.xx, -self.yy) + } +} + +impl core::ops::Mul for Diagonal2 { + type Output = Vec2; + + fn mul(self, rhs: Vec2) -> Vec2 { + Vec2::new(self.xx * rhs.x, self.yy * rhs.y) + } +} + +impl core::ops::Mul for Diagonal2 { + type Output = Point; + + fn mul(self, rhs: Point) -> Point { + Point::new(self.xx * rhs.x, self.yy * rhs.y) + } +} + +// Note: a bunch more ops on `Diagonal2` could be implemented, but for now we'll stick to what we need. + +/// Expand a path. +/// +/// Expands a filled path by the expansion, which allows separate x and y factors. The +/// path (and the result) is interpreted according to the nonzero winding rule. Both +/// factors should be positive. A negative expansion will shrink the path but is also +/// likely to leave intersection artifacts at corners. +/// +/// The direction of the expansion is based on the signed area of the overall path. +/// This should give expected results most of the time, but there are exceptions. For a +/// figure-eight path, one lobe will be expanded and the other shrunk. Similarly if +/// there are two disjoint subpaths with opposite winding. +/// +/// The tolerance is mostly for joins and robustness; it is not used to guide +/// subdivision. Rather, each Bézier segment in the input generally results in one +/// cubic Bézier in the output. Thus, it is not expected to work well when the +/// expansion factor is large compared with the radius of curvature on the input. +pub fn expand_path( + path: impl Shape, + mut expand: Diagonal2, + join: Join, + miter_limit: f64, + tolerance: f64, +) -> BezPath { + if segments(close_subpaths(path.path_elements(tolerance))).area() >= 0.0 { + expand = -expand; + } + expand_path_signed(path, expand, join, miter_limit, tolerance) +} + +/// Expand a path when the sign is known. +/// +/// Applies the expansion based on the path orientation, so that expansion happens +/// with positive `expand` values on subpaths with negative area, or vice versa. This +/// is backwards from the intuitive sign convention, but results from the choice of +/// convention for the offset primitives. +pub fn expand_path_signed( + path: impl Shape, + expand: Diagonal2, + join: Join, + miter_limit: f64, + tolerance: f64, +) -> BezPath { + let result = BezPath::new(); + let mut ctx = ExpandCtx { + expand, + join, + miter_limit, + tolerance, + result, + first_n: None, + first_tan: Vec2::default(), + last_pt: Point::default(), + last_n: None, + last_tan: Vec2::default(), + }; + let mut first_pt = Point::default(); + for el in path.path_elements(tolerance) { + match el { + PathEl::MoveTo(point) => { + ctx.do_close_path(first_pt); + first_pt = point; + ctx.last_pt = point; + } + PathEl::LineTo(p1) => ctx.do_line(p1), + PathEl::QuadTo(p1, p2) => ctx.do_quad(p1, p2), + PathEl::CurveTo(p1, p2, p3) => ctx.do_cubic(p1, p2, p3), + PathEl::ClosePath => ctx.do_close_path(first_pt), + } + } + // Treat all subpaths as closed; close if left open in input. + ctx.do_close_path(first_pt); + ctx.result +} + +impl ExpandCtx { + /// Helper function to determine if a distance is within tolerance. + fn in_tolerance(&self, v: Vec2) -> bool { + v.hypot2() < self.tolerance * self.tolerance + } + + /// Process a line segment. Includes initial join. + fn do_line(&mut self, p1: Point) { + if p1 == self.last_pt { + return; + } + let tan = p1 - self.last_pt; + let n = self.expand.scale_normal(tan.turn_90()); + self.do_join(n, tan, true); + let out_p1 = p1 + n; + self.result.line_to(out_p1); + self.last_n = Some(n); + self.last_tan = tan; + self.last_pt = p1; + } + + /// Process a quadratic Bézier segment. Includes initial join. + fn do_quad(&mut self, p1: Point, p2: Point) { + let q0 = p1 - self.last_pt; + let q1 = p2 - p1; + if self.in_tolerance(q0) || self.in_tolerance(q1) { + self.do_line(p2); + return; + } + let einv = self.expand.inv(); + let utan0 = (einv * q0).normalize(); + let utan1 = (einv * q1).normalize(); + let det = utan1.cross(utan0); + if det.abs() < 1e-10 { + self.do_line(p2); + return; + } + let utanm = (einv * (p2 - self.last_pt)).normalize(); + let n0 = self.expand.abs() * utan0.turn_90(); + let n1 = self.expand.abs() * utan1.turn_90(); + let mid_chord = self.last_pt.midpoint(p2); + let m = mid_chord.midpoint(p1) + self.expand.abs() * utanm.turn_90(); + let out_p0 = self.last_pt + n0; + let out_p3 = p2 + n1; + let rhs = einv * (m - out_p0.midpoint(out_p3)); + let idet = (8. / 3.) / det; + let a = (utan1.cross(rhs) * idet).max(0.0); + let b = (utan0.cross(rhs) * idet).max(0.0); + self.do_join(n0, q0, false); + let out_p1 = out_p0 + self.expand * (a * utan0); + let out_p2 = out_p3 - self.expand * (b * utan1); + self.result.curve_to(out_p1, out_p2, out_p3); + self.last_n = Some(n1); + self.last_tan = q1; + self.last_pt = p2; + } + + /// Process a cubic segment. Includes initial join. + fn do_cubic(&mut self, p1: Point, p2: Point, p3: Point) { + let einv = self.expand.inv(); + let c = CubicBez::new(einv * self.last_pt, einv * p1, einv * p2, einv * p3); + let (tan0, tan1) = PathSeg::Cubic(c).tangents(); + let utan0 = tan0.normalize(); + let utan1 = tan1.normalize(); + let q = c.deriv(); + let p1xp0 = q.p1.to_vec2().cross(q.p0.to_vec2()); + let p2xp1 = q.p2.to_vec2().cross(q.p1.to_vec2()); + let cx = CubicCtx { q, utan0, utan1 }; + // First we try one-point, but only if there isn't one inflection point. + let mut soln = if p1xp0 * p2xp1 >= 0.0 { + try_one_point(&cx) + } else { + None + }; + if soln.is_none() { + // We try two-point linear if we don't have a one-point solution. A + // more sophisticated approach would be to evaluate error and pick a + // minimum, but that would be more complexity and take time. This is + // very likely good enough for the purpose. + soln = two_point_linear(&cx); + } + if let Some((a, b)) = soln { + let n0 = self.expand.abs() * utan0.turn_90(); + let n1 = self.expand.abs() * utan1.turn_90(); + self.do_join(n0, self.expand * utan0, false); + let out_p3 = p3 + n1; + // TODO: clamp to correct direction + let out_p1 = p1 + n0 + self.expand.abs() * (a * utan0); + let out_p2 = p2 + n1 + self.expand.abs() * (b * utan1); + self.result.curve_to(out_p1, out_p2, out_p3); + self.last_n = Some(n1); + self.last_tan = self.expand * utan1; + self.last_pt = p3; + } else { + self.do_line(p3); + } + } + + /// Do a join. + /// + /// The `tan` parameter is a vector tangent to the start of the new segment. + /// The `n` parameter is the normal vector (turned tangent) scaled by the expansion. + fn do_join(&mut self, n: Vec2, tan: Vec2, is_line: bool) { + // TODO: other join types etc + if let Some(last_n) = self.last_n { + let p = self.last_pt + n; + if !self.in_tolerance(n - last_n) { + if self.join != Join::Bevel { + let cross = self.last_tan.cross(tan); + if cross * self.expand.xx < 0.0 { + match self.join { + Join::Bevel => unreachable!(), + Join::Miter => { + let dot = self.last_tan.dot(tan); + let hypot = cross.hypot(dot); + if 2.0 * hypot < (hypot + dot) * self.miter_limit * self.miter_limit + { + let h = (n - last_n).cross(tan) / self.last_tan.cross(tan); + let miter_pt = self.last_pt + last_n + h * self.last_tan; + // A cheap optimization to reduce line segments with joins to lines + if let Some(PathEl::LineTo(p)) = + self.result.elements_mut().last_mut() + { + *p = miter_pt; + } else { + self.result.line_to(miter_pt); + } + if is_line { + return; + } + } + } + Join::Round => { + // Cheaper inverse; everything is normalized so we don't care about uniform scaling. + let einv = Diagonal2::new(self.expand.yy, self.expand.xx); + let last_tann = einv * self.last_tan; + let tann = einv * tan; + let crossn = (last_tann).cross(tann); + let dotn = (last_tann).dot(tann); + let angle = crossn.atan2(dotn).abs(); + let nt = self.expand * tann.normalize(); + let a = Affine::new([ + n.x, + n.y, + nt.x, + nt.y, + self.last_pt.x, + self.last_pt.y, + ]); + let arc: Arc = + Arc::new(Point::ORIGIN, (1.0, 1.0), -angle, angle, 0.0); + let tolerance = self.tolerance / einv.xx.abs().max(einv.yy.abs()); + arc.to_cubic_beziers(tolerance, |p1, p2, p3| { + self.result.curve_to(a * p1, a * p2, a * p3); + }); + return; + } + } + } + } + // Bevel case + self.result.line_to(p); + } + } else { + self.result.move_to(self.last_pt + n); + self.first_n = Some(n); + self.first_tan = tan; + } + } + + /// Close an open subpath if there is one; no-op if already closed. + fn do_close_path(&mut self, first_pt: Point) { + if let Some(first_n) = self.first_n.take() { + // could do this test inside do_line for all lines, but it already checks for 0-length + if first_pt.distance_squared(self.last_pt) > self.tolerance * self.tolerance { + self.do_line(first_pt); + } + self.do_join(first_n, self.first_tan, true); + self.result.close_path(); + } + self.last_n = None; + } +} + +// Note: here is our own copy of sophisticated cubic Bézier offset logic. We have +// the ability to apply anisotropic expansion, but not cusp detection or subdivision, +// and I've also stripped out all the error evaluation. At some point, we want to +// redo stroking, and there may be an opportunity to share code. + +/// Try to compute one-point shape control for a cubic. +/// +/// Result is (a, b) parameters. +fn try_one_point(cx: &CubicCtx) -> Option<(f64, f64)> { + // TODO: possibly reduce duplication with quadratic case. + let tan = cx.q.eval(0.5).to_vec2(); + let tan_hypot2 = tan.hypot2(); + if tan_hypot2 < 1e-12 { + return None; + } + let utan = tan / tan_hypot2.sqrt(); + let z = (utan - 0.5 * (cx.utan0 + cx.utan1)).turn_90(); + let cross = cx.utan0.cross(cx.utan1); + if cross.abs() < 1e-12 { + return None; + } + let idet = (8. / 3.) / cross; + let a = z.cross(cx.utan1) * idet; + let b = cx.utan0.cross(z) * idet; + //let delta_tan = 0.75 * (b * cx.utan1 - a * cx.utan0) + 1.5 * (cx.utan1 - cx.utan0).turn_90(); + //let angle_err = delta_tan.cross(utan); + //let err_est = 0.16 * angle_err.abs(); + Some((a, b)) +} + +fn two_point_linear(cx: &CubicCtx) -> Option<(f64, f64)> { + const T0: f64 = 0.35; + let s = [T0, 1.0 - T0].map(|t| { + let utan = cx.q.eval(t).to_vec2().normalize(); + let n = utan.turn_90(); + let utan0_n = cx.utan0.dot(n); + let utan1_n = cx.utan1.dot(n); + let utan0xn = cx.utan0.dot(utan); + let utan1xn = cx.utan1.dot(utan); + let mt = 1.0 - t; + let b0 = mt * mt * mt; + let b1 = 3.0 * mt * t * mt; + let b2 = 3.0 * mt * t * t; + let b3 = t * t * t; + let a_n = b1 * utan0_n; + let b_n = b2 * utan1_n; + let c_n = (b0 + b1) * utan0xn + (b2 + b3) * utan1xn - 1.0; + TwoPointSample { a_n, b_n, c_n } + }); + let det = s[0].a_n * s[1].b_n - s[1].a_n * s[0].b_n; + // Consider both near-zero and NaN determinants to be failures. + if det.abs().partial_cmp(&1e-12) != Some(core::cmp::Ordering::Greater) { + return None; + } + let idet = -1.0 / det; + let a = idet * (s[0].c_n * s[1].b_n - s[1].c_n * s[0].b_n); + let b = idet * (s[0].a_n * s[1].c_n - s[1].a_n * s[0].c_n); + Some((a, b)) +} + +#[cfg(test)] +mod tests { + use std::f64::consts::PI; + + use crate::{ + Affine, BezPath, Circle, Diagonal2, Join, ParamCurveMoments, PathEl, Point, Rect, Shape, + Size, Vec2, expand_path, + }; + + #[test] + fn expand_circle_basic() { + const CENTER: Point = Point::new(100., 100.); + const RADIUS: f64 = 10.0; + let circle = Circle::new(CENTER, RADIUS); + let expected_area = PI * RADIUS.powi(2); + let expected_perimeter = 2.0 * PI * RADIUS; + assert!((circle.area() - expected_area).abs() < 1e-9); + assert!((circle.perimeter(1e-12) - expected_perimeter).abs() < 1e-9); + const R_DELTA: f64 = 2.0; + const EXPAND: Diagonal2 = Diagonal2::new(R_DELTA, R_DELTA); + let expanded = expand_path(circle, EXPAND, Join::Bevel, 4.0, 1e-3); + let expected_area_expanded = PI * (RADIUS + R_DELTA).powi(2); + let expected_perimeter_expanded = 2.0 * PI * (RADIUS + R_DELTA); + assert!((expanded.area() - expected_area_expanded).abs() < 4e-2); + assert!((expanded.perimeter(1e-12) - expected_perimeter_expanded).abs() < 3e-3); + + let mirror = Affine::reflect(CENTER, Vec2::new(0.0, 1.0)); + // We have to convert to a path here as the circle type doesn't support negative area. + let circle_mirror = mirror * circle.to_path(1e-3); + let expanded_mirror = expand_path(circle_mirror, EXPAND, Join::Bevel, 4.0, 1e-3); + assert!((-expanded_mirror.area() - expected_area_expanded).abs() < 4e-2); + assert!((expanded_mirror.perimeter(1e-12) - expected_perimeter_expanded).abs() < 3e-3); + } + + #[test] + fn expand_ellipse_anisotropic() { + const CENTER: Point = Point::new(100., 100.); + const RADIUS: f64 = 10.0; + let circle = Circle::new(CENTER, RADIUS); + const STRETCH: f64 = 2.717; + let ellipse = Affine::scale_non_uniform(STRETCH, 1.0) * circle; + let expected_area = PI * RADIUS.powi(2) * STRETCH; + assert!((ellipse.area() - expected_area).abs() < 1e-9); + const R_DELTA: f64 = 2.0; + const EXPAND: Diagonal2 = Diagonal2::new(R_DELTA * STRETCH, R_DELTA); + let expanded = expand_path(ellipse, EXPAND, Join::Bevel, 4.0, 1e-3); + let expected_area_expanded = PI * (RADIUS + R_DELTA).powi(2) * STRETCH; + assert!((expanded.area() - expected_area_expanded).abs() < 4e-2); + } + + #[test] + fn expand_rect() { + const CENTER: Point = Point::new(100., 100.); + const SIZE: Size = Size::new(30., 20.); + let rect = Rect::from_center_size(CENTER, SIZE); + assert!((rect.area() - SIZE.area()).abs() < 1e-9); + const EXPAND: Diagonal2 = Diagonal2::new(10.0, 10.0); + let mitered = expand_path(rect, EXPAND, Join::Miter, 4.0, 1e-3); + let expected_area_mitered = + (SIZE.width + 2.0 * EXPAND.xx) * (SIZE.height + 2.0 * EXPAND.yy); + assert!((mitered.area() - expected_area_mitered).abs() < 1e-9); + + let beveled = expand_path(rect, EXPAND, Join::Bevel, 4.0, 1e-3); + let expected_area_beveled = expected_area_mitered - 2.0 * EXPAND.xx * EXPAND.yy; + assert!((beveled.area() - expected_area_beveled).abs() < 1e-9); + + let rounded = expand_path(rect, EXPAND, Join::Round, 4.0, 0.1); + let expected_area_rounded = expected_area_mitered - (4.0 - PI) * EXPAND.xx * EXPAND.yy; + assert!((rounded.area() - expected_area_rounded).abs() < 1e-1); + } + + #[test] + fn expand_rounding_tolerance() { + const CENTER: Point = Point::new(100., 100.); + const SIZE: Size = Size::new(30., 20.); + let rect = Rect::from_center_size(CENTER, SIZE); + const EXPAND: Diagonal2 = Diagonal2::new(10.0, 10.0); + let expected_area_mitered = + (SIZE.width + 2.0 * EXPAND.xx) * (SIZE.height + 2.0 * EXPAND.yy); + let expected_area_rounded = expected_area_mitered - (4.0 - PI) * EXPAND.xx * EXPAND.yy; + let rounded = expand_path(rect, EXPAND, Join::Round, 4.0, 1e-3); + assert!((rounded.area() - expected_area_rounded).abs() < 2e-3); + // Validate that a lower tolerance increases accuracy. + let rounded_fine = expand_path(rect, EXPAND, Join::Round, 4.0, 1e-6); + assert!((rounded_fine.area() - expected_area_rounded).abs() < 3e-5); + } + + #[test] + fn expand_glyph_shape() { + // WARNING: this test is fragile. If there is optimization to simplify inner joins by + // computing intersections, the measurements change. A properly written test would + // compare the result after path intersection, or alternatively probe for zero/nonzero + // winding number for a collection of sample points. But at least it is sensitive to + // regressions. + + // Roboto "e" glyph + let path = BezPath::from_svg( + "M10.359375,-0.359375 Q6.484375,-0.359375 4.0625,2.1875 Q1.640625,4.734375 1.640625,8.984375 \ + L1.640625,9.578125 Q1.640625,12.40625 2.71875,14.625 Q3.796875,16.859375 5.734375,18.109375 \ + Q7.6875,19.375 9.953125,19.375 Q13.65625,19.375 15.703125,16.921875 Q17.765625,14.484375 17.765625,9.9375 \ + L17.765625,8.578125 L4.890625,8.578125 Q4.953125,5.765625 6.53125,4.03125 Q8.109375,2.296875 10.53125,2.296875 \ + Q12.25,2.296875 13.4375,3 Q14.640625,3.703125 15.546875,4.875 L17.53125,3.328125 Q15.140625,-0.359375 10.359375,-0.359375 Z \ + M9.953125,16.703125 Q7.984375,16.703125 6.640625,15.265625 Q5.3125,13.828125 5,11.25 L14.515625,11.25 L14.515625,11.5 \ + Q14.375,13.96875 13.171875,15.328125 Q11.984375,16.703125 9.953125,16.703125 Z", + ) + .unwrap(); + const EXPAND: Diagonal2 = Diagonal2::new(1.5, 1.0); + let expanded = expand_path(&path, EXPAND, Join::Round, 4.0, 0.1); + //println!("{}", expanded.to_svg()); + // The outline has been visually verified, these are measurements taken from known-good. + const EXPECTED_AREA: f64 = -291.3217958410297; + const EXPECTED_PERIMETER: f64 = 120.89147879578239; + const EXPECTED_MOMENT_X: f64 = -2788.568539588466; + const EXPECTED_MOMENT_Y: f64 = -2801.3818805722685; + const EXPECTED_MOMENT_XX: f64 = -34280.940819978576; + const EXPECTED_MOMENT_XY: f64 = -26971.281063345254; + const EXPECTED_MOMENT_YY: f64 = -36722.298990246876; + assert!((expanded.area() - EXPECTED_AREA).abs() < 1e-3); + assert!((expanded.perimeter(1e-9) - EXPECTED_PERIMETER).abs() < 1e-3); + let moments = expanded.moments(); + assert!((moments.moment_x - EXPECTED_MOMENT_X).abs() < 1e-3); + assert!((moments.moment_y - EXPECTED_MOMENT_Y).abs() < 1e-3); + assert!((moments.moment_xx - EXPECTED_MOMENT_XX).abs() < 1e-3); + assert!((moments.moment_xy - EXPECTED_MOMENT_XY).abs() < 1e-3); + assert!((moments.moment_yy - EXPECTED_MOMENT_YY).abs() < 1e-3); + } + + #[test] + fn assert_expand_subpath_closed() { + let mut path = BezPath::new(); + path.move_to((0.0, 0.0)); + path.line_to((100.0, 0.0)); + path.line_to((100.0, 100.0)); + path.line_to((0.0, 100.0)); + + let expanded = expand_path(path, Diagonal2::new(10.0, 10.0), Join::Miter, 4.0, 1e-3); + assert_eq!(expanded.elements().last(), Some(&PathEl::ClosePath)); + } + + #[test] + fn expand_degenerate_input() { + let path = BezPath::from_svg("M0,0 C0,0 0,0 0,0 Z").unwrap(); + let expanded = expand_path(path, Diagonal2::new(10.0, 10.0), Join::Miter, 4.0, 1e-3); + assert!(expanded.is_empty()); + } + + #[test] + fn expand_degenerate_ghost() { + let mut path = BezPath::new(); + path.extend(Rect::new(0.0, 0.0, 10.0, 10.0).path_elements(1e-3)); + let expected = expand_path(&path, Diagonal2::new(1.0, 1.0), Join::Miter, 4.0, 1e-3); + + path.move_to((20.0, 20.0)); + path.close_path(); + let actual = expand_path(&path, Diagonal2::new(1.0, 1.0), Join::Miter, 4.0, 1e-3); + + assert_eq!(actual, expected); + } + + #[test] + fn expand_open_subpath_uses_implicit_close_for_area_sign() { + let mut open = BezPath::new(); + open.move_to((100.0, 100.0)); + open.line_to((110.0, 100.0)); + open.line_to((100.0, 110.0)); + + let mut closed = open.clone(); + closed.close_path(); + + let expand = Diagonal2::new(1.0, 1.0); + let open_expanded = expand_path(open, expand, Join::Miter, 4.0, 1e-3); + let closed_expanded = expand_path(closed, expand, Join::Miter, 4.0, 1e-3); + + assert_eq!(open_expanded, closed_expanded); + } +} diff --git a/vendor/kurbo/src/fit.rs b/vendor/kurbo/src/fit.rs new file mode 100644 index 0000000000..1f739cb868 --- /dev/null +++ b/vendor/kurbo/src/fit.rs @@ -0,0 +1,719 @@ +// Copyright 2022 the Kurbo Authors +// SPDX-License-Identifier: Apache-2.0 OR MIT + +//! An implementation of cubic Bézier curve fitting based on a quartic +//! solver making signed area and moment match the source curve. + +use core::ops::Range; + +use alloc::vec::Vec; + +use arrayvec::ArrayVec; + +use crate::{ + Affine, BezPath, CubicBez, Line, ParamCurve, ParamCurveArclen, ParamCurveNearest, Point, Vec2, + common::{ + GAUSS_LEGENDRE_COEFFS_16, factor_quartic_inner, solve_cubic, solve_itp_fallible, + solve_quadratic, + }, +}; + +#[cfg(not(feature = "std"))] +use crate::common::FloatFuncs; + +/// The source curve for curve fitting. +/// +/// This trait is a general representation of curves to be used as input to a curve +/// fitting process. It can represent source curves with cusps and corners, though +/// if the corners are known in advance, it may be better to run curve fitting on +/// subcurves bounded by the corners. +/// +/// The trait primarily works by sampling the source curve and computing the position +/// and derivative at each sample. Those derivatives are then used for multiple +/// sub-tasks, including ensuring G1 continuity at subdivision points, computing the +/// area and moment of the curve for curve fitting, and casting rays for evaluation +/// of a distance metric to test accuracy. +/// +/// A major motivation is computation of offset curves, which often have cusps, but +/// the presence and location of those cusps is not generally known. It is also +/// intended for conversion between curve types (for example, piecewise Euler spiral +/// or NURBS), and distortion effects such as perspective transform. +/// +/// Note general similarities to [`ParamCurve`] but also important differences. +/// Instead of separate [`eval`] and evaluation of derivative, have a single +/// [`sample_pt_deriv`] method which can be more efficient and also handles cusps more +/// robustly. Also there is no method for subsegment, as that is not needed and +/// would be annoying to implement. +/// +/// [`ParamCurve`]: crate::ParamCurve +/// [`eval`]: crate::ParamCurve::eval +/// [`sample_pt_deriv`]: ParamCurveFit::sample_pt_deriv +pub trait ParamCurveFit { + /// Evaluate the curve and its tangent at parameter `t`. + /// + /// For a regular curve (one not containing a cusp or corner), the + /// derivative is a good choice for the tangent vector and the `sign` + /// parameter can be ignored. Otherwise, the `sign` parameter selects which + /// side of the discontinuity the tangent will be sampled from. + /// + /// Generally `t` is in the range [0..1]. + fn sample_pt_tangent(&self, t: f64, sign: f64) -> CurveFitSample; + + /// Evaluate the point and derivative at parameter `t`. + /// + /// In curves with cusps, the derivative can go to zero. + fn sample_pt_deriv(&self, t: f64) -> (Point, Vec2); + + /// Compute moment integrals. + /// + /// This method computes the integrals of y dx, x y dx, and y^2 dx over the + /// length of this curve. From these integrals it is fairly straightforward + /// to derive the moments needed for curve fitting. + /// + /// A default implementation is provided which does quadrature integration + /// with Green's theorem, in terms of samples evaluated with + /// [`sample_pt_deriv`]. + /// + /// [`sample_pt_deriv`]: ParamCurveFit::sample_pt_deriv + fn moment_integrals(&self, range: Range) -> (f64, f64, f64) { + let t0 = 0.5 * (range.start + range.end); + let dt = 0.5 * (range.end - range.start); + let (a, x, y) = GAUSS_LEGENDRE_COEFFS_16 + .iter() + .map(|(wi, xi)| { + let t = t0 + xi * dt; + let (p, d) = self.sample_pt_deriv(t); + let a = wi * d.x * p.y; + let x = p.x * a; + let y = p.y * a; + (a, x, y) + }) + .fold((0.0, 0.0, 0.0), |(a0, x0, y0), (a1, x1, y1)| { + (a0 + a1, x0 + x1, y0 + y1) + }); + (a * dt, x * dt, y * dt) + } + + /// Find a cusp or corner within the given range. + /// + /// If the range contains a corner or cusp, return it. If there is more + /// than one such discontinuity, any can be reported, as the function will + /// be called repeatedly after subdivision of the range. + /// + /// Do not report cusps at the endpoints of the range, as this may cause + /// potentially infinite subdivision. In particular, when a cusp is reported + /// and this method is called on a subdivided range bounded by the reported + /// cusp, then the subsequent call should not report a cusp there. + /// + /// The definition of what exactly constitutes a cusp is somewhat loose. + /// If a cusp is missed, then the curve fitting algorithm will attempt to + /// fit the curve with a smooth curve, which is generally not a disaster + /// will usually result in more subdivision. Conversely, it might be useful + /// to report near-cusps, specifically points of curvature maxima where the + /// curvature is large but still mathematically finite. + fn break_cusp(&self, range: Range) -> Option; +} + +/// A sample point of a curve for fitting. +pub struct CurveFitSample { + /// A point on the curve at the sample location. + pub p: Point, + /// A vector tangent to the curve at the sample location. + pub tangent: Vec2, +} + +impl CurveFitSample { + /// Intersect a ray orthogonal to the tangent with the given cubic. + /// + /// Returns a vector of `t` values on the cubic. + fn intersect(&self, c: CubicBez) -> ArrayVec { + let p1 = 3.0 * (c.p1 - c.p0); + let p2 = 3.0 * c.p2.to_vec2() - 6.0 * c.p1.to_vec2() + 3.0 * c.p0.to_vec2(); + let p3 = (c.p3 - c.p0) - 3.0 * (c.p2 - c.p1); + let c0 = (c.p0 - self.p).dot(self.tangent); + let c1 = p1.dot(self.tangent); + let c2 = p2.dot(self.tangent); + let c3 = p3.dot(self.tangent); + solve_cubic(c0, c1, c2, c3) + .into_iter() + .filter(|t| (0.0..=1.0).contains(t)) + .collect() + } +} + +/// Generate a Bézier path that fits the source curve. +/// +/// This function is still experimental and the signature might change; it's possible +/// it might become a method on the [`ParamCurveFit`] trait. +/// +/// This function recursively subdivides the curve in half by the parameter when the +/// accuracy is not met. That gives a reasonably optimized result but not necessarily +/// the minimum number of segments. +/// +/// In general, the resulting Bézier path should have a Fréchet distance less than +/// the provided `accuracy` parameter. However, this is not a rigorous guarantee, as +/// the error metric is computed approximately. +/// +/// This function is intended for use when the source curve is piecewise continuous, +/// with the discontinuities reported by the cusp method. In applications (such as +/// stroke expansion) where this property may not hold, it is up to the client to +/// detect and handle such cases. Even so, best effort is made to avoid infinite +/// subdivision. +/// +/// When a higher degree of optimization is desired (at considerably more runtime cost), +/// consider [`fit_to_bezpath_opt`] instead. +pub fn fit_to_bezpath(source: &impl ParamCurveFit, accuracy: f64) -> BezPath { + let mut path = BezPath::new(); + fit_to_bezpath_rec(source, 0.0..1.0, accuracy, &mut path); + path +} + +// Discussion question: possibly should take endpoint samples, to avoid +// duplication of that work. +fn fit_to_bezpath_rec( + source: &impl ParamCurveFit, + range: Range, + accuracy: f64, + path: &mut BezPath, +) { + let start = range.start; + let end = range.end; + let start_p = source.sample_pt_tangent(range.start, 1.0).p; + let end_p = source.sample_pt_tangent(range.end, -1.0).p; + if start_p.distance_squared(end_p) <= accuracy * accuracy { + if let Some((c, _)) = try_fit_line(source, accuracy, range, start_p, end_p) { + if path.is_empty() { + path.move_to(c.p0); + } + path.curve_to(c.p1, c.p2, c.p3); + return; + } + } + let t = if let Some(t) = source.break_cusp(start..end) { + t + } else if let Some((c, _)) = fit_to_cubic(source, start..end, accuracy) { + if path.is_empty() { + path.move_to(c.p0); + } + path.curve_to(c.p1, c.p2, c.p3); + return; + } else { + // A smarter approach is possible than midpoint subdivision, but would be + // a significant increase in complexity. + 0.5 * (start + end) + }; + if t == start || t == end { + // infinite recursion, just draw a line + let p1 = start_p.lerp(end_p, 1.0 / 3.0); + let p2 = end_p.lerp(start_p, 1.0 / 3.0); + if path.is_empty() { + path.move_to(start_p); + } + path.curve_to(p1, p2, end_p); + return; + } + fit_to_bezpath_rec(source, start..t, accuracy, path); + fit_to_bezpath_rec(source, t..end, accuracy, path); +} + +const N_SAMPLE: usize = 20; + +/// An acceleration structure for estimating curve distance +struct CurveDist { + samples: ArrayVec, + arcparams: ArrayVec, + range: Range, + /// A "spicy" curve is one with potentially extreme curvature variation, + /// so use arc length measurement for better accuracy. + spicy: bool, +} + +impl CurveDist { + fn from_curve(source: &impl ParamCurveFit, range: Range) -> Self { + let step = (range.end - range.start) * (1.0 / (N_SAMPLE + 1) as f64); + let mut last_tan = None; + let mut spicy = false; + const SPICY_THRESH: f64 = 0.2; + let mut samples = ArrayVec::new(); + for i in 0..N_SAMPLE + 2 { + let sample = source.sample_pt_tangent(range.start + i as f64 * step, 1.0); + if let Some(last_tan) = last_tan { + let cross = sample.tangent.cross(last_tan); + let dot = sample.tangent.dot(last_tan); + if cross.abs() > SPICY_THRESH * dot.abs() { + spicy = true; + } + } + last_tan = Some(sample.tangent); + if i > 0 && i < N_SAMPLE + 1 { + samples.push(sample); + } + } + CurveDist { + samples, + arcparams: ArrayVec::default(), + range, + spicy, + } + } + + fn compute_arc_params(&mut self, source: &impl ParamCurveFit) { + const N_SUBSAMPLE: usize = 10; + let (start, end) = (self.range.start, self.range.end); + let dt = (end - start) * (1.0 / ((N_SAMPLE + 1) * N_SUBSAMPLE) as f64); + let mut arclen = 0.0; + for i in 0..N_SAMPLE + 1 { + for j in 0..N_SUBSAMPLE { + let t = start + dt * ((i * N_SUBSAMPLE + j) as f64 + 0.5); + let (_, deriv) = source.sample_pt_deriv(t); + arclen += deriv.hypot(); + } + if i < N_SAMPLE { + self.arcparams.push(arclen); + } + } + let arclen_inv = arclen.recip(); + for x in &mut self.arcparams { + *x *= arclen_inv; + } + } + + /// Evaluate distance based on arc length parametrization + fn eval_arc(&self, c: CubicBez, acc2: f64) -> Option { + // TODO: this could perhaps be tuned. + const EPS: f64 = 1e-9; + let c_arclen = c.arclen(EPS); + let mut max_err2 = 0.0; + for (sample, s) in self.samples.iter().zip(&self.arcparams) { + let t = c.inv_arclen(c_arclen * s, EPS); + let err = sample.p.distance_squared(c.eval(t)); + max_err2 = err.max(max_err2); + if max_err2 > acc2 { + return None; + } + } + Some(max_err2) + } + + /// Evaluate distance to a cubic approximation. + /// + /// If distance exceeds stated accuracy, can return `None`. Note that + /// `acc2` is the square of the target. + /// + /// Returns the square of the error, which is intended to be a good + /// approximation of the Fréchet distance. + fn eval_ray(&self, c: CubicBez, acc2: f64) -> Option { + let mut max_err2 = 0.0; + for sample in &self.samples { + let mut best = acc2 + 1.0; + for t in sample.intersect(c) { + let err = sample.p.distance_squared(c.eval(t)); + best = best.min(err); + } + max_err2 = best.max(max_err2); + if max_err2 > acc2 { + return None; + } + } + Some(max_err2) + } + + fn eval_dist(&mut self, source: &impl ParamCurveFit, c: CubicBez, acc2: f64) -> Option { + // Always compute cheaper distance, hoping for early-out. + let ray_dist = self.eval_ray(c, acc2)?; + if !self.spicy { + return Some(ray_dist); + } + if self.arcparams.is_empty() { + self.compute_arc_params(source); + } + self.eval_arc(c, acc2) + } +} + +/// As described in [Simplifying Bézier paths], strictly optimizing for +/// Fréchet distance can create bumps. The problem is curves with long +/// control arms (distance from the control point to the corresponding +/// endpoint). We mitigate that by applying a penalty as a multiplier to +/// the measured error (approximate Fréchet distance). This is ReLU-like, +/// with a value of 1.0 below the elbow, and a given slope above it. The +/// values here have been determined empirically to give good results. +/// +/// [Simplifying Bézier paths]: +/// https://raphlinus.github.io/curves/2023/04/18/bezpath-simplify.html +const D_PENALTY_ELBOW: f64 = 0.65; +const D_PENALTY_SLOPE: f64 = 2.0; + +/// Try fitting a line. +/// +/// This is especially useful for very short chords, in which the standard +/// cubic fit is not numerically stable. The tangents are not considered, so +/// it's useful in cusp and near-cusp situations where the tangents are not +/// reliable, as well. +/// +/// Returns the line raised to a cubic and the error, if within tolerance. +fn try_fit_line( + source: &impl ParamCurveFit, + accuracy: f64, + range: Range, + start: Point, + end: Point, +) -> Option<(CubicBez, f64)> { + let acc2 = accuracy * accuracy; + let chord_l = Line::new(start, end); + const SHORT_N: usize = 7; + let mut max_err2 = 0.0; + let dt = (range.end - range.start) / (SHORT_N + 1) as f64; + for i in 0..SHORT_N { + let t = range.start + (i + 1) as f64 * dt; + let p = source.sample_pt_deriv(t).0; + let err2 = chord_l.nearest(p, accuracy).distance_sq; + if err2 > acc2 { + // Not in tolerance; likely subdivision will help. + return None; + } + max_err2 = err2.max(max_err2); + } + let p1 = start.lerp(end, 1.0 / 3.0); + let p2 = end.lerp(start, 1.0 / 3.0); + let c = CubicBez::new(start, p1, p2, end); + Some((c, max_err2)) +} + +/// Fit a single cubic to a range of the source curve. +/// +/// Returns the cubic segment and the square of the error. +/// Discussion question: should this be a method on the trait instead? +pub fn fit_to_cubic( + source: &impl ParamCurveFit, + range: Range, + accuracy: f64, +) -> Option<(CubicBez, f64)> { + let start = source.sample_pt_tangent(range.start, 1.0); + let end = source.sample_pt_tangent(range.end, -1.0); + let d = end.p - start.p; + let chord2 = d.hypot2(); + let acc2 = accuracy * accuracy; + if chord2 <= acc2 { + // Special case very short chords; try to fit a line. + return try_fit_line(source, accuracy, range, start.p, end.p); + } + let th = d.atan2(); + fn mod_2pi(th: f64) -> f64 { + let th_scaled = th * core::f64::consts::FRAC_1_PI * 0.5; + core::f64::consts::PI * 2.0 * (th_scaled - th_scaled.round()) + } + let th0 = mod_2pi(start.tangent.atan2() - th); + let th1 = mod_2pi(th - end.tangent.atan2()); + + let (mut area, mut x, mut y) = source.moment_integrals(range.clone()); + let (x0, y0) = (start.p.x, start.p.y); + let (dx, dy) = (d.x, d.y); + // Subtract off area of chord + area -= dx * (y0 + 0.5 * dy); + // `area` is signed area of closed curve segment. + // This quantity is invariant to translation and rotation. + + // Subtract off moment of chord + let dy_3 = dy * (1. / 3.); + x -= dx * (x0 * y0 + 0.5 * (x0 * dy + y0 * dx) + dy_3 * dx); + y -= dx * (y0 * y0 + y0 * dy + dy_3 * dy); + // Translate start point to origin; convert raw integrals to moments. + x -= x0 * area; + y = 0.5 * y - y0 * area; + // Rotate into place (this also scales up by chordlength for efficiency). + let moment = d.x * x + d.y * y; + // `moment` is the chordlength times the x moment of the curve translated + // so its start point is on the origin, and rotated so its end point is on the + // x axis. + + let chord2_inv = chord2.recip(); + let unit_area = area * chord2_inv; + let mx = moment * chord2_inv.powi(2); + // `unit_area` is signed area scaled to unit chord; `mx` is scaled x moment + + let chord = chord2.sqrt(); + let aff = Affine::translate(start.p.to_vec2()) * Affine::rotate(th) * Affine::scale(chord); + let mut curve_dist = CurveDist::from_curve(source, range); + let mut best_c = None; + let mut best_err2 = None; + for (cand, d0, d1) in cubic_fit(th0, th1, unit_area, mx) { + let c = aff * cand; + if let Some(err2) = curve_dist.eval_dist(source, c, acc2) { + fn scale_f(d: f64) -> f64 { + 1.0 + (d - D_PENALTY_ELBOW).max(0.0) * D_PENALTY_SLOPE + } + let scale = scale_f(d0).max(scale_f(d1)).powi(2); + let err2 = err2 * scale; + if err2 < acc2 && best_err2.map(|best| err2 < best).unwrap_or(true) { + best_c = Some(c); + best_err2 = Some(err2); + } + } + } + match (best_c, best_err2) { + (Some(c), Some(err2)) => Some((c, err2)), + _ => None, + } +} + +/// Returns curves matching area and moment, given unit chord. +fn cubic_fit(th0: f64, th1: f64, area: f64, mx: f64) -> ArrayVec<(CubicBez, f64, f64), 4> { + // Note: maybe we want to take unit vectors instead of angle? Shouldn't + // matter much either way though. + let (s0, c0) = th0.sin_cos(); + let (s1, c1) = th1.sin_cos(); + let a4 = -9. + * c0 + * (((2. * s1 * c1 * c0 + s0 * (2. * c1 * c1 - 1.)) * c0 - 2. * s1 * c1) * c0 + - c1 * c1 * s0); + let a3 = 12. + * ((((c1 * (30. * area * c1 - s1) - 15. * area) * c0 + 2. * s0 + - c1 * s0 * (c1 + 30. * area * s1)) + * c0 + + c1 * (s1 - 15. * area * c1)) + * c0 + - s0 * c1 * c1); + let a2 = 12. + * ((((70. * mx + 15. * area) * s1 * s1 + c1 * (9. * s1 - 70. * c1 * mx - 5. * c1 * area)) + * c0 + - 5. * s0 * s1 * (3. * s1 - 4. * c1 * (7. * mx + area))) + * c0 + - c1 * (9. * s1 - 70. * c1 * mx - 5. * c1 * area)); + let a1 = 16. + * (((12. * s0 - 5. * c0 * (42. * mx - 17. * area)) * s1 + - 70. * c1 * (3. * mx - area) * s0 + - 75. * c0 * c1 * area * area) + * s1 + - 75. * c1 * c1 * area * area * s0); + let a0 = 80. * s1 * (42. * s1 * mx - 25. * area * (s1 - c1 * area)); + // TODO: "roots" is not a good name for this variable, as it also contains + // the real part of complex conjugate pairs. + let mut roots = ArrayVec::::new(); + const EPS: f64 = 1e-12; + if a4.abs() > EPS { + let a = a3 / a4; + let b = a2 / a4; + let c = a1 / a4; + let d = a0 / a4; + if let Some(quads) = factor_quartic_inner(a, b, c, d, false) { + for (qc1, qc0) in quads { + let qroots = solve_quadratic(qc0, qc1, 1.0); + if qroots.is_empty() { + // Real part of pair of complex roots + roots.push(-0.5 * qc1); + } else { + roots.extend(qroots); + } + } + } + } else if a3.abs() > EPS { + roots.extend(solve_cubic(a0, a1, a2, a3)); + } else if a2.abs() > EPS || a1.abs() > EPS || a0.abs() > EPS { + roots.extend(solve_quadratic(a0, a1, a2)); + } else { + return [( + CubicBez::new((0.0, 0.0), (1. / 3., 0.0), (2. / 3., 0.0), (1., 0.0)), + 1f64 / 3., + 1f64 / 3., + )] + .into_iter() + .collect(); + } + + let s01 = s0 * c1 + s1 * c0; + roots + .iter() + .filter_map(|&d0| { + let (d0, d1) = if d0 > 0.0 { + let d1 = (d0 * s0 - area * (10. / 3.)) / (0.5 * d0 * s01 - s1); + if d1 > 0.0 { (d0, d1) } else { (s1 / s01, 0.0) } + } else { + (0.0, s0 / s01) + }; + // We could implement a maximum d value here. + if d0 >= 0.0 && d1 >= 0.0 { + Some(( + CubicBez::new( + (0.0, 0.0), + (d0 * c0, d0 * s0), + (1.0 - d1 * c1, d1 * s1), + (1.0, 0.0), + ), + d0, + d1, + )) + } else { + None + } + }) + .collect() +} + +/// Generate a highly optimized Bézier path that fits the source curve. +/// +/// This function is still experimental and the signature might change; it's possible +/// it might become a method on the [`ParamCurveFit`] trait. +/// +/// This function is considerably slower than [`fit_to_bezpath`], as it computes +/// optimal subdivision points. Its result is expected to be very close to the optimum +/// possible Bézier path for the source curve, in that it has a minimal number of curve +/// segments, and a minimal error over all paths with that number of segments. +/// +/// See [`fit_to_bezpath`] for an explanation of the `accuracy` parameter. +pub fn fit_to_bezpath_opt(source: &impl ParamCurveFit, accuracy: f64) -> BezPath { + let mut cusps = Vec::new(); + let mut path = BezPath::new(); + let mut t0 = 0.0; + loop { + let t1 = cusps.last().copied().unwrap_or(1.0); + match fit_to_bezpath_opt_inner(source, accuracy, t0..t1, &mut path) { + Some(t) => cusps.push(t), + None => match cusps.pop() { + Some(t) => t0 = t, + None => break, + }, + } + } + path +} + +/// Fit a range without cusps. +/// +/// On Ok return, range has been added to the path. On Err return, report a cusp (and don't +/// mutate path). +fn fit_to_bezpath_opt_inner( + source: &impl ParamCurveFit, + accuracy: f64, + range: Range, + path: &mut BezPath, +) -> Option { + if let Some(t) = source.break_cusp(range.clone()) { + return Some(t); + } + let err; + if let Some((c, err2)) = fit_to_cubic(source, range.clone(), accuracy) { + err = err2.sqrt(); + if err < accuracy { + if range.start == 0.0 { + path.move_to(c.p0); + } + path.curve_to(c.p1, c.p2, c.p3); + return None; + } + } else { + err = 2.0 * accuracy; + } + let (mut t0, t1) = (range.start, range.end); + let mut n = 0; + let last_err; + loop { + n += 1; + match fit_opt_segment(source, accuracy, t0..t1) { + FitResult::ParamVal(t) => t0 = t, + FitResult::SegmentError(err) => { + last_err = err; + break; + } + FitResult::CuspFound(t) => return Some(t), + } + } + t0 = range.start; + const EPS: f64 = 1e-9; + let f = |x| fit_opt_err_delta(source, x, accuracy, t0..t1, n); + let k1 = 0.2 / accuracy; + let ya = -err; + let yb = accuracy - last_err; + let (_, x) = match solve_itp_fallible(f, 0.0, accuracy, EPS, 1, k1, ya, yb) { + Ok(x) => x, + Err(t) => return Some(t), + }; + //println!("got fit with n={}, err={}", n, x); + let path_len = path.elements().len(); + for i in 0..n { + let t1 = if i < n - 1 { + match fit_opt_segment(source, x, t0..range.end) { + FitResult::ParamVal(t1) => t1, + FitResult::SegmentError(_) => range.end, + FitResult::CuspFound(t) => { + path.truncate(path_len); + return Some(t); + } + } + } else { + range.end + }; + let (c, _) = fit_to_cubic(source, t0..t1, accuracy).unwrap(); + if i == 0 && range.start == 0.0 { + path.move_to(c.p0); + } + path.curve_to(c.p1, c.p2, c.p3); + t0 = t1; + if t0 == range.end { + // This is unlikely but could happen when not monotonic. + break; + } + } + None +} + +fn measure_one_seg(source: &impl ParamCurveFit, range: Range, limit: f64) -> Option { + fit_to_cubic(source, range, limit).map(|(_, err2)| err2.sqrt()) +} + +enum FitResult { + /// The parameter (`t`) value that meets the desired accuracy. + ParamVal(f64), + /// Error of the measured segment. + SegmentError(f64), + /// The parameter value where a cusp was found. + CuspFound(f64), +} + +fn fit_opt_segment(source: &impl ParamCurveFit, accuracy: f64, range: Range) -> FitResult { + if let Some(t) = source.break_cusp(range.clone()) { + return FitResult::CuspFound(t); + } + let missing_err = accuracy * 2.0; + let err = measure_one_seg(source, range.clone(), accuracy).unwrap_or(missing_err); + if err <= accuracy { + return FitResult::SegmentError(err); + } + let (t0, t1) = (range.start, range.end); + let f = |x| { + if let Some(t) = source.break_cusp(range.clone()) { + return Err(t); + } + let err = measure_one_seg(source, t0..x, accuracy).unwrap_or(missing_err); + Ok(err - accuracy) + }; + const EPS: f64 = 1e-9; + let k1 = 2.0 / (t1 - t0); + match solve_itp_fallible(f, t0, t1, EPS, 1, k1, -accuracy, err - accuracy) { + Ok((t1, _)) => FitResult::ParamVal(t1), + Err(t) => FitResult::CuspFound(t), + } +} + +// Ok result is delta error (accuracy - error of last seg). +// Err result is a cusp. +fn fit_opt_err_delta( + source: &impl ParamCurveFit, + accuracy: f64, + limit: f64, + range: Range, + n: usize, +) -> Result { + let (mut t0, t1) = (range.start, range.end); + for _ in 0..n - 1 { + t0 = match fit_opt_segment(source, accuracy, t0..t1) { + FitResult::ParamVal(t0) => t0, + // In this case, n - 1 will work, which of course means the error is highly + // non-monotonic. We should probably harvest that solution. + FitResult::SegmentError(_) => return Ok(accuracy), + FitResult::CuspFound(t) => return Err(t), + } + } + let err = measure_one_seg(source, t0..t1, limit).unwrap_or(accuracy * 2.0); + Ok(accuracy - err) +} diff --git a/vendor/kurbo/src/insets.rs b/vendor/kurbo/src/insets.rs new file mode 100644 index 0000000000..a2d61e0183 --- /dev/null +++ b/vendor/kurbo/src/insets.rs @@ -0,0 +1,404 @@ +// Copyright 2019 the Kurbo Authors +// SPDX-License-Identifier: Apache-2.0 OR MIT + +//! A description of the distances between the edges of two rectangles. + +use core::ops::{Add, Div, Mul, Neg, Sub}; + +use crate::{Rect, Size}; + +/// Insets from the edges of a rectangle. +/// +/// +/// The inset value for each edge can be thought of as a delta computed from +/// the center of the rect to that edge. For instance, with an inset of `2.0` on +/// the x-axis, a rectangle with the origin `(0.0, 0.0)` with that inset added +/// will have the new origin at `(-2.0, 0.0)`. +/// +/// Put alternatively, a positive inset represents increased distance from center, +/// and a negative inset represents decreased distance from center. +/// +/// # Examples +/// +/// Positive insets added to a [`Rect`] produce a larger [`Rect`]: +/// ``` +/// # use kurbo::{Insets, Rect}; +/// let rect = Rect::from_origin_size((0., 0.,), (10., 10.,)); +/// let insets = Insets::uniform_xy(3., 0.,); +/// +/// let inset_rect = rect + insets; +/// assert_eq!(inset_rect.width(), 16.0, "10.0 + 3.0 × 2"); +/// assert_eq!(inset_rect.x0, -3.0); +/// ``` +/// +/// Negative insets added to a [`Rect`] produce a smaller [`Rect`]: +/// +/// ``` +/// # use kurbo::{Insets, Rect}; +/// let rect = Rect::from_origin_size((0., 0.,), (10., 10.,)); +/// let insets = Insets::uniform_xy(-3., 0.,); +/// +/// let inset_rect = rect + insets; +/// assert_eq!(inset_rect.width(), 4.0, "10.0 - 3.0 × 2"); +/// assert_eq!(inset_rect.x0, 3.0); +/// ``` +/// +/// [`Insets`] operate on the absolute rectangle [`Rect::abs`], and so ignore +/// existing negative widths and heights. +/// +/// ``` +/// # use kurbo::{Insets, Rect}; +/// let rect = Rect::new(7., 11., 0., 0.,); +/// let insets = Insets::uniform_xy(0., 1.,); +/// +/// assert_eq!(rect.width(), -7.0); +/// +/// let inset_rect = rect + insets; +/// assert_eq!(inset_rect.width(), 7.0); +/// assert_eq!(inset_rect.x0, 0.0); +/// assert_eq!(inset_rect.height(), 13.0); +/// ``` +/// +/// The width and height of an inset operation can still be negative if the +/// [`Insets`]' dimensions are greater than the dimensions of the original [`Rect`]. +/// +/// ``` +/// # use kurbo::{Insets, Rect}; +/// let rect = Rect::new(0., 0., 3., 5.); +/// let insets = Insets::uniform_xy(0., 7.,); +/// +/// let inset_rect = rect - insets; +/// assert_eq!(inset_rect.height(), -9., "5 - 7 × 2") +/// ``` +/// +/// `Rect - Rect = Insets`: +/// +/// +/// ``` +/// # use kurbo::{Insets, Rect}; +/// let rect = Rect::new(0., 0., 5., 11.); +/// let insets = Insets::uniform_xy(1., 7.,); +/// +/// let inset_rect = rect + insets; +/// let insets2 = inset_rect - rect; +/// +/// assert_eq!(insets2.x0, insets.x0); +/// assert_eq!(insets2.y1, insets.y1); +/// assert_eq!(insets2.x_value(), insets.x_value()); +/// assert_eq!(insets2.y_value(), insets.y_value()); +/// ``` +#[derive(Clone, Copy, Default, Debug, PartialEq)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +pub struct Insets { + /// The minimum x coordinate (left edge). + pub x0: f64, + /// The minimum y coordinate (top edge in y-down spaces). + pub y0: f64, + /// The maximum x coordinate (right edge). + pub x1: f64, + /// The maximum y coordinate (bottom edge in y-down spaces). + pub y1: f64, +} + +impl Insets { + /// Zeroed insets. + pub const ZERO: Insets = Insets::uniform(0.); + + /// New uniform insets. + #[inline(always)] + pub const fn uniform(d: f64) -> Insets { + Insets { + x0: d, + y0: d, + x1: d, + y1: d, + } + } + + /// New insets with uniform values along each axis. + #[inline(always)] + pub const fn uniform_xy(x: f64, y: f64) -> Insets { + Insets { + x0: x, + y0: y, + x1: x, + y1: y, + } + } + + /// New insets. The ordering of the arguments is "left, top, right, bottom", + /// assuming a y-down coordinate space. + #[inline(always)] + pub const fn new(x0: f64, y0: f64, x1: f64, y1: f64) -> Insets { + Insets { x0, y0, x1, y1 } + } + + /// The total delta on the x-axis represented by these insets. + /// + /// # Examples + /// + /// ``` + /// use kurbo::Insets; + /// + /// let insets = Insets::uniform_xy(3., 8.); + /// assert_eq!(insets.x_value(), 6.); + /// + /// let insets = Insets::new(5., 0., -12., 0.,); + /// assert_eq!(insets.x_value(), -7.); + /// ``` + #[inline] + pub const fn x_value(self) -> f64 { + self.x0 + self.x1 + } + + /// The total delta on the y-axis represented by these insets. + /// + /// # Examples + /// + /// ``` + /// use kurbo::Insets; + /// + /// let insets = Insets::uniform_xy(3., 7.); + /// assert_eq!(insets.y_value(), 14.); + /// + /// let insets = Insets::new(5., 10., -12., 4.,); + /// assert_eq!(insets.y_value(), 14.); + /// ``` + #[inline] + pub const fn y_value(self) -> f64 { + self.y0 + self.y1 + } + + /// Returns the total delta represented by these insets as a [`Size`]. + /// + /// This is equivalent to creating a [`Size`] from the values returned by + /// [`x_value`] and [`y_value`]. + /// + /// This function may return a size with negative values. + /// + /// # Examples + /// + /// ``` + /// use kurbo::{Insets, Size}; + /// + /// let insets = Insets::new(11.1, -43.3, 3.333, -0.0); + /// assert_eq!(insets.size(), Size::new(insets.x_value(), insets.y_value())); + /// ``` + /// + /// [`x_value`]: Insets::x_value + /// [`y_value`]: Insets::y_value + pub const fn size(self) -> Size { + Size::new(self.x_value(), self.y_value()) + } + + /// Return `true` iff all values are nonnegative. + pub const fn are_nonnegative(self) -> bool { + let Insets { x0, y0, x1, y1 } = self; + x0 >= 0.0 && y0 >= 0.0 && x1 >= 0.0 && y1 >= 0.0 + } + + /// Return new `Insets` with all negative values replaced with `0.0`. + /// + /// This is provided as a convenience for applications where negative insets + /// are not meaningful. + /// + /// # Examples + /// + /// ``` + /// use kurbo::Insets; + /// + /// let insets = Insets::new(-10., 3., -0.2, 4.); + /// let nonnegative = insets.nonnegative(); + /// assert_eq!(nonnegative.x_value(), 0.0); + /// assert_eq!(nonnegative.y_value(), 7.0); + /// ``` + pub const fn nonnegative(self) -> Insets { + let Insets { x0, y0, x1, y1 } = self; + Insets { + x0: x0.max(0.0), + y0: y0.max(0.0), + x1: x1.max(0.0), + y1: y1.max(0.0), + } + } + + /// Are these insets finite? + #[inline] + pub const fn is_finite(&self) -> bool { + self.x0.is_finite() && self.y0.is_finite() && self.x1.is_finite() && self.y1.is_finite() + } + + /// Are these insets NaN? + #[inline] + pub const fn is_nan(&self) -> bool { + self.x0.is_nan() || self.y0.is_nan() || self.x1.is_nan() || self.y1.is_nan() + } + + /// Returns the component-wise minimum of `self` and `other`. + /// + /// # Examples + /// + /// ``` + /// use kurbo::Insets; + /// + /// let this = Insets::new(1., 2., 3., 4.); + /// let other = Insets::new(4., 3., 2., 1.); + /// + /// assert_eq!(this.min(other), Insets::new(1., 2., 2., 1.)); + /// ``` + pub const fn min(self, other: Insets) -> Self { + Self { + x0: self.x0.min(other.x0), + x1: self.x1.min(other.x1), + y0: self.y0.min(other.y0), + y1: self.y1.min(other.y1), + } + } + + /// Returns the component-wise maximum of `self` and `other`. + /// + /// # Examples + /// + /// ``` + /// use kurbo::Insets; + /// + /// let this = Insets::new(1., 2., 3., 4.); + /// let other = Insets::new(4., 3., 2., 1.); + /// + /// assert_eq!(this.max(other), Insets::new(4., 3., 3., 4.)); + /// ``` + pub const fn max(self, other: Insets) -> Self { + Self { + x0: self.x0.max(other.x0), + x1: self.x1.max(other.x1), + y0: self.y0.max(other.y0), + y1: self.y1.max(other.y1), + } + } +} + +impl Neg for Insets { + type Output = Insets; + + #[inline] + fn neg(self) -> Insets { + Insets::new(-self.x0, -self.y0, -self.x1, -self.y1) + } +} + +impl Add for Insets { + type Output = Insets; + + fn add(self, other: Insets) -> Self::Output { + Insets { + x0: self.x0 + other.x0, + x1: self.x1 + other.x1, + y0: self.y0 + other.y0, + y1: self.y1 + other.y1, + } + } +} + +impl Sub for Insets { + type Output = Insets; + + fn sub(self, other: Insets) -> Self::Output { + Insets { + x0: self.x0 - other.x0, + x1: self.x1 - other.x1, + y0: self.y0 - other.y0, + y1: self.y1 - other.y1, + } + } +} + +impl Add for Insets { + type Output = Rect; + + #[inline] + #[allow(clippy::suspicious_arithmetic_impl)] + fn add(self, other: Rect) -> Rect { + let other = other.abs(); + Rect::new( + other.x0 - self.x0, + other.y0 - self.y0, + other.x1 + self.x1, + other.y1 + self.y1, + ) + } +} + +impl Add for Rect { + type Output = Rect; + + #[inline] + fn add(self, other: Insets) -> Rect { + other + self + } +} + +impl Sub for Insets { + type Output = Rect; + + #[inline] + fn sub(self, other: Rect) -> Rect { + other + -self + } +} + +impl Mul for Insets { + type Output = Insets; + + fn mul(self, rhs: f64) -> Self::Output { + Self { + x0: self.x0 * rhs, + y0: self.y0 * rhs, + x1: self.x1 * rhs, + y1: self.y1 * rhs, + } + } +} + +impl Div for Insets { + type Output = Insets; + + fn div(self, rhs: f64) -> Self::Output { + Self { + x0: self.x0 / rhs, + y0: self.y0 / rhs, + x1: self.x1 / rhs, + y1: self.y1 / rhs, + } + } +} + +impl Sub for Rect { + type Output = Rect; + + #[inline] + fn sub(self, other: Insets) -> Rect { + other - self + } +} + +impl From for Insets { + #[inline(always)] + fn from(src: f64) -> Insets { + Insets::uniform(src) + } +} + +impl From<(f64, f64)> for Insets { + #[inline(always)] + fn from(src: (f64, f64)) -> Insets { + Insets::uniform_xy(src.0, src.1) + } +} + +impl From<(f64, f64, f64, f64)> for Insets { + #[inline(always)] + fn from(src: (f64, f64, f64, f64)) -> Insets { + Insets::new(src.0, src.1, src.2, src.3) + } +} diff --git a/vendor/kurbo/src/interop_euclid.rs b/vendor/kurbo/src/interop_euclid.rs new file mode 100644 index 0000000000..322bd43286 --- /dev/null +++ b/vendor/kurbo/src/interop_euclid.rs @@ -0,0 +1,91 @@ +// Copyright 2025 the Kurbo Authors +// SPDX-License-Identifier: Apache-2.0 OR MIT + +use euclid::UnknownUnit; + +impl From> for crate::Vec2 { + #[inline(always)] + fn from(value: euclid::Vector2D) -> Self { + Self::new(value.x, value.y) + } +} + +impl From for euclid::Vector2D { + #[inline(always)] + fn from(value: crate::Vec2) -> Self { + Self::new(value.x, value.y) + } +} + +impl From> for crate::Point { + #[inline(always)] + fn from(value: euclid::Point2D) -> Self { + Self::new(value.x, value.y) + } +} + +impl From for euclid::Point2D { + #[inline(always)] + fn from(value: crate::Point) -> Self { + Self::new(value.x, value.y) + } +} + +impl From> for crate::Size { + #[inline(always)] + fn from(value: euclid::Size2D) -> Self { + Self::new(value.width, value.height) + } +} + +impl From for euclid::Size2D { + #[inline(always)] + fn from(value: crate::Size) -> Self { + Self::new(value.width, value.height) + } +} + +impl From> for crate::Rect { + #[inline] + fn from(value: euclid::Rect) -> Self { + Self::from_origin_size(value.origin, value.size) + } +} + +impl From for euclid::Rect { + #[inline] + fn from(value: crate::Rect) -> Self { + Self::new(value.origin().into(), value.size().into()) + } +} + +impl From> for crate::Rect { + #[inline] + fn from(value: euclid::Box2D) -> Self { + Self::from_points(value.min, value.max) + } +} + +impl From for euclid::Box2D { + #[inline] + fn from(value: crate::Rect) -> Self { + Self::new( + euclid::Point2D::new(value.min_x(), value.min_y()), + euclid::Point2D::new(value.max_x(), value.max_y()), + ) + } +} + +impl From> for crate::Affine { + #[inline(always)] + fn from(t: euclid::Transform2D) -> Self { + Self::new(t.to_array()) + } +} + +impl From for euclid::Transform2D { + #[inline(always)] + fn from(a: crate::Affine) -> Self { + Self::from_array(a.as_coeffs()) + } +} diff --git a/vendor/kurbo/src/lib.rs b/vendor/kurbo/src/lib.rs new file mode 100644 index 0000000000..ae92bd3999 --- /dev/null +++ b/vendor/kurbo/src/lib.rs @@ -0,0 +1,189 @@ +// Copyright 2018 the Kurbo Authors +// SPDX-License-Identifier: Apache-2.0 OR MIT + +//! 2D geometry, with a focus on curves. +//! +//! The kurbo library contains data structures and algorithms for curves and +//! vector paths. It was designed to serve the needs of 2D graphics applications, +//! but it is intended to be general enough to be useful for other applications. +//! It can be used as "vocabulary types" for representing curves and paths, and +//! also contains a number of computational geometry methods. +//! +//! # Examples +//! +//! Basic UI-style geometry: +//! ``` +//! use kurbo::{Insets, Point, Rect, Size, Vec2}; +//! +//! let pt = Point::new(10.0, 10.0); +//! let vector = Vec2::new(5.0, -5.0); +//! let pt2 = pt + vector; +//! assert_eq!(pt2, Point::new(15.0, 5.0)); +//! +//! let rect = Rect::from_points(pt, pt2); +//! assert_eq!(rect, Rect::from_origin_size((10.0, 5.0), (5.0, 5.0))); +//! +//! let insets = Insets::uniform(1.0); +//! let inset_rect = rect - insets; +//! assert_eq!(inset_rect.size(), Size::new(3.0, 3.0)); +//! ``` +//! +//! Finding the closest position on a [`Shape`]'s perimeter to a [`Point`]: +//! +//! ``` +//! use kurbo::{Circle, ParamCurve, ParamCurveNearest, Point, Shape}; +//! +//! const DESIRED_ACCURACY: f64 = 0.1; +//! +//! /// Given a shape and a point, returns the closest position on the shape's +//! /// perimeter, or `None` if the shape is malformed. +//! fn closest_perimeter_point(shape: impl Shape, pt: Point) -> Option { +//! let mut best: Option<(Point, f64)> = None; +//! for segment in shape.path_segments(DESIRED_ACCURACY) { +//! let nearest = segment.nearest(pt, DESIRED_ACCURACY); +//! if best.map(|(_, best_d)| nearest.distance_sq < best_d).unwrap_or(true) { +//! best = Some((segment.eval(nearest.t), nearest.distance_sq)) +//! } +//! } +//! best.map(|(point, _)| point) +//! } +//! +//! let circle = Circle::new((5.0, 5.0), 5.0); +//! let hit_point = Point::new(5.0, -2.0); +//! let expectation = Point::new(5.0, 0.0); +//! let hit = closest_perimeter_point(circle, hit_point).unwrap(); +//! assert!(hit.distance(expectation) <= DESIRED_ACCURACY); +//! ``` +//! +//! # Feature Flags +//! +//! The following crate [feature flags](https://doc.rust-lang.org/cargo/reference/features.html#dependency-features) are available: +//! +//! - `std` (enabled by default): Get floating point functions from the standard library +//! (likely using your target's libc). +//! - `libm`: Use floating point implementations from [libm][]. +//! This is useful for `no_std` environments. +//! However, note that the `libm` crate is not as efficient as the standard library. +//! - `mint`: Enable `From`/`Into` conversion of Kurbo and [mint][] types, enabling interoperability +//! with other graphics libraries. +//! - `euclid`: Enable `From`/`Into` conversion of Kurbo and [euclid][] types. +//! Note that if you're using both Kurbo and euclid at the same time, you *must* +//! also enable one of euclid's `std` or `libm` features. +//! - `serde`: Implement `serde::Deserialize` and `serde::Serialize` on various types. +//! - `schemars`: Add best-effort support for using Kurbo types in JSON schemas using [schemars][]. +//! +//! At least one of `std` and `libm` is required; `std` overrides `libm`. +//! Note that Kurbo does require that an allocator is available (i.e. it uses [alloc]). + +// LINEBENDER LINT SET - lib.rs - v4 +// See https://linebender.org/wiki/canonical-lints/ +// These lints shouldn't apply to examples or tests. +#![cfg_attr(not(test), warn(unused_crate_dependencies))] +// These lints shouldn't apply to examples. +#![warn(clippy::print_stdout, clippy::print_stderr)] +// Targeting e.g. 32-bit means structs containing usize can give false positives for 64-bit. +#![cfg_attr(target_pointer_width = "64", warn(clippy::trivially_copy_pass_by_ref))] +// END LINEBENDER LINT SET +#![cfg_attr(docsrs, feature(doc_cfg))] +#![cfg_attr(all(not(feature = "std"), not(test)), no_std)] +#![allow( + clippy::unreadable_literal, + clippy::many_single_char_names, + clippy::excessive_precision, + clippy::bool_to_int_with_if +)] +// The following lints are part of the Linebender standard set, +// but resolving them has been deferred for now. +// Feel free to send a PR that solves one or more of these. +#![allow( + missing_debug_implementations, + elided_lifetimes_in_paths, + trivial_numeric_casts, + unnameable_types, + clippy::use_self, + clippy::cast_possible_truncation, + clippy::missing_assert_message, + clippy::unseparated_literal_suffix, + clippy::duplicated_attributes, + clippy::allow_attributes_without_reason +)] + +#[cfg(not(any(feature = "std", feature = "libm")))] +compile_error!("kurbo requires either the `std` or `libm` feature"); + +// Suppress the unused_crate_dependencies lint when both std and libm are specified. +#[cfg(all(feature = "std", feature = "libm"))] +use libm as _; + +extern crate alloc; + +mod affine; +mod arc; +mod axis; +mod bezpath; +mod circle; +pub mod common; +mod cubicbez; +mod ellipse; +mod expand; +mod fit; +mod insets; +mod line; +mod mindist; +mod moments; +pub mod offset; +mod param_curve; +mod point; +mod quadbez; +mod quadspline; +mod rect; +mod rounded_rect; +mod rounded_rect_radii; +mod shape; +pub mod simplify; +mod size; +mod stroke; +mod svg; +mod translate_scale; +mod triangle; +mod vec2; + +#[cfg(feature = "euclid")] +mod interop_euclid; + +pub use crate::affine::Affine; +pub use crate::arc::{Arc, ArcAppendIter}; +pub use crate::axis::Axis; +pub use crate::bezpath::{ + BezPath, LineIntersection, MinDistance, PathEl, PathSeg, PathSegIter, Segments, flatten, + segments, +}; +pub use crate::circle::{Circle, CirclePathIter, CircleSegment}; +pub use crate::cubicbez::{CubicBez, CubicBezIter, CuspType, cubics_to_quadratic_splines}; +pub use crate::ellipse::Ellipse; +pub use crate::expand::{Diagonal2, expand_path, expand_path_signed}; +pub use crate::fit::{ + CurveFitSample, ParamCurveFit, fit_to_bezpath, fit_to_bezpath_opt, fit_to_cubic, +}; +pub use crate::insets::Insets; +pub use crate::line::{ConstPoint, Line, LinePathIter}; +pub use crate::moments::{Moments, ParamCurveMoments}; +pub use crate::param_curve::{ + DEFAULT_ACCURACY, MAX_EXTREMA, Nearest, ParamCurve, ParamCurveArclen, ParamCurveArea, + ParamCurveCurvature, ParamCurveDeriv, ParamCurveExtrema, ParamCurveNearest, +}; +pub use crate::point::Point; +pub use crate::quadbez::{QuadBez, QuadBezIter}; +pub use crate::quadspline::QuadSpline; +pub use crate::rect::{Rect, RectPathIter}; +pub use crate::rounded_rect::{RoundedRect, RoundedRectPathIter}; +pub use crate::rounded_rect_radii::RoundedRectRadii; +pub use crate::shape::Shape; +pub use crate::size::Size; +pub use crate::stroke::{ + Cap, Dashes, Join, Stroke, StrokeCtx, StrokeOptLevel, StrokeOpts, dash, stroke, stroke_with, +}; +pub use crate::svg::{SvgArc, SvgParseError}; +pub use crate::translate_scale::TranslateScale; +pub use crate::triangle::{Triangle, TrianglePathIter}; +pub use crate::vec2::Vec2; diff --git a/vendor/kurbo/src/line.rs b/vendor/kurbo/src/line.rs new file mode 100644 index 0000000000..8f8ee2a9b7 --- /dev/null +++ b/vendor/kurbo/src/line.rs @@ -0,0 +1,448 @@ +// Copyright 2018 the Kurbo Authors +// SPDX-License-Identifier: Apache-2.0 OR MIT + +//! Lines. + +use core::ops::{Add, Mul, Range, Sub}; + +use arrayvec::ArrayVec; + +use crate::{ + Affine, DEFAULT_ACCURACY, MAX_EXTREMA, Nearest, ParamCurve, ParamCurveArclen, ParamCurveArea, + ParamCurveCurvature, ParamCurveDeriv, ParamCurveExtrema, ParamCurveNearest, PathEl, Point, + Rect, Shape, Vec2, +}; + +/// A single line. +#[derive(Clone, Copy, Debug, PartialEq)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +pub struct Line { + /// The line's start point. + pub p0: Point, + /// The line's end point. + pub p1: Point, +} + +impl Line { + /// Create a new line. + #[inline(always)] + pub fn new(p0: impl Into, p1: impl Into) -> Line { + Line { + p0: p0.into(), + p1: p1.into(), + } + } + + /// Returns a copy of this `Line` with the end points swapped so that it + /// points in the opposite direction. + #[must_use] + #[inline(always)] + pub const fn reversed(&self) -> Line { + Self { + p0: self.p1, + p1: self.p0, + } + } + + /// The length of the line. + #[inline] + pub fn length(self) -> f64 { + self.arclen(DEFAULT_ACCURACY) + } + + /// The midpoint of the line. + /// + /// This is the same as calling [`Point::midpoint`] with + /// the endpoints of this line. + #[must_use] + #[inline] + pub fn midpoint(&self) -> Point { + self.p0.midpoint(self.p1) + } + + /// Computes the point where two lines, if extended to infinity, would cross. + pub fn crossing_point(self, other: Line) -> Option { + let ab = self.p1 - self.p0; + let cd = other.p1 - other.p0; + let pcd = ab.cross(cd); + if pcd == 0.0 { + return None; + } + let h = ab.cross(self.p0 - other.p0) / pcd; + Some(other.p0 + cd * h) + } + + /// Is this line `finite`? + /// + /// [finite]: f64::is_finite + #[inline] + pub const fn is_finite(self) -> bool { + self.p0.is_finite() && self.p1.is_finite() + } + + /// Is this line `NaN`? + /// + /// [NaN]: f64::is_nan + #[inline] + pub const fn is_nan(self) -> bool { + self.p0.is_nan() || self.p1.is_nan() + } +} + +impl From<(Point, Point)> for Line { + #[inline(always)] + fn from((from, to): (Point, Point)) -> Self { + Line::new(from, to) + } +} + +impl From<(Point, Vec2)> for Line { + #[inline(always)] + fn from((origin, displacement): (Point, Vec2)) -> Self { + Line::new(origin, origin + displacement) + } +} + +impl ParamCurve for Line { + #[inline] + fn eval(&self, t: f64) -> Point { + self.p0.lerp(self.p1, t) + } + + #[inline] + fn subsegment(&self, range: Range) -> Line { + Line { + p0: self.eval(range.start), + p1: self.eval(range.end), + } + } + + #[inline(always)] + fn start(&self) -> Point { + self.p0 + } + + #[inline(always)] + fn end(&self) -> Point { + self.p1 + } +} + +impl ParamCurveDeriv for Line { + type DerivResult = ConstPoint; + + #[inline] + fn deriv(&self) -> ConstPoint { + ConstPoint((self.p1 - self.p0).to_point()) + } +} + +impl ParamCurveArclen for Line { + #[inline] + fn arclen(&self, _accuracy: f64) -> f64 { + (self.p1 - self.p0).hypot() + } + + #[inline] + fn inv_arclen(&self, arclen: f64, _accuracy: f64) -> f64 { + arclen / (self.p1 - self.p0).hypot() + } +} + +impl ParamCurveArea for Line { + #[inline] + fn signed_area(&self) -> f64 { + self.p0.to_vec2().cross(self.p1.to_vec2()) * 0.5 + } +} + +impl ParamCurveNearest for Line { + #[inline] + fn nearest(&self, p: Point, _accuracy: f64) -> Nearest { + let d = self.p1 - self.p0; + let v = p - self.p0; + + // Calculate projection parameter `t` of the point onto the line segment s(t), with + // s(t) = (1-t) * p0 + t * p1. + // + // Note when the segment has 0 length, this will be positive or negative infinity or NaN; + // see the clamping below. + let t = d.dot(v) / d.hypot2(); + + // Clamp the parameter to be on the line segment. This clamps negative infinity and NaN to + // `0.`, and positive infinity to `1.`. + #[expect( + clippy::manual_clamp, + reason = "`clamp` uses slightly more instructions than chained `max` and `min` on x86 and aarch64" + )] + let t = { t.max(0.).min(1.) }; + + // Calculate ||p - s(t)||^2. + let distance_sq = (v - t * d).hypot2(); + + Nearest { distance_sq, t } + } +} + +impl ParamCurveCurvature for Line { + #[inline(always)] + fn curvature(&self, _t: f64) -> f64 { + 0.0 + } +} + +impl ParamCurveExtrema for Line { + #[inline] + fn extrema(&self) -> ArrayVec { + ArrayVec::new() + } +} + +/// A trivial "curve" that is just a constant. +#[derive(Clone, Copy, Debug)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +pub struct ConstPoint(Point); + +impl ConstPoint { + /// Is this point [finite]? + /// + /// [finite]: f64::is_finite + #[inline] + pub const fn is_finite(self) -> bool { + self.0.is_finite() + } + + /// Is this point [NaN]? + /// + /// [NaN]: f64::is_nan + #[inline] + pub const fn is_nan(self) -> bool { + self.0.is_nan() + } +} + +impl ParamCurve for ConstPoint { + #[inline(always)] + fn eval(&self, _t: f64) -> Point { + self.0 + } + + #[inline(always)] + fn subsegment(&self, _range: Range) -> ConstPoint { + *self + } +} + +impl ParamCurveDeriv for ConstPoint { + type DerivResult = ConstPoint; + + #[inline(always)] + fn deriv(&self) -> ConstPoint { + ConstPoint(Point::new(0.0, 0.0)) + } +} + +impl ParamCurveArclen for ConstPoint { + #[inline(always)] + fn arclen(&self, _accuracy: f64) -> f64 { + 0.0 + } + + #[inline(always)] + fn inv_arclen(&self, _arclen: f64, _accuracy: f64) -> f64 { + 0.0 + } +} + +impl Mul for Affine { + type Output = Line; + + #[inline] + fn mul(self, other: Line) -> Line { + Line { + p0: self * other.p0, + p1: self * other.p1, + } + } +} + +impl Add for Line { + type Output = Line; + + #[inline] + fn add(self, v: Vec2) -> Line { + Line::new(self.p0 + v, self.p1 + v) + } +} + +impl Sub for Line { + type Output = Line; + + #[inline] + fn sub(self, v: Vec2) -> Line { + Line::new(self.p0 - v, self.p1 - v) + } +} + +/// An iterator yielding the path for a single line. +#[doc(hidden)] +pub struct LinePathIter { + line: Line, + ix: usize, +} + +impl Shape for Line { + type PathElementsIter<'iter> = LinePathIter; + + #[inline] + fn path_elements(&self, _tolerance: f64) -> LinePathIter { + LinePathIter { line: *self, ix: 0 } + } + + /// Returning zero here is consistent with the contract (area is + /// only meaningful for closed shapes), but an argument can be made + /// that the contract should be tightened to include the Green's + /// theorem contribution. + #[inline(always)] + fn area(&self) -> f64 { + 0.0 + } + + #[inline] + fn perimeter(&self, _accuracy: f64) -> f64 { + (self.p1 - self.p0).hypot() + } + + /// Same consideration as `area`. + #[inline(always)] + fn winding(&self, _pt: Point) -> i32 { + 0 + } + + #[inline(always)] + fn bounding_box(&self) -> Rect { + Rect::from_points(self.p0, self.p1) + } + + #[inline(always)] + fn as_line(&self) -> Option { + Some(*self) + } +} + +impl Iterator for LinePathIter { + type Item = PathEl; + + fn next(&mut self) -> Option { + self.ix += 1; + match self.ix { + 1 => Some(PathEl::MoveTo(self.line.p0)), + 2 => Some(PathEl::LineTo(self.line.p1)), + _ => None, + } + } +} + +#[cfg(test)] +mod tests { + use crate::{Line, ParamCurveArclen, Point}; + + #[test] + fn line_reversed() { + let l = Line::new((0.0, 0.0), (1.0, 1.0)); + let f = l.reversed(); + + assert_eq!(l.p0, f.p1); + assert_eq!(l.p1, f.p0); + + // Reversing it again should result in the original line + assert_eq!(l, f.reversed()); + } + + #[test] + fn line_arclen() { + let l = Line::new((0.0, 0.0), (1.0, 1.0)); + let true_len = 2.0f64.sqrt(); + let epsilon = 1e-9; + assert!(l.arclen(epsilon) - true_len < epsilon); + + let t = l.inv_arclen(true_len / 3.0, epsilon); + assert!((t - 1.0 / 3.0).abs() < epsilon); + } + + #[test] + fn line_midpoint() { + let l = Line::new((0.0, 0.0), (2.0, 4.0)); + assert_eq!(l.midpoint(), Point::new(1.0, 2.0)); + } + + #[test] + fn line_is_finite() { + assert!( + (Line { + p0: Point { x: 0., y: 0. }, + p1: Point { x: 1., y: 1. } + }) + .is_finite() + ); + + assert!( + !(Line { + p0: Point { x: 0., y: 0. }, + p1: Point { + x: f64::INFINITY, + y: 1. + } + }) + .is_finite() + ); + + assert!( + !(Line { + p0: Point { x: 0., y: 0. }, + p1: Point { + x: 0., + y: f64::INFINITY + } + }) + .is_finite() + ); + } + + #[test] + fn line_nearest() { + use crate::{ParamCurve, ParamCurveNearest}; + + const EPSILON: f64 = 1e-9; + + let line = Line::new((-4., 0.), (2., 1.)); + + // Projects onto the line segment end point. + let point = Point::new(4., 0.); + let nearest = line.nearest(point, 0.); + assert_eq!(nearest.t, 1.); + assert!((nearest.distance_sq - line.p1.distance_squared(point)).abs() < EPSILON); + + // Projects onto the line segment start point. + let point = Point::new(0., -50.); + let nearest = line.nearest(point, 0.); + assert_eq!(nearest.t, 0.); + assert!((nearest.distance_sq - line.p0.distance_squared(point)).abs() < EPSILON); + + // Projects onto the line segment proper (not just onto one of its extrema). + let point = Point::new(-1., 0.5); + let nearest = line.nearest(point, 0.); + assert!(nearest.t > 0. && nearest.t < 1.); + // Ensure evaluating and calculating distance manually has the same result. + assert!( + (line.eval(nearest.t).distance_squared(point) - nearest.distance_sq).abs() < EPSILON + ); + + // Test minimality while avoiding reimplementing projection in this test by checking that + // moving to a slightly different point on the segment increases the distance. + assert!(line.eval(nearest.t * 0.95).distance_squared(point) > nearest.distance_sq); + assert!(line.eval(nearest.t * 1.05).distance_squared(point) > nearest.distance_sq); + } +} diff --git a/vendor/kurbo/src/mindist.rs b/vendor/kurbo/src/mindist.rs new file mode 100644 index 0000000000..3c741aaa26 --- /dev/null +++ b/vendor/kurbo/src/mindist.rs @@ -0,0 +1,359 @@ +// Copyright 2021 the Kurbo Authors +// SPDX-License-Identifier: Apache-2.0 OR MIT + +//! Minimum distance between two Bézier curves +//! +//! This implements the algorithm in "Computing the minimum distance between +//! two Bézier curves", Chen et al., *Journal of Computational and Applied +//! Mathematics* 229(2009), 294-301 + +use crate::Vec2; +use core::cmp::Ordering; + +#[cfg(not(feature = "std"))] +use crate::common::FloatFuncs; + +/// Given the control points of n- and m-dimensional Bézier curves in `bez1` and `bez2` +/// respectively, calculate the minimum distance between the two curves. +/// +/// This should work for arbitrary Bézier curves up to and including degree 255, but only lines, +/// quadratics and cubics are tested. +/// +/// Returns a tuple of the distance, the path time `t1` of the closest point on the first Bézier, +/// and the path time `t2` of the closest point on the second Bézier. +/// +/// # Panics +/// +/// This panics if more than 256 control points are given in `bez1` or `bez2`, i.e., if either +/// Bézier is of degree greater than 255. +pub(crate) fn min_dist_param( + bez1: &[Vec2], + bez2: &[Vec2], + u: (f64, f64), + v: (f64, f64), + epsilon: f64, + best_alpha: Option, +) -> (f64, f64, f64) { + assert!(!bez1.is_empty() && !bez2.is_empty()); + let n = u8::try_from(bez1.len() - 1).expect("At most 256 control points"); + let m = u8::try_from(bez2.len() - 1).expect("At most 256 control points"); + let (umin, umax) = u; + let (vmin, vmax) = v; + let umid = (umin + umax) / 2.0; + let vmid = (vmin + vmax) / 2.0; + let svalues: [(f64, f64, f64); 4] = [ + (S(umin, vmin, bez1, bez2), umin, vmin), + (S(umin, vmax, bez1, bez2), umin, vmax), + (S(umax, vmin, bez1, bez2), umax, vmin), + (S(umax, vmax, bez1, bez2), umax, vmax), + ]; + let alpha: f64 = svalues.iter().map(|(a, _, _)| *a).reduce(f64::min).unwrap(); + if let Some(best) = best_alpha { + if alpha > best { + return (alpha, umid, vmid); + } + } + + if (umax - umin).abs() < epsilon || (vmax - vmin).abs() < epsilon { + return (alpha, umid, vmid); + } + + // Property one: D(r>k) > alpha + let mut is_outside = true; + let mut min_drk = None; + let mut min_ij = None; + for r in 0..(2 * n) { + for k in 0..(2 * m) { + let d_rk = D_rk(r, k, bez1, bez2); + if d_rk < alpha { + is_outside = false; + } + if min_drk.is_none() || Some(d_rk) < min_drk { + min_drk = Some(d_rk); + min_ij = Some((r, k)); + } + } + } + if is_outside { + return (alpha, umid, vmid); + } + + // Property two: boundary check + let mut at_boundary0on_bez1 = true; + let mut at_boundary1on_bez1 = true; + let mut at_boundary0on_bez2 = true; + let mut at_boundary1on_bez2 = true; + for i in 0..2 * n { + for j in 0..2 * m { + let dij = D_rk(i, j, bez1, bez2); + let dkj = D_rk(0, j, bez1, bez2); + if dij < dkj { + at_boundary0on_bez1 = false; + } + let dkj = D_rk(2 * n, j, bez1, bez2); + if dij < dkj { + at_boundary1on_bez1 = false; + } + let dkj = D_rk(i, 0, bez1, bez2); + if dij < dkj { + at_boundary0on_bez2 = false; + } + let dkj = D_rk(i, 2 * m, bez1, bez2); + if dij < dkj { + at_boundary1on_bez2 = false; + } + } + } + if at_boundary0on_bez1 && at_boundary0on_bez2 { + return svalues[0]; + } + if at_boundary0on_bez1 && at_boundary1on_bez2 { + return svalues[1]; + } + if at_boundary1on_bez1 && at_boundary0on_bez2 { + return svalues[2]; + } + if at_boundary1on_bez1 && at_boundary1on_bez2 { + return svalues[3]; + } + + let (min_i, min_j) = min_ij.unwrap(); + let new_umid = umin + (umax - umin) * (min_i as f64 / (2 * n) as f64); + let new_vmid = vmin + (vmax - vmin) * (min_j as f64 / (2 * m) as f64); + + // Subdivide + let results = [ + min_dist_param( + bez1, + bez2, + (umin, new_umid), + (vmin, new_vmid), + epsilon, + Some(alpha), + ), + min_dist_param( + bez1, + bez2, + (umin, new_umid), + (new_vmid, vmax), + epsilon, + Some(alpha), + ), + min_dist_param( + bez1, + bez2, + (new_umid, umax), + (vmin, new_vmid), + epsilon, + Some(alpha), + ), + min_dist_param( + bez1, + bez2, + (new_umid, umax), + (new_vmid, vmax), + epsilon, + Some(alpha), + ), + ]; + + *results + .iter() + .min_by(|a, b| a.0.partial_cmp(&b.0).unwrap_or(Ordering::Less)) + .unwrap() +} + +// $ S(u,v)=\sum_{r=0}^{2n} \sum _{k=0}^{2m} D_{r,k} B_{2n}^r(u) B_{2m}^k(v) $ + +#[allow(non_snake_case)] +fn S(u: f64, v: f64, bez1: &[Vec2], bez2: &[Vec2]) -> f64 { + #[expect( + clippy::cast_possible_truncation, + reason = "By the checks in `min_dist_param` we know `bez1.len()` and `bez2.len()` are less than or equal to 256" + )] + let (n, m) = { ((bez1.len() - 1) as u8, (bez2.len() - 1) as u8) }; + let mut summand = 0.0; + for r in 0..=2 * n { + for k in 0..=2 * m { + summand += + D_rk(r, k, bez1, bez2) * basis_function(2 * n, r, u) * basis_function(2 * m, k, v); + } + } + summand +} + +// $ C_{r,k} = ( \sum_{i=\theta}^\upsilon P_i C_n^i C_n^{r-i} / C_{2n}^r ) \cdot (\sum_{j=\sigma}^\varsigma Q_j C_m^j C_m^{k-j} / C_{2m}^k ) $ +#[allow(non_snake_case)] +fn C_rk(r: u8, k: u8, bez1: &[Vec2], bez2: &[Vec2]) -> f64 { + #[expect( + clippy::cast_possible_truncation, + reason = "By the checks in `min_dist_param` we know `bez1.len()` and `bez2.len()` are less than or equal to 256" + )] + let (n, m) = { ((bez1.len() - 1) as u8, (bez2.len() - 1) as u8) }; + let upsilon = r.min(n); + let theta = r - n.min(r); + let mut left: Vec2 = Vec2::ZERO; + for i in theta..upsilon + 1 { + let item = bez1[usize::from(i)]; + left += item * (choose(n, i) * choose(n, r - i)) as f64 / (choose(2 * n, r) as f64); + } + + let varsigma = k.min(m); + let sigma = k - m.min(k); + let mut right: Vec2 = Vec2::ZERO; + for j in sigma..varsigma + 1 { + let item = bez2[usize::from(j)]; + right += item * (choose(m, j) * choose(m, k - j)) as f64 / (choose(2 * m, k) as f64); + } + left.dot(right) +} + +// $ A_r=\sum _{i=\theta} ^\upsilon (P_i \cdot P_{r-i}) C_n^i C_n^{r-i} / C_{2n}^r $ +// ($ B_k $ is just the same as $ A_r $ but for the other curve.) + +#[allow(non_snake_case)] +fn A_r(r: u8, p: &[Vec2]) -> f64 { + #[expect( + clippy::cast_possible_truncation, + reason = "By the checks in `min_dist_param` we know `p.len()` is less than or equal to 256" + )] + let n = (p.len() - 1) as u8; + let upsilon = r.min(n); + let theta = r - n.min(r); + (theta..=upsilon) + .map(|i| { + let dot = p[usize::from(i)].dot(p[usize::from(r - i)]); // These are bounds checked by the sum limits + let factor = (choose(n, i) * choose(n, r - i)) as f64 / (choose(2 * n, r) as f64); + dot * factor + }) + .sum() +} + +#[allow(non_snake_case)] +fn D_rk(r: u8, k: u8, bez1: &[Vec2], bez2: &[Vec2]) -> f64 { + // In the paper, B_k is used for the second factor, but it's the same thing + A_r(r, bez1) + A_r(k, bez2) - 2.0 * C_rk(r, k, bez1, bez2) +} + +// Bézier basis function +fn basis_function(n: u8, i: u8, u: f64) -> f64 { + choose(n, i) as f64 * (1.0 - u).powi((n - i) as i32) * u.powi(i as i32) +} + +// Binomial co-efficient, but returning zeros for values outside of domain +fn choose(n: u8, k: u8) -> u32 { + let mut n = n as u32; + let k = k as u32; + if k > n { + return 0; + } + let mut p = 1; + for i in 1..=(n - k) { + p *= n; + p /= i; + n -= 1; + } + p +} + +#[cfg(test)] +mod tests { + use crate::mindist::A_r; + use crate::mindist::{D_rk, choose}; + use crate::param_curve::ParamCurve; + use crate::{CubicBez, Line, PathSeg, Vec2}; + + #[test] + fn test_choose() { + assert_eq!(choose(6, 0), 1); + assert_eq!(choose(6, 1), 6); + assert_eq!(choose(6, 2), 15); + } + + #[test] + fn test_d_rk() { + let bez1 = vec![ + Vec2::new(129.0, 139.0), + Vec2::new(190.0, 139.0), + Vec2::new(201.0, 364.0), + Vec2::new(90.0, 364.0), + ]; + let bez2 = vec![ + Vec2::new(309.0, 159.0), + Vec2::new(178.0, 159.0), + Vec2::new(215.0, 408.0), + Vec2::new(309.0, 408.0), + ]; + let b = A_r(1, &bez2); + assert!((b - 80283.0).abs() < 0.005, "B_1(Q)={b:?}"); + let d = D_rk(0, 1, &bez1, &bez2); + assert!((d - 9220.0).abs() < 0.005, "D={d:?}"); + } + + #[test] + fn test_mindist() { + let bez1 = PathSeg::Cubic(CubicBez::new( + (129.0, 139.0), + (190.0, 139.0), + (201.0, 364.0), + (90.0, 364.0), + )); + let bez2 = PathSeg::Cubic(CubicBez::new( + (309.0, 159.0), + (178.0, 159.0), + (215.0, 408.0), + (309.0, 408.0), + )); + let mindist = bez1.min_dist(bez2, 0.001); + assert!((mindist.distance - 50.9966).abs() < 0.5); + } + + #[test] + fn test_overflow() { + let bez1 = PathSeg::Cubic(CubicBez::new( + (232.0, 126.0), + (134.0, 126.0), + (139.0, 232.0), + (141.0, 301.0), + )); + let bez2 = PathSeg::Line(Line::new((359.0, 416.0), (367.0, 755.0))); + let mindist = bez1.min_dist(bez2, 0.001); + assert!((mindist.distance - 246.4731222669117).abs() < 0.5); + } + + #[test] + fn test_out_of_order() { + let bez1 = PathSeg::Cubic(CubicBez::new( + (287.0, 182.0), + (346.0, 277.0), + (356.0, 299.0), + (359.0, 416.0), + )); + let bez2 = PathSeg::Line(Line::new((141.0, 301.0), (152.0, 709.0))); + let mindist1 = bez1.min_dist(bez2, 0.5); + let mindist2 = bez2.min_dist(bez1, 0.5); + assert!((mindist1.distance - mindist2.distance).abs() < 0.5); + } + + #[test] + fn test_line_curve() { + let line = PathSeg::Line(Line::new((929.0, 335.0), (911.0, 340.0))); + + let line_as_bez = PathSeg::Cubic(CubicBez::new( + line.eval(0.0), + line.eval(1.0 / 3.0), + line.eval(2.0 / 3.0), + line.eval(1.0), + )); + + let bez2 = PathSeg::Cubic(CubicBez::new( + (1052.0, 401.0), + (1048.0, 305.0), + (1046.0, 216.0), + (1054.0, 146.0), + )); + let mindist_as_bez = line_as_bez.min_dist(bez2, 0.5); + let mindist_as_line = line.min_dist(bez2, 0.5); + assert!((mindist_as_line.distance - mindist_as_bez.distance).abs() < 0.5); + } +} diff --git a/vendor/kurbo/src/moments.rs b/vendor/kurbo/src/moments.rs new file mode 100644 index 0000000000..c54fe71a7b --- /dev/null +++ b/vendor/kurbo/src/moments.rs @@ -0,0 +1,594 @@ +// Copyright 2025 the Kurbo Authors +// SPDX-License-Identifier: Apache-2.0 OR MIT + +use crate::{PathEl, Point}; + +#[cfg(not(feature = "std"))] +use crate::common::FloatFuncs; + +/// A collect of moment integrals for a path, used for computing +/// shape properties like area, centroid, and inertia. +/// +/// The moments are computed using Green's theorem, which relates the +/// integrals of a function over a closed curve to the integrals of its +/// partial derivatives over the region enclosed by the curve. +#[derive(Debug, Default, Copy, Clone)] +pub struct Moments { + /// The first moment of area about the x-axis. + pub moment_x: f64, + /// The first moment of area about the y-axis. + pub moment_y: f64, + /// The second moment of area about the x-axis (also known as the + /// area moment of inertia about the x-axis). + pub moment_xx: f64, + /// The second moment of area about the xy-axis (also known as the + /// product of inertia). + pub moment_xy: f64, + /// The second moment of area about the y-axis (also known as the + /// area moment of inertia about the y-axis). + pub moment_yy: f64, +} + +impl core::ops::Add for Moments { + type Output = Self; + + fn add(self, rhs: Self) -> Self::Output { + Self { + moment_x: self.moment_x + rhs.moment_x, + moment_y: self.moment_y + rhs.moment_y, + moment_xx: self.moment_xx + rhs.moment_xx, + moment_xy: self.moment_xy + rhs.moment_xy, + moment_yy: self.moment_yy + rhs.moment_yy, + } + } +} + +impl Moments { + // The code below is derived from fontTools's fontTools.pens.momentsPen, which is in turn generated + // by running sympy on the Green's theorem integral expressions. + fn handle_line(&mut self, p0: Point, p1: Point) { + let (x0, y0) = (p0.x, p0.y); + let (x1, y1) = (p1.x, p1.y); + let r0 = x1 * y0; + let r1 = x1 * y1; + let r2 = x1.powi(2); + let r3 = r2 * y1; + let r4 = y0 - y1; + let r5 = r4 * x0; + let r6 = x0.powi(2); + let r7 = 2.0 * y0; + let r8 = y0.powi(2); + let r9 = y1.powi(2); + let r10 = x1.powi(3); + let r11 = y0.powi(3); + let r12 = y1.powi(3); + self.moment_x += -r2 * y0 / 6.0 - r3 / 3.0 - r5 * x1 / 6.0 + r6 * (r7 + y1) / 6.0; + self.moment_y += + -r0 * y1 / 6.0 - r8 * x1 / 6.0 - r9 * x1 / 6.0 + x0 * (r8 + r9 + y0 * y1) / 6.0; + self.moment_xx += -r10 * y0 / 12.0 - r10 * y1 / 4.0 - r2 * r5 / 12.0 - r4 * r6 * x1 / 12.0 + + x0.powi(3) * (3.0 * y0 + y1) / 12.0; + self.moment_xy += -r2 * r8 / 24.0 - r2 * r9 / 8.0 - r3 * r7 / 24.0 + + r6 * (r7 * y1 + 3.0 * r8 + r9) / 24.0 + - x0 * x1 * (r8 - r9) / 12.0; + self.moment_yy += -r0 * r9 / 12.0 - r1 * r8 / 12.0 - r11 * x1 / 12.0 - r12 * x1 / 12.0 + + x0 * (r11 + r12 + r8 * y1 + r9 * y0) / 12.0; + } + + fn handle_quad(&mut self, p0: Point, p1: Point, p2: Point) { + let (x0, y0) = (p0.x, p0.y); + let x1 = p1.x; + let y1 = p1.y; + let x2 = p2.x; + let y2 = p2.y; + + let r0 = 2.0 * y1; + let r1 = r0 * x2; + let r2 = x2 * y2; + let r3 = 3.0 * r2; + let r4 = 2.0 * x1; + let r5 = 3.0 * y0; + let r6 = x1.powi(2); + let r7 = x2.powi(2); + let r8 = 4.0 * y1; + let r9 = 10.0 * y2; + let r10 = 2.0 * y2; + let r11 = r4 * x2; + let r12 = x0.powi(2); + let r13 = 10.0 * y0; + let r14 = r4 * y2; + let r15 = x2 * y0; + let r16 = 4.0 * x1; + let r17 = r0 * x1 + r2; + let r18 = r2 * r8; + let r19 = y1.powi(2); + let r20 = 2.0 * r19; + let r21 = y2.powi(2); + let r22 = r21 * x2; + let r23 = 5.0 * r22; + let r24 = y0.powi(2); + let r25 = y0 * y2; + let r26 = 5.0 * r24; + let r27 = x1.powi(3); + let r28 = x2.powi(3); + let r29 = 30.0 * y1; + let r30 = 6.0 * y1; + let r31 = 10.0 * r7 * x1; + let r32 = 5.0 * y2; + let r33 = 12.0 * r6; + let r34 = 30.0 * x1; + let r35 = x1 * y1; + let r36 = r3 + 20.0 * r35; + let r37 = 12.0 * x1; + let r38 = 20.0 * r6; + let r39 = 8.0 * r6 * y1; + let r40 = r32 * r7; + let r41 = 60.0 * y1; + let r42 = 20.0 * r19; + let r43 = 4.0 * r19; + let r44 = 15.0 * r21; + let r45 = 12.0 * x2; + let r46 = 12.0 * y2; + let r47 = 6.0 * x1; + let r48 = 8.0 * r19 * x1 + r23; + let r49 = 8.0 * y1.powi(3); + let r50 = y2.powi(3); + let r51 = y0.powi(3); + let r52 = 10.0 * y1; + let r53 = 12.0 * y1; + self.moment_x += -r11 * (-r10 + y1) / 30.0 + r12 * (r13 + r8 + y2) / 30.0 + r6 * y2 / 15.0 + - r7 * r8 / 30.0 + - r7 * r9 / 30.0 + + x0 * (r14 - r15 - r16 * y0 + r17) / 30.0 + - y0 * (r11 + 2.0 * r6 + r7) / 30.0; + self.moment_y += -r18 / 30.0 - r20 * x2 / 30.0 - r23 / 30.0 - r24 * (r16 + x2) / 30.0 + + x0 * (r0 * y2 + r20 + r21 + r25 + r26 + r8 * y0) / 30.0 + + x1 * y2 * (r10 + y1) / 15.0 + - y0 * (r1 + r17) / 30.0; + self.moment_xx += r12 * (r1 - 5.0 * r15 - r34 * y0 + r36 + r9 * x1) / 420.0 + + 2.0 * r27 * y2 / 105.0 + - r28 * r29 / 420.0 + - r28 * y2 / 4.0 + - r31 * (r0 - 3.0 * y2) / 420.0 + - r6 * x2 * (r0 - r32) / 105.0 + + x0.powi(3) * (r30 + 21.0 * y0 + y2) / 84.0 + - x0 * (r0 * r7 + r15 * r37 - r2 * r37 - r33 * y2 + r38 * y0 - r39 - r40 + r5 * r7) + / 420.0 + - y0 * (8.0 * r27 + 5.0 * r28 + r31 + r33 * x2) / 420.0; + self.moment_xy += r12 * (r13 * y2 + 3.0 * r21 + 105.0 * r24 + r41 * y0 + r42 + r46 * y1) + / 840.0 + - r16 * x2 * (r43 - r44) / 840.0 + - r21 * r7 / 8.0 + - r24 * (r38 + r45 * x1 + 3.0 * r7) / 840.0 + - r41 * r7 * y2 / 840.0 + - r42 * r7 / 840.0 + + r6 * y2 * (r32 + r8) / 210.0 + + x0 * (-r15 * r8 + r16 * r25 + r18 + r21 * r47 - r24 * r34 - r26 * x2 + + r35 * r46 + + r48) + / 420.0 + - y0 * (r16 * r2 + r30 * r7 + r35 * r45 + r39 + r40) / 420.0; + + self.moment_yy += -r2 * r42 / 420.0 + - r22 * r29 / 420.0 + - r24 * (r14 + r36 + r52 * x2) / 420.0 + - r49 * x2 / 420.0 + - r50 * x2 / 12.0 + - r51 * (r47 + x2) / 84.0 + + x0 * (r19 * r46 + + r21 * r5 + + r21 * r52 + + r24 * r29 + + r25 * r53 + + r26 * y2 + + r42 * y0 + + r49 + + 5.0 * r50 + + 35.0 * r51) + / 420.0 + + x1 * y2 * (r43 + r44 + r9 * y1) / 210.0 + - y0 * (r19 * r45 + r2 * r53 - r21 * r4 + r48) / 420.0; + } + + fn handle_cubic(&mut self, p0: Point, p1: Point, p2: Point, p3: Point) { + let x0 = p0.x; + let y0 = p0.y; + let x1 = p1.x; + let y1 = p1.y; + let x2 = p2.x; + let y2 = p2.y; + let x3 = p3.x; + let y3 = p3.y; + + let r0 = 6.0 * y2; + let r1 = r0 * x3; + let r2 = 10.0 * y3; + let r3 = r2 * x3; + let r4 = 3.0 * y1; + let r5 = 6.0 * x1; + let r6 = 3.0 * x2; + let r7 = 6.0 * y1; + let r8 = 3.0 * y2; + let r9 = x2.powi(2); + let r10 = 45.0 * r9; + let r11 = r10 * y3; + let r12 = x3.powi(2); + let r13 = r12 * y2; + let r14 = r12 * y3; + let r15 = 7.0 * y3; + let r16 = 15.0 * x3; + let r17 = r16 * x2; + let r18 = x1.powi(2); + let r19 = 9.0 * r18; + let r20 = x0.powi(2); + let r21 = 21.0 * y1; + let r22 = 9.0 * r9; + let r23 = r7 * x3; + let r24 = 9.0 * y2; + let r25 = r24 * x2 + r3; + let r26 = 9.0 * x2; + let r27 = x2 * y3; + let r28 = -r26 * y1 + 15.0 * r27; + let r29 = 3.0 * x1; + let r30 = 45.0 * x1; + let r31 = 12.0 * x3; + let r32 = 45.0 * r18; + let r33 = 5.0 * r12; + let r34 = r8 * x3; + let r35 = 105.0 * y0; + let r36 = 30.0 * y0; + let r37 = r36 * x2; + let r38 = 5.0 * x3; + let r39 = 15.0 * y3; + let r40 = 5.0 * y3; + let r41 = r40 * x3; + let r42 = x2 * y2; + let r43 = 18.0 * r42; + let r44 = 45.0 * y1; + let r45 = r41 + r43 + r44 * x1; + let r46 = y2 * y3; + let r47 = r46 * x3; + let r48 = y2.powi(2); + let r49 = 45.0 * r48; + let r50 = r49 * x3; + let r51 = y3.powi(2); + let r52 = r51 * x3; + let r53 = y1.powi(2); + let r54 = 9.0 * r53; + let r55 = y0.powi(2); + let r56 = 21.0 * x1; + let r57 = 6.0 * x2; + let r58 = r16 * y2; + let r59 = r39 * y2; + let r60 = 9.0 * r48; + let r61 = r6 * y3; + let r62 = 3.0 * y3; + let r63 = r36 * y2; + let r64 = y1 * y3; + let r65 = 45.0 * r53; + let r66 = 5.0 * r51; + let r67 = x2.powi(3); + let r68 = x3.powi(3); + let r69 = 630.0 * y2; + let r70 = 126.0 * x3; + let r71 = x1.powi(3); + let r72 = 126.0 * x2; + let r73 = 63.0 * r9; + let r74 = r73 * x3; + let r75 = r15 * x3 + 15.0 * r42; + let r76 = 630.0 * x1; + let r77 = 14.0 * x3; + let r78 = 21.0 * r27; + let r79 = 42.0 * x1; + let r80 = 42.0 * x2; + let r81 = x1 * y2; + let r82 = 63.0 * r42; + let r83 = x1 * y1; + let r84 = r41 + r82 + 378.0 * r83; + let r85 = x2 * x3; + let r86 = r85 * y1; + let r87 = r27 * x3; + let r88 = 27.0 * r9; + let r89 = r88 * y2; + let r90 = 42.0 * r14; + let r91 = 90.0 * x1; + let r92 = 189.0 * r18; + let r93 = 378.0 * r18; + let r94 = r12 * y1; + let r95 = 252.0 * x1 * x2; + let r96 = r79 * x3; + let r97 = 30.0 * r85; + let r98 = r83 * x3; + let r99 = 30.0 * x3; + let r100 = 42.0 * x3; + let r101 = r42 * x1; + let r102 = r10 * y2 + 14.0 * r14 + 126.0 * r18 * y1 + r81 * r99; + let r103 = 378.0 * r48; + let r104 = 18.0 * y1; + let r105 = r104 * y2; + let r106 = y0 * y1; + let r107 = 252.0 * y2; + let r108 = r107 * y0; + let r109 = y0 * y3; + let r110 = 42.0 * r64; + let r111 = 378.0 * r53; + let r112 = 63.0 * r48; + let r113 = 27.0 * x2; + let r114 = r27 * y2; + let r115 = r113 * r48 + 42.0 * r52; + let r116 = x3 * y3; + let r117 = 54.0 * r42; + let r118 = r51 * x1; + let r119 = r51 * x2; + let r120 = r48 * x1; + let r121 = 21.0 * x3; + let r122 = r64 * x1; + let r123 = r81 * y3; + let r124 = 30.0 * r27 * y1 + r49 * x2 + 14.0 * r52 + 126.0 * r53 * x1; + let r125 = y2.powi(3); + let r126 = y3.powi(3); + let r127 = y1.powi(3); + let r128 = y0.powi(3); + let r129 = r51 * y2; + let r130 = r112 * y3 + r21 * r51; + let r131 = 189.0 * r53; + let r132 = 90.0 * y2; + self.moment_x += r11 / 840.0 - r13 / 8.0 - r14 / 3.0 - r17 * (-r15 + r8) / 840.0 + + r19 * (r8 + 2.0 * y3) / 840.0 + + r20 * (r0 + r21 + 56.0 * y0 + y3) / 168.0 + + r29 * (-r23 + r25 + r28) / 840.0 + - r4 * (10.0 * r12 + r17 + r22) / 840.0 + + x0 * (12.0 * r27 + r30 * y2 + r34 - r35 * x1 - r37 - r38 * y0 + r39 * x1 - r4 * x3 + + r45) + / 840.0 + - y0 * (r17 + r30 * x2 + r31 * x1 + r32 + r33 + 18.0 * r9) / 840.0; + self.moment_y += -r4 * (r25 + r58) / 840.0 + - r47 / 8.0 + - r50 / 840.0 + - r52 / 6.0 + - r54 * (r6 + 2.0 * x3) / 840.0 + - r55 * (r56 + r57 + x3) / 168.0 + + x0 * (r35 * y1 + + r40 * y0 + + r44 * y2 + + 18.0 * r48 + + 140.0 * r55 + + r59 + + r63 + + 12.0 * r64 + + r65 + + r66) + / 840.0 + + x1 * (r24 * y1 + 10.0 * r51 + r59 + r60 + r7 * y3) / 280.0 + + x2 * y3 * (r15 + r8) / 56.0 + - y0 * (r16 * y1 + r31 * y2 + r44 * x2 + r45 + r61 - r62 * x1) / 840.0; + self.moment_xx += -r12 * r72 * (-r40 + r8) / 9240.0 + + 3.0 * r18 * (r28 + r34 - r38 * y1 + r75) / 3080.0 + + r20 + * (r24 * x3 - r72 * y0 - r76 * y0 - r77 * y0 + + r78 + + r79 * y3 + + r80 * y1 + + 210.0 * r81 + + r84) + / 9240.0 + - r29 + * (r12 * r21 + 14.0 * r13 + r44 * r9 - r73 * y3 + 54.0 * r86 + - 84.0 * r87 + - r89 + - r90) + / 9240.0 + - r4 * (70.0 * r12 * x2 + 27.0 * r67 + 42.0 * r68 + r74) / 9240.0 + + 3.0 * r67 * y3 / 220.0 + - r68 * r69 / 9240.0 + - r68 * y3 / 4.0 + - r70 * r9 * (-r62 + y2) / 9240.0 + + 3.0 * r71 * (r24 + r40) / 3080.0 + + x0.powi(3) * (r24 + r44 + 165.0 * y0 + y3) / 660.0 + + x0 * (r100 * r27 + 162.0 * r101 + r102 + r11 + 63.0 * r18 * y3 + r27 * r91 + - r33 * y0 + - r37 * x3 + + r43 * x3 + - r73 * y0 + - r88 * y1 + + r92 * y2 + - r93 * y0 + - 9.0 * r94 + - r95 * y0 + - r96 * y0 + - r97 * y1 + - 18.0 * r98 + + r99 * x1 * y3) + / 9240.0 + - y0 * (r12 * r56 + + r12 * r80 + + r32 * x3 + + 45.0 * r67 + + 14.0 * r68 + + 126.0 * r71 + + r74 + + r85 * r91 + + 135.0 * r9 * x1 + + r92 * x2) + / 9240.0; + self.moment_xy += -r103 * r12 / 18480.0 - r12 * r51 / 8.0 - 3.0 * r14 * y2 / 44.0 + + 3.0 * r18 * (r105 + r2 * y1 + 18.0 * r46 + 15.0 * r48 + 7.0 * r51) / 6160.0 + + r20 + * (1260.0 * r106 + + r107 * y1 + + r108 + + 28.0 * r109 + + r110 + + r111 + + r112 + + 30.0 * r46 + + 2310.0 * r55 + + r66) + / 18480.0 + - r54 * (7.0 * r12 + 18.0 * r85 + 15.0 * r9) / 18480.0 + - r55 * (r33 + r73 + r93 + r95 + r96 + r97) / 18480.0 + - r7 * (42.0 * r13 + r82 * x3 + 28.0 * r87 + r89 + r90) / 18480.0 + - 3.0 * r85 * (r48 - r66) / 220.0 + + 3.0 * r9 * y3 * (r62 + 2.0 * y2) / 440.0 + + x0 * (-r1 * y0 - 84.0 * r106 * x2 + + r109 * r56 + + 54.0 * r114 + + r117 * y1 + + 15.0 * r118 + + 21.0 * r119 + + 81.0 * r120 + + r121 * r46 + + 54.0 * r122 + + 60.0 * r123 + + r124 + - r21 * x3 * y0 + + r23 * y3 + - r54 * x3 + - r55 * r72 + - r55 * r76 + - r55 * r77 + + r57 * y0 * y3 + + r60 * x3 + + 84.0 * r81 * y0 + + 189.0 * r81 * y1) + / 9240.0 + + x1 * (r104 * r27 - r105 * x3 - r113 * r53 + 63.0 * r114 + r115 - r16 * r53 + + 28.0 * r47 + + r51 * r80) + / 3080.0 + - y0 * (54.0 * r101 + r102 + r116 * r5 + r117 * x3 + 21.0 * r13 - r19 * y3 + + r22 * y3 + + r78 * x3 + + 189.0 * r83 * x2 + + 60.0 * r86 + + 81.0 * r9 * y1 + + 15.0 * r94 + + 54.0 * r98) + / 9240.0; + self.moment_yy += -r103 * r116 / 9240.0 + - r125 * r70 / 9240.0 + - r126 * x3 / 12.0 + - 3.0 * r127 * (r26 + r38) / 3080.0 + - r128 * (r26 + r30 + x3) / 660.0 + - r4 * (r112 * x3 + r115 - 14.0 * r119 + 84.0 * r47) / 9240.0 + - r52 * r69 / 9240.0 + - r54 * (r58 + r61 + r75) / 9240.0 + - r55 * (r100 * y1 + r121 * y2 + r26 * y3 + r79 * y2 + r84 + 210.0 * x2 * y1) / 9240.0 + + x0 * (r108 * y1 + + r110 * y0 + + r111 * y0 + + r112 * y0 + + 45.0 * r125 + + 14.0 * r126 + + 126.0 * r127 + + 770.0 * r128 + + 42.0 * r129 + + r130 + + r131 * y2 + + r132 * r64 + + 135.0 * r48 * y1 + + 630.0 * r55 * y1 + + 126.0 * r55 * y2 + + 14.0 * r55 * y3 + + r63 * y3 + + r65 * y3 + + r66 * y0) + / 9240.0 + + x1 * (27.0 * r125 + + 42.0 * r126 + + 70.0 * r129 + + r130 + + r39 * r53 + + r44 * r48 + + 27.0 * r53 * y2 + + 54.0 * r64 * y2) + / 3080.0 + + 3.0 * x2 * y3 * (r48 + r66 + r8 * y3) / 220.0 + - y0 * (r100 * r46 + 18.0 * r114 + - 9.0 * r118 + - 27.0 * r120 + - 18.0 * r122 + - 30.0 * r123 + + r124 + + r131 * x2 + + r132 * x3 * y1 + + 162.0 * r42 * y1 + + r50 + + 63.0 * r53 * x3 + + r64 * r99) + / 9240.0; + } +} + +/// A trait for types that can provide moment integrals for a path using Green's theorem. +pub trait ParamCurveMoments<'a> { + /// Returns the moment integrals for the path using Green's theorem. + fn moments(&'a self) -> Moments; +} + +impl<'a, T: 'a> ParamCurveMoments<'a> for T +where + &'a T: IntoIterator, +{ + fn moments(&'a self) -> Moments { + let mut moments = Moments::default(); + let mut start_pt: Point = Point::ZERO; + let mut cur: Point = Point::ZERO; + for el in self { + match el { + PathEl::MoveTo(p) => { + start_pt = p; + cur = p; + } + PathEl::LineTo(p) => { + moments.handle_line(cur, p); + cur = p; + } + PathEl::QuadTo(p0, p1) => { + moments.handle_quad(cur, p0, p1); + cur = p1; + } + PathEl::CurveTo(p1, p2, p3) => { + moments.handle_cubic(cur, p1, p2, p3); + cur = p3; + } + PathEl::ClosePath => { + if cur != start_pt { + moments.handle_line(cur, start_pt); + cur = start_pt; + } + } + } + } + moments + } +} + +#[cfg(test)] +mod tests { + use crate::BezPath; + + use super::*; + + macro_rules! assert_approx_eq { + ($x: expr, $y: expr) => { + assert!(($x - $y).abs() < 1e-8, "{} != {}", $x, $y); + }; + } + + #[test] + fn test_moments() { + let path = BezPath::from_vec(vec![ + PathEl::MoveTo(Point::new(0.0, 0.0)), + PathEl::LineTo(Point::new(1.0, 0.0)), + PathEl::LineTo(Point::new(1.0, 1.0)), + PathEl::LineTo(Point::new(0.0, 1.0)), + PathEl::ClosePath, + ]); + let moments = path.moments(); + assert_approx_eq!(moments.moment_x, 0.5); + assert_approx_eq!(moments.moment_y, 0.5); + assert_approx_eq!(moments.moment_xx, 0.3333333333333333); + assert_approx_eq!(moments.moment_xy, 0.25); + assert_approx_eq!(moments.moment_yy, 0.3333333333333333); + } +} diff --git a/vendor/kurbo/src/offset.rs b/vendor/kurbo/src/offset.rs new file mode 100644 index 0000000000..48ecfad14e --- /dev/null +++ b/vendor/kurbo/src/offset.rs @@ -0,0 +1,668 @@ +// Copyright 2022 the Kurbo Authors +// SPDX-License-Identifier: Apache-2.0 OR MIT + +//! Computation of offset curves of cubic Béziers. +//! +//! The main algorithm in this module is a new technique designed for robustness +//! and speed. The details are involved; hopefully there will be a paper. + +use arrayvec::ArrayVec; + +#[cfg(not(feature = "std"))] +use crate::common::FloatFuncs; + +use crate::{ + BezPath, CubicBez, ParamCurve, ParamCurveDeriv, PathSeg, Point, QuadBez, Vec2, + common::{solve_itp, solve_quadratic}, +}; + +/// State used for computing an offset curve of a single cubic. +struct CubicOffset { + /// The cubic being offset. This has been regularized. + c: CubicBez, + /// The derivative of `c`. + q: QuadBez, + /// The offset distance (same as the argument). + d: f64, + /// `c0 + c1 t + c2 t^2` is the cross product of second and first + /// derivatives of the underlying cubic, multiplied by the offset. + /// This is used for computing cusps on the offset curve. + /// + /// Note that given a curve `c(t)`, its signed curvature is + /// `c''(t) x c'(t) / ||c'(t)||^3`. See also [`Self::cusp_sign`]. + c0: f64, + c1: f64, + c2: f64, + /// The tolerance (same as the argument). + tolerance: f64, +} + +// We never let cusp values have an absolute value smaller than +// this. When a cusp is found, determine its sign and use this value. +const CUSP_EPSILON: f64 = 1e-12; + +/// Number of points for least-squares fit and error evaluation. +/// +/// This value is a tradeoff between accuracy and performance. The main risk in it +/// being to small is under-sampling the error and thus letting excessive error +/// slip through. That said, the "arc drawing" approach is designed to be robust +/// and not generate approximate results with narrow error peaks, even in near-cusp +/// "J" shape curves. +const N_LSE: usize = 8; + +/// The proportion of transverse error that is blended in the least-squares logic. +const BLEND: f64 = 1e-3; + +/// Maximum recursion depth. +/// +/// Recursion is bounded to this depth, so the total number of subdivisions will +/// not exceed two to this power. +/// +/// This is primarily a "belt and suspenders" robustness guard. In normal operation, +/// the recursion bound should never be reached, as accuracy improves very quickly +/// on subdivision. For unreasonably large coordinate values or small tolerances, it +/// is possible, and in those cases the result will be out of tolerance. +/// +/// Perhaps should be configurable. +const MAX_DEPTH: usize = 8; + +/// State local to a subdivision +struct OffsetRec { + t0: f64, + t1: f64, + // unit tangent at t0 + utan0: Vec2, + // unit tangent at t1 + utan1: Vec2, + cusp0: f64, + cusp1: f64, + /// Recursion depth + depth: usize, +} + +/// Result of error evaluation +struct ErrEval { + /// Maximum detected error + err_squared: f64, + /// Unit normals sampled uniformly across approximation + unorms: [Vec2; N_LSE], + /// Difference between point on source curve and normal from approximation. + err_vecs: [Vec2; N_LSE], +} + +/// Result of subdivision +struct SubdivisionPoint { + /// Source curve t value at subdivision point + t: f64, + /// Unit tangent at subdivision point + utan: Vec2, +} + +/// Compute an approximate offset curve. +/// +/// The parallel curve of `c` offset by `d` is written to the `result` path. +/// +/// There is a fair amount of attention to robustness, but this method is not suitable +/// for degenerate cubics with entirely co-linear control points. Those cases should be +/// handled before calling this function, by replacing them with linear segments. +pub fn offset_cubic(c: CubicBez, d: f64, tolerance: f64, result: &mut BezPath) { + result.truncate(0); + // A tuning parameter for regularization. A value too large may distort the curve, + // while a value too small may fail to generate smooth curves. This is a somewhat + // arbitrary value, and should be revisited. + const DIM_TUNE: f64 = 0.25; + // We use regularization to perturb the curve to avoid *interior* zero-derivative + // cusps. There is robustness logic in place to handle zero derivatives at the + // endpoints. + // + // As a performance note, it might be a good idea to move regularization and + // tangent determination to the caller, as those computations are the same for both + // signs of `d`. + let c_regularized = c.regularize_cusp(tolerance * DIM_TUNE); + let co = CubicOffset::new(c_regularized, d, tolerance); + let (tan0, tan1) = PathSeg::Cubic(c).tangents(); + let utan0 = tan0.normalize(); + let utan1 = tan1.normalize(); + let cusp0 = co.endpoint_cusp(co.q.p0, co.c0); + let cusp1 = co.endpoint_cusp(co.q.p2, co.c0 + co.c1 + co.c2); + result.move_to(c.p0 + d * utan0.turn_90()); + let rec = OffsetRec::new(0., 1., utan0, utan1, cusp0, cusp1, 0); + co.offset_rec(&rec, result); +} + +impl CubicOffset { + /// Create a new curve from Bézier segment and offset. + fn new(c: CubicBez, d: f64, tolerance: f64) -> Self { + let q = c.deriv(); + let d2 = 2.0 * d; + let p1xp0 = q.p1.to_vec2().cross(q.p0.to_vec2()); + let p2xp0 = q.p2.to_vec2().cross(q.p0.to_vec2()); + let p2xp1 = q.p2.to_vec2().cross(q.p1.to_vec2()); + CubicOffset { + c, + q, + d, + c0: d2 * p1xp0, + c1: d2 * (p2xp0 - 2.0 * p1xp0), + c2: d2 * (p2xp1 - p2xp0 + p1xp0), + tolerance, + } + } + + /// Compute curvature of the source curve times offset plus 1. + /// + /// This quantity is called "cusp" because cusps appear in the offset curve + /// where this value crosses zero. This is based on the geometric property + /// that the offset curve has a cusp when the radius of curvature of the + /// source curve is equal to the offset curve's distance. + /// + /// Note: there is a potential division by zero when the derivative vanishes. + /// We avoid doing so for interior points by regularizing the cubic beforehand. + /// We avoid doing so for endpoints by calling `endpoint_cusp` instead. + fn cusp_sign(&self, t: f64) -> f64 { + let ds2 = self.q.eval(t).to_vec2().hypot2(); + ((self.c2 * t + self.c1) * t + self.c0) / (ds2 * ds2.sqrt()) + 1.0 + } + + /// Compute cusp value of endpoint. + /// + /// This is a special case of [`Self::cusp_sign`]. For the start point, `tan` should be + /// the start point tangent and `y` should be `c0`. For the end point, `tan` should be + /// the end point tangent and `y` should be `c0 + c1 + c2`. + /// + /// This is just evaluating the polynomial at t=0 and t=1. + /// + /// See [`Self::cusp_sign`] for a description of what "cusp value" means. + fn endpoint_cusp(&self, tan: Point, y: f64) -> f64 { + // Robustness to avoid divide-by-zero when derivatives vanish + const TAN_DIST_EPSILON: f64 = 1e-12; + let tan_dist = tan.to_vec2().hypot().max(TAN_DIST_EPSILON); + let rsqrt = 1.0 / tan_dist; + y * (rsqrt * rsqrt * rsqrt) + 1.0 + } + + /// Primary entry point for recursive subdivision. + /// + /// At a high level, this method determines whether subdivision is necessary. If + /// so, it determines a subdivision point and then recursively calls itself on + /// both subdivisions. If not, it computes a single cubic Bézier to approximate + /// the offset curve, and appends it to `result`. + fn offset_rec(&self, rec: &OffsetRec, result: &mut BezPath) { + // First, determine whether the offset curve contains a cusp. If the sign + // of the cusp value (curvature times offset plus 1) is different at the + // subdivision endpoints, then there is definitely a cusp inside. Find it and + // subdivide there. + // + // Note that there's a possibility the curve has two (or, potentially, any + // even number). We don't rigorously check for this case; if the measured + // error comes in under the tolerance, we simply accept it. Otherwise, in + // the common case we expect to detect a sign crossing from the new + // subdivision point. + if rec.cusp0 * rec.cusp1 < 0.0 { + let a = rec.t0; + let b = rec.t1; + let s = rec.cusp1.signum(); + let f = |t| s * self.cusp_sign(t); + let k1 = 0.2 / (b - a); + const ITP_EPS: f64 = 1e-12; + let t = solve_itp(f, a, b, ITP_EPS, 1, k1, s * rec.cusp0, s * rec.cusp1); + // TODO(robustness): If we're unlucky, there will be 3 cusps between t0 + // and t1, and the solver will land on the middle one. In that case, the + // derivative on cusp will be the opposite sign as expected. + // + // If we're even more unlucky, there is a second-order cusp, both zero + // cusp value and zero derivative. + let utan_t = self.q.eval(t).to_vec2().normalize(); + let cusp_t_minus = CUSP_EPSILON.copysign(rec.cusp0); + let cusp_t_plus = CUSP_EPSILON.copysign(rec.cusp1); + self.subdivide(rec, result, t, utan_t, cusp_t_minus, cusp_t_plus); + return; + } + // We determine the first approximation to the offset curve. + let (mut a, mut b) = self.draw_arc(rec); + let dt = (rec.t1 - rec.t0) * (1.0 / (N_LSE + 1) as f64); + // These represent t values on the source curve. + let mut ts = core::array::from_fn(|i| rec.t0 + (i + 1) as f64 * dt); + let mut c_approx = self.apply(rec, a, b); + let err_init = self.eval_err(rec, c_approx, &mut ts); + let mut err = err_init; + // Number of least-squares refinement steps. More gives a smaller + // error, but takes more time. + const N_REFINE: usize = 2; + for _ in 0..N_REFINE { + if err.err_squared <= self.tolerance * self.tolerance { + break; + } + let (a2, b2) = self.refine_least_squares(rec, a, b, &err); + let c_approx2 = self.apply(rec, a2, b2); + let err2 = self.eval_err(rec, c_approx2, &mut ts); + if err2.err_squared >= err.err_squared { + break; + } + err = err2; + (a, b) = (a2, b2); + c_approx = c_approx2; + } + if rec.depth < MAX_DEPTH && err.err_squared > self.tolerance * self.tolerance { + let SubdivisionPoint { t, utan } = self.find_subdivision_point(rec); + // TODO(robustness): if cusp is extremely near zero, then assign epsilon + // with alternate signs based on derivative of cusp. + let cusp = self.cusp_sign(t); + self.subdivide(rec, result, t, utan, cusp, cusp); + } else { + result.curve_to(c_approx.p1, c_approx.p2, c_approx.p3); + } + } + + /// Recursively subdivide. + /// + /// In the case of subdividing at a cusp, the cusp value at the subdivision point + /// is mathematically zero, but in those cases we treat it as a signed infinitesimal + /// value representing the values at t minus epsilon and t plus epsilon. + /// + /// Note that unit tangents are passed down explicitly. In the general case, they + /// are equal to the derivative (evaluated at that t value) normalized to unit + /// length, but in cases where the derivative is near-zero, they are computed more + /// robustly. + fn subdivide( + &self, + rec: &OffsetRec, + result: &mut BezPath, + t: f64, + utan_t: Vec2, + cusp_t_minus: f64, + cusp_t_plus: f64, + ) { + let rec0 = OffsetRec::new( + rec.t0, + t, + rec.utan0, + utan_t, + rec.cusp0, + cusp_t_minus, + rec.depth + 1, + ); + self.offset_rec(&rec0, result); + let rec1 = OffsetRec::new( + t, + rec.t1, + utan_t, + rec.utan1, + cusp_t_plus, + rec.cusp1, + rec.depth + 1, + ); + self.offset_rec(&rec1, result); + } + + /// Convert from (a, b) parameter space to the approximate cubic Bézier. + /// + /// The offset approximation can be considered `B(t) + d * D(t)`, where `D(t)` + /// is roughly a unit vector in the direction of the unit normal of the source + /// curve. (The word "roughly" is appropriate because transverse error may + /// cancel out normal error, resulting in a lower error than either alone). + /// The endpoints of `D(t)` must be the unit normals of the source curve, and + /// the endpoint tangents of `D(t)` must tangent to the endpoint tangents of + /// the source curve, to ensure G1 continuity. + /// + /// The (a, b) parameters refer to the magnitude of the vector from the endpoint + /// to the corresponding control point in `D(t)`, the direction being determined + /// by the unit tangent. + /// + /// When the candidate solution would lead to negative distance from the + /// endpoint to the control point, that distance is clamped to zero. Otherwise + /// such solutions should be considered invalid, and have the unpleasant + /// property of sometimes passing error tolerance checks. + fn apply(&self, rec: &OffsetRec, a: f64, b: f64) -> CubicBez { + // wondering if p0 and p3 should be in rec + // Scale factor from derivatives to displacements + let s = (1. / 3.) * (rec.t1 - rec.t0); + let p0 = self.c.eval(rec.t0) + self.d * rec.utan0.turn_90(); + let l0 = s * self.q.eval(rec.t0).to_vec2().length() + a * self.d; + let mut p1 = p0; + if l0 * rec.cusp0 > 0.0 { + p1 += l0 * rec.utan0; + } + let p3 = self.c.eval(rec.t1) + self.d * rec.utan1.turn_90(); + let mut p2 = p3; + let l1 = s * self.q.eval(rec.t1).to_vec2().length() - b * self.d; + if l1 * rec.cusp1 > 0.0 { + p2 -= l1 * rec.utan1; + } + CubicBez::new(p0, p1, p2, p3) + } + + /// Compute arc approximation. + /// + /// This is called "arc drawing" because if we just look at the delta + /// vector, it describes an arc from the initial unit normal to the final unit + /// normal, with "as smooth as possible" parametrization. This approximation + /// is not necessarily great, but is very robust, and in particular, accuracy + /// does not degrade for J shaped near-cusp source curves or when the offset + /// distance is large (with respect to the source curve arc length). + /// + /// It is a pretty good approximation overall and has very clean O(n^4) scaling. + /// Its worst performance is on curves with a large cubic component, where it + /// undershoots. The theory is that the least squares refinement improves those + /// cases. + fn draw_arc(&self, rec: &OffsetRec) -> (f64, f64) { + // possible optimization: this can probably be done with vectors + // rather than arctangent + let th = rec.utan1.cross(rec.utan0).atan2(rec.utan1.dot(rec.utan0)); + let a = (2. / 3.) / (1.0 + (0.5 * th).cos()) * 2.0 * (0.5 * th).sin(); + let b = -a; + (a, b) + } + + /// Evaluate error and also refine t values. + /// + /// Returns evaluation of error including error vectors and (squared) + /// maximum error. + /// + /// The vector of t values represents points on the source curve; the logic + /// here is a Newton step to bring those points closer to the normal ray of + /// the approximation. + fn eval_err(&self, rec: &OffsetRec, c_approx: CubicBez, ts: &mut [f64; N_LSE]) -> ErrEval { + let qa = c_approx.deriv(); + let mut err_squared = 0.0; + let mut unorms = [Vec2::ZERO; N_LSE]; + let mut err_vecs = [Vec2::ZERO; N_LSE]; + for i in 0..N_LSE { + let ta = (i + 1) as f64 * (1.0 / (N_LSE + 1) as f64); + let mut t = ts[i]; + let p = self.c.eval(t); + // Newton step to refine t value + let pa = c_approx.eval(ta); + let tana = qa.eval(ta).to_vec2(); + t += tana.dot(pa - p) / tana.dot(self.q.eval(t).to_vec2()); + t = t.max(rec.t0).min(rec.t1); + ts[i] = t; + let cusp = rec.cusp0.signum(); + let unorm = cusp * tana.normalize().turn_90(); + unorms[i] = unorm; + let p_new = self.c.eval(t) + self.d * unorm; + let err_vec = pa - p_new; + err_vecs[i] = err_vec; + let mut dist_err_squared = err_vec.length_squared(); + if !dist_err_squared.is_finite() { + // A hack to make sure we reject bad refinements + dist_err_squared = 1e12; + } + // Note: consider also incorporating angle error + err_squared = dist_err_squared.max(err_squared); + } + ErrEval { + err_squared, + unorms, + err_vecs, + } + } + + /// Refine an approximation, minimizing least squares error. + /// + /// Compute the approximation that minimizes least squares error, based on the given error + /// evaluation. + /// + /// The effectiveness of this refinement varies. Basically, if the curve has a large cubic + /// component, then the arc drawing will undershoot systematically and this refinement will + /// reduce error considerably. In other cases, it will eventually converge to a local + /// minimum, but convergence is slow. + /// + /// The `BLEND` parameter controls a tradeoff between robustness and speed of convergence. + /// In the happy case, convergence is fast and not very sensitive to this parameter. If the + /// parameter is too small, then in near-parabola cases the determinant will be small and + /// the result not numerically stable. + /// + /// A value of 1.0 for `BLEND` corresponds to essentially the Hoschek method, minimizing + /// Euclidean distance (which tends to over-anchor on the given t values). A value of 0 would + /// minimize the dot product of error wrt the normal vector, ignoring the cross product + /// component. + /// + /// A possible future direction would be to tune the parameter adaptively. + fn refine_least_squares(&self, rec: &OffsetRec, a: f64, b: f64, err: &ErrEval) -> (f64, f64) { + let mut aa = 0.0; + let mut ab = 0.0; + let mut ac = 0.0; + let mut bb = 0.0; + let mut bc = 0.0; + for i in 0..N_LSE { + let n = err.unorms[i]; + let err_vec = err.err_vecs[i]; + let c_n = err_vec.dot(n); + let c_t = err_vec.cross(n); + let a_n = A_WEIGHTS[i] * rec.utan0.dot(n); + let a_t = A_WEIGHTS[i] * rec.utan0.cross(n); + let b_n = B_WEIGHTS[i] * rec.utan1.dot(n); + let b_t = B_WEIGHTS[i] * rec.utan1.cross(n); + aa += a_n * a_n + BLEND * (a_t * a_t); + ab += a_n * b_n + BLEND * a_t * b_t; + ac += a_n * c_n + BLEND * a_t * c_t; + bb += b_n * b_n + BLEND * (b_t * b_t); + bc += b_n * c_n + BLEND * b_t * c_t; + } + let idet = 1.0 / (self.d * (aa * bb - ab * ab)); + let delta_a = idet * (ac * bb - ab * bc); + let delta_b = idet * (aa * bc - ac * ab); + (a - delta_a, b - delta_b) + } + + /// Decide where to subdivide when error is exceeded. + /// + /// For curves not containing an inflection point, subdivide at the tangent + /// bisecting the endpoint tangents. The logic is that for a near cusp in the + /// source curve, you want the subdivided sections to be approximately + /// circular arcs with progressively smaller angles. + /// + /// When there is an inflection point (or, more specifically, when the curve + /// crosses its chord), bisecting the angle can lead to very lopsided arc + /// lengths, so just subdivide by t in that case. + fn find_subdivision_point(&self, rec: &OffsetRec) -> SubdivisionPoint { + let t = 0.5 * (rec.t0 + rec.t1); + let q_t = self.q.eval(t).to_vec2(); + let x0 = rec.utan0.cross(q_t).abs(); + let x1 = rec.utan1.cross(q_t).abs(); + const SUBDIVIDE_THRESH: f64 = 0.1; + if x0 > SUBDIVIDE_THRESH * x1 && x1 > SUBDIVIDE_THRESH * x0 { + let utan = q_t.normalize(); + return SubdivisionPoint { t, utan }; + } + + // Note: do we want to track p0 & p3 in rec, to avoid repeated eval? + let chord = self.c.eval(rec.t1) - self.c.eval(rec.t0); + if chord.cross(rec.utan0) * chord.cross(rec.utan1) < 0.0 { + let tan = rec.utan0 + rec.utan1; + if let Some(subdivision) = + self.subdivide_for_tangent(rec.utan0, rec.t0, rec.t1, tan, false) + { + return subdivision; + } + } + // Curve definitely has an inflection point + // Try to subdivide based on integral of absolute curvature. + + // Tangents at recursion endpoints and inflection points. + let mut tangents: ArrayVec = ArrayVec::new(); + let mut ts: ArrayVec = ArrayVec::new(); + tangents.push(rec.utan0); + ts.push(rec.t0); + for t in self.c.inflections() { + if t > rec.t0 && t < rec.t1 { + tangents.push(self.q.eval(t).to_vec2()); + ts.push(t); + } + } + tangents.push(rec.utan1); + ts.push(rec.t1); + let mut arc_angles: ArrayVec = ArrayVec::new(); + let mut sum = 0.0; + for i in 0..tangents.len() - 1 { + let tan0 = tangents[i]; + let tan1 = tangents[i + 1]; + let th = tan0.cross(tan1).atan2(tan0.dot(tan1)); + sum += th.abs(); + arc_angles.push(th); + } + let mut target = sum * 0.5; + let mut i = 0; + while arc_angles[i].abs() < target { + target -= arc_angles[i].abs(); + i += 1; + } + let rotation = Vec2::from_angle(target.copysign(arc_angles[i])); + let base = tangents[i]; + let tan = base.rotate_scale(rotation); + let utan0 = if i == 0 { rec.utan0 } else { base.normalize() }; + self.subdivide_for_tangent(utan0, ts[i], ts[i + 1], tan, true) + .unwrap() + } + + /// Find a subdivision point, given a tangent vector. + /// + /// When subdividing by bisecting the angle (or, more generally, subdividing by + /// the L1 norm of curvature when there are inflection points), we find the + /// subdivision point by solving for the tangent matching, specifically the + /// cross-product of the tangent and the curve's derivative being zero. For + /// internal cusps, subdividing near the cusp is a good thing, but there is + /// still a robustness concern for vanishing derivative at the endpoints. + fn subdivide_for_tangent( + &self, + utan0: Vec2, + t0: f64, + t1: f64, + tan: Vec2, + force: bool, + ) -> Option { + let mut t = 0.0; + let mut n_soln = 0; + // set up quadratic equation for matching tangents + let z0 = tan.cross(self.q.p0.to_vec2()); + let z1 = tan.cross(self.q.p1.to_vec2()); + let z2 = tan.cross(self.q.p2.to_vec2()); + let c0 = z0; + let c1 = 2.0 * (z1 - z0); + let c2 = (z2 - z1) - (z1 - z0); + for root in solve_quadratic(c0, c1, c2) { + if root >= t0 && root <= t1 { + t = root; + n_soln += 1; + } + } + if n_soln != 1 { + if !force { + return None; + } + // Numerical failure, try to subdivide at cusp; we pick the + // smaller derivative. + if self.q.eval(t0).to_vec2().length_squared() + > self.q.eval(t1).to_vec2().length_squared() + { + t = t1; + } else { + t = t0; + } + } + let q = self.q.eval(t).to_vec2(); + const UTAN_EPSILON: f64 = 1e-12; + let utan = if n_soln == 1 && q.length_squared() >= UTAN_EPSILON { + q.normalize() + } else if tan.length_squared() >= UTAN_EPSILON { + // Curve has a zero-derivative cusp but angles well defined + tan.normalize() + } else { + // 180 degree U-turn, arbitrarily pick a direction. + // If we get to this point, there will probably be a failure. + utan0.turn_90() + }; + Some(SubdivisionPoint { t, utan }) + } +} + +impl OffsetRec { + #[allow(clippy::too_many_arguments)] + fn new( + t0: f64, + t1: f64, + utan0: Vec2, + utan1: Vec2, + cusp0: f64, + cusp1: f64, + depth: usize, + ) -> Self { + OffsetRec { + t0, + t1, + utan0, + utan1, + cusp0, + cusp1, + depth, + } + } +} + +/// Compute Bézier weights for evenly subdivided t values. +const fn mk_a_weights(rev: bool) -> [f64; N_LSE] { + let mut result = [0.0; N_LSE]; + let mut i = 0; + while i < N_LSE { + let t = (i + 1) as f64 / (N_LSE + 1) as f64; + let mt = 1. - t; + let ix = if rev { N_LSE - 1 - i } else { i }; + result[ix] = 3.0 * mt * t * mt; + i += 1; + } + result +} + +const A_WEIGHTS: [f64; N_LSE] = mk_a_weights(false); +const B_WEIGHTS: [f64; N_LSE] = mk_a_weights(true); + +#[cfg(test)] +mod tests { + use super::offset_cubic; + use crate::{BezPath, CubicBez, PathEl}; + + // This test tries combinations of parameters that have caused problems in the past. + #[test] + fn pathological_curves() { + let curve = CubicBez { + p0: (-1236.3746269978635, 152.17981429574826).into(), + p1: (-1175.18662093517, 108.04721798590596).into(), + p2: (-1152.142883879584, 105.76260301083356).into(), + p3: (-1151.842639804639, 105.73040758939104).into(), + }; + let offset = 3603.7267536453924; + let accuracy = 0.1; + + let mut result = BezPath::new(); + offset_cubic(curve, offset, accuracy, &mut result); + assert!(matches!(result.iter().next(), Some(PathEl::MoveTo(_)))); + + let mut result = BezPath::new(); + offset_cubic(curve, offset, accuracy, &mut result); + assert!(matches!(result.iter().next(), Some(PathEl::MoveTo(_)))); + } + + /// Cubic offset that used to trigger infinite recursion. + #[test] + fn infinite_recursion() { + const TOLERANCE: f64 = 0.1; + const OFFSET: f64 = -0.5; + let c = CubicBez::new( + (1096.2962962962963, 593.90243902439033), + (1043.6213991769548, 593.90243902439033), + (1030.4526748971193, 593.90243902439033), + (1056.7901234567901, 593.90243902439033), + ); + + let mut result = BezPath::new(); + offset_cubic(c, OFFSET, TOLERANCE, &mut result); + } + + #[test] + fn test_cubic_offset_simple_line() { + let cubic = CubicBez::new((0., 0.), (10., 0.), (20., 0.), (30., 0.)); + let mut result = BezPath::new(); + offset_cubic(cubic, 5., 1e-6, &mut result); + } +} diff --git a/vendor/kurbo/src/param_curve.rs b/vendor/kurbo/src/param_curve.rs new file mode 100644 index 0000000000..7fff046d89 --- /dev/null +++ b/vendor/kurbo/src/param_curve.rs @@ -0,0 +1,221 @@ +// Copyright 2018 the Kurbo Authors +// SPDX-License-Identifier: Apache-2.0 OR MIT + +//! A trait for curves parameterized by a scalar. + +use core::ops::Range; + +use arrayvec::ArrayVec; + +use crate::{Point, Rect, common}; + +#[cfg(not(feature = "std"))] +use crate::common::FloatFuncs; + +/// A default value for methods that take an 'accuracy' argument. +/// +/// This value is intended to be suitable for general-purpose use, such as +/// 2d graphics. +pub const DEFAULT_ACCURACY: f64 = 1e-6; + +/// A curve parameterized by a scalar. +/// +/// If the result is interpreted as a point, this represents a curve. +/// But the result can be interpreted as a vector as well. +pub trait ParamCurve: Sized { + /// Evaluate the curve at parameter `t`. + /// + /// Generally `t` is in the range [0..1]. + fn eval(&self, t: f64) -> Point; + + /// Get a subsegment of the curve for the given parameter range. + fn subsegment(&self, range: Range) -> Self; + + /// Subdivide into (roughly) halves. + #[inline] + fn subdivide(&self) -> (Self, Self) { + (self.subsegment(0.0..0.5), self.subsegment(0.5..1.0)) + } + + /// The start point. + fn start(&self) -> Point { + self.eval(0.0) + } + + /// The end point. + fn end(&self) -> Point { + self.eval(1.0) + } +} + +// TODO: I might not want to have separate traits for all these. + +/// A differentiable parameterized curve. +pub trait ParamCurveDeriv { + /// The parametric curve obtained by taking the derivative of this one. + type DerivResult: ParamCurve; + + /// The derivative of the curve. + /// + /// Note that the type of the return value is somewhat inaccurate, as + /// the derivative of a curve (mapping of param to point) is a mapping + /// of param to vector. We choose to accept this rather than have a + /// more complex type scheme. + fn deriv(&self) -> Self::DerivResult; + + /// Estimate arclength using Gaussian quadrature. + /// + /// The coefficients are assumed to cover the range (-1..1), which is + /// traditional. + #[inline] + fn gauss_arclen(&self, coeffs: &[(f64, f64)]) -> f64 { + let d = self.deriv(); + coeffs + .iter() + .map(|(wi, xi)| wi * d.eval(0.5 * (xi + 1.0)).to_vec2().hypot()) + .sum::() + * 0.5 + } +} + +/// A parameterized curve that can have its arc length measured. +pub trait ParamCurveArclen: ParamCurve { + /// The arc length of the curve. + /// + /// The result is accurate to the given accuracy (subject to + /// roundoff errors for ridiculously low values). Compute time + /// may vary with accuracy, if the curve needs to be subdivided. + fn arclen(&self, accuracy: f64) -> f64; + + /// Solve for the parameter that has the given arc length from the start. + /// + /// This implementation uses the IPT method, as provided by + /// [`common::solve_itp`]. This is as robust as bisection but + /// typically converges faster. In addition, the method takes + /// care to compute arc lengths of increasingly smaller segments + /// of the curve, as that is likely faster than repeatedly + /// computing the arc length of the segment starting at t=0. + fn inv_arclen(&self, arclen: f64, accuracy: f64) -> f64 { + if arclen <= 0.0 { + return 0.0; + } + let total_arclen = self.arclen(accuracy); + if arclen >= total_arclen { + return 1.0; + } + let mut t_last = 0.0; + let mut arclen_last = 0.0; + let epsilon = accuracy / total_arclen; + let n = 1.0 - epsilon.log2().ceil().min(0.0); + let inner_accuracy = accuracy / n; + let f = |t: f64| { + let (range, dir) = if t > t_last { + (t_last..t, 1.0) + } else { + (t..t_last, -1.0) + }; + let arc = self.subsegment(range).arclen(inner_accuracy); + arclen_last += arc * dir; + t_last = t; + arclen_last - arclen + }; + common::solve_itp(f, 0.0, 1.0, epsilon, 1, 0.2, -arclen, total_arclen - arclen) + } +} + +/// A parameterized curve that can have its signed area measured. +pub trait ParamCurveArea { + /// Compute the signed area under the curve. + /// + /// For a closed path, the signed area of the path is the sum of signed + /// areas of the segments. This is a variant of the "shoelace formula." + /// See: + /// and + /// + /// + /// This can be computed exactly for Béziers thanks to Green's theorem, + /// and also for simple curves such as circular arcs. For more exotic + /// curves, it's probably best to subdivide to cubics. We leave that + /// to the caller, which is why we don't give an accuracy param here. + fn signed_area(&self) -> f64; +} + +/// The nearest position on a curve to some point. +/// +/// This is returned by [`ParamCurveNearest::nearest`] +#[derive(Debug, Clone, Copy)] +pub struct Nearest { + /// The square of the distance from the nearest position on the curve + /// to the given point. + pub distance_sq: f64, + /// The position on the curve of the nearest point, as a parameter. + /// + /// To resolve this to a [`Point`], use [`ParamCurve::eval`]. + pub t: f64, +} + +/// A parameterized curve that reports the nearest point. +pub trait ParamCurveNearest { + /// Find the position on the curve that is nearest to the given point. + /// + /// This returns a [`Nearest`] struct that contains information about + /// the position. + fn nearest(&self, p: Point, accuracy: f64) -> Nearest; +} + +/// A parameterized curve that reports its curvature. +pub trait ParamCurveCurvature: ParamCurveDeriv +where + Self::DerivResult: ParamCurveDeriv, +{ + /// Compute the signed curvature at parameter `t`. + #[inline] + fn curvature(&self, t: f64) -> f64 { + let deriv = self.deriv(); + let deriv2 = deriv.deriv(); + let d = deriv.eval(t).to_vec2(); + let d2 = deriv2.eval(t).to_vec2(); + // TODO: What's the convention for sign? I think it should match signed + // area - a positive area curve should have positive curvature. + d2.cross(d) * d.hypot2().powf(-1.5) + } +} + +/// The maximum number of extrema that can be reported in the `ParamCurveExtrema` trait. +/// +/// This is 4 to support cubic Béziers. If other curves are used, they should be +/// subdivided to limit the number of extrema. +pub const MAX_EXTREMA: usize = 4; + +/// A parameterized curve that reports its extrema. +pub trait ParamCurveExtrema: ParamCurve { + /// Compute the extrema of the curve. + /// + /// Only extrema within the interior of the curve count. + /// At most four extrema can be reported, which is sufficient for + /// cubic Béziers. + /// + /// The extrema should be reported in increasing parameter order. + fn extrema(&self) -> ArrayVec; + + /// Return parameter ranges, each of which is monotonic within the range. + fn extrema_ranges(&self) -> ArrayVec, { MAX_EXTREMA + 1 }> { + let mut result = ArrayVec::new(); + let mut t0 = 0.0; + for t in self.extrema() { + result.push(t0..t); + t0 = t; + } + result.push(t0..1.0); + result + } + + /// The smallest rectangle that encloses the curve in the range (0..1). + fn bounding_box(&self) -> Rect { + let mut bbox = Rect::from_points(self.start(), self.end()); + for t in self.extrema() { + bbox = bbox.union_pt(self.eval(t)); + } + bbox + } +} diff --git a/vendor/kurbo/src/point.rs b/vendor/kurbo/src/point.rs new file mode 100644 index 0000000000..fd3045d925 --- /dev/null +++ b/vendor/kurbo/src/point.rs @@ -0,0 +1,398 @@ +// Copyright 2019 the Kurbo Authors +// SPDX-License-Identifier: Apache-2.0 OR MIT + +//! A 2D point. + +use core::fmt; +use core::ops::{Add, AddAssign, Sub, SubAssign}; + +use crate::common::FloatExt; +use crate::{Axis, Vec2}; + +#[cfg(not(feature = "std"))] +use crate::common::FloatFuncs; + +/// A 2D point. +/// +/// This type represents a point in 2D space. It has the same layout as [`Vec2`], but +/// its meaning is different: `Vec2` represents a change in location (for example velocity). +/// +/// In general, `kurbo` overloads math operators where it makes sense, for example implementing +/// `Affine * Point` as the point under the affine transformation. However `Point + Point` and +/// `f64 * Point` are not implemented, because the operations do not make geometric sense. If you +/// need to apply these operations, then 1) check what you're doing makes geometric sense, then 2) +/// use [`Point::to_vec2`] to convert the point to a `Vec2`. +#[derive(Clone, Copy, Default, PartialEq)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +pub struct Point { + /// The x coordinate. + pub x: f64, + /// The y coordinate. + pub y: f64, +} + +impl Point { + /// The point (0, 0). + pub const ZERO: Point = Point::new(0., 0.); + + /// The point at the origin; (0, 0). + pub const ORIGIN: Point = Point::new(0., 0.); + + /// Create a new `Point` with the provided `x` and `y` coordinates. + #[inline(always)] + pub const fn new(x: f64, y: f64) -> Self { + Point { x, y } + } + + /// Convert this point into a `Vec2`. + #[inline(always)] + pub const fn to_vec2(self) -> Vec2 { + Vec2::new(self.x, self.y) + } + + /// Linearly interpolate between two points. + #[inline] + pub fn lerp(self, other: Point, t: f64) -> Point { + self.to_vec2().lerp(other.to_vec2(), t).to_point() + } + + /// Determine the midpoint of two points. + #[inline] + pub const fn midpoint(self, other: Point) -> Point { + Point::new(0.5 * (self.x + other.x), 0.5 * (self.y + other.y)) + } + + /// Euclidean distance. + /// + /// See [`Vec2::hypot`] for the same operation on [`Vec2`]. + #[inline] + pub fn distance(self, other: Point) -> f64 { + (self - other).hypot() + } + + /// Squared Euclidean distance. + /// + /// See [`Vec2::hypot2`] for the same operation on [`Vec2`]. + #[inline] + pub fn distance_squared(self, other: Point) -> f64 { + (self - other).hypot2() + } + + /// Returns a new `Point`, with `x` and `y` [rounded] to the nearest integer. + /// + /// # Examples + /// + /// ``` + /// use kurbo::Point; + /// let a = Point::new(3.3, 3.6).round(); + /// let b = Point::new(3.0, -3.1).round(); + /// assert_eq!(a.x, 3.0); + /// assert_eq!(a.y, 4.0); + /// assert_eq!(b.x, 3.0); + /// assert_eq!(b.y, -3.0); + /// ``` + /// + /// [rounded]: f64::round + #[inline] + pub fn round(self) -> Point { + Point::new(self.x.round(), self.y.round()) + } + + /// Returns a new `Point`, + /// with `x` and `y` [rounded up] to the nearest integer, + /// unless they are already an integer. + /// + /// # Examples + /// + /// ``` + /// use kurbo::Point; + /// let a = Point::new(3.3, 3.6).ceil(); + /// let b = Point::new(3.0, -3.1).ceil(); + /// assert_eq!(a.x, 4.0); + /// assert_eq!(a.y, 4.0); + /// assert_eq!(b.x, 3.0); + /// assert_eq!(b.y, -3.0); + /// ``` + /// + /// [rounded up]: f64::ceil + #[inline] + pub fn ceil(self) -> Point { + Point::new(self.x.ceil(), self.y.ceil()) + } + + /// Returns a new `Point`, + /// with `x` and `y` [rounded down] to the nearest integer, + /// unless they are already an integer. + /// + /// # Examples + /// + /// ``` + /// use kurbo::Point; + /// let a = Point::new(3.3, 3.6).floor(); + /// let b = Point::new(3.0, -3.1).floor(); + /// assert_eq!(a.x, 3.0); + /// assert_eq!(a.y, 3.0); + /// assert_eq!(b.x, 3.0); + /// assert_eq!(b.y, -4.0); + /// ``` + /// + /// [rounded down]: f64::floor + #[inline] + pub fn floor(self) -> Point { + Point::new(self.x.floor(), self.y.floor()) + } + + /// Returns a new `Point`, + /// with `x` and `y` [rounded away] from zero to the nearest integer, + /// unless they are already an integer. + /// + /// # Examples + /// + /// ``` + /// use kurbo::Point; + /// let a = Point::new(3.3, 3.6).expand(); + /// let b = Point::new(3.0, -3.1).expand(); + /// assert_eq!(a.x, 4.0); + /// assert_eq!(a.y, 4.0); + /// assert_eq!(b.x, 3.0); + /// assert_eq!(b.y, -4.0); + /// ``` + /// + /// [rounded away]: FloatExt::expand + #[inline] + pub fn expand(self) -> Point { + Point::new(self.x.expand(), self.y.expand()) + } + + /// Returns a new `Point`, + /// with `x` and `y` [rounded towards] zero to the nearest integer, + /// unless they are already an integer. + /// + /// # Examples + /// + /// ``` + /// use kurbo::Point; + /// let a = Point::new(3.3, 3.6).trunc(); + /// let b = Point::new(3.0, -3.1).trunc(); + /// assert_eq!(a.x, 3.0); + /// assert_eq!(a.y, 3.0); + /// assert_eq!(b.x, 3.0); + /// assert_eq!(b.y, -3.0); + /// ``` + /// + /// [rounded towards]: f64::trunc + #[inline] + pub fn trunc(self) -> Point { + Point::new(self.x.trunc(), self.y.trunc()) + } + + /// Is this point [finite]? + /// + /// [finite]: f64::is_finite + #[inline] + pub const fn is_finite(self) -> bool { + self.x.is_finite() && self.y.is_finite() + } + + /// Is this point [`NaN`]? + /// + /// [`NaN`]: f64::is_nan + #[inline] + pub const fn is_nan(self) -> bool { + self.x.is_nan() || self.y.is_nan() + } + + /// Get the member matching the given axis. + #[inline] + pub const fn get_coord(self, axis: Axis) -> f64 { + match axis { + Axis::Horizontal => self.x, + Axis::Vertical => self.y, + } + } + + /// Get a mutable reference to the member matching the given axis. + #[inline] + pub const fn get_coord_mut(&mut self, axis: Axis) -> &mut f64 { + match axis { + Axis::Horizontal => &mut self.x, + Axis::Vertical => &mut self.y, + } + } + + /// Set the member matching the given axis to the given value. + #[inline] + pub const fn set_coord(&mut self, axis: Axis, value: f64) { + match axis { + Axis::Horizontal => self.x = value, + Axis::Vertical => self.y = value, + } + } +} + +impl From<(f32, f32)> for Point { + #[inline(always)] + fn from(v: (f32, f32)) -> Point { + Point { + x: v.0 as f64, + y: v.1 as f64, + } + } +} + +impl From<(f64, f64)> for Point { + #[inline(always)] + fn from(v: (f64, f64)) -> Point { + Point { x: v.0, y: v.1 } + } +} + +impl From for (f64, f64) { + #[inline(always)] + fn from(v: Point) -> (f64, f64) { + (v.x, v.y) + } +} + +impl Add for Point { + type Output = Point; + + #[inline] + fn add(self, other: Vec2) -> Self { + Point::new(self.x + other.x, self.y + other.y) + } +} + +impl AddAssign for Point { + #[inline] + fn add_assign(&mut self, other: Vec2) { + *self = Point::new(self.x + other.x, self.y + other.y); + } +} + +impl Sub for Point { + type Output = Point; + + #[inline] + fn sub(self, other: Vec2) -> Self { + Point::new(self.x - other.x, self.y - other.y) + } +} + +impl SubAssign for Point { + #[inline] + fn sub_assign(&mut self, other: Vec2) { + *self = Point::new(self.x - other.x, self.y - other.y); + } +} + +impl Add<(f64, f64)> for Point { + type Output = Point; + + #[inline] + fn add(self, (x, y): (f64, f64)) -> Self { + Point::new(self.x + x, self.y + y) + } +} + +impl AddAssign<(f64, f64)> for Point { + #[inline] + fn add_assign(&mut self, (x, y): (f64, f64)) { + *self = Point::new(self.x + x, self.y + y); + } +} + +impl Sub<(f64, f64)> for Point { + type Output = Point; + + #[inline] + fn sub(self, (x, y): (f64, f64)) -> Self { + Point::new(self.x - x, self.y - y) + } +} + +impl SubAssign<(f64, f64)> for Point { + #[inline] + fn sub_assign(&mut self, (x, y): (f64, f64)) { + *self = Point::new(self.x - x, self.y - y); + } +} + +impl Sub for Point { + type Output = Vec2; + + #[inline] + fn sub(self, other: Point) -> Vec2 { + Vec2::new(self.x - other.x, self.y - other.y) + } +} + +impl fmt::Debug for Point { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "({:?}, {:?})", self.x, self.y) + } +} + +impl fmt::Display for Point { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + write!(formatter, "(")?; + fmt::Display::fmt(&self.x, formatter)?; + write!(formatter, ", ")?; + fmt::Display::fmt(&self.y, formatter)?; + write!(formatter, ")") + } +} + +#[cfg(feature = "mint")] +impl From for mint::Point2 { + #[inline(always)] + fn from(p: Point) -> mint::Point2 { + mint::Point2 { x: p.x, y: p.y } + } +} + +#[cfg(feature = "mint")] +impl From> for Point { + #[inline(always)] + fn from(p: mint::Point2) -> Point { + Point { x: p.x, y: p.y } + } +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn point_arithmetic() { + assert_eq!( + Point::new(0., 0.) - Vec2::new(10., 0.), + Point::new(-10., 0.) + ); + assert_eq!( + Point::new(0., 0.) - Point::new(-5., 101.), + Vec2::new(5., -101.) + ); + } + + #[test] + #[allow(clippy::float_cmp)] + fn distance() { + let p1 = Point::new(0., 10.); + let p2 = Point::new(0., 5.); + assert_eq!(p1.distance(p2), 5.); + + let p1 = Point::new(-11., 1.); + let p2 = Point::new(-7., -2.); + assert_eq!(p1.distance(p2), 5.); + } + + #[test] + fn display() { + let p = Point::new(0.12345, 9.87654); + assert_eq!(format!("{p}"), "(0.12345, 9.87654)"); + + let p = Point::new(0.12345, 9.87654); + assert_eq!(format!("{p:.2}"), "(0.12, 9.88)"); + } +} diff --git a/vendor/kurbo/src/quadbez.rs b/vendor/kurbo/src/quadbez.rs new file mode 100644 index 0000000000..5a68283a2e --- /dev/null +++ b/vendor/kurbo/src/quadbez.rs @@ -0,0 +1,594 @@ +// Copyright 2018 the Kurbo Authors +// SPDX-License-Identifier: Apache-2.0 OR MIT + +//! Quadratic Bézier segments. + +use core::ops::{Mul, Range}; + +use arrayvec::ArrayVec; + +use crate::MAX_EXTREMA; +use crate::common::{solve_cubic, solve_quadratic}; +use crate::{ + Affine, CubicBez, Line, Nearest, ParamCurve, ParamCurveArclen, ParamCurveArea, + ParamCurveCurvature, ParamCurveDeriv, ParamCurveExtrema, ParamCurveNearest, PathEl, Point, + Rect, Shape, +}; + +#[cfg(not(feature = "std"))] +use crate::common::FloatFuncs; + +/// A single quadratic Bézier segment. +#[derive(Clone, Copy, Debug, PartialEq)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +#[allow(missing_docs)] +pub struct QuadBez { + pub p0: Point, + pub p1: Point, + pub p2: Point, +} + +impl QuadBez { + /// Create a new quadratic Bézier segment. + #[inline] + pub fn new>(p0: V, p1: V, p2: V) -> QuadBez { + QuadBez { + p0: p0.into(), + p1: p1.into(), + p2: p2.into(), + } + } + + /// Raise the order by 1. + /// + /// Returns a cubic Bézier segment that exactly represents this quadratic. + #[inline] + pub fn raise(&self) -> CubicBez { + CubicBez::new( + self.p0, + self.p0 + (2.0 / 3.0) * (self.p1 - self.p0), + self.p2 + (2.0 / 3.0) * (self.p1 - self.p2), + self.p2, + ) + } + + /// Estimate the number of subdivisions for flattening. + pub(crate) fn estimate_subdiv(&self, sqrt_tol: f64) -> FlattenParams { + // Determine transformation to $y = x^2$ parabola. + let d01 = self.p1 - self.p0; + let d12 = self.p2 - self.p1; + let dd = d01 - d12; + let cross = (self.p2 - self.p0).cross(dd); + let x0 = d01.dot(dd) * cross.recip(); + let x2 = d12.dot(dd) * cross.recip(); + let scale = (cross / (dd.hypot() * (x2 - x0))).abs(); + + // Compute number of subdivisions needed. + let a0 = approx_parabola_integral(x0); + let a2 = approx_parabola_integral(x2); + let val = if scale.is_finite() { + let da = (a2 - a0).abs(); + let sqrt_scale = scale.sqrt(); + if x0.signum() == x2.signum() { + da * sqrt_scale + } else { + // Handle cusp case (segment contains curvature maximum) + let xmin = sqrt_tol / sqrt_scale; + sqrt_tol * da / approx_parabola_integral(xmin) + } + } else { + 0.0 + }; + let u0 = approx_parabola_inv_integral(a0); + let u2 = approx_parabola_inv_integral(a2); + let uscale = (u2 - u0).recip(); + FlattenParams { + a0, + a2, + u0, + uscale, + val, + } + } + + // Maps a value from 0..1 to 0..1. + pub(crate) fn determine_subdiv_t(&self, params: &FlattenParams, x: f64) -> f64 { + let a = params.a0 + (params.a2 - params.a0) * x; + let u = approx_parabola_inv_integral(a); + (u - params.u0) * params.uscale + } + + /// Is this quadratic Bezier curve finite? + #[inline] + pub const fn is_finite(&self) -> bool { + self.p0.is_finite() && self.p1.is_finite() && self.p2.is_finite() + } + + /// Is this quadratic Bezier curve NaN? + #[inline] + pub const fn is_nan(&self) -> bool { + self.p0.is_nan() || self.p1.is_nan() || self.p2.is_nan() + } + + /// Finds the value of `t` for which `self.eval(t)` is about `y`. + /// + /// Assumes that this segment is monotonic in `y` and that it crosses + /// the height `y`. (Under these assumptions, there is a unique answer.) + pub(crate) fn solve_monotonic_for_y(&self, y: f64) -> f64 { + let start = self.start(); + let end = self.end(); + + debug_assert!(start.y.min(end.y) <= y && y <= start.y.max(end.y)); + let a = end.y - 2.0 * self.p1.y + start.y; + let b = 2.0 * (self.p1.y - start.y); + let c = start.y - y; + + for t in solve_quadratic(c, b, a) { + if (0.0..=1.0).contains(&t) { + return t; + } + } + + // Even though we asserted that our y range contains `y`, it's possible + // that we failed to find a solution numerically. (For example, rounding + // of a, b, or c might have pushed the root outside of [0.0, 1.0].) + // If we failed to find a solution, the real solution should be close + // to one of the endpoints. So just find whichever endpoint was closer. + if (start.y - y).abs() <= (end.y - y).abs() { + 0.0 + } else { + 1.0 + } + } +} + +/// An iterator for quadratic beziers. +pub struct QuadBezIter { + quad: QuadBez, + ix: usize, +} + +impl Shape for QuadBez { + type PathElementsIter<'iter> = QuadBezIter; + + #[inline] + fn path_elements(&self, _tolerance: f64) -> QuadBezIter { + QuadBezIter { quad: *self, ix: 0 } + } + + fn area(&self) -> f64 { + 0.0 + } + + #[inline] + fn perimeter(&self, accuracy: f64) -> f64 { + self.arclen(accuracy) + } + + fn winding(&self, _pt: Point) -> i32 { + 0 + } + + #[inline] + fn bounding_box(&self) -> Rect { + ParamCurveExtrema::bounding_box(self) + } +} + +impl Iterator for QuadBezIter { + type Item = PathEl; + + fn next(&mut self) -> Option { + self.ix += 1; + match self.ix { + 1 => Some(PathEl::MoveTo(self.quad.p0)), + 2 => Some(PathEl::QuadTo(self.quad.p1, self.quad.p2)), + _ => None, + } + } +} + +pub(crate) struct FlattenParams { + a0: f64, + a2: f64, + u0: f64, + uscale: f64, + /// The number of `subdivisions * 2 * sqrt_tol`. + pub(crate) val: f64, +} + +/// An approximation to $\int (1 + 4x^2) ^ -0.25 dx$ +/// +/// This is used for flattening curves. +fn approx_parabola_integral(x: f64) -> f64 { + const D: f64 = 0.67; + x / (1.0 - D + (D.powi(4) + 0.25 * x * x).sqrt().sqrt()) +} + +/// An approximation to the inverse parabola integral. +fn approx_parabola_inv_integral(x: f64) -> f64 { + const B: f64 = 0.39; + x * (1.0 - B + (B * B + 0.25 * x * x).sqrt()) +} + +impl ParamCurve for QuadBez { + #[inline] + fn eval(&self, t: f64) -> Point { + let mt = 1.0 - t; + (self.p0.to_vec2() * (mt * mt) + + (self.p1.to_vec2() * (mt * 2.0) + self.p2.to_vec2() * t) * t) + .to_point() + } + + fn subsegment(&self, range: Range) -> QuadBez { + let (t0, t1) = (range.start, range.end); + let p0 = self.eval(t0); + let p2 = self.eval(t1); + let p1 = p0 + (self.p1 - self.p0).lerp(self.p2 - self.p1, t0) * (t1 - t0); + QuadBez { p0, p1, p2 } + } + + /// Subdivide into halves, using de Casteljau. + #[inline] + fn subdivide(&self) -> (QuadBez, QuadBez) { + let pm = self.eval(0.5); + ( + QuadBez::new(self.p0, self.p0.midpoint(self.p1), pm), + QuadBez::new(pm, self.p1.midpoint(self.p2), self.p2), + ) + } + + #[inline] + fn start(&self) -> Point { + self.p0 + } + + #[inline] + fn end(&self) -> Point { + self.p2 + } +} + +impl ParamCurveDeriv for QuadBez { + type DerivResult = Line; + + #[inline] + fn deriv(&self) -> Line { + Line::new( + (2.0 * (self.p1.to_vec2() - self.p0.to_vec2())).to_point(), + (2.0 * (self.p2.to_vec2() - self.p1.to_vec2())).to_point(), + ) + } +} + +impl ParamCurveArclen for QuadBez { + /// Arclength of a quadratic Bézier segment. + /// + /// This computation is based on an analytical formula. Since that formula suffers + /// from numerical instability when the curve is very close to a straight line, we + /// detect that case and fall back to Legendre-Gauss quadrature. + /// + /// Accuracy should be better than 1e-13 over the entire range. + /// + /// Adapted from + /// with permission. + fn arclen(&self, _accuracy: f64) -> f64 { + let d2 = self.p0.to_vec2() - 2.0 * self.p1.to_vec2() + self.p2.to_vec2(); + let a = d2.hypot2(); + let d1 = self.p1 - self.p0; + let c = d1.hypot2(); + if a < 5e-4 * c { + // This case happens for nearly straight Béziers. + // + // Calculate arclength using Legendre-Gauss quadrature using formula from Behdad + // in https://github.com/Pomax/BezierInfo-2/issues/77 + let v0 = (-0.492943519233745 * self.p0.to_vec2() + + 0.430331482911935 * self.p1.to_vec2() + + 0.0626120363218102 * self.p2.to_vec2()) + .hypot(); + let v1 = ((self.p2 - self.p0) * 0.4444444444444444).hypot(); + let v2 = (-0.0626120363218102 * self.p0.to_vec2() + - 0.430331482911935 * self.p1.to_vec2() + + 0.492943519233745 * self.p2.to_vec2()) + .hypot(); + return v0 + v1 + v2; + } + let b = 2.0 * d2.dot(d1); + + let sabc = (a + b + c).sqrt(); + let a2 = a.powf(-0.5); + let a32 = a2.powi(3); + let c2 = 2.0 * c.sqrt(); + let ba_c2 = b * a2 + c2; + + let v0 = 0.25 * a2 * a2 * b * (2.0 * sabc - c2) + sabc; + // TODO: justify and fine-tune this exact constant. + // The factor of a2 here is a little arbitrary: we really want + // to test whether ba_c2 is small, but it's also important for + // this comparison to be scale-invariant. We chose a2 (instead of, + // for example, c2 on the rhs) because it's unchanged under + // reversing the parametrization. + if ba_c2 * a2 < 1e-13 { + // This case happens for Béziers with a sharp kink. + v0 + } else { + v0 + 0.25 + * a32 + * (4.0 * c * a - b * b) + * (((2.0 * a + b) * a2 + 2.0 * sabc) / ba_c2).ln() + } + } +} + +impl ParamCurveArea for QuadBez { + #[inline] + fn signed_area(&self) -> f64 { + (self.p0.x * (2.0 * self.p1.y + self.p2.y) + 2.0 * self.p1.x * (self.p2.y - self.p0.y) + - self.p2.x * (self.p0.y + 2.0 * self.p1.y)) + * (1.0 / 6.0) + } +} + +impl ParamCurveNearest for QuadBez { + /// Find the nearest point, using analytical algorithm based on cubic root finding. + fn nearest(&self, p: Point, _accuracy: f64) -> Nearest { + fn eval_t(p: Point, t_best: &mut f64, r_best: &mut Option, t: f64, p0: Point) { + let r = (p0 - p).hypot2(); + if r_best.map(|r_best| r < r_best).unwrap_or(true) { + *r_best = Some(r); + *t_best = t; + } + } + fn try_t( + q: &QuadBez, + p: Point, + t_best: &mut f64, + r_best: &mut Option, + t: f64, + ) -> bool { + if !(0.0..=1.0).contains(&t) { + return true; + } + eval_t(p, t_best, r_best, t, q.eval(t)); + false + } + let d0 = self.p1 - self.p0; + let d1 = self.p0.to_vec2() + self.p2.to_vec2() - 2.0 * self.p1.to_vec2(); + let d = self.p0 - p; + let c0 = d.dot(d0); + let c1 = 2.0 * d0.hypot2() + d.dot(d1); + let c2 = 3.0 * d1.dot(d0); + let c3 = d1.hypot2(); + let roots = solve_cubic(c0, c1, c2, c3); + let mut r_best = None; + let mut t_best = 0.0; + let mut need_ends = false; + if roots.is_empty() { + need_ends = true; + } + for &t in &roots { + need_ends |= try_t(self, p, &mut t_best, &mut r_best, t); + } + if need_ends { + eval_t(p, &mut t_best, &mut r_best, 0.0, self.p0); + eval_t(p, &mut t_best, &mut r_best, 1.0, self.p2); + } + + Nearest { + t: t_best, + distance_sq: r_best.unwrap(), + } + } +} + +impl ParamCurveCurvature for QuadBez {} + +impl ParamCurveExtrema for QuadBez { + fn extrema(&self) -> ArrayVec { + let mut result = ArrayVec::new(); + let d0 = self.p1 - self.p0; + let d1 = self.p2 - self.p1; + let dd = d1 - d0; + if dd.x != 0.0 { + let t = -d0.x / dd.x; + if t > 0.0 && t < 1.0 { + result.push(t); + } + } + if dd.y != 0.0 { + let t = -d0.y / dd.y; + if t > 0.0 && t < 1.0 { + result.push(t); + if result.len() == 2 && result[0] > t { + result.swap(0, 1); + } + } + } + result + } +} + +impl Mul for Affine { + type Output = QuadBez; + + #[inline] + fn mul(self, other: QuadBez) -> QuadBez { + QuadBez { + p0: self * other.p0, + p1: self * other.p1, + p2: self * other.p2, + } + } +} + +#[cfg(test)] +mod tests { + use crate::{ + Affine, Nearest, ParamCurve, ParamCurveArclen, ParamCurveArea, ParamCurveDeriv, + ParamCurveExtrema, ParamCurveNearest, Point, QuadBez, + }; + + fn assert_near(p0: Point, p1: Point, epsilon: f64) { + assert!((p1 - p0).hypot() < epsilon, "{p0:?} != {p1:?}"); + } + + #[test] + fn quadbez_deriv() { + let q = QuadBez::new((0.0, 0.0), (0.0, 0.5), (1.0, 1.0)); + let deriv = q.deriv(); + + let n = 10; + for i in 0..=n { + let t = (i as f64) * (n as f64).recip(); + let delta = 1e-6; + let p = q.eval(t); + let p1 = q.eval(t + delta); + let d_approx = (p1 - p) * delta.recip(); + let d = deriv.eval(t).to_vec2(); + assert!((d - d_approx).hypot() < delta * 2.0); + } + } + + #[test] + fn quadbez_arclen() { + let q = QuadBez::new((0.0, 0.0), (0.0, 0.5), (1.0, 1.0)); + let true_arclen = 0.5 * 5.0f64.sqrt() + 0.25 * (2.0 + 5.0f64.sqrt()).ln(); + for i in 0..12 { + let accuracy = 0.1f64.powi(i); + let est = q.arclen(accuracy); + let error = est - true_arclen; + assert!(error.abs() < accuracy, "{est} != {true_arclen}"); + } + } + + #[test] + fn quadbez_arclen_pathological() { + let q = QuadBez::new((-1.0, 0.0), (1.03, 0.0), (1.0, 0.0)); + let true_arclen = 2.0008737864167325; // A rough empirical calculation + let accuracy = 1e-11; + let est = q.arclen(accuracy); + assert!( + (est - true_arclen).abs() < accuracy, + "{est} != {true_arclen}" + ); + } + + #[test] + fn quadbez_subsegment() { + let q = QuadBez::new((3.1, 4.1), (5.9, 2.6), (5.3, 5.8)); + let t0 = 0.1; + let t1 = 0.8; + let qs = q.subsegment(t0..t1); + let epsilon = 1e-12; + let n = 10; + for i in 0..=n { + let t = (i as f64) * (n as f64).recip(); + let ts = t0 + t * (t1 - t0); + assert_near(q.eval(ts), qs.eval(t), epsilon); + } + } + + #[test] + fn quadbez_raise() { + let q = QuadBez::new((3.1, 4.1), (5.9, 2.6), (5.3, 5.8)); + let c = q.raise(); + let qd = q.deriv(); + let cd = c.deriv(); + let epsilon = 1e-12; + let n = 10; + for i in 0..=n { + let t = (i as f64) * (n as f64).recip(); + assert_near(q.eval(t), c.eval(t), epsilon); + assert_near(qd.eval(t), cd.eval(t), epsilon); + } + } + + #[test] + fn quadbez_signed_area() { + // y = 1 - x^2 + let q = QuadBez::new((1.0, 0.0), (0.5, 1.0), (0.0, 1.0)); + let epsilon = 1e-12; + assert!((q.signed_area() - 2.0 / 3.0).abs() < epsilon); + assert!(((Affine::rotate(0.5) * q).signed_area() - 2.0 / 3.0).abs() < epsilon); + assert!(((Affine::translate((0.0, 1.0)) * q).signed_area() - 3.5 / 3.0).abs() < epsilon); + assert!(((Affine::translate((1.0, 0.0)) * q).signed_area() - 3.5 / 3.0).abs() < epsilon); + } + + fn verify(result: Nearest, expected: f64) { + assert!( + (result.t - expected).abs() < 1e-6, + "got {result:?} expected {expected}" + ); + } + + #[test] + fn quadbez_nearest() { + // y = x^2 + let q = QuadBez::new((-1.0, 1.0), (0.0, -1.0), (1.0, 1.0)); + verify(q.nearest((0.0, 0.0).into(), 1e-3), 0.5); + verify(q.nearest((0.0, 0.1).into(), 1e-3), 0.5); + verify(q.nearest((0.0, -0.1).into(), 1e-3), 0.5); + verify(q.nearest((0.5, 0.25).into(), 1e-3), 0.75); + verify(q.nearest((1.0, 1.0).into(), 1e-3), 1.0); + verify(q.nearest((1.1, 1.1).into(), 1e-3), 1.0); + verify(q.nearest((-1.1, 1.1).into(), 1e-3), 0.0); + let a = Affine::rotate(0.5); + verify((a * q).nearest(a * Point::new(0.5, 0.25), 1e-3), 0.75); + } + + // This test exposes a degenerate case in the solver used internally + // by the "nearest" calculation - the cubic term is zero. + #[test] + fn quadbez_nearest_low_order() { + let q = QuadBez::new((-1.0, 0.0), (0.0, 0.0), (1.0, 0.0)); + + verify(q.nearest((0.0, 0.0).into(), 1e-3), 0.5); + verify(q.nearest((0.0, 1.0).into(), 1e-3), 0.5); + } + + #[test] + fn quadbez_nearest_rounding_panic() { + let quad = QuadBez::new( + (-1.0394736842105263, 0.0), + (0.8210526315789474, -1.511111111111111), + (0.0, 1.9333333333333333), + ); + let test = Point::new(-1.7976931348623157e308, 0.8571428571428571); + // accuracy ignored + let _res = quad.nearest(test, 1e-6); + // if we got here then we didn't panic + } + + #[test] + fn quadbez_extrema() { + // y = x^2 + let q = QuadBez::new((-1.0, 1.0), (0.0, -1.0), (1.0, 1.0)); + let extrema = q.extrema(); + assert_eq!(extrema.len(), 1); + assert!((extrema[0] - 0.5).abs() < 1e-6); + + let q = QuadBez::new((0.0, 0.5), (1.0, 1.0), (0.5, 0.0)); + let extrema = q.extrema(); + assert_eq!(extrema.len(), 2); + assert!((extrema[0] - 1.0 / 3.0).abs() < 1e-6); + assert!((extrema[1] - 2.0 / 3.0).abs() < 1e-6); + + // Reverse direction + let q = QuadBez::new((0.5, 0.0), (1.0, 1.0), (0.0, 0.5)); + let extrema = q.extrema(); + assert_eq!(extrema.len(), 2); + assert!((extrema[0] - 1.0 / 3.0).abs() < 1e-6); + assert!((extrema[1] - 2.0 / 3.0).abs() < 1e-6); + } + + // A regression test for #477: the approximate-linearity test for + // using the analytic solution needs to be scale-invariant. + #[test] + fn perimeter_not_nan() { + let q = QuadBez::new((2685., -1251.), (2253., -1303.), (2253., -1303.)); + + let len = q.arclen(crate::DEFAULT_ACCURACY); + assert!(len.is_finite()); + } +} diff --git a/vendor/kurbo/src/quadspline.rs b/vendor/kurbo/src/quadspline.rs new file mode 100644 index 0000000000..51b823ef4d --- /dev/null +++ b/vendor/kurbo/src/quadspline.rs @@ -0,0 +1,130 @@ +// Copyright 2021 the Kurbo Authors +// SPDX-License-Identifier: Apache-2.0 OR MIT + +//! Quadratic Bézier splines. +use crate::Point; + +use crate::QuadBez; +use alloc::vec::Vec; + +/// A quadratic Bézier spline in [B-spline](https://en.wikipedia.org/wiki/B-spline) format. +#[derive(Clone, Debug, PartialEq)] +pub struct QuadSpline(Vec); + +impl QuadSpline { + /// Construct a new `QuadSpline` from an array of [`Point`]s. + #[inline(always)] + pub fn new(points: Vec) -> Self { + Self(points) + } + + /// Return the spline's control [`Point`]s. + #[inline(always)] + pub fn points(&self) -> &[Point] { + &self.0 + } + + /// Return an iterator over the implied [`QuadBez`] sequence. + /// + /// The returned quads are guaranteed to be G1 continuous. + #[inline(always)] + pub fn to_quads(&self) -> impl Iterator + '_ { + ToQuadBez { + idx: 0, + points: &self.0, + } + } +} + +struct ToQuadBez<'a> { + idx: usize, + points: &'a Vec, +} + +impl Iterator for ToQuadBez<'_> { + type Item = QuadBez; + + fn next(&mut self) -> Option { + let [mut p0, p1, mut p2]: [Point; 3] = + self.points.get(self.idx..=self.idx + 2)?.try_into().ok()?; + + if self.idx != 0 { + p0 = p0.midpoint(p1); + } + if self.idx + 2 < self.points.len() - 1 { + p2 = p1.midpoint(p2); + } + + self.idx += 1; + + Some(QuadBez { p0, p1, p2 }) + } +} + +#[cfg(test)] +mod tests { + use crate::{Point, QuadBez, QuadSpline}; + + #[test] + fn no_points_no_quads() { + assert!(QuadSpline::new(Vec::new()).to_quads().next().is_none()); + } + + #[test] + fn one_point_no_quads() { + assert!( + QuadSpline::new(vec![Point::new(1.0, 1.0)]) + .to_quads() + .next() + .is_none() + ); + } + + #[test] + fn two_points_no_quads() { + assert!( + QuadSpline::new(vec![Point::new(1.0, 1.0), Point::new(1.0, 1.0)]) + .to_quads() + .next() + .is_none() + ); + } + + #[test] + fn three_points_same_quad() { + let p0 = Point::new(1.0, 1.0); + let p1 = Point::new(2.0, 2.0); + let p2 = Point::new(3.0, 3.0); + assert_eq!( + vec![QuadBez { p0, p1, p2 }], + QuadSpline::new(vec![p0, p1, p2]) + .to_quads() + .collect::>() + ); + } + + #[test] + fn four_points_implicit_on_curve() { + let p0 = Point::new(1.0, 1.0); + let p1 = Point::new(3.0, 3.0); + let p2 = Point::new(5.0, 5.0); + let p3 = Point::new(8.0, 8.0); + assert_eq!( + vec![ + QuadBez { + p0, + p1, + p2: p1.midpoint(p2) + }, + QuadBez { + p0: p1.midpoint(p2), + p1: p2, + p2: p3 + } + ], + QuadSpline::new(vec![p0, p1, p2, p3]) + .to_quads() + .collect::>() + ); + } +} diff --git a/vendor/kurbo/src/rect.rs b/vendor/kurbo/src/rect.rs new file mode 100644 index 0000000000..9a2b54a8ca --- /dev/null +++ b/vendor/kurbo/src/rect.rs @@ -0,0 +1,1053 @@ +// Copyright 2019 the Kurbo Authors +// SPDX-License-Identifier: Apache-2.0 OR MIT + +//! A rectangle. + +use core::fmt; +use core::ops::{Add, Sub}; + +use crate::{ + Axis, Ellipse, Insets, PathEl, Point, RoundedRect, RoundedRectRadii, Shape, Size, Vec2, +}; + +#[cfg(not(feature = "std"))] +use crate::common::FloatFuncs; + +/// A rectangle. +#[derive(Clone, Copy, Default, PartialEq)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +pub struct Rect { + /// The minimum x coordinate (left edge). + pub x0: f64, + /// The minimum y coordinate (top edge in y-down spaces). + pub y0: f64, + /// The maximum x coordinate (right edge). + pub x1: f64, + /// The maximum y coordinate (bottom edge in y-down spaces). + pub y1: f64, +} + +impl Rect { + /// The empty rectangle at the origin. + pub const ZERO: Rect = Rect::new(0., 0., 0., 0.); + + /// A new rectangle from minimum and maximum coordinates. + #[inline(always)] + pub const fn new(x0: f64, y0: f64, x1: f64, y1: f64) -> Rect { + Rect { x0, y0, x1, y1 } + } + + /// A new rectangle from two points. + /// + /// The result will have non-negative width and height. + #[inline] + pub fn from_points(p0: impl Into, p1: impl Into) -> Rect { + let p0 = p0.into(); + let p1 = p1.into(); + Rect::new(p0.x, p0.y, p1.x, p1.y).abs() + } + + /// A new rectangle from origin and size. + /// + /// The result will have non-negative width and height. + #[inline] + pub fn from_origin_size(origin: impl Into, size: impl Into) -> Rect { + let origin = origin.into(); + Rect::from_points(origin, origin + size.into().to_vec2()) + } + + /// A new rectangle from center and size. + #[inline] + pub fn from_center_size(center: impl Into, size: impl Into) -> Rect { + let center = center.into(); + let size = 0.5 * size.into(); + Rect::new( + center.x - size.width, + center.y - size.height, + center.x + size.width, + center.y + size.height, + ) + } + + /// Create a new `Rect` with the same size as `self` and a new origin. + #[inline] + pub fn with_origin(self, origin: impl Into) -> Rect { + Rect::from_origin_size(origin, self.size()) + } + + /// Create a new `Rect` with the same origin as `self` and a new size. + #[inline] + pub fn with_size(self, size: impl Into) -> Rect { + Rect::from_origin_size(self.origin(), size) + } + + /// Create a new `Rect` by applying the [`Insets`]. + /// + /// This will not preserve negative width and height. + /// + /// # Examples + /// + /// ``` + /// use kurbo::Rect; + /// let inset_rect = Rect::new(0., 0., 10., 10.,).inset(2.); + /// assert_eq!(inset_rect.width(), 14.0); + /// assert_eq!(inset_rect.x0, -2.0); + /// assert_eq!(inset_rect.x1, 12.0); + /// ``` + #[inline] + pub fn inset(self, insets: impl Into) -> Rect { + self + insets.into() + } + + /// The width of the rectangle. + /// + /// Note: nothing forbids negative width. + #[inline] + pub const fn width(&self) -> f64 { + self.x1 - self.x0 + } + + /// The height of the rectangle. + /// + /// Note: nothing forbids negative height. + #[inline] + pub const fn height(&self) -> f64 { + self.y1 - self.y0 + } + + /// Returns the minimum value for the x-coordinate of the rectangle. + #[inline] + pub const fn min_x(&self) -> f64 { + self.x0.min(self.x1) + } + + /// Returns the maximum value for the x-coordinate of the rectangle. + #[inline] + pub const fn max_x(&self) -> f64 { + self.x0.max(self.x1) + } + + /// Returns the minimum value for the y-coordinate of the rectangle. + #[inline] + pub const fn min_y(&self) -> f64 { + self.y0.min(self.y1) + } + + /// Returns the maximum value for the y-coordinate of the rectangle. + #[inline] + pub const fn max_y(&self) -> f64 { + self.y0.max(self.y1) + } + + /// The origin of the rectangle. + /// + /// This is the top left corner in a y-down space and with + /// non-negative width and height. + #[inline(always)] + pub const fn origin(&self) -> Point { + Point::new(self.x0, self.y0) + } + + /// The size of the rectangle. + #[inline] + pub const fn size(&self) -> Size { + Size::new(self.width(), self.height()) + } + + /// The area of the rectangle. + #[inline] + pub const fn area(&self) -> f64 { + self.width() * self.height() + } + + /// Whether this rectangle has zero area. + #[doc(alias = "is_empty")] + #[inline] + pub const fn is_zero_area(&self) -> bool { + self.area() == 0.0 + } + + /// The center point of the rectangle. + #[inline] + pub const fn center(&self) -> Point { + Point::new(0.5 * (self.x0 + self.x1), 0.5 * (self.y0 + self.y1)) + } + + /// Returns `true` if `point` lies within `self`. + #[inline] + pub fn contains(&self, point: impl Into) -> bool { + let point = point.into(); + point.x >= self.x0 && point.x < self.x1 && point.y >= self.y0 && point.y < self.y1 + } + + /// Take absolute value of width and height. + /// + /// The resulting rect has the same extents as the original, but is + /// guaranteed to have non-negative width and height. + #[inline] + pub const fn abs(&self) -> Rect { + let Rect { x0, y0, x1, y1 } = *self; + Rect::new(x0.min(x1), y0.min(y1), x0.max(x1), y0.max(y1)) + } + + /// The smallest rectangle enclosing two rectangles. + /// + /// Results are valid only if width and height are non-negative. + #[inline] + pub const fn union(&self, other: Rect) -> Rect { + Rect::new( + self.x0.min(other.x0), + self.y0.min(other.y0), + self.x1.max(other.x1), + self.y1.max(other.y1), + ) + } + + /// Compute the union with one point. + /// + /// This method includes the perimeter of zero-area rectangles. + /// Thus, a succession of `union_pt` operations on a series of + /// points yields their enclosing rectangle. + /// + /// Results are valid only if width and height are non-negative. + pub fn union_pt(&self, pt: impl Into) -> Rect { + let pt = pt.into(); + Rect::new( + self.x0.min(pt.x), + self.y0.min(pt.y), + self.x1.max(pt.x), + self.y1.max(pt.y), + ) + } + + /// The intersection of two rectangles. + /// + /// The result is zero-area if either input has negative width or + /// height. The result always has non-negative width and height. + /// + /// If you want to determine whether two rectangles intersect, use the + /// [`overlaps`] method instead. + /// + /// [`overlaps`]: Rect::overlaps + #[inline] + pub const fn intersect(&self, other: Rect) -> Rect { + let x0 = self.x0.max(other.x0); + let y0 = self.y0.max(other.y0); + let x1 = self.x1.min(other.x1); + let y1 = self.y1.min(other.y1); + Rect::new(x0, y0, x1.max(x0), y1.max(y0)) + } + + /// Determines whether this rectangle overlaps with another in any way. + /// + /// Note that the edge of the rectangle is considered to be part of itself, meaning + /// that two rectangles that share an edge are considered to overlap. + /// + /// Returns `true` if the rectangles overlap, `false` otherwise. + /// + /// If you want to compute the *intersection* of two rectangles, use the + /// [`intersect`] method instead. + /// + /// [`intersect`]: Rect::intersect + /// + /// # Examples + /// + /// ``` + /// use kurbo::Rect; + /// + /// let rect1 = Rect::new(0.0, 0.0, 10.0, 10.0); + /// let rect2 = Rect::new(5.0, 5.0, 15.0, 15.0); + /// assert!(rect1.overlaps(rect2)); + /// + /// let rect1 = Rect::new(0.0, 0.0, 10.0, 10.0); + /// let rect2 = Rect::new(10.0, 0.0, 20.0, 10.0); + /// assert!(rect1.overlaps(rect2)); + /// ``` + #[inline] + pub const fn overlaps(&self, other: Rect) -> bool { + self.x0 <= other.x1 && self.x1 >= other.x0 && self.y0 <= other.y1 && self.y1 >= other.y0 + } + + /// Returns whether this rectangle contains another rectangle. + /// + /// A rectangle is considered to contain another rectangle if the other + /// rectangle is fully enclosed within the bounds of this rectangle. + /// + /// # Examples + /// + /// ``` + /// use kurbo::Rect; + /// + /// let rect1 = Rect::new(0.0, 0.0, 10.0, 10.0); + /// let rect2 = Rect::new(2.0, 2.0, 4.0, 4.0); + /// assert!(rect1.contains_rect(rect2)); + /// ``` + /// + /// Two equal rectangles are considered to contain each other. + /// + /// ``` + /// use kurbo::Rect; + /// + /// let rect = Rect::new(0.0, 0.0, 10.0, 10.0); + /// assert!(rect.contains_rect(rect)); + /// ``` + #[inline] + pub const fn contains_rect(&self, other: Rect) -> bool { + self.x0 <= other.x0 && self.y0 <= other.y0 && self.x1 >= other.x1 && self.y1 >= other.y1 + } + + /// Expand a rectangle by a constant amount in both directions. + /// + /// The logic simply applies the amount in each direction. If rectangle + /// area or added dimensions are negative, this could give odd results. + pub const fn inflate(&self, width: f64, height: f64) -> Rect { + Rect::new( + self.x0 - width, + self.y0 - height, + self.x1 + width, + self.y1 + height, + ) + } + + /// Returns a new `Rect`, + /// with each coordinate value [rounded] to the nearest integer. + /// + /// # Examples + /// + /// ``` + /// use kurbo::Rect; + /// let rect = Rect::new(3.3, 3.6, 3.0, -3.1).round(); + /// assert_eq!(rect.x0, 3.0); + /// assert_eq!(rect.y0, 4.0); + /// assert_eq!(rect.x1, 3.0); + /// assert_eq!(rect.y1, -3.0); + /// ``` + /// + /// [rounded]: f64::round + #[inline] + pub fn round(self) -> Rect { + Rect::new( + self.x0.round(), + self.y0.round(), + self.x1.round(), + self.y1.round(), + ) + } + + /// Returns a new `Rect`, + /// with each coordinate value [rounded up] to the nearest integer, + /// unless they are already an integer. + /// + /// # Examples + /// + /// ``` + /// use kurbo::Rect; + /// let rect = Rect::new(3.3, 3.6, 3.0, -3.1).ceil(); + /// assert_eq!(rect.x0, 4.0); + /// assert_eq!(rect.y0, 4.0); + /// assert_eq!(rect.x1, 3.0); + /// assert_eq!(rect.y1, -3.0); + /// ``` + /// + /// [rounded up]: f64::ceil + #[inline] + pub fn ceil(self) -> Rect { + Rect::new( + self.x0.ceil(), + self.y0.ceil(), + self.x1.ceil(), + self.y1.ceil(), + ) + } + + /// Returns a new `Rect`, + /// with each coordinate value [rounded down] to the nearest integer, + /// unless they are already an integer. + /// + /// # Examples + /// + /// ``` + /// use kurbo::Rect; + /// let rect = Rect::new(3.3, 3.6, 3.0, -3.1).floor(); + /// assert_eq!(rect.x0, 3.0); + /// assert_eq!(rect.y0, 3.0); + /// assert_eq!(rect.x1, 3.0); + /// assert_eq!(rect.y1, -4.0); + /// ``` + /// + /// [rounded down]: f64::floor + #[inline] + pub fn floor(self) -> Rect { + Rect::new( + self.x0.floor(), + self.y0.floor(), + self.x1.floor(), + self.y1.floor(), + ) + } + + /// Returns a new `Rect`, + /// with each coordinate value rounded away from the center of the `Rect` + /// to the nearest integer, unless they are already an integer. + /// That is to say this function will return the smallest possible `Rect` + /// with integer coordinates that is a superset of `self`. + /// + /// # Examples + /// + /// ``` + /// use kurbo::Rect; + /// + /// // In positive space + /// let rect = Rect::new(3.3, 3.6, 5.6, 4.1).expand(); + /// assert_eq!(rect.x0, 3.0); + /// assert_eq!(rect.y0, 3.0); + /// assert_eq!(rect.x1, 6.0); + /// assert_eq!(rect.y1, 5.0); + /// + /// // In both positive and negative space + /// let rect = Rect::new(-3.3, -3.6, 5.6, 4.1).expand(); + /// assert_eq!(rect.x0, -4.0); + /// assert_eq!(rect.y0, -4.0); + /// assert_eq!(rect.x1, 6.0); + /// assert_eq!(rect.y1, 5.0); + /// + /// // In negative space + /// let rect = Rect::new(-5.6, -4.1, -3.3, -3.6).expand(); + /// assert_eq!(rect.x0, -6.0); + /// assert_eq!(rect.y0, -5.0); + /// assert_eq!(rect.x1, -3.0); + /// assert_eq!(rect.y1, -3.0); + /// + /// // Inverse orientation + /// let rect = Rect::new(5.6, -3.6, 3.3, -4.1).expand(); + /// assert_eq!(rect.x0, 6.0); + /// assert_eq!(rect.y0, -3.0); + /// assert_eq!(rect.x1, 3.0); + /// assert_eq!(rect.y1, -5.0); + /// ``` + #[inline] + pub fn expand(self) -> Rect { + // The compiler optimizer will remove the if branching. + let (x0, x1) = if self.x0 < self.x1 { + (self.x0.floor(), self.x1.ceil()) + } else { + (self.x0.ceil(), self.x1.floor()) + }; + let (y0, y1) = if self.y0 < self.y1 { + (self.y0.floor(), self.y1.ceil()) + } else { + (self.y0.ceil(), self.y1.floor()) + }; + Rect::new(x0, y0, x1, y1) + } + + /// Returns a new `Rect`, + /// with each coordinate value rounded towards the center of the `Rect` + /// to the nearest integer, unless they are already an integer. + /// That is to say this function will return the biggest possible `Rect` + /// with integer coordinates that is a subset of `self`. + /// + /// # Examples + /// + /// ``` + /// use kurbo::Rect; + /// + /// // In positive space + /// let rect = Rect::new(3.3, 3.6, 5.6, 4.1).trunc(); + /// assert_eq!(rect.x0, 4.0); + /// assert_eq!(rect.y0, 4.0); + /// assert_eq!(rect.x1, 5.0); + /// assert_eq!(rect.y1, 4.0); + /// + /// // In both positive and negative space + /// let rect = Rect::new(-3.3, -3.6, 5.6, 4.1).trunc(); + /// assert_eq!(rect.x0, -3.0); + /// assert_eq!(rect.y0, -3.0); + /// assert_eq!(rect.x1, 5.0); + /// assert_eq!(rect.y1, 4.0); + /// + /// // In negative space + /// let rect = Rect::new(-5.6, -4.1, -3.3, -3.6).trunc(); + /// assert_eq!(rect.x0, -5.0); + /// assert_eq!(rect.y0, -4.0); + /// assert_eq!(rect.x1, -4.0); + /// assert_eq!(rect.y1, -4.0); + /// + /// // Inverse orientation + /// let rect = Rect::new(5.6, -3.6, 3.3, -4.1).trunc(); + /// assert_eq!(rect.x0, 5.0); + /// assert_eq!(rect.y0, -4.0); + /// assert_eq!(rect.x1, 4.0); + /// assert_eq!(rect.y1, -4.0); + /// ``` + #[inline] + pub fn trunc(self) -> Rect { + // The compiler optimizer will remove the if branching. + let (x0, x1) = if self.x0 < self.x1 { + (self.x0.ceil(), self.x1.floor()) + } else { + (self.x0.floor(), self.x1.ceil()) + }; + let (y0, y1) = if self.y0 < self.y1 { + (self.y0.ceil(), self.y1.floor()) + } else { + (self.y0.floor(), self.y1.ceil()) + }; + Rect::new(x0, y0, x1, y1) + } + + /// Scales the `Rect` by `factor` with respect to the origin (the point `(0, 0)`). + /// + /// # Examples + /// + /// ``` + /// use kurbo::Rect; + /// + /// let rect = Rect::new(2., 2., 4., 6.).scale_from_origin(2.); + /// assert_eq!(rect.x0, 4.); + /// assert_eq!(rect.x1, 8.); + /// ``` + #[inline] + pub const fn scale_from_origin(self, factor: f64) -> Rect { + Rect { + x0: self.x0 * factor, + y0: self.y0 * factor, + x1: self.x1 * factor, + y1: self.y1 * factor, + } + } + + /// Creates a new [`RoundedRect`] from this `Rect` and the provided + /// corner [radius](RoundedRectRadii). + #[inline] + pub fn to_rounded_rect(self, radii: impl Into) -> RoundedRect { + RoundedRect::from_rect(self, radii) + } + + /// Returns the [`Ellipse`] that is bounded by this `Rect`. + #[inline] + pub fn to_ellipse(self) -> Ellipse { + Ellipse::from_rect(self) + } + + /// The aspect ratio of this `Rect`. + /// + /// This is defined as the width divided by the height. It measures the + /// "squareness" of the rectangle (a value of `1` is square). + /// + /// If the height is `0`, the output will be `sign(self.width) * infinity`. + /// If the width and height are both `0`, then the output will be `NaN`. + #[inline] + pub const fn aspect_ratio_width(self) -> f64 { + self.size().aspect_ratio_width() + } + + /// **The inverse** of the aspect ratio of this `Rect`. + /// + /// Aspect ratios are usually defined as the ratio of the width to the height, but + /// this method incorrectly returns the ratio of height to width. + /// You should generally prefer [`aspect_ratio_width`](Self::aspect_ratio_width). + /// + /// If the width is `0` the output will be `sign(y1 - y0) * infinity`. + /// + /// If the width and height are both `0`, the result will be `NaN`. + #[deprecated( + note = "You should use `aspect_ratio_width` instead, as this method returns a potentially unexpected value.", + since = "0.12.0" + )] + #[inline] + pub fn aspect_ratio(&self) -> f64 { + #[expect(deprecated, reason = "This method is deprecated for the same reason.")] + self.size().aspect_ratio() + } + + /// Returns the largest possible `Rect` with the given `aspect_ratio` + /// that is fully contained in `self`. + /// + /// The aspect ratio is specified fractionally, as `width / height`. + /// + /// The resulting rectangle will be centered if it is smaller than this rectangle. + /// + /// # Examples + /// + /// ``` + /// # use kurbo::Rect; + /// let outer = Rect::new(0.0, 0.0, 10.0, 20.0); + /// let inner = outer.inscribed_rect_with_aspect_ratio(1.0); + /// // The new `Rect` is a square centered at the center of `outer`. + /// assert_eq!(inner, Rect::new(0.0, 5.0, 10.0, 15.0)); + /// ``` + pub const fn inscribed_rect_with_aspect_ratio(&self, aspect_ratio: f64) -> Rect { + let self_size @ Size { width, height } = self.size(); + let self_aspect = self_size.aspect_ratio_width(); + + // TODO the parameter `1e-9` was chosen quickly and may not be optimal. + // if self_aspect is `NaN`, that means we're the 0x0 rectangle (or have a `NaN`). + // We don't want NaNs in the output for the 0x0 rectangle + if self_aspect.is_nan() || (self_aspect - aspect_ratio).abs() < 1e-9 { + // short circuit + *self + } else if self_aspect.abs() < aspect_ratio.abs() { + // Our width/height is less than the requested width/height + // We use a smaller height to increase the ratio. + // shrink y to fit + let new_height = width * aspect_ratio.recip(); + let gap = (height - new_height) * 0.5; + let y0 = self.y0 + gap; + let y1 = self.y1 - gap; + Rect::new(self.x0, y0, self.x1, y1) + } else { + // shrink x to fit + let new_width = height * aspect_ratio; + let gap = (width - new_width) * 0.5; + let x0 = self.x0 + gap; + let x1 = self.x1 - gap; + Rect::new(x0, self.y0, x1, self.y1) + } + } + + /// Returns the largest possible `Rect` with the given **inverse**_aspect_ratio + /// that is fully contained in `self`. + /// + /// Aspect ratios are usually defined as the ratio of the width to the height, but + /// this method accepts an aspect ratio specified fractionally as `height / width`. + /// You should generally prefer + /// [`inscribed_rect_with_aspect_ratio`](Self::inscribed_rect_with_aspect_ratio), which + /// takes a "normal" aspect ratio. + /// + /// The resulting rectangle will be centered if it is smaller than this rectangle. + #[deprecated( + note = "You should use `inscribed_rect_with_aspect_ratio` instead, as this method expects an unusually defined parameter.", + since = "0.12.0" + )] + pub fn contained_rect_with_aspect_ratio(&self, inverse_aspect_ratio: f64) -> Rect { + self.inscribed_rect_with_aspect_ratio(1. / inverse_aspect_ratio) + } + + /// Is this rectangle [finite]? + /// + /// [finite]: f64::is_finite + #[inline] + pub const fn is_finite(&self) -> bool { + self.x0.is_finite() && self.x1.is_finite() && self.y0.is_finite() && self.y1.is_finite() + } + + /// Is this rectangle [NaN]? + /// + /// [NaN]: f64::is_nan + #[inline] + pub const fn is_nan(&self) -> bool { + self.x0.is_nan() || self.y0.is_nan() || self.x1.is_nan() || self.y1.is_nan() + } + + /// Get the members matching the given axis. + #[inline] + pub const fn get_coords(self, axis: Axis) -> (f64, f64) { + match axis { + Axis::Horizontal => (self.x0, self.x1), + Axis::Vertical => (self.y0, self.y1), + } + } + + /// Get a mutable reference to the members matching the given axis. + #[inline] + pub const fn get_coords_mut(&mut self, axis: Axis) -> (&mut f64, &mut f64) { + match axis { + Axis::Horizontal => (&mut self.x0, &mut self.x1), + Axis::Vertical => (&mut self.y0, &mut self.y1), + } + } + + /// Set the members matching the given axis to the given values. + #[inline] + pub const fn set_coords(&mut self, axis: Axis, v0: f64, v1: f64) { + match axis { + Axis::Horizontal => (self.x0, self.x1) = (v0, v1), + Axis::Vertical => (self.y0, self.y1) = (v0, v1), + } + } +} + +impl From<(Point, Point)> for Rect { + #[inline(always)] + fn from(points: (Point, Point)) -> Rect { + Rect::from_points(points.0, points.1) + } +} + +impl From<(Point, Size)> for Rect { + fn from(params: (Point, Size)) -> Rect { + Rect::from_origin_size(params.0, params.1) + } +} + +impl Add for Rect { + type Output = Rect; + + #[inline] + fn add(self, v: Vec2) -> Rect { + Rect::new(self.x0 + v.x, self.y0 + v.y, self.x1 + v.x, self.y1 + v.y) + } +} + +impl Sub for Rect { + type Output = Rect; + + #[inline] + fn sub(self, v: Vec2) -> Rect { + Rect::new(self.x0 - v.x, self.y0 - v.y, self.x1 - v.x, self.y1 - v.y) + } +} + +impl Sub for Rect { + type Output = Insets; + + #[inline] + fn sub(self, other: Rect) -> Insets { + let x0 = other.x0 - self.x0; + let y0 = other.y0 - self.y0; + let x1 = self.x1 - other.x1; + let y1 = self.y1 - other.y1; + Insets { x0, y0, x1, y1 } + } +} + +#[doc(hidden)] +pub struct RectPathIter { + rect: Rect, + ix: usize, +} + +impl Shape for Rect { + type PathElementsIter<'iter> = RectPathIter; + + fn path_elements(&self, _tolerance: f64) -> RectPathIter { + RectPathIter { rect: *self, ix: 0 } + } + + // It's a bit of duplication having both this and the impl method, but + // removing that would require using the trait. We'll leave it for now. + #[inline] + fn area(&self) -> f64 { + Rect::area(self) + } + + #[inline] + fn perimeter(&self, _accuracy: f64) -> f64 { + 2.0 * (self.width().abs() + self.height().abs()) + } + + /// Note: this function is carefully designed so that if the plane is + /// tiled with rectangles, the winding number will be nonzero for exactly + /// one of them. + #[inline] + fn winding(&self, pt: Point) -> i32 { + let xmin = self.x0.min(self.x1); + let xmax = self.x0.max(self.x1); + let ymin = self.y0.min(self.y1); + let ymax = self.y0.max(self.y1); + if pt.x >= xmin && pt.x < xmax && pt.y >= ymin && pt.y < ymax { + if (self.x1 > self.x0) ^ (self.y1 > self.y0) { + -1 + } else { + 1 + } + } else { + 0 + } + } + + #[inline] + fn bounding_box(&self) -> Rect { + self.abs() + } + + #[inline(always)] + fn as_rect(&self) -> Option { + Some(*self) + } + + #[inline] + fn contains(&self, pt: Point) -> bool { + self.contains(pt) + } +} + +// This is clockwise in a y-down coordinate system for positive area. +impl Iterator for RectPathIter { + type Item = PathEl; + + fn next(&mut self) -> Option { + self.ix += 1; + match self.ix { + 1 => Some(PathEl::MoveTo(Point::new(self.rect.x0, self.rect.y0))), + 2 => Some(PathEl::LineTo(Point::new(self.rect.x1, self.rect.y0))), + 3 => Some(PathEl::LineTo(Point::new(self.rect.x1, self.rect.y1))), + 4 => Some(PathEl::LineTo(Point::new(self.rect.x0, self.rect.y1))), + 5 => Some(PathEl::ClosePath), + _ => None, + } + } +} + +impl fmt::Debug for Rect { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + if f.alternate() { + write!( + f, + "Rect {{ origin: {:?}, size: {:?} }}", + self.origin(), + self.size() + ) + } else { + write!( + f, + "Rect {{ x0: {:?}, y0: {:?}, x1: {:?}, y1: {:?} }}", + self.x0, self.y0, self.x1, self.y1 + ) + } + } +} + +impl fmt::Display for Rect { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "Rect {{ ")?; + fmt::Display::fmt(&self.origin(), f)?; + write!(f, " ")?; + fmt::Display::fmt(&self.size(), f)?; + write!(f, " }}") + } +} + +#[cfg(test)] +mod tests { + use crate::{Point, Rect, Shape}; + + fn assert_approx_eq(x: f64, y: f64) { + assert!((x - y).abs() < 1e-7); + } + + #[test] + fn area_sign() { + let r = Rect::new(0.0, 0.0, 10.0, 10.0); + let center = r.center(); + assert_approx_eq(r.area(), 100.0); + + assert_eq!(r.winding(center), 1); + + let p = r.to_path(1e-9); + assert_approx_eq(r.area(), p.area()); + assert_eq!(r.winding(center), p.winding(center)); + + let r_flip = Rect::new(0.0, 10.0, 10.0, 0.0); + assert_approx_eq(r_flip.area(), -100.0); + + assert_eq!(r_flip.winding(Point::new(5.0, 5.0)), -1); + let p_flip = r_flip.to_path(1e-9); + assert_approx_eq(r_flip.area(), p_flip.area()); + assert_eq!(r_flip.winding(center), p_flip.winding(center)); + } + + #[test] + fn display() { + let r = Rect::from_origin_size((10., 12.23214), (22.222222222, 23.1)); + assert_eq!( + format!("{r}"), + "Rect { (10, 12.23214) (22.222222222×23.1) }" + ); + assert_eq!(format!("{r:.2}"), "Rect { (10.00, 12.23) (22.22×23.10) }"); + } + + /* TODO uncomment when a (possibly approximate) equality test has been decided on + #[test] + fn rect_from_center_size() { + assert_eq!( + Rect::from_center_size(Point::new(3.0, 2.0), Size::new(2.0, 4.0)), + Rect::new(2.0, 0.0, 4.0, 4.0) + ); + } + */ + + #[test] + #[expect( + deprecated, + reason = "Testing behaviour of deprecated function is still as expected." + )] + fn contained_rect_with_aspect_ratio() { + #[track_caller] + fn case(outer: [f64; 4], aspect_ratio: f64, expected: [f64; 4]) { + let outer = Rect::new(outer[0], outer[1], outer[2], outer[3]); + let expected = Rect::new(expected[0], expected[1], expected[2], expected[3]); + assert_eq!( + outer.contained_rect_with_aspect_ratio(aspect_ratio), + expected + ); + assert!( + expected.size().width.abs() <= outer.size().width.abs() + && expected.size().width.abs() <= outer.size().height.abs(), + "Sanity check {expected} should be smaller than {outer}." + ); + } + // squares (different point orderings) + case([0.0, 0.0, 10.0, 20.0], 1.0, [0.0, 5.0, 10.0, 15.0]); + case([0.0, 20.0, 10.0, 0.0], 1.0, [0.0, 5.0, 10.0, 15.0]); + case([10.0, 0.0, 0.0, 20.0], 1.0, [10.0, 15.0, 0.0, 5.0]); + case([10.0, 20.0, 0.0, 0.0], 1.0, [10.0, 15.0, 0.0, 5.0]); + // non-square + case([0.0, 0.0, 10.0, 20.0], 0.5, [0.0, 7.5, 10.0, 12.5]); + // same aspect ratio + case([0.0, 0.0, 10.0, 20.0], 2.0, [0.0, 0.0, 10.0, 20.0]); + // negative aspect ratio + case([0.0, 0.0, 10.0, 20.0], -1.0, [0.0, 15.0, 10.0, 5.0]); + // infinite aspect ratio + case([0.0, 0.0, 10.0, 20.0], f64::INFINITY, [5.0, 0.0, 5.0, 20.0]); + // zero aspect ratio + case([0.0, 0.0, 10.0, 20.0], 0.0, [0.0, 10.0, 10.0, 10.0]); + // zero width rect + case([0.0, 0.0, 0.0, 20.0], 1.0, [0.0, 10.0, 0.0, 10.0]); + // many zeros + case([0.0, 0.0, 0.0, 20.0], 0.0, [0.0, 10.0, 0.0, 10.0]); + // everything zero + case([0.0, 0.0, 0.0, 0.0], 0.0, [0.0, 0.0, 0.0, 0.0]); + } + + #[test] + fn inscribed_rect_with_aspect_ratio() { + #[track_caller] + fn case(outer: [f64; 4], aspect_ratio: f64, expected: [f64; 4]) { + let outer = Rect::new(outer[0], outer[1], outer[2], outer[3]); + let expected = Rect::new(expected[0], expected[1], expected[2], expected[3]); + assert_eq!( + outer.inscribed_rect_with_aspect_ratio(aspect_ratio), + expected + ); + assert!( + expected.size().width.abs() <= outer.size().width.abs() + && expected.size().width.abs() <= outer.size().height.abs(), + "Sanity check {expected} should be smaller than {outer}." + ); + } + // squares (different point orderings) + case([0.0, 0.0, 10.0, 20.0], 1.0, [0.0, 5.0, 10.0, 15.0]); + case([0.0, 20.0, 10.0, 0.0], 1.0, [0.0, 5.0, 10.0, 15.0]); + case([10.0, 0.0, 0.0, 20.0], 1.0, [10.0, 15.0, 0.0, 5.0]); + case([10.0, 20.0, 0.0, 0.0], 1.0, [10.0, 15.0, 0.0, 5.0]); + // same aspect ratio + case([0.0, 0.0, 10.0, 20.0], 0.5, [0.0, 0.0, 10.0, 20.0]); + // non-square + case([0.0, 0.0, 10.0, 20.0], 2.0, [0.0, 7.5, 10.0, 12.5]); + // negative aspect ratio + case([0.0, 0.0, 10.0, 20.0], -1.0, [0.0, 15.0, 10.0, 5.0]); + // infinite aspect ratio, horizontal line through the center + case( + [0.0, 0.0, 10.0, 20.0], + f64::INFINITY, + [0.0, 10.0, 10.0, 10.0], + ); + // zero aspect ratio, vertical line through the center + case([0.0, 0.0, 10.0, 20.0], 0.0, [5.0, 0.0, 5.0, 20.0]); + // zero width rect + case([0.0, 0.0, 0.0, 20.0], 1.0, [0.0, 10.0, 0.0, 10.0]); + // many zeros, vertical line + case([0.0, 0.0, 0.0, 20.0], 0.0, [0.0, 0.0, 0.0, 20.0]); + // many zeros + case([0.0, 0.0, 20.0, 0.0], 0.0, [10.0, 0.0, 10.0, 0.0]); + // everything zero + case([0.0, 0.0, 0.0, 0.0], 0.0, [0.0, 0.0, 0.0, 0.0]); + } + + #[test] + #[expect(deprecated, reason = "Testing deprecated function.")] + fn aspect_ratio() { + let test = Rect::new(0.0, 0.0, 1.0, 1.0); + assert!((test.aspect_ratio() - 1.0).abs() < 1e-6); + } + + #[test] + fn aspect_ratio_width() { + let test = Rect::new(0.0, 0.0, 1.0, 1.0); + assert!((test.aspect_ratio_width() - 1.0).abs() < 1e-6); + // 16:10 + let test = Rect::new(0.0, 0.0, 16.0, 10.0); + assert!((test.aspect_ratio_width() - 1.6).abs() < 1e-6); + // 16:9 screen resolutions + let test = Rect::new(0.0, 0.0, 1920.0, 1080.0); + assert!((test.aspect_ratio_width() - (16. / 9.)).abs() < 1e-6); + } + + #[test] + fn contained_rect_overlaps() { + let outer = Rect::new(0.0, 0.0, 10.0, 10.0); + let inner = Rect::new(2.0, 2.0, 4.0, 4.0); + assert!(outer.overlaps(inner)); + } + + #[test] + fn overlapping_rect_overlaps() { + let a = Rect::new(0.0, 0.0, 10.0, 10.0); + let b = Rect::new(5.0, 5.0, 15.0, 15.0); + assert!(a.overlaps(b)); + } + + #[test] + fn disjoint_rect_overlaps() { + let a = Rect::new(0.0, 0.0, 10.0, 10.0); + let b = Rect::new(11.0, 11.0, 15.0, 15.0); + assert!(!a.overlaps(b)); + } + + #[test] + fn sharing_edge_overlaps() { + let a = Rect::new(0.0, 0.0, 10.0, 10.0); + let b = Rect::new(10.0, 0.0, 20.0, 10.0); + assert!(a.overlaps(b)); + } + + // Test the two other directions in case there is a bug that only appears in one direction. + #[test] + fn disjoint_rect_overlaps_negative() { + let a = Rect::new(0.0, 0.0, 10.0, 10.0); + let b = Rect::new(-10.0, -10.0, -5.0, -5.0); + assert!(!a.overlaps(b)); + } + + #[test] + fn contained_rectangle_contains() { + let outer = Rect::new(0.0, 0.0, 10.0, 10.0); + let inner = Rect::new(2.0, 2.0, 4.0, 4.0); + assert!(outer.contains_rect(inner)); + } + + #[test] + fn overlapping_rectangle_contains() { + let outer = Rect::new(0.0, 0.0, 10.0, 10.0); + let inner = Rect::new(5.0, 5.0, 15.0, 15.0); + assert!(!outer.contains_rect(inner)); + } + + #[test] + fn disjoint_rectangle_contains() { + let outer = Rect::new(0.0, 0.0, 10.0, 10.0); + let inner = Rect::new(11.0, 11.0, 15.0, 15.0); + assert!(!outer.contains_rect(inner)); + } + + #[test] + fn rect_intersect_zero() { + // These rectangles don't overlap vertically. + let a = Rect::new(25., 101., 200., 130.); + let b = Rect::new(0., 0., 100., 100.); + + for intersection in [a.intersect(b), b.intersect(a)] { + assert_eq!(intersection.x0, 25.); + assert_eq!(intersection.x1, 100.); + assert_eq!(intersection.area(), 0.); + assert_eq!(intersection.y0, intersection.y1); + + // We don't guarantee this in the documentation, but the intersection's `y` values should + // be a sensible value taken from the input. + assert!([0., 100., 101., 130.].contains(&intersection.y0)); + } + } +} diff --git a/vendor/kurbo/src/rounded_rect.rs b/vendor/kurbo/src/rounded_rect.rs new file mode 100644 index 0000000000..26625f79bc --- /dev/null +++ b/vendor/kurbo/src/rounded_rect.rs @@ -0,0 +1,489 @@ +// Copyright 2019 the Kurbo Authors +// SPDX-License-Identifier: Apache-2.0 OR MIT + +//! A rectangle with rounded corners. + +use core::f64::consts::{FRAC_PI_2, FRAC_PI_4}; +use core::ops::{Add, Sub}; + +use crate::{Arc, PathEl, Point, Rect, RoundedRectRadii, Shape, Size, Vec2, arc::ArcAppendIter}; + +#[allow(unused_imports)] // This is unused in later versions of Rust because of additions to core::f32 +#[cfg(not(feature = "std"))] +use crate::common::FloatFuncs; + +/// A rectangle with rounded corners. +/// +/// By construction the rounded rectangle will have +/// non-negative dimensions and radii clamped to half size of the rect. +/// The rounded rectangle can have different radii for each corner. +/// +/// The easiest way to create a `RoundedRect` is often to create a [`Rect`], +/// and then call [`to_rounded_rect`]. +/// +/// ``` +/// use kurbo::{RoundedRect, RoundedRectRadii}; +/// +/// // Create a rounded rectangle with a single radius for all corners: +/// RoundedRect::new(0.0, 0.0, 10.0, 10.0, 5.0); +/// +/// // Or, specify different radii for each corner, clockwise from the top-left: +/// RoundedRect::new(0.0, 0.0, 10.0, 10.0, (1.0, 2.0, 3.0, 4.0)); +/// ``` +/// +/// [`to_rounded_rect`]: Rect::to_rounded_rect +#[derive(Clone, Copy, Default, Debug, PartialEq)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +pub struct RoundedRect { + /// Coordinates of the rectangle. + rect: Rect, + /// Radius of all four corners. + radii: RoundedRectRadii, +} + +impl RoundedRect { + /// A new rectangle from minimum and maximum coordinates. + /// + /// The result will have non-negative width, height and radii. + #[inline] + pub fn new( + x0: f64, + y0: f64, + x1: f64, + y1: f64, + radii: impl Into, + ) -> RoundedRect { + RoundedRect::from_rect(Rect::new(x0, y0, x1, y1), radii) + } + + /// A new rounded rectangle from a rectangle and corner radii. + /// + /// The result will have non-negative width, height and radii. + /// + /// See also [`Rect::to_rounded_rect`], which offers the same utility. + #[inline] + pub fn from_rect(rect: Rect, radii: impl Into) -> RoundedRect { + let rect = rect.abs(); + let shortest_side_length = (rect.width()).min(rect.height()); + let radii = radii.into().abs().clamp(shortest_side_length / 2.0); + + RoundedRect { rect, radii } + } + + /// A new rectangle from two [`Point`]s. + /// + /// The result will have non-negative width, height and radius. + #[inline] + pub fn from_points( + p0: impl Into, + p1: impl Into, + radii: impl Into, + ) -> RoundedRect { + Rect::from_points(p0, p1).to_rounded_rect(radii) + } + + /// A new rectangle from origin and size. + /// + /// The result will have non-negative width, height and radius. + #[inline] + pub fn from_origin_size( + origin: impl Into, + size: impl Into, + radii: impl Into, + ) -> RoundedRect { + Rect::from_origin_size(origin, size).to_rounded_rect(radii) + } + + /// The width of the rectangle. + #[inline] + pub const fn width(&self) -> f64 { + self.rect.width() + } + + /// The height of the rectangle. + #[inline] + pub const fn height(&self) -> f64 { + self.rect.height() + } + + /// Radii of the rounded corners. + #[inline(always)] + pub const fn radii(&self) -> RoundedRectRadii { + self.radii + } + + /// The (non-rounded) rectangle. + #[inline(always)] + pub const fn rect(&self) -> Rect { + self.rect + } + + /// The origin of the rectangle. + /// + /// This is the top left corner in a y-down space. + #[inline(always)] + pub const fn origin(&self) -> Point { + self.rect.origin() + } + + /// The center point of the rectangle. + #[inline] + pub const fn center(&self) -> Point { + self.rect.center() + } + + /// Is this rounded rectangle finite? + #[inline] + pub const fn is_finite(&self) -> bool { + self.rect.is_finite() && self.radii.is_finite() + } + + /// Is this rounded rectangle NaN? + #[inline] + pub const fn is_nan(&self) -> bool { + self.rect.is_nan() || self.radii.is_nan() + } +} + +#[doc(hidden)] +pub struct RoundedRectPathIter { + idx: usize, + rect: RectPathIter, + arcs: [ArcAppendIter; 4], +} + +impl Shape for RoundedRect { + type PathElementsIter<'iter> = RoundedRectPathIter; + + fn path_elements(&self, tolerance: f64) -> RoundedRectPathIter { + let radii = self.radii(); + + let build_arc_iter = |i, center, ellipse_radii| { + let arc = Arc { + center, + radii: ellipse_radii, + start_angle: FRAC_PI_2 * i as f64, + sweep_angle: FRAC_PI_2, + x_rotation: 0.0, + }; + arc.append_iter(tolerance) + }; + + // Note: order follows the rectangle path iterator. + let arcs = [ + build_arc_iter( + 2, + Point { + x: self.rect.x0 + radii.top_left, + y: self.rect.y0 + radii.top_left, + }, + Vec2 { + x: radii.top_left, + y: radii.top_left, + }, + ), + build_arc_iter( + 3, + Point { + x: self.rect.x1 - radii.top_right, + y: self.rect.y0 + radii.top_right, + }, + Vec2 { + x: radii.top_right, + y: radii.top_right, + }, + ), + build_arc_iter( + 0, + Point { + x: self.rect.x1 - radii.bottom_right, + y: self.rect.y1 - radii.bottom_right, + }, + Vec2 { + x: radii.bottom_right, + y: radii.bottom_right, + }, + ), + build_arc_iter( + 1, + Point { + x: self.rect.x0 + radii.bottom_left, + y: self.rect.y1 - radii.bottom_left, + }, + Vec2 { + x: radii.bottom_left, + y: radii.bottom_left, + }, + ), + ]; + + let rect = RectPathIter { + rect: self.rect, + ix: 0, + radii, + }; + + RoundedRectPathIter { idx: 0, rect, arcs } + } + + #[inline] + fn area(&self) -> f64 { + // A corner is a quarter-circle, i.e. + // .............# + // . ###### + // . ######### + // . ########### + // . ############ + // .############# + // ############## + // |-----r------| + // For each corner, we need to subtract the square that bounds this + // quarter-circle, and add back in the area of quarter circle. + + let radii = self.radii(); + + // Start with the area of the bounding rectangle. For each corner, + // subtract the area of the corner under the quarter-circle, and add + // back the area of the quarter-circle. + self.rect.area() + + [ + radii.top_left, + radii.top_right, + radii.bottom_right, + radii.bottom_left, + ] + .iter() + .map(|radius| (FRAC_PI_4 - 1.0) * radius * radius) + .sum::() + } + + #[inline] + fn perimeter(&self, _accuracy: f64) -> f64 { + // A corner is a quarter-circle, i.e. + // .............# + // . # + // . # + // . # + // . # + // .# + // # + // |-----r------| + // If we start with the bounding rectangle, then subtract 2r (the + // straight edge outside the circle) and add 1/4 * pi * (2r) (the + // perimeter of the quarter-circle) for each corner with radius r, we + // get the perimeter of the shape. + + let radii = self.radii(); + + // Start with the full perimeter. For each corner, subtract the + // border surrounding the rounded corner and add the quarter-circle + // perimeter. + self.rect.perimeter(1.0) + + ([ + radii.top_left, + radii.top_right, + radii.bottom_right, + radii.bottom_left, + ]) + .iter() + .map(|radius| (-2.0 + FRAC_PI_2) * radius) + .sum::() + } + + #[inline] + fn winding(&self, mut pt: Point) -> i32 { + let center = self.center(); + + // 1. Translate the point relative to the center of the rectangle. + pt.x -= center.x; + pt.y -= center.y; + + // 2. Pick a radius value to use based on which quadrant the point is + // in. + let radius = { + /// Calculates `if !cond { a } else { b }`. + /// + /// This function is theoretically pretty nonsensical to have, as the compiler should + /// pretty trivially be able to compile both this function and the explicit + /// `if`-statement equivalent to the same thing. However, for some reason, writing + /// these bit operations explicitly causes the compiler to be better about prefetching + /// the rounded rect data. + /// + /// See for more. + #[inline(always)] + fn select(a: f64, b: f64, cond: bool) -> f64 { + let mask = (cond as u64).wrapping_neg(); // 0 or !0 + f64::from_bits((a.to_bits() & !mask) | (b.to_bits() & mask)) + } + + let radii = self.radii(); + let radius_top = select(radii.top_left, radii.top_right, pt.x >= 0.); + let radius_bottom = select(radii.bottom_left, radii.bottom_right, pt.x >= 0.); + select(radius_top, radius_bottom, pt.y >= 0.) + }; + + // 3. This is the width and height of a rectangle with one corner at + // the center of the rounded rectangle, and another corner at the + // center of the relevant corner circle. + let inside_half_width = (self.width() / 2.0 - radius).max(0.0); + let inside_half_height = (self.height() / 2.0 - radius).max(0.0); + + // 4. Three things are happening here. + // + // First, the x- and y-values are being reflected into the positive + // (bottom-right quadrant). The radius has already been determined, + // so it doesn't matter what quadrant is used. + // + // After reflecting, the points are clamped so that their x- and y- + // values can't be lower than the x- and y- values of the center of + // the corner circle, and the coordinate system is transformed + // again, putting (0, 0) at the center of the corner circle. + let px = (pt.x.abs() - inside_half_width).max(0.0); + let py = (pt.y.abs() - inside_half_height).max(0.0); + + // 5. The transforms above clamp all input points such that they will + // be inside the rounded rectangle if the corresponding output point + // (px, py) is inside a circle centered around the origin with the + // given radius. + let inside = px * px + py * py <= radius * radius; + if inside { 1 } else { 0 } + } + + #[inline] + fn bounding_box(&self) -> Rect { + self.rect.bounding_box() + } + + #[inline(always)] + fn as_rounded_rect(&self) -> Option { + Some(*self) + } +} + +struct RectPathIter { + rect: Rect, + radii: RoundedRectRadii, + ix: usize, +} + +// This is clockwise in a y-down coordinate system for positive area. +impl Iterator for RectPathIter { + type Item = PathEl; + + fn next(&mut self) -> Option { + self.ix += 1; + match self.ix { + 1 => Some(PathEl::MoveTo(Point::new( + self.rect.x0, + self.rect.y0 + self.radii.top_left, + ))), + 2 => Some(PathEl::LineTo(Point::new( + self.rect.x1 - self.radii.top_right, + self.rect.y0, + ))), + 3 => Some(PathEl::LineTo(Point::new( + self.rect.x1, + self.rect.y1 - self.radii.bottom_right, + ))), + 4 => Some(PathEl::LineTo(Point::new( + self.rect.x0 + self.radii.bottom_left, + self.rect.y1, + ))), + 5 => Some(PathEl::ClosePath), + _ => None, + } + } +} + +// This is clockwise in a y-down coordinate system for positive area. +impl Iterator for RoundedRectPathIter { + type Item = PathEl; + + fn next(&mut self) -> Option { + if self.idx > 4 { + return None; + } + + // Iterate between rectangle and arc iterators. + // Rect iterator will start and end the path. + + // Initial point set by the rect iterator + if self.idx == 0 { + self.idx += 1; + return self.rect.next(); + } + + // Generate the arc curve elements. + // If we reached the end of the arc, add a line towards next arc (rect iterator). + match self.arcs[self.idx - 1].next() { + Some(elem) => Some(elem), + None => { + self.idx += 1; + self.rect.next() + } + } + } +} + +impl Add for RoundedRect { + type Output = RoundedRect; + + #[inline] + fn add(self, v: Vec2) -> RoundedRect { + RoundedRect::from_rect(self.rect + v, self.radii) + } +} + +impl Sub for RoundedRect { + type Output = RoundedRect; + + #[inline] + fn sub(self, v: Vec2) -> RoundedRect { + RoundedRect::from_rect(self.rect - v, self.radii) + } +} + +#[cfg(test)] +mod tests { + use crate::{Circle, Point, Rect, RoundedRect, Shape}; + + #[test] + fn area() { + let epsilon = 1e-9; + + // Extremum: 0.0 radius corner -> rectangle + let rect = Rect::new(0.0, 0.0, 100.0, 100.0); + let rounded_rect = RoundedRect::new(0.0, 0.0, 100.0, 100.0, 0.0); + assert!((rect.area() - rounded_rect.area()).abs() < epsilon); + + // Extremum: half-size radius corner -> circle + let circle = Circle::new((0.0, 0.0), 50.0); + let rounded_rect = RoundedRect::new(0.0, 0.0, 100.0, 100.0, 50.0); + assert!((circle.area() - rounded_rect.area()).abs() < epsilon); + } + + #[test] + fn winding() { + let rect = RoundedRect::new(-5.0, -5.0, 10.0, 20.0, (5.0, 5.0, 5.0, 0.0)); + assert_eq!(rect.winding(Point::new(0.0, 0.0)), 1); + assert_eq!(rect.winding(Point::new(-5.0, 0.0)), 1); // left edge + assert_eq!(rect.winding(Point::new(0.0, 20.0)), 1); // bottom edge + assert_eq!(rect.winding(Point::new(10.0, 20.0)), 0); // bottom-right corner + assert_eq!(rect.winding(Point::new(-5.0, 20.0)), 1); // bottom-left corner (has a radius of 0) + assert_eq!(rect.winding(Point::new(-10.0, 0.0)), 0); + + let rect = RoundedRect::new(-10.0, -20.0, 10.0, 20.0, 0.0); // rectangle + assert_eq!(rect.winding(Point::new(10.0, 20.0)), 1); // bottom-right corner + } + + #[test] + fn bez_conversion() { + let rect = RoundedRect::new(-5.0, -5.0, 10.0, 20.0, 5.0); + let p = rect.to_path(1e-9); + // Note: could be more systematic about tolerance tightness. + let epsilon = 1e-7; + assert!((rect.area() - p.area()).abs() < epsilon); + assert_eq!(p.winding(Point::new(0.0, 0.0)), 1); + } +} diff --git a/vendor/kurbo/src/rounded_rect_radii.rs b/vendor/kurbo/src/rounded_rect_radii.rs new file mode 100644 index 0000000000..3a1632a2b1 --- /dev/null +++ b/vendor/kurbo/src/rounded_rect_radii.rs @@ -0,0 +1,124 @@ +// Copyright 2021 the Kurbo Authors +// SPDX-License-Identifier: Apache-2.0 OR MIT + +//! A description of the radii for each corner of a rounded rectangle. + +use core::convert::From; + +#[allow(unused_imports)] // This is unused in later versions of Rust because of additions to core::f32 +#[cfg(not(feature = "std"))] +use crate::common::FloatFuncs; + +/// Radii for each corner of a rounded rectangle. +/// +/// The use of `top` as in `top_left` assumes a y-down coordinate space. Piet +/// (and Druid by extension) uses a y-down coordinate space, but Kurbo also +/// supports a y-up coordinate space, in which case `top_left` would actually +/// refer to the bottom-left corner, and vice versa. Top may not always +/// actually be the top, but `top` corners will always have a smaller y-value +/// than `bottom` corners. +#[derive(Clone, Copy, Default, Debug, PartialEq)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +pub struct RoundedRectRadii { + /// The radius of the top-left corner. + pub top_left: f64, + /// The radius of the top-right corner. + pub top_right: f64, + /// The radius of the bottom-right corner. + pub bottom_right: f64, + /// The radius of the bottom-left corner. + pub bottom_left: f64, +} + +impl RoundedRectRadii { + /// Create a new `RoundedRectRadii`. This function takes radius values for + /// the four corners. The argument order is `top_left`, `top_right`, + /// `bottom_right`, `bottom_left`, or clockwise starting from `top_left`. + #[inline(always)] + pub const fn new(top_left: f64, top_right: f64, bottom_right: f64, bottom_left: f64) -> Self { + RoundedRectRadii { + top_left, + top_right, + bottom_right, + bottom_left, + } + } + + /// Create a new `RoundedRectRadii` from a single radius. The `radius` + /// argument will be set as the radius for all four corners. + #[inline(always)] + pub const fn from_single_radius(radius: f64) -> Self { + RoundedRectRadii { + top_left: radius, + top_right: radius, + bottom_right: radius, + bottom_left: radius, + } + } + + /// Takes the absolute value of all corner radii. + pub const fn abs(&self) -> Self { + RoundedRectRadii::new( + self.top_left.abs(), + self.top_right.abs(), + self.bottom_right.abs(), + self.bottom_left.abs(), + ) + } + + /// For each corner, takes the min of that corner's radius and `max`. + pub const fn clamp(&self, max: f64) -> Self { + RoundedRectRadii::new( + self.top_left.min(max), + self.top_right.min(max), + self.bottom_right.min(max), + self.bottom_left.min(max), + ) + } + + /// Returns `true` if all radius values are finite. + pub const fn is_finite(&self) -> bool { + self.top_left.is_finite() + && self.top_right.is_finite() + && self.bottom_right.is_finite() + && self.bottom_left.is_finite() + } + + /// Returns `true` if any corner radius value is NaN. + pub const fn is_nan(&self) -> bool { + self.top_left.is_nan() + || self.top_right.is_nan() + || self.bottom_right.is_nan() + || self.bottom_left.is_nan() + } + + /// If all radii are equal, returns the value of the radii. Otherwise, + /// returns `None`. + pub const fn as_single_radius(&self) -> Option { + let epsilon = 1e-9; + + if (self.top_left - self.top_right).abs() < epsilon + && (self.top_right - self.bottom_right).abs() < epsilon + && (self.bottom_right - self.bottom_left).abs() < epsilon + { + Some(self.top_left) + } else { + None + } + } +} + +impl From for RoundedRectRadii { + #[inline(always)] + fn from(radius: f64) -> Self { + RoundedRectRadii::from_single_radius(radius) + } +} + +impl From<(f64, f64, f64, f64)> for RoundedRectRadii { + #[inline(always)] + fn from(radii: (f64, f64, f64, f64)) -> Self { + RoundedRectRadii::new(radii.0, radii.1, radii.2, radii.3) + } +} diff --git a/vendor/kurbo/src/shape.rs b/vendor/kurbo/src/shape.rs new file mode 100644 index 0000000000..fb28450890 --- /dev/null +++ b/vendor/kurbo/src/shape.rs @@ -0,0 +1,229 @@ +// Copyright 2019 the Kurbo Authors +// SPDX-License-Identifier: Apache-2.0 OR MIT + +//! A generic trait for shapes. + +use crate::{BezPath, Circle, Line, PathEl, Point, Rect, RoundedRect, Segments, segments}; + +/// A generic trait for open and closed shapes. +/// +/// This trait provides conversion from shapes to [`BezPath`]s, as well as +/// general geometry functionality like computing [`area`], [`bounding_box`]es, +/// and [`winding`] number. +/// +/// [`area`]: Shape::area +/// [`bounding_box`]: Shape::bounding_box +/// [`winding`]: Shape::winding +pub trait Shape { + /// The iterator returned by the [`path_elements`] method. + /// + /// [`path_elements`]: Shape::path_elements + type PathElementsIter<'iter>: Iterator + 'iter + where + Self: 'iter; + + /// Returns an iterator over this shape expressed as [`PathEl`]s; + /// that is, as Bézier path _elements_. + /// + /// All shapes can be represented as Béziers, but in many situations + /// (such as when interfacing with a platform drawing API) there are more + /// efficient native types for specific concrete shapes. In this case, + /// the user should exhaust the `as_` methods ([`as_rect`], [`as_line`], etc) + /// before converting to a [`BezPath`], as those are likely to be more + /// efficient. + /// + /// In many cases, shapes are able to iterate their elements without + /// allocating; however creating a [`BezPath`] object always allocates. + /// If you need an owned [`BezPath`] you can use [`to_path`] instead. + /// + /// # Tolerance + /// + /// The `tolerance` parameter controls the accuracy of + /// conversion of geometric primitives to Bézier curves, as + /// curves such as circles cannot be represented exactly but + /// only approximated. For drawing as in UI elements, a value + /// of 0.1 is appropriate, as it is unlikely to be visible to + /// the eye. For scientific applications, a smaller value + /// might be appropriate. Note that in general the number of + /// cubic Bézier segments scales as `tolerance ^ (-1/6)`. + /// + /// [`as_rect`]: Shape::as_rect + /// [`as_line`]: Shape::as_line + /// [`to_path`]: Shape::to_path + fn path_elements(&self, tolerance: f64) -> Self::PathElementsIter<'_>; + + /// Convert to a Bézier path. + /// + /// This always allocates. It is appropriate when both the source + /// shape and the resulting path are to be retained. + /// + /// If you only need to iterate the elements (such as to convert them to + /// drawing commands for a given 2D graphics API) you should prefer + /// [`path_elements`], which can avoid allocating where possible. + /// + /// The `tolerance` parameter is the same as for [`path_elements`]. + /// + /// [`path_elements`]: Shape::path_elements + fn to_path(&self, tolerance: f64) -> BezPath { + self.path_elements(tolerance).collect() + } + + /// Convert into a Bézier path. + /// + /// This allocates in the general case, but is zero-cost if the + /// shape is already a [`BezPath`]. + /// + /// The `tolerance` parameter is the same as for [`path_elements()`]. + /// + /// [`path_elements()`]: Shape::path_elements + fn into_path(self, tolerance: f64) -> BezPath + where + Self: Sized, + { + self.to_path(tolerance) + } + + /// Returns an iterator over this shape expressed as Bézier path + /// _segments_ ([`PathSeg`]s). + /// + /// The allocation behaviour and `tolerance` parameter are the + /// same as for [`path_elements()`] + /// + /// [`PathSeg`]: crate::PathSeg + /// [`path_elements()`]: Shape::path_elements + fn path_segments(&self, tolerance: f64) -> Segments> { + segments(self.path_elements(tolerance)) + } + + /// Signed area. + /// + /// This method only produces meaningful results with closed shapes. + /// + /// The convention for positive area is that y increases when x is + /// positive. Thus, it is clockwise when down is increasing y (the + /// usual convention for graphics), and anticlockwise when + /// up is increasing y (the usual convention for math). + fn area(&self) -> f64; + + /// Total length of perimeter. + //FIXME: document the accuracy param + fn perimeter(&self, accuracy: f64) -> f64; + + /// The [winding number] of a point. + /// + /// This method only produces meaningful results with closed shapes. + /// + /// The sign of the winding number is consistent with that of [`area`], + /// meaning it is +1 when the point is inside a positive area shape + /// and -1 when it is inside a negative area shape. Of course, greater + /// magnitude values are also possible when the shape is more complex. + /// + /// [`area`]: Shape::area + /// [winding number]: https://mathworld.wolfram.com/ContourWindingNumber.html + fn winding(&self, pt: Point) -> i32; + + /// Returns `true` if the [`Point`] is inside this shape. + /// + /// This is only meaningful for closed shapes. Some shapes may have specialized + /// implementations of this function or of [`winding`] determination. + /// + /// The default implementation uses the non-zero winding rule. + /// + /// To determine containment using the even-odd winding rule, check the + /// [`winding`] directly. + /// + /// [`winding`]: Self::winding + fn contains(&self, pt: Point) -> bool { + self.winding(pt) != 0 + } + + /// The smallest rectangle that encloses the shape. + fn bounding_box(&self) -> Rect; + + /// If the shape is a line, make it available. + fn as_line(&self) -> Option { + None + } + + /// If the shape is a rectangle, make it available. + fn as_rect(&self) -> Option { + None + } + + /// If the shape is a rounded rectangle, make it available. + fn as_rounded_rect(&self) -> Option { + None + } + + /// If the shape is a circle, make it available. + fn as_circle(&self) -> Option { + None + } + + /// If the shape is stored as a slice of path elements, make + /// that available. + /// + /// Note: when GAT's land, a method like `path_elements` would be + /// able to iterate through the slice with no extra allocation, + /// without making any assumption that storage is contiguous. + fn as_path_slice(&self) -> Option<&[PathEl]> { + None + } +} + +/// Blanket implementation so `impl Shape` will accept owned or reference. +impl<'a, T: Shape> Shape for &'a T { + type PathElementsIter<'iter> + = T::PathElementsIter<'iter> + where + T: 'iter, + 'a: 'iter; + + fn path_elements(&self, tolerance: f64) -> Self::PathElementsIter<'_> { + (*self).path_elements(tolerance) + } + + fn to_path(&self, tolerance: f64) -> BezPath { + (*self).to_path(tolerance) + } + + fn path_segments(&self, tolerance: f64) -> Segments> { + (*self).path_segments(tolerance) + } + + fn area(&self) -> f64 { + (*self).area() + } + + fn perimeter(&self, accuracy: f64) -> f64 { + (*self).perimeter(accuracy) + } + + fn winding(&self, pt: Point) -> i32 { + (*self).winding(pt) + } + + fn bounding_box(&self) -> Rect { + (*self).bounding_box() + } + + fn as_line(&self) -> Option { + (*self).as_line() + } + + fn as_rect(&self) -> Option { + (*self).as_rect() + } + + fn as_rounded_rect(&self) -> Option { + (*self).as_rounded_rect() + } + + fn as_circle(&self) -> Option { + (*self).as_circle() + } + + fn as_path_slice(&self) -> Option<&[PathEl]> { + (*self).as_path_slice() + } +} diff --git a/vendor/kurbo/src/simplify.rs b/vendor/kurbo/src/simplify.rs new file mode 100644 index 0000000000..411571e38b --- /dev/null +++ b/vendor/kurbo/src/simplify.rs @@ -0,0 +1,396 @@ +// Copyright 2022 the Kurbo Authors +// SPDX-License-Identifier: Apache-2.0 OR MIT + +//! Simplification of a Bézier path. +//! +//! This module is currently experimental. +//! +//! The methods in this module create a `SimplifyBezPath` object, which can then +//! be fed to [`fit_to_bezpath`] or [`fit_to_bezpath_opt`] depending on the degree +//! of optimization desired. +//! +//! The implementation uses a number of techniques to achieve high performance and +//! accuracy. The parameter (generally written `t`) evenly divides the curve segments +//! in the original, so sampling can be done in constant time. The derivatives are +//! computed analytically, as that is straightforward with Béziers. +//! +//! The areas and moments are computed analytically (using Green's theorem), and +//! the prefix sum is stored. Thus, it is possible to analytically compute the area +//! and moment of any subdivision of the curve, also in constant time, by taking +//! the difference of two stored prefix sum values, then fixing up the subsegments. +//! +//! A current limitation (hoped to be addressed in the future) is that non-regular +//! cubic segments may have tangents computed incorrectly. This can easily happen, +//! for example when setting a control point equal to an endpoint. +//! +//! In addition, this method does not report corners (adjoining segments where the +//! tangents are not continuous). It is not clear whether it's best to handle such +//! cases here, or in client code. +//! +//! [`fit_to_bezpath`]: crate::fit_to_bezpath +//! [`fit_to_bezpath_opt`]: crate::fit_to_bezpath_opt + +use alloc::vec::Vec; + +use core::ops::Range; + +#[cfg(not(feature = "std"))] +use crate::common::FloatFuncs; + +use crate::{ + BezPath, CubicBez, CurveFitSample, Line, ParamCurve, ParamCurveDeriv, ParamCurveFit, PathEl, + PathSeg, Point, QuadBez, Vec2, fit_to_bezpath, fit_to_bezpath_opt, +}; + +/// A Bézier path which has been prepared for simplification. +/// +/// See the [module-level documentation] for a bit more discussion of the approach, +/// and how this struct is to be used. +/// +/// [module-level documentation]: crate::simplify +pub struct SimplifyBezPath(Vec); + +struct SimplifyCubic { + c: CubicBez, + // The inclusive prefix sum of the moment integrals + moments: (f64, f64, f64), +} + +/// Options for simplifying paths. +pub struct SimplifyOptions { + /// The tangent of the minimum angle below which the path is considered smooth. + angle_thresh: f64, + opt_level: SimplifyOptLevel, +} + +/// Optimization level for simplification. +pub enum SimplifyOptLevel { + /// Subdivide; faster but not as optimized results. + Subdivide, + /// Optimize subdivision points. + Optimize, +} + +impl Default for SimplifyOptions { + fn default() -> Self { + let opt_level = SimplifyOptLevel::Subdivide; + SimplifyOptions { + angle_thresh: 1e-3, + opt_level, + } + } +} + +#[doc(hidden)] +/// Compute moment integrals. +/// +/// This is exposed for testing purposes but is an internal detail. We can +/// add to the public, documented interface if there is a use case. +pub fn moment_integrals(c: CubicBez) -> (f64, f64, f64) { + let (x0, y0) = (c.p0.x, c.p0.y); + let (x1, y1) = (c.p1.x - x0, c.p1.y - y0); + let (x2, y2) = (c.p2.x - x0, c.p2.y - y0); + let (x3, y3) = (c.p3.x - x0, c.p3.y - y0); + + let r0 = 3. * x1; + let r1 = 3. * y1; + let r2 = x2 * y3; + let r3 = x3 * y2; + let r4 = x3 * y3; + let r5 = 27. * y1; + let r6 = x1 * x2; + let r7 = 27. * y2; + let r8 = 45. * r2; + let r9 = 18. * x3; + let r10 = x1 * y1; + let r11 = 30. * x1; + let r12 = 45. * x3; + let r13 = x2 * y1; + let r14 = 45. * r3; + let r15 = x1.powi(2); + let r16 = 18. * y3; + let r17 = x2.powi(2); + let r18 = 45. * y3; + let r19 = x3.powi(2); + let r20 = 30. * y1; + let r21 = y2.powi(2); + let r22 = y3.powi(2); + let r23 = y1.powi(2); + let a = -r0 * y2 - r0 * y3 + r1 * x2 + r1 * x3 - 6. * r2 + 6. * r3 + 10. * r4; + + // Scale and add chord + let lift = x3 * y0; + let area = a * 0.05 + lift; + let x = r10 * r9 - r11 * r4 + r12 * r13 + r14 * x2 - r15 * r16 - r15 * r7 - r17 * r18 + + r17 * r5 + + r19 * r20 + + 105. * r19 * y2 + + 280. * r19 * y3 + - 105. * r2 * x3 + + r5 * r6 + - r6 * r7 + - r8 * x1; + let y = -r10 * r16 - r10 * r7 - r11 * r22 + r12 * r21 + r13 * r7 + r14 * y1 - r18 * x1 * y2 + + r20 * r4 + - 27. * r21 * x1 + - 105. * r22 * x2 + + 140. * r22 * x3 + + r23 * r9 + + 27. * r23 * x2 + + 105. * r3 * y3 + - r8 * y2; + + let mx = x * (1. / 840.) + x0 * area + 0.5 * x3 * lift; + let my = y * (1. / 420.) + y0 * a * 0.1 + y0 * lift; + + (area, mx, my) +} + +impl SimplifyBezPath { + /// Set up a new Bézier path for simplification. + /// + /// Currently this is not dealing with discontinuities at all, but it + /// could be extended to do so. + pub fn new(path: impl IntoIterator) -> Self { + let (mut a, mut x, mut y) = (0.0, 0.0, 0.0); + let els = crate::segments(path) + .map(|seg| { + let c = seg.to_cubic(); + let (ai, xi, yi) = moment_integrals(c); + a += ai; + x += xi; + y += yi; + SimplifyCubic { + c, + moments: (a, x, y), + } + }) + .collect(); + SimplifyBezPath(els) + } + + /// Resolve a `t` value to a cubic. + /// + /// Also return the resulting `t` value for the selected cubic. + fn scale(&self, t: f64) -> (usize, f64) { + let t_scale = t * self.0.len() as f64; + let t_floor = t_scale.floor(); + (t_floor as usize, t_scale - t_floor) + } + + fn moment_integrals(&self, i: usize, range: Range) -> (f64, f64, f64) { + if range.end == range.start { + (0.0, 0.0, 0.0) + } else { + moment_integrals(self.0[i].c.subsegment(range)) + } + } +} + +impl ParamCurveFit for SimplifyBezPath { + fn sample_pt_deriv(&self, t: f64) -> (Point, Vec2) { + let (mut i, mut t0) = self.scale(t); + let n = self.0.len(); + if i == n { + i -= 1; + t0 = 1.0; + } + let c = self.0[i].c; + (c.eval(t0), c.deriv().eval(t0).to_vec2() * n as f64) + } + + fn sample_pt_tangent(&self, t: f64, _: f64) -> CurveFitSample { + let (mut i, mut t0) = self.scale(t); + if i == self.0.len() { + i -= 1; + t0 = 1.0; + } + let c = self.0[i].c; + let p = c.eval(t0); + let tangent = c.deriv().eval(t0).to_vec2(); + CurveFitSample { p, tangent } + } + + // We could use the default implementation, but provide our own, mostly + // because it is possible to efficiently provide an analytically accurate + // answer. + fn moment_integrals(&self, range: Range) -> (f64, f64, f64) { + let (i0, t0) = self.scale(range.start); + let (i1, t1) = self.scale(range.end); + if i0 == i1 { + self.moment_integrals(i0, t0..t1) + } else { + let (a0, x0, y0) = self.moment_integrals(i0, t0..1.0); + let (a1, x1, y1) = self.moment_integrals(i1, 0.0..t1); + let (mut a, mut x, mut y) = (a0 + a1, x0 + x1, y0 + y1); + if i1 > i0 + 1 { + let (a2, x2, y2) = self.0[i0].moments; + let (a3, x3, y3) = self.0[i1 - 1].moments; + a += a3 - a2; + x += x3 - x2; + y += y3 - y2; + } + (a, x, y) + } + } + + fn break_cusp(&self, _: Range) -> Option { + None + } +} + +#[derive(Default)] +struct SimplifyState { + queue: BezPath, + result: BezPath, + needs_moveto: bool, +} + +impl SimplifyState { + fn add_seg(&mut self, seg: PathSeg) { + if self.queue.is_empty() { + self.queue.move_to(seg.start()); + } + match seg { + PathSeg::Line(l) => self.queue.line_to(l.p1), + PathSeg::Quad(q) => self.queue.quad_to(q.p1, q.p2), + PathSeg::Cubic(c) => self.queue.curve_to(c.p1, c.p2, c.p3), + } + } + + fn flush(&mut self, accuracy: f64, options: &SimplifyOptions) { + if self.queue.is_empty() { + return; + } + if self.queue.elements().len() == 2 { + // Queue is just one segment (count is moveto + primitive) + // Just output the segment, no simplification is possible. + self.result + .extend(self.queue.iter().skip(!self.needs_moveto as usize)); + } else { + let s = SimplifyBezPath::new(&self.queue); + let b = match options.opt_level { + SimplifyOptLevel::Subdivide => fit_to_bezpath(&s, accuracy), + SimplifyOptLevel::Optimize => fit_to_bezpath_opt(&s, accuracy), + }; + self.result + .extend(b.iter().skip(!self.needs_moveto as usize)); + } + self.needs_moveto = false; + self.queue.truncate(0); + } +} + +/// Simplify a Bézier path. +/// +/// This function simplifies an arbitrary Bézier path; it is designed to handle +/// multiple subpaths and also corners. +/// +/// The underlying curve-fitting approach works best if the source path is very +/// smooth. If it contains higher frequency noise, then results may be poor, as +/// the resulting curve matches the original with G1 continuity at each subdivision +/// point, and also preserves the area. For such inputs, consider some form of +/// smoothing or low-pass filtering before simplification. In particular, if the +/// input is derived from a sequence of points, consider fitting a smooth spline. +/// +/// We may add such capabilities in the future, possibly as opt-in smoothing +/// specified through the options. +pub fn simplify_bezpath( + path: impl IntoIterator, + accuracy: f64, + options: &SimplifyOptions, +) -> BezPath { + let mut last_pt = None; + let mut last_seg: Option = None; + let mut state = SimplifyState::default(); + for el in path { + let mut this_seg = None; + match el { + PathEl::MoveTo(p) => { + state.flush(accuracy, options); + state.needs_moveto = true; + last_pt = Some(p); + } + PathEl::LineTo(p) => { + let last = last_pt.unwrap(); + if last == p { + continue; + } + this_seg = Some(PathSeg::Line(Line::new(last, p))); + } + PathEl::QuadTo(p1, p2) => { + let last = last_pt.unwrap(); + if last == p1 && last == p2 { + continue; + } + this_seg = Some(PathSeg::Quad(QuadBez::new(last, p1, p2))); + } + PathEl::CurveTo(p1, p2, p3) => { + let last = last_pt.unwrap(); + if last == p1 && last == p2 && last == p3 { + continue; + } + this_seg = Some(PathSeg::Cubic(CubicBez::new(last, p1, p2, p3))); + } + PathEl::ClosePath => { + state.flush(accuracy, options); + state.result.close_path(); + state.needs_moveto = true; + last_seg = None; + continue; + } + } + if let Some(seg) = this_seg { + if let Some(last) = last_seg { + let last_tan = last.tangents().1; + let this_tan = seg.tangents().0; + if last_tan.cross(this_tan).abs() + > last_tan.dot(this_tan).abs() * options.angle_thresh + { + state.flush(accuracy, options); + } + } + last_pt = Some(seg.end()); + state.add_seg(seg); + } + last_seg = this_seg; + } + state.flush(accuracy, options); + state.result +} + +impl SimplifyOptions { + /// Set optimization level. + pub fn opt_level(mut self, level: SimplifyOptLevel) -> Self { + self.opt_level = level; + self + } + + /// Set angle threshold. + /// + /// The tangent of the angle below which joins are considered smooth and + /// not corners. The default is approximately 1 milliradian. + pub fn angle_thresh(mut self, thresh: f64) -> Self { + self.angle_thresh = thresh; + self + } +} + +#[cfg(test)] +mod tests { + use crate::BezPath; + + use super::{SimplifyOptions, simplify_bezpath}; + + #[test] + fn simplify_lines_corner() { + // Make sure lines are passed through unchanged if there is a corner. + let mut path = BezPath::new(); + path.move_to((1., 2.)); + path.line_to((3., 4.)); + path.line_to((10., 5.)); + let options = SimplifyOptions::default(); + let simplified = simplify_bezpath(path.clone(), 1.0, &options); + assert_eq!(path, simplified); + } +} diff --git a/vendor/kurbo/src/size.rs b/vendor/kurbo/src/size.rs new file mode 100644 index 0000000000..ad1f6c6579 --- /dev/null +++ b/vendor/kurbo/src/size.rs @@ -0,0 +1,492 @@ +// Copyright 2019 the Kurbo Authors +// SPDX-License-Identifier: Apache-2.0 OR MIT + +//! A 2D size. + +use core::fmt; +use core::ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Sub, SubAssign}; + +use crate::common::FloatExt; +use crate::{Axis, Rect, RoundedRect, RoundedRectRadii, Vec2}; + +#[cfg(not(feature = "std"))] +use crate::common::FloatFuncs; + +/// A 2D size. +#[derive(Clone, Copy, Default, PartialEq)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +pub struct Size { + /// The width. + pub width: f64, + /// The height. + pub height: f64, +} + +impl Size { + /// A size with zero width or height. + pub const ZERO: Size = Size::new(0., 0.); + + /// A size with width and height set to `f64::INFINITY`. + pub const INFINITY: Size = Size::new(f64::INFINITY, f64::INFINITY); + + /// Create a new `Size` with the provided `width` and `height`. + #[inline(always)] + pub const fn new(width: f64, height: f64) -> Self { + Size { width, height } + } + + /// Returns the max of `width` and `height`. + /// + /// # Examples + /// + /// ``` + /// use kurbo::Size; + /// let size = Size::new(-10.5, 42.0); + /// assert_eq!(size.max_side(), 42.0); + /// ``` + pub const fn max_side(self) -> f64 { + self.width.max(self.height) + } + + /// Returns the min of `width` and `height`. + /// + /// # Examples + /// + /// ``` + /// use kurbo::Size; + /// let size = Size::new(-10.5, 42.0); + /// assert_eq!(size.min_side(), -10.5); + /// ``` + pub const fn min_side(self) -> f64 { + self.width.min(self.height) + } + + /// The area covered by this size. + #[inline] + pub const fn area(self) -> f64 { + self.width * self.height + } + + /// Whether this size has zero area. + #[doc(alias = "is_empty")] + #[inline] + pub const fn is_zero_area(self) -> bool { + self.area() == 0.0 + } + + /// Returns the component-wise minimum of `self` and `other`. + /// + /// # Examples + /// + /// ``` + /// use kurbo::Size; + /// + /// let this = Size::new(0., 100.); + /// let other = Size::new(10., 10.); + /// + /// assert_eq!(this.min(other), Size::new(0., 10.)); + /// ``` + pub const fn min(self, other: Size) -> Self { + Size { + width: self.width.min(other.width), + height: self.height.min(other.height), + } + } + + /// Returns the component-wise maximum of `self` and `other`. + /// + /// # Examples + /// + /// ``` + /// use kurbo::Size; + /// + /// let this = Size::new(0., 100.); + /// let other = Size::new(10., 10.); + /// + /// assert_eq!(this.max(other), Size::new(10., 100.)); + /// ``` + pub const fn max(self, other: Size) -> Self { + Size { + width: self.width.max(other.width), + height: self.height.max(other.height), + } + } + + /// Returns a new size bounded by `min` and `max.` + /// + /// # Examples + /// + /// ``` + /// use kurbo::Size; + /// + /// let this = Size::new(0., 100.); + /// let min = Size::new(10., 10.,); + /// let max = Size::new(50., 50.); + /// assert_eq!(this.clamp(min, max), Size::new(10., 50.)) + /// ``` + pub const fn clamp(self, min: Size, max: Size) -> Self { + self.max(min).min(max) + } + + /// Convert this size into a [`Vec2`], with `width` mapped to `x` and `height` + /// mapped to `y`. + #[inline(always)] + pub const fn to_vec2(self) -> Vec2 { + Vec2::new(self.width, self.height) + } + + /// Returns a new `Size`, + /// with `width` and `height` [rounded] to the nearest integer. + /// + /// # Examples + /// + /// ``` + /// use kurbo::Size; + /// let size_pos = Size::new(3.3, 3.6).round(); + /// assert_eq!(size_pos.width, 3.0); + /// assert_eq!(size_pos.height, 4.0); + /// let size_neg = Size::new(-3.3, -3.6).round(); + /// assert_eq!(size_neg.width, -3.0); + /// assert_eq!(size_neg.height, -4.0); + /// ``` + /// + /// [rounded]: f64::round + #[inline] + pub fn round(self) -> Size { + Size::new(self.width.round(), self.height.round()) + } + + /// Returns a new `Size`, + /// with `width` and `height` [rounded up] to the nearest integer, + /// unless they are already an integer. + /// + /// # Examples + /// + /// ``` + /// use kurbo::Size; + /// let size_pos = Size::new(3.3, 3.6).ceil(); + /// assert_eq!(size_pos.width, 4.0); + /// assert_eq!(size_pos.height, 4.0); + /// let size_neg = Size::new(-3.3, -3.6).ceil(); + /// assert_eq!(size_neg.width, -3.0); + /// assert_eq!(size_neg.height, -3.0); + /// ``` + /// + /// [rounded up]: f64::ceil + #[inline] + pub fn ceil(self) -> Size { + Size::new(self.width.ceil(), self.height.ceil()) + } + + /// Returns a new `Size`, + /// with `width` and `height` [rounded down] to the nearest integer, + /// unless they are already an integer. + /// + /// # Examples + /// + /// ``` + /// use kurbo::Size; + /// let size_pos = Size::new(3.3, 3.6).floor(); + /// assert_eq!(size_pos.width, 3.0); + /// assert_eq!(size_pos.height, 3.0); + /// let size_neg = Size::new(-3.3, -3.6).floor(); + /// assert_eq!(size_neg.width, -4.0); + /// assert_eq!(size_neg.height, -4.0); + /// ``` + /// + /// [rounded down]: f64::floor + #[inline] + pub fn floor(self) -> Size { + Size::new(self.width.floor(), self.height.floor()) + } + + /// Returns a new `Size`, + /// with `width` and `height` [rounded away] from zero to the nearest integer, + /// unless they are already an integer. + /// + /// # Examples + /// + /// ``` + /// use kurbo::Size; + /// let size_pos = Size::new(3.3, 3.6).expand(); + /// assert_eq!(size_pos.width, 4.0); + /// assert_eq!(size_pos.height, 4.0); + /// let size_neg = Size::new(-3.3, -3.6).expand(); + /// assert_eq!(size_neg.width, -4.0); + /// assert_eq!(size_neg.height, -4.0); + /// ``` + /// + /// [rounded away]: FloatExt::expand + #[inline] + pub fn expand(self) -> Size { + Size::new(self.width.expand(), self.height.expand()) + } + + /// Returns a new `Size`, + /// with `width` and `height` [rounded towards] zero to the nearest integer, + /// unless they are already an integer. + /// + /// # Examples + /// + /// ``` + /// use kurbo::Size; + /// let size_pos = Size::new(3.3, 3.6).trunc(); + /// assert_eq!(size_pos.width, 3.0); + /// assert_eq!(size_pos.height, 3.0); + /// let size_neg = Size::new(-3.3, -3.6).trunc(); + /// assert_eq!(size_neg.width, -3.0); + /// assert_eq!(size_neg.height, -3.0); + /// ``` + /// + /// [rounded towards]: f64::trunc + #[inline] + pub fn trunc(self) -> Size { + Size::new(self.width.trunc(), self.height.trunc()) + } + + /// Returns the aspect ratio of a rectangle with this size. + /// + /// The aspect ratio is the ratio of the width to the height. + /// + /// If the height is `0`, the output will be `sign(self.width) * infinity`. If the width and + /// height are both `0`, then the output will be `NaN`. + #[inline] + pub const fn aspect_ratio_width(self) -> f64 { + // ratio is determined by width / height + // https://en.wikipedia.org/wiki/Aspect_ratio_(image) + // https://en.wikipedia.org/wiki/Ratio + self.width / self.height + } + + /// Returns **the inverse** of the aspect ratio of a rectangle with this size. + /// + /// Aspect ratios are usually defined as the ratio of the width to the height, but + /// this method incorrectly returns the ratio of height to width. + /// You should generally prefer [`aspect_ratio_width`](Self::aspect_ratio_width). + /// + /// If the width is `0`, the output will be `sign(self.height) * infinity`. If the width and + /// height are both `0`, then the output will be `NaN`. + #[deprecated( + note = "You should use `aspect_ratio_width` instead, as this method returns a potentially unexpected value.", + since = "0.12.0" + )] + #[inline] + // TODO: When we remove this, we should also work out what to do with aspect_ratio_width + // The tentatitive plan is to rename `aspect_ratio_width` back to this name + pub const fn aspect_ratio(self) -> f64 { + self.height / self.width + } + + /// Convert this `Size` into a [`Rect`] with origin `(0.0, 0.0)`. + #[inline(always)] + pub const fn to_rect(self) -> Rect { + Rect::new(0., 0., self.width, self.height) + } + + /// Convert this `Size` into a [`RoundedRect`] with origin `(0.0, 0.0)` and + /// the provided corner radius. + #[inline] + pub fn to_rounded_rect(self, radii: impl Into) -> RoundedRect { + self.to_rect().to_rounded_rect(radii) + } + + /// Is this size [finite]? + /// + /// [finite]: f64::is_finite + #[inline] + pub const fn is_finite(self) -> bool { + self.width.is_finite() && self.height.is_finite() + } + + /// Is this size [NaN]? + /// + /// [NaN]: f64::is_nan + #[inline] + pub const fn is_nan(self) -> bool { + self.width.is_nan() || self.height.is_nan() + } + + /// Get the member matching the given axis. + #[inline] + pub const fn get_coord(self, axis: Axis) -> f64 { + match axis { + Axis::Horizontal => self.width, + Axis::Vertical => self.height, + } + } + + /// Get a mutable reference to the member matching the given axis. + #[inline] + pub const fn get_coord_mut(&mut self, axis: Axis) -> &mut f64 { + match axis { + Axis::Horizontal => &mut self.width, + Axis::Vertical => &mut self.height, + } + } + + /// Set the member matching the given axis to the given value. + #[inline] + pub const fn set_coord(&mut self, axis: Axis, value: f64) { + match axis { + Axis::Horizontal => self.width = value, + Axis::Vertical => self.height = value, + } + } +} + +impl fmt::Debug for Size { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "{:?}W×{:?}H", self.width, self.height) + } +} + +impl fmt::Display for Size { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + write!(formatter, "(")?; + fmt::Display::fmt(&self.width, formatter)?; + write!(formatter, "×")?; + fmt::Display::fmt(&self.height, formatter)?; + write!(formatter, ")") + } +} + +impl MulAssign for Size { + #[inline] + fn mul_assign(&mut self, other: f64) { + *self = Size { + width: self.width * other, + height: self.height * other, + }; + } +} + +impl Mul for f64 { + type Output = Size; + + #[inline] + fn mul(self, other: Size) -> Size { + other * self + } +} + +impl Mul for Size { + type Output = Size; + + #[inline] + fn mul(self, other: f64) -> Size { + Size { + width: self.width * other, + height: self.height * other, + } + } +} + +impl DivAssign for Size { + #[inline] + fn div_assign(&mut self, other: f64) { + *self = Size { + width: self.width / other, + height: self.height / other, + }; + } +} + +impl Div for Size { + type Output = Size; + + #[inline] + fn div(self, other: f64) -> Size { + Size { + width: self.width / other, + height: self.height / other, + } + } +} + +impl Add for Size { + type Output = Size; + #[inline] + fn add(self, other: Size) -> Size { + Size { + width: self.width + other.width, + height: self.height + other.height, + } + } +} + +impl AddAssign for Size { + #[inline] + fn add_assign(&mut self, other: Size) { + *self = *self + other; + } +} + +impl Sub for Size { + type Output = Size; + #[inline] + fn sub(self, other: Size) -> Size { + Size { + width: self.width - other.width, + height: self.height - other.height, + } + } +} + +impl SubAssign for Size { + #[inline] + fn sub_assign(&mut self, other: Size) { + *self = *self - other; + } +} + +impl From<(f64, f64)> for Size { + #[inline(always)] + fn from(v: (f64, f64)) -> Size { + Size { + width: v.0, + height: v.1, + } + } +} + +impl From for (f64, f64) { + #[inline(always)] + fn from(v: Size) -> (f64, f64) { + (v.width, v.height) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn display() { + let s = Size::new(-0.12345, 9.87654); + assert_eq!(format!("{s}"), "(-0.12345×9.87654)"); + + let s = Size::new(-0.12345, 9.87654); + assert_eq!(format!("{s:+6.2}"), "( -0.12× +9.88)"); + } + + #[test] + #[expect(deprecated, reason = "Testing deprecated function.")] + fn aspect_ratio() { + let s = Size::new(1.0, 1.0); + assert!((s.aspect_ratio() - 1.0).abs() < 1e-6); + } + + #[test] + fn aspect_ratio_width() { + let s = Size::new(1.0, 1.0); + assert!((s.aspect_ratio_width() - 1.0).abs() < 1e-6); + + // 3:2 film (mm) + let s = Size::new(36.0, 24.0); + assert!((s.aspect_ratio_width() - 1.5).abs() < 1e-6); + // 4k screen + let s = Size::new(3840.0, 2160.0); + assert!((s.aspect_ratio_width() - (16. / 9.)).abs() < 1e-6); + } +} diff --git a/vendor/kurbo/src/stroke.rs b/vendor/kurbo/src/stroke.rs new file mode 100644 index 0000000000..4c9477d947 --- /dev/null +++ b/vendor/kurbo/src/stroke.rs @@ -0,0 +1,1181 @@ +// Copyright 2023 the Kurbo Authors +// SPDX-License-Identifier: Apache-2.0 OR MIT + +use core::{borrow::Borrow, f64::consts::PI}; + +use alloc::vec::Vec; + +use smallvec::SmallVec; + +#[cfg(not(feature = "std"))] +use crate::common::FloatFuncs; + +use crate::{ + Affine, Arc, BezPath, CubicBez, Line, ParamCurve, ParamCurveArclen, PathEl, PathSeg, Point, + QuadBez, Vec2, common::solve_quadratic, +}; + +/// Defines the connection between two segments of a stroke. +#[derive(Copy, Clone, PartialEq, Eq, Debug)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +pub enum Join { + /// A straight line connecting the segments. + Bevel, + /// The segments are extended to their natural intersection point. + Miter, + /// An arc between the segments. + Round, +} + +/// Defines the shape to be drawn at the ends of a stroke. +#[derive(Copy, Clone, PartialEq, Eq, Debug)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +pub enum Cap { + /// Flat cap. + Butt, + /// Square cap with dimensions equal to half the stroke width. + Square, + /// Rounded cap with radius equal to half the stroke width. + Round, +} + +/// The visual style of a stroke. +#[derive(Clone, Debug, PartialEq)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +pub struct Stroke { + /// Width of the stroke. + pub width: f64, + /// Style for connecting segments of the stroke. + pub join: Join, + /// Limit for miter joins. + pub miter_limit: f64, + /// Style for capping the beginning of an open subpath. + pub start_cap: Cap, + /// Style for capping the end of an open subpath. + pub end_cap: Cap, + /// Lengths of dashes in alternating on/off order. + pub dash_pattern: Dashes, + /// Offset of the first dash. + pub dash_offset: f64, +} + +/// Options for path stroking. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct StrokeOpts { + opt_level: StrokeOptLevel, + /// When `true`, dashes are emitted in the order they appear along the path. The default `false` delays a subpath's first dash so it can be merged with a dash that wraps through `ClosePath`; this option disables both the reorder and the wraparound merge, so a dash spanning the seam is truncated there. + stable_dash_order: bool, +} + +/// Optimization level for computing stroke outlines. +/// +/// Note that in the current implementation, this setting has no effect. +/// However, having a tradeoff between optimization of number of segments +/// and speed makes sense and may be added in the future, so applications +/// should set it appropriately. For real time rendering, the appropriate +/// value is `Subdivide`. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum StrokeOptLevel { + /// Adaptively subdivide segments in half. + Subdivide, + /// Compute optimized subdivision points to minimize error. + Optimized, +} + +impl Default for StrokeOpts { + fn default() -> Self { + let opt_level = StrokeOptLevel::Subdivide; + StrokeOpts { + opt_level, + stable_dash_order: false, + } + } +} + +impl Default for Stroke { + fn default() -> Self { + Self::new(1.0) + } +} + +impl Stroke { + /// Creates a new stroke with the specified width. + pub const fn new(width: f64) -> Self { + Self { + width, + join: Join::Round, + miter_limit: 4.0, + start_cap: Cap::Round, + end_cap: Cap::Round, + dash_pattern: SmallVec::new_const(), + dash_offset: 0.0, + } + } + + /// Builder method for setting the join style. + pub const fn with_join(mut self, join: Join) -> Self { + self.join = join; + self + } + + /// Builder method for setting the limit for miter joins. + pub const fn with_miter_limit(mut self, limit: f64) -> Self { + self.miter_limit = limit; + self + } + + /// Builder method for setting the cap style for the start of the stroke. + pub const fn with_start_cap(mut self, cap: Cap) -> Self { + self.start_cap = cap; + self + } + + /// Builder method for setting the cap style for the end of the stroke. + pub const fn with_end_cap(mut self, cap: Cap) -> Self { + self.end_cap = cap; + self + } + + /// Builder method for setting the cap style. + pub const fn with_caps(mut self, cap: Cap) -> Self { + self.start_cap = cap; + self.end_cap = cap; + self + } + + /// Builder method for setting the dashing parameters. + pub fn with_dashes

(mut self, offset: f64, pattern: P) -> Self + where + P: IntoIterator, + P::Item: Borrow, + { + self.dash_offset = offset; + self.dash_pattern.clear(); + self.dash_pattern + .extend(pattern.into_iter().map(|dash| *dash.borrow())); + self + } + + /// Returns `true` if all floating-point stroke parameters are [finite]. + /// + /// [finite]: f64::is_finite + pub fn is_finite(&self) -> bool { + self.width.is_finite() + && self.miter_limit.is_finite() + && self.dash_offset.is_finite() + && self.dash_pattern.iter().all(|dash| dash.is_finite()) + } + + /// Returns `true` if any floating-point stroke parameter is [`NaN`]. + /// + /// [`NaN`]: f64::is_nan + pub fn is_nan(&self) -> bool { + self.width.is_nan() + || self.miter_limit.is_nan() + || self.dash_offset.is_nan() + || self.dash_pattern.iter().any(|dash| dash.is_nan()) + } +} + +impl StrokeOpts { + /// Set optimization level for computing stroke outlines. + pub fn opt_level(mut self, opt_level: StrokeOptLevel) -> Self { + self.opt_level = opt_level; + self + } + + /// When `true`, dashes are emitted in the order they appear along the path. + pub fn stable_dash_order(mut self, stable: bool) -> Self { + self.stable_dash_order = stable; + self + } +} + +/// Collection of values representing lengths in a dash pattern. +pub type Dashes = SmallVec<[f64; 4]>; + +/// A structure that is used for creating strokes. +/// +/// See also [`stroke_with`]. +#[derive(Default, Debug)] +pub struct StrokeCtx { + // As a possible future optimization, we might not need separate storage + // for forward and backward paths, we can add forward to the output in-place. + // However, this structure is clearer and the cost fairly modest. + output: BezPath, + forward_path: BezPath, + backward_path: BezPath, + result_path: BezPath, + start_pt: Point, + start_norm: Vec2, + start_tan: Vec2, + last_pt: Point, + last_tan: Vec2, + // Precomputation of the join threshold, to optimize per-join logic. + // If hypot < (hypot + dot) * join_thresh, omit join altogether. + join_thresh: f64, +} + +impl StrokeCtx { + /// Return the path that defines the expanded stroke. + pub fn output(&self) -> &BezPath { + &self.output + } +} + +impl StrokeCtx { + fn reset(&mut self) { + self.output.truncate(0); + self.forward_path.truncate(0); + self.backward_path.truncate(0); + self.start_pt = Point::default(); + self.start_norm = Vec2::default(); + self.start_tan = Vec2::default(); + self.last_pt = Point::default(); + self.last_tan = Vec2::default(); + self.join_thresh = 0.0; + } +} + +/// Expand a stroke into a fill. +/// +/// The `tolerance` parameter controls the accuracy of the result. In general, +/// the number of subdivisions in the output scales at least to the -1/4 power +/// of the parameter, for example making it 1/16 as big generates twice as many +/// segments. Currently the algorithm is not tuned for extremely fine tolerances. +/// The theoretically optimum scaling exponent is -1/6, but achieving this may +/// require slow numerical techniques (currently a subject of research). The +/// appropriate value depends on the application; if the result of the stroke +/// will be scaled up, a smaller value is needed. +/// +/// This method attempts a fairly high degree of correctness, but ultimately +/// is based on computing parallel curves and adding joins and caps, rather than +/// computing the rigorously correct parallel sweep (which requires evolutes in +/// the general case). See [Nehab 2020] for more discussion. +/// +/// [Nehab 2020]: https://dl.acm.org/doi/10.1145/3386569.3392392 +pub fn stroke( + path: impl IntoIterator, + style: &Stroke, + opts: &StrokeOpts, + tolerance: f64, +) -> BezPath { + let mut ctx = StrokeCtx::default(); + stroke_with(path, style, opts, tolerance, &mut ctx); + + ctx.output +} + +/// Expand a stroke into a fill. +/// +/// This is the same as [`stroke`], except for the fact that you can explicitly pass a +/// `StrokeCtx`. By doing so, you can reuse the same context over multiple calls and ensure +/// that the number of reallocations is minimized. +/// +/// Unlike [`stroke`], this method doesn't return an owned version of the expanded stroke as a +/// [`BezPath`]. Instead, you can get a reference to the resulting path by calling +/// [`StrokeCtx::output`]. +pub fn stroke_with( + path: impl IntoIterator, + style: &Stroke, + opts: &StrokeOpts, + tolerance: f64, + ctx: &mut StrokeCtx, +) { + if style.dash_pattern.is_empty() { + stroke_undashed(path, style, tolerance, ctx); + } else { + let dashed = dash_iter( + path.into_iter(), + style.dash_offset, + &style.dash_pattern, + opts.stable_dash_order, + ); + stroke_undashed(dashed, style, tolerance, ctx); + } +} + +/// Version of stroke expansion for styles with no dashes. +fn stroke_undashed( + path: impl IntoIterator, + style: &Stroke, + tolerance: f64, + ctx: &mut StrokeCtx, +) { + ctx.reset(); + ctx.join_thresh = 2.0 * tolerance / style.width; + + for el in path { + let p0 = ctx.last_pt; + match el { + PathEl::MoveTo(p) => { + ctx.finish(style); + ctx.start_pt = p; + ctx.last_pt = p; + } + PathEl::LineTo(p1) => { + if p1 != p0 { + let tangent = p1 - p0; + ctx.do_join(style, tangent); + ctx.last_tan = tangent; + ctx.do_line(style, tangent, p1); + } + } + PathEl::QuadTo(p1, p2) => { + if p1 != p0 || p2 != p0 { + let q = QuadBez::new(p0, p1, p2); + let (tan0, tan1) = PathSeg::Quad(q).tangents(); + ctx.do_join(style, tan0); + ctx.do_cubic(style, q.raise(), tolerance); + ctx.last_tan = tan1; + } + } + PathEl::CurveTo(p1, p2, p3) => { + if p1 != p0 || p2 != p0 || p3 != p0 { + let c = CubicBez::new(p0, p1, p2, p3); + let (tan0, tan1) = PathSeg::Cubic(c).tangents(); + ctx.do_join(style, tan0); + ctx.do_cubic(style, c, tolerance); + ctx.last_tan = tan1; + } + } + PathEl::ClosePath => { + if p0 != ctx.start_pt { + let tangent = ctx.start_pt - p0; + ctx.do_join(style, tangent); + ctx.last_tan = tangent; + ctx.do_line(style, tangent, ctx.start_pt); + } + ctx.finish_closed(style); + } + } + } + ctx.finish(style); +} + +fn round_cap(out: &mut BezPath, tolerance: f64, center: Point, norm: Vec2) { + round_join(out, tolerance, center, norm, PI); +} + +fn round_join(out: &mut BezPath, tolerance: f64, center: Point, norm: Vec2, angle: f64) { + let a = Affine::new([norm.x, norm.y, -norm.y, norm.x, center.x, center.y]); + let arc = Arc::new(Point::ORIGIN, (1.0, 1.0), PI - angle, angle, 0.0); + arc.to_cubic_beziers(tolerance, |p1, p2, p3| out.curve_to(a * p1, a * p2, a * p3)); +} + +fn round_join_rev(out: &mut BezPath, tolerance: f64, center: Point, norm: Vec2, angle: f64) { + let a = Affine::new([norm.x, norm.y, norm.y, -norm.x, center.x, center.y]); + let arc = Arc::new(Point::ORIGIN, (1.0, 1.0), PI - angle, angle, 0.0); + arc.to_cubic_beziers(tolerance, |p1, p2, p3| out.curve_to(a * p1, a * p2, a * p3)); +} + +fn square_cap(out: &mut BezPath, close: bool, center: Point, norm: Vec2) { + let a = Affine::new([norm.x, norm.y, -norm.y, norm.x, center.x, center.y]); + out.line_to(a * Point::new(1.0, 1.0)); + out.line_to(a * Point::new(-1.0, 1.0)); + if close { + out.close_path(); + } else { + out.line_to(a * Point::new(-1.0, 0.0)); + } +} + +fn extend_reversed(out: &mut BezPath, elements: &[PathEl]) { + for i in (1..elements.len()).rev() { + let end = elements[i - 1].end_point().unwrap(); + match elements[i] { + PathEl::LineTo(_) => out.line_to(end), + PathEl::QuadTo(p1, _) => out.quad_to(p1, end), + PathEl::CurveTo(p1, p2, _) => out.curve_to(p2, p1, end), + _ => unreachable!(), + } + } +} + +impl StrokeCtx { + /// Append forward and backward paths to output. + fn finish(&mut self, style: &Stroke) { + // TODO: scale + let tolerance = 1e-3; + if self.forward_path.is_empty() { + return; + } + self.output.extend(&self.forward_path); + let back_els = self.backward_path.elements(); + let return_p = back_els[back_els.len() - 1].end_point().unwrap(); + let d = self.last_pt - return_p; + match style.end_cap { + Cap::Butt => self.output.line_to(return_p), + Cap::Round => round_cap(&mut self.output, tolerance, self.last_pt, d), + Cap::Square => square_cap(&mut self.output, false, self.last_pt, d), + } + extend_reversed(&mut self.output, back_els); + match style.start_cap { + Cap::Butt => self.output.close_path(), + Cap::Round => round_cap(&mut self.output, tolerance, self.start_pt, self.start_norm), + Cap::Square => square_cap(&mut self.output, true, self.start_pt, self.start_norm), + } + + self.forward_path.truncate(0); + self.backward_path.truncate(0); + } + + /// Finish a closed path + fn finish_closed(&mut self, style: &Stroke) { + if self.forward_path.is_empty() { + return; + } + self.do_join(style, self.start_tan); + self.output.extend(&self.forward_path); + self.output.close_path(); + let back_els = self.backward_path.elements(); + let last_pt = back_els[back_els.len() - 1].end_point().unwrap(); + self.output.move_to(last_pt); + extend_reversed(&mut self.output, back_els); + self.output.close_path(); + self.forward_path.truncate(0); + self.backward_path.truncate(0); + } + + fn do_join(&mut self, style: &Stroke, tan0: Vec2) { + // TODO: scale + let tolerance = 1e-3; + let scale = 0.5 * style.width / tan0.hypot(); + let norm = scale * Vec2::new(-tan0.y, tan0.x); + let p0 = self.last_pt; + if self.forward_path.elements().is_empty() { + self.forward_path.move_to(p0 - norm); + self.backward_path.move_to(p0 + norm); + self.start_tan = tan0; + self.start_norm = norm; + } else { + let ab = self.last_tan; + let cd = tan0; + let cross = ab.cross(cd); + let dot = ab.dot(cd); + let hypot = cross.hypot(dot); + // possible TODO: a minor speedup could be squaring both sides + if dot <= 0.0 || cross.abs() >= hypot * self.join_thresh { + match style.join { + Join::Bevel => { + self.forward_path.line_to(p0 - norm); + self.backward_path.line_to(p0 + norm); + } + Join::Miter => { + if 2.0 * hypot < (hypot + dot) * style.miter_limit.powi(2) { + // TODO: maybe better to store last_norm or derive from path? + let last_scale = 0.5 * style.width / ab.hypot(); + let last_norm = last_scale * Vec2::new(-ab.y, ab.x); + if cross > 0.0 { + let fp_last = p0 - last_norm; + let fp_this = p0 - norm; + let h = ab.cross(fp_this - fp_last) / cross; + let miter_pt = fp_this - cd * h; + self.forward_path.line_to(miter_pt); + self.backward_path.line_to(p0); + } else if cross < 0.0 { + let fp_last = p0 + last_norm; + let fp_this = p0 + norm; + let h = ab.cross(fp_this - fp_last) / cross; + let miter_pt = fp_this - cd * h; + self.backward_path.line_to(miter_pt); + self.forward_path.line_to(p0); + } + } + self.forward_path.line_to(p0 - norm); + self.backward_path.line_to(p0 + norm); + } + Join::Round => { + let angle = cross.atan2(dot); + if angle > 0.0 { + self.backward_path.line_to(p0 + norm); + round_join(&mut self.forward_path, tolerance, p0, norm, angle); + } else { + self.forward_path.line_to(p0 - norm); + round_join_rev(&mut self.backward_path, tolerance, p0, -norm, -angle); + } + } + } + } + } + } + + fn do_line(&mut self, style: &Stroke, tangent: Vec2, p1: Point) { + let scale = 0.5 * style.width / tangent.hypot(); + let norm = scale * Vec2::new(-tangent.y, tangent.x); + self.forward_path.line_to(p1 - norm); + self.backward_path.line_to(p1 + norm); + self.last_pt = p1; + } + + fn do_cubic(&mut self, style: &Stroke, c: CubicBez, tolerance: f64) { + // First, detect degenerate linear case + + // Ordinarily, this is the direction of the chord, but if the chord is very + // short, we take the longer control arm. + let chord = c.p3 - c.p0; + let mut chord_ref = chord; + let mut chord_ref_hypot2 = chord_ref.hypot2(); + let d01 = c.p1 - c.p0; + if d01.hypot2() > chord_ref_hypot2 { + chord_ref = d01; + chord_ref_hypot2 = chord_ref.hypot2(); + } + let d23 = c.p3 - c.p2; + if d23.hypot2() > chord_ref_hypot2 { + chord_ref = d23; + chord_ref_hypot2 = chord_ref.hypot2(); + } + // Project Bézier onto chord + let p0 = c.p0.to_vec2().dot(chord_ref); + let p1 = c.p1.to_vec2().dot(chord_ref); + let p2 = c.p2.to_vec2().dot(chord_ref); + let p3 = c.p3.to_vec2().dot(chord_ref); + const ENDPOINT_D: f64 = 0.01; + if p3 <= p0 + || p1 > p2 + || p1 < p0 + ENDPOINT_D * (p3 - p0) + || p2 > p3 - ENDPOINT_D * (p3 - p0) + { + // potentially a cusp inside + let x01 = d01.cross(chord_ref); + let x23 = d23.cross(chord_ref); + let x03 = chord.cross(chord_ref); + let thresh = tolerance.powi(2) * chord_ref_hypot2; + if x01 * x01 < thresh && x23 * x23 < thresh && x03 * x03 < thresh { + // control points are nearly co-linear + let midpoint = c.p0.midpoint(c.p3); + // Mapping back from projection of reference chord + let ref_vec = chord_ref / chord_ref_hypot2; + let ref_pt = midpoint - 0.5 * (p0 + p3) * ref_vec; + self.do_linear(style, c, [p0, p1, p2, p3], ref_pt, ref_vec); + return; + } + } + + crate::offset::offset_cubic(c, -0.5 * style.width, tolerance, &mut self.result_path); + self.forward_path.extend(self.result_path.iter().skip(1)); + crate::offset::offset_cubic(c, 0.5 * style.width, tolerance, &mut self.result_path); + self.backward_path.extend(self.result_path.iter().skip(1)); + self.last_pt = c.p3; + } + + /// Do a cubic which is actually linear. + /// + /// The `p` argument is the control points projected to the reference chord. + /// The ref arguments are the inverse map of a projection back to the client + /// coordinate space. + fn do_linear( + &mut self, + style: &Stroke, + c: CubicBez, + p: [f64; 4], + ref_pt: Point, + ref_vec: Vec2, + ) { + // Always do round join, to model cusp as limit of finite curvature (see Nehab). + let style = Stroke::new(style.width).with_join(Join::Round); + // Tangents of endpoints (for connecting to joins) + let (tan0, tan1) = PathSeg::Cubic(c).tangents(); + self.last_tan = tan0; + // find cusps + let c0 = p[1] - p[0]; + let c1 = 2.0 * p[2] - 4.0 * p[1] + 2.0 * p[0]; + let c2 = p[3] - 3.0 * p[2] + 3.0 * p[1] - p[0]; + let roots = solve_quadratic(c0, c1, c2); + // discard cusps right at endpoints + const EPSILON: f64 = 1e-6; + for t in roots { + if t > EPSILON && t < 1.0 - EPSILON { + let mt = 1.0 - t; + let z = mt * (mt * mt * p[0] + 3.0 * t * (mt * p[1] + t * p[2])) + t * t * t * p[3]; + let p = ref_pt + z * ref_vec; + let tan = p - self.last_pt; + self.do_join(&style, tan); + self.do_line(&style, tan, p); + self.last_tan = tan; + } + } + let tan = c.p3 - self.last_pt; + self.do_join(&style, tan); + self.do_line(&style, tan, c.p3); + self.last_tan = tan; + self.do_join(&style, tan1); + } +} + +/// An implementation of dashing as an iterator-to-iterator transformation. +struct DashIterator<'a, T> { + inner: T, + input_done: bool, + closepath_pending: bool, + dashes: &'a [f64], + dash_ix: usize, + init_dash_ix: usize, + init_dash_remaining: f64, + init_is_active: bool, + is_active: bool, + state: DashState, + current_seg: PathSeg, + t: f64, + dash_remaining: f64, + seg_remaining: f64, + start_pt: Point, + last_pt: Point, + stash: Vec, + stash_ix: usize, + stable_dash_order: bool, + needs_moveto: bool, +} + +#[derive(PartialEq, Eq)] +enum DashState { + NeedInput, + ToStash, + Working, + FromStash, +} + +impl> Iterator for DashIterator<'_, T> { + type Item = PathEl; + + fn next(&mut self) -> Option { + loop { + match self.state { + DashState::NeedInput => { + if self.input_done { + return None; + } + self.get_input(); + if self.input_done { + return None; + } + self.state = DashState::ToStash; + } + DashState::ToStash => { + if let Some(el) = self.step() { + if self.stable_dash_order { + return Some(el); + } + self.stash.push(el); + } + } + DashState::Working => { + if let Some(el) = self.step() { + return Some(el); + } + } + DashState::FromStash => { + if let Some(el) = self.stash.get(self.stash_ix) { + self.stash_ix += 1; + return Some(*el); + } else { + self.stash.clear(); + self.stash_ix = 0; + if self.input_done { + return None; + } + if self.closepath_pending { + self.closepath_pending = false; + self.state = DashState::NeedInput; + } else { + self.state = DashState::ToStash; + } + } + } + } + } + } +} + +fn seg_to_el(el: &PathSeg) -> PathEl { + match el { + PathSeg::Line(l) => PathEl::LineTo(l.p1), + PathSeg::Quad(q) => PathEl::QuadTo(q.p1, q.p2), + PathSeg::Cubic(c) => PathEl::CurveTo(c.p1, c.p2, c.p3), + } +} + +const DASH_ACCURACY: f64 = 1e-6; + +/// Create a new dashing iterator. +/// +/// Handling of dashes is fairly orthogonal to stroke expansion. This iterator +/// is an internal detail of the stroke expansion logic, but is also available +/// separately, and is expected to be useful when doing stroke expansion on +/// GPU. +/// +/// It is implemented as an iterator-to-iterator transform. Because it consumes +/// the input sequentially and produces consistent output with correct joins, +/// it requires internal state and may allocate. +/// +/// Accuracy is currently hard-coded to 1e-6. This is better than generally +/// expected, and care is taken to get cusps correct, among other things. +pub fn dash<'a>( + inner: impl Iterator + 'a, + dash_offset: f64, + dashes: &'a [f64], +) -> impl Iterator + 'a { + dash_iter(inner, dash_offset, dashes, false) +} + +fn dash_iter<'a>( + inner: impl Iterator + 'a, + dash_offset: f64, + dashes: &'a [f64], + stable_dash_order: bool, +) -> DashIterator<'a, impl Iterator + 'a> { + // Ensure that offset is positive and minimal by normalization using period + let period = dashes.iter().sum(); + // The SVG spec requires odd-length dash arrays to be doubled to become even-length: + // + // This prevents gaps and dashes from swapping with one another as the offset increases. + let period = if dashes.len() % 2 == 1 { + 2.0 * period + } else { + period + }; + let dash_offset = dash_offset.rem_euclid(period); + + let mut dash_ix = 0; + let mut dash_remaining = dashes[dash_ix] - dash_offset; + let mut is_active = true; + // Find place in dashes array for initial offset. + while dash_remaining < 0.0 { + dash_ix = (dash_ix + 1) % dashes.len(); + dash_remaining += dashes[dash_ix]; + is_active = !is_active; + } + DashIterator { + inner, + input_done: false, + closepath_pending: false, + dashes, + dash_ix, + init_dash_ix: dash_ix, + init_dash_remaining: dash_remaining, + init_is_active: is_active, + is_active, + state: DashState::NeedInput, + current_seg: PathSeg::Line(Line::new(Point::ORIGIN, Point::ORIGIN)), + t: 0.0, + dash_remaining, + seg_remaining: 0.0, + start_pt: Point::ORIGIN, + last_pt: Point::ORIGIN, + stash: Vec::new(), + stash_ix: 0, + stable_dash_order, + needs_moveto: true, + } +} + +impl<'a, T: Iterator> DashIterator<'a, T> { + fn get_input(&mut self) { + loop { + if self.closepath_pending { + self.handle_closepath(); + break; + } + let Some(next_el) = self.inner.next() else { + self.input_done = true; + self.state = DashState::FromStash; + return; + }; + let p0 = self.last_pt; + match next_el { + PathEl::MoveTo(p) => { + if !self.stash.is_empty() { + self.state = DashState::FromStash; + } + self.start_pt = p; + self.last_pt = p; + self.reset_phase(); + continue; + } + PathEl::LineTo(p1) => { + let l = Line::new(p0, p1); + self.seg_remaining = l.arclen(DASH_ACCURACY); + self.current_seg = PathSeg::Line(l); + self.last_pt = p1; + } + PathEl::QuadTo(p1, p2) => { + let q = QuadBez::new(p0, p1, p2); + self.seg_remaining = q.arclen(DASH_ACCURACY); + self.current_seg = PathSeg::Quad(q); + self.last_pt = p2; + } + PathEl::CurveTo(p1, p2, p3) => { + let c = CubicBez::new(p0, p1, p2, p3); + self.seg_remaining = c.arclen(DASH_ACCURACY); + self.current_seg = PathSeg::Cubic(c); + self.last_pt = p3; + } + PathEl::ClosePath => { + self.closepath_pending = true; + if p0 != self.start_pt { + let l = Line::new(p0, self.start_pt); + self.seg_remaining = l.arclen(DASH_ACCURACY); + self.current_seg = PathSeg::Line(l); + self.last_pt = self.start_pt; + } else { + self.handle_closepath(); + } + } + } + break; + } + self.t = 0.0; + } + + /// Move arc length forward to next event. + fn step(&mut self) -> Option { + let mut result = None; + if self.state == DashState::ToStash && self.needs_moveto { + self.needs_moveto = false; + if self.is_active { + result = Some(PathEl::MoveTo(self.current_seg.start())); + } else { + self.state = DashState::Working; + } + } else if self.dash_remaining < self.seg_remaining { + // next transition is a dash transition + let seg = self.current_seg.subsegment(self.t..1.0); + let t1 = seg.inv_arclen(self.dash_remaining, DASH_ACCURACY); + if self.is_active { + let subseg = seg.subsegment(0.0..t1); + result = Some(seg_to_el(&subseg)); + self.state = DashState::Working; + } else { + let p = seg.eval(t1); + result = Some(PathEl::MoveTo(p)); + } + self.is_active = !self.is_active; + self.t += t1 * (1.0 - self.t); + self.seg_remaining -= self.dash_remaining; + self.dash_ix += 1; + if self.dash_ix == self.dashes.len() { + self.dash_ix = 0; + } + self.dash_remaining = self.dashes[self.dash_ix]; + } else { + if self.is_active { + let seg = self.current_seg.subsegment(self.t..1.0); + result = Some(seg_to_el(&seg)); + } + self.dash_remaining -= self.seg_remaining; + self.get_input(); + } + result + } + + fn handle_closepath(&mut self) { + if self.state == DashState::ToStash { + // Have looped back without breaking a dash, just play it back + self.stash.push(PathEl::ClosePath); + } else if self.is_active && !self.stable_dash_order { + // connect with path in stash, skip MoveTo. + self.stash_ix = 1; + } + self.state = DashState::FromStash; + self.reset_phase(); + } + + fn reset_phase(&mut self) { + self.dash_ix = self.init_dash_ix; + self.dash_remaining = self.init_dash_remaining; + self.is_active = self.init_is_active; + self.needs_moveto = true; + } +} + +#[cfg(test)] +mod tests { + use super::dash_iter; + use crate::{ + BezPath, Cap::Butt, CubicBez, Join::Miter, Line, PathEl, PathSeg, Shape, Stroke, + StrokeOpts, dash, segments, stroke, + }; + + // A degenerate stroke with a cusp at the endpoint. + #[test] + fn pathological_stroke() { + let curve = CubicBez::new( + (602.469, 286.585), + (641.975, 286.585), + (562.963, 286.585), + (562.963, 286.585), + ); + let path = curve.into_path(0.1); + let stroke_style = Stroke::new(1.); + let stroked = stroke(path, &stroke_style, &StrokeOpts::default(), 0.001); + assert!(stroked.is_finite()); + } + + #[test] + /// + fn dash_miter_join() { + let path = BezPath::from_vec(vec![ + PathEl::MoveTo((70.0, 80.0).into()), + PathEl::LineTo((0.0, 80.0).into()), + PathEl::LineTo((0.0, 77.0).into()), + ]); + let expected_stroke = BezPath::from_vec(vec![ + PathEl::MoveTo((70.0, 90.0).into()), + PathEl::LineTo((0.0, 90.0).into()), + // Miter join point on forward path + PathEl::LineTo((-10.0, 90.0).into()), + PathEl::LineTo((-10.0, 80.0).into()), + PathEl::LineTo((-10.0, 77.0).into()), + PathEl::LineTo((10.0, 77.0).into()), + PathEl::LineTo((10.0, 80.0).into()), + // Miter join point on backward path + PathEl::LineTo((0.0, 80.0).into()), + PathEl::LineTo((0.0, 70.0).into()), + PathEl::LineTo((70.0, 70.0).into()), + PathEl::ClosePath, + ]); + let stroke_style = Stroke::new(20.0) + .with_join(Miter) + .with_caps(Butt) + .with_dashes(0.0, [73.0, 12.0]); + let stroke = stroke(path, &stroke_style, &StrokeOpts::default(), 0.25); + assert_eq!(stroke, expected_stroke); + } + + // Test cases adapted from https://github.com/linebender/vello/pull/388 + #[test] + fn broken_strokes() { + let broken_cubics = [ + [ + (465.24423, 107.11105), + (475.50754, 107.11105), + (475.50754, 107.11105), + (475.50754, 107.11105), + ], + [(0., -0.01), (128., 128.001), (128., -0.01), (0., 128.001)], // Near-cusp + [(0., 0.), (0., -10.), (0., -10.), (0., 10.)], // Flat line with 180 + [(10., 0.), (0., 0.), (20., 0.), (10., 0.)], // Flat line with 2 180s + [(39., -39.), (40., -40.), (40., -40.), (0., 0.)], // Flat diagonal with 180 + [(40., 40.), (0., 0.), (200., 200.), (0., 0.)], // Diag w/ an internal 180 + [(0., 0.), (1e-2, 0.), (-1e-2, 0.), (0., 0.)], // Circle + // Flat line with no turns: + [ + (400.75, 100.05), + (400.75, 100.05), + (100.05, 300.95), + (100.05, 300.95), + ], + [(0.5, 0.), (0., 0.), (20., 0.), (10., 0.)], // Flat line with 2 180s + [(10., 0.), (0., 0.), (10., 0.), (10., 0.)], // Flat line with a 180 + ]; + let stroke_style = Stroke::new(30.).with_caps(Butt).with_join(Miter); + for cubic in &broken_cubics { + let path = CubicBez::new(cubic[0], cubic[1], cubic[2], cubic[3]).into_path(0.1); + let stroked = stroke(path, &stroke_style, &StrokeOpts::default(), 0.001); + assert!(stroked.is_finite()); + } + } + + #[test] + fn dash_sequence() { + let shape = Line::new((0.0, 0.0), (21.0, 0.0)); + let dashes = [1., 5., 2., 5.]; + let expansion = [ + PathSeg::Line(Line::new((6., 0.), (8., 0.))), + PathSeg::Line(Line::new((13., 0.), (14., 0.))), + PathSeg::Line(Line::new((19., 0.), (21., 0.))), + PathSeg::Line(Line::new((0., 0.), (1., 0.))), + ]; + let iter = segments(dash(shape.path_elements(0.), 0., &dashes)); + assert_eq!(iter.collect::>(), expansion); + } + + #[test] + fn dash_sequence_closed_path() { + let shape = crate::Rect::from_points((0.0, 0.0), (4.0, 4.0)); + let dashes = [5., 1.]; + let expansion = [ + PathEl::MoveTo((4.0, 2.0).into()), + PathEl::LineTo((4.0, 4.0).into()), + PathEl::LineTo((1.0, 4.0).into()), + PathEl::MoveTo((0.0, 4.0).into()), + PathEl::LineTo((0.0, 0.0).into()), + PathEl::LineTo((4.0, 0.0).into()), + PathEl::LineTo((4.0, 1.0).into()), + ]; + let iter = dash(shape.path_elements(0.), 0., &dashes); + assert_eq!(iter.collect::>(), expansion); + } + + #[test] + fn dash_sequence_stable_order() { + let shape = Line::new((0.0, 0.0), (21.0, 0.0)); + let dashes = [1., 5., 2., 5.]; + let expansion = [ + PathSeg::Line(Line::new((0., 0.), (1., 0.))), + PathSeg::Line(Line::new((6., 0.), (8., 0.))), + PathSeg::Line(Line::new((13., 0.), (14., 0.))), + PathSeg::Line(Line::new((19., 0.), (21., 0.))), + ]; + let iter = segments(dash_iter(shape.path_elements(0.), 0., &dashes, true)); + assert_eq!(iter.collect::>(), expansion); + } + + #[test] + fn dash_sequence_closed_path_stable_order() { + let shape = crate::Rect::from_points((0.0, 0.0), (4.0, 4.0)); + let dashes = [5., 1.]; + let expansion = [ + PathEl::MoveTo((0.0, 0.0).into()), + PathEl::LineTo((4.0, 0.0).into()), + PathEl::LineTo((4.0, 1.0).into()), + PathEl::MoveTo((4.0, 2.0).into()), + PathEl::LineTo((4.0, 4.0).into()), + PathEl::LineTo((1.0, 4.0).into()), + PathEl::MoveTo((0.0, 4.0).into()), + PathEl::LineTo((0.0, 0.0).into()), + ]; + let iter = dash_iter(shape.path_elements(0.), 0., &dashes, true); + assert_eq!(iter.collect::>(), expansion); + } + + #[test] + fn dash_sequence_offset() { + // Same as dash_sequence, but with a dash offset + // of 3, which skips the first dash and cuts into + // the first gap. + let shape = Line::new((0.0, 0.0), (21.0, 0.0)); + let dashes = [1., 5., 2., 5.]; + let expansion = [ + PathSeg::Line(Line::new((3., 0.), (5., 0.))), + PathSeg::Line(Line::new((10., 0.), (11., 0.))), + PathSeg::Line(Line::new((16., 0.), (18., 0.))), + ]; + let iter = segments(dash(shape.path_elements(0.), 3., &dashes)); + assert_eq!(iter.collect::>(), expansion); + } + + // Differently-sized subpaths verify stable mode restarts the dash pattern per subpath without leaking state. + #[test] + fn dash_stable_order_multi_subpath() { + let mut path = BezPath::new(); + path.move_to((0., 0.)); + path.line_to((2., 0.)); + path.line_to((2., 2.)); + path.line_to((0., 2.)); + path.close_path(); + path.move_to((10., 10.)); + path.line_to((15., 10.)); + path.line_to((15., 14.)); + path.line_to((10., 14.)); + path.close_path(); + let dashes = [3., 1.]; + let expansion = [ + PathEl::MoveTo((0., 0.).into()), + PathEl::LineTo((2., 0.).into()), + PathEl::LineTo((2., 1.).into()), + PathEl::MoveTo((2., 2.).into()), + PathEl::LineTo((0., 2.).into()), + PathEl::LineTo((0., 1.).into()), + PathEl::MoveTo((10., 10.).into()), + PathEl::LineTo((13., 10.).into()), + PathEl::MoveTo((14., 10.).into()), + PathEl::LineTo((15., 10.).into()), + PathEl::LineTo((15., 12.).into()), + PathEl::MoveTo((15., 13.).into()), + PathEl::LineTo((15., 14.).into()), + PathEl::LineTo((13., 14.).into()), + PathEl::MoveTo((12., 14.).into()), + PathEl::LineTo((10., 14.).into()), + PathEl::LineTo((10., 13.).into()), + PathEl::MoveTo((10., 12.).into()), + PathEl::LineTo((10., 10.).into()), + ]; + let iter = dash_iter(path.into_iter(), 0., &dashes, true); + assert_eq!(iter.collect::>(), expansion); + } + + #[test] + fn dash_negative_offset() { + let shape = Line::new((0.0, 0.0), (28.0, 0.0)); + let dashes = [4., 2.]; + let pos = segments(dash(shape.path_elements(0.), 60., &dashes)).collect::>(); + let neg = segments(dash(shape.path_elements(0.), -60., &dashes)).collect::>(); + assert_eq!(neg, pos); + } + + #[test] + fn dash_odd_length_matches_doubled() { + let shape = Line::new((0.0, 0.0), (50.0, 0.0)); + let odd = [10.]; + let doubled = [10., 10.]; + for offset in [0., 5., 9., 10., 11., 15., 20., 25., 100., -7.] { + let from_odd = + segments(dash(shape.path_elements(0.), offset, &odd)).collect::>(); + let from_doubled = + segments(dash(shape.path_elements(0.), offset, &doubled)).collect::>(); + assert_eq!(from_odd, from_doubled, "mismatch at offset {offset}"); + } + } + + #[test] + fn dash_three_element_matches_doubled() { + let shape = Line::new((0.0, 0.0), (200.0, 0.0)); + let three = [20., 10., 3.]; + let doubled = [20., 10., 3., 20., 10., 3.]; + for offset in [0., 15., 32., 33., 34., 50., 66., 99.] { + let from_three = + segments(dash(shape.path_elements(0.), offset, &three)).collect::>(); + let from_doubled = + segments(dash(shape.path_elements(0.), offset, &doubled)).collect::>(); + assert_eq!(from_three, from_doubled, "mismatch at offset {offset}"); + } + } + + #[test] + fn stroke_is_finite_fields() { + let finite = Stroke::new(2.0) + .with_miter_limit(4.0) + .with_dashes(0.0, [1.0, 2.0]); + assert!(finite.is_finite()); + + let non_finite_width = Stroke::new(f64::INFINITY); + assert!(!non_finite_width.is_finite()); + + let non_finite_miter = Stroke::new(2.0).with_miter_limit(f64::NAN); + assert!(!non_finite_miter.is_finite()); + + let non_finite_dash_offset = Stroke::new(2.0).with_dashes(f64::NEG_INFINITY, [1.0, 2.0]); + assert!(!non_finite_dash_offset.is_finite()); + + let non_finite_dash_pattern = Stroke::new(2.0).with_dashes(0.0, [1.0, f64::NAN]); + assert!(!non_finite_dash_pattern.is_finite()); + } + + #[test] + fn stroke_is_nan_fields() { + let finite = Stroke::new(2.0) + .with_miter_limit(4.0) + .with_dashes(0.0, [1.0, 2.0]); + assert!(!finite.is_nan()); + + let nan_width = Stroke::new(f64::NAN); + assert!(nan_width.is_nan()); + + let nan_miter = Stroke::new(2.0).with_miter_limit(f64::NAN); + assert!(nan_miter.is_nan()); + + let nan_dash_offset = Stroke::new(2.0).with_dashes(f64::NAN, [1.0, 2.0]); + assert!(nan_dash_offset.is_nan()); + + let nan_dash_pattern = Stroke::new(2.0).with_dashes(0.0, [1.0, f64::NAN]); + assert!(nan_dash_pattern.is_nan()); + + let infinite_width = Stroke::new(f64::INFINITY); + assert!(!infinite_width.is_nan()); + } +} diff --git a/vendor/kurbo/src/svg.rs b/vendor/kurbo/src/svg.rs new file mode 100644 index 0000000000..0935381d61 --- /dev/null +++ b/vendor/kurbo/src/svg.rs @@ -0,0 +1,692 @@ +// Copyright 2018 the Kurbo Authors +// SPDX-License-Identifier: Apache-2.0 OR MIT + +//! SVG path representation. + +use alloc::vec::Vec; +use core::error::Error; +use core::f64::consts::PI; +use core::fmt::{self, Display, Formatter}; +#[cfg(feature = "std")] +use std::io::{self, Write}; + +use crate::{Arc, BezPath, ParamCurve, PathEl, PathSeg, Point, Vec2}; + +#[cfg(not(feature = "std"))] +use crate::common::FloatFuncs; + +// Note: the SVG arc logic is heavily adapted from https://github.com/nical/lyon + +/// A single SVG arc segment. +#[derive(Clone, Copy, Debug)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +pub struct SvgArc { + /// The arc's start point. + pub from: Point, + /// The arc's end point. + pub to: Point, + /// The arc's radii, where the vector's x-component is the radius in the + /// positive x direction after applying `x_rotation`. + pub radii: Vec2, + /// How much the arc is rotated, in radians. + pub x_rotation: f64, + /// Does this arc sweep through more than π radians? + pub large_arc: bool, + /// Determines if the arc should begin moving at positive angles. + pub sweep: bool, +} + +impl BezPath { + /// Create a `BezPath` with segments corresponding to the sequence of + /// `PathSeg`s + pub fn from_path_segments(segments: impl Iterator) -> BezPath { + let mut path_elements = Vec::new(); + let mut current_pos = None; + + for segment in segments { + let start = segment.start(); + if Some(start) != current_pos { + path_elements.push(PathEl::MoveTo(start)); + } + path_elements.push(match segment { + PathSeg::Line(l) => PathEl::LineTo(l.p1), + PathSeg::Quad(q) => PathEl::QuadTo(q.p1, q.p2), + PathSeg::Cubic(c) => PathEl::CurveTo(c.p1, c.p2, c.p3), + }); + + current_pos = Some(segment.end()); + } + + BezPath::from_vec(path_elements) + } + + /// Convert the path to an SVG path string representation. + /// + /// The current implementation doesn't take any special care to produce a + /// short string (reducing precision, using relative movement). + #[cfg(feature = "std")] + pub fn to_svg(&self) -> String { + let mut buffer = Vec::new(); + self.write_to(&mut buffer).unwrap(); + String::from_utf8(buffer).unwrap() + } + + /// Write the SVG representation of this path to the provided buffer. + #[cfg(feature = "std")] + pub fn write_to(&self, mut writer: W) -> io::Result<()> { + for (i, el) in self.elements().iter().enumerate() { + if i > 0 { + write!(writer, " ")?; + } + match *el { + PathEl::MoveTo(p) => write!(writer, "M{},{}", p.x, p.y)?, + PathEl::LineTo(p) => write!(writer, "L{},{}", p.x, p.y)?, + PathEl::QuadTo(p1, p2) => write!(writer, "Q{},{} {},{}", p1.x, p1.y, p2.x, p2.y)?, + PathEl::CurveTo(p1, p2, p3) => write!( + writer, + "C{},{} {},{} {},{}", + p1.x, p1.y, p2.x, p2.y, p3.x, p3.y + )?, + PathEl::ClosePath => write!(writer, "Z")?, + } + } + + Ok(()) + } + + /// Try to parse a bezier path from an SVG path element. + /// + /// This is implemented on a best-effort basis, intended for cases where the + /// user controls the source of paths, and is not intended as a replacement + /// for a general, robust SVG parser. + pub fn from_svg(data: &str) -> Result { + let mut lexer = SvgLexer::new(data); + let mut path = BezPath::new(); + let mut last_cmd = 0; + let mut last_ctrl = None; + let mut first_pt = Point::ORIGIN; + let mut implicit_moveto = None; + while let Some(c) = lexer.get_cmd(last_cmd) { + if c != b'm' && c != b'M' { + if path.elements().is_empty() { + return Err(SvgParseError::UninitializedPath); + } + + if let Some(pt) = implicit_moveto.take() { + path.move_to(pt); + } + } + match c { + b'm' | b'M' => { + implicit_moveto = None; + let pt = lexer.get_maybe_relative(c)?; + path.move_to(pt); + lexer.last_pt = pt; + first_pt = pt; + last_ctrl = Some(pt); + last_cmd = c - (b'M' - b'L'); + } + b'l' | b'L' => { + let pt = lexer.get_maybe_relative(c)?; + path.line_to(pt); + lexer.last_pt = pt; + last_ctrl = Some(pt); + last_cmd = c; + } + b'h' | b'H' => { + let mut x = lexer.get_number()?; + lexer.opt_comma(); + if c == b'h' { + x += lexer.last_pt.x; + } + let pt = Point::new(x, lexer.last_pt.y); + path.line_to(pt); + lexer.last_pt = pt; + last_ctrl = Some(pt); + last_cmd = c; + } + b'v' | b'V' => { + let mut y = lexer.get_number()?; + lexer.opt_comma(); + if c == b'v' { + y += lexer.last_pt.y; + } + let pt = Point::new(lexer.last_pt.x, y); + path.line_to(pt); + lexer.last_pt = pt; + last_ctrl = Some(pt); + last_cmd = c; + } + b'q' | b'Q' => { + let p1 = lexer.get_maybe_relative(c)?; + let p2 = lexer.get_maybe_relative(c)?; + path.quad_to(p1, p2); + last_ctrl = Some(p1); + lexer.last_pt = p2; + last_cmd = c; + } + b't' | b'T' => { + let p1 = match last_ctrl { + Some(ctrl) => (2.0 * lexer.last_pt.to_vec2() - ctrl.to_vec2()).to_point(), + None => lexer.last_pt, + }; + let p2 = lexer.get_maybe_relative(c)?; + path.quad_to(p1, p2); + last_ctrl = Some(p1); + lexer.last_pt = p2; + last_cmd = c; + } + b'c' | b'C' => { + let p1 = lexer.get_maybe_relative(c)?; + let p2 = lexer.get_maybe_relative(c)?; + let p3 = lexer.get_maybe_relative(c)?; + path.curve_to(p1, p2, p3); + last_ctrl = Some(p2); + lexer.last_pt = p3; + last_cmd = c; + } + b's' | b'S' => { + let p1 = match last_ctrl { + Some(ctrl) => (2.0 * lexer.last_pt.to_vec2() - ctrl.to_vec2()).to_point(), + None => lexer.last_pt, + }; + let p2 = lexer.get_maybe_relative(c)?; + let p3 = lexer.get_maybe_relative(c)?; + path.curve_to(p1, p2, p3); + last_ctrl = Some(p2); + lexer.last_pt = p3; + last_cmd = c; + } + b'a' | b'A' => { + let radii = lexer.get_number_pair()?; + let x_rotation = lexer.get_number()?.to_radians(); + lexer.opt_comma(); + let large_arc = lexer.get_flag()?; + lexer.opt_comma(); + let sweep = lexer.get_flag()?; + lexer.opt_comma(); + let p = lexer.get_maybe_relative(c)?; + let svg_arc = SvgArc { + from: lexer.last_pt, + to: p, + radii: radii.to_vec2(), + x_rotation, + large_arc, + sweep, + }; + + match Arc::from_svg_arc(&svg_arc) { + Some(arc) => { + // TODO: consider making tolerance configurable + arc.to_cubic_beziers(0.1, |p1, p2, p3| { + path.curve_to(p1, p2, p3); + }); + } + None => { + path.line_to(p); + } + } + + last_ctrl = Some(p); + lexer.last_pt = p; + last_cmd = c; + } + b'z' | b'Z' => { + path.close_path(); + lexer.last_pt = first_pt; + implicit_moveto = Some(first_pt); + } + _ => return Err(SvgParseError::UnknownCommand(c as char)), + } + } + Ok(path) + } +} + +/// An error which can be returned when parsing an SVG. +#[derive(Debug)] +#[non_exhaustive] +pub enum SvgParseError { + /// A number was expected. + Wrong, + /// The input string ended while still expecting input. + UnexpectedEof, + /// Encountered an unknown command letter. + UnknownCommand(char), + /// Encountered a command that precedes expected 'moveto' command. + UninitializedPath, +} + +impl Display for SvgParseError { + fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { + match self { + SvgParseError::Wrong => write!(f, "Unable to parse a number"), + SvgParseError::UnexpectedEof => write!(f, "Unexpected EOF"), + SvgParseError::UnknownCommand(letter) => write!(f, "Unknown command, \"{letter}\""), + SvgParseError::UninitializedPath => { + write!(f, "Uninitialized path (missing moveto command)") + } + } + } +} + +impl Error for SvgParseError {} + +struct SvgLexer<'a> { + data: &'a str, + ix: usize, + pub last_pt: Point, +} + +impl SvgLexer<'_> { + fn new(data: &str) -> SvgLexer<'_> { + SvgLexer { + data, + ix: 0, + last_pt: Point::ORIGIN, + } + } + + fn skip_ws(&mut self) { + while let Some(&c) = self.data.as_bytes().get(self.ix) { + if !(c == b' ' || c == 9 || c == 10 || c == 12 || c == 13) { + break; + } + self.ix += 1; + } + } + + fn get_cmd(&mut self, last_cmd: u8) -> Option { + self.skip_ws(); + if let Some(c) = self.get_byte() { + if c.is_ascii_lowercase() || c.is_ascii_uppercase() { + return Some(c); + } else if last_cmd != 0 && (c == b'-' || c == b'.' || c.is_ascii_digit()) { + // Plausible number start + self.unget(); + return Some(last_cmd); + } else { + self.unget(); + } + } + None + } + + fn get_byte(&mut self) -> Option { + self.data.as_bytes().get(self.ix).map(|&c| { + self.ix += 1; + c + }) + } + + fn unget(&mut self) { + self.ix -= 1; + } + + fn get_number(&mut self) -> Result { + self.skip_ws(); + let start = self.ix; + let c = self.get_byte().ok_or(SvgParseError::UnexpectedEof)?; + if !(c == b'-' || c == b'+') { + self.unget(); + } + let mut digit_count = 0; + let mut seen_period = false; + while let Some(c) = self.get_byte() { + if c.is_ascii_digit() { + digit_count += 1; + } else if c == b'.' && !seen_period { + seen_period = true; + } else { + self.unget(); + break; + } + } + if let Some(c) = self.get_byte() { + if c == b'e' || c == b'E' { + let mut c = self.get_byte().ok_or(SvgParseError::Wrong)?; + if c == b'-' || c == b'+' { + c = self.get_byte().ok_or(SvgParseError::Wrong)?; + } + if !c.is_ascii_digit() { + return Err(SvgParseError::Wrong); + } + while let Some(c) = self.get_byte() { + if !c.is_ascii_digit() { + self.unget(); + break; + } + } + } else { + self.unget(); + } + } + if digit_count > 0 { + self.data[start..self.ix] + .parse() + .map_err(|_| SvgParseError::Wrong) + } else { + Err(SvgParseError::Wrong) + } + } + + fn get_flag(&mut self) -> Result { + self.skip_ws(); + match self.get_byte().ok_or(SvgParseError::UnexpectedEof)? { + b'0' => Ok(false), + b'1' => Ok(true), + _ => Err(SvgParseError::Wrong), + } + } + + fn get_number_pair(&mut self) -> Result { + let x = self.get_number()?; + self.opt_comma(); + let y = self.get_number()?; + self.opt_comma(); + Ok(Point::new(x, y)) + } + + fn get_maybe_relative(&mut self, cmd: u8) -> Result { + let pt = self.get_number_pair()?; + if cmd.is_ascii_lowercase() { + Ok(self.last_pt + pt.to_vec2()) + } else { + Ok(pt) + } + } + + fn opt_comma(&mut self) { + self.skip_ws(); + if let Some(c) = self.get_byte() { + if c != b',' { + self.unget(); + } + } + } +} + +impl SvgArc { + /// Checks that arc is actually a straight line. + /// + /// In this case, it can be replaced with a `LineTo`. + pub fn is_straight_line(&self) -> bool { + self.radii.x.abs() <= 1e-5 || self.radii.y.abs() <= 1e-5 || self.from == self.to + } +} + +impl Arc { + /// Creates an `Arc` from a `SvgArc`. + /// + /// Returns `None` if `arc` is actually a straight line. + pub fn from_svg_arc(arc: &SvgArc) -> Option { + // Have to check this first, otherwise `sum_of_sq` will be 0. + if arc.is_straight_line() { + return None; + } + + let mut rx = arc.radii.x.abs(); + let mut ry = arc.radii.y.abs(); + + let xr = arc.x_rotation % (2.0 * PI); + let (sin_phi, cos_phi) = xr.sin_cos(); + let hd_x = (arc.from.x - arc.to.x) * 0.5; + let hd_y = (arc.from.y - arc.to.y) * 0.5; + let hs_x = (arc.from.x + arc.to.x) * 0.5; + let hs_y = (arc.from.y + arc.to.y) * 0.5; + + // F6.5.1 + let p = Vec2::new( + cos_phi * hd_x + sin_phi * hd_y, + -sin_phi * hd_x + cos_phi * hd_y, + ); + + // Sanitize the radii. + // If rf > 1 it means the radii are too small for the arc to + // possibly connect the end points. In this situation we scale + // them up according to the formula provided by the SVG spec. + + // F6.6.2 + let rf = p.x * p.x / (rx * rx) + p.y * p.y / (ry * ry); + if rf > 1.0 { + let scale = rf.sqrt(); + rx *= scale; + ry *= scale; + } + + let rxry = rx * ry; + let rxpy = rx * p.y; + let rypx = ry * p.x; + let sum_of_sq = rxpy * rxpy + rypx * rypx; + + debug_assert!(sum_of_sq != 0.0); + + // F6.5.2 + let sign_coe = if arc.large_arc == arc.sweep { + -1.0 + } else { + 1.0 + }; + let coe = sign_coe * ((rxry * rxry - sum_of_sq) / sum_of_sq).abs().sqrt(); + let transformed_cx = coe * rxpy / ry; + let transformed_cy = -coe * rypx / rx; + + // F6.5.3 + let center = Point::new( + cos_phi * transformed_cx - sin_phi * transformed_cy + hs_x, + sin_phi * transformed_cx + cos_phi * transformed_cy + hs_y, + ); + + let start_v = Vec2::new((p.x - transformed_cx) / rx, (p.y - transformed_cy) / ry); + let end_v = Vec2::new((-p.x - transformed_cx) / rx, (-p.y - transformed_cy) / ry); + + let start_angle = start_v.atan2(); + + let mut sweep_angle = (end_v.atan2() - start_angle) % (2.0 * PI); + + if arc.sweep && sweep_angle < 0.0 { + sweep_angle += 2.0 * PI; + } else if !arc.sweep && sweep_angle > 0.0 { + sweep_angle -= 2.0 * PI; + } + + Some(Arc { + center, + radii: Vec2::new(rx, ry), + start_angle, + sweep_angle, + x_rotation: arc.x_rotation, + }) + } +} + +#[cfg(test)] +mod tests { + use crate::{BezPath, CubicBez, Line, ParamCurve, PathEl, PathSeg, Point, QuadBez, Shape}; + + #[test] + fn test_parse_svg() { + let path = BezPath::from_svg("m10 10 100 0 0 100 -100 0z").unwrap(); + assert_eq!(path.segments().count(), 4); + } + + #[test] + fn test_parse_svg2() { + let path = + BezPath::from_svg("M3.5 8a.5.5 0 01.5-.5h8a.5.5 0 010 1H4a.5.5 0 01-.5-.5z").unwrap(); + assert_eq!(path.segments().count(), 6); + } + + #[test] + fn test_parse_svg_arc() { + let path = BezPath::from_svg("M 100 100 A 25 25 0 1 0 -25 25 z").unwrap(); + assert_eq!(path.segments().count(), 3); + } + + // Regression test for #51 + #[test] + #[allow(clippy::float_cmp)] + fn test_parse_svg_arc_pie() { + let path = BezPath::from_svg("M 100 100 h 25 a 25 25 0 1 0 -25 25 z").unwrap(); + // Approximate figures, but useful for regression testing + assert_eq!(path.area().round(), -1473.0); + assert_eq!(path.perimeter(1e-6).round(), 168.0); + } + + #[test] + fn test_parse_svg_uninitialized() { + let path = BezPath::from_svg("L10 10 100 0 0 100"); + assert!(path.is_err()); + } + + #[test] + #[allow(clippy::float_cmp)] + fn test_parse_scientific_notation() { + let path = BezPath::from_svg("M 0 0 L 1e-123 -4E+5").unwrap(); + assert_eq!( + path.elements(), + &[ + PathEl::MoveTo(Point { x: 0.0, y: 0.0 }), + PathEl::LineTo(Point { + x: 1e-123, + y: -4E+5 + }) + ] + ); + } + + #[test] + fn test_write_svg_single() { + let segments = [CubicBez::new( + Point::new(10., 10.), + Point::new(20., 20.), + Point::new(30., 30.), + Point::new(40., 40.), + ) + .into()]; + let path = BezPath::from_path_segments(segments.iter().cloned()); + + assert_eq!(path.to_svg(), "M10,10 C20,20 30,30 40,40"); + } + + #[test] + fn test_write_svg_two_nomove() { + let segments = [ + CubicBez::new( + Point::new(10., 10.), + Point::new(20., 20.), + Point::new(30., 30.), + Point::new(40., 40.), + ) + .into(), + CubicBez::new( + Point::new(40., 40.), + Point::new(30., 30.), + Point::new(20., 20.), + Point::new(10., 10.), + ) + .into(), + ]; + let path = BezPath::from_path_segments(segments.iter().cloned()); + + assert_eq!( + path.to_svg(), + "M10,10 C20,20 30,30 40,40 C30,30 20,20 10,10" + ); + } + + #[test] + fn test_write_svg_two_move() { + let segments = [ + CubicBez::new( + Point::new(10., 10.), + Point::new(20., 20.), + Point::new(30., 30.), + Point::new(40., 40.), + ) + .into(), + CubicBez::new( + Point::new(50., 50.), + Point::new(30., 30.), + Point::new(20., 20.), + Point::new(10., 10.), + ) + .into(), + ]; + let path = BezPath::from_path_segments(segments.iter().cloned()); + + assert_eq!( + path.to_svg(), + "M10,10 C20,20 30,30 40,40 M50,50 C30,30 20,20 10,10" + ); + } + + use rand::prelude::*; + // Suppress the unused_crate_dependencies lint for getrandom. + #[cfg(all( + target_arch = "wasm32", + target_vendor = "unknown", + target_os = "unknown" + ))] + use getrandom as _; + + fn gen_random_path_sequence(rng: &mut impl Rng) -> Vec { + const MAX_LENGTH: u32 = 10; + + let mut elements = vec![]; + let mut position = None; + + let length = rng.random_range(0..MAX_LENGTH); + for _ in 0..length { + let should_follow: bool = rand::random_bool(0.5); + let kind = rng.random_range(0..3); + + let first = position + .filter(|_| should_follow) + .unwrap_or_else(|| Point::new(rng.random(), rng.random())); + + let element: PathSeg = match kind { + 0 => Line::new(first, Point::new(rng.random(), rng.random())).into(), + + 1 => QuadBez::new( + first, + Point::new(rng.random(), rng.random()), + Point::new(rng.random(), rng.random()), + ) + .into(), + + 2 => CubicBez::new( + first, + Point::new(rng.random(), rng.random()), + Point::new(rng.random(), rng.random()), + Point::new(rng.random(), rng.random()), + ) + .into(), + + _ => unreachable!(), + }; + + position = Some(element.end()); + elements.push(element); + } + + elements + } + + #[test] + fn test_serialize_deserialize() { + const N_TESTS: u32 = 100; + let mut rng = rand::rng(); + + for _ in 0..N_TESTS { + let vec = gen_random_path_sequence(&mut rng); + let ser = BezPath::from_path_segments(vec.iter().cloned()).to_svg(); + let deser = BezPath::from_svg(&ser).expect("failed deserialization"); + + let deser_vec = deser.segments().collect::>(); + + assert_eq!(vec, deser_vec); + } + } +} diff --git a/vendor/kurbo/src/translate_scale.rs b/vendor/kurbo/src/translate_scale.rs new file mode 100644 index 0000000000..d9db142639 --- /dev/null +++ b/vendor/kurbo/src/translate_scale.rs @@ -0,0 +1,345 @@ +// Copyright 2019 the Kurbo Authors +// SPDX-License-Identifier: Apache-2.0 OR MIT + +//! A transformation that includes both scale and translation. + +use core::ops::{Add, AddAssign, Mul, MulAssign, Sub, SubAssign}; + +use crate::{ + Affine, Circle, CubicBez, Line, Point, QuadBez, Rect, RoundedRect, RoundedRectRadii, Vec2, +}; + +/// A transformation consisting of a uniform scaling followed by a translation. +/// +/// If the translation is `(x, y)` and the scale is `s`, then this +/// transformation represents this augmented matrix: +/// +/// ```text +/// | s 0 x | +/// | 0 s y | +/// | 0 0 1 | +/// ``` +/// +/// See [`Affine`] for more details about the +/// equivalence with augmented matrices. +/// +/// Various multiplication ops are defined, and these are all defined +/// to be consistent with matrix multiplication. Therefore, +/// `TranslateScale * Point` is defined but not the other way around. +/// +/// Also note that multiplication is not commutative. Thus, +/// `TranslateScale::scale(2.0) * TranslateScale::translate(Vec2::new(1.0, 0.0))` +/// has a translation of (2, 0), while +/// `TranslateScale::translate(Vec2::new(1.0, 0.0)) * TranslateScale::scale(2.0)` +/// has a translation of (1, 0). (Both have a scale of 2; also note that +/// the first case can be written +/// `2.0 * TranslateScale::translate(Vec2::new(1.0, 0.0))` as this case +/// has an implicit conversion). +/// +/// This transformation is less powerful than [`Affine`], but can be applied +/// to more primitives, especially including [`Rect`]. +#[derive(Clone, Copy, Debug)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +pub struct TranslateScale { + /// The translation component of this transformation + pub translation: Vec2, + /// The scale component of this transformation + pub scale: f64, +} + +impl TranslateScale { + /// Create a new transformation from translation and scale. + #[inline(always)] + pub const fn new(translation: Vec2, scale: f64) -> TranslateScale { + TranslateScale { translation, scale } + } + + /// Create a new transformation with scale only. + #[inline(always)] + pub const fn scale(s: f64) -> TranslateScale { + TranslateScale::new(Vec2::ZERO, s) + } + + /// Create a new transformation with translation only. + #[inline(always)] + pub fn translate(translation: impl Into) -> TranslateScale { + TranslateScale::new(translation.into(), 1.0) + } + + /// Create a transform that scales about a point other than the origin. + /// + /// # Examples + /// + /// ``` + /// # use kurbo::{Point, TranslateScale}; + /// # fn assert_near(p0: Point, p1: Point) { + /// # assert!((p1 - p0).hypot() < 1e-9, "{p0:?} != {p1:?}"); + /// # } + /// let center = Point::new(1., 1.); + /// let ts = TranslateScale::from_scale_about(2., center); + /// // Should keep the point (1., 1.) stationary + /// assert_near(ts * center, center); + /// // (2., 2.) -> (3., 3.) + /// assert_near(ts * Point::new(2., 2.), Point::new(3., 3.)); + /// ``` + #[inline] + pub fn from_scale_about(scale: f64, focus: impl Into) -> Self { + // We need to create a transform that is equivalent to translating `focus` + // to the origin, followed by a normal scale, followed by reversing the translation. + // We need to find the (translation ∘ scale) that matches this. + let focus = focus.into().to_vec2(); + let translation = focus - focus * scale; + Self::new(translation, scale) + } + + /// Compute the inverse transform. + /// + /// Multiplying a transform with its inverse (either on the + /// left or right) results in the identity transform + /// (modulo floating point rounding errors). + /// + /// Produces NaN values when scale is zero. + #[inline] + pub fn inverse(self) -> TranslateScale { + let scale_recip = self.scale.recip(); + TranslateScale { + translation: self.translation * -scale_recip, + scale: scale_recip, + } + } + + /// Is this translate/scale [finite]? + /// + /// [finite]: f64::is_finite + #[inline] + pub fn is_finite(&self) -> bool { + self.translation.is_finite() && self.scale.is_finite() + } + + /// Is this translate/scale [NaN]? + /// + /// [NaN]: f64::is_nan + #[inline] + pub fn is_nan(&self) -> bool { + self.translation.is_nan() || self.scale.is_nan() + } +} + +impl Default for TranslateScale { + #[inline(always)] + fn default() -> TranslateScale { + TranslateScale::new(Vec2::ZERO, 1.0) + } +} + +impl From for Affine { + #[inline(always)] + fn from(ts: TranslateScale) -> Affine { + let TranslateScale { translation, scale } = ts; + Affine::new([scale, 0.0, 0.0, scale, translation.x, translation.y]) + } +} + +impl Mul for TranslateScale { + type Output = Point; + + #[inline] + fn mul(self, other: Point) -> Point { + (self.scale * other.to_vec2()).to_point() + self.translation + } +} + +impl Mul for TranslateScale { + type Output = TranslateScale; + + #[inline] + fn mul(self, other: TranslateScale) -> TranslateScale { + TranslateScale { + translation: self.translation + self.scale * other.translation, + scale: self.scale * other.scale, + } + } +} + +impl MulAssign for TranslateScale { + #[inline] + fn mul_assign(&mut self, other: TranslateScale) { + *self = self.mul(other); + } +} + +impl Mul for f64 { + type Output = TranslateScale; + + #[inline] + fn mul(self, other: TranslateScale) -> TranslateScale { + TranslateScale { + translation: other.translation * self, + scale: other.scale * self, + } + } +} + +impl Add for TranslateScale { + type Output = TranslateScale; + + #[inline] + fn add(self, other: Vec2) -> TranslateScale { + TranslateScale { + translation: self.translation + other, + scale: self.scale, + } + } +} + +impl Add for Vec2 { + type Output = TranslateScale; + + #[inline] + fn add(self, other: TranslateScale) -> TranslateScale { + other + self + } +} + +impl AddAssign for TranslateScale { + #[inline] + fn add_assign(&mut self, other: Vec2) { + *self = self.add(other); + } +} + +impl Sub for TranslateScale { + type Output = TranslateScale; + + #[inline] + fn sub(self, other: Vec2) -> TranslateScale { + TranslateScale { + translation: self.translation - other, + scale: self.scale, + } + } +} + +impl SubAssign for TranslateScale { + #[inline] + fn sub_assign(&mut self, other: Vec2) { + *self = self.sub(other); + } +} + +impl Mul for TranslateScale { + type Output = Circle; + + #[inline] + fn mul(self, other: Circle) -> Circle { + Circle::new(self * other.center, self.scale * other.radius) + } +} + +impl Mul for TranslateScale { + type Output = Line; + + #[inline] + fn mul(self, other: Line) -> Line { + Line::new(self * other.p0, self * other.p1) + } +} + +impl Mul for TranslateScale { + type Output = Rect; + + #[inline] + fn mul(self, other: Rect) -> Rect { + let pt0 = self * Point::new(other.x0, other.y0); + let pt1 = self * Point::new(other.x1, other.y1); + (pt0, pt1).into() + } +} + +impl Mul for TranslateScale { + type Output = RoundedRect; + + #[inline] + fn mul(self, other: RoundedRect) -> RoundedRect { + RoundedRect::from_rect(self * other.rect(), self * other.radii()) + } +} + +impl Mul for TranslateScale { + type Output = RoundedRectRadii; + + #[inline] + fn mul(self, other: RoundedRectRadii) -> RoundedRectRadii { + RoundedRectRadii::new( + self.scale * other.top_left, + self.scale * other.top_right, + self.scale * other.bottom_right, + self.scale * other.bottom_left, + ) + } +} + +impl Mul for TranslateScale { + type Output = QuadBez; + + #[inline] + fn mul(self, other: QuadBez) -> QuadBez { + QuadBez::new(self * other.p0, self * other.p1, self * other.p2) + } +} + +impl Mul for TranslateScale { + type Output = CubicBez; + + #[inline] + fn mul(self, other: CubicBez) -> CubicBez { + CubicBez::new( + self * other.p0, + self * other.p1, + self * other.p2, + self * other.p3, + ) + } +} + +#[cfg(test)] +mod tests { + use crate::{Affine, Point, TranslateScale, Vec2}; + + fn assert_near(p0: Point, p1: Point) { + assert!((p1 - p0).hypot() < 1e-9, "{p0:?} != {p1:?}"); + } + + #[test] + fn translate_scale() { + let p = Point::new(3.0, 4.0); + let ts = TranslateScale::new(Vec2::new(5.0, 6.0), 2.0); + + assert_near(ts * p, Point::new(11.0, 14.0)); + } + + #[test] + fn conversions() { + let p = Point::new(3.0, 4.0); + let s = 2.0; + let t = Vec2::new(5.0, 6.0); + let ts = TranslateScale::new(t, s); + + // Test that conversion to affine is consistent. + let a: Affine = ts.into(); + assert_near(ts * p, a * p); + + assert_near((s * p.to_vec2()).to_point(), TranslateScale::scale(s) * p); + assert_near(p + t, TranslateScale::translate(t) * p); + } + + #[test] + fn inverse() { + let p = Point::new(3.0, 4.0); + let ts = TranslateScale::new(Vec2::new(5.0, 6.0), 2.0); + + assert_near(p, (ts * ts.inverse()) * p); + assert_near(p, (ts.inverse() * ts) * p); + } +} diff --git a/vendor/kurbo/src/triangle.rs b/vendor/kurbo/src/triangle.rs new file mode 100644 index 0000000000..7c3a6990a1 --- /dev/null +++ b/vendor/kurbo/src/triangle.rs @@ -0,0 +1,373 @@ +// Copyright 2024 the Kurbo Authors +// SPDX-License-Identifier: Apache-2.0 OR MIT + +//! Triangle shape +use crate::{Circle, PathEl, Point, Rect, Shape, Vec2}; + +use core::cmp::*; +use core::f64::consts::FRAC_PI_4; +use core::ops::{Add, Sub}; + +#[cfg(not(feature = "std"))] +use crate::common::FloatFuncs; + +/// Triangle +// A +// * +// / \ +// / \ +// *-----* +// B C +#[derive(Clone, Copy, PartialEq, Debug)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +pub struct Triangle { + /// vertex a. + pub a: Point, + /// vertex b. + pub b: Point, + /// vertex c. + pub c: Point, +} + +impl Triangle { + /// The empty [`Triangle`] at the origin. + pub const ZERO: Self = Self::from_coords((0., 0.), (0., 0.), (0., 0.)); + + /// Equilateral [`Triangle`] with the x-axis unit vector as its base. + pub const EQUILATERAL: Self = Self::from_coords( + ( + 1.0 / 2.0, + 1.732050807568877293527446341505872367_f64 / 2.0, /* (sqrt 3)/2 */ + ), + (0.0, 0.0), + (1.0, 0.0), + ); + + /// A new [`Triangle`] from three vertices ([`Point`]s). + #[inline(always)] + pub fn new(a: impl Into, b: impl Into, c: impl Into) -> Self { + Self { + a: a.into(), + b: b.into(), + c: c.into(), + } + } + + /// A new [`Triangle`] from three float vertex coordinates. + /// + /// Works as a constant [`Triangle::new`]. + #[inline(always)] + pub const fn from_coords(a: (f64, f64), b: (f64, f64), c: (f64, f64)) -> Self { + Self { + a: Point::new(a.0, a.1), + b: Point::new(b.0, b.1), + c: Point::new(c.0, c.1), + } + } + + /// The centroid of the [`Triangle`]. + #[inline] + pub fn centroid(&self) -> Point { + (1.0 / 3.0 * (self.a.to_vec2() + self.b.to_vec2() + self.c.to_vec2())).to_point() + } + + /// The offset of each vertex from the centroid. + #[inline] + pub fn offsets(&self) -> [Vec2; 3] { + let centroid = self.centroid().to_vec2(); + + [ + (self.a.to_vec2() - centroid), + (self.b.to_vec2() - centroid), + (self.c.to_vec2() - centroid), + ] + } + + /// The area of the [`Triangle`]. + #[inline] + pub fn area(&self) -> f64 { + 0.5 * (self.b - self.a).cross(self.c - self.a) + } + + /// Whether this [`Triangle`] has zero area. + #[doc(alias = "is_empty")] + #[inline] + pub fn is_zero_area(&self) -> bool { + self.area() == 0.0 + } + + /// The inscribed circle of [`Triangle`]. + /// + /// This is defined as the greatest [`Circle`] that lies within the [`Triangle`]. + #[doc(alias = "incircle")] + #[inline] + pub fn inscribed_circle(&self) -> Circle { + let ab = self.a.distance(self.b); + let bc = self.b.distance(self.c); + let ac = self.a.distance(self.c); + + // [`Vec2::div`] also multiplies by the reciprocal of the argument, but as this reciprocal + // is reused below to calculate the radius, there's explicitly only one division needed. + let perimeter_recip = 1. / (ab + bc + ac); + let incenter = (self.a.to_vec2() * bc + self.b.to_vec2() * ac + self.c.to_vec2() * ab) + * perimeter_recip; + + Circle::new(incenter.to_point(), 2.0 * self.area() * perimeter_recip) + } + + /// The circumscribed circle of [`Triangle`]. + /// + /// This is defined as the smallest [`Circle`] which intercepts each vertex of the [`Triangle`]. + #[doc(alias = "circumcircle")] + #[inline] + pub fn circumscribed_circle(&self) -> Circle { + let b = self.b - self.a; + let c = self.c - self.a; + let b_len2 = b.hypot2(); + let c_len2 = c.hypot2(); + let d_recip = 0.5 / b.cross(c); + + let x = (c.y * b_len2 - b.y * c_len2) * d_recip; + let y = (b.x * c_len2 - c.x * b_len2) * d_recip; + let r = (b_len2 * c_len2).sqrt() * (c - b).hypot() * d_recip; + + Circle::new(self.a + Vec2::new(x, y), r) + } + + /// Expand the triangle by a constant amount (`scalar`) in all directions. + #[doc(alias = "offset")] + pub fn inflate(&self, scalar: f64) -> Self { + let centroid = self.centroid(); + + Self::new( + centroid + (0.0, scalar), + centroid + scalar * Vec2::from_angle(5.0 * FRAC_PI_4), + centroid + scalar * Vec2::from_angle(7.0 * FRAC_PI_4), + ) + } + + /// Is this [`Triangle`] [finite]? + /// + /// [finite]: f64::is_finite + #[inline] + pub const fn is_finite(&self) -> bool { + self.a.is_finite() && self.b.is_finite() && self.c.is_finite() + } + + /// Is this [`Triangle`] [NaN]? + /// + /// [NaN]: f64::is_nan + #[inline] + pub const fn is_nan(&self) -> bool { + self.a.is_nan() || self.b.is_nan() || self.c.is_nan() + } +} + +impl From<(Point, Point, Point)> for Triangle { + fn from(points: (Point, Point, Point)) -> Triangle { + Triangle::new(points.0, points.1, points.2) + } +} + +impl Add for Triangle { + type Output = Triangle; + + #[inline] + fn add(self, v: Vec2) -> Triangle { + Triangle::new(self.a + v, self.b + v, self.c + v) + } +} + +impl Sub for Triangle { + type Output = Triangle; + + #[inline] + fn sub(self, v: Vec2) -> Triangle { + Triangle::new(self.a - v, self.b - v, self.c - v) + } +} + +#[doc(hidden)] +pub struct TrianglePathIter { + triangle: Triangle, + ix: usize, +} + +impl Shape for Triangle { + type PathElementsIter<'iter> = TrianglePathIter; + + fn path_elements(&self, _tolerance: f64) -> TrianglePathIter { + TrianglePathIter { + triangle: *self, + ix: 0, + } + } + + #[inline] + fn area(&self) -> f64 { + Triangle::area(self) + } + + #[inline] + fn perimeter(&self, _accuracy: f64) -> f64 { + self.a.distance(self.b) + self.b.distance(self.c) + self.c.distance(self.a) + } + + #[inline] + fn winding(&self, pt: Point) -> i32 { + let s0 = (self.b - self.a).cross(pt - self.a).signum(); + let s1 = (self.c - self.b).cross(pt - self.b).signum(); + let s2 = (self.a - self.c).cross(pt - self.c).signum(); + + if s0 == s1 && s1 == s2 { s0 as i32 } else { 0 } + } + + #[inline] + fn bounding_box(&self) -> Rect { + Rect::new( + self.a.x.min(self.b.x.min(self.c.x)), + self.a.y.min(self.b.y.min(self.c.y)), + self.a.x.max(self.b.x.max(self.c.x)), + self.a.y.max(self.b.y.max(self.c.y)), + ) + } +} + +// Note: vertices a, b and c are not guaranteed to be in order as described in the struct comments +// (i.e. as "vertex a is topmost, vertex b is leftmost, and vertex c is rightmost") +impl Iterator for TrianglePathIter { + type Item = PathEl; + + fn next(&mut self) -> Option { + self.ix += 1; + match self.ix { + 1 => Some(PathEl::MoveTo(self.triangle.a)), + 2 => Some(PathEl::LineTo(self.triangle.b)), + 3 => Some(PathEl::LineTo(self.triangle.c)), + 4 => Some(PathEl::ClosePath), + _ => None, + } + } +} + +// TODO: better and more tests +#[cfg(test)] +mod tests { + use crate::{Point, Triangle, Vec2}; + + fn assert_approx_eq(x: f64, y: f64, max_relative_error: f64) { + assert!( + (x - y).abs() <= f64::max(x.abs(), y.abs()) * max_relative_error, + "{x} != {y}" + ); + } + + fn assert_approx_eq_point(x: Point, y: Point, max_relative_error: f64) { + assert_approx_eq(x.x, y.x, max_relative_error); + assert_approx_eq(x.y, y.y, max_relative_error); + } + + #[test] + fn centroid() { + let test = Triangle::from_coords((-90.02, 3.5), (7.2, -9.3), (8.0, 9.1)).centroid(); + let expected = Point::new(-24.94, 1.1); + + assert_approx_eq_point(test, expected, f64::EPSILON * 100.); + } + + #[test] + fn offsets() { + let test = Triangle::from_coords((-20.0, 180.2), (1.2, 0.0), (290.0, 100.0)).offsets(); + let expected = [ + Vec2::new(-110.4, 86.8), + Vec2::new(-89.2, -93.4), + Vec2::new(199.6, 6.6), + ]; + + test.iter().zip(expected.iter()).for_each(|(t, e)| { + assert_approx_eq_point(t.to_point(), e.to_point(), f64::EPSILON * 100.); + }); + } + + #[test] + fn area() { + let test = Triangle::new( + (12123.423, 2382.7834), + (7892.729, 238.459), + (7820.2, 712.23), + ); + let expected = 1079952.9157407999; + + // initial + assert_approx_eq(test.area(), -expected, f64::EPSILON * 100.); + // permutate vertex + let test = Triangle::new(test.b, test.a, test.c); + assert_approx_eq(test.area(), expected, f64::EPSILON * 100.); + } + + #[test] + fn circumcenter() { + let test = Triangle::EQUILATERAL.circumscribed_circle().center; + let expected = Point::new(0.5, 0.28867513459481288); + + assert_approx_eq_point(test, expected, f64::EPSILON * 100.); + } + + #[test] + fn inradius() { + let test = Triangle::EQUILATERAL.inscribed_circle().radius; + let expected = 0.28867513459481287; + + assert_approx_eq(test, expected, f64::EPSILON * 100.); + } + + #[test] + fn circumradius() { + let test = Triangle::EQUILATERAL; + let expected = 0.57735026918962576; + + assert_approx_eq( + test.circumscribed_circle().radius, + expected, + f64::EPSILON * 100., + ); + // permute vertex + let test = Triangle::new(test.b, test.a, test.c); + assert_approx_eq( + test.circumscribed_circle().radius, + -expected, + f64::EPSILON * 100., + ); + } + + #[test] + fn inscribed_circle() { + let test = Triangle::new((-4., 1.), (-4., -1.), (10., 3.)); + + let inscribed = test.inscribed_circle(); + assert_approx_eq_point( + inscribed.center, + (-3.0880178529263671, 0.20904207741504303).into(), + f64::EPSILON * 100., + ); + assert_approx_eq(inscribed.radius, 0.91198214707363295, f64::EPSILON * 100.); + } + + #[test] + fn circumscribed_circle() { + let test = Triangle::new((-4., 1.), (-4., -1.), (10., 3.)); + + let circumscribed = test.circumscribed_circle(); + assert_approx_eq_point( + circumscribed.center, + (3.2857142857142857, 0.).into(), + f64::EPSILON * 100., + ); + assert_approx_eq( + circumscribed.radius, + 7.3540215292764288, + f64::EPSILON * 100., + ); + } +} diff --git a/vendor/kurbo/src/vec2.rs b/vendor/kurbo/src/vec2.rs new file mode 100644 index 0000000000..38aa2c2775 --- /dev/null +++ b/vendor/kurbo/src/vec2.rs @@ -0,0 +1,568 @@ +// Copyright 2018 the Kurbo Authors +// SPDX-License-Identifier: Apache-2.0 OR MIT + +//! A simple 2D vector. + +use core::fmt; +use core::iter::Sum; +use core::ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Neg, Sub, SubAssign}; + +use crate::common::FloatExt; +use crate::{Axis, Point, Size}; + +#[cfg(not(feature = "std"))] +use crate::common::FloatFuncs; + +/// A 2D vector. +/// +/// This is intended primarily for a vector in the mathematical sense, +/// but it can be interpreted as a translation, and converted to and +/// from a [`Point`] (vector relative to the origin) and [`Size`]. +#[derive(Clone, Copy, Default, Debug, PartialEq)] +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +pub struct Vec2 { + /// The x-coordinate. + pub x: f64, + /// The y-coordinate. + pub y: f64, +} + +impl Vec2 { + /// The vector (0, 0). + pub const ZERO: Vec2 = Vec2::new(0., 0.); + + /// Create a new vector. + #[inline(always)] + pub const fn new(x: f64, y: f64) -> Vec2 { + Vec2 { x, y } + } + + /// Convert this vector into a [`Point`]. + #[inline(always)] + pub const fn to_point(self) -> Point { + Point::new(self.x, self.y) + } + + /// Convert this vector into a [`Size`]. + #[inline(always)] + pub const fn to_size(self) -> Size { + Size::new(self.x, self.y) + } + + /// Create a vector with the same value for `x` and `y`. + #[inline(always)] + pub const fn splat(v: f64) -> Self { + Vec2 { x: v, y: v } + } + + /// Dot product of two vectors. + #[inline] + pub const fn dot(self, other: Vec2) -> f64 { + self.x * other.x + self.y * other.y + } + + /// Cross product of two vectors. + /// + /// This is signed so that `(1, 0) × (0, 1) = 1`. + /// + /// The following relations hold: + /// + /// `u.cross(v) = -v.cross(u)` + /// + /// `v.cross(v) = 0.0` + #[inline] + pub const fn cross(self, other: Vec2) -> f64 { + self.x * other.y - self.y * other.x + } + + /// Magnitude of vector. + /// + /// See [`Point::distance`] for the same operation on [`Point`]. + /// + /// # Examples + /// + /// ``` + /// use kurbo::Vec2; + /// let v = Vec2::new(3.0, 4.0); + /// assert_eq!(v.hypot(), 5.0); + /// ``` + #[inline] + pub fn hypot(self) -> f64 { + // Avoid f64::hypot as it calls a slow library function. + self.hypot2().sqrt() + } + + /// Magnitude of vector. + /// + /// This is an alias for [`Vec2::hypot`]. + #[inline] + pub fn length(self) -> f64 { + self.hypot() + } + + /// Magnitude squared of vector. + /// + /// See [`Point::distance_squared`] for the same operation on [`Point`]. + /// + /// # Examples + /// + /// ``` + /// use kurbo::Vec2; + /// let v = Vec2::new(3.0, 4.0); + /// assert_eq!(v.hypot2(), 25.0); + /// ``` + #[inline] + pub const fn hypot2(self) -> f64 { + self.dot(self) + } + + /// Magnitude squared of vector. + /// + /// This is an alias for [`Vec2::hypot2`]. + #[inline] + pub const fn length_squared(self) -> f64 { + self.hypot2() + } + + /// Find the angle in radians between this vector and the vector `Vec2 { x: 1.0, y: 0.0 }` + /// in the positive `y` direction. + /// + /// If the vector is interpreted as a complex number, this is the argument. + /// The angle is expressed in radians. + #[inline] + pub fn atan2(self) -> f64 { + self.y.atan2(self.x) + } + + /// Find the angle in radians between this vector and the vector `Vec2 { x: 1.0, y: 0.0 }` + /// in the positive `y` direction. + /// + /// This is an alias for [`Vec2::atan2`]. + #[inline] + pub fn angle(self) -> f64 { + self.atan2() + } + + /// A unit vector of the given angle. + /// + /// With `th` at zero, the result is the positive X unit vector, and + /// at π/2, it is the positive Y unit vector. The angle is expressed + /// in radians. + /// + /// Thus, in a Y-down coordinate system (as is common for graphics), + /// it is a clockwise rotation, and in Y-up (traditional for math), it + /// is anti-clockwise. This convention is consistent with + /// [`Affine::rotate`]. + /// + /// [`Affine::rotate`]: crate::Affine::rotate + #[inline] + pub fn from_angle(th: f64) -> Vec2 { + let (th_sin, th_cos) = th.sin_cos(); + Vec2 { + x: th_cos, + y: th_sin, + } + } + + /// Linearly interpolate between two vectors. + #[inline] + pub fn lerp(self, other: Vec2, t: f64) -> Vec2 { + self + t * (other - self) + } + + /// Returns a vector of [magnitude] 1.0 with the same angle as `self`; i.e. + /// a unit/direction vector. + /// + /// This produces `NaN` values when the magnitude is `0`. + /// + /// [magnitude]: Self::hypot + #[inline] + pub fn normalize(self) -> Vec2 { + self / self.hypot() + } + + /// Returns a new `Vec2`, + /// with `x` and `y` [rounded] to the nearest integer. + /// + /// # Examples + /// + /// ``` + /// use kurbo::Vec2; + /// let a = Vec2::new(3.3, 3.6).round(); + /// let b = Vec2::new(3.0, -3.1).round(); + /// assert_eq!(a.x, 3.0); + /// assert_eq!(a.y, 4.0); + /// assert_eq!(b.x, 3.0); + /// assert_eq!(b.y, -3.0); + /// ``` + /// + /// [rounded]: f64::round + #[inline] + pub fn round(self) -> Vec2 { + Vec2::new(self.x.round(), self.y.round()) + } + + /// Returns a new `Vec2`, + /// with `x` and `y` [rounded up] to the nearest integer, + /// unless they are already an integer. + /// + /// # Examples + /// + /// ``` + /// use kurbo::Vec2; + /// let a = Vec2::new(3.3, 3.6).ceil(); + /// let b = Vec2::new(3.0, -3.1).ceil(); + /// assert_eq!(a.x, 4.0); + /// assert_eq!(a.y, 4.0); + /// assert_eq!(b.x, 3.0); + /// assert_eq!(b.y, -3.0); + /// ``` + /// + /// [rounded up]: f64::ceil + #[inline] + pub fn ceil(self) -> Vec2 { + Vec2::new(self.x.ceil(), self.y.ceil()) + } + + /// Returns a new `Vec2`, + /// with `x` and `y` [rounded down] to the nearest integer, + /// unless they are already an integer. + /// + /// # Examples + /// + /// ``` + /// use kurbo::Vec2; + /// let a = Vec2::new(3.3, 3.6).floor(); + /// let b = Vec2::new(3.0, -3.1).floor(); + /// assert_eq!(a.x, 3.0); + /// assert_eq!(a.y, 3.0); + /// assert_eq!(b.x, 3.0); + /// assert_eq!(b.y, -4.0); + /// ``` + /// + /// [rounded down]: f64::floor + #[inline] + pub fn floor(self) -> Vec2 { + Vec2::new(self.x.floor(), self.y.floor()) + } + + /// Returns a new `Vec2`, + /// with `x` and `y` [rounded away] from zero to the nearest integer, + /// unless they are already an integer. + /// + /// # Examples + /// + /// ``` + /// use kurbo::Vec2; + /// let a = Vec2::new(3.3, 3.6).expand(); + /// let b = Vec2::new(3.0, -3.1).expand(); + /// assert_eq!(a.x, 4.0); + /// assert_eq!(a.y, 4.0); + /// assert_eq!(b.x, 3.0); + /// assert_eq!(b.y, -4.0); + /// ``` + /// + /// [rounded away]: FloatExt::expand + #[inline] + pub fn expand(self) -> Vec2 { + Vec2::new(self.x.expand(), self.y.expand()) + } + + /// Returns a new `Vec2`, + /// with `x` and `y` [rounded towards] zero to the nearest integer, + /// unless they are already an integer. + /// + /// # Examples + /// + /// ``` + /// use kurbo::Vec2; + /// let a = Vec2::new(3.3, 3.6).trunc(); + /// let b = Vec2::new(3.0, -3.1).trunc(); + /// assert_eq!(a.x, 3.0); + /// assert_eq!(a.y, 3.0); + /// assert_eq!(b.x, 3.0); + /// assert_eq!(b.y, -3.0); + /// ``` + /// + /// [rounded towards]: f64::trunc + #[inline] + pub fn trunc(self) -> Vec2 { + Vec2::new(self.x.trunc(), self.y.trunc()) + } + + /// Is this `Vec2` [finite]? + /// + /// [finite]: f64::is_finite + #[inline] + pub const fn is_finite(self) -> bool { + self.x.is_finite() && self.y.is_finite() + } + + /// Is this `Vec2` [`NaN`]? + /// + /// [`NaN`]: f64::is_nan + #[inline] + pub const fn is_nan(self) -> bool { + self.x.is_nan() || self.y.is_nan() + } + + /// Divides this `Vec2` by a scalar. + /// + /// Unlike the division by scalar operator, which multiplies by the + /// reciprocal for performance, this performs the division + /// per-component for consistent rounding behavior. + pub(crate) fn div_exact(self, divisor: f64) -> Vec2 { + Vec2 { + x: self.x / divisor, + y: self.y / divisor, + } + } + + /// Turn by 90 degrees. + /// + /// The rotation is clockwise in a Y-down coordinate system. The following relations hold: + /// + /// `u.dot(v) = u.cross(v.turn_90())` + /// + /// `u.cross(v) = u.turn_90().dot(v)` + #[inline] + pub const fn turn_90(self) -> Vec2 { + Vec2::new(-self.y, self.x) + } + + /// Combine two vectors interpreted as rotation and scaling. + /// + /// Interpret both vectors as a rotation and a scale, and combine + /// their effects. by adding the angles and multiplying the magnitudes. + /// This operation is equivalent to multiplication when the vectors + /// are interpreted as complex numbers. It is commutative. + #[inline] + pub const fn rotate_scale(self, rhs: Vec2) -> Vec2 { + Vec2::new( + self.x * rhs.x - self.y * rhs.y, + self.x * rhs.y + self.y * rhs.x, + ) + } + + /// Get the member matching the given axis. + #[inline] + pub const fn get_coord(self, axis: Axis) -> f64 { + match axis { + Axis::Horizontal => self.x, + Axis::Vertical => self.y, + } + } + + /// Get a mutable reference to the member matching the given axis. + #[inline] + pub const fn get_coord_mut(&mut self, axis: Axis) -> &mut f64 { + match axis { + Axis::Horizontal => &mut self.x, + Axis::Vertical => &mut self.y, + } + } + + /// Set the member matching the given axis to the given value. + #[inline] + pub const fn set_coord(&mut self, axis: Axis, value: f64) { + match axis { + Axis::Horizontal => self.x = value, + Axis::Vertical => self.y = value, + } + } +} + +impl From<(f64, f64)> for Vec2 { + #[inline(always)] + fn from(v: (f64, f64)) -> Vec2 { + Vec2 { x: v.0, y: v.1 } + } +} + +impl From for (f64, f64) { + #[inline(always)] + fn from(v: Vec2) -> (f64, f64) { + (v.x, v.y) + } +} + +impl Add for Vec2 { + type Output = Vec2; + + #[inline] + fn add(self, other: Vec2) -> Vec2 { + Vec2 { + x: self.x + other.x, + y: self.y + other.y, + } + } +} + +impl AddAssign for Vec2 { + #[inline] + fn add_assign(&mut self, other: Vec2) { + *self = Vec2 { + x: self.x + other.x, + y: self.y + other.y, + } + } +} + +impl Sum for Vec2 { + fn sum>(iter: I) -> Self { + iter.fold(Vec2::ZERO, |sum, v| sum + v) + } +} + +impl Sub for Vec2 { + type Output = Vec2; + + #[inline] + fn sub(self, other: Vec2) -> Vec2 { + Vec2 { + x: self.x - other.x, + y: self.y - other.y, + } + } +} + +impl SubAssign for Vec2 { + #[inline] + fn sub_assign(&mut self, other: Vec2) { + *self = Vec2 { + x: self.x - other.x, + y: self.y - other.y, + } + } +} + +impl Mul for Vec2 { + type Output = Vec2; + + #[inline] + fn mul(self, other: f64) -> Vec2 { + Vec2 { + x: self.x * other, + y: self.y * other, + } + } +} + +impl MulAssign for Vec2 { + #[inline] + fn mul_assign(&mut self, other: f64) { + *self = Vec2 { + x: self.x * other, + y: self.y * other, + }; + } +} + +impl Mul for f64 { + type Output = Vec2; + + #[inline] + fn mul(self, other: Vec2) -> Vec2 { + other * self + } +} + +impl Div for Vec2 { + type Output = Vec2; + + /// Note: division by a scalar is implemented by multiplying by the reciprocal. + /// + /// This is more efficient but has different roundoff behavior than division. + #[inline] + #[allow(clippy::suspicious_arithmetic_impl)] + fn div(self, other: f64) -> Vec2 { + self * other.recip() + } +} + +impl DivAssign for Vec2 { + #[inline] + fn div_assign(&mut self, other: f64) { + self.mul_assign(other.recip()); + } +} + +impl Neg for Vec2 { + type Output = Vec2; + + #[inline] + fn neg(self) -> Vec2 { + Vec2 { + x: -self.x, + y: -self.y, + } + } +} + +impl fmt::Display for Vec2 { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + write!(formatter, "𝐯=(")?; + fmt::Display::fmt(&self.x, formatter)?; + write!(formatter, ", ")?; + fmt::Display::fmt(&self.y, formatter)?; + write!(formatter, ")") + } +} + +// Conversions to and from mint +#[cfg(feature = "mint")] +impl From for mint::Vector2 { + #[inline(always)] + fn from(p: Vec2) -> mint::Vector2 { + mint::Vector2 { x: p.x, y: p.y } + } +} + +#[cfg(feature = "mint")] +impl From> for Vec2 { + #[inline(always)] + fn from(p: mint::Vector2) -> Vec2 { + Vec2 { x: p.x, y: p.y } + } +} + +#[cfg(test)] +mod tests { + use core::f64::consts::FRAC_PI_2; + + use super::*; + #[test] + fn display() { + let v = Vec2::new(1.2332421, 532.10721213123); + let s = format!("{v:.2}"); + assert_eq!(s.as_str(), "𝐯=(1.23, 532.11)"); + } + + #[test] + fn cross_sign() { + let v = Vec2::new(1., 0.).cross(Vec2::new(0., 1.)); + assert_eq!(v, 1.); + } + + #[test] + fn turn_90() { + let u = Vec2::new(0.1, 0.2); + let turned = u.turn_90(); + // This should be exactly equal by IEEE rules, might fail + // in fastmath conditions. + assert_eq!(u.length(), turned.length()); + const EPSILON: f64 = 1e-12; + assert!((u.angle() + FRAC_PI_2 - turned.angle()).abs() < EPSILON); + } + + #[test] + fn rotate_scale() { + let u = Vec2::new(0.1, 0.2); + let v = Vec2::new(0.3, -0.4); + let uv = u.rotate_scale(v); + const EPSILON: f64 = 1e-12; + assert!((u.length() * v.length() - uv.length()).abs() < EPSILON); + assert!((u.angle() + v.angle() - uv.angle()).abs() < EPSILON); + } +} From 08525664c3b5623271d7b872bd8cb2daad71de52 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 27 Nov 2026 13:38:22 -0800 Subject: [PATCH 2/3] kurbo: a stroke skips zero tangents instead of giving NaN A collinear cubic that runs back and forth is stroked by StrokeCtx::do_linear, which steps from cusp to cusp. After rounding, two cusps can land on the same point, or a cusp on the end point, and the tangent between them is exactly zero. do_join and do_line divide by the tangent's length, so the whole outline held NaN coordinates and a renderer that fills it draws no stroke. do_linear now skips such a step. The stroker had the same fault for a quadratic or cubic that ends where it starts with control arms shorter than 1e-6: PathSeg::tangents falls back to the chord, which is zero. Such a curve is now skipped, as a zero-length line already is. The linear_cubic_with_coincident_cusps and tiny_closed_loops tests fail on the published package. README.craft.md, SOURCE.json and NOTICE list the patches. --- NOTICE | 7 +-- vendor/kurbo/README.craft.md | 34 ++++++++----- vendor/kurbo/SOURCE.json | 7 ++- vendor/kurbo/src/stroke.rs | 92 +++++++++++++++++++++++++++++++++--- 4 files changed, 118 insertions(+), 22 deletions(-) diff --git a/NOTICE b/NOTICE index c71d5321e4..d474937863 100644 --- a/NOTICE +++ b/NOTICE @@ -297,9 +297,10 @@ patches and the files left out. kurbo kurbo 0.13.1 (https://crates.io/crates/kurbo/0.13.1, https://github.com/linebender/kurbo), MIT OR -Apache-2.0, is stored in vendor/kurbo with its upstream license files. Its sources read "Copyright -2018 the Kurbo Authors", and its LICENSE-MIT reads "Copyright (c) 2018 Raph Levien". See -vendor/kurbo/README.craft.md and vendor/kurbo/SOURCE.json for provenance. +Apache-2.0, is stored in vendor/kurbo with its upstream license files and local patches, to +src/stroke.rs. Its source files carry "Copyright the Kurbo Authors" lines (2018 to 2026), +and its LICENSE-MIT reads "Copyright (c) 2018 Raph Levien". See vendor/kurbo/README.craft.md and +vendor/kurbo/SOURCE.json for provenance and the local patches. Platform lifecycle source provenance diff --git a/vendor/kurbo/README.craft.md b/vendor/kurbo/README.craft.md index 431f05d267..9b5a225dff 100644 --- a/vendor/kurbo/README.craft.md +++ b/vendor/kurbo/README.craft.md @@ -1,14 +1,25 @@ # Local kurbo 0.13.1 copy -This is the crates.io kurbo 0.13.1 package (MIT OR Apache-2.0) with no file changed. +This is the crates.io kurbo 0.13.1 package (MIT OR Apache-2.0) with the local patches listed below. `.cargo_vcs_info.json` names the commit it was packaged from, `838b69ef35f3381cefc007d86aa8364f5a6dc673`, the `v0.13.1` tag of [linebender/kurbo](https://github.com/linebender/kurbo/tree/838b69ef35f3381cefc007d86aa8364f5a6dc673/kurbo). -Every file here except this one and `SOURCE.json` is byte for byte the file in the `.crate` archive. -`SOURCE.json` records the hash of the `.crate` download (`source_archive_sha256`) and, for every file -kept, the hash in the package (`source_sha256`) and the hash here (`sha256`). `local_patches` is -empty, and no file of the package is left out. +The patched file is `src/stroke.rs`. + +Every file here except this one, `SOURCE.json` and the patched file is byte for byte the file in the +`.crate` archive. `SOURCE.json` records the hash of the `.crate` download (`source_archive_sha256`) +and, for every file kept, the hash in the package (`source_sha256`) and the hash here (`sha256`). +`local_patches` describes each local change. No file of the package is left out. + +## Local changes + +| File | Change | +|---|---| +| `src/stroke.rs` | `StrokeCtx::do_linear` skips a cusp, or the end point, whose tangent from the point before it is exactly zero, instead of passing the tangent to `do_join` and `do_line`, which divide by its length. After rounding, a collinear cubic that runs back and forth can put two cusps at the same point, or a cusp on the end point, and the whole outline then held NaN coordinates. The `linear_cubic_with_coincident_cusps` test strokes one cubic of each kind with every join, two widths and two tolerances. Code comments label the change `Craft patch (zero tangent)`. | +| `src/stroke.rs` | The stroker skips a quadratic or cubic whose start or end tangent is zero, as it skips a zero-length line. `PathSeg::tangents` falls back to the chord when the control arms are shorter than 1e-6, and a curve that ends where it starts has a zero chord, so such a closed loop gave NaN coordinates in the outline. The `tiny_closed_loops` test strokes loops with arms of 1e-7 and 1e-5, on their own and after a line. Code comments label the change `Craft patch (zero tangent)`. | + +Every change here updates this table and `SOURCE.json` in the same commit. ## Using it @@ -26,10 +37,10 @@ resolves to crates.io. ## Tests -`scripts/test-pdf-backends.sh` runs the package's unit and doc tests with every feature, and its -other backend tests build against this copy. The workspace's own tests also build against it through -the patch entry. No workflow runs clippy on this copy. Run the tests and the builds without `std` and -for Wasm from this directory: +`scripts/test-pdf-backends.sh` runs the package's unit and doc tests with every feature, and builds +its `hayro` and `hayro-interpret` tests against this copy. The workspace's own tests also build +against it through the patch entry. No workflow runs clippy on this copy. Run the tests and the +builds without `std` and for Wasm from this directory: ```sh cargo test --locked --all-features @@ -37,7 +48,8 @@ cargo check --locked --no-default-features --features libm cargo test --locked --all-features --target wasm32-unknown-unknown --no-run ``` -The package's tests need the `std` feature. Clippy 1.100.0 with `-D warnings` stops at one lint in the -package as published, `needless_late_init` in `src/common.rs`; the copy keeps that code unchanged. +The package's tests need the `std` feature. Clippy 1.100.0 with `-D warnings` reports two lints in +the package as published, `needless_late_init` in `src/common.rs` and `useless_borrows_in_formatting` +in a test in `src/cubicbez.rs`; the copy keeps that code unchanged. Cargo writes to `target/` in this directory, which the root `.gitignore` excludes. diff --git a/vendor/kurbo/SOURCE.json b/vendor/kurbo/SOURCE.json index 8d8dde697f..d3439b29c8 100644 --- a/vendor/kurbo/SOURCE.json +++ b/vendor/kurbo/SOURCE.json @@ -7,7 +7,10 @@ "upstream_repository": "https://github.com/linebender/kurbo", "upstream_revision": "838b69ef35f3381cefc007d86aa8364f5a6dc673", "upstream_directory": "kurbo", - "local_patches": [], + "local_patches": [ + "In `src/stroke.rs`, `StrokeCtx::do_linear` skips a cusp, or the end point, whose tangent from the point before it is exactly zero, instead of passing the tangent to `do_join` and `do_line`, which divide by its length, so a collinear cubic whose cusps round onto the point before them or onto its end point no longer gives NaN coordinates. The test `stroke::tests::linear_cubic_with_coincident_cusps` covers it.", + "In `src/stroke.rs`, the stroker skips a quadratic or cubic whose start or end tangent from `PathSeg::tangents` is zero, as it skips a zero-length line, so a closed loop with control arms shorter than 1e-6 no longer gives NaN coordinates. The test `stroke::tests::tiny_closed_loops` covers it." + ], "files": [ { "path": ".cargo_vcs_info.json", "source_sha256": "4bfe3d4ab606efdb8e558db546ae666decc53fa3caa34865b4f66ffa67449a66", "source_git_blob": null, "sha256": "4bfe3d4ab606efdb8e558db546ae666decc53fa3caa34865b4f66ffa67449a66" }, { "path": "Cargo.lock", "source_sha256": "1f13e8fcd58e548bb2130320c3ed5addb20ff658722d3f20b697c2a6a0b27e90", "source_git_blob": null, "sha256": "1f13e8fcd58e548bb2130320c3ed5addb20ff658722d3f20b697c2a6a0b27e90" }, @@ -57,7 +60,7 @@ { "path": "src/shape.rs", "source_sha256": "226a32a1996d298e9587cc921b7cc8644ca6e04b2c740732e0a63ab00d3351ae", "source_git_blob": null, "sha256": "226a32a1996d298e9587cc921b7cc8644ca6e04b2c740732e0a63ab00d3351ae" }, { "path": "src/simplify.rs", "source_sha256": "771fc68a2dd0a00d994906176641bcb17c9351b3d1205e037a78a5893b51a684", "source_git_blob": null, "sha256": "771fc68a2dd0a00d994906176641bcb17c9351b3d1205e037a78a5893b51a684" }, { "path": "src/size.rs", "source_sha256": "645a1f7ba1528b1b10e5881d53019eac428e556c1d9bdea8d3f42ce351c00950", "source_git_blob": null, "sha256": "645a1f7ba1528b1b10e5881d53019eac428e556c1d9bdea8d3f42ce351c00950" }, - { "path": "src/stroke.rs", "source_sha256": "9ae69c57571d653a34ded745e176869ef587e4ff5c3dcb1607a398df7e029498", "source_git_blob": null, "sha256": "9ae69c57571d653a34ded745e176869ef587e4ff5c3dcb1607a398df7e029498" }, + { "path": "src/stroke.rs", "source_sha256": "9ae69c57571d653a34ded745e176869ef587e4ff5c3dcb1607a398df7e029498", "source_git_blob": null, "sha256": "9f430ffc660e8777551d4c67cc1ff3e4006539c7f31680626721c2105f054c9e" }, { "path": "src/svg.rs", "source_sha256": "b403a258614b3e287c3e5210b0745814f08acda92e95696bdddbf50e341fa3be", "source_git_blob": null, "sha256": "b403a258614b3e287c3e5210b0745814f08acda92e95696bdddbf50e341fa3be" }, { "path": "src/translate_scale.rs", "source_sha256": "8b82eb5f46744cb9a044263e200d79d797270616320337e4230356942ab85f1a", "source_git_blob": null, "sha256": "8b82eb5f46744cb9a044263e200d79d797270616320337e4230356942ab85f1a" }, { "path": "src/triangle.rs", "source_sha256": "27a6cddb109ae36ef55c470261c689d085502ab72a47f3a32ca22e771df7b03e", "source_git_blob": null, "sha256": "27a6cddb109ae36ef55c470261c689d085502ab72a47f3a32ca22e771df7b03e" }, diff --git a/vendor/kurbo/src/stroke.rs b/vendor/kurbo/src/stroke.rs index 4c9477d947..a55fc495a3 100644 --- a/vendor/kurbo/src/stroke.rs +++ b/vendor/kurbo/src/stroke.rs @@ -328,6 +328,14 @@ fn stroke_undashed( if p1 != p0 || p2 != p0 { let q = QuadBez::new(p0, p1, p2); let (tan0, tan1) = PathSeg::Quad(q).tangents(); + // Craft patch (zero tangent): `tangents` falls back to the + // chord when the control arms are shorter than its + // threshold, and the chord of a loop that ends where it + // starts is zero. Such a loop is skipped like a zero-length + // line. + if tan0 == Vec2::ZERO || tan1 == Vec2::ZERO { + continue; + } ctx.do_join(style, tan0); ctx.do_cubic(style, q.raise(), tolerance); ctx.last_tan = tan1; @@ -337,6 +345,10 @@ fn stroke_undashed( if p1 != p0 || p2 != p0 || p3 != p0 { let c = CubicBez::new(p0, p1, p2, p3); let (tan0, tan1) = PathSeg::Cubic(c).tangents(); + // Craft patch (zero tangent): as for a quadratic above. + if tan0 == Vec2::ZERO || tan1 == Vec2::ZERO { + continue; + } ctx.do_join(style, tan0); ctx.do_cubic(style, c, tolerance); ctx.last_tan = tan1; @@ -594,15 +606,21 @@ impl StrokeCtx { let z = mt * (mt * mt * p[0] + 3.0 * t * (mt * p[1] + t * p[2])) + t * t * t * p[3]; let p = ref_pt + z * ref_vec; let tan = p - self.last_pt; - self.do_join(&style, tan); - self.do_line(&style, tan, p); - self.last_tan = tan; + // Craft patch (zero tangent): after rounding, a cusp can land + // on the previous point, and a zero tangent has no normal. + if tan != Vec2::ZERO { + self.do_join(&style, tan); + self.do_line(&style, tan, p); + self.last_tan = tan; + } } } let tan = c.p3 - self.last_pt; - self.do_join(&style, tan); - self.do_line(&style, tan, c.p3); - self.last_tan = tan; + if tan != Vec2::ZERO { + self.do_join(&style, tan); + self.do_line(&style, tan, c.p3); + self.last_tan = tan; + } self.do_join(&style, tan1); } } @@ -1178,4 +1196,66 @@ mod tests { let infinite_width = Stroke::new(f64::INFINITY); assert!(!infinite_width.is_nan()); } + + // A curve that ends where it starts, with control arms shorter than the + // threshold of `PathSeg::tangents`, has a zero tangent at both ends. + #[test] + fn tiny_closed_loops() { + for arm in [1e-7, 1e-5] { + for lead_in in [false, true] { + let mut cubic = BezPath::new(); + let mut quad = BezPath::new(); + for path in [&mut cubic, &mut quad] { + path.move_to((0.0, 10.0)); + if lead_in { + path.line_to((10.0, 10.0)); + } else { + path.move_to((10.0, 10.0)); + } + } + cubic.curve_to((10.0 + arm, 10.0), (10.0 + arm, 10.0 + arm), (10.0, 10.0)); + quad.quad_to((10.0 + arm, 10.0), (10.0, 10.0)); + for path in [&mut cubic, &mut quad] { + path.line_to((10.0, 20.0)); + } + for (name, path) in [("cubic", &cubic), ("quad", &quad)] { + let outline = stroke(path, &Stroke::new(2.0), &StrokeOpts::default(), 0.25); + assert!(outline.is_finite(), "{name} {arm} {lead_in}"); + let bounds = outline.bounding_box(); + assert!( + bounds.y0 < 10.0 && bounds.y1 > 20.0, + "{name} {arm} {lead_in} {bounds:?}" + ); + } + } + } + } + + // A collinear cubic that runs back and forth has cusps. After rounding, a + // cusp can map to the point before it or to the end point, giving a zero + // tangent. In the first path, a double cusp root gives two cusps at the + // same point; in the second, the cusp rounds to the end point. + #[test] + fn linear_cubic_with_coincident_cusps() { + use crate::Join; + for svg in [ + "M342.22660294061905,5 C342.22654190545893,5 342.22660294061905,5 342.22654190545893,5", + "M697.7493196978551,5 C697.7493115238381,5 697.7492364261329,5 697.7492364262838,5", + ] { + let path = BezPath::from_svg(svg).unwrap(); + for join in [Join::Bevel, Miter, Join::Round] { + for width in [0.3, 3.0] { + for tolerance in [0.25, 0.01] { + let style = Stroke::new(width).with_join(join); + let outline = stroke(&path, &style, &StrokeOpts::default(), tolerance); + assert!( + !outline.elements().is_empty(), + "{svg} {join:?} {width} {tolerance}" + ); + assert!(outline.is_finite(), "{svg} {join:?} {width} {tolerance}"); + } + } + } + } + } } From ecc26335c9a29b97f8285a9ce5304a9258be6a36 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 27 Nov 2026 16:42:17 -0800 Subject: [PATCH 3/3] kurbo: a tiny quadratic loop keeps its own tangents in the stroker The stroker checks a quadratic's tangents, then strokes the cubic that QuadBez::raise gives, whose control arms are 2/3 as long. With arms between 1e-6 and 1.5e-6, the quadratic's arms pass the threshold of PathSeg::tangents, but the cubic's do not, so do_linear looked up the cubic's tangents again, got the zero chord, and its final join added NaN coordinates to the outline. do_cubic and do_linear now take the segment's tangents from the caller, which has checked that they are not zero. A cubic gets the same tangents as before. tiny_closed_loops now also strokes loops with arms of 1.25e-6, and fails without the change. README.craft.md and SOURCE.json describe it. --- vendor/kurbo/README.craft.md | 2 +- vendor/kurbo/SOURCE.json | 4 ++-- vendor/kurbo/src/stroke.rs | 22 ++++++++++++++-------- 3 files changed, 17 insertions(+), 11 deletions(-) diff --git a/vendor/kurbo/README.craft.md b/vendor/kurbo/README.craft.md index 9b5a225dff..75b94038e2 100644 --- a/vendor/kurbo/README.craft.md +++ b/vendor/kurbo/README.craft.md @@ -17,7 +17,7 @@ and, for every file kept, the hash in the package (`source_sha256`) and the hash | File | Change | |---|---| | `src/stroke.rs` | `StrokeCtx::do_linear` skips a cusp, or the end point, whose tangent from the point before it is exactly zero, instead of passing the tangent to `do_join` and `do_line`, which divide by its length. After rounding, a collinear cubic that runs back and forth can put two cusps at the same point, or a cusp on the end point, and the whole outline then held NaN coordinates. The `linear_cubic_with_coincident_cusps` test strokes one cubic of each kind with every join, two widths and two tolerances. Code comments label the change `Craft patch (zero tangent)`. | -| `src/stroke.rs` | The stroker skips a quadratic or cubic whose start or end tangent is zero, as it skips a zero-length line. `PathSeg::tangents` falls back to the chord when the control arms are shorter than 1e-6, and a curve that ends where it starts has a zero chord, so such a closed loop gave NaN coordinates in the outline. The `tiny_closed_loops` test strokes loops with arms of 1e-7 and 1e-5, on their own and after a line. Code comments label the change `Craft patch (zero tangent)`. | +| `src/stroke.rs` | The stroker skips a quadratic or cubic whose start or end tangent is zero, as it skips a zero-length line. `PathSeg::tangents` falls back to the chord when the control arms are shorter than 1e-6, and a curve that ends where it starts has a zero chord, so such a closed loop gave NaN coordinates in the outline. A quadratic is stroked as the cubic it raises to, whose control arms are 2/3 as long, so the quadratic's own tangents are passed on to `do_cubic` and `do_linear`. The `tiny_closed_loops` test strokes loops with arms of 1e-7, 1.25e-6 and 1e-5, on their own and after a line. Code comments label the change `Craft patch (zero tangent)`. | Every change here updates this table and `SOURCE.json` in the same commit. diff --git a/vendor/kurbo/SOURCE.json b/vendor/kurbo/SOURCE.json index d3439b29c8..e381d32cb7 100644 --- a/vendor/kurbo/SOURCE.json +++ b/vendor/kurbo/SOURCE.json @@ -9,7 +9,7 @@ "upstream_directory": "kurbo", "local_patches": [ "In `src/stroke.rs`, `StrokeCtx::do_linear` skips a cusp, or the end point, whose tangent from the point before it is exactly zero, instead of passing the tangent to `do_join` and `do_line`, which divide by its length, so a collinear cubic whose cusps round onto the point before them or onto its end point no longer gives NaN coordinates. The test `stroke::tests::linear_cubic_with_coincident_cusps` covers it.", - "In `src/stroke.rs`, the stroker skips a quadratic or cubic whose start or end tangent from `PathSeg::tangents` is zero, as it skips a zero-length line, so a closed loop with control arms shorter than 1e-6 no longer gives NaN coordinates. The test `stroke::tests::tiny_closed_loops` covers it." + "In `src/stroke.rs`, the stroker skips a quadratic or cubic whose start or end tangent from `PathSeg::tangents` is zero, as it skips a zero-length line, so a closed loop with control arms shorter than 1e-6 no longer gives NaN coordinates; a quadratic's own tangents are passed on to `do_cubic` and `do_linear`, since the cubic it raises to has control arms 2/3 as long. The test `stroke::tests::tiny_closed_loops` covers it." ], "files": [ { "path": ".cargo_vcs_info.json", "source_sha256": "4bfe3d4ab606efdb8e558db546ae666decc53fa3caa34865b4f66ffa67449a66", "source_git_blob": null, "sha256": "4bfe3d4ab606efdb8e558db546ae666decc53fa3caa34865b4f66ffa67449a66" }, @@ -60,7 +60,7 @@ { "path": "src/shape.rs", "source_sha256": "226a32a1996d298e9587cc921b7cc8644ca6e04b2c740732e0a63ab00d3351ae", "source_git_blob": null, "sha256": "226a32a1996d298e9587cc921b7cc8644ca6e04b2c740732e0a63ab00d3351ae" }, { "path": "src/simplify.rs", "source_sha256": "771fc68a2dd0a00d994906176641bcb17c9351b3d1205e037a78a5893b51a684", "source_git_blob": null, "sha256": "771fc68a2dd0a00d994906176641bcb17c9351b3d1205e037a78a5893b51a684" }, { "path": "src/size.rs", "source_sha256": "645a1f7ba1528b1b10e5881d53019eac428e556c1d9bdea8d3f42ce351c00950", "source_git_blob": null, "sha256": "645a1f7ba1528b1b10e5881d53019eac428e556c1d9bdea8d3f42ce351c00950" }, - { "path": "src/stroke.rs", "source_sha256": "9ae69c57571d653a34ded745e176869ef587e4ff5c3dcb1607a398df7e029498", "source_git_blob": null, "sha256": "9f430ffc660e8777551d4c67cc1ff3e4006539c7f31680626721c2105f054c9e" }, + { "path": "src/stroke.rs", "source_sha256": "9ae69c57571d653a34ded745e176869ef587e4ff5c3dcb1607a398df7e029498", "source_git_blob": null, "sha256": "18f6f59a8935516f42c8790cda61f6e0993c33dc0d9db8fbe1b6b3bb4c6a6cf0" }, { "path": "src/svg.rs", "source_sha256": "b403a258614b3e287c3e5210b0745814f08acda92e95696bdddbf50e341fa3be", "source_git_blob": null, "sha256": "b403a258614b3e287c3e5210b0745814f08acda92e95696bdddbf50e341fa3be" }, { "path": "src/translate_scale.rs", "source_sha256": "8b82eb5f46744cb9a044263e200d79d797270616320337e4230356942ab85f1a", "source_git_blob": null, "sha256": "8b82eb5f46744cb9a044263e200d79d797270616320337e4230356942ab85f1a" }, { "path": "src/triangle.rs", "source_sha256": "27a6cddb109ae36ef55c470261c689d085502ab72a47f3a32ca22e771df7b03e", "source_git_blob": null, "sha256": "27a6cddb109ae36ef55c470261c689d085502ab72a47f3a32ca22e771df7b03e" }, diff --git a/vendor/kurbo/src/stroke.rs b/vendor/kurbo/src/stroke.rs index a55fc495a3..2cdeb87d5a 100644 --- a/vendor/kurbo/src/stroke.rs +++ b/vendor/kurbo/src/stroke.rs @@ -337,7 +337,10 @@ fn stroke_undashed( continue; } ctx.do_join(style, tan0); - ctx.do_cubic(style, q.raise(), tolerance); + // Craft patch (zero tangent): the raised cubic's control + // arms are 2/3 as long and can fall under the threshold + // of `tangents`, so the quadratic's tangents are passed on. + ctx.do_cubic(style, q.raise(), (tan0, tan1), tolerance); ctx.last_tan = tan1; } } @@ -350,7 +353,7 @@ fn stroke_undashed( continue; } ctx.do_join(style, tan0); - ctx.do_cubic(style, c, tolerance); + ctx.do_cubic(style, c, (tan0, tan1), tolerance); ctx.last_tan = tan1; } } @@ -523,7 +526,7 @@ impl StrokeCtx { self.last_pt = p1; } - fn do_cubic(&mut self, style: &Stroke, c: CubicBez, tolerance: f64) { + fn do_cubic(&mut self, style: &Stroke, c: CubicBez, tangents: (Vec2, Vec2), tolerance: f64) { // First, detect degenerate linear case // Ordinarily, this is the direction of the chord, but if the chord is very @@ -563,7 +566,7 @@ impl StrokeCtx { // Mapping back from projection of reference chord let ref_vec = chord_ref / chord_ref_hypot2; let ref_pt = midpoint - 0.5 * (p0 + p3) * ref_vec; - self.do_linear(style, c, [p0, p1, p2, p3], ref_pt, ref_vec); + self.do_linear(style, c, tangents, [p0, p1, p2, p3], ref_pt, ref_vec); return; } } @@ -584,14 +587,15 @@ impl StrokeCtx { &mut self, style: &Stroke, c: CubicBez, + (tan0, tan1): (Vec2, Vec2), p: [f64; 4], ref_pt: Point, ref_vec: Vec2, ) { // Always do round join, to model cusp as limit of finite curvature (see Nehab). let style = Stroke::new(style.width).with_join(Join::Round); - // Tangents of endpoints (for connecting to joins) - let (tan0, tan1) = PathSeg::Cubic(c).tangents(); + // Tangents of endpoints (for connecting to joins) are those of the + // segment, which the caller has checked are nonzero. self.last_tan = tan0; // find cusps let c0 = p[1] - p[0]; @@ -1198,10 +1202,12 @@ mod tests { } // A curve that ends where it starts, with control arms shorter than the - // threshold of `PathSeg::tangents`, has a zero tangent at both ends. + // threshold of `PathSeg::tangents`, has a zero tangent at both ends. A + // quadratic with arms of 1.25e-6 passes that threshold, but the cubic it + // is raised to has arms of 2/3 that length, which do not. #[test] fn tiny_closed_loops() { - for arm in [1e-7, 1e-5] { + for arm in [1e-7, 1.25e-6, 1e-5] { for lead_in in [false, true] { let mut cubic = BezPath::new(); let mut quad = BezPath::new();